diff --git a/.gitignore b/.gitignore index 3c45938..a020bfa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ node_modules/ *.log .DS_Store + +# 开发工程文件:docs 五级文档框架不进项目 git 仓库 +docs/ +AGENTS.md diff --git a/README.md b/README.md index 9d36af5..a21bf93 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/verification.md b/docs/verification.md deleted file mode 100644 index a8f9a6f..0000000 --- a/docs/verification.md +++ /dev/null @@ -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 语义测试)。 diff --git a/lib/client.js b/lib/client.js index a8971b8..9f4a1d6 100644 --- a/lib/client.js +++ b/lib/client.js @@ -65,10 +65,16 @@ window.__ModuleLoader__.load({ //#endregion //#region src/core/matcher.ts /** - * 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. */ /** One rule match against a workspace's path and title. */ function ruleMatches(rule, path, title) { @@ -81,16 +87,121 @@ window.__ModuleLoader__.load({ } 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. */ function classify(categories, path, title) { for (const category of categories) if (category.rules.some((rule) => ruleMatches(rule, path, title))) return category; } + /** Display name of a rule category: the rename override when present. */ + function ruleDisplayName(manual, originalName) { + return manual?.renamed?.[originalName] ?? originalName; + } + /** Whether a rule category has been hidden by a UI delete. */ + function isHiddenRule(manual, originalName) { + return manual?.hidden?.includes(originalName) ?? false; + } + /** Original YAML rule name whose display name equals `key` (undefined when none). */ + function originalRuleNameForDisplay(categories, manual, key) { + return categories.find((c) => ruleDisplayName(manual, c.name) === key)?.name; + } + function effectiveCategories(config, manual) { + const entries = []; + const seen = /* @__PURE__ */ new Set(); + 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 === void 0 || order.length === 0) return entries; + 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 !== void 0 && pb !== void 0) return pa - pb; + if (pa !== void 0) return -1; + if (pb !== void 0) return 1; + return 0; + }); + } + /** Display keys of all effective categories (uncategorized bucket excluded). */ + function displayCategoryKeys(config, manual) { + 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`). + */ + function resolveCategory(config, manual, workspaceId, path, title) { + const override = manual?.assignments[workspaceId]; + if (override !== void 0) return override ?? void 0; + const matched = classify(config.categories, path, title); + if (matched === void 0) return void 0; + if (isHiddenRule(manual, matched.name)) return void 0; + return ruleDisplayName(manual, matched.name); + } + /** + * Names that may not be used for a new/renamed group: the reserved + * uncategorized label plus every current display key. + */ + function takenCategoryNames(config, manual) { + const taken = new Set(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. + */ + function orderedWorkspaceIds(manual, categoryKey, members) { + const stored = manual?.workspaceOrder?.[categoryKey]; + if (stored === void 0 || stored.length === 0) return [...members]; + const memberSet = new Set(members); + const ordered = []; + const seen = /* @__PURE__ */ new Set(); + 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. */ + function moveBefore(list, id, beforeId) { + const rest = list.filter((x) => x !== id); + if (beforeId === void 0) 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. */ + function moveAfter(list, id, afterId) { + const rest = list.filter((x) => x !== id); + if (afterId === void 0) return [...rest, id]; + const index = rest.indexOf(afterId); + if (index === -1) return [...rest, id]; + rest.splice(index + 1, 0, id); + return rest; + } //#endregion //#region src/client/tree.ts /** @@ -143,33 +254,41 @@ window.__ModuleLoader__.load({ * @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. */ - function deriveGroups(list, workspaces, archivedSessionIds, config, view) { + function deriveGroups(list, workspaces, archivedSessionIds, config, view, manual) { const archived = new Set(archivedSessionIds); const expandedCategories = new Set(view.expandedCategories); const expandedWorkspaces = new Set(view.expandedWorkspaces); const descendants = (0, _deepseek_ai_dsh_client_runtime_client.indexSubagentDescendants)(list.byId); const byCategory = /* @__PURE__ */ new Map(); - const categorized = /* @__PURE__ */ new Set(); - 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 !== void 0 ? 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 === void 0 ? void 0 : workspaces.find((w) => w.sessionIds.includes(list.current))?.workspaceId; const nodes = []; - for (const [key, bucket] of byCategory) { - if (bucket.length === 0) continue; + const orderedKeys = [...effectiveCategories(config, manual).map((e) => e.key), UNCATEGORIZED_KEY]; + for (const key of orderedKeys) { + const bucket = byCategory.get(key) ?? []; + if (bucket.length === 0 && !manualCategories.has(key)) continue; const expanded = expandedCategories.has(key); + const ordered = orderedWorkspaceIds(manual, key, bucket.map((w) => w.workspaceId)); const workspaceNodes = []; let containsCurrent = false; - for (const workspace of bucket) { + for (const workspaceId of ordered) { + const workspace = bucket.find((w) => w.workspaceId === workspaceId); + if (workspace === void 0) continue; const sessions = workspaceSessions(list, workspace, archived, descendants); const wsExpanded = expandedWorkspaces.has(workspace.workspaceId); const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId; @@ -251,20 +370,24 @@ window.__ModuleLoader__.load({ * 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. */ - function deriveSearchGroups(list, workspaces, config, matchedIds, archivedSessionIds, snippetsBySession) { + function deriveSearchGroups(list, workspaces, config, matchedIds, archivedSessionIds, manual, snippetsBySession) { const archived = new Set(archivedSessionIds); const descendants = (0, _deepseek_ai_dsh_client_runtime_client.indexSubagentDescendants)(list.byId); const byCategory = /* @__PURE__ */ new Map(); - 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) { const nodes = []; for (const id of workspace.sessionIds) { @@ -280,8 +403,7 @@ window.__ModuleLoader__.load({ }); } if (nodes.length === 0) continue; - const category = classify(config.categories, workspace.path, workspace.title); - const key = category !== void 0 ? 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, @@ -295,8 +417,10 @@ window.__ModuleLoader__.load({ }); } const categories = []; - for (const [key, workspaceNodes] of byCategory) { - if (workspaceNodes.length === 0) continue; + const orderedKeys = [...effectiveCategories(config, manual).map((e) => e.key), UNCATEGORIZED_KEY]; + for (const key of orderedKeys) { + const workspaceNodes = byCategory.get(key); + if (workspaceNodes === void 0 || workspaceNodes.length === 0) continue; categories.push({ key, label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key, @@ -314,7 +438,20 @@ window.__ModuleLoader__.load({ * 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. */ + /** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */ + const DND_WORKSPACE_TYPE = "application/x-dsh-workspace-groups"; + /** dataTransfer type carrying the dragged category key (group reorder). */ + const DND_CATEGORY_TYPE = "application/x-dsh-workspace-groups-category"; + /** Whether a drag carries any of the plugin's payloads (drop targets accept both). */ + function hasPluginDragType(types) { + const list = Array.from(types); + return list.includes("application/x-dsh-workspace-groups") || list.includes("application/x-dsh-workspace-groups-category"); + } /** Pending interaction status → primitives StateDot state. */ function pendingState(status) { switch (status) { @@ -343,15 +480,27 @@ window.__ModuleLoader__.load({ if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`; return `${Math.floor(diff / (365 * DAY))}y`; } - /** One category folder row. */ - function CategoryRow({ node, t, onToggle }) { + /** + * 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. + */ + function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }) { + const [menuOpen, setMenuOpen] = (0, react.useState)(false); const count = node.workspaces.length; + const manageable = onRename !== void 0 && onDelete !== void 0; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("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 !== void 0, onClick: onToggle, + onDragStart: onDragStartCategory, + onDragOver: onRowDragOver, + onDragLeave: onRowDragLeave, + onDrop: onRowDrop, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `wgChevron${node.expanded ? " wgChevronOpen" : ""}`, @@ -368,28 +517,84 @@ window.__ModuleLoader__.load({ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "wgCategoryCount", children: count + }), + manageable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgRowActions", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, { + open: menuOpen, + onClose: () => { + setMenuOpen(false); + }, + items: [{ + id: "rename", + label: t("group.rename"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEditOutline16, {}) + }, { + id: "delete", + label: t("group.delete"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutline16, {}), + danger: true + }], + onSelect: (id) => { + setMenuOpen(false); + if (id === "rename") onRename(); + if (id === "delete") onDelete(); + }, + portal: true, + closeOnPointerLeave: true, + anchor: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + draggable: false, + "aria-label": `${t("group.rename")} ${node.label}`, + onClick: (e) => { + e.stopPropagation(); + setMenuOpen((v) => !v); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEllipsisOutline16, {}) + }) + }) }) ] }); } - /** One workspace folder row inside a category. */ - function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }) { + /** One workspace folder row inside a category: draggable source + drop target. */ + function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, hasOverride = false, onMoveOut, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }) { const [menuOpen, setMenuOpen] = (0, react.useState)(false); - const menuItems = [{ - id: "rename", - label: t("workspace.rename"), - icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEditOutline16, {}) - }, { - id: "delete", - label: t("workspace.delete"), - icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutline16, {}), - danger: true - }]; + const menuItems = [ + ...hasOverride && onMoveOut !== void 0 ? [{ + id: "moveOut", + label: t("workspace.moveToUncategorized"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutline16, { size: 16 }) + }] : [], + { + id: "rename", + label: t("workspace.rename"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEditOutline16, {}) + }, + { + id: "delete", + label: t("workspace.delete"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutline16, {}), + danger: true + } + ]; + const onDragStart = (event) => { + event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId); + event.dataTransfer.effectAllowed = "move"; + onDragStartExtra?.(); + }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("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: true, onClick: onToggle, + onDragStart, + onDragOver: onRowDragOver, + onDragLeave: onRowDragLeave, + onDrop: onRowDrop, children: [ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: `wgChevron${node.expanded ? " wgChevronOpen" : ""}`, @@ -414,6 +619,7 @@ window.__ModuleLoader__.load({ items: menuItems, onSelect: (id) => { setMenuOpen(false); + if (id === "moveOut") onMoveOut?.(); if (id === "rename") onRename(); if (id === "delete") onDelete(); }, @@ -422,6 +628,7 @@ window.__ModuleLoader__.load({ anchor: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: "wgIconButton", + draggable: false, "aria-label": `${t("workspace.rename")} ${node.label}`, onClick: (e) => { e.stopPropagation(); @@ -432,6 +639,7 @@ window.__ModuleLoader__.load({ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { type: "button", className: "wgIconButton", + draggable: false, "aria-label": `${t("session.new")} ${node.label}`, onClick: (e) => { e.stopPropagation(); @@ -521,35 +729,83 @@ window.__ModuleLoader__.load({ }); } //#endregion - //#region \0dsh-workspace-groups-inline-css:/Users/zcol/Project/dsh-workspace-groups/src/client/styles.css.mjs - var styles_css_default = ".wgRoot{flex-direction:column;flex:1;min-height:0;display:flex}.wgSectionHeader{flex:none;align-items:center;gap:4px;height:36px;padding:0 12px;display:flex}.wgSectionLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:45%;color:var(--dsw-fg-1,inherit);flex:none;font-size:12px;font-weight:600;overflow:hidden}.wgIconButton{width:26px;height:26px;color:var(--dsw-fg-2,inherit);cursor:pointer;background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:0;display:inline-flex}.wgIconButton:hover{background:var(--dsw-bg-hover,#7f7f7f1f);color:var(--dsw-fg-1,inherit)}.wgIconButton:disabled{opacity:.5;cursor:default}.wgSearch{flex:1;align-items:center;min-width:0;max-width:28px;margin-left:auto;transition:max-width .18s;display:flex}.wgSearchExpanded{max-width:100%}.wgSearchInput{min-width:0;color:var(--dsw-fg-1,inherit);background:0 0;border:none;outline:none;flex:1;padding:0;font-size:12px}.wgTreeBody{flex:1;min-height:0;padding:0 8px 8px;overflow-y:auto}.wgList{flex-direction:column;gap:1px;display:flex}.wgEmpty{text-align:center;color:var(--dsw-fg-3,#7f7f7fcc);padding:16px 8px;font-size:12px}.wgCategoryRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px;display:flex}.wgCategoryRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgChevron{width:14px;height:14px;color:var(--dsw-fg-3,#7f7f7fcc);flex:none;justify-content:center;align-items:center;transition:transform .12s;display:inline-flex}.wgChevronOpen{transform:rotate(90deg)}.wgCategoryIcon{color:var(--dsw-fg-2,inherit);flex:none;justify-content:center;align-items:center;display:inline-flex}.wgCategoryLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;font-weight:600;overflow:hidden}.wgCategoryCount{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgProjectRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px 0 20px;display:flex}.wgProjectRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgProjectActive{color:var(--dsw-accent,#4a90d9)}.wgProjectLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;overflow:hidden}.wgRowActions{opacity:0;flex:none;align-items:center;gap:2px;display:inline-flex}.wgProjectRow:hover .wgRowActions,.wgProjectRow:focus-within .wgRowActions{opacity:1}.wgSessionRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:6px;height:30px;padding:0 4px 0 40px;display:flex}.wgSessionRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgSessionRow:hover .wgRowActions,.wgSessionRow:focus-within .wgRowActions{opacity:1}.wgSelected{background:var(--dsw-bg-selected,#4a90d92e)}.wgStatusSlot{flex:none;justify-content:center;align-items:center;width:14px;height:14px;display:inline-flex}.wgSessionTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;overflow:hidden}.wgSessionTime{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgVisuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.wgMatched{background:var(--dsw-bg-selected,#4a90d92e)}.wgSessionSnippet{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-3,#7f7f7fcc);flex:1;font-size:11px;overflow:hidden}.wgSearchStatus{color:var(--dsw-fg-3,#7f7f7fcc);text-align:center;padding:8px;font-size:11px}.wgRail{flex-direction:column;align-items:center;gap:4px;padding:8px 0;display:flex}.wgAddError{color:var(--dsw-fg-1,inherit);white-space:pre-wrap;word-break:break-word;max-height:200px;font-size:12px;overflow-y:auto}.wgRenameInput{border:1px solid var(--dsw-border,#7f7f7f4d);background:var(--dsw-bg-1,transparent);width:100%;color:var(--dsw-fg-1,inherit);border-radius:6px;outline:none;padding:6px 8px;font-size:13px}.wgRenameInput:focus{border-color:var(--dsw-accent,#4a90d9)}"; + //#region \0dsh-workspace-groups-inline-css:/Users/zcol/Project/DSH-工作区分组/src/client/styles.css.mjs + var styles_css_default = ".wgRoot{flex-direction:column;flex:1;min-height:0;display:flex}.wgSectionHeader{flex:none;align-items:center;gap:4px;height:36px;padding:0 12px;display:flex}.wgSectionLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:45%;color:var(--dsw-fg-1,inherit);flex:none;font-size:12px;font-weight:600;overflow:hidden}.wgIconButton{width:26px;height:26px;color:var(--dsw-fg-2,inherit);cursor:pointer;background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:0;display:inline-flex}.wgIconButton:hover{background:var(--dsw-bg-hover,#7f7f7f1f);color:var(--dsw-fg-1,inherit)}.wgIconButton:disabled{opacity:.5;cursor:default}.wgSearch{flex:1;align-items:center;min-width:0;max-width:28px;margin-left:auto;transition:max-width .18s;display:flex}.wgSearchExpanded{max-width:100%}.wgSearchInput{min-width:0;color:var(--dsw-fg-1,inherit);background:0 0;border:none;outline:none;flex:1;padding:0;font-size:12px}.wgTreeBody{flex:1;min-height:0;padding:0 8px 8px;overflow-y:auto}.wgList{flex-direction:column;gap:1px;display:flex}.wgEmpty{text-align:center;color:var(--dsw-fg-3,#7f7f7fcc);padding:16px 8px;font-size:12px}.wgCategoryRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px;display:flex;position:relative}.wgCategoryRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgCategoryRow:hover .wgRowActions,.wgCategoryRow:focus-within .wgRowActions{opacity:1}.wgDropTarget{background:var(--dsw-bg-selected,#4a90d92e);outline:1px dashed var(--dsw-accent,#4a90d9);outline-offset:-1px}.wgInsertBefore:before,.wgInsertAfter:after{content:\"\";background:var(--dsw-accent,#4a90d9);height:2px;box-shadow:0 0 0 1px color-mix(in srgb, var(--dsw-accent,#4a90d9) 25%, transparent);pointer-events:none;z-index:6;border-radius:1px;position:absolute;left:2px;right:2px}.wgInsertBefore:before{top:-1px}.wgInsertAfter:after{bottom:-1px}.wgChevron{width:14px;height:14px;color:var(--dsw-fg-3,#7f7f7fcc);flex:none;justify-content:center;align-items:center;transition:transform .12s;display:inline-flex}.wgChevronOpen{transform:rotate(90deg)}.wgCategoryIcon{color:var(--dsw-fg-2,inherit);flex:none;justify-content:center;align-items:center;display:inline-flex}.wgCategoryLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;font-weight:600;overflow:hidden}.wgCategoryCount{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgProjectRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px 0 20px;display:flex;position:relative}.wgProjectRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgProjectActive{color:var(--dsw-accent,#4a90d9)}.wgProjectLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;overflow:hidden}.wgRowActions{opacity:0;flex:none;align-items:center;gap:2px;display:inline-flex}.wgProjectRow:hover .wgRowActions,.wgProjectRow:focus-within .wgRowActions{opacity:1}.wgSessionRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:6px;height:30px;padding:0 4px 0 40px;display:flex}.wgSessionRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgSessionRow:hover .wgRowActions,.wgSessionRow:focus-within .wgRowActions{opacity:1}.wgSelected{background:var(--dsw-bg-selected,#4a90d92e)}.wgStatusSlot{flex:none;justify-content:center;align-items:center;width:14px;height:14px;display:inline-flex}.wgSessionTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;overflow:hidden}.wgSessionTime{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgVisuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.wgMatched{background:var(--dsw-bg-selected,#4a90d92e)}.wgSessionSnippet{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-3,#7f7f7fcc);flex:1;font-size:11px;overflow:hidden}.wgSearchStatus{color:var(--dsw-fg-3,#7f7f7fcc);text-align:center;padding:8px;font-size:11px}.wgManualError{color:var(--dsw-fg-1,inherit);text-align:left;word-break:break-word}.wgRail{flex-direction:column;align-items:center;gap:4px;padding:8px 0;display:flex}.wgAddError{color:var(--dsw-fg-1,inherit);white-space:pre-wrap;word-break:break-word;max-height:200px;font-size:12px;overflow-y:auto}.wgRenameInput{border:1px solid var(--dsw-border,#7f7f7f4d);background:var(--dsw-bg-1,transparent);width:100%;color:var(--dsw-fg-1,inherit);border-radius:6px;outline:none;padding:6px 8px;font-size:13px}.wgRenameInput:focus{border-color:var(--dsw-accent,#4a90d9)}"; //#endregion //#region src/client/GroupsBrowser.tsx /** * 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). */ const SEARCH_DEBOUNCE_MS = 250; const SEARCH_QUERY_MAX_CODE_UNITS = 500; + const EMPTY_MANUAL = { + categories: [], + assignments: {}, + categoryOrder: [], + workspaceOrder: {}, + renamed: {}, + hidden: [] + }; + /** Materialize optional overlay fields so every update is a plain object edit. */ + function normalizeManual(manual) { + return { + categories: manual.categories, + assignments: manual.assignments, + categoryOrder: manual.categoryOrder ?? [], + workspaceOrder: manual.workspaceOrder ?? {}, + renamed: manual.renamed ?? {}, + hidden: manual.hidden ?? [] + }; + } function sanitizeSearchQuery(value) { const withoutNul = value.replaceAll("\0", ""); if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul; return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS); } - /** Minimal fetch of the grouping config (host route; no-cache revalidation). */ + /** Light runtime guard for the manual overlay attached to the config fetch. */ + function isManualGroups(value) { + if (typeof value !== "object" || value === null) return false; + const candidate = value; + 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() { 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(); - return Array.isArray(body.categories) ? body : { categories: [] }; + return { + config: Array.isArray(body.categories) ? body : { categories: [] }, + manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL + }; + } + /** Persist the whole runtime overlay (idempotent; the host validates + writes). */ + async function saveManualOverlay(manual) { + 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 {} + throw new Error(message); + } } /** * Render the browsing region. @@ -567,16 +823,22 @@ window.__ModuleLoader__.load({ }; }, []); const [config, setConfig] = (0, react.useState)({ categories: [] }); + const [manual, setManual] = (0, react.useState)(EMPTY_MANUAL); const [configError, setConfigError] = (0, react.useState)(null); const reloadConfig = () => { setConfigError(null); - fetchGroupsConfig().then(setConfig).catch((reason) => { + fetchGroupsConfig().then(({ config: nextConfig, manual: nextManual }) => { + setConfig(nextConfig); + setManual(nextManual); + }).catch((reason) => { setConfigError(reason instanceof Error ? reason.message : String(reason)); }); }; (0, react.useEffect)(() => { reloadConfig(); }, []); + const [manualError, setManualError] = (0, react.useState)(null); + const [manualSaving, setManualSaving] = (0, react.useState)(false); const workspaces = useWorkspaces((state) => state.items); const workspacePhase = useWorkspaces((state) => state.phase); const archivedSessionIds = useWorkspaces((state) => state.archivedSessionIds); @@ -587,7 +849,7 @@ window.__ModuleLoader__.load({ const currentWorkspaceKey = current === void 0 ? void 0 : workspaces.find((w) => w.sessionIds.includes(current))?.workspaceId; (0, react.useEffect)(() => { if (current === void 0 || currentWorkspaceKey === void 0) return; - const category = categoriesForCurrent(config, workspaces, current); + const category = categoriesForCurrent(config, workspaces, current, manual); if (category !== void 0 && !Object.hasOwn(categoryExpansion, category)) actions.setCategoryExpanded(category, true); if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) actions.setWorkspaceExpanded(currentWorkspaceKey, true); }, [ @@ -595,16 +857,18 @@ window.__ModuleLoader__.load({ currentWorkspaceKey, config, workspaces, + manual, categoryExpansion, workspaceExpansion, actions ]); (0, react.useEffect)(() => { if (workspacePhase !== "ready") return; - actions.retainKeys(config.categories.map((c) => c.name), workspaces.map((w) => w.workspaceId)); + actions.retainKeys(displayCategoryKeys(config, manual), workspaces.map((w) => w.workspaceId)); }, [ actions, config, + manual, workspacePhase, workspaces ]); @@ -682,11 +946,12 @@ window.__ModuleLoader__.load({ const groups = (0, react.useMemo)(() => deriveGroups(list, workspaces, archivedSessionIds, config, { expandedCategories, expandedWorkspaces - }), [ + }, manual), [ list, workspaces, archivedSessionIds, config, + manual, expandedCategories, expandedWorkspaces ]); @@ -775,6 +1040,222 @@ window.__ModuleLoader__.load({ console.warn("session archive rejected:", reason); }); }; + const [groupDialog, setGroupDialog] = (0, react.useState)(null); + const [groupDraft, setGroupDraft] = (0, react.useState)(""); + const [groupError, setGroupError] = (0, react.useState)(null); + const [groupBusy, setGroupBusy] = (0, react.useState)(false); + const [groupDeleteTarget, setGroupDeleteTarget] = (0, react.useState)(null); + const [groupDeleting, setGroupDeleting] = (0, react.useState)(false); + const [groupDeleteError, setGroupDeleteError] = (0, react.useState)(null); + const takenNames = (0, react.useMemo)(() => takenCategoryNames(config, manual), [config, manual]); + const groupTrimmed = groupDraft.trim(); + const groupNameIssue = groupDialog !== null && groupTrimmed !== "" ? groupTrimmed === "未分类" ? 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 : void 0; + const renaming = groupDialog.mode === "rename" && from !== name; + let next; + if (groupDialog.mode === "create") next = { + ...manual, + categories: [...manual.categories, name] + }; + else { + const originalRule = from !== void 0 ? originalRuleNameForDisplay(config.categories, manual, from) : void 0; + next = { + ...manual, + ...originalRule !== void 0 ? { renamed: { + ...manual.renamed, + [originalRule]: name + } } : { categories: manual.categories.map((c) => c === from ? name : c) }, + assignments: Object.fromEntries(Object.entries(manual.assignments).map(([id, category]) => [id, category === from ? name : category])), + workspaceOrder: Object.fromEntries(Object.entries(manual.workspaceOrder).map(([key, ids]) => [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(""); + if (renaming) actions.setCategoryExpanded(name, true); + }).catch((reason) => { + 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); + 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 = { + ...manual, + assignments, + workspaceOrder, + categoryOrder: manual.categoryOrder.filter((key) => key !== name), + ...originalRule !== void 0 ? { + 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) => { + setGroupDeleting(false); + setGroupDeleteError(reason instanceof Error ? reason.message : String(reason)); + }); + }; + const [dragIndicator, setDragIndicator] = (0, react.useState)(null); + (0, react.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, categoryKey, beforeWorkspaceId, afterWorkspaceId) => { + if (manualSaving) return; + const workspace = workspaces.find((w) => w.workspaceId === workspaceId); + if (workspace === void 0) return; + setManualSaving(true); + try { + let next; + if (categoryKey === UNCATEGORIZED_KEY) { + 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 !== void 0 ? moveAfter(manual.workspaceOrder[categoryKey] ?? [], workspaceId, afterWorkspaceId) : moveBefore(manual.workspaceOrder[categoryKey] ?? [], workspaceId, beforeWorkspaceId); + const workspaceOrder = { + ...manual.workspaceOrder, + [categoryKey]: targetOrder + }; + if (movingAcross && currentKey !== void 0 && workspaceOrder[currentKey] !== void 0) 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, beforeKey, afterKey) => { + if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return; + setManualSaving(true); + try { + const order = displayCategoryKeys(config, manual); + const categoryOrder = afterKey !== void 0 ? moveAfter(order, draggedKey, afterKey) : moveBefore(order, draggedKey, beforeKey); + const next = { + ...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, row) => (event) => { + event.preventDefault(); + setDragIndicator(null); + const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE); + if (draggedCategory !== "") { + const rect = event.currentTarget.getBoundingClientRect(); + const before = event.clientY < rect.top + rect.height / 2; + const beforeKey = row.kind === "category" && before ? row.key : void 0; + const afterKey = row.kind === "category" && !before ? row.key : void 0; + moveCategory(draggedCategory, beforeKey, afterKey); + return; + } + const workspaceId = event.dataTransfer.getData("application/x-dsh-workspace-groups") || event.dataTransfer.getData("text/plain"); + if (workspaceId === "") return; + const rect = event.currentTarget.getBoundingClientRect(); + const before = event.clientY < rect.top + rect.height / 2; + const beforeWsid = row.kind === "workspace" && before ? row.key : void 0; + const afterWsid = row.kind === "workspace" && !before ? row.key : void 0; + moveWorkspaceTo(workspaceId, categoryKey, beforeWsid, afterWsid); + }; + const onDragOverRow = (row) => (event) => { + if (!hasPluginDragType(event.dataTransfer.types)) return; + const draggingCategory = Array.from(event.dataTransfer.types).includes(DND_CATEGORY_TYPE); + if (draggingCategory && row.kind !== "category") return; + event.preventDefault(); + event.dataTransfer.dropEffect = "move"; + const rect = event.currentTarget.getBoundingClientRect(); + const before = event.clientY < rect.top + rect.height / 2; + if (draggingCategory || row.kind === "workspace") setDragIndicator((prev) => prev?.mode === "line" && prev.row.kind === row.kind && prev.row.key === row.key && prev.before === before ? prev : { + mode: "line", + row, + before + }); + else setDragIndicator((prev) => prev?.mode === "into" && prev.categoryKey === row.key ? prev : { + mode: "into", + categoryKey: row.key + }); + }; + const onDragLeaveRow = (event) => { + if (event.currentTarget.contains(event.relatedTarget)) return; + setDragIndicator(null); + }; + const onDragStartWorkspace = (workspaceId) => () => { + const workspace = workspaces.find((w) => w.workspaceId === workspaceId); + const sourceKey = workspace === void 0 ? void 0 : resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title); + for (const key of Object.keys(categoryExpansion)) { + if (!categoryExpansion[key]) continue; + if (sourceKey !== void 0 && key === sourceKey) continue; + actions.setCategoryExpanded(key, false); + } + for (const key of Object.keys(workspaceExpansion)) if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false); + }; + const onDragStartCategory = (categoryKey) => (event) => { + 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 /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: `wgRoot${wide ? "" : " wgRail"}`, @@ -829,6 +1310,22 @@ window.__ModuleLoader__.load({ }) ] }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, { + label: t("group.create"), + side: "bottom", + delayMs: 500, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + "aria-label": t("group.create"), + onClick: () => { + setGroupDraft(""); + setGroupError(null); + setGroupDialog({ mode: "create" }); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutline16, { size: wide ? 16 : 18 }) + }) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, { label: t("workspace.add"), side: "bottom", @@ -862,61 +1359,171 @@ window.__ModuleLoader__.load({ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: "wgTreeBody", - children: [configError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { - className: "wgSearchStatus", - role: "status", - children: t("configUnavailable") - }), wide && normalizedQuery !== "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchBody, { - list, - workspaces, - config, - archivedSessionIds, - query: normalizedQuery, - remote: remoteSearch, - resultLimit: searchResultLimit, - current, - now, - open, - t - }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { - className: "wgList", - role: "tree", - "aria-label": t("section.workspaces"), - children: [groups.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { - className: "wgEmpty", - children: workspacePhase === "ready" ? t("empty.noWorkspaces") : t("empty.none") - }), groups.map((category) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CategorySection, { - category, + children: [ + configError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgSearchStatus", + role: "status", + children: t("configUnavailable") + }), + manualError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "wgSearchStatus wgManualError", + role: "alert", + children: [ + t("manual.saveError"), + ": ", + manualError + ] + }), + wide && normalizedQuery !== "" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchBody, { + list, + workspaces, + config, + archivedSessionIds, + query: normalizedQuery, + remote: remoteSearch, + resultLimit: searchResultLimit, current, now, - t, - onToggleCategory: () => { - actions.setCategoryExpanded(category.key, !category.expanded); + open, + manual, + t + }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "wgList", + role: "tree", + "aria-label": t("section.workspaces"), + children: [groups.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgEmpty", + children: workspacePhase === "ready" ? t("empty.noWorkspaces") : t("empty.none") + }), groups.map((category) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CategorySection, { + category, + current, + now, + t, + manageable: category.key !== UNCATEGORIZED_KEY, + dragIndicator, + onDragOverRow, + onDragLeaveRow, + onDropRow, + ...category.key === UNCATEGORIZED_KEY ? {} : { onDragStartCategory: onDragStartCategory(category.key) }, + onDragStartWorkspace, + onToggleCategory: () => { + actions.setCategoryExpanded(category.key, !category.expanded); + }, + onToggleWorkspace: (key) => { + actions.setWorkspaceExpanded(key, !workspaceExpansion[key]); + }, + onNewSession: startSession, + onOpen: open, + onRenameRequest: (workspaceId, title) => { + setRenameTarget({ + workspaceId, + currentTitle: title + }); + setRenameDraft(title); + setRenameError(null); + }, + onDeleteRequest: (workspaceId, title) => { + setDeleteTarget({ + workspaceId, + title + }); + setDeleteError(null); + }, + onSessionRename, + onSessionArchive, + onFork: forkSession, + onGroupRename: () => { + setGroupDraft(category.key); + setGroupError(null); + setGroupDialog({ + mode: "rename", + from: category.key + }); + }, + onGroupDelete: () => { + setGroupDeleteTarget(category.key); + setGroupDeleteError(null); + }, + onMoveOut: (workspaceId) => { + moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY); + }, + hasOverride: (workspaceId) => Object.hasOwn(manual.assignments, workspaceId) + }, category.key))] + }) + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { + open: groupDialog !== null, + onClose: () => { + setGroupDialog(null); + }, + closeLabel: t("close"), + title: groupDialog?.mode === "rename" ? t("group.renameTitle") : t("group.createTitle"), + footer: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "outline", + onClick: () => { + setGroupDialog(null); + }, + children: t("group.createCancel") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "primary", + disabled: groupBlocked, + onClick: confirmGroupDialog, + children: groupDialog?.mode === "rename" ? t("group.renameConfirm") : t("group.createConfirm") + })] }), + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", { + className: "wgRenameInput", + value: groupDraft, + "aria-label": t("group.createPlaceholder"), + placeholder: t("group.createPlaceholder"), + autoFocus: true, + onChange: (e) => { + setGroupDraft(e.target.value); + setGroupError(null); }, - onToggleWorkspace: (key) => { - actions.setWorkspaceExpanded(key, !workspaceExpansion[key]); - }, - onNewSession: startSession, - onOpen: open, - onRenameRequest: (workspaceId, title) => { - setRenameTarget({ - workspaceId, - currentTitle: title - }); - setRenameDraft(title); - setRenameError(null); - }, - onDeleteRequest: (workspaceId, title) => { - setDeleteTarget({ - workspaceId, - title - }); - setDeleteError(null); - }, - onSessionRename, - onSessionArchive, - onFork: forkSession - }, category.key))] + onKeyDown: (e) => { + if (e.key === "Enter") confirmGroupDialog(); + } + }), + groupNameIssue !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgAddError", + role: "alert", + children: groupNameIssue + }), + groupError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgAddError", + role: "alert", + children: groupError + }) + ] + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { + open: groupDeleteTarget !== null, + onClose: () => { + setGroupDeleteTarget(null); + }, + closeLabel: t("close"), + title: t("group.deleteTitle"), + footer: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "outline", + onClick: () => { + setGroupDeleteTarget(null); + }, + children: t("group.deleteCancel") + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "outline", + disabled: groupDeleting, + onClick: confirmGroupDelete, + children: t("group.delete") + })] }), + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgAddError", + children: t("group.deleteConfirm") + }), groupDeleteError !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgAddError", + role: "alert", + children: groupDeleteError })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { @@ -1047,19 +1654,37 @@ window.__ModuleLoader__.load({ }); } /** Resolve the category label containing the current session (auto-expand helper). */ - function categoriesForCurrent(config, workspaces, current) { + function categoriesForCurrent(config, workspaces, current, manual) { const workspace = workspaces.find((w) => w.sessionIds.includes(current)); if (workspace === void 0) return void 0; - 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 }) { + const categoryLine = dragIndicator?.mode === "line" && dragIndicator.row.kind === "category" && dragIndicator.row.key === category.key ? dragIndicator.before ? "before" : "after" : void 0; + const categoryInto = dragIndicator?.mode === "into" && dragIndicator.categoryKey === category.key; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { role: "group", children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CategoryRow, { node: category, t, - onToggle: onToggleCategory + onToggle: onToggleCategory, + ...manageable ? { + onRename: onGroupRename, + onDelete: onGroupDelete, + onDragStartCategory + } : {}, + dropActive: categoryInto, + ...categoryLine !== void 0 ? { insertLine: categoryLine } : {}, + onRowDragOver: onDragOverRow({ + kind: "category", + key: category.key + }), + onRowDragLeave: onDragLeaveRow, + onRowDrop: onDropRow(category.key, { + kind: "category", + key: category.key + }) }), category.expanded && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { role: "group", children: category.workspaces.map((workspace) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { @@ -1078,7 +1703,23 @@ window.__ModuleLoader__.load({ }, 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) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { node: session, currentId: current, @@ -1098,7 +1739,7 @@ window.__ModuleLoader__.load({ * 分类文件夹 → 项目文件夹 → 命中会话行. 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 }) { const currentRemote = remote.query === query ? remote : { query, status: "loading", @@ -1114,12 +1755,13 @@ window.__ModuleLoader__.load({ currentRemote, resultLimit ]); - const groups = (0, react.useMemo)(() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, matches.snippetsBySession), [ + const groups = (0, react.useMemo)(() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession), [ list, workspaces, config, matches, - archivedSessionIds + archivedSessionIds, + manual ]); const pending = currentRemote.status === "loading"; const failed = currentRemote.status === "error"; @@ -1211,6 +1853,22 @@ window.__ModuleLoader__.load({ "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": "归档", @@ -1259,6 +1917,22 @@ window.__ModuleLoader__.load({ "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", diff --git a/lib/client.js.map b/lib/client.js.map index ef22741..8ff2cb6 100644 --- a/lib/client.js.map +++ b/lib/client.js.map @@ -1 +1 @@ -{"version":3,"file":"client.js","names":["defineStore","indexSubagentDescendants","IconTriangleRightFill14","IconFolderOpen16","IconFolderClose16","useState","IconEditOutline16","IconTrashOutline16","Menu","IconEllipsisOutline16","IconPlusOutline16","IconBranchOutline16","IconArchiveOutline20","StateDot","css","useState","useRef","useMemo","IconSearchOutline16","IconCloseFill14","Tooltip","IconProjectAddOutline16","Modal","Button"],"sources":["../src/client/store-core.ts","../src/client/stores.ts","../src/core/types.ts","../src/core/matcher.ts","../src/client/tree.ts","../src/client/rows.tsx","../src/client/GroupsBrowser.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Pure expansion-state transforms for the workspace-groups store. Kept free\n * of any runtime import so both the store (which binds them via defineStore)\n * and unit tests (which exercise them directly) share one implementation.\n *\n * Expansion semantics follow the official ui-workspace store: collapse\n * WRITES `false` (never deletes the key). The browser's auto-expand guard\n * uses `Object.hasOwn` — a present `false` means \"user deliberately\n * collapsed this\" and must NOT be re-expanded; only a fully absent key means\n * \"never touched\" and may auto-expand. (Earlier versions deleted the key on\n * collapse, which made the current category/workspace impossible to fold.)\n */\n\n/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */\nexport interface GroupsViewState {\n /** Category folder expansion keyed by category label (absent = never touched). */\n categoryExpansion: Record\n /** Workspace folder expansion keyed by workspace id (absent = never touched). */\n workspaceExpansion: Record\n}\n\n/** Collapse writes `false` (key retained); expand writes `true`. */\nexport function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\n state.categoryExpansion[key] = expanded\n}\n\n/** Collapse writes `false` (key retained); expand writes `true`. */\nexport function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\n state.workspaceExpansion[key] = expanded\n}\n\n/** Drop expansion keys that no longer exist (renames/deletes/config edits). */\nexport function retainKeysImpl(\n state: GroupsViewState,\n categoryKeys: readonly string[],\n workspaceKeys: readonly string[],\n): void {\n state.categoryExpansion = Object.fromEntries(\n Object.entries(state.categoryExpansion).filter(([key]) => categoryKeys.includes(key)),\n )\n state.workspaceExpansion = Object.fromEntries(\n Object.entries(state.workspaceExpansion).filter(([key]) => workspaceKeys.includes(key)),\n )\n}\n","/**\n * The workspace-groups viewing store: category / workspace folder expansion,\n * persisted across reloads under an independent key (the official\n * ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch\n * it). Module level exports the factory only (a module-level handle would pin\n * the store identity across plugin reloads); register() receives the factory\n * and the browser derives its PropsStore share from the return type.\n *\n * The action implementations live in `store-core.ts` (pure, runtime-free) so\n * unit tests exercise the real semantics without a browser module loader;\n * this file only binds them through defineStore.\n */\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client'\nimport {\n retainKeysImpl,\n setCategoryExpandedImpl,\n setWorkspaceExpandedImpl,\n type GroupsViewState,\n} from './store-core.ts'\n\n/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */\ntype GroupsViewActions = {\n setCategoryExpanded: typeof setCategoryExpandedImpl\n setWorkspaceExpanded: typeof setWorkspaceExpandedImpl\n retainKeys: typeof retainKeysImpl\n}\n\n/**\n * Create the workspace-groups viewing store handle.\n * @returns the store handle (spec + type + identity + factory in one).\n */\nexport function createGroupsViewStore(): EngineStoreHandle {\n return defineStore({\n init: () => ({ categoryExpansion: {}, workspaceExpansion: {} }),\n persist: 'dsh.workspace.groups.view.v1',\n actions: {\n setCategoryExpanded: setCategoryExpandedImpl,\n setWorkspaceExpanded: setWorkspaceExpandedImpl,\n retainKeys: retainKeysImpl,\n },\n })\n}\n\nexport type { GroupsViewState } from './store-core.ts'\n","/**\n * Shared config types for dsh-workspace-groups. Pure types (zero runtime\n * deps) so both halves — the node half (sidecar YAML reading) and the\n * browser half (tree derivation) — compile against the same contract.\n */\n\n/** One classification rule: any rule that matches places the workspace in the category. */\nexport interface GroupRule {\n /** Absolute path prefix match (normalized, case-sensitive). */\n pathPrefix?: string\n /** Case-insensitive substring match against the workspace display title. */\n nameContains?: string\n /** Case-insensitive substring match against the workspace directory basename. */\n basenameContains?: string\n /** Exact absolute path match (normalized). */\n pathExact?: string\n}\n\n/** One category folder in the sidebar tree. */\nexport interface GroupCategory {\n /** Display label of the category folder. */\n name: string\n /** Rules; a workspace is classified here when ANY rule matches. */\n rules: GroupRule[]\n}\n\n/** The full sidecar configuration (mirrors workspace-groups.yaml). */\nexport interface GroupsConfig {\n /** Category folders, in render order. First match wins. */\n categories: GroupCategory[]\n}\n\n/** The label of the fallback bucket for unmatched workspaces. */\nexport const UNCATEGORIZED_LABEL = '未分类'\n\n/** Normalize a path for prefix matching: trailing slashes stripped. */\nexport function normalizePath(path: string): string {\n return path.replace(/[/\\\\]+$/, '')\n}\n","/**\n * Pure classification logic: decides which category a workspace belongs to.\n * Shared by the host half (validation) and the client half (tree derivation),\n * so the rule semantics can never drift between the config surface and the\n * rendered tree.\n */\nimport { normalizePath, type GroupCategory, type GroupRule } from './types.ts'\n\n/** One rule match against a workspace's path and title. */\nfunction ruleMatches(rule: GroupRule, path: string, title: string): boolean {\n const normalized = normalizePath(path)\n if (rule.pathPrefix !== undefined && normalized.startsWith(normalizePath(rule.pathPrefix))) return true\n if (rule.pathExact !== undefined && normalized === normalizePath(rule.pathExact)) return true\n if (rule.nameContains !== undefined && title.toLowerCase().includes(rule.nameContains.toLowerCase())) return true\n if (rule.basenameContains !== undefined) {\n const base = path.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop() ?? ''\n if (base.toLowerCase().includes(rule.basenameContains.toLowerCase())) return true\n }\n return false\n}\n\n/**\n * Classify a workspace into its category.\n * @param categories - configured categories, in render order.\n * @param path - workspace canonical directory path.\n * @param title - workspace display title.\n * @returns the matching category, or undefined when no rule matches.\n */\nexport function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {\n for (const category of categories) {\n if (category.rules.some(rule => ruleMatches(rule, path, title))) return category\n }\n return undefined\n}\n","/**\n * Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →\n * 会话行. Pure derivation — all inputs are snapshots; the renderer never\n * scans. Session visibility rules mirror the official ui-workspace tree\n * (blank rows only when current, archived excluded, subagent rows excluded).\n */\nimport {\n indexSubagentDescendants,\n type PendingInteractionStatus,\n type SessionId,\n type SessionListState,\n type SessionSearchResultItem,\n type SessionSummary,\n type SubagentDescendantSummary,\n type WorkspaceId,\n type WorkspaceView,\n} from '@deepseek-ai/dsh-client-runtime/client'\nimport { classify } from '../core/matcher.ts'\nimport { UNCATEGORIZED_LABEL, type GroupsConfig } from '../core/types.ts'\n\n/** One top-level session row inside a workspace folder. */\nexport interface SessionNode {\n id: SessionId\n /** Stored display title; blank rows show the localized New Session label. */\n title: string\n /** The provisional blank session (renderer shows the localized New Session title). */\n blank: boolean\n pendingInteraction?: PendingInteractionStatus\n running: boolean\n /** Running descendants connected through uninterrupted subagent-origin lineage. */\n runningSubagentCount: number\n /** Finished running while not selected and not yet opened (the green \"done\" reminder dot). */\n completed: boolean\n updatedAt: number\n /** Search-hit marker (rendered with a highlighted tint in search mode). */\n matched?: boolean\n /** Content-match snippet from the Host search (search mode only). */\n snippet?: string\n}\n\n/** One workspace folder row inside a category folder. */\nexport interface WorkspaceGroupNode {\n workspaceId: WorkspaceId\n /** Canonical host directory path. */\n path: string\n /** Display title. */\n label: string\n /** Workspace creation time (epoch ms). */\n createdAt: number\n /** Total visible sessions in the folder. */\n sessionCount: number\n expanded: boolean\n /** The folder contains the selected session (active folder tint). */\n containsCurrent: boolean\n /** Visible session rows (empty while the folder is folded). */\n sessions: readonly SessionNode[]\n}\n\n/** One category folder at the top of the tree. */\nexport interface CategoryNode {\n /** Stable category key: the configured label, or the uncategorized bucket. */\n key: string\n /** Display label. */\n label: string\n expanded: boolean\n /** The category contains the selected session (active folder tint). */\n containsCurrent: boolean\n /** Workspace folders in host order. */\n workspaces: readonly WorkspaceGroupNode[]\n}\n\n/** Viewing state consumed by the derivation. */\nexport interface GroupsTreeView {\n expandedCategories: readonly string[]\n expandedWorkspaces: readonly string[]\n}\n\n/** Key of the uncategorized bucket (matches the config fallback label). */\nexport const UNCATEGORIZED_KEY = UNCATEGORIZED_LABEL\n\n/** Directory display label: basename of the path (both separators accepted). */\nexport function workspaceLabel(cwd: string | undefined): string {\n if (cwd === undefined || cwd === '') return UNCATEGORIZED_LABEL\n const base = cwd.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop()\n return base !== undefined && base !== '' ? base : cwd\n}\n\n/** Ordinary sessions are visible; blank only when current; archived/subagent never. */\nfunction sessionVisible(session: SessionSummary, current: SessionId | undefined, archived: ReadonlySet): boolean {\n return session.origin !== 'subagent'\n && !archived.has(session.id)\n && (!session.blank || session.id === current)\n}\n\n/** Blank rows display the localized New Session label (never enters search). */\nfunction sessionTitle(session: SessionSummary): string {\n return session.blank ? 'New Session' : session.displayTitle\n}\n\nfunction sessionNode(\n s: SessionSummary,\n descendants: ReadonlyMap,\n): SessionNode {\n return {\n id: s.id,\n title: sessionTitle(s),\n blank: s.blank,\n running: s.running,\n runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,\n completed: s.completed === true,\n updatedAt: s.updatedAt,\n ...(s.pendingInteraction === undefined ? {} : { pendingInteraction: s.pendingInteraction }),\n }\n}\n\n/** Visible sessions of one workspace in its stored account order. */\nfunction workspaceSessions(\n list: SessionListState,\n workspace: WorkspaceView,\n archived: ReadonlySet,\n descendants: ReadonlyMap,\n): SessionNode[] {\n const nodes: SessionNode[] = []\n for (const id of workspace.sessionIds) {\n const summary = list.byId[id]\n if (summary === undefined) continue // account may lead the list pull; appears when the summary lands\n if (!sessionVisible(summary, list.current, archived)) continue\n nodes.push(sessionNode(summary, descendants))\n }\n return nodes\n}\n\n/**\n * Derive the three-level tree.\n * @param list - sessions list snapshot (`current` feeds containsCurrent).\n * @param workspaces - real workspaces in stable Host order.\n * @param archivedSessionIds - registry-global archive set.\n * @param config - sidecar grouping config.\n * @param view - local expansion arrays.\n * @returns category sections in render order (configured categories first, uncategorized last).\n */\nexport function deriveGroups(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n archivedSessionIds: readonly SessionId[],\n config: GroupsConfig,\n view: GroupsTreeView,\n): CategoryNode[] {\n const archived = new Set(archivedSessionIds)\n const expandedCategories = new Set(view.expandedCategories)\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\n const descendants = indexSubagentDescendants(list.byId)\n\n // Bucket workspaces by category, preserving host order inside each bucket.\n const byCategory = new Map()\n const categorized = new Set()\n for (const category of config.categories) {\n byCategory.set(category.name, [])\n }\n for (const workspace of workspaces) {\n const category = classify(config.categories, workspace.path, workspace.title)\n const key = category !== undefined ? category.name : UNCATEGORIZED_KEY\n if (!byCategory.has(key)) byCategory.set(key, [])\n byCategory.get(key)!.push(workspace)\n categorized.add(workspace.workspaceId)\n }\n\n const currentWorkspaceId = list.current === undefined\n ? undefined\n : workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId\n\n const nodes: CategoryNode[] = []\n for (const [key, bucket] of byCategory) {\n if (bucket.length === 0) continue\n const expanded = expandedCategories.has(key)\n const workspaceNodes: WorkspaceGroupNode[] = []\n let containsCurrent = false\n for (const workspace of bucket) {\n const sessions = workspaceSessions(list, workspace, archived, descendants)\n const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)\n const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId\n if (wsContainsCurrent) containsCurrent = true\n workspaceNodes.push({\n workspaceId: workspace.workspaceId,\n path: workspace.path,\n label: workspace.title,\n createdAt: Date.parse(workspace.createdAt),\n sessionCount: sessions.length,\n expanded: wsExpanded,\n containsCurrent: wsContainsCurrent,\n sessions: wsExpanded ? sessions : [],\n })\n }\n nodes.push({\n key,\n label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,\n expanded,\n containsCurrent,\n workspaces: workspaceNodes,\n })\n }\n return nodes\n}\n\n/** Recency comparator: newest first, id as the deterministic tiebreak. */\nfunction byRecency(a: SessionSummary, b: SessionSummary): number {\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\n return a.id < b.id ? -1 : 1\n}\n\n/** Bounded set of matched sessions plus content snippets (feeds the search tree). */\nexport interface SearchMatchSet {\n /** Session ids that matched (local metadata hits + Host content hits). */\n matchedIds: ReadonlySet\n /** Content-match snippets keyed by session id (Host search only). */\n snippetsBySession: ReadonlyMap\n hasMore: boolean\n}\n\n/**\n * Compute the matched-session set: immediate title/Workspace substring matches\n * from the local list, merged with ranked Host content matches. The consumer\n * (SearchBody) derives the pruned three-level tree from these ids.\n */\nexport function deriveSearchMatches(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n config: GroupsConfig,\n query: string,\n archivedSessionIds: readonly SessionId[],\n content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },\n limit: number,\n): SearchMatchSet {\n const q = query.trim().toLowerCase()\n if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }\n const archived = new Set(archivedSessionIds)\n const descendants = indexSubagentDescendants(list.byId)\n\n const workspaceBySession = new Map()\n for (const workspace of workspaces) {\n for (const sessionId of workspace.sessionIds) {\n if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)\n }\n }\n const labelOf = (summary: SessionSummary): string =>\n workspaceBySession.get(summary.id)?.title ?? workspaceLabel(summary.cwd)\n\n const local: SessionSummary[] = []\n for (const id of list.ids) {\n const summary = list.byId[id]\n if (summary === undefined || summary.blank || !sessionVisible(summary, list.current, archived)) continue\n if (\n sessionTitle(summary).toLowerCase().includes(q)\n || labelOf(summary).toLowerCase().includes(q)\n ) {\n local.push(summary)\n }\n }\n local.sort(byRecency)\n\n const ordered: SessionSummary[] = []\n const included = new Set()\n const include = (summary: SessionSummary): void => {\n if (included.has(summary.id)) return\n included.add(summary.id)\n ordered.push(summary)\n }\n for (const summary of local) include(summary)\n for (const item of content.items) {\n const summary = list.byId[item.sessionId]\n if (summary !== undefined && !summary.blank && sessionVisible(summary, list.current, archived)) include(summary)\n }\n\n const snippets = new Map()\n for (const item of content.items) {\n if (item.snippet !== undefined) snippets.set(item.sessionId, item.snippet)\n }\n\n return {\n matchedIds: ordered.slice(0, limit).reduce((set, summary) => { set.add(summary.id); return set }, new Set()),\n snippetsBySession: snippets,\n hasMore: content.hasMore || ordered.length > limit,\n }\n}\n\n/**\n * Build a three-level search tree containing ONLY the branches that hold a\n * matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched\n * session carries `matched: true` so rows render with the search-hit tint.\n *\n * @param list - sessions list snapshot.\n * @param workspaces - real workspaces in stable Host order.\n * @param config - sidecar grouping config.\n * @param matchedIds - set of session ids that matched the query.\n * @param archivedSessionIds - registry-global archive set.\n * @param snippetsBySession - optional content-match snippets keyed by session id.\n * @returns categories in render order, pruned to matched branches only.\n */\nexport function deriveSearchGroups(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n config: GroupsConfig,\n matchedIds: ReadonlySet,\n archivedSessionIds: readonly SessionId[],\n snippetsBySession?: ReadonlyMap,\n): CategoryNode[] {\n const archived = new Set(archivedSessionIds)\n const descendants = indexSubagentDescendants(list.byId)\n\n const byCategory = new Map()\n for (const category of config.categories) byCategory.set(category.name, [])\n\n for (const workspace of workspaces) {\n // Only sessions that matched the query and are visible in this folder.\n const nodes: SessionNode[] = []\n for (const id of workspace.sessionIds) {\n const summary = list.byId[id]\n if (summary === undefined || !matchedIds.has(id)) continue\n if (!sessionVisible(summary, list.current, archived)) continue\n const node = sessionNode(summary, descendants)\n const snippet = snippetsBySession?.get(id)\n nodes.push({\n ...node,\n matched: true,\n ...(snippet === undefined ? {} : { snippet }),\n })\n }\n if (nodes.length === 0) continue\n\n const category = classify(config.categories, workspace.path, workspace.title)\n const key = category !== undefined ? category.name : UNCATEGORIZED_KEY\n if (!byCategory.has(key)) byCategory.set(key, [])\n byCategory.get(key)!.push({\n workspaceId: workspace.workspaceId,\n path: workspace.path,\n label: workspace.title,\n createdAt: Date.parse(workspace.createdAt),\n sessionCount: nodes.length,\n expanded: true,\n containsCurrent: false,\n sessions: nodes,\n })\n }\n\n const categories: CategoryNode[] = []\n for (const [key, workspaceNodes] of byCategory) {\n if (workspaceNodes.length === 0) continue\n categories.push({\n key,\n label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,\n expanded: true,\n containsCurrent: false,\n workspaces: workspaceNodes,\n })\n }\n return categories\n}\n","/**\n * Row components for the workspace-groups tree. Kept dependency-light: they\n * consume only React, primitives (StateDot/Menu/icons), and the shared CSS\n * string. Each row owns its hover actions menu; dialogs live in the browser\n * root so they survive row unmounts during collapse.\n */\nimport { useState } from 'react'\nimport {\n IconArchiveOutline20,\n IconBranchOutline16,\n IconEditOutline16,\n IconEllipsisOutline16,\n IconFolderClose16,\n IconFolderOpen16,\n IconPlusOutline16,\n IconTriangleRightFill14,\n IconTrashOutline16,\n Menu,\n StateDot,\n type StateDotState,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { WorkspaceGroupsKey } from './locales.ts'\nimport type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'\n\ntype T = TranslateNS<'workspaceGroups'>\n\n/** Pending interaction status → primitives StateDot state. */\nfunction pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {\n switch (status) {\n case 'approval':\n case 'plan-review':\n case 'question':\n return 'warning'\n default:\n return undefined\n }\n}\n\n/** Primary status dot state for a session row. */\nexport function sessionDotState(node: Pick): StateDotState {\n if (pendingState(node.pendingInteraction) !== undefined) return 'warning'\n if (node.running || node.runningSubagentCount > 0) return 'ongoing'\n return node.completed ? 'done' : 'done'\n}\n\n/** Compact relative time (\"now\"/\"5min\"/\"3h\"/\"2d\"/\"4mo\"/\"1y\"). */\nexport function relativeTimeLabel(updatedAt: number, now: number): string {\n const diff = Math.max(0, now - updatedAt)\n const MIN = 60_000\n const HOUR = 3_600_000\n const DAY = 86_400_000\n if (diff < MIN) return 'now'\n if (diff < HOUR) return `${Math.floor(diff / MIN)}min`\n if (diff < DAY) return `${Math.floor(diff / HOUR)}h`\n if (diff < 30 * DAY) return `${Math.floor(diff / DAY)}d`\n if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`\n return `${Math.floor(diff / (365 * DAY))}y`\n}\n\n/** One category folder row. */\nexport function CategoryRow({ node, t, onToggle }: {\n node: CategoryNode\n t: T\n onToggle: () => void\n}) {\n const count = node.workspaces.length\n return (\n \n \n \n \n \n {node.expanded ? : }\n \n {node.label}\n {count}\n \n )\n}\n\n/** One workspace folder row inside a category. */\nexport function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }: {\n node: WorkspaceGroupNode\n t: T\n onToggle: () => void\n onNewSession: () => void\n onRename: () => void\n onDelete: () => void\n}) {\n const [menuOpen, setMenuOpen] = useState(false)\n const menuItems = [\n { id: 'rename', label: t('workspace.rename'), icon: },\n { id: 'delete', label: t('workspace.delete'), icon: , danger: true },\n ]\n return (\n \n \n \n \n \n {node.expanded ? : }\n \n {node.label}\n \n { setMenuOpen(false) }}\n items={menuItems}\n onSelect={(id) => {\n setMenuOpen(false)\n if (id === 'rename') onRename()\n if (id === 'delete') onDelete()\n }}\n portal\n closeOnPointerLeave\n anchor={(\n { e.stopPropagation(); setMenuOpen(v => !v) }}\n >\n \n \n )}\n />\n { e.stopPropagation(); onNewSession() }}\n >\n \n \n \n \n )\n}\n\n/** One session leaf row. */\nexport function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {\n node: SessionNode\n currentId: string | undefined\n now: number\n t: T\n onOpen: (id: SessionNode['id']) => void\n onRename: (id: SessionNode['id'], currentTitle: string) => void\n onFork: (id: SessionNode['id']) => void\n onArchive: (id: SessionNode['id']) => void\n}) {\n const selected = node.id === currentId\n const [menuOpen, setMenuOpen] = useState(false)\n const showStatus = true\n const menuItems = [\n { id: 'rename', label: t('session.rename'), icon: },\n { id: 'fork', label: t('session.fork'), icon: },\n { id: 'archive', label: t('session.archive'), icon: },\n ]\n return (\n { onOpen(node.id) }}\n >\n \n {showStatus && }\n \n {node.title}\n {!node.blank && {relativeTimeLabel(node.updatedAt, now)}}\n {node.snippet !== undefined && (\n {node.snippet}\n )}\n {!node.blank && (\n \n { setMenuOpen(false) }}\n items={menuItems}\n onSelect={(id) => {\n setMenuOpen(false)\n if (id === 'rename') onRename(node.id, node.title)\n if (id === 'fork') onFork(node.id)\n if (id === 'archive') onArchive(node.id)\n }}\n portal\n closeOnPointerLeave\n anchor={(\n { e.stopPropagation(); setMenuOpen(v => !v) }}\n >\n \n \n )}\n />\n \n )}\n \n )\n}\n\nexport type { T }\n","/**\n * The workspace-groups browsing region filling the sidebar shell's\n * `sidebar.workspaces` hole: section header (title + right-aligned search +\n * add workspace), the three-level tree (category → workspace → session),\n * and the workspace/session dialogs. Wide state renders the full browser;\n * rail state renders the two region icons (search / add workspace) as 36px\n * controls on the shell's shared rail entry path, each requesting expansion\n * through the owner share.\n *\n * Data: workspaces/sessions via the framework global hooks; grouping config\n * via the host half's `/workspace-groups/config` route (refetched on mount).\n */\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport {\n Button,\n IconCloseFill14,\n IconProjectAddOutline16,\n IconSearchOutline16,\n Modal,\n Tooltip,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { SessionId, SessionListState, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'\nimport { classify } from '../core/matcher.ts'\nimport type { GroupsConfig } from '../core/types.ts'\nimport type { GroupsBrowserProps } from './contract.ts'\nimport { deriveGroups, deriveSearchGroups, deriveSearchMatches, type CategoryNode } from './tree.ts'\nimport { CategoryRow, SessionRow, WorkspaceRow } from './rows.tsx'\nimport css from './styles.css?inline'\n\nconst SEARCH_DEBOUNCE_MS = 250\nconst SEARCH_QUERY_MAX_CODE_UNITS = 500\n\nfunction sanitizeSearchQuery(value: string): string {\n const withoutNul = value.replaceAll('\\0', '')\n if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul\n return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS)\n}\n\n/** Immutable membership toggle for the local expand-all array. */\nfunction toggled(list: readonly string[], key: string): string[] {\n return list.includes(key) ? list.filter(k => k !== key) : [...list, key]\n}\n\ninterface RemoteSearchState {\n query: string\n status: 'idle' | 'loading' | 'ready' | 'error'\n items: readonly SessionSearchResultItem[]\n hasMore: boolean\n}\n\n/** Minimal fetch of the grouping config (host route; no-cache revalidation). */\nasync function fetchGroupsConfig(): Promise {\n const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })\n if (!response.ok) throw new Error(`config request failed: ${response.status}`)\n const body = (await response.json()) as GroupsConfig\n return Array.isArray(body.categories) ? body : { categories: [] }\n}\n\n/**\n * Render the browsing region.\n * @param props - composed slot props (shell owner share + store + injected actions).\n * @returns the region element tree.\n */\nexport function GroupsBrowser({\n wide,\n expandSidebar,\n useSessions,\n useWorkspaces,\n useStore,\n actions,\n startSession,\n open,\n renameSession,\n forkSession,\n renameWorkspace,\n deleteWorkspace,\n insertWorkspaceBefore,\n archiveSession,\n insertSessionBefore,\n createWorkspace,\n pickDirectory,\n searchSessions,\n searchResultLimit,\n t,\n}: GroupsBrowserProps) {\n // Inject the stylesheet once per fiber; dispose removes it (HMR safe).\n useEffect(() => {\n const style = document.createElement('style')\n style.setAttribute('data-plugin', 'dsh-workspace-groups')\n style.textContent = css\n document.head.append(style)\n return () => { style.remove() }\n }, [])\n\n // Grouping config from the host route.\n const [config, setConfig] = useState({ categories: [] })\n const [configError, setConfigError] = useState(null)\n const reloadConfig = () => {\n setConfigError(null)\n fetchGroupsConfig().then(setConfig).catch((reason: unknown) => {\n setConfigError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n useEffect(() => { reloadConfig() }, [])\n\n const workspaces = useWorkspaces(state => state.items)\n const workspacePhase = useWorkspaces(state => state.phase)\n const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)\n const categoryExpansion = useStore(s => s.categoryExpansion)\n const workspaceExpansion = useStore(s => s.workspaceExpansion)\n\n const list = useSessions(s => s)\n const current = list.current\n const currentWorkspaceKey = current === undefined\n ? undefined\n : (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)\n\n // Auto-expand the category + workspace containing the current session, but\n // ONLY when the user has never touched that key (`Object.hasOwn`): a\n // present `false` is a deliberate collapse and must stay folded. Without\n // this guard the effect re-expands the just-collapsed current category on\n // every store change (the reported \"cannot collapse\" bug).\n useEffect(() => {\n if (current === undefined || currentWorkspaceKey === undefined) return\n const category = categoriesForCurrent(config, workspaces, current)\n if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {\n actions.setCategoryExpanded(category, true)\n }\n if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {\n actions.setWorkspaceExpanded(currentWorkspaceKey, true)\n }\n }, [current, currentWorkspaceKey, config, workspaces, categoryExpansion, workspaceExpansion, actions])\n\n // Drop expansion keys that no longer exist (config edits / workspace deletion).\n useEffect(() => {\n if (workspacePhase !== 'ready') return\n actions.retainKeys(\n config.categories.map(c => c.name),\n workspaces.map(w => w.workspaceId as string),\n )\n }, [actions, config, workspacePhase, workspaces])\n\n const [query, setQuery] = useState('')\n const [searchExpanded, setSearchExpanded] = useState(false)\n const normalizedQuery = sanitizeSearchQuery(query).trim()\n const [remoteSearch, setRemoteSearch] = useState({\n query: '', status: 'idle', items: [], hasMore: false,\n })\n const searchInput = useRef(null)\n const searchRoot = useRef(null)\n\n // Search debounce + abort, same posture as the official browser.\n useEffect(() => {\n if (normalizedQuery === '') {\n setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false })\n return\n }\n const controller = new AbortController()\n setRemoteSearch({ query: normalizedQuery, status: 'loading', items: [], hasMore: false })\n const timer = window.setTimeout(() => {\n searchSessions(normalizedQuery, controller.signal).then((result) => {\n if (controller.signal.aborted) return\n setRemoteSearch({ query: normalizedQuery, status: 'ready', items: result.items, hasMore: result.hasMore })\n }).catch(() => {\n if (controller.signal.aborted) return\n setRemoteSearch({ query: normalizedQuery, status: 'error', items: [], hasMore: false })\n })\n }, SEARCH_DEBOUNCE_MS)\n return () => {\n window.clearTimeout(timer)\n controller.abort()\n }\n }, [normalizedQuery, searchSessions])\n\n // Outside-click dismissal of the search box.\n useEffect(() => {\n if (!wide || !searchExpanded) return\n const onClick = (event: MouseEvent): void => {\n if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return\n searchInput.current?.blur()\n if (normalizedQuery !== '') return\n setSearchExpanded(false)\n }\n document.addEventListener('click', onClick)\n return () => { document.removeEventListener('click', onClick) }\n }, [normalizedQuery, wide, searchExpanded])\n\n const expandedCategories = useMemo(\n () => Object.entries(categoryExpansion).filter(([, v]) => v).map(([k]) => k),\n [categoryExpansion],\n )\n const expandedWorkspaces = useMemo(\n () => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),\n [workspaceExpansion],\n )\n const groups = useMemo(\n () => deriveGroups(list, workspaces, archivedSessionIds, config, {\n expandedCategories,\n expandedWorkspaces,\n }),\n [list, workspaces, archivedSessionIds, config, expandedCategories, expandedWorkspaces],\n )\n\n // Add workspace flow: self-contained (no directory-flow hole dependency).\n const [adding, setAdding] = useState(false)\n const [addError, setAddError] = useState(null)\n const [addErrorOpen, setAddErrorOpen] = useState(false)\n const addWorkspace = async (): Promise => {\n if (adding) return\n setAdding(true)\n setAddError(null)\n setAddErrorOpen(false)\n try {\n const path = await pickDirectory()\n if (path === null) return // cancelled\n const workspace = await createWorkspace({ path })\n startSession(workspace.workspaceId)\n } catch (reason) {\n const message = reason instanceof Error ? reason.message : String(reason)\n setAddError(message)\n setAddErrorOpen(true)\n } finally {\n setAdding(false)\n }\n }\n\n // Workspace rename dialog.\n const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null)\n const [renameDraft, setRenameDraft] = useState('')\n const [renaming, setRenaming] = useState(false)\n const [renameError, setRenameError] = useState(null)\n const renameTrimmed = renameDraft.trim()\n const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle\n && workspaces.some(w => w.title === renameTrimmed)\n const renameBlocked = renaming || renameTrimmed === '' || renameTarget === null\n || renameTrimmed === renameTarget.currentTitle || renameDuplicate\n const confirmRename = () => {\n if (renameBlocked || renameTarget === null) return\n setRenaming(true)\n setRenameError(null)\n renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {\n setRenaming(false)\n setRenameTarget(null)\n }).catch((reason: unknown) => {\n setRenaming(false)\n setRenameError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n // Workspace delete dialog.\n const [deleteTarget, setDeleteTarget] = useState<{ workspaceId: WorkspaceId; title: string } | null>(null)\n const [deleting, setDeleting] = useState(false)\n const [deleteError, setDeleteError] = useState(null)\n const confirmDelete = () => {\n if (deleting || deleteTarget === null) return\n setDeleting(true)\n setDeleteError(null)\n deleteWorkspace(deleteTarget.workspaceId).then(() => {\n setDeleting(false)\n setDeleteTarget(null)\n }).catch((reason: unknown) => {\n setDeleting(false)\n setDeleteError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n // Session rename dialog.\n const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionId; currentTitle: string } | null>(null)\n const [sessionRenameDraft, setSessionRenameDraft] = useState('')\n const [sessionRenaming, setSessionRenaming] = useState(false)\n const [sessionRenameError, setSessionRenameError] = useState(null)\n const sessionRenameTrimmed = sessionRenameDraft.trim()\n const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null\n const confirmSessionRename = () => {\n if (sessionRenameBlocked || sessionRenameTarget === null) return\n setSessionRenaming(true)\n setSessionRenameError(null)\n renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {\n setSessionRenaming(false)\n setSessionRenameTarget(null)\n }).catch((reason: unknown) => {\n setSessionRenaming(false)\n setSessionRenameError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n const onSessionRename = (sessionId: SessionId, currentTitle: string) => {\n setSessionRenameTarget({ sessionId, currentTitle })\n setSessionRenameDraft(currentTitle)\n setSessionRenameError(null)\n }\n\n const onSessionArchive = (sessionId: SessionId) => {\n archiveSession(sessionId).catch((reason: unknown) => {\n console.warn('session archive rejected:', reason)\n })\n }\n\n const now = Date.now()\n\n return (\n
\n
\n {wide && {t('section.workspaces')}}\n {wide && (\n
\n { setSearchExpanded(true) }}\n >\n \n \n {searchExpanded && (\n { setQuery(sanitizeSearchQuery(e.target.value)) }}\n onKeyDown={(e) => {\n if (e.key !== 'Escape') return\n setQuery('')\n setSearchExpanded(false)\n }}\n />\n )}\n {searchExpanded && (\n {\n e.stopPropagation()\n setQuery('')\n setSearchExpanded(false)\n }}\n >\n \n \n )}\n
\n )}\n \n \n \n \n \n
\n\n {!wide && (\n
\n \n { setSearchExpanded(true); expandSidebar() }}\n >\n \n \n \n
\n )}\n\n
\n {configError !== null && (\n
{t('configUnavailable')}
\n )}\n {wide && normalizedQuery !== '' ? (\n \n ) : (\n
\n {groups.length === 0 && (\n
{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}
\n )}\n {groups.map((category) => (\n { actions.setCategoryExpanded(category.key, !category.expanded) }}\n onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\n onNewSession={startSession}\n onOpen={open}\n onRenameRequest={(workspaceId, title) => {\n setRenameTarget({ workspaceId, currentTitle: title })\n setRenameDraft(title)\n setRenameError(null)\n }}\n onDeleteRequest={(workspaceId, title) => {\n setDeleteTarget({ workspaceId, title })\n setDeleteError(null)\n }}\n onSessionRename={onSessionRename}\n onSessionArchive={onSessionArchive}\n onFork={forkSession}\n />\n ))}\n
\n )}\n
\n\n {/* Workspace rename dialog */}\n { setRenameTarget(null) }}\n closeLabel={t('close')}\n title={t('workspace.renameTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n { setRenameDraft(e.target.value) }}\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmRename() }}\n />\n {renameError !== null &&
{renameError}
}\n \n\n {/* Workspace delete dialog */}\n { setDeleteTarget(null) }}\n closeLabel={t('close')}\n title={t('workspace.deleteTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n
{t('workspace.deleteConfirm')}
\n {deleteError !== null &&
{deleteError}
}\n \n\n {/* Session rename dialog */}\n { setSessionRenameTarget(null) }}\n closeLabel={t('close')}\n title={t('session.renameTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n { setSessionRenameDraft(e.target.value) }}\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmSessionRename() }}\n />\n {sessionRenameError !== null &&
{sessionRenameError}
}\n \n\n {/* Add workspace error dialog */}\n { setAddErrorOpen(false) }}\n closeLabel={t('close')}\n title={t('workspace.addErrorTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n
{addError}
\n \n
\n )\n}\n\n/** Resolve the category label containing the current session (auto-expand helper). */\nfunction categoriesForCurrent(\n config: GroupsConfig,\n workspaces: readonly WorkspaceView[],\n current: SessionId,\n): string | undefined {\n const workspace = workspaces.find(w => w.sessionIds.includes(current))\n if (workspace === undefined) return undefined\n return classify(config.categories, workspace.path, workspace.title)?.name\n}\n\n/** One category section: header row + expanded workspace folders. */\nfunction CategorySection({ category, current, now, t, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork }: {\n category: CategoryNode\n current: SessionId | undefined\n now: number\n t: GroupsBrowserProps['t']\n onToggleCategory: () => void\n onToggleWorkspace: (key: string) => void\n onNewSession: (workspaceId?: WorkspaceId) => void\n onOpen: (sessionId: SessionId) => void\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\n onSessionArchive: (sessionId: SessionId) => void\n onFork: (sessionId: SessionId) => void\n}) {\n return (\n
\n \n {category.expanded && (\n
\n {category.workspaces.map((workspace) => (\n
\n { onToggleWorkspace(workspace.workspaceId as string) }}\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\n />\n {workspace.expanded && workspace.sessions.map((session) => (\n \n ))}\n
\n ))}\n
\n )}\n
\n )\n}\n\n/**\n * Search body rendered as a three-level tree pruned to matched branches:\n * 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as\n * the idle tree, so search keeps the same folder hierarchy the user is used to.\n */\nfunction SearchBody({ list, workspaces, config, archivedSessionIds, query, remote, resultLimit, current, now, open, t }: {\n list: SessionListState\n workspaces: readonly WorkspaceView[]\n config: GroupsConfig\n archivedSessionIds: readonly SessionId[]\n query: string\n remote: RemoteSearchState\n resultLimit: number\n current: SessionId | undefined\n now: number\n open: (sessionId: SessionId) => void\n t: GroupsBrowserProps['t']\n}) {\n const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }\n const matches = useMemo(\n () => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),\n [list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],\n )\n const groups = useMemo(\n () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, matches.snippetsBySession),\n [list, workspaces, config, matches, archivedSessionIds],\n )\n const pending = currentRemote.status === 'loading'\n const failed = currentRemote.status === 'error'\n return (\n
\n {groups.map((category) => (\n
\n {}} />\n
\n {category.workspaces.map((workspace) => (\n
\n {}}\n onNewSession={() => {}}\n onRename={() => {}}\n onDelete={() => {}}\n />\n
\n {workspace.sessions.map((session) => (\n {}}\n onFork={() => {}}\n onArchive={() => {}}\n />\n ))}\n
\n
\n ))}\n
\n
\n ))}\n {pending &&
{t('search.pending')}
}\n {failed &&
{t('search.unavailable')}
}\n {!pending && groups.length === 0 && (\n
{t('search.noMatches')}
\n )}\n {matches.hasMore && (\n
{t('search.hasMore')}
\n )}\n
\n )\n}\n","/**\n * Locale dictionaries for the workspace-groups browser. The namespace is\n * `workspaceGroups` (independent from ui-workspace's `workspace` namespace).\n */\nimport type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'\n\n/** Dictionary keys of the workspaceGroups namespace (single source of truth). */\nexport type WorkspaceGroupsKey =\n | 'section.workspaces'\n | 'section.sessions'\n | 'search'\n | 'search.placeholder'\n | 'search.clear'\n | 'search.noMatches'\n | 'search.unavailable'\n | 'search.pending'\n | 'search.hasMore'\n | 'search.results.aria'\n | 'workspace.add'\n | 'workspace.addBusy'\n | 'workspace.addError'\n | 'workspace.addErrorTitle'\n | 'workspace.rename'\n | 'workspace.delete'\n | 'workspace.deleteTitle'\n | 'workspace.deleteConfirm'\n | 'workspace.deleteCancel'\n | 'workspace.renaming'\n | 'workspace.deleting'\n | 'workspace.renameTitle'\n | 'workspace.renamePlaceholder'\n | 'workspace.renameConfirm'\n | 'workspace.renameCancel'\n | 'session.new'\n | 'session.rename'\n | 'session.archive'\n | 'session.fork'\n | 'session.renameTitle'\n | 'session.renamePlaceholder'\n | 'session.renameConfirm'\n | 'session.renameCancel'\n | 'session.renaming'\n | 'uncategorized'\n | 'empty.none'\n | 'empty.noWorkspaces'\n | 'close'\n | 'cancel'\n | 'confirm'\n | 'retry'\n | 'configUnavailable'\n | 'collapse'\n | 'expandMore'\n | 'newSession'\n\nexport type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>\n\n/** Simplified Chinese dictionary. */\nexport const zh: WorkspaceGroupsDict = {\n 'section.workspaces': '工作区',\n 'section.sessions': '会话',\n search: '搜索',\n 'search.placeholder': '搜索会话…',\n 'search.clear': '清除',\n 'search.noMatches': '没有匹配的会话',\n 'search.unavailable': '搜索不可用',\n 'search.pending': '搜索中…',\n 'search.hasMore': '结果过多,请细化关键词',\n 'search.results.aria': '搜索结果',\n 'workspace.add': '添加工作区',\n 'workspace.addBusy': '正在添加…',\n 'workspace.addError': '添加失败',\n 'workspace.addErrorTitle': '无法添加工作区',\n 'workspace.rename': '重命名',\n 'workspace.delete': '删除',\n 'workspace.deleteTitle': '删除工作区',\n 'workspace.deleteConfirm': '仅删除注册信息,目录与会话日志保留。确定删除?',\n 'workspace.deleteCancel': '取消删除',\n 'workspace.renaming': '重命名中…',\n 'workspace.deleting': '删除中…',\n 'workspace.renameTitle': '重命名工作区',\n 'workspace.renamePlaceholder': '工作区名称',\n 'workspace.renameConfirm': '重命名',\n 'workspace.renameCancel': '取消',\n 'session.new': '新建会话',\n 'session.rename': '重命名会话',\n 'session.archive': '归档',\n 'session.fork': '派生',\n 'session.renameTitle': '重命名会话',\n 'session.renamePlaceholder': '会话名称',\n 'session.renameConfirm': '重命名',\n 'session.renameCancel': '取消',\n 'session.renaming': '重命名中…',\n uncategorized: '未分类',\n 'empty.none': '暂无内容',\n 'empty.noWorkspaces': '还没有工作区',\n close: '关闭',\n cancel: '取消',\n confirm: '确定',\n retry: '重试',\n configUnavailable: '分组配置不可用',\n collapse: '折叠',\n expandMore: '展开全部',\n newSession: '新建会话',\n}\n\n/** English dictionary. */\nexport const en: WorkspaceGroupsDict = {\n 'section.workspaces': 'Workspaces',\n 'section.sessions': 'Sessions',\n search: 'Search',\n 'search.placeholder': 'Search sessions…',\n 'search.clear': 'Clear',\n 'search.noMatches': 'No matching sessions',\n 'search.unavailable': 'Search unavailable',\n 'search.pending': 'Searching…',\n 'search.hasMore': 'Too many results — refine the query',\n 'search.results.aria': 'Search results',\n 'workspace.add': 'Add workspace',\n 'workspace.addBusy': 'Adding…',\n 'workspace.addError': 'Add failed',\n 'workspace.addErrorTitle': 'Could not add workspace',\n 'workspace.rename': 'Rename',\n 'workspace.delete': 'Delete',\n 'workspace.deleteTitle': 'Delete workspace',\n 'workspace.deleteConfirm': 'Only the registration is removed; the directory and session logs stay. Delete?',\n 'workspace.deleteCancel': 'Cancel delete',\n 'workspace.renaming': 'Renaming…',\n 'workspace.deleting': 'Deleting…',\n 'workspace.renameTitle': 'Rename workspace',\n 'workspace.renamePlaceholder': 'Workspace name',\n 'workspace.renameConfirm': 'Rename',\n 'workspace.renameCancel': 'Cancel',\n 'session.new': 'New Session',\n 'session.rename': 'Rename session',\n 'session.archive': 'Archive',\n 'session.fork': 'Fork',\n 'session.renameTitle': 'Rename session',\n 'session.renamePlaceholder': 'Session name',\n 'session.renameConfirm': 'Rename',\n 'session.renameCancel': 'Cancel',\n 'session.renaming': 'Renaming…',\n uncategorized: 'Uncategorized',\n 'empty.none': 'Nothing here',\n 'empty.noWorkspaces': 'No workspaces yet',\n close: 'Close',\n cancel: 'Cancel',\n confirm: 'Confirm',\n retry: 'Retry',\n configUnavailable: 'Grouping config unavailable',\n collapse: 'Collapse',\n expandMore: 'Show all',\n newSession: 'New Session',\n}\n","/**\n * dsh-workspace-groups client half: registers the three-level grouped\n * workspace browser into the `sidebar.workspaces` slot, shadowing the\n * official ui-workspace browser.\n *\n * Shadowing mechanics (SlotCore semantics):\n * - `sidebar.workspaces` is a `single`/`root` slot. The official browser\n * registers at priority 0; this entry registers at priority -1, and the\n * single-cell shadow rule makes the LOWEST priority the winner — the\n * sidebar renders this browser instead of the official one.\n * - This entry deliberately declares NO child slots: the official entry\n * already declared `sidebar.workspaces.directoryFlow` (a second declaration\n * of an occupied child key throws). Add Workspace is therefore self-\n * contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.\n */\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type { GroupsBrowserInjected } from './contract.ts'\nimport { createGroupsViewStore } from './stores.ts'\nimport { GroupsBrowser } from './GroupsBrowser.tsx'\nimport { en, zh, type WorkspaceGroupsKey } from './locales.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The workspace-groups browsing region copy. */\n workspaceGroups: WorkspaceGroupsKey\n }\n}\n\n/** Dictionary namespace owned by this plugin. */\nconst NS = 'workspaceGroups'\n\n/** Required services (cordis fiber inject). */\nexport const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection']\n\n/**\n * Register the grouped browser once the sidebar slot declaration is on the\n * ledger. Inject factory returns plain callbacks; data reads use the\n * framework's global hooks.\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-workspace-groups: dictionaries')\n\n const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {\n const result = await ctx.sessions.search(query, signal)\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n }\n\n const browserInjected = (): GroupsBrowserInjected => ({\n startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },\n open: (sessionId) => { ctx.sessions.open(sessionId) },\n searchSessions,\n searchResultLimit: ctx.sessions.searchResultLimit,\n renameSession: async (sessionId, title) => {\n const session = ctx.sessions.binding(sessionId)?.session\n if (session === undefined) throw new Error(`unknown session \"${sessionId}\"`)\n const result = await session.rename(title)\n if (!result.ok) throw new Error(result.error.message)\n },\n forkSession: (sessionId) => {\n ctx.sessions.fork({ sessionId, increaseTitle: true })\n .then((childId) => { ctx.sessions.open(childId) })\n .catch(() => {})\n },\n renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },\n deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },\n insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {\n await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)\n },\n archiveSession: async (sessionId) => { await ctx.workspaces.archiveSession(sessionId) },\n insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {\n await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)\n },\n createWorkspace: input => ctx.workspaces.create(input),\n pickDirectory: () => ctx.workspaces.pickDirectory(),\n hooks: {\n hostDescription: (ctx.get('connection') as ConnectionHandle).hostDescription,\n },\n })\n\n // priority: -1 — lower than the official browser's default 0, so the\n // single-slot shadow rule elects this entry. No children declaration: the\n // official entry already owns `sidebar.workspaces.directoryFlow`.\n ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(\n {\n name: 'sidebar.workspaces',\n priority: -1,\n store: createGroupsViewStore(),\n inject: browserInjected,\n locale: NS,\n registrant: 'dsh-workspace-groups',\n },\n GroupsBrowser,\n ))\n}\n"],"mappings":";;;;;;;;;;;;EAsBA,SAAgB,wBAAwB,OAAwB,KAAa,UAAyB;GACpG,MAAM,kBAAkB,OAAO;EACjC;;EAGA,SAAgB,yBAAyB,OAAwB,KAAa,UAAyB;GACrG,MAAM,mBAAmB,OAAO;EAClC;;EAGA,SAAgB,eACd,OACA,cACA,eACM;GACN,MAAM,oBAAoB,OAAO,YAC/B,OAAO,QAAQ,MAAM,iBAAiB,CAAC,CAAC,QAAQ,CA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IACR,YAAY;GACd,GACA,aACF,CAAC;EACH"} \ No newline at end of file +{"version":3,"file":"client.js","names":["defineStore","indexSubagentDescendants","useState","IconTriangleRightFill14","IconFolderOpen16","IconFolderClose16","Menu","IconEditOutline16","IconTrashOutline16","IconEllipsisOutline16","IconFolderOpenOutline16","IconPlusOutline16","IconBranchOutline16","IconArchiveOutline20","StateDot","css","useState","useRef","useMemo","IconSearchOutline16","IconCloseFill14","Tooltip","IconFolderOpenOutline16","IconProjectAddOutline16","Modal","Button"],"sources":["../src/client/store-core.ts","../src/client/stores.ts","../src/core/types.ts","../src/core/matcher.ts","../src/client/tree.ts","../src/client/rows.tsx","../src/client/GroupsBrowser.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Pure expansion-state transforms for the workspace-groups store. Kept free\n * of any runtime import so both the store (which binds them via defineStore)\n * and unit tests (which exercise them directly) share one implementation.\n *\n * Expansion semantics follow the official ui-workspace store: collapse\n * WRITES `false` (never deletes the key). The browser's auto-expand guard\n * uses `Object.hasOwn` — a present `false` means \"user deliberately\n * collapsed this\" and must NOT be re-expanded; only a fully absent key means\n * \"never touched\" and may auto-expand. (Earlier versions deleted the key on\n * collapse, which made the current category/workspace impossible to fold.)\n */\n\n/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */\nexport interface GroupsViewState {\n /** Category folder expansion keyed by category label (absent = never touched). */\n categoryExpansion: Record\n /** Workspace folder expansion keyed by workspace id (absent = never touched). */\n workspaceExpansion: Record\n}\n\n/** Collapse writes `false` (key retained); expand writes `true`. */\nexport function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\n state.categoryExpansion[key] = expanded\n}\n\n/** Collapse writes `false` (key retained); expand writes `true`. */\nexport function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\n state.workspaceExpansion[key] = expanded\n}\n\n/** Drop expansion keys that no longer exist (renames/deletes/config edits). */\nexport function retainKeysImpl(\n state: GroupsViewState,\n categoryKeys: readonly string[],\n workspaceKeys: readonly string[],\n): void {\n state.categoryExpansion = Object.fromEntries(\n Object.entries(state.categoryExpansion).filter(([key]) => categoryKeys.includes(key)),\n )\n state.workspaceExpansion = Object.fromEntries(\n Object.entries(state.workspaceExpansion).filter(([key]) => workspaceKeys.includes(key)),\n )\n}\n","/**\n * The workspace-groups viewing store: category / workspace folder expansion,\n * persisted across reloads under an independent key (the official\n * ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch\n * it). Module level exports the factory only (a module-level handle would pin\n * the store identity across plugin reloads); register() receives the factory\n * and the browser derives its PropsStore share from the return type.\n *\n * The action implementations live in `store-core.ts` (pure, runtime-free) so\n * unit tests exercise the real semantics without a browser module loader;\n * this file only binds them through defineStore.\n */\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client'\nimport {\n retainKeysImpl,\n setCategoryExpandedImpl,\n setWorkspaceExpandedImpl,\n type GroupsViewState,\n} from './store-core.ts'\n\n/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */\ntype GroupsViewActions = {\n setCategoryExpanded: typeof setCategoryExpandedImpl\n setWorkspaceExpanded: typeof setWorkspaceExpandedImpl\n retainKeys: typeof retainKeysImpl\n}\n\n/**\n * Create the workspace-groups viewing store handle.\n * @returns the store handle (spec + type + identity + factory in one).\n */\nexport function createGroupsViewStore(): EngineStoreHandle {\n return defineStore({\n init: () => ({ categoryExpansion: {}, workspaceExpansion: {} }),\n persist: 'dsh.workspace.groups.view.v1',\n actions: {\n setCategoryExpanded: setCategoryExpandedImpl,\n setWorkspaceExpanded: setWorkspaceExpandedImpl,\n retainKeys: retainKeysImpl,\n },\n })\n}\n\nexport type { GroupsViewState } from './store-core.ts'\n","/**\n * Shared config types for dsh-workspace-groups. Pure types (zero runtime\n * deps) so both halves — the node half (sidecar YAML reading) and the\n * browser half (tree derivation) — compile against the same contract.\n */\n\n/** One classification rule: any rule that matches places the workspace in the category. */\nexport interface GroupRule {\n /** Absolute path prefix match (normalized, case-sensitive). */\n pathPrefix?: string\n /** Case-insensitive substring match against the workspace display title. */\n nameContains?: string\n /** Case-insensitive substring match against the workspace directory basename. */\n basenameContains?: string\n /** Exact absolute path match (normalized). */\n pathExact?: string\n}\n\n/** One category folder in the sidebar tree. */\nexport interface GroupCategory {\n /** Display label of the category folder. */\n name: string\n /** Rules; a workspace is classified here when ANY rule matches. */\n rules: GroupRule[]\n}\n\n/** The full sidecar configuration (mirrors workspace-groups.yaml). */\nexport interface GroupsConfig {\n /** Category folders, in render order. First match wins. */\n categories: GroupCategory[]\n /**\n * Runtime grouping overlay (manual groups + per-workspace overrides).\n * Optional: the YAML file itself never carries it — the host GET route\n * merges it from `workspace-groups.manual.json`, and the browser PUT route\n * replaces it whole.\n */\n manual?: ManualGroups\n}\n\n/**\n * Runtime-managed grouping overlay: groups created in the sidebar UI plus\n * per-workspace category overrides and user-controlled ordering. Owned by the\n * plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never\n * written back into the operator YAML.\n *\n * All new fields are optional for backward compatibility (files written by\n * older plugin versions keep working); rendering falls back to sensible\n * defaults when they are absent.\n */\nexport interface ManualGroups {\n /**\n * Manually created category folder names. These have no rules — they render\n * even while empty (a new group appears before anything is dragged into\n * it) and hold only workspaces assigned to them.\n */\n categories: string[]\n /**\n * Per-workspace category override, keyed by workspace id. Value is a\n * category display name (rule or manual), or `null` to force the workspace\n * into the uncategorized bucket even when a rule would match. An absent\n * key means \"classify by rules\".\n */\n assignments: Record\n /**\n * Display order of all category keys (rule display names + manual names).\n * The uncategorized bucket is never listed — it always renders last.\n * Absent = rule categories first (YAML order), manual groups appended in\n * creation order.\n */\n categoryOrder?: string[]\n /**\n * Per-category ordered workspace ids (user drag-reorder within a group).\n * Keyed by category display name; absent key = host registration order.\n */\n workspaceOrder?: Record\n /**\n * Rule category rename overrides: original YAML rule category name →\n * display name (UI rename of a rule group). Rules still classify by the\n * original name; only the rendered label/keys change.\n */\n renamed?: Record\n /**\n * Rule category original names hidden by a UI delete. Hidden rules are\n * inert: workspaces matching them fall into the uncategorized bucket.\n */\n hidden?: string[]\n}\n\n/** The label of the fallback bucket for unmatched workspaces. */\nexport const UNCATEGORIZED_LABEL = '未分类'\n\n/** Normalize a path for prefix matching: trailing slashes stripped. */\nexport function normalizePath(path: string): string {\n return path.replace(/[/\\\\]+$/, '')\n}\n","/**\n * Pure classification + ordering logic: decides which category a workspace\n * belongs to and how categories/workspaces are ordered. Shared by the host\n * half (validation) and the client half (tree derivation), so the semantics\n * can never drift between the config surface and the rendered tree.\n *\n * Category identity: a category's STABLE origin is its YAML rule category\n * name (or a manual-group name). Its DISPLAY key is what the tree renders and\n * what assignments reference — for rule categories that is the rename\n * override when present. Hidden rule categories are inert: workspaces that\n * would match them fall into the uncategorized bucket.\n */\nimport {\n normalizePath,\n UNCATEGORIZED_LABEL,\n type GroupCategory,\n type GroupRule,\n type GroupsConfig,\n type ManualGroups,\n} from './types.ts'\n\n/** One rule match against a workspace's path and title. */\nfunction ruleMatches(rule: GroupRule, path: string, title: string): boolean {\n const normalized = normalizePath(path)\n if (rule.pathPrefix !== undefined && normalized.startsWith(normalizePath(rule.pathPrefix))) return true\n if (rule.pathExact !== undefined && normalized === normalizePath(rule.pathExact)) return true\n if (rule.nameContains !== undefined && title.toLowerCase().includes(rule.nameContains.toLowerCase())) return true\n if (rule.basenameContains !== undefined) {\n const base = path.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop() ?? ''\n if (base.toLowerCase().includes(rule.basenameContains.toLowerCase())) return true\n }\n return false\n}\n\n/** Classify a workspace by rules only; hidden categories are inert. */\nexport function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {\n for (const category of categories) {\n if (category.rules.some(rule => ruleMatches(rule, path, title))) return category\n }\n return undefined\n}\n\n/** Display name of a rule category: the rename override when present. */\nexport function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string {\n return manual?.renamed?.[originalName] ?? originalName\n}\n\n/** Whether a rule category has been hidden by a UI delete. */\nexport function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean {\n return manual?.hidden?.includes(originalName) ?? false\n}\n\n/** Rule category display names, in YAML render order (hidden ones excluded). */\nexport function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[] {\n const names: string[] = []\n for (const category of categories) {\n if (isHiddenRule(manual, category.name)) continue\n names.push(ruleDisplayName(manual, category.name))\n }\n return names\n}\n\n/** Original YAML rule name whose display name equals `key` (undefined when none). */\nexport function originalRuleNameForDisplay(\n categories: readonly GroupCategory[],\n manual: ManualGroups | undefined,\n key: string,\n): string | undefined {\n return categories.find(c => ruleDisplayName(manual, c.name) === key)?.name\n}\n\n/**\n * Effective category entries in display order: rule categories (YAML order,\n * hidden skipped, renamed applied) first, then manual-only groups in\n * creation order — unless `manual.categoryOrder` overrides the sequence.\n * The uncategorized bucket is never included (it always renders last).\n */\nexport interface EffectiveCategory {\n /** Display key (what the tree renders and assignments reference). */\n key: string\n /** Origin: a YAML rule category or a manual group. */\n source: 'rule' | 'manual'\n}\n\nexport function effectiveCategories(\n config: GroupsConfig,\n manual: ManualGroups | undefined,\n): EffectiveCategory[] {\n const entries: EffectiveCategory[] = []\n const seen = new Set()\n for (const category of config.categories) {\n if (isHiddenRule(manual, category.name)) continue\n const key = ruleDisplayName(manual, category.name)\n if (seen.has(key)) continue\n seen.add(key)\n entries.push({ key, source: 'rule' })\n }\n for (const name of manual?.categories ?? []) {\n if (seen.has(name)) continue\n seen.add(name)\n entries.push({ key: name, source: 'manual' })\n }\n const order = manual?.categoryOrder\n if (order === undefined || order.length === 0) return entries\n // Stable sort by position in categoryOrder; entries absent from the order\n // keep their relative default position after all ordered ones.\n const position = new Map(order.map((key, index) => [key, index]))\n return [...entries].sort((a, b) => {\n const pa = position.get(a.key)\n const pb = position.get(b.key)\n if (pa !== undefined && pb !== undefined) return pa - pb\n if (pa !== undefined) return -1\n if (pb !== undefined) return 1\n return 0\n })\n}\n\n/** Display keys of all effective categories (uncategorized bucket excluded). */\nexport function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[] {\n return effectiveCategories(config, manual).map(e => e.key)\n}\n\n/**\n * Resolve the category key a workspace renders under. Precedence:\n * manual override (`null` = force uncategorized) → rule classification\n * (hidden rules inert) → uncategorized bucket (`undefined`).\n */\nexport function resolveCategory(\n config: GroupsConfig,\n manual: ManualGroups | undefined,\n workspaceId: string,\n path: string,\n title: string,\n): string | undefined {\n const override = manual?.assignments[workspaceId]\n if (override !== undefined) return override ?? undefined // null forces the uncategorized bucket\n const matched = classify(config.categories, path, title)\n if (matched === undefined) return undefined\n if (isHiddenRule(manual, matched.name)) return undefined\n return ruleDisplayName(manual, matched.name)\n}\n\n/** Whether a category key is a manual-only group (manageable via list). */\nexport function isManualOnlyCategory(\n config: GroupsConfig,\n manual: ManualGroups | undefined,\n key: string,\n): boolean {\n return (manual?.categories.includes(key) ?? false) && !ruleDisplayNames(config.categories, manual).includes(key)\n}\n\n/**\n * Names that may not be used for a new/renamed group: the reserved\n * uncategorized label plus every current display key.\n */\nexport function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set {\n const taken = new Set(displayCategoryKeys(config, manual))\n taken.add(UNCATEGORIZED_LABEL)\n return taken\n}\n\n/**\n * Order a bucket of workspace ids: the stored per-category order first\n * (filtered to actual members), then any remaining members in `fallback`\n * (host) order. Deterministic; the renderer never re-sorts on its own.\n */\nexport function orderedWorkspaceIds(\n manual: ManualGroups | undefined,\n categoryKey: string,\n members: readonly string[],\n): string[] {\n const stored = manual?.workspaceOrder?.[categoryKey]\n if (stored === undefined || stored.length === 0) return [...members]\n const memberSet = new Set(members)\n const ordered: string[] = []\n const seen = new Set()\n for (const id of stored) {\n if (!memberSet.has(id) || seen.has(id)) continue\n seen.add(id)\n ordered.push(id)\n }\n for (const id of members) {\n if (seen.has(id)) continue\n ordered.push(id)\n }\n return ordered\n}\n\n/** Move `id` before `beforeId` (undefined = append) within an ordered list. */\nexport function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[] {\n const rest = list.filter(x => x !== id)\n if (beforeId === undefined) return [...rest, id]\n const index = rest.indexOf(beforeId)\n if (index === -1) return [...rest, id]\n rest.splice(index, 0, id)\n return rest\n}\n\n/** Move `id` after `afterId` (undefined = append) within an ordered list. */\nexport function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[] {\n const rest = list.filter(x => x !== id)\n if (afterId === undefined) return [...rest, id]\n const index = rest.indexOf(afterId)\n if (index === -1) return [...rest, id]\n rest.splice(index + 1, 0, id)\n return rest\n}\n","/**\n * Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →\n * 会话行. Pure derivation — all inputs are snapshots; the renderer never\n * scans. Session visibility rules mirror the official ui-workspace tree\n * (blank rows only when current, archived excluded, subagent rows excluded).\n */\nimport {\n indexSubagentDescendants,\n type PendingInteractionStatus,\n type SessionId,\n type SessionListState,\n type SessionSearchResultItem,\n type SessionSummary,\n type SubagentDescendantSummary,\n type WorkspaceId,\n type WorkspaceView,\n} from '@deepseek-ai/dsh-client-runtime/client'\nimport { effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'\nimport { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'\n\n/** One top-level session row inside a workspace folder. */\nexport interface SessionNode {\n id: SessionId\n /** Stored display title; blank rows show the localized New Session label. */\n title: string\n /** The provisional blank session (renderer shows the localized New Session title). */\n blank: boolean\n pendingInteraction?: PendingInteractionStatus\n running: boolean\n /** Running descendants connected through uninterrupted subagent-origin lineage. */\n runningSubagentCount: number\n /** Finished running while not selected and not yet opened (the green \"done\" reminder dot). */\n completed: boolean\n updatedAt: number\n /** Search-hit marker (rendered with a highlighted tint in search mode). */\n matched?: boolean\n /** Content-match snippet from the Host search (search mode only). */\n snippet?: string\n}\n\n/** One workspace folder row inside a category folder. */\nexport interface WorkspaceGroupNode {\n workspaceId: WorkspaceId\n /** Canonical host directory path. */\n path: string\n /** Display title. */\n label: string\n /** Workspace creation time (epoch ms). */\n createdAt: number\n /** Total visible sessions in the folder. */\n sessionCount: number\n expanded: boolean\n /** The folder contains the selected session (active folder tint). */\n containsCurrent: boolean\n /** Visible session rows (empty while the folder is folded). */\n sessions: readonly SessionNode[]\n}\n\n/** One category folder at the top of the tree. */\nexport interface CategoryNode {\n /** Stable category key: the configured label, or the uncategorized bucket. */\n key: string\n /** Display label. */\n label: string\n expanded: boolean\n /** The category contains the selected session (active folder tint). */\n containsCurrent: boolean\n /** Workspace folders in host order. */\n workspaces: readonly WorkspaceGroupNode[]\n}\n\n/** Viewing state consumed by the derivation. */\nexport interface GroupsTreeView {\n expandedCategories: readonly string[]\n expandedWorkspaces: readonly string[]\n}\n\n/** Key of the uncategorized bucket (matches the config fallback label). */\nexport const UNCATEGORIZED_KEY = UNCATEGORIZED_LABEL\n\n/** Directory display label: basename of the path (both separators accepted). */\nexport function workspaceLabel(cwd: string | undefined): string {\n if (cwd === undefined || cwd === '') return UNCATEGORIZED_LABEL\n const base = cwd.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop()\n return base !== undefined && base !== '' ? base : cwd\n}\n\n/** Ordinary sessions are visible; blank only when current; archived/subagent never. */\nfunction sessionVisible(session: SessionSummary, current: SessionId | undefined, archived: ReadonlySet): boolean {\n return session.origin !== 'subagent'\n && !archived.has(session.id)\n && (!session.blank || session.id === current)\n}\n\n/** Blank rows display the localized New Session label (never enters search). */\nfunction sessionTitle(session: SessionSummary): string {\n return session.blank ? 'New Session' : session.displayTitle\n}\n\nfunction sessionNode(\n s: SessionSummary,\n descendants: ReadonlyMap,\n): SessionNode {\n return {\n id: s.id,\n title: sessionTitle(s),\n blank: s.blank,\n running: s.running,\n runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,\n completed: s.completed === true,\n updatedAt: s.updatedAt,\n ...(s.pendingInteraction === undefined ? {} : { pendingInteraction: s.pendingInteraction }),\n }\n}\n\n/** Visible sessions of one workspace in its stored account order. */\nfunction workspaceSessions(\n list: SessionListState,\n workspace: WorkspaceView,\n archived: ReadonlySet,\n descendants: ReadonlyMap,\n): SessionNode[] {\n const nodes: SessionNode[] = []\n for (const id of workspace.sessionIds) {\n const summary = list.byId[id]\n if (summary === undefined) continue // account may lead the list pull; appears when the summary lands\n if (!sessionVisible(summary, list.current, archived)) continue\n nodes.push(sessionNode(summary, descendants))\n }\n return nodes\n}\n\n/**\n * Derive the three-level tree.\n * @param list - sessions list snapshot (`current` feeds containsCurrent).\n * @param workspaces - real workspaces in stable Host order.\n * @param archivedSessionIds - registry-global archive set.\n * @param config - sidecar grouping config (rule categories).\n * @param view - local expansion arrays.\n * @param manual - runtime overlay (manual groups + overrides). A workspace's\n * manual override wins over rule classification; removing it reverts to rules.\n * @returns category sections in render order (rule categories first, then\n * manual-only ones, uncategorized last). Manual groups render even while\n * empty; empty rule buckets stay hidden.\n */\nexport function deriveGroups(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n archivedSessionIds: readonly SessionId[],\n config: GroupsConfig,\n view: GroupsTreeView,\n manual: ManualGroups,\n): CategoryNode[] {\n const archived = new Set(archivedSessionIds)\n const expandedCategories = new Set(view.expandedCategories)\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\n const descendants = indexSubagentDescendants(list.byId)\n\n // Bucket workspaces by display key. Seed with every effective category so\n // manual groups render while empty; the uncategorized bucket is appended\n // LAST (groups always sit above ungrouped projects).\n const byCategory = new Map()\n for (const { key } of effectiveCategories(config, manual)) {\n byCategory.set(key, [])\n }\n byCategory.set(UNCATEGORIZED_KEY, [])\n for (const workspace of workspaces) {\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\n ?? UNCATEGORIZED_KEY\n if (!byCategory.has(key)) byCategory.set(key, [])\n byCategory.get(key)!.push(workspace)\n }\n\n const manualCategories = new Set(manual.categories)\n const currentWorkspaceId = list.current === undefined\n ? undefined\n : workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId\n\n const nodes: CategoryNode[] = []\n // Effective categories in display order (categoryOrder applied), then the\n // uncategorized bucket pinned to the very bottom.\n const orderedKeys = [\n ...effectiveCategories(config, manual).map(e => e.key),\n UNCATEGORIZED_KEY,\n ]\n for (const key of orderedKeys) {\n const bucket = byCategory.get(key) ?? []\n // Manual groups stay visible while empty; everything else hides when empty.\n if (bucket.length === 0 && !manualCategories.has(key)) continue\n const expanded = expandedCategories.has(key)\n const ordered = orderedWorkspaceIds(manual, key, bucket.map(w => w.workspaceId as string))\n const workspaceNodes: WorkspaceGroupNode[] = []\n let containsCurrent = false\n for (const workspaceId of ordered) {\n const workspace = bucket.find(w => w.workspaceId === workspaceId)\n if (workspace === undefined) continue\n const sessions = workspaceSessions(list, workspace, archived, descendants)\n const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)\n const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId\n if (wsContainsCurrent) containsCurrent = true\n workspaceNodes.push({\n workspaceId: workspace.workspaceId,\n path: workspace.path,\n label: workspace.title,\n createdAt: Date.parse(workspace.createdAt),\n sessionCount: sessions.length,\n expanded: wsExpanded,\n containsCurrent: wsContainsCurrent,\n sessions: wsExpanded ? sessions : [],\n })\n }\n nodes.push({\n key,\n label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,\n expanded,\n containsCurrent,\n workspaces: workspaceNodes,\n })\n }\n return nodes\n}\n\n/** Recency comparator: newest first, id as the deterministic tiebreak. */\nfunction byRecency(a: SessionSummary, b: SessionSummary): number {\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\n return a.id < b.id ? -1 : 1\n}\n\n/** Bounded set of matched sessions plus content snippets (feeds the search tree). */\nexport interface SearchMatchSet {\n /** Session ids that matched (local metadata hits + Host content hits). */\n matchedIds: ReadonlySet\n /** Content-match snippets keyed by session id (Host search only). */\n snippetsBySession: ReadonlyMap\n hasMore: boolean\n}\n\n/**\n * Compute the matched-session set: immediate title/Workspace substring matches\n * from the local list, merged with ranked Host content matches. The consumer\n * (SearchBody) derives the pruned three-level tree from these ids.\n */\nexport function deriveSearchMatches(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n config: GroupsConfig,\n query: string,\n archivedSessionIds: readonly SessionId[],\n content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },\n limit: number,\n): SearchMatchSet {\n const q = query.trim().toLowerCase()\n if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }\n const archived = new Set(archivedSessionIds)\n const descendants = indexSubagentDescendants(list.byId)\n\n const workspaceBySession = new Map()\n for (const workspace of workspaces) {\n for (const sessionId of workspace.sessionIds) {\n if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)\n }\n }\n const labelOf = (summary: SessionSummary): string =>\n workspaceBySession.get(summary.id)?.title ?? workspaceLabel(summary.cwd)\n\n const local: SessionSummary[] = []\n for (const id of list.ids) {\n const summary = list.byId[id]\n if (summary === undefined || summary.blank || !sessionVisible(summary, list.current, archived)) continue\n if (\n sessionTitle(summary).toLowerCase().includes(q)\n || labelOf(summary).toLowerCase().includes(q)\n ) {\n local.push(summary)\n }\n }\n local.sort(byRecency)\n\n const ordered: SessionSummary[] = []\n const included = new Set()\n const include = (summary: SessionSummary): void => {\n if (included.has(summary.id)) return\n included.add(summary.id)\n ordered.push(summary)\n }\n for (const summary of local) include(summary)\n for (const item of content.items) {\n const summary = list.byId[item.sessionId]\n if (summary !== undefined && !summary.blank && sessionVisible(summary, list.current, archived)) include(summary)\n }\n\n const snippets = new Map()\n for (const item of content.items) {\n if (item.snippet !== undefined) snippets.set(item.sessionId, item.snippet)\n }\n\n return {\n matchedIds: ordered.slice(0, limit).reduce((set, summary) => { set.add(summary.id); return set }, new Set()),\n snippetsBySession: snippets,\n hasMore: content.hasMore || ordered.length > limit,\n }\n}\n\n/**\n * Build a three-level search tree containing ONLY the branches that hold a\n * matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched\n * session carries `matched: true` so rows render with the search-hit tint.\n * Classification uses the same precedence as the idle tree (manual override →\n * rules), so search shows the same grouping the user sees.\n *\n * @param list - sessions list snapshot.\n * @param workspaces - real workspaces in stable Host order.\n * @param config - sidecar grouping config.\n * @param matchedIds - set of session ids that matched the query.\n * @param archivedSessionIds - registry-global archive set.\n * @param manual - runtime overlay (manual groups + overrides).\n * @param snippetsBySession - optional content-match snippets keyed by session id.\n * @returns categories in render order, pruned to matched branches only.\n */\nexport function deriveSearchGroups(\n list: SessionListState,\n workspaces: readonly WorkspaceView[],\n config: GroupsConfig,\n matchedIds: ReadonlySet,\n archivedSessionIds: readonly SessionId[],\n manual: ManualGroups,\n snippetsBySession?: ReadonlyMap,\n): CategoryNode[] {\n const archived = new Set(archivedSessionIds)\n const descendants = indexSubagentDescendants(list.byId)\n\n const byCategory = new Map()\n for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])\n byCategory.set(UNCATEGORIZED_KEY, [])\n\n for (const workspace of workspaces) {\n // Only sessions that matched the query and are visible in this folder.\n const nodes: SessionNode[] = []\n for (const id of workspace.sessionIds) {\n const summary = list.byId[id]\n if (summary === undefined || !matchedIds.has(id)) continue\n if (!sessionVisible(summary, list.current, archived)) continue\n const node = sessionNode(summary, descendants)\n const snippet = snippetsBySession?.get(id)\n nodes.push({\n ...node,\n matched: true,\n ...(snippet === undefined ? {} : { snippet }),\n })\n }\n if (nodes.length === 0) continue\n\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\n ?? UNCATEGORIZED_KEY\n if (!byCategory.has(key)) byCategory.set(key, [])\n byCategory.get(key)!.push({\n workspaceId: workspace.workspaceId,\n path: workspace.path,\n label: workspace.title,\n createdAt: Date.parse(workspace.createdAt),\n sessionCount: nodes.length,\n expanded: true,\n containsCurrent: false,\n sessions: nodes,\n })\n }\n\n const categories: CategoryNode[] = []\n // Same display order as the idle tree; the uncategorized bucket stays last.\n const orderedKeys = [\n ...effectiveCategories(config, manual).map(e => e.key),\n UNCATEGORIZED_KEY,\n ]\n for (const key of orderedKeys) {\n const workspaceNodes = byCategory.get(key)\n if (workspaceNodes === undefined || workspaceNodes.length === 0) continue\n categories.push({\n key,\n label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,\n expanded: true,\n containsCurrent: false,\n workspaces: workspaceNodes,\n })\n }\n return categories\n}\n","/**\n * Row components for the workspace-groups tree. Kept dependency-light: they\n * consume only React, primitives (StateDot/Menu/icons), and the shared CSS\n * string. Each row owns its hover actions menu; dialogs live in the browser\n * root so they survive row unmounts during collapse.\n *\n * Drag & drop: workspace rows are draggable sources; category rows (and\n * workspace rows, standing for their containing category) are drop targets.\n * The payload is a custom dataTransfer type so only in-plugin drags land.\n */\nimport { useState, type DragEvent } from 'react'\nimport {\n IconArchiveOutline20,\n IconBranchOutline16,\n IconEditOutline16,\n IconEllipsisOutline16,\n IconFolderClose16,\n IconFolderOpen16,\n IconFolderOpenOutline16,\n IconPlusOutline16,\n IconTriangleRightFill14,\n IconTrashOutline16,\n Menu,\n StateDot,\n type StateDotState,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { WorkspaceGroupsKey } from './locales.ts'\nimport type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'\n\ntype T = TranslateNS<'workspaceGroups'>\n\n/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */\nexport const DND_WORKSPACE_TYPE = 'application/x-dsh-workspace-groups'\n/** dataTransfer type carrying the dragged category key (group reorder). */\nexport const DND_CATEGORY_TYPE = 'application/x-dsh-workspace-groups-category'\n\n/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */\nexport function hasPluginDragType(types: DOMStringList | readonly string[]): boolean {\n const list = Array.from(types as Iterable)\n return list.includes(DND_WORKSPACE_TYPE) || list.includes(DND_CATEGORY_TYPE)\n}\n\n/** Pending interaction status → primitives StateDot state. */\nfunction pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {\n switch (status) {\n case 'approval':\n case 'plan-review':\n case 'question':\n return 'warning'\n default:\n return undefined\n }\n}\n\n/** Primary status dot state for a session row. */\nexport function sessionDotState(node: Pick): StateDotState {\n if (pendingState(node.pendingInteraction) !== undefined) return 'warning'\n if (node.running || node.runningSubagentCount > 0) return 'ongoing'\n return node.completed ? 'done' : 'done'\n}\n\n/** Compact relative time (\"now\"/\"5min\"/\"3h\"/\"2d\"/\"4mo\"/\"1y\"). */\nexport function relativeTimeLabel(updatedAt: number, now: number): string {\n const diff = Math.max(0, now - updatedAt)\n const MIN = 60_000\n const HOUR = 3_600_000\n const DAY = 86_400_000\n if (diff < MIN) return 'now'\n if (diff < HOUR) return `${Math.floor(diff / MIN)}min`\n if (diff < DAY) return `${Math.floor(diff / HOUR)}h`\n if (diff < 30 * DAY) return `${Math.floor(diff / DAY)}d`\n if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`\n return `${Math.floor(diff / (365 * DAY))}y`\n}\n\n/** Drop-target props shared by category and workspace rows (all optional). */\nexport interface RowDropProps {\n /** Row is under the dragged workspace — show the drop highlight. */\n dropActive?: boolean\n /** Insertion indicator: a line above (before) or below (after) this row. */\n insertLine?: 'before' | 'after'\n /** Accept a drag over this row (must preventDefault to allow the drop). */\n onRowDragOver?: (event: DragEvent) => void\n /** Clear the highlight when the pointer leaves the row. */\n onRowDragLeave?: (event: DragEvent) => void\n /** Drop a workspace onto this row. */\n onRowDrop?: (event: DragEvent) => void\n}\n\n/**\n * One category folder row: toggle, rename/delete menu (every group — rule\n * groups via overlay renames/hides), draggable source for group reorder and\n * drop target for both workspace moves and group reorders.\n */\nexport function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {\n node: CategoryNode\n t: T\n onToggle: () => void\n /** Rename/delete actions; the hover menu renders only when both provided. */\n onRename?: () => void\n onDelete?: () => void\n /** Group reorder source; the row becomes draggable only when provided. */\n onDragStartCategory?: (event: DragEvent) => void\n} & RowDropProps) {\n const [menuOpen, setMenuOpen] = useState(false)\n const count = node.workspaces.length\n const manageable = onRename !== undefined && onDelete !== undefined\n return (\n \n \n \n \n \n {node.expanded ? : }\n \n {node.label}\n {count}\n {manageable && (\n \n { setMenuOpen(false) }}\n items={[\n { id: 'rename', label: t('group.rename'), icon: },\n { id: 'delete', label: t('group.delete'), icon: , danger: true },\n ]}\n onSelect={(id) => {\n setMenuOpen(false)\n if (id === 'rename') onRename()\n if (id === 'delete') onDelete()\n }}\n portal\n closeOnPointerLeave\n anchor={(\n { e.stopPropagation(); setMenuOpen(v => !v) }}\n >\n \n \n )}\n />\n \n )}\n \n )\n}\n\n/** One workspace folder row inside a category: draggable source + drop target. */\nexport function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, hasOverride = false, onMoveOut, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {\n node: WorkspaceGroupNode\n t: T\n onToggle: () => void\n onNewSession: () => void\n onRename: () => void\n onDelete: () => void\n /** Workspace has a manual group override — offer \"move to uncategorized\". */\n hasOverride?: boolean\n onMoveOut?: () => void\n /** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */\n onDragStartExtra?: () => void\n} & RowDropProps) {\n const [menuOpen, setMenuOpen] = useState(false)\n const menuItems = [\n ...(hasOverride && onMoveOut !== undefined\n ? [{ id: 'moveOut', label: t('workspace.moveToUncategorized'), icon: }]\n : []),\n { id: 'rename', label: t('workspace.rename'), icon: },\n { id: 'delete', label: t('workspace.delete'), icon: , danger: true },\n ]\n const onDragStart = (event: DragEvent): void => {\n event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId)\n event.dataTransfer.effectAllowed = 'move'\n onDragStartExtra?.()\n }\n return (\n \n \n \n \n \n {node.expanded ? : }\n \n {node.label}\n \n { setMenuOpen(false) }}\n items={menuItems}\n onSelect={(id) => {\n setMenuOpen(false)\n if (id === 'moveOut') onMoveOut?.()\n if (id === 'rename') onRename()\n if (id === 'delete') onDelete()\n }}\n portal\n closeOnPointerLeave\n anchor={(\n { e.stopPropagation(); setMenuOpen(v => !v) }}\n >\n \n \n )}\n />\n { e.stopPropagation(); onNewSession() }}\n >\n \n \n \n \n )\n}\n\n/** One session leaf row. */\nexport function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {\n node: SessionNode\n currentId: string | undefined\n now: number\n t: T\n onOpen: (id: SessionNode['id']) => void\n onRename: (id: SessionNode['id'], currentTitle: string) => void\n onFork: (id: SessionNode['id']) => void\n onArchive: (id: SessionNode['id']) => void\n}) {\n const selected = node.id === currentId\n const [menuOpen, setMenuOpen] = useState(false)\n const showStatus = true\n const menuItems = [\n { id: 'rename', label: t('session.rename'), icon: },\n { id: 'fork', label: t('session.fork'), icon: },\n { id: 'archive', label: t('session.archive'), icon: },\n ]\n return (\n { onOpen(node.id) }}\n >\n \n {showStatus && }\n \n {node.title}\n {!node.blank && {relativeTimeLabel(node.updatedAt, now)}}\n {node.snippet !== undefined && (\n {node.snippet}\n )}\n {!node.blank && (\n \n { setMenuOpen(false) }}\n items={menuItems}\n onSelect={(id) => {\n setMenuOpen(false)\n if (id === 'rename') onRename(node.id, node.title)\n if (id === 'fork') onFork(node.id)\n if (id === 'archive') onArchive(node.id)\n }}\n portal\n closeOnPointerLeave\n anchor={(\n { e.stopPropagation(); setMenuOpen(v => !v) }}\n >\n \n \n )}\n />\n \n )}\n \n )\n}\n\nexport type { T }\n","/**\n * The workspace-groups browsing region filling the sidebar shell's\n * `sidebar.workspaces` hole: section header (title + right-aligned search +\n * new-group + add workspace), the three-level tree (category → workspace →\n * session), group management dialogs, and the workspace/session dialogs. Wide\n * state renders the full browser; rail state renders the two region icons\n * (search / add workspace) as 36px controls on the shell's shared rail entry\n * path, each requesting expansion through the owner share.\n *\n * Data: workspaces/sessions via the framework global hooks; grouping config\n * via the host half's `/workspace-groups/config` route (refetched on mount).\n * Runtime group management (create/rename/delete any group, drag workspaces\n * between groups and into position, drag groups into position) persists\n * through `PUT /workspace-groups/manual`; the sidecar YAML is never rewritten\n * (rule-group rename/delete ride the overlay `renamed`/`hidden` maps).\n */\nimport { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'\nimport {\n Button,\n IconCloseFill14,\n IconFolderOpenOutline16,\n IconProjectAddOutline16,\n IconSearchOutline16,\n Modal,\n Tooltip,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { SessionId, SessionListState, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'\nimport {\n displayCategoryKeys,\n moveAfter,\n moveBefore,\n originalRuleNameForDisplay,\n resolveCategory,\n takenCategoryNames,\n} from '../core/matcher.ts'\nimport { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'\nimport type { GroupsBrowserProps } from './contract.ts'\nimport { deriveGroups, deriveSearchGroups, deriveSearchMatches, UNCATEGORIZED_KEY, type CategoryNode } from './tree.ts'\nimport { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, WorkspaceRow } from './rows.tsx'\nimport css from './styles.css?inline'\n\nconst SEARCH_DEBOUNCE_MS = 250\nconst SEARCH_QUERY_MAX_CODE_UNITS = 500\n\n/** Overlay with every optional field materialized (plain-object edits, no undefined spreads). */\ntype NormalizedManual = Required\n\nconst EMPTY_MANUAL: NormalizedManual = {\n categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [],\n}\n\n/** Materialize optional overlay fields so every update is a plain object edit. */\nfunction normalizeManual(manual: ManualGroups): NormalizedManual {\n return {\n categories: manual.categories,\n assignments: manual.assignments,\n categoryOrder: manual.categoryOrder ?? [],\n workspaceOrder: manual.workspaceOrder ?? {},\n renamed: manual.renamed ?? {},\n hidden: manual.hidden ?? [],\n }\n}\n\nfunction sanitizeSearchQuery(value: string): string {\n const withoutNul = value.replaceAll('\\0', '')\n if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul\n return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS)\n}\n\n/** Immutable membership toggle for the local expand-all array. */\nfunction toggled(list: readonly string[], key: string): string[] {\n return list.includes(key) ? list.filter(k => k !== key) : [...list, key]\n}\n\ninterface RemoteSearchState {\n query: string\n status: 'idle' | 'loading' | 'ready' | 'error'\n items: readonly SessionSearchResultItem[]\n hasMore: boolean\n}\n\n/** Light runtime guard for the manual overlay attached to the config fetch. */\nfunction isManualGroups(value: unknown): value is ManualGroups {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as { categories?: unknown; assignments?: unknown }\n return Array.isArray(candidate.categories) && typeof candidate.assignments === 'object' && candidate.assignments !== null\n}\n\n/** Minimal fetch of the grouping config + runtime overlay (no-cache revalidation). */\nasync function fetchGroupsConfig(): Promise<{ config: GroupsConfig; manual: NormalizedManual }> {\n const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })\n if (!response.ok) throw new Error(`config request failed: ${response.status}`)\n const body = (await response.json()) as GroupsConfig\n const config: GroupsConfig = Array.isArray(body.categories) ? body : { categories: [] }\n return { config, manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL }\n}\n\n/** Persist the whole runtime overlay (idempotent; the host validates + writes). */\nasync function saveManualOverlay(manual: ManualGroups): Promise {\n const response = await fetch('/workspace-groups/manual', {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(manual),\n })\n if (!response.ok) {\n let message = `manual save failed: ${response.status}`\n try {\n const text = await response.text()\n if (text !== '') message = text\n } catch { /* keep the fallback message */ }\n throw new Error(message)\n }\n}\n\n/** One group-management dialog state: create, or rename an existing group. */\ntype GroupDialogState = { mode: 'create' } | { mode: 'rename'; from: string } | null\n\n/** Row reference used by drop targets: which kind of row, which key. */\nexport type DropRowRef = { kind: 'category' | 'workspace'; key: string }\n\n/**\n * Current drop indicator. A `line` renders a 2px insertion line above/below a\n * row (project reorder inside a group, or group reorder); an `into` renders\n * the whole-row highlight used when dropping a project into a group. Drop\n * handlers re-derive before/after from the drop event itself, so the\n * indicator is purely visual and can never go stale.\n */\nexport type DragIndicator =\n | { mode: 'line'; row: DropRowRef; before: boolean }\n | { mode: 'into'; categoryKey: string }\n | null\n\n/**\n * Render the browsing region.\n * @param props - composed slot props (shell owner share + store + injected actions).\n * @returns the region element tree.\n */\nexport function GroupsBrowser({\n wide,\n expandSidebar,\n useSessions,\n useWorkspaces,\n useStore,\n actions,\n startSession,\n open,\n renameSession,\n forkSession,\n renameWorkspace,\n deleteWorkspace,\n insertWorkspaceBefore,\n archiveSession,\n insertSessionBefore,\n createWorkspace,\n pickDirectory,\n searchSessions,\n searchResultLimit,\n t,\n}: GroupsBrowserProps) {\n // Inject the stylesheet once per fiber; dispose removes it (HMR safe).\n useEffect(() => {\n const style = document.createElement('style')\n style.setAttribute('data-plugin', 'dsh-workspace-groups')\n style.textContent = css\n document.head.append(style)\n return () => { style.remove() }\n }, [])\n\n // Grouping config from the host route + the runtime manual overlay.\n const [config, setConfig] = useState({ categories: [] })\n const [manual, setManual] = useState(EMPTY_MANUAL)\n const [configError, setConfigError] = useState(null)\n const reloadConfig = () => {\n setConfigError(null)\n fetchGroupsConfig().then(({ config: nextConfig, manual: nextManual }) => {\n setConfig(nextConfig)\n setManual(nextManual)\n }).catch((reason: unknown) => {\n setConfigError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n useEffect(() => { reloadConfig() }, [])\n\n // Transient save errors for drag/menu group operations (dialog errors are local).\n const [manualError, setManualError] = useState(null)\n const [manualSaving, setManualSaving] = useState(false)\n\n const workspaces = useWorkspaces(state => state.items)\n const workspacePhase = useWorkspaces(state => state.phase)\n const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)\n const categoryExpansion = useStore(s => s.categoryExpansion)\n const workspaceExpansion = useStore(s => s.workspaceExpansion)\n\n const list = useSessions(s => s)\n const current = list.current\n const currentWorkspaceKey = current === undefined\n ? undefined\n : (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)\n\n // Auto-expand the category + workspace containing the current session, but\n // ONLY when the user has never touched that key (`Object.hasOwn`): a\n // present `false` is a deliberate collapse and must stay folded. Without\n // this guard the effect re-expands the just-collapsed current category on\n // every store change (the reported \"cannot collapse\" bug).\n useEffect(() => {\n if (current === undefined || currentWorkspaceKey === undefined) return\n const category = categoriesForCurrent(config, workspaces, current, manual)\n if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {\n actions.setCategoryExpanded(category, true)\n }\n if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {\n actions.setWorkspaceExpanded(currentWorkspaceKey, true)\n }\n }, [current, currentWorkspaceKey, config, workspaces, manual, categoryExpansion, workspaceExpansion, actions])\n\n // Drop expansion keys that no longer exist (group edits / workspace deletion).\n useEffect(() => {\n if (workspacePhase !== 'ready') return\n actions.retainKeys(\n displayCategoryKeys(config, manual),\n workspaces.map(w => w.workspaceId as string),\n )\n }, [actions, config, manual, workspacePhase, workspaces])\n\n const [query, setQuery] = useState('')\n const [searchExpanded, setSearchExpanded] = useState(false)\n const normalizedQuery = sanitizeSearchQuery(query).trim()\n const [remoteSearch, setRemoteSearch] = useState({\n query: '', status: 'idle', items: [], hasMore: false,\n })\n const searchInput = useRef(null)\n const searchRoot = useRef(null)\n\n // Search debounce + abort, same posture as the official browser.\n useEffect(() => {\n if (normalizedQuery === '') {\n setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false })\n return\n }\n const controller = new AbortController()\n setRemoteSearch({ query: normalizedQuery, status: 'loading', items: [], hasMore: false })\n const timer = window.setTimeout(() => {\n searchSessions(normalizedQuery, controller.signal).then((result) => {\n if (controller.signal.aborted) return\n setRemoteSearch({ query: normalizedQuery, status: 'ready', items: result.items, hasMore: result.hasMore })\n }).catch(() => {\n if (controller.signal.aborted) return\n setRemoteSearch({ query: normalizedQuery, status: 'error', items: [], hasMore: false })\n })\n }, SEARCH_DEBOUNCE_MS)\n return () => {\n window.clearTimeout(timer)\n controller.abort()\n }\n }, [normalizedQuery, searchSessions])\n\n // Outside-click dismissal of the search box.\n useEffect(() => {\n if (!wide || !searchExpanded) return\n const onClick = (event: MouseEvent): void => {\n if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return\n searchInput.current?.blur()\n if (normalizedQuery !== '') return\n setSearchExpanded(false)\n }\n document.addEventListener('click', onClick)\n return () => { document.removeEventListener('click', onClick) }\n }, [normalizedQuery, wide, searchExpanded])\n\n const expandedCategories = useMemo(\n () => Object.entries(categoryExpansion).filter(([, v]) => v).map(([k]) => k),\n [categoryExpansion],\n )\n const expandedWorkspaces = useMemo(\n () => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),\n [workspaceExpansion],\n )\n const groups = useMemo(\n () => deriveGroups(list, workspaces, archivedSessionIds, config, {\n expandedCategories,\n expandedWorkspaces,\n }, manual),\n [list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],\n )\n\n // Add workspace flow: self-contained (no directory-flow hole dependency).\n const [adding, setAdding] = useState(false)\n const [addError, setAddError] = useState(null)\n const [addErrorOpen, setAddErrorOpen] = useState(false)\n const addWorkspace = async (): Promise => {\n if (adding) return\n setAdding(true)\n setAddError(null)\n setAddErrorOpen(false)\n try {\n const path = await pickDirectory()\n if (path === null) return // cancelled\n const workspace = await createWorkspace({ path })\n startSession(workspace.workspaceId)\n } catch (reason) {\n const message = reason instanceof Error ? reason.message : String(reason)\n setAddError(message)\n setAddErrorOpen(true)\n } finally {\n setAdding(false)\n }\n }\n\n // Workspace rename dialog.\n const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null)\n const [renameDraft, setRenameDraft] = useState('')\n const [renaming, setRenaming] = useState(false)\n const [renameError, setRenameError] = useState(null)\n const renameTrimmed = renameDraft.trim()\n const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle\n && workspaces.some(w => w.title === renameTrimmed)\n const renameBlocked = renaming || renameTrimmed === '' || renameTarget === null\n || renameTrimmed === renameTarget.currentTitle || renameDuplicate\n const confirmRename = () => {\n if (renameBlocked || renameTarget === null) return\n setRenaming(true)\n setRenameError(null)\n renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {\n setRenaming(false)\n setRenameTarget(null)\n }).catch((reason: unknown) => {\n setRenaming(false)\n setRenameError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n // Workspace delete dialog.\n const [deleteTarget, setDeleteTarget] = useState<{ workspaceId: WorkspaceId; title: string } | null>(null)\n const [deleting, setDeleting] = useState(false)\n const [deleteError, setDeleteError] = useState(null)\n const confirmDelete = () => {\n if (deleting || deleteTarget === null) return\n setDeleting(true)\n setDeleteError(null)\n deleteWorkspace(deleteTarget.workspaceId).then(() => {\n setDeleting(false)\n setDeleteTarget(null)\n }).catch((reason: unknown) => {\n setDeleting(false)\n setDeleteError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n // Session rename dialog.\n const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionId; currentTitle: string } | null>(null)\n const [sessionRenameDraft, setSessionRenameDraft] = useState('')\n const [sessionRenaming, setSessionRenaming] = useState(false)\n const [sessionRenameError, setSessionRenameError] = useState(null)\n const sessionRenameTrimmed = sessionRenameDraft.trim()\n const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null\n const confirmSessionRename = () => {\n if (sessionRenameBlocked || sessionRenameTarget === null) return\n setSessionRenaming(true)\n setSessionRenameError(null)\n renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {\n setSessionRenaming(false)\n setSessionRenameTarget(null)\n }).catch((reason: unknown) => {\n setSessionRenaming(false)\n setSessionRenameError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n const onSessionRename = (sessionId: SessionId, currentTitle: string) => {\n setSessionRenameTarget({ sessionId, currentTitle })\n setSessionRenameDraft(currentTitle)\n setSessionRenameError(null)\n }\n\n const onSessionArchive = (sessionId: SessionId) => {\n archiveSession(sessionId).catch((reason: unknown) => {\n console.warn('session archive rejected:', reason)\n })\n }\n\n // ---- Runtime group management ----------------------------------------------\n\n const [groupDialog, setGroupDialog] = useState(null)\n const [groupDraft, setGroupDraft] = useState('')\n const [groupError, setGroupError] = useState(null)\n const [groupBusy, setGroupBusy] = useState(false)\n const [groupDeleteTarget, setGroupDeleteTarget] = useState(null)\n const [groupDeleting, setGroupDeleting] = useState(false)\n const [groupDeleteError, setGroupDeleteError] = useState(null)\n\n const takenNames = useMemo(() => takenCategoryNames(config, manual), [config, manual])\n\n const groupTrimmed = groupDraft.trim()\n const groupNameIssue = groupDialog !== null && groupTrimmed !== ''\n ? (groupTrimmed === UNCATEGORIZED_LABEL\n ? t('group.nameReserved')\n : (groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\n ? null\n : takenNames.has(groupTrimmed) ? t('group.nameDuplicate') : null)\n : null\n const groupBlocked = groupBusy || groupTrimmed === '' || groupNameIssue !== null\n || (groupDialog !== null && groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\n\n const confirmGroupDialog = () => {\n if (groupBlocked || groupDialog === null) return\n const name = groupTrimmed\n const from = groupDialog.mode === 'rename' ? groupDialog.from : undefined\n const renaming = groupDialog.mode === 'rename' && from !== name\n\n let next: NormalizedManual\n if (groupDialog.mode === 'create') {\n next = { ...manual, categories: [...manual.categories, name] }\n } else {\n // Rename: rule groups ride the `renamed` map, manual groups the list;\n // every reference (assignments / workspaceOrder / categoryOrder) follows.\n const originalRule = from !== undefined ? originalRuleNameForDisplay(config.categories, manual, from) : undefined\n next = {\n ...manual,\n ...(originalRule !== undefined\n ? { renamed: { ...manual.renamed, [originalRule]: name } }\n : { categories: manual.categories.map(c => c === from ? name : c) }),\n assignments: Object.fromEntries(\n Object.entries(manual.assignments).map(([id, category]): [string, string | null] => [id, category === from ? name : category]),\n ),\n workspaceOrder: Object.fromEntries(\n Object.entries(manual.workspaceOrder).map(([key, ids]): [string, string[]] => [key === from ? name : key, ids]),\n ),\n categoryOrder: manual.categoryOrder.map(key => key === from ? name : key),\n }\n }\n\n setGroupBusy(true)\n setGroupError(null)\n saveManualOverlay(next).then(() => {\n setManual(next)\n setManualError(null)\n setGroupBusy(false)\n setGroupDialog(null)\n setGroupDraft('')\n // Keep the renamed group open (its old expansion key is dropped by retainKeys).\n if (renaming) actions.setCategoryExpanded(name, true)\n }).catch((reason: unknown) => {\n setGroupBusy(false)\n setGroupError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n const confirmGroupDelete = () => {\n if (groupDeleting || groupDeleteTarget === null) return\n const name = groupDeleteTarget\n const originalRule = originalRuleNameForDisplay(config.categories, manual, name)\n\n // Every project currently in the group goes to 未分类 (forced, not rule-\n // reclassified), regardless of how it landed there.\n const assignments = { ...manual.assignments }\n for (const workspace of workspaces) {\n if (resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) === name) {\n assignments[workspace.workspaceId] = null\n }\n }\n const workspaceOrder = Object.fromEntries(\n Object.entries(manual.workspaceOrder).filter(([key]) => key !== name),\n )\n const next: NormalizedManual = {\n ...manual,\n assignments,\n workspaceOrder,\n categoryOrder: manual.categoryOrder.filter(key => key !== name),\n ...(originalRule !== undefined\n ? {\n renamed: Object.fromEntries(Object.entries(manual.renamed).filter(([key]) => key !== originalRule)),\n hidden: [...manual.hidden, originalRule],\n }\n : { categories: manual.categories.filter(c => c !== name) }),\n }\n\n setGroupDeleting(true)\n setGroupDeleteError(null)\n saveManualOverlay(next).then(() => {\n setManual(next)\n setManualError(null)\n setGroupDeleting(false)\n setGroupDeleteTarget(null)\n }).catch((reason: unknown) => {\n setGroupDeleting(false)\n setGroupDeleteError(reason instanceof Error ? reason.message : String(reason))\n })\n }\n\n // ---- Drag & drop (move/reorder workspaces, reorder groups) ------------------\n\n const [dragIndicator, setDragIndicator] = useState(null)\n\n // Cancel any stale indicator when a drag ends outside a row (or is aborted).\n useEffect(() => {\n const clear = () => setDragIndicator(null)\n document.addEventListener('dragend', clear)\n return () => { document.removeEventListener('dragend', clear) }\n }, [])\n\n /** Move a workspace into a category (or reorder inside it when `beforeWorkspaceId`/`afterWorkspaceId`). */\n const moveWorkspaceTo = async (workspaceId: string, categoryKey: string, beforeWorkspaceId?: string, afterWorkspaceId?: string): Promise => {\n if (manualSaving) return\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\n if (workspace === undefined) return\n setManualSaving(true)\n try {\n let next: NormalizedManual\n if (categoryKey === UNCATEGORIZED_KEY) {\n // Drop on 未分类: force uncategorized and drop from every order list.\n const assignments = { ...manual.assignments, [workspaceId]: null }\n const workspaceOrder = Object.fromEntries(\n Object.entries(manual.workspaceOrder).map(([key, ids]) => [key, ids.filter(id => id !== workspaceId)]),\n )\n next = { ...manual, assignments, workspaceOrder }\n } else {\n const currentKey = resolveCategory(config, manual, workspaceId, workspace.path, workspace.title)\n const movingAcross = currentKey !== categoryKey\n const assignments = movingAcross\n ? { ...manual.assignments, [workspaceId]: categoryKey }\n : manual.assignments\n const targetOrder = afterWorkspaceId !== undefined\n ? moveAfter(manual.workspaceOrder[categoryKey] ?? [], workspaceId, afterWorkspaceId)\n : moveBefore(manual.workspaceOrder[categoryKey] ?? [], workspaceId, beforeWorkspaceId)\n const workspaceOrder = { ...manual.workspaceOrder, [categoryKey]: targetOrder }\n if (movingAcross && currentKey !== undefined && workspaceOrder[currentKey] !== undefined) {\n workspaceOrder[currentKey] = workspaceOrder[currentKey]!.filter(id => id !== workspaceId)\n }\n next = { ...manual, assignments, workspaceOrder }\n }\n await saveManualOverlay(next)\n setManual(next)\n setManualError(null)\n if (categoryKey !== UNCATEGORIZED_KEY) actions.setCategoryExpanded(categoryKey, true)\n } catch (reason) {\n setManualError(reason instanceof Error ? reason.message : String(reason))\n } finally {\n setManualSaving(false)\n }\n }\n\n /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */\n const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise => {\n if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return\n setManualSaving(true)\n try {\n const order = displayCategoryKeys(config, manual)\n const categoryOrder = afterKey !== undefined\n ? moveAfter(order, draggedKey, afterKey)\n : moveBefore(order, draggedKey, beforeKey)\n const next: NormalizedManual = { ...manual, categoryOrder }\n await saveManualOverlay(next)\n setManual(next)\n setManualError(null)\n } catch (reason) {\n setManualError(reason instanceof Error ? reason.message : String(reason))\n } finally {\n setManualSaving(false)\n }\n }\n\n /**\n * Drop on a row. The insertion point is re-derived from the drop event's\n * position (top half = before, bottom half = after), so it always matches\n * the indicator the user last saw — even when dragover and drop arrive in\n * the same tick.\n */\n const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {\n event.preventDefault()\n setDragIndicator(null)\n const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE)\n if (draggedCategory !== '') {\n // Group reorder: only category rows are targets (project rows fold\n // during group drags); before/after follows the drop position.\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\n const before = event.clientY < rect.top + rect.height / 2\n const beforeKey = row.kind === 'category' && before ? row.key : undefined\n const afterKey = row.kind === 'category' && !before ? row.key : undefined\n void moveCategory(draggedCategory, beforeKey, afterKey)\n return\n }\n const workspaceId = event.dataTransfer.getData(DND_WORKSPACE_TYPE) || event.dataTransfer.getData('text/plain')\n if (workspaceId === '') return\n // Project move/reorder: a line on a project row = reorder before/after it;\n // dropping anywhere else in a category = move into the group (its end).\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\n const before = event.clientY < rect.top + rect.height / 2\n const beforeWsid = row.kind === 'workspace' && before ? row.key : undefined\n const afterWsid = row.kind === 'workspace' && !before ? row.key : undefined\n void moveWorkspaceTo(workspaceId, categoryKey, beforeWsid, afterWsid)\n }\n\n const onDragOverRow = (row: DropRowRef) => (event: DragEvent): void => {\n if (!hasPluginDragType(event.dataTransfer.types)) return\n const draggingCategory = Array.from(event.dataTransfer.types as Iterable).includes(DND_CATEGORY_TYPE)\n if (draggingCategory && row.kind !== 'category') return // group drags target category rows only\n event.preventDefault()\n event.dataTransfer.dropEffect = 'move'\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\n const before = event.clientY < rect.top + rect.height / 2\n if (draggingCategory || row.kind === 'workspace') {\n // Group reorder (line on a category row) or project reorder inside a\n // group (line on a project row).\n setDragIndicator(prev =>\n prev?.mode === 'line' && prev.row.kind === row.kind && prev.row.key === row.key && prev.before === before\n ? prev\n : { mode: 'line', row, before })\n } else {\n // Dropping a project INTO a group: whole-row highlight.\n setDragIndicator(prev =>\n prev?.mode === 'into' && prev.categoryKey === row.key ? prev : { mode: 'into', categoryKey: row.key })\n }\n }\n\n const onDragLeaveRow = (event: DragEvent): void => {\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return\n setDragIndicator(null)\n }\n\n // While dragging a project, everything else folds: other categories collapse\n // (project rows render only inside expanded categories), and every session\n // expansion collapses — the source category stays open so dropping on a\n // sibling row can reorder inside it.\n const onDragStartWorkspace = (workspaceId: string) => (): void => {\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\n const sourceKey = workspace === undefined\n ? undefined\n : resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\n for (const key of Object.keys(categoryExpansion)) {\n if (!categoryExpansion[key]) continue\n if (sourceKey !== undefined && key === sourceKey) continue\n actions.setCategoryExpanded(key, false)\n }\n for (const key of Object.keys(workspaceExpansion)) {\n if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false)\n }\n }\n\n // While dragging a group, every group folds (their rows stay visible as\n // reorder targets).\n const onDragStartCategory = (categoryKey: string) => (event: DragEvent): void => {\n event.dataTransfer.setData(DND_CATEGORY_TYPE, categoryKey)\n event.dataTransfer.effectAllowed = 'move'\n for (const key of Object.keys(categoryExpansion)) {\n if (categoryExpansion[key]) actions.setCategoryExpanded(key, false)\n }\n }\n\n const now = Date.now()\n\n return (\n
\n
\n {wide && {t('section.workspaces')}}\n {wide && (\n
\n { setSearchExpanded(true) }}\n >\n \n \n {searchExpanded && (\n { setQuery(sanitizeSearchQuery(e.target.value)) }}\n onKeyDown={(e) => {\n if (e.key !== 'Escape') return\n setQuery('')\n setSearchExpanded(false)\n }}\n />\n )}\n {searchExpanded && (\n {\n e.stopPropagation()\n setQuery('')\n setSearchExpanded(false)\n }}\n >\n \n \n )}\n
\n )}\n \n {\n setGroupDraft('')\n setGroupError(null)\n setGroupDialog({ mode: 'create' })\n }}\n >\n \n \n \n \n \n \n \n \n
\n\n {!wide && (\n
\n \n { setSearchExpanded(true); expandSidebar() }}\n >\n \n \n \n
\n )}\n\n
\n {configError !== null && (\n
{t('configUnavailable')}
\n )}\n {manualError !== null && (\n
{t('manual.saveError')}: {manualError}
\n )}\n {wide && normalizedQuery !== '' ? (\n \n ) : (\n
\n {groups.length === 0 && (\n
{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}
\n )}\n {groups.map((category) => (\n { actions.setCategoryExpanded(category.key, !category.expanded) }}\n onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\n onNewSession={startSession}\n onOpen={open}\n onRenameRequest={(workspaceId, title) => {\n setRenameTarget({ workspaceId, currentTitle: title })\n setRenameDraft(title)\n setRenameError(null)\n }}\n onDeleteRequest={(workspaceId, title) => {\n setDeleteTarget({ workspaceId, title })\n setDeleteError(null)\n }}\n onSessionRename={onSessionRename}\n onSessionArchive={onSessionArchive}\n onFork={forkSession}\n onGroupRename={() => {\n setGroupDraft(category.key)\n setGroupError(null)\n setGroupDialog({ mode: 'rename', from: category.key })\n }}\n onGroupDelete={() => {\n setGroupDeleteTarget(category.key)\n setGroupDeleteError(null)\n }}\n onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}\n hasOverride={(workspaceId) => Object.hasOwn(manual.assignments, workspaceId)}\n />\n ))}\n
\n )}\n
\n\n {/* Group create / rename dialog */}\n { setGroupDialog(null) }}\n closeLabel={t('close')}\n title={groupDialog?.mode === 'rename' ? t('group.renameTitle') : t('group.createTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n { setGroupDraft(e.target.value); setGroupError(null) }}\n onKeyDown={(e) => { if (e.key === 'Enter') confirmGroupDialog() }}\n />\n {groupNameIssue !== null &&
{groupNameIssue}
}\n {groupError !== null &&
{groupError}
}\n \n\n {/* Group delete dialog */}\n { setGroupDeleteTarget(null) }}\n closeLabel={t('close')}\n title={t('group.deleteTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n
{t('group.deleteConfirm')}
\n {groupDeleteError !== null &&
{groupDeleteError}
}\n \n\n {/* Workspace rename dialog */}\n { setRenameTarget(null) }}\n closeLabel={t('close')}\n title={t('workspace.renameTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n { setRenameDraft(e.target.value) }}\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmRename() }}\n />\n {renameError !== null &&
{renameError}
}\n \n\n {/* Workspace delete dialog */}\n { setDeleteTarget(null) }}\n closeLabel={t('close')}\n title={t('workspace.deleteTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n
{t('workspace.deleteConfirm')}
\n {deleteError !== null &&
{deleteError}
}\n \n\n {/* Session rename dialog */}\n { setSessionRenameTarget(null) }}\n closeLabel={t('close')}\n title={t('session.renameTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n { setSessionRenameDraft(e.target.value) }}\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmSessionRename() }}\n />\n {sessionRenameError !== null &&
{sessionRenameError}
}\n \n\n {/* Add workspace error dialog */}\n { setAddErrorOpen(false) }}\n closeLabel={t('close')}\n title={t('workspace.addErrorTitle')}\n footer={(\n <>\n \n \n \n )}\n >\n
{addError}
\n \n
\n )\n}\n\n/** Resolve the category label containing the current session (auto-expand helper). */\nfunction categoriesForCurrent(\n config: GroupsConfig,\n workspaces: readonly WorkspaceView[],\n current: SessionId,\n manual: ManualGroups,\n): string | undefined {\n const workspace = workspaces.find(w => w.sessionIds.includes(current))\n if (workspace === undefined) return undefined\n return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\n}\n\n/** One category section: header row + expanded workspace folders. */\nfunction 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 }: {\n category: CategoryNode\n current: SessionId | undefined\n now: number\n t: GroupsBrowserProps['t']\n /** Rename/delete menu + group reorder source (false for the uncategorized bucket). */\n manageable: boolean\n dragIndicator: DragIndicator\n onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void\n onDragLeaveRow: (event: DragEvent) => void\n /** Drop factory: bind the target category and the row kind (before/after re-derived at drop time). */\n onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void\n onDragStartCategory?: (event: DragEvent) => void\n onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void\n onToggleCategory: () => void\n onToggleWorkspace: (key: string) => void\n onNewSession: (workspaceId?: WorkspaceId) => void\n onOpen: (sessionId: SessionId) => void\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\n onSessionArchive: (sessionId: SessionId) => void\n onFork: (sessionId: SessionId) => void\n onGroupRename: () => void\n onGroupDelete: () => void\n onMoveOut: (workspaceId: WorkspaceId) => void\n hasOverride: (workspaceId: WorkspaceId) => boolean\n}) {\n const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key\n ? (dragIndicator.before ? 'before' : 'after')\n : undefined\n const categoryInto = dragIndicator?.mode === 'into' && dragIndicator.categoryKey === category.key\n return (\n
\n \n {category.expanded && (\n
\n {category.workspaces.map((workspace) => (\n
\n { onToggleWorkspace(workspace.workspaceId as string) }}\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\n hasOverride={hasOverride(workspace.workspaceId)}\n onMoveOut={() => { onMoveOut(workspace.workspaceId) }}\n dropActive={false}\n {...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId\n ? { insertLine: dragIndicator.before ? 'before' : 'after' }\n : {})}\n onRowDragOver={onDragOverRow({ kind: 'workspace', key: workspace.workspaceId })}\n onRowDragLeave={onDragLeaveRow}\n onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}\n onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}\n />\n {workspace.expanded && workspace.sessions.map((session) => (\n \n ))}\n
\n ))}\n
\n )}\n
\n )\n}\n\n/**\n * Search body rendered as a three-level tree pruned to matched branches:\n * 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as\n * the idle tree, so search keeps the same folder hierarchy the user is used to.\n */\nfunction SearchBody({ list, workspaces, config, archivedSessionIds, query, remote, resultLimit, current, now, open, manual, t }: {\n list: SessionListState\n workspaces: readonly WorkspaceView[]\n config: GroupsConfig\n archivedSessionIds: readonly SessionId[]\n query: string\n remote: RemoteSearchState\n resultLimit: number\n current: SessionId | undefined\n now: number\n open: (sessionId: SessionId) => void\n manual: ManualGroups\n t: GroupsBrowserProps['t']\n}) {\n const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }\n const matches = useMemo(\n () => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),\n [list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],\n )\n const groups = useMemo(\n () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession),\n [list, workspaces, config, matches, archivedSessionIds, manual],\n )\n const pending = currentRemote.status === 'loading'\n const failed = currentRemote.status === 'error'\n return (\n
\n {groups.map((category) => (\n
\n {}} />\n
\n {category.workspaces.map((workspace) => (\n
\n {}}\n onNewSession={() => {}}\n onRename={() => {}}\n onDelete={() => {}}\n />\n
\n {workspace.sessions.map((session) => (\n {}}\n onFork={() => {}}\n onArchive={() => {}}\n />\n ))}\n
\n
\n ))}\n
\n
\n ))}\n {pending &&
{t('search.pending')}
}\n {failed &&
{t('search.unavailable')}
}\n {!pending && groups.length === 0 && (\n
{t('search.noMatches')}
\n )}\n {matches.hasMore && (\n
{t('search.hasMore')}
\n )}\n
\n )\n}\n","/**\n * Locale dictionaries for the workspace-groups browser. The namespace is\n * `workspaceGroups` (independent from ui-workspace's `workspace` namespace).\n */\nimport type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'\n\n/** Dictionary keys of the workspaceGroups namespace (single source of truth). */\nexport type WorkspaceGroupsKey =\n | 'section.workspaces'\n | 'section.sessions'\n | 'search'\n | 'search.placeholder'\n | 'search.clear'\n | 'search.noMatches'\n | 'search.unavailable'\n | 'search.pending'\n | 'search.hasMore'\n | 'search.results.aria'\n | 'workspace.add'\n | 'workspace.addBusy'\n | 'workspace.addError'\n | 'workspace.addErrorTitle'\n | 'workspace.rename'\n | 'workspace.delete'\n | 'workspace.deleteTitle'\n | 'workspace.deleteConfirm'\n | 'workspace.deleteCancel'\n | 'workspace.renaming'\n | 'workspace.deleting'\n | 'workspace.renameTitle'\n | 'workspace.renamePlaceholder'\n | 'workspace.renameConfirm'\n | 'workspace.renameCancel'\n | 'workspace.moveToUncategorized'\n | 'group.create'\n | 'group.createTitle'\n | 'group.createPlaceholder'\n | 'group.createConfirm'\n | 'group.createCancel'\n | 'group.rename'\n | 'group.renameTitle'\n | 'group.renameConfirm'\n | 'group.delete'\n | 'group.deleteTitle'\n | 'group.deleteConfirm'\n | 'group.deleteCancel'\n | 'group.nameDuplicate'\n | 'group.nameReserved'\n | 'manual.saveError'\n | 'session.new'\n | 'session.rename'\n | 'session.archive'\n | 'session.fork'\n | 'session.renameTitle'\n | 'session.renamePlaceholder'\n | 'session.renameConfirm'\n | 'session.renameCancel'\n | 'session.renaming'\n | 'uncategorized'\n | 'empty.none'\n | 'empty.noWorkspaces'\n | 'close'\n | 'cancel'\n | 'confirm'\n | 'retry'\n | 'configUnavailable'\n | 'collapse'\n | 'expandMore'\n | 'newSession'\n\nexport type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>\n\n/** Simplified Chinese dictionary. */\nexport const zh: WorkspaceGroupsDict = {\n 'section.workspaces': '工作区',\n 'section.sessions': '会话',\n search: '搜索',\n 'search.placeholder': '搜索会话…',\n 'search.clear': '清除',\n 'search.noMatches': '没有匹配的会话',\n 'search.unavailable': '搜索不可用',\n 'search.pending': '搜索中…',\n 'search.hasMore': '结果过多,请细化关键词',\n 'search.results.aria': '搜索结果',\n 'workspace.add': '添加工作区',\n 'workspace.addBusy': '正在添加…',\n 'workspace.addError': '添加失败',\n 'workspace.addErrorTitle': '无法添加工作区',\n 'workspace.rename': '重命名',\n 'workspace.delete': '删除',\n 'workspace.deleteTitle': '删除工作区',\n 'workspace.deleteConfirm': '仅删除注册信息,目录与会话日志保留。确定删除?',\n 'workspace.deleteCancel': '取消删除',\n 'workspace.renaming': '重命名中…',\n 'workspace.deleting': '删除中…',\n 'workspace.renameTitle': '重命名工作区',\n 'workspace.renamePlaceholder': '工作区名称',\n 'workspace.renameConfirm': '重命名',\n 'workspace.renameCancel': '取消',\n 'workspace.moveToUncategorized': '移到未分类',\n 'group.create': '新建分组',\n 'group.createTitle': '新建分组',\n 'group.createPlaceholder': '分组名称',\n 'group.createConfirm': '创建',\n 'group.createCancel': '取消',\n 'group.rename': '重命名分组',\n 'group.renameTitle': '重命名分组',\n 'group.renameConfirm': '重命名',\n 'group.delete': '删除分组',\n 'group.deleteTitle': '删除分组',\n 'group.deleteConfirm': '删除后,该分组内的所有项目将回到「未分类」。确定删除?',\n 'group.deleteCancel': '取消删除',\n 'group.nameDuplicate': '已存在同名分组',\n 'group.nameReserved': '该名称不可用',\n 'manual.saveError': '分组变更保存失败',\n 'session.new': '新建会话',\n 'session.rename': '重命名会话',\n 'session.archive': '归档',\n 'session.fork': '派生',\n 'session.renameTitle': '重命名会话',\n 'session.renamePlaceholder': '会话名称',\n 'session.renameConfirm': '重命名',\n 'session.renameCancel': '取消',\n 'session.renaming': '重命名中…',\n uncategorized: '未分类',\n 'empty.none': '暂无内容',\n 'empty.noWorkspaces': '还没有工作区',\n close: '关闭',\n cancel: '取消',\n confirm: '确定',\n retry: '重试',\n configUnavailable: '分组配置不可用',\n collapse: '折叠',\n expandMore: '展开全部',\n newSession: '新建会话',\n}\n\n/** English dictionary. */\nexport const en: WorkspaceGroupsDict = {\n 'section.workspaces': 'Workspaces',\n 'section.sessions': 'Sessions',\n search: 'Search',\n 'search.placeholder': 'Search sessions…',\n 'search.clear': 'Clear',\n 'search.noMatches': 'No matching sessions',\n 'search.unavailable': 'Search unavailable',\n 'search.pending': 'Searching…',\n 'search.hasMore': 'Too many results — refine the query',\n 'search.results.aria': 'Search results',\n 'workspace.add': 'Add workspace',\n 'workspace.addBusy': 'Adding…',\n 'workspace.addError': 'Add failed',\n 'workspace.addErrorTitle': 'Could not add workspace',\n 'workspace.rename': 'Rename',\n 'workspace.delete': 'Delete',\n 'workspace.deleteTitle': 'Delete workspace',\n 'workspace.deleteConfirm': 'Only the registration is removed; the directory and session logs stay. Delete?',\n 'workspace.deleteCancel': 'Cancel delete',\n 'workspace.renaming': 'Renaming…',\n 'workspace.deleting': 'Deleting…',\n 'workspace.renameTitle': 'Rename workspace',\n 'workspace.renamePlaceholder': 'Workspace name',\n 'workspace.renameConfirm': 'Rename',\n 'workspace.renameCancel': 'Cancel',\n 'workspace.moveToUncategorized': 'Move to Uncategorized',\n 'group.create': 'New group',\n 'group.createTitle': 'New group',\n 'group.createPlaceholder': 'Group name',\n 'group.createConfirm': 'Create',\n 'group.createCancel': 'Cancel',\n 'group.rename': 'Rename group',\n 'group.renameTitle': 'Rename group',\n 'group.renameConfirm': 'Rename',\n 'group.delete': 'Delete group',\n 'group.deleteTitle': 'Delete group',\n 'group.deleteConfirm': 'Deleting removes this group; every project inside it returns to Uncategorized. Delete?',\n 'group.deleteCancel': 'Cancel delete',\n 'group.nameDuplicate': 'A group with this name already exists',\n 'group.nameReserved': 'This name is not available',\n 'manual.saveError': 'Could not save group changes',\n 'session.new': 'New Session',\n 'session.rename': 'Rename session',\n 'session.archive': 'Archive',\n 'session.fork': 'Fork',\n 'session.renameTitle': 'Rename session',\n 'session.renamePlaceholder': 'Session name',\n 'session.renameConfirm': 'Rename',\n 'session.renameCancel': 'Cancel',\n 'session.renaming': 'Renaming…',\n uncategorized: 'Uncategorized',\n 'empty.none': 'Nothing here',\n 'empty.noWorkspaces': 'No workspaces yet',\n close: 'Close',\n cancel: 'Cancel',\n confirm: 'Confirm',\n retry: 'Retry',\n configUnavailable: 'Grouping config unavailable',\n collapse: 'Collapse',\n expandMore: 'Show all',\n newSession: 'New Session',\n}\n","/**\n * dsh-workspace-groups client half: registers the three-level grouped\n * workspace browser into the `sidebar.workspaces` slot, shadowing the\n * official ui-workspace browser.\n *\n * Shadowing mechanics (SlotCore semantics):\n * - `sidebar.workspaces` is a `single`/`root` slot. The official browser\n * registers at priority 0; this entry registers at priority -1, and the\n * single-cell shadow rule makes the LOWEST priority the winner — the\n * sidebar renders this browser instead of the official one.\n * - This entry deliberately declares NO child slots: the official entry\n * already declared `sidebar.workspaces.directoryFlow` (a second declaration\n * of an occupied child key throws). Add Workspace is therefore self-\n * contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.\n */\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\nimport type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\nimport type { GroupsBrowserInjected } from './contract.ts'\nimport { createGroupsViewStore } from './stores.ts'\nimport { GroupsBrowser } from './GroupsBrowser.tsx'\nimport { en, zh, type WorkspaceGroupsKey } from './locales.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The workspace-groups browsing region copy. */\n workspaceGroups: WorkspaceGroupsKey\n }\n}\n\n/** Dictionary namespace owned by this plugin. */\nconst NS = 'workspaceGroups'\n\n/** Required services (cordis fiber inject). */\nexport const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection']\n\n/**\n * Register the grouped browser once the sidebar slot declaration is on the\n * ledger. Inject factory returns plain callbacks; data reads use the\n * framework's global hooks.\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-workspace-groups: dictionaries')\n\n const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {\n const result = await ctx.sessions.search(query, signal)\n if (!result.ok) throw new Error(result.error.message)\n return result.value\n }\n\n const browserInjected = (): GroupsBrowserInjected => ({\n startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },\n open: (sessionId) => { ctx.sessions.open(sessionId) },\n searchSessions,\n searchResultLimit: ctx.sessions.searchResultLimit,\n renameSession: async (sessionId, title) => {\n const session = ctx.sessions.binding(sessionId)?.session\n if (session === undefined) throw new Error(`unknown session \"${sessionId}\"`)\n const result = await session.rename(title)\n if (!result.ok) throw new Error(result.error.message)\n },\n forkSession: (sessionId) => {\n ctx.sessions.fork({ sessionId, increaseTitle: true })\n .then((childId) => { ctx.sessions.open(childId) })\n .catch(() => {})\n },\n renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },\n deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },\n insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {\n await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)\n },\n archiveSession: async (sessionId) => { await ctx.workspaces.archiveSession(sessionId) },\n insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {\n await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)\n },\n createWorkspace: input => ctx.workspaces.create(input),\n pickDirectory: () => ctx.workspaces.pickDirectory(),\n hooks: {\n hostDescription: (ctx.get('connection') as ConnectionHandle).hostDescription,\n },\n })\n\n // priority: -1 — lower than the official browser's default 0, so the\n // single-slot shadow rule elects this entry. No children declaration: the\n // official entry already owns `sidebar.workspaces.directoryFlow`.\n ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(\n {\n name: 'sidebar.workspaces',\n priority: -1,\n store: createGroupsViewStore(),\n inject: browserInjected,\n locale: NS,\n registrant: 'dsh-workspace-groups',\n },\n GroupsBrowser,\n ))\n}\n"],"mappings":";;;;;;;;;;;;EAsBA,SAAgB,wBAAwB,OAAwB,KAAa,UAAyB;GACpG,MAAM,kBAAkB,OAAO;EACjC;;EAGA,SAAgB,yBAAyB,OAAwB,KAAa,UAAyB;GACrG,MAAM,mBAAmB,OAAO;EAClC;;EAGA,SAAgB,eACd,OACA,cACA,eACM;GACN,MAAM,oBAAoB,OAAO,YAC/B,OAAO,QAAQ,MAAM,iBAAiB,CAAC,CAAC,QAAQ,CAAC,SAAS,aAAa,SAAS,GAAG,CAAC,CACtF;GACA,MAAM,qBAAqB,OAAO,YAChC,OAAO,QAAQ,MAAM,kBAAkB,CAAC,CAAC,QAAQ,CAAC,SAAS,cAAc,SAAS,GAAG,CAAC,CACxF;EACF;;;;;;;;;;;;;;;;;;;ECZA,SAAgB,wBAA+E;GAC7F,QAAA,GAAOA,uCAAAA,YAAAA,CAAY;IACjB,aAAa;KAAE,mBAAmB,CAAC;KAAG,oBAAoB,CAAC;IAAE;IAC7D,SAAS;IACT,SAAS;KACP,qBAAqB;KACrB,sBAAsB;KACtB,YAAY;IACd;GACF,CAAC;EACH;;;;ECgDA,MAAa,sBAAsB;;EAGnC,SAAgB,cAAc,MAAsB;G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AClD,MAAM,YAAY;MAAE,IAAI,SAAS,KAAK,OAAO;KAAE,CAAC,CAAC,CACjD,YAAY,CAAC,CAAC;IACnB;IACA,iBAAiB,OAAO,aAAa,UAAU;KAAE,MAAM,IAAI,WAAW,OAAO,aAAa,KAAK;IAAE;IACjG,iBAAiB,OAAO,gBAAgB;KAAE,MAAM,IAAI,WAAW,OAAO,WAAW;IAAE;IACnF,uBAAuB,OAAO,aAAa,sBAAsB;KAC/D,MAAM,IAAI,WAAW,aAAa,aAAa,iBAAiB;IAClE;IACA,gBAAgB,OAAO,cAAc;KAAE,MAAM,IAAI,WAAW,eAAe,SAAS;IAAE;IACtF,qBAAqB,OAAO,aAAa,WAAW,oBAAoB;KACtE,MAAM,IAAI,WAAW,oBAAoB,aAAa,WAAW,eAAe;IAClF;IACA,kBAAiB,UAAS,IAAI,WAAW,OAAO,KAAK;IACrD,qBAAqB,IAAI,WAAW,cAAc;IAClD,OAAO,EACL,iBAAkB,IAAI,IAAI,YAAY,CAAC,CAAsB,gBAC/D;GACF;GAKA,IAAI,MAAM,OAAO,4BAA4B,IAAI,MAAM,SACrD;IACE,MAAM;IACN,UAAU;IACV,OAAO,sBAAsB;IAC7B,QAAQ;IACR,QAAQ;IACR,YAAY;GACd,GACA,aACF,CAAC;EACH"} \ No newline at end of file diff --git a/lib/index.js b/lib/index.js index e235a9b..b810b10 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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 }; diff --git a/lib/types/client/GroupsBrowser.d.ts b/lib/types/client/GroupsBrowser.d.ts index 89f5e4f..a11d3a7 100644 --- a/lib/types/client/GroupsBrowser.d.ts +++ b/lib/types/client/GroupsBrowser.d.ts @@ -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). diff --git a/lib/types/client/locales.d.ts b/lib/types/client/locales.d.ts index 2a183d3..7de80a6 100644 --- a/lib/types/client/locales.d.ts +++ b/lib/types/client/locales.d.ts @@ -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; diff --git a/lib/types/client/rows.d.ts b/lib/types/client/rows.d.ts index 21e3af1..254867e 100644 --- a/lib/types/client/rows.d.ts +++ b/lib/types/client/rows.d.ts @@ -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): 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; diff --git a/lib/types/client/tree.d.ts b/lib/types/client/tree.d.ts index bbcdda9..b10d47b 100644 --- a/lib/types/client/tree.d.ts +++ b/lib/types/client/tree.d.ts @@ -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, archivedSessionIds: readonly SessionId[], snippetsBySession?: ReadonlyMap): CategoryNode[]; +export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap): CategoryNode[]; diff --git a/lib/types/core/matcher.d.ts b/lib/types/core/matcher.d.ts index 879c3c0..f8e8164 100644 --- a/lib/types/core/matcher.d.ts +++ b/lib/types/core/matcher.d.ts @@ -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; +/** + * 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[]; diff --git a/lib/types/core/types.d.ts b/lib/types/core/types.d.ts index 16d26c4..9b06ef0 100644 --- a/lib/types/core/types.d.ts +++ b/lib/types/core/types.d.ts @@ -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; + /** + * 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; + /** + * 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; + /** + * 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"; diff --git a/lib/types/host-manual.d.ts b/lib/types/host-manual.d.ts new file mode 100644 index 0000000..70c4316 --- /dev/null +++ b/lib/types/host-manual.d.ts @@ -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; +/** + * 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; diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 91192a3..2433efe 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -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; diff --git a/screenshot.png b/screenshot.png index 8e7bf01..ffb2fe0 100644 Binary files a/screenshot.png and b/screenshot.png differ diff --git a/scripts/verify-groups.mjs b/scripts/verify-groups.mjs new file mode 100644 index 0000000..6232b3d --- /dev/null +++ b/scripts/verify-groups.mjs @@ -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()) diff --git a/src/client/GroupsBrowser.tsx b/src/client/GroupsBrowser.tsx index 3866d18..14dafc8 100644 --- a/src/client/GroupsBrowser.tsx +++ b/src/client/GroupsBrowser.tsx @@ -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 + +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 { +/** 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 { + 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({ categories: [] }) + const [manual, setManual] = useState(EMPTY_MANUAL) const [configError, setConfigError] = useState(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(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(null) + const [groupDraft, setGroupDraft] = useState('') + const [groupError, setGroupError] = useState(null) + const [groupBusy, setGroupBusy] = useState(false) + const [groupDeleteTarget, setGroupDeleteTarget] = useState(null) + const [groupDeleting, setGroupDeleting] = useState(false) + const [groupDeleteError, setGroupDeleteError] = useState(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(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 => { + 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 => { + 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).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({ )} )} + + + + + + )} + > + { setGroupDraft(e.target.value); setGroupError(null) }} + onKeyDown={(e) => { if (e.key === 'Enter') confirmGroupDialog() }} + /> + {groupNameIssue !== null &&
{groupNameIssue}
} + {groupError !== null &&
{groupError}
} + + + {/* Group delete dialog */} + { setGroupDeleteTarget(null) }} + closeLabel={t('close')} + title={t('group.deleteTitle')} + footer={( + <> + + + + )} + > +
{t('group.deleteConfirm')}
+ {groupDeleteError !== null &&
{groupDeleteError}
} +
+ {/* Workspace rename dialog */} 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 (
- + {category.expanded && (
{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) => ( 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' diff --git a/src/client/locales.ts b/src/client/locales.ts index 8b23a90..c5b140e 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -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', diff --git a/src/client/rows.tsx b/src/client/rows.tsx index e2bc8c5..0926bdc 100644 --- a/src/client/rows.tsx +++ b/src/client/rows.tsx @@ -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) + 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 (
@@ -81,30 +128,79 @@ export function CategoryRow({ node, t, onToggle }: { {node.label} {count} + {manageable && ( + + { setMenuOpen(false) }} + items={[ + { id: 'rename', label: t('group.rename'), icon: }, + { id: 'delete', label: t('group.delete'), icon: , danger: true }, + ]} + onSelect={(id) => { + setMenuOpen(false) + if (id === 'rename') onRename() + if (id === 'delete') onDelete() + }} + portal + closeOnPointerLeave + anchor={( + + )} + /> + + )}
) } -/** 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: }] + : []), { id: 'rename', label: t('workspace.rename'), icon: }, { id: 'delete', label: t('workspace.delete'), icon: , danger: true }, ] + const onDragStart = (event: DragEvent): void => { + event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId) + event.dataTransfer.effectAllowed = 'move' + onDragStartExtra?.() + } return (
@@ -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