From 0db6e06ccf44f68c47ee7eee793a4d8d0d16bd89 Mon Sep 17 00:00:00 2001 From: qyh15 Date: Wed, 28 Oct 2026 00:41:51 +0800 Subject: [PATCH] feat(sidebar): multi-root workspaces (extra folders + one root per project) A DSH workspace owns exactly one canonical directory, so the folder layer is a plugin-side overlay instead of a core change: \/workspace-groups.folders.json stores extra folders and the chosen root per workspace id (strict on write, tolerant on read). The tree gains a folder row only when a project actually has extras, and sessions are partitioned by their recorded cwd with the most specific folder winning. A folder row can start a session in its own directory through sessions.create({workspaceId, cwd}); the base folder keeps the platform gesture so repeated clicks reuse the blank session. Folders start expanded so attaching one never hides rows that were already visible. --- DEVELOPMENT.md | 10 +- README.md | 42 +- README_ZH.md | 17 +- lib/client.js | 1017 ++++++++++++++++++++++--- lib/client.js.map | 2 +- lib/index.js | 298 ++++++++ lib/types/client/GroupsBrowser.d.ts | 2 +- lib/types/client/contract.d.ts | 5 + lib/types/client/folders-persist.d.ts | 33 + lib/types/client/locales.d.ts | 2 +- lib/types/client/rows.d.ts | 32 +- lib/types/client/tree.d.ts | 50 +- lib/types/core/folders.d.ts | 91 +++ lib/types/host-folders.d.ts | 46 ++ src/client/GroupsBrowser.tsx | 565 ++++++++++++-- src/client/contract.ts | 5 + src/client/folders-persist.ts | 97 +++ src/client/index.ts | 11 + src/client/locales.ts | 39 + src/client/rows.tsx | 122 ++- src/client/styles.css | 112 +++ src/client/tree.ts | 165 +++- src/core/folders.ts | 196 +++++ src/host-folders.ts | 240 ++++++ src/index.ts | 66 ++ tests/folders.test.ts | 254 ++++++ tools/verify-folders.mjs | 146 ++++ 27 files changed, 3467 insertions(+), 198 deletions(-) create mode 100644 lib/types/client/folders-persist.d.ts create mode 100644 lib/types/core/folders.d.ts create mode 100644 lib/types/host-folders.d.ts create mode 100644 src/client/folders-persist.ts create mode 100644 src/core/folders.ts create mode 100644 src/host-folders.ts create mode 100644 tests/folders.test.ts create mode 100644 tools/verify-folders.mjs diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index dc3373d..c2c37ef 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -34,9 +34,10 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30 | 文件 | 职责 | | --- | --- | -| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 条路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual` | +| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT /workspace-groups/folders` | | `src/host-config.ts` | 读用户 YAML 分类规则(默认 `~/.dsh/workspace-groups.yaml`),校验后以 JSON 下发 | | `src/host-manual.ts` | 运行期分组覆盖(手动分组 + 单工作区归类覆盖),落 `$DSH_HOME/workspace-groups.manual.json` | +| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容) | | `src/host-tabs.ts` | 会话标签条的宿主侧持久化。放在宿主是因为**浏览器存储按 origin 隔离,而 origin 含端口**,`dsh web`/测试/桌面壳端口各不相同 | | `src/context-types.ts` | 本插件消费的 cordis 服务结构类型(第三方插件拿不到 monorepo 内的 `declare module` 合并) | @@ -46,6 +47,7 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30 | --- | --- | | `src/core/types.ts` | 规则配置类型,零运行时依赖 | | `src/core/matcher.ts` | 归类与排序的纯函数:工作区归哪个分类、分类/工作区怎么排。宿主校验与客户端建树共用,语义不会漂移 | +| `src/core/folders.ts` | 多文件夹的纯函数:有效文件夹列表、根目录解析、cwd 归属(最具体优先)。宿主校验与客户端建树共用 | 浏览器半边(`src/client/`,输出 CJS 闭包工厂): @@ -55,7 +57,8 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30 | `contract.ts` | 注入共享契约(`GroupsBrowserInjected`),镜像官方 ui-workspace 的注入形状 | | `GroupsBrowser.tsx` | 主 UI:分区头(标题/搜索/新建分组/添加工作区)+ 三级树 + 分组/工作区/会话对话框 | | `rows.tsx` | 树的行组件(行内菜单、状态点、图标),对话框挂在 browser root 以免折叠时卸载 | -| `tree.ts` | 纯派生:分类文件夹 → 项目文件夹 → 会话行;可见性规则对齐官方树 | +| `tree.ts` | 纯派生:分类文件夹 → 项目文件夹 →(可选)文件夹行 → 会话行;可见性规则对齐官方树 | +| `folders-persist.ts` | 文件夹 overlay 的客户端侧,读写宿主 `/workspace-groups/folders` | | `locales.ts` | `workspaceGroups` 命名空间词典(zh/en + key 联合类型) | | `styles.css` | 全部样式,`?inline` 导入后由构建期 lightningcss 压缩内联 | | `branch.ts` / `FlowerBranch.tsx` | 侧栏当前行的「花朵」标记(几何计算在 `branch.ts`,仍由单测覆盖;连线与逐行圆点已移除,只画花朵) | @@ -71,7 +74,8 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30 | `stores.ts` | 视图 store 工厂(展开状态,独立持久化 key,不碰官方 `dsh.workspace.view.v5`) | | `store-hook.ts` | 面向 store 实例的框架形状选择器 hook(`useSyncExternalStoreWithSelector`) | -其它:`tests/*.test.ts`(vitest,覆盖 core matcher/tree/store),`cordis.patch.yml` +其它:`tests/*.test.ts`(vitest,覆盖 core matcher/tree/store/tabs/folders), +`tools/verify-folders.mjs`(沙箱内 vitest 起不来时的等价纯 node 断言),`cordis.patch.yml` (cordis 插件补丁层),`scripts/verify-groups.mjs`,`workspace-groups.example.yaml`。 ## 3. 构建 / 校验 / 装回去 diff --git a/README.md b/README.md index 4ab10bd..8e93971 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,23 @@ skipped for large subtrees, during drag folding, and under `prefers-reduced-motion` - Stored in the overlay's `appearance` map — **never in the rule YAML** (see below) +### Multiple folders per workspace (multi-root) +- **Attach extra folders to a project**: the project row's `⋯` menu opens **文件夹…** + (`Folders…`), which lists the project's own directory as the **base folder** (always folder + #0, never removable) plus any extra folders you pick +- **One root folder per project**: the radio column in that dialog and the folder row's + `⋯ → 设为根目录` choose which folder new sessions default to; the root row is hoisted to the + top of the folder list and carries a ★ badge +- **Sessions partition by their own cwd**: a project with extra folders shows a folder row + above its sessions, and each session drops into the folder that contains its working + directory (most specific folder wins, case-insensitive on Windows). Projects without extra + folders keep the flat two-level shape — nothing changes for them +- **Start a session in a specific folder**: the hover `+` on a folder row opens a session whose + cwd is that folder; the base folder keeps the platform's own "new session" gesture so + clicking it twice reuses the blank session instead of stacking empty ones +- Folders start expanded, so attaching one never hides sessions that were already visible; + collapse state is per-view and intentionally not persisted + ### Search & operations - **Tree-shaped search**: results keep the three-level structure (category → project → matched session), matched rows highlighted with a content snippet, 250ms debounce @@ -88,7 +105,9 @@ - Every manual action (groups, grouping, ordering, rename, hide) is written to the plugin's own overlay (`~/.dsh/workspace-groups.manual.json`), validated by the host and **written atomically** (a malformed write returns 400 and keeps the previous file); the tab strip gets - the same treatment in its own file (`~/.dsh/workspace-groups.tabs.json`) + the same treatment in its own file (`~/.dsh/workspace-groups.tabs.json`), and so do the + extra folders / root choice of a project (`~/.dsh/workspace-groups.folders.json`, strict on + write, tolerant on read — unknown or vanished folders are dropped instead of breaking the tree) - **Zero intrusion**: never touches `~/.dsh/storages/workspace.json`, session on-disk structures, or the official `@deepseek-ai/dsh-client-ui-workspace` package; the rule YAML is never rewritten @@ -307,20 +326,29 @@ Artifact contract (mirrors the official client packages): ``` src/ - index.ts # host half: config snapshot route + manual write route + index.ts # host half: config snapshot route + manual / tabs / folders write routes host-config.ts # sidecar YAML reading/validation host-manual.ts # runtime overlay read/write/validation (atomic publish) + host-folders.ts # per-workspace extra folders + root overlay (strict write, tolerant read) + host-tabs.ts # session tab strip persistence (atomic publish) context-types.ts # host-side cordis service structure types core/ types.ts # config types (shared by both halves) matcher.ts # classification + manual override priority + ordering pure functions (shared) + folders.ts # multi-root pure logic: effective folders / root / cwd ownership (shared) client/ index.ts # apply: registers sidebar.workspaces (priority -1) contract.ts # injected surface types stores.ts # expansion-state store (persist: dsh.workspace.groups.view.v1) - tree.ts # three-level tree derivation + tree search derivation - GroupsBrowser.tsx # browser region component (group dialogs + drag grouping/ordering + insertion indicator) - rows.tsx # category/project/session/search-result rows (drag sources/targets) + tree.ts # three-level tree derivation + folder partition + tree search derivation + GroupsBrowser.tsx # browser region component (group dialogs + folder dialog + drag grouping/ordering) + rows.tsx # category/project/folder/session/search-result rows (drag sources/targets) + SessionTabs.tsx # tab strip (pin / drag reorder / context menu / inline rename) + tab-store.ts # tab strip store (order, pin, title override) + tab-persist.ts # tab strip wire calls (GET/PUT /workspace-groups/tabs) + folders-persist.ts # folder overlay wire calls (GET/PUT /workspace-groups/folders) + FlowerBranch.tsx # bloom marker on the active row (geometry in branch.ts) + branch.ts # flower geometry pure functions (unit tested) locales.ts # zh/en copy styles.css # inline styles tests/ @@ -328,6 +356,10 @@ tests/ manual.test.ts # overlay validation + atomic file round-trip tree.test.ts # tree derivation rendering contract (manual group empty render / override priority) store.test.ts # expansion semantics (collapse writes false, never deletes the key) + tabs.test.ts # tab strip pure logic (append/remove/ordered/restore/indicator) + folders.test.ts # multi-root pure logic + strict/tolerant overlay parsing +tools/ + verify-folders.mjs # plain-node verifier for the folder layer (vitest cannot spawn in the sandbox) scripts/ verify-groups.mjs # real-browser CDP verification (self-spawns headless Chrome, auto-restores the scene) ``` diff --git a/README_ZH.md b/README_ZH.md index e520437..c89ca44 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -65,6 +65,19 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点 花不会滞后于所在行;大树、拖动折叠中、`prefers-reduced-motion` 下自动跳过动画 - 存放在 overlay 的 `appearance` 里,**绝不写进规则 YAML** +### 一个工作区多个文件夹(multi-root) +- **给项目挂多个文件夹**:项目行的 `⋯` 菜单里点 **文件夹…**,弹窗第一行是项目自带的 + 目录(**基础文件夹**,永远是 #0,不可移除),下面是你自己加的额外文件夹 +- **每个项目一个根目录**:弹窗里的单选列,或文件夹行的 `⋯ → 设为根目录`,决定“新建会话” + 默认落在哪个文件夹;根目录那一行会被提到最前面并带 ★ 标记 +- **会话按自己的 cwd 归位**:项目一旦有额外文件夹,会话上方会多出文件夹行,每条会话按 + 自己记录的 cwd 落进所属文件夹(最具体的文件夹优先,Windows 下大小写不敏感);没有额外 + 文件夹的项目保持原来的两层扁平结构,行为完全不变 +- **在指定文件夹里开会话**:文件夹行悬停的 `+` 会以该文件夹为 cwd 新建会话;基础文件夹 + 沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话 +- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态, + 故意不持久化 + ### 搜索与操作 - **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 + 内容摘要,防抖 250ms @@ -74,7 +87,9 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点 ### 持久化与零侵入 - 所有手动操作(分组、归类、排序、改名、隐藏)写入插件自有 overlay (`~/.dsh/workspace-groups.manual.json`),host 校验后**原子写入**(写坏返回 400 并 - 保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json` + 保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json`;项目的 + 额外文件夹与根目录选择也一样,独立文件 `~/.dsh/workspace-groups.folders.json` + (写时严格、读时宽容 —— 不认识的文件夹直接丢弃,不会把树弄坏) - **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、不修改官方 `@deepseek-ai/dsh-client-ui-workspace` 包;规则 YAML 永不改写 - **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本 diff --git a/lib/client.js b/lib/client.js index 485e2ad..fc18169 100644 --- a/lib/client.js +++ b/lib/client.js @@ -939,6 +939,162 @@ window.__ModuleLoader__.load({ return indexed; } //#endregion + //#region src/core/folders.ts + /** Canonical empty document, shared so callers need not allocate one each time. */ + const EMPTY_FOLDERS_DOCUMENT = { + version: 1, + workspaces: {} + }; + /** `C:\…` or `C:/…` — a drive-rooted Windows path. */ + const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u; + /** `\\server\share` — a Windows UNC path. */ + const WINDOWS_UNC = /^\\\\/u; + /** True for both Windows path spellings accepted by the write validator. */ + function isWindowsStyle(path) { + return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path); + } + /** + * Comparison form of one path: trimmed, separator-normalized and, for Windows + * spellings, lower-cased (drive letters and file names are case-insensitive + * there). Trailing separators are dropped except for a drive/UNC/root prefix. + * @param path - raw path as stored or picked. + * @returns the canonical comparison form. + */ + function canonicalPath(path) { + const trimmed = path.trim(); + if (isWindowsStyle(trimmed)) { + let value = trimmed.replaceAll("/", "\\").toLowerCase(); + while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1); + return value; + } + let value = trimmed; + while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1); + return value; + } + /** + * Path equality: case-insensitive for Windows-style paths, tolerant of + * trailing separators, exact for POSIX paths. + * @param a - first path. + * @param b - second path. + */ + function samePath(a, b) { + return canonicalPath(a) === canonicalPath(b); + } + /** + * Look up the folder entry saved for one workspace. + * @param doc - folders document. + * @param workspaceId - host workspace id. + * @returns the entry, or undefined when the workspace has none. + */ + function entryFor(doc, workspaceId) { + return doc.workspaces[workspaceId]; + } + /** + * The workspace's effective folder list, base first. The base cannot be + * duplicated and blank extra entries are dropped. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + */ + function effectiveFolders(workspacePath, entry) { + const extras = []; + for (const folder of entry?.folders ?? []) { + if (folder.trim() === "") continue; + if (samePath(folder, workspacePath)) continue; + if (extras.some((existing) => samePath(existing, folder))) continue; + extras.push(folder); + } + return [workspacePath, ...extras]; + } + /** + * The folder new sessions start in by default. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the stored root when it names an effective extra folder, else the + * workspace's own directory. + */ + function rootOf(workspacePath, entry) { + const root = entry?.root; + if (root === void 0) return workspacePath; + return effectiveFolders(workspacePath, entry).find((folder) => samePath(folder, root)) ?? workspacePath; + } + /** + * Owning folder of a session cwd: the most specific (longest) effective folder + * that equals the cwd or is a proper path ancestor of it. + * @param cwd - recorded session cwd; undefined means "the workspace itself". + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the owning folder, or the workspace path when nothing matches. + */ + function folderOfCwd(cwd, workspacePath, entry) { + if (cwd === void 0) return workspacePath; + const target = canonicalPath(cwd); + let best; + let bestLength = -1; + for (const folder of effectiveFolders(workspacePath, entry)) { + const root = canonicalPath(folder); + if (root === "") continue; + const separator = isWindowsStyle(root) ? "\\" : "/"; + const prefix = root.endsWith(separator) ? root : `${root}${separator}`; + if (target !== root && !target.startsWith(prefix)) continue; + if (root.length > bestLength) { + best = folder; + bestLength = root.length; + } + } + return best ?? workspacePath; + } + /** + * Append an extra folder. Idempotent under `samePath`, and the stored root (if + * any) survives untouched. + * @param entry - current entry, or undefined for a workspace with no extras. + * @param path - folder path to append. + */ + function addFolder(entry, path) { + const folders = entry?.folders ?? []; + const root = entry?.root; + const trimmed = path.trim(); + const keepRoot = root === void 0 ? {} : { root }; + if (trimmed === "" || folders.some((folder) => samePath(folder, trimmed))) return { + folders: [...folders], + ...keepRoot + }; + return { + folders: [...folders, trimmed], + ...keepRoot + }; + } + /** + * Drop an extra folder. A root that pointed at it is cleared, so the workspace + * falls back to its own directory instead of referencing a folder it no longer + * has. + * @param entry - current entry, or undefined. + * @param path - folder path to drop. + */ + function removeFolder(entry, path) { + const remaining = (entry?.folders ?? []).filter((folder) => !samePath(folder, path)); + const root = entry?.root; + return { + folders: remaining, + ...root !== void 0 && !samePath(root, path) ? { root } : {} + }; + } + /** + * Designate the root folder. Only an extra folder can be stored: naming the + * base directory means "no explicit root", which is represented by clearing + * the key. + * @param entry - current entry, or undefined. + * @param path - folder to make the root. + */ + function setRoot(entry, path) { + const folders = entry?.folders ?? []; + const match = folders.find((folder) => samePath(folder, path)); + if (match === void 0) return { folders: [...folders] }; + return { + folders: [...folders], + root: match + }; + } + //#endregion //#region src/client/tree.ts /** * The Session the Conversation is currently showing. @@ -1003,6 +1159,73 @@ window.__ModuleLoader__.load({ return nodes; } /** + * Display label of one folder: the last path segment. A drive root (`C:\`) or + * the POSIX root has no segment, so the whole path is the honest label. + * @param path - absolute folder path. + */ + function folderLabel(path) { + const trimmed = path.replace(/[/\\]+$/u, ""); + if (trimmed === "" || /^[A-Za-z]:$/u.test(trimmed)) return path; + const base = trimmed.split(/[/\\]/u).pop(); + return base !== void 0 && base !== "" ? base : path; + } + /** Stable identity of one folder row (same path may live under two workspaces). */ + function folderKey(workspaceId, path) { + return `${workspaceId}\u0000${path}`; + } + /** + * Split a workspace's visible sessions between its base directory and its extra + * folders. Sessions keep the order they already had inside their owner, and a + * workspace with no extra folder returns its sessions untouched — the pre- + * folders node shape (no `folders` key at all). + * @param workspaceId - owning workspace. + * @param workspacePath - canonical directory (folder #0). + * @param sessions - every visible session of the workspace, in host order. + * @param list - sessions list snapshot (records each session's cwd). + * @param entry - saved extra folders + root for this workspace. + * @param collapsedFolders - collapsed folder-row keys. Undefined means "nothing + * is collapsed", which is both the default view and what search uses so every + * hit is visible without another click. + */ + function applyFolders(workspaceId, workspacePath, sessions, list, entry, collapsedFolders) { + const extras = effectiveFolders(workspacePath, entry).slice(1); + if (extras.length === 0) return { sessions }; + const root = rootOf(workspacePath, entry); + const base = []; + const byFolder = /* @__PURE__ */ new Map(); + for (const node of sessions) { + const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry); + if (samePath(owner, workspacePath)) { + base.push(node); + continue; + } + const bucket = byFolder.get(owner); + if (bucket === void 0) byFolder.set(owner, [node]); + else bucket.push(node); + } + const folderNode = (path, isBase) => { + const owned = isBase ? base : byFolder.get(path) ?? []; + return { + path, + label: folderLabel(path), + isRoot: samePath(path, root), + expanded: collapsedFolders === void 0 || !collapsedFolders.has(folderKey(workspaceId, path)), + isBase, + sessions: owned + }; + }; + const folders = [folderNode(workspacePath, true), ...extras.map((path) => folderNode(path, false))]; + const rootIndex = folders.findIndex((folder) => folder.isRoot); + if (rootIndex > 0) { + const [rootFolder] = folders.splice(rootIndex, 1); + if (rootFolder !== void 0) folders.unshift(rootFolder); + } + return { + sessions: base, + folders + }; + } + /** * Derive the three-level tree. * @param list - sessions list snapshot (`current` feeds containsCurrent). * @param workspaces - real workspaces in stable Host order. @@ -1013,14 +1236,18 @@ window.__ModuleLoader__.load({ * manual override wins over rule classification; removing it reverts to rules. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root. A workspace with extras + * gains folder rows and its extra-folder sessions move under them; a workspace + * without extras keeps exactly the pre-folders node shape. * @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, manual, statuses = /* @__PURE__ */ new Map()) { + function deriveGroups(list, workspaces, archivedSessionIds, config, view, manual, statuses = /* @__PURE__ */ new Map(), folders = EMPTY_FOLDERS_DOCUMENT) { const archived = new Set(archivedSessionIds); const expandedCategories = new Set(view.expandedCategories); const expandedWorkspaces = new Set(view.expandedWorkspaces); + const collapsedFolders = new Set(view.collapsedFolders ?? []); const descendants = indexSubagentDescendants(list.byId); const current = currentSessionId(list); const byCategory = /* @__PURE__ */ new Map(); @@ -1047,6 +1274,7 @@ window.__ModuleLoader__.load({ const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current); const wsExpanded = expandedWorkspaces.has(workspace.workspaceId); const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId; + const partitioned = applyFolders(workspace.workspaceId, workspace.path, sessions, list, entryFor(folders, workspace.workspaceId), collapsedFolders); if (wsContainsCurrent) containsCurrent = true; workspaceNodes.push({ workspaceId: workspace.workspaceId, @@ -1056,7 +1284,8 @@ window.__ModuleLoader__.load({ sessionCount: sessions.length, expanded: wsExpanded, containsCurrent: wsContainsCurrent, - sessions: wsExpanded ? sessions : [] + sessions: wsExpanded ? partitioned.sessions : [], + ...partitioned.folders === void 0 ? {} : { folders: partitioned.folders } }); } const appearance = categoryAppearance(manual, key); @@ -1078,9 +1307,10 @@ window.__ModuleLoader__.load({ * folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`), * falling back to host registration order. */ - function deriveTopLevel(list, workspaces, archivedSessionIds, config, view, manual, statuses = /* @__PURE__ */ new Map()) { + function deriveTopLevel(list, workspaces, archivedSessionIds, config, view, manual, statuses = /* @__PURE__ */ new Map(), folders = EMPTY_FOLDERS_DOCUMENT) { const archived = new Set(archivedSessionIds); const expandedWorkspaces = new Set(view.expandedWorkspaces); + const collapsedFolders = new Set(view.collapsedFolders ?? []); const descendants = indexSubagentDescendants(list.byId); const current = currentSessionId(list); const currentWorkspaceId = current === void 0 ? void 0 : workspaces.find((w) => w.sessionIds.includes(current))?.workspaceId; @@ -1092,6 +1322,7 @@ window.__ModuleLoader__.load({ if (workspace === void 0) continue; const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current); const wsExpanded = expandedWorkspaces.has(workspaceId); + const partitioned = applyFolders(workspace.workspaceId, workspace.path, sessions, list, entryFor(folders, workspaceId), collapsedFolders); nodes.push({ workspaceId: workspace.workspaceId, path: workspace.path, @@ -1100,7 +1331,8 @@ window.__ModuleLoader__.load({ sessionCount: sessions.length, expanded: wsExpanded, containsCurrent: workspace.workspaceId === currentWorkspaceId, - sessions: wsExpanded ? sessions : [] + sessions: wsExpanded ? partitioned.sessions : [], + ...partitioned.folders === void 0 ? {} : { folders: partitioned.folders } }); } return nodes; @@ -1175,10 +1407,12 @@ window.__ModuleLoader__.load({ * @param snippetsBySession - optional content-match snippets keyed by session id. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root, so a hit inside an extra + * folder surfaces under that folder instead of flat under the project. * @returns group folders in render order plus top-level matched workspaces, * pruned to matched branches only. */ - function deriveSearchGroups(list, workspaces, config, matchedIds, archivedSessionIds, manual, snippetsBySession, statuses = /* @__PURE__ */ new Map()) { + function deriveSearchGroups(list, workspaces, config, matchedIds, archivedSessionIds, manual, snippetsBySession, statuses = /* @__PURE__ */ new Map(), folders = EMPTY_FOLDERS_DOCUMENT) { const archived = new Set(archivedSessionIds); const descendants = indexSubagentDescendants(list.byId); const current = currentSessionId(list); @@ -1200,6 +1434,7 @@ window.__ModuleLoader__.load({ }); } if (nodes.length === 0) continue; + const partitioned = applyFolders(workspace.workspaceId, workspace.path, nodes, list, entryFor(folders, workspace.workspaceId), void 0); const node = { workspaceId: workspace.workspaceId, path: workspace.path, @@ -1208,7 +1443,8 @@ window.__ModuleLoader__.load({ sessionCount: nodes.length, expanded: true, containsCurrent: false, - sessions: nodes + sessions: partitioned.sessions, + ...partitioned.folders === void 0 ? {} : { folders: partitioned.folders } }; const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title); if (key === void 0) { @@ -1447,7 +1683,7 @@ window.__ModuleLoader__.load({ }); } /** One workspace folder row inside a category: draggable source + drop target. */ - function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }) { + function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onManageFolders, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }) { const [menuOpen, setMenuOpen] = (0, react.useState)(false); const menuItems = [ ...onOpenInFolder !== void 0 ? [{ @@ -1460,6 +1696,11 @@ window.__ModuleLoader__.load({ label: t("workspace.moveOutOfGroup"), icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconRightUpOutlineRegular, { size: 16 }) }] : [], + ...onManageFolders !== void 0 ? [{ + id: "folders", + label: t("folder.manage"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular, { size: 16 }) + }] : [], { id: "rename", label: t("workspace.rename"), @@ -1517,6 +1758,7 @@ window.__ModuleLoader__.load({ setMenuOpen(false); if (id === "openInFolder") onOpenInFolder?.(); if (id === "moveOut") onMoveOut?.(); + if (id === "folders") onManageFolders?.(); if (id === "rename") onRename(); if (id === "delete") onDelete(); }, @@ -1548,6 +1790,123 @@ window.__ModuleLoader__.load({ ] }); } + /** + * One folder row under a project: the base directory (folder #0) plus every + * extra folder of that workspace. Sits at the session indent level so the + * 42/58/74 ladder is preserved, and its own session rows indent one step + * deeper (see `.wgSessionNested`). + * + * Deliberately NOT a drag source or drop target: folders are a fixed, + * host-ordered list; reordering them would need a write path this feature does + * not have. + */ + function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating = false }) { + const [menuOpen, setMenuOpen] = (0, react.useState)(false); + const menuItems = [ + { + id: "newSession", + label: t("session.new"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutlineRegular, {}) + }, + ...onOpenInFolder !== void 0 ? [{ + id: "openInFolder", + label: t("workspace.openInFolder"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular, { size: 16 }) + }] : [], + ...node.isRoot ? [] : [{ + id: "setRoot", + label: t("folder.setRoot"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPinOutlineRegular, {}) + }], + ...node.isBase ? [] : [{ + type: "separator", + id: "folder-menu-separator" + }, { + id: "remove", + label: t("folder.remove"), + icon: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutlineRegular, {}), + danger: true + }] + ]; + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: `wgFolderRow${node.isRoot ? " wgFolderRooted" : ""}${node.isBase ? " wgFolderBase" : ""}`, + role: "treeitem", + "aria-expanded": node.expanded, + "aria-label": node.label, + "data-wg-row-folder": "", + "data-wg-folder": node.path, + ...node.isRoot ? { "data-wg-folder-root": "" } : {}, + "data-wg-branch-row": "", + onClick: onToggle, + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: `wgChevron${node.expanded ? " wgChevronOpen" : ""}`, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTriangleRightFillMedium, {}) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgCategoryIcon", + "data-wg-row-icon": "folder", + children: node.expanded ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenMedium, {}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderCloseMedium, {}) + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderLabel", + title: node.path, + children: node.label + }), + node.isRoot && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderRoot", + title: t("folder.rootBadge"), + "aria-label": t("folder.rootBadge"), + children: "★" + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderCount", + children: node.sessions.length + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "wgRowActions", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, { + open: menuOpen, + onClose: () => { + setMenuOpen(false); + }, + items: menuItems, + onSelect: (id) => { + setMenuOpen(false); + if (id === "newSession") onNewSession(); + if (id === "openInFolder") onOpenInFolder?.(); + if (id === "setRoot") onSetRoot(); + if (id === "remove") onRemove(); + }, + portal: true, + closeOnPointerLeave: true, + anchor: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + draggable: false, + "aria-label": `${t("folder.title")} ${node.label}`, + onClick: (e) => { + e.stopPropagation(); + setMenuOpen((v) => !v); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEllipsisOutlineRegular, {}) + }) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + draggable: false, + disabled: creating, + "aria-label": `${t("session.new")} ${node.label}`, + onClick: (e) => { + e.stopPropagation(); + onNewSession(); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutlineRegular, {}) + })] + }) + ] + }); + } /** Keyframe names the disclosure animation relies on (styles.css). */ const ROW_GROUP_OPEN_ANIMATION = "wg-rows-in"; const ROW_GROUP_CLOSE_ANIMATION = "wg-rows-out"; @@ -1610,7 +1969,7 @@ window.__ModuleLoader__.load({ }); } /** One session leaf row. */ - function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }) { + function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested = false }) { const selected = node.id === currentId; const [menuOpen, setMenuOpen] = (0, react.useState)(false); const showStatus = !selected; @@ -1632,7 +1991,7 @@ window.__ModuleLoader__.load({ } ]; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { - className: `wgSessionRow${selected ? " wgSelected" : ""}${node.matched === true ? " wgMatched" : ""}`, + className: `wgSessionRow${nested ? " wgSessionNested" : ""}${selected ? " wgSelected" : ""}${node.matched === true ? " wgMatched" : ""}`, role: "treeitem", "aria-selected": selected, "data-wg-branch-row": "", @@ -1690,6 +2049,97 @@ window.__ModuleLoader__.load({ }); } //#endregion + //#region src/client/folders-persist.ts + /** + * Client side of the per-workspace folder list, talking to + * `GET|PUT /workspace-groups/folders` on the host. + * + * The document is the host's JSON sidecar verbatim (`version` + `workspaces`), + * so the client and the host agree on one shape: `folders` holds EXTRA folders + * only — the workspace's canonical directory is implicit folder #0 — and + * `root` names one of those extras (absent means "the workspace itself"). + * + * Reads are best-effort, like the manual overlay and the tab strip: a failed + * read means "no extra folders". A failed write, however, rejects so the caller + * can say so — a folder row that silently forgot its edit would be worse than + * the toast. + */ + /** Host route holding the folder overlay. */ + const FOLDERS_ROUTE = "/workspace-groups/folders"; + /** + * Read one workspace entry off the wire, dropping the entry when it is + * unusable. + * @param value - one value of the stored `workspaces` mapping. + * @returns the entry, or null for a malformed one. + */ + function parseWireEntry(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const row = value; + if (!Array.isArray(row.folders)) return null; + const folders = []; + for (const candidate of row.folders) { + if (typeof candidate !== "string" || candidate.trim() === "") continue; + folders.push(candidate); + } + const root = typeof row.root === "string" && row.root.trim() !== "" ? row.root : void 0; + return { + folders, + ...root === void 0 ? {} : { root } + }; + } + /** + * Fetch the stored folder overlay. + * @param fetchImpl - fetch implementation (injectable for tests). + * @returns the document; the empty document on any failure. + */ + async function loadFolders(fetchImpl = fetch) { + try { + const response = await fetchImpl(FOLDERS_ROUTE, { + method: "GET", + cache: "no-store" + }); + if (!response.ok) return EMPTY_FOLDERS_DOCUMENT; + const body = await response.json(); + if (typeof body !== "object" || body === null) return EMPTY_FOLDERS_DOCUMENT; + const source = body; + if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT; + if (typeof source.workspaces !== "object" || source.workspaces === null || Array.isArray(source.workspaces)) return { + version: 1, + workspaces: {} + }; + const workspaces = {}; + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + const entry = parseWireEntry(value); + if (entry !== null) workspaces[workspaceId] = entry; + } + return { + version: 1, + workspaces + }; + } catch { + return EMPTY_FOLDERS_DOCUMENT; + } + } + /** + * Store the whole folder overlay. + * + * Unlike the tab strip this does NOT swallow failures: folder edits are explicit + * row/dialog actions, so the caller turns a rejection into a toast instead of + * leaving the user with a row that silently forgot its folder. + * @param document - the client's current document. + * @param fetchImpl - fetch implementation (injectable for tests). + */ + async function saveFolders(document, fetchImpl = fetch) { + const response = await fetchImpl(FOLDERS_ROUTE, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(document), + cache: "no-store", + keepalive: true + }); + if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`); + } + //#endregion //#region src/client/open-folder.ts /** * Transport for the official open-in-app host routes served by @@ -3083,13 +3533,13 @@ window.__ModuleLoader__.load({ } //#endregion //#region \0dsh-workspace-groups-inline-css:C:\Users\qyh15\Documents\dsh-workspaces-goups-new\dsh-workspace-groups\src\client\styles.css.mjs - var styles_css_default = ".wgRoot{box-sizing:border-box;flex-direction:column;flex:1;width:100%;min-height:0;display:flex;overflow:hidden}.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}[data-wg-color=red]{--wg-group-tint:#d9534f}[data-wg-color=orange]{--wg-group-tint:#e08a3c}[data-wg-color=amber]{--wg-group-tint:#d9a521}[data-wg-color=green]{--wg-group-tint:#3fa45b}[data-wg-color=teal]{--wg-group-tint:#2f9e93}[data-wg-color=blue]{--wg-group-tint:#4a90d9}[data-wg-color=indigo]{--wg-group-tint:#5b6fd6}[data-wg-color=purple]{--wg-group-tint:#9a63c9}[data-wg-color=pink]{--wg-group-tint:#d4659c}[data-wg-color=gray]{--wg-group-tint:#8a8a8a}.wgCategoryRow[data-wg-color]{box-shadow:inset 2px 0 0 var(--wg-group-tint)}.wgCategoryRow[data-wg-color] .wgCategoryIcon{color:var(--wg-group-tint)}.wgCategoryRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.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}.wgCategoryGlyph{font-size:12px;line-height:1}.wgCategoryPin{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;display:inline-flex}.wgProjectRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px 0 20px;display:flex;position:relative}.wgProjectFlat{padding-left:4px}.wgTopLevelArea{margin-top:2px;padding-bottom:10px}.wgTopLevelEmpty{border-radius:4px;height:14px;position:relative}.wgTopLevelEmptyLine{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;border-radius:1px;position:absolute;top:50%;left:2px;right:2px}.wgTopLevelEmptyActive{background:var(--dsw-bg-selected,#4a90d92e)}.wgProjectRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgProjectActive .wgProjectLabel{font-weight:700}.wgProjectLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:1;font-size:12px;font-weight:500;overflow:hidden}.wgRowActions{opacity:0;flex:none;align-items:center;gap:2px;display:inline-flex}.wgProjectRow:hover .wgRowActions,.wgProjectRow:focus-within .wgRowActions{opacity:1}.wgTreeWrap{position:relative}.wgBranch{z-index:2;pointer-events:none;transition:opacity .12s;position:absolute;top:0;left:0;overflow:visible}.wgTreeWrap:has([data-wg-animating]) .wgBranch{opacity:0}.wgTreeWrap>.wgList{z-index:1;position:relative}.wgFlowerArt{transform-box:fill-box;transform-origin:50%;animation:4s linear infinite paused wg-flower-spin}.wgFlowerSpinning .wgFlowerArt{animation-play-state:running}@keyframes wg-flower-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (prefers-reduced-motion:reduce){.wgFlowerArt,.wgRowsOpening,.wgRowsClosing{animation:none}.wgBranch{transition:none}}.wgRows{grid-template-rows:1fr;display:grid}.wgRowsInner{min-height:0}.wgRowsOpening{animation:.18s cubic-bezier(.2,.8,.2,1) wg-rows-in}.wgRowsClosing{pointer-events:none;animation:.16s cubic-bezier(.4,0,1,1) forwards wg-rows-out}.wgRowsOpening .wgRowsInner,.wgRowsClosing .wgRowsInner{overflow:hidden}@keyframes wg-rows-in{0%{opacity:.35;grid-template-rows:0fr}to{opacity:1;grid-template-rows:1fr}}@keyframes wg-rows-out{0%{opacity:1;grid-template-rows:1fr}to{opacity:0;grid-template-rows:0fr}}.wgTreeChildren{position:relative}.wgSessionRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:6px;height:28px;padding:0 4px 0 54px;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-alias-label-secondary,var(--dsw-fg-2,inherit));flex:1;font-size:12px;overflow:hidden}.wgSelected .wgSessionTitle{color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-weight:500}.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:12px;padding:8px 0 0;display:flex;overflow:hidden}.wgRail .wgSectionHeader{flex-direction:column;align-self:center;align-items:center;gap:12px;width:36px;height:auto;padding:0}.wgRail .wgIconButton{border-radius:50%;width:36px;height:36px}.wgRail .wgTreeBody{display:none}.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)}.wgAppearanceSection{flex-direction:column;gap:6px;display:flex}.wgAppearanceLabel{color:var(--dsw-fg-3,#7f7f7fcc);font-size:11px;font-weight:600}.wgSwatchRow{flex-wrap:wrap;gap:6px;display:flex}.wgSwatch{cursor:pointer;border:1px solid var(--dsw-alias-border-l2,#7f7f7f47);border-radius:5px;width:20px;height:20px;padding:0}.wgSwatch[data-wg-color]{background:var(--wg-group-tint)}.wgSwatch:disabled{cursor:default;opacity:.5}.wgSwatchActive{outline:2px solid var(--dsw-accent,#4a90d9);outline-offset:1px}.wgSwatchDefault{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgIconGrid{grid-template-columns:repeat(10,1fr);gap:4px;display:grid}.wgIconCell{cursor:pointer;color:var(--dsw-fg-2,inherit);background:0 0;border:0;border-radius:5px;justify-content:center;align-items:center;width:24px;height:24px;padding:0;display:inline-flex}.wgIconCell:hover:not(:disabled){background:var(--dsw-bg-hover,#7f7f7f1f)}.wgIconCell[aria-pressed=true]{background:var(--dsw-bg-selected,#4a90d92e)}.wgIconCell:disabled{cursor:default;opacity:.5}.wgQuickOverlay{z-index:1100;background:var(--dsw-alias-bg-mask-1,#00000052);backdrop-filter:var(--dsw-mask-blur,blur(2px));justify-content:center;align-items:flex-start;padding:10vh 24px 24px;display:flex;position:fixed;inset:0}.wgQuickCard{border:1px solid var(--dsw-border,#7f7f7f33);background:var(--dsw-alias-bg-layer-2,var(--dsw-bg-1,#fff));width:min(640px,100%);max-height:min(560px,90vh - 48px);box-shadow:var(--dsw-elevation-prominent,0 16px 48px #00000040);box-sizing:border-box;border-radius:12px;flex-direction:column;gap:10px;padding:14px;display:flex;overflow:hidden}.wgQuickHeader{flex:none;justify-content:space-between;align-items:center;gap:12px;display:flex}.wgQuickTitle{color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-size:13px;font-weight:600}.wgQuickTabs{gap:2px;display:flex}.wgQuickTab{color:var(--dsw-alias-label-secondary,var(--dsw-fg-2,inherit));cursor:pointer;background:0 0;border:none;border-radius:6px;align-items:center;gap:6px;padding:4px 12px;font-family:inherit;font-size:12px;display:inline-flex}.wgQuickTab:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgQuickTabActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-selected,#4a90d92e));color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-weight:600}.wgQuickTabCount{background:var(--dsw-accent,#4a90d9);color:#fff;text-align:center;border-radius:8px;min-width:16px;height:16px;padding:0 4px;font-size:10px;font-weight:600;line-height:16px}.wgQuickSearchWrap{flex:none}.wgQuickSearch{border:1px solid var(--dsw-border,#7f7f7f4d);background:var(--dsw-bg-1,transparent);width:100%;height:34px;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));box-sizing:border-box;border-radius:8px;outline:none;padding:0 10px;font-family:inherit;font-size:13px}.wgQuickSearch:focus{border-color:var(--dsw-accent,#4a90d9)}.wgQuickList{flex-direction:column;flex:auto;gap:2px;min-height:64px;padding-right:2px;display:flex;overflow-y:auto}.wgQuickRow{cursor:pointer;text-align:left;box-sizing:border-box;background:0 0;border:none;border-radius:8px;flex-direction:column;flex:none;gap:2px;width:100%;padding:7px 10px;font-family:inherit;display:flex}.wgQuickRow:hover,.wgQuickRowActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgQuickRowSelected,.wgQuickRowCurrent{background:var(--dsw-bg-selected,#4a90d92e)}.wgQuickRowMain{align-items:center;gap:8px;width:100%;min-width:0;display:flex}.wgQuickRowTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:1;font-size:13px;font-weight:500;overflow:hidden}.wgQuickRunBadge{color:var(--dsw-accent,#4a90d9);flex:none;font-size:11px}.wgQuickTime{color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:none;font-size:11px}.wgQuickRowSub{min-width:0;display:flex}.wgQuickRowPath{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:1;font-size:11px;overflow:hidden}.wgQuickEmpty{text-align:center;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));padding:24px 8px;font-size:12px}.wgQuickFooter{flex:none;align-items:center;gap:8px;padding-top:2px;display:flex}.wgQuickSelected{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:1;font-size:12px;overflow:hidden}.wgQuickHint{text-align:center;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:none;font-size:11px}.wgTabs{box-sizing:border-box;border-bottom:1px solid var(--dsw-alias-border-l2,#7f7f7f33);background:0 0;flex:none;align-items:stretch;gap:4px;min-width:0;height:56px;padding:8px 10px;display:flex}.wgTabsScroll{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;overscroll-behavior-x:contain;box-sizing:border-box;flex:auto;align-items:stretch;gap:6px;min-width:0;padding:1px 0;display:flex;overflow:auto hidden}.wgTabsScroll::-webkit-scrollbar{width:0;height:0;display:none}.wgTab{min-width:0;max-width:240px;box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2,#7f7f7f2e);color:var(--dsw-alias-label-secondary,var(--dsw-fg-2,inherit));border-radius:8px;flex:none;align-items:center;padding:0 6px 0 10px;transition:background .12s,box-shadow .12s;display:inline-flex}.wgTabText{flex-direction:column;flex:auto;justify-content:center;align-items:flex-start;gap:3px;min-width:0;height:100%;display:flex}.wgTabProject{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:100%;font-family:var(--dsw-font-mono,ui-monospace, SFMono-Regular, Menlo, monospace);letter-spacing:.02em;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,inherit));opacity:.85;flex:none;font-size:10px;line-height:13px;overflow:hidden}.wgTab:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgTabActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f));box-shadow:inset 0 0 0 1px var(--dsw-alias-label-secondary,#7f7f7f73);color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit))}.wgTabActive .wgTabProject{opacity:1}.wgTabMain{box-sizing:border-box;min-width:0;height:100%;color:inherit;cursor:pointer;background:0 0;border:none;flex:auto;align-items:center;gap:8px;padding:6px 0;font-family:inherit;font-size:12px;display:inline-flex}.wgTabStatus{flex:none;justify-content:center;align-items:center;width:12px;height:12px;display:inline-flex}.wgTabStatus[data-tab-state=idle]{opacity:.45}.wgTabLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:100%;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:none;font-size:12px;line-height:16px;overflow:hidden}.wgTabText>.wgTabLabel:only-child{align-self:center}.wgTabClose{width:20px;height:20px;color:inherit;cursor:pointer;opacity:0;background:0 0;border:none;border-radius:5px;flex:none;justify-content:center;align-items:center;margin-left:2px;padding:0;transition:opacity .12s,background .12s;display:inline-flex}.wgTab:hover .wgTabClose,.wgTab:focus-within .wgTabClose,.wgTabActive .wgTabClose{opacity:1}.wgTabClose:hover{background:var(--dsw-alias-interactive-bg-hover-solid,#7f7f7f33)}.wgTab{position:relative}.wgTabPinned{box-shadow:inset 0 0 0 1px var(--dsw-alias-label-secondary,#7f7f7f73)}.wgTabPin{opacity:.55;width:12px;height:12px;color:inherit;flex:none;justify-content:center;align-items:center;margin-left:4px;display:inline-flex}.wgTabDragging{opacity:.42}.wgTabDropBefore:before,.wgTabDropAfter:before{content:\"\";background:var(--dsw-alias-label-primary,var(--dsw-fg-1,#4a90d9));border-radius:2px;width:2px;position:absolute;top:2px;bottom:2px}.wgTabDropBefore:before{left:-4px}.wgTabDropAfter:before{right:-4px}.wgTabRename{box-sizing:border-box;min-width:88px;height:100%;color:inherit;background:var(--dsw-alias-bg-elevated,var(--dsw-bg-1,transparent));border:1px solid var(--dsw-alias-label-secondary,#7f7f7f73);border-radius:6px;outline:none;flex:auto;margin:2px 0;padding:0 6px;font-family:inherit;font-size:12px}.wgTabMenu{z-index:2147483000;box-sizing:border-box;background:var(--dsw-alias-bg-popup,var(--dsw-bg-2,#1e1e1e));border:1px solid var(--dsw-alias-border-l2,#7f7f7f33);border-radius:8px;flex-direction:column;min-width:196px;padding:4px;display:flex;position:fixed;box-shadow:0 8px 24px #0003,0 1px 2px #0000001f}.wgTabMenuItem{width:100%;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));text-align:left;cursor:pointer;background:0 0;border:none;border-radius:5px;padding:6px 10px;font-family:inherit;font-size:12px;line-height:16px}.wgTabMenuItem:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgTabMenuItem:disabled{cursor:default;opacity:.4}.wgTabMenuDanger{color:var(--dsw-alias-label-error,var(--dsw-fg-error,#d9534f))}.wgTabMenuSeparator{background:var(--dsw-alias-border-l2,#7f7f7f33);height:1px;margin:4px 6px}"; + var styles_css_default = ".wgRoot{box-sizing:border-box;flex-direction:column;flex:1;width:100%;min-height:0;display:flex;overflow:hidden}.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}[data-wg-color=red]{--wg-group-tint:#d9534f}[data-wg-color=orange]{--wg-group-tint:#e08a3c}[data-wg-color=amber]{--wg-group-tint:#d9a521}[data-wg-color=green]{--wg-group-tint:#3fa45b}[data-wg-color=teal]{--wg-group-tint:#2f9e93}[data-wg-color=blue]{--wg-group-tint:#4a90d9}[data-wg-color=indigo]{--wg-group-tint:#5b6fd6}[data-wg-color=purple]{--wg-group-tint:#9a63c9}[data-wg-color=pink]{--wg-group-tint:#d4659c}[data-wg-color=gray]{--wg-group-tint:#8a8a8a}.wgCategoryRow[data-wg-color]{box-shadow:inset 2px 0 0 var(--wg-group-tint)}.wgCategoryRow[data-wg-color] .wgCategoryIcon{color:var(--wg-group-tint)}.wgCategoryRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.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}.wgCategoryGlyph{font-size:12px;line-height:1}.wgCategoryPin{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;display:inline-flex}.wgProjectRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px 0 20px;display:flex;position:relative}.wgProjectFlat{padding-left:4px}.wgTopLevelArea{margin-top:2px;padding-bottom:10px}.wgTopLevelEmpty{border-radius:4px;height:14px;position:relative}.wgTopLevelEmptyLine{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;border-radius:1px;position:absolute;top:50%;left:2px;right:2px}.wgTopLevelEmptyActive{background:var(--dsw-bg-selected,#4a90d92e)}.wgProjectRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgProjectActive .wgProjectLabel{font-weight:700}.wgProjectLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:1;font-size:12px;font-weight:500;overflow:hidden}.wgRowActions{opacity:0;flex:none;align-items:center;gap:2px;display:inline-flex}.wgProjectRow:hover .wgRowActions,.wgProjectRow:focus-within .wgRowActions{opacity:1}.wgFolderRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:4px;height:28px;padding:0 4px 0 38px;display:flex;position:relative}.wgFolderRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgFolderRow:hover .wgRowActions,.wgFolderRow:focus-within .wgRowActions{opacity:1}.wgFolderLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:1;font-size:12px;font-weight:500;overflow:hidden}.wgFolderBase .wgFolderLabel{font-weight:600}.wgFolderRoot{color:var(--dsw-accent,#4a90d9);flex:none;font-size:11px;line-height:1}.wgFolderCount{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgSessionNested{padding-left:70px}.wgTreeWrap{position:relative}.wgBranch{z-index:2;pointer-events:none;transition:opacity .12s;position:absolute;top:0;left:0;overflow:visible}.wgTreeWrap:has([data-wg-animating]) .wgBranch{opacity:0}.wgTreeWrap>.wgList{z-index:1;position:relative}.wgFlowerArt{transform-box:fill-box;transform-origin:50%;animation:4s linear infinite paused wg-flower-spin}.wgFlowerSpinning .wgFlowerArt{animation-play-state:running}@keyframes wg-flower-spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (prefers-reduced-motion:reduce){.wgFlowerArt,.wgRowsOpening,.wgRowsClosing{animation:none}.wgBranch{transition:none}}.wgRows{grid-template-rows:1fr;display:grid}.wgRowsInner{min-height:0}.wgRowsOpening{animation:.18s cubic-bezier(.2,.8,.2,1) wg-rows-in}.wgRowsClosing{pointer-events:none;animation:.16s cubic-bezier(.4,0,1,1) forwards wg-rows-out}.wgRowsOpening .wgRowsInner,.wgRowsClosing .wgRowsInner{overflow:hidden}@keyframes wg-rows-in{0%{opacity:.35;grid-template-rows:0fr}to{opacity:1;grid-template-rows:1fr}}@keyframes wg-rows-out{0%{opacity:1;grid-template-rows:1fr}to{opacity:0;grid-template-rows:0fr}}.wgTreeChildren{position:relative}.wgSessionRow{cursor:pointer;user-select:none;border-radius:6px;align-items:center;gap:6px;height:28px;padding:0 4px 0 54px;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-alias-label-secondary,var(--dsw-fg-2,inherit));flex:1;font-size:12px;overflow:hidden}.wgSelected .wgSessionTitle{color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-weight:500}.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:12px;padding:8px 0 0;display:flex;overflow:hidden}.wgRail .wgSectionHeader{flex-direction:column;align-self:center;align-items:center;gap:12px;width:36px;height:auto;padding:0}.wgRail .wgIconButton{border-radius:50%;width:36px;height:36px}.wgRail .wgTreeBody{display:none}.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)}.wgFolderList{flex-direction:column;gap:4px;display:flex}.wgFolderListRow{border-radius:6px;align-items:center;gap:6px;padding:4px 4px 4px 2px;display:flex}.wgFolderListRow:hover{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgFolderRadio{accent-color:var(--dsw-accent,#4a90d9);flex:none;margin:0}.wgFolderListLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-fg-1,inherit);flex:1;font-size:12px;overflow:hidden}.wgFolderListTag{color:var(--dsw-fg-3,#7f7f7fcc);flex:none;font-size:11px}.wgFolderListActions{flex:none;align-items:center;gap:2px;display:inline-flex}.wgFolderListFooter{margin-top:8px}.wgAppearanceSection{flex-direction:column;gap:6px;display:flex}.wgAppearanceLabel{color:var(--dsw-fg-3,#7f7f7fcc);font-size:11px;font-weight:600}.wgSwatchRow{flex-wrap:wrap;gap:6px;display:flex}.wgSwatch{cursor:pointer;border:1px solid var(--dsw-alias-border-l2,#7f7f7f47);border-radius:5px;width:20px;height:20px;padding:0}.wgSwatch[data-wg-color]{background:var(--wg-group-tint)}.wgSwatch:disabled{cursor:default;opacity:.5}.wgSwatchActive{outline:2px solid var(--dsw-accent,#4a90d9);outline-offset:1px}.wgSwatchDefault{background:var(--dsw-bg-hover,#7f7f7f1f)}.wgIconGrid{grid-template-columns:repeat(10,1fr);gap:4px;display:grid}.wgIconCell{cursor:pointer;color:var(--dsw-fg-2,inherit);background:0 0;border:0;border-radius:5px;justify-content:center;align-items:center;width:24px;height:24px;padding:0;display:inline-flex}.wgIconCell:hover:not(:disabled){background:var(--dsw-bg-hover,#7f7f7f1f)}.wgIconCell[aria-pressed=true]{background:var(--dsw-bg-selected,#4a90d92e)}.wgIconCell:disabled{cursor:default;opacity:.5}.wgQuickOverlay{z-index:1100;background:var(--dsw-alias-bg-mask-1,#00000052);backdrop-filter:var(--dsw-mask-blur,blur(2px));justify-content:center;align-items:flex-start;padding:10vh 24px 24px;display:flex;position:fixed;inset:0}.wgQuickCard{border:1px solid var(--dsw-border,#7f7f7f33);background:var(--dsw-alias-bg-layer-2,var(--dsw-bg-1,#fff));width:min(640px,100%);max-height:min(560px,90vh - 48px);box-shadow:var(--dsw-elevation-prominent,0 16px 48px #00000040);box-sizing:border-box;border-radius:12px;flex-direction:column;gap:10px;padding:14px;display:flex;overflow:hidden}.wgQuickHeader{flex:none;justify-content:space-between;align-items:center;gap:12px;display:flex}.wgQuickTitle{color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-size:13px;font-weight:600}.wgQuickTabs{gap:2px;display:flex}.wgQuickTab{color:var(--dsw-alias-label-secondary,var(--dsw-fg-2,inherit));cursor:pointer;background:0 0;border:none;border-radius:6px;align-items:center;gap:6px;padding:4px 12px;font-family:inherit;font-size:12px;display:inline-flex}.wgQuickTab:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgQuickTabActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-selected,#4a90d92e));color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));font-weight:600}.wgQuickTabCount{background:var(--dsw-accent,#4a90d9);color:#fff;text-align:center;border-radius:8px;min-width:16px;height:16px;padding:0 4px;font-size:10px;font-weight:600;line-height:16px}.wgQuickSearchWrap{flex:none}.wgQuickSearch{border:1px solid var(--dsw-border,#7f7f7f4d);background:var(--dsw-bg-1,transparent);width:100%;height:34px;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));box-sizing:border-box;border-radius:8px;outline:none;padding:0 10px;font-family:inherit;font-size:13px}.wgQuickSearch:focus{border-color:var(--dsw-accent,#4a90d9)}.wgQuickList{flex-direction:column;flex:auto;gap:2px;min-height:64px;padding-right:2px;display:flex;overflow-y:auto}.wgQuickRow{cursor:pointer;text-align:left;box-sizing:border-box;background:0 0;border:none;border-radius:8px;flex-direction:column;flex:none;gap:2px;width:100%;padding:7px 10px;font-family:inherit;display:flex}.wgQuickRow:hover,.wgQuickRowActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgQuickRowSelected,.wgQuickRowCurrent{background:var(--dsw-bg-selected,#4a90d92e)}.wgQuickRowMain{align-items:center;gap:8px;width:100%;min-width:0;display:flex}.wgQuickRowTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:1;font-size:13px;font-weight:500;overflow:hidden}.wgQuickRunBadge{color:var(--dsw-accent,#4a90d9);flex:none;font-size:11px}.wgQuickTime{color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:none;font-size:11px}.wgQuickRowSub{min-width:0;display:flex}.wgQuickRowPath{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:1;font-size:11px;overflow:hidden}.wgQuickEmpty{text-align:center;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));padding:24px 8px;font-size:12px}.wgQuickFooter{flex:none;align-items:center;gap:8px;padding-top:2px;display:flex}.wgQuickSelected{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:1;font-size:12px;overflow:hidden}.wgQuickHint{text-align:center;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,#7f7f7fcc));flex:none;font-size:11px}.wgTabs{box-sizing:border-box;border-bottom:1px solid var(--dsw-alias-border-l2,#7f7f7f33);background:0 0;flex:none;align-items:stretch;gap:4px;min-width:0;height:56px;padding:8px 10px;display:flex}.wgTabsScroll{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;overscroll-behavior-x:contain;box-sizing:border-box;flex:auto;align-items:stretch;gap:6px;min-width:0;padding:1px 0;display:flex;overflow:auto hidden}.wgTabsScroll::-webkit-scrollbar{width:0;height:0;display:none}.wgTab{min-width:0;max-width:240px;box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2,#7f7f7f2e);color:var(--dsw-alias-label-secondary,var(--dsw-fg-2,inherit));border-radius:8px;flex:none;align-items:center;padding:0 6px 0 10px;transition:background .12s,box-shadow .12s;display:inline-flex}.wgTabText{flex-direction:column;flex:auto;justify-content:center;align-items:flex-start;gap:3px;min-width:0;height:100%;display:flex}.wgTabProject{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:100%;font-family:var(--dsw-font-mono,ui-monospace, SFMono-Regular, Menlo, monospace);letter-spacing:.02em;color:var(--dsw-alias-label-secondary,var(--dsw-fg-3,inherit));opacity:.85;flex:none;font-size:10px;line-height:13px;overflow:hidden}.wgTab:hover{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgTabActive{background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f));box-shadow:inset 0 0 0 1px var(--dsw-alias-label-secondary,#7f7f7f73);color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit))}.wgTabActive .wgTabProject{opacity:1}.wgTabMain{box-sizing:border-box;min-width:0;height:100%;color:inherit;cursor:pointer;background:0 0;border:none;flex:auto;align-items:center;gap:8px;padding:6px 0;font-family:inherit;font-size:12px;display:inline-flex}.wgTabStatus{flex:none;justify-content:center;align-items:center;width:12px;height:12px;display:inline-flex}.wgTabStatus[data-tab-state=idle]{opacity:.45}.wgTabLabel{text-overflow:ellipsis;white-space:nowrap;min-width:0;max-width:100%;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));flex:none;font-size:12px;line-height:16px;overflow:hidden}.wgTabText>.wgTabLabel:only-child{align-self:center}.wgTabClose{width:20px;height:20px;color:inherit;cursor:pointer;opacity:0;background:0 0;border:none;border-radius:5px;flex:none;justify-content:center;align-items:center;margin-left:2px;padding:0;transition:opacity .12s,background .12s;display:inline-flex}.wgTab:hover .wgTabClose,.wgTab:focus-within .wgTabClose,.wgTabActive .wgTabClose{opacity:1}.wgTabClose:hover{background:var(--dsw-alias-interactive-bg-hover-solid,#7f7f7f33)}.wgTab{position:relative}.wgTabPinned{box-shadow:inset 0 0 0 1px var(--dsw-alias-label-secondary,#7f7f7f73)}.wgTabPin{opacity:.55;width:12px;height:12px;color:inherit;flex:none;justify-content:center;align-items:center;margin-left:4px;display:inline-flex}.wgTabDragging{opacity:.42}.wgTabDropBefore:before,.wgTabDropAfter:before{content:\"\";background:var(--dsw-alias-label-primary,var(--dsw-fg-1,#4a90d9));border-radius:2px;width:2px;position:absolute;top:2px;bottom:2px}.wgTabDropBefore:before{left:-4px}.wgTabDropAfter:before{right:-4px}.wgTabRename{box-sizing:border-box;min-width:88px;height:100%;color:inherit;background:var(--dsw-alias-bg-elevated,var(--dsw-bg-1,transparent));border:1px solid var(--dsw-alias-label-secondary,#7f7f7f73);border-radius:6px;outline:none;flex:auto;margin:2px 0;padding:0 6px;font-family:inherit;font-size:12px}.wgTabMenu{z-index:2147483000;box-sizing:border-box;background:var(--dsw-alias-bg-popup,var(--dsw-bg-2,#1e1e1e));border:1px solid var(--dsw-alias-border-l2,#7f7f7f33);border-radius:8px;flex-direction:column;min-width:196px;padding:4px;display:flex;position:fixed;box-shadow:0 8px 24px #0003,0 1px 2px #0000001f}.wgTabMenuItem{width:100%;color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));text-align:left;cursor:pointer;background:0 0;border:none;border-radius:5px;padding:6px 10px;font-family:inherit;font-size:12px;line-height:16px}.wgTabMenuItem:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,var(--dsw-bg-hover,#7f7f7f1f))}.wgTabMenuItem:disabled{cursor:default;opacity:.4}.wgTabMenuDanger{color:var(--dsw-alias-label-error,var(--dsw-fg-error,#d9534f))}.wgTabMenuSeparator{background:var(--dsw-alias-border-l2,#7f7f7f33);height:1px;margin:4px 6px}"; //#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 + - * new-group + add workspace), the three-level tree (category → workspace → + * 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 @@ -3140,7 +3590,7 @@ window.__ModuleLoader__.load({ function categoryRowCount(category) { return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0); } - /** Palette id → i18n key for the colour picker (keeps literal key types intact). */ + /** Palette id — i18n key for the colour picker (keeps literal key types intact). */ const COLOR_LABEL_KEYS = { red: "color.red", orange: "color.orange", @@ -3195,7 +3645,7 @@ window.__ModuleLoader__.load({ * @param props - composed slot props (shell owner share + store + injected actions). * @returns the region element tree. */ - function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t }) { + function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t }) { (0, react.useEffect)(() => { const style = document.createElement("style"); style.setAttribute("data-plugin", "dsh-workspace-groups"); @@ -3234,6 +3684,21 @@ window.__ModuleLoader__.load({ }, []); const [manualError, setManualError] = (0, react.useState)(null); const [manualSaving, setManualSaving] = (0, react.useState)(false); + const [foldersDoc, setFoldersDoc] = (0, react.useState)(EMPTY_FOLDERS_DOCUMENT); + const [collapsedFolderKeys, setCollapsedFolderKeys] = (0, react.useState)([]); + const [foldersTarget, setFoldersTarget] = (0, react.useState)(null); + const [foldersBusy, setFoldersBusy] = (0, react.useState)(false); + const [creatingSessionIn, setCreatingSessionIn] = (0, react.useState)(null); + (0, react.useEffect)(() => { + let cancelled = false; + loadFolders().then((document) => { + if (cancelled) return; + setFoldersDoc(document); + }); + return () => { + cancelled = true; + }; + }, []); const workspaces = useWorkspaces((state) => state.items); const workspacePhase = useWorkspaces((state) => state.phase); const archivedSessionIds = useWorkspaces((state) => state.archivedSessionIds); @@ -3353,8 +3818,9 @@ window.__ModuleLoader__.load({ const [dragging, setDragging] = (0, react.useState)(null); const groups = (0, react.useMemo)(() => deriveGroups(list, workspaces, archivedSessionIds, config, { expandedCategories, - expandedWorkspaces - }, manual, statuses), [ + expandedWorkspaces, + collapsedFolders: collapsedFolderKeys + }, manual, statuses, foldersDoc), [ list, workspaces, archivedSessionIds, @@ -3362,12 +3828,15 @@ window.__ModuleLoader__.load({ manual, statuses, expandedCategories, - expandedWorkspaces + expandedWorkspaces, + collapsedFolderKeys, + foldersDoc ]); const topLevel = (0, react.useMemo)(() => deriveTopLevel(list, workspaces, archivedSessionIds, config, { expandedCategories, - expandedWorkspaces - }, manual, statuses), [ + expandedWorkspaces, + collapsedFolders: collapsedFolderKeys + }, manual, statuses, foldersDoc), [ list, workspaces, archivedSessionIds, @@ -3375,7 +3844,9 @@ window.__ModuleLoader__.load({ manual, statuses, expandedCategories, - expandedWorkspaces + expandedWorkspaces, + collapsedFolderKeys, + foldersDoc ]); const categoryByWorkspace = (0, react.useMemo)(() => { const map = /* @__PURE__ */ new Map(); @@ -3498,6 +3969,98 @@ window.__ModuleLoader__.load({ }); }); }; + const notifyFolder = (text) => { + setFolderError({ + id: Date.now(), + text + }); + }; + const persistFolders = (next) => { + setFoldersDoc(next); + saveFolders(next).catch((reason) => { + const detail = reason instanceof Error ? reason.message : String(reason); + notifyFolder(`${t("folder.saveError")}: ${detail}`); + }); + }; + /** Write one workspace's entry; zero extra folders removes the key entirely. */ + const writeFolderEntry = (workspaceId, entry) => { + const next = { ...foldersDoc.workspaces }; + const key = workspaceId; + if (entry.folders.length === 0) delete next[key]; + else next[key] = entry; + persistFolders({ + version: 1, + workspaces: next + }); + }; + const toggleFolder = (workspaceId, path) => { + const key = folderKey(workspaceId, path); + setCollapsedFolderKeys((keys) => keys.includes(key) ? keys.filter((k) => k !== key) : [...keys, key]); + }; + const addFolderTo = async (workspaceId) => { + if (foldersBusy) return; + const workspace = workspaces.find((w) => w.workspaceId === workspaceId); + if (workspace === void 0) return; + setFoldersBusy(true); + try { + const path = await pickDirectory(); + if (path === null) return; + const entry = entryFor(foldersDoc, workspaceId); + if (effectiveFolders(workspace.path, entry).some((folder) => samePath(folder, path))) { + notifyFolder(t("folder.duplicate")); + return; + } + writeFolderEntry(workspaceId, addFolder(entry, path)); + } catch (reason) { + const detail = reason instanceof Error ? reason.message : String(reason); + notifyFolder(`${t("folder.addError")}: ${detail}`); + } finally { + setFoldersBusy(false); + } + }; + const setFolderRoot = (workspaceId, path) => { + writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), path)); + }; + const removeFolderFrom = (workspaceId, path) => { + writeFolderEntry(workspaceId, removeFolder(entryFor(foldersDoc, workspaceId), path)); + }; + /** + * "New session here": an extra folder's own directory becomes the Session cwd. + * The base folder keeps the platform's own gesture instead, because that one + * reuses the blank session it already opened; creating a fresh Session on + * every click would pile up empty sessions. One creation in flight at a time; + * a rejection surfaces the failure and creates nothing else. + */ + const startSessionInFolder = (workspaceId, path, isBase) => { + if (isBase) { + startSession(workspaceId); + return; + } + if (creatingSessionIn !== null) return; + setCreatingSessionIn(folderKey(workspaceId, path)); + createSessionIn(workspaceId, path).catch((reason) => { + const detail = reason instanceof Error ? reason.message : String(reason); + notifyFolder(`${t("folder.sessionError")}: ${detail}`); + }).finally(() => { + setCreatingSessionIn(null); + }); + }; + /** A project row's plus button — starts in that workspace's root folder. */ + const startSessionAtRoot = (workspaceId) => { + const workspace = workspaceId === void 0 ? void 0 : workspaces.find((w) => w.workspaceId === workspaceId); + if (workspace === void 0) { + startSession(workspaceId); + return; + } + const root = rootOf(workspace.path, entryFor(foldersDoc, workspaceId)); + startSessionInFolder(workspaceId, root, samePath(root, workspace.path)); + }; + const openFolderPath = folderApp === void 0 ? void 0 : (path) => { + openPathInApp(folderApp, path).catch((reason) => { + const detail = reason instanceof Error ? reason.message : String(reason); + notifyFolder(`${t("workspace.openInFolderError")}: ${detail}`); + }); + }; const [groupDialog, setGroupDialog] = (0, react.useState)(null); const [groupDraft, setGroupDraft] = (0, react.useState)(""); const [groupError, setGroupError] = (0, react.useState)(null); @@ -3662,7 +4225,7 @@ window.__ModuleLoader__.load({ setManualSaving(false); } }; - /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */ + /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (no target = append). */ const moveCategory = async (draggedKey, beforeKey, afterKey) => { if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return; setManualSaving(true); @@ -3806,9 +4369,9 @@ window.__ModuleLoader__.load({ setDragIndicator(null); }; /** - * Drag over the TOP-LEVEL AREA's blank space (not on a row — rows stop - * propagation). An insertion line shows the landing spot: empty top level → - * a standalone line under the last group; non-empty → a line below the last + * Drag over the TOP-LEVEL AREA's blank space (not on a row ???rows stop + * propagation). An insertion line shows the landing spot: empty top level — + * a standalone line under the last group; non-empty — a line below the last * top-level row (end of the list). */ const onDragOverTopLevelArea = (event) => { @@ -3990,6 +4553,7 @@ window.__ModuleLoader__.load({ now, open, manual, + folders: foldersDoc, t }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: "wgTreeWrap", @@ -4023,8 +4587,17 @@ window.__ModuleLoader__.load({ onToggleWorkspace: (key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]); }, - onNewSession: startSession, + onNewSession: startSessionAtRoot, onOpen: open, + onToggleFolder: toggleFolder, + onFolderNewSession: startSessionInFolder, + onFolderSetRoot: setFolderRoot, + onFolderRemove: removeFolderFrom, + onOpenFolderPath: openFolderPath, + onManageFolders: (workspaceId) => { + setFoldersTarget(workspaceId); + }, + creatingFolderKey: creatingSessionIn, onRenameRequest: (workspaceId, title) => { setRenameTarget({ workspaceId, @@ -4089,8 +4662,17 @@ window.__ModuleLoader__.load({ onToggleWorkspace: (key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]); }, - onNewSession: startSession, + onNewSession: startSessionAtRoot, onOpen: open, + onToggleFolder: toggleFolder, + onFolderNewSession: startSessionInFolder, + onFolderSetRoot: setFolderRoot, + onFolderRemove: removeFolderFrom, + onOpenFolderPath: openFolderPath, + onManageFolders: (workspaceId) => { + setFoldersTarget(workspaceId); + }, + creatingFolderKey: creatingSessionIn, onRenameRequest: (workspaceId, title) => { setRenameTarget({ workspaceId, @@ -4315,6 +4897,32 @@ window.__ModuleLoader__.load({ }) ] }) }), + foldersTarget !== null && (() => { + const workspace = workspaces.find((w) => w.workspaceId === foldersTarget); + if (workspace === void 0) return null; + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FoldersDialog, { + workspace, + entry: entryFor(foldersDoc, foldersTarget), + t, + busy: foldersBusy, + canOpen: openFolderPath !== void 0, + onClose: () => { + setFoldersTarget(null); + }, + onAdd: () => { + addFolderTo(foldersTarget); + }, + onSetRoot: (path) => { + setFolderRoot(foldersTarget, path); + }, + onRemove: (path) => { + removeFolderFrom(foldersTarget, path); + }, + onOpenFolder: (path) => { + openFolderPath?.(path); + } + }); + })(), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { open: renameTarget !== null, onClose: () => { @@ -4469,8 +5077,78 @@ window.__ModuleLoader__.load({ if (workspace === void 0) return void 0; return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title); } + /** + * The expanded session rows of one project. Workspaces with extra folders get + * one folder row per folder (root first) and hang their sessions off that + * folder; a workspace without extra folders renders today's flat list, so the + * common case is unchanged row-for-row. + */ + function WorkspaceSubtree({ workspace, current, now, t, animate, onOpen, onSessionRename, onSessionArchive, onFork, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, creatingFolderKey }) { + const folders = workspace.folders; + if (folders === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RowGroup, { + expanded: workspace.expanded, + className: "wgTreeChildren", + animate: animate && workspace.sessions.length <= ANIMATION_ROW_CAP, + children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { + node: session, + currentId: current, + now, + t, + onOpen, + onRename: onSessionRename, + onFork, + onArchive: onSessionArchive + }, session.id)) + }); + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RowGroup, { + expanded: workspace.expanded, + className: "wgTreeChildren", + animate: animate && folders.length + workspace.sessions.length <= ANIMATION_ROW_CAP, + children: folders.map((folder) => { + const key = folderKey(workspace.workspaceId, folder.path); + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + role: "group", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(FolderRow, { + node: folder, + t, + creating: creatingFolderKey === key, + onToggle: () => { + onToggleFolder(workspace.workspaceId, folder.path); + }, + onNewSession: () => { + onFolderNewSession(workspace.workspaceId, folder.path, folder.isBase); + }, + onSetRoot: () => { + onFolderSetRoot(workspace.workspaceId, folder.path); + }, + onRemove: () => { + onFolderRemove(workspace.workspaceId, folder.path); + }, + ...onOpenFolderPath !== void 0 ? { onOpenInFolder: () => { + onOpenFolderPath(folder.path); + } } : {} + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RowGroup, { + expanded: folder.expanded, + className: "wgTreeChildren", + animate: animate && folder.sessions.length <= ANIMATION_ROW_CAP, + children: folder.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { + node: session, + nested: true, + currentId: current, + now, + t, + onOpen, + onRename: onSessionRename, + onFork, + onArchive: onSessionArchive + }, session.id)) + })] + }, key); + }) + }); + } /** One category section: header row + expanded workspace folders. */ - function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder }) { + function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }) { 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", { @@ -4534,21 +5212,26 @@ window.__ModuleLoader__.load({ kind: "workspace", key: workspace.workspaceId }), - onDragStartExtra: onDragStartWorkspace(workspace.workspaceId) - }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RowGroup, { - expanded: workspace.expanded, - className: "wgTreeChildren", - animate: animate && workspace.sessions.length <= ANIMATION_ROW_CAP, - children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { - node: session, - currentId: current, - now, - t, - onOpen, - onRename: onSessionRename, - onFork, - onArchive: onSessionArchive - }, session.id)) + onDragStartExtra: onDragStartWorkspace(workspace.workspaceId), + onManageFolders: () => { + onManageFolders(workspace.workspaceId); + } + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceSubtree, { + workspace, + current, + now, + t, + animate, + onOpen, + onSessionRename, + onSessionArchive, + onFork, + onToggleFolder, + onFolderNewSession, + onFolderSetRoot, + onFolderRemove, + onOpenFolderPath, + creatingFolderKey })] }, workspace.workspaceId)) })] @@ -4563,7 +5246,7 @@ window.__ModuleLoader__.load({ * last row); * - an empty top level shows a standalone line under the last group folder. */ - function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder }) { + function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }) { const emptyLineActive = dragIndicator?.mode === "line" && dragIndicator.row.kind === "topLevel" && dragIndicator.row.key === topLevelRef.key; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { role: "group", @@ -4610,31 +5293,84 @@ window.__ModuleLoader__.load({ kind: "topLevel", key: workspace.workspaceId }), - onDragStartExtra: onDragStartWorkspace(workspace.workspaceId) - }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RowGroup, { - expanded: workspace.expanded, - className: "wgTreeChildren", - animate: !dragging && workspace.sessions.length <= ANIMATION_ROW_CAP, - children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { - node: session, - currentId: current, - now, - t, - onOpen, - onRename: onSessionRename, - onFork, - onArchive: onSessionArchive - }, session.id)) + onDragStartExtra: onDragStartWorkspace(workspace.workspaceId), + onManageFolders: () => { + onManageFolders(workspace.workspaceId); + } + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(WorkspaceSubtree, { + workspace, + current, + now, + t, + animate: !dragging, + onOpen, + onSessionRename, + onSessionArchive, + onFork, + onToggleFolder, + onFolderNewSession, + onFolderSetRoot, + onFolderRemove, + onOpenFolderPath, + creatingFolderKey })] }, workspace.workspaceId))] }); } /** + * Search hits inside one project. When the project owns extra folders the hits + * keep their folder row (all expanded, since search prunes to matches) so a + * match never loses the folder it came from. + */ + function SearchSubtree({ workspace, current, now, open, t }) { + const folders = workspace.folders; + if (folders === void 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + role: "group", + children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { + node: session, + currentId: current, + now, + t, + onOpen: open, + onRename: () => {}, + onFork: () => {}, + onArchive: () => {} + }, session.id)) + }); + return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + role: "group", + children: folders.map((folder) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + role: "group", + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(FolderRow, { + node: folder, + t, + onToggle: () => {}, + onNewSession: () => {}, + onSetRoot: () => {}, + onRemove: () => {} + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + role: "group", + children: folder.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { + node: session, + nested: true, + currentId: current, + now, + t, + onOpen: open, + onRename: () => {}, + onFork: () => {}, + onArchive: () => {} + }, session.id)) + })] + }, folderKey(workspace.workspaceId, folder.path))) + }); + } + /** * Search body rendered as a three-level tree pruned to matched branches: - * 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as + * Only branches that contain a hit are rendered, which keeps a long list short. 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, statuses, query, remote, resultLimit, current, now, open, manual, t }) { + function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, folders, t }) { const currentRemote = remote.query === query ? remote : { query, status: "loading", @@ -4650,14 +5386,15 @@ window.__ModuleLoader__.load({ currentRemote, resultLimit ]); - const searchTree = (0, react.useMemo)(() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses), [ + const searchTree = (0, react.useMemo)(() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses, folders), [ list, workspaces, config, matches, archivedSessionIds, manual, - statuses + statuses, + folders ]); const groups = searchTree.categories; const searchTopLevel = searchTree.topLevel; @@ -4685,18 +5422,12 @@ window.__ModuleLoader__.load({ onNewSession: () => {}, onRename: () => {}, onDelete: () => {} - }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { - role: "group", - children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { - node: session, - currentId: current, - now, - t, - onOpen: open, - onRename: () => {}, - onFork: () => {}, - onArchive: () => {} - }, session.id)) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchSubtree, { + workspace, + current, + now, + open, + t })] }, workspace.workspaceId)) })] @@ -4711,18 +5442,12 @@ window.__ModuleLoader__.load({ onNewSession: () => {}, onRename: () => {}, onDelete: () => {} - }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { - role: "group", - children: workspace.sessions.map((session) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SessionRow, { - node: session, - currentId: current, - now, - t, - onOpen: open, - onRename: () => {}, - onFork: () => {}, - onArchive: () => {} - }, session.id)) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SearchSubtree, { + workspace, + current, + now, + open, + t })] }, workspace.workspaceId)), pending && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { @@ -4746,6 +5471,94 @@ window.__ModuleLoader__.load({ ] }); } + /** + * Folder list dialog for one workspace: the base folder first, then every extra + * folder in stored order. The radio column chooses the root (the folder new + * sessions default to); open/remove act per row, and removing the base folder is + * never offered because the workspace's canonical directory cannot be dropped. + */ + function FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onSetRoot, onRemove, onOpenFolder }) { + const folders = effectiveFolders(workspace.path, entry); + const root = rootOf(workspace.path, entry); + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { + open: true, + onClose, + closeLabel: t("close"), + title: t("folder.title"), + footer: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "primary", + onClick: onClose, + children: t("folder.done") + }), + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgFolderList", + role: "list", + "aria-label": t("folder.listAria"), + children: folders.map((path, index) => { + const isBase = index === 0; + const isRoot = samePath(path, root); + const label = folderLabel(path); + return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { + className: "wgFolderListRow", + role: "listitem", + children: [ + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", { + type: "radio", + className: "wgFolderRadio", + name: "wg-folder-root", + checked: isRoot, + "aria-label": `${t("folder.rootBadge")} ${label}`, + onChange: () => { + onSetRoot(path); + } + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderListLabel", + title: path, + children: label + }), + isBase && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderListTag", + children: t("folder.base") + }), + isRoot && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgFolderListTag", + children: t("folder.rootBadge") + }), + /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", { + className: "wgFolderListActions", + children: [canOpen && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + "aria-label": `${t("workspace.openInFolder")} ${label}`, + onClick: () => { + onOpenFolder(path); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpenOutlineRegular, { size: 16 }) + }), !isBase && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + "aria-label": `${t("folder.remove")} ${label}`, + onClick: () => { + onRemove(path); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutlineRegular, {}) + })] + }) + ] + }, path); + }) + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + className: "wgFolderListFooter", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + variant: "outline", + disabled: busy, + onClick: onAdd, + children: t("folder.add") + }) + })] + }); + } //#endregion //#region src/client/locales.ts /** Simplified Chinese dictionary. */ @@ -4778,6 +5591,19 @@ window.__ModuleLoader__.load({ "workspace.moveOutOfGroup": "移出分组", "workspace.openInFolder": "在文件夹中打开", "workspace.openInFolderError": "打开文件夹失败", + "folder.title": "文件夹", + "folder.manage": "文件夹…", + "folder.listAria": "工作区文件夹", + "folder.base": "基础文件夹", + "folder.setRoot": "设为根目录", + "folder.rootBadge": "根目录", + "folder.remove": "从工作区移除", + "folder.add": "添加文件夹", + "folder.done": "完成", + "folder.duplicate": "该文件夹已在此工作区中", + "folder.addError": "添加文件夹失败", + "folder.sessionError": "新建会话失败", + "folder.saveError": "文件夹保存失败", "group.create": "新建分组", "group.createTitle": "新建分组", "group.createPlaceholder": "分组名称", @@ -4891,6 +5717,19 @@ window.__ModuleLoader__.load({ "workspace.moveOutOfGroup": "Move out of group", "workspace.openInFolder": "Open in folder", "workspace.openInFolderError": "Could not open the folder", + "folder.title": "Folders", + "folder.manage": "Folders…", + "folder.listAria": "Workspace folders", + "folder.base": "Base folder", + "folder.setRoot": "Set as root", + "folder.rootBadge": "Root", + "folder.remove": "Remove from workspace", + "folder.add": "Add folder", + "folder.done": "Done", + "folder.duplicate": "That folder is already in this workspace", + "folder.addError": "Could not add the folder", + "folder.sessionError": "Could not start a session", + "folder.saveError": "Could not save folders", "group.create": "New group", "group.createTitle": "New group", "group.createPlaceholder": "Group name", @@ -5048,6 +5887,14 @@ window.__ModuleLoader__.load({ startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId); }, + createSessionIn: async (workspaceId, cwd) => { + const sessionId = await ctx.sessions.create({ + workspaceId, + ...cwd === void 0 ? {} : { cwd } + }); + ctx.uiWorkspace.openSession(sessionId); + return sessionId; + }, open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId); }, diff --git a/lib/client.js.map b/lib/client.js.map index fbdfacc..96891bc 100644 --- a/lib/client.js.map +++ b/lib/client.js.map @@ -1 +1 @@ -{"version":3,"file":"client.js","names":["defineStore","defineStore","useRef","useCallback","useSyncExternalStore","IconFolderCloseMedium","IconWorkspaceTreeOutlineMedium","IconCodeOutlineMedium","IconCordisPluginOutlineMedium","IconSkillOutlineMedium","IconDataOutlineMedium","IconDatabaseOutlineMedium","IconApiOutlineMedium","IconPlanOutlineMedium","IconGoalOutlineMedium","IconLightOutlineMedium","IconGlobeOutlineMedium","IconArchiveOutlineMedium","IconBranchOutlineMedium","IconUsersOutlineMedium","IconClockOutlineMedium","IconShieldOutlineMedium","IconChecklistOutlineMedium","IconSparkleMedium","IconTreeCornerMedium","useState","IconPinFillMedium","IconPinOutlineRegular","IconSlidersTwoOutlineRegular","IconEditOutlineRegular","IconTrashOutlineRegular","IconTriangleRightFillMedium","IconFolderOpenMedium","Menu","IconEllipsisOutlineRegular","IconFolderOpenOutlineRegular","IconRightUpOutlineRegular","IconProjectAddOutlineRegular","IconPlusOutlineRegular","useRef","IconBranchOutlineRegular","IconArchiveOutlineRegular","StateDot","useState","useRef","useMemo","createPortal","Button","StateDot","useMemo","useState","useRef","StateDot","IconPinFillMedium","Tooltip","IconCloseFillMedium","createPortal","useState","useRef","css","useState","useRef","useMemo","IconSearchOutlineRegular","IconCloseFillMedium","Tooltip","IconFolderOpenOutlineRegular","IconProjectAddOutlineRegular","Modal","Button","Toast","IconWarningOutlineRegular"],"sources":["../src/client/store-core.ts","../src/client/stores.ts","../src/client/tabs.ts","../src/client/tab-store.ts","../src/client/tab-persist.ts","../src/client/store-hook.ts","../src/core/types.ts","../src/core/matcher.ts","../src/client/subagent-lineage.ts","../src/client/tree.ts","../src/client/rows.tsx","../src/client/open-folder.ts","../src/client/quick.ts","../src/client/QuickPanel.tsx","../src/client/tab-seat.ts","../src/client/SessionTabs.tsx","../src/client/branch.ts","../src/client/FlowerBranch.tsx","../src/client/GroupsBrowser.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\r\n * Pure expansion-state transforms for the workspace-groups store. Kept free\r\n * of any runtime import so both the store (which binds them via defineStore)\r\n * and unit tests (which exercise them directly) share one implementation.\r\n *\r\n * Expansion semantics follow the official ui-workspace store: collapse\r\n * WRITES `false` (never deletes the key). The browser's auto-expand guard\r\n * uses `Object.hasOwn` — a present `false` means \"user deliberately\r\n * collapsed this\" and must NOT be re-expanded; only a fully absent key means\r\n * \"never touched\" and may auto-expand. (Earlier versions deleted the key on\r\n * collapse, which made the current category/workspace impossible to fold.)\r\n */\r\n\r\n/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */\r\nexport interface GroupsViewState {\r\n /** Category folder expansion keyed by category label (absent = never touched). */\r\n categoryExpansion: Record\r\n /** Workspace folder expansion keyed by workspace id (absent = never touched). */\r\n workspaceExpansion: Record\r\n}\r\n\r\n/** Collapse writes `false` (key retained); expand writes `true`. */\r\nexport function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\r\n state.categoryExpansion[key] = expanded\r\n}\r\n\r\n/** Collapse writes `false` (key retained); expand writes `true`. */\r\nexport function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\r\n state.workspaceExpansion[key] = expanded\r\n}\r\n\r\n/** Drop expansion keys that no longer exist (renames/deletes/config edits). */\r\nexport function retainKeysImpl(\r\n state: GroupsViewState,\r\n categoryKeys: readonly string[],\r\n workspaceKeys: readonly string[],\r\n): void {\r\n state.categoryExpansion = Object.fromEntries(\r\n Object.entries(state.categoryExpansion).filter(([key]) => categoryKeys.includes(key)),\r\n )\r\n state.workspaceExpansion = Object.fromEntries(\r\n Object.entries(state.workspaceExpansion).filter(([key]) => workspaceKeys.includes(key)),\r\n )\r\n}\r\n","/**\r\n * The workspace-groups viewing store: category / workspace folder expansion,\r\n * persisted across reloads under an independent key (the official\r\n * ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch\r\n * it). Module level exports the factory only (a module-level handle would pin\r\n * the store identity across plugin reloads); register() receives the factory\r\n * and the browser derives its PropsStore share from the return type.\r\n *\r\n * The action implementations live in `store-core.ts` (pure, runtime-free) so\r\n * unit tests exercise the real semantics without a browser module loader;\r\n * this file only binds them through defineStore.\r\n */\r\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'\r\nimport {\r\n retainKeysImpl,\r\n setCategoryExpandedImpl,\r\n setWorkspaceExpandedImpl,\r\n type GroupsViewState,\r\n} from './store-core.ts'\r\n\r\n/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */\r\ntype GroupsViewActions = {\r\n setCategoryExpanded: typeof setCategoryExpandedImpl\r\n setWorkspaceExpanded: typeof setWorkspaceExpandedImpl\r\n retainKeys: typeof retainKeysImpl\r\n}\r\n\r\n/**\r\n * Create the workspace-groups viewing store handle.\r\n * @returns the store handle (spec + type + identity + factory in one).\r\n */\r\nexport function createGroupsViewStore(): EngineStoreHandle {\r\n return defineStore({\r\n init: () => ({ categoryExpansion: {}, workspaceExpansion: {} }),\r\n persist: 'dsh.workspace.groups.view.v1',\r\n actions: {\r\n setCategoryExpanded: setCategoryExpandedImpl,\r\n setWorkspaceExpanded: setWorkspaceExpandedImpl,\r\n retainKeys: retainKeysImpl,\r\n },\r\n })\r\n}\r\n\r\nexport type { GroupsViewState } from './store-core.ts'\r\n","/**\r\n * Pure session-tab state: the ordered strip of sessions the user has opened,\r\n * the active one, and each tab's derived presentation.\r\n *\r\n * Position model: a tab's place in the strip is decided when it is first opened\r\n * and otherwise only moves when the USER moves it. Switching to a tab, or\r\n * re-opening a session that already has one, leaves the strip exactly as it was\r\n * — so clicking a chip never moves the chip out from under the pointer. The\r\n * order changes on: a session opening for the FIRST time (append), a tab closing\r\n * (remove), a drag (move), and a pin toggle (which carries the chip across the\r\n * pinned boundary).\r\n *\r\n * The array IS the display order, with one invariant the transforms maintain:\r\n * every pinned tab sits before every unpinned one. New tabs therefore append at\r\n * the end (the unpinned block) and pinning/unpinning re-inserts at the boundary\r\n * between the two blocks. A stored strip from an older build has no `pinned`\r\n * flag, which reads as \"unpinned\" and satisfies the invariant as-is.\r\n *\r\n * Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):\r\n * the component owns the ref + React state, this module owns every rule, and\r\n * unit tests exercise the real semantics without a browser module loader.\r\n *\r\n * Retention note: a tab outlives whatever it points at. The strip is a list of\r\n * things the USER opened, so nothing here consults the session catalog — a tab\r\n * whose session is gone stays visible until the user closes it, and no\r\n * background sweep ever trims the strip.\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { SessionStatus } from '@deepseek-ai/dsh-client-ui-session/client'\r\n\r\n/** One open tab: a session id plus its arrival key (React list identity). */\r\nexport interface SessionTab {\r\n /** The session the tab shows. */\r\n readonly sessionId: SessionId\r\n /**\r\n * Monotonic arrival key. It doubles as the React `key`, so it must stay\r\n * attached to the session for the tab's whole life — a reused key would make\r\n * React move an existing chip's DOM node instead of reconciling it in place.\r\n */\r\n readonly order: number\r\n /**\r\n * Pinned tabs stay at the front of the strip and survive `close others`.\r\n *\r\n * Absent means unpinned: that is both the `false` case and the shape an older\r\n * build's stored strip has, so no migration step is needed to read one back.\r\n */\r\n readonly pinned?: boolean\r\n /**\r\n * A label the user typed for THIS tab, overriding the session's title.\r\n *\r\n * Kept separate from the session title on purpose: renaming a tab here must\r\n * not rewrite the conversation's own name (which the sidebar and the search\r\n * results show). Absent/empty means \"follow the session\".\r\n */\r\n readonly title?: string\r\n}\r\n\r\n/** Feature switch: whether opening a session also surfaces a tab. */\r\nexport type TabOpenMode = 'auto' | 'manual'\r\n\r\n/** Per-tab indicator derived from the catalog summary and the live UI status. */\r\nexport interface SessionTabIndicator {\r\n /** A domain request is waiting for the user (approval / plan review / question). */\r\n readonly attention: boolean\r\n /** The agent is producing output, or a descendant subagent is. */\r\n readonly running: boolean\r\n /** The turn finished while the tab was in the background and was never looked at. */\r\n readonly unread: boolean\r\n /** Idle tab whose session already has a title (a settled conversation). */\r\n readonly settled: boolean\r\n}\r\n\r\n/**\r\n * Add a session to the strip, or leave an existing entry exactly where it is.\r\n *\r\n * Arrival order is the strip's only order, so re-opening a session that already\r\n * has a tab is a NO-OP: the tab keeps its position and its arrival key. Moving\r\n * it to the front here would fight the whole point of stable positions — a user\r\n * clicking through sessions would watch the strip reshuffle on every click.\r\n *\r\n * @param tabs - current strip (oldest first).\r\n * @param sessionId - arriving session.\r\n * @param nextOrder - monotonic arrival counter to spend when appending.\r\n * @returns the strip, unchanged (same array) when the session already has a tab.\r\n */\r\nexport function appendTab(tabs: readonly SessionTab[], sessionId: SessionId, nextOrder: number): SessionTab[] {\r\n const existing = tabs.find(tab => tab.sessionId === sessionId)\r\n if (existing !== undefined) return tabs as SessionTab[]\r\n return [...tabs, { sessionId, order: nextOrder }]\r\n}\r\n\r\n/**\r\n * Remove one session's tab. An absent session leaves the strip untouched.\r\n * @param tabs - current strip.\r\n * @param sessionId - session whose tab closes.\r\n * @returns a new strip.\r\n */\r\nexport function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n return tabs.filter(tab => tab.sessionId !== sessionId)\r\n}\r\n\r\n/**\r\n * Whether a tab is pinned (absent counts as unpinned).\r\n * @param tab - the tab.\r\n * @returns true when the tab belongs in the pinned block.\r\n */\r\nfunction isPinned(tab: SessionTab): boolean {\r\n return tab.pinned === true\r\n}\r\n\r\n/**\r\n * Count the leading pinned block.\r\n *\r\n * The transforms keep every pinned tab before every unpinned one, so the pinned\r\n * block is always a prefix and its length is the single index that separates\r\n * the two blocks — which is exactly where a chip lands when it changes sides.\r\n *\r\n * @param tabs - strip in display order.\r\n * @returns how many leading tabs are pinned.\r\n */\r\nexport function pinnedCount(tabs: readonly SessionTab[]): number {\r\n let count = 0\r\n while (count < tabs.length && isPinned(tabs[count] as SessionTab)) count += 1\r\n return count\r\n}\r\n\r\n/**\r\n * Stable-partition a strip so every pinned tab precedes every unpinned one.\r\n *\r\n * Needed by the restore path: stored tabs are merged onto whatever the startup\r\n * flow already opened, and an append would otherwise park a pinned tab at the\r\n * end of the strip. Already-normalized strips come back as a copy.\r\n *\r\n * @param tabs - any strip.\r\n * @returns a strip satisfying the pinned-first invariant.\r\n */\r\nexport function normalizeTabs(tabs: readonly SessionTab[]): SessionTab[] {\r\n const pinned = tabs.filter(isPinned)\r\n if (pinned.length === 0 || pinned.length === tabs.length) return [...tabs]\r\n return [...pinned, ...tabs.filter(tab => !isPinned(tab))]\r\n}\r\n\r\n/**\r\n * Move one tab to a new place in the strip (drag and drop).\r\n *\r\n * `targetIndex` is an index in the RESULTING strip. The move is clamped to the\r\n * tab's own block — a dragged chip can be reordered within the pinned block or\r\n * within the unpinned one, but never carried across that boundary. Crossing it\r\n * is `togglePinTab`'s job, because it changes the tab's meaning rather than\r\n * just its position: pinning is what makes a tab survive `close others`.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the tab being moved.\r\n * @param targetIndex - desired index in the resulting strip.\r\n * @returns a new strip, or the same array when nothing moved.\r\n */\r\nexport function moveTab(\r\n tabs: readonly SessionTab[],\r\n sessionId: SessionId,\r\n targetIndex: number,\r\n): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const moving = tabs[from] as SessionTab\r\n const rest = tabs.filter(tab => tab.sessionId !== sessionId)\r\n const boundary = pinnedCount(rest)\r\n const min = isPinned(moving) ? 0 : boundary\r\n const max = isPinned(moving) ? boundary : rest.length\r\n const clamped = Math.min(Math.max(Math.trunc(targetIndex), min), max)\r\n if (clamped === from) return tabs as SessionTab[]\r\n return [...rest.slice(0, clamped), moving, ...rest.slice(clamped)]\r\n}\r\n\r\n/**\r\n * Pin or unpin one tab, re-inserting it at the boundary between the blocks.\r\n *\r\n * Pinning puts the chip at the END of the pinned block (next to the other\r\n * kept tabs) and unpinning at the START of the unpinned one, so a toggle never\r\n * throws a chip to the far end of the strip.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the tab to toggle.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function togglePinTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const moving = tabs[from] as SessionTab\r\n const rest = tabs.filter(tab => tab.sessionId !== sessionId)\r\n const boundary = pinnedCount(rest)\r\n const repinned: SessionTab = isPinned(moving)\r\n ? { sessionId: moving.sessionId, order: moving.order, ...(moving.title !== undefined ? { title: moving.title } : {}) }\r\n : { sessionId: moving.sessionId, order: moving.order, pinned: true, ...(moving.title !== undefined ? { title: moving.title } : {}) }\r\n return [...rest.slice(0, boundary), repinned, ...rest.slice(boundary)]\r\n}\r\n\r\n/**\r\n * Set or clear one tab's own label.\r\n *\r\n * A blank value CLEARS the override (the chip falls back to the session title)\r\n * rather than storing an empty label, so \"rename to nothing\" and \"rename back to\r\n * the session title\" are the same gesture.\r\n *\r\n * @param tabs - strip.\r\n * @param sessionId - the tab to relabel.\r\n * @param title - the new label; blank clears it.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function renameTab(\r\n tabs: readonly SessionTab[],\r\n sessionId: SessionId,\r\n title: string | undefined,\r\n): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const trimmed = title?.trim() ?? ''\r\n // No change: return the same array so the store can skip the write.\r\n if ((tabs[from]?.title ?? '') === trimmed) return tabs as SessionTab[]\r\n return tabs.map((tab) => {\r\n if (tab.sessionId !== sessionId) return tab\r\n if (trimmed === '') {\r\n const { title: _cleared, ...rest } = tab\r\n void _cleared\r\n return rest\r\n }\r\n return { ...tab, title: trimmed }\r\n })\r\n}\r\n\r\n/**\r\n * Close every tab except one — pinned tabs stay.\r\n *\r\n * Pinning is exactly how a user says \"keep this no matter what\"; letting\r\n * `close others` eat the pinned block would make the flag pointless.\r\n *\r\n * @param tabs - strip.\r\n * @param keepSessionId - the tab to keep (plus every pinned one).\r\n * @returns a new strip.\r\n */\r\nexport function closeOtherTabs(tabs: readonly SessionTab[], keepSessionId: SessionId): SessionTab[] {\r\n if (!tabs.some(tab => tab.sessionId === keepSessionId)) return tabs as SessionTab[]\r\n return tabs.filter(tab => isPinned(tab) || tab.sessionId === keepSessionId)\r\n}\r\n\r\n/**\r\n * Close every tab after one in display order.\r\n *\r\n * \"After\" is display order (pinned block first), which is the order the user\r\n * sees; a pinned tab is never after an unpinned one, so this cannot silently\r\n * drop the kept block.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the last tab that stays.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function closeTabsAfter(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n return tabs.slice(0, from + 1)\r\n}\r\n\r\n/**\r\n * Order the strip for display: strictly by arrival, regardless of which tab is\r\n * active.\r\n *\r\n * Position is a property of the TAB, not of the selection. Switching to a tab\r\n * must not move it — an earlier version pulled the active tab to the front,\r\n * which made every click reshuffle the strip and slid the chip out from under\r\n * the pointer that had just clicked it.\r\n *\r\n * `activeId` is therefore accepted only to document that \"active\" deliberately\r\n * does NOT participate in ordering; it is unused. The returned array is a copy\r\n * so callers cannot mutate the store's state through it.\r\n *\r\n * @param tabs - strip in arrival order.\r\n * @param activeId - the open session, if it has a tab (intentionally unused).\r\n * @returns a new array in arrival order.\r\n */\r\nexport function orderedTabs(tabs: readonly SessionTab[], activeId: SessionId | undefined): SessionTab[] {\r\n void activeId\r\n return [...tabs]\r\n}\r\n\r\n/**\r\n * Whether the open session must surface a tab.\r\n *\r\n * A tab means \"this conversation is in play right now\", not \"I once opened\r\n * this\". Browsing history is what the sidebar is for; opening an old\r\n * conversation to read it should not litter the strip, which is the whole point\r\n * of the strip being a working set rather than a second session list.\r\n *\r\n * A session therefore earns a tab only once a conversation has actually STARTED\r\n * in it and is still engaged, which is any of:\r\n * - **running** — the agent is producing output (including subagents);\r\n * - **waiting on you** — an approval / plan review / question is pending;\r\n * - **unseen completion** — it finished while you were elsewhere, so the tab is\r\n * the thing that tells you to come back.\r\n *\r\n * A still-blank draft gets NO tab: the tab appears the moment the first message\r\n * is sent (which is when the controller flips `blank` on `turn/start`). Once the\r\n * turn ends and you have read the result, the session is settled history and\r\n * does not earn a tab — so clicking through finished conversations leaves the\r\n * strip alone. Tabs already opened stay open: this gate only decides whether a\r\n * NEW tab appears, never whether an existing one closes.\r\n *\r\n * `blank` (from `sessionListMetadata`) is exactly \"no turn has started\": the\r\n * controller flips it to false on `turn/start`. It is the right signal for\r\n * \"has this conversation begun\", and the wrong one ALONE — a conversation\r\n * finished a week ago is also non-blank, which is why the earlier `!blank` rule\r\n * surfaced every old conversation the user clicked.\r\n *\r\n * @param mode - feature switch ('auto' applies the engagement rule).\r\n * @param summary - the session's catalog row (absent while the catalog has not\r\n * caught up with a just-created session).\r\n * @param status - the session's unified UI status (absent → no live signal).\r\n * @returns true when a tab belongs in the strip.\r\n */\r\nexport function shouldOpenTab(\r\n mode: TabOpenMode,\r\n summary: SessionSummary | undefined,\r\n status: SessionStatus | undefined,\r\n): boolean {\r\n if (mode === 'manual') return false\r\n if (summary === undefined) return false\r\n // No turn yet: a scratch draft is not a conversation, so it holds no tab. The\r\n // first message flips `blank`, and the tab appears then.\r\n if (summary.blank) return false\r\n // A conversation has begun. Keep the tab only while it is still in play.\r\n if (summary.running) return true\r\n if (status?.running === true) return true\r\n if (status?.pendingInteraction !== undefined) return true\r\n if (status?.completionUnread === true) return true\r\n // Begun, but quiet and read: settled history, not a working tab.\r\n return false\r\n}\r\n\r\n/**\r\n * Derive one tab's indicators from the catalog row and the unified UI status.\r\n * @param summary - the tab session's catalog row (absent → inert indicators).\r\n * @param status - the tab session's unified UI status (absent → idle).\r\n * @returns the indicator quadruple.\r\n */\r\nexport function tabIndicator(\r\n summary: SessionSummary | undefined,\r\n status: SessionStatus | undefined,\r\n): SessionTabIndicator {\r\n const pending = status?.pendingInteraction !== undefined\r\n const running = status?.running === true || summary?.running === true\r\n const unread = status?.completionUnread === true\r\n const blank = summary?.blank !== false\r\n return {\r\n attention: pending,\r\n running,\r\n unread,\r\n settled: !pending && !running && !unread && summary !== undefined && !blank,\r\n }\r\n}\r\n\r\n/**\r\n * Where one session lives: the project (workspace) that accounts for it.\r\n *\r\n * Tabs carry this because a strip of bare session titles is ambiguous once\r\n * several projects are open — two checkouts both named \"api\", or a session\r\n * titled after a file, give no hint which project it belongs to.\r\n */\r\nexport interface TabProject {\r\n /** Stable workspace id. */\r\n readonly workspaceId: string\r\n /** Display label: the workspace title, falling back to its directory name. */\r\n readonly label: string\r\n /** Canonical directory path, for the tooltip. */\r\n readonly path: string\r\n}\r\n\r\n/**\r\n * Index sessions by the project that owns them.\r\n *\r\n * Membership comes from the workspace registry (`sessionIds`), which is the same\r\n * authority the sidebar tree uses — a tab and its sidebar row therefore agree on\r\n * the project without a second derivation.\r\n *\r\n * Built once per render pass rather than scanned per tab: a strip of N tabs over\r\n * M projects is O(N×M) with a naive `find` per tab.\r\n *\r\n * @param workspaces - workspace views from the controller snapshot.\r\n * @returns a session id → project map; sessions in no workspace are absent.\r\n */\r\nexport function projectIndex(\r\n workspaces: readonly WorkspaceViewLike[],\r\n): ReadonlyMap {\r\n const index = new Map()\r\n for (const workspace of workspaces) {\r\n const label = projectLabel(workspace)\r\n const project: TabProject = {\r\n workspaceId: workspace.workspaceId,\r\n label,\r\n path: workspace.path,\r\n }\r\n for (const sessionId of workspace.sessionIds) {\r\n // First writer wins: a session wrongly listed by two workspaces keeps the\r\n // first, so the tab never flickers between labels across renders.\r\n if (!index.has(sessionId)) index.set(sessionId, project)\r\n }\r\n }\r\n return index\r\n}\r\n\r\n/** Minimal workspace shape this module needs (keeps it importable in tests). */\r\nexport interface WorkspaceViewLike {\r\n readonly workspaceId: string\r\n readonly path: string\r\n readonly title: string\r\n readonly sessionIds: readonly SessionId[]\r\n}\r\n\r\n/**\r\n * Display label for a project: its title, else the directory basename.\r\n * @param workspace - workspace view.\r\n * @returns a non-empty label, falling back to the raw path.\r\n */\r\nexport function projectLabel(workspace: Pick): string {\r\n const title = workspace.title.trim()\r\n if (title !== '') return title\r\n // Both separators: the host path may be Windows or POSIX.\r\n const parts = workspace.path.split(/[\\\\/]/).filter(part => part !== '')\r\n return parts[parts.length - 1] ?? workspace.path\r\n}\r\n\r\n/**\r\n * Whether two strips are the same sequence of sessions (arrival keys ignored).\r\n * @param left - previous strip.\r\n * @param right - next strip.\r\n * @returns true when no entry was added, removed, or reordered.\r\n */\r\nexport function sameTabs(left: readonly SessionTab[], right: readonly SessionTab[]): boolean {\r\n return left.length === right.length\r\n && left.every((tab, index) => right[index]?.sessionId === tab.sessionId)\r\n}\r\n\r\n/** Session-tab strip state (the shape the store persists). */\r\nexport interface SessionTabsState {\r\n /** Open tabs in arrival order — the strip's one and only order. */\r\n tabs: SessionTab[]\r\n /** Monotonic arrival counter; each FIRST-time session spends one. */\r\n order: number\r\n}\r\n\r\n/**\r\n * Store transform: add the open session, or leave its existing tab in place.\r\n *\r\n * Live here rather than in `tab-store.ts` so unit tests can exercise the real\r\n * semantics without importing `@deepseek-ai/dsh-client-store` (which pulls\r\n * `zustand` into the test process). The store module binds these into its\r\n * actions table.\r\n *\r\n * The no-op guard matters: this runs on EVERY catalog change for the open\r\n * session, so an unguarded write would wake the strip and spend arrival keys on\r\n * every projection tick.\r\n *\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the session that just became open.\r\n */\r\nexport function touchTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = appendTab(state.tabs, sessionId, state.order + 1)\r\n // Same array => the session already had a tab; nothing changed, so nothing is\r\n // written and no subscriber wakes.\r\n if (next === state.tabs) return\r\n state.order += 1\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close one tab. Closing a session that has no tab is not a\r\n * state change, so it writes nothing.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to close.\r\n */\r\nexport function closeTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = removeTab(state.tabs, sessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: adopt tabs loaded from the host, MERGING with whatever is\r\n * already in the strip.\r\n *\r\n * Async by nature (the host read is a `fetch`), so it can land after the browser\r\n * has already opened a tab for the current session. Merging — rather than\r\n * \"ignore the read if the strip is non-empty\" — is what makes a restart safe:\r\n * the tab opened during startup survives AND the stored tabs still come back.\r\n * (Bailing on a non-empty strip would silently drop every stored tab whenever\r\n * the startup tab won the race, which is the common case for a session that is\r\n * running or unread.)\r\n *\r\n * The arrival counter is lifted above every restored key so a tab opened later\r\n * cannot reuse one; a reused key makes React move a chip's DOM node instead of\r\n * reconciling it.\r\n *\r\n * @param state - store draft, mutated in place.\r\n * @param tabs - tabs read from the host, oldest first.\r\n */\r\nexport function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void {\r\n if (tabs.length === 0) return\r\n const present = new Set(state.tabs.map(tab => tab.sessionId))\r\n const additions: SessionTab[] = []\r\n let order = state.order\r\n for (const tab of tabs) {\r\n // Never duplicate: a session already in the strip keeps its existing entry\r\n // and position.\r\n if (present.has(tab.sessionId)) continue\r\n present.add(tab.sessionId)\r\n // Re-key onto a fresh, monotonically increasing counter so a restored key\r\n // can never collide with one already spent.\r\n order += 1\r\n // Carry the chip's own presentation across the restore: a pinned tab or a\r\n // custom label that came back unpinned/untitled would silently lose the\r\n // user's configuration on every restart.\r\n additions.push({\r\n sessionId: tab.sessionId,\r\n order,\r\n ...(tab.pinned === true ? { pinned: true } : {}),\r\n ...(tab.title !== undefined ? { title: tab.title } : {}),\r\n })\r\n }\r\n if (additions.length > 0) {\r\n const merged = [...state.tabs, ...additions]\r\n // Restored tabs can be pinned, and appending them would park a pinned chip\r\n // past the unpinned ones. Re-establish the pinned-first invariant.\r\n state.tabs = merged.some(isPinned) ? normalizeTabs(merged) : merged\r\n }\r\n state.order = order\r\n}\r\n\r\n/**\r\n * Store transform: pin or unpin one tab.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to toggle.\r\n */\r\nexport function pinTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = togglePinTab(state.tabs, sessionId)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: move one tab to a new index (drag and drop).\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab being moved.\r\n * @param targetIndex - desired index in the resulting strip.\r\n */\r\nexport function moveTabImpl(state: SessionTabsState, sessionId: SessionId, targetIndex: number): void {\r\n const next = moveTab(state.tabs, sessionId, targetIndex)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: set or clear one tab's own label.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to relabel.\r\n * @param title - the new label; blank clears it.\r\n */\r\nexport function renameTabImpl(state: SessionTabsState, sessionId: SessionId, title: string | undefined): void {\r\n const next = renameTab(state.tabs, sessionId, title)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close every unlisted tab, keeping the pinned ones.\r\n * @param state - store draft, mutated in place.\r\n * @param keepSessionId - the tab to keep.\r\n */\r\nexport function closeOthersImpl(state: SessionTabsState, keepSessionId: SessionId): void {\r\n const next = closeOtherTabs(state.tabs, keepSessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close every tab after one in display order.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the last tab that stays.\r\n */\r\nexport function closeAfterImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = closeTabsAfter(state.tabs, sessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n","/**\r\n * The session-tab store: the `defineStore` binding and nothing else.\r\n *\r\n * The action TRANSFORMS live in `tabs.ts` (pure, runtime-free), so unit tests\r\n * exercise the real semantics without pulling in the store engine — this module\r\n * is the only place that needs `@deepseek-ai/dsh-client-store`, and importing it\r\n * from a test would drag `zustand` into the test process.\r\n *\r\n * One handle, one scope: the tab store is seated by the `sidebar.workspaces`\r\n * entry alone. The tab strip is a CHILD of that entry (rendered through a DOM\r\n * portal into the conversation column), not a second slot registration, so the\r\n * handle is never mounted under a second, differently-scoped slot — which the\r\n * registry rejects outright (\"one handle, one scope\").\r\n *\r\n * Placement is navigation, not data: the strip derives its active chip from the\r\n * open session, and arrival order is the strip's only order, so nothing here\r\n * mirrors selection.\r\n */\r\nimport { defineStore, type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport {\r\n closeAfterImpl,\r\n closeOthersImpl,\r\n closeTabImpl,\r\n moveTabImpl,\r\n pinTabImpl,\r\n renameTabImpl,\r\n restoreTabsImpl,\r\n touchTabImpl,\r\n type SessionTab,\r\n type SessionTabsState,\r\n} from './tabs.ts'\r\n\r\nexport type { SessionTabsState }\r\n\r\n/**\r\n * Session-tab strip actions (bound by the framework, handed to the browser).\r\n *\r\n * There is deliberately NO \"drop tabs whose session vanished\" action. An open\r\n * tab is closed by the USER and by nothing else — a program that trims the strip\r\n * on its own eventually eats tabs the user wanted, and the whole point of the\r\n * strip is that it holds what you opened.\r\n *\r\n * This is also why the store needs no catalog at all: it never consults one.\r\n */\r\nexport interface SessionTabsActions {\r\n /** Add the open session, or leave its existing tab untouched in place. */\r\n touch: (sessionId: SessionId) => void\r\n /** Close one tab; navigation is untouchable from here (the caller decides). */\r\n close: (sessionId: SessionId) => void\r\n /**\r\n * Replace the strip with tabs loaded from the host.\r\n *\r\n * The host read is a `fetch`, so it cannot happen inside `init()`. This action\r\n * is how the async result lands, and it is a no-op once the user has already\r\n * opened a tab — a slow response must never discard what they just did.\r\n */\r\n restore: (tabs: readonly SessionTab[]) => void\r\n /** Pin or unpin one tab (re-inserts it at the block boundary). */\r\n pin: (sessionId: SessionId) => void\r\n /** Move one tab to an index in the resulting strip (drag and drop). */\r\n move: (sessionId: SessionId, targetIndex: number) => void\r\n /** Set (or clear, with a blank value) one tab's own label. */\r\n rename: (sessionId: SessionId, title: string | undefined) => void\r\n /** Close everything except one tab; pinned tabs are kept. */\r\n closeOthers: (sessionId: SessionId) => void\r\n /** Close every tab after one in display order. */\r\n closeAfter: (sessionId: SessionId) => void\r\n}\r\n\r\n/** Annotation twin of the actions literal below (structural `ActionsDecl`). */\r\ntype SessionTabsActionsDecl = {\r\n touch: typeof touchTabImpl\r\n close: typeof closeTabImpl\r\n restore: typeof restoreTabsImpl\r\n pin: typeof pinTabImpl\r\n move: typeof moveTabImpl\r\n rename: typeof renameTabImpl\r\n closeOthers: typeof closeOthersImpl\r\n closeAfter: typeof closeAfterImpl\r\n}\r\n\r\n/**\r\n * The tab store's registered handle: identity + spec + the instance factory the\r\n * framework resolves per entry x scope. It deliberately does NOT claim the live\r\n * instance's faces (`getSnapshot` / `actions`) — `defineStore`'s concrete return\r\n * is structurally narrower, and this alias has to stay a type that value can be\r\n * assigned to.\r\n */\r\nexport type SessionTabsStoreHandle = StoreHandle\r\n\r\n/**\r\n * The live tab store value: the handle's `create()` product, which carries the\r\n * baked write set and the snapshot source. Named here so the registrations and\r\n * the strip's props can share one type without importing the store engine.\r\n */\r\nexport type SessionTabsInstance = ReturnType['create']>\r\n\r\n/**\r\n * Create the session-tab store handle.\r\n *\r\n * The strip starts EMPTY and is hydrated by the caller through the `restore`\r\n * action: persistence lives on the host behind a `fetch`, which cannot run\r\n * during `init()`. Browser storage is deliberately not used — the origin\r\n * includes the port, and every launch picks a new one, so `localStorage` and\r\n * `sessionStorage` both start empty on the next start.\r\n *\r\n * @returns the store handle (spec + type + identity + factory in one).\r\n */\r\nexport function createSessionTabsStore(): EngineStoreHandle {\r\n return defineStore({\r\n init: (): SessionTabsState => ({ tabs: [], order: 0 }),\r\n actions: {\r\n touch: touchTabImpl,\r\n close: closeTabImpl,\r\n restore: restoreTabsImpl,\r\n pin: pinTabImpl,\r\n move: moveTabImpl,\r\n rename: renameTabImpl,\r\n closeOthers: closeOthersImpl,\r\n closeAfter: closeAfterImpl,\r\n },\r\n })\r\n}\r\n\r\nexport type { SessionTab }","/**\r\n * Client side of the session-tab persistence, talking to\r\n * `GET|PUT /workspace-groups/tabs` on the host.\r\n *\r\n * Why not browser storage: **the origin includes the PORT**, and every `dsh web`\r\n * / `dsh test` / desktop launch picks a different one. `localStorage` and\r\n * `sessionStorage` are both scoped to the origin, so they start empty on the\r\n * next launch — a tab list kept there survives a reload only when the port\r\n * happens to match. The host's JSON sidecar has no such problem, which is why\r\n * the strip is stored there and read back verbatim.\r\n *\r\n * There is deliberately no per-browser-session marker. A marker has to live in\r\n * browser storage, which the port invalidates, so every restart looked like a\r\n * fresh session and silently discarded the user's tabs — the exact failure this\r\n * module exists to prevent.\r\n *\r\n * Every call is best-effort: a failed read means \"no tabs\" and a failed write is\r\n * swallowed, because the strip is a convenience and must never break the app.\r\n */\r\n\r\n/** Host route holding the strip. */\r\nexport const TABS_ROUTE = '/workspace-groups/tabs'\r\n\r\n/** One tab as it crosses the wire. */\r\nexport interface WireTab {\r\n readonly sessionId: string\r\n readonly order: number\r\n /** Pinned tabs are restored at the front of the strip. */\r\n readonly pinned?: boolean\r\n /** A label the user typed for the tab itself (absent = follow the session). */\r\n readonly title?: string\r\n}\r\n\r\n/**\r\n * Read one tab row off the wire, dropping the row when it is unusable.\r\n * @param entry - one element of the stored `tabs` array.\r\n * @returns the tab, or null for a malformed row.\r\n */\r\nfunction parseWireTab(entry: unknown): WireTab | null {\r\n if (typeof entry !== 'object' || entry === null) return null\r\n const row = entry as Record\r\n if (typeof row.sessionId !== 'string' || row.sessionId === '') return null\r\n if (typeof row.order !== 'number' || !Number.isFinite(row.order)) return null\r\n const pinned = row.pinned === true\r\n const title = typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : undefined\r\n return {\r\n sessionId: row.sessionId,\r\n order: row.order,\r\n ...(pinned ? { pinned: true } : {}),\r\n ...(title !== undefined ? { title } : {}),\r\n }\r\n}\r\n\r\n/**\r\n * Fetch the stored strip.\r\n * @param fetchImpl - fetch implementation (injectable for tests).\r\n * @returns the tabs, oldest first; empty on any failure.\r\n */\r\nexport async function loadTabs(fetchImpl: typeof fetch = fetch): Promise {\r\n try {\r\n const response = await fetchImpl(TABS_ROUTE, {\r\n method: 'GET',\r\n // Per-session state; a cached response would restore stale tabs.\r\n cache: 'no-store',\r\n })\r\n if (!response.ok) return []\r\n const body: unknown = await response.json()\r\n if (typeof body !== 'object' || body === null) return []\r\n const list = (body as { tabs?: unknown }).tabs\r\n if (!Array.isArray(list)) return []\r\n const tabs: WireTab[] = []\r\n for (const entry of list) {\r\n const tab = parseWireTab(entry)\r\n if (tab !== null) tabs.push(tab)\r\n }\r\n return tabs\r\n } catch {\r\n return []\r\n }\r\n}\r\n\r\n/**\r\n * Store the strip. Failures are swallowed.\r\n * @param state - the client's current strip and its arrival counter.\r\n * @param fetchImpl - fetch implementation (injectable for tests).\r\n */\r\nexport async function saveTabs(\r\n state: { order: number; tabs: readonly WireTab[] },\r\n fetchImpl: typeof fetch = fetch,\r\n): Promise {\r\n try {\r\n await fetchImpl(TABS_ROUTE, {\r\n method: 'PUT',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify({ order: state.order, tabs: state.tabs }),\r\n cache: 'no-store',\r\n // Survive a navigation that happens while the request is in flight; the\r\n // write is idempotent so a re-send is harmless.\r\n keepalive: true,\r\n })\r\n } catch {\r\n // Offline or the host is restarting: the next change writes the full state\r\n // again, so nothing is lost beyond this tick.\r\n }\r\n}\r\n","/**\r\n * A framework-shaped selector hook over a store instance.\r\n *\r\n * The renderer builds this hook for slot seats (`bindSnapshotSelector` in\r\n * ui-renderer, wrapping React's `useSyncExternalStoreWithSelector`), but the tab\r\n * strip is NOT a slot occupant: it renders through a DOM seat as a child of this\r\n * plugin's own `sidebar.workspaces` occupant, so it receives its store face as a\r\n * plain prop and needs the equivalent binding here.\r\n *\r\n * The implementation mirrors React's `useSyncExternalStoreWithSelector` without\r\n * depending on the `use-sync-external-store` package (it is not resolvable from\r\n * this plugin). The two behaviours that matter:\r\n *\r\n * - identity-stable subscribe/getSnapshot closures, so the strip never\r\n * resubscribes across renders;\r\n * - a memoized selection: the selector re-runs only when the state reference\r\n * changes, and an equal result (by `eq`, defaulting to `Object.is`) returns\r\n * the PREVIOUS reference, so a selector allocating a fresh array or object\r\n * does not spin the render loop.\r\n *\r\n * The hook must be called unconditionally (Rules of Hooks).\r\n */\r\nimport { useCallback, useRef, useSyncExternalStore } from 'react'\r\nimport type { ActionsDecl, StoreInstance } from '@deepseek-ai/dsh-client-store'\r\n\r\n/** One memory cell: the state it was derived from, and the value it produced. */\r\ninterface Selection {\r\n state: T\r\n value: S\r\n /** Whether `value` was produced by the selector (vs. carried over as equal). */\r\n hasValue: boolean\r\n}\r\n\r\n/**\r\n * Build a selector hook bound to one store instance.\r\n * @param instance - the live store instance (snapshot source).\r\n * @returns a `SnapshotSelectorHook`-compatible hook over that instance.\r\n */\r\nexport function createStoreHook>(\r\n instance: StoreInstance,\r\n): (selector: (state: T) => S, eq?: (a: S, b: S) => boolean) => S {\r\n // Captured once: stable closures keep uSES from resubscribing every render.\r\n const subscribe = (onChange: () => void): (() => void) => instance.subscribe(onChange)\r\n const getState = (): T => instance.getSnapshot()\r\n\r\n return function useSelector(\r\n selector: (state: T) => S,\r\n eq?: (a: S, b: S) => boolean,\r\n ): S {\r\n // Seeded eagerly so the first render selects without an extra pass.\r\n const memory = useRef | null>(null)\r\n\r\n // Re-select the value for the current state. Called by uSES on every\r\n // notification AND on every render; the memory makes it cheap and\r\n // reference-stable.\r\n const getSelection = useCallback((): S => {\r\n const state = getState()\r\n const previous = memory.current\r\n\r\n // Same state object => the previous value is still valid. This is the\r\n // path that lets an allocating selector stay reference-stable.\r\n if (previous !== null && previous.hasValue && Object.is(previous.state, state)) {\r\n return previous.value\r\n }\r\n\r\n const value = selector(state)\r\n\r\n // New state, but an equal value: carry the old reference forward so uSES\r\n // sees no change and skips the re-render.\r\n if (previous !== null && previous.hasValue) {\r\n const equal = eq !== undefined ? eq(previous.value, value) : Object.is(previous.value, value)\r\n if (equal) {\r\n memory.current = { state, value: previous.value, hasValue: true }\r\n return previous.value\r\n }\r\n }\r\n\r\n memory.current = { state, value, hasValue: true }\r\n return value\r\n }, [selector, eq])\r\n\r\n // The third argument is the server snapshot; the client plugin never\r\n // server-renders, so the same getter is correct for both.\r\n return useSyncExternalStore(subscribe, getSelection, getSelection)\r\n }\r\n}\r\n","/**\r\n * Shared config types for @dsh-xhl/workspace-groups. Pure types (zero runtime\r\n * deps) so both halves — the node half (sidecar YAML reading) and the\r\n * browser half (tree derivation) — compile against the same contract.\r\n */\r\n\r\n/** One classification rule: any rule that matches places the workspace in the category. */\r\nexport interface GroupRule {\r\n /** Absolute path prefix match (normalized, case-sensitive). */\r\n pathPrefix?: string\r\n /** Case-insensitive substring match against the workspace display title. */\r\n nameContains?: string\r\n /** Case-insensitive substring match against the workspace directory basename. */\r\n basenameContains?: string\r\n /** Exact absolute path match (normalized). */\r\n pathExact?: string\r\n}\r\n\r\n/** One category folder in the sidebar tree. */\r\nexport interface GroupCategory {\r\n /** Display label of the category folder. */\r\n name: string\r\n /** Rules; a workspace is classified here when ANY rule matches. */\r\n rules: GroupRule[]\r\n}\r\n\r\n/** Theme-safe palette id for a group's accent. */\r\nexport type GroupColor =\r\n | 'red' | 'orange' | 'amber' | 'green' | 'teal'\r\n | 'blue' | 'indigo' | 'purple' | 'pink' | 'gray'\r\n\r\n/** Whitelist shared by the host write-validation and the client picker. */\r\nexport const GROUP_COLORS: readonly GroupColor[] = [\r\n 'red', 'orange', 'amber', 'green', 'teal',\r\n 'blue', 'indigo', 'purple', 'pink', 'gray',\r\n]\r\n\r\n/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */\r\nexport type GroupIconId =\r\n | 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data'\r\n | 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe'\r\n | 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist'\r\n | 'sparkle' | 'tree'\r\n\r\nexport const GROUP_ICON_IDS: readonly GroupIconId[] = [\r\n 'folder', 'workspace', 'code', 'plugin', 'skill', 'data',\r\n 'database', 'api', 'plan', 'goal', 'light', 'globe',\r\n 'archive', 'branch', 'users', 'clock', 'shield', 'checklist',\r\n 'sparkle', 'tree',\r\n]\r\n\r\n/**\r\n * Presentation metadata for one group. Every field optional.\r\n *\r\n * The explicit `| undefined` on each field is what lets a UI patch clear a\r\n * value (`pruneAppearance` then drops it): under `exactOptionalPropertyTypes`\r\n * a bare `color?: GroupColor` would reject `{ color: undefined }`.\r\n */\r\nexport interface CategoryAppearance {\r\n /** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */\r\n color?: GroupColor | undefined\r\n /** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */\r\n icon?: string | undefined\r\n /** Pinned groups sort before unpinned ones (within the manual order). */\r\n pinned?: boolean | undefined\r\n}\r\n\r\n/** The full sidecar configuration (mirrors workspace-groups.yaml). */\r\nexport interface GroupsConfig {\r\n /** Category folders, in render order. First match wins. */\r\n categories: GroupCategory[]\r\n /**\r\n * Runtime grouping overlay (manual groups + per-workspace overrides).\r\n * Optional: the YAML file itself never carries it — the host GET route\r\n * merges it from `workspace-groups.manual.json`, and the browser PUT route\r\n * replaces it whole.\r\n */\r\n manual?: ManualGroups\r\n}\r\n\r\n/**\r\n * Runtime-managed grouping overlay: groups created in the sidebar UI plus\r\n * per-workspace category overrides and user-controlled ordering. Owned by the\r\n * plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never\r\n * written back into the operator YAML.\r\n *\r\n * All new fields are optional for backward compatibility (files written by\r\n * older plugin versions keep working); rendering falls back to sensible\r\n * defaults when they are absent. Note that an older plugin version writes the\r\n * whole file back, which silently drops fields it does not know about — e.g.\r\n * `appearance` (group color / icon / pin) is lost after a downgrade.\r\n */\r\nexport interface ManualGroups {\r\n /**\r\n * Manually created category folder names. These have no rules — they render\r\n * even while empty (a new group appears before anything is dragged into\r\n * it) and hold only workspaces assigned to them.\r\n */\r\n categories: string[]\r\n /**\r\n * Per-workspace category override, keyed by workspace id. Value is a\r\n * category display name (rule or manual), or `null` to force the workspace\r\n * into the uncategorized bucket even when a rule would match. An absent\r\n * key means \"classify by rules\".\r\n */\r\n assignments: Record\r\n /**\r\n * Display order of all category keys (rule display names + manual names).\r\n * The uncategorized bucket is never listed — it always renders last.\r\n * Absent = rule categories first (YAML order), manual groups appended in\r\n * creation order.\r\n */\r\n categoryOrder?: string[]\r\n /**\r\n * Per-category ordered workspace ids (user drag-reorder within a group).\r\n * Keyed by category display name; absent key = host registration order.\r\n */\r\n workspaceOrder?: Record\r\n /**\r\n * Rule category rename overrides: original YAML rule category name →\r\n * display name (UI rename of a rule group). Rules still classify by the\r\n * original name; only the rendered label/keys change.\r\n */\r\n renamed?: Record\r\n /**\r\n * Rule category original names hidden by a UI delete. Hidden rules are\r\n * inert: workspaces matching them become top-level (ungrouped).\r\n */\r\n hidden?: string[]\r\n /**\r\n * Per-group presentation, keyed by category DISPLAY name (same key space as\r\n * `categoryOrder`). Optional per field; an absent group has no presentation.\r\n * Dangling keys (a YAML category that no longer exists) are tolerated on read\r\n * and on write — see validateManualGroups.\r\n */\r\n appearance?: Record\r\n}\r\n\r\n/**\r\n * Legacy label of the fallback bucket. The top-level (ungrouped) concept\r\n * replaced the rendered \"未分类\" bucket: workspaces in no group render as\r\n * top-level rows beside the group folders. The constant survives for data\r\n * compatibility (reserved name, assignment null marker).\r\n */\r\nexport const UNCATEGORIZED_LABEL = '未分类'\r\n\r\n/**\r\n * Reserved key under `workspaceOrder` holding the manual order of TOP-LEVEL\r\n * (ungrouped) project rows. Distinct from any real group display name (a group\r\n * may not be named this), so it can never collide; the top-level list's order\r\n * is preserved exactly like a group's, and top-level rows can be reordered by\r\n * dragging.\r\n */\r\nexport const TOP_LEVEL_ORDER_KEY = '__topLevel__'\r\n\r\n/** Normalize a path for prefix matching: trailing slashes stripped. */\r\nexport function normalizePath(path: string): string {\r\n return path.replace(/[/\\\\]+$/, '')\r\n}\r\n","/**\r\n * Pure classification + ordering logic: decides which category a workspace\r\n * belongs to and how categories/workspaces are ordered. Shared by the host\r\n * half (validation) and the client half (tree derivation), so the semantics\r\n * can never drift between the config surface and the rendered tree.\r\n *\r\n * Category identity: a category's STABLE origin is its YAML rule category\r\n * name (or a manual-group name). Its DISPLAY key is what the tree renders and\r\n * what assignments reference — for rule categories that is the rename\r\n * override when present. Hidden rule categories are inert: workspaces that\r\n * would match them become top-level (ungrouped).\r\n */\r\nimport {\r\n normalizePath,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupCategory,\r\n type GroupRule,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from './types.ts'\r\n\r\n/** One rule match against a workspace's path and title. */\r\nfunction ruleMatches(rule: GroupRule, path: string, title: string): boolean {\r\n const normalized = normalizePath(path)\r\n if (rule.pathPrefix !== undefined && normalized.startsWith(normalizePath(rule.pathPrefix))) return true\r\n if (rule.pathExact !== undefined && normalized === normalizePath(rule.pathExact)) return true\r\n if (rule.nameContains !== undefined && title.toLowerCase().includes(rule.nameContains.toLowerCase())) return true\r\n if (rule.basenameContains !== undefined) {\r\n const base = path.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop() ?? ''\r\n if (base.toLowerCase().includes(rule.basenameContains.toLowerCase())) return true\r\n }\r\n return false\r\n}\r\n\r\n/** Classify a workspace by rules only; hidden categories are inert. */\r\nexport function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {\r\n for (const category of categories) {\r\n if (category.rules.some(rule => ruleMatches(rule, path, title))) return category\r\n }\r\n return undefined\r\n}\r\n\r\n/** Display name of a rule category: the rename override when present. */\r\nexport function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string {\r\n return manual?.renamed?.[originalName] ?? originalName\r\n}\r\n\r\n/** Whether a rule category has been hidden by a UI delete. */\r\nexport function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean {\r\n return manual?.hidden?.includes(originalName) ?? false\r\n}\r\n\r\n/** Presentation for a category display key, or undefined when unset. */\r\nexport function categoryAppearance(\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): CategoryAppearance | undefined {\r\n return manual?.appearance?.[key]\r\n}\r\n\r\n/** Whether a category display key is pinned. */\r\nexport function isCategoryPinned(manual: ManualGroups | undefined, key: string): boolean {\r\n return categoryAppearance(manual, key)?.pinned === true\r\n}\r\n\r\n/**\r\n * Drop empty presentation fields: `undefined` values, `pinned: false`, `icon: ''`.\r\n * Returns undefined when nothing is left, so callers can delete the whole entry.\r\n */\r\nexport function pruneAppearance(value: CategoryAppearance): CategoryAppearance | undefined {\r\n const result: CategoryAppearance = {}\r\n if (value.color !== undefined) result.color = value.color\r\n if (value.icon !== undefined && value.icon.trim() !== '') result.icon = value.icon\r\n if (value.pinned === true) result.pinned = true\r\n return Object.keys(result).length === 0 ? undefined : result\r\n}\r\n\r\n/** Rule category display names, in YAML render order (hidden ones excluded). */\r\nexport function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[] {\r\n const names: string[] = []\r\n for (const category of categories) {\r\n if (isHiddenRule(manual, category.name)) continue\r\n names.push(ruleDisplayName(manual, category.name))\r\n }\r\n return names\r\n}\r\n\r\n/** Original YAML rule name whose display name equals `key` (undefined when none). */\r\nexport function originalRuleNameForDisplay(\r\n categories: readonly GroupCategory[],\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): string | undefined {\r\n return categories.find(c => ruleDisplayName(manual, c.name) === key)?.name\r\n}\r\n\r\n/**\r\n * Effective category entries in display order: rule categories (YAML order,\r\n * hidden skipped, renamed applied) first, then manual-only groups in\r\n * creation order — unless `manual.categoryOrder` overrides the sequence.\r\n * Top-level (ungrouped) workspaces are never included; they render as\r\n * separate top-level rows after the group folders.\r\n *\r\n * The pin partition is part of DISPLAY ORDER, not a render-time concern:\r\n * pinned groups sort before unpinned ones *within* the manual order, and both\r\n * the tree and the drag-drop landing neighbours read this list, so they can\r\n * never disagree about what sits next to what.\r\n */\r\nexport interface EffectiveCategory {\r\n /** Display key (what the tree renders and assignments reference). */\r\n key: string\r\n /** Origin: a YAML rule category or a manual group. */\r\n source: 'rule' | 'manual'\r\n}\r\n\r\n/** Apply `manual.categoryOrder` to the default sequence (stable). */\r\nfunction orderByCategoryOrder(\r\n entries: EffectiveCategory[],\r\n order: readonly string[] | undefined,\r\n): EffectiveCategory[] {\r\n if (order === undefined || order.length === 0) return entries\r\n // Stable sort by position in categoryOrder; entries absent from the order\r\n // keep their relative default position after all ordered ones.\r\n const position = new Map(order.map((key, index) => [key, index]))\r\n return [...entries].sort((a, b) => {\r\n const pa = position.get(a.key)\r\n const pb = position.get(b.key)\r\n if (pa !== undefined && pb !== undefined) return pa - pb\r\n if (pa !== undefined) return -1\r\n if (pb !== undefined) return 1\r\n return 0\r\n })\r\n}\r\n\r\n/** Stable partition: pinned groups first, unpinned ones keep their order. */\r\nfunction pinnedFirst(entries: EffectiveCategory[], manual: ManualGroups | undefined): EffectiveCategory[] {\r\n if (manual?.appearance === undefined) return entries\r\n const pinned = (entry: EffectiveCategory): number => Number(isCategoryPinned(manual, entry.key))\r\n return [...entries].sort((a, b) => pinned(b) - pinned(a))\r\n}\r\n\r\nexport function effectiveCategories(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n): EffectiveCategory[] {\r\n const entries: EffectiveCategory[] = []\r\n const seen = new Set()\r\n for (const category of config.categories) {\r\n if (isHiddenRule(manual, category.name)) continue\r\n const key = ruleDisplayName(manual, category.name)\r\n if (seen.has(key)) continue\r\n seen.add(key)\r\n entries.push({ key, source: 'rule' })\r\n }\r\n for (const name of manual?.categories ?? []) {\r\n if (seen.has(name)) continue\r\n seen.add(name)\r\n entries.push({ key: name, source: 'manual' })\r\n }\r\n return pinnedFirst(orderByCategoryOrder(entries, manual?.categoryOrder), manual)\r\n}\r\n\r\n/** Display keys of all effective categories (top-level workspaces excluded). */\r\nexport function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[] {\r\n return effectiveCategories(config, manual).map(e => e.key)\r\n}\r\n\r\n/**\r\n * Resolve the category key a workspace renders under, or `undefined` when it\r\n * is top-level (ungrouped). Precedence: manual override (`null` = forced\r\n * top-level) → rule classification (hidden rules inert) → top-level.\r\n */\r\nexport function resolveCategory(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n workspaceId: string,\r\n path: string,\r\n title: string,\r\n): string | undefined {\r\n const override = manual?.assignments[workspaceId]\r\n if (override !== undefined) return override ?? undefined // null forces top-level\r\n const matched = classify(config.categories, path, title)\r\n if (matched === undefined) return undefined\r\n if (isHiddenRule(manual, matched.name)) return undefined\r\n return ruleDisplayName(manual, matched.name)\r\n}\r\n\r\n/** Whether a category key is a manual-only group (manageable via list). */\r\nexport function isManualOnlyCategory(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): boolean {\r\n return (manual?.categories.includes(key) ?? false) && !ruleDisplayNames(config.categories, manual).includes(key)\r\n}\r\n\r\n/**\r\n * Names that may not be used for a new/renamed group: the legacy reserved\r\n * label plus every current display key.\r\n */\r\nexport function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set {\r\n const taken = new Set(displayCategoryKeys(config, manual))\r\n taken.add(UNCATEGORIZED_LABEL)\r\n return taken\r\n}\r\n\r\n/**\r\n * Order a bucket of workspace ids: the stored per-category order first\r\n * (filtered to actual members), then any remaining members in `fallback`\r\n * (host) order. Deterministic; the renderer never re-sorts on its own.\r\n */\r\nexport function orderedWorkspaceIds(\r\n manual: ManualGroups | undefined,\r\n categoryKey: string,\r\n members: readonly string[],\r\n): string[] {\r\n const stored = manual?.workspaceOrder?.[categoryKey]\r\n if (stored === undefined || stored.length === 0) return [...members]\r\n const memberSet = new Set(members)\r\n const ordered: string[] = []\r\n const seen = new Set()\r\n for (const id of stored) {\r\n if (!memberSet.has(id) || seen.has(id)) continue\r\n seen.add(id)\r\n ordered.push(id)\r\n }\r\n for (const id of members) {\r\n if (seen.has(id)) continue\r\n ordered.push(id)\r\n }\r\n return ordered\r\n}\r\n\r\n/** Move `id` before `beforeId` (undefined = append) within an ordered list. */\r\nexport function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[] {\r\n const rest = list.filter(x => x !== id)\r\n if (beforeId === undefined) return [...rest, id]\r\n const index = rest.indexOf(beforeId)\r\n if (index === -1) return [...rest, id]\r\n rest.splice(index, 0, id)\r\n return rest\r\n}\r\n\r\n/** Move `id` after `afterId` (undefined = append) within an ordered list. */\r\nexport function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[] {\r\n const rest = list.filter(x => x !== id)\r\n if (afterId === undefined) return [...rest, id]\r\n const index = rest.indexOf(afterId)\r\n if (index === -1) return [...rest, id]\r\n rest.splice(index + 1, 0, id)\r\n return rest\r\n}\r\n","/**\r\n * Plugin-owned projection of descendant counts from Session summaries.\r\n *\r\n * 0.1.2 移除了 `@deepseek-ai/dsh-client-runtime/client`(平台模块表不再提供\r\n * `indexSubagentDescendants`),官方 ui-workspace 改为各自持有本地副本\r\n * (packages/client/ui-workspace/src/client/subagent-lineage.ts,MIT)。这里\r\n * 保持同一实现,使运行中的子代理会话数在树行上继续可见。\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\n\r\ninterface LineageEntry {\r\n readonly id: SessionId\r\n readonly parentId?: SessionId\r\n readonly origin?: 'subagent'\r\n readonly running: boolean\r\n}\r\n\r\n/** Descendant counts for one possible parent Session. */\r\nexport interface SubagentDescendantSummary {\r\n readonly count: number\r\n readonly runningCount: number\r\n}\r\n\r\n/**\r\n * Index uninterrupted subagent descendants under each ancestor.\r\n * @param summaries - Session summaries keyed by id.\r\n * @returns descendant totals keyed by possible parent id.\r\n */\r\nexport function indexSubagentDescendants(\r\n summaries: Readonly>,\r\n): ReadonlyMap {\r\n const indexed = new Map()\r\n for (const descendant of Object.values(summaries)) {\r\n if (descendant.origin !== 'subagent') continue\r\n const seen = new Set()\r\n let current: LineageEntry | undefined = descendant\r\n while (current?.origin === 'subagent' && current.parentId !== undefined && !seen.has(current.id)) {\r\n seen.add(current.id)\r\n const aggregate = indexed.get(current.parentId)\r\n if (aggregate === undefined) {\r\n indexed.set(current.parentId, { count: 1, runningCount: descendant.running ? 1 : 0 })\r\n } else {\r\n aggregate.count += 1\r\n if (descendant.running) aggregate.runningCount += 1\r\n }\r\n current = summaries[current.parentId]\r\n }\r\n }\r\n return indexed\r\n}\r\n","/**\r\n * Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →\r\n * 会话行. Pure derivation — all inputs are snapshots; the renderer never\r\n * scans. Session visibility rules mirror the official ui-workspace tree\r\n * (blank rows only when current, archived excluded, subagent rows excluded).\r\n */\r\nimport type {\r\n SessionListState,\r\n SessionSearchResultItem,\r\n SessionSummary,\r\n} from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\n// Type-only: the unified UI status snapshot. 0.1.6 把 running / pendingInteraction /\r\n// 未读完成提示收敛为 ui-session 的 SessionStatusSnapshot;SessionSummary.completed\r\n// 与 SessionListState.current 同时移除,当前会话改由 `mainView` 保留位推导。\r\nimport type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport { indexSubagentDescendants, type SubagentDescendantSummary } from './subagent-lineage.ts'\r\nimport { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'\r\nimport {\r\n TOP_LEVEL_ORDER_KEY,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from '../core/types.ts'\r\n\r\n/** Pending interaction kinds with dedicated Workspace-row presentation. */\r\nexport type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question'\r\n\r\n/** Current unified UI status by Session (ui-session snapshot). */\r\ntype SessionStatuses = SessionStatusSnapshot\r\n\r\n/**\r\n * The Session the Conversation is currently showing.\r\n *\r\n * 0.1.6 removed `SessionListState.current`: selection is expressed as the\r\n * Session retained through the `mainView` reference source (the ui-workspace\r\n * navigation holds exactly one). Same read the official browser performs.\r\n * @param list - sessions list snapshot.\r\n * @returns the retained Session id, or undefined while no Session is selected.\r\n */\r\nexport function currentSessionId(list: SessionListState): SessionId | undefined {\r\n return Object.values(list.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id\r\n}\r\n\r\n/** Keep navigation presentation independent from domain-owned interaction objects. */\r\nfunction visiblePendingKind(kind: string | undefined): SessionPendingInteractionStatus | undefined {\r\n switch (kind) {\r\n case 'approval':\r\n case 'plan-review':\r\n case 'question':\r\n return kind\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/** One top-level session row inside a workspace folder. */\r\nexport interface SessionNode {\r\n id: SessionId\r\n /** Stored display title; blank rows show the localized New Session label. */\r\n title: string\r\n /** The provisional blank session (renderer shows the localized New Session title). */\r\n blank: boolean\r\n pendingInteraction?: SessionPendingInteractionStatus\r\n running: boolean\r\n /** Running descendants connected through uninterrupted subagent-origin lineage. */\r\n runningSubagentCount: number\r\n /** Finished running while not selected and not yet opened (the green \"done\" reminder dot). */\r\n completed: boolean\r\n updatedAt: number\r\n /** Search-hit marker (rendered with a highlighted tint in search mode). */\r\n matched?: boolean\r\n /** Content-match snippet from the Host search (search mode only). */\r\n snippet?: string\r\n}\r\n\r\n/** One workspace folder row inside a category folder. */\r\nexport interface WorkspaceGroupNode {\r\n workspaceId: WorkspaceId\r\n /** Canonical host directory path. */\r\n path: string\r\n /** Display title. */\r\n label: string\r\n /** Workspace creation time (epoch ms). */\r\n createdAt: number\r\n /** Total visible sessions in the folder. */\r\n sessionCount: number\r\n expanded: boolean\r\n /** The folder contains the selected session (active folder tint). */\r\n containsCurrent: boolean\r\n /** Visible session rows (empty while the folder is folded). */\r\n sessions: readonly SessionNode[]\r\n}\r\n\r\n/** One category folder at the top of the tree. */\r\nexport interface CategoryNode {\r\n /** Stable category key: the configured label, or the uncategorized bucket. */\r\n key: string\r\n /** Display label. */\r\n label: string\r\n expanded: boolean\r\n /** The category contains the selected session (active folder tint). */\r\n containsCurrent: boolean\r\n /** Workspace folders in host order. */\r\n workspaces: readonly WorkspaceGroupNode[]\r\n /** Presentation (color / icon / pin) for this category, when configured. */\r\n appearance?: CategoryAppearance\r\n}\r\n\r\n/** Viewing state consumed by the derivation. */\r\nexport interface GroupsTreeView {\r\n expandedCategories: readonly string[]\r\n expandedWorkspaces: readonly string[]\r\n}\r\n\r\n/** Key of the uncategorized bucket (matches the config fallback label). */\r\nexport const UNCATEGORIZED_KEY = UNCATEGORIZED_LABEL\r\n\r\n/** Directory display label: basename of the path (both separators accepted). */\r\nexport function workspaceLabel(cwd: string | undefined): string {\r\n if (cwd === undefined || cwd === '') return UNCATEGORIZED_LABEL\r\n const base = cwd.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop()\r\n return base !== undefined && base !== '' ? base : cwd\r\n}\r\n\r\n/** Ordinary sessions are visible; blank only when current; archived/subagent never. */\r\nfunction sessionVisible(session: SessionSummary, current: SessionId | undefined, archived: ReadonlySet): boolean {\r\n return session.origin !== 'subagent'\r\n && !archived.has(session.id)\r\n && (!session.blank || session.id === current)\r\n}\r\n\r\n/** Blank rows display the localized New Session label (never enters search). */\r\nfunction sessionTitle(session: SessionSummary): string {\r\n return session.blank ? 'New Session' : session.displayTitle\r\n}\r\n\r\nfunction sessionNode(\r\n s: SessionSummary,\r\n descendants: ReadonlyMap,\r\n statuses: SessionStatuses,\r\n): SessionNode {\r\n // `SessionStatusSnapshot` is typed as ReadonlyMap, but the framework binds a\r\n // plain record at runtime (client.js: `statuses[sessionId]`). Read both shapes\r\n // so a hook backed by an object never throws \"statuses.get is not a function\".\r\n const status = typeof (statuses as { get?: unknown } | undefined)?.get === 'function'\r\n ? statuses.get(s.id)\r\n : (statuses as unknown as Record)[s.id]\r\n const pending = visiblePendingKind(status?.pendingInteraction?.kind)\r\n return {\r\n id: s.id,\r\n title: sessionTitle(s),\r\n blank: s.blank,\r\n running: status?.running ?? s.running,\r\n runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,\r\n completed: status?.completionUnread === true,\r\n updatedAt: s.updatedAt,\r\n ...(pending === undefined ? {} : { pendingInteraction: pending }),\r\n }\r\n}\r\n\r\n/** Visible sessions of one workspace in its stored account order. */\r\nfunction workspaceSessions(\r\n list: SessionListState,\r\n workspace: WorkspaceView,\r\n archived: ReadonlySet,\r\n descendants: ReadonlyMap,\r\n statuses: SessionStatuses,\r\n current: SessionId | undefined,\r\n): SessionNode[] {\r\n const nodes: SessionNode[] = []\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined) continue // account may lead the list pull; appears when the summary lands\r\n if (!sessionVisible(summary, current, archived)) continue\r\n nodes.push(sessionNode(summary, descendants, statuses))\r\n }\r\n return nodes\r\n}\r\n\r\n/**\r\n * Derive the three-level tree.\r\n * @param list - sessions list snapshot (`current` feeds containsCurrent).\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param archivedSessionIds - registry-global archive set.\r\n * @param config - sidecar grouping config (rule categories).\r\n * @param view - local expansion arrays.\r\n * @param manual - runtime overlay (manual groups + overrides). A workspace's\r\n * manual override wins over rule classification; removing it reverts to rules.\r\n * @param statuses - unified UI status by Session (drives the running / warning\r\n * / unread-completion row indicators); defaults to none (tests).\r\n * @returns category sections in render order (rule categories first, then\r\n * manual-only ones, uncategorized last). Manual groups render even while\r\n * empty; empty rule buckets stay hidden.\r\n */\r\nexport function deriveGroups(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n archivedSessionIds: readonly SessionId[],\r\n config: GroupsConfig,\r\n view: GroupsTreeView,\r\n manual: ManualGroups,\r\n statuses: SessionStatuses = new Map(),\r\n): CategoryNode[] {\r\n const archived = new Set(archivedSessionIds)\r\n const expandedCategories = new Set(view.expandedCategories)\r\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n // Bucket workspaces by display key. Seed with every effective category so\r\n // manual groups render while empty. Top-level (ungrouped) workspaces are\r\n // handled by deriveTopLevel and never land here.\r\n const byCategory = new Map()\r\n for (const { key } of effectiveCategories(config, manual)) {\r\n byCategory.set(key, [])\r\n }\r\n for (const workspace of workspaces) {\r\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n if (key === undefined) continue // top-level — rendered by deriveTopLevel\r\n if (!byCategory.has(key)) byCategory.set(key, [])\r\n byCategory.get(key)!.push(workspace)\r\n }\r\n\r\n const manualCategories = new Set(manual.categories)\r\n const currentWorkspaceId = current === undefined\r\n ? undefined\r\n : workspaces.find(w => w.sessionIds.includes(current))?.workspaceId\r\n\r\n const nodes: CategoryNode[] = []\r\n // Effective categories in display order (categoryOrder applied).\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) {\r\n const bucket = byCategory.get(key) ?? []\r\n // Manual groups stay visible while empty; everything else hides when empty.\r\n if (bucket.length === 0 && !manualCategories.has(key)) continue\r\n const expanded = expandedCategories.has(key)\r\n const ordered = orderedWorkspaceIds(manual, key, bucket.map(w => w.workspaceId as string))\r\n const workspaceNodes: WorkspaceGroupNode[] = []\r\n let containsCurrent = false\r\n for (const workspaceId of ordered) {\r\n const workspace = bucket.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) continue\r\n const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)\r\n const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)\r\n const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId\r\n if (wsContainsCurrent) containsCurrent = true\r\n workspaceNodes.push({\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: sessions.length,\r\n expanded: wsExpanded,\r\n containsCurrent: wsContainsCurrent,\r\n sessions: wsExpanded ? sessions : [],\r\n })\r\n }\r\n const appearance = categoryAppearance(manual, key)\r\n nodes.push({\r\n key,\r\n label: key,\r\n expanded,\r\n containsCurrent,\r\n workspaces: workspaceNodes,\r\n ...(appearance === undefined ? {} : { appearance }),\r\n })\r\n }\r\n return nodes\r\n}\r\n\r\n/**\r\n * Top-level (ungrouped) workspace rows: workspaces resolving to no category\r\n * (no manual override and no matching rule, or a forced `null` override).\r\n * Rendered after the group folders as plain project rows (not inside any\r\n * folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`),\r\n * falling back to host registration order.\r\n */\r\nexport function deriveTopLevel(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n archivedSessionIds: readonly SessionId[],\r\n config: GroupsConfig,\r\n view: GroupsTreeView,\r\n manual: ManualGroups,\r\n statuses: SessionStatuses = new Map(),\r\n): WorkspaceGroupNode[] {\r\n const archived = new Set(archivedSessionIds)\r\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n const currentWorkspaceId = current === undefined\r\n ? undefined\r\n : workspaces.find(w => w.sessionIds.includes(current))?.workspaceId\r\n\r\n const topLevelIds = workspaces\r\n .filter(w => resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)\r\n .map(w => w.workspaceId as string)\r\n const ordered = orderedWorkspaceIds(manual, TOP_LEVEL_ORDER_KEY, topLevelIds)\r\n\r\n const nodes: WorkspaceGroupNode[] = []\r\n for (const workspaceId of ordered) {\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) continue\r\n const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)\r\n const wsExpanded = expandedWorkspaces.has(workspaceId)\r\n nodes.push({\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: sessions.length,\r\n expanded: wsExpanded,\r\n containsCurrent: workspace.workspaceId === currentWorkspaceId,\r\n sessions: wsExpanded ? sessions : [],\r\n })\r\n }\r\n return nodes\r\n}\r\n\r\n/** Recency comparator: newest first, id as the deterministic tiebreak. */\r\nfunction byRecency(a: SessionSummary, b: SessionSummary): number {\r\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\r\n return a.id < b.id ? -1 : 1\r\n}\r\n\r\n/** Bounded set of matched sessions plus content snippets (feeds the search tree). */\r\nexport interface SearchMatchSet {\r\n /** Session ids that matched (local metadata hits + Host content hits). */\r\n matchedIds: ReadonlySet\r\n /** Content-match snippets keyed by session id (Host search only). */\r\n snippetsBySession: ReadonlyMap\r\n hasMore: boolean\r\n}\r\n\r\n/**\r\n * Compute the matched-session set: immediate title/Workspace substring matches\r\n * from the local list, merged with ranked Host content matches. The consumer\r\n * (SearchBody) derives the pruned three-level tree from these ids.\r\n */\r\nexport function deriveSearchMatches(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n config: GroupsConfig,\r\n query: string,\r\n archivedSessionIds: readonly SessionId[],\r\n content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },\r\n limit: number,\r\n): SearchMatchSet {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }\r\n const archived = new Set(archivedSessionIds)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n const workspaceBySession = new Map()\r\n for (const workspace of workspaces) {\r\n for (const sessionId of workspace.sessionIds) {\r\n if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)\r\n }\r\n }\r\n const labelOf = (summary: SessionSummary): string =>\r\n workspaceBySession.get(summary.id)?.title ?? workspaceLabel(summary.cwd)\r\n\r\n const local: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || summary.blank || !sessionVisible(summary, current, archived)) continue\r\n if (\r\n sessionTitle(summary).toLowerCase().includes(q)\r\n || labelOf(summary).toLowerCase().includes(q)\r\n ) {\r\n local.push(summary)\r\n }\r\n }\r\n local.sort(byRecency)\r\n\r\n const ordered: SessionSummary[] = []\r\n const included = new Set()\r\n const include = (summary: SessionSummary): void => {\r\n if (included.has(summary.id)) return\r\n included.add(summary.id)\r\n ordered.push(summary)\r\n }\r\n for (const summary of local) include(summary)\r\n for (const item of content.items) {\r\n const summary = list.byId[item.sessionId]\r\n if (summary !== undefined && !summary.blank && sessionVisible(summary, current, archived)) include(summary)\r\n }\r\n\r\n const snippets = new Map()\r\n for (const item of content.items) {\r\n if (item.snippet !== undefined) snippets.set(item.sessionId, item.snippet)\r\n }\r\n\r\n return {\r\n matchedIds: ordered.slice(0, limit).reduce((set, summary) => { set.add(summary.id); return set }, new Set()),\r\n snippetsBySession: snippets,\r\n hasMore: content.hasMore || ordered.length > limit,\r\n }\r\n}\r\n\r\n/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */\r\nexport interface SearchTree {\r\n /** Group folders containing matched sessions, in display order. */\r\n categories: CategoryNode[]\r\n /** Top-level (ungrouped) workspaces holding matched sessions. */\r\n topLevel: WorkspaceGroupNode[]\r\n}\r\n\r\n/**\r\n * Build a three-level search tree containing ONLY the branches that hold a\r\n * matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched\r\n * session carries `matched: true` so rows render with the search-hit tint.\r\n * Classification uses the same precedence as the idle tree (manual override →\r\n * rules), so search shows the same grouping the user sees. Matched top-level\r\n * workspaces are returned separately (rendered as plain rows).\r\n *\r\n * @param list - sessions list snapshot.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param config - sidecar grouping config.\r\n * @param matchedIds - set of session ids that matched the query.\r\n * @param archivedSessionIds - registry-global archive set.\r\n * @param manual - runtime overlay (manual groups + overrides).\r\n * @param snippetsBySession - optional content-match snippets keyed by session id.\r\n * @param statuses - unified UI status by Session (drives the running / warning\r\n * / unread-completion row indicators); defaults to none (tests).\r\n * @returns group folders in render order plus top-level matched workspaces,\r\n * pruned to matched branches only.\r\n */\r\nexport function deriveSearchGroups(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n config: GroupsConfig,\r\n matchedIds: ReadonlySet,\r\n archivedSessionIds: readonly SessionId[],\r\n manual: ManualGroups,\r\n snippetsBySession?: ReadonlyMap,\r\n statuses: SessionStatuses = new Map(),\r\n): SearchTree {\r\n const archived = new Set(archivedSessionIds)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n const byCategory = new Map()\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])\r\n\r\n const topLevel: WorkspaceGroupNode[] = []\r\n for (const workspace of workspaces) {\r\n // Only sessions that matched the query and are visible in this folder.\r\n const nodes: SessionNode[] = []\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || !matchedIds.has(id)) continue\r\n if (!sessionVisible(summary, current, archived)) continue\r\n const node = sessionNode(summary, descendants, statuses)\r\n const snippet = snippetsBySession?.get(id)\r\n nodes.push({\r\n ...node,\r\n matched: true,\r\n ...(snippet === undefined ? {} : { snippet }),\r\n })\r\n }\r\n if (nodes.length === 0) continue\r\n\r\n const node: WorkspaceGroupNode = {\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: nodes.length,\r\n expanded: true,\r\n containsCurrent: false,\r\n sessions: nodes,\r\n }\r\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n if (key === undefined) {\r\n topLevel.push(node)\r\n continue\r\n }\r\n if (!byCategory.has(key)) byCategory.set(key, [])\r\n byCategory.get(key)!.push(node)\r\n }\r\n\r\n const categories: CategoryNode[] = []\r\n // Same display order as the idle tree.\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) {\r\n const workspaceNodes = byCategory.get(key)\r\n if (workspaceNodes === undefined || workspaceNodes.length === 0) continue\r\n const appearance = categoryAppearance(manual, key)\r\n categories.push({\r\n key,\r\n label: key,\r\n expanded: true,\r\n containsCurrent: false,\r\n workspaces: workspaceNodes,\r\n ...(appearance === undefined ? {} : { appearance }),\r\n })\r\n }\r\n return { categories, topLevel }\r\n}\r\n","/**\r\n * Row components for the workspace-groups tree. Kept dependency-light: they\r\n * consume only React, primitives (StateDot/Menu/icons), and the shared CSS\r\n * string. Each row owns its hover actions menu; dialogs live in the browser\r\n * root so they survive row unmounts during collapse.\r\n *\r\n * Drag & drop: workspace rows are draggable sources; category rows (and\r\n * workspace rows, standing for their containing category) are drop targets.\r\n * The payload is a custom dataTransfer type so only in-plugin drags land.\r\n */\r\nimport { useEffect, useRef, useState, type AnimationEvent, type DragEvent, type ReactNode } from 'react'\r\nimport {\r\n IconApiOutlineMedium,\r\n IconArchiveOutlineRegular,\r\n IconArchiveOutlineMedium,\r\n IconBranchOutlineMedium,\r\n IconBranchOutlineRegular,\r\n IconChecklistOutlineMedium,\r\n IconClockOutlineMedium,\r\n IconCodeOutlineMedium,\r\n IconCordisPluginOutlineMedium,\r\n IconDataOutlineMedium,\r\n IconDatabaseOutlineMedium,\r\n IconEditOutlineRegular,\r\n IconEllipsisOutlineRegular,\r\n IconFolderCloseMedium,\r\n IconFolderOpenMedium,\r\n IconFolderOpenOutlineRegular,\r\n IconGlobeOutlineMedium,\r\n IconGoalOutlineMedium,\r\n IconLightOutlineMedium,\r\n IconPinFillMedium,\r\n IconPinOutlineRegular,\r\n IconPlanOutlineMedium,\r\n IconPlusOutlineRegular,\r\n IconProjectAddOutlineRegular,\r\n IconRightUpOutlineRegular,\r\n IconShieldOutlineMedium,\r\n IconSkillOutlineMedium,\r\n IconSlidersTwoOutlineRegular,\r\n IconSparkleMedium,\r\n IconTreeCornerMedium,\r\n IconTriangleRightFillMedium,\r\n IconTrashOutlineRegular,\r\n IconUsersOutlineMedium,\r\n IconWorkspaceTreeOutlineMedium,\r\n Menu,\r\n StateDot,\r\n type MenuEntry,\r\n type StateDotState,\r\n} from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\r\nimport type { WorkspaceGroupsKey } from './locales.ts'\r\nimport type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'\r\n\r\ntype T = TranslateNS<'workspaceGroups'>\r\n\r\n/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */\r\nexport const DND_WORKSPACE_TYPE = 'application/x-dsh-workspace-groups'\r\n/** dataTransfer type carrying the dragged category key (group reorder). */\r\nexport const DND_CATEGORY_TYPE = 'application/x-dsh-workspace-groups-category'\r\n\r\n/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */\r\nexport function hasPluginDragType(types: DOMStringList | readonly string[]): boolean {\r\n const list = Array.from(types as Iterable)\r\n return list.includes(DND_WORKSPACE_TYPE) || list.includes(DND_CATEGORY_TYPE)\r\n}\r\n\r\n/** Pending interaction status → primitives StateDot state. */\r\nfunction pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {\r\n switch (status) {\r\n case 'approval':\r\n case 'plan-review':\r\n case 'question':\r\n return 'warning'\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/** Primary status dot state for a session row. */\r\nexport function sessionDotState(node: Pick): StateDotState {\r\n if (pendingState(node.pendingInteraction) !== undefined) return 'warning'\r\n if (node.running || node.runningSubagentCount > 0) return 'ongoing'\r\n return node.completed ? 'done' : 'done'\r\n}\r\n\r\n/** Compact relative time (\"now\"/\"5min\"/\"3h\"/\"2d\"/\"4mo\"/\"1y\"). */\r\nexport function relativeTimeLabel(updatedAt: number, now: number): string {\r\n const diff = Math.max(0, now - updatedAt)\r\n const MIN = 60_000\r\n const HOUR = 3_600_000\r\n const DAY = 86_400_000\r\n if (diff < MIN) return 'now'\r\n if (diff < HOUR) return `${Math.floor(diff / MIN)}min`\r\n if (diff < DAY) return `${Math.floor(diff / HOUR)}h`\r\n if (diff < 30 * DAY) return `${Math.floor(diff / DAY)}d`\r\n if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`\r\n return `${Math.floor(diff / (365 * DAY))}y`\r\n}\r\n\r\n/** Drop-target props shared by category and workspace rows (all optional). */\r\nexport interface RowDropProps {\r\n /** Row is under the dragged workspace — show the drop highlight. */\r\n dropActive?: boolean\r\n /** Insertion indicator: a line above (before) or below (after) this row. */\r\n insertLine?: 'before' | 'after'\r\n /** Accept a drag over this row (must preventDefault to allow the drop). */\r\n onRowDragOver?: (event: DragEvent) => void\r\n /** Clear the highlight when the pointer leaves the row. */\r\n onRowDragLeave?: (event: DragEvent) => void\r\n /** Drop a workspace onto this row. */\r\n onRowDrop?: (event: DragEvent) => void\r\n}\r\n\r\n/**\r\n * Preset group icon ids → primitives artwork. Medium stroke to match the\r\n * folder glyph used by unprefixed groups. Keyed by plain string so an id from\r\n * a newer host (or a hand-edited JSON file) degrades instead of throwing.\r\n */\r\nconst CATEGORY_ICONS: Record = {\r\n folder: ,\r\n workspace: ,\r\n code: ,\r\n plugin: ,\r\n skill: ,\r\n data: ,\r\n database: ,\r\n api: ,\r\n plan: ,\r\n goal: ,\r\n light: ,\r\n globe: ,\r\n archive: ,\r\n branch: ,\r\n users: ,\r\n clock: ,\r\n shield: ,\r\n checklist: ,\r\n sparkle: ,\r\n tree: ,\r\n}\r\n\r\n/**\r\n * Resolve a stored `appearance.icon` value: a preset id renders the artwork,\r\n * a 1–4 character glyph renders as text, and anything else returns null so the\r\n * caller keeps the default folder icon.\r\n */\r\nfunction resolveCategoryIcon(icon: string | undefined): ReactNode | null {\r\n if (icon === undefined || icon === '') return null\r\n const preset = CATEGORY_ICONS[icon]\r\n if (preset !== undefined) return preset\r\n return Array.from(icon).length <= 4 ? {icon} : null\r\n}\r\n\r\n/**\r\n * Render one stored icon value (preset artwork or a short glyph). Shared by the\r\n * category row's icon slot and the appearance picker grid, so both show exactly\r\n * the same artwork. `fallback` renders when the value is empty or unknown.\r\n */\r\nexport function CategoryGlyph({ icon, fallback = null }: { icon: string | undefined; fallback?: ReactNode }): JSX.Element {\r\n return <>{resolveCategoryIcon(icon) ?? fallback}\r\n}\r\n\r\n/**\r\n * One category folder row: toggle, rename/delete menu (every group — rule\r\n * groups via overlay renames/hides), draggable source for group reorder and\r\n * drop target for both workspace moves and group reorders.\r\n */\r\nexport function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {\r\n node: CategoryNode\r\n t: T\r\n onToggle: () => void\r\n /** Rename/delete actions; the hover menu renders only when both provided. */\r\n onRename?: () => void\r\n onDelete?: () => void\r\n /** Pin/unpin this group (menu row). */\r\n onTogglePin?: () => void\r\n /** Open the appearance dialog (menu row). */\r\n onEditAppearance?: () => void\r\n /** Group reorder source; the row becomes draggable only when provided. */\r\n onDragStartCategory?: (event: DragEvent) => void\r\n} & RowDropProps) {\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n const count = node.workspaces.length\r\n const manageable = onRename !== undefined && onDelete !== undefined\r\n const pinned = node.appearance?.pinned === true\r\n const menuItems: MenuEntry[] = [\r\n ...(onTogglePin === undefined\r\n ? []\r\n : [{\r\n id: 'pin',\r\n label: pinned ? t('group.unpin') : t('group.pin'),\r\n icon: pinned ? : ,\r\n }]),\r\n ...(onEditAppearance === undefined\r\n ? []\r\n : [{ id: 'appearance', label: t('group.appearance'), icon: }]),\r\n { type: 'separator', id: 'group-menu-separator' },\r\n { id: 'rename', label: t('group.rename'), icon: },\r\n { id: 'delete', label: t('group.delete'), icon: , danger: true },\r\n ]\r\n return (\r\n \r\n \r\n \r\n \r\n \r\n : }\r\n />\r\n \r\n {node.label}\r\n {count}\r\n {pinned && (\r\n \r\n \r\n \r\n )}\r\n {manageable && (\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'pin') onTogglePin?.()\r\n if (id === 'appearance') onEditAppearance?.()\r\n if (id === 'rename') onRename()\r\n if (id === 'delete') onDelete()\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n \r\n )}\r\n \r\n )\r\n}\r\n\r\n/** One workspace folder row inside a category: draggable source + drop target. */\r\nexport function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {\r\n node: WorkspaceGroupNode\r\n t: T\r\n onToggle: () => void\r\n onNewSession: () => void\r\n onRename: () => void\r\n onDelete: () => void\r\n /** Project currently sits inside a group — offer \"move out of group\". */\r\n canMoveOut?: boolean\r\n onMoveOut?: () => void\r\n /**\r\n * Open the project directory in the host's file manager. Omitted when the\r\n * host resolved no folder application (no capability, or a remote launch),\r\n * which keeps the entry out of the menu entirely.\r\n */\r\n onOpenInFolder?: () => void\r\n /** Render as a top-level row (no folder indentation). */\r\n flat?: boolean\r\n /** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */\r\n onDragStartExtra?: () => void\r\n} & RowDropProps) {\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n const menuItems = [\r\n ...(onOpenInFolder !== undefined\r\n ? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: }]\r\n : []),\r\n ...(canMoveOut && onMoveOut !== undefined\r\n ? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: }]\r\n : []),\r\n { id: 'rename', label: t('workspace.rename'), icon: },\r\n { id: 'delete', label: t('workspace.delete'), icon: , danger: true },\r\n ]\r\n const onDragStart = (event: DragEvent): void => {\r\n event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId)\r\n event.dataTransfer.effectAllowed = 'move'\r\n onDragStartExtra?.()\r\n }\r\n return (\r\n \r\n \r\n \r\n \r\n \r\n {/* Project rows use the project glyph (same as the official workspace\r\n browser) so groups (folder glyph) and projects stay distinguishable. */}\r\n \r\n \r\n {node.label}\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'openInFolder') onOpenInFolder?.()\r\n if (id === 'moveOut') onMoveOut?.()\r\n if (id === 'rename') onRename()\r\n if (id === 'delete') onDelete()\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n { e.stopPropagation(); onNewSession() }}\r\n >\r\n \r\n \r\n \r\n \r\n )\r\n}\r\n\r\n/**\r\n * Children container for one folder's rows.\r\n *\r\n * Keeps the tree's `role=\"group\"` semantics and gives the rows a single\r\n * positioned ancestor. It used to draw a per-folder guide rail; that is now the\r\n * flower branch's job (one continuous stem for the whole tree, see\r\n * `FlowerBranch.tsx`), so this is structure only.\r\n */\r\nexport function TreeChildren({ children }: { children: ReactNode }) {\r\n return (\r\n
\r\n {children}\r\n
\r\n )\r\n}\r\n\r\n/** Keyframe names the disclosure animation relies on (styles.css). */\r\nconst ROW_GROUP_OPEN_ANIMATION = 'wg-rows-in'\r\nconst ROW_GROUP_CLOSE_ANIMATION = 'wg-rows-out'\r\n\r\n/** Upper bound for one disclosure animation (180ms open / 160ms close). */\r\nconst ROW_GROUP_ANIMATION_FALLBACK_MS = 400\r\n\r\n/** Lifecycle of one animated disclosure body. */\r\ntype RowGroupPhase = 'opening' | 'open' | 'closing' | 'closed'\r\n\r\n/** Whether the user asked the OS to reduce motion (no sync unmount without it). */\r\nfunction prefersReducedMotion(): boolean {\r\n return typeof window !== 'undefined'\r\n && typeof window.matchMedia === 'function'\r\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches\r\n}\r\n\r\n/**\r\n * Animated disclosure body shared by the category and project levels.\r\n *\r\n * Collapsed state renders nothing at all (same DOM as the old\r\n * `{expanded && …}`), so hidden subtrees cost no layout. Expanding plays a\r\n * 0fr→1fr grid animation; collapsing keeps the rows mounted for one closing\r\n * animation and unmounts on its `animationend`. `prefers-reduced-motion`\r\n * unmounts synchronously instead — waiting for an `animationend` that CSS\r\n * disabled would leave the group stuck half-closed.\r\n *\r\n * The flower-branch overlay cannot follow a moving row box, so the animation\r\n * phase exposes `data-wg-animating` (styles.css fades the vine while it is\r\n * present).\r\n */\r\nexport function RowGroup({ expanded, className, animate = true, children }: {\r\n expanded: boolean\r\n className?: string\r\n /** Disable the animation for huge subtrees or during drag folding. */\r\n animate?: boolean\r\n children: ReactNode\r\n}): JSX.Element | null {\r\n const [phase, setPhase] = useState(expanded ? 'open' : 'closed')\r\n const previousExpanded = useRef(expanded)\r\n // Adjust state while rendering (React's documented prop-change pattern) so a\r\n // reduced-motion collapse unmounts in the same commit instead of flashing\r\n // the old rows for a frame.\r\n if (previousExpanded.current !== expanded) {\r\n previousExpanded.current = expanded\r\n if (expanded) setPhase(animate && !prefersReducedMotion() ? 'opening' : 'open')\r\n else setPhase(animate && !prefersReducedMotion() ? 'closing' : 'closed')\r\n }\r\n // Insurance against a missing `animationend` (interrupted or skipped\r\n // animation): the animating phase holds `pointer-events:none` and keeps a\r\n // collapsed body mounted, so it must always settle on its own.\r\n useEffect(() => {\r\n if (phase !== 'opening' && phase !== 'closing') return undefined\r\n const timer = window.setTimeout(() => {\r\n setPhase(phase === 'opening' ? 'open' : 'closed')\r\n }, ROW_GROUP_ANIMATION_FALLBACK_MS)\r\n return () => { window.clearTimeout(timer) }\r\n }, [phase])\r\n if (phase === 'closed') return null\r\n const animating = phase === 'opening' || phase === 'closing'\r\n const classes = `wgRows${className === undefined ? '' : ` ${className}`}${phase === 'opening' ? ' wgRowsOpening' : ''}${phase === 'closing' ? ' wgRowsClosing' : ''}`\r\n const onAnimationEnd = (event: AnimationEvent): void => {\r\n if (event.target !== event.currentTarget) return\r\n if (phase === 'opening' && event.animationName === ROW_GROUP_OPEN_ANIMATION) setPhase('open')\r\n if (phase === 'closing' && event.animationName === ROW_GROUP_CLOSE_ANIMATION) setPhase('closed')\r\n }\r\n return (\r\n \r\n
{children}
\r\n \r\n )\r\n}\r\n\r\n/** One session leaf row. */\r\nexport function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {\r\n node: SessionNode\r\n currentId: string | undefined\r\n now: number\r\n t: T\r\n onOpen: (id: SessionNode['id']) => void\r\n onRename: (id: SessionNode['id'], currentTitle: string) => void\r\n onFork: (id: SessionNode['id']) => void\r\n onArchive: (id: SessionNode['id']) => void\r\n}) {\r\n const selected = node.id === currentId\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n // The ACTIVE session hands its status slot to the flower: the branch anchors\r\n // on this cell (`anchorX` targets `.wgStatusSlot`), so the bloom and the dot\r\n // occupy the same 14px square. Drawing both puts the dot's green \"ongoing\"\r\n // ring (or the loading spinner) on top of the petals, which is what made the\r\n // flower look broken. The flower already carries this row's state — it turns\r\n // exactly while the session runs — so the dot is redundant here anyway.\r\n const showStatus = !selected\r\n const menuItems = [\r\n { id: 'rename', label: t('session.rename'), icon: },\r\n { id: 'fork', label: t('session.fork'), icon: },\r\n { id: 'archive', label: t('session.archive'), icon: },\r\n ]\r\n return (\r\n { onOpen(node.id) }}\r\n >\r\n \r\n {showStatus && }\r\n \r\n {node.title}\r\n {!node.blank && {relativeTimeLabel(node.updatedAt, now)}}\r\n {node.snippet !== undefined && (\r\n {node.snippet}\r\n )}\r\n {!node.blank && (\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'rename') onRename(node.id, node.title)\r\n if (id === 'fork') onFork(node.id)\r\n if (id === 'archive') onArchive(node.id)\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n \r\n )}\r\n \r\n )\r\n}\r\n\r\nexport type { T }\r\n","/**\r\n * Transport for the official open-in-app host routes served by\r\n * `@deepseek-ai/dsh-host-open-in-app`. The project row offers \"open this\r\n * project's folder\" by asking that host half for the applications it verified\r\n * as installed, then POSTing the launcher it already resolved — this plugin\r\n * never probes or spawns a launcher itself, and a host without the capability\r\n * (no resolved application, e.g. an SSH launch) simply yields no menu entry.\r\n */\r\n\r\n/** GET route serving the probed application ids (host-owned constant). */\r\nexport const OPEN_IN_APP_APPS_ROUTE = '/open-in-app/apps'\r\n\r\n/** POST route launching one resolved application on one absolute directory. */\r\nexport const OPEN_IN_APP_OPEN_ROUTE = '/open-in-app/open'\r\n\r\n/**\r\n * Catalog ids that open a directory in the platform file manager, most\r\n * specific first (the official catalog names one per platform: `explorer` on\r\n * Windows, `finder` on macOS, `filemanager` on Linux).\r\n */\r\nconst FOLDER_APP_IDS = ['explorer', 'finder', 'filemanager'] as const\r\n\r\n/**\r\n * The installed file-manager id for this host, or undefined when the host\r\n * resolved none (the row then offers no \"open in folder\" entry).\r\n * @param apps - installed catalog ids from the apps route.\r\n * @returns the preferred available id.\r\n */\r\nexport function folderAppId(apps: readonly string[]): string | undefined {\r\n for (const id of FOLDER_APP_IDS) {\r\n if (apps.includes(id)) return id\r\n }\r\n return undefined\r\n}\r\n\r\n/**\r\n * Resolve the browser's Host base with the connection carrier's null-origin\r\n * fallback (same rule the official button uses): a sandboxed document reports\r\n * the literal origin \"null\", which cannot address the host.\r\n * @returns the absolute base URL of the current Host.\r\n */\r\nfunction hostBase(): string {\r\n const origin = globalThis.location?.origin\r\n return origin !== undefined && origin !== 'null' ? origin : 'http://dsh.internal'\r\n}\r\n\r\n/**\r\n * Read the host's installed-application ids. A host without the capability\r\n * (or one that refuses) reads as an empty list rather than an error, so the\r\n * caller can treat \"no apps\" and \"no route\" identically.\r\n * @param signal - aborts the read when the browser half unmounts.\r\n * @returns installed catalog ids, in host menu order.\r\n */\r\nexport async function fetchOpenInApps(signal?: AbortSignal): Promise {\r\n const response = await fetch(new URL(OPEN_IN_APP_APPS_ROUTE, hostBase()), {\r\n headers: { accept: 'application/json' },\r\n cache: 'no-store',\r\n ...(signal === undefined ? {} : { signal }),\r\n })\r\n if (!response.ok) throw new Error(`open-in-app apps request failed: ${response.status}`)\r\n const payload: unknown = await response.json()\r\n const apps = (payload as { apps?: unknown }).apps\r\n return Array.isArray(apps) ? apps.filter((id): id is string => typeof id === 'string') : []\r\n}\r\n\r\n/**\r\n * Launch one installed application on one absolute directory.\r\n * @param appId - catalog id from the apps route.\r\n * @param path - the project's absolute directory.\r\n * @returns after the host acknowledged the launch; rejects on any refusal.\r\n */\r\nexport async function openPathInApp(appId: string, path: string): Promise {\r\n const response = await fetch(new URL(OPEN_IN_APP_OPEN_ROUTE, hostBase()), {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify({ app: appId, path }),\r\n })\r\n if (!response.ok) throw new Error(`open-in-app launch failed: ${response.status}`)\r\n}\r\n","/**\r\n * Pure data shaping for the Ctrl+R quick switch panel. Runtime-free (same\r\n * discipline as store-core.ts): unit tests exercise the real semantics\r\n * without a browser module loader; the panel only binds them to the\r\n * framework's global hooks.\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\n\r\n/** A session row eligible for quick switching: running, top-level, real. */\r\nfunction quickEligible(summary: SessionSummary): boolean {\r\n return summary.running === true && summary.origin !== 'subagent' && !summary.blank\r\n}\r\n\r\n/**\r\n * Running quick-switchable sessions across the whole list, newest first.\r\n * @param list - sessions list snapshot.\r\n * @param archived - registry-global archive set (archived rows never surface).\r\n * @returns running summaries in recency order (id as deterministic tiebreak).\r\n */\r\nexport function runningSessions(list: SessionListState, archived: ReadonlySet): SessionSummary[] {\r\n const out: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n if (archived.has(id)) continue\r\n const summary = list.byId[id]\r\n if (summary !== undefined && quickEligible(summary)) out.push(summary)\r\n }\r\n out.sort((a, b) => (b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)))\r\n return out\r\n}\r\n\r\n/**\r\n * Every quick-switchable session across the whole list — the sessions tab's\r\n * data: running rows pinned on top, everything else under them, both groups\r\n * newest first. Visibility mirrors the tree (subagent rows never; archived\r\n * never; a blank row only while it is the open session).\r\n * @param list - sessions list snapshot.\r\n * @param archived - registry-global archive set (archived rows never surface).\r\n * @param current - the selected session (`mainView` retention; keeps its blank row visible).\r\n * @returns summaries with running first, then recency (id as deterministic tiebreak).\r\n */\r\nexport function allSessions(\r\n list: SessionListState,\r\n archived: ReadonlySet,\r\n current: SessionId | undefined,\r\n): SessionSummary[] {\r\n const out: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n if (archived.has(id)) continue\r\n const summary = list.byId[id]\r\n if (summary === undefined) continue\r\n if (summary.origin === 'subagent') continue\r\n if (summary.blank && summary.id !== current) continue\r\n out.push(summary)\r\n }\r\n out.sort((a, b) => {\r\n if (a.running !== b.running) return a.running ? -1 : 1\r\n return b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)\r\n })\r\n return out\r\n}\r\n\r\n/**\r\n * Session search for the quick panel: display-title or owning-workspace-title\r\n * substring match (trimmed, case-insensitive). Filters only — the incoming\r\n * running-first/recency order is preserved verbatim, so \"running on top\"\r\n * survives any query.\r\n * @param sessions - allSessions() output (running pinned on top, then recency).\r\n * @param query - raw query.\r\n * @param workspaceTitleOf - owning workspace title resolver (sub-line source).\r\n * @param limit - hard render cap.\r\n * @returns matching sessions in the given order.\r\n */\r\nexport function filterSessions(\r\n sessions: readonly SessionSummary[],\r\n query: string,\r\n workspaceTitleOf: (session: SessionSummary) => string | undefined,\r\n limit = 200,\r\n): SessionSummary[] {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return sessions.slice(0, limit)\r\n const out: SessionSummary[] = []\r\n for (const session of sessions) {\r\n const workspace = workspaceTitleOf(session)?.toLowerCase() ?? ''\r\n if (session.displayTitle.toLowerCase().includes(q) || workspace.includes(q)) out.push(session)\r\n }\r\n return out.slice(0, limit)\r\n}\r\n\r\n/**\r\n * Most recently updated running session inside one workspace.\r\n * @param list - sessions list snapshot.\r\n * @param workspace - target workspace (its session account order is irrelevant;\r\n * recency picks the row).\r\n * @returns the session id, or undefined when nothing in the workspace runs.\r\n */\r\nexport function latestRunningInWorkspace(list: SessionListState, workspace: WorkspaceView): SessionId | undefined {\r\n let best: SessionId | undefined\r\n let bestTime = Number.NEGATIVE_INFINITY\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || !quickEligible(summary)) continue\r\n if (summary.updatedAt > bestTime) {\r\n best = summary.id\r\n bestTime = summary.updatedAt\r\n }\r\n }\r\n return best\r\n}\r\n\r\n/**\r\n * Running-session count per workspace id (badge on the workspace tab rows).\r\n * @param running - runningSessions() output.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @returns counts keyed by workspace id; absent key = none running.\r\n */\r\nexport function runningCountByWorkspace(\r\n running: readonly SessionSummary[],\r\n workspaces: readonly WorkspaceView[],\r\n): Map {\r\n const counts = new Map()\r\n if (running.length === 0) return counts\r\n const runningIds = new Set(running.map(s => s.id))\r\n for (const workspace of workspaces) {\r\n let count = 0\r\n for (const sessionId of workspace.sessionIds) {\r\n if (runningIds.has(sessionId)) count += 1\r\n }\r\n if (count > 0) counts.set(workspace.workspaceId as string, count)\r\n }\r\n return counts\r\n}\r\n\r\n/**\r\n * The workspace that owns the currently open session.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param currentSessionId - the selected session (`mainView` retention); may be undefined\r\n * (no session open, cleared selection) or an id no listed workspace holds\r\n * (e.g. an addressed subagent session).\r\n * @returns the workspace id, or undefined when there is no active workspace.\r\n */\r\nexport function activeWorkspaceId(\r\n workspaces: readonly WorkspaceView[],\r\n currentSessionId: SessionId | undefined,\r\n): string | undefined {\r\n if (currentSessionId === undefined) return undefined\r\n const workspace = workspaces.find(w => w.sessionIds.includes(currentSessionId))\r\n return workspace?.workspaceId as string | undefined\r\n}\r\n\r\n/**\r\n * Workspace search for the quick panel: title prefix → title substring →\r\n * category label substring → path substring; ties keep host order via a\r\n * stable title compare inside one rank.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param query - raw query (trimmed, case-insensitive).\r\n * @param categoryLabelOf - category label resolver (grouped workspaces only).\r\n * @param limit - hard render cap.\r\n * @returns ranked matches; an empty query returns host order.\r\n */\r\nexport function filterWorkspaces(\r\n workspaces: readonly WorkspaceView[],\r\n query: string,\r\n categoryLabelOf?: (workspace: WorkspaceView) => string | undefined,\r\n limit = 50,\r\n): WorkspaceView[] {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return workspaces.slice(0, limit)\r\n const scored: { workspace: WorkspaceView; score: number }[] = []\r\n for (const workspace of workspaces) {\r\n const title = workspace.title.toLowerCase()\r\n const path = workspace.path.toLowerCase()\r\n const category = (categoryLabelOf?.(workspace) ?? '').toLowerCase()\r\n let score: number | undefined\r\n if (title.startsWith(q)) score = 0\r\n else if (title.includes(q)) score = 1\r\n else if (category !== '' && category.includes(q)) score = 2\r\n else if (path.includes(q)) score = 3\r\n if (score !== undefined) scored.push({ workspace, score })\r\n }\r\n scored.sort((a, b) => (a.score !== b.score\r\n ? a.score - b.score\r\n : a.workspace.title.localeCompare(b.workspace.title)))\r\n return scored.slice(0, limit).map(entry => entry.workspace)\r\n}\r\n","/**\r\n * Ctrl+R quick switch panel: two tabs over the framework's global hooks.\r\n *\r\n * - Workspaces tab: search real Workspaces, select one, then either start a\r\n * New Session in it or jump straight to its most recently updated running\r\n * session (the button reads the none-running state and disables).\r\n * - Sessions tab: every top-level session across workspaces — running ones\r\n * pinned on top, everything else under them, both groups newest first; one\r\n * click (or Enter) opens it. The shared search input filters by session or\r\n * workspace title and never re-sorts, so the running-first order survives.\r\n *\r\n * Current-row marker: the open workspace (workspaces tab) and the open\r\n * session (sessions tab) render `.wgQuickRowCurrent`; with no current\r\n * session — or one no listed workspace holds — nothing is marked.\r\n *\r\n * Mount discipline: the parent conditionally mounts this component, so every\r\n * open starts from a fresh query/selection (quick-switcher semantics). The\r\n * overlay portals to document.body (sidebar ancestors clip `fixed`), sizes\r\n * itself like a launcher (top-anchored, 640px) instead of the host Modal's\r\n * 380px dialog, and handles Escape / mask click by itself. Pure data shaping\r\n * lives in quick.ts; this file only binds hooks + actions.\r\n */\r\nimport { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react'\r\nimport { createPortal } from 'react-dom'\r\nimport { Button, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\r\nimport type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport { activeWorkspaceId, allSessions, filterSessions, filterWorkspaces, latestRunningInWorkspace, runningCountByWorkspace, runningSessions } from './quick.ts'\r\nimport { relativeTimeLabel } from './rows.tsx'\r\n\r\n/** Which surface of the quick panel is active. */\r\nexport type QuickTab = 'workspaces' | 'sessions'\r\n\r\n/** The locale seat's translate function (same shape GroupsBrowser receives). */\r\ntype Translate = PropsLocale<'workspaceGroups'>['t']\r\n\r\n/** Quick panel props: hooks snapshots + the two injected verbs + shared CSS context. */\r\nexport type QuickPanelProps = {\r\n /** Close request (Escape, mask click, action completed, or parent Ctrl+R toggle). */\r\n onClose: () => void\r\n /** Sessions list snapshot (drives running detection). */\r\n list: SessionListState\r\n /** Real workspaces in stable Host order. */\r\n workspaces: readonly WorkspaceView[]\r\n /** Registry-global archive set. */\r\n archivedSessionIds: readonly SessionId[]\r\n /** Category label per grouped workspace id (badge column; top-level absent). */\r\n categoryByWorkspace: ReadonlyMap\r\n /** The Session the Conversation currently shows (mainView retention), if any. */\r\n current: SessionId | undefined\r\n /** Start a New Session in a workspace (injected share verb). */\r\n startSession: (workspaceId?: WorkspaceId) => void\r\n /** Open a real Session (injected share verb). */\r\n openSession: (sessionId: SessionId) => void\r\n /** Render clock for relative times (parent refreshes per render). */\r\n now: number\r\n /** Dictionary accessor (workspaceGroups namespace). */\r\n t: Translate\r\n}\r\n\r\n/** Basename of a host path (both separators; shortens the workspace row sub-line). */\r\nfunction pathBasename(path: string): string {\r\n const trimmed = path.replace(/[/\\\\]+$/, '')\r\n const base = trimmed.split(/[/\\\\]/).pop()\r\n return base !== undefined && base !== '' ? base : trimmed\r\n}\r\n\r\n/**\r\n * Render the quick switch panel (portaled overlay).\r\n * @param props - hooks snapshots + injected verbs.\r\n * @returns the panel element tree.\r\n */\r\nexport function QuickPanel({\r\n onClose,\r\n list,\r\n workspaces,\r\n archivedSessionIds,\r\n categoryByWorkspace,\r\n current: currentSessionId,\r\n startSession,\r\n openSession,\r\n now,\r\n t,\r\n}: QuickPanelProps) {\r\n const [tab, setTab] = useState('workspaces')\r\n const [query, setQuery] = useState('')\r\n const [selectedId, setSelectedId] = useState(null)\r\n const [activeIndex, setActiveIndex] = useState(0)\r\n const inputRef = useRef(null)\r\n const activeRowRef = useRef(null)\r\n\r\n const archived = useMemo(() => new Set(archivedSessionIds), [archivedSessionIds])\r\n const running = useMemo(() => runningSessions(list, archived), [list, archived])\r\n const runCounts = useMemo(() => runningCountByWorkspace(running, workspaces), [running, workspaces])\r\n const filtered = useMemo(\r\n () => filterWorkspaces(workspaces, query, ws => categoryByWorkspace.get(ws.workspaceId as string)),\r\n [workspaces, query, categoryByWorkspace],\r\n )\r\n\r\n // Where the user is right now: the open session and its owning workspace.\r\n // Both may be absent (no mainView retention, or a session no listed\r\n // workspace holds) — the current-row marker simply never renders then.\r\n const currentWorkspaceId = useMemo(\r\n () => activeWorkspaceId(workspaces, currentSessionId),\r\n [workspaces, currentSessionId],\r\n )\r\n\r\n // Sessions tab data: every top-level session, running pinned on top then\r\n // recency, filtered by the shared search query (filter never re-sorts).\r\n const sessions = useMemo(\r\n () => allSessions(list, archived, currentSessionId),\r\n [list, archived, currentSessionId],\r\n )\r\n // Owning workspace title per session id (row sub-line + search field);\r\n // first workspace wins — a session lives in exactly one.\r\n const workspaceTitleBySession = useMemo(() => {\r\n const map = new Map()\r\n for (const workspace of workspaces) {\r\n for (const sessionId of workspace.sessionIds) {\r\n if (!map.has(sessionId)) map.set(sessionId, workspace.title)\r\n }\r\n }\r\n return map\r\n }, [workspaces])\r\n const filteredSessions = useMemo(\r\n () => filterSessions(sessions, query, s => workspaceTitleBySession.get(s.id)),\r\n [sessions, query, workspaceTitleBySession],\r\n )\r\n\r\n const selected = selectedId === null\r\n ? undefined\r\n : workspaces.find(w => (w.workspaceId as string) === selectedId)\r\n const selectedRunningId = selected === undefined ? undefined : latestRunningInWorkspace(list, selected)\r\n\r\n // Focus the search input whenever a tab becomes reachable (both tabs own it).\r\n useEffect(() => {\r\n inputRef.current?.focus()\r\n }, [tab])\r\n\r\n // Keep the keyboard-active row visible while arrowing through the list.\r\n useEffect(() => {\r\n activeRowRef.current?.scrollIntoView({ block: 'nearest' })\r\n }, [activeIndex])\r\n\r\n /** Select the workspace and close (New Session verb). */\r\n const launchNewSession = (workspace: WorkspaceView): void => {\r\n startSession(workspace.workspaceId)\r\n onClose()\r\n }\r\n\r\n /** Open a session row and close (sessions tab click or Enter). */\r\n const launchSession = (sessionId: SessionId): void => {\r\n openSession(sessionId)\r\n onClose()\r\n }\r\n\r\n /** Switch tabs; the query carries over, the per-tab selection resets. */\r\n const switchTab = (next: QuickTab): void => {\r\n setTab(next)\r\n setSelectedId(null)\r\n setActiveIndex(0)\r\n }\r\n\r\n /** Search-input keyboard: arrows move the active row; Enter confirms it. */\r\n const onSearchKeyDown = (e: KeyboardEvent): void => {\r\n if (e.key === 'ArrowDown') {\r\n e.preventDefault()\r\n const max = (tab === 'workspaces' ? filtered.length : filteredSessions.length) - 1\r\n setActiveIndex(i => Math.min(i + 1, Math.max(max, 0)))\r\n } else if (e.key === 'ArrowUp') {\r\n e.preventDefault()\r\n setActiveIndex(i => Math.max(i - 1, 0))\r\n } else if (e.key === 'Enter') {\r\n e.preventDefault()\r\n if (tab === 'workspaces') {\r\n if (selected === undefined) {\r\n const target = filtered[activeIndex]\r\n if (target !== undefined) setSelectedId(target.workspaceId as string)\r\n } else {\r\n launchNewSession(selected)\r\n }\r\n } else {\r\n const target = filteredSessions[activeIndex]\r\n if (target !== undefined) launchSession(target.id)\r\n }\r\n }\r\n }\r\n\r\n /** Escape closes (capture so row buttons and the input can't swallow it). */\r\n const onCardKeyDown = (e: KeyboardEvent): void => {\r\n if (e.key === 'Escape') {\r\n e.preventDefault()\r\n e.stopPropagation()\r\n onClose()\r\n }\r\n }\r\n\r\n /** Mask click closes; clicks inside the card never reach the mask. */\r\n const onOverlayMouseDown = (e: MouseEvent): void => {\r\n if (e.target === e.currentTarget) onClose()\r\n }\r\n\r\n const selectWorkspace = (id: string): void => {\r\n setSelectedId(id)\r\n inputRef.current?.focus()\r\n }\r\n\r\n return createPortal(\r\n
\r\n \r\n
\r\n {t('quick.title')}\r\n
\r\n { switchTab('workspaces') }}\r\n >\r\n {t('quick.tab.workspaces')}\r\n \r\n { switchTab('sessions') }}\r\n >\r\n {t('quick.tab.sessions')}\r\n {running.length > 0 && {running.length}}\r\n \r\n
\r\n
\r\n\r\n {/* Shared search: workspaces on one tab, sessions on the other. */}\r\n
\r\n {\r\n setQuery(e.target.value)\r\n setSelectedId(null)\r\n setActiveIndex(0)\r\n }}\r\n onKeyDown={onSearchKeyDown}\r\n />\r\n
\r\n {tab === 'workspaces' ? (\r\n <>\r\n
\r\n {filtered.map((workspace, i) => {\r\n const id = workspace.workspaceId as string\r\n const count = runCounts.get(id) ?? 0\r\n const category = categoryByWorkspace.get(id)\r\n const isCurrent = id === currentWorkspaceId\r\n return (\r\n { setActiveIndex(i) }}\r\n onClick={() => { selectWorkspace(id) }}\r\n >\r\n \r\n {workspace.title}\r\n {count > 0 && ● {count}}\r\n \r\n \r\n \r\n {category !== undefined ? `${category} · ${pathBasename(workspace.path)}` : pathBasename(workspace.path)}\r\n \r\n \r\n \r\n )\r\n })}\r\n {filtered.length === 0 &&
{t('quick.empty.workspaces')}
}\r\n
\r\n
\r\n \r\n {selected === undefined ? t('quick.select.hint') : selected.title}\r\n \r\n { if (selectedRunningId !== undefined) launchSession(selectedRunningId) }}\r\n >\r\n {selectedRunningId !== undefined ? t('quick.action.running') : t('quick.action.noneRunning')}\r\n \r\n { if (selected !== undefined) launchNewSession(selected) }}\r\n >\r\n {t('quick.action.newSession')}\r\n \r\n
\r\n \r\n ) : (\r\n
\r\n {filteredSessions.map((session, i) => {\r\n const workspaceTitle = workspaceTitleBySession.get(session.id) ?? ''\r\n const isCurrent = session.id === currentSessionId\r\n return (\r\n { setActiveIndex(i) }}\r\n onClick={() => { launchSession(session.id) }}\r\n >\r\n \r\n \r\n {session.blank ? t('newSession') : session.displayTitle}\r\n {relativeTimeLabel(session.updatedAt, now)}\r\n \r\n \r\n {workspaceTitle}\r\n \r\n \r\n )\r\n })}\r\n {filteredSessions.length === 0 &&
{t('quick.empty.sessions')}
}\r\n
\r\n )}\r\n\r\n
{t('quick.hint')}
\r\n
\r\n ,\r\n document.body,\r\n )\r\n}\r\n","/**\r\n * DOM seat for the session tab strip.\r\n *\r\n * Why this exists instead of a slot: the strip belongs at the very top of the\r\n * conversation column — `pI_x6G_centerCol` (ui-layout's AppFrame `.centerCol`,\r\n * a hashed CSS-Modules class). That column declares NO child slots: its only\r\n * child is the `main` slot's occupant (`renderSlot('main', …)`, the\r\n * Conversation or a global panel), so there is nowhere to register. The\r\n * shipped slot in that neighbourhood — `conversation.composer.dock` — is the\r\n * band UNDER the composer card, a different place entirely.\r\n *\r\n * So the strip gets a real DOM seat: this module finds the column, prepends a\r\n * `
` to it, and hands that element to a React portal. The element is\r\n * OURS, never React's: it is inserted outside the column's child list that\r\n * React reconciles, and it is re-inserted if React (or a theme/titlebar\r\n * re-render) ever drops it.\r\n *\r\n * Two hazards this module is built around:\r\n *\r\n * 1. `centerCol` is a hashed class name (`pI_x6G_centerCol`) that changes when\r\n * the package is rebuilt. Matching is therefore done on the *structural*\r\n * contract — a grid-item column that holds the `main` panel — plus a\r\n * `[class*=\"_centerCol\"]` probe, never on the exact hash.\r\n * 2. The column mounts after the client plugin's `apply()` runs. Discovery is\r\n * therefore a MutationObserver on `document.body` plus a `requestAnimationFrame`\r\n * retry, and both are torn down when the owning effect disposes.\r\n */\r\n\r\n/** Persistent marker for the injected container (survives React re-renders). */\r\nconst SEAT_ATTRIBUTE = 'data-wg-tab-seat'\r\n\r\n/** Sentinel attribute on the container so discovery can skip our own node. */\r\nconst SEAT_SELECTOR = `[${SEAT_ATTRIBUTE}]`\r\n\r\n/**\r\n * Match the conversation column by its hashed CSS-Modules class.\r\n *\r\n * The hash prefix (`pI_x6G_`) is build-dependent, so the probe matches the\r\n * `_centerCol` suffix that the Modules transform always preserves. A plain\r\n * `class*=\"centerCol\"` scan would risk matching unrelated utility classes, so\r\n * the leading underscore is required.\r\n * @param root - subtree to scan (normally `document`).\r\n * @returns the column element, or null while it has not mounted.\r\n */\r\nfunction findCenterColumn(root: ParentNode): HTMLElement | null {\r\n // Fast path: the seat is already in place and still attached, which is the\r\n // steady state on every re-render (portal into an existing element).\r\n const existing = root.querySelector(SEAT_SELECTOR)\r\n if (existing?.isConnected === true) return existing.parentElement\r\n\r\n // Structural probe: the column is the direct child of the app frame grid\r\n // that contains the `main` panel. Querying the class suffix first keeps this\r\n // to one selector evaluation in the common case.\r\n const column = root.querySelector('[class*=\"_centerCol\"]')\r\n if (column !== null) return column\r\n\r\n // Nothing matched: either the shell has not mounted yet, or the Modules hash\r\n // convention changed. Returning null keeps the caller in its wait loop\r\n // instead of guessing at a wrong node (which would visually corrupt the\r\n // shell). The strip simply appears once the frame is up.\r\n return null\r\n}\r\n\r\n/** A mounted seat: the host element plus the disposer that removes it. */\r\nexport interface TabSeat {\r\n /**\r\n * The element the React portal renders into — null until the conversation\r\n * column mounts. The portal is simply not rendered while this is null.\r\n */\r\n readonly host: HTMLElement | null\r\n /** Remove the seat and stop watching for the column. */\r\n dispose: () => void\r\n}\r\n\r\n/**\r\n * Ensure a seat exists as the FIRST child of the conversation column, creating\r\n * it if needed, and keep it there for as long as the returned handle is live.\r\n *\r\n * The seat element is created once and reused: a portal that re-mounts into a\r\n * fresh node on every shell re-render would drop the tab strip's React state\r\n * and visible focus. If React removes the node (it owns the column's child\r\n * list, and our node is not part of it), the observer re-inserts the SAME\r\n * element, so the portal's subtree moves with it.\r\n *\r\n * @param onReady - called with the host element each time it becomes attached\r\n * (once immediately when the column already exists). Used to seed React\r\n * state; may fire more than once if the column is remounted.\r\n * @returns the seat handle. `host` is null until the column appears, so the\r\n * caller renders nothing meanwhile and starts rendering when `onReady`\r\n * fires. Never null: a missing column must degrade to \"no strip\", not to a\r\n * thrown error that would take the whole client plugin down.\r\n */\r\nexport function mountTabSeat(onReady: (host: HTMLElement) => void): TabSeat {\r\n let host: HTMLElement | null = null\r\n let column: HTMLElement | null = null\r\n let observer: MutationObserver | null = null\r\n let raf = 0\r\n let attempts = 0\r\n let disposed = false\r\n\r\n // Bounded retry: ~5s at 60fps. The shell mounts well inside this; the bound\r\n // exists so a missing column degrades to \"no strip\" instead of a permanent\r\n // frame loop.\r\n const MAX_ATTEMPTS = 300\r\n\r\n /**\r\n * Put the seat at the head of the column, creating it on first success.\r\n * Idempotent: a seat already first is left untouched, so repeated calls from\r\n * the observer cause no DOM churn (and therefore no observer feedback loop —\r\n * our insertion schedules one more callback, which then takes this early\r\n * return instead of re-inserting).\r\n */\r\n const place = (target: HTMLElement): void => {\r\n if (disposed) return\r\n if (host === null) {\r\n host = document.createElement('div')\r\n host.setAttribute(SEAT_ATTRIBUTE, '')\r\n }\r\n if (target.firstChild === host) return\r\n target.insertBefore(host, target.firstChild)\r\n }\r\n\r\n /** Locate the column and, on success, seat the host and notify the caller. */\r\n const tryMount = (): boolean => {\r\n if (disposed) return true\r\n // Steady state: the column we already found is still attached.\r\n if (column !== null && column.isConnected) {\r\n place(column)\r\n return true\r\n }\r\n const found = findCenterColumn(document)\r\n if (found === null) return false\r\n // A different column than last time (shell remount): re-seat AND re-notify,\r\n // because the caller may hold a stale host element from the old tree.\r\n const changed = found !== column\r\n column = found\r\n place(found)\r\n if (changed) onReady(host as HTMLElement)\r\n return true\r\n }\r\n\r\n const tick = (): void => {\r\n if (disposed) return\r\n raf = 0\r\n if (tryMount()) return\r\n attempts += 1\r\n if (attempts >= MAX_ATTEMPTS) return\r\n raf = requestAnimationFrame(tick)\r\n }\r\n\r\n // The observer covers both \"column mounts later\" and \"React dropped our\r\n // node\": either way the child list changes and we re-seat. `requestAnimationFrame`\r\n // alone would miss a removal that happens after the retry budget is spent.\r\n observer = new MutationObserver(() => {\r\n if (disposed) return\r\n if (tryMount()) return\r\n if (raf === 0 && attempts < MAX_ATTEMPTS) raf = requestAnimationFrame(tick)\r\n })\r\n observer.observe(document.body, { childList: true, subtree: true })\r\n\r\n if (!tryMount() && raf === 0) raf = requestAnimationFrame(tick)\r\n\r\n return {\r\n get host(): HTMLElement | null {\r\n // Null until the column mounts; the caller's `onReady` fires at the same\r\n // moment this becomes non-null, so the two never disagree.\r\n return host\r\n },\r\n dispose: () => {\r\n disposed = true\r\n if (raf !== 0) cancelAnimationFrame(raf)\r\n raf = 0\r\n observer?.disconnect()\r\n observer = null\r\n host?.remove()\r\n host = null\r\n column = null\r\n },\r\n } as TabSeat\r\n}\r\n","/**\n * The session tab strip: one chip per opened conversation, rendered into the\n * DOM seat at the head of the conversation column (see `tab-seat.ts` for why\n * this is a DOM injection rather than a slot).\n *\n * A tab is a *view* of the open session, not a second navigation model:\n * clicking a chip navigates through `ctx.uiWorkspace.openSession`, which is the\n * one path that retains a target session; the owning component derives the\n * strip from the open session plus the tab store.\n *\n * The active chip is derived, never stored: it is the chip whose session is the\n * open one, so clicking a background chip immediately shows that chip active.\n *\n * Every affordance beyond \"click to switch\" is an explicit USER gesture, and\n * each one maps to exactly one store action: middle-click closes, the context\n * menu pins / renames / closes a range, a drag reorders, and a double-click\n * edits the tab's own label. None of them can run on their own — the strip stays\n * a record of what the user opened.\n */\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n IconCloseFillMedium,\n IconPinFillMedium,\n StateDot,\n Tooltip,\n type StateDotState,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\nimport type { SessionsTabsProps } from './contract.ts'\nimport { mountTabSeat } from './tab-seat.ts'\nimport {\n orderedTabs,\n projectIndex,\n tabIndicator,\n type SessionTab,\n type SessionTabIndicator,\n} from './tabs.ts'\nimport { currentSessionId } from './tree.ts'\n\n/** Dot state for one tab (the sidebar's session rows share this vocabulary). */\nfunction dotState(indicator: SessionTabIndicator): StateDotState {\n if (indicator.attention) return 'warning'\n if (indicator.running) return 'ongoing'\n return 'done'\n}\n\n/** Where the context menu is pinned, and which chip it belongs to. */\ninterface MenuAnchor {\n readonly sessionId: SessionId\n readonly x: number\n readonly y: number\n}\n\n/** Which chip a drag is hovering, and which half of it. */\ninterface DropTarget {\n readonly sessionId: SessionId\n readonly side: 'before' | 'after'\n}\n\n/** In-flight inline label edit. */\ninterface LabelEdit {\n readonly sessionId: SessionId\n readonly draft: string\n}\n\n/** One row of the tab context menu. */\nfunction MenuRow({\n label,\n onSelect,\n disabled = false,\n danger = false,\n}: {\n readonly label: string\n readonly onSelect: () => void\n readonly disabled?: boolean\n readonly danger?: boolean\n}) {\n return (\n \n {label}\n \n )\n}\n\n/**\n * Render the session tab strip into the conversation column's head seat.\n * @param props - tab store, catalog/status hooks, navigation, locale.\n * @returns the portal (or null until the column has mounted).\n */\nexport function SessionTabs({\n useTabs,\n actions,\n useSessions,\n useSessionStatus,\n useWorkspaces,\n activate,\n rename,\n t,\n}: SessionsTabsProps) {\n const tabs = useTabs(s => s.tabs)\n const list = useSessions(s => s)\n const statuses = useSessionStatus(s => s)\n const currentId = useSessions(s => currentSessionId(s))\n const workspaces = useWorkspaces(s => s.items)\n\n // Session → owning project, in one pass over the workspace registry. This is\n // what lets each chip name its project; without it a strip of session titles\n // is ambiguous as soon as two projects are open.\n const projects = useMemo(() => projectIndex(workspaces), [workspaces])\n\n // The seat is a DOM node outside React's tree, so it cannot arrive through\n // props; it is discovered once per mount and held in state to trigger the\n // portal's first render when the column appears.\n const [seat, setSeat] = useState(null)\n // The scrolling row, for wheel redirection and keep-active-in-view.\n const scrollRef = useRef(null)\n // The open context menu, its chip, and its viewport position.\n const [menu, setMenu] = useState(null)\n // The chip whose label is being typed into, plus the in-progress text.\n const [editing, setEditing] = useState(null)\n // The chip being dragged and the chip/half it would land on.\n const [dragging, setDragging] = useState(null)\n const [dropTarget, setDropTarget] = useState(null)\n // Timestamp of the last drag end: a drop must not also count as a click on\n // the chip it landed on (which would navigate away from what was just moved).\n const dragEndedAt = useRef(0)\n\n useEffect(() => {\n const mounted = mountTabSeat(setSeat)\n // The column may already exist, in which case onReady fired synchronously\n // during mountTabSeat and setSeat is already queued; adopt it here too so\n // the very first paint has a host instead of waiting a frame.\n if (mounted.host !== null) setSeat(mounted.host)\n return () => {\n mounted.dispose()\n // The portal must stop targeting a removed node before the next mount.\n setSeat(null)\n }\n }, [])\n\n // The strip renders exactly the tabs the store holds. There is deliberately NO\n // filtering against the session catalog and no \"close tabs whose session\n // vanished\" sweep: a tab is removed when the USER closes it, and by nothing\n // else. Trimming automatically also misfires — the catalog is briefly empty on\n // every load, which deleted restored tabs before the sessions arrived.\n const display = useMemo(() => orderedTabs(tabs, currentId), [tabs, currentId])\n const index = useMemo(() => new Map(display.map((tab, at) => [tab.sessionId, at])), [display])\n\n // With the row scrollable, the active chip can sit outside the viewport —\n // e.g. after clicking a session in the sidebar that has a tab far to the\n // right. Bring it into view on selection change. `block: 'nearest'` keeps\n // this a horizontal-only scroll, and `inline: 'nearest'` avoids nudging the\n // row when the chip is already fully visible.\n useEffect(() => {\n const el = scrollRef.current\n if (el === null || currentId === undefined) return\n const chip = el.querySelector(`[data-tab-session=\"${CSS.escape(currentId)}\"]`)\n chip?.scrollIntoView({ block: 'nearest', inline: 'nearest' })\n }, [currentId, display.length])\n\n // Dismiss the context menu on any interaction outside it. Pointerdown covers\n // both buttons; Escape and a viewport change (which would leave a fixed menu\n // pointing at the wrong chip) close it too. `capture` matters for the scroll\n // case: the strip's own row scrolls without bubbling a scroll event up.\n useEffect(() => {\n if (menu === null) return\n const dismiss = (): void => { setMenu(null) }\n const onPointerDown = (event: PointerEvent): void => {\n const target = event.target\n if (target instanceof Element && target.closest('.wgTabMenu') !== null) return\n dismiss()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') dismiss()\n }\n document.addEventListener('pointerdown', onPointerDown, true)\n document.addEventListener('keydown', onKeyDown)\n window.addEventListener('resize', dismiss)\n window.addEventListener('scroll', dismiss, true)\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true)\n document.removeEventListener('keydown', onKeyDown)\n window.removeEventListener('resize', dismiss)\n window.removeEventListener('scroll', dismiss, true)\n }\n }, [menu])\n\n if (seat === null || display.length === 0) return null\n\n /** Commit the in-flight label edit (blank clears the override). */\n const commitEdit = (): void => {\n if (editing === null) return\n actions.rename(editing.sessionId, editing.draft)\n setEditing(null)\n }\n\n /** Start editing a tab's own label, pre-filled with what the chip shows. */\n const startEdit = (sessionId: SessionId, current: string): void => {\n setMenu(null)\n setEditing({ sessionId, draft: current })\n }\n\n /** Translate a drop onto `target` into an index in the resulting strip. */\n const dropIndexFor = (draggedSessionId: SessionId, target: DropTarget): number | null => {\n const from = index.get(draggedSessionId)\n const at = index.get(target.sessionId)\n if (from === undefined || at === undefined || from === at) return null\n // Insertion index in the CURRENT strip, then corrected for the removal the\n // move implies: removing a chip before the insertion point shifts it left.\n const insertion = at + (target.side === 'after' ? 1 : 0)\n return from < insertion ? insertion - 1 : insertion\n }\n\n const chips = display.map((tab: SessionTab, at: number) => {\n const summary = list.byId[tab.sessionId]\n // A restored tab can render before its catalog row arrives. Show the\n // session id meanwhile rather than an empty chip — the tab is real, and\n // the title fills in as soon as the catalog catches up.\n const sessionLabel = summary === undefined\n ? tab.sessionId\n : summary.blank ? t('newSession') : summary.displayTitle\n // The user's own label wins over the session title; blank means \"follow the\n // session\", so the override is absent rather than empty.\n const label = tab.title ?? sessionLabel\n const active = tab.sessionId === currentId\n const pinned = tab.pinned === true\n const indicator = tabIndicator(summary, statuses.get(tab.sessionId))\n // The project this session belongs to. Absent for a session that is in\n // no workspace (a bare session, or one just created before the\n // registry caught up) — the chip then shows the title alone rather\n // than a placeholder.\n const project = projects.get(tab.sessionId)\n // Title attribute carries the full pair plus the directory, so the\n // truncated chip text is recoverable on hover.\n const tip = project === undefined\n ? label\n : `${project.label} · ${label}\\n${project.path}`\n const drop = dropTarget !== null && dropTarget.sessionId === tab.sessionId ? dropTarget.side : null\n const isEditing = editing !== null && editing.sessionId === tab.sessionId\n const draft = isEditing && editing !== null ? editing.draft : ''\n const className = [\n 'wgTab',\n active ? 'wgTabActive' : '',\n pinned ? 'wgTabPinned' : '',\n dragging === tab.sessionId ? 'wgTabDragging' : '',\n drop === 'before' ? 'wgTabDropBefore' : '',\n drop === 'after' ? 'wgTabDropAfter' : '',\n ].filter(part => part !== '').join(' ')\n return (\n {\n // Middle click closes, the way every other tab strip behaves. Only\n // button 1: a right click opens the menu instead.\n if (event.button !== 1) return\n event.preventDefault()\n actions.close(tab.sessionId)\n }}\n onContextMenu={(event) => {\n event.preventDefault()\n setEditing(null)\n setMenu({\n sessionId: tab.sessionId,\n // Clamp inside the viewport so a chip near the right edge does not\n // open a menu that runs off-screen.\n x: Math.min(event.clientX, window.innerWidth - 208),\n y: Math.min(event.clientY, window.innerHeight - 240),\n })\n }}\n onDragStart={(event) => {\n event.dataTransfer.effectAllowed = 'move'\n event.dataTransfer.setData('text/plain', tab.sessionId)\n setDragging(tab.sessionId)\n setMenu(null)\n }}\n onDragOver={(event) => {\n if (dragging === null || dragging === tab.sessionId) return\n event.preventDefault()\n event.dataTransfer.dropEffect = 'move'\n const rect = event.currentTarget.getBoundingClientRect()\n const side = event.clientX < rect.left + rect.width / 2 ? 'before' : 'after'\n setDropTarget({ sessionId: tab.sessionId, side })\n }}\n onDrop={(event) => {\n event.preventDefault()\n if (dragging !== null && dropTarget !== null) {\n const target = dropIndexFor(dragging, dropTarget)\n if (target !== null) actions.move(dragging, target)\n }\n setDragging(null)\n setDropTarget(null)\n dragEndedAt.current = Date.now()\n }}\n onDragEnd={() => {\n setDragging(null)\n setDropTarget(null)\n dragEndedAt.current = Date.now()\n }}\n >\n {isEditing ? (\n { event.currentTarget.select() }}\n onChange={(event) => { setEditing({ sessionId: tab.sessionId, draft: event.target.value }) }}\n onClick={(event) => { event.stopPropagation() }}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n commitEdit()\n } else if (event.key === 'Escape') {\n event.preventDefault()\n setEditing(null)\n }\n }}\n onBlur={() => { commitEdit() }}\n />\n ) : (\n <>\n {\n if (Date.now() - dragEndedAt.current < 250) return\n activate(tab.sessionId)\n }}\n onDoubleClick={() => { startEdit(tab.sessionId, label) }}\n >\n \n \n \n {/* Two stacked lines, folder-style: the project (short, quiet)\n over the session title (long, primary). The project line is\n omitted for a session in no workspace, which lets the title\n use the full height rather than leaving a blank row. */}\n \n {project !== undefined && (\n {project.label}\n )}\n {label}\n \n \n {pinned && (\n \n \n \n )}\n \n {\n event.stopPropagation()\n actions.close(tab.sessionId)\n }}\n >\n \n \n \n \n )}\n
\n )\n })\n\n // The menu's chip, resolved against the current strip: a menu opened on a chip\n // that has since disappeared renders nothing rather than acting on a stale id.\n const menuTab = menu === null ? undefined : display.find(tab => tab.sessionId === menu.sessionId)\n const menuIndex = menuTab === undefined ? -1 : at(display, menuTab)\n const menuLabel = menuTab === undefined\n ? ''\n : menuTab.title ?? list.byId[menuTab.sessionId]?.displayTitle ?? menuTab.sessionId\n const menuPinned = menuTab?.pinned === true\n const canCloseRight = menuIndex >= 0 && menuIndex < display.length - 1\n\n return createPortal(\n <>\n
\n {\n // A plain wheel reports only `deltaY`, and the overflow here is\n // horizontal, so without this the wheel would do nothing over the\n // strip (or scroll the transcript behind it). Redirect the dominant\n // delta to scrollLeft, and only swallow the event once there is\n // somewhere left to scroll — otherwise a wheel at either end keeps\n // propagating and the page still scrolls normally.\n const el = event.currentTarget\n if (el.scrollWidth <= el.clientWidth) return\n const delta = Math.abs(event.deltaY) > Math.abs(event.deltaX) ? event.deltaY : event.deltaX\n if (delta === 0) return\n const atStart = el.scrollLeft <= 0 && delta < 0\n const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 1 && delta > 0\n if (atStart || atEnd) return\n el.scrollLeft += delta\n event.preventDefault()\n }}\n >\n {chips}\n
\n \n {menu !== null && menuTab !== undefined && createPortal(\n \n {\n actions.pin(menu.sessionId)\n setMenu(null)\n }}\n />\n { startEdit(menu.sessionId, menuLabel) }}\n />\n {\n setMenu(null)\n rename(menu.sessionId, menuLabel)\n }}\n />\n
\n {\n setMenu(null)\n actions.close(menu.sessionId)\n }}\n />\n {\n setMenu(null)\n actions.closeOthers(menu.sessionId)\n }}\n />\n {\n setMenu(null)\n actions.closeAfter(menu.sessionId)\n }}\n />\n
,\n document.body,\n )}\n ,\n seat,\n )\n}\n\n/** Index of one tab in the strip, used by the menu's range actions. */\nfunction at(tabs: readonly SessionTab[], target: SessionTab): number {\n return tabs.findIndex(tab => tab.sessionId === target.sessionId)\n}\n","/**\r\n * The \"flower branch\" geometry for the sidebar tree.\r\n *\r\n * Reproduces the RewampUI *Flower Sidebar* mechanism: a single curly branch runs\r\n * down the left of the nav list, drawn as SVG so it can be *grown* — a faded\r\n * dashed ghost shows the whole route, and a solid stroke is drawn only as far as\r\n * the row you are on. Each row gets a dot sitting exactly on the curve, and the\r\n * active row's dot blooms.\r\n *\r\n * How it maps onto OUR tree (three levels: 分组 folder → 项目 folder → 会话 row):\r\n *\r\n * - The branch is **one continuous path** through every visible row, not one\r\n * rail per folder. That is what makes it read as a plant rather than as the\r\n * per-folder rail it replaces.\r\n * - The stem runs at `STEM_X`; at each **group boundary** it kinks outward to\r\n * `BULGE_X` and back — a half-pitch out plus a half-pitch back, which is\r\n * exactly the reference's 32px rhythm.\r\n * - Rows that are not group boundaries sit on a straight run, one row pitch\r\n * apart, each carrying a dot at its own y.\r\n *\r\n * Runtime-free on purpose (same discipline as `tabs.ts` / `store-core.ts`): the\r\n * component measures the DOM and hands plain numbers here, so the geometry is\r\n * unit-testable without a browser.\r\n */\r\n\r\n/** Horizontal position of the stem's straight runs. */\r\n/**\r\n * Default x for a row's anchor, in SVG coordinates.\r\n *\r\n * A fallback only: rows carry their OWN measured `x`, because the tree indents\r\n * with per-row padding rather than one shared origin. A folder's chevron and a\r\n * session's text sit at different x, and no single constant lands on both.\r\n */\r\nexport const STEM_X = 30\r\n\r\n/** Default vertical pitch between two rows. */\r\nexport const ROW_PITCH = 32\r\n\r\n/**\r\n * One row the branch must pass through.\r\n *\r\n * Both coordinates are MEASURED, not derived:\r\n * - `y` because the tree mixes row heights and inter-row gaps (deriving one\r\n * pitch from a single gap drifted the dots up to 15px off their rows);\r\n * - `x` because the tree indents per row via padding, so a folder's chevron and\r\n * a session's text are at different x.\r\n */\r\nexport interface BranchRow {\r\n /** Stable key, used to match a row to its dot. */\r\n readonly key: string\r\n /** Row centre y, in the SVG's coordinate space. */\r\n readonly y: number\r\n /**\r\n * Row anchor x, in the SVG's coordinate space.\r\n *\r\n * A folder row's anchor is its CHEVRON centre — the triangle the user already\r\n * reads as \"this row opens\" — so the stem visually hangs off the marker rather\r\n * than floating beside it. A session row's anchor is the indent its text sits\r\n * on.\r\n */\r\n readonly x: number\r\n /**\r\n * Row kind. A `'group'` row starts a new group and makes the stem kink;\r\n * an `'item'` row runs straight (or curves back in right after a group).\r\n */\r\n readonly kind: 'group' | 'item'\r\n /** Whether this is the row the user is currently on (the bloomed dot). */\r\n readonly active: boolean\r\n}\r\n\r\n/** A dot on the branch: one per row, positioned on the curve. */\r\nexport interface BranchDot {\r\n /** The row this dot belongs to. */\r\n readonly key: string\r\n readonly cx: number\r\n readonly cy: number\r\n readonly active: boolean\r\n}\r\n\r\n/**\r\n * The bloom that flowers at the branch's endpoint.\r\n *\r\n * The endpoint is where the GROWN stroke stops — the row the user is on — not\r\n * the last visible row: the stem is drawn to the active row, so that is where\r\n * the plant has visibly reached, whether the tree is folded above it or not.\r\n *\r\n * This is deliberately the ONE row an active marker names, so the flower can\r\n * never disagree with the stem about where the branch ends.\r\n */\r\nexport interface BranchFlower {\r\n /** Row whose endpoint carries the bloom (the active row's key). */\r\n readonly key: string\r\n /** Endpoint x: the last dot's centre, i.e. exactly where the grown path stops. */\r\n readonly cx: number\r\n /** Endpoint y, on the measured row centre. */\r\n readonly cy: number\r\n}\r\n\r\n/** The branch: one path for the ghost, its total length, and the dots. */\r\nexport interface Branch {\r\n /** Full route, drawn as the faded dashed ghost. */\r\n readonly ghostPath: string\r\n /** Path up to and including the active row (the \"grown\" part). */\r\n readonly grownPath: string\r\n /** Drawn length of the full route. */\r\n readonly ghostLength: number\r\n /** Drawn length of the grown part. */\r\n readonly grownLength: number\r\n /** Dots, in row order. */\r\n readonly dots: readonly BranchDot[]\r\n /**\r\n * Bloom at the grown path's endpoint, or NULL when no row carries the active\r\n * marker.\r\n *\r\n * Deliberately stricter than `grownPath`: the stem has to be *some* path even\r\n * when nothing is active (it collapses to the bare origin, drawing nothing),\r\n * but a bloom with no active row has nothing to be the flower OF. Falling back\r\n * to the first dot — the earlier rule — put the blossom on a folder row at the\r\n * top of the tree as soon as the open session's folder was collapsed, because\r\n * folding removes the only row carrying the marker. No active row means no\r\n * flower.\r\n */\r\n readonly flower: BranchFlower | null\r\n /** Total vertical extent, so the SVG box can be sized. */\r\n readonly height: number\r\n}\r\n\r\n/**\r\n * Internal: one move of the route, kept as STRUCTURE rather than only as a path\r\n * string. The endpoint trim below has to shorten the final move along its own\r\n * direction, which is only sound if the segment still knows where it goes.\r\n */\r\ninterface Segment {\r\n /** SVG path command for the full move. */\r\n readonly d: string\r\n /** Length the move contributes to the run. */\r\n readonly length: number\r\n /** Where the move starts. */\r\n readonly from: { readonly x: number; readonly y: number }\r\n /** Where the move ends. */\r\n readonly to: { readonly x: number; readonly y: number }\r\n /** Bulge x for a curved move (the curve is vertical-tangent at both ends). */\r\n readonly controlX?: number\r\n}\r\n\r\n/**\r\n * Plan the route: one segment per row after the first, plus the dot positions.\r\n *\r\n * Kept separate from the string assembly so the length walk and the SVG `d`\r\n * always describe the same geometry — measuring one path against another is how\r\n * a grown/ghost pair drifts out of sync.\r\n *\r\n * The stem lands on each row's OWN anchor (x) and centre (y), so uneven row\r\n * heights and the tree's per-row indents both stay exact. A group row's anchor\r\n * is pushed out by `BULGE_OFFSET`, which is what creates the kink.\r\n *\r\n * @param rows - visible rows in render order, carrying measured anchors.\r\n * @returns the per-row segments and dot x positions.\r\n */\r\nfunction plan(rows: readonly BranchRow[]): { segments: Segment[]; dotX: number[] } {\r\n const segments: Segment[] = []\r\n const first = rows[0] as BranchRow\r\n const dotX: number[] = [first.x]\r\n let x = first.x\r\n\r\n for (let i = 1; i < rows.length; i += 1) {\r\n const row = rows[i] as BranchRow\r\n const prev = rows[i - 1] as BranchRow\r\n const startY = prev.y\r\n const endY = row.y\r\n const midY = startY + (endY - startY) / 2\r\n\r\n // Every dot lands on its OWN anchor; the stem simply travels between them.\r\n // When two consecutive rows share an anchor (sessions under one project) the\r\n // travel is a straight run; when it changes (a folder's chevron sits left of\r\n // its children's dots) the stem swings out through an S-curve, which is what\r\n // reads as the branch stepping around the folder marker.\r\n const target = row.x\r\n\r\n if (target === x) {\r\n segments.push({\r\n d: `L ${x} ${endY}`,\r\n length: Math.abs(endY - startY),\r\n from: { x, y: startY },\r\n to: { x, y: endY },\r\n })\r\n } else {\r\n // Two halves so the tangent is vertical at both ends, matching the\r\n // reference's curve rhythm.\r\n segments.push({\r\n d: `C ${x} ${midY}, ${target} ${midY}, ${target} ${endY}`,\r\n length: Math.hypot(target - x, endY - midY),\r\n from: { x, y: startY },\r\n to: { x: target, y: endY },\r\n controlX: x,\r\n })\r\n x = target\r\n }\r\n dotX.push(x)\r\n }\r\n\r\n return { segments, dotX }\r\n}\r\n\r\n/**\r\n * How far short of the flower's centre the stem stops, in SVG user units.\r\n *\r\n * The bloom is drawn ON the endpoint, so a stem that runs all the way to the\r\n * centre is visible through the petal notches and reads as a line crossing the\r\n * flower. Stopping the stroke at (a little over) the bloom's radius keeps the\r\n * stem ending cleanly at the flower's edge, where it reads as a stalk holding\r\n * the bloom.\r\n *\r\n * 7 units ≈ the 6.2-unit flower radius plus a hair, so the stroke's round cap\r\n * tucks just under the outer petals without a visible gap.\r\n */\r\nexport const STEM_END_CLEARANCE = 7\r\n\r\n/**\r\n * Shorten a move so it stops `clearance` short of its end point.\r\n *\r\n * Used only on the LAST move of the grown run, which is what hides the stroke\r\n * behind the bloom. A straight move is trimmed along its axis; a curved move is\r\n * trimmed by moving its end and its control point together, which shortens the\r\n * curve while keeping its vertical tangents (so the kink's shape is preserved\r\n * rather than being flattened into a line).\r\n *\r\n * Returns the move unchanged when it is too short to trim (the stem would\r\n * invert), so a cramped layout degrades to \"line meets flower\" rather than\r\n * producing a backwards path.\r\n *\r\n * @param segment - the move to shorten.\r\n * @param clearance - distance to stop short of the end.\r\n * @returns the shortened move.\r\n */\r\nfunction trimEnd(segment: Segment, clearance: number): Segment {\r\n const { from, to } = segment\r\n const span = Math.hypot(to.x - from.x, to.y - from.y)\r\n if (span <= clearance) return segment\r\n\r\n if (segment.controlX === undefined) {\r\n // Straight: retreat along the axis by the clearance.\r\n const ratio = (span - clearance) / span\r\n const endX = from.x + (to.x - from.x) * ratio\r\n const endY = from.y + (to.y - from.y) * ratio\r\n return { ...segment, d: `L ${endX} ${endY}`, to: { x: endX, y: endY }, length: span - clearance }\r\n }\r\n\r\n // Curved: the move is two mirrored halves, so retreating the END by half the\r\n // clearance and the control point by the full one shortens it symmetrically\r\n // while keeping both tangents vertical.\r\n const endY = to.y - clearance\r\n const controlY = from.y + (to.y - from.y) / 2 - clearance\r\n const endX = to.x\r\n return {\r\n ...segment,\r\n d: `C ${segment.controlX} ${controlY}, ${endX} ${controlY}, ${endX} ${endY}`,\r\n to: { x: endX, y: endY },\r\n length: Math.max(0, segment.length - clearance),\r\n }\r\n}\r\n\r\n/**\r\n * Build the branch for a list of rows.\r\n *\r\n * @param rows - visible rows in render order, each carrying its MEASURED centre.\r\n * @returns the branch geometry; empty strings when there are no rows.\r\n */\r\nexport function buildBranch(rows: readonly BranchRow[]): Branch {\r\n const first = rows[0]\r\n if (first === undefined) {\r\n return { ghostPath: '', grownPath: '', ghostLength: 0, grownLength: 0, dots: [], flower: null, height: 0 }\r\n }\r\n\r\n const { segments, dotX } = plan(rows)\r\n const head = `M ${first.x} ${first.y}`\r\n\r\n const dots: BranchDot[] = rows.map((row, index) => ({\r\n key: row.key,\r\n cx: dotX[index] ?? row.x,\r\n cy: row.y,\r\n active: row.active,\r\n }))\r\n\r\n // The grown stroke stops AT the active row, so its path contains every\r\n // segment before that row and none after. An active first row grows nothing\r\n // beyond the origin, which is correct (the dot sits on the stem origin).\r\n //\r\n // `activeIndex < 0` is the NO-ACTIVE-ROW case: the open session's folder was\r\n // collapsed, or the catalog has not resolved yet. The stem then collapses to\r\n // the bare origin (drawing nothing), and — crucially — `hasActive` stays false\r\n // so no flower is produced. Conflating this with \"the first row is active\" is\r\n // what used to sprout the blossom on a top-level folder row.\r\n const activeIndex = rows.findIndex(row => row.active)\r\n const hasActive = activeIndex >= 0\r\n const grownTo = hasActive ? activeIndex : 0\r\n\r\n // The bloom sits on the endpoint of `grownPath`, which `join` puts at the\r\n // active row. It therefore uses the SAME index as the grown stroke, so the\r\n // flower and the stem can never disagree about where the branch ends — and it\r\n // exists ONLY when a row actually claimed the marker.\r\n const flowerAt = dots[grownTo] as BranchDot | undefined\r\n const flower: BranchFlower | null = hasActive && flowerAt !== undefined\r\n ? { key: flowerAt.key, cx: flowerAt.cx, cy: flowerAt.cy }\r\n : null\r\n\r\n const join = (list: readonly Segment[]): string =>\r\n list.length === 0 ? head : [head, ...list.map(s => s.d)].join(' ')\r\n\r\n // The grown run: every move before the active row, plus the move INTO it —\r\n // which is the one trimmed so the stroke stops at the bloom's edge instead of\r\n // crossing the flower. The GHOST keeps its full length: it is a faint dashed\r\n // route at 28% opacity, and shortening it too would leave the last row's\r\n // guide visibly detached from that row.\r\n const grownSegments = segments.slice(0, grownTo)\r\n const lastGrown = grownSegments[grownSegments.length - 1]\r\n const grownStroke = lastGrown === undefined\r\n ? grownSegments\r\n : [...grownSegments.slice(0, -1), trimEnd(lastGrown, STEM_END_CLEARANCE)]\r\n\r\n const lengthOf = (count: number): number =>\r\n segments.slice(0, count).reduce((sum, s) => sum + s.length, 0)\r\n\r\n const last = rows[rows.length - 1] as BranchRow\r\n // Half a row height of breathing room below the last dot, so the stem does not\r\n // stop dead on the final row.\r\n const tail = rows.length > 1 ? Math.abs(last.y - (rows[rows.length - 2] as BranchRow).y) / 2 : 0\r\n\r\n return {\r\n ghostPath: join(segments),\r\n grownPath: join(grownStroke),\r\n ghostLength: lengthOf(segments.length),\r\n // The grown length follows the TRIMMED run, so a consumer measuring the\r\n // stroke (a dash animation, say) stays consistent with what is drawn.\r\n grownLength: Math.max(0, lengthOf(grownTo) - (lastGrown === undefined ? 0 : STEM_END_CLEARANCE)),\r\n dots,\r\n flower,\r\n height: last.y + tail,\r\n }\r\n}\r\n","/**\r\n * The flower marker: an SVG overlay that draws a single bloom on the row you are\r\n * currently on.\r\n *\r\n * Originally ported from the RewampUI *Flower Sidebar* reference, which drew a\r\n * continuous curly stem down the whole tree — a dashed \"ghost\" route plus a\r\n * solid stroke \"grown\" to the active row — with a dot on every row and the bloom\r\n * at its tip. **The stem and the dots are gone**: they read as a stray black line\r\n * down the sidebar, and depth is already carried by the row indentation. Only the\r\n * bloom remains, still spinning while the current session works and resting when\r\n * it is idle.\r\n *\r\n * The SVG is `pointer-events: none` and `overflow: visible`, so it is pure\r\n * decoration over the real rows and never intercepts a click.\r\n *\r\n * Measurement, not layout: the rows are rendered by the tree itself (they carry\r\n * drag handlers, menus and hover state), so this component reads each row's\r\n * vertical centre and anchor from the DOM and feeds plain numbers to\r\n * `buildBranch`. That keeps the geometry unit-tested (`branch.ts`) while the SVG\r\n * stays a dumb renderer of it — and leaves the branch math intact should the stem\r\n * ever come back.\r\n *\r\n * Re-measured on: row count changes (expand/collapse, new session), the active\r\n * row changing, and container resize. A `ResizeObserver` on the scroll body\r\n * covers the last one without a window listener.\r\n *\r\n * The bloom's spin is NOT re-measured here: it arrives as the `spinning` prop\r\n * and is applied as a class, so a status flip never re-runs the DOM measurement\r\n * above (the tree is the expensive part, not the class swap).\r\n */\r\nimport { useEffect, useRef, useState } from 'react'\r\nimport { buildBranch, type Branch, type BranchRow } from './branch.ts'\r\n\r\n/**\r\n * Attribute the tree puts on every row the branch should connect. */\r\nexport const BRANCH_ROW_ATTRIBUTE = 'data-wg-branch-row'\r\n\r\n/**\r\n * Attribute marking the row the stem should grow to.\r\n *\r\n * Only the DEEPEST row gets this (the session). Its ancestors — the project and\r\n * the category that contain it — deliberately do NOT, because a session belongs\r\n * to both and marking all three would make \"which row is active?\" ambiguous.\r\n * When several rows do carry it, the deepest (last in document order) wins.\r\n */\r\nexport const BRANCH_ACTIVE_ATTRIBUTE = 'data-wg-branch-active'\r\n\r\n/** Row kind marker: a group boundary kinks the stem. */\r\nexport const BRANCH_GROUP_ATTRIBUTE = 'data-wg-branch-group'\r\n\r\n/**\r\n * The bloom's petal outline, in the 1024-unit box the artwork was drawn in.\r\n *\r\n * This is the user's own flower glyph verbatim: an eight-petal bloom around a\r\n * ringed center. Kept as a path (not a component) because it is a constant.\r\n */\r\nconst FLOWER_PATH = 'M375.3728 841.8432c92.96-12.5184 203.8784-71.264 299.5456-166.9248 22.6112-22.6112 43.1616-46.08 61.5232-69.952C712.7616 786.3936 621.2608 921.6 512 921.6c-51.1488 0-98.4-29.632-136.6272-79.7568z m-87.808-422.8096C311.2384 237.6064 402.7328 102.4 512 102.4c51.1488 0 98.4 29.632 136.6272 79.7568-92.96 12.5184-203.8784 71.264-299.5456 166.9248a719.1232 719.1232 0 0 0-61.5232 69.952z m-129.536 139.5648c57.3248 74.2464 163.6608 140.9344 294.336 175.9488a719.1232 719.1232 0 0 0 91.3472 18.304c-168.9664 70.208-331.808 58.5728-386.432-36.0512-25.5744-44.288-23.5456-100.032 0.7552-158.2016z m322.2592-287.4496c168.9664-70.208 331.808-58.5728 386.432 36.0512 25.5744 44.288 23.5456 100.032-0.7552 158.2016-57.3184-74.2464-163.648-140.9344-294.336-175.9488a719.1232 719.1232 0 0 0-91.3408-18.304zM294.656 228.7552c-35.6352 86.7648-40.224 212.1984-5.2032 342.8736a719.1232 719.1232 0 0 0 29.8176 88.256C173.9904 548.6592 102.6432 401.824 157.2736 307.2c25.5744-44.288 74.8608-70.4 137.3824-78.4448z m410.0736 135.36c145.28 111.2256 216.6272 258.0608 161.9968 352.6848-25.5744 44.288-74.8608 70.4-137.3824 78.4448 35.6352-86.7648 40.224-212.1984 5.2032-342.8736a719.1232 719.1232 0 0 0-29.8176-88.256zM512 678.4c-88.3648 0-160-71.6352-160-160s71.6352-160 160-160 160 71.6352 160 160-71.6352 160-160 160z m0-83.2c42.4128 0 76.8-34.3872 76.8-76.8s-34.3872-76.8-76.8-76.8-76.8 34.3872-76.8 76.8 34.3872 76.8 76.8 76.8z'\r\n\r\n/** Petal colour: the accent the glyph was drawn in. */\r\nconst FLOWER_PETAL = '#fa541c'\r\n\r\n/**\r\n * Rendered size of the bloom, as a scale factor over the authored 1024 box.\r\n *\r\n * 17 / 1024 ≈ 0.0166 puts the flower at ~17px: clear of neighbouring rows (rows\r\n * are 28px tall) while still reading as a flower rather than a dot at the end of\r\n * the stem.\r\n */\r\nconst FLOWER_SCALE = 17 / 1024\r\n\r\n/**\r\n * Centre of the artwork inside its own 1024-unit box, measured from the path.\r\n *\r\n * Both the recentring AND the rotation are expressed with this ONE pair of user\r\n * units, so neither depends on a percentage or on a reference box. Verified\r\n * against the live DOM: the path's own `getBBox()` centre is exactly (512, 512).\r\n */\r\nconst FLOWER_CENTRE = 512\r\n\r\n/**\r\n * The bloom at the branch's endpoint.\r\n *\r\n * Anchoring is done entirely by these transforms, in this order:\r\n *\r\n * 1. `translate(cx cy)` — put the origin on the stem's tip (the endpoint of\r\n * the grown stroke).\r\n * 2. `scale(FLOWER_SCALE)` — shrink the 1024-unit artwork about that origin.\r\n * 3. `translate(-512 -512)` — bring the glyph's own centre (512, 512) onto the\r\n * origin, so the flower is centred on the tip.\r\n *\r\n * The spin is applied by `wgFlowerArt` in CSS as a `rotate()` composed AFTER\r\n * that recentring (`translate(-512 -512) rotate(...)`), so the bloom turns about\r\n * its own centre and the recentring never drifts as it rotates.\r\n *\r\n * Note what is deliberately NOT used here: a percentage `translate(-50%, -50%)`\r\n * or `transform-box: fill-box` + percentage `transform-origin`. Measured on the\r\n * live page, the percentage form resolved against the SVG VIEWPORT rather than\r\n * the path's box, translating by (-24, -409.5) instead of (-373, -409.6) and\r\n * parking the bloom well right of the stem. Explicit user units remove the\r\n * question: 512 is the measured centre, not an inferred one.\r\n *\r\n * The flower rests while the session is idle and turns while it works: one\r\n * animation, paused rather than removed, so a state flip resumes the turn\r\n * instead of snapping the petals back to 0deg.\r\n *\r\n * @param props - endpoint coordinates and whether the session is working.\r\n * @returns the bloom group.\r\n */\r\nfunction Flower({ cx, cy, spinning }: { cx: number; cy: number; spinning: boolean }) {\r\n return (\r\n \r\n \r\n \r\n )\r\n}\r\n\r\n/**\r\n * Render the branch for the rows currently inside `scope`.\r\n * @param props - the element to measure, and whether the open session is working.\r\n * @returns the SVG overlay, or null until at least one row is measured.\r\n */\r\nexport function FlowerBranch({ scope, spinning }: { scope: HTMLElement | null; spinning: boolean }) {\r\n const [rows, setRows] = useState([])\r\n\r\n // A cheap change key: the caller cannot tell us when a row expanded, so we\r\n // watch the attribute count and the active row instead of diffing every node.\r\n const measureKey = useRef('')\r\n // The measured pixel pitch is per-list, not the module default: our rows are\r\n // 28/30px tall in places, and assuming 32 would drift the dots off the rows.\r\n const [branch, setBranch] = useState(null)\r\n\r\n useEffect(() => {\r\n if (scope === null) {\r\n setRows([])\r\n setBranch(null)\r\n return\r\n }\r\n\r\n const measure = (): void => {\r\n const nodes = Array.from(scope.querySelectorAll(`[${BRANCH_ROW_ATTRIBUTE}]`))\r\n const first = nodes[0]\r\n if (first === undefined) {\r\n if (measureKey.current !== '') {\r\n measureKey.current = ''\r\n setRows([])\r\n setBranch(null)\r\n }\r\n return\r\n }\r\n\r\n // Exactly one row carries the marker (the session); if a caller ever marks\r\n // several, the deepest wins so the stem still lands on a real leaf.\r\n const activeIndex = nodes.reduce(\r\n (found, node, index) => (node.hasAttribute(BRANCH_ACTIVE_ATTRIBUTE) ? index : found),\r\n -1,\r\n )\r\n const kinds = nodes.map(n => (n.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item')).join('')\r\n const key = `${nodes.length}|${activeIndex}|${kinds}|${Math.round(scope.clientWidth)}`\r\n if (key === measureKey.current) return\r\n measureKey.current = key\r\n\r\n // Each row carries its OWN measured anchor: y because the tree mixes row\r\n // heights, x because it indents per row via padding (a folder's chevron and\r\n // a session's text do not share an x).\r\n const measured: BranchRow[] = nodes.map((node, index) => ({\r\n key: `${index}`,\r\n y: center(node),\r\n x: anchorX(node),\r\n kind: node.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item',\r\n active: index === activeIndex,\r\n }))\r\n\r\n setRows(measured)\r\n setBranch(buildBranch(measured))\r\n }\r\n\r\n /** Vertical centre of a node, relative to the scope box. */\r\n function center(node: HTMLElement): number {\r\n const r = node.getBoundingClientRect()\r\n const s = (scope as HTMLElement).getBoundingClientRect()\r\n return r.top - s.top + r.height / 2\r\n }\r\n\r\n /**\r\n * Horizontal anchor of a row, relative to the scope box.\r\n *\r\n * A row with a chevron anchors to that triangle's CENTRE: it is the marker\r\n * the user already reads as \"this row opens\", so the stem hangs off it\r\n * instead of floating beside it. A chevron-less row (a session) has no\r\n * marker, so it anchors to where its own content starts — the status dot's\r\n * centre, which is the first thing in the row.\r\n */\r\n function anchorX(node: HTMLElement): number {\r\n const s = (scope as HTMLElement).getBoundingClientRect()\r\n const marker = node.querySelector('.wgChevron')\r\n ?? node.querySelector('[class*=\"wgStatusSlot\"]')\r\n ?? node.querySelector('[class*=\"wgCategoryIcon\"]')\r\n ?? node.querySelector('[class*=\"wgRowIcon\"]')\r\n const box = (marker ?? node).getBoundingClientRect()\r\n return box.left - s.left + box.width / 2\r\n }\r\n\r\n measure()\r\n\r\n // Row set changes (expand/collapse/new session) arrive as childList edits.\r\n const observer = new MutationObserver(measure)\r\n observer.observe(scope, { childList: true, subtree: true, attributes: true, attributeFilter: [BRANCH_ACTIVE_ATTRIBUTE] })\r\n\r\n // Width changes reflow row heights in the rail/wide layouts.\r\n const resizer = new ResizeObserver(measure)\r\n resizer.observe(scope)\r\n\r\n return () => {\r\n observer.disconnect()\r\n resizer.disconnect()\r\n }\r\n }, [scope])\r\n\r\n if (branch === null || rows.length === 0) return null\r\n\r\n // Only the bloom is drawn. The stem (ghost + grown stroke) and the per-row\r\n // dots were removed on request: they read as a stray black line down the\r\n // sidebar and the depth is already carried by the indentation, so the flower\r\n // alone marks the row you are on. `branch` is still BUILT from the measured\r\n // rows — it is what gives the bloom its position — but its path geometry is\r\n // no longer rendered.\r\n if (branch.flower === null) return null\r\n\r\n return (\r\n \r\n \r\n \r\n )\r\n}\r\n","/**\r\n * The workspace-groups browsing region filling the sidebar shell's\r\n * `sidebar.workspaces` hole: section header (title + right-aligned search +\r\n * new-group + add workspace), the three-level tree (category → workspace →\r\n * session), group management dialogs, and the workspace/session dialogs. Wide\r\n * state renders the full browser; rail state renders the two region icons\r\n * (search / add workspace) as 36px controls on the shell's shared rail entry\r\n * path, each requesting expansion through the owner share.\r\n *\r\n * Data: workspaces/sessions via the framework global hooks; grouping config\r\n * via the host half's `/workspace-groups/config` route (refetched on mount).\r\n * Runtime group management (create/rename/delete any group, drag workspaces\r\n * between groups and into position, drag groups into position) persists\r\n * through `PUT /workspace-groups/manual`; the sidecar YAML is never rewritten\r\n * (rule-group rename/delete ride the overlay `renamed`/`hidden` maps).\r\n */\r\nimport { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'\r\nimport {\r\n Button,\r\n IconCloseFillMedium,\r\n IconFolderOpenOutlineRegular,\r\n IconProjectAddOutlineRegular,\r\n IconSearchOutlineRegular,\r\n IconWarningOutlineRegular,\r\n Modal,\r\n Toast,\r\n Tooltip,\r\n} from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'\r\nimport {\r\n displayCategoryKeys,\r\n isCategoryPinned,\r\n moveAfter,\r\n moveBefore,\r\n originalRuleNameForDisplay,\r\n pruneAppearance,\r\n resolveCategory,\r\n takenCategoryNames,\r\n} from '../core/matcher.ts'\r\nimport {\r\n GROUP_COLORS,\r\n GROUP_ICON_IDS,\r\n TOP_LEVEL_ORDER_KEY,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupColor,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from '../core/types.ts'\r\nimport type { GroupsBrowserProps } from './contract.ts'\r\nimport { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'\r\nimport { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'\r\nimport type { WorkspaceGroupsKey } from './locales.ts'\r\nimport { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'\r\nimport { QuickPanel } from './QuickPanel.tsx'\r\nimport { SessionTabs } from './SessionTabs.tsx'\r\nimport { FlowerBranch } from './FlowerBranch.tsx'\r\nimport css from './styles.css?inline'\r\n\r\nconst SEARCH_DEBOUNCE_MS = 250\r\nconst SEARCH_QUERY_MAX_CODE_UNITS = 500\r\n\r\n/** Overlay with every optional field materialized (plain-object edits, no undefined spreads). */\r\ntype NormalizedManual = Required\r\n\r\nconst EMPTY_MANUAL: NormalizedManual = {\r\n categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [], appearance: {},\r\n}\r\n\r\n/** Materialize optional overlay fields so every update is a plain object edit. */\r\nfunction normalizeManual(manual: ManualGroups): NormalizedManual {\r\n return {\r\n categories: manual.categories,\r\n assignments: manual.assignments,\r\n categoryOrder: manual.categoryOrder ?? [],\r\n workspaceOrder: manual.workspaceOrder ?? {},\r\n renamed: manual.renamed ?? {},\r\n hidden: manual.hidden ?? [],\r\n appearance: manual.appearance ?? {},\r\n }\r\n}\r\n\r\n/**\r\n * Largest subtree (rows including the level header) that still animates: a\r\n * 100-session project expanding with a grid animation janks the sidebar, so\r\n * wide subtrees snap open instead.\r\n */\r\nconst ANIMATION_ROW_CAP = 40\r\n\r\n/**\r\n * Mirrors the host icon validator (`parseAppearance`) so invalid custom glyphs\r\n * fail locally instead of turning the whole overlay PUT into a 400.\r\n */\r\nconst ICON_VALUE_PATTERN = /^(?:[a-z][a-z0-9-]{0,23}|[^\\s\\u0000-\\u001f\\u007f]{1,4})$/u\r\n\r\n/** Rows a group reveals when expanded (projects + their visible sessions). */\r\nfunction categoryRowCount(category: CategoryNode): number {\r\n return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0)\r\n}\r\n\r\n/** Palette id → i18n key for the colour picker (keeps literal key types intact). */\r\nconst COLOR_LABEL_KEYS: Record = {\r\n red: 'color.red',\r\n orange: 'color.orange',\r\n amber: 'color.amber',\r\n green: 'color.green',\r\n teal: 'color.teal',\r\n blue: 'color.blue',\r\n indigo: 'color.indigo',\r\n purple: 'color.purple',\r\n pink: 'color.pink',\r\n gray: 'color.gray',\r\n}\r\n\r\nfunction sanitizeSearchQuery(value: string): string {\r\n const withoutNul = value.replaceAll('\\0', '')\r\n if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul\r\n return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS)\r\n}\r\n\r\n/** Immutable membership toggle for the local expand-all array. */\r\nfunction toggled(list: readonly string[], key: string): string[] {\r\n return list.includes(key) ? list.filter(k => k !== key) : [...list, key]\r\n}\r\n\r\ninterface RemoteSearchState {\r\n query: string\r\n status: 'idle' | 'loading' | 'ready' | 'error'\r\n items: readonly SessionSearchResultItem[]\r\n hasMore: boolean\r\n}\r\n\r\n/** Light runtime guard for the manual overlay attached to the config fetch. */\r\nfunction isManualGroups(value: unknown): value is ManualGroups {\r\n if (typeof value !== 'object' || value === null) return false\r\n const candidate = value as { categories?: unknown; assignments?: unknown }\r\n return Array.isArray(candidate.categories) && typeof candidate.assignments === 'object' && candidate.assignments !== null\r\n}\r\n\r\n/** Minimal fetch of the grouping config + runtime overlay (no-cache revalidation). */\r\nasync function fetchGroupsConfig(): Promise<{ config: GroupsConfig; manual: NormalizedManual }> {\r\n const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })\r\n if (!response.ok) throw new Error(`config request failed: ${response.status}`)\r\n const body = (await response.json()) as GroupsConfig\r\n const config: GroupsConfig = Array.isArray(body.categories) ? body : { categories: [] }\r\n return { config, manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL }\r\n}\r\n\r\n/** Persist the whole runtime overlay (idempotent; the host validates + writes). */\r\nasync function saveManualOverlay(manual: ManualGroups): Promise {\r\n const response = await fetch('/workspace-groups/manual', {\r\n method: 'PUT',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify(manual),\r\n })\r\n if (!response.ok) {\r\n let message = `manual save failed: ${response.status}`\r\n try {\r\n const text = await response.text()\r\n if (text !== '') message = text\r\n } catch { /* keep the fallback message */ }\r\n throw new Error(message)\r\n }\r\n}\r\n\r\n/** One group-management dialog state: create, or rename an existing group. */\r\ntype GroupDialogState = { mode: 'create' } | { mode: 'rename'; from: string } | null\r\n\r\n/** Row reference used by drop targets: which kind of row, which key. */\r\nexport type DropRowRef = { kind: 'category' | 'workspace' | 'topLevel'; key: string }\r\n\r\n/**\r\n * Which level's rows fold while a drag is in progress: dragging a project\r\n * folds every project row (grouped AND top-level), dragging a group folds\r\n * every group row. The other level keeps its expansion untouched.\r\n */\r\nexport type DragLevel = 'workspace' | 'category' | null\r\n\r\n/**\r\n * Current drop indicator. A `line` renders a 2px insertion line above/below a\r\n * row (project reorder inside a group, or group reorder); an `into` renders\r\n * the whole-row highlight used when dropping a project into a group. Drop\r\n * handlers re-derive before/after from the drop event itself, so the\r\n * indicator is purely visual and can never go stale.\r\n */\r\nexport type DragIndicator =\r\n | { mode: 'line'; row: DropRowRef; before: boolean }\r\n | { mode: 'into'; categoryKey: string }\r\n | null\r\n\r\n/**\r\n * Render the browsing region.\r\n * @param props - composed slot props (shell owner share + store + injected actions).\r\n * @returns the region element tree.\r\n */\r\nexport function GroupsBrowser({\r\n wide,\r\n expandSidebar,\r\n useSessions,\r\n useWorkspaces,\r\n useSessionStatus,\r\n useStore,\r\n actions,\r\n startSession,\r\n open,\r\n renameSession,\r\n forkSession,\r\n renameWorkspace,\r\n deleteWorkspace,\r\n insertWorkspaceBefore,\r\n archiveSession,\r\n insertSessionBefore,\r\n createWorkspace,\r\n pickDirectory,\r\n searchSessions,\r\n searchResultLimit,\r\n openTab,\r\n useTabs,\r\n tabActions,\r\n t,\r\n}: GroupsBrowserProps) {\r\n // Inject the stylesheet once per fiber; dispose removes it (HMR safe).\r\n useEffect(() => {\r\n const style = document.createElement('style')\r\n style.setAttribute('data-plugin', 'dsh-workspace-groups')\r\n style.textContent = css\r\n document.head.append(style)\r\n return () => { style.remove() }\r\n }, [])\r\n\r\n // Ctrl+R toggles the quick switch panel. Capture phase + preventDefault:\r\n // beats the browser's page-reload default and any shell-level handler.\r\n const [quickOpen, setQuickOpen] = useState(false)\r\n useEffect(() => {\r\n const onKeyDown = (e: KeyboardEvent): void => {\r\n if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (e.key === 'r' || e.key === 'R')) {\r\n e.preventDefault()\r\n e.stopPropagation()\r\n setQuickOpen(v => !v)\r\n }\r\n }\r\n window.addEventListener('keydown', onKeyDown, true)\r\n return () => window.removeEventListener('keydown', onKeyDown, true)\r\n }, [])\r\n\r\n // Grouping config from the host route + the runtime manual overlay.\r\n const [config, setConfig] = useState({ categories: [] })\r\n const [manual, setManual] = useState(EMPTY_MANUAL)\r\n const [configError, setConfigError] = useState(null)\r\n const reloadConfig = () => {\r\n setConfigError(null)\r\n fetchGroupsConfig().then(({ config: nextConfig, manual: nextManual }) => {\r\n setConfig(nextConfig)\r\n setManual(nextManual)\r\n }).catch((reason: unknown) => {\r\n setConfigError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n useEffect(() => { reloadConfig() }, [])\r\n\r\n // Transient save errors for drag/menu group operations (dialog errors are local).\r\n const [manualError, setManualError] = useState(null)\r\n const [manualSaving, setManualSaving] = useState(false)\r\n\r\n const workspaces = useWorkspaces(state => state.items)\r\n const workspacePhase = useWorkspaces(state => state.phase)\r\n const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)\r\n const categoryExpansion = useStore(s => s.categoryExpansion)\r\n const workspaceExpansion = useStore(s => s.workspaceExpansion)\r\n\r\n const list = useSessions(s => s)\r\n const statuses = useSessionStatus(s => s)\r\n // 0.1.6: the selected Session is the one retained through `mainView`, not a\r\n // `list.current` field (the list snapshot carries catalog facts only).\r\n const current = currentSessionId(list)\r\n const currentWorkspaceKey = current === undefined\r\n ? undefined\r\n : (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)\r\n\r\n // Whether the open session is WORKING right now, which is what makes the\r\n // flower at the branch's endpoint turn. Read from the unified status snapshot\r\n // (the catalog summary alone goes stale), folded together with the session's\r\n // own `running` so a subagent-only turn still counts.\r\n //\r\n // Derived as a boolean on purpose: the overlay re-measures through its own\r\n // MutationObserver, so handing it a live value would re-render the tree on\r\n // every status tick.\r\n const currentRunning = current !== undefined\r\n && ((statuses.get(current)?.running ?? false) || (list.byId[current]?.running ?? false))\r\n\r\n // Auto-expand the category + workspace containing the current session, but\r\n // ONLY when the user has never touched that key (`Object.hasOwn`): a\r\n // present `false` is a deliberate collapse and must stay folded. Without\r\n // this guard the effect re-expands the just-collapsed current category on\r\n // every store change (the reported \"cannot collapse\" bug).\r\n useEffect(() => {\r\n if (current === undefined || currentWorkspaceKey === undefined) return\r\n const category = categoriesForCurrent(config, workspaces, current, manual)\r\n if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {\r\n actions.setCategoryExpanded(category, true)\r\n }\r\n if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {\r\n actions.setWorkspaceExpanded(currentWorkspaceKey, true)\r\n }\r\n }, [current, currentWorkspaceKey, config, workspaces, manual, categoryExpansion, workspaceExpansion, actions])\r\n\r\n // Drop expansion keys that no longer exist (group edits / workspace deletion).\r\n useEffect(() => {\r\n if (workspacePhase !== 'ready') return\r\n actions.retainKeys(\r\n displayCategoryKeys(config, manual),\r\n workspaces.map(w => w.workspaceId as string),\r\n )\r\n }, [actions, config, manual, workspacePhase, workspaces])\r\n\r\n // Session tabs: the strip lives in the conversation column, but its lifecycle\r\n // belongs here — the browser already derives the open session for its own tree,\r\n // so one effect covers every way a session can be opened (sidebar row,\r\n // workspace New Session, quick panel, conversation-header crumbs).\r\n //\r\n // `statuses` is a dependency on purpose: a session earns its tab when it\r\n // STARTS working, which is a status change, not a catalog change. Without it a\r\n // conversation that began while already open would never surface a tab.\r\n useEffect(() => {\r\n if (current === undefined) return\r\n openTab(current, statuses.get(current))\r\n }, [current, list, statuses, openTab])\r\n\r\n const [query, setQuery] = useState('')\r\n const [searchExpanded, setSearchExpanded] = useState(false)\r\n const normalizedQuery = sanitizeSearchQuery(query).trim()\r\n const [remoteSearch, setRemoteSearch] = useState({\r\n query: '', status: 'idle', items: [], hasMore: false,\r\n })\r\n const searchInput = useRef(null)\r\n const searchRoot = useRef(null)\r\n // Box the flower branch measures and paints into. Held as a ref (not state)\r\n // because the overlay re-measures on its own MutationObserver; a state update\r\n // here would re-render the whole tree on every layout tick.\r\n const branchScope = useRef(null)\r\n\r\n // Search debounce + abort, same posture as the official browser.\r\n useEffect(() => {\r\n if (normalizedQuery === '') {\r\n setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false })\r\n return\r\n }\r\n const controller = new AbortController()\r\n setRemoteSearch({ query: normalizedQuery, status: 'loading', items: [], hasMore: false })\r\n const timer = window.setTimeout(() => {\r\n searchSessions(normalizedQuery, controller.signal).then((result) => {\r\n if (controller.signal.aborted) return\r\n setRemoteSearch({ query: normalizedQuery, status: 'ready', items: result.items, hasMore: result.hasMore })\r\n }).catch(() => {\r\n if (controller.signal.aborted) return\r\n setRemoteSearch({ query: normalizedQuery, status: 'error', items: [], hasMore: false })\r\n })\r\n }, SEARCH_DEBOUNCE_MS)\r\n return () => {\r\n window.clearTimeout(timer)\r\n controller.abort()\r\n }\r\n }, [normalizedQuery, searchSessions])\r\n\r\n // Outside-click dismissal of the search box.\r\n useEffect(() => {\r\n if (!wide || !searchExpanded) return\r\n const onClick = (event: MouseEvent): void => {\r\n if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return\r\n searchInput.current?.blur()\r\n if (normalizedQuery !== '') return\r\n setSearchExpanded(false)\r\n }\r\n document.addEventListener('click', onClick)\r\n return () => { document.removeEventListener('click', onClick) }\r\n }, [normalizedQuery, wide, searchExpanded])\r\n\r\n const expandedCategories = useMemo(\r\n () => Object.entries(categoryExpansion).filter(([, v]) => v).map(([k]) => k),\r\n [categoryExpansion],\r\n )\r\n const expandedWorkspaces = useMemo(\r\n () => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),\r\n [workspaceExpansion],\r\n )\r\n // Which level is being dragged: drives the top-level drop target (project\r\n // drags only) and which level's rows fold.\r\n const [dragging, setDragging] = useState(null)\r\n const groups = useMemo(\r\n () => deriveGroups(list, workspaces, archivedSessionIds, config, {\r\n expandedCategories,\r\n expandedWorkspaces,\r\n }, manual, statuses),\r\n [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],\r\n )\r\n // Top-level (ungrouped) workspace rows, rendered after the group folders.\r\n const topLevel = useMemo(\r\n () => deriveTopLevel(list, workspaces, archivedSessionIds, config, {\r\n expandedCategories,\r\n expandedWorkspaces,\r\n }, manual, statuses),\r\n [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],\r\n )\r\n // Quick panel (Ctrl+R): category label per grouped workspace id (the tree\r\n // derivation already resolved grouping; top-level workspaces stay absent).\r\n const categoryByWorkspace = useMemo(() => {\r\n const map = new Map()\r\n for (const category of groups) {\r\n for (const workspace of category.workspaces) map.set(workspace.workspaceId as string, category.label)\r\n }\r\n return map\r\n }, [groups])\r\n // While dragging a project, an empty top-level area must still show a landing\r\n // line — otherwise a project can never be dragged OUT of a group when every\r\n // project is currently grouped.\r\n const topLevelDropActive = dragging === 'workspace' && topLevel.length === 0\r\n // The top-level area is the move-out landing spot: rows reorder with an\r\n // insertion line (before/after), and the blank space below the last row\r\n // appends to the end of the list. No whole-area highlight box.\r\n const topLevelRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY }\r\n\r\n // Add workspace flow: self-contained (no directory-flow hole dependency).\r\n const [adding, setAdding] = useState(false)\r\n const [addError, setAddError] = useState(null)\r\n const [addErrorOpen, setAddErrorOpen] = useState(false)\r\n const addWorkspace = async (): Promise => {\r\n if (adding) return\r\n setAdding(true)\r\n setAddError(null)\r\n setAddErrorOpen(false)\r\n try {\r\n const path = await pickDirectory()\r\n if (path === null) return // cancelled\r\n const workspace = await createWorkspace({ path })\r\n startSession(workspace.workspaceId)\r\n } catch (reason) {\r\n const message = reason instanceof Error ? reason.message : String(reason)\r\n setAddError(message)\r\n setAddErrorOpen(true)\r\n } finally {\r\n setAdding(false)\r\n }\r\n }\r\n\r\n // Workspace rename dialog.\r\n const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null)\r\n const [renameDraft, setRenameDraft] = useState('')\r\n const [renaming, setRenaming] = useState(false)\r\n const [renameError, setRenameError] = useState(null)\r\n const renameTrimmed = renameDraft.trim()\r\n const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle\r\n && workspaces.some(w => w.title === renameTrimmed)\r\n const renameBlocked = renaming || renameTrimmed === '' || renameTarget === null\r\n || renameTrimmed === renameTarget.currentTitle || renameDuplicate\r\n const confirmRename = () => {\r\n if (renameBlocked || renameTarget === null) return\r\n setRenaming(true)\r\n setRenameError(null)\r\n renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {\r\n setRenaming(false)\r\n setRenameTarget(null)\r\n }).catch((reason: unknown) => {\r\n setRenaming(false)\r\n setRenameError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // Workspace delete dialog.\r\n const [deleteTarget, setDeleteTarget] = useState<{ workspaceId: WorkspaceId; title: string } | null>(null)\r\n const [deleting, setDeleting] = useState(false)\r\n const [deleteError, setDeleteError] = useState(null)\r\n const confirmDelete = () => {\r\n if (deleting || deleteTarget === null) return\r\n setDeleting(true)\r\n setDeleteError(null)\r\n deleteWorkspace(deleteTarget.workspaceId).then(() => {\r\n setDeleting(false)\r\n setDeleteTarget(null)\r\n }).catch((reason: unknown) => {\r\n setDeleting(false)\r\n setDeleteError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // Session rename dialog.\r\n const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionId; currentTitle: string } | null>(null)\r\n const [sessionRenameDraft, setSessionRenameDraft] = useState('')\r\n const [sessionRenaming, setSessionRenaming] = useState(false)\r\n const [sessionRenameError, setSessionRenameError] = useState(null)\r\n const sessionRenameTrimmed = sessionRenameDraft.trim()\r\n const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null\r\n const confirmSessionRename = () => {\r\n if (sessionRenameBlocked || sessionRenameTarget === null) return\r\n setSessionRenaming(true)\r\n setSessionRenameError(null)\r\n renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {\r\n setSessionRenaming(false)\r\n setSessionRenameTarget(null)\r\n }).catch((reason: unknown) => {\r\n setSessionRenaming(false)\r\n setSessionRenameError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n const onSessionRename = (sessionId: SessionId, currentTitle: string) => {\r\n setSessionRenameTarget({ sessionId, currentTitle })\r\n setSessionRenameDraft(currentTitle)\r\n setSessionRenameError(null)\r\n }\r\n\r\n // The strip is a child of this component (rendered through a DOM portal), so\r\n // it shares this fiber's props directly: renames call the dialog owner here,\r\n // and activation goes through the same navigation verb the sidebar rows use.\r\n const activateTab = (sessionId: SessionId) => { open(sessionId) }\r\n\r\n const onSessionArchive = (sessionId: SessionId) => {\r\n archiveSession(sessionId).catch((reason: unknown) => {\r\n console.warn('session archive rejected:', reason)\r\n })\r\n }\r\n\r\n // \"Open in folder\": the host half of the official open-in-app plugin resolves\r\n // which applications it can launch; the project row then just posts the\r\n // project directory to that host's launch route. One availability read per\r\n // mount — a host without the capability (or a refused read) leaves\r\n // `folderApp` undefined, which drops the menu entry rather than failing.\r\n const [folderApp, setFolderApp] = useState(undefined)\r\n const [folderError, setFolderError] = useState<{ id: number; text: string } | null>(null)\r\n useEffect(() => {\r\n const controller = new AbortController()\r\n fetchOpenInApps(controller.signal).then((apps) => {\r\n if (controller.signal.aborted) return\r\n setFolderApp(folderAppId(apps))\r\n }).catch(() => { /* no capability: the row simply offers no folder entry */ })\r\n return () => { controller.abort() }\r\n }, [])\r\n\r\n const openInFolder = folderApp === undefined\r\n ? undefined\r\n : (workspaceId: WorkspaceId): void => {\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n openPathInApp(folderApp, workspace.path).catch((reason: unknown) => {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n setFolderError({ id: Date.now(), text: `${t('workspace.openInFolderError')}: ${detail}` })\r\n })\r\n }\r\n\r\n // ---- Runtime group management ----------------------------------------------\r\n\r\n const [groupDialog, setGroupDialog] = useState(null)\r\n const [groupDraft, setGroupDraft] = useState('')\r\n const [groupError, setGroupError] = useState(null)\r\n const [groupBusy, setGroupBusy] = useState(false)\r\n const [groupDeleteTarget, setGroupDeleteTarget] = useState(null)\r\n const [groupDeleting, setGroupDeleting] = useState(false)\r\n const [groupDeleteError, setGroupDeleteError] = useState(null)\r\n\r\n // Appearance dialog (color / icon / pin) for one group display key. Every\r\n // control applies immediately (optimistic merge + save); there is no OK, so\r\n // `appearanceTarget` also doubles as the open flag.\r\n const [appearanceTarget, setAppearanceTarget] = useState(null)\r\n const [appearanceDraft, setAppearanceDraft] = useState({})\r\n const [appearanceError, setAppearanceError] = useState(null)\r\n\r\n const takenNames = useMemo(() => takenCategoryNames(config, manual), [config, manual])\r\n\r\n const groupTrimmed = groupDraft.trim()\r\n const groupNameIssue = groupDialog !== null && groupTrimmed !== ''\r\n ? (groupTrimmed === UNCATEGORIZED_LABEL\r\n ? t('group.nameReserved')\r\n : (groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\r\n ? null\r\n : takenNames.has(groupTrimmed) ? t('group.nameDuplicate') : null)\r\n : null\r\n const groupBlocked = groupBusy || groupTrimmed === '' || groupNameIssue !== null\r\n || (groupDialog !== null && groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\r\n\r\n const confirmGroupDialog = () => {\r\n if (groupBlocked || groupDialog === null) return\r\n const name = groupTrimmed\r\n const from = groupDialog.mode === 'rename' ? groupDialog.from : undefined\r\n const renaming = groupDialog.mode === 'rename' && from !== name\r\n\r\n let next: NormalizedManual\r\n if (groupDialog.mode === 'create') {\r\n next = { ...manual, categories: [...manual.categories, name] }\r\n } else {\r\n // Rename: rule groups ride the `renamed` map, manual groups the list;\r\n // every reference (assignments / workspaceOrder / categoryOrder) follows.\r\n const originalRule = from !== undefined ? originalRuleNameForDisplay(config.categories, manual, from) : undefined\r\n next = {\r\n ...manual,\r\n ...(originalRule !== undefined\r\n ? { renamed: { ...manual.renamed, [originalRule]: name } }\r\n : { categories: manual.categories.map(c => c === from ? name : c) }),\r\n assignments: Object.fromEntries(\r\n Object.entries(manual.assignments).map(([id, category]): [string, string | null] => [id, category === from ? name : category]),\r\n ),\r\n workspaceOrder: Object.fromEntries(\r\n Object.entries(manual.workspaceOrder).map(([key, ids]): [string, string[]] => [key === from ? name : key, ids]),\r\n ),\r\n categoryOrder: manual.categoryOrder.map(key => key === from ? name : key),\r\n // Appearance is keyed by display name too: move the entry instead of\r\n // leaving the colour/icon/pin behind under the old name.\r\n appearance: from === undefined || from === name\r\n ? manual.appearance\r\n : Object.fromEntries(\r\n Object.entries(manual.appearance).map(([key, value]): [string, CategoryAppearance] => [key === from ? name : key, value]),\r\n ),\r\n }\r\n }\r\n\r\n setGroupBusy(true)\r\n setGroupError(null)\r\n saveManualOverlay(next).then(() => {\r\n setManual(next)\r\n setManualError(null)\r\n setGroupBusy(false)\r\n setGroupDialog(null)\r\n setGroupDraft('')\r\n // Keep the renamed group open (its old expansion key is dropped by retainKeys).\r\n if (renaming) actions.setCategoryExpanded(name, true)\r\n }).catch((reason: unknown) => {\r\n setGroupBusy(false)\r\n setGroupError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n const confirmGroupDelete = () => {\r\n if (groupDeleting || groupDeleteTarget === null) return\r\n const name = groupDeleteTarget\r\n const originalRule = originalRuleNameForDisplay(config.categories, manual, name)\r\n\r\n // Every project currently in the group goes to 未分类 (forced, not rule-\r\n // reclassified), regardless of how it landed there.\r\n const assignments = { ...manual.assignments }\r\n for (const workspace of workspaces) {\r\n if (resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) === name) {\r\n assignments[workspace.workspaceId] = null\r\n }\r\n }\r\n const workspaceOrder = Object.fromEntries(\r\n Object.entries(manual.workspaceOrder).filter(([key]) => key !== name),\r\n )\r\n const next: NormalizedManual = {\r\n ...manual,\r\n assignments,\r\n workspaceOrder,\r\n categoryOrder: manual.categoryOrder.filter(key => key !== name),\r\n // Drop the presentation entry with the group itself (a dangling key would\r\n // silently re-attach if a new group ever reused the name).\r\n appearance: Object.fromEntries(\r\n Object.entries(manual.appearance).filter(([key]) => key !== name),\r\n ),\r\n ...(originalRule !== undefined\r\n ? {\r\n renamed: Object.fromEntries(Object.entries(manual.renamed).filter(([key]) => key !== originalRule)),\r\n hidden: [...manual.hidden, originalRule],\r\n }\r\n : { categories: manual.categories.filter(c => c !== name) }),\r\n }\r\n\r\n setGroupDeleting(true)\r\n setGroupDeleteError(null)\r\n saveManualOverlay(next).then(() => {\r\n setManual(next)\r\n setManualError(null)\r\n setGroupDeleting(false)\r\n setGroupDeleteTarget(null)\r\n }).catch((reason: unknown) => {\r\n setGroupDeleting(false)\r\n setGroupDeleteError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // ---- Drag & drop (move/reorder workspaces, reorder groups) ------------------\r\n\r\n const [dragIndicator, setDragIndicator] = useState(null)\r\n\r\n // Expansion state taken at dragstart; dragend restores it so the folding\r\n // caused by a drag is always undone afterwards (\"结束后恢复\").\r\n const expansionSnapshot = useRef<{ categories: Record; workspaces: Record } | null>(null)\r\n // Live expansion state for the dragend restore (the document-level listener\r\n // is registered once, so it must read current values through a ref).\r\n const liveExpansionRef = useRef({ categoryExpansion, workspaceExpansion, actions })\r\n liveExpansionRef.current = { categoryExpansion, workspaceExpansion, actions }\r\n\r\n // Cancel any stale indicator when a drag ends outside a row (or is aborted),\r\n // and restore the expansion snapshot taken at dragstart.\r\n useEffect(() => {\r\n const clear = () => {\r\n setDragIndicator(null)\r\n setDragging(null)\r\n const snapshot = expansionSnapshot.current\r\n if (snapshot === null) return\r\n expansionSnapshot.current = null\r\n const { categoryExpansion: currentCategories, workspaceExpansion: currentWorkspaces, actions: currentActions } = liveExpansionRef.current\r\n for (const [key, value] of Object.entries(snapshot.categories)) {\r\n if (currentCategories[key] !== value) currentActions.setCategoryExpanded(key, value)\r\n }\r\n for (const [key, value] of Object.entries(snapshot.workspaces)) {\r\n if (currentWorkspaces[key] !== value) currentActions.setWorkspaceExpanded(key, value)\r\n }\r\n }\r\n document.addEventListener('dragend', clear)\r\n return () => { document.removeEventListener('dragend', clear) }\r\n }, [])\r\n\r\n /** Move a workspace into a category (or reorder inside it when `beforeWorkspaceId`/`afterWorkspaceId`). */\r\n const moveWorkspaceTo = async (workspaceId: string, categoryKey: string, beforeWorkspaceId?: string, afterWorkspaceId?: string): Promise => {\r\n if (manualSaving) return\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n setManualSaving(true)\r\n try {\r\n let next: NormalizedManual\r\n if (categoryKey === UNCATEGORIZED_KEY) {\r\n // Move to the TOP LEVEL: force ungrouped (null) and drop from every\r\n // group's order list, while recording the position inside the ordered\r\n // top-level list (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`).\r\n const assignments = { ...manual.assignments, [workspaceId]: null }\r\n const workspaceOrder: Record = {}\r\n for (const [key, ids] of Object.entries(manual.workspaceOrder)) {\r\n if (key === TOP_LEVEL_ORDER_KEY) continue\r\n workspaceOrder[key] = ids.filter(id => id !== workspaceId)\r\n }\r\n const topLevelIds = workspaces\r\n .filter(w => w.workspaceId !== workspaceId && resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)\r\n .map(w => w.workspaceId as string)\r\n workspaceOrder[TOP_LEVEL_ORDER_KEY] = afterWorkspaceId !== undefined\r\n ? moveAfter(topLevelIds, workspaceId, afterWorkspaceId)\r\n : moveBefore(topLevelIds, workspaceId, beforeWorkspaceId)\r\n next = { ...manual, assignments, workspaceOrder }\r\n } else {\r\n const currentKey = resolveCategory(config, manual, workspaceId, workspace.path, workspace.title)\r\n const movingAcross = currentKey !== categoryKey\r\n const assignments = movingAcross\r\n ? { ...manual.assignments, [workspaceId]: categoryKey }\r\n : manual.assignments\r\n const targetOrder = afterWorkspaceId !== undefined\r\n ? moveAfter(manual.workspaceOrder[categoryKey] ?? [], workspaceId, afterWorkspaceId)\r\n : moveBefore(manual.workspaceOrder[categoryKey] ?? [], workspaceId, beforeWorkspaceId)\r\n const workspaceOrder = { ...manual.workspaceOrder, [categoryKey]: targetOrder }\r\n if (movingAcross && currentKey !== undefined && workspaceOrder[currentKey] !== undefined) {\r\n workspaceOrder[currentKey] = workspaceOrder[currentKey]!.filter(id => id !== workspaceId)\r\n }\r\n next = { ...manual, assignments, workspaceOrder }\r\n }\r\n await saveManualOverlay(next)\r\n setManual(next)\r\n setManualError(null)\r\n if (categoryKey !== UNCATEGORIZED_KEY) actions.setCategoryExpanded(categoryKey, true)\r\n } catch (reason) {\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */\r\n const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise => {\r\n if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return\r\n setManualSaving(true)\r\n try {\r\n const order = displayCategoryKeys(config, manual)\r\n const categoryOrder = afterKey !== undefined\r\n ? moveAfter(order, draggedKey, afterKey)\r\n : moveBefore(order, draggedKey, beforeKey)\r\n // Pinned groups sort before unpinned ones, so a drop across that boundary\r\n // only sticks when the dragged group adopts the neighbour's pin state in\r\n // the SAME write. Otherwise the derived order snaps it back and the drop\r\n // looks broken (spec §7.2).\r\n const neighbourKey = afterKey ?? beforeKey\r\n let appearance = manual.appearance\r\n if (neighbourKey !== undefined && isCategoryPinned(manual, neighbourKey) !== isCategoryPinned(manual, draggedKey)) {\r\n const cleaned = pruneAppearance({\r\n ...(manual.appearance[draggedKey] ?? {}),\r\n pinned: isCategoryPinned(manual, neighbourKey),\r\n })\r\n appearance = { ...manual.appearance }\r\n if (cleaned === undefined) delete appearance[draggedKey]\r\n else appearance[draggedKey] = cleaned\r\n }\r\n const next: NormalizedManual = { ...manual, categoryOrder, appearance }\r\n await saveManualOverlay(next)\r\n setManual(next)\r\n setManualError(null)\r\n } catch (reason) {\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /**\r\n * Merge a presentation patch for one group and persist the overlay.\r\n * Optimistic: the tree reflects the change immediately and rolls back if the\r\n * host refuses the write (the dialog has no confirm step).\r\n */\r\n const updateCategoryAppearance = async (key: string, patch: CategoryAppearance): Promise => {\r\n if (manualSaving) return\r\n setManualSaving(true)\r\n const previous = manual\r\n try {\r\n const merged: CategoryAppearance = { ...(manual.appearance[key] ?? {}), ...patch }\r\n const appearance = { ...manual.appearance }\r\n const cleaned = pruneAppearance(merged)\r\n if (cleaned === undefined) delete appearance[key]\r\n else appearance[key] = cleaned\r\n const next: NormalizedManual = { ...manual, appearance }\r\n setManual(next)\r\n await saveManualOverlay(next)\r\n setManualError(null)\r\n } catch (reason) {\r\n setManual(previous)\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /** Pin/unpin a group (pinned groups render above the normal order). */\r\n const toggleCategoryPinned = async (key: string): Promise => {\r\n await updateCategoryAppearance(key, { pinned: !isCategoryPinned(manual, key) })\r\n }\r\n\r\n /** Appearance currently shown in the dialog (empty while it is closed). */\r\n const appearanceCurrent: CategoryAppearance = appearanceTarget === null\r\n ? {}\r\n : (manual.appearance[appearanceTarget] ?? {})\r\n\r\n /**\r\n * Commit the custom-icon text field. Invalid input is blocked locally (the\r\n * host would 400 the whole overlay save); an empty field clears the icon.\r\n */\r\n const commitAppearanceIcon = (): void => {\r\n if (appearanceTarget === null) return\r\n const icon = (appearanceDraft.icon ?? '').trim()\r\n if (icon !== '' && !ICON_VALUE_PATTERN.test(icon)) {\r\n setAppearanceError(t('group.iconInvalid'))\r\n return\r\n }\r\n setAppearanceError(null)\r\n /* Blur fires before a neighbouring click and on every dialog close: skip\r\n the PUT when the field still matches the stored value. */\r\n if (icon === (appearanceCurrent.icon ?? '')) return\r\n void updateCategoryAppearance(appearanceTarget, { icon: icon === '' ? undefined : icon })\r\n }\r\n\r\n /**\r\n * Drop on a row. The insertion point is re-derived from the drop event's\r\n * position (top half = before, bottom half = after), so it always matches\r\n * the indicator the user last saw — even when dragover and drop arrive in\r\n * the same tick.\r\n */\r\n const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {\r\n event.preventDefault()\r\n // Keep the drop from bubbling to the enclosing top-level area (which is\r\n // also a move-out target): a row drop and the area-drop below it must not\r\n // both fire moveWorkspaceTo.\r\n event.stopPropagation()\r\n setDragIndicator(null)\r\n setDragging(null)\r\n const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE)\r\n if (draggedCategory !== '') {\r\n // Group reorder: only category rows are targets (project rows fold\r\n // during group drags); before/after follows the drop position.\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const beforeKey = row.kind === 'category' && before ? row.key : undefined\r\n const afterKey = row.kind === 'category' && !before ? row.key : undefined\r\n void moveCategory(draggedCategory, beforeKey, afterKey)\r\n return\r\n }\r\n const workspaceId = event.dataTransfer.getData(DND_WORKSPACE_TYPE) || event.dataTransfer.getData('text/plain')\r\n if (workspaceId === '') return\r\n if (row.kind === 'topLevel') {\r\n // Top-level row / top-level blank drop = move OUT of any group (forced\r\n // top-level, rules ignored) and set the position inside the ordered\r\n // top-level list. A row drop re-derives before/after from the drop\r\n // position; a bare area drop (key = UNCATEGORIZED_KEY) appends to the end.\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const specificKey = row.key === UNCATEGORIZED_KEY ? undefined : row.key\r\n void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY, before ? specificKey : undefined, !before ? specificKey : undefined)\r\n return\r\n }\r\n // Project move/reorder: a line on a project row = reorder before/after it;\r\n // dropping anywhere else in a category = move into the group (its end).\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const beforeWsid = row.kind === 'workspace' && before ? row.key : undefined\r\n const afterWsid = row.kind === 'workspace' && !before ? row.key : undefined\r\n void moveWorkspaceTo(workspaceId, categoryKey, beforeWsid, afterWsid)\r\n }\r\n\r\n const onDragOverRow = (row: DropRowRef) => (event: DragEvent): void => {\r\n if (!hasPluginDragType(event.dataTransfer.types)) return\r\n const draggingCategory = Array.from(event.dataTransfer.types as Iterable).includes(DND_CATEGORY_TYPE)\r\n if (draggingCategory && row.kind !== 'category') return // group drags target category rows only\r\n event.preventDefault()\r\n // Keep a row's dragover from bubbling to the enclosing top-level area\r\n // (which would interpret it as the end-of-list landing).\r\n event.stopPropagation()\r\n event.dataTransfer.dropEffect = 'move'\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n if (draggingCategory || row.kind === 'workspace' || row.kind === 'topLevel') {\r\n // Group reorder (line on a category row), project reorder inside a\r\n // group (line on a project row), or top-level reorder (line on a\r\n // top-level project row).\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === row.kind && prev.row.key === row.key && prev.before === before\r\n ? prev\r\n : { mode: 'line', row, before })\r\n } else {\r\n // Dropping a project INTO a group: whole-row highlight.\r\n setDragIndicator(prev =>\r\n prev?.mode === 'into' && prev.categoryKey === row.key ? prev : { mode: 'into', categoryKey: row.key })\r\n }\r\n }\r\n\r\n const onDragLeaveRow = (event: DragEvent): void => {\r\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return\r\n setDragIndicator(null)\r\n }\r\n\r\n /**\r\n * Drag over the TOP-LEVEL AREA's blank space (not on a row — rows stop\r\n * propagation). An insertion line shows the landing spot: empty top level →\r\n * a standalone line under the last group; non-empty → a line below the last\r\n * top-level row (end of the list).\r\n */\r\n const onDragOverTopLevelArea = (event: DragEvent): void => {\r\n if (!hasPluginDragType(event.dataTransfer.types)) return\r\n const draggingCategory = Array.from(event.dataTransfer.types as Iterable).includes(DND_CATEGORY_TYPE)\r\n if (draggingCategory) return // group drags never target the top-level area\r\n event.preventDefault()\r\n event.dataTransfer.dropEffect = 'move'\r\n const last = topLevel.length > 0 ? topLevel[topLevel.length - 1] : undefined\r\n if (last !== undefined) {\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === 'topLevel' && prev.row.key === last.workspaceId && prev.before === false\r\n ? prev\r\n : { mode: 'line', row: { kind: 'topLevel', key: last.workspaceId }, before: false })\r\n } else {\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === 'topLevel' && prev.row.key === topLevelRef.key && prev.before === false\r\n ? prev\r\n : { mode: 'line', row: topLevelRef, before: false })\r\n }\r\n }\r\n\r\n // While dragging a project, only PROJECT rows fold — every expanded\r\n // workspace collapses (inside groups AND top-level); group rows keep their\r\n // expansion so the user still sees where groups are. dragend restores the\r\n // snapshot taken here.\r\n const onDragStartWorkspace = (_workspaceId: string) => (): void => {\r\n setDragging('workspace')\r\n expansionSnapshot.current = {\r\n categories: { ...categoryExpansion },\r\n workspaces: { ...workspaceExpansion },\r\n }\r\n for (const key of Object.keys(workspaceExpansion)) {\r\n if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false)\r\n }\r\n }\r\n\r\n // While dragging a group, only GROUP rows fold (their rows stay visible as\r\n // reorder targets); project rows keep their expansion. dragend restores the\r\n // snapshot taken here.\r\n const onDragStartCategory = (categoryKey: string) => (event: DragEvent): void => {\r\n event.dataTransfer.setData(DND_CATEGORY_TYPE, categoryKey)\r\n event.dataTransfer.effectAllowed = 'move'\r\n setDragging('category')\r\n expansionSnapshot.current = {\r\n categories: { ...categoryExpansion },\r\n workspaces: { ...workspaceExpansion },\r\n }\r\n for (const key of Object.keys(categoryExpansion)) {\r\n if (categoryExpansion[key]) actions.setCategoryExpanded(key, false)\r\n }\r\n }\r\n\r\n const now = Date.now()\r\n\r\n return (\r\n
\r\n {/* The tab strip portals itself into the conversation column's head seat,\r\n so its position here is irrelevant to where it appears; rendering it\r\n from this component is what keeps it on this fiber (and therefore on\r\n this store's single scope) while still reaching the other column. */}\r\n \r\n
\r\n {wide && {t('section.workspaces')}}\r\n {wide && (\r\n
\r\n { setSearchExpanded(true) }}\r\n >\r\n \r\n \r\n {searchExpanded && (\r\n { setQuery(sanitizeSearchQuery(e.target.value)) }}\r\n onKeyDown={(e) => {\r\n if (e.key !== 'Escape') return\r\n setQuery('')\r\n setSearchExpanded(false)\r\n }}\r\n />\r\n )}\r\n {searchExpanded && (\r\n {\r\n e.stopPropagation()\r\n setQuery('')\r\n setSearchExpanded(false)\r\n }}\r\n >\r\n \r\n \r\n )}\r\n
\r\n )}\r\n \r\n {\r\n setGroupDraft('')\r\n setGroupError(null)\r\n setGroupDialog({ mode: 'create' })\r\n }}\r\n >\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
\r\n\r\n {!wide && (\r\n
\r\n \r\n { setSearchExpanded(true); expandSidebar() }}\r\n >\r\n \r\n \r\n \r\n
\r\n )}\r\n\r\n
\r\n {configError !== null && (\r\n
{t('configUnavailable')}
\r\n )}\r\n {manualError !== null && (\r\n
{t('manual.saveError')}: {manualError}
\r\n )}\r\n {wide && normalizedQuery !== '' ? (\r\n \r\n ) : (\r\n /* The branch overlay lives beside the tree, not inside it: it measures\r\n the rows and paints behind them, so it must share their box without\r\n becoming a row itself (which would break role=\"tree\" semantics and\r\n the index-based measurement). */\r\n
\r\n \r\n
\r\n {groups.length === 0 && topLevel.length === 0 && !topLevelDropActive && (\r\n
{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}
\r\n )}\r\n {groups.map((category) => (\r\n { actions.setCategoryExpanded(category.key, !category.expanded) }}\r\n onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\r\n onNewSession={startSession}\r\n onOpen={open}\r\n onRenameRequest={(workspaceId, title) => {\r\n setRenameTarget({ workspaceId, currentTitle: title })\r\n setRenameDraft(title)\r\n setRenameError(null)\r\n }}\r\n onDeleteRequest={(workspaceId, title) => {\r\n setDeleteTarget({ workspaceId, title })\r\n setDeleteError(null)\r\n }}\r\n onSessionRename={onSessionRename}\r\n onSessionArchive={onSessionArchive}\r\n onFork={forkSession}\r\n onGroupRename={() => {\r\n setGroupDraft(category.key)\r\n setGroupError(null)\r\n setGroupDialog({ mode: 'rename', from: category.key })\r\n }}\r\n onGroupDelete={() => {\r\n setGroupDeleteTarget(category.key)\r\n setGroupDeleteError(null)\r\n }}\r\n onGroupTogglePin={() => { void toggleCategoryPinned(category.key) }}\r\n onGroupAppearance={() => {\r\n setAppearanceDraft(manual.appearance[category.key] ?? {})\r\n setAppearanceError(null)\r\n setAppearanceTarget(category.key)\r\n }}\r\n animate={dragging === null}\r\n onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}\r\n onOpenInFolder={openInFolder}\r\n canMoveOut={(workspaceId) => {\r\n // The menu \"移出分组\" is offered for any project that\r\n // currently sits inside a group (rule-classified or manual) —\r\n // not just overridden ones. Top-level projects\r\n // (resolveCategory === undefined) don't need it.\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n return workspace !== undefined\r\n && resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) !== undefined\r\n }}\r\n />\r\n ))}\r\n {/* Top-level (ungrouped) workspaces, rendered after the group\r\n folders. While dragging a project the whole area is the\r\n move-out landing spot (a line shows the insert position;\r\n an empty top level shows a line under the last group). */}\r\n {(topLevel.length > 0 || topLevelDropActive) && (\r\n { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\r\n onNewSession={startSession}\r\n onOpen={open}\r\n onRenameRequest={(workspaceId, title) => {\r\n setRenameTarget({ workspaceId, currentTitle: title })\r\n setRenameDraft(title)\r\n setRenameError(null)\r\n }}\r\n onDeleteRequest={(workspaceId, title) => {\r\n setDeleteTarget({ workspaceId, title })\r\n setDeleteError(null)\r\n }}\r\n onSessionRename={onSessionRename}\r\n onSessionArchive={onSessionArchive}\r\n onFork={forkSession}\r\n onOpenInFolder={openInFolder}\r\n />\r\n )}\r\n
\r\n
\r\n )}\r\n
\r\n\r\n {/* Group create / rename dialog */}\r\n { setGroupDialog(null) }}\r\n closeLabel={t('close')}\r\n title={groupDialog?.mode === 'rename' ? t('group.renameTitle') : t('group.createTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setGroupDraft(e.target.value); setGroupError(null) }}\r\n onKeyDown={(e) => { if (e.key === 'Enter') confirmGroupDialog() }}\r\n />\r\n {groupNameIssue !== null &&
{groupNameIssue}
}\r\n {groupError !== null &&
{groupError}
}\r\n \r\n\r\n {/* Group delete dialog */}\r\n { setGroupDeleteTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('group.deleteTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{t('group.deleteConfirm')}
\r\n {groupDeleteError !== null &&
{groupDeleteError}
}\r\n \r\n\r\n {/* Group appearance dialog: every control writes immediately (optimistic\r\n patch + rollback banner), so the footer is only \"done\". */}\r\n { setAppearanceTarget(null) }}\r\n closeLabel={t('group.appearanceDone')}\r\n title={t('group.appearanceTitle')}\r\n footer={(\r\n \r\n )}\r\n >\r\n {appearanceTarget !== null && (\r\n <>\r\n
\r\n
{t('group.color')}
\r\n
\r\n { void updateCategoryAppearance(appearanceTarget, { color: undefined }) }}\r\n />\r\n {GROUP_COLORS.map((color) => {\r\n const active = appearanceCurrent.color === color\r\n return (\r\n { void updateCategoryAppearance(appearanceTarget, { color }) }}\r\n />\r\n )\r\n })}\r\n
\r\n
\r\n
\r\n
{t('group.icon')}
\r\n
\r\n {GROUP_ICON_IDS.map((id) => {\r\n const active = appearanceCurrent.icon === id\r\n return (\r\n {\r\n setAppearanceDraft({ ...appearanceDraft, icon: id })\r\n setAppearanceError(null)\r\n void updateCategoryAppearance(appearanceTarget, { icon: id })\r\n }}\r\n >\r\n \r\n \r\n )\r\n })}\r\n
\r\n {\r\n setAppearanceDraft({ ...appearanceDraft, icon: e.target.value })\r\n setAppearanceError(null)\r\n }}\r\n onKeyDown={(e) => { if (e.key === 'Enter') commitAppearanceIcon() }}\r\n onBlur={(event) => {\r\n /* A swatch / preset click moves focus out of the field in the\r\n same gesture and writes its own patch — committing the stale\r\n draft here would race it and could overwrite the preset. */\r\n const next = event.relatedTarget\r\n if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return\r\n commitAppearanceIcon()\r\n }}\r\n />\r\n
\r\n
\r\n { void updateCategoryAppearance(appearanceTarget, { pinned: appearanceCurrent.pinned !== true }) }}\r\n >\r\n {appearanceCurrent.pinned === true ? t('group.unpin') : t('group.pin')}\r\n \r\n
\r\n {appearanceError !== null &&
{appearanceError}
}\r\n \r\n )}\r\n \r\n\r\n {/* Workspace rename dialog */}\r\n { setRenameTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.renameTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setRenameDraft(e.target.value) }}\r\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmRename() }}\r\n />\r\n {renameError !== null &&
{renameError}
}\r\n \r\n\r\n {/* Workspace delete dialog */}\r\n { setDeleteTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.deleteTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{t('workspace.deleteConfirm')}
\r\n {deleteError !== null &&
{deleteError}
}\r\n \r\n\r\n {/* Session rename dialog */}\r\n { setSessionRenameTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('session.renameTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setSessionRenameDraft(e.target.value) }}\r\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmSessionRename() }}\r\n />\r\n {sessionRenameError !== null &&
{sessionRenameError}
}\r\n \r\n\r\n {/* Add workspace error dialog */}\r\n { setAddErrorOpen(false) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.addErrorTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{addError}
\r\n \r\n\r\n {/* \"Open in folder\" failure: transient banner, keyed per attempt so a\r\n repeat failure restarts the cycle. */}\r\n {folderError !== null && (\r\n }\r\n onDone={() => { setFolderError(null) }}\r\n />\r\n )}\r\n\r\n {/* Ctrl+R quick switch panel (conditionally mounted: fresh query per open). */}\r\n {quickOpen && (\r\n { setQuickOpen(false) }}\r\n list={list}\r\n workspaces={workspaces}\r\n archivedSessionIds={archivedSessionIds}\r\n categoryByWorkspace={categoryByWorkspace}\r\n current={current}\r\n startSession={startSession}\r\n openSession={open}\r\n now={now}\r\n t={t}\r\n />\r\n )}\r\n
\r\n )\r\n}\r\n\r\n/** Resolve the category label containing the current session (auto-expand helper). */\r\nfunction categoriesForCurrent(\r\n config: GroupsConfig,\r\n workspaces: readonly WorkspaceView[],\r\n current: SessionId,\r\n manual: ManualGroups,\r\n): string | undefined {\r\n const workspace = workspaces.find(w => w.sessionIds.includes(current))\r\n if (workspace === undefined) return undefined\r\n return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n}\r\n\r\n/** One category section: header row + expanded workspace folders. */\r\nfunction CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder }: {\r\n category: CategoryNode\r\n current: SessionId | undefined\r\n now: number\r\n t: GroupsBrowserProps['t']\r\n dragIndicator: DragIndicator\r\n /** Whether the disclosure animation may play (false while a drag folds rows). */\r\n animate: boolean\r\n onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void\r\n onDragLeaveRow: (event: DragEvent) => void\r\n /** Drop factory: bind the target category and the row kind (before/after re-derived at drop time). */\r\n onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void\r\n onDragStartCategory: (event: DragEvent) => void\r\n onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void\r\n onToggleCategory: () => void\r\n onToggleWorkspace: (key: string) => void\r\n onNewSession: (workspaceId?: WorkspaceId) => void\r\n onOpen: (sessionId: SessionId) => void\r\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\r\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\r\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\r\n onSessionArchive: (sessionId: SessionId) => void\r\n onFork: (sessionId: SessionId) => void\r\n onGroupRename: () => void\r\n onGroupDelete: () => void\r\n /** Pin/unpin this group from its row menu. */\r\n onGroupTogglePin: () => void\r\n /** Open the appearance dialog for this group. */\r\n onGroupAppearance: () => void\r\n onMoveOut: (workspaceId: WorkspaceId) => void\r\n canMoveOut: (workspaceId: WorkspaceId) => boolean\r\n /** Absent when the host resolved no folder application. */\r\n onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined\r\n}) {\r\n const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key\r\n ? (dragIndicator.before ? 'before' : 'after')\r\n : undefined\r\n const categoryInto = dragIndicator?.mode === 'into' && dragIndicator.categoryKey === category.key\r\n return (\r\n
\r\n \r\n \r\n {category.workspaces.map((workspace) => (\r\n
\r\n { onToggleWorkspace(workspace.workspaceId as string) }}\r\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\r\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\r\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\r\n canMoveOut={canMoveOut(workspace.workspaceId)}\r\n onMoveOut={() => { onMoveOut(workspace.workspaceId) }}\r\n {...(onOpenInFolder !== undefined\r\n ? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }\r\n : {})}\r\n dropActive={false}\r\n {...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId\r\n ? { insertLine: dragIndicator.before ? 'before' : 'after' }\r\n : {})}\r\n onRowDragOver={onDragOverRow({ kind: 'workspace', key: workspace.workspaceId })}\r\n onRowDragLeave={onDragLeaveRow}\r\n onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}\r\n onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}\r\n />\r\n \r\n {workspace.sessions.map((session) => (\r\n \r\n ))}\r\n \r\n
\r\n ))}\r\n \r\n
\r\n )\r\n}\r\n\r\n/**\r\n * Top-level (ungrouped) workspace rows rendered after the group folders. While\r\n * a project drag is in progress the WHOLE top-level area is the move-out\r\n * landing spot, shown with an insertion LINE (not a highlight box):\r\n * - a top-level row reorders before/after it (line above/below, like a group);\r\n * - the blank space below the last row appends to the end (line below the\r\n * last row);\r\n * - an empty top level shows a standalone line under the last group folder.\r\n */\r\nfunction TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder }: {\r\n topLevel: readonly WorkspaceGroupNode[]\r\n current: SessionId | undefined\r\n now: number\r\n t: GroupsBrowserProps['t']\r\n /** A project drag is in progress (drives the empty-top-level landing line). */\r\n dragging: boolean\r\n dragIndicator: DragIndicator\r\n topLevelRef: DropRowRef\r\n onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void\r\n onDragOverTopLevelArea: (event: DragEvent) => void\r\n onDragLeaveRow: (event: DragEvent) => void\r\n onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void\r\n onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void\r\n onToggleWorkspace: (key: string) => void\r\n onNewSession: (workspaceId?: WorkspaceId) => void\r\n onOpen: (sessionId: SessionId) => void\r\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\r\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\r\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\r\n onSessionArchive: (sessionId: SessionId) => void\r\n onFork: (sessionId: SessionId) => void\r\n /** Absent when the host resolved no folder application. */\r\n onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined\r\n}) {\r\n const emptyLineActive = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === topLevelRef.key\r\n return (\r\n \r\n {topLevel.length === 0 && dragging && (\r\n \r\n \r\n \r\n )}\r\n {topLevel.map((workspace) => (\r\n
\r\n { onToggleWorkspace(workspace.workspaceId as string) }}\r\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\r\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\r\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\r\n {...(onOpenInFolder !== undefined\r\n ? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }\r\n : {})}\r\n {...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === workspace.workspaceId\r\n ? { insertLine: dragIndicator.before ? 'before' : 'after' }\r\n : {})}\r\n onRowDragOver={onDragOverRow({ kind: 'topLevel', key: workspace.workspaceId })}\r\n onRowDragLeave={onDragLeaveRow}\r\n onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })}\r\n onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}\r\n />\r\n \r\n {workspace.sessions.map((session) => (\r\n \r\n ))}\r\n \r\n
\r\n ))}\r\n \r\n )\r\n}\r\n\r\n/**\r\n * Search body rendered as a three-level tree pruned to matched branches:\r\n * 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as\r\n * the idle tree, so search keeps the same folder hierarchy the user is used to.\r\n */\r\nfunction SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, t }: {\r\n list: SessionListState\r\n workspaces: readonly WorkspaceView[]\r\n config: GroupsConfig\r\n archivedSessionIds: readonly SessionId[]\r\n statuses: SessionStatusSnapshot\r\n query: string\r\n remote: RemoteSearchState\r\n resultLimit: number\r\n current: SessionId | undefined\r\n now: number\r\n open: (sessionId: SessionId) => void\r\n manual: ManualGroups\r\n t: GroupsBrowserProps['t']\r\n}) {\r\n const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }\r\n const matches = useMemo(\r\n () => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),\r\n [list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],\r\n )\r\n const searchTree = useMemo(\r\n () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses),\r\n [list, workspaces, config, matches, archivedSessionIds, manual, statuses],\r\n )\r\n const groups = searchTree.categories\r\n const searchTopLevel = searchTree.topLevel\r\n const pending = currentRemote.status === 'loading'\r\n const failed = currentRemote.status === 'error'\r\n return (\r\n
\r\n {groups.map((category) => (\r\n
\r\n {}} />\r\n
\r\n {category.workspaces.map((workspace) => (\r\n
\r\n {}}\r\n onNewSession={() => {}}\r\n onRename={() => {}}\r\n onDelete={() => {}}\r\n />\r\n
\r\n {workspace.sessions.map((session) => (\r\n {}}\r\n onFork={() => {}}\r\n onArchive={() => {}}\r\n />\r\n ))}\r\n
\r\n
\r\n ))}\r\n
\r\n
\r\n ))}\r\n {searchTopLevel.map((workspace) => (\r\n
\r\n {}}\r\n onNewSession={() => {}}\r\n onRename={() => {}}\r\n onDelete={() => {}}\r\n />\r\n
\r\n {workspace.sessions.map((session) => (\r\n {}}\r\n onFork={() => {}}\r\n onArchive={() => {}}\r\n />\r\n ))}\r\n
\r\n
\r\n ))}\r\n {pending &&
{t('search.pending')}
}\r\n {failed &&
{t('search.unavailable')}
}\r\n {!pending && groups.length === 0 && searchTopLevel.length === 0 && (\r\n
{t('search.noMatches')}
\r\n )}\r\n {matches.hasMore && (\r\n
{t('search.hasMore')}
\r\n )}\r\n
\r\n )\r\n}\r\n","/**\r\n * Locale dictionaries for the workspace-groups browser. The namespace is\r\n * `workspaceGroups` (independent from ui-workspace's `workspace` namespace).\r\n */\r\nimport type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'\r\n\r\n/** Dictionary keys of the workspaceGroups namespace (single source of truth). */\r\nexport type WorkspaceGroupsKey =\r\n | 'section.workspaces'\r\n | 'section.sessions'\r\n | 'search'\r\n | 'search.placeholder'\r\n | 'search.clear'\r\n | 'search.noMatches'\r\n | 'search.unavailable'\r\n | 'search.pending'\r\n | 'search.hasMore'\r\n | 'search.results.aria'\r\n | 'workspace.add'\r\n | 'workspace.addBusy'\r\n | 'workspace.addError'\r\n | 'workspace.addErrorTitle'\r\n | 'workspace.rename'\r\n | 'workspace.delete'\r\n | 'workspace.deleteTitle'\r\n | 'workspace.deleteConfirm'\r\n | 'workspace.deleteCancel'\r\n | 'workspace.renaming'\r\n | 'workspace.deleting'\r\n | 'workspace.renameTitle'\r\n | 'workspace.renamePlaceholder'\r\n | 'workspace.renameConfirm'\r\n | 'workspace.renameCancel'\r\n | 'workspace.moveOutOfGroup'\r\n | 'workspace.openInFolder'\r\n | 'workspace.openInFolderError'\r\n | 'group.create'\r\n | 'group.createTitle'\r\n | 'group.createPlaceholder'\r\n | 'group.createConfirm'\r\n | 'group.createCancel'\r\n | 'group.rename'\r\n | 'group.renameTitle'\r\n | 'group.renameConfirm'\r\n | 'group.delete'\r\n | 'group.deleteTitle'\r\n | 'group.deleteConfirm'\r\n | 'group.deleteCancel'\r\n | 'group.nameDuplicate'\r\n | 'group.nameReserved'\r\n | 'group.pin'\r\n | 'group.unpin'\r\n | 'group.pinned'\r\n | 'group.appearance'\r\n | 'group.appearanceTitle'\r\n | 'group.appearanceDone'\r\n | 'group.color'\r\n | 'group.colorDefault'\r\n | 'group.icon'\r\n | 'group.iconDefault'\r\n | 'group.iconCustom'\r\n | 'group.iconInvalid'\r\n | 'color.red'\r\n | 'color.orange'\r\n | 'color.amber'\r\n | 'color.green'\r\n | 'color.teal'\r\n | 'color.blue'\r\n | 'color.indigo'\r\n | 'color.purple'\r\n | 'color.pink'\r\n | 'color.gray'\r\n | 'section.topLevel'\r\n | 'manual.saveError'\r\n | 'session.new'\r\n | 'session.rename'\r\n | 'session.archive'\r\n | 'session.fork'\r\n | 'session.renameTitle'\r\n | 'session.renamePlaceholder'\r\n | 'session.renameConfirm'\r\n | 'session.renameCancel'\r\n | 'session.renaming'\r\n | 'uncategorized'\r\n | 'empty.none'\r\n | 'empty.noWorkspaces'\r\n | 'close'\r\n | 'cancel'\r\n | 'confirm'\r\n | 'retry'\r\n | 'configUnavailable'\r\n | 'collapse'\r\n | 'expandMore'\r\n | 'newSession'\r\n | 'quick.title'\r\n | 'quick.tab.workspaces'\r\n | 'quick.tab.sessions'\r\n | 'quick.search.placeholder'\r\n | 'quick.search.sessions'\r\n | 'quick.empty.workspaces'\r\n | 'quick.action.newSession'\r\n | 'quick.action.running'\r\n | 'quick.action.noneRunning'\r\n | 'quick.empty.sessions'\r\n | 'quick.select.hint'\r\n | 'quick.hint'\r\n | 'tabs.aria'\r\n | 'tabs.close'\r\n | 'tabs.archive'\r\n | 'tabs.pin'\r\n | 'tabs.unpin'\r\n | 'tabs.pinned'\r\n | 'tabs.rename'\r\n | 'tabs.renameSession'\r\n | 'tabs.renamePlaceholder'\r\n | 'tabs.closeOthers'\r\n | 'tabs.closeRight'\r\n | 'tabs.dragHint'\r\n\r\nexport type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>\r\n\r\n/** Simplified Chinese dictionary. */\r\nexport const zh: WorkspaceGroupsDict = {\r\n 'section.workspaces': '工作区',\r\n 'section.sessions': '会话',\r\n search: '搜索',\r\n 'search.placeholder': '搜索会话…',\r\n 'search.clear': '清除',\r\n 'search.noMatches': '没有匹配的会话',\r\n 'search.unavailable': '搜索不可用',\r\n 'search.pending': '搜索中…',\r\n 'search.hasMore': '结果过多,请细化关键词',\r\n 'search.results.aria': '搜索结果',\r\n 'workspace.add': '添加工作区',\r\n 'workspace.addBusy': '正在添加…',\r\n 'workspace.addError': '添加失败',\r\n 'workspace.addErrorTitle': '无法添加工作区',\r\n 'workspace.rename': '重命名',\r\n 'workspace.delete': '删除',\r\n 'workspace.deleteTitle': '删除工作区',\r\n 'workspace.deleteConfirm': '仅删除注册信息,目录与会话日志保留。确定删除?',\r\n 'workspace.deleteCancel': '取消删除',\r\n 'workspace.renaming': '重命名中…',\r\n 'workspace.deleting': '删除中…',\r\n 'workspace.renameTitle': '重命名工作区',\r\n 'workspace.renamePlaceholder': '工作区名称',\r\n 'workspace.renameConfirm': '重命名',\r\n 'workspace.renameCancel': '取消',\r\n 'workspace.moveOutOfGroup': '移出分组',\r\n 'workspace.openInFolder': '在文件夹中打开',\r\n 'workspace.openInFolderError': '打开文件夹失败',\r\n 'group.create': '新建分组',\r\n 'group.createTitle': '新建分组',\r\n 'group.createPlaceholder': '分组名称',\r\n 'group.createConfirm': '创建',\r\n 'group.createCancel': '取消',\r\n 'group.rename': '重命名分组',\r\n 'group.renameTitle': '重命名分组',\r\n 'group.renameConfirm': '重命名',\r\n 'group.delete': '删除分组',\r\n 'group.deleteTitle': '删除分组',\r\n 'group.deleteConfirm': '删除后,该分组内的所有项目将移到顶层(不归组)。确定删除?',\r\n 'group.deleteCancel': '取消删除',\r\n 'group.nameDuplicate': '已存在同名分组',\r\n 'group.nameReserved': '该名称不可用',\r\n 'group.pin': '置顶分组',\r\n 'group.unpin': '取消置顶',\r\n 'group.pinned': '已置顶',\r\n 'group.appearance': '颜色与图标…',\r\n 'group.appearanceTitle': '分组外观',\r\n 'group.appearanceDone': '完成',\r\n 'group.color': '颜色',\r\n 'group.colorDefault': '默认',\r\n 'group.icon': '图标',\r\n 'group.iconDefault': '默认图标',\r\n 'group.iconCustom': '自定义字符',\r\n 'group.iconInvalid': '图标需为预设图标或 1–4 个字符',\r\n 'color.red': '红色',\r\n 'color.orange': '橙色',\r\n 'color.amber': '琥珀',\r\n 'color.green': '绿色',\r\n 'color.teal': '青色',\r\n 'color.blue': '蓝色',\r\n 'color.indigo': '靛蓝',\r\n 'color.purple': '紫色',\r\n 'color.pink': '粉色',\r\n 'color.gray': '灰色',\r\n 'section.topLevel': '顶层项目',\r\n 'manual.saveError': '分组变更保存失败',\r\n 'session.new': '新建会话',\r\n 'session.rename': '重命名会话',\r\n 'session.archive': '归档',\r\n 'session.fork': '派生',\r\n 'session.renameTitle': '重命名会话',\r\n 'session.renamePlaceholder': '会话名称',\r\n 'session.renameConfirm': '重命名',\r\n 'session.renameCancel': '取消',\r\n 'session.renaming': '重命名中…',\r\n uncategorized: '未分类',\r\n 'empty.none': '暂无内容',\r\n 'empty.noWorkspaces': '还没有工作区',\r\n close: '关闭',\r\n cancel: '取消',\r\n confirm: '确定',\r\n retry: '重试',\r\n configUnavailable: '分组配置不可用',\r\n collapse: '折叠',\r\n expandMore: '展开全部',\r\n newSession: '新建会话',\r\n 'quick.title': '快速切换',\r\n 'quick.tab.workspaces': '工作区',\r\n 'quick.tab.sessions': '全部会话',\r\n 'quick.search.placeholder': '搜索工作区…',\r\n 'quick.search.sessions': '搜索会话…',\r\n 'quick.empty.workspaces': '没有匹配的工作区',\r\n 'quick.action.newSession': '新建会话',\r\n 'quick.action.running': '切到运行中的会话',\r\n 'quick.action.noneRunning': '没有正在运行的会话',\r\n 'quick.empty.sessions': '还没有会话',\r\n 'quick.select.hint': '在上方选择一个工作区',\r\n 'quick.hint': 'Ctrl+R 开关 · Enter 打开/新建 · Esc 关闭',\r\n 'tabs.aria': '已打开的会话',\r\n 'tabs.close': '关闭标签',\r\n 'tabs.archive': '归档',\r\n 'tabs.pin': '固定标签',\r\n 'tabs.unpin': '取消固定',\r\n 'tabs.pinned': '已固定(关闭其他时保留)',\r\n 'tabs.rename': '重命名标签',\r\n 'tabs.renameSession': '重命名会话…',\r\n 'tabs.renamePlaceholder': '标签名,留空恢复会话标题',\r\n 'tabs.closeOthers': '关闭其他标签',\r\n 'tabs.closeRight': '关闭右侧标签',\r\n 'tabs.dragHint': '拖动可排序',\r\n}\r\n\r\n/** English dictionary. */\r\nexport const en: WorkspaceGroupsDict = {\r\n 'section.workspaces': 'Workspaces',\r\n 'section.sessions': 'Sessions',\r\n search: 'Search',\r\n 'search.placeholder': 'Search sessions…',\r\n 'search.clear': 'Clear',\r\n 'search.noMatches': 'No matching sessions',\r\n 'search.unavailable': 'Search unavailable',\r\n 'search.pending': 'Searching…',\r\n 'search.hasMore': 'Too many results — refine the query',\r\n 'search.results.aria': 'Search results',\r\n 'workspace.add': 'Add workspace',\r\n 'workspace.addBusy': 'Adding…',\r\n 'workspace.addError': 'Add failed',\r\n 'workspace.addErrorTitle': 'Could not add workspace',\r\n 'workspace.rename': 'Rename',\r\n 'workspace.delete': 'Delete',\r\n 'workspace.deleteTitle': 'Delete workspace',\r\n 'workspace.deleteConfirm': 'Only the registration is removed; the directory and session logs stay. Delete?',\r\n 'workspace.deleteCancel': 'Cancel delete',\r\n 'workspace.renaming': 'Renaming…',\r\n 'workspace.deleting': 'Deleting…',\r\n 'workspace.renameTitle': 'Rename workspace',\r\n 'workspace.renamePlaceholder': 'Workspace name',\r\n 'workspace.renameConfirm': 'Rename',\r\n 'workspace.renameCancel': 'Cancel',\r\n 'workspace.moveOutOfGroup': 'Move out of group',\r\n 'workspace.openInFolder': 'Open in folder',\r\n 'workspace.openInFolderError': 'Could not open the folder',\r\n 'group.create': 'New group',\r\n 'group.createTitle': 'New group',\r\n 'group.createPlaceholder': 'Group name',\r\n 'group.createConfirm': 'Create',\r\n 'group.createCancel': 'Cancel',\r\n 'group.rename': 'Rename group',\r\n 'group.renameTitle': 'Rename group',\r\n 'group.renameConfirm': 'Rename',\r\n 'group.delete': 'Delete group',\r\n 'group.deleteTitle': 'Delete group',\r\n 'group.deleteConfirm': 'Deleting removes this group; every project inside it moves to the top level (ungrouped). Delete?',\r\n 'group.deleteCancel': 'Cancel delete',\r\n 'group.nameDuplicate': 'A group with this name already exists',\r\n 'group.nameReserved': 'This name is not available',\r\n 'group.pin': 'Pin group',\r\n 'group.unpin': 'Unpin group',\r\n 'group.pinned': 'Pinned',\r\n 'group.appearance': 'Color & icon…',\r\n 'group.appearanceTitle': 'Group appearance',\r\n 'group.appearanceDone': 'Done',\r\n 'group.color': 'Color',\r\n 'group.colorDefault': 'Default',\r\n 'group.icon': 'Icon',\r\n 'group.iconDefault': 'Default icon',\r\n 'group.iconCustom': 'Custom character',\r\n 'group.iconInvalid': 'Use a preset icon or 1–4 characters',\r\n 'color.red': 'Red',\r\n 'color.orange': 'Orange',\r\n 'color.amber': 'Amber',\r\n 'color.green': 'Green',\r\n 'color.teal': 'Teal',\r\n 'color.blue': 'Blue',\r\n 'color.indigo': 'Indigo',\r\n 'color.purple': 'Purple',\r\n 'color.pink': 'Pink',\r\n 'color.gray': 'Gray',\r\n 'section.topLevel': 'Top-level projects',\r\n 'manual.saveError': 'Could not save group changes',\r\n 'session.new': 'New Session',\r\n 'session.rename': 'Rename session',\r\n 'session.archive': 'Archive',\r\n 'session.fork': 'Fork',\r\n 'session.renameTitle': 'Rename session',\r\n 'session.renamePlaceholder': 'Session name',\r\n 'session.renameConfirm': 'Rename',\r\n 'session.renameCancel': 'Cancel',\r\n 'session.renaming': 'Renaming…',\r\n uncategorized: 'Uncategorized',\r\n 'empty.none': 'Nothing here',\r\n 'empty.noWorkspaces': 'No workspaces yet',\r\n close: 'Close',\r\n cancel: 'Cancel',\r\n confirm: 'Confirm',\r\n retry: 'Retry',\r\n configUnavailable: 'Grouping config unavailable',\r\n collapse: 'Collapse',\r\n expandMore: 'Show all',\r\n newSession: 'New Session',\r\n 'quick.title': 'Quick switch',\r\n 'quick.tab.workspaces': 'Workspaces',\r\n 'quick.tab.sessions': 'All sessions',\r\n 'quick.search.placeholder': 'Search workspaces…',\r\n 'quick.search.sessions': 'Search sessions…',\r\n 'quick.empty.workspaces': 'No matching workspaces',\r\n 'quick.action.newSession': 'New Session',\r\n 'quick.action.running': 'Switch to running session',\r\n 'quick.action.noneRunning': 'No running session',\r\n 'quick.empty.sessions': 'No sessions yet',\r\n 'quick.select.hint': 'Pick a workspace above',\r\n 'quick.hint': 'Ctrl+R toggle · Enter open/new · Esc close',\r\n 'tabs.aria': 'Open sessions',\r\n 'tabs.close': 'Close tab',\r\n 'tabs.archive': 'Archive',\r\n 'tabs.pin': 'Pin tab',\r\n 'tabs.unpin': 'Unpin tab',\r\n 'tabs.pinned': 'Pinned (kept by Close others)',\r\n 'tabs.rename': 'Rename tab',\r\n 'tabs.renameSession': 'Rename session…',\r\n 'tabs.renamePlaceholder': 'Tab name — blank restores the session title',\r\n 'tabs.closeOthers': 'Close other tabs',\r\n 'tabs.closeRight': 'Close tabs to the right',\r\n 'tabs.dragHint': 'Drag to reorder',\r\n}\r\n","/**\r\n * @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated\r\n * view that hangs off it:\r\n *\r\n * The three-level grouped workspace browser into `sidebar.workspaces`,\r\n * shadowing the official ui-workspace browser.\r\n *\r\n * Shadowing mechanics (SlotCore semantics):\r\n * - `sidebar.workspaces` is a `single`/`root` slot. The official browser\r\n * registers at priority 0; this entry registers at priority -1, and the\r\n * single-cell shadow rule makes the LOWEST priority the winner — the\r\n * sidebar renders this browser instead of the official one.\r\n * - This entry deliberately declares NO child slots: the official entry\r\n * already declared `sidebar.workspaces.directoryFlow` (a second declaration\r\n * of an occupied child key throws). Add Workspace is therefore self-\r\n * contained — the shared navigation service + `workspaces.create()`, no\r\n * hole.\r\n *\r\n * The session tab strip is NOT a second registration. It renders into a DOM\r\n * seat at the head of the conversation column (`pI_x6G_centerCol`) because that\r\n * column declares no child slot — its only child is the `main` slot's occupant\r\n * — so there is nowhere to register. See `tab-seat.ts` for the injection and\r\n * `SessionTabs.tsx` for the portal.\r\n *\r\n * Two consequences of that choice, both deliberate:\r\n * - The strip is a CHILD of this entry's component, so it inherits this\r\n * fiber's frame; it needs no injected seam, no cross-entry callback set,\r\n * and the rename dialog stays owned by one place.\r\n * - The tab store is seated by exactly ONE entry. Registering one handle\r\n * under a second, differently-scoped slot throws inside the registry\r\n * (\"one handle, one scope\") and would abort this whole `apply()` — which\r\n * is precisely why the strip does not occupy a slot.\r\n *\r\n * 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从\r\n * `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务\r\n * (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位\r\n * 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该\r\n * 服务,只保留改名、删除、排序、搜索等数据动作。\r\n */\r\nimport type { Context } from '@deepseek-ai/cordis'\r\n// Type-only service merges: sessions/workspaces controllers, the ui-workspace\r\n// navigation service face (ctx.uiWorkspace), locale dictionary seat, the\r\n// SlotRegistry, and the sidebar SlotMap.\r\nimport type {} from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type {} from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\r\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\r\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\r\nimport type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'\r\n// `useWorkspaces` is contributed by the ui-workspace browser domain (same\r\n// declaration as the official ui-workspace client half).\r\nimport type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { GroupsBrowserInjected } from './contract.ts'\r\nimport { createGroupsViewStore } from './stores.ts'\r\nimport { createSessionTabsStore } from './tab-store.ts'\r\nimport { loadTabs, saveTabs } from './tab-persist.ts'\r\nimport { createStoreHook } from './store-hook.ts'\r\nimport { shouldOpenTab, type TabOpenMode } from './tabs.ts'\r\nimport { GroupsBrowser } from './GroupsBrowser.tsx'\r\nimport { en, zh, type WorkspaceGroupsKey } from './locales.ts'\r\n\r\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\r\n interface LocaleNamespaceMap {\r\n /** The workspace-groups browsing region copy. */\r\n workspaceGroups: WorkspaceGroupsKey\r\n }\r\n\r\n interface GlobalStandardProps {\r\n /** Selector hook over the pure Workspace Controller snapshot. */\r\n useWorkspaces: SnapshotSelectorHook\r\n }\r\n}\r\n\r\n/** Dictionary namespace owned by this plugin. */\r\nconst NS = 'workspaceGroups'\r\n\r\n/**\r\n * Tab visibility policy. `auto` is the behaviour the feature was asked for —\r\n * opening a session that has no tab yet adds one at the front of the strip;\r\n * `manual` leaves the strip to callers that drive `openTab` themselves.\r\n */\r\nconst TAB_OPEN_MODE: TabOpenMode = 'auto'\r\n\r\n/**\r\n * Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`\r\n * is the shipped navigation face this entry delegates selection to.\r\n */\r\nexport const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']\r\n\r\n/**\r\n * Register the grouped browser once the sidebar slot declaration is on the\r\n * ledger. Inject factory returns plain callbacks; data reads use the\r\n * framework's global hooks.\r\n * @param ctx - client root context.\r\n */\r\nexport function apply(ctx: Context): void {\r\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), '@dsh-xhl/workspace-groups: dictionaries')\r\n\r\n // ONE store, ONE scope. The tab store is seated only by the\r\n // `sidebar.workspaces` entry below (scope root); the strip reads it as a\r\n // plain prop because it renders as a CHILD of that entry through a DOM\r\n // portal, not as a second slot occupant. Seating the same handle under a\r\n // session-scoped slot as well throws inside the registry\r\n // (one handle, one scope) and would abort this whole apply().\r\n const tabsStore = createSessionTabsStore()\r\n const tabInstance = tabsStore.create()\r\n const tabWrites = tabInstance.actions\r\n\r\n // Persist the strip on the HOST, not in browser storage: the origin includes\r\n // the port and every launch picks a new one, so localStorage/sessionStorage\r\n // both start empty next time.\r\n //\r\n // Writes are GATED until the initial restore has settled. The store starts\r\n // empty and the browser's own effects run before the host read resolves, so an\r\n // ungated subscriber would write that empty state over the stored tabs —\r\n // erasing exactly what it was supposed to restore. `hydrated` is the latch.\r\n let hydrated = false\r\n ctx.effect(() => {\r\n const stop = tabInstance.subscribe(() => {\r\n if (!hydrated) return\r\n void saveTabs({\r\n order: tabInstance.getSnapshot().order,\r\n tabs: tabInstance.getSnapshot().tabs,\r\n })\r\n })\r\n return () => { stop() }\r\n }, '@dsh-xhl/workspace-groups: tab persistence')\r\n\r\n // Hydrate once from the host, then open the write gate.\r\n //\r\n // `restore` is a no-op if the user already opened a tab while this was in\r\n // flight, so a slow response cannot discard live work. The settle deliberately\r\n // does NOT write: writing the strip here would erase the stored tabs whenever\r\n // the read came back empty for a transient reason (host still booting, a\r\n // dropped request). Only a real state CHANGE persists, via the subscriber.\r\n ctx.effect(() => {\r\n let cancelled = false\r\n void loadTabs().then((tabs) => {\r\n if (cancelled) return\r\n if (tabs.length > 0) {\r\n tabWrites.restore(tabs.map(tab => ({\r\n sessionId: tab.sessionId as SessionId,\r\n order: tab.order,\r\n ...(tab.pinned === true ? { pinned: true } : {}),\r\n ...(tab.title !== undefined ? { title: tab.title } : {}),\r\n })))\r\n }\r\n hydrated = true\r\n }).catch(() => {\r\n // The read failed; leave the gate open so the user's own actions persist,\r\n // but never write on the strength of a failed read.\r\n if (!cancelled) hydrated = true\r\n })\r\n return () => { cancelled = true }\r\n }, '@dsh-xhl/workspace-groups: tab restore')\r\n\r\n const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {\r\n const result = await ctx.sessions.search(query, signal)\r\n if (!result.ok) throw new Error(result.error.message)\r\n return result.value\r\n }\r\n\r\n const browserInjected = (): GroupsBrowserInjected => ({\r\n // Navigation verbs belong to the shipped ui-workspace service: it owns the\r\n // retained `mainView` selection, supersession and pending-navigation\r\n // cancellation (0.1.6 moved them out of `ctx.sessions`).\r\n startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },\r\n open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },\r\n forkSession: (sessionId) => {\r\n ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {\r\n console.warn('fork session failed:', reason)\r\n })\r\n },\r\n archiveSession: async (sessionId) => {\r\n await ctx.uiWorkspace.archiveSession(sessionId)\r\n // The tab is deliberately LEFT ALONE. Archiving hides the session from the\r\n // grouped surfaces, but a tab is something the user opened, and the rule\r\n // for this strip is that only they close one — an automatic close here\r\n // would silently drop work they were keeping an eye on. The chip keeps\r\n // rendering (falling back to the session id when the title no longer\r\n // resolves).\r\n },\r\n pickDirectory: () => ctx.uiWorkspace.pickDirectory(),\r\n searchSessions,\r\n searchResultLimit: ctx.sessions.searchResultLimit,\r\n // Directory-flow hole occupancy. The official ui-workspace browser gates\r\n // its \"Add workspace…\" affordance on the hole being occupied (the shipped\r\n // picker package's client half fills it); this browser drives the picker\r\n // itself through `pickDirectory`, so it must keep the hole occupied or the\r\n // official entry (still live at priority 0) would silently withdraw the\r\n // affordance.\r\n hooks: {\r\n directoryFlow: {\r\n getSnapshot: () => true,\r\n subscribe: () => () => {},\r\n },\r\n },\r\n // Data-only verbs stay on the controllers.\r\n renameSession: async (sessionId, title) => {\r\n const session = ctx.sessions.binding(sessionId)?.session\r\n if (session === undefined) throw new Error(`unknown session \"${sessionId}\"`)\r\n const result = await session.rename(title)\r\n if (!result.ok) throw new Error(result.error.message)\r\n },\r\n renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },\r\n deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },\r\n insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {\r\n await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)\r\n },\r\n insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {\r\n await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)\r\n },\r\n createWorkspace: input => ctx.workspaces.create(input),\r\n // \"Show a tab for what I just opened\" — but only while it is actually in\r\n // play. The browser decides per session (see `shouldOpenTab`): a draft that\r\n // has not been talked to, and settled history, both stay out of the strip.\r\n // The status arrives from the caller because it is a live UI fact read\r\n // through a hook, which this (non-React) factory cannot reach.\r\n openTab: (sessionId, status) => {\r\n const summary = ctx.sessions.list.getSnapshot().byId[sessionId]\r\n if (shouldOpenTab(TAB_OPEN_MODE, summary, status)) tabWrites.touch(sessionId)\r\n },\r\n // The strip rides this entry's own store seat, so it needs both faces\r\n // explicitly: a selector hook over the one live instance, and the baked\r\n // writes. Both come from the same instance the browser writes through.\r\n useTabs: createStoreHook(tabInstance),\r\n tabActions: tabWrites,\r\n })\r\n\r\n // priority: -1 — lower than the official browser's default 0, so the\r\n // single-slot shadow rule elects this entry. No children declaration: the\r\n // official entry already owns `sidebar.workspaces.directoryFlow`.\r\n //\r\n // The official WorkspaceBrowser entry is NEVER disposed — shadowing only\r\n // changes which entry renders (activation just bumps the store's mount\r\n // count). Both entries live at the same cell, so if this one ever throws\r\n // during render the slot core retires it for the rest of its registration's\r\n // life and silently falls back to the official browser. Anything that can\r\n // throw belongs outside the hot path.\r\n ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(\r\n {\r\n name: 'sidebar.workspaces',\r\n priority: -1,\r\n store: createGroupsViewStore(),\r\n inject: browserInjected,\r\n locale: NS,\r\n registrant: '@dsh-xhl/workspace-groups',\r\n },\r\n GroupsBrowser,\r\n ))\r\n}\r\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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eAAe,SAAS;IAOhD;IACA,qBAAqB,IAAI,YAAY,cAAc;IACnD;IACA,mBAAmB,IAAI,SAAS;IAOhC,OAAO,EACL,eAAe;KACb,mBAAmB;KACnB,uBAAuB,CAAC;IAC1B,EACF;IAEA,eAAe,OAAO,WAAW,UAAU;KACzC,MAAM,UAAU,IAAI,SAAS,QAAQ,SAAS,CAAC,EAAE;KACjD,IAAI,YAAY,KAAA,GAAW,MAAM,IAAI,MAAM,oBAAoB,UAAU,EAAE;KAC3E,MAAM,SAAS,MAAM,QAAQ,OAAO,KAAK;KACzC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,MAAM,OAAO,MAAM,OAAO;IACtD;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,qBAAqB,OAAO,aAAa,WAAW,oBAAoB;KACtE,MAAM,IAAI,WAAW,oBAAoB,aAAa,WAAW,eAAe;IAClF;IACA,kBAAiB,UAAS,IAAI,WAAW,OAAO,KAAK;IAMrD,UAAU,WAAW,WAAW;KAC9B,MAAM,UAAU,IAAI,SAAS,KAAK,YAAY,CAAC,CAAC,KAAK;KACrD,IAAI,cAAc,eAAe,SAAS,MAAM,GAAG,UAAU,MAAM,SAAS;IAC9E;IAIA,SAAS,gBAAgB,WAAW;IACpC,YAAY;GACd;GAYA,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 +{"version":3,"file":"client.js","names":["defineStore","defineStore","useRef","useCallback","useSyncExternalStore","IconFolderCloseMedium","IconWorkspaceTreeOutlineMedium","IconCodeOutlineMedium","IconCordisPluginOutlineMedium","IconSkillOutlineMedium","IconDataOutlineMedium","IconDatabaseOutlineMedium","IconApiOutlineMedium","IconPlanOutlineMedium","IconGoalOutlineMedium","IconLightOutlineMedium","IconGlobeOutlineMedium","IconArchiveOutlineMedium","IconBranchOutlineMedium","IconUsersOutlineMedium","IconClockOutlineMedium","IconShieldOutlineMedium","IconChecklistOutlineMedium","IconSparkleMedium","IconTreeCornerMedium","useState","IconPinFillMedium","IconPinOutlineRegular","IconSlidersTwoOutlineRegular","IconEditOutlineRegular","IconTrashOutlineRegular","IconTriangleRightFillMedium","IconFolderOpenMedium","Menu","IconEllipsisOutlineRegular","IconFolderOpenOutlineRegular","IconRightUpOutlineRegular","IconProjectAddOutlineRegular","IconPlusOutlineRegular","useRef","IconBranchOutlineRegular","IconArchiveOutlineRegular","StateDot","useState","useRef","useMemo","createPortal","Button","StateDot","useMemo","useState","useRef","StateDot","IconPinFillMedium","Tooltip","IconCloseFillMedium","createPortal","useState","useRef","css","useState","useRef","useMemo","IconSearchOutlineRegular","IconCloseFillMedium","Tooltip","IconFolderOpenOutlineRegular","IconProjectAddOutlineRegular","Modal","Button","Toast","IconWarningOutlineRegular","IconTrashOutlineRegular"],"sources":["../src/client/store-core.ts","../src/client/stores.ts","../src/client/tabs.ts","../src/client/tab-store.ts","../src/client/tab-persist.ts","../src/client/store-hook.ts","../src/core/types.ts","../src/core/matcher.ts","../src/client/subagent-lineage.ts","../src/core/folders.ts","../src/client/tree.ts","../src/client/rows.tsx","../src/client/folders-persist.ts","../src/client/open-folder.ts","../src/client/quick.ts","../src/client/QuickPanel.tsx","../src/client/tab-seat.ts","../src/client/SessionTabs.tsx","../src/client/branch.ts","../src/client/FlowerBranch.tsx","../src/client/GroupsBrowser.tsx","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\r\n * Pure expansion-state transforms for the workspace-groups store. Kept free\r\n * of any runtime import so both the store (which binds them via defineStore)\r\n * and unit tests (which exercise them directly) share one implementation.\r\n *\r\n * Expansion semantics follow the official ui-workspace store: collapse\r\n * WRITES `false` (never deletes the key). The browser's auto-expand guard\r\n * uses `Object.hasOwn` — a present `false` means \"user deliberately\r\n * collapsed this\" and must NOT be re-expanded; only a fully absent key means\r\n * \"never touched\" and may auto-expand. (Earlier versions deleted the key on\r\n * collapse, which made the current category/workspace impossible to fold.)\r\n */\r\n\r\n/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */\r\nexport interface GroupsViewState {\r\n /** Category folder expansion keyed by category label (absent = never touched). */\r\n categoryExpansion: Record\r\n /** Workspace folder expansion keyed by workspace id (absent = never touched). */\r\n workspaceExpansion: Record\r\n}\r\n\r\n/** Collapse writes `false` (key retained); expand writes `true`. */\r\nexport function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\r\n state.categoryExpansion[key] = expanded\r\n}\r\n\r\n/** Collapse writes `false` (key retained); expand writes `true`. */\r\nexport function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {\r\n state.workspaceExpansion[key] = expanded\r\n}\r\n\r\n/** Drop expansion keys that no longer exist (renames/deletes/config edits). */\r\nexport function retainKeysImpl(\r\n state: GroupsViewState,\r\n categoryKeys: readonly string[],\r\n workspaceKeys: readonly string[],\r\n): void {\r\n state.categoryExpansion = Object.fromEntries(\r\n Object.entries(state.categoryExpansion).filter(([key]) => categoryKeys.includes(key)),\r\n )\r\n state.workspaceExpansion = Object.fromEntries(\r\n Object.entries(state.workspaceExpansion).filter(([key]) => workspaceKeys.includes(key)),\r\n )\r\n}\r\n","/**\r\n * The workspace-groups viewing store: category / workspace folder expansion,\r\n * persisted across reloads under an independent key (the official\r\n * ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch\r\n * it). Module level exports the factory only (a module-level handle would pin\r\n * the store identity across plugin reloads); register() receives the factory\r\n * and the browser derives its PropsStore share from the return type.\r\n *\r\n * The action implementations live in `store-core.ts` (pure, runtime-free) so\r\n * unit tests exercise the real semantics without a browser module loader;\r\n * this file only binds them through defineStore.\r\n */\r\nimport { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'\r\nimport {\r\n retainKeysImpl,\r\n setCategoryExpandedImpl,\r\n setWorkspaceExpandedImpl,\r\n type GroupsViewState,\r\n} from './store-core.ts'\r\n\r\n/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */\r\ntype GroupsViewActions = {\r\n setCategoryExpanded: typeof setCategoryExpandedImpl\r\n setWorkspaceExpanded: typeof setWorkspaceExpandedImpl\r\n retainKeys: typeof retainKeysImpl\r\n}\r\n\r\n/**\r\n * Create the workspace-groups viewing store handle.\r\n * @returns the store handle (spec + type + identity + factory in one).\r\n */\r\nexport function createGroupsViewStore(): EngineStoreHandle {\r\n return defineStore({\r\n init: () => ({ categoryExpansion: {}, workspaceExpansion: {} }),\r\n persist: 'dsh.workspace.groups.view.v1',\r\n actions: {\r\n setCategoryExpanded: setCategoryExpandedImpl,\r\n setWorkspaceExpanded: setWorkspaceExpandedImpl,\r\n retainKeys: retainKeysImpl,\r\n },\r\n })\r\n}\r\n\r\nexport type { GroupsViewState } from './store-core.ts'\r\n","/**\r\n * Pure session-tab state: the ordered strip of sessions the user has opened,\r\n * the active one, and each tab's derived presentation.\r\n *\r\n * Position model: a tab's place in the strip is decided when it is first opened\r\n * and otherwise only moves when the USER moves it. Switching to a tab, or\r\n * re-opening a session that already has one, leaves the strip exactly as it was\r\n * — so clicking a chip never moves the chip out from under the pointer. The\r\n * order changes on: a session opening for the FIRST time (append), a tab closing\r\n * (remove), a drag (move), and a pin toggle (which carries the chip across the\r\n * pinned boundary).\r\n *\r\n * The array IS the display order, with one invariant the transforms maintain:\r\n * every pinned tab sits before every unpinned one. New tabs therefore append at\r\n * the end (the unpinned block) and pinning/unpinning re-inserts at the boundary\r\n * between the two blocks. A stored strip from an older build has no `pinned`\r\n * flag, which reads as \"unpinned\" and satisfies the invariant as-is.\r\n *\r\n * Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):\r\n * the component owns the ref + React state, this module owns every rule, and\r\n * unit tests exercise the real semantics without a browser module loader.\r\n *\r\n * Retention note: a tab outlives whatever it points at. The strip is a list of\r\n * things the USER opened, so nothing here consults the session catalog — a tab\r\n * whose session is gone stays visible until the user closes it, and no\r\n * background sweep ever trims the strip.\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { SessionStatus } from '@deepseek-ai/dsh-client-ui-session/client'\r\n\r\n/** One open tab: a session id plus its arrival key (React list identity). */\r\nexport interface SessionTab {\r\n /** The session the tab shows. */\r\n readonly sessionId: SessionId\r\n /**\r\n * Monotonic arrival key. It doubles as the React `key`, so it must stay\r\n * attached to the session for the tab's whole life — a reused key would make\r\n * React move an existing chip's DOM node instead of reconciling it in place.\r\n */\r\n readonly order: number\r\n /**\r\n * Pinned tabs stay at the front of the strip and survive `close others`.\r\n *\r\n * Absent means unpinned: that is both the `false` case and the shape an older\r\n * build's stored strip has, so no migration step is needed to read one back.\r\n */\r\n readonly pinned?: boolean\r\n /**\r\n * A label the user typed for THIS tab, overriding the session's title.\r\n *\r\n * Kept separate from the session title on purpose: renaming a tab here must\r\n * not rewrite the conversation's own name (which the sidebar and the search\r\n * results show). Absent/empty means \"follow the session\".\r\n */\r\n readonly title?: string\r\n}\r\n\r\n/** Feature switch: whether opening a session also surfaces a tab. */\r\nexport type TabOpenMode = 'auto' | 'manual'\r\n\r\n/** Per-tab indicator derived from the catalog summary and the live UI status. */\r\nexport interface SessionTabIndicator {\r\n /** A domain request is waiting for the user (approval / plan review / question). */\r\n readonly attention: boolean\r\n /** The agent is producing output, or a descendant subagent is. */\r\n readonly running: boolean\r\n /** The turn finished while the tab was in the background and was never looked at. */\r\n readonly unread: boolean\r\n /** Idle tab whose session already has a title (a settled conversation). */\r\n readonly settled: boolean\r\n}\r\n\r\n/**\r\n * Add a session to the strip, or leave an existing entry exactly where it is.\r\n *\r\n * Arrival order is the strip's only order, so re-opening a session that already\r\n * has a tab is a NO-OP: the tab keeps its position and its arrival key. Moving\r\n * it to the front here would fight the whole point of stable positions — a user\r\n * clicking through sessions would watch the strip reshuffle on every click.\r\n *\r\n * @param tabs - current strip (oldest first).\r\n * @param sessionId - arriving session.\r\n * @param nextOrder - monotonic arrival counter to spend when appending.\r\n * @returns the strip, unchanged (same array) when the session already has a tab.\r\n */\r\nexport function appendTab(tabs: readonly SessionTab[], sessionId: SessionId, nextOrder: number): SessionTab[] {\r\n const existing = tabs.find(tab => tab.sessionId === sessionId)\r\n if (existing !== undefined) return tabs as SessionTab[]\r\n return [...tabs, { sessionId, order: nextOrder }]\r\n}\r\n\r\n/**\r\n * Remove one session's tab. An absent session leaves the strip untouched.\r\n * @param tabs - current strip.\r\n * @param sessionId - session whose tab closes.\r\n * @returns a new strip.\r\n */\r\nexport function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n return tabs.filter(tab => tab.sessionId !== sessionId)\r\n}\r\n\r\n/**\r\n * Whether a tab is pinned (absent counts as unpinned).\r\n * @param tab - the tab.\r\n * @returns true when the tab belongs in the pinned block.\r\n */\r\nfunction isPinned(tab: SessionTab): boolean {\r\n return tab.pinned === true\r\n}\r\n\r\n/**\r\n * Count the leading pinned block.\r\n *\r\n * The transforms keep every pinned tab before every unpinned one, so the pinned\r\n * block is always a prefix and its length is the single index that separates\r\n * the two blocks — which is exactly where a chip lands when it changes sides.\r\n *\r\n * @param tabs - strip in display order.\r\n * @returns how many leading tabs are pinned.\r\n */\r\nexport function pinnedCount(tabs: readonly SessionTab[]): number {\r\n let count = 0\r\n while (count < tabs.length && isPinned(tabs[count] as SessionTab)) count += 1\r\n return count\r\n}\r\n\r\n/**\r\n * Stable-partition a strip so every pinned tab precedes every unpinned one.\r\n *\r\n * Needed by the restore path: stored tabs are merged onto whatever the startup\r\n * flow already opened, and an append would otherwise park a pinned tab at the\r\n * end of the strip. Already-normalized strips come back as a copy.\r\n *\r\n * @param tabs - any strip.\r\n * @returns a strip satisfying the pinned-first invariant.\r\n */\r\nexport function normalizeTabs(tabs: readonly SessionTab[]): SessionTab[] {\r\n const pinned = tabs.filter(isPinned)\r\n if (pinned.length === 0 || pinned.length === tabs.length) return [...tabs]\r\n return [...pinned, ...tabs.filter(tab => !isPinned(tab))]\r\n}\r\n\r\n/**\r\n * Move one tab to a new place in the strip (drag and drop).\r\n *\r\n * `targetIndex` is an index in the RESULTING strip. The move is clamped to the\r\n * tab's own block — a dragged chip can be reordered within the pinned block or\r\n * within the unpinned one, but never carried across that boundary. Crossing it\r\n * is `togglePinTab`'s job, because it changes the tab's meaning rather than\r\n * just its position: pinning is what makes a tab survive `close others`.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the tab being moved.\r\n * @param targetIndex - desired index in the resulting strip.\r\n * @returns a new strip, or the same array when nothing moved.\r\n */\r\nexport function moveTab(\r\n tabs: readonly SessionTab[],\r\n sessionId: SessionId,\r\n targetIndex: number,\r\n): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const moving = tabs[from] as SessionTab\r\n const rest = tabs.filter(tab => tab.sessionId !== sessionId)\r\n const boundary = pinnedCount(rest)\r\n const min = isPinned(moving) ? 0 : boundary\r\n const max = isPinned(moving) ? boundary : rest.length\r\n const clamped = Math.min(Math.max(Math.trunc(targetIndex), min), max)\r\n if (clamped === from) return tabs as SessionTab[]\r\n return [...rest.slice(0, clamped), moving, ...rest.slice(clamped)]\r\n}\r\n\r\n/**\r\n * Pin or unpin one tab, re-inserting it at the boundary between the blocks.\r\n *\r\n * Pinning puts the chip at the END of the pinned block (next to the other\r\n * kept tabs) and unpinning at the START of the unpinned one, so a toggle never\r\n * throws a chip to the far end of the strip.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the tab to toggle.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function togglePinTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const moving = tabs[from] as SessionTab\r\n const rest = tabs.filter(tab => tab.sessionId !== sessionId)\r\n const boundary = pinnedCount(rest)\r\n const repinned: SessionTab = isPinned(moving)\r\n ? { sessionId: moving.sessionId, order: moving.order, ...(moving.title !== undefined ? { title: moving.title } : {}) }\r\n : { sessionId: moving.sessionId, order: moving.order, pinned: true, ...(moving.title !== undefined ? { title: moving.title } : {}) }\r\n return [...rest.slice(0, boundary), repinned, ...rest.slice(boundary)]\r\n}\r\n\r\n/**\r\n * Set or clear one tab's own label.\r\n *\r\n * A blank value CLEARS the override (the chip falls back to the session title)\r\n * rather than storing an empty label, so \"rename to nothing\" and \"rename back to\r\n * the session title\" are the same gesture.\r\n *\r\n * @param tabs - strip.\r\n * @param sessionId - the tab to relabel.\r\n * @param title - the new label; blank clears it.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function renameTab(\r\n tabs: readonly SessionTab[],\r\n sessionId: SessionId,\r\n title: string | undefined,\r\n): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n const trimmed = title?.trim() ?? ''\r\n // No change: return the same array so the store can skip the write.\r\n if ((tabs[from]?.title ?? '') === trimmed) return tabs as SessionTab[]\r\n return tabs.map((tab) => {\r\n if (tab.sessionId !== sessionId) return tab\r\n if (trimmed === '') {\r\n const { title: _cleared, ...rest } = tab\r\n void _cleared\r\n return rest\r\n }\r\n return { ...tab, title: trimmed }\r\n })\r\n}\r\n\r\n/**\r\n * Close every tab except one — pinned tabs stay.\r\n *\r\n * Pinning is exactly how a user says \"keep this no matter what\"; letting\r\n * `close others` eat the pinned block would make the flag pointless.\r\n *\r\n * @param tabs - strip.\r\n * @param keepSessionId - the tab to keep (plus every pinned one).\r\n * @returns a new strip.\r\n */\r\nexport function closeOtherTabs(tabs: readonly SessionTab[], keepSessionId: SessionId): SessionTab[] {\r\n if (!tabs.some(tab => tab.sessionId === keepSessionId)) return tabs as SessionTab[]\r\n return tabs.filter(tab => isPinned(tab) || tab.sessionId === keepSessionId)\r\n}\r\n\r\n/**\r\n * Close every tab after one in display order.\r\n *\r\n * \"After\" is display order (pinned block first), which is the order the user\r\n * sees; a pinned tab is never after an unpinned one, so this cannot silently\r\n * drop the kept block.\r\n *\r\n * @param tabs - strip in display order.\r\n * @param sessionId - the last tab that stays.\r\n * @returns a new strip, or the same array when the tab is absent.\r\n */\r\nexport function closeTabsAfter(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[] {\r\n const from = tabs.findIndex(tab => tab.sessionId === sessionId)\r\n if (from < 0) return tabs as SessionTab[]\r\n return tabs.slice(0, from + 1)\r\n}\r\n\r\n/**\r\n * Order the strip for display: strictly by arrival, regardless of which tab is\r\n * active.\r\n *\r\n * Position is a property of the TAB, not of the selection. Switching to a tab\r\n * must not move it — an earlier version pulled the active tab to the front,\r\n * which made every click reshuffle the strip and slid the chip out from under\r\n * the pointer that had just clicked it.\r\n *\r\n * `activeId` is therefore accepted only to document that \"active\" deliberately\r\n * does NOT participate in ordering; it is unused. The returned array is a copy\r\n * so callers cannot mutate the store's state through it.\r\n *\r\n * @param tabs - strip in arrival order.\r\n * @param activeId - the open session, if it has a tab (intentionally unused).\r\n * @returns a new array in arrival order.\r\n */\r\nexport function orderedTabs(tabs: readonly SessionTab[], activeId: SessionId | undefined): SessionTab[] {\r\n void activeId\r\n return [...tabs]\r\n}\r\n\r\n/**\r\n * Whether the open session must surface a tab.\r\n *\r\n * A tab means \"this conversation is in play right now\", not \"I once opened\r\n * this\". Browsing history is what the sidebar is for; opening an old\r\n * conversation to read it should not litter the strip, which is the whole point\r\n * of the strip being a working set rather than a second session list.\r\n *\r\n * A session therefore earns a tab only once a conversation has actually STARTED\r\n * in it and is still engaged, which is any of:\r\n * - **running** — the agent is producing output (including subagents);\r\n * - **waiting on you** — an approval / plan review / question is pending;\r\n * - **unseen completion** — it finished while you were elsewhere, so the tab is\r\n * the thing that tells you to come back.\r\n *\r\n * A still-blank draft gets NO tab: the tab appears the moment the first message\r\n * is sent (which is when the controller flips `blank` on `turn/start`). Once the\r\n * turn ends and you have read the result, the session is settled history and\r\n * does not earn a tab — so clicking through finished conversations leaves the\r\n * strip alone. Tabs already opened stay open: this gate only decides whether a\r\n * NEW tab appears, never whether an existing one closes.\r\n *\r\n * `blank` (from `sessionListMetadata`) is exactly \"no turn has started\": the\r\n * controller flips it to false on `turn/start`. It is the right signal for\r\n * \"has this conversation begun\", and the wrong one ALONE — a conversation\r\n * finished a week ago is also non-blank, which is why the earlier `!blank` rule\r\n * surfaced every old conversation the user clicked.\r\n *\r\n * @param mode - feature switch ('auto' applies the engagement rule).\r\n * @param summary - the session's catalog row (absent while the catalog has not\r\n * caught up with a just-created session).\r\n * @param status - the session's unified UI status (absent → no live signal).\r\n * @returns true when a tab belongs in the strip.\r\n */\r\nexport function shouldOpenTab(\r\n mode: TabOpenMode,\r\n summary: SessionSummary | undefined,\r\n status: SessionStatus | undefined,\r\n): boolean {\r\n if (mode === 'manual') return false\r\n if (summary === undefined) return false\r\n // No turn yet: a scratch draft is not a conversation, so it holds no tab. The\r\n // first message flips `blank`, and the tab appears then.\r\n if (summary.blank) return false\r\n // A conversation has begun. Keep the tab only while it is still in play.\r\n if (summary.running) return true\r\n if (status?.running === true) return true\r\n if (status?.pendingInteraction !== undefined) return true\r\n if (status?.completionUnread === true) return true\r\n // Begun, but quiet and read: settled history, not a working tab.\r\n return false\r\n}\r\n\r\n/**\r\n * Derive one tab's indicators from the catalog row and the unified UI status.\r\n * @param summary - the tab session's catalog row (absent → inert indicators).\r\n * @param status - the tab session's unified UI status (absent → idle).\r\n * @returns the indicator quadruple.\r\n */\r\nexport function tabIndicator(\r\n summary: SessionSummary | undefined,\r\n status: SessionStatus | undefined,\r\n): SessionTabIndicator {\r\n const pending = status?.pendingInteraction !== undefined\r\n const running = status?.running === true || summary?.running === true\r\n const unread = status?.completionUnread === true\r\n const blank = summary?.blank !== false\r\n return {\r\n attention: pending,\r\n running,\r\n unread,\r\n settled: !pending && !running && !unread && summary !== undefined && !blank,\r\n }\r\n}\r\n\r\n/**\r\n * Where one session lives: the project (workspace) that accounts for it.\r\n *\r\n * Tabs carry this because a strip of bare session titles is ambiguous once\r\n * several projects are open — two checkouts both named \"api\", or a session\r\n * titled after a file, give no hint which project it belongs to.\r\n */\r\nexport interface TabProject {\r\n /** Stable workspace id. */\r\n readonly workspaceId: string\r\n /** Display label: the workspace title, falling back to its directory name. */\r\n readonly label: string\r\n /** Canonical directory path, for the tooltip. */\r\n readonly path: string\r\n}\r\n\r\n/**\r\n * Index sessions by the project that owns them.\r\n *\r\n * Membership comes from the workspace registry (`sessionIds`), which is the same\r\n * authority the sidebar tree uses — a tab and its sidebar row therefore agree on\r\n * the project without a second derivation.\r\n *\r\n * Built once per render pass rather than scanned per tab: a strip of N tabs over\r\n * M projects is O(N×M) with a naive `find` per tab.\r\n *\r\n * @param workspaces - workspace views from the controller snapshot.\r\n * @returns a session id → project map; sessions in no workspace are absent.\r\n */\r\nexport function projectIndex(\r\n workspaces: readonly WorkspaceViewLike[],\r\n): ReadonlyMap {\r\n const index = new Map()\r\n for (const workspace of workspaces) {\r\n const label = projectLabel(workspace)\r\n const project: TabProject = {\r\n workspaceId: workspace.workspaceId,\r\n label,\r\n path: workspace.path,\r\n }\r\n for (const sessionId of workspace.sessionIds) {\r\n // First writer wins: a session wrongly listed by two workspaces keeps the\r\n // first, so the tab never flickers between labels across renders.\r\n if (!index.has(sessionId)) index.set(sessionId, project)\r\n }\r\n }\r\n return index\r\n}\r\n\r\n/** Minimal workspace shape this module needs (keeps it importable in tests). */\r\nexport interface WorkspaceViewLike {\r\n readonly workspaceId: string\r\n readonly path: string\r\n readonly title: string\r\n readonly sessionIds: readonly SessionId[]\r\n}\r\n\r\n/**\r\n * Display label for a project: its title, else the directory basename.\r\n * @param workspace - workspace view.\r\n * @returns a non-empty label, falling back to the raw path.\r\n */\r\nexport function projectLabel(workspace: Pick): string {\r\n const title = workspace.title.trim()\r\n if (title !== '') return title\r\n // Both separators: the host path may be Windows or POSIX.\r\n const parts = workspace.path.split(/[\\\\/]/).filter(part => part !== '')\r\n return parts[parts.length - 1] ?? workspace.path\r\n}\r\n\r\n/**\r\n * Whether two strips are the same sequence of sessions (arrival keys ignored).\r\n * @param left - previous strip.\r\n * @param right - next strip.\r\n * @returns true when no entry was added, removed, or reordered.\r\n */\r\nexport function sameTabs(left: readonly SessionTab[], right: readonly SessionTab[]): boolean {\r\n return left.length === right.length\r\n && left.every((tab, index) => right[index]?.sessionId === tab.sessionId)\r\n}\r\n\r\n/** Session-tab strip state (the shape the store persists). */\r\nexport interface SessionTabsState {\r\n /** Open tabs in arrival order — the strip's one and only order. */\r\n tabs: SessionTab[]\r\n /** Monotonic arrival counter; each FIRST-time session spends one. */\r\n order: number\r\n}\r\n\r\n/**\r\n * Store transform: add the open session, or leave its existing tab in place.\r\n *\r\n * Live here rather than in `tab-store.ts` so unit tests can exercise the real\r\n * semantics without importing `@deepseek-ai/dsh-client-store` (which pulls\r\n * `zustand` into the test process). The store module binds these into its\r\n * actions table.\r\n *\r\n * The no-op guard matters: this runs on EVERY catalog change for the open\r\n * session, so an unguarded write would wake the strip and spend arrival keys on\r\n * every projection tick.\r\n *\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the session that just became open.\r\n */\r\nexport function touchTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = appendTab(state.tabs, sessionId, state.order + 1)\r\n // Same array => the session already had a tab; nothing changed, so nothing is\r\n // written and no subscriber wakes.\r\n if (next === state.tabs) return\r\n state.order += 1\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close one tab. Closing a session that has no tab is not a\r\n * state change, so it writes nothing.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to close.\r\n */\r\nexport function closeTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = removeTab(state.tabs, sessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: adopt tabs loaded from the host, MERGING with whatever is\r\n * already in the strip.\r\n *\r\n * Async by nature (the host read is a `fetch`), so it can land after the browser\r\n * has already opened a tab for the current session. Merging — rather than\r\n * \"ignore the read if the strip is non-empty\" — is what makes a restart safe:\r\n * the tab opened during startup survives AND the stored tabs still come back.\r\n * (Bailing on a non-empty strip would silently drop every stored tab whenever\r\n * the startup tab won the race, which is the common case for a session that is\r\n * running or unread.)\r\n *\r\n * The arrival counter is lifted above every restored key so a tab opened later\r\n * cannot reuse one; a reused key makes React move a chip's DOM node instead of\r\n * reconciling it.\r\n *\r\n * @param state - store draft, mutated in place.\r\n * @param tabs - tabs read from the host, oldest first.\r\n */\r\nexport function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void {\r\n if (tabs.length === 0) return\r\n const present = new Set(state.tabs.map(tab => tab.sessionId))\r\n const additions: SessionTab[] = []\r\n let order = state.order\r\n for (const tab of tabs) {\r\n // Never duplicate: a session already in the strip keeps its existing entry\r\n // and position.\r\n if (present.has(tab.sessionId)) continue\r\n present.add(tab.sessionId)\r\n // Re-key onto a fresh, monotonically increasing counter so a restored key\r\n // can never collide with one already spent.\r\n order += 1\r\n // Carry the chip's own presentation across the restore: a pinned tab or a\r\n // custom label that came back unpinned/untitled would silently lose the\r\n // user's configuration on every restart.\r\n additions.push({\r\n sessionId: tab.sessionId,\r\n order,\r\n ...(tab.pinned === true ? { pinned: true } : {}),\r\n ...(tab.title !== undefined ? { title: tab.title } : {}),\r\n })\r\n }\r\n if (additions.length > 0) {\r\n const merged = [...state.tabs, ...additions]\r\n // Restored tabs can be pinned, and appending them would park a pinned chip\r\n // past the unpinned ones. Re-establish the pinned-first invariant.\r\n state.tabs = merged.some(isPinned) ? normalizeTabs(merged) : merged\r\n }\r\n state.order = order\r\n}\r\n\r\n/**\r\n * Store transform: pin or unpin one tab.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to toggle.\r\n */\r\nexport function pinTabImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = togglePinTab(state.tabs, sessionId)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: move one tab to a new index (drag and drop).\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab being moved.\r\n * @param targetIndex - desired index in the resulting strip.\r\n */\r\nexport function moveTabImpl(state: SessionTabsState, sessionId: SessionId, targetIndex: number): void {\r\n const next = moveTab(state.tabs, sessionId, targetIndex)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: set or clear one tab's own label.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the tab to relabel.\r\n * @param title - the new label; blank clears it.\r\n */\r\nexport function renameTabImpl(state: SessionTabsState, sessionId: SessionId, title: string | undefined): void {\r\n const next = renameTab(state.tabs, sessionId, title)\r\n if (next === state.tabs) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close every unlisted tab, keeping the pinned ones.\r\n * @param state - store draft, mutated in place.\r\n * @param keepSessionId - the tab to keep.\r\n */\r\nexport function closeOthersImpl(state: SessionTabsState, keepSessionId: SessionId): void {\r\n const next = closeOtherTabs(state.tabs, keepSessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n\r\n/**\r\n * Store transform: close every tab after one in display order.\r\n * @param state - store draft, mutated in place.\r\n * @param sessionId - the last tab that stays.\r\n */\r\nexport function closeAfterImpl(state: SessionTabsState, sessionId: SessionId): void {\r\n const next = closeTabsAfter(state.tabs, sessionId)\r\n if (next.length === state.tabs.length) return\r\n state.tabs = next\r\n}\r\n","/**\r\n * The session-tab store: the `defineStore` binding and nothing else.\r\n *\r\n * The action TRANSFORMS live in `tabs.ts` (pure, runtime-free), so unit tests\r\n * exercise the real semantics without pulling in the store engine — this module\r\n * is the only place that needs `@deepseek-ai/dsh-client-store`, and importing it\r\n * from a test would drag `zustand` into the test process.\r\n *\r\n * One handle, one scope: the tab store is seated by the `sidebar.workspaces`\r\n * entry alone. The tab strip is a CHILD of that entry (rendered through a DOM\r\n * portal into the conversation column), not a second slot registration, so the\r\n * handle is never mounted under a second, differently-scoped slot — which the\r\n * registry rejects outright (\"one handle, one scope\").\r\n *\r\n * Placement is navigation, not data: the strip derives its active chip from the\r\n * open session, and arrival order is the strip's only order, so nothing here\r\n * mirrors selection.\r\n */\r\nimport { defineStore, type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport {\r\n closeAfterImpl,\r\n closeOthersImpl,\r\n closeTabImpl,\r\n moveTabImpl,\r\n pinTabImpl,\r\n renameTabImpl,\r\n restoreTabsImpl,\r\n touchTabImpl,\r\n type SessionTab,\r\n type SessionTabsState,\r\n} from './tabs.ts'\r\n\r\nexport type { SessionTabsState }\r\n\r\n/**\r\n * Session-tab strip actions (bound by the framework, handed to the browser).\r\n *\r\n * There is deliberately NO \"drop tabs whose session vanished\" action. An open\r\n * tab is closed by the USER and by nothing else — a program that trims the strip\r\n * on its own eventually eats tabs the user wanted, and the whole point of the\r\n * strip is that it holds what you opened.\r\n *\r\n * This is also why the store needs no catalog at all: it never consults one.\r\n */\r\nexport interface SessionTabsActions {\r\n /** Add the open session, or leave its existing tab untouched in place. */\r\n touch: (sessionId: SessionId) => void\r\n /** Close one tab; navigation is untouchable from here (the caller decides). */\r\n close: (sessionId: SessionId) => void\r\n /**\r\n * Replace the strip with tabs loaded from the host.\r\n *\r\n * The host read is a `fetch`, so it cannot happen inside `init()`. This action\r\n * is how the async result lands, and it is a no-op once the user has already\r\n * opened a tab — a slow response must never discard what they just did.\r\n */\r\n restore: (tabs: readonly SessionTab[]) => void\r\n /** Pin or unpin one tab (re-inserts it at the block boundary). */\r\n pin: (sessionId: SessionId) => void\r\n /** Move one tab to an index in the resulting strip (drag and drop). */\r\n move: (sessionId: SessionId, targetIndex: number) => void\r\n /** Set (or clear, with a blank value) one tab's own label. */\r\n rename: (sessionId: SessionId, title: string | undefined) => void\r\n /** Close everything except one tab; pinned tabs are kept. */\r\n closeOthers: (sessionId: SessionId) => void\r\n /** Close every tab after one in display order. */\r\n closeAfter: (sessionId: SessionId) => void\r\n}\r\n\r\n/** Annotation twin of the actions literal below (structural `ActionsDecl`). */\r\ntype SessionTabsActionsDecl = {\r\n touch: typeof touchTabImpl\r\n close: typeof closeTabImpl\r\n restore: typeof restoreTabsImpl\r\n pin: typeof pinTabImpl\r\n move: typeof moveTabImpl\r\n rename: typeof renameTabImpl\r\n closeOthers: typeof closeOthersImpl\r\n closeAfter: typeof closeAfterImpl\r\n}\r\n\r\n/**\r\n * The tab store's registered handle: identity + spec + the instance factory the\r\n * framework resolves per entry x scope. It deliberately does NOT claim the live\r\n * instance's faces (`getSnapshot` / `actions`) — `defineStore`'s concrete return\r\n * is structurally narrower, and this alias has to stay a type that value can be\r\n * assigned to.\r\n */\r\nexport type SessionTabsStoreHandle = StoreHandle\r\n\r\n/**\r\n * The live tab store value: the handle's `create()` product, which carries the\r\n * baked write set and the snapshot source. Named here so the registrations and\r\n * the strip's props can share one type without importing the store engine.\r\n */\r\nexport type SessionTabsInstance = ReturnType['create']>\r\n\r\n/**\r\n * Create the session-tab store handle.\r\n *\r\n * The strip starts EMPTY and is hydrated by the caller through the `restore`\r\n * action: persistence lives on the host behind a `fetch`, which cannot run\r\n * during `init()`. Browser storage is deliberately not used — the origin\r\n * includes the port, and every launch picks a new one, so `localStorage` and\r\n * `sessionStorage` both start empty on the next start.\r\n *\r\n * @returns the store handle (spec + type + identity + factory in one).\r\n */\r\nexport function createSessionTabsStore(): EngineStoreHandle {\r\n return defineStore({\r\n init: (): SessionTabsState => ({ tabs: [], order: 0 }),\r\n actions: {\r\n touch: touchTabImpl,\r\n close: closeTabImpl,\r\n restore: restoreTabsImpl,\r\n pin: pinTabImpl,\r\n move: moveTabImpl,\r\n rename: renameTabImpl,\r\n closeOthers: closeOthersImpl,\r\n closeAfter: closeAfterImpl,\r\n },\r\n })\r\n}\r\n\r\nexport type { SessionTab }","/**\r\n * Client side of the session-tab persistence, talking to\r\n * `GET|PUT /workspace-groups/tabs` on the host.\r\n *\r\n * Why not browser storage: **the origin includes the PORT**, and every `dsh web`\r\n * / `dsh test` / desktop launch picks a different one. `localStorage` and\r\n * `sessionStorage` are both scoped to the origin, so they start empty on the\r\n * next launch — a tab list kept there survives a reload only when the port\r\n * happens to match. The host's JSON sidecar has no such problem, which is why\r\n * the strip is stored there and read back verbatim.\r\n *\r\n * There is deliberately no per-browser-session marker. A marker has to live in\r\n * browser storage, which the port invalidates, so every restart looked like a\r\n * fresh session and silently discarded the user's tabs — the exact failure this\r\n * module exists to prevent.\r\n *\r\n * Every call is best-effort: a failed read means \"no tabs\" and a failed write is\r\n * swallowed, because the strip is a convenience and must never break the app.\r\n */\r\n\r\n/** Host route holding the strip. */\r\nexport const TABS_ROUTE = '/workspace-groups/tabs'\r\n\r\n/** One tab as it crosses the wire. */\r\nexport interface WireTab {\r\n readonly sessionId: string\r\n readonly order: number\r\n /** Pinned tabs are restored at the front of the strip. */\r\n readonly pinned?: boolean\r\n /** A label the user typed for the tab itself (absent = follow the session). */\r\n readonly title?: string\r\n}\r\n\r\n/**\r\n * Read one tab row off the wire, dropping the row when it is unusable.\r\n * @param entry - one element of the stored `tabs` array.\r\n * @returns the tab, or null for a malformed row.\r\n */\r\nfunction parseWireTab(entry: unknown): WireTab | null {\r\n if (typeof entry !== 'object' || entry === null) return null\r\n const row = entry as Record\r\n if (typeof row.sessionId !== 'string' || row.sessionId === '') return null\r\n if (typeof row.order !== 'number' || !Number.isFinite(row.order)) return null\r\n const pinned = row.pinned === true\r\n const title = typeof row.title === 'string' && row.title.trim() !== '' ? row.title.trim() : undefined\r\n return {\r\n sessionId: row.sessionId,\r\n order: row.order,\r\n ...(pinned ? { pinned: true } : {}),\r\n ...(title !== undefined ? { title } : {}),\r\n }\r\n}\r\n\r\n/**\r\n * Fetch the stored strip.\r\n * @param fetchImpl - fetch implementation (injectable for tests).\r\n * @returns the tabs, oldest first; empty on any failure.\r\n */\r\nexport async function loadTabs(fetchImpl: typeof fetch = fetch): Promise {\r\n try {\r\n const response = await fetchImpl(TABS_ROUTE, {\r\n method: 'GET',\r\n // Per-session state; a cached response would restore stale tabs.\r\n cache: 'no-store',\r\n })\r\n if (!response.ok) return []\r\n const body: unknown = await response.json()\r\n if (typeof body !== 'object' || body === null) return []\r\n const list = (body as { tabs?: unknown }).tabs\r\n if (!Array.isArray(list)) return []\r\n const tabs: WireTab[] = []\r\n for (const entry of list) {\r\n const tab = parseWireTab(entry)\r\n if (tab !== null) tabs.push(tab)\r\n }\r\n return tabs\r\n } catch {\r\n return []\r\n }\r\n}\r\n\r\n/**\r\n * Store the strip. Failures are swallowed.\r\n * @param state - the client's current strip and its arrival counter.\r\n * @param fetchImpl - fetch implementation (injectable for tests).\r\n */\r\nexport async function saveTabs(\r\n state: { order: number; tabs: readonly WireTab[] },\r\n fetchImpl: typeof fetch = fetch,\r\n): Promise {\r\n try {\r\n await fetchImpl(TABS_ROUTE, {\r\n method: 'PUT',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify({ order: state.order, tabs: state.tabs }),\r\n cache: 'no-store',\r\n // Survive a navigation that happens while the request is in flight; the\r\n // write is idempotent so a re-send is harmless.\r\n keepalive: true,\r\n })\r\n } catch {\r\n // Offline or the host is restarting: the next change writes the full state\r\n // again, so nothing is lost beyond this tick.\r\n }\r\n}\r\n","/**\r\n * A framework-shaped selector hook over a store instance.\r\n *\r\n * The renderer builds this hook for slot seats (`bindSnapshotSelector` in\r\n * ui-renderer, wrapping React's `useSyncExternalStoreWithSelector`), but the tab\r\n * strip is NOT a slot occupant: it renders through a DOM seat as a child of this\r\n * plugin's own `sidebar.workspaces` occupant, so it receives its store face as a\r\n * plain prop and needs the equivalent binding here.\r\n *\r\n * The implementation mirrors React's `useSyncExternalStoreWithSelector` without\r\n * depending on the `use-sync-external-store` package (it is not resolvable from\r\n * this plugin). The two behaviours that matter:\r\n *\r\n * - identity-stable subscribe/getSnapshot closures, so the strip never\r\n * resubscribes across renders;\r\n * - a memoized selection: the selector re-runs only when the state reference\r\n * changes, and an equal result (by `eq`, defaulting to `Object.is`) returns\r\n * the PREVIOUS reference, so a selector allocating a fresh array or object\r\n * does not spin the render loop.\r\n *\r\n * The hook must be called unconditionally (Rules of Hooks).\r\n */\r\nimport { useCallback, useRef, useSyncExternalStore } from 'react'\r\nimport type { ActionsDecl, StoreInstance } from '@deepseek-ai/dsh-client-store'\r\n\r\n/** One memory cell: the state it was derived from, and the value it produced. */\r\ninterface Selection {\r\n state: T\r\n value: S\r\n /** Whether `value` was produced by the selector (vs. carried over as equal). */\r\n hasValue: boolean\r\n}\r\n\r\n/**\r\n * Build a selector hook bound to one store instance.\r\n * @param instance - the live store instance (snapshot source).\r\n * @returns a `SnapshotSelectorHook`-compatible hook over that instance.\r\n */\r\nexport function createStoreHook>(\r\n instance: StoreInstance,\r\n): (selector: (state: T) => S, eq?: (a: S, b: S) => boolean) => S {\r\n // Captured once: stable closures keep uSES from resubscribing every render.\r\n const subscribe = (onChange: () => void): (() => void) => instance.subscribe(onChange)\r\n const getState = (): T => instance.getSnapshot()\r\n\r\n return function useSelector(\r\n selector: (state: T) => S,\r\n eq?: (a: S, b: S) => boolean,\r\n ): S {\r\n // Seeded eagerly so the first render selects without an extra pass.\r\n const memory = useRef | null>(null)\r\n\r\n // Re-select the value for the current state. Called by uSES on every\r\n // notification AND on every render; the memory makes it cheap and\r\n // reference-stable.\r\n const getSelection = useCallback((): S => {\r\n const state = getState()\r\n const previous = memory.current\r\n\r\n // Same state object => the previous value is still valid. This is the\r\n // path that lets an allocating selector stay reference-stable.\r\n if (previous !== null && previous.hasValue && Object.is(previous.state, state)) {\r\n return previous.value\r\n }\r\n\r\n const value = selector(state)\r\n\r\n // New state, but an equal value: carry the old reference forward so uSES\r\n // sees no change and skips the re-render.\r\n if (previous !== null && previous.hasValue) {\r\n const equal = eq !== undefined ? eq(previous.value, value) : Object.is(previous.value, value)\r\n if (equal) {\r\n memory.current = { state, value: previous.value, hasValue: true }\r\n return previous.value\r\n }\r\n }\r\n\r\n memory.current = { state, value, hasValue: true }\r\n return value\r\n }, [selector, eq])\r\n\r\n // The third argument is the server snapshot; the client plugin never\r\n // server-renders, so the same getter is correct for both.\r\n return useSyncExternalStore(subscribe, getSelection, getSelection)\r\n }\r\n}\r\n","/**\r\n * Shared config types for @dsh-xhl/workspace-groups. Pure types (zero runtime\r\n * deps) so both halves — the node half (sidecar YAML reading) and the\r\n * browser half (tree derivation) — compile against the same contract.\r\n */\r\n\r\n/** One classification rule: any rule that matches places the workspace in the category. */\r\nexport interface GroupRule {\r\n /** Absolute path prefix match (normalized, case-sensitive). */\r\n pathPrefix?: string\r\n /** Case-insensitive substring match against the workspace display title. */\r\n nameContains?: string\r\n /** Case-insensitive substring match against the workspace directory basename. */\r\n basenameContains?: string\r\n /** Exact absolute path match (normalized). */\r\n pathExact?: string\r\n}\r\n\r\n/** One category folder in the sidebar tree. */\r\nexport interface GroupCategory {\r\n /** Display label of the category folder. */\r\n name: string\r\n /** Rules; a workspace is classified here when ANY rule matches. */\r\n rules: GroupRule[]\r\n}\r\n\r\n/** Theme-safe palette id for a group's accent. */\r\nexport type GroupColor =\r\n | 'red' | 'orange' | 'amber' | 'green' | 'teal'\r\n | 'blue' | 'indigo' | 'purple' | 'pink' | 'gray'\r\n\r\n/** Whitelist shared by the host write-validation and the client picker. */\r\nexport const GROUP_COLORS: readonly GroupColor[] = [\r\n 'red', 'orange', 'amber', 'green', 'teal',\r\n 'blue', 'indigo', 'purple', 'pink', 'gray',\r\n]\r\n\r\n/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */\r\nexport type GroupIconId =\r\n | 'folder' | 'workspace' | 'code' | 'plugin' | 'skill' | 'data'\r\n | 'database' | 'api' | 'plan' | 'goal' | 'light' | 'globe'\r\n | 'archive' | 'branch' | 'users' | 'clock' | 'shield' | 'checklist'\r\n | 'sparkle' | 'tree'\r\n\r\nexport const GROUP_ICON_IDS: readonly GroupIconId[] = [\r\n 'folder', 'workspace', 'code', 'plugin', 'skill', 'data',\r\n 'database', 'api', 'plan', 'goal', 'light', 'globe',\r\n 'archive', 'branch', 'users', 'clock', 'shield', 'checklist',\r\n 'sparkle', 'tree',\r\n]\r\n\r\n/**\r\n * Presentation metadata for one group. Every field optional.\r\n *\r\n * The explicit `| undefined` on each field is what lets a UI patch clear a\r\n * value (`pruneAppearance` then drops it): under `exactOptionalPropertyTypes`\r\n * a bare `color?: GroupColor` would reject `{ color: undefined }`.\r\n */\r\nexport interface CategoryAppearance {\r\n /** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */\r\n color?: GroupColor | undefined\r\n /** `GroupIconId` preset id, or a short glyph (1–4 code units, emoji/latin). */\r\n icon?: string | undefined\r\n /** Pinned groups sort before unpinned ones (within the manual order). */\r\n pinned?: boolean | undefined\r\n}\r\n\r\n/** The full sidecar configuration (mirrors workspace-groups.yaml). */\r\nexport interface GroupsConfig {\r\n /** Category folders, in render order. First match wins. */\r\n categories: GroupCategory[]\r\n /**\r\n * Runtime grouping overlay (manual groups + per-workspace overrides).\r\n * Optional: the YAML file itself never carries it — the host GET route\r\n * merges it from `workspace-groups.manual.json`, and the browser PUT route\r\n * replaces it whole.\r\n */\r\n manual?: ManualGroups\r\n}\r\n\r\n/**\r\n * Runtime-managed grouping overlay: groups created in the sidebar UI plus\r\n * per-workspace category overrides and user-controlled ordering. Owned by the\r\n * plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never\r\n * written back into the operator YAML.\r\n *\r\n * All new fields are optional for backward compatibility (files written by\r\n * older plugin versions keep working); rendering falls back to sensible\r\n * defaults when they are absent. Note that an older plugin version writes the\r\n * whole file back, which silently drops fields it does not know about — e.g.\r\n * `appearance` (group color / icon / pin) is lost after a downgrade.\r\n */\r\nexport interface ManualGroups {\r\n /**\r\n * Manually created category folder names. These have no rules — they render\r\n * even while empty (a new group appears before anything is dragged into\r\n * it) and hold only workspaces assigned to them.\r\n */\r\n categories: string[]\r\n /**\r\n * Per-workspace category override, keyed by workspace id. Value is a\r\n * category display name (rule or manual), or `null` to force the workspace\r\n * into the uncategorized bucket even when a rule would match. An absent\r\n * key means \"classify by rules\".\r\n */\r\n assignments: Record\r\n /**\r\n * Display order of all category keys (rule display names + manual names).\r\n * The uncategorized bucket is never listed — it always renders last.\r\n * Absent = rule categories first (YAML order), manual groups appended in\r\n * creation order.\r\n */\r\n categoryOrder?: string[]\r\n /**\r\n * Per-category ordered workspace ids (user drag-reorder within a group).\r\n * Keyed by category display name; absent key = host registration order.\r\n */\r\n workspaceOrder?: Record\r\n /**\r\n * Rule category rename overrides: original YAML rule category name →\r\n * display name (UI rename of a rule group). Rules still classify by the\r\n * original name; only the rendered label/keys change.\r\n */\r\n renamed?: Record\r\n /**\r\n * Rule category original names hidden by a UI delete. Hidden rules are\r\n * inert: workspaces matching them become top-level (ungrouped).\r\n */\r\n hidden?: string[]\r\n /**\r\n * Per-group presentation, keyed by category DISPLAY name (same key space as\r\n * `categoryOrder`). Optional per field; an absent group has no presentation.\r\n * Dangling keys (a YAML category that no longer exists) are tolerated on read\r\n * and on write — see validateManualGroups.\r\n */\r\n appearance?: Record\r\n}\r\n\r\n/**\r\n * Legacy label of the fallback bucket. The top-level (ungrouped) concept\r\n * replaced the rendered \"未分类\" bucket: workspaces in no group render as\r\n * top-level rows beside the group folders. The constant survives for data\r\n * compatibility (reserved name, assignment null marker).\r\n */\r\nexport const UNCATEGORIZED_LABEL = '未分类'\r\n\r\n/**\r\n * Reserved key under `workspaceOrder` holding the manual order of TOP-LEVEL\r\n * (ungrouped) project rows. Distinct from any real group display name (a group\r\n * may not be named this), so it can never collide; the top-level list's order\r\n * is preserved exactly like a group's, and top-level rows can be reordered by\r\n * dragging.\r\n */\r\nexport const TOP_LEVEL_ORDER_KEY = '__topLevel__'\r\n\r\n/** Normalize a path for prefix matching: trailing slashes stripped. */\r\nexport function normalizePath(path: string): string {\r\n return path.replace(/[/\\\\]+$/, '')\r\n}\r\n","/**\r\n * Pure classification + ordering logic: decides which category a workspace\r\n * belongs to and how categories/workspaces are ordered. Shared by the host\r\n * half (validation) and the client half (tree derivation), so the semantics\r\n * can never drift between the config surface and the rendered tree.\r\n *\r\n * Category identity: a category's STABLE origin is its YAML rule category\r\n * name (or a manual-group name). Its DISPLAY key is what the tree renders and\r\n * what assignments reference — for rule categories that is the rename\r\n * override when present. Hidden rule categories are inert: workspaces that\r\n * would match them become top-level (ungrouped).\r\n */\r\nimport {\r\n normalizePath,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupCategory,\r\n type GroupRule,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from './types.ts'\r\n\r\n/** One rule match against a workspace's path and title. */\r\nfunction ruleMatches(rule: GroupRule, path: string, title: string): boolean {\r\n const normalized = normalizePath(path)\r\n if (rule.pathPrefix !== undefined && normalized.startsWith(normalizePath(rule.pathPrefix))) return true\r\n if (rule.pathExact !== undefined && normalized === normalizePath(rule.pathExact)) return true\r\n if (rule.nameContains !== undefined && title.toLowerCase().includes(rule.nameContains.toLowerCase())) return true\r\n if (rule.basenameContains !== undefined) {\r\n const base = path.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop() ?? ''\r\n if (base.toLowerCase().includes(rule.basenameContains.toLowerCase())) return true\r\n }\r\n return false\r\n}\r\n\r\n/** Classify a workspace by rules only; hidden categories are inert. */\r\nexport function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {\r\n for (const category of categories) {\r\n if (category.rules.some(rule => ruleMatches(rule, path, title))) return category\r\n }\r\n return undefined\r\n}\r\n\r\n/** Display name of a rule category: the rename override when present. */\r\nexport function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string {\r\n return manual?.renamed?.[originalName] ?? originalName\r\n}\r\n\r\n/** Whether a rule category has been hidden by a UI delete. */\r\nexport function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean {\r\n return manual?.hidden?.includes(originalName) ?? false\r\n}\r\n\r\n/** Presentation for a category display key, or undefined when unset. */\r\nexport function categoryAppearance(\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): CategoryAppearance | undefined {\r\n return manual?.appearance?.[key]\r\n}\r\n\r\n/** Whether a category display key is pinned. */\r\nexport function isCategoryPinned(manual: ManualGroups | undefined, key: string): boolean {\r\n return categoryAppearance(manual, key)?.pinned === true\r\n}\r\n\r\n/**\r\n * Drop empty presentation fields: `undefined` values, `pinned: false`, `icon: ''`.\r\n * Returns undefined when nothing is left, so callers can delete the whole entry.\r\n */\r\nexport function pruneAppearance(value: CategoryAppearance): CategoryAppearance | undefined {\r\n const result: CategoryAppearance = {}\r\n if (value.color !== undefined) result.color = value.color\r\n if (value.icon !== undefined && value.icon.trim() !== '') result.icon = value.icon\r\n if (value.pinned === true) result.pinned = true\r\n return Object.keys(result).length === 0 ? undefined : result\r\n}\r\n\r\n/** Rule category display names, in YAML render order (hidden ones excluded). */\r\nexport function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[] {\r\n const names: string[] = []\r\n for (const category of categories) {\r\n if (isHiddenRule(manual, category.name)) continue\r\n names.push(ruleDisplayName(manual, category.name))\r\n }\r\n return names\r\n}\r\n\r\n/** Original YAML rule name whose display name equals `key` (undefined when none). */\r\nexport function originalRuleNameForDisplay(\r\n categories: readonly GroupCategory[],\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): string | undefined {\r\n return categories.find(c => ruleDisplayName(manual, c.name) === key)?.name\r\n}\r\n\r\n/**\r\n * Effective category entries in display order: rule categories (YAML order,\r\n * hidden skipped, renamed applied) first, then manual-only groups in\r\n * creation order — unless `manual.categoryOrder` overrides the sequence.\r\n * Top-level (ungrouped) workspaces are never included; they render as\r\n * separate top-level rows after the group folders.\r\n *\r\n * The pin partition is part of DISPLAY ORDER, not a render-time concern:\r\n * pinned groups sort before unpinned ones *within* the manual order, and both\r\n * the tree and the drag-drop landing neighbours read this list, so they can\r\n * never disagree about what sits next to what.\r\n */\r\nexport interface EffectiveCategory {\r\n /** Display key (what the tree renders and assignments reference). */\r\n key: string\r\n /** Origin: a YAML rule category or a manual group. */\r\n source: 'rule' | 'manual'\r\n}\r\n\r\n/** Apply `manual.categoryOrder` to the default sequence (stable). */\r\nfunction orderByCategoryOrder(\r\n entries: EffectiveCategory[],\r\n order: readonly string[] | undefined,\r\n): EffectiveCategory[] {\r\n if (order === undefined || order.length === 0) return entries\r\n // Stable sort by position in categoryOrder; entries absent from the order\r\n // keep their relative default position after all ordered ones.\r\n const position = new Map(order.map((key, index) => [key, index]))\r\n return [...entries].sort((a, b) => {\r\n const pa = position.get(a.key)\r\n const pb = position.get(b.key)\r\n if (pa !== undefined && pb !== undefined) return pa - pb\r\n if (pa !== undefined) return -1\r\n if (pb !== undefined) return 1\r\n return 0\r\n })\r\n}\r\n\r\n/** Stable partition: pinned groups first, unpinned ones keep their order. */\r\nfunction pinnedFirst(entries: EffectiveCategory[], manual: ManualGroups | undefined): EffectiveCategory[] {\r\n if (manual?.appearance === undefined) return entries\r\n const pinned = (entry: EffectiveCategory): number => Number(isCategoryPinned(manual, entry.key))\r\n return [...entries].sort((a, b) => pinned(b) - pinned(a))\r\n}\r\n\r\nexport function effectiveCategories(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n): EffectiveCategory[] {\r\n const entries: EffectiveCategory[] = []\r\n const seen = new Set()\r\n for (const category of config.categories) {\r\n if (isHiddenRule(manual, category.name)) continue\r\n const key = ruleDisplayName(manual, category.name)\r\n if (seen.has(key)) continue\r\n seen.add(key)\r\n entries.push({ key, source: 'rule' })\r\n }\r\n for (const name of manual?.categories ?? []) {\r\n if (seen.has(name)) continue\r\n seen.add(name)\r\n entries.push({ key: name, source: 'manual' })\r\n }\r\n return pinnedFirst(orderByCategoryOrder(entries, manual?.categoryOrder), manual)\r\n}\r\n\r\n/** Display keys of all effective categories (top-level workspaces excluded). */\r\nexport function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[] {\r\n return effectiveCategories(config, manual).map(e => e.key)\r\n}\r\n\r\n/**\r\n * Resolve the category key a workspace renders under, or `undefined` when it\r\n * is top-level (ungrouped). Precedence: manual override (`null` = forced\r\n * top-level) → rule classification (hidden rules inert) → top-level.\r\n */\r\nexport function resolveCategory(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n workspaceId: string,\r\n path: string,\r\n title: string,\r\n): string | undefined {\r\n const override = manual?.assignments[workspaceId]\r\n if (override !== undefined) return override ?? undefined // null forces top-level\r\n const matched = classify(config.categories, path, title)\r\n if (matched === undefined) return undefined\r\n if (isHiddenRule(manual, matched.name)) return undefined\r\n return ruleDisplayName(manual, matched.name)\r\n}\r\n\r\n/** Whether a category key is a manual-only group (manageable via list). */\r\nexport function isManualOnlyCategory(\r\n config: GroupsConfig,\r\n manual: ManualGroups | undefined,\r\n key: string,\r\n): boolean {\r\n return (manual?.categories.includes(key) ?? false) && !ruleDisplayNames(config.categories, manual).includes(key)\r\n}\r\n\r\n/**\r\n * Names that may not be used for a new/renamed group: the legacy reserved\r\n * label plus every current display key.\r\n */\r\nexport function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set {\r\n const taken = new Set(displayCategoryKeys(config, manual))\r\n taken.add(UNCATEGORIZED_LABEL)\r\n return taken\r\n}\r\n\r\n/**\r\n * Order a bucket of workspace ids: the stored per-category order first\r\n * (filtered to actual members), then any remaining members in `fallback`\r\n * (host) order. Deterministic; the renderer never re-sorts on its own.\r\n */\r\nexport function orderedWorkspaceIds(\r\n manual: ManualGroups | undefined,\r\n categoryKey: string,\r\n members: readonly string[],\r\n): string[] {\r\n const stored = manual?.workspaceOrder?.[categoryKey]\r\n if (stored === undefined || stored.length === 0) return [...members]\r\n const memberSet = new Set(members)\r\n const ordered: string[] = []\r\n const seen = new Set()\r\n for (const id of stored) {\r\n if (!memberSet.has(id) || seen.has(id)) continue\r\n seen.add(id)\r\n ordered.push(id)\r\n }\r\n for (const id of members) {\r\n if (seen.has(id)) continue\r\n ordered.push(id)\r\n }\r\n return ordered\r\n}\r\n\r\n/** Move `id` before `beforeId` (undefined = append) within an ordered list. */\r\nexport function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[] {\r\n const rest = list.filter(x => x !== id)\r\n if (beforeId === undefined) return [...rest, id]\r\n const index = rest.indexOf(beforeId)\r\n if (index === -1) return [...rest, id]\r\n rest.splice(index, 0, id)\r\n return rest\r\n}\r\n\r\n/** Move `id` after `afterId` (undefined = append) within an ordered list. */\r\nexport function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[] {\r\n const rest = list.filter(x => x !== id)\r\n if (afterId === undefined) return [...rest, id]\r\n const index = rest.indexOf(afterId)\r\n if (index === -1) return [...rest, id]\r\n rest.splice(index + 1, 0, id)\r\n return rest\r\n}\r\n","/**\r\n * Plugin-owned projection of descendant counts from Session summaries.\r\n *\r\n * 0.1.2 移除了 `@deepseek-ai/dsh-client-runtime/client`(平台模块表不再提供\r\n * `indexSubagentDescendants`),官方 ui-workspace 改为各自持有本地副本\r\n * (packages/client/ui-workspace/src/client/subagent-lineage.ts,MIT)。这里\r\n * 保持同一实现,使运行中的子代理会话数在树行上继续可见。\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\n\r\ninterface LineageEntry {\r\n readonly id: SessionId\r\n readonly parentId?: SessionId\r\n readonly origin?: 'subagent'\r\n readonly running: boolean\r\n}\r\n\r\n/** Descendant counts for one possible parent Session. */\r\nexport interface SubagentDescendantSummary {\r\n readonly count: number\r\n readonly runningCount: number\r\n}\r\n\r\n/**\r\n * Index uninterrupted subagent descendants under each ancestor.\r\n * @param summaries - Session summaries keyed by id.\r\n * @returns descendant totals keyed by possible parent id.\r\n */\r\nexport function indexSubagentDescendants(\r\n summaries: Readonly>,\r\n): ReadonlyMap {\r\n const indexed = new Map()\r\n for (const descendant of Object.values(summaries)) {\r\n if (descendant.origin !== 'subagent') continue\r\n const seen = new Set()\r\n let current: LineageEntry | undefined = descendant\r\n while (current?.origin === 'subagent' && current.parentId !== undefined && !seen.has(current.id)) {\r\n seen.add(current.id)\r\n const aggregate = indexed.get(current.parentId)\r\n if (aggregate === undefined) {\r\n indexed.set(current.parentId, { count: 1, runningCount: descendant.running ? 1 : 0 })\r\n } else {\r\n aggregate.count += 1\r\n if (descendant.running) aggregate.runningCount += 1\r\n }\r\n current = summaries[current.parentId]\r\n }\r\n }\r\n return indexed\r\n}\r\n","/**\n * Pure folder-list logic for per-workspace multi-root folders.\n *\n * DSH core gives a workspace exactly ONE canonical directory\n * (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA\n * folders on top of it, plus one designated root folder per workspace:\n *\n * - the canonical directory is always folder #0 (the \"base\"); it cannot be\n * removed and may be the root;\n * - `root` is stored only when it names an EXTRA folder — \"base is the root\"\n * is expressed by omitting the key, so the base path is never duplicated\n * into the sidecar;\n * - a session whose recorded `cwd` lives inside an extra folder belongs to\n * that folder, not to the project row.\n *\n * Everything here is pure and platform-agnostic: it imports no React, no DOM\n * and no cordis so plain Node (the verifier, the host route) can load it.\n */\n\n/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */\nexport interface WorkspaceFolderEntry {\n readonly folders: readonly string[]\n readonly root?: string\n}\n\n/** The whole `workspace-groups.folders.json` document. */\nexport interface FoldersDocument {\n readonly version: 1\n readonly workspaces: Readonly>\n}\n\n/** Canonical empty document, shared so callers need not allocate one each time. */\nexport const EMPTY_FOLDERS_DOCUMENT: FoldersDocument = { version: 1, workspaces: {} }\n\n/** `C:\\…` or `C:/…` — a drive-rooted Windows path. */\nconst WINDOWS_DRIVE = /^[A-Za-z]:[\\\\/]/u\n\n/** `\\\\server\\share` — a Windows UNC path. */\nconst WINDOWS_UNC = /^\\\\\\\\/u\n\n/** True for both Windows path spellings accepted by the write validator. */\nfunction isWindowsStyle(path: string): boolean {\n return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)\n}\n\n/**\n * Comparison form of one path: trimmed, separator-normalized and, for Windows\n * spellings, lower-cased (drive letters and file names are case-insensitive\n * there). Trailing separators are dropped except for a drive/UNC/root prefix.\n * @param path - raw path as stored or picked.\n * @returns the canonical comparison form.\n */\nfunction canonicalPath(path: string): string {\n const trimmed = path.trim()\n if (isWindowsStyle(trimmed)) {\n let value = trimmed.replaceAll('/', '\\\\').toLowerCase()\n // `C:\\` is three characters and already a root; `\\\\srv\\share\\` keeps its\n // trailing separator only while a further segment remains.\n while (value.length > 3 && value.endsWith('\\\\')) value = value.slice(0, -1)\n return value\n }\n let value = trimmed\n while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)\n return value\n}\n\n/**\n * Path equality: case-insensitive for Windows-style paths, tolerant of\n * trailing separators, exact for POSIX paths.\n * @param a - first path.\n * @param b - second path.\n */\nexport function samePath(a: string, b: string): boolean {\n return canonicalPath(a) === canonicalPath(b)\n}\n\n/**\n * Look up the folder entry saved for one workspace.\n * @param doc - folders document.\n * @param workspaceId - host workspace id.\n * @returns the entry, or undefined when the workspace has none.\n */\nexport function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined {\n return doc.workspaces[workspaceId]\n}\n\n/**\n * The workspace's effective folder list, base first. The base cannot be\n * duplicated and blank extra entries are dropped.\n * @param workspacePath - canonical directory of the workspace.\n * @param entry - saved folder entry, if any.\n */\nexport function effectiveFolders(\n workspacePath: string,\n entry: WorkspaceFolderEntry | undefined,\n): readonly string[] {\n const extras: string[] = []\n for (const folder of entry?.folders ?? []) {\n if (folder.trim() === '') continue\n if (samePath(folder, workspacePath)) continue\n if (extras.some(existing => samePath(existing, folder))) continue\n extras.push(folder)\n }\n return [workspacePath, ...extras]\n}\n\n/**\n * The folder new sessions start in by default.\n * @param workspacePath - canonical directory of the workspace.\n * @param entry - saved folder entry, if any.\n * @returns the stored root when it names an effective extra folder, else the\n * workspace's own directory.\n */\nexport function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string {\n const root = entry?.root\n if (root === undefined) return workspacePath\n const folders = effectiveFolders(workspacePath, entry)\n return folders.find(folder => samePath(folder, root)) ?? workspacePath\n}\n\n/**\n * Owning folder of a session cwd: the most specific (longest) effective folder\n * that equals the cwd or is a proper path ancestor of it.\n * @param cwd - recorded session cwd; undefined means \"the workspace itself\".\n * @param workspacePath - canonical directory of the workspace.\n * @param entry - saved folder entry, if any.\n * @returns the owning folder, or the workspace path when nothing matches.\n */\nexport function folderOfCwd(\n cwd: string | undefined,\n workspacePath: string,\n entry: WorkspaceFolderEntry | undefined,\n): string {\n if (cwd === undefined) return workspacePath\n const target = canonicalPath(cwd)\n let best: string | undefined\n let bestLength = -1\n for (const folder of effectiveFolders(workspacePath, entry)) {\n const root = canonicalPath(folder)\n if (root === '') continue\n const separator = isWindowsStyle(root) ? '\\\\' : '/'\n const prefix = root.endsWith(separator) ? root : `${root}${separator}`\n if (target !== root && !target.startsWith(prefix)) continue\n if (root.length > bestLength) {\n best = folder\n bestLength = root.length\n }\n }\n return best ?? workspacePath\n}\n\n/**\n * Append an extra folder. Idempotent under `samePath`, and the stored root (if\n * any) survives untouched.\n * @param entry - current entry, or undefined for a workspace with no extras.\n * @param path - folder path to append.\n */\nexport function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {\n const folders = entry?.folders ?? []\n const root = entry?.root\n const trimmed = path.trim()\n const keepRoot = root === undefined ? {} : { root }\n if (trimmed === '' || folders.some(folder => samePath(folder, trimmed))) {\n return { folders: [...folders], ...keepRoot }\n }\n return { folders: [...folders, trimmed], ...keepRoot }\n}\n\n/**\n * Drop an extra folder. A root that pointed at it is cleared, so the workspace\n * falls back to its own directory instead of referencing a folder it no longer\n * has.\n * @param entry - current entry, or undefined.\n * @param path - folder path to drop.\n */\nexport function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {\n const folders = entry?.folders ?? []\n const remaining = folders.filter(folder => !samePath(folder, path))\n const root = entry?.root\n const keepRoot = root !== undefined && !samePath(root, path)\n return { folders: remaining, ...(keepRoot ? { root } : {}) }\n}\n\n/**\n * Designate the root folder. Only an extra folder can be stored: naming the\n * base directory means \"no explicit root\", which is represented by clearing\n * the key.\n * @param entry - current entry, or undefined.\n * @param path - folder to make the root.\n */\nexport function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {\n const folders = entry?.folders ?? []\n const match = folders.find(folder => samePath(folder, path))\n if (match === undefined) return { folders: [...folders] }\n return { folders: [...folders], root: match }\n}\n","/**\r\n * Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →\r\n * 会话行. Pure derivation — all inputs are snapshots; the renderer never\r\n * scans. Session visibility rules mirror the official ui-workspace tree\r\n * (blank rows only when current, archived excluded, subagent rows excluded).\r\n */\r\nimport type {\r\n SessionListState,\r\n SessionSearchResultItem,\r\n SessionSummary,\r\n} from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\n// Type-only: the unified UI status snapshot. 0.1.6 把 running / pendingInteraction /\r\n// 未读完成提示收敛为 ui-session 的 SessionStatusSnapshot;SessionSummary.completed\r\n// 与 SessionListState.current 同时移除,当前会话改由 `mainView` 保留位推导。\r\nimport type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport { indexSubagentDescendants, type SubagentDescendantSummary } from './subagent-lineage.ts'\r\nimport { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'\r\nimport {\r\n EMPTY_FOLDERS_DOCUMENT,\r\n effectiveFolders,\r\n entryFor,\r\n folderOfCwd,\r\n rootOf,\r\n samePath,\r\n type FoldersDocument,\r\n type WorkspaceFolderEntry,\r\n} from '../core/folders.ts'\r\nimport {\r\n TOP_LEVEL_ORDER_KEY,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from '../core/types.ts'\r\n\r\n/** Pending interaction kinds with dedicated Workspace-row presentation. */\r\nexport type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question'\r\n\r\n/** Current unified UI status by Session (ui-session snapshot). */\r\ntype SessionStatuses = SessionStatusSnapshot\r\n\r\n/**\r\n * The Session the Conversation is currently showing.\r\n *\r\n * 0.1.6 removed `SessionListState.current`: selection is expressed as the\r\n * Session retained through the `mainView` reference source (the ui-workspace\r\n * navigation holds exactly one). Same read the official browser performs.\r\n * @param list - sessions list snapshot.\r\n * @returns the retained Session id, or undefined while no Session is selected.\r\n */\r\nexport function currentSessionId(list: SessionListState): SessionId | undefined {\r\n return Object.values(list.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id\r\n}\r\n\r\n/** Keep navigation presentation independent from domain-owned interaction objects. */\r\nfunction visiblePendingKind(kind: string | undefined): SessionPendingInteractionStatus | undefined {\r\n switch (kind) {\r\n case 'approval':\r\n case 'plan-review':\r\n case 'question':\r\n return kind\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/** One top-level session row inside a workspace folder. */\r\nexport interface SessionNode {\r\n id: SessionId\r\n /** Stored display title; blank rows show the localized New Session label. */\r\n title: string\r\n /** The provisional blank session (renderer shows the localized New Session title). */\r\n blank: boolean\r\n pendingInteraction?: SessionPendingInteractionStatus\r\n running: boolean\r\n /** Running descendants connected through uninterrupted subagent-origin lineage. */\r\n runningSubagentCount: number\r\n /** Finished running while not selected and not yet opened (the green \"done\" reminder dot). */\r\n completed: boolean\r\n updatedAt: number\r\n /** Search-hit marker (rendered with a highlighted tint in search mode). */\r\n matched?: boolean\r\n /** Content-match snippet from the Host search (search mode only). */\r\n snippet?: string\r\n}\r\n\r\n/** One folder row inside a workspace folder (base or extra). */\r\nexport interface FolderNode {\r\n /** Absolute folder path. */\r\n path: string\r\n /** Display label: last path segment, or the whole path for drive roots. */\r\n label: string\r\n /** The workspace's default target for new sessions (★). */\r\n isRoot: boolean\r\n expanded: boolean\r\n /** The workspace's own canonical directory (folder #0); cannot be removed. */\r\n isBase: boolean\r\n /** Visible sessions whose recorded cwd lives inside this folder. */\r\n sessions: readonly SessionNode[]\r\n}\r\n\r\n/** One workspace folder row inside a category folder. */\r\nexport interface WorkspaceGroupNode {\r\n workspaceId: WorkspaceId\r\n /** Canonical host directory path. */\r\n path: string\r\n /** Display title. */\r\n label: string\r\n /** Workspace creation time (epoch ms). */\r\n createdAt: number\r\n /** Total visible sessions in the folder (every folder included). */\r\n sessionCount: number\r\n expanded: boolean\r\n /** The folder contains the selected session (active folder tint). */\r\n containsCurrent: boolean\r\n /** Base-owned visible session rows (empty while the folder is folded). */\r\n sessions: readonly SessionNode[]\r\n /**\r\n * Folder rows, present only when the workspace carries at least one extra\r\n * folder: root first, then stored order, base included. Absent means \"this\r\n * workspace has exactly one directory\", the plain pre-folders node shape.\r\n */\r\n folders?: readonly FolderNode[]\r\n}\r\n\r\n/** One category folder at the top of the tree. */\r\nexport interface CategoryNode {\r\n /** Stable category key: the configured label, or the uncategorized bucket. */\r\n key: string\r\n /** Display label. */\r\n label: string\r\n expanded: boolean\r\n /** The category contains the selected session (active folder tint). */\r\n containsCurrent: boolean\r\n /** Workspace folders in host order. */\r\n workspaces: readonly WorkspaceGroupNode[]\r\n /** Presentation (color / icon / pin) for this category, when configured. */\r\n appearance?: CategoryAppearance\r\n}\r\n\r\n/** Viewing state consumed by the derivation. */\r\nexport interface GroupsTreeView {\r\n expandedCategories: readonly string[]\r\n expandedWorkspaces: readonly string[]\r\n /**\r\n * Collapsed folder rows, keyed by `folderKey(workspaceId, path)`. Folders are\r\n * expanded by default: adding a folder must never hide the sessions that used\r\n * to show flat under the project.\r\n */\r\n collapsedFolders?: readonly string[]\r\n}\r\n\r\n/** Key of the uncategorized bucket (matches the config fallback label). */\r\nexport const UNCATEGORIZED_KEY = UNCATEGORIZED_LABEL\r\n\r\n/** Directory display label: basename of the path (both separators accepted). */\r\nexport function workspaceLabel(cwd: string | undefined): string {\r\n if (cwd === undefined || cwd === '') return UNCATEGORIZED_LABEL\r\n const base = cwd.replace(/[/\\\\]+$/, '').split(/[/\\\\]/).pop()\r\n return base !== undefined && base !== '' ? base : cwd\r\n}\r\n\r\n/** Ordinary sessions are visible; blank only when current; archived/subagent never. */\r\nfunction sessionVisible(session: SessionSummary, current: SessionId | undefined, archived: ReadonlySet): boolean {\r\n return session.origin !== 'subagent'\r\n && !archived.has(session.id)\r\n && (!session.blank || session.id === current)\r\n}\r\n\r\n/** Blank rows display the localized New Session label (never enters search). */\r\nfunction sessionTitle(session: SessionSummary): string {\r\n return session.blank ? 'New Session' : session.displayTitle\r\n}\r\n\r\nfunction sessionNode(\r\n s: SessionSummary,\r\n descendants: ReadonlyMap,\r\n statuses: SessionStatuses,\r\n): SessionNode {\r\n // `SessionStatusSnapshot` is typed as ReadonlyMap, but the framework binds a\r\n // plain record at runtime (client.js: `statuses[sessionId]`). Read both shapes\r\n // so a hook backed by an object never throws \"statuses.get is not a function\".\r\n const status = typeof (statuses as { get?: unknown } | undefined)?.get === 'function'\r\n ? statuses.get(s.id)\r\n : (statuses as unknown as Record)[s.id]\r\n const pending = visiblePendingKind(status?.pendingInteraction?.kind)\r\n return {\r\n id: s.id,\r\n title: sessionTitle(s),\r\n blank: s.blank,\r\n running: status?.running ?? s.running,\r\n runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,\r\n completed: status?.completionUnread === true,\r\n updatedAt: s.updatedAt,\r\n ...(pending === undefined ? {} : { pendingInteraction: pending }),\r\n }\r\n}\r\n\r\n/** Visible sessions of one workspace in its stored account order. */\r\nfunction workspaceSessions(\r\n list: SessionListState,\r\n workspace: WorkspaceView,\r\n archived: ReadonlySet,\r\n descendants: ReadonlyMap,\r\n statuses: SessionStatuses,\r\n current: SessionId | undefined,\r\n): SessionNode[] {\r\n const nodes: SessionNode[] = []\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined) continue // account may lead the list pull; appears when the summary lands\r\n if (!sessionVisible(summary, current, archived)) continue\r\n nodes.push(sessionNode(summary, descendants, statuses))\r\n }\r\n return nodes\r\n}\r\n\r\n/**\r\n * Display label of one folder: the last path segment. A drive root (`C:\\`) or\r\n * the POSIX root has no segment, so the whole path is the honest label.\r\n * @param path - absolute folder path.\r\n */\r\nexport function folderLabel(path: string): string {\r\n const trimmed = path.replace(/[/\\\\]+$/u, '')\r\n if (trimmed === '' || /^[A-Za-z]:$/u.test(trimmed)) return path\r\n const base = trimmed.split(/[/\\\\]/u).pop()\r\n return base !== undefined && base !== '' ? base : path\r\n}\r\n\r\n/** Stable identity of one folder row (same path may live under two workspaces). */\r\nexport function folderKey(workspaceId: WorkspaceId, path: string): string {\r\n return `${workspaceId}\\u0000${path}`\r\n}\r\n\r\n/**\r\n * Split a workspace's visible sessions between its base directory and its extra\r\n * folders. Sessions keep the order they already had inside their owner, and a\r\n * workspace with no extra folder returns its sessions untouched — the pre-\r\n * folders node shape (no `folders` key at all).\r\n * @param workspaceId - owning workspace.\r\n * @param workspacePath - canonical directory (folder #0).\r\n * @param sessions - every visible session of the workspace, in host order.\r\n * @param list - sessions list snapshot (records each session's cwd).\r\n * @param entry - saved extra folders + root for this workspace.\r\n * @param collapsedFolders - collapsed folder-row keys. Undefined means \"nothing\r\n * is collapsed\", which is both the default view and what search uses so every\r\n * hit is visible without another click.\r\n */\r\nfunction applyFolders(\r\n workspaceId: WorkspaceId,\r\n workspacePath: string,\r\n sessions: readonly SessionNode[],\r\n list: SessionListState,\r\n entry: WorkspaceFolderEntry | undefined,\r\n collapsedFolders: ReadonlySet | undefined,\r\n): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {\r\n const extras = effectiveFolders(workspacePath, entry).slice(1)\r\n if (extras.length === 0) return { sessions }\r\n const root = rootOf(workspacePath, entry)\r\n const base: SessionNode[] = []\r\n const byFolder = new Map()\r\n for (const node of sessions) {\r\n const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry)\r\n if (samePath(owner, workspacePath)) {\r\n base.push(node)\r\n continue\r\n }\r\n const bucket = byFolder.get(owner)\r\n if (bucket === undefined) byFolder.set(owner, [node])\r\n else bucket.push(node)\r\n }\r\n const folderNode = (path: string, isBase: boolean): FolderNode => {\r\n const owned = isBase ? base : (byFolder.get(path) ?? [])\r\n return {\r\n path,\r\n label: folderLabel(path),\r\n isRoot: samePath(path, root),\r\n expanded: collapsedFolders === undefined || !collapsedFolders.has(folderKey(workspaceId, path)),\r\n isBase,\r\n // Every owned session is kept on the node so the row's count stays honest\r\n // while the folder is collapsed; the RowGroup does the hiding.\r\n sessions: owned,\r\n }\r\n }\r\n const folders: FolderNode[] = [\r\n folderNode(workspacePath, true),\r\n ...extras.map(path => folderNode(path, false)),\r\n ]\r\n // Root first, then stored order: moving the root row to the front keeps the\r\n // remaining rows (base included) in their stored order.\r\n const rootIndex = folders.findIndex(folder => folder.isRoot)\r\n if (rootIndex > 0) {\r\n const [rootFolder] = folders.splice(rootIndex, 1)\r\n if (rootFolder !== undefined) folders.unshift(rootFolder)\r\n }\r\n return { sessions: base, folders }\r\n}\r\n\r\n/**\r\n * Derive the three-level tree.\r\n * @param list - sessions list snapshot (`current` feeds containsCurrent).\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param archivedSessionIds - registry-global archive set.\r\n * @param config - sidecar grouping config (rule categories).\r\n * @param view - local expansion arrays.\r\n * @param manual - runtime overlay (manual groups + overrides). A workspace's\r\n * manual override wins over rule classification; removing it reverts to rules.\r\n * @param statuses - unified UI status by Session (drives the running / warning\r\n * / unread-completion row indicators); defaults to none (tests).\r\n * @param folders - per-workspace extra folders + root. A workspace with extras\r\n * gains folder rows and its extra-folder sessions move under them; a workspace\r\n * without extras keeps exactly the pre-folders node shape.\r\n * @returns category sections in render order (rule categories first, then\r\n * manual-only ones, uncategorized last). Manual groups render even while\r\n * empty; empty rule buckets stay hidden.\r\n */\r\nexport function deriveGroups(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n archivedSessionIds: readonly SessionId[],\r\n config: GroupsConfig,\r\n view: GroupsTreeView,\r\n manual: ManualGroups,\r\n statuses: SessionStatuses = new Map(),\r\n folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,\r\n): CategoryNode[] {\r\n const archived = new Set(archivedSessionIds)\r\n const expandedCategories = new Set(view.expandedCategories)\r\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\r\n const collapsedFolders = new Set(view.collapsedFolders ?? [])\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n // Bucket workspaces by display key. Seed with every effective category so\r\n // manual groups render while empty. Top-level (ungrouped) workspaces are\r\n // handled by deriveTopLevel and never land here.\r\n const byCategory = new Map()\r\n for (const { key } of effectiveCategories(config, manual)) {\r\n byCategory.set(key, [])\r\n }\r\n for (const workspace of workspaces) {\r\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n if (key === undefined) continue // top-level — rendered by deriveTopLevel\r\n if (!byCategory.has(key)) byCategory.set(key, [])\r\n byCategory.get(key)!.push(workspace)\r\n }\r\n\r\n const manualCategories = new Set(manual.categories)\r\n const currentWorkspaceId = current === undefined\r\n ? undefined\r\n : workspaces.find(w => w.sessionIds.includes(current))?.workspaceId\r\n\r\n const nodes: CategoryNode[] = []\r\n // Effective categories in display order (categoryOrder applied).\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) {\r\n const bucket = byCategory.get(key) ?? []\r\n // Manual groups stay visible while empty; everything else hides when empty.\r\n if (bucket.length === 0 && !manualCategories.has(key)) continue\r\n const expanded = expandedCategories.has(key)\r\n const ordered = orderedWorkspaceIds(manual, key, bucket.map(w => w.workspaceId as string))\r\n const workspaceNodes: WorkspaceGroupNode[] = []\r\n let containsCurrent = false\r\n for (const workspaceId of ordered) {\r\n const workspace = bucket.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) continue\r\n const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)\r\n const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)\r\n const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId\r\n const partitioned = applyFolders(\r\n workspace.workspaceId,\r\n workspace.path,\r\n sessions,\r\n list,\r\n entryFor(folders, workspace.workspaceId as string),\r\n collapsedFolders,\r\n )\r\n if (wsContainsCurrent) containsCurrent = true\r\n workspaceNodes.push({\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: sessions.length,\r\n expanded: wsExpanded,\r\n containsCurrent: wsContainsCurrent,\r\n sessions: wsExpanded ? partitioned.sessions : [],\r\n ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),\r\n })\r\n }\r\n const appearance = categoryAppearance(manual, key)\r\n nodes.push({\r\n key,\r\n label: key,\r\n expanded,\r\n containsCurrent,\r\n workspaces: workspaceNodes,\r\n ...(appearance === undefined ? {} : { appearance }),\r\n })\r\n }\r\n return nodes\r\n}\r\n\r\n/**\r\n * Top-level (ungrouped) workspace rows: workspaces resolving to no category\r\n * (no manual override and no matching rule, or a forced `null` override).\r\n * Rendered after the group folders as plain project rows (not inside any\r\n * folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`),\r\n * falling back to host registration order.\r\n */\r\nexport function deriveTopLevel(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n archivedSessionIds: readonly SessionId[],\r\n config: GroupsConfig,\r\n view: GroupsTreeView,\r\n manual: ManualGroups,\r\n statuses: SessionStatuses = new Map(),\r\n folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,\r\n): WorkspaceGroupNode[] {\r\n const archived = new Set(archivedSessionIds)\r\n const expandedWorkspaces = new Set(view.expandedWorkspaces)\r\n const collapsedFolders = new Set(view.collapsedFolders ?? [])\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n const currentWorkspaceId = current === undefined\r\n ? undefined\r\n : workspaces.find(w => w.sessionIds.includes(current))?.workspaceId\r\n\r\n const topLevelIds = workspaces\r\n .filter(w => resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)\r\n .map(w => w.workspaceId as string)\r\n const ordered = orderedWorkspaceIds(manual, TOP_LEVEL_ORDER_KEY, topLevelIds)\r\n\r\n const nodes: WorkspaceGroupNode[] = []\r\n for (const workspaceId of ordered) {\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) continue\r\n const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)\r\n const wsExpanded = expandedWorkspaces.has(workspaceId)\r\n const partitioned = applyFolders(\r\n workspace.workspaceId,\r\n workspace.path,\r\n sessions,\r\n list,\r\n entryFor(folders, workspaceId),\r\n collapsedFolders,\r\n )\r\n nodes.push({\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: sessions.length,\r\n expanded: wsExpanded,\r\n containsCurrent: workspace.workspaceId === currentWorkspaceId,\r\n sessions: wsExpanded ? partitioned.sessions : [],\r\n ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),\r\n })\r\n }\r\n return nodes\r\n}\r\n\r\n/** Recency comparator: newest first, id as the deterministic tiebreak. */\r\nfunction byRecency(a: SessionSummary, b: SessionSummary): number {\r\n if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt\r\n return a.id < b.id ? -1 : 1\r\n}\r\n\r\n/** Bounded set of matched sessions plus content snippets (feeds the search tree). */\r\nexport interface SearchMatchSet {\r\n /** Session ids that matched (local metadata hits + Host content hits). */\r\n matchedIds: ReadonlySet\r\n /** Content-match snippets keyed by session id (Host search only). */\r\n snippetsBySession: ReadonlyMap\r\n hasMore: boolean\r\n}\r\n\r\n/**\r\n * Compute the matched-session set: immediate title/Workspace substring matches\r\n * from the local list, merged with ranked Host content matches. The consumer\r\n * (SearchBody) derives the pruned three-level tree from these ids.\r\n */\r\nexport function deriveSearchMatches(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n config: GroupsConfig,\r\n query: string,\r\n archivedSessionIds: readonly SessionId[],\r\n content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },\r\n limit: number,\r\n): SearchMatchSet {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }\r\n const archived = new Set(archivedSessionIds)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n const workspaceBySession = new Map()\r\n for (const workspace of workspaces) {\r\n for (const sessionId of workspace.sessionIds) {\r\n if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)\r\n }\r\n }\r\n const labelOf = (summary: SessionSummary): string =>\r\n workspaceBySession.get(summary.id)?.title ?? workspaceLabel(summary.cwd)\r\n\r\n const local: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || summary.blank || !sessionVisible(summary, current, archived)) continue\r\n if (\r\n sessionTitle(summary).toLowerCase().includes(q)\r\n || labelOf(summary).toLowerCase().includes(q)\r\n ) {\r\n local.push(summary)\r\n }\r\n }\r\n local.sort(byRecency)\r\n\r\n const ordered: SessionSummary[] = []\r\n const included = new Set()\r\n const include = (summary: SessionSummary): void => {\r\n if (included.has(summary.id)) return\r\n included.add(summary.id)\r\n ordered.push(summary)\r\n }\r\n for (const summary of local) include(summary)\r\n for (const item of content.items) {\r\n const summary = list.byId[item.sessionId]\r\n if (summary !== undefined && !summary.blank && sessionVisible(summary, current, archived)) include(summary)\r\n }\r\n\r\n const snippets = new Map()\r\n for (const item of content.items) {\r\n if (item.snippet !== undefined) snippets.set(item.sessionId, item.snippet)\r\n }\r\n\r\n return {\r\n matchedIds: ordered.slice(0, limit).reduce((set, summary) => { set.add(summary.id); return set }, new Set()),\r\n snippetsBySession: snippets,\r\n hasMore: content.hasMore || ordered.length > limit,\r\n }\r\n}\r\n\r\n/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */\r\nexport interface SearchTree {\r\n /** Group folders containing matched sessions, in display order. */\r\n categories: CategoryNode[]\r\n /** Top-level (ungrouped) workspaces holding matched sessions. */\r\n topLevel: WorkspaceGroupNode[]\r\n}\r\n\r\n/**\r\n * Build a three-level search tree containing ONLY the branches that hold a\r\n * matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched\r\n * session carries `matched: true` so rows render with the search-hit tint.\r\n * Classification uses the same precedence as the idle tree (manual override →\r\n * rules), so search shows the same grouping the user sees. Matched top-level\r\n * workspaces are returned separately (rendered as plain rows).\r\n *\r\n * @param list - sessions list snapshot.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param config - sidecar grouping config.\r\n * @param matchedIds - set of session ids that matched the query.\r\n * @param archivedSessionIds - registry-global archive set.\r\n * @param manual - runtime overlay (manual groups + overrides).\r\n * @param snippetsBySession - optional content-match snippets keyed by session id.\r\n * @param statuses - unified UI status by Session (drives the running / warning\r\n * / unread-completion row indicators); defaults to none (tests).\r\n * @param folders - per-workspace extra folders + root, so a hit inside an extra\r\n * folder surfaces under that folder instead of flat under the project.\r\n * @returns group folders in render order plus top-level matched workspaces,\r\n * pruned to matched branches only.\r\n */\r\nexport function deriveSearchGroups(\r\n list: SessionListState,\r\n workspaces: readonly WorkspaceView[],\r\n config: GroupsConfig,\r\n matchedIds: ReadonlySet,\r\n archivedSessionIds: readonly SessionId[],\r\n manual: ManualGroups,\r\n snippetsBySession?: ReadonlyMap,\r\n statuses: SessionStatuses = new Map(),\r\n folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,\r\n): SearchTree {\r\n const archived = new Set(archivedSessionIds)\r\n const descendants = indexSubagentDescendants(list.byId)\r\n const current = currentSessionId(list)\r\n\r\n const byCategory = new Map()\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])\r\n\r\n const topLevel: WorkspaceGroupNode[] = []\r\n for (const workspace of workspaces) {\r\n // Only sessions that matched the query and are visible in this folder.\r\n const nodes: SessionNode[] = []\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || !matchedIds.has(id)) continue\r\n if (!sessionVisible(summary, current, archived)) continue\r\n const node = sessionNode(summary, descendants, statuses)\r\n const snippet = snippetsBySession?.get(id)\r\n nodes.push({\r\n ...node,\r\n matched: true,\r\n ...(snippet === undefined ? {} : { snippet }),\r\n })\r\n }\r\n if (nodes.length === 0) continue\r\n\r\n const partitioned = applyFolders(\r\n workspace.workspaceId,\r\n workspace.path,\r\n nodes,\r\n list,\r\n entryFor(folders, workspace.workspaceId as string),\r\n undefined,\r\n )\r\n const node: WorkspaceGroupNode = {\r\n workspaceId: workspace.workspaceId,\r\n path: workspace.path,\r\n label: workspace.title,\r\n createdAt: Date.parse(workspace.createdAt),\r\n sessionCount: nodes.length,\r\n expanded: true,\r\n containsCurrent: false,\r\n sessions: partitioned.sessions,\r\n ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),\r\n }\r\n const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n if (key === undefined) {\r\n topLevel.push(node)\r\n continue\r\n }\r\n if (!byCategory.has(key)) byCategory.set(key, [])\r\n byCategory.get(key)!.push(node)\r\n }\r\n\r\n const categories: CategoryNode[] = []\r\n // Same display order as the idle tree.\r\n for (const key of effectiveCategories(config, manual).map(e => e.key)) {\r\n const workspaceNodes = byCategory.get(key)\r\n if (workspaceNodes === undefined || workspaceNodes.length === 0) continue\r\n const appearance = categoryAppearance(manual, key)\r\n categories.push({\r\n key,\r\n label: key,\r\n expanded: true,\r\n containsCurrent: false,\r\n workspaces: workspaceNodes,\r\n ...(appearance === undefined ? {} : { appearance }),\r\n })\r\n }\r\n return { categories, topLevel }\r\n}\r\n","/**\r\n * Row components for the workspace-groups tree. Kept dependency-light: they\r\n * consume only React, primitives (StateDot/Menu/icons), and the shared CSS\r\n * string. Each row owns its hover actions menu; dialogs live in the browser\r\n * root so they survive row unmounts during collapse.\r\n *\r\n * Drag & drop: workspace rows are draggable sources; category rows (and\r\n * workspace rows, standing for their containing category) are drop targets.\r\n * The payload is a custom dataTransfer type so only in-plugin drags land.\r\n */\r\nimport { useEffect, useRef, useState, type AnimationEvent, type DragEvent, type ReactNode } from 'react'\r\nimport {\r\n IconApiOutlineMedium,\r\n IconArchiveOutlineRegular,\r\n IconArchiveOutlineMedium,\r\n IconBranchOutlineMedium,\r\n IconBranchOutlineRegular,\r\n IconChecklistOutlineMedium,\r\n IconClockOutlineMedium,\r\n IconCodeOutlineMedium,\r\n IconCordisPluginOutlineMedium,\r\n IconDataOutlineMedium,\r\n IconDatabaseOutlineMedium,\r\n IconEditOutlineRegular,\r\n IconEllipsisOutlineRegular,\r\n IconFolderCloseMedium,\r\n IconFolderOpenMedium,\r\n IconFolderOpenOutlineRegular,\r\n IconGlobeOutlineMedium,\r\n IconGoalOutlineMedium,\r\n IconLightOutlineMedium,\r\n IconPinFillMedium,\r\n IconPinOutlineRegular,\r\n IconPlanOutlineMedium,\r\n IconPlusOutlineRegular,\r\n IconProjectAddOutlineRegular,\r\n IconRightUpOutlineRegular,\r\n IconShieldOutlineMedium,\r\n IconSkillOutlineMedium,\r\n IconSlidersTwoOutlineRegular,\r\n IconSparkleMedium,\r\n IconTreeCornerMedium,\r\n IconTriangleRightFillMedium,\r\n IconTrashOutlineRegular,\r\n IconUsersOutlineMedium,\r\n IconWorkspaceTreeOutlineMedium,\r\n Menu,\r\n StateDot,\r\n type MenuEntry,\r\n type StateDotState,\r\n} from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'\r\nimport type { WorkspaceGroupsKey } from './locales.ts'\r\nimport type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts'\r\n\r\ntype T = TranslateNS<'workspaceGroups'>\r\n\r\n/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */\r\nexport const DND_WORKSPACE_TYPE = 'application/x-dsh-workspace-groups'\r\n/** dataTransfer type carrying the dragged category key (group reorder). */\r\nexport const DND_CATEGORY_TYPE = 'application/x-dsh-workspace-groups-category'\r\n\r\n/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */\r\nexport function hasPluginDragType(types: DOMStringList | readonly string[]): boolean {\r\n const list = Array.from(types as Iterable)\r\n return list.includes(DND_WORKSPACE_TYPE) || list.includes(DND_CATEGORY_TYPE)\r\n}\r\n\r\n/** Pending interaction status → primitives StateDot state. */\r\nfunction pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {\r\n switch (status) {\r\n case 'approval':\r\n case 'plan-review':\r\n case 'question':\r\n return 'warning'\r\n default:\r\n return undefined\r\n }\r\n}\r\n\r\n/** Primary status dot state for a session row. */\r\nexport function sessionDotState(node: Pick): StateDotState {\r\n if (pendingState(node.pendingInteraction) !== undefined) return 'warning'\r\n if (node.running || node.runningSubagentCount > 0) return 'ongoing'\r\n return node.completed ? 'done' : 'done'\r\n}\r\n\r\n/** Compact relative time (\"now\"/\"5min\"/\"3h\"/\"2d\"/\"4mo\"/\"1y\"). */\r\nexport function relativeTimeLabel(updatedAt: number, now: number): string {\r\n const diff = Math.max(0, now - updatedAt)\r\n const MIN = 60_000\r\n const HOUR = 3_600_000\r\n const DAY = 86_400_000\r\n if (diff < MIN) return 'now'\r\n if (diff < HOUR) return `${Math.floor(diff / MIN)}min`\r\n if (diff < DAY) return `${Math.floor(diff / HOUR)}h`\r\n if (diff < 30 * DAY) return `${Math.floor(diff / DAY)}d`\r\n if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`\r\n return `${Math.floor(diff / (365 * DAY))}y`\r\n}\r\n\r\n/** Drop-target props shared by category and workspace rows (all optional). */\r\nexport interface RowDropProps {\r\n /** Row is under the dragged workspace — show the drop highlight. */\r\n dropActive?: boolean\r\n /** Insertion indicator: a line above (before) or below (after) this row. */\r\n insertLine?: 'before' | 'after'\r\n /** Accept a drag over this row (must preventDefault to allow the drop). */\r\n onRowDragOver?: (event: DragEvent) => void\r\n /** Clear the highlight when the pointer leaves the row. */\r\n onRowDragLeave?: (event: DragEvent) => void\r\n /** Drop a workspace onto this row. */\r\n onRowDrop?: (event: DragEvent) => void\r\n}\r\n\r\n/**\r\n * Preset group icon ids → primitives artwork. Medium stroke to match the\r\n * folder glyph used by unprefixed groups. Keyed by plain string so an id from\r\n * a newer host (or a hand-edited JSON file) degrades instead of throwing.\r\n */\r\nconst CATEGORY_ICONS: Record = {\r\n folder: ,\r\n workspace: ,\r\n code: ,\r\n plugin: ,\r\n skill: ,\r\n data: ,\r\n database: ,\r\n api: ,\r\n plan: ,\r\n goal: ,\r\n light: ,\r\n globe: ,\r\n archive: ,\r\n branch: ,\r\n users: ,\r\n clock: ,\r\n shield: ,\r\n checklist: ,\r\n sparkle: ,\r\n tree: ,\r\n}\r\n\r\n/**\r\n * Resolve a stored `appearance.icon` value: a preset id renders the artwork,\r\n * a 1–4 character glyph renders as text, and anything else returns null so the\r\n * caller keeps the default folder icon.\r\n */\r\nfunction resolveCategoryIcon(icon: string | undefined): ReactNode | null {\r\n if (icon === undefined || icon === '') return null\r\n const preset = CATEGORY_ICONS[icon]\r\n if (preset !== undefined) return preset\r\n return Array.from(icon).length <= 4 ? {icon} : null\r\n}\r\n\r\n/**\r\n * Render one stored icon value (preset artwork or a short glyph). Shared by the\r\n * category row's icon slot and the appearance picker grid, so both show exactly\r\n * the same artwork. `fallback` renders when the value is empty or unknown.\r\n */\r\nexport function CategoryGlyph({ icon, fallback = null }: { icon: string | undefined; fallback?: ReactNode }): JSX.Element {\r\n return <>{resolveCategoryIcon(icon) ?? fallback}\r\n}\r\n\r\n/**\r\n * One category folder row: toggle, rename/delete menu (every group — rule\r\n * groups via overlay renames/hides), draggable source for group reorder and\r\n * drop target for both workspace moves and group reorders.\r\n */\r\nexport function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {\r\n node: CategoryNode\r\n t: T\r\n onToggle: () => void\r\n /** Rename/delete actions; the hover menu renders only when both provided. */\r\n onRename?: () => void\r\n onDelete?: () => void\r\n /** Pin/unpin this group (menu row). */\r\n onTogglePin?: () => void\r\n /** Open the appearance dialog (menu row). */\r\n onEditAppearance?: () => void\r\n /** Group reorder source; the row becomes draggable only when provided. */\r\n onDragStartCategory?: (event: DragEvent) => void\r\n} & RowDropProps) {\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n const count = node.workspaces.length\r\n const manageable = onRename !== undefined && onDelete !== undefined\r\n const pinned = node.appearance?.pinned === true\r\n const menuItems: MenuEntry[] = [\r\n ...(onTogglePin === undefined\r\n ? []\r\n : [{\r\n id: 'pin',\r\n label: pinned ? t('group.unpin') : t('group.pin'),\r\n icon: pinned ? : ,\r\n }]),\r\n ...(onEditAppearance === undefined\r\n ? []\r\n : [{ id: 'appearance', label: t('group.appearance'), icon: }]),\r\n { type: 'separator', id: 'group-menu-separator' },\r\n { id: 'rename', label: t('group.rename'), icon: },\r\n { id: 'delete', label: t('group.delete'), icon: , danger: true },\r\n ]\r\n return (\r\n \r\n \r\n \r\n \r\n \r\n : }\r\n />\r\n \r\n {node.label}\r\n {count}\r\n {pinned && (\r\n \r\n \r\n \r\n )}\r\n {manageable && (\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'pin') onTogglePin?.()\r\n if (id === 'appearance') onEditAppearance?.()\r\n if (id === 'rename') onRename()\r\n if (id === 'delete') onDelete()\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n \r\n )}\r\n \r\n )\r\n}\r\n\r\n/** One workspace folder row inside a category: draggable source + drop target. */\r\nexport function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onManageFolders, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {\r\n node: WorkspaceGroupNode\r\n t: T\r\n onToggle: () => void\r\n onNewSession: () => void\r\n onRename: () => void\r\n onDelete: () => void\r\n /** Project currently sits inside a group — offer \"move out of group\". */\r\n canMoveOut?: boolean\r\n onMoveOut?: () => void\r\n /** Open the folder-management dialog (extra folders + root). */\r\n onManageFolders?: () => void\r\n /**\r\n * Open the project directory in the host's file manager. Omitted when the\r\n * host resolved no folder application (no capability, or a remote launch),\r\n * which keeps the entry out of the menu entirely.\r\n */\r\n onOpenInFolder?: () => void\r\n /** Render as a top-level row (no folder indentation). */\r\n flat?: boolean\r\n /** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */\r\n onDragStartExtra?: () => void\r\n} & RowDropProps) {\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n const menuItems: MenuEntry[] = [\r\n ...(onOpenInFolder !== undefined\r\n ? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: }]\r\n : []),\r\n ...(canMoveOut && onMoveOut !== undefined\r\n ? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: }]\r\n : []),\r\n ...(onManageFolders !== undefined\r\n ? [{ id: 'folders', label: t('folder.manage'), icon: }]\r\n : []),\r\n { id: 'rename', label: t('workspace.rename'), icon: },\r\n { id: 'delete', label: t('workspace.delete'), icon: , danger: true },\r\n ]\r\n const onDragStart = (event: DragEvent): void => {\r\n event.dataTransfer.setData(DND_WORKSPACE_TYPE, node.workspaceId)\r\n event.dataTransfer.effectAllowed = 'move'\r\n onDragStartExtra?.()\r\n }\r\n return (\r\n \r\n \r\n \r\n \r\n \r\n {/* Project rows use the project glyph (same as the official workspace\r\n browser) so groups (folder glyph) and projects stay distinguishable. */}\r\n \r\n \r\n {node.label}\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'openInFolder') onOpenInFolder?.()\r\n if (id === 'moveOut') onMoveOut?.()\r\n if (id === 'folders') onManageFolders?.()\r\n if (id === 'rename') onRename()\r\n if (id === 'delete') onDelete()\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n { e.stopPropagation(); onNewSession() }}\r\n >\r\n \r\n \r\n \r\n \r\n )\r\n}\r\n\r\n/**\r\n * One folder row under a project: the base directory (folder #0) plus every\r\n * extra folder of that workspace. Sits at the session indent level so the\r\n * 42/58/74 ladder is preserved, and its own session rows indent one step\r\n * deeper (see `.wgSessionNested`).\r\n *\r\n * Deliberately NOT a drag source or drop target: folders are a fixed,\r\n * host-ordered list; reordering them would need a write path this feature does\r\n * not have.\r\n */\r\nexport function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating = false }: {\r\n node: FolderNode\r\n t: T\r\n onToggle: () => void\r\n onNewSession: () => void\r\n onSetRoot: () => void\r\n onRemove: () => void\r\n /** Absent when the host resolved no folder application. */\r\n onOpenInFolder?: () => void\r\n /** A session is being created here: the hover + stays disabled. */\r\n creating?: boolean\r\n}) {\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n const menuItems: MenuEntry[] = [\r\n { id: 'newSession', label: t('session.new'), icon: },\r\n ...(onOpenInFolder !== undefined\r\n ? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: }]\r\n : []),\r\n ...(node.isRoot\r\n ? []\r\n : [{ id: 'setRoot', label: t('folder.setRoot'), icon: }]),\r\n ...(node.isBase\r\n ? []\r\n : [\r\n { type: 'separator' as const, id: 'folder-menu-separator' },\r\n { id: 'remove', label: t('folder.remove'), icon: , danger: true },\r\n ]),\r\n ]\r\n return (\r\n \r\n \r\n \r\n \r\n \r\n {node.expanded ? : }\r\n \r\n {node.label}\r\n {node.isRoot && (\r\n ★\r\n )}\r\n {node.sessions.length}\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'newSession') onNewSession()\r\n if (id === 'openInFolder') onOpenInFolder?.()\r\n if (id === 'setRoot') onSetRoot()\r\n if (id === 'remove') onRemove()\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n { e.stopPropagation(); onNewSession() }}\r\n >\r\n \r\n \r\n \r\n \r\n )\r\n}\r\n\r\n/**\r\n * Children container for one folder's rows.\r\n *\r\n * Keeps the tree's `role=\"group\"` semantics and gives the rows a single\r\n * positioned ancestor. It used to draw a per-folder guide rail; that is now the\r\n * flower branch's job (one continuous stem for the whole tree, see\r\n * `FlowerBranch.tsx`), so this is structure only.\r\n */\r\nexport function TreeChildren({ children }: { children: ReactNode }) {\r\n return (\r\n
\r\n {children}\r\n
\r\n )\r\n}\r\n\r\n/** Keyframe names the disclosure animation relies on (styles.css). */\r\nconst ROW_GROUP_OPEN_ANIMATION = 'wg-rows-in'\r\nconst ROW_GROUP_CLOSE_ANIMATION = 'wg-rows-out'\r\n\r\n/** Upper bound for one disclosure animation (180ms open / 160ms close). */\r\nconst ROW_GROUP_ANIMATION_FALLBACK_MS = 400\r\n\r\n/** Lifecycle of one animated disclosure body. */\r\ntype RowGroupPhase = 'opening' | 'open' | 'closing' | 'closed'\r\n\r\n/** Whether the user asked the OS to reduce motion (no sync unmount without it). */\r\nfunction prefersReducedMotion(): boolean {\r\n return typeof window !== 'undefined'\r\n && typeof window.matchMedia === 'function'\r\n && window.matchMedia('(prefers-reduced-motion: reduce)').matches\r\n}\r\n\r\n/**\r\n * Animated disclosure body shared by the category and project levels.\r\n *\r\n * Collapsed state renders nothing at all (same DOM as the old\r\n * `{expanded && …}`), so hidden subtrees cost no layout. Expanding plays a\r\n * 0fr→1fr grid animation; collapsing keeps the rows mounted for one closing\r\n * animation and unmounts on its `animationend`. `prefers-reduced-motion`\r\n * unmounts synchronously instead — waiting for an `animationend` that CSS\r\n * disabled would leave the group stuck half-closed.\r\n *\r\n * The flower-branch overlay cannot follow a moving row box, so the animation\r\n * phase exposes `data-wg-animating` (styles.css fades the vine while it is\r\n * present).\r\n */\r\nexport function RowGroup({ expanded, className, animate = true, children }: {\r\n expanded: boolean\r\n className?: string\r\n /** Disable the animation for huge subtrees or during drag folding. */\r\n animate?: boolean\r\n children: ReactNode\r\n}): JSX.Element | null {\r\n const [phase, setPhase] = useState(expanded ? 'open' : 'closed')\r\n const previousExpanded = useRef(expanded)\r\n // Adjust state while rendering (React's documented prop-change pattern) so a\r\n // reduced-motion collapse unmounts in the same commit instead of flashing\r\n // the old rows for a frame.\r\n if (previousExpanded.current !== expanded) {\r\n previousExpanded.current = expanded\r\n if (expanded) setPhase(animate && !prefersReducedMotion() ? 'opening' : 'open')\r\n else setPhase(animate && !prefersReducedMotion() ? 'closing' : 'closed')\r\n }\r\n // Insurance against a missing `animationend` (interrupted or skipped\r\n // animation): the animating phase holds `pointer-events:none` and keeps a\r\n // collapsed body mounted, so it must always settle on its own.\r\n useEffect(() => {\r\n if (phase !== 'opening' && phase !== 'closing') return undefined\r\n const timer = window.setTimeout(() => {\r\n setPhase(phase === 'opening' ? 'open' : 'closed')\r\n }, ROW_GROUP_ANIMATION_FALLBACK_MS)\r\n return () => { window.clearTimeout(timer) }\r\n }, [phase])\r\n if (phase === 'closed') return null\r\n const animating = phase === 'opening' || phase === 'closing'\r\n const classes = `wgRows${className === undefined ? '' : ` ${className}`}${phase === 'opening' ? ' wgRowsOpening' : ''}${phase === 'closing' ? ' wgRowsClosing' : ''}`\r\n const onAnimationEnd = (event: AnimationEvent): void => {\r\n if (event.target !== event.currentTarget) return\r\n if (phase === 'opening' && event.animationName === ROW_GROUP_OPEN_ANIMATION) setPhase('open')\r\n if (phase === 'closing' && event.animationName === ROW_GROUP_CLOSE_ANIMATION) setPhase('closed')\r\n }\r\n return (\r\n \r\n
{children}
\r\n \r\n )\r\n}\r\n\r\n/** One session leaf row. */\r\nexport function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested = false }: {\r\n node: SessionNode\r\n currentId: string | undefined\r\n now: number\r\n t: T\r\n onOpen: (id: SessionNode['id']) => void\r\n onRename: (id: SessionNode['id'], currentTitle: string) => void\r\n onFork: (id: SessionNode['id']) => void\r\n onArchive: (id: SessionNode['id']) => void\r\n /** Rendered under a folder row: one indent step deeper than a plain session. */\r\n nested?: boolean\r\n}) {\r\n const selected = node.id === currentId\r\n const [menuOpen, setMenuOpen] = useState(false)\r\n // The ACTIVE session hands its status slot to the flower: the branch anchors\r\n // on this cell (`anchorX` targets `.wgStatusSlot`), so the bloom and the dot\r\n // occupy the same 14px square. Drawing both puts the dot's green \"ongoing\"\r\n // ring (or the loading spinner) on top of the petals, which is what made the\r\n // flower look broken. The flower already carries this row's state — it turns\r\n // exactly while the session runs — so the dot is redundant here anyway.\r\n const showStatus = !selected\r\n const menuItems = [\r\n { id: 'rename', label: t('session.rename'), icon: },\r\n { id: 'fork', label: t('session.fork'), icon: },\r\n { id: 'archive', label: t('session.archive'), icon: },\r\n ]\r\n return (\r\n { onOpen(node.id) }}\r\n >\r\n \r\n {showStatus && }\r\n \r\n {node.title}\r\n {!node.blank && {relativeTimeLabel(node.updatedAt, now)}}\r\n {node.snippet !== undefined && (\r\n {node.snippet}\r\n )}\r\n {!node.blank && (\r\n \r\n { setMenuOpen(false) }}\r\n items={menuItems}\r\n onSelect={(id) => {\r\n setMenuOpen(false)\r\n if (id === 'rename') onRename(node.id, node.title)\r\n if (id === 'fork') onFork(node.id)\r\n if (id === 'archive') onArchive(node.id)\r\n }}\r\n portal\r\n closeOnPointerLeave\r\n anchor={(\r\n { e.stopPropagation(); setMenuOpen(v => !v) }}\r\n >\r\n \r\n \r\n )}\r\n />\r\n \r\n )}\r\n \r\n )\r\n}\r\n\r\nexport type { T }\r\n","/**\n * Client side of the per-workspace folder list, talking to\n * `GET|PUT /workspace-groups/folders` on the host.\n *\n * The document is the host's JSON sidecar verbatim (`version` + `workspaces`),\n * so the client and the host agree on one shape: `folders` holds EXTRA folders\n * only — the workspace's canonical directory is implicit folder #0 — and\n * `root` names one of those extras (absent means \"the workspace itself\").\n *\n * Reads are best-effort, like the manual overlay and the tab strip: a failed\n * read means \"no extra folders\". A failed write, however, rejects so the caller\n * can say so — a folder row that silently forgot its edit would be worse than\n * the toast.\n */\nimport {\n EMPTY_FOLDERS_DOCUMENT,\n type FoldersDocument,\n type WorkspaceFolderEntry,\n} from '../core/folders.ts'\n\n/** Host route holding the folder overlay. */\nexport const FOLDERS_ROUTE = '/workspace-groups/folders'\n\n/**\n * Read one workspace entry off the wire, dropping the entry when it is\n * unusable.\n * @param value - one value of the stored `workspaces` mapping.\n * @returns the entry, or null for a malformed one.\n */\nfunction parseWireEntry(value: unknown): WorkspaceFolderEntry | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const row = value as Record\n if (!Array.isArray(row.folders)) return null\n const folders: string[] = []\n for (const candidate of row.folders) {\n if (typeof candidate !== 'string' || candidate.trim() === '') continue\n folders.push(candidate)\n }\n const root = typeof row.root === 'string' && row.root.trim() !== '' ? row.root : undefined\n return { folders, ...(root === undefined ? {} : { root }) }\n}\n\n/**\n * Fetch the stored folder overlay.\n * @param fetchImpl - fetch implementation (injectable for tests).\n * @returns the document; the empty document on any failure.\n */\nexport async function loadFolders(fetchImpl: typeof fetch = fetch): Promise {\n try {\n const response = await fetchImpl(FOLDERS_ROUTE, {\n method: 'GET',\n // Folders are user state; a cached response would show stale rows.\n cache: 'no-store',\n })\n if (!response.ok) return EMPTY_FOLDERS_DOCUMENT\n const body: unknown = await response.json()\n if (typeof body !== 'object' || body === null) return EMPTY_FOLDERS_DOCUMENT\n const source = body as Record\n if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT\n if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {\n return { version: 1, workspaces: {} }\n }\n const workspaces: Record = {}\n for (const [workspaceId, value] of Object.entries(source.workspaces)) {\n const entry = parseWireEntry(value)\n if (entry !== null) workspaces[workspaceId] = entry\n }\n return { version: 1, workspaces }\n } catch {\n return EMPTY_FOLDERS_DOCUMENT\n }\n}\n\n/**\n * Store the whole folder overlay.\n *\n * Unlike the tab strip this does NOT swallow failures: folder edits are explicit\n * row/dialog actions, so the caller turns a rejection into a toast instead of\n * leaving the user with a row that silently forgot its folder.\n * @param document - the client's current document.\n * @param fetchImpl - fetch implementation (injectable for tests).\n */\nexport async function saveFolders(\n document: FoldersDocument,\n fetchImpl: typeof fetch = fetch,\n): Promise {\n const response = await fetchImpl(FOLDERS_ROUTE, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(document),\n cache: 'no-store',\n // The write is idempotent, so surviving a navigation with keepalive is\n // safe and avoids losing the just-added folder.\n keepalive: true,\n })\n if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)\n}\n","/**\r\n * Transport for the official open-in-app host routes served by\r\n * `@deepseek-ai/dsh-host-open-in-app`. The project row offers \"open this\r\n * project's folder\" by asking that host half for the applications it verified\r\n * as installed, then POSTing the launcher it already resolved — this plugin\r\n * never probes or spawns a launcher itself, and a host without the capability\r\n * (no resolved application, e.g. an SSH launch) simply yields no menu entry.\r\n */\r\n\r\n/** GET route serving the probed application ids (host-owned constant). */\r\nexport const OPEN_IN_APP_APPS_ROUTE = '/open-in-app/apps'\r\n\r\n/** POST route launching one resolved application on one absolute directory. */\r\nexport const OPEN_IN_APP_OPEN_ROUTE = '/open-in-app/open'\r\n\r\n/**\r\n * Catalog ids that open a directory in the platform file manager, most\r\n * specific first (the official catalog names one per platform: `explorer` on\r\n * Windows, `finder` on macOS, `filemanager` on Linux).\r\n */\r\nconst FOLDER_APP_IDS = ['explorer', 'finder', 'filemanager'] as const\r\n\r\n/**\r\n * The installed file-manager id for this host, or undefined when the host\r\n * resolved none (the row then offers no \"open in folder\" entry).\r\n * @param apps - installed catalog ids from the apps route.\r\n * @returns the preferred available id.\r\n */\r\nexport function folderAppId(apps: readonly string[]): string | undefined {\r\n for (const id of FOLDER_APP_IDS) {\r\n if (apps.includes(id)) return id\r\n }\r\n return undefined\r\n}\r\n\r\n/**\r\n * Resolve the browser's Host base with the connection carrier's null-origin\r\n * fallback (same rule the official button uses): a sandboxed document reports\r\n * the literal origin \"null\", which cannot address the host.\r\n * @returns the absolute base URL of the current Host.\r\n */\r\nfunction hostBase(): string {\r\n const origin = globalThis.location?.origin\r\n return origin !== undefined && origin !== 'null' ? origin : 'http://dsh.internal'\r\n}\r\n\r\n/**\r\n * Read the host's installed-application ids. A host without the capability\r\n * (or one that refuses) reads as an empty list rather than an error, so the\r\n * caller can treat \"no apps\" and \"no route\" identically.\r\n * @param signal - aborts the read when the browser half unmounts.\r\n * @returns installed catalog ids, in host menu order.\r\n */\r\nexport async function fetchOpenInApps(signal?: AbortSignal): Promise {\r\n const response = await fetch(new URL(OPEN_IN_APP_APPS_ROUTE, hostBase()), {\r\n headers: { accept: 'application/json' },\r\n cache: 'no-store',\r\n ...(signal === undefined ? {} : { signal }),\r\n })\r\n if (!response.ok) throw new Error(`open-in-app apps request failed: ${response.status}`)\r\n const payload: unknown = await response.json()\r\n const apps = (payload as { apps?: unknown }).apps\r\n return Array.isArray(apps) ? apps.filter((id): id is string => typeof id === 'string') : []\r\n}\r\n\r\n/**\r\n * Launch one installed application on one absolute directory.\r\n * @param appId - catalog id from the apps route.\r\n * @param path - the project's absolute directory.\r\n * @returns after the host acknowledged the launch; rejects on any refusal.\r\n */\r\nexport async function openPathInApp(appId: string, path: string): Promise {\r\n const response = await fetch(new URL(OPEN_IN_APP_OPEN_ROUTE, hostBase()), {\r\n method: 'POST',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify({ app: appId, path }),\r\n })\r\n if (!response.ok) throw new Error(`open-in-app launch failed: ${response.status}`)\r\n}\r\n","/**\r\n * Pure data shaping for the Ctrl+R quick switch panel. Runtime-free (same\r\n * discipline as store-core.ts): unit tests exercise the real semantics\r\n * without a browser module loader; the panel only binds them to the\r\n * framework's global hooks.\r\n */\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\n\r\n/** A session row eligible for quick switching: running, top-level, real. */\r\nfunction quickEligible(summary: SessionSummary): boolean {\r\n return summary.running === true && summary.origin !== 'subagent' && !summary.blank\r\n}\r\n\r\n/**\r\n * Running quick-switchable sessions across the whole list, newest first.\r\n * @param list - sessions list snapshot.\r\n * @param archived - registry-global archive set (archived rows never surface).\r\n * @returns running summaries in recency order (id as deterministic tiebreak).\r\n */\r\nexport function runningSessions(list: SessionListState, archived: ReadonlySet): SessionSummary[] {\r\n const out: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n if (archived.has(id)) continue\r\n const summary = list.byId[id]\r\n if (summary !== undefined && quickEligible(summary)) out.push(summary)\r\n }\r\n out.sort((a, b) => (b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)))\r\n return out\r\n}\r\n\r\n/**\r\n * Every quick-switchable session across the whole list — the sessions tab's\r\n * data: running rows pinned on top, everything else under them, both groups\r\n * newest first. Visibility mirrors the tree (subagent rows never; archived\r\n * never; a blank row only while it is the open session).\r\n * @param list - sessions list snapshot.\r\n * @param archived - registry-global archive set (archived rows never surface).\r\n * @param current - the selected session (`mainView` retention; keeps its blank row visible).\r\n * @returns summaries with running first, then recency (id as deterministic tiebreak).\r\n */\r\nexport function allSessions(\r\n list: SessionListState,\r\n archived: ReadonlySet,\r\n current: SessionId | undefined,\r\n): SessionSummary[] {\r\n const out: SessionSummary[] = []\r\n for (const id of list.ids) {\r\n if (archived.has(id)) continue\r\n const summary = list.byId[id]\r\n if (summary === undefined) continue\r\n if (summary.origin === 'subagent') continue\r\n if (summary.blank && summary.id !== current) continue\r\n out.push(summary)\r\n }\r\n out.sort((a, b) => {\r\n if (a.running !== b.running) return a.running ? -1 : 1\r\n return b.updatedAt !== a.updatedAt ? b.updatedAt - a.updatedAt : (a.id < b.id ? -1 : 1)\r\n })\r\n return out\r\n}\r\n\r\n/**\r\n * Session search for the quick panel: display-title or owning-workspace-title\r\n * substring match (trimmed, case-insensitive). Filters only — the incoming\r\n * running-first/recency order is preserved verbatim, so \"running on top\"\r\n * survives any query.\r\n * @param sessions - allSessions() output (running pinned on top, then recency).\r\n * @param query - raw query.\r\n * @param workspaceTitleOf - owning workspace title resolver (sub-line source).\r\n * @param limit - hard render cap.\r\n * @returns matching sessions in the given order.\r\n */\r\nexport function filterSessions(\r\n sessions: readonly SessionSummary[],\r\n query: string,\r\n workspaceTitleOf: (session: SessionSummary) => string | undefined,\r\n limit = 200,\r\n): SessionSummary[] {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return sessions.slice(0, limit)\r\n const out: SessionSummary[] = []\r\n for (const session of sessions) {\r\n const workspace = workspaceTitleOf(session)?.toLowerCase() ?? ''\r\n if (session.displayTitle.toLowerCase().includes(q) || workspace.includes(q)) out.push(session)\r\n }\r\n return out.slice(0, limit)\r\n}\r\n\r\n/**\r\n * Most recently updated running session inside one workspace.\r\n * @param list - sessions list snapshot.\r\n * @param workspace - target workspace (its session account order is irrelevant;\r\n * recency picks the row).\r\n * @returns the session id, or undefined when nothing in the workspace runs.\r\n */\r\nexport function latestRunningInWorkspace(list: SessionListState, workspace: WorkspaceView): SessionId | undefined {\r\n let best: SessionId | undefined\r\n let bestTime = Number.NEGATIVE_INFINITY\r\n for (const id of workspace.sessionIds) {\r\n const summary = list.byId[id]\r\n if (summary === undefined || !quickEligible(summary)) continue\r\n if (summary.updatedAt > bestTime) {\r\n best = summary.id\r\n bestTime = summary.updatedAt\r\n }\r\n }\r\n return best\r\n}\r\n\r\n/**\r\n * Running-session count per workspace id (badge on the workspace tab rows).\r\n * @param running - runningSessions() output.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @returns counts keyed by workspace id; absent key = none running.\r\n */\r\nexport function runningCountByWorkspace(\r\n running: readonly SessionSummary[],\r\n workspaces: readonly WorkspaceView[],\r\n): Map {\r\n const counts = new Map()\r\n if (running.length === 0) return counts\r\n const runningIds = new Set(running.map(s => s.id))\r\n for (const workspace of workspaces) {\r\n let count = 0\r\n for (const sessionId of workspace.sessionIds) {\r\n if (runningIds.has(sessionId)) count += 1\r\n }\r\n if (count > 0) counts.set(workspace.workspaceId as string, count)\r\n }\r\n return counts\r\n}\r\n\r\n/**\r\n * The workspace that owns the currently open session.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param currentSessionId - the selected session (`mainView` retention); may be undefined\r\n * (no session open, cleared selection) or an id no listed workspace holds\r\n * (e.g. an addressed subagent session).\r\n * @returns the workspace id, or undefined when there is no active workspace.\r\n */\r\nexport function activeWorkspaceId(\r\n workspaces: readonly WorkspaceView[],\r\n currentSessionId: SessionId | undefined,\r\n): string | undefined {\r\n if (currentSessionId === undefined) return undefined\r\n const workspace = workspaces.find(w => w.sessionIds.includes(currentSessionId))\r\n return workspace?.workspaceId as string | undefined\r\n}\r\n\r\n/**\r\n * Workspace search for the quick panel: title prefix → title substring →\r\n * category label substring → path substring; ties keep host order via a\r\n * stable title compare inside one rank.\r\n * @param workspaces - real workspaces in stable Host order.\r\n * @param query - raw query (trimmed, case-insensitive).\r\n * @param categoryLabelOf - category label resolver (grouped workspaces only).\r\n * @param limit - hard render cap.\r\n * @returns ranked matches; an empty query returns host order.\r\n */\r\nexport function filterWorkspaces(\r\n workspaces: readonly WorkspaceView[],\r\n query: string,\r\n categoryLabelOf?: (workspace: WorkspaceView) => string | undefined,\r\n limit = 50,\r\n): WorkspaceView[] {\r\n const q = query.trim().toLowerCase()\r\n if (q === '') return workspaces.slice(0, limit)\r\n const scored: { workspace: WorkspaceView; score: number }[] = []\r\n for (const workspace of workspaces) {\r\n const title = workspace.title.toLowerCase()\r\n const path = workspace.path.toLowerCase()\r\n const category = (categoryLabelOf?.(workspace) ?? '').toLowerCase()\r\n let score: number | undefined\r\n if (title.startsWith(q)) score = 0\r\n else if (title.includes(q)) score = 1\r\n else if (category !== '' && category.includes(q)) score = 2\r\n else if (path.includes(q)) score = 3\r\n if (score !== undefined) scored.push({ workspace, score })\r\n }\r\n scored.sort((a, b) => (a.score !== b.score\r\n ? a.score - b.score\r\n : a.workspace.title.localeCompare(b.workspace.title)))\r\n return scored.slice(0, limit).map(entry => entry.workspace)\r\n}\r\n","/**\r\n * Ctrl+R quick switch panel: two tabs over the framework's global hooks.\r\n *\r\n * - Workspaces tab: search real Workspaces, select one, then either start a\r\n * New Session in it or jump straight to its most recently updated running\r\n * session (the button reads the none-running state and disables).\r\n * - Sessions tab: every top-level session across workspaces — running ones\r\n * pinned on top, everything else under them, both groups newest first; one\r\n * click (or Enter) opens it. The shared search input filters by session or\r\n * workspace title and never re-sorts, so the running-first order survives.\r\n *\r\n * Current-row marker: the open workspace (workspaces tab) and the open\r\n * session (sessions tab) render `.wgQuickRowCurrent`; with no current\r\n * session — or one no listed workspace holds — nothing is marked.\r\n *\r\n * Mount discipline: the parent conditionally mounts this component, so every\r\n * open starts from a fresh query/selection (quick-switcher semantics). The\r\n * overlay portals to document.body (sidebar ancestors clip `fixed`), sizes\r\n * itself like a launcher (top-anchored, 640px) instead of the host Modal's\r\n * 380px dialog, and handles Escape / mask click by itself. Pure data shaping\r\n * lives in quick.ts; this file only binds hooks + actions.\r\n */\r\nimport { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react'\r\nimport { createPortal } from 'react-dom'\r\nimport { Button, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\r\nimport type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport { activeWorkspaceId, allSessions, filterSessions, filterWorkspaces, latestRunningInWorkspace, runningCountByWorkspace, runningSessions } from './quick.ts'\r\nimport { relativeTimeLabel } from './rows.tsx'\r\n\r\n/** Which surface of the quick panel is active. */\r\nexport type QuickTab = 'workspaces' | 'sessions'\r\n\r\n/** The locale seat's translate function (same shape GroupsBrowser receives). */\r\ntype Translate = PropsLocale<'workspaceGroups'>['t']\r\n\r\n/** Quick panel props: hooks snapshots + the two injected verbs + shared CSS context. */\r\nexport type QuickPanelProps = {\r\n /** Close request (Escape, mask click, action completed, or parent Ctrl+R toggle). */\r\n onClose: () => void\r\n /** Sessions list snapshot (drives running detection). */\r\n list: SessionListState\r\n /** Real workspaces in stable Host order. */\r\n workspaces: readonly WorkspaceView[]\r\n /** Registry-global archive set. */\r\n archivedSessionIds: readonly SessionId[]\r\n /** Category label per grouped workspace id (badge column; top-level absent). */\r\n categoryByWorkspace: ReadonlyMap\r\n /** The Session the Conversation currently shows (mainView retention), if any. */\r\n current: SessionId | undefined\r\n /** Start a New Session in a workspace (injected share verb). */\r\n startSession: (workspaceId?: WorkspaceId) => void\r\n /** Open a real Session (injected share verb). */\r\n openSession: (sessionId: SessionId) => void\r\n /** Render clock for relative times (parent refreshes per render). */\r\n now: number\r\n /** Dictionary accessor (workspaceGroups namespace). */\r\n t: Translate\r\n}\r\n\r\n/** Basename of a host path (both separators; shortens the workspace row sub-line). */\r\nfunction pathBasename(path: string): string {\r\n const trimmed = path.replace(/[/\\\\]+$/, '')\r\n const base = trimmed.split(/[/\\\\]/).pop()\r\n return base !== undefined && base !== '' ? base : trimmed\r\n}\r\n\r\n/**\r\n * Render the quick switch panel (portaled overlay).\r\n * @param props - hooks snapshots + injected verbs.\r\n * @returns the panel element tree.\r\n */\r\nexport function QuickPanel({\r\n onClose,\r\n list,\r\n workspaces,\r\n archivedSessionIds,\r\n categoryByWorkspace,\r\n current: currentSessionId,\r\n startSession,\r\n openSession,\r\n now,\r\n t,\r\n}: QuickPanelProps) {\r\n const [tab, setTab] = useState('workspaces')\r\n const [query, setQuery] = useState('')\r\n const [selectedId, setSelectedId] = useState(null)\r\n const [activeIndex, setActiveIndex] = useState(0)\r\n const inputRef = useRef(null)\r\n const activeRowRef = useRef(null)\r\n\r\n const archived = useMemo(() => new Set(archivedSessionIds), [archivedSessionIds])\r\n const running = useMemo(() => runningSessions(list, archived), [list, archived])\r\n const runCounts = useMemo(() => runningCountByWorkspace(running, workspaces), [running, workspaces])\r\n const filtered = useMemo(\r\n () => filterWorkspaces(workspaces, query, ws => categoryByWorkspace.get(ws.workspaceId as string)),\r\n [workspaces, query, categoryByWorkspace],\r\n )\r\n\r\n // Where the user is right now: the open session and its owning workspace.\r\n // Both may be absent (no mainView retention, or a session no listed\r\n // workspace holds) — the current-row marker simply never renders then.\r\n const currentWorkspaceId = useMemo(\r\n () => activeWorkspaceId(workspaces, currentSessionId),\r\n [workspaces, currentSessionId],\r\n )\r\n\r\n // Sessions tab data: every top-level session, running pinned on top then\r\n // recency, filtered by the shared search query (filter never re-sorts).\r\n const sessions = useMemo(\r\n () => allSessions(list, archived, currentSessionId),\r\n [list, archived, currentSessionId],\r\n )\r\n // Owning workspace title per session id (row sub-line + search field);\r\n // first workspace wins — a session lives in exactly one.\r\n const workspaceTitleBySession = useMemo(() => {\r\n const map = new Map()\r\n for (const workspace of workspaces) {\r\n for (const sessionId of workspace.sessionIds) {\r\n if (!map.has(sessionId)) map.set(sessionId, workspace.title)\r\n }\r\n }\r\n return map\r\n }, [workspaces])\r\n const filteredSessions = useMemo(\r\n () => filterSessions(sessions, query, s => workspaceTitleBySession.get(s.id)),\r\n [sessions, query, workspaceTitleBySession],\r\n )\r\n\r\n const selected = selectedId === null\r\n ? undefined\r\n : workspaces.find(w => (w.workspaceId as string) === selectedId)\r\n const selectedRunningId = selected === undefined ? undefined : latestRunningInWorkspace(list, selected)\r\n\r\n // Focus the search input whenever a tab becomes reachable (both tabs own it).\r\n useEffect(() => {\r\n inputRef.current?.focus()\r\n }, [tab])\r\n\r\n // Keep the keyboard-active row visible while arrowing through the list.\r\n useEffect(() => {\r\n activeRowRef.current?.scrollIntoView({ block: 'nearest' })\r\n }, [activeIndex])\r\n\r\n /** Select the workspace and close (New Session verb). */\r\n const launchNewSession = (workspace: WorkspaceView): void => {\r\n startSession(workspace.workspaceId)\r\n onClose()\r\n }\r\n\r\n /** Open a session row and close (sessions tab click or Enter). */\r\n const launchSession = (sessionId: SessionId): void => {\r\n openSession(sessionId)\r\n onClose()\r\n }\r\n\r\n /** Switch tabs; the query carries over, the per-tab selection resets. */\r\n const switchTab = (next: QuickTab): void => {\r\n setTab(next)\r\n setSelectedId(null)\r\n setActiveIndex(0)\r\n }\r\n\r\n /** Search-input keyboard: arrows move the active row; Enter confirms it. */\r\n const onSearchKeyDown = (e: KeyboardEvent): void => {\r\n if (e.key === 'ArrowDown') {\r\n e.preventDefault()\r\n const max = (tab === 'workspaces' ? filtered.length : filteredSessions.length) - 1\r\n setActiveIndex(i => Math.min(i + 1, Math.max(max, 0)))\r\n } else if (e.key === 'ArrowUp') {\r\n e.preventDefault()\r\n setActiveIndex(i => Math.max(i - 1, 0))\r\n } else if (e.key === 'Enter') {\r\n e.preventDefault()\r\n if (tab === 'workspaces') {\r\n if (selected === undefined) {\r\n const target = filtered[activeIndex]\r\n if (target !== undefined) setSelectedId(target.workspaceId as string)\r\n } else {\r\n launchNewSession(selected)\r\n }\r\n } else {\r\n const target = filteredSessions[activeIndex]\r\n if (target !== undefined) launchSession(target.id)\r\n }\r\n }\r\n }\r\n\r\n /** Escape closes (capture so row buttons and the input can't swallow it). */\r\n const onCardKeyDown = (e: KeyboardEvent): void => {\r\n if (e.key === 'Escape') {\r\n e.preventDefault()\r\n e.stopPropagation()\r\n onClose()\r\n }\r\n }\r\n\r\n /** Mask click closes; clicks inside the card never reach the mask. */\r\n const onOverlayMouseDown = (e: MouseEvent): void => {\r\n if (e.target === e.currentTarget) onClose()\r\n }\r\n\r\n const selectWorkspace = (id: string): void => {\r\n setSelectedId(id)\r\n inputRef.current?.focus()\r\n }\r\n\r\n return createPortal(\r\n
\r\n \r\n
\r\n {t('quick.title')}\r\n
\r\n { switchTab('workspaces') }}\r\n >\r\n {t('quick.tab.workspaces')}\r\n \r\n { switchTab('sessions') }}\r\n >\r\n {t('quick.tab.sessions')}\r\n {running.length > 0 && {running.length}}\r\n \r\n
\r\n
\r\n\r\n {/* Shared search: workspaces on one tab, sessions on the other. */}\r\n
\r\n {\r\n setQuery(e.target.value)\r\n setSelectedId(null)\r\n setActiveIndex(0)\r\n }}\r\n onKeyDown={onSearchKeyDown}\r\n />\r\n
\r\n {tab === 'workspaces' ? (\r\n <>\r\n
\r\n {filtered.map((workspace, i) => {\r\n const id = workspace.workspaceId as string\r\n const count = runCounts.get(id) ?? 0\r\n const category = categoryByWorkspace.get(id)\r\n const isCurrent = id === currentWorkspaceId\r\n return (\r\n { setActiveIndex(i) }}\r\n onClick={() => { selectWorkspace(id) }}\r\n >\r\n \r\n {workspace.title}\r\n {count > 0 && ● {count}}\r\n \r\n \r\n \r\n {category !== undefined ? `${category} · ${pathBasename(workspace.path)}` : pathBasename(workspace.path)}\r\n \r\n \r\n \r\n )\r\n })}\r\n {filtered.length === 0 &&
{t('quick.empty.workspaces')}
}\r\n
\r\n
\r\n \r\n {selected === undefined ? t('quick.select.hint') : selected.title}\r\n \r\n { if (selectedRunningId !== undefined) launchSession(selectedRunningId) }}\r\n >\r\n {selectedRunningId !== undefined ? t('quick.action.running') : t('quick.action.noneRunning')}\r\n \r\n { if (selected !== undefined) launchNewSession(selected) }}\r\n >\r\n {t('quick.action.newSession')}\r\n \r\n
\r\n \r\n ) : (\r\n
\r\n {filteredSessions.map((session, i) => {\r\n const workspaceTitle = workspaceTitleBySession.get(session.id) ?? ''\r\n const isCurrent = session.id === currentSessionId\r\n return (\r\n { setActiveIndex(i) }}\r\n onClick={() => { launchSession(session.id) }}\r\n >\r\n \r\n \r\n {session.blank ? t('newSession') : session.displayTitle}\r\n {relativeTimeLabel(session.updatedAt, now)}\r\n \r\n \r\n {workspaceTitle}\r\n \r\n \r\n )\r\n })}\r\n {filteredSessions.length === 0 &&
{t('quick.empty.sessions')}
}\r\n
\r\n )}\r\n\r\n
{t('quick.hint')}
\r\n
\r\n ,\r\n document.body,\r\n )\r\n}\r\n","/**\r\n * DOM seat for the session tab strip.\r\n *\r\n * Why this exists instead of a slot: the strip belongs at the very top of the\r\n * conversation column — `pI_x6G_centerCol` (ui-layout's AppFrame `.centerCol`,\r\n * a hashed CSS-Modules class). That column declares NO child slots: its only\r\n * child is the `main` slot's occupant (`renderSlot('main', …)`, the\r\n * Conversation or a global panel), so there is nowhere to register. The\r\n * shipped slot in that neighbourhood — `conversation.composer.dock` — is the\r\n * band UNDER the composer card, a different place entirely.\r\n *\r\n * So the strip gets a real DOM seat: this module finds the column, prepends a\r\n * `
` to it, and hands that element to a React portal. The element is\r\n * OURS, never React's: it is inserted outside the column's child list that\r\n * React reconciles, and it is re-inserted if React (or a theme/titlebar\r\n * re-render) ever drops it.\r\n *\r\n * Two hazards this module is built around:\r\n *\r\n * 1. `centerCol` is a hashed class name (`pI_x6G_centerCol`) that changes when\r\n * the package is rebuilt. Matching is therefore done on the *structural*\r\n * contract — a grid-item column that holds the `main` panel — plus a\r\n * `[class*=\"_centerCol\"]` probe, never on the exact hash.\r\n * 2. The column mounts after the client plugin's `apply()` runs. Discovery is\r\n * therefore a MutationObserver on `document.body` plus a `requestAnimationFrame`\r\n * retry, and both are torn down when the owning effect disposes.\r\n */\r\n\r\n/** Persistent marker for the injected container (survives React re-renders). */\r\nconst SEAT_ATTRIBUTE = 'data-wg-tab-seat'\r\n\r\n/** Sentinel attribute on the container so discovery can skip our own node. */\r\nconst SEAT_SELECTOR = `[${SEAT_ATTRIBUTE}]`\r\n\r\n/**\r\n * Match the conversation column by its hashed CSS-Modules class.\r\n *\r\n * The hash prefix (`pI_x6G_`) is build-dependent, so the probe matches the\r\n * `_centerCol` suffix that the Modules transform always preserves. A plain\r\n * `class*=\"centerCol\"` scan would risk matching unrelated utility classes, so\r\n * the leading underscore is required.\r\n * @param root - subtree to scan (normally `document`).\r\n * @returns the column element, or null while it has not mounted.\r\n */\r\nfunction findCenterColumn(root: ParentNode): HTMLElement | null {\r\n // Fast path: the seat is already in place and still attached, which is the\r\n // steady state on every re-render (portal into an existing element).\r\n const existing = root.querySelector(SEAT_SELECTOR)\r\n if (existing?.isConnected === true) return existing.parentElement\r\n\r\n // Structural probe: the column is the direct child of the app frame grid\r\n // that contains the `main` panel. Querying the class suffix first keeps this\r\n // to one selector evaluation in the common case.\r\n const column = root.querySelector('[class*=\"_centerCol\"]')\r\n if (column !== null) return column\r\n\r\n // Nothing matched: either the shell has not mounted yet, or the Modules hash\r\n // convention changed. Returning null keeps the caller in its wait loop\r\n // instead of guessing at a wrong node (which would visually corrupt the\r\n // shell). The strip simply appears once the frame is up.\r\n return null\r\n}\r\n\r\n/** A mounted seat: the host element plus the disposer that removes it. */\r\nexport interface TabSeat {\r\n /**\r\n * The element the React portal renders into — null until the conversation\r\n * column mounts. The portal is simply not rendered while this is null.\r\n */\r\n readonly host: HTMLElement | null\r\n /** Remove the seat and stop watching for the column. */\r\n dispose: () => void\r\n}\r\n\r\n/**\r\n * Ensure a seat exists as the FIRST child of the conversation column, creating\r\n * it if needed, and keep it there for as long as the returned handle is live.\r\n *\r\n * The seat element is created once and reused: a portal that re-mounts into a\r\n * fresh node on every shell re-render would drop the tab strip's React state\r\n * and visible focus. If React removes the node (it owns the column's child\r\n * list, and our node is not part of it), the observer re-inserts the SAME\r\n * element, so the portal's subtree moves with it.\r\n *\r\n * @param onReady - called with the host element each time it becomes attached\r\n * (once immediately when the column already exists). Used to seed React\r\n * state; may fire more than once if the column is remounted.\r\n * @returns the seat handle. `host` is null until the column appears, so the\r\n * caller renders nothing meanwhile and starts rendering when `onReady`\r\n * fires. Never null: a missing column must degrade to \"no strip\", not to a\r\n * thrown error that would take the whole client plugin down.\r\n */\r\nexport function mountTabSeat(onReady: (host: HTMLElement) => void): TabSeat {\r\n let host: HTMLElement | null = null\r\n let column: HTMLElement | null = null\r\n let observer: MutationObserver | null = null\r\n let raf = 0\r\n let attempts = 0\r\n let disposed = false\r\n\r\n // Bounded retry: ~5s at 60fps. The shell mounts well inside this; the bound\r\n // exists so a missing column degrades to \"no strip\" instead of a permanent\r\n // frame loop.\r\n const MAX_ATTEMPTS = 300\r\n\r\n /**\r\n * Put the seat at the head of the column, creating it on first success.\r\n * Idempotent: a seat already first is left untouched, so repeated calls from\r\n * the observer cause no DOM churn (and therefore no observer feedback loop —\r\n * our insertion schedules one more callback, which then takes this early\r\n * return instead of re-inserting).\r\n */\r\n const place = (target: HTMLElement): void => {\r\n if (disposed) return\r\n if (host === null) {\r\n host = document.createElement('div')\r\n host.setAttribute(SEAT_ATTRIBUTE, '')\r\n }\r\n if (target.firstChild === host) return\r\n target.insertBefore(host, target.firstChild)\r\n }\r\n\r\n /** Locate the column and, on success, seat the host and notify the caller. */\r\n const tryMount = (): boolean => {\r\n if (disposed) return true\r\n // Steady state: the column we already found is still attached.\r\n if (column !== null && column.isConnected) {\r\n place(column)\r\n return true\r\n }\r\n const found = findCenterColumn(document)\r\n if (found === null) return false\r\n // A different column than last time (shell remount): re-seat AND re-notify,\r\n // because the caller may hold a stale host element from the old tree.\r\n const changed = found !== column\r\n column = found\r\n place(found)\r\n if (changed) onReady(host as HTMLElement)\r\n return true\r\n }\r\n\r\n const tick = (): void => {\r\n if (disposed) return\r\n raf = 0\r\n if (tryMount()) return\r\n attempts += 1\r\n if (attempts >= MAX_ATTEMPTS) return\r\n raf = requestAnimationFrame(tick)\r\n }\r\n\r\n // The observer covers both \"column mounts later\" and \"React dropped our\r\n // node\": either way the child list changes and we re-seat. `requestAnimationFrame`\r\n // alone would miss a removal that happens after the retry budget is spent.\r\n observer = new MutationObserver(() => {\r\n if (disposed) return\r\n if (tryMount()) return\r\n if (raf === 0 && attempts < MAX_ATTEMPTS) raf = requestAnimationFrame(tick)\r\n })\r\n observer.observe(document.body, { childList: true, subtree: true })\r\n\r\n if (!tryMount() && raf === 0) raf = requestAnimationFrame(tick)\r\n\r\n return {\r\n get host(): HTMLElement | null {\r\n // Null until the column mounts; the caller's `onReady` fires at the same\r\n // moment this becomes non-null, so the two never disagree.\r\n return host\r\n },\r\n dispose: () => {\r\n disposed = true\r\n if (raf !== 0) cancelAnimationFrame(raf)\r\n raf = 0\r\n observer?.disconnect()\r\n observer = null\r\n host?.remove()\r\n host = null\r\n column = null\r\n },\r\n } as TabSeat\r\n}\r\n","/**\n * The session tab strip: one chip per opened conversation, rendered into the\n * DOM seat at the head of the conversation column (see `tab-seat.ts` for why\n * this is a DOM injection rather than a slot).\n *\n * A tab is a *view* of the open session, not a second navigation model:\n * clicking a chip navigates through `ctx.uiWorkspace.openSession`, which is the\n * one path that retains a target session; the owning component derives the\n * strip from the open session plus the tab store.\n *\n * The active chip is derived, never stored: it is the chip whose session is the\n * open one, so clicking a background chip immediately shows that chip active.\n *\n * Every affordance beyond \"click to switch\" is an explicit USER gesture, and\n * each one maps to exactly one store action: middle-click closes, the context\n * menu pins / renames / closes a range, a drag reorders, and a double-click\n * edits the tab's own label. None of them can run on their own — the strip stays\n * a record of what the user opened.\n */\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n IconCloseFillMedium,\n IconPinFillMedium,\n StateDot,\n Tooltip,\n type StateDotState,\n} from '@deepseek-ai/dsh-client-ui-primitives'\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\nimport type { SessionsTabsProps } from './contract.ts'\nimport { mountTabSeat } from './tab-seat.ts'\nimport {\n orderedTabs,\n projectIndex,\n tabIndicator,\n type SessionTab,\n type SessionTabIndicator,\n} from './tabs.ts'\nimport { currentSessionId } from './tree.ts'\n\n/** Dot state for one tab (the sidebar's session rows share this vocabulary). */\nfunction dotState(indicator: SessionTabIndicator): StateDotState {\n if (indicator.attention) return 'warning'\n if (indicator.running) return 'ongoing'\n return 'done'\n}\n\n/** Where the context menu is pinned, and which chip it belongs to. */\ninterface MenuAnchor {\n readonly sessionId: SessionId\n readonly x: number\n readonly y: number\n}\n\n/** Which chip a drag is hovering, and which half of it. */\ninterface DropTarget {\n readonly sessionId: SessionId\n readonly side: 'before' | 'after'\n}\n\n/** In-flight inline label edit. */\ninterface LabelEdit {\n readonly sessionId: SessionId\n readonly draft: string\n}\n\n/** One row of the tab context menu. */\nfunction MenuRow({\n label,\n onSelect,\n disabled = false,\n danger = false,\n}: {\n readonly label: string\n readonly onSelect: () => void\n readonly disabled?: boolean\n readonly danger?: boolean\n}) {\n return (\n \n {label}\n \n )\n}\n\n/**\n * Render the session tab strip into the conversation column's head seat.\n * @param props - tab store, catalog/status hooks, navigation, locale.\n * @returns the portal (or null until the column has mounted).\n */\nexport function SessionTabs({\n useTabs,\n actions,\n useSessions,\n useSessionStatus,\n useWorkspaces,\n activate,\n rename,\n t,\n}: SessionsTabsProps) {\n const tabs = useTabs(s => s.tabs)\n const list = useSessions(s => s)\n const statuses = useSessionStatus(s => s)\n const currentId = useSessions(s => currentSessionId(s))\n const workspaces = useWorkspaces(s => s.items)\n\n // Session → owning project, in one pass over the workspace registry. This is\n // what lets each chip name its project; without it a strip of session titles\n // is ambiguous as soon as two projects are open.\n const projects = useMemo(() => projectIndex(workspaces), [workspaces])\n\n // The seat is a DOM node outside React's tree, so it cannot arrive through\n // props; it is discovered once per mount and held in state to trigger the\n // portal's first render when the column appears.\n const [seat, setSeat] = useState(null)\n // The scrolling row, for wheel redirection and keep-active-in-view.\n const scrollRef = useRef(null)\n // The open context menu, its chip, and its viewport position.\n const [menu, setMenu] = useState(null)\n // The chip whose label is being typed into, plus the in-progress text.\n const [editing, setEditing] = useState(null)\n // The chip being dragged and the chip/half it would land on.\n const [dragging, setDragging] = useState(null)\n const [dropTarget, setDropTarget] = useState(null)\n // Timestamp of the last drag end: a drop must not also count as a click on\n // the chip it landed on (which would navigate away from what was just moved).\n const dragEndedAt = useRef(0)\n\n useEffect(() => {\n const mounted = mountTabSeat(setSeat)\n // The column may already exist, in which case onReady fired synchronously\n // during mountTabSeat and setSeat is already queued; adopt it here too so\n // the very first paint has a host instead of waiting a frame.\n if (mounted.host !== null) setSeat(mounted.host)\n return () => {\n mounted.dispose()\n // The portal must stop targeting a removed node before the next mount.\n setSeat(null)\n }\n }, [])\n\n // The strip renders exactly the tabs the store holds. There is deliberately NO\n // filtering against the session catalog and no \"close tabs whose session\n // vanished\" sweep: a tab is removed when the USER closes it, and by nothing\n // else. Trimming automatically also misfires — the catalog is briefly empty on\n // every load, which deleted restored tabs before the sessions arrived.\n const display = useMemo(() => orderedTabs(tabs, currentId), [tabs, currentId])\n const index = useMemo(() => new Map(display.map((tab, at) => [tab.sessionId, at])), [display])\n\n // With the row scrollable, the active chip can sit outside the viewport —\n // e.g. after clicking a session in the sidebar that has a tab far to the\n // right. Bring it into view on selection change. `block: 'nearest'` keeps\n // this a horizontal-only scroll, and `inline: 'nearest'` avoids nudging the\n // row when the chip is already fully visible.\n useEffect(() => {\n const el = scrollRef.current\n if (el === null || currentId === undefined) return\n const chip = el.querySelector(`[data-tab-session=\"${CSS.escape(currentId)}\"]`)\n chip?.scrollIntoView({ block: 'nearest', inline: 'nearest' })\n }, [currentId, display.length])\n\n // Dismiss the context menu on any interaction outside it. Pointerdown covers\n // both buttons; Escape and a viewport change (which would leave a fixed menu\n // pointing at the wrong chip) close it too. `capture` matters for the scroll\n // case: the strip's own row scrolls without bubbling a scroll event up.\n useEffect(() => {\n if (menu === null) return\n const dismiss = (): void => { setMenu(null) }\n const onPointerDown = (event: PointerEvent): void => {\n const target = event.target\n if (target instanceof Element && target.closest('.wgTabMenu') !== null) return\n dismiss()\n }\n const onKeyDown = (event: KeyboardEvent): void => {\n if (event.key === 'Escape') dismiss()\n }\n document.addEventListener('pointerdown', onPointerDown, true)\n document.addEventListener('keydown', onKeyDown)\n window.addEventListener('resize', dismiss)\n window.addEventListener('scroll', dismiss, true)\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true)\n document.removeEventListener('keydown', onKeyDown)\n window.removeEventListener('resize', dismiss)\n window.removeEventListener('scroll', dismiss, true)\n }\n }, [menu])\n\n if (seat === null || display.length === 0) return null\n\n /** Commit the in-flight label edit (blank clears the override). */\n const commitEdit = (): void => {\n if (editing === null) return\n actions.rename(editing.sessionId, editing.draft)\n setEditing(null)\n }\n\n /** Start editing a tab's own label, pre-filled with what the chip shows. */\n const startEdit = (sessionId: SessionId, current: string): void => {\n setMenu(null)\n setEditing({ sessionId, draft: current })\n }\n\n /** Translate a drop onto `target` into an index in the resulting strip. */\n const dropIndexFor = (draggedSessionId: SessionId, target: DropTarget): number | null => {\n const from = index.get(draggedSessionId)\n const at = index.get(target.sessionId)\n if (from === undefined || at === undefined || from === at) return null\n // Insertion index in the CURRENT strip, then corrected for the removal the\n // move implies: removing a chip before the insertion point shifts it left.\n const insertion = at + (target.side === 'after' ? 1 : 0)\n return from < insertion ? insertion - 1 : insertion\n }\n\n const chips = display.map((tab: SessionTab, at: number) => {\n const summary = list.byId[tab.sessionId]\n // A restored tab can render before its catalog row arrives. Show the\n // session id meanwhile rather than an empty chip — the tab is real, and\n // the title fills in as soon as the catalog catches up.\n const sessionLabel = summary === undefined\n ? tab.sessionId\n : summary.blank ? t('newSession') : summary.displayTitle\n // The user's own label wins over the session title; blank means \"follow the\n // session\", so the override is absent rather than empty.\n const label = tab.title ?? sessionLabel\n const active = tab.sessionId === currentId\n const pinned = tab.pinned === true\n const indicator = tabIndicator(summary, statuses.get(tab.sessionId))\n // The project this session belongs to. Absent for a session that is in\n // no workspace (a bare session, or one just created before the\n // registry caught up) — the chip then shows the title alone rather\n // than a placeholder.\n const project = projects.get(tab.sessionId)\n // Title attribute carries the full pair plus the directory, so the\n // truncated chip text is recoverable on hover.\n const tip = project === undefined\n ? label\n : `${project.label} · ${label}\\n${project.path}`\n const drop = dropTarget !== null && dropTarget.sessionId === tab.sessionId ? dropTarget.side : null\n const isEditing = editing !== null && editing.sessionId === tab.sessionId\n const draft = isEditing && editing !== null ? editing.draft : ''\n const className = [\n 'wgTab',\n active ? 'wgTabActive' : '',\n pinned ? 'wgTabPinned' : '',\n dragging === tab.sessionId ? 'wgTabDragging' : '',\n drop === 'before' ? 'wgTabDropBefore' : '',\n drop === 'after' ? 'wgTabDropAfter' : '',\n ].filter(part => part !== '').join(' ')\n return (\n {\n // Middle click closes, the way every other tab strip behaves. Only\n // button 1: a right click opens the menu instead.\n if (event.button !== 1) return\n event.preventDefault()\n actions.close(tab.sessionId)\n }}\n onContextMenu={(event) => {\n event.preventDefault()\n setEditing(null)\n setMenu({\n sessionId: tab.sessionId,\n // Clamp inside the viewport so a chip near the right edge does not\n // open a menu that runs off-screen.\n x: Math.min(event.clientX, window.innerWidth - 208),\n y: Math.min(event.clientY, window.innerHeight - 240),\n })\n }}\n onDragStart={(event) => {\n event.dataTransfer.effectAllowed = 'move'\n event.dataTransfer.setData('text/plain', tab.sessionId)\n setDragging(tab.sessionId)\n setMenu(null)\n }}\n onDragOver={(event) => {\n if (dragging === null || dragging === tab.sessionId) return\n event.preventDefault()\n event.dataTransfer.dropEffect = 'move'\n const rect = event.currentTarget.getBoundingClientRect()\n const side = event.clientX < rect.left + rect.width / 2 ? 'before' : 'after'\n setDropTarget({ sessionId: tab.sessionId, side })\n }}\n onDrop={(event) => {\n event.preventDefault()\n if (dragging !== null && dropTarget !== null) {\n const target = dropIndexFor(dragging, dropTarget)\n if (target !== null) actions.move(dragging, target)\n }\n setDragging(null)\n setDropTarget(null)\n dragEndedAt.current = Date.now()\n }}\n onDragEnd={() => {\n setDragging(null)\n setDropTarget(null)\n dragEndedAt.current = Date.now()\n }}\n >\n {isEditing ? (\n { event.currentTarget.select() }}\n onChange={(event) => { setEditing({ sessionId: tab.sessionId, draft: event.target.value }) }}\n onClick={(event) => { event.stopPropagation() }}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n commitEdit()\n } else if (event.key === 'Escape') {\n event.preventDefault()\n setEditing(null)\n }\n }}\n onBlur={() => { commitEdit() }}\n />\n ) : (\n <>\n {\n if (Date.now() - dragEndedAt.current < 250) return\n activate(tab.sessionId)\n }}\n onDoubleClick={() => { startEdit(tab.sessionId, label) }}\n >\n \n \n \n {/* Two stacked lines, folder-style: the project (short, quiet)\n over the session title (long, primary). The project line is\n omitted for a session in no workspace, which lets the title\n use the full height rather than leaving a blank row. */}\n \n {project !== undefined && (\n {project.label}\n )}\n {label}\n \n \n {pinned && (\n \n \n \n )}\n \n {\n event.stopPropagation()\n actions.close(tab.sessionId)\n }}\n >\n \n \n \n \n )}\n
\n )\n })\n\n // The menu's chip, resolved against the current strip: a menu opened on a chip\n // that has since disappeared renders nothing rather than acting on a stale id.\n const menuTab = menu === null ? undefined : display.find(tab => tab.sessionId === menu.sessionId)\n const menuIndex = menuTab === undefined ? -1 : at(display, menuTab)\n const menuLabel = menuTab === undefined\n ? ''\n : menuTab.title ?? list.byId[menuTab.sessionId]?.displayTitle ?? menuTab.sessionId\n const menuPinned = menuTab?.pinned === true\n const canCloseRight = menuIndex >= 0 && menuIndex < display.length - 1\n\n return createPortal(\n <>\n
\n {\n // A plain wheel reports only `deltaY`, and the overflow here is\n // horizontal, so without this the wheel would do nothing over the\n // strip (or scroll the transcript behind it). Redirect the dominant\n // delta to scrollLeft, and only swallow the event once there is\n // somewhere left to scroll — otherwise a wheel at either end keeps\n // propagating and the page still scrolls normally.\n const el = event.currentTarget\n if (el.scrollWidth <= el.clientWidth) return\n const delta = Math.abs(event.deltaY) > Math.abs(event.deltaX) ? event.deltaY : event.deltaX\n if (delta === 0) return\n const atStart = el.scrollLeft <= 0 && delta < 0\n const atEnd = el.scrollLeft + el.clientWidth >= el.scrollWidth - 1 && delta > 0\n if (atStart || atEnd) return\n el.scrollLeft += delta\n event.preventDefault()\n }}\n >\n {chips}\n
\n \n {menu !== null && menuTab !== undefined && createPortal(\n \n {\n actions.pin(menu.sessionId)\n setMenu(null)\n }}\n />\n { startEdit(menu.sessionId, menuLabel) }}\n />\n {\n setMenu(null)\n rename(menu.sessionId, menuLabel)\n }}\n />\n
\n {\n setMenu(null)\n actions.close(menu.sessionId)\n }}\n />\n {\n setMenu(null)\n actions.closeOthers(menu.sessionId)\n }}\n />\n {\n setMenu(null)\n actions.closeAfter(menu.sessionId)\n }}\n />\n
,\n document.body,\n )}\n ,\n seat,\n )\n}\n\n/** Index of one tab in the strip, used by the menu's range actions. */\nfunction at(tabs: readonly SessionTab[], target: SessionTab): number {\n return tabs.findIndex(tab => tab.sessionId === target.sessionId)\n}\n","/**\r\n * The \"flower branch\" geometry for the sidebar tree.\r\n *\r\n * Reproduces the RewampUI *Flower Sidebar* mechanism: a single curly branch runs\r\n * down the left of the nav list, drawn as SVG so it can be *grown* — a faded\r\n * dashed ghost shows the whole route, and a solid stroke is drawn only as far as\r\n * the row you are on. Each row gets a dot sitting exactly on the curve, and the\r\n * active row's dot blooms.\r\n *\r\n * How it maps onto OUR tree (three levels: 分组 folder → 项目 folder → 会话 row):\r\n *\r\n * - The branch is **one continuous path** through every visible row, not one\r\n * rail per folder. That is what makes it read as a plant rather than as the\r\n * per-folder rail it replaces.\r\n * - The stem runs at `STEM_X`; at each **group boundary** it kinks outward to\r\n * `BULGE_X` and back — a half-pitch out plus a half-pitch back, which is\r\n * exactly the reference's 32px rhythm.\r\n * - Rows that are not group boundaries sit on a straight run, one row pitch\r\n * apart, each carrying a dot at its own y.\r\n *\r\n * Runtime-free on purpose (same discipline as `tabs.ts` / `store-core.ts`): the\r\n * component measures the DOM and hands plain numbers here, so the geometry is\r\n * unit-testable without a browser.\r\n */\r\n\r\n/** Horizontal position of the stem's straight runs. */\r\n/**\r\n * Default x for a row's anchor, in SVG coordinates.\r\n *\r\n * A fallback only: rows carry their OWN measured `x`, because the tree indents\r\n * with per-row padding rather than one shared origin. A folder's chevron and a\r\n * session's text sit at different x, and no single constant lands on both.\r\n */\r\nexport const STEM_X = 30\r\n\r\n/** Default vertical pitch between two rows. */\r\nexport const ROW_PITCH = 32\r\n\r\n/**\r\n * One row the branch must pass through.\r\n *\r\n * Both coordinates are MEASURED, not derived:\r\n * - `y` because the tree mixes row heights and inter-row gaps (deriving one\r\n * pitch from a single gap drifted the dots up to 15px off their rows);\r\n * - `x` because the tree indents per row via padding, so a folder's chevron and\r\n * a session's text are at different x.\r\n */\r\nexport interface BranchRow {\r\n /** Stable key, used to match a row to its dot. */\r\n readonly key: string\r\n /** Row centre y, in the SVG's coordinate space. */\r\n readonly y: number\r\n /**\r\n * Row anchor x, in the SVG's coordinate space.\r\n *\r\n * A folder row's anchor is its CHEVRON centre — the triangle the user already\r\n * reads as \"this row opens\" — so the stem visually hangs off the marker rather\r\n * than floating beside it. A session row's anchor is the indent its text sits\r\n * on.\r\n */\r\n readonly x: number\r\n /**\r\n * Row kind. A `'group'` row starts a new group and makes the stem kink;\r\n * an `'item'` row runs straight (or curves back in right after a group).\r\n */\r\n readonly kind: 'group' | 'item'\r\n /** Whether this is the row the user is currently on (the bloomed dot). */\r\n readonly active: boolean\r\n}\r\n\r\n/** A dot on the branch: one per row, positioned on the curve. */\r\nexport interface BranchDot {\r\n /** The row this dot belongs to. */\r\n readonly key: string\r\n readonly cx: number\r\n readonly cy: number\r\n readonly active: boolean\r\n}\r\n\r\n/**\r\n * The bloom that flowers at the branch's endpoint.\r\n *\r\n * The endpoint is where the GROWN stroke stops — the row the user is on — not\r\n * the last visible row: the stem is drawn to the active row, so that is where\r\n * the plant has visibly reached, whether the tree is folded above it or not.\r\n *\r\n * This is deliberately the ONE row an active marker names, so the flower can\r\n * never disagree with the stem about where the branch ends.\r\n */\r\nexport interface BranchFlower {\r\n /** Row whose endpoint carries the bloom (the active row's key). */\r\n readonly key: string\r\n /** Endpoint x: the last dot's centre, i.e. exactly where the grown path stops. */\r\n readonly cx: number\r\n /** Endpoint y, on the measured row centre. */\r\n readonly cy: number\r\n}\r\n\r\n/** The branch: one path for the ghost, its total length, and the dots. */\r\nexport interface Branch {\r\n /** Full route, drawn as the faded dashed ghost. */\r\n readonly ghostPath: string\r\n /** Path up to and including the active row (the \"grown\" part). */\r\n readonly grownPath: string\r\n /** Drawn length of the full route. */\r\n readonly ghostLength: number\r\n /** Drawn length of the grown part. */\r\n readonly grownLength: number\r\n /** Dots, in row order. */\r\n readonly dots: readonly BranchDot[]\r\n /**\r\n * Bloom at the grown path's endpoint, or NULL when no row carries the active\r\n * marker.\r\n *\r\n * Deliberately stricter than `grownPath`: the stem has to be *some* path even\r\n * when nothing is active (it collapses to the bare origin, drawing nothing),\r\n * but a bloom with no active row has nothing to be the flower OF. Falling back\r\n * to the first dot — the earlier rule — put the blossom on a folder row at the\r\n * top of the tree as soon as the open session's folder was collapsed, because\r\n * folding removes the only row carrying the marker. No active row means no\r\n * flower.\r\n */\r\n readonly flower: BranchFlower | null\r\n /** Total vertical extent, so the SVG box can be sized. */\r\n readonly height: number\r\n}\r\n\r\n/**\r\n * Internal: one move of the route, kept as STRUCTURE rather than only as a path\r\n * string. The endpoint trim below has to shorten the final move along its own\r\n * direction, which is only sound if the segment still knows where it goes.\r\n */\r\ninterface Segment {\r\n /** SVG path command for the full move. */\r\n readonly d: string\r\n /** Length the move contributes to the run. */\r\n readonly length: number\r\n /** Where the move starts. */\r\n readonly from: { readonly x: number; readonly y: number }\r\n /** Where the move ends. */\r\n readonly to: { readonly x: number; readonly y: number }\r\n /** Bulge x for a curved move (the curve is vertical-tangent at both ends). */\r\n readonly controlX?: number\r\n}\r\n\r\n/**\r\n * Plan the route: one segment per row after the first, plus the dot positions.\r\n *\r\n * Kept separate from the string assembly so the length walk and the SVG `d`\r\n * always describe the same geometry — measuring one path against another is how\r\n * a grown/ghost pair drifts out of sync.\r\n *\r\n * The stem lands on each row's OWN anchor (x) and centre (y), so uneven row\r\n * heights and the tree's per-row indents both stay exact. A group row's anchor\r\n * is pushed out by `BULGE_OFFSET`, which is what creates the kink.\r\n *\r\n * @param rows - visible rows in render order, carrying measured anchors.\r\n * @returns the per-row segments and dot x positions.\r\n */\r\nfunction plan(rows: readonly BranchRow[]): { segments: Segment[]; dotX: number[] } {\r\n const segments: Segment[] = []\r\n const first = rows[0] as BranchRow\r\n const dotX: number[] = [first.x]\r\n let x = first.x\r\n\r\n for (let i = 1; i < rows.length; i += 1) {\r\n const row = rows[i] as BranchRow\r\n const prev = rows[i - 1] as BranchRow\r\n const startY = prev.y\r\n const endY = row.y\r\n const midY = startY + (endY - startY) / 2\r\n\r\n // Every dot lands on its OWN anchor; the stem simply travels between them.\r\n // When two consecutive rows share an anchor (sessions under one project) the\r\n // travel is a straight run; when it changes (a folder's chevron sits left of\r\n // its children's dots) the stem swings out through an S-curve, which is what\r\n // reads as the branch stepping around the folder marker.\r\n const target = row.x\r\n\r\n if (target === x) {\r\n segments.push({\r\n d: `L ${x} ${endY}`,\r\n length: Math.abs(endY - startY),\r\n from: { x, y: startY },\r\n to: { x, y: endY },\r\n })\r\n } else {\r\n // Two halves so the tangent is vertical at both ends, matching the\r\n // reference's curve rhythm.\r\n segments.push({\r\n d: `C ${x} ${midY}, ${target} ${midY}, ${target} ${endY}`,\r\n length: Math.hypot(target - x, endY - midY),\r\n from: { x, y: startY },\r\n to: { x: target, y: endY },\r\n controlX: x,\r\n })\r\n x = target\r\n }\r\n dotX.push(x)\r\n }\r\n\r\n return { segments, dotX }\r\n}\r\n\r\n/**\r\n * How far short of the flower's centre the stem stops, in SVG user units.\r\n *\r\n * The bloom is drawn ON the endpoint, so a stem that runs all the way to the\r\n * centre is visible through the petal notches and reads as a line crossing the\r\n * flower. Stopping the stroke at (a little over) the bloom's radius keeps the\r\n * stem ending cleanly at the flower's edge, where it reads as a stalk holding\r\n * the bloom.\r\n *\r\n * 7 units ≈ the 6.2-unit flower radius plus a hair, so the stroke's round cap\r\n * tucks just under the outer petals without a visible gap.\r\n */\r\nexport const STEM_END_CLEARANCE = 7\r\n\r\n/**\r\n * Shorten a move so it stops `clearance` short of its end point.\r\n *\r\n * Used only on the LAST move of the grown run, which is what hides the stroke\r\n * behind the bloom. A straight move is trimmed along its axis; a curved move is\r\n * trimmed by moving its end and its control point together, which shortens the\r\n * curve while keeping its vertical tangents (so the kink's shape is preserved\r\n * rather than being flattened into a line).\r\n *\r\n * Returns the move unchanged when it is too short to trim (the stem would\r\n * invert), so a cramped layout degrades to \"line meets flower\" rather than\r\n * producing a backwards path.\r\n *\r\n * @param segment - the move to shorten.\r\n * @param clearance - distance to stop short of the end.\r\n * @returns the shortened move.\r\n */\r\nfunction trimEnd(segment: Segment, clearance: number): Segment {\r\n const { from, to } = segment\r\n const span = Math.hypot(to.x - from.x, to.y - from.y)\r\n if (span <= clearance) return segment\r\n\r\n if (segment.controlX === undefined) {\r\n // Straight: retreat along the axis by the clearance.\r\n const ratio = (span - clearance) / span\r\n const endX = from.x + (to.x - from.x) * ratio\r\n const endY = from.y + (to.y - from.y) * ratio\r\n return { ...segment, d: `L ${endX} ${endY}`, to: { x: endX, y: endY }, length: span - clearance }\r\n }\r\n\r\n // Curved: the move is two mirrored halves, so retreating the END by half the\r\n // clearance and the control point by the full one shortens it symmetrically\r\n // while keeping both tangents vertical.\r\n const endY = to.y - clearance\r\n const controlY = from.y + (to.y - from.y) / 2 - clearance\r\n const endX = to.x\r\n return {\r\n ...segment,\r\n d: `C ${segment.controlX} ${controlY}, ${endX} ${controlY}, ${endX} ${endY}`,\r\n to: { x: endX, y: endY },\r\n length: Math.max(0, segment.length - clearance),\r\n }\r\n}\r\n\r\n/**\r\n * Build the branch for a list of rows.\r\n *\r\n * @param rows - visible rows in render order, each carrying its MEASURED centre.\r\n * @returns the branch geometry; empty strings when there are no rows.\r\n */\r\nexport function buildBranch(rows: readonly BranchRow[]): Branch {\r\n const first = rows[0]\r\n if (first === undefined) {\r\n return { ghostPath: '', grownPath: '', ghostLength: 0, grownLength: 0, dots: [], flower: null, height: 0 }\r\n }\r\n\r\n const { segments, dotX } = plan(rows)\r\n const head = `M ${first.x} ${first.y}`\r\n\r\n const dots: BranchDot[] = rows.map((row, index) => ({\r\n key: row.key,\r\n cx: dotX[index] ?? row.x,\r\n cy: row.y,\r\n active: row.active,\r\n }))\r\n\r\n // The grown stroke stops AT the active row, so its path contains every\r\n // segment before that row and none after. An active first row grows nothing\r\n // beyond the origin, which is correct (the dot sits on the stem origin).\r\n //\r\n // `activeIndex < 0` is the NO-ACTIVE-ROW case: the open session's folder was\r\n // collapsed, or the catalog has not resolved yet. The stem then collapses to\r\n // the bare origin (drawing nothing), and — crucially — `hasActive` stays false\r\n // so no flower is produced. Conflating this with \"the first row is active\" is\r\n // what used to sprout the blossom on a top-level folder row.\r\n const activeIndex = rows.findIndex(row => row.active)\r\n const hasActive = activeIndex >= 0\r\n const grownTo = hasActive ? activeIndex : 0\r\n\r\n // The bloom sits on the endpoint of `grownPath`, which `join` puts at the\r\n // active row. It therefore uses the SAME index as the grown stroke, so the\r\n // flower and the stem can never disagree about where the branch ends — and it\r\n // exists ONLY when a row actually claimed the marker.\r\n const flowerAt = dots[grownTo] as BranchDot | undefined\r\n const flower: BranchFlower | null = hasActive && flowerAt !== undefined\r\n ? { key: flowerAt.key, cx: flowerAt.cx, cy: flowerAt.cy }\r\n : null\r\n\r\n const join = (list: readonly Segment[]): string =>\r\n list.length === 0 ? head : [head, ...list.map(s => s.d)].join(' ')\r\n\r\n // The grown run: every move before the active row, plus the move INTO it —\r\n // which is the one trimmed so the stroke stops at the bloom's edge instead of\r\n // crossing the flower. The GHOST keeps its full length: it is a faint dashed\r\n // route at 28% opacity, and shortening it too would leave the last row's\r\n // guide visibly detached from that row.\r\n const grownSegments = segments.slice(0, grownTo)\r\n const lastGrown = grownSegments[grownSegments.length - 1]\r\n const grownStroke = lastGrown === undefined\r\n ? grownSegments\r\n : [...grownSegments.slice(0, -1), trimEnd(lastGrown, STEM_END_CLEARANCE)]\r\n\r\n const lengthOf = (count: number): number =>\r\n segments.slice(0, count).reduce((sum, s) => sum + s.length, 0)\r\n\r\n const last = rows[rows.length - 1] as BranchRow\r\n // Half a row height of breathing room below the last dot, so the stem does not\r\n // stop dead on the final row.\r\n const tail = rows.length > 1 ? Math.abs(last.y - (rows[rows.length - 2] as BranchRow).y) / 2 : 0\r\n\r\n return {\r\n ghostPath: join(segments),\r\n grownPath: join(grownStroke),\r\n ghostLength: lengthOf(segments.length),\r\n // The grown length follows the TRIMMED run, so a consumer measuring the\r\n // stroke (a dash animation, say) stays consistent with what is drawn.\r\n grownLength: Math.max(0, lengthOf(grownTo) - (lastGrown === undefined ? 0 : STEM_END_CLEARANCE)),\r\n dots,\r\n flower,\r\n height: last.y + tail,\r\n }\r\n}\r\n","/**\r\n * The flower marker: an SVG overlay that draws a single bloom on the row you are\r\n * currently on.\r\n *\r\n * Originally ported from the RewampUI *Flower Sidebar* reference, which drew a\r\n * continuous curly stem down the whole tree — a dashed \"ghost\" route plus a\r\n * solid stroke \"grown\" to the active row — with a dot on every row and the bloom\r\n * at its tip. **The stem and the dots are gone**: they read as a stray black line\r\n * down the sidebar, and depth is already carried by the row indentation. Only the\r\n * bloom remains, still spinning while the current session works and resting when\r\n * it is idle.\r\n *\r\n * The SVG is `pointer-events: none` and `overflow: visible`, so it is pure\r\n * decoration over the real rows and never intercepts a click.\r\n *\r\n * Measurement, not layout: the rows are rendered by the tree itself (they carry\r\n * drag handlers, menus and hover state), so this component reads each row's\r\n * vertical centre and anchor from the DOM and feeds plain numbers to\r\n * `buildBranch`. That keeps the geometry unit-tested (`branch.ts`) while the SVG\r\n * stays a dumb renderer of it — and leaves the branch math intact should the stem\r\n * ever come back.\r\n *\r\n * Re-measured on: row count changes (expand/collapse, new session), the active\r\n * row changing, and container resize. A `ResizeObserver` on the scroll body\r\n * covers the last one without a window listener.\r\n *\r\n * The bloom's spin is NOT re-measured here: it arrives as the `spinning` prop\r\n * and is applied as a class, so a status flip never re-runs the DOM measurement\r\n * above (the tree is the expensive part, not the class swap).\r\n */\r\nimport { useEffect, useRef, useState } from 'react'\r\nimport { buildBranch, type Branch, type BranchRow } from './branch.ts'\r\n\r\n/**\r\n * Attribute the tree puts on every row the branch should connect. */\r\nexport const BRANCH_ROW_ATTRIBUTE = 'data-wg-branch-row'\r\n\r\n/**\r\n * Attribute marking the row the stem should grow to.\r\n *\r\n * Only the DEEPEST row gets this (the session). Its ancestors — the project and\r\n * the category that contain it — deliberately do NOT, because a session belongs\r\n * to both and marking all three would make \"which row is active?\" ambiguous.\r\n * When several rows do carry it, the deepest (last in document order) wins.\r\n */\r\nexport const BRANCH_ACTIVE_ATTRIBUTE = 'data-wg-branch-active'\r\n\r\n/** Row kind marker: a group boundary kinks the stem. */\r\nexport const BRANCH_GROUP_ATTRIBUTE = 'data-wg-branch-group'\r\n\r\n/**\r\n * The bloom's petal outline, in the 1024-unit box the artwork was drawn in.\r\n *\r\n * This is the user's own flower glyph verbatim: an eight-petal bloom around a\r\n * ringed center. Kept as a path (not a component) because it is a constant.\r\n */\r\nconst FLOWER_PATH = 'M375.3728 841.8432c92.96-12.5184 203.8784-71.264 299.5456-166.9248 22.6112-22.6112 43.1616-46.08 61.5232-69.952C712.7616 786.3936 621.2608 921.6 512 921.6c-51.1488 0-98.4-29.632-136.6272-79.7568z m-87.808-422.8096C311.2384 237.6064 402.7328 102.4 512 102.4c51.1488 0 98.4 29.632 136.6272 79.7568-92.96 12.5184-203.8784 71.264-299.5456 166.9248a719.1232 719.1232 0 0 0-61.5232 69.952z m-129.536 139.5648c57.3248 74.2464 163.6608 140.9344 294.336 175.9488a719.1232 719.1232 0 0 0 91.3472 18.304c-168.9664 70.208-331.808 58.5728-386.432-36.0512-25.5744-44.288-23.5456-100.032 0.7552-158.2016z m322.2592-287.4496c168.9664-70.208 331.808-58.5728 386.432 36.0512 25.5744 44.288 23.5456 100.032-0.7552 158.2016-57.3184-74.2464-163.648-140.9344-294.336-175.9488a719.1232 719.1232 0 0 0-91.3408-18.304zM294.656 228.7552c-35.6352 86.7648-40.224 212.1984-5.2032 342.8736a719.1232 719.1232 0 0 0 29.8176 88.256C173.9904 548.6592 102.6432 401.824 157.2736 307.2c25.5744-44.288 74.8608-70.4 137.3824-78.4448z m410.0736 135.36c145.28 111.2256 216.6272 258.0608 161.9968 352.6848-25.5744 44.288-74.8608 70.4-137.3824 78.4448 35.6352-86.7648 40.224-212.1984 5.2032-342.8736a719.1232 719.1232 0 0 0-29.8176-88.256zM512 678.4c-88.3648 0-160-71.6352-160-160s71.6352-160 160-160 160 71.6352 160 160-71.6352 160-160 160z m0-83.2c42.4128 0 76.8-34.3872 76.8-76.8s-34.3872-76.8-76.8-76.8-76.8 34.3872-76.8 76.8 34.3872 76.8 76.8 76.8z'\r\n\r\n/** Petal colour: the accent the glyph was drawn in. */\r\nconst FLOWER_PETAL = '#fa541c'\r\n\r\n/**\r\n * Rendered size of the bloom, as a scale factor over the authored 1024 box.\r\n *\r\n * 17 / 1024 ≈ 0.0166 puts the flower at ~17px: clear of neighbouring rows (rows\r\n * are 28px tall) while still reading as a flower rather than a dot at the end of\r\n * the stem.\r\n */\r\nconst FLOWER_SCALE = 17 / 1024\r\n\r\n/**\r\n * Centre of the artwork inside its own 1024-unit box, measured from the path.\r\n *\r\n * Both the recentring AND the rotation are expressed with this ONE pair of user\r\n * units, so neither depends on a percentage or on a reference box. Verified\r\n * against the live DOM: the path's own `getBBox()` centre is exactly (512, 512).\r\n */\r\nconst FLOWER_CENTRE = 512\r\n\r\n/**\r\n * The bloom at the branch's endpoint.\r\n *\r\n * Anchoring is done entirely by these transforms, in this order:\r\n *\r\n * 1. `translate(cx cy)` — put the origin on the stem's tip (the endpoint of\r\n * the grown stroke).\r\n * 2. `scale(FLOWER_SCALE)` — shrink the 1024-unit artwork about that origin.\r\n * 3. `translate(-512 -512)` — bring the glyph's own centre (512, 512) onto the\r\n * origin, so the flower is centred on the tip.\r\n *\r\n * The spin is applied by `wgFlowerArt` in CSS as a `rotate()` composed AFTER\r\n * that recentring (`translate(-512 -512) rotate(...)`), so the bloom turns about\r\n * its own centre and the recentring never drifts as it rotates.\r\n *\r\n * Note what is deliberately NOT used here: a percentage `translate(-50%, -50%)`\r\n * or `transform-box: fill-box` + percentage `transform-origin`. Measured on the\r\n * live page, the percentage form resolved against the SVG VIEWPORT rather than\r\n * the path's box, translating by (-24, -409.5) instead of (-373, -409.6) and\r\n * parking the bloom well right of the stem. Explicit user units remove the\r\n * question: 512 is the measured centre, not an inferred one.\r\n *\r\n * The flower rests while the session is idle and turns while it works: one\r\n * animation, paused rather than removed, so a state flip resumes the turn\r\n * instead of snapping the petals back to 0deg.\r\n *\r\n * @param props - endpoint coordinates and whether the session is working.\r\n * @returns the bloom group.\r\n */\r\nfunction Flower({ cx, cy, spinning }: { cx: number; cy: number; spinning: boolean }) {\r\n return (\r\n \r\n \r\n \r\n )\r\n}\r\n\r\n/**\r\n * Render the branch for the rows currently inside `scope`.\r\n * @param props - the element to measure, and whether the open session is working.\r\n * @returns the SVG overlay, or null until at least one row is measured.\r\n */\r\nexport function FlowerBranch({ scope, spinning }: { scope: HTMLElement | null; spinning: boolean }) {\r\n const [rows, setRows] = useState([])\r\n\r\n // A cheap change key: the caller cannot tell us when a row expanded, so we\r\n // watch the attribute count and the active row instead of diffing every node.\r\n const measureKey = useRef('')\r\n // The measured pixel pitch is per-list, not the module default: our rows are\r\n // 28/30px tall in places, and assuming 32 would drift the dots off the rows.\r\n const [branch, setBranch] = useState(null)\r\n\r\n useEffect(() => {\r\n if (scope === null) {\r\n setRows([])\r\n setBranch(null)\r\n return\r\n }\r\n\r\n const measure = (): void => {\r\n const nodes = Array.from(scope.querySelectorAll(`[${BRANCH_ROW_ATTRIBUTE}]`))\r\n const first = nodes[0]\r\n if (first === undefined) {\r\n if (measureKey.current !== '') {\r\n measureKey.current = ''\r\n setRows([])\r\n setBranch(null)\r\n }\r\n return\r\n }\r\n\r\n // Exactly one row carries the marker (the session); if a caller ever marks\r\n // several, the deepest wins so the stem still lands on a real leaf.\r\n const activeIndex = nodes.reduce(\r\n (found, node, index) => (node.hasAttribute(BRANCH_ACTIVE_ATTRIBUTE) ? index : found),\r\n -1,\r\n )\r\n const kinds = nodes.map(n => (n.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item')).join('')\r\n const key = `${nodes.length}|${activeIndex}|${kinds}|${Math.round(scope.clientWidth)}`\r\n if (key === measureKey.current) return\r\n measureKey.current = key\r\n\r\n // Each row carries its OWN measured anchor: y because the tree mixes row\r\n // heights, x because it indents per row via padding (a folder's chevron and\r\n // a session's text do not share an x).\r\n const measured: BranchRow[] = nodes.map((node, index) => ({\r\n key: `${index}`,\r\n y: center(node),\r\n x: anchorX(node),\r\n kind: node.hasAttribute(BRANCH_GROUP_ATTRIBUTE) ? 'group' : 'item',\r\n active: index === activeIndex,\r\n }))\r\n\r\n setRows(measured)\r\n setBranch(buildBranch(measured))\r\n }\r\n\r\n /** Vertical centre of a node, relative to the scope box. */\r\n function center(node: HTMLElement): number {\r\n const r = node.getBoundingClientRect()\r\n const s = (scope as HTMLElement).getBoundingClientRect()\r\n return r.top - s.top + r.height / 2\r\n }\r\n\r\n /**\r\n * Horizontal anchor of a row, relative to the scope box.\r\n *\r\n * A row with a chevron anchors to that triangle's CENTRE: it is the marker\r\n * the user already reads as \"this row opens\", so the stem hangs off it\r\n * instead of floating beside it. A chevron-less row (a session) has no\r\n * marker, so it anchors to where its own content starts — the status dot's\r\n * centre, which is the first thing in the row.\r\n */\r\n function anchorX(node: HTMLElement): number {\r\n const s = (scope as HTMLElement).getBoundingClientRect()\r\n const marker = node.querySelector('.wgChevron')\r\n ?? node.querySelector('[class*=\"wgStatusSlot\"]')\r\n ?? node.querySelector('[class*=\"wgCategoryIcon\"]')\r\n ?? node.querySelector('[class*=\"wgRowIcon\"]')\r\n const box = (marker ?? node).getBoundingClientRect()\r\n return box.left - s.left + box.width / 2\r\n }\r\n\r\n measure()\r\n\r\n // Row set changes (expand/collapse/new session) arrive as childList edits.\r\n const observer = new MutationObserver(measure)\r\n observer.observe(scope, { childList: true, subtree: true, attributes: true, attributeFilter: [BRANCH_ACTIVE_ATTRIBUTE] })\r\n\r\n // Width changes reflow row heights in the rail/wide layouts.\r\n const resizer = new ResizeObserver(measure)\r\n resizer.observe(scope)\r\n\r\n return () => {\r\n observer.disconnect()\r\n resizer.disconnect()\r\n }\r\n }, [scope])\r\n\r\n if (branch === null || rows.length === 0) return null\r\n\r\n // Only the bloom is drawn. The stem (ghost + grown stroke) and the per-row\r\n // dots were removed on request: they read as a stray black line down the\r\n // sidebar and the depth is already carried by the indentation, so the flower\r\n // alone marks the row you are on. `branch` is still BUILT from the measured\r\n // rows — it is what gives the bloom its position — but its path geometry is\r\n // no longer rendered.\r\n if (branch.flower === null) return null\r\n\r\n return (\r\n \r\n \r\n \r\n )\r\n}\r\n","/**\r\n * The workspace-groups browsing region filling the sidebar shell's\r\n * `sidebar.workspaces` hole: section header (title + right-aligned search +\r\n * new-group + add workspace), the three-level tree (category — workspace —\r\n * session), group management dialogs, and the workspace/session dialogs. Wide\r\n * state renders the full browser; rail state renders the two region icons\r\n * (search / add workspace) as 36px controls on the shell's shared rail entry\r\n * path, each requesting expansion through the owner share.\r\n *\r\n * Data: workspaces/sessions via the framework global hooks; grouping config\r\n * via the host half's `/workspace-groups/config` route (refetched on mount).\r\n * Runtime group management (create/rename/delete any group, drag workspaces\r\n * between groups and into position, drag groups into position) persists\r\n * through `PUT /workspace-groups/manual`; the sidecar YAML is never rewritten\r\n * (rule-group rename/delete ride the overlay `renamed`/`hidden` maps).\r\n */\r\nimport { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'\r\nimport {\r\n Button,\r\n IconCloseFillMedium,\r\n IconFolderOpenOutlineRegular,\r\n IconProjectAddOutlineRegular,\r\n IconSearchOutlineRegular,\r\n IconTrashOutlineRegular,\r\n IconWarningOutlineRegular,\r\n Modal,\r\n Toast,\r\n Tooltip,\r\n} from '@deepseek-ai/dsh-client-ui-primitives'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'\r\nimport {\r\n displayCategoryKeys,\r\n isCategoryPinned,\r\n moveAfter,\r\n moveBefore,\r\n originalRuleNameForDisplay,\r\n pruneAppearance,\r\n resolveCategory,\r\n takenCategoryNames,\r\n} from '../core/matcher.ts'\r\nimport {\r\n GROUP_COLORS,\r\n GROUP_ICON_IDS,\r\n TOP_LEVEL_ORDER_KEY,\r\n UNCATEGORIZED_LABEL,\r\n type CategoryAppearance,\r\n type GroupColor,\r\n type GroupsConfig,\r\n type ManualGroups,\r\n} from '../core/types.ts'\r\nimport type { GroupsBrowserProps } from './contract.ts'\r\nimport { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'\r\nimport { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'\r\nimport type { WorkspaceGroupsKey } from './locales.ts'\r\nimport { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'\r\nimport { loadFolders, saveFolders } from './folders-persist.ts'\r\nimport { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'\r\nimport { QuickPanel } from './QuickPanel.tsx'\r\nimport { SessionTabs } from './SessionTabs.tsx'\r\nimport { FlowerBranch } from './FlowerBranch.tsx'\r\nimport css from './styles.css?inline'\r\n\r\nconst SEARCH_DEBOUNCE_MS = 250\r\nconst SEARCH_QUERY_MAX_CODE_UNITS = 500\r\n\r\n/** Overlay with every optional field materialized (plain-object edits, no undefined spreads). */\r\ntype NormalizedManual = Required\r\n\r\nconst EMPTY_MANUAL: NormalizedManual = {\r\n categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [], appearance: {},\r\n}\r\n\r\n/** Materialize optional overlay fields so every update is a plain object edit. */\r\nfunction normalizeManual(manual: ManualGroups): NormalizedManual {\r\n return {\r\n categories: manual.categories,\r\n assignments: manual.assignments,\r\n categoryOrder: manual.categoryOrder ?? [],\r\n workspaceOrder: manual.workspaceOrder ?? {},\r\n renamed: manual.renamed ?? {},\r\n hidden: manual.hidden ?? [],\r\n appearance: manual.appearance ?? {},\r\n }\r\n}\r\n\r\n/**\r\n * Largest subtree (rows including the level header) that still animates: a\r\n * 100-session project expanding with a grid animation janks the sidebar, so\r\n * wide subtrees snap open instead.\r\n */\r\nconst ANIMATION_ROW_CAP = 40\r\n\r\n/**\r\n * Mirrors the host icon validator (`parseAppearance`) so invalid custom glyphs\r\n * fail locally instead of turning the whole overlay PUT into a 400.\r\n */\r\nconst ICON_VALUE_PATTERN = /^(?:[a-z][a-z0-9-]{0,23}|[^\\s\\u0000-\\u001f\\u007f]{1,4})$/u\r\n\r\n/** Rows a group reveals when expanded (projects + their visible sessions). */\r\nfunction categoryRowCount(category: CategoryNode): number {\r\n return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0)\r\n}\r\n\r\n/** Palette id — i18n key for the colour picker (keeps literal key types intact). */\r\nconst COLOR_LABEL_KEYS: Record = {\r\n red: 'color.red',\r\n orange: 'color.orange',\r\n amber: 'color.amber',\r\n green: 'color.green',\r\n teal: 'color.teal',\r\n blue: 'color.blue',\r\n indigo: 'color.indigo',\r\n purple: 'color.purple',\r\n pink: 'color.pink',\r\n gray: 'color.gray',\r\n}\r\n\r\nfunction sanitizeSearchQuery(value: string): string {\r\n const withoutNul = value.replaceAll('\\0', '')\r\n if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul\r\n return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS)\r\n}\r\n\r\n/** Immutable membership toggle for the local expand-all array. */\r\nfunction toggled(list: readonly string[], key: string): string[] {\r\n return list.includes(key) ? list.filter(k => k !== key) : [...list, key]\r\n}\r\n\r\ninterface RemoteSearchState {\r\n query: string\r\n status: 'idle' | 'loading' | 'ready' | 'error'\r\n items: readonly SessionSearchResultItem[]\r\n hasMore: boolean\r\n}\r\n\r\n/** Light runtime guard for the manual overlay attached to the config fetch. */\r\nfunction isManualGroups(value: unknown): value is ManualGroups {\r\n if (typeof value !== 'object' || value === null) return false\r\n const candidate = value as { categories?: unknown; assignments?: unknown }\r\n return Array.isArray(candidate.categories) && typeof candidate.assignments === 'object' && candidate.assignments !== null\r\n}\r\n\r\n/** Minimal fetch of the grouping config + runtime overlay (no-cache revalidation). */\r\nasync function fetchGroupsConfig(): Promise<{ config: GroupsConfig; manual: NormalizedManual }> {\r\n const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })\r\n if (!response.ok) throw new Error(`config request failed: ${response.status}`)\r\n const body = (await response.json()) as GroupsConfig\r\n const config: GroupsConfig = Array.isArray(body.categories) ? body : { categories: [] }\r\n return { config, manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL }\r\n}\r\n\r\n/** Persist the whole runtime overlay (idempotent; the host validates + writes). */\r\nasync function saveManualOverlay(manual: ManualGroups): Promise {\r\n const response = await fetch('/workspace-groups/manual', {\r\n method: 'PUT',\r\n headers: { 'Content-Type': 'application/json' },\r\n body: JSON.stringify(manual),\r\n })\r\n if (!response.ok) {\r\n let message = `manual save failed: ${response.status}`\r\n try {\r\n const text = await response.text()\r\n if (text !== '') message = text\r\n } catch { /* keep the fallback message */ }\r\n throw new Error(message)\r\n }\r\n}\r\n\r\n/** One group-management dialog state: create, or rename an existing group. */\r\ntype GroupDialogState = { mode: 'create' } | { mode: 'rename'; from: string } | null\r\n\r\n/** Row reference used by drop targets: which kind of row, which key. */\r\nexport type DropRowRef = { kind: 'category' | 'workspace' | 'topLevel'; key: string }\r\n\r\n/**\r\n * Which level's rows fold while a drag is in progress: dragging a project\r\n * folds every project row (grouped AND top-level), dragging a group folds\r\n * every group row. The other level keeps its expansion untouched.\r\n */\r\nexport type DragLevel = 'workspace' | 'category' | null\r\n\r\n/**\r\n * Current drop indicator. A `line` renders a 2px insertion line above/below a\r\n * row (project reorder inside a group, or group reorder); an `into` renders\r\n * the whole-row highlight used when dropping a project into a group. Drop\r\n * handlers re-derive before/after from the drop event itself, so the\r\n * indicator is purely visual and can never go stale.\r\n */\r\nexport type DragIndicator =\r\n | { mode: 'line'; row: DropRowRef; before: boolean }\r\n | { mode: 'into'; categoryKey: string }\r\n | null\r\n\r\n/**\r\n * Render the browsing region.\r\n * @param props - composed slot props (shell owner share + store + injected actions).\r\n * @returns the region element tree.\r\n */\r\nexport function GroupsBrowser({\r\n wide,\r\n expandSidebar,\r\n useSessions,\r\n useWorkspaces,\r\n useSessionStatus,\r\n useStore,\r\n actions,\r\n startSession,\r\n createSessionIn,\r\n open,\r\n renameSession,\r\n forkSession,\r\n renameWorkspace,\r\n deleteWorkspace,\r\n insertWorkspaceBefore,\r\n archiveSession,\r\n insertSessionBefore,\r\n createWorkspace,\r\n pickDirectory,\r\n searchSessions,\r\n searchResultLimit,\r\n openTab,\r\n useTabs,\r\n tabActions,\r\n t,\r\n}: GroupsBrowserProps) {\r\n // Inject the stylesheet once per fiber; dispose removes it (HMR safe).\r\n useEffect(() => {\r\n const style = document.createElement('style')\r\n style.setAttribute('data-plugin', 'dsh-workspace-groups')\r\n style.textContent = css\r\n document.head.append(style)\r\n return () => { style.remove() }\r\n }, [])\r\n\r\n // Ctrl+R toggles the quick switch panel. Capture phase + preventDefault:\r\n // beats the browser's page-reload default and any shell-level handler.\r\n const [quickOpen, setQuickOpen] = useState(false)\r\n useEffect(() => {\r\n const onKeyDown = (e: KeyboardEvent): void => {\r\n if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (e.key === 'r' || e.key === 'R')) {\r\n e.preventDefault()\r\n e.stopPropagation()\r\n setQuickOpen(v => !v)\r\n }\r\n }\r\n window.addEventListener('keydown', onKeyDown, true)\r\n return () => window.removeEventListener('keydown', onKeyDown, true)\r\n }, [])\r\n\r\n // Grouping config from the host route + the runtime manual overlay.\r\n const [config, setConfig] = useState({ categories: [] })\r\n const [manual, setManual] = useState(EMPTY_MANUAL)\r\n const [configError, setConfigError] = useState(null)\r\n const reloadConfig = () => {\r\n setConfigError(null)\r\n fetchGroupsConfig().then(({ config: nextConfig, manual: nextManual }) => {\r\n setConfig(nextConfig)\r\n setManual(nextManual)\r\n }).catch((reason: unknown) => {\r\n setConfigError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n useEffect(() => { reloadConfig() }, [])\r\n\r\n // Transient save errors for drag/menu group operations (dialog errors are local).\r\n const [manualError, setManualError] = useState(null)\r\n const [manualSaving, setManualSaving] = useState(false)\r\n\r\n // ---- Per-workspace folders (multi-root) -------------------------------------\r\n //\r\n // A second host sidecar (`/workspace-groups/folders`) lists each workspace's\r\n // extra folders plus the optional root folder. It is read once per mount and\r\n // written back whole, like the manual overlay above; a failed write is a\r\n // toast rather than a banner because every edit here is a one-off row action.\r\n const [foldersDoc, setFoldersDoc] = useState(EMPTY_FOLDERS_DOCUMENT)\r\n // Folder collapse is component state, not store state: it is a transient view\r\n // of the row list, like the quick panel, so it is deliberately NOT persisted\r\n // with the category/workspace expansion keys. Folders start expanded, so\r\n // attaching a folder never hides sessions the user could already see.\r\n const [collapsedFolderKeys, setCollapsedFolderKeys] = useState([])\r\n const [foldersTarget, setFoldersTarget] = useState(null)\r\n const [foldersBusy, setFoldersBusy] = useState(false)\r\n const [creatingSessionIn, setCreatingSessionIn] = useState(null)\r\n useEffect(() => {\r\n let cancelled = false\r\n void loadFolders().then((document) => {\r\n if (cancelled) return\r\n setFoldersDoc(document)\r\n })\r\n return () => { cancelled = true }\r\n }, [])\r\n\r\n const workspaces = useWorkspaces(state => state.items)\r\n const workspacePhase = useWorkspaces(state => state.phase)\r\n const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)\r\n const categoryExpansion = useStore(s => s.categoryExpansion)\r\n const workspaceExpansion = useStore(s => s.workspaceExpansion)\r\n\r\n const list = useSessions(s => s)\r\n const statuses = useSessionStatus(s => s)\r\n // 0.1.6: the selected Session is the one retained through `mainView`, not a\r\n // `list.current` field (the list snapshot carries catalog facts only).\r\n const current = currentSessionId(list)\r\n const currentWorkspaceKey = current === undefined\r\n ? undefined\r\n : (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)\r\n\r\n // Whether the open session is WORKING right now, which is what makes the\r\n // flower at the branch's endpoint turn. Read from the unified status snapshot\r\n // (the catalog summary alone goes stale), folded together with the session's\r\n // own `running` so a subagent-only turn still counts.\r\n //\r\n // Derived as a boolean on purpose: the overlay re-measures through its own\r\n // MutationObserver, so handing it a live value would re-render the tree on\r\n // every status tick.\r\n const currentRunning = current !== undefined\r\n && ((statuses.get(current)?.running ?? false) || (list.byId[current]?.running ?? false))\r\n\r\n // Auto-expand the category + workspace containing the current session, but\r\n // ONLY when the user has never touched that key (`Object.hasOwn`): a\r\n // present `false` is a deliberate collapse and must stay folded. Without\r\n // this guard the effect re-expands the just-collapsed current category on\r\n // every store change (the reported \"cannot collapse\" bug).\r\n useEffect(() => {\r\n if (current === undefined || currentWorkspaceKey === undefined) return\r\n const category = categoriesForCurrent(config, workspaces, current, manual)\r\n if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {\r\n actions.setCategoryExpanded(category, true)\r\n }\r\n if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {\r\n actions.setWorkspaceExpanded(currentWorkspaceKey, true)\r\n }\r\n }, [current, currentWorkspaceKey, config, workspaces, manual, categoryExpansion, workspaceExpansion, actions])\r\n\r\n // Drop expansion keys that no longer exist (group edits / workspace deletion).\r\n useEffect(() => {\r\n if (workspacePhase !== 'ready') return\r\n actions.retainKeys(\r\n displayCategoryKeys(config, manual),\r\n workspaces.map(w => w.workspaceId as string),\r\n )\r\n }, [actions, config, manual, workspacePhase, workspaces])\r\n\r\n // Session tabs: the strip lives in the conversation column, but its lifecycle\r\n // belongs here — the browser already derives the open session for its own tree,\r\n // so one effect covers every way a session can be opened (sidebar row,\r\n // workspace New Session, quick panel, conversation-header crumbs).\r\n //\r\n // `statuses` is a dependency on purpose: a session earns its tab when it\r\n // STARTS working, which is a status change, not a catalog change. Without it a\r\n // conversation that began while already open would never surface a tab.\r\n useEffect(() => {\r\n if (current === undefined) return\r\n openTab(current, statuses.get(current))\r\n }, [current, list, statuses, openTab])\r\n\r\n const [query, setQuery] = useState('')\r\n const [searchExpanded, setSearchExpanded] = useState(false)\r\n const normalizedQuery = sanitizeSearchQuery(query).trim()\r\n const [remoteSearch, setRemoteSearch] = useState({\r\n query: '', status: 'idle', items: [], hasMore: false,\r\n })\r\n const searchInput = useRef(null)\r\n const searchRoot = useRef(null)\r\n // Box the flower branch measures and paints into. Held as a ref (not state)\r\n // because the overlay re-measures on its own MutationObserver; a state update\r\n // here would re-render the whole tree on every layout tick.\r\n const branchScope = useRef(null)\r\n\r\n // Search debounce + abort, same posture as the official browser.\r\n useEffect(() => {\r\n if (normalizedQuery === '') {\r\n setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false })\r\n return\r\n }\r\n const controller = new AbortController()\r\n setRemoteSearch({ query: normalizedQuery, status: 'loading', items: [], hasMore: false })\r\n const timer = window.setTimeout(() => {\r\n searchSessions(normalizedQuery, controller.signal).then((result) => {\r\n if (controller.signal.aborted) return\r\n setRemoteSearch({ query: normalizedQuery, status: 'ready', items: result.items, hasMore: result.hasMore })\r\n }).catch(() => {\r\n if (controller.signal.aborted) return\r\n setRemoteSearch({ query: normalizedQuery, status: 'error', items: [], hasMore: false })\r\n })\r\n }, SEARCH_DEBOUNCE_MS)\r\n return () => {\r\n window.clearTimeout(timer)\r\n controller.abort()\r\n }\r\n }, [normalizedQuery, searchSessions])\r\n\r\n // Outside-click dismissal of the search box.\r\n useEffect(() => {\r\n if (!wide || !searchExpanded) return\r\n const onClick = (event: MouseEvent): void => {\r\n if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return\r\n searchInput.current?.blur()\r\n if (normalizedQuery !== '') return\r\n setSearchExpanded(false)\r\n }\r\n document.addEventListener('click', onClick)\r\n return () => { document.removeEventListener('click', onClick) }\r\n }, [normalizedQuery, wide, searchExpanded])\r\n\r\n const expandedCategories = useMemo(\r\n () => Object.entries(categoryExpansion).filter(([, v]) => v).map(([k]) => k),\r\n [categoryExpansion],\r\n )\r\n const expandedWorkspaces = useMemo(\r\n () => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),\r\n [workspaceExpansion],\r\n )\r\n // Which level is being dragged: drives the top-level drop target (project\r\n // drags only) and which level's rows fold.\r\n const [dragging, setDragging] = useState(null)\r\n const groups = useMemo(\r\n () => deriveGroups(list, workspaces, archivedSessionIds, config, {\r\n expandedCategories,\r\n expandedWorkspaces,\r\n collapsedFolders: collapsedFolderKeys,\r\n }, manual, statuses, foldersDoc),\r\n [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc],\r\n )\r\n // Top-level (ungrouped) workspace rows, rendered after the group folders.\r\n const topLevel = useMemo(\r\n () => deriveTopLevel(list, workspaces, archivedSessionIds, config, {\r\n expandedCategories,\r\n expandedWorkspaces,\r\n collapsedFolders: collapsedFolderKeys,\r\n }, manual, statuses, foldersDoc),\r\n [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc],\r\n )\r\n // Quick panel (Ctrl+R): category label per grouped workspace id (the tree\r\n // derivation already resolved grouping; top-level workspaces stay absent).\r\n const categoryByWorkspace = useMemo(() => {\r\n const map = new Map()\r\n for (const category of groups) {\r\n for (const workspace of category.workspaces) map.set(workspace.workspaceId as string, category.label)\r\n }\r\n return map\r\n }, [groups])\r\n // While dragging a project, an empty top-level area must still show a landing\r\n // line — otherwise a project can never be dragged OUT of a group when every\r\n // project is currently grouped.\r\n const topLevelDropActive = dragging === 'workspace' && topLevel.length === 0\r\n // The top-level area is the move-out landing spot: rows reorder with an\r\n // insertion line (before/after), and the blank space below the last row\r\n // appends to the end of the list. No whole-area highlight box.\r\n const topLevelRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY }\r\n\r\n // Add workspace flow: self-contained (no directory-flow hole dependency).\r\n const [adding, setAdding] = useState(false)\r\n const [addError, setAddError] = useState(null)\r\n const [addErrorOpen, setAddErrorOpen] = useState(false)\r\n const addWorkspace = async (): Promise => {\r\n if (adding) return\r\n setAdding(true)\r\n setAddError(null)\r\n setAddErrorOpen(false)\r\n try {\r\n const path = await pickDirectory()\r\n if (path === null) return // cancelled\r\n const workspace = await createWorkspace({ path })\r\n startSession(workspace.workspaceId)\r\n } catch (reason) {\r\n const message = reason instanceof Error ? reason.message : String(reason)\r\n setAddError(message)\r\n setAddErrorOpen(true)\r\n } finally {\r\n setAdding(false)\r\n }\r\n }\r\n\r\n // Workspace rename dialog.\r\n const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null)\r\n const [renameDraft, setRenameDraft] = useState('')\r\n const [renaming, setRenaming] = useState(false)\r\n const [renameError, setRenameError] = useState(null)\r\n const renameTrimmed = renameDraft.trim()\r\n const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle\r\n && workspaces.some(w => w.title === renameTrimmed)\r\n const renameBlocked = renaming || renameTrimmed === '' || renameTarget === null\r\n || renameTrimmed === renameTarget.currentTitle || renameDuplicate\r\n const confirmRename = () => {\r\n if (renameBlocked || renameTarget === null) return\r\n setRenaming(true)\r\n setRenameError(null)\r\n renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {\r\n setRenaming(false)\r\n setRenameTarget(null)\r\n }).catch((reason: unknown) => {\r\n setRenaming(false)\r\n setRenameError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // Workspace delete dialog.\r\n const [deleteTarget, setDeleteTarget] = useState<{ workspaceId: WorkspaceId; title: string } | null>(null)\r\n const [deleting, setDeleting] = useState(false)\r\n const [deleteError, setDeleteError] = useState(null)\r\n const confirmDelete = () => {\r\n if (deleting || deleteTarget === null) return\r\n setDeleting(true)\r\n setDeleteError(null)\r\n deleteWorkspace(deleteTarget.workspaceId).then(() => {\r\n setDeleting(false)\r\n setDeleteTarget(null)\r\n }).catch((reason: unknown) => {\r\n setDeleting(false)\r\n setDeleteError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // Session rename dialog.\r\n const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionId; currentTitle: string } | null>(null)\r\n const [sessionRenameDraft, setSessionRenameDraft] = useState('')\r\n const [sessionRenaming, setSessionRenaming] = useState(false)\r\n const [sessionRenameError, setSessionRenameError] = useState(null)\r\n const sessionRenameTrimmed = sessionRenameDraft.trim()\r\n const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null\r\n const confirmSessionRename = () => {\r\n if (sessionRenameBlocked || sessionRenameTarget === null) return\r\n setSessionRenaming(true)\r\n setSessionRenameError(null)\r\n renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {\r\n setSessionRenaming(false)\r\n setSessionRenameTarget(null)\r\n }).catch((reason: unknown) => {\r\n setSessionRenaming(false)\r\n setSessionRenameError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n const onSessionRename = (sessionId: SessionId, currentTitle: string) => {\r\n setSessionRenameTarget({ sessionId, currentTitle })\r\n setSessionRenameDraft(currentTitle)\r\n setSessionRenameError(null)\r\n }\r\n\r\n // The strip is a child of this component (rendered through a DOM portal), so\r\n // it shares this fiber's props directly: renames call the dialog owner here,\r\n // and activation goes through the same navigation verb the sidebar rows use.\r\n const activateTab = (sessionId: SessionId) => { open(sessionId) }\r\n\r\n const onSessionArchive = (sessionId: SessionId) => {\r\n archiveSession(sessionId).catch((reason: unknown) => {\r\n console.warn('session archive rejected:', reason)\r\n })\r\n }\r\n\r\n // \"Open in folder\": the host half of the official open-in-app plugin resolves\r\n // which applications it can launch; the project row then just posts the\r\n // project directory to that host's launch route. One availability read per\r\n // mount — a host without the capability (or a refused read) leaves\r\n // `folderApp` undefined, which drops the menu entry rather than failing.\r\n const [folderApp, setFolderApp] = useState(undefined)\r\n const [folderError, setFolderError] = useState<{ id: number; text: string } | null>(null)\r\n useEffect(() => {\r\n const controller = new AbortController()\r\n fetchOpenInApps(controller.signal).then((apps) => {\r\n if (controller.signal.aborted) return\r\n setFolderApp(folderAppId(apps))\r\n }).catch(() => { /* no capability: the row simply offers no folder entry */ })\r\n return () => { controller.abort() }\r\n }, [])\r\n\r\n const openInFolder = folderApp === undefined\r\n ? undefined\r\n : (workspaceId: WorkspaceId): void => {\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n openPathInApp(folderApp, workspace.path).catch((reason: unknown) => {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n setFolderError({ id: Date.now(), text: `${t('workspace.openInFolderError')}: ${detail}` })\r\n })\r\n }\r\n\r\n // ---- Folder overlay editing -------------------------------------------------\r\n\r\n const notifyFolder = (text: string): void => {\r\n setFolderError({ id: Date.now(), text })\r\n }\r\n\r\n const persistFolders = (next: FoldersDocument): void => {\r\n setFoldersDoc(next)\r\n saveFolders(next).catch((reason: unknown) => {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n notifyFolder(`${t('folder.saveError')}: ${detail}`)\r\n })\r\n }\r\n\r\n /** Write one workspace's entry; zero extra folders removes the key entirely. */\r\n const writeFolderEntry = (workspaceId: WorkspaceId, entry: WorkspaceFolderEntry): void => {\r\n const next: Record = { ...foldersDoc.workspaces }\r\n const key = workspaceId as string\r\n if (entry.folders.length === 0) delete next[key]\r\n else next[key] = entry\r\n persistFolders({ version: 1, workspaces: next })\r\n }\r\n\r\n const toggleFolder = (workspaceId: WorkspaceId, path: string): void => {\r\n const key = folderKey(workspaceId, path)\r\n setCollapsedFolderKeys(keys => (keys.includes(key) ? keys.filter(k => k !== key) : [...keys, key]))\r\n }\r\n\r\n const addFolderTo = async (workspaceId: WorkspaceId): Promise => {\r\n if (foldersBusy) return\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n setFoldersBusy(true)\r\n try {\r\n const path = await pickDirectory()\r\n if (path === null) return // cancelled\r\n const entry = entryFor(foldersDoc, workspaceId as string)\r\n if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {\r\n notifyFolder(t('folder.duplicate'))\r\n return\r\n }\r\n writeFolderEntry(workspaceId, addFolder(entry, path))\r\n } catch (reason) {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n notifyFolder(`${t('folder.addError')}: ${detail}`)\r\n } finally {\r\n setFoldersBusy(false)\r\n }\r\n }\r\n\r\n const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {\r\n writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))\r\n }\r\n\r\n const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => {\r\n writeFolderEntry(workspaceId, removeFolder(entryFor(foldersDoc, workspaceId as string), path))\r\n }\r\n\r\n /**\r\n * \"New session here\": an extra folder's own directory becomes the Session cwd.\r\n * The base folder keeps the platform's own gesture instead, because that one\r\n * reuses the blank session it already opened; creating a fresh Session on\r\n * every click would pile up empty sessions. One creation in flight at a time;\r\n * a rejection surfaces the failure and creates nothing else.\r\n */\r\n const startSessionInFolder = (workspaceId: WorkspaceId, path: string, isBase: boolean): void => {\r\n if (isBase) {\r\n startSession(workspaceId)\r\n return\r\n }\r\n if (creatingSessionIn !== null) return\r\n setCreatingSessionIn(folderKey(workspaceId, path))\r\n createSessionIn(workspaceId, path).catch((reason: unknown) => {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n notifyFolder(`${t('folder.sessionError')}: ${detail}`)\r\n }).finally(() => {\r\n setCreatingSessionIn(null)\r\n })\r\n }\r\n\r\n /** A project row's plus button — starts in that workspace's root folder. */\r\n const startSessionAtRoot = (workspaceId?: WorkspaceId): void => {\r\n const workspace = workspaceId === undefined ? undefined : workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) {\r\n startSession(workspaceId)\r\n return\r\n }\r\n const root = rootOf(workspace.path, entryFor(foldersDoc, workspaceId as string))\r\n startSessionInFolder(workspaceId as WorkspaceId, root, samePath(root, workspace.path))\r\n }\r\n\r\n // Absent when the host offers no folder application: folder rows then drop\r\n // their \"open folder\" entry instead of failing at the click.\r\n const openFolderPath = folderApp === undefined\r\n ? undefined\r\n : (path: string): void => {\r\n openPathInApp(folderApp, path).catch((reason: unknown) => {\r\n const detail = reason instanceof Error ? reason.message : String(reason)\r\n notifyFolder(`${t('workspace.openInFolderError')}: ${detail}`)\r\n })\r\n }\r\n\r\n // ---- Runtime group management ----------------------------------------------\r\n\r\n const [groupDialog, setGroupDialog] = useState(null)\r\n const [groupDraft, setGroupDraft] = useState('')\r\n const [groupError, setGroupError] = useState(null)\r\n const [groupBusy, setGroupBusy] = useState(false)\r\n const [groupDeleteTarget, setGroupDeleteTarget] = useState(null)\r\n const [groupDeleting, setGroupDeleting] = useState(false)\r\n const [groupDeleteError, setGroupDeleteError] = useState(null)\r\n\r\n // Appearance dialog (color / icon / pin) for one group display key. Every\r\n // control applies immediately (optimistic merge + save); there is no OK, so\r\n // `appearanceTarget` also doubles as the open flag.\r\n const [appearanceTarget, setAppearanceTarget] = useState(null)\r\n const [appearanceDraft, setAppearanceDraft] = useState({})\r\n const [appearanceError, setAppearanceError] = useState(null)\r\n\r\n const takenNames = useMemo(() => takenCategoryNames(config, manual), [config, manual])\r\n\r\n const groupTrimmed = groupDraft.trim()\r\n const groupNameIssue = groupDialog !== null && groupTrimmed !== ''\r\n ? (groupTrimmed === UNCATEGORIZED_LABEL\r\n ? t('group.nameReserved')\r\n : (groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\r\n ? null\r\n : takenNames.has(groupTrimmed) ? t('group.nameDuplicate') : null)\r\n : null\r\n const groupBlocked = groupBusy || groupTrimmed === '' || groupNameIssue !== null\r\n || (groupDialog !== null && groupDialog.mode === 'rename' && groupTrimmed === groupDialog.from)\r\n\r\n const confirmGroupDialog = () => {\r\n if (groupBlocked || groupDialog === null) return\r\n const name = groupTrimmed\r\n const from = groupDialog.mode === 'rename' ? groupDialog.from : undefined\r\n const renaming = groupDialog.mode === 'rename' && from !== name\r\n\r\n let next: NormalizedManual\r\n if (groupDialog.mode === 'create') {\r\n next = { ...manual, categories: [...manual.categories, name] }\r\n } else {\r\n // Rename: rule groups ride the `renamed` map, manual groups the list;\r\n // every reference (assignments / workspaceOrder / categoryOrder) follows.\r\n const originalRule = from !== undefined ? originalRuleNameForDisplay(config.categories, manual, from) : undefined\r\n next = {\r\n ...manual,\r\n ...(originalRule !== undefined\r\n ? { renamed: { ...manual.renamed, [originalRule]: name } }\r\n : { categories: manual.categories.map(c => c === from ? name : c) }),\r\n assignments: Object.fromEntries(\r\n Object.entries(manual.assignments).map(([id, category]): [string, string | null] => [id, category === from ? name : category]),\r\n ),\r\n workspaceOrder: Object.fromEntries(\r\n Object.entries(manual.workspaceOrder).map(([key, ids]): [string, string[]] => [key === from ? name : key, ids]),\r\n ),\r\n categoryOrder: manual.categoryOrder.map(key => key === from ? name : key),\r\n // Appearance is keyed by display name too: move the entry instead of\r\n // leaving the colour/icon/pin behind under the old name.\r\n appearance: from === undefined || from === name\r\n ? manual.appearance\r\n : Object.fromEntries(\r\n Object.entries(manual.appearance).map(([key, value]): [string, CategoryAppearance] => [key === from ? name : key, value]),\r\n ),\r\n }\r\n }\r\n\r\n setGroupBusy(true)\r\n setGroupError(null)\r\n saveManualOverlay(next).then(() => {\r\n setManual(next)\r\n setManualError(null)\r\n setGroupBusy(false)\r\n setGroupDialog(null)\r\n setGroupDraft('')\r\n // Keep the renamed group open (its old expansion key is dropped by retainKeys).\r\n if (renaming) actions.setCategoryExpanded(name, true)\r\n }).catch((reason: unknown) => {\r\n setGroupBusy(false)\r\n setGroupError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n const confirmGroupDelete = () => {\r\n if (groupDeleting || groupDeleteTarget === null) return\r\n const name = groupDeleteTarget\r\n const originalRule = originalRuleNameForDisplay(config.categories, manual, name)\r\n\r\n // Every project currently in the group goes to the uncategorized bucket (forced, not rule-\r\n // reclassified), regardless of how it landed there.\r\n const assignments = { ...manual.assignments }\r\n for (const workspace of workspaces) {\r\n if (resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) === name) {\r\n assignments[workspace.workspaceId] = null\r\n }\r\n }\r\n const workspaceOrder = Object.fromEntries(\r\n Object.entries(manual.workspaceOrder).filter(([key]) => key !== name),\r\n )\r\n const next: NormalizedManual = {\r\n ...manual,\r\n assignments,\r\n workspaceOrder,\r\n categoryOrder: manual.categoryOrder.filter(key => key !== name),\r\n // Drop the presentation entry with the group itself (a dangling key would\r\n // silently re-attach if a new group ever reused the name).\r\n appearance: Object.fromEntries(\r\n Object.entries(manual.appearance).filter(([key]) => key !== name),\r\n ),\r\n ...(originalRule !== undefined\r\n ? {\r\n renamed: Object.fromEntries(Object.entries(manual.renamed).filter(([key]) => key !== originalRule)),\r\n hidden: [...manual.hidden, originalRule],\r\n }\r\n : { categories: manual.categories.filter(c => c !== name) }),\r\n }\r\n\r\n setGroupDeleting(true)\r\n setGroupDeleteError(null)\r\n saveManualOverlay(next).then(() => {\r\n setManual(next)\r\n setManualError(null)\r\n setGroupDeleting(false)\r\n setGroupDeleteTarget(null)\r\n }).catch((reason: unknown) => {\r\n setGroupDeleting(false)\r\n setGroupDeleteError(reason instanceof Error ? reason.message : String(reason))\r\n })\r\n }\r\n\r\n // ---- Drag & drop (move/reorder workspaces, reorder groups) ------------------\r\n\r\n const [dragIndicator, setDragIndicator] = useState(null)\r\n\r\n // Expansion state taken at dragstart; dragend restores it so the folding\r\n // caused by a drag is always undone afterwards.\r\n const expansionSnapshot = useRef<{ categories: Record; workspaces: Record } | null>(null)\r\n // Live expansion state for the dragend restore (the document-level listener\r\n // is registered once, so it must read current values through a ref).\r\n const liveExpansionRef = useRef({ categoryExpansion, workspaceExpansion, actions })\r\n liveExpansionRef.current = { categoryExpansion, workspaceExpansion, actions }\r\n\r\n // Cancel any stale indicator when a drag ends outside a row (or is aborted),\r\n // and restore the expansion snapshot taken at dragstart.\r\n useEffect(() => {\r\n const clear = () => {\r\n setDragIndicator(null)\r\n setDragging(null)\r\n const snapshot = expansionSnapshot.current\r\n if (snapshot === null) return\r\n expansionSnapshot.current = null\r\n const { categoryExpansion: currentCategories, workspaceExpansion: currentWorkspaces, actions: currentActions } = liveExpansionRef.current\r\n for (const [key, value] of Object.entries(snapshot.categories)) {\r\n if (currentCategories[key] !== value) currentActions.setCategoryExpanded(key, value)\r\n }\r\n for (const [key, value] of Object.entries(snapshot.workspaces)) {\r\n if (currentWorkspaces[key] !== value) currentActions.setWorkspaceExpanded(key, value)\r\n }\r\n }\r\n document.addEventListener('dragend', clear)\r\n return () => { document.removeEventListener('dragend', clear) }\r\n }, [])\r\n\r\n /** Move a workspace into a category (or reorder inside it when `beforeWorkspaceId`/`afterWorkspaceId`). */\r\n const moveWorkspaceTo = async (workspaceId: string, categoryKey: string, beforeWorkspaceId?: string, afterWorkspaceId?: string): Promise => {\r\n if (manualSaving) return\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n setManualSaving(true)\r\n try {\r\n let next: NormalizedManual\r\n if (categoryKey === UNCATEGORIZED_KEY) {\r\n // Move to the TOP LEVEL: force ungrouped (null) and drop from every\r\n // group's order list, while recording the position inside the ordered\r\n // top-level list (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`).\r\n const assignments = { ...manual.assignments, [workspaceId]: null }\r\n const workspaceOrder: Record = {}\r\n for (const [key, ids] of Object.entries(manual.workspaceOrder)) {\r\n if (key === TOP_LEVEL_ORDER_KEY) continue\r\n workspaceOrder[key] = ids.filter(id => id !== workspaceId)\r\n }\r\n const topLevelIds = workspaces\r\n .filter(w => w.workspaceId !== workspaceId && resolveCategory(config, manual, w.workspaceId, w.path, w.title) === undefined)\r\n .map(w => w.workspaceId as string)\r\n workspaceOrder[TOP_LEVEL_ORDER_KEY] = afterWorkspaceId !== undefined\r\n ? moveAfter(topLevelIds, workspaceId, afterWorkspaceId)\r\n : moveBefore(topLevelIds, workspaceId, beforeWorkspaceId)\r\n next = { ...manual, assignments, workspaceOrder }\r\n } else {\r\n const currentKey = resolveCategory(config, manual, workspaceId, workspace.path, workspace.title)\r\n const movingAcross = currentKey !== categoryKey\r\n const assignments = movingAcross\r\n ? { ...manual.assignments, [workspaceId]: categoryKey }\r\n : manual.assignments\r\n const targetOrder = afterWorkspaceId !== undefined\r\n ? moveAfter(manual.workspaceOrder[categoryKey] ?? [], workspaceId, afterWorkspaceId)\r\n : moveBefore(manual.workspaceOrder[categoryKey] ?? [], workspaceId, beforeWorkspaceId)\r\n const workspaceOrder = { ...manual.workspaceOrder, [categoryKey]: targetOrder }\r\n if (movingAcross && currentKey !== undefined && workspaceOrder[currentKey] !== undefined) {\r\n workspaceOrder[currentKey] = workspaceOrder[currentKey]!.filter(id => id !== workspaceId)\r\n }\r\n next = { ...manual, assignments, workspaceOrder }\r\n }\r\n await saveManualOverlay(next)\r\n setManual(next)\r\n setManualError(null)\r\n if (categoryKey !== UNCATEGORIZED_KEY) actions.setCategoryExpanded(categoryKey, true)\r\n } catch (reason) {\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (no target = append). */\r\n const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise => {\r\n if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return\r\n setManualSaving(true)\r\n try {\r\n const order = displayCategoryKeys(config, manual)\r\n const categoryOrder = afterKey !== undefined\r\n ? moveAfter(order, draggedKey, afterKey)\r\n : moveBefore(order, draggedKey, beforeKey)\r\n // Pinned groups sort before unpinned ones, so a drop across that boundary\r\n // only sticks when the dragged group adopts the neighbour's pin state in\r\n // the SAME write. Otherwise the derived order snaps it back and the drop\r\n // looks broken (spec §7.2).\r\n const neighbourKey = afterKey ?? beforeKey\r\n let appearance = manual.appearance\r\n if (neighbourKey !== undefined && isCategoryPinned(manual, neighbourKey) !== isCategoryPinned(manual, draggedKey)) {\r\n const cleaned = pruneAppearance({\r\n ...(manual.appearance[draggedKey] ?? {}),\r\n pinned: isCategoryPinned(manual, neighbourKey),\r\n })\r\n appearance = { ...manual.appearance }\r\n if (cleaned === undefined) delete appearance[draggedKey]\r\n else appearance[draggedKey] = cleaned\r\n }\r\n const next: NormalizedManual = { ...manual, categoryOrder, appearance }\r\n await saveManualOverlay(next)\r\n setManual(next)\r\n setManualError(null)\r\n } catch (reason) {\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /**\r\n * Merge a presentation patch for one group and persist the overlay.\r\n * Optimistic: the tree reflects the change immediately and rolls back if the\r\n * host refuses the write (the dialog has no confirm step).\r\n */\r\n const updateCategoryAppearance = async (key: string, patch: CategoryAppearance): Promise => {\r\n if (manualSaving) return\r\n setManualSaving(true)\r\n const previous = manual\r\n try {\r\n const merged: CategoryAppearance = { ...(manual.appearance[key] ?? {}), ...patch }\r\n const appearance = { ...manual.appearance }\r\n const cleaned = pruneAppearance(merged)\r\n if (cleaned === undefined) delete appearance[key]\r\n else appearance[key] = cleaned\r\n const next: NormalizedManual = { ...manual, appearance }\r\n setManual(next)\r\n await saveManualOverlay(next)\r\n setManualError(null)\r\n } catch (reason) {\r\n setManual(previous)\r\n setManualError(reason instanceof Error ? reason.message : String(reason))\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\r\n\r\n /** Pin/unpin a group (pinned groups render above the normal order). */\r\n const toggleCategoryPinned = async (key: string): Promise => {\r\n await updateCategoryAppearance(key, { pinned: !isCategoryPinned(manual, key) })\r\n }\r\n\r\n /** Appearance currently shown in the dialog (empty while it is closed). */\r\n const appearanceCurrent: CategoryAppearance = appearanceTarget === null\r\n ? {}\r\n : (manual.appearance[appearanceTarget] ?? {})\r\n\r\n /**\r\n * Commit the custom-icon text field. Invalid input is blocked locally (the\r\n * host would 400 the whole overlay save); an empty field clears the icon.\r\n */\r\n const commitAppearanceIcon = (): void => {\r\n if (appearanceTarget === null) return\r\n const icon = (appearanceDraft.icon ?? '').trim()\r\n if (icon !== '' && !ICON_VALUE_PATTERN.test(icon)) {\r\n setAppearanceError(t('group.iconInvalid'))\r\n return\r\n }\r\n setAppearanceError(null)\r\n /* Blur fires before a neighbouring click and on every dialog close: skip\r\n the PUT when the field still matches the stored value. */\r\n if (icon === (appearanceCurrent.icon ?? '')) return\r\n void updateCategoryAppearance(appearanceTarget, { icon: icon === '' ? undefined : icon })\r\n }\r\n\r\n /**\r\n * Drop on a row. The insertion point is re-derived from the drop event's\r\n * position (top half = before, bottom half = after), so it always matches\r\n * the indicator the user last saw — even when dragover and drop arrive in\r\n * the same tick.\r\n */\r\n const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {\r\n event.preventDefault()\r\n // Keep the drop from bubbling to the enclosing top-level area (which is\r\n // also a move-out target): a row drop and the area-drop below it must not\r\n // both fire moveWorkspaceTo.\r\n event.stopPropagation()\r\n setDragIndicator(null)\r\n setDragging(null)\r\n const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE)\r\n if (draggedCategory !== '') {\r\n // Group reorder: only category rows are targets (project rows fold\r\n // during group drags); before/after follows the drop position.\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const beforeKey = row.kind === 'category' && before ? row.key : undefined\r\n const afterKey = row.kind === 'category' && !before ? row.key : undefined\r\n void moveCategory(draggedCategory, beforeKey, afterKey)\r\n return\r\n }\r\n const workspaceId = event.dataTransfer.getData(DND_WORKSPACE_TYPE) || event.dataTransfer.getData('text/plain')\r\n if (workspaceId === '') return\r\n if (row.kind === 'topLevel') {\r\n // Top-level row / top-level blank drop = move OUT of any group (forced\r\n // top-level, rules ignored) and set the position inside the ordered\r\n // top-level list. A row drop re-derives before/after from the drop\r\n // position; a bare area drop (key = UNCATEGORIZED_KEY) appends to the end.\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const specificKey = row.key === UNCATEGORIZED_KEY ? undefined : row.key\r\n void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY, before ? specificKey : undefined, !before ? specificKey : undefined)\r\n return\r\n }\r\n // Project move/reorder: a line on a project row = reorder before/after it;\r\n // dropping anywhere else in a category = move into the group (its end).\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n const beforeWsid = row.kind === 'workspace' && before ? row.key : undefined\r\n const afterWsid = row.kind === 'workspace' && !before ? row.key : undefined\r\n void moveWorkspaceTo(workspaceId, categoryKey, beforeWsid, afterWsid)\r\n }\r\n\r\n const onDragOverRow = (row: DropRowRef) => (event: DragEvent): void => {\r\n if (!hasPluginDragType(event.dataTransfer.types)) return\r\n const draggingCategory = Array.from(event.dataTransfer.types as Iterable).includes(DND_CATEGORY_TYPE)\r\n if (draggingCategory && row.kind !== 'category') return // group drags target category rows only\r\n event.preventDefault()\r\n // Keep a row's dragover from bubbling to the enclosing top-level area\r\n // (which would interpret it as the end-of-list landing).\r\n event.stopPropagation()\r\n event.dataTransfer.dropEffect = 'move'\r\n const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()\r\n const before = event.clientY < rect.top + rect.height / 2\r\n if (draggingCategory || row.kind === 'workspace' || row.kind === 'topLevel') {\r\n // Group reorder (line on a category row), project reorder inside a\r\n // group (line on a project row), or top-level reorder (line on a\r\n // top-level project row).\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === row.kind && prev.row.key === row.key && prev.before === before\r\n ? prev\r\n : { mode: 'line', row, before })\r\n } else {\r\n // Dropping a project INTO a group: whole-row highlight.\r\n setDragIndicator(prev =>\r\n prev?.mode === 'into' && prev.categoryKey === row.key ? prev : { mode: 'into', categoryKey: row.key })\r\n }\r\n }\r\n\r\n const onDragLeaveRow = (event: DragEvent): void => {\r\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return\r\n setDragIndicator(null)\r\n }\r\n\r\n /**\r\n * Drag over the TOP-LEVEL AREA's blank space (not on a row ???rows stop\r\n * propagation). An insertion line shows the landing spot: empty top level —\r\n * a standalone line under the last group; non-empty — a line below the last\r\n * top-level row (end of the list).\r\n */\r\n const onDragOverTopLevelArea = (event: DragEvent): void => {\r\n if (!hasPluginDragType(event.dataTransfer.types)) return\r\n const draggingCategory = Array.from(event.dataTransfer.types as Iterable).includes(DND_CATEGORY_TYPE)\r\n if (draggingCategory) return // group drags never target the top-level area\r\n event.preventDefault()\r\n event.dataTransfer.dropEffect = 'move'\r\n const last = topLevel.length > 0 ? topLevel[topLevel.length - 1] : undefined\r\n if (last !== undefined) {\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === 'topLevel' && prev.row.key === last.workspaceId && prev.before === false\r\n ? prev\r\n : { mode: 'line', row: { kind: 'topLevel', key: last.workspaceId }, before: false })\r\n } else {\r\n setDragIndicator(prev =>\r\n prev?.mode === 'line' && prev.row.kind === 'topLevel' && prev.row.key === topLevelRef.key && prev.before === false\r\n ? prev\r\n : { mode: 'line', row: topLevelRef, before: false })\r\n }\r\n }\r\n\r\n // While dragging a project, only PROJECT rows fold — every expanded\r\n // workspace collapses (inside groups AND top-level); group rows keep their\r\n // expansion so the user still sees where groups are. dragend restores the\r\n // snapshot taken here.\r\n const onDragStartWorkspace = (_workspaceId: string) => (): void => {\r\n setDragging('workspace')\r\n expansionSnapshot.current = {\r\n categories: { ...categoryExpansion },\r\n workspaces: { ...workspaceExpansion },\r\n }\r\n for (const key of Object.keys(workspaceExpansion)) {\r\n if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false)\r\n }\r\n }\r\n\r\n // While dragging a group, only GROUP rows fold (their rows stay visible as\r\n // reorder targets); project rows keep their expansion. dragend restores the\r\n // snapshot taken here.\r\n const onDragStartCategory = (categoryKey: string) => (event: DragEvent): void => {\r\n event.dataTransfer.setData(DND_CATEGORY_TYPE, categoryKey)\r\n event.dataTransfer.effectAllowed = 'move'\r\n setDragging('category')\r\n expansionSnapshot.current = {\r\n categories: { ...categoryExpansion },\r\n workspaces: { ...workspaceExpansion },\r\n }\r\n for (const key of Object.keys(categoryExpansion)) {\r\n if (categoryExpansion[key]) actions.setCategoryExpanded(key, false)\r\n }\r\n }\r\n\r\n const now = Date.now()\r\n\r\n return (\r\n
\r\n {/* The tab strip portals itself into the conversation column's head seat,\r\n so its position here is irrelevant to where it appears; rendering it\r\n from this component is what keeps it on this fiber (and therefore on\r\n this store's single scope) while still reaching the other column. */}\r\n \r\n
\r\n {wide && {t('section.workspaces')}}\r\n {wide && (\r\n
\r\n { setSearchExpanded(true) }}\r\n >\r\n \r\n \r\n {searchExpanded && (\r\n { setQuery(sanitizeSearchQuery(e.target.value)) }}\r\n onKeyDown={(e) => {\r\n if (e.key !== 'Escape') return\r\n setQuery('')\r\n setSearchExpanded(false)\r\n }}\r\n />\r\n )}\r\n {searchExpanded && (\r\n {\r\n e.stopPropagation()\r\n setQuery('')\r\n setSearchExpanded(false)\r\n }}\r\n >\r\n \r\n \r\n )}\r\n
\r\n )}\r\n \r\n {\r\n setGroupDraft('')\r\n setGroupError(null)\r\n setGroupDialog({ mode: 'create' })\r\n }}\r\n >\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
\r\n\r\n {!wide && (\r\n
\r\n \r\n { setSearchExpanded(true); expandSidebar() }}\r\n >\r\n \r\n \r\n \r\n
\r\n )}\r\n\r\n
\r\n {configError !== null && (\r\n
{t('configUnavailable')}
\r\n )}\r\n {manualError !== null && (\r\n
{t('manual.saveError')}: {manualError}
\r\n )}\r\n {wide && normalizedQuery !== '' ? (\r\n \r\n ) : (\r\n /* The branch overlay lives beside the tree, not inside it: it measures\r\n the rows and paints behind them, so it must share their box without\r\n becoming a row itself (which would break role=\"tree\" semantics and\r\n the index-based measurement). */\r\n
\r\n \r\n
\r\n {groups.length === 0 && topLevel.length === 0 && !topLevelDropActive && (\r\n
{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}
\r\n )}\r\n {groups.map((category) => (\r\n { actions.setCategoryExpanded(category.key, !category.expanded) }}\r\n onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\r\n onNewSession={startSessionAtRoot}\r\n onOpen={open}\r\n onToggleFolder={toggleFolder}\r\n onFolderNewSession={startSessionInFolder}\r\n onFolderSetRoot={setFolderRoot}\r\n onFolderRemove={removeFolderFrom}\r\n onOpenFolderPath={openFolderPath}\r\n onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}\r\n creatingFolderKey={creatingSessionIn}\r\n onRenameRequest={(workspaceId, title) => {\r\n setRenameTarget({ workspaceId, currentTitle: title })\r\n setRenameDraft(title)\r\n setRenameError(null)\r\n }}\r\n onDeleteRequest={(workspaceId, title) => {\r\n setDeleteTarget({ workspaceId, title })\r\n setDeleteError(null)\r\n }}\r\n onSessionRename={onSessionRename}\r\n onSessionArchive={onSessionArchive}\r\n onFork={forkSession}\r\n onGroupRename={() => {\r\n setGroupDraft(category.key)\r\n setGroupError(null)\r\n setGroupDialog({ mode: 'rename', from: category.key })\r\n }}\r\n onGroupDelete={() => {\r\n setGroupDeleteTarget(category.key)\r\n setGroupDeleteError(null)\r\n }}\r\n onGroupTogglePin={() => { void toggleCategoryPinned(category.key) }}\r\n onGroupAppearance={() => {\r\n setAppearanceDraft(manual.appearance[category.key] ?? {})\r\n setAppearanceError(null)\r\n setAppearanceTarget(category.key)\r\n }}\r\n animate={dragging === null}\r\n onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}\r\n onOpenInFolder={openInFolder}\r\n canMoveOut={(workspaceId) => {\r\n // The menu \"Move out of group\" is offered for any project that\r\n // currently sits inside a group (rule-classified or manual) —\r\n // not just overridden ones. Top-level projects\r\n // (resolveCategory === undefined) don't need it.\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n return workspace !== undefined\r\n && resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) !== undefined\r\n }}\r\n />\r\n ))}\r\n {/* Top-level (ungrouped) workspaces, rendered after the group\r\n folders. While dragging a project the whole area is the\r\n move-out landing spot (a line shows the insert position;\r\n an empty top level shows a line under the last group). */}\r\n {(topLevel.length > 0 || topLevelDropActive) && (\r\n { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}\r\n onNewSession={startSessionAtRoot}\r\n onOpen={open}\r\n onToggleFolder={toggleFolder}\r\n onFolderNewSession={startSessionInFolder}\r\n onFolderSetRoot={setFolderRoot}\r\n onFolderRemove={removeFolderFrom}\r\n onOpenFolderPath={openFolderPath}\r\n onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}\r\n creatingFolderKey={creatingSessionIn}\r\n onRenameRequest={(workspaceId, title) => {\r\n setRenameTarget({ workspaceId, currentTitle: title })\r\n setRenameDraft(title)\r\n setRenameError(null)\r\n }}\r\n onDeleteRequest={(workspaceId, title) => {\r\n setDeleteTarget({ workspaceId, title })\r\n setDeleteError(null)\r\n }}\r\n onSessionRename={onSessionRename}\r\n onSessionArchive={onSessionArchive}\r\n onFork={forkSession}\r\n onOpenInFolder={openInFolder}\r\n />\r\n )}\r\n
\r\n
\r\n )}\r\n
\r\n\r\n {/* Group create / rename dialog */}\r\n { setGroupDialog(null) }}\r\n closeLabel={t('close')}\r\n title={groupDialog?.mode === 'rename' ? t('group.renameTitle') : t('group.createTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setGroupDraft(e.target.value); setGroupError(null) }}\r\n onKeyDown={(e) => { if (e.key === 'Enter') confirmGroupDialog() }}\r\n />\r\n {groupNameIssue !== null &&
{groupNameIssue}
}\r\n {groupError !== null &&
{groupError}
}\r\n \r\n\r\n {/* Group delete dialog */}\r\n { setGroupDeleteTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('group.deleteTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{t('group.deleteConfirm')}
\r\n {groupDeleteError !== null &&
{groupDeleteError}
}\r\n \r\n\r\n {/* Group appearance dialog: every control writes immediately (optimistic\r\n patch + rollback banner), so the footer is only \"done\". */}\r\n { setAppearanceTarget(null) }}\r\n closeLabel={t('group.appearanceDone')}\r\n title={t('group.appearanceTitle')}\r\n footer={(\r\n \r\n )}\r\n >\r\n {appearanceTarget !== null && (\r\n <>\r\n
\r\n
{t('group.color')}
\r\n
\r\n { void updateCategoryAppearance(appearanceTarget, { color: undefined }) }}\r\n />\r\n {GROUP_COLORS.map((color) => {\r\n const active = appearanceCurrent.color === color\r\n return (\r\n { void updateCategoryAppearance(appearanceTarget, { color }) }}\r\n />\r\n )\r\n })}\r\n
\r\n
\r\n
\r\n
{t('group.icon')}
\r\n
\r\n {GROUP_ICON_IDS.map((id) => {\r\n const active = appearanceCurrent.icon === id\r\n return (\r\n {\r\n setAppearanceDraft({ ...appearanceDraft, icon: id })\r\n setAppearanceError(null)\r\n void updateCategoryAppearance(appearanceTarget, { icon: id })\r\n }}\r\n >\r\n \r\n \r\n )\r\n })}\r\n
\r\n {\r\n setAppearanceDraft({ ...appearanceDraft, icon: e.target.value })\r\n setAppearanceError(null)\r\n }}\r\n onKeyDown={(e) => { if (e.key === 'Enter') commitAppearanceIcon() }}\r\n onBlur={(event) => {\r\n /* A swatch / preset click moves focus out of the field in the\r\n same gesture and writes its own patch — committing the stale\r\n draft here would race it and could overwrite the preset. */\r\n const next = event.relatedTarget\r\n if (next instanceof Element && next.closest('.wgSwatch, .wgIconCell') !== null) return\r\n commitAppearanceIcon()\r\n }}\r\n />\r\n
\r\n
\r\n { void updateCategoryAppearance(appearanceTarget, { pinned: appearanceCurrent.pinned !== true }) }}\r\n >\r\n {appearanceCurrent.pinned === true ? t('group.unpin') : t('group.pin')}\r\n \r\n
\r\n {appearanceError !== null &&
{appearanceError}
}\r\n \r\n )}\r\n \r\n\r\n {/* Per-workspace folders dialog: base + extra folders, root radio,\r\n open/remove per row. Mounted only while a project row asked for it. */}\r\n {foldersTarget !== null && (() => {\r\n const workspace = workspaces.find(w => w.workspaceId === foldersTarget)\r\n if (workspace === undefined) return null\r\n return (\r\n { setFoldersTarget(null) }}\r\n onAdd={() => { void addFolderTo(foldersTarget) }}\r\n onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}\r\n onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}\r\n onOpenFolder={(path) => { openFolderPath?.(path) }}\r\n />\r\n )\r\n })()}\r\n\r\n {/* Workspace rename dialog */}\r\n { setRenameTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.renameTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setRenameDraft(e.target.value) }}\r\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmRename() }}\r\n />\r\n {renameError !== null &&
{renameError}
}\r\n \r\n\r\n {/* Workspace delete dialog */}\r\n { setDeleteTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.deleteTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{t('workspace.deleteConfirm')}
\r\n {deleteError !== null &&
{deleteError}
}\r\n \r\n\r\n {/* Session rename dialog */}\r\n { setSessionRenameTarget(null) }}\r\n closeLabel={t('close')}\r\n title={t('session.renameTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n { setSessionRenameDraft(e.target.value) }}\r\n onKeyDown={(e) => { if (e.key === \"Enter\") confirmSessionRename() }}\r\n />\r\n {sessionRenameError !== null &&
{sessionRenameError}
}\r\n \r\n\r\n {/* Add workspace error dialog */}\r\n { setAddErrorOpen(false) }}\r\n closeLabel={t('close')}\r\n title={t('workspace.addErrorTitle')}\r\n footer={(\r\n <>\r\n \r\n \r\n \r\n )}\r\n >\r\n
{addError}
\r\n \r\n\r\n {/* \"Open in folder\" failure: transient banner, keyed per attempt so a\r\n repeat failure restarts the cycle. */}\r\n {folderError !== null && (\r\n }\r\n onDone={() => { setFolderError(null) }}\r\n />\r\n )}\r\n\r\n {/* Ctrl+R quick switch panel (conditionally mounted: fresh query per open). */}\r\n {quickOpen && (\r\n { setQuickOpen(false) }}\r\n list={list}\r\n workspaces={workspaces}\r\n archivedSessionIds={archivedSessionIds}\r\n categoryByWorkspace={categoryByWorkspace}\r\n current={current}\r\n startSession={startSession}\r\n openSession={open}\r\n now={now}\r\n t={t}\r\n />\r\n )}\r\n
\r\n )\r\n}\r\n\r\n/** Resolve the category label containing the current session (auto-expand helper). */\r\nfunction categoriesForCurrent(\r\n config: GroupsConfig,\r\n workspaces: readonly WorkspaceView[],\r\n current: SessionId,\r\n manual: ManualGroups,\r\n): string | undefined {\r\n const workspace = workspaces.find(w => w.sessionIds.includes(current))\r\n if (workspace === undefined) return undefined\r\n return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)\r\n}\r\n\r\n/**\r\n * The expanded session rows of one project. Workspaces with extra folders get\r\n * one folder row per folder (root first) and hang their sessions off that\r\n * folder; a workspace without extra folders renders today's flat list, so the\r\n * common case is unchanged row-for-row.\r\n */\r\nfunction WorkspaceSubtree({ workspace, current, now, t, animate, onOpen, onSessionRename, onSessionArchive, onFork, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, creatingFolderKey }: {\r\n workspace: WorkspaceGroupNode\r\n current: SessionId | undefined\r\n now: number\r\n t: GroupsBrowserProps['t']\r\n animate: boolean\r\n onOpen: (sessionId: SessionId) => void\r\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\r\n onSessionArchive: (sessionId: SessionId) => void\r\n onFork: (sessionId: SessionId) => void\r\n onToggleFolder: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void\r\n onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderRemove: (workspaceId: WorkspaceId, path: string) => void\r\n onOpenFolderPath?: ((path: string) => void) | undefined\r\n creatingFolderKey: string | null\r\n}) {\r\n const folders = workspace.folders\r\n if (folders === undefined) {\r\n return (\r\n \r\n {workspace.sessions.map((session) => (\r\n \r\n ))}\r\n \r\n )\r\n }\r\n return (\r\n \r\n {folders.map((folder) => {\r\n const key = folderKey(workspace.workspaceId, folder.path)\r\n return (\r\n
\r\n { onToggleFolder(workspace.workspaceId, folder.path) }}\r\n onNewSession={() => { onFolderNewSession(workspace.workspaceId, folder.path, folder.isBase) }}\r\n onSetRoot={() => { onFolderSetRoot(workspace.workspaceId, folder.path) }}\r\n onRemove={() => { onFolderRemove(workspace.workspaceId, folder.path) }}\r\n {...(onOpenFolderPath !== undefined\r\n ? { onOpenInFolder: () => { onOpenFolderPath(folder.path) } }\r\n : {})}\r\n />\r\n \r\n {folder.sessions.map((session) => (\r\n \r\n ))}\r\n \r\n
\r\n )\r\n })}\r\n \r\n )\r\n}\r\n\r\n/** One category section: header row + expanded workspace folders. */\r\nfunction CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {\r\n category: CategoryNode\r\n current: SessionId | undefined\r\n now: number\r\n t: GroupsBrowserProps['t']\r\n dragIndicator: DragIndicator\r\n /** Whether the disclosure animation may play (false while a drag folds rows). */\r\n animate: boolean\r\n onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void\r\n onDragLeaveRow: (event: DragEvent) => void\r\n /** Drop factory: bind the target category and the row kind (before/after re-derived at drop time). */\r\n onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void\r\n onDragStartCategory: (event: DragEvent) => void\r\n onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void\r\n onToggleCategory: () => void\r\n onToggleWorkspace: (key: string) => void\r\n onNewSession: (workspaceId?: WorkspaceId) => void\r\n onOpen: (sessionId: SessionId) => void\r\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\r\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\r\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\r\n onSessionArchive: (sessionId: SessionId) => void\r\n onFork: (sessionId: SessionId) => void\r\n onGroupRename: () => void\r\n onGroupDelete: () => void\r\n /** Pin/unpin this group from its row menu. */\r\n onGroupTogglePin: () => void\r\n /** Open the appearance dialog for this group. */\r\n onGroupAppearance: () => void\r\n onMoveOut: (workspaceId: WorkspaceId) => void\r\n canMoveOut: (workspaceId: WorkspaceId) => boolean\r\n onToggleFolder: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void\r\n onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderRemove: (workspaceId: WorkspaceId, path: string) => void\r\n onManageFolders: (workspaceId: WorkspaceId) => void\r\n /** Creation in flight, keyed by `folderKey`; disables the row's controls */\r\n creatingFolderKey: string | null\r\n /** Absent when the host resolved no folder application. */\r\n onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined\r\n /** Absent when the host resolved no folder application. */\r\n onOpenFolderPath?: ((path: string) => void) | undefined\r\n}) {\r\n const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key\r\n ? (dragIndicator.before ? 'before' : 'after')\r\n : undefined\r\n const categoryInto = dragIndicator?.mode === 'into' && dragIndicator.categoryKey === category.key\r\n return (\r\n
\r\n \r\n \r\n {category.workspaces.map((workspace) => (\r\n
\r\n { onToggleWorkspace(workspace.workspaceId as string) }}\r\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\r\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\r\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\r\n canMoveOut={canMoveOut(workspace.workspaceId)}\r\n onMoveOut={() => { onMoveOut(workspace.workspaceId) }}\r\n {...(onOpenInFolder !== undefined\r\n ? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }\r\n : {})}\r\n dropActive={false}\r\n {...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'workspace' && dragIndicator.row.key === workspace.workspaceId\r\n ? { insertLine: dragIndicator.before ? 'before' : 'after' }\r\n : {})}\r\n onRowDragOver={onDragOverRow({ kind: 'workspace', key: workspace.workspaceId })}\r\n onRowDragLeave={onDragLeaveRow}\r\n onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}\r\n onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}\r\n onManageFolders={() => { onManageFolders(workspace.workspaceId) }}\r\n />\r\n \r\n
\r\n ))}\r\n \r\n
\r\n )\r\n}\r\n\r\n/**\r\n * Top-level (ungrouped) workspace rows rendered after the group folders. While\r\n * a project drag is in progress the WHOLE top-level area is the move-out\r\n * landing spot, shown with an insertion LINE (not a highlight box):\r\n * - a top-level row reorders before/after it (line above/below, like a group);\r\n * - the blank space below the last row appends to the end (line below the\r\n * last row);\r\n * - an empty top level shows a standalone line under the last group folder.\r\n */\r\nfunction TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {\r\n topLevel: readonly WorkspaceGroupNode[]\r\n current: SessionId | undefined\r\n now: number\r\n t: GroupsBrowserProps['t']\r\n /** A project drag is in progress (drives the empty-top-level landing line). */\r\n dragging: boolean\r\n dragIndicator: DragIndicator\r\n topLevelRef: DropRowRef\r\n onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void\r\n onDragOverTopLevelArea: (event: DragEvent) => void\r\n onDragLeaveRow: (event: DragEvent) => void\r\n onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void\r\n onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void\r\n onToggleWorkspace: (key: string) => void\r\n onNewSession: (workspaceId?: WorkspaceId) => void\r\n onOpen: (sessionId: SessionId) => void\r\n onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void\r\n onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void\r\n onSessionRename: (sessionId: SessionId, currentTitle: string) => void\r\n onSessionArchive: (sessionId: SessionId) => void\r\n onFork: (sessionId: SessionId) => void\r\n onToggleFolder: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void\r\n onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void\r\n onFolderRemove: (workspaceId: WorkspaceId, path: string) => void\r\n onManageFolders: (workspaceId: WorkspaceId) => void\r\n creatingFolderKey: string | null\r\n /** Absent when the host resolved no folder application. */\r\n onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined\r\n /** Absent when the host resolved no folder application. */\r\n onOpenFolderPath?: ((path: string) => void) | undefined\r\n}) {\r\n const emptyLineActive = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === topLevelRef.key\r\n return (\r\n \r\n {topLevel.length === 0 && dragging && (\r\n \r\n \r\n \r\n )}\r\n {topLevel.map((workspace) => (\r\n
\r\n { onToggleWorkspace(workspace.workspaceId as string) }}\r\n onNewSession={() => { onNewSession(workspace.workspaceId) }}\r\n onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}\r\n onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}\r\n {...(onOpenInFolder !== undefined\r\n ? { onOpenInFolder: () => { onOpenInFolder(workspace.workspaceId) } }\r\n : {})}\r\n {...(dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === workspace.workspaceId\r\n ? { insertLine: dragIndicator.before ? 'before' : 'after' }\r\n : {})}\r\n onRowDragOver={onDragOverRow({ kind: 'topLevel', key: workspace.workspaceId })}\r\n onRowDragLeave={onDragLeaveRow}\r\n onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })}\r\n onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}\r\n onManageFolders={() => { onManageFolders(workspace.workspaceId) }}\r\n />\r\n \r\n
\r\n ))}\r\n \r\n )\r\n}\r\n\r\n/**\r\n * Search hits inside one project. When the project owns extra folders the hits\r\n * keep their folder row (all expanded, since search prunes to matches) so a\r\n * match never loses the folder it came from.\r\n */\r\nfunction SearchSubtree({ workspace, current, now, open, t }: {\r\n workspace: WorkspaceGroupNode\r\n current: SessionId | undefined\r\n now: number\r\n open: (sessionId: SessionId) => void\r\n t: GroupsBrowserProps['t']\r\n}) {\r\n const folders = workspace.folders\r\n if (folders === undefined) {\r\n return (\r\n
\r\n {workspace.sessions.map((session) => (\r\n {}}\r\n onFork={() => {}}\r\n onArchive={() => {}}\r\n />\r\n ))}\r\n
\r\n )\r\n }\r\n return (\r\n
\r\n {folders.map((folder) => (\r\n
\r\n {}}\r\n onNewSession={() => {}}\r\n onSetRoot={() => {}}\r\n onRemove={() => {}}\r\n />\r\n
\r\n {folder.sessions.map((session) => (\r\n {}}\r\n onFork={() => {}}\r\n onArchive={() => {}}\r\n />\r\n ))}\r\n
\r\n
\r\n ))}\r\n
\r\n )\r\n}\r\n\r\n/**\r\n * Search body rendered as a three-level tree pruned to matched branches:\r\n * Only branches that contain a hit are rendered, which keeps a long list short. Reuses the same row components as\r\n * the idle tree, so search keeps the same folder hierarchy the user is used to.\r\n */\r\nfunction SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, folders, t }: {\r\n list: SessionListState\r\n workspaces: readonly WorkspaceView[]\r\n config: GroupsConfig\r\n archivedSessionIds: readonly SessionId[]\r\n statuses: SessionStatusSnapshot\r\n query: string\r\n remote: RemoteSearchState\r\n resultLimit: number\r\n current: SessionId | undefined\r\n now: number\r\n open: (sessionId: SessionId) => void\r\n manual: ManualGroups\r\n folders: FoldersDocument\r\n t: GroupsBrowserProps['t']\r\n}) {\r\n const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }\r\n const matches = useMemo(\r\n () => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),\r\n [list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],\r\n )\r\n const searchTree = useMemo(\r\n () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses, folders),\r\n [list, workspaces, config, matches, archivedSessionIds, manual, statuses, folders],\r\n )\r\n const groups = searchTree.categories\r\n const searchTopLevel = searchTree.topLevel\r\n const pending = currentRemote.status === 'loading'\r\n const failed = currentRemote.status === 'error'\r\n return (\r\n
\r\n {groups.map((category) => (\r\n
\r\n {}} />\r\n
\r\n {category.workspaces.map((workspace) => (\r\n
\r\n {}}\r\n onNewSession={() => {}}\r\n onRename={() => {}}\r\n onDelete={() => {}}\r\n />\r\n \r\n
\r\n ))}\r\n
\r\n
\r\n ))}\r\n {searchTopLevel.map((workspace) => (\r\n
\r\n {}}\r\n onNewSession={() => {}}\r\n onRename={() => {}}\r\n onDelete={() => {}}\r\n />\r\n \r\n
\r\n ))}\r\n {pending &&
{t('search.pending')}
}\r\n {failed &&
{t('search.unavailable')}
}\r\n {!pending && groups.length === 0 && searchTopLevel.length === 0 && (\r\n
{t('search.noMatches')}
\r\n )}\r\n {matches.hasMore && (\r\n
{t('search.hasMore')}
\r\n )}\r\n
\r\n )\r\n}\r\n\r\n/**\r\n * Folder list dialog for one workspace: the base folder first, then every extra\r\n * folder in stored order. The radio column chooses the root (the folder new\r\n * sessions default to); open/remove act per row, and removing the base folder is\r\n * never offered because the workspace's canonical directory cannot be dropped.\r\n */\r\nfunction FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onSetRoot, onRemove, onOpenFolder }: {\r\n workspace: WorkspaceView\r\n entry: WorkspaceFolderEntry | undefined\r\n t: GroupsBrowserProps['t']\r\n busy: boolean\r\n canOpen: boolean\r\n onClose: () => void\r\n onAdd: () => void\r\n onSetRoot: (path: string) => void\r\n onRemove: (path: string) => void\r\n onOpenFolder: (path: string) => void\r\n}) {\r\n const folders = effectiveFolders(workspace.path, entry)\r\n const root = rootOf(workspace.path, entry)\r\n return (\r\n {t('folder.done')}\r\n )}\r\n >\r\n
\r\n {folders.map((path, index) => {\r\n const isBase = index === 0\r\n const isRoot = samePath(path, root)\r\n const label = folderLabel(path)\r\n return (\r\n
\r\n { onSetRoot(path) }}\r\n />\r\n {label}\r\n {isBase && {t('folder.base')}}\r\n {isRoot && {t('folder.rootBadge')}}\r\n \r\n {canOpen && (\r\n { onOpenFolder(path) }}\r\n >\r\n \r\n \r\n )}\r\n {!isBase && (\r\n { onRemove(path) }}\r\n >\r\n \r\n \r\n )}\r\n \r\n
\r\n )\r\n })}\r\n
\r\n
\r\n \r\n
\r\n \r\n )\r\n}\r\n","/**\r\n * Locale dictionaries for the workspace-groups browser. The namespace is\r\n * `workspaceGroups` (independent from ui-workspace's `workspace` namespace).\r\n */\r\nimport type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'\r\n\r\n/** Dictionary keys of the workspaceGroups namespace (single source of truth). */\r\nexport type WorkspaceGroupsKey =\r\n | 'section.workspaces'\r\n | 'section.sessions'\r\n | 'search'\r\n | 'search.placeholder'\r\n | 'search.clear'\r\n | 'search.noMatches'\r\n | 'search.unavailable'\r\n | 'search.pending'\r\n | 'search.hasMore'\r\n | 'search.results.aria'\r\n | 'workspace.add'\r\n | 'workspace.addBusy'\r\n | 'workspace.addError'\r\n | 'workspace.addErrorTitle'\r\n | 'workspace.rename'\r\n | 'workspace.delete'\r\n | 'workspace.deleteTitle'\r\n | 'workspace.deleteConfirm'\r\n | 'workspace.deleteCancel'\r\n | 'workspace.renaming'\r\n | 'workspace.deleting'\r\n | 'workspace.renameTitle'\r\n | 'workspace.renamePlaceholder'\r\n | 'workspace.renameConfirm'\r\n | 'workspace.renameCancel'\r\n | 'workspace.moveOutOfGroup'\r\n | 'workspace.openInFolder'\r\n | 'workspace.openInFolderError'\r\n | 'folder.title'\r\n | 'folder.manage'\r\n | 'folder.listAria'\r\n | 'folder.base'\r\n | 'folder.setRoot'\r\n | 'folder.rootBadge'\r\n | 'folder.remove'\r\n | 'folder.add'\r\n | 'folder.done'\r\n | 'folder.duplicate'\r\n | 'folder.addError'\r\n | 'folder.sessionError'\r\n | 'folder.saveError'\r\n | 'group.create'\r\n | 'group.createTitle'\r\n | 'group.createPlaceholder'\r\n | 'group.createConfirm'\r\n | 'group.createCancel'\r\n | 'group.rename'\r\n | 'group.renameTitle'\r\n | 'group.renameConfirm'\r\n | 'group.delete'\r\n | 'group.deleteTitle'\r\n | 'group.deleteConfirm'\r\n | 'group.deleteCancel'\r\n | 'group.nameDuplicate'\r\n | 'group.nameReserved'\r\n | 'group.pin'\r\n | 'group.unpin'\r\n | 'group.pinned'\r\n | 'group.appearance'\r\n | 'group.appearanceTitle'\r\n | 'group.appearanceDone'\r\n | 'group.color'\r\n | 'group.colorDefault'\r\n | 'group.icon'\r\n | 'group.iconDefault'\r\n | 'group.iconCustom'\r\n | 'group.iconInvalid'\r\n | 'color.red'\r\n | 'color.orange'\r\n | 'color.amber'\r\n | 'color.green'\r\n | 'color.teal'\r\n | 'color.blue'\r\n | 'color.indigo'\r\n | 'color.purple'\r\n | 'color.pink'\r\n | 'color.gray'\r\n | 'section.topLevel'\r\n | 'manual.saveError'\r\n | 'session.new'\r\n | 'session.rename'\r\n | 'session.archive'\r\n | 'session.fork'\r\n | 'session.renameTitle'\r\n | 'session.renamePlaceholder'\r\n | 'session.renameConfirm'\r\n | 'session.renameCancel'\r\n | 'session.renaming'\r\n | 'uncategorized'\r\n | 'empty.none'\r\n | 'empty.noWorkspaces'\r\n | 'close'\r\n | 'cancel'\r\n | 'confirm'\r\n | 'retry'\r\n | 'configUnavailable'\r\n | 'collapse'\r\n | 'expandMore'\r\n | 'newSession'\r\n | 'quick.title'\r\n | 'quick.tab.workspaces'\r\n | 'quick.tab.sessions'\r\n | 'quick.search.placeholder'\r\n | 'quick.search.sessions'\r\n | 'quick.empty.workspaces'\r\n | 'quick.action.newSession'\r\n | 'quick.action.running'\r\n | 'quick.action.noneRunning'\r\n | 'quick.empty.sessions'\r\n | 'quick.select.hint'\r\n | 'quick.hint'\r\n | 'tabs.aria'\r\n | 'tabs.close'\r\n | 'tabs.archive'\r\n | 'tabs.pin'\r\n | 'tabs.unpin'\r\n | 'tabs.pinned'\r\n | 'tabs.rename'\r\n | 'tabs.renameSession'\r\n | 'tabs.renamePlaceholder'\r\n | 'tabs.closeOthers'\r\n | 'tabs.closeRight'\r\n | 'tabs.dragHint'\r\n\r\nexport type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>\r\n\r\n/** Simplified Chinese dictionary. */\r\nexport const zh: WorkspaceGroupsDict = {\r\n 'section.workspaces': '工作区',\r\n 'section.sessions': '会话',\r\n search: '搜索',\r\n 'search.placeholder': '搜索会话…',\r\n 'search.clear': '清除',\r\n 'search.noMatches': '没有匹配的会话',\r\n 'search.unavailable': '搜索不可用',\r\n 'search.pending': '搜索中…',\r\n 'search.hasMore': '结果过多,请细化关键词',\r\n 'search.results.aria': '搜索结果',\r\n 'workspace.add': '添加工作区',\r\n 'workspace.addBusy': '正在添加…',\r\n 'workspace.addError': '添加失败',\r\n 'workspace.addErrorTitle': '无法添加工作区',\r\n 'workspace.rename': '重命名',\r\n 'workspace.delete': '删除',\r\n 'workspace.deleteTitle': '删除工作区',\r\n 'workspace.deleteConfirm': '仅删除注册信息,目录与会话日志保留。确定删除?',\r\n 'workspace.deleteCancel': '取消删除',\r\n 'workspace.renaming': '重命名中…',\r\n 'workspace.deleting': '删除中…',\r\n 'workspace.renameTitle': '重命名工作区',\r\n 'workspace.renamePlaceholder': '工作区名称',\r\n 'workspace.renameConfirm': '重命名',\r\n 'workspace.renameCancel': '取消',\r\n 'workspace.moveOutOfGroup': '移出分组',\r\n 'workspace.openInFolder': '在文件夹中打开',\r\n 'workspace.openInFolderError': '打开文件夹失败',\r\n 'folder.title': '文件夹',\r\n 'folder.manage': '文件夹…',\r\n 'folder.listAria': '工作区文件夹',\r\n 'folder.base': '基础文件夹',\r\n 'folder.setRoot': '设为根目录',\r\n 'folder.rootBadge': '根目录',\r\n 'folder.remove': '从工作区移除',\r\n 'folder.add': '添加文件夹',\r\n 'folder.done': '完成',\r\n 'folder.duplicate': '该文件夹已在此工作区中',\r\n 'folder.addError': '添加文件夹失败',\r\n 'folder.sessionError': '新建会话失败',\r\n 'folder.saveError': '文件夹保存失败',\r\n 'group.create': '新建分组',\r\n 'group.createTitle': '新建分组',\r\n 'group.createPlaceholder': '分组名称',\r\n 'group.createConfirm': '创建',\r\n 'group.createCancel': '取消',\r\n 'group.rename': '重命名分组',\r\n 'group.renameTitle': '重命名分组',\r\n 'group.renameConfirm': '重命名',\r\n 'group.delete': '删除分组',\r\n 'group.deleteTitle': '删除分组',\r\n 'group.deleteConfirm': '删除后,该分组内的所有项目将移到顶层(不归组)。确定删除?',\r\n 'group.deleteCancel': '取消删除',\r\n 'group.nameDuplicate': '已存在同名分组',\r\n 'group.nameReserved': '该名称不可用',\r\n 'group.pin': '置顶分组',\r\n 'group.unpin': '取消置顶',\r\n 'group.pinned': '已置顶',\r\n 'group.appearance': '颜色与图标…',\r\n 'group.appearanceTitle': '分组外观',\r\n 'group.appearanceDone': '完成',\r\n 'group.color': '颜色',\r\n 'group.colorDefault': '默认',\r\n 'group.icon': '图标',\r\n 'group.iconDefault': '默认图标',\r\n 'group.iconCustom': '自定义字符',\r\n 'group.iconInvalid': '图标需为预设图标或 1–4 个字符',\r\n 'color.red': '红色',\r\n 'color.orange': '橙色',\r\n 'color.amber': '琥珀',\r\n 'color.green': '绿色',\r\n 'color.teal': '青色',\r\n 'color.blue': '蓝色',\r\n 'color.indigo': '靛蓝',\r\n 'color.purple': '紫色',\r\n 'color.pink': '粉色',\r\n 'color.gray': '灰色',\r\n 'section.topLevel': '顶层项目',\r\n 'manual.saveError': '分组变更保存失败',\r\n 'session.new': '新建会话',\r\n 'session.rename': '重命名会话',\r\n 'session.archive': '归档',\r\n 'session.fork': '派生',\r\n 'session.renameTitle': '重命名会话',\r\n 'session.renamePlaceholder': '会话名称',\r\n 'session.renameConfirm': '重命名',\r\n 'session.renameCancel': '取消',\r\n 'session.renaming': '重命名中…',\r\n uncategorized: '未分类',\r\n 'empty.none': '暂无内容',\r\n 'empty.noWorkspaces': '还没有工作区',\r\n close: '关闭',\r\n cancel: '取消',\r\n confirm: '确定',\r\n retry: '重试',\r\n configUnavailable: '分组配置不可用',\r\n collapse: '折叠',\r\n expandMore: '展开全部',\r\n newSession: '新建会话',\r\n 'quick.title': '快速切换',\r\n 'quick.tab.workspaces': '工作区',\r\n 'quick.tab.sessions': '全部会话',\r\n 'quick.search.placeholder': '搜索工作区…',\r\n 'quick.search.sessions': '搜索会话…',\r\n 'quick.empty.workspaces': '没有匹配的工作区',\r\n 'quick.action.newSession': '新建会话',\r\n 'quick.action.running': '切到运行中的会话',\r\n 'quick.action.noneRunning': '没有正在运行的会话',\r\n 'quick.empty.sessions': '还没有会话',\r\n 'quick.select.hint': '在上方选择一个工作区',\r\n 'quick.hint': 'Ctrl+R 开关 · Enter 打开/新建 · Esc 关闭',\r\n 'tabs.aria': '已打开的会话',\r\n 'tabs.close': '关闭标签',\r\n 'tabs.archive': '归档',\r\n 'tabs.pin': '固定标签',\r\n 'tabs.unpin': '取消固定',\r\n 'tabs.pinned': '已固定(关闭其他时保留)',\r\n 'tabs.rename': '重命名标签',\r\n 'tabs.renameSession': '重命名会话…',\r\n 'tabs.renamePlaceholder': '标签名,留空恢复会话标题',\r\n 'tabs.closeOthers': '关闭其他标签',\r\n 'tabs.closeRight': '关闭右侧标签',\r\n 'tabs.dragHint': '拖动可排序',\r\n}\r\n\r\n/** English dictionary. */\r\nexport const en: WorkspaceGroupsDict = {\r\n 'section.workspaces': 'Workspaces',\r\n 'section.sessions': 'Sessions',\r\n search: 'Search',\r\n 'search.placeholder': 'Search sessions…',\r\n 'search.clear': 'Clear',\r\n 'search.noMatches': 'No matching sessions',\r\n 'search.unavailable': 'Search unavailable',\r\n 'search.pending': 'Searching…',\r\n 'search.hasMore': 'Too many results — refine the query',\r\n 'search.results.aria': 'Search results',\r\n 'workspace.add': 'Add workspace',\r\n 'workspace.addBusy': 'Adding…',\r\n 'workspace.addError': 'Add failed',\r\n 'workspace.addErrorTitle': 'Could not add workspace',\r\n 'workspace.rename': 'Rename',\r\n 'workspace.delete': 'Delete',\r\n 'workspace.deleteTitle': 'Delete workspace',\r\n 'workspace.deleteConfirm': 'Only the registration is removed; the directory and session logs stay. Delete?',\r\n 'workspace.deleteCancel': 'Cancel delete',\r\n 'workspace.renaming': 'Renaming…',\r\n 'workspace.deleting': 'Deleting…',\r\n 'workspace.renameTitle': 'Rename workspace',\r\n 'workspace.renamePlaceholder': 'Workspace name',\r\n 'workspace.renameConfirm': 'Rename',\r\n 'workspace.renameCancel': 'Cancel',\r\n 'workspace.moveOutOfGroup': 'Move out of group',\r\n 'workspace.openInFolder': 'Open in folder',\r\n 'workspace.openInFolderError': 'Could not open the folder',\r\n 'folder.title': 'Folders',\r\n 'folder.manage': 'Folders…',\r\n 'folder.listAria': 'Workspace folders',\r\n 'folder.base': 'Base folder',\r\n 'folder.setRoot': 'Set as root',\r\n 'folder.rootBadge': 'Root',\r\n 'folder.remove': 'Remove from workspace',\r\n 'folder.add': 'Add folder',\r\n 'folder.done': 'Done',\r\n 'folder.duplicate': 'That folder is already in this workspace',\r\n 'folder.addError': 'Could not add the folder',\r\n 'folder.sessionError': 'Could not start a session',\r\n 'folder.saveError': 'Could not save folders',\r\n 'group.create': 'New group',\r\n 'group.createTitle': 'New group',\r\n 'group.createPlaceholder': 'Group name',\r\n 'group.createConfirm': 'Create',\r\n 'group.createCancel': 'Cancel',\r\n 'group.rename': 'Rename group',\r\n 'group.renameTitle': 'Rename group',\r\n 'group.renameConfirm': 'Rename',\r\n 'group.delete': 'Delete group',\r\n 'group.deleteTitle': 'Delete group',\r\n 'group.deleteConfirm': 'Deleting removes this group; every project inside it moves to the top level (ungrouped). Delete?',\r\n 'group.deleteCancel': 'Cancel delete',\r\n 'group.nameDuplicate': 'A group with this name already exists',\r\n 'group.nameReserved': 'This name is not available',\r\n 'group.pin': 'Pin group',\r\n 'group.unpin': 'Unpin group',\r\n 'group.pinned': 'Pinned',\r\n 'group.appearance': 'Color & icon…',\r\n 'group.appearanceTitle': 'Group appearance',\r\n 'group.appearanceDone': 'Done',\r\n 'group.color': 'Color',\r\n 'group.colorDefault': 'Default',\r\n 'group.icon': 'Icon',\r\n 'group.iconDefault': 'Default icon',\r\n 'group.iconCustom': 'Custom character',\r\n 'group.iconInvalid': 'Use a preset icon or 1–4 characters',\r\n 'color.red': 'Red',\r\n 'color.orange': 'Orange',\r\n 'color.amber': 'Amber',\r\n 'color.green': 'Green',\r\n 'color.teal': 'Teal',\r\n 'color.blue': 'Blue',\r\n 'color.indigo': 'Indigo',\r\n 'color.purple': 'Purple',\r\n 'color.pink': 'Pink',\r\n 'color.gray': 'Gray',\r\n 'section.topLevel': 'Top-level projects',\r\n 'manual.saveError': 'Could not save group changes',\r\n 'session.new': 'New Session',\r\n 'session.rename': 'Rename session',\r\n 'session.archive': 'Archive',\r\n 'session.fork': 'Fork',\r\n 'session.renameTitle': 'Rename session',\r\n 'session.renamePlaceholder': 'Session name',\r\n 'session.renameConfirm': 'Rename',\r\n 'session.renameCancel': 'Cancel',\r\n 'session.renaming': 'Renaming…',\r\n uncategorized: 'Uncategorized',\r\n 'empty.none': 'Nothing here',\r\n 'empty.noWorkspaces': 'No workspaces yet',\r\n close: 'Close',\r\n cancel: 'Cancel',\r\n confirm: 'Confirm',\r\n retry: 'Retry',\r\n configUnavailable: 'Grouping config unavailable',\r\n collapse: 'Collapse',\r\n expandMore: 'Show all',\r\n newSession: 'New Session',\r\n 'quick.title': 'Quick switch',\r\n 'quick.tab.workspaces': 'Workspaces',\r\n 'quick.tab.sessions': 'All sessions',\r\n 'quick.search.placeholder': 'Search workspaces…',\r\n 'quick.search.sessions': 'Search sessions…',\r\n 'quick.empty.workspaces': 'No matching workspaces',\r\n 'quick.action.newSession': 'New Session',\r\n 'quick.action.running': 'Switch to running session',\r\n 'quick.action.noneRunning': 'No running session',\r\n 'quick.empty.sessions': 'No sessions yet',\r\n 'quick.select.hint': 'Pick a workspace above',\r\n 'quick.hint': 'Ctrl+R toggle · Enter open/new · Esc close',\r\n 'tabs.aria': 'Open sessions',\r\n 'tabs.close': 'Close tab',\r\n 'tabs.archive': 'Archive',\r\n 'tabs.pin': 'Pin tab',\r\n 'tabs.unpin': 'Unpin tab',\r\n 'tabs.pinned': 'Pinned (kept by Close others)',\r\n 'tabs.rename': 'Rename tab',\r\n 'tabs.renameSession': 'Rename session…',\r\n 'tabs.renamePlaceholder': 'Tab name — blank restores the session title',\r\n 'tabs.closeOthers': 'Close other tabs',\r\n 'tabs.closeRight': 'Close tabs to the right',\r\n 'tabs.dragHint': 'Drag to reorder',\r\n}\r\n","/**\r\n * @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated\r\n * view that hangs off it:\r\n *\r\n * The three-level grouped workspace browser into `sidebar.workspaces`,\r\n * shadowing the official ui-workspace browser.\r\n *\r\n * Shadowing mechanics (SlotCore semantics):\r\n * - `sidebar.workspaces` is a `single`/`root` slot. The official browser\r\n * registers at priority 0; this entry registers at priority -1, and the\r\n * single-cell shadow rule makes the LOWEST priority the winner — the\r\n * sidebar renders this browser instead of the official one.\r\n * - This entry deliberately declares NO child slots: the official entry\r\n * already declared `sidebar.workspaces.directoryFlow` (a second declaration\r\n * of an occupied child key throws). Add Workspace is therefore self-\r\n * contained — the shared navigation service + `workspaces.create()`, no\r\n * hole.\r\n *\r\n * The session tab strip is NOT a second registration. It renders into a DOM\r\n * seat at the head of the conversation column (`pI_x6G_centerCol`) because that\r\n * column declares no child slot — its only child is the `main` slot's occupant\r\n * — so there is nowhere to register. See `tab-seat.ts` for the injection and\r\n * `SessionTabs.tsx` for the portal.\r\n *\r\n * Two consequences of that choice, both deliberate:\r\n * - The strip is a CHILD of this entry's component, so it inherits this\r\n * fiber's frame; it needs no injected seam, no cross-entry callback set,\r\n * and the rename dialog stays owned by one place.\r\n * - The tab store is seated by exactly ONE entry. Registering one handle\r\n * under a second, differently-scoped slot throws inside the registry\r\n * (\"one handle, one scope\") and would abort this whole `apply()` — which\r\n * is precisely why the strip does not occupy a slot.\r\n *\r\n * 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从\r\n * `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务\r\n * (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位\r\n * 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该\r\n * 服务,只保留改名、删除、排序、搜索等数据动作。\r\n */\r\nimport type { Context } from '@deepseek-ai/cordis'\r\n// Type-only service merges: sessions/workspaces controllers, the ui-workspace\r\n// navigation service face (ctx.uiWorkspace), locale dictionary seat, the\r\n// SlotRegistry, and the sidebar SlotMap.\r\nimport type {} from '@deepseek-ai/dsh-api-session-controller/client'\r\nimport type {} from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\r\nimport type {} from '@deepseek-ai/dsh-client-ui-renderer/client'\r\nimport type {} from '@deepseek-ai/dsh-client-ui-workspace/client'\r\nimport type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'\r\n// `useWorkspaces` is contributed by the ui-workspace browser domain (same\r\n// declaration as the official ui-workspace client half).\r\nimport type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'\r\nimport type { SessionId } from '@deepseek-ai/dsh-session/types'\r\nimport type { GroupsBrowserInjected } from './contract.ts'\r\nimport { createGroupsViewStore } from './stores.ts'\r\nimport { createSessionTabsStore } from './tab-store.ts'\r\nimport { loadTabs, saveTabs } from './tab-persist.ts'\r\nimport { createStoreHook } from './store-hook.ts'\r\nimport { shouldOpenTab, type TabOpenMode } from './tabs.ts'\r\nimport { GroupsBrowser } from './GroupsBrowser.tsx'\r\nimport { en, zh, type WorkspaceGroupsKey } from './locales.ts'\r\n\r\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\r\n interface LocaleNamespaceMap {\r\n /** The workspace-groups browsing region copy. */\r\n workspaceGroups: WorkspaceGroupsKey\r\n }\r\n\r\n interface GlobalStandardProps {\r\n /** Selector hook over the pure Workspace Controller snapshot. */\r\n useWorkspaces: SnapshotSelectorHook\r\n }\r\n}\r\n\r\n/** Dictionary namespace owned by this plugin. */\r\nconst NS = 'workspaceGroups'\r\n\r\n/**\r\n * Tab visibility policy. `auto` is the behaviour the feature was asked for —\r\n * opening a session that has no tab yet adds one at the front of the strip;\r\n * `manual` leaves the strip to callers that drive `openTab` themselves.\r\n */\r\nconst TAB_OPEN_MODE: TabOpenMode = 'auto'\r\n\r\n/**\r\n * Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`\r\n * is the shipped navigation face this entry delegates selection to.\r\n */\r\nexport const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']\r\n\r\n/**\r\n * Register the grouped browser once the sidebar slot declaration is on the\r\n * ledger. Inject factory returns plain callbacks; data reads use the\r\n * framework's global hooks.\r\n * @param ctx - client root context.\r\n */\r\nexport function apply(ctx: Context): void {\r\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), '@dsh-xhl/workspace-groups: dictionaries')\r\n\r\n // ONE store, ONE scope. The tab store is seated only by the\r\n // `sidebar.workspaces` entry below (scope root); the strip reads it as a\r\n // plain prop because it renders as a CHILD of that entry through a DOM\r\n // portal, not as a second slot occupant. Seating the same handle under a\r\n // session-scoped slot as well throws inside the registry\r\n // (one handle, one scope) and would abort this whole apply().\r\n const tabsStore = createSessionTabsStore()\r\n const tabInstance = tabsStore.create()\r\n const tabWrites = tabInstance.actions\r\n\r\n // Persist the strip on the HOST, not in browser storage: the origin includes\r\n // the port and every launch picks a new one, so localStorage/sessionStorage\r\n // both start empty next time.\r\n //\r\n // Writes are GATED until the initial restore has settled. The store starts\r\n // empty and the browser's own effects run before the host read resolves, so an\r\n // ungated subscriber would write that empty state over the stored tabs —\r\n // erasing exactly what it was supposed to restore. `hydrated` is the latch.\r\n let hydrated = false\r\n ctx.effect(() => {\r\n const stop = tabInstance.subscribe(() => {\r\n if (!hydrated) return\r\n void saveTabs({\r\n order: tabInstance.getSnapshot().order,\r\n tabs: tabInstance.getSnapshot().tabs,\r\n })\r\n })\r\n return () => { stop() }\r\n }, '@dsh-xhl/workspace-groups: tab persistence')\r\n\r\n // Hydrate once from the host, then open the write gate.\r\n //\r\n // `restore` is a no-op if the user already opened a tab while this was in\r\n // flight, so a slow response cannot discard live work. The settle deliberately\r\n // does NOT write: writing the strip here would erase the stored tabs whenever\r\n // the read came back empty for a transient reason (host still booting, a\r\n // dropped request). Only a real state CHANGE persists, via the subscriber.\r\n ctx.effect(() => {\r\n let cancelled = false\r\n void loadTabs().then((tabs) => {\r\n if (cancelled) return\r\n if (tabs.length > 0) {\r\n tabWrites.restore(tabs.map(tab => ({\r\n sessionId: tab.sessionId as SessionId,\r\n order: tab.order,\r\n ...(tab.pinned === true ? { pinned: true } : {}),\r\n ...(tab.title !== undefined ? { title: tab.title } : {}),\r\n })))\r\n }\r\n hydrated = true\r\n }).catch(() => {\r\n // The read failed; leave the gate open so the user's own actions persist,\r\n // but never write on the strength of a failed read.\r\n if (!cancelled) hydrated = true\r\n })\r\n return () => { cancelled = true }\r\n }, '@dsh-xhl/workspace-groups: tab restore')\r\n\r\n const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {\r\n const result = await ctx.sessions.search(query, signal)\r\n if (!result.ok) throw new Error(result.error.message)\r\n return result.value\r\n }\r\n\r\n const browserInjected = (): GroupsBrowserInjected => ({\r\n // Navigation verbs belong to the shipped ui-workspace service: it owns the\r\n // retained `mainView` selection, supersession and pending-navigation\r\n // cancellation (0.1.6 moved them out of `ctx.sessions`).\r\n startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },\r\n // Folder rows create a real Session rooted in that folder. `cwd` stays out\r\n // of the call for the base folder (the Workspace's canonical directory),\r\n // where the controller already defaults to `WorkspaceView.path`.\r\n createSessionIn: async (workspaceId, cwd) => {\r\n const sessionId = await ctx.sessions.create({\r\n workspaceId,\r\n ...(cwd === undefined ? {} : { cwd }),\r\n })\r\n ctx.uiWorkspace.openSession(sessionId)\r\n return sessionId\r\n },\r\n open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },\r\n forkSession: (sessionId) => {\r\n ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {\r\n console.warn('fork session failed:', reason)\r\n })\r\n },\r\n archiveSession: async (sessionId) => {\r\n await ctx.uiWorkspace.archiveSession(sessionId)\r\n // The tab is deliberately LEFT ALONE. Archiving hides the session from the\r\n // grouped surfaces, but a tab is something the user opened, and the rule\r\n // for this strip is that only they close one — an automatic close here\r\n // would silently drop work they were keeping an eye on. The chip keeps\r\n // rendering (falling back to the session id when the title no longer\r\n // resolves).\r\n },\r\n pickDirectory: () => ctx.uiWorkspace.pickDirectory(),\r\n searchSessions,\r\n searchResultLimit: ctx.sessions.searchResultLimit,\r\n // Directory-flow hole occupancy. The official ui-workspace browser gates\r\n // its \"Add workspace…\" affordance on the hole being occupied (the shipped\r\n // picker package's client half fills it); this browser drives the picker\r\n // itself through `pickDirectory`, so it must keep the hole occupied or the\r\n // official entry (still live at priority 0) would silently withdraw the\r\n // affordance.\r\n hooks: {\r\n directoryFlow: {\r\n getSnapshot: () => true,\r\n subscribe: () => () => {},\r\n },\r\n },\r\n // Data-only verbs stay on the controllers.\r\n renameSession: async (sessionId, title) => {\r\n const session = ctx.sessions.binding(sessionId)?.session\r\n if (session === undefined) throw new Error(`unknown session \"${sessionId}\"`)\r\n const result = await session.rename(title)\r\n if (!result.ok) throw new Error(result.error.message)\r\n },\r\n renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },\r\n deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },\r\n insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {\r\n await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)\r\n },\r\n insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {\r\n await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)\r\n },\r\n createWorkspace: input => ctx.workspaces.create(input),\r\n // \"Show a tab for what I just opened\" — but only while it is actually in\r\n // play. The browser decides per session (see `shouldOpenTab`): a draft that\r\n // has not been talked to, and settled history, both stay out of the strip.\r\n // The status arrives from the caller because it is a live UI fact read\r\n // through a hook, which this (non-React) factory cannot reach.\r\n openTab: (sessionId, status) => {\r\n const summary = ctx.sessions.list.getSnapshot().byId[sessionId]\r\n if (shouldOpenTab(TAB_OPEN_MODE, summary, status)) tabWrites.touch(sessionId)\r\n },\r\n // The strip rides this entry's own store seat, so it needs both faces\r\n // explicitly: a selector hook over the one live instance, and the baked\r\n // writes. Both come from the same instance the browser writes through.\r\n useTabs: createStoreHook(tabInstance),\r\n tabActions: tabWrites,\r\n })\r\n\r\n // priority: -1 — lower than the official browser's default 0, so the\r\n // single-slot shadow rule elects this entry. No children declaration: the\r\n // official entry already owns `sidebar.workspaces.directoryFlow`.\r\n //\r\n // The official WorkspaceBrowser entry is NEVER disposed — shadowing only\r\n // changes which entry renders (activation just bumps the store's mount\r\n // count). Both entries live at the same cell, so if this one ever throws\r\n // during render the slot core retires it for the rest of its registration's\r\n // life and silently falls back to the official browser. Anything that can\r\n // throw belongs outside the hot path.\r\n ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(\r\n {\r\n name: 'sidebar.workspaces',\r\n priority: -1,\r\n store: createGroupsViewStore(),\r\n inject: browserInjected,\r\n locale: NS,\r\n registrant: '@dsh-xhl/workspace-groups',\r\n },\r\n GroupsBrowser,\r\n ))\r\n}\r\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,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C3E,MAAM,SAAS,MAAM,QAAQ,OAAO,KAAK;KACzC,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,MAAM,OAAO,MAAM,OAAO;IACtD;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,qBAAqB,OAAO,aAAa,WAAW,oBAAoB;KACtE,MAAM,IAAI,WAAW,oBAAoB,aAAa,WAAW,eAAe;IAClF;IACA,kBAAiB,UAAS,IAAI,WAAW,OAAO,KAAK;IAMrD,UAAU,WAAW,WAAW;KAC9B,MAAM,UAAU,IAAI,SAAS,KAAK,YAAY,CAAC,CAAC,KAAK;KACrD,IAAI,cAAc,eAAe,SAAS,MAAM,GAAG,UAAU,MAAM,SAAS;IAC9E;IAIA,SAAS,gBAAgB,WAAW;IACpC,YAAY;GACd;GAYA,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 41be719..8297439 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2897,6 +2897,255 @@ function documentForTabs(state) { }; } //#endregion +//#region src/core/folders.ts +/** Canonical empty document, shared so callers need not allocate one each time. */ +const EMPTY_FOLDERS_DOCUMENT = { + version: 1, + workspaces: {} +}; +/** `C:\…` or `C:/…` — a drive-rooted Windows path. */ +const WINDOWS_DRIVE$1 = /^[A-Za-z]:[\\/]/u; +/** `\\server\share` — a Windows UNC path. */ +const WINDOWS_UNC$1 = /^\\\\/u; +/** True for both Windows path spellings accepted by the write validator. */ +function isWindowsStyle(path) { + return WINDOWS_DRIVE$1.test(path) || WINDOWS_UNC$1.test(path); +} +/** +* Comparison form of one path: trimmed, separator-normalized and, for Windows +* spellings, lower-cased (drive letters and file names are case-insensitive +* there). Trailing separators are dropped except for a drive/UNC/root prefix. +* @param path - raw path as stored or picked. +* @returns the canonical comparison form. +*/ +function canonicalPath(path) { + const trimmed = path.trim(); + if (isWindowsStyle(trimmed)) { + let value = trimmed.replaceAll("/", "\\").toLowerCase(); + while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1); + return value; + } + let value = trimmed; + while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1); + return value; +} +/** +* Path equality: case-insensitive for Windows-style paths, tolerant of +* trailing separators, exact for POSIX paths. +* @param a - first path. +* @param b - second path. +*/ +function samePath(a, b) { + return canonicalPath(a) === canonicalPath(b); +} +//#endregion +//#region src/host-folders.ts +/** +* Folder overlay for @dsh-xhl/workspace-groups: the per-workspace list of +* EXTRA folders plus the designated root folder. Stored in a plugin-owned JSON +* sidecar (`$DSH_HOME/workspace-groups.folders.json`), next to the manual +* grouping overlay, because neither DSH core nor the YAML rule source knows +* about folders: core gives a workspace exactly one canonical directory and the +* YAML stays the classification source. +* +* Writes are strict (the browser PUT route validates the whole document before +* replacing it, atomically: temp file + fsync + rename) and reads tolerate +* hand-edited content (junk entries are dropped instead of thrown), for the +* same reason the manual overlay does: a stale or malformed sidecar must never +* freeze the tree. +*/ +/** File name of the folder sidecar (also the stable error-text prefix). */ +const FOLDERS_FILE_NAME = "workspace-groups.folders.json"; +const FOLDER_PATH_LIMIT = 1024; +/** `C:\…` or `C:/…` — a drive-rooted Windows path. */ +const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u; +/** `\\server\share` — a Windows UNC path. */ +const WINDOWS_UNC = /^\\\\/u; +/** `/…` — a POSIX absolute path. */ +const POSIX_ABSOLUTE = /^\//u; +/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */ +function defaultFoldersPath() { + const home = process.env.DSH_HOME !== void 0 && process.env.DSH_HOME !== "" ? process.env.DSH_HOME : resolve(homedir(), ".dsh"); + return resolve(home, FOLDERS_FILE_NAME); +} +/** +* True when `path` is absolute in the host platform's spelling: a drive +* letter or UNC prefix on Windows, a leading slash elsewhere. +* @param path - candidate path. +*/ +function isAbsoluteFolderPath(path) { + return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path); +} +/** Reject helper carrying the stable file-scoped message prefix. */ +function invalid(detail) { + throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`); +} +/** +* Parse one workspace entry. +* @param value - raw entry from the document. +* @param workspaceId - owning workspace id (used in messages). +* @param strict - throw on the first problem, or drop junk and return undefined. +* @returns the normalized entry, or undefined when nothing usable remains. +*/ +function parseFolderEntry(value, workspaceId, strict) { + const fail = (detail) => { + if (strict) invalid(`workspace "${workspaceId}": ${detail}`); + }; + if (typeof value !== "object" || value === null || Array.isArray(value)) { + fail("entry must be an object"); + return; + } + const source = value; + if (source.folders === void 0) { + fail("folders is required"); + return; + } + if (!Array.isArray(source.folders)) { + fail("folders must be a list"); + return; + } + if (strict && source.folders.length > 32) invalid(`workspace "${workspaceId}": at most 32 folders`); + const folders = []; + for (const candidate of source.folders) { + if (typeof candidate !== "string") { + fail("folder paths must be strings"); + continue; + } + const path = candidate.trim(); + if (path === "") { + fail("folder paths must be non-empty"); + continue; + } + if (path.includes("\0")) { + fail(`folder path "${path}" contains a NUL character`); + continue; + } + if (path.length > 1024) { + fail(`folder path exceeds ${FOLDER_PATH_LIMIT} characters`); + continue; + } + if (!isAbsoluteFolderPath(path)) { + fail(`folder path "${path}" must be absolute`); + continue; + } + if (folders.some((existing) => samePath(existing, path))) { + fail(`duplicate folder path "${path}"`); + continue; + } + if (folders.length >= 32) { + fail(`at most 32 folders`); + break; + } + folders.push(path); + } + let root; + if (source.root !== void 0) { + if (typeof source.root !== "string") fail("root must be a string"); + else { + const candidate = source.root.trim(); + const member = folders.find((folder) => samePath(folder, candidate)); + if (member === void 0) fail(`root "${candidate}" must name one of folders`); + else root = member; + } + } + if (folders.length === 0 && root === void 0) return void 0; + return { + folders, + ...root === void 0 ? {} : { root } + }; +} +/** +* Tolerant reader: shape-normalizes whatever was on disk and drops unusable +* workspaces, folders and roots instead of throwing. A missing, non-mapping or +* unknown-version document yields the empty document. +* @param raw - parsed JSON value. +*/ +function parseFoldersDocument(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return EMPTY_FOLDERS_DOCUMENT; + const source = raw; + if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT; + if (typeof source.workspaces !== "object" || source.workspaces === null || Array.isArray(source.workspaces)) return { + version: 1, + workspaces: {} + }; + const workspaces = {}; + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + if (workspaceId.trim() === "" || workspaceId.length > 200) continue; + const entry = parseFolderEntry(value, workspaceId, false); + if (entry !== void 0) workspaces[workspaceId] = entry; + } + return { + version: 1, + workspaces + }; +} +/** +* Strict writer-side validation. Every rule is enforced and the first problem +* throws, so the PUT route rejects instead of persisting a half-valid file. +* @param raw - parsed JSON value from the request body. +* @returns the normalized document to save. +* @throws when version, workspace ids, folder paths, duplicates or the root +* membership are wrong. +*/ +function validateFoldersDocument(raw) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) invalid("top-level value must be a mapping"); + const source = raw; + if (source.version !== 1) invalid("version must be 1"); + if (typeof source.workspaces !== "object" || source.workspaces === null || Array.isArray(source.workspaces)) invalid("workspaces must be a mapping"); + const workspaces = {}; + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + if (workspaceId.trim() === "" || workspaceId.length > 200) invalid(`workspace ids must be non-empty strings of at most 200 characters`); + const entry = parseFolderEntry(value, workspaceId, true); + if (entry !== void 0) workspaces[workspaceId] = entry; + } + return { + version: 1, + workspaces + }; +} +/** +* Read + tolerate the overlay file. A missing or unreadable file yields the +* empty document: folders are a convenience, and a broken sidecar must not take +* the tree down with it. +* @param path - overlay file path. +*/ +async function readFoldersDocument(path) { + try { + const text = await readFile(path, "utf8"); + return parseFoldersDocument(JSON.parse(text)); + } catch { + return EMPTY_FOLDERS_DOCUMENT; + } +} +/** +* 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 document - validated document to persist. +*/ +async function writeFoldersDocument(path, document) { + const json = `${JSON.stringify(document, 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-xhl/workspace-groups"; @@ -2965,6 +3214,7 @@ function apply(ctx) { const configPath = defaultConfigPath(); const manualPath = defaultManualPath(); const tabsPath = defaultTabsPath(); + const foldersPath = defaultFoldersPath(); ctx.effect(() => ctx.webServer.register({ kind: "exact", path: "/workspace-groups/config", @@ -3084,6 +3334,54 @@ function apply(ctx) { res.end(body); } }), "@dsh-xhl/workspace-groups: /workspace-groups/manual route"); + ctx.effect(() => ctx.webServer.register({ + kind: "exact", + path: "/workspace-groups/folders", + handler: async (req, res) => { + if (req.method === "GET" || req.method === "HEAD") { + const document = await readFoldersDocument(foldersPath); + const body = JSON.stringify(document); + res.writeHead(200, { + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-store", + "Content-Length": Buffer.byteLength(body) + }); + res.end(req.method === "HEAD" ? void 0 : body); + return; + } + 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 document; + try { + document = validateFoldersDocument(raw); + } catch (error) { + writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`); + return; + } + try { + await writeFoldersDocument(foldersPath, document); + } catch (error) { + writeError(res, 500, `workspace-groups: failed to write folder overlay: ${error instanceof Error ? error.message : String(error)}`); + return; + } + const body = JSON.stringify(document); + res.writeHead(200, { + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-store", + "Content-Length": Buffer.byteLength(body) + }); + res.end(body); + } + }), "@dsh-xhl/workspace-groups: /workspace-groups/folders route"); } //#endregion export { apply, inject, name }; diff --git a/lib/types/client/GroupsBrowser.d.ts b/lib/types/client/GroupsBrowser.d.ts index 6996987..b0b86e3 100644 --- a/lib/types/client/GroupsBrowser.d.ts +++ b/lib/types/client/GroupsBrowser.d.ts @@ -30,4 +30,4 @@ export type DragIndicator = { * @param props - composed slot props (shell owner share + store + injected actions). * @returns the region element tree. */ -export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element; +export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element; diff --git a/lib/types/client/contract.d.ts b/lib/types/client/contract.d.ts index 7640121..4e47c19 100644 --- a/lib/types/client/contract.d.ts +++ b/lib/types/client/contract.d.ts @@ -30,6 +30,11 @@ export type GroupsBrowserInjected = { }; /** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */ startSession: (workspaceId?: WorkspaceId) => void; + /** + * Create a real Session in one folder of a Workspace and open it. `cwd` is + * omitted for the base folder (the Workspace's own canonical directory). + */ + createSessionIn: (workspaceId: WorkspaceId, cwd?: string) => Promise; /** Open a real Session. */ open: (sessionId: SessionId) => void; /** Search current visible conversation messages. */ diff --git a/lib/types/client/folders-persist.d.ts b/lib/types/client/folders-persist.d.ts new file mode 100644 index 0000000..cae775f --- /dev/null +++ b/lib/types/client/folders-persist.d.ts @@ -0,0 +1,33 @@ +/** + * Client side of the per-workspace folder list, talking to + * `GET|PUT /workspace-groups/folders` on the host. + * + * The document is the host's JSON sidecar verbatim (`version` + `workspaces`), + * so the client and the host agree on one shape: `folders` holds EXTRA folders + * only — the workspace's canonical directory is implicit folder #0 — and + * `root` names one of those extras (absent means "the workspace itself"). + * + * Reads are best-effort, like the manual overlay and the tab strip: a failed + * read means "no extra folders". A failed write, however, rejects so the caller + * can say so — a folder row that silently forgot its edit would be worse than + * the toast. + */ +import { type FoldersDocument } from '../core/folders.ts'; +/** Host route holding the folder overlay. */ +export declare const FOLDERS_ROUTE = "/workspace-groups/folders"; +/** + * Fetch the stored folder overlay. + * @param fetchImpl - fetch implementation (injectable for tests). + * @returns the document; the empty document on any failure. + */ +export declare function loadFolders(fetchImpl?: typeof fetch): Promise; +/** + * Store the whole folder overlay. + * + * Unlike the tab strip this does NOT swallow failures: folder edits are explicit + * row/dialog actions, so the caller turns a rejection into a toast instead of + * leaving the user with a row that silently forgot its folder. + * @param document - the client's current document. + * @param fetchImpl - fetch implementation (injectable for tests). + */ +export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise; diff --git a/lib/types/client/locales.d.ts b/lib/types/client/locales.d.ts index 720bee6..b33e624 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' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint'; +export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint'; export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>; /** Simplified Chinese dictionary. */ export declare const zh: WorkspaceGroupsDict; diff --git a/lib/types/client/rows.d.ts b/lib/types/client/rows.d.ts index 783a512..2b37e76 100644 --- a/lib/types/client/rows.d.ts +++ b/lib/types/client/rows.d.ts @@ -11,7 +11,7 @@ import { type DragEvent, type ReactNode } 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'; +import type { CategoryNode, FolderNode, 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"; @@ -65,7 +65,7 @@ export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, onT 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, canMoveOut, onMoveOut, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: { +export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, onManageFolders, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: { node: WorkspaceGroupNode; t: T; onToggle: () => void; @@ -75,6 +75,8 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename /** Project currently sits inside a group — offer "move out of group". */ canMoveOut?: boolean; onMoveOut?: () => void; + /** Open the folder-management dialog (extra folders + root). */ + onManageFolders?: () => void; /** * Open the project directory in the host's file manager. Omitted when the * host resolved no folder application (no capability, or a remote launch), @@ -86,6 +88,28 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename /** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */ onDragStartExtra?: () => void; } & RowDropProps): import("react").JSX.Element; +/** + * One folder row under a project: the base directory (folder #0) plus every + * extra folder of that workspace. Sits at the session indent level so the + * 42/58/74 ladder is preserved, and its own session rows indent one step + * deeper (see `.wgSessionNested`). + * + * Deliberately NOT a drag source or drop target: folders are a fixed, + * host-ordered list; reordering them would need a write path this feature does + * not have. + */ +export declare function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating }: { + node: FolderNode; + t: T; + onToggle: () => void; + onNewSession: () => void; + onSetRoot: () => void; + onRemove: () => void; + /** Absent when the host resolved no folder application. */ + onOpenInFolder?: () => void; + /** A session is being created here: the hover + stays disabled. */ + creating?: boolean; +}): import("react").JSX.Element; /** * Children container for one folder's rows. * @@ -119,7 +143,7 @@ export declare function RowGroup({ expanded, className, animate, children }: { children: ReactNode; }): JSX.Element | null; /** One session leaf row. */ -export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: { +export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested }: { node: SessionNode; currentId: string | undefined; now: number; @@ -128,5 +152,7 @@ export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onRename: (id: SessionNode['id'], currentTitle: string) => void; onFork: (id: SessionNode['id']) => void; onArchive: (id: SessionNode['id']) => void; + /** Rendered under a folder row: one indent step deeper than a plain session. */ + nested?: boolean; }): import("react").JSX.Element; export type { T }; diff --git a/lib/types/client/tree.d.ts b/lib/types/client/tree.d.ts index 28694d6..e3c323d 100644 --- a/lib/types/client/tree.d.ts +++ b/lib/types/client/tree.d.ts @@ -8,6 +8,7 @@ import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'; import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'; import type { SessionId } from '@deepseek-ai/dsh-session/types'; +import { type FoldersDocument } from '../core/folders.ts'; import { type CategoryAppearance, type GroupsConfig, type ManualGroups } from '../core/types.ts'; /** Pending interaction kinds with dedicated Workspace-row presentation. */ export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question'; @@ -42,6 +43,20 @@ export interface SessionNode { /** Content-match snippet from the Host search (search mode only). */ snippet?: string; } +/** One folder row inside a workspace folder (base or extra). */ +export interface FolderNode { + /** Absolute folder path. */ + path: string; + /** Display label: last path segment, or the whole path for drive roots. */ + label: string; + /** The workspace's default target for new sessions (★). */ + isRoot: boolean; + expanded: boolean; + /** The workspace's own canonical directory (folder #0); cannot be removed. */ + isBase: boolean; + /** Visible sessions whose recorded cwd lives inside this folder. */ + sessions: readonly SessionNode[]; +} /** One workspace folder row inside a category folder. */ export interface WorkspaceGroupNode { workspaceId: WorkspaceId; @@ -51,13 +66,19 @@ export interface WorkspaceGroupNode { label: string; /** Workspace creation time (epoch ms). */ createdAt: number; - /** Total visible sessions in the folder. */ + /** Total visible sessions in the folder (every folder included). */ sessionCount: number; expanded: boolean; /** The folder contains the selected session (active folder tint). */ containsCurrent: boolean; - /** Visible session rows (empty while the folder is folded). */ + /** Base-owned visible session rows (empty while the folder is folded). */ sessions: readonly SessionNode[]; + /** + * Folder rows, present only when the workspace carries at least one extra + * folder: root first, then stored order, base included. Absent means "this + * workspace has exactly one directory", the plain pre-folders node shape. + */ + folders?: readonly FolderNode[]; } /** One category folder at the top of the tree. */ export interface CategoryNode { @@ -77,11 +98,25 @@ export interface CategoryNode { export interface GroupsTreeView { expandedCategories: readonly string[]; expandedWorkspaces: readonly string[]; + /** + * Collapsed folder rows, keyed by `folderKey(workspaceId, path)`. Folders are + * expanded by default: adding a folder must never hide the sessions that used + * to show flat under the project. + */ + collapsedFolders?: readonly string[]; } /** Key of the uncategorized bucket (matches the config fallback label). */ export declare const UNCATEGORIZED_KEY = "\u672A\u5206\u7C7B"; /** Directory display label: basename of the path (both separators accepted). */ export declare function workspaceLabel(cwd: string | undefined): string; +/** + * Display label of one folder: the last path segment. A drive root (`C:\`) or + * the POSIX root has no segment, so the whole path is the honest label. + * @param path - absolute folder path. + */ +export declare function folderLabel(path: string): string; +/** Stable identity of one folder row (same path may live under two workspaces). */ +export declare function folderKey(workspaceId: WorkspaceId, path: string): string; /** * Derive the three-level tree. * @param list - sessions list snapshot (`current` feeds containsCurrent). @@ -93,11 +128,14 @@ export declare function workspaceLabel(cwd: string | undefined): string; * manual override wins over rule classification; removing it reverts to rules. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root. A workspace with extras + * gains folder rows and its extra-folder sessions move under them; a workspace + * without extras keeps exactly the pre-folders node shape. * @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, manual: ManualGroups, statuses?: SessionStatuses): CategoryNode[]; +export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): CategoryNode[]; /** * Top-level (ungrouped) workspace rows: workspaces resolving to no category * (no manual override and no matching rule, or a forced `null` override). @@ -105,7 +143,7 @@ export declare function deriveGroups(list: SessionListState, workspaces: readonl * folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`), * falling back to host registration order. */ -export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses): WorkspaceGroupNode[]; +export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode[]; /** 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). */ @@ -147,8 +185,10 @@ export interface SearchTree { * @param snippetsBySession - optional content-match snippets keyed by session id. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root, so a hit inside an extra + * folder surfaces under that folder instead of flat under the project. * @returns group folders in render order plus top-level matched workspaces, * pruned to matched branches only. */ -export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap, statuses?: SessionStatuses): SearchTree; +export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap, statuses?: SessionStatuses, folders?: FoldersDocument): SearchTree; export {}; diff --git a/lib/types/core/folders.d.ts b/lib/types/core/folders.d.ts new file mode 100644 index 0000000..69ac77a --- /dev/null +++ b/lib/types/core/folders.d.ts @@ -0,0 +1,91 @@ +/** + * Pure folder-list logic for per-workspace multi-root folders. + * + * DSH core gives a workspace exactly ONE canonical directory + * (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA + * folders on top of it, plus one designated root folder per workspace: + * + * - the canonical directory is always folder #0 (the "base"); it cannot be + * removed and may be the root; + * - `root` is stored only when it names an EXTRA folder — "base is the root" + * is expressed by omitting the key, so the base path is never duplicated + * into the sidecar; + * - a session whose recorded `cwd` lives inside an extra folder belongs to + * that folder, not to the project row. + * + * Everything here is pure and platform-agnostic: it imports no React, no DOM + * and no cordis so plain Node (the verifier, the host route) can load it. + */ +/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */ +export interface WorkspaceFolderEntry { + readonly folders: readonly string[]; + readonly root?: string; +} +/** The whole `workspace-groups.folders.json` document. */ +export interface FoldersDocument { + readonly version: 1; + readonly workspaces: Readonly>; +} +/** Canonical empty document, shared so callers need not allocate one each time. */ +export declare const EMPTY_FOLDERS_DOCUMENT: FoldersDocument; +/** + * Path equality: case-insensitive for Windows-style paths, tolerant of + * trailing separators, exact for POSIX paths. + * @param a - first path. + * @param b - second path. + */ +export declare function samePath(a: string, b: string): boolean; +/** + * Look up the folder entry saved for one workspace. + * @param doc - folders document. + * @param workspaceId - host workspace id. + * @returns the entry, or undefined when the workspace has none. + */ +export declare function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined; +/** + * The workspace's effective folder list, base first. The base cannot be + * duplicated and blank extra entries are dropped. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + */ +export declare function effectiveFolders(workspacePath: string, entry: WorkspaceFolderEntry | undefined): readonly string[]; +/** + * The folder new sessions start in by default. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the stored root when it names an effective extra folder, else the + * workspace's own directory. + */ +export declare function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string; +/** + * Owning folder of a session cwd: the most specific (longest) effective folder + * that equals the cwd or is a proper path ancestor of it. + * @param cwd - recorded session cwd; undefined means "the workspace itself". + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the owning folder, or the workspace path when nothing matches. + */ +export declare function folderOfCwd(cwd: string | undefined, workspacePath: string, entry: WorkspaceFolderEntry | undefined): string; +/** + * Append an extra folder. Idempotent under `samePath`, and the stored root (if + * any) survives untouched. + * @param entry - current entry, or undefined for a workspace with no extras. + * @param path - folder path to append. + */ +export declare function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry; +/** + * Drop an extra folder. A root that pointed at it is cleared, so the workspace + * falls back to its own directory instead of referencing a folder it no longer + * has. + * @param entry - current entry, or undefined. + * @param path - folder path to drop. + */ +export declare function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry; +/** + * Designate the root folder. Only an extra folder can be stored: naming the + * base directory means "no explicit root", which is represented by clearing + * the key. + * @param entry - current entry, or undefined. + * @param path - folder to make the root. + */ +export declare function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry; diff --git a/lib/types/host-folders.d.ts b/lib/types/host-folders.d.ts new file mode 100644 index 0000000..a2ca889 --- /dev/null +++ b/lib/types/host-folders.d.ts @@ -0,0 +1,46 @@ +import { type FoldersDocument } from './core/folders.ts'; +/** File name of the folder sidecar (also the stable error-text prefix). */ +export declare const FOLDERS_FILE_NAME = "workspace-groups.folders.json"; +/** Hard limits enforced at the write boundary. */ +export declare const FOLDERS_PER_WORKSPACE_LIMIT = 32; +export declare const WORKSPACE_ID_LIMIT = 200; +export declare const FOLDER_PATH_LIMIT = 1024; +/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */ +export declare function defaultFoldersPath(): string; +/** + * True when `path` is absolute in the host platform's spelling: a drive + * letter or UNC prefix on Windows, a leading slash elsewhere. + * @param path - candidate path. + */ +export declare function isAbsoluteFolderPath(path: string): boolean; +/** + * Tolerant reader: shape-normalizes whatever was on disk and drops unusable + * workspaces, folders and roots instead of throwing. A missing, non-mapping or + * unknown-version document yields the empty document. + * @param raw - parsed JSON value. + */ +export declare function parseFoldersDocument(raw: unknown): FoldersDocument; +/** + * Strict writer-side validation. Every rule is enforced and the first problem + * throws, so the PUT route rejects instead of persisting a half-valid file. + * @param raw - parsed JSON value from the request body. + * @returns the normalized document to save. + * @throws when version, workspace ids, folder paths, duplicates or the root + * membership are wrong. + */ +export declare function validateFoldersDocument(raw: unknown): FoldersDocument; +/** + * Read + tolerate the overlay file. A missing or unreadable file yields the + * empty document: folders are a convenience, and a broken sidecar must not take + * the tree down with it. + * @param path - overlay file path. + */ +export declare function readFoldersDocument(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 document - validated document to persist. + */ +export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise; diff --git a/src/client/GroupsBrowser.tsx b/src/client/GroupsBrowser.tsx index 14b40a1..a9abf43 100644 --- a/src/client/GroupsBrowser.tsx +++ b/src/client/GroupsBrowser.tsx @@ -1,7 +1,7 @@ /** * The workspace-groups browsing region filling the sidebar shell's * `sidebar.workspaces` hole: section header (title + right-aligned search + - * new-group + add workspace), the three-level tree (category → workspace → + * 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 @@ -21,6 +21,7 @@ import { IconFolderOpenOutlineRegular, IconProjectAddOutlineRegular, IconSearchOutlineRegular, + IconTrashOutlineRegular, IconWarningOutlineRegular, Modal, Toast, @@ -51,9 +52,11 @@ import { type ManualGroups, } from '../core/types.ts' import type { GroupsBrowserProps } from './contract.ts' -import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts' -import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx' +import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts' +import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx' import type { WorkspaceGroupsKey } from './locales.ts' +import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts' +import { loadFolders, saveFolders } from './folders-persist.ts' import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts' import { QuickPanel } from './QuickPanel.tsx' import { SessionTabs } from './SessionTabs.tsx' @@ -101,7 +104,7 @@ function categoryRowCount(category: CategoryNode): number { return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0) } -/** Palette id → i18n key for the colour picker (keeps literal key types intact). */ +/** Palette id — i18n key for the colour picker (keeps literal key types intact). */ const COLOR_LABEL_KEYS: Record = { red: 'color.red', orange: 'color.orange', @@ -205,6 +208,7 @@ export function GroupsBrowser({ useStore, actions, startSession, + createSessionIn, open, renameSession, forkSession, @@ -265,6 +269,30 @@ export function GroupsBrowser({ const [manualError, setManualError] = useState(null) const [manualSaving, setManualSaving] = useState(false) + // ---- Per-workspace folders (multi-root) ------------------------------------- + // + // A second host sidecar (`/workspace-groups/folders`) lists each workspace's + // extra folders plus the optional root folder. It is read once per mount and + // written back whole, like the manual overlay above; a failed write is a + // toast rather than a banner because every edit here is a one-off row action. + const [foldersDoc, setFoldersDoc] = useState(EMPTY_FOLDERS_DOCUMENT) + // Folder collapse is component state, not store state: it is a transient view + // of the row list, like the quick panel, so it is deliberately NOT persisted + // with the category/workspace expansion keys. Folders start expanded, so + // attaching a folder never hides sessions the user could already see. + const [collapsedFolderKeys, setCollapsedFolderKeys] = useState([]) + const [foldersTarget, setFoldersTarget] = useState(null) + const [foldersBusy, setFoldersBusy] = useState(false) + const [creatingSessionIn, setCreatingSessionIn] = useState(null) + useEffect(() => { + let cancelled = false + void loadFolders().then((document) => { + if (cancelled) return + setFoldersDoc(document) + }) + return () => { cancelled = true } + }, []) + const workspaces = useWorkspaces(state => state.items) const workspacePhase = useWorkspaces(state => state.phase) const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds) @@ -393,16 +421,18 @@ export function GroupsBrowser({ () => deriveGroups(list, workspaces, archivedSessionIds, config, { expandedCategories, expandedWorkspaces, - }, manual, statuses), - [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces], + collapsedFolders: collapsedFolderKeys, + }, manual, statuses, foldersDoc), + [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc], ) // Top-level (ungrouped) workspace rows, rendered after the group folders. const topLevel = useMemo( () => deriveTopLevel(list, workspaces, archivedSessionIds, config, { expandedCategories, expandedWorkspaces, - }, manual, statuses), - [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces], + collapsedFolders: collapsedFolderKeys, + }, manual, statuses, foldersDoc), + [list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc], ) // Quick panel (Ctrl+R): category label per grouped workspace id (the tree // derivation already resolved grouping; top-level workspaces stay absent). @@ -548,6 +578,108 @@ export function GroupsBrowser({ }) } + // ---- Folder overlay editing ------------------------------------------------- + + const notifyFolder = (text: string): void => { + setFolderError({ id: Date.now(), text }) + } + + const persistFolders = (next: FoldersDocument): void => { + setFoldersDoc(next) + saveFolders(next).catch((reason: unknown) => { + const detail = reason instanceof Error ? reason.message : String(reason) + notifyFolder(`${t('folder.saveError')}: ${detail}`) + }) + } + + /** Write one workspace's entry; zero extra folders removes the key entirely. */ + const writeFolderEntry = (workspaceId: WorkspaceId, entry: WorkspaceFolderEntry): void => { + const next: Record = { ...foldersDoc.workspaces } + const key = workspaceId as string + if (entry.folders.length === 0) delete next[key] + else next[key] = entry + persistFolders({ version: 1, workspaces: next }) + } + + const toggleFolder = (workspaceId: WorkspaceId, path: string): void => { + const key = folderKey(workspaceId, path) + setCollapsedFolderKeys(keys => (keys.includes(key) ? keys.filter(k => k !== key) : [...keys, key])) + } + + const addFolderTo = async (workspaceId: WorkspaceId): Promise => { + if (foldersBusy) return + const workspace = workspaces.find(w => w.workspaceId === workspaceId) + if (workspace === undefined) return + setFoldersBusy(true) + try { + const path = await pickDirectory() + if (path === null) return // cancelled + const entry = entryFor(foldersDoc, workspaceId as string) + if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) { + notifyFolder(t('folder.duplicate')) + return + } + writeFolderEntry(workspaceId, addFolder(entry, path)) + } catch (reason) { + const detail = reason instanceof Error ? reason.message : String(reason) + notifyFolder(`${t('folder.addError')}: ${detail}`) + } finally { + setFoldersBusy(false) + } + } + + const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => { + writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path)) + } + + const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => { + writeFolderEntry(workspaceId, removeFolder(entryFor(foldersDoc, workspaceId as string), path)) + } + + /** + * "New session here": an extra folder's own directory becomes the Session cwd. + * The base folder keeps the platform's own gesture instead, because that one + * reuses the blank session it already opened; creating a fresh Session on + * every click would pile up empty sessions. One creation in flight at a time; + * a rejection surfaces the failure and creates nothing else. + */ + const startSessionInFolder = (workspaceId: WorkspaceId, path: string, isBase: boolean): void => { + if (isBase) { + startSession(workspaceId) + return + } + if (creatingSessionIn !== null) return + setCreatingSessionIn(folderKey(workspaceId, path)) + createSessionIn(workspaceId, path).catch((reason: unknown) => { + const detail = reason instanceof Error ? reason.message : String(reason) + notifyFolder(`${t('folder.sessionError')}: ${detail}`) + }).finally(() => { + setCreatingSessionIn(null) + }) + } + + /** A project row's plus button — starts in that workspace's root folder. */ + const startSessionAtRoot = (workspaceId?: WorkspaceId): void => { + const workspace = workspaceId === undefined ? undefined : workspaces.find(w => w.workspaceId === workspaceId) + if (workspace === undefined) { + startSession(workspaceId) + return + } + const root = rootOf(workspace.path, entryFor(foldersDoc, workspaceId as string)) + startSessionInFolder(workspaceId as WorkspaceId, root, samePath(root, workspace.path)) + } + + // Absent when the host offers no folder application: folder rows then drop + // their "open folder" entry instead of failing at the click. + const openFolderPath = folderApp === undefined + ? undefined + : (path: string): void => { + openPathInApp(folderApp, path).catch((reason: unknown) => { + const detail = reason instanceof Error ? reason.message : String(reason) + notifyFolder(`${t('workspace.openInFolderError')}: ${detail}`) + }) + } + // ---- Runtime group management ---------------------------------------------- const [groupDialog, setGroupDialog] = useState(null) @@ -634,7 +766,7 @@ export function GroupsBrowser({ const name = groupDeleteTarget const originalRule = originalRuleNameForDisplay(config.categories, manual, name) - // Every project currently in the group goes to 未分类 (forced, not rule- + // Every project currently in the group goes to the uncategorized bucket (forced, not rule- // reclassified), regardless of how it landed there. const assignments = { ...manual.assignments } for (const workspace of workspaces) { @@ -681,7 +813,7 @@ export function GroupsBrowser({ const [dragIndicator, setDragIndicator] = useState(null) // Expansion state taken at dragstart; dragend restores it so the folding - // caused by a drag is always undone afterwards ("结束后恢复"). + // caused by a drag is always undone afterwards. const expansionSnapshot = useRef<{ categories: Record; workspaces: Record } | null>(null) // Live expansion state for the dragend restore (the document-level listener // is registered once, so it must read current values through a ref). @@ -760,7 +892,7 @@ export function GroupsBrowser({ } } - /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */ + /** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (no target = append). */ const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise => { if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return setManualSaving(true) @@ -929,9 +1061,9 @@ export function GroupsBrowser({ } /** - * Drag over the TOP-LEVEL AREA's blank space (not on a row — rows stop - * propagation). An insertion line shows the landing spot: empty top level → - * a standalone line under the last group; non-empty → a line below the last + * Drag over the TOP-LEVEL AREA's blank space (not on a row ???rows stop + * propagation). An insertion line shows the landing spot: empty top level — + * a standalone line under the last group; non-empty — a line below the last * top-level row (end of the list). */ const onDragOverTopLevelArea = (event: DragEvent): void => { @@ -1111,6 +1243,7 @@ export function GroupsBrowser({ now={now} open={open} manual={manual} + folders={foldersDoc} t={t} /> ) : ( @@ -1139,8 +1272,15 @@ export function GroupsBrowser({ onDragStartWorkspace={onDragStartWorkspace} onToggleCategory={() => { actions.setCategoryExpanded(category.key, !category.expanded) }} onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }} - onNewSession={startSession} + onNewSession={startSessionAtRoot} onOpen={open} + onToggleFolder={toggleFolder} + onFolderNewSession={startSessionInFolder} + onFolderSetRoot={setFolderRoot} + onFolderRemove={removeFolderFrom} + onOpenFolderPath={openFolderPath} + onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }} + creatingFolderKey={creatingSessionIn} onRenameRequest={(workspaceId, title) => { setRenameTarget({ workspaceId, currentTitle: title }) setRenameDraft(title) @@ -1172,7 +1312,7 @@ export function GroupsBrowser({ onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }} onOpenInFolder={openInFolder} canMoveOut={(workspaceId) => { - // The menu "移出分组" is offered for any project that + // The menu "Move out of group" is offered for any project that // currently sits inside a group (rule-classified or manual) — // not just overridden ones. Top-level projects // (resolveCategory === undefined) don't need it. @@ -1201,8 +1341,15 @@ export function GroupsBrowser({ onDropRow={onDropRow} onDragStartWorkspace={onDragStartWorkspace} onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }} - onNewSession={startSession} + onNewSession={startSessionAtRoot} onOpen={open} + onToggleFolder={toggleFolder} + onFolderNewSession={startSessionInFolder} + onFolderSetRoot={setFolderRoot} + onFolderRemove={removeFolderFrom} + onOpenFolderPath={openFolderPath} + onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }} + creatingFolderKey={creatingSessionIn} onRenameRequest={(workspaceId, title) => { setRenameTarget({ workspaceId, currentTitle: title }) setRenameDraft(title) @@ -1371,6 +1518,27 @@ export function GroupsBrowser({ )} + {/* Per-workspace folders dialog: base + extra folders, root radio, + open/remove per row. Mounted only while a project row asked for it. */} + {foldersTarget !== null && (() => { + const workspace = workspaces.find(w => w.workspaceId === foldersTarget) + if (workspace === undefined) return null + return ( + { setFoldersTarget(null) }} + onAdd={() => { void addFolderTo(foldersTarget) }} + onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }} + onRemove={(path) => { removeFolderFrom(foldersTarget, path) }} + onOpenFolder={(path) => { openFolderPath?.(path) }} + /> + ) + })()} + {/* Workspace rename dialog */} void + onSessionRename: (sessionId: SessionId, currentTitle: string) => void + onSessionArchive: (sessionId: SessionId) => void + onFork: (sessionId: SessionId) => void + onToggleFolder: (workspaceId: WorkspaceId, path: string) => void + onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void + onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void + onFolderRemove: (workspaceId: WorkspaceId, path: string) => void + onOpenFolderPath?: ((path: string) => void) | undefined + creatingFolderKey: string | null +}) { + const folders = workspace.folders + if (folders === undefined) { + return ( + + {workspace.sessions.map((session) => ( + + ))} + + ) + } + return ( + + {folders.map((folder) => { + const key = folderKey(workspace.workspaceId, folder.path) + return ( +
+ { onToggleFolder(workspace.workspaceId, folder.path) }} + onNewSession={() => { onFolderNewSession(workspace.workspaceId, folder.path, folder.isBase) }} + onSetRoot={() => { onFolderSetRoot(workspace.workspaceId, folder.path) }} + onRemove={() => { onFolderRemove(workspace.workspaceId, folder.path) }} + {...(onOpenFolderPath !== undefined + ? { onOpenInFolder: () => { onOpenFolderPath(folder.path) } } + : {})} + /> + + {folder.sessions.map((session) => ( + + ))} + +
+ ) + })} +
+ ) +} + /** One category section: header row + expanded workspace folders. */ -function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder }: { +function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: { category: CategoryNode current: SessionId | undefined now: number @@ -1526,8 +1790,17 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR onGroupAppearance: () => void onMoveOut: (workspaceId: WorkspaceId) => void canMoveOut: (workspaceId: WorkspaceId) => boolean + onToggleFolder: (workspaceId: WorkspaceId, path: string) => void + onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void + onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void + onFolderRemove: (workspaceId: WorkspaceId, path: string) => void + onManageFolders: (workspaceId: WorkspaceId) => void + /** Creation in flight, keyed by `folderKey`; disables the row's controls */ + creatingFolderKey: string | null /** Absent when the host resolved no folder application. */ onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined + /** Absent when the host resolved no folder application. */ + onOpenFolderPath?: ((path: string) => void) | undefined }) { const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key ? (dragIndicator.before ? 'before' : 'after') @@ -1577,26 +1850,25 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR onRowDragLeave={onDragLeaveRow} onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })} onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)} + onManageFolders={() => { onManageFolders(workspace.workspaceId) }} + /> + - - {workspace.sessions.map((session) => ( - - ))} - ))} @@ -1613,7 +1885,7 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR * last row); * - an empty top level shows a standalone line under the last group folder. */ -function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder }: { +function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: { topLevel: readonly WorkspaceGroupNode[] current: SessionId | undefined now: number @@ -1635,8 +1907,16 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t onSessionRename: (sessionId: SessionId, currentTitle: string) => void onSessionArchive: (sessionId: SessionId) => void onFork: (sessionId: SessionId) => void + onToggleFolder: (workspaceId: WorkspaceId, path: string) => void + onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void + onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void + onFolderRemove: (workspaceId: WorkspaceId, path: string) => void + onManageFolders: (workspaceId: WorkspaceId) => void + creatingFolderKey: string | null /** Absent when the host resolved no folder application. */ onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined + /** Absent when the host resolved no folder application. */ + onOpenFolderPath?: ((path: string) => void) | undefined }) { const emptyLineActive = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === topLevelRef.key return ( @@ -1679,26 +1959,91 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t onRowDragLeave={onDragLeaveRow} onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })} onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)} + onManageFolders={() => { onManageFolders(workspace.workspaceId) }} /> - - {workspace.sessions.map((session) => ( + + + ))} + + ) +} + +/** + * Search hits inside one project. When the project owns extra folders the hits + * keep their folder row (all expanded, since search prunes to matches) so a + * match never loses the folder it came from. + */ +function SearchSubtree({ workspace, current, now, open, t }: { + workspace: WorkspaceGroupNode + current: SessionId | undefined + now: number + open: (sessionId: SessionId) => void + t: GroupsBrowserProps['t'] +}) { + const folders = workspace.folders + if (folders === undefined) { + return ( +
+ {workspace.sessions.map((session) => ( + {}} + onFork={() => {}} + onArchive={() => {}} + /> + ))} +
+ ) + } + return ( +
+ {folders.map((folder) => ( +
+ {}} + onNewSession={() => {}} + onSetRoot={() => {}} + onRemove={() => {}} + /> +
+ {folder.sessions.map((session) => ( {}} + onFork={() => {}} + onArchive={() => {}} /> ))} - +
))}
@@ -1707,10 +2052,10 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t /** * Search body rendered as a three-level tree pruned to matched branches: - * 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as + * Only branches that contain a hit are rendered, which keeps a long list short. 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, statuses, query, remote, resultLimit, current, now, open, manual, t }: { +function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, folders, t }: { list: SessionListState workspaces: readonly WorkspaceView[] config: GroupsConfig @@ -1723,6 +2068,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu now: number open: (sessionId: SessionId) => void manual: ManualGroups + folders: FoldersDocument t: GroupsBrowserProps['t'] }) { const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false } @@ -1731,8 +2077,8 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu [list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit], ) const searchTree = useMemo( - () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses), - [list, workspaces, config, matches, archivedSessionIds, manual, statuses], + () => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses, folders), + [list, workspaces, config, matches, archivedSessionIds, manual, statuses, folders], ) const groups = searchTree.categories const searchTopLevel = searchTree.topLevel @@ -1754,21 +2100,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu onRename={() => {}} onDelete={() => {}} /> -
- {workspace.sessions.map((session) => ( - {}} - onFork={() => {}} - onArchive={() => {}} - /> - ))} -
+ ))} @@ -1785,21 +2117,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu onRename={() => {}} onDelete={() => {}} /> -
- {workspace.sessions.map((session) => ( - {}} - onFork={() => {}} - onArchive={() => {}} - /> - ))} -
+ ))} {pending &&
{t('search.pending')}
} @@ -1813,3 +2131,84 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu ) } + +/** + * Folder list dialog for one workspace: the base folder first, then every extra + * folder in stored order. The radio column chooses the root (the folder new + * sessions default to); open/remove act per row, and removing the base folder is + * never offered because the workspace's canonical directory cannot be dropped. + */ +function FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onSetRoot, onRemove, onOpenFolder }: { + workspace: WorkspaceView + entry: WorkspaceFolderEntry | undefined + t: GroupsBrowserProps['t'] + busy: boolean + canOpen: boolean + onClose: () => void + onAdd: () => void + onSetRoot: (path: string) => void + onRemove: (path: string) => void + onOpenFolder: (path: string) => void +}) { + const folders = effectiveFolders(workspace.path, entry) + const root = rootOf(workspace.path, entry) + return ( + {t('folder.done')} + )} + > +
+ {folders.map((path, index) => { + const isBase = index === 0 + const isRoot = samePath(path, root) + const label = folderLabel(path) + return ( +
+ { onSetRoot(path) }} + /> + {label} + {isBase && {t('folder.base')}} + {isRoot && {t('folder.rootBadge')}} + + {canOpen && ( + + )} + {!isBase && ( + + )} + +
+ ) + })} +
+
+ +
+
+ ) +} diff --git a/src/client/contract.ts b/src/client/contract.ts index b541684..bcd1692 100644 --- a/src/client/contract.ts +++ b/src/client/contract.ts @@ -35,6 +35,11 @@ export type GroupsBrowserInjected = { }; /** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */ startSession: (workspaceId?: WorkspaceId) => void; + /** + * Create a real Session in one folder of a Workspace and open it. `cwd` is + * omitted for the base folder (the Workspace's own canonical directory). + */ + createSessionIn: (workspaceId: WorkspaceId, cwd?: string) => Promise; /** Open a real Session. */ open: (sessionId: SessionId) => void; /** Search current visible conversation messages. */ diff --git a/src/client/folders-persist.ts b/src/client/folders-persist.ts new file mode 100644 index 0000000..c5dd248 --- /dev/null +++ b/src/client/folders-persist.ts @@ -0,0 +1,97 @@ +/** + * Client side of the per-workspace folder list, talking to + * `GET|PUT /workspace-groups/folders` on the host. + * + * The document is the host's JSON sidecar verbatim (`version` + `workspaces`), + * so the client and the host agree on one shape: `folders` holds EXTRA folders + * only — the workspace's canonical directory is implicit folder #0 — and + * `root` names one of those extras (absent means "the workspace itself"). + * + * Reads are best-effort, like the manual overlay and the tab strip: a failed + * read means "no extra folders". A failed write, however, rejects so the caller + * can say so — a folder row that silently forgot its edit would be worse than + * the toast. + */ +import { + EMPTY_FOLDERS_DOCUMENT, + type FoldersDocument, + type WorkspaceFolderEntry, +} from '../core/folders.ts' + +/** Host route holding the folder overlay. */ +export const FOLDERS_ROUTE = '/workspace-groups/folders' + +/** + * Read one workspace entry off the wire, dropping the entry when it is + * unusable. + * @param value - one value of the stored `workspaces` mapping. + * @returns the entry, or null for a malformed one. + */ +function parseWireEntry(value: unknown): WorkspaceFolderEntry | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return null + const row = value as Record + if (!Array.isArray(row.folders)) return null + const folders: string[] = [] + for (const candidate of row.folders) { + if (typeof candidate !== 'string' || candidate.trim() === '') continue + folders.push(candidate) + } + const root = typeof row.root === 'string' && row.root.trim() !== '' ? row.root : undefined + return { folders, ...(root === undefined ? {} : { root }) } +} + +/** + * Fetch the stored folder overlay. + * @param fetchImpl - fetch implementation (injectable for tests). + * @returns the document; the empty document on any failure. + */ +export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise { + try { + const response = await fetchImpl(FOLDERS_ROUTE, { + method: 'GET', + // Folders are user state; a cached response would show stale rows. + cache: 'no-store', + }) + if (!response.ok) return EMPTY_FOLDERS_DOCUMENT + const body: unknown = await response.json() + if (typeof body !== 'object' || body === null) return EMPTY_FOLDERS_DOCUMENT + const source = body as Record + if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT + if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) { + return { version: 1, workspaces: {} } + } + const workspaces: Record = {} + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + const entry = parseWireEntry(value) + if (entry !== null) workspaces[workspaceId] = entry + } + return { version: 1, workspaces } + } catch { + return EMPTY_FOLDERS_DOCUMENT + } +} + +/** + * Store the whole folder overlay. + * + * Unlike the tab strip this does NOT swallow failures: folder edits are explicit + * row/dialog actions, so the caller turns a rejection into a toast instead of + * leaving the user with a row that silently forgot its folder. + * @param document - the client's current document. + * @param fetchImpl - fetch implementation (injectable for tests). + */ +export async function saveFolders( + document: FoldersDocument, + fetchImpl: typeof fetch = fetch, +): Promise { + const response = await fetchImpl(FOLDERS_ROUTE, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(document), + cache: 'no-store', + // The write is idempotent, so surviving a navigation with keepalive is + // safe and avoids losing the just-added folder. + keepalive: true, + }) + if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`) +} diff --git a/src/client/index.ts b/src/client/index.ts index 684d680..6eb56a0 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -166,6 +166,17 @@ export function apply(ctx: Context): void { // retained `mainView` selection, supersession and pending-navigation // cancellation (0.1.6 moved them out of `ctx.sessions`). startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) }, + // Folder rows create a real Session rooted in that folder. `cwd` stays out + // of the call for the base folder (the Workspace's canonical directory), + // where the controller already defaults to `WorkspaceView.path`. + createSessionIn: async (workspaceId, cwd) => { + const sessionId = await ctx.sessions.create({ + workspaceId, + ...(cwd === undefined ? {} : { cwd }), + }) + ctx.uiWorkspace.openSession(sessionId) + return sessionId + }, open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) }, forkSession: (sessionId) => { ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => { diff --git a/src/client/locales.ts b/src/client/locales.ts index 7db42e0..f8fb1b6 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -34,6 +34,19 @@ export type WorkspaceGroupsKey = | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' + | 'folder.title' + | 'folder.manage' + | 'folder.listAria' + | 'folder.base' + | 'folder.setRoot' + | 'folder.rootBadge' + | 'folder.remove' + | 'folder.add' + | 'folder.done' + | 'folder.duplicate' + | 'folder.addError' + | 'folder.sessionError' + | 'folder.saveError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' @@ -149,6 +162,19 @@ export const zh: WorkspaceGroupsDict = { 'workspace.moveOutOfGroup': '移出分组', 'workspace.openInFolder': '在文件夹中打开', 'workspace.openInFolderError': '打开文件夹失败', + 'folder.title': '文件夹', + 'folder.manage': '文件夹…', + 'folder.listAria': '工作区文件夹', + 'folder.base': '基础文件夹', + 'folder.setRoot': '设为根目录', + 'folder.rootBadge': '根目录', + 'folder.remove': '从工作区移除', + 'folder.add': '添加文件夹', + 'folder.done': '完成', + 'folder.duplicate': '该文件夹已在此工作区中', + 'folder.addError': '添加文件夹失败', + 'folder.sessionError': '新建会话失败', + 'folder.saveError': '文件夹保存失败', 'group.create': '新建分组', 'group.createTitle': '新建分组', 'group.createPlaceholder': '分组名称', @@ -263,6 +289,19 @@ export const en: WorkspaceGroupsDict = { 'workspace.moveOutOfGroup': 'Move out of group', 'workspace.openInFolder': 'Open in folder', 'workspace.openInFolderError': 'Could not open the folder', + 'folder.title': 'Folders', + 'folder.manage': 'Folders…', + 'folder.listAria': 'Workspace folders', + 'folder.base': 'Base folder', + 'folder.setRoot': 'Set as root', + 'folder.rootBadge': 'Root', + 'folder.remove': 'Remove from workspace', + 'folder.add': 'Add folder', + 'folder.done': 'Done', + 'folder.duplicate': 'That folder is already in this workspace', + 'folder.addError': 'Could not add the folder', + 'folder.sessionError': 'Could not start a session', + 'folder.saveError': 'Could not save folders', 'group.create': 'New group', 'group.createTitle': 'New group', 'group.createPlaceholder': 'Group name', diff --git a/src/client/rows.tsx b/src/client/rows.tsx index 70ed1b1..2574af6 100644 --- a/src/client/rows.tsx +++ b/src/client/rows.tsx @@ -51,7 +51,7 @@ import { } from '@deepseek-ai/dsh-client-ui-primitives' import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import type { WorkspaceGroupsKey } from './locales.ts' -import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts' +import type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts' type T = TranslateNS<'workspaceGroups'> @@ -271,7 +271,7 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin } /** One workspace folder row inside a category: draggable source + drop target. */ -export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: { +export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onManageFolders, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: { node: WorkspaceGroupNode t: T onToggle: () => void @@ -281,6 +281,8 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele /** Project currently sits inside a group — offer "move out of group". */ canMoveOut?: boolean onMoveOut?: () => void + /** Open the folder-management dialog (extra folders + root). */ + onManageFolders?: () => void /** * Open the project directory in the host's file manager. Omitted when the * host resolved no folder application (no capability, or a remote launch), @@ -293,13 +295,16 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele onDragStartExtra?: () => void } & RowDropProps) { const [menuOpen, setMenuOpen] = useState(false) - const menuItems = [ + const menuItems: MenuEntry[] = [ ...(onOpenInFolder !== undefined ? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: }] : []), ...(canMoveOut && onMoveOut !== undefined ? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: }] : []), + ...(onManageFolders !== undefined + ? [{ id: 'folders', label: t('folder.manage'), icon: }] + : []), { id: 'rename', label: t('workspace.rename'), icon: }, { id: 'delete', label: t('workspace.delete'), icon: , danger: true }, ] @@ -348,6 +353,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele setMenuOpen(false) if (id === 'openInFolder') onOpenInFolder?.() if (id === 'moveOut') onMoveOut?.() + if (id === 'folders') onManageFolders?.() if (id === 'rename') onRename() if (id === 'delete') onDelete() }} @@ -379,6 +385,110 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele ) } +/** + * One folder row under a project: the base directory (folder #0) plus every + * extra folder of that workspace. Sits at the session indent level so the + * 42/58/74 ladder is preserved, and its own session rows indent one step + * deeper (see `.wgSessionNested`). + * + * Deliberately NOT a drag source or drop target: folders are a fixed, + * host-ordered list; reordering them would need a write path this feature does + * not have. + */ +export function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating = false }: { + node: FolderNode + t: T + onToggle: () => void + onNewSession: () => void + onSetRoot: () => void + onRemove: () => void + /** Absent when the host resolved no folder application. */ + onOpenInFolder?: () => void + /** A session is being created here: the hover + stays disabled. */ + creating?: boolean +}) { + const [menuOpen, setMenuOpen] = useState(false) + const menuItems: MenuEntry[] = [ + { id: 'newSession', label: t('session.new'), icon: }, + ...(onOpenInFolder !== undefined + ? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: }] + : []), + ...(node.isRoot + ? [] + : [{ id: 'setRoot', label: t('folder.setRoot'), icon: }]), + ...(node.isBase + ? [] + : [ + { type: 'separator' as const, id: 'folder-menu-separator' }, + { id: 'remove', label: t('folder.remove'), icon: , danger: true }, + ]), + ] + return ( +
+ + + + + {node.expanded ? : } + + {node.label} + {node.isRoot && ( + ★ + )} + {node.sessions.length} + + { setMenuOpen(false) }} + items={menuItems} + onSelect={(id) => { + setMenuOpen(false) + if (id === 'newSession') onNewSession() + if (id === 'openInFolder') onOpenInFolder?.() + if (id === 'setRoot') onSetRoot() + if (id === 'remove') onRemove() + }} + portal + closeOnPointerLeave + anchor={( + + )} + /> + + +
+ ) +} + /** * Children container for one folder's rows. * @@ -476,7 +586,7 @@ export function RowGroup({ expanded, className, animate = true, children }: { } /** One session leaf row. */ -export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: { +export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested = false }: { node: SessionNode currentId: string | undefined now: number @@ -485,6 +595,8 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onRename: (id: SessionNode['id'], currentTitle: string) => void onFork: (id: SessionNode['id']) => void onArchive: (id: SessionNode['id']) => void + /** Rendered under a folder row: one indent step deeper than a plain session. */ + nested?: boolean }) { const selected = node.id === currentId const [menuOpen, setMenuOpen] = useState(false) @@ -502,7 +614,7 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, ] return (
| undefined, +): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } { + const extras = effectiveFolders(workspacePath, entry).slice(1) + if (extras.length === 0) return { sessions } + const root = rootOf(workspacePath, entry) + const base: SessionNode[] = [] + const byFolder = new Map() + for (const node of sessions) { + const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry) + if (samePath(owner, workspacePath)) { + base.push(node) + continue + } + const bucket = byFolder.get(owner) + if (bucket === undefined) byFolder.set(owner, [node]) + else bucket.push(node) + } + const folderNode = (path: string, isBase: boolean): FolderNode => { + const owned = isBase ? base : (byFolder.get(path) ?? []) + return { + path, + label: folderLabel(path), + isRoot: samePath(path, root), + expanded: collapsedFolders === undefined || !collapsedFolders.has(folderKey(workspaceId, path)), + isBase, + // Every owned session is kept on the node so the row's count stays honest + // while the folder is collapsed; the RowGroup does the hiding. + sessions: owned, + } + } + const folders: FolderNode[] = [ + folderNode(workspacePath, true), + ...extras.map(path => folderNode(path, false)), + ] + // Root first, then stored order: moving the root row to the front keeps the + // remaining rows (base included) in their stored order. + const rootIndex = folders.findIndex(folder => folder.isRoot) + if (rootIndex > 0) { + const [rootFolder] = folders.splice(rootIndex, 1) + if (rootFolder !== undefined) folders.unshift(rootFolder) + } + return { sessions: base, folders } +} + /** * Derive the three-level tree. * @param list - sessions list snapshot (`current` feeds containsCurrent). @@ -191,6 +309,9 @@ function workspaceSessions( * manual override wins over rule classification; removing it reverts to rules. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root. A workspace with extras + * gains folder rows and its extra-folder sessions move under them; a workspace + * without extras keeps exactly the pre-folders node shape. * @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. @@ -203,10 +324,12 @@ export function deriveGroups( view: GroupsTreeView, manual: ManualGroups, statuses: SessionStatuses = new Map(), + folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT, ): CategoryNode[] { const archived = new Set(archivedSessionIds) const expandedCategories = new Set(view.expandedCategories) const expandedWorkspaces = new Set(view.expandedWorkspaces) + const collapsedFolders = new Set(view.collapsedFolders ?? []) const descendants = indexSubagentDescendants(list.byId) const current = currentSessionId(list) @@ -245,6 +368,14 @@ export function deriveGroups( const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current) const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string) const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId + const partitioned = applyFolders( + workspace.workspaceId, + workspace.path, + sessions, + list, + entryFor(folders, workspace.workspaceId as string), + collapsedFolders, + ) if (wsContainsCurrent) containsCurrent = true workspaceNodes.push({ workspaceId: workspace.workspaceId, @@ -254,7 +385,8 @@ export function deriveGroups( sessionCount: sessions.length, expanded: wsExpanded, containsCurrent: wsContainsCurrent, - sessions: wsExpanded ? sessions : [], + sessions: wsExpanded ? partitioned.sessions : [], + ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }), }) } const appearance = categoryAppearance(manual, key) @@ -285,9 +417,11 @@ export function deriveTopLevel( view: GroupsTreeView, manual: ManualGroups, statuses: SessionStatuses = new Map(), + folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT, ): WorkspaceGroupNode[] { const archived = new Set(archivedSessionIds) const expandedWorkspaces = new Set(view.expandedWorkspaces) + const collapsedFolders = new Set(view.collapsedFolders ?? []) const descendants = indexSubagentDescendants(list.byId) const current = currentSessionId(list) const currentWorkspaceId = current === undefined @@ -305,6 +439,14 @@ export function deriveTopLevel( if (workspace === undefined) continue const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current) const wsExpanded = expandedWorkspaces.has(workspaceId) + const partitioned = applyFolders( + workspace.workspaceId, + workspace.path, + sessions, + list, + entryFor(folders, workspaceId), + collapsedFolders, + ) nodes.push({ workspaceId: workspace.workspaceId, path: workspace.path, @@ -313,7 +455,8 @@ export function deriveTopLevel( sessionCount: sessions.length, expanded: wsExpanded, containsCurrent: workspace.workspaceId === currentWorkspaceId, - sessions: wsExpanded ? sessions : [], + sessions: wsExpanded ? partitioned.sessions : [], + ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }), }) } return nodes @@ -426,6 +569,8 @@ export interface SearchTree { * @param snippetsBySession - optional content-match snippets keyed by session id. * @param statuses - unified UI status by Session (drives the running / warning * / unread-completion row indicators); defaults to none (tests). + * @param folders - per-workspace extra folders + root, so a hit inside an extra + * folder surfaces under that folder instead of flat under the project. * @returns group folders in render order plus top-level matched workspaces, * pruned to matched branches only. */ @@ -438,6 +583,7 @@ export function deriveSearchGroups( manual: ManualGroups, snippetsBySession?: ReadonlyMap, statuses: SessionStatuses = new Map(), + folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT, ): SearchTree { const archived = new Set(archivedSessionIds) const descendants = indexSubagentDescendants(list.byId) @@ -464,6 +610,14 @@ export function deriveSearchGroups( } if (nodes.length === 0) continue + const partitioned = applyFolders( + workspace.workspaceId, + workspace.path, + nodes, + list, + entryFor(folders, workspace.workspaceId as string), + undefined, + ) const node: WorkspaceGroupNode = { workspaceId: workspace.workspaceId, path: workspace.path, @@ -472,7 +626,8 @@ export function deriveSearchGroups( sessionCount: nodes.length, expanded: true, containsCurrent: false, - sessions: nodes, + sessions: partitioned.sessions, + ...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }), } const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) if (key === undefined) { diff --git a/src/core/folders.ts b/src/core/folders.ts new file mode 100644 index 0000000..6bfcd62 --- /dev/null +++ b/src/core/folders.ts @@ -0,0 +1,196 @@ +/** + * Pure folder-list logic for per-workspace multi-root folders. + * + * DSH core gives a workspace exactly ONE canonical directory + * (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA + * folders on top of it, plus one designated root folder per workspace: + * + * - the canonical directory is always folder #0 (the "base"); it cannot be + * removed and may be the root; + * - `root` is stored only when it names an EXTRA folder — "base is the root" + * is expressed by omitting the key, so the base path is never duplicated + * into the sidecar; + * - a session whose recorded `cwd` lives inside an extra folder belongs to + * that folder, not to the project row. + * + * Everything here is pure and platform-agnostic: it imports no React, no DOM + * and no cordis so plain Node (the verifier, the host route) can load it. + */ + +/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */ +export interface WorkspaceFolderEntry { + readonly folders: readonly string[] + readonly root?: string +} + +/** The whole `workspace-groups.folders.json` document. */ +export interface FoldersDocument { + readonly version: 1 + readonly workspaces: Readonly> +} + +/** Canonical empty document, shared so callers need not allocate one each time. */ +export const EMPTY_FOLDERS_DOCUMENT: FoldersDocument = { version: 1, workspaces: {} } + +/** `C:\…` or `C:/…` — a drive-rooted Windows path. */ +const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u + +/** `\\server\share` — a Windows UNC path. */ +const WINDOWS_UNC = /^\\\\/u + +/** True for both Windows path spellings accepted by the write validator. */ +function isWindowsStyle(path: string): boolean { + return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) +} + +/** + * Comparison form of one path: trimmed, separator-normalized and, for Windows + * spellings, lower-cased (drive letters and file names are case-insensitive + * there). Trailing separators are dropped except for a drive/UNC/root prefix. + * @param path - raw path as stored or picked. + * @returns the canonical comparison form. + */ +function canonicalPath(path: string): string { + const trimmed = path.trim() + if (isWindowsStyle(trimmed)) { + let value = trimmed.replaceAll('/', '\\').toLowerCase() + // `C:\` is three characters and already a root; `\\srv\share\` keeps its + // trailing separator only while a further segment remains. + while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1) + return value + } + let value = trimmed + while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1) + return value +} + +/** + * Path equality: case-insensitive for Windows-style paths, tolerant of + * trailing separators, exact for POSIX paths. + * @param a - first path. + * @param b - second path. + */ +export function samePath(a: string, b: string): boolean { + return canonicalPath(a) === canonicalPath(b) +} + +/** + * Look up the folder entry saved for one workspace. + * @param doc - folders document. + * @param workspaceId - host workspace id. + * @returns the entry, or undefined when the workspace has none. + */ +export function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined { + return doc.workspaces[workspaceId] +} + +/** + * The workspace's effective folder list, base first. The base cannot be + * duplicated and blank extra entries are dropped. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + */ +export function effectiveFolders( + workspacePath: string, + entry: WorkspaceFolderEntry | undefined, +): readonly string[] { + const extras: string[] = [] + for (const folder of entry?.folders ?? []) { + if (folder.trim() === '') continue + if (samePath(folder, workspacePath)) continue + if (extras.some(existing => samePath(existing, folder))) continue + extras.push(folder) + } + return [workspacePath, ...extras] +} + +/** + * The folder new sessions start in by default. + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the stored root when it names an effective extra folder, else the + * workspace's own directory. + */ +export function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string { + const root = entry?.root + if (root === undefined) return workspacePath + const folders = effectiveFolders(workspacePath, entry) + return folders.find(folder => samePath(folder, root)) ?? workspacePath +} + +/** + * Owning folder of a session cwd: the most specific (longest) effective folder + * that equals the cwd or is a proper path ancestor of it. + * @param cwd - recorded session cwd; undefined means "the workspace itself". + * @param workspacePath - canonical directory of the workspace. + * @param entry - saved folder entry, if any. + * @returns the owning folder, or the workspace path when nothing matches. + */ +export function folderOfCwd( + cwd: string | undefined, + workspacePath: string, + entry: WorkspaceFolderEntry | undefined, +): string { + if (cwd === undefined) return workspacePath + const target = canonicalPath(cwd) + let best: string | undefined + let bestLength = -1 + for (const folder of effectiveFolders(workspacePath, entry)) { + const root = canonicalPath(folder) + if (root === '') continue + const separator = isWindowsStyle(root) ? '\\' : '/' + const prefix = root.endsWith(separator) ? root : `${root}${separator}` + if (target !== root && !target.startsWith(prefix)) continue + if (root.length > bestLength) { + best = folder + bestLength = root.length + } + } + return best ?? workspacePath +} + +/** + * Append an extra folder. Idempotent under `samePath`, and the stored root (if + * any) survives untouched. + * @param entry - current entry, or undefined for a workspace with no extras. + * @param path - folder path to append. + */ +export function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry { + const folders = entry?.folders ?? [] + const root = entry?.root + const trimmed = path.trim() + const keepRoot = root === undefined ? {} : { root } + if (trimmed === '' || folders.some(folder => samePath(folder, trimmed))) { + return { folders: [...folders], ...keepRoot } + } + return { folders: [...folders, trimmed], ...keepRoot } +} + +/** + * Drop an extra folder. A root that pointed at it is cleared, so the workspace + * falls back to its own directory instead of referencing a folder it no longer + * has. + * @param entry - current entry, or undefined. + * @param path - folder path to drop. + */ +export function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry { + const folders = entry?.folders ?? [] + const remaining = folders.filter(folder => !samePath(folder, path)) + const root = entry?.root + const keepRoot = root !== undefined && !samePath(root, path) + return { folders: remaining, ...(keepRoot ? { root } : {}) } +} + +/** + * Designate the root folder. Only an extra folder can be stored: naming the + * base directory means "no explicit root", which is represented by clearing + * the key. + * @param entry - current entry, or undefined. + * @param path - folder to make the root. + */ +export function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry { + const folders = entry?.folders ?? [] + const match = folders.find(folder => samePath(folder, path)) + if (match === undefined) return { folders: [...folders] } + return { folders: [...folders], root: match } +} diff --git a/src/host-folders.ts b/src/host-folders.ts new file mode 100644 index 0000000..440f70b --- /dev/null +++ b/src/host-folders.ts @@ -0,0 +1,240 @@ +/** + * Folder overlay for @dsh-xhl/workspace-groups: the per-workspace list of + * EXTRA folders plus the designated root folder. Stored in a plugin-owned JSON + * sidecar (`$DSH_HOME/workspace-groups.folders.json`), next to the manual + * grouping overlay, because neither DSH core nor the YAML rule source knows + * about folders: core gives a workspace exactly one canonical directory and the + * YAML stays the classification source. + * + * Writes are strict (the browser PUT route validates the whole document before + * replacing it, atomically: temp file + fsync + rename) and reads tolerate + * hand-edited content (junk entries are dropped instead of thrown), for the + * same reason the manual overlay does: a stale or malformed sidecar must never + * freeze the tree. + */ +import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { homedir } from 'node:os' +import { + EMPTY_FOLDERS_DOCUMENT, + samePath, + type FoldersDocument, + type WorkspaceFolderEntry, +} from './core/folders.ts' + +/** File name of the folder sidecar (also the stable error-text prefix). */ +export const FOLDERS_FILE_NAME = 'workspace-groups.folders.json' + +/** Hard limits enforced at the write boundary. */ +export const FOLDERS_PER_WORKSPACE_LIMIT = 32 +export const WORKSPACE_ID_LIMIT = 200 +export const FOLDER_PATH_LIMIT = 1024 + +/** `C:\…` or `C:/…` — a drive-rooted Windows path. */ +const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u + +/** `\\server\share` — a Windows UNC path. */ +const WINDOWS_UNC = /^\\\\/u + +/** `/…` — a POSIX absolute path. */ +const POSIX_ABSOLUTE = /^\//u + +/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */ +export function defaultFoldersPath(): string { + const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== '' + ? process.env.DSH_HOME + : resolve(homedir(), '.dsh') + return resolve(home, FOLDERS_FILE_NAME) +} + +/** + * True when `path` is absolute in the host platform's spelling: a drive + * letter or UNC prefix on Windows, a leading slash elsewhere. + * @param path - candidate path. + */ +export function isAbsoluteFolderPath(path: string): boolean { + return process.platform === 'win32' + ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) + : POSIX_ABSOLUTE.test(path) +} + +/** Reject helper carrying the stable file-scoped message prefix. */ +function invalid(detail: string): never { + throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`) +} + +/** + * Parse one workspace entry. + * @param value - raw entry from the document. + * @param workspaceId - owning workspace id (used in messages). + * @param strict - throw on the first problem, or drop junk and return undefined. + * @returns the normalized entry, or undefined when nothing usable remains. + */ +function parseFolderEntry( + value: unknown, + workspaceId: string, + strict: boolean, +): WorkspaceFolderEntry | undefined { + const fail = (detail: string): void => { + if (strict) invalid(`workspace "${workspaceId}": ${detail}`) + } + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + fail('entry must be an object') + return undefined + } + const source = value as Record + if (source.folders === undefined) { + fail('folders is required') + return undefined + } + if (!Array.isArray(source.folders)) { + fail('folders must be a list') + return undefined + } + if (strict && source.folders.length > FOLDERS_PER_WORKSPACE_LIMIT) { + invalid(`workspace "${workspaceId}": at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`) + } + + const folders: string[] = [] + for (const candidate of source.folders) { + if (typeof candidate !== 'string') { + fail('folder paths must be strings') + continue + } + const path = candidate.trim() + if (path === '') { + fail('folder paths must be non-empty') + continue + } + if (path.includes('\u0000')) { + fail(`folder path "${path}" contains a NUL character`) + continue + } + if (path.length > FOLDER_PATH_LIMIT) { + fail(`folder path exceeds ${FOLDER_PATH_LIMIT} characters`) + continue + } + if (!isAbsoluteFolderPath(path)) { + fail(`folder path "${path}" must be absolute`) + continue + } + if (folders.some(existing => samePath(existing, path))) { + fail(`duplicate folder path "${path}"`) + continue + } + if (folders.length >= FOLDERS_PER_WORKSPACE_LIMIT) { + fail(`at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`) + break + } + folders.push(path) + } + + let root: string | undefined + if (source.root !== undefined) { + if (typeof source.root !== 'string') { + fail('root must be a string') + } else { + const candidate = source.root.trim() + const member = folders.find(folder => samePath(folder, candidate)) + if (member === undefined) fail(`root "${candidate}" must name one of folders`) + else root = member + } + } + + if (folders.length === 0 && root === undefined) return undefined + return { folders, ...(root === undefined ? {} : { root }) } +} + +/** + * Tolerant reader: shape-normalizes whatever was on disk and drops unusable + * workspaces, folders and roots instead of throwing. A missing, non-mapping or + * unknown-version document yields the empty document. + * @param raw - parsed JSON value. + */ +export function parseFoldersDocument(raw: unknown): FoldersDocument { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return EMPTY_FOLDERS_DOCUMENT + const source = raw as Record + if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT + if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) { + return { version: 1, workspaces: {} } + } + const workspaces: Record = {} + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT) continue + const entry = parseFolderEntry(value, workspaceId, false) + if (entry !== undefined) workspaces[workspaceId] = entry + } + return { version: 1, workspaces } +} + +/** + * Strict writer-side validation. Every rule is enforced and the first problem + * throws, so the PUT route rejects instead of persisting a half-valid file. + * @param raw - parsed JSON value from the request body. + * @returns the normalized document to save. + * @throws when version, workspace ids, folder paths, duplicates or the root + * membership are wrong. + */ +export function validateFoldersDocument(raw: unknown): FoldersDocument { + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) { + invalid('top-level value must be a mapping') + } + const source = raw as Record + if (source.version !== 1) invalid('version must be 1') + if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) { + invalid('workspaces must be a mapping') + } + const workspaces: Record = {} + for (const [workspaceId, value] of Object.entries(source.workspaces)) { + if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT) { + invalid(`workspace ids must be non-empty strings of at most ${WORKSPACE_ID_LIMIT} characters`) + } + const entry = parseFolderEntry(value, workspaceId, true) + if (entry !== undefined) workspaces[workspaceId] = entry + } + return { version: 1, workspaces } +} + +/** + * Read + tolerate the overlay file. A missing or unreadable file yields the + * empty document: folders are a convenience, and a broken sidecar must not take + * the tree down with it. + * @param path - overlay file path. + */ +export async function readFoldersDocument(path: string): Promise { + try { + const text = await readFile(path, 'utf8') + return parseFoldersDocument(JSON.parse(text)) + } catch { + return EMPTY_FOLDERS_DOCUMENT + } +} + +/** + * 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 document - validated document to persist. + */ +export async function writeFoldersDocument(path: string, document: FoldersDocument): Promise { + const json = `${JSON.stringify(document, 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 + } +} diff --git a/src/index.ts b/src/index.ts index 20a11e0..e7a57f2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,11 @@ * - `PUT /workspace-groups/manual` — replace the whole manual overlay * (manual groups + per-workspace overrides). Validated against the current * rule categories, written atomically to the plugin-owned JSON sidecar. + * - `GET /workspace-groups/folders` — the per-workspace extra-folder overlay + * plus each workspace's root folder. + * - `PUT /workspace-groups/folders` — replace the folder overlay whole. + * Strictly validated (absolute paths, no duplicates, root membership) and + * written atomically; the saved document is echoed back. * * Core workspace.json / session storage is never touched. */ @@ -34,6 +39,12 @@ import { type PersistedTab, type TabsDocument, } from './host-tabs.ts' +import { + defaultFoldersPath, + readFoldersDocument, + validateFoldersDocument, + writeFoldersDocument, +} from './host-folders.ts' /** Plugin identity for cordis.yml rows. */ export const name = '@dsh-xhl/workspace-groups' @@ -104,6 +115,7 @@ export function apply(ctx: GroupsContext): void { const configPath = defaultConfigPath() const manualPath = defaultManualPath() const tabsPath = defaultTabsPath() + const foldersPath = defaultFoldersPath() ctx.effect(() => ctx.webServer.register({ kind: 'exact', @@ -230,4 +242,58 @@ export function apply(ctx: GroupsContext): void { res.end(body) }, }), '@dsh-xhl/workspace-groups: /workspace-groups/manual route') + + ctx.effect(() => ctx.webServer.register({ + kind: 'exact', + path: '/workspace-groups/folders', + handler: async (req, res) => { + if (req.method === 'GET' || req.method === 'HEAD') { + // The reader is tolerant by construction (a missing or torn sidecar is + // the empty document), so it cannot fail a GET. + const document = await readFoldersDocument(foldersPath) + const body = JSON.stringify(document) + res.writeHead(200, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'Content-Length': Buffer.byteLength(body), + }) + res.end(req.method === 'HEAD' ? undefined : body) + return + } + if (req.method !== 'PUT') { + writeError(res, 405, 'method not allowed') + return + } + let raw: unknown + try { + raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES)) + } catch (error) { + const status = error instanceof HttpError ? error.status : 400 + writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`) + return + } + let document + try { + document = validateFoldersDocument(raw) + } catch (error) { + writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`) + return + } + try { + await writeFoldersDocument(foldersPath, document) + } catch (error) { + writeError(res, 500, `workspace-groups: failed to write folder overlay: ${error instanceof Error ? error.message : String(error)}`) + return + } + // Echo the normalized document: the client renders exactly what the host + // accepted, not its own (possibly trimmed) guess. + const body = JSON.stringify(document) + res.writeHead(200, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + 'Content-Length': Buffer.byteLength(body), + }) + res.end(body) + }, + }), '@dsh-xhl/workspace-groups: /workspace-groups/folders route') } diff --git a/tests/folders.test.ts b/tests/folders.test.ts new file mode 100644 index 0000000..8b620fb --- /dev/null +++ b/tests/folders.test.ts @@ -0,0 +1,254 @@ +/** + * Per-workspace folder tests: the pure folder logic (path identity, root + * resolution, cwd ownership, entry editing) plus the host overlay's strict + * write validation and tolerant read, including the atomic file round-trip. + */ +import { describe, expect, it } from 'vitest' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { + addFolder, + effectiveFolders, + entryFor, + folderOfCwd, + removeFolder, + rootOf, + samePath, + setRoot, + type FoldersDocument, + type WorkspaceFolderEntry, +} from '../src/core/folders.ts' +import { + parseFoldersDocument, + readFoldersDocument, + validateFoldersDocument, + writeFoldersDocument, +} from '../src/host-folders.ts' + +const BASE = 'C:\\work\\project' +const EXTRA = 'C:\\work\\extra' + +describe('samePath', () => { + it('is case-insensitive for Windows-style paths', () => { + expect(samePath('C:\\Work\\Project', 'c:\\work\\project')).toBe(true) + }) + + it('ignores trailing separators', () => { + expect(samePath('C:\\work\\project\\', 'C:\\work\\project')).toBe(true) + expect(samePath('/home/me/project/', '/home/me/project')).toBe(true) + }) + + it('treats both separators as equal on Windows-style paths', () => { + expect(samePath('C:/work/project', 'C:\\work\\project')).toBe(true) + }) + + it('distinguishes different POSIX paths case-sensitively', () => { + expect(samePath('/home/me/Project', '/home/me/project')).toBe(false) + }) +}) + +describe('effectiveFolders / rootOf / entryFor', () => { + it('puts the workspace path first', () => { + expect(effectiveFolders(BASE, undefined)).toEqual([BASE]) + expect(effectiveFolders(BASE, { folders: [EXTRA] })).toEqual([BASE, EXTRA]) + }) + + it('drops blank, self-referencing and duplicate extras', () => { + expect(effectiveFolders(BASE, { folders: [' ', BASE, 'C:\\WORK\\EXTRA', EXTRA, EXTRA] })) + .toEqual([BASE, 'C:\\WORK\\EXTRA']) + }) + + it('falls back to the workspace path when no root is stored', () => { + expect(rootOf(BASE, undefined)).toBe(BASE) + expect(rootOf(BASE, { folders: [EXTRA] })).toBe(BASE) + }) + + it('returns the stored root', () => { + expect(rootOf(BASE, { folders: [EXTRA], root: EXTRA })).toBe(EXTRA) + }) + + it('ignores a dangling root that names no effective folder', () => { + expect(rootOf(BASE, { folders: [EXTRA], root: 'D:\\gone' })).toBe(BASE) + }) + + it('reads entries by workspace id', () => { + const document: FoldersDocument = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } } + expect(entryFor(document, 'ws-1')).toEqual({ folders: [EXTRA] }) + expect(entryFor(document, 'ws-2')).toBeUndefined() + }) +}) + +describe('folderOfCwd', () => { + const entry: WorkspaceFolderEntry = { folders: [EXTRA, 'C:\\work\\extra\\nested'] } + + it('returns the workspace path for an undefined cwd', () => { + expect(folderOfCwd(undefined, BASE, entry)).toBe(BASE) + }) + + it('returns the base for a cwd inside the workspace', () => { + expect(folderOfCwd('C:\\work\\project\\src', BASE, entry)).toBe(BASE) + }) + + it('returns the owning extra folder', () => { + expect(folderOfCwd('C:\\work\\extra\\src', BASE, entry)).toBe(EXTRA) + }) + + it('returns the most specific folder for a nested folder', () => { + expect(folderOfCwd('C:\\work\\extra\\nested\\deep', BASE, entry)).toBe('C:\\work\\extra\\nested') + }) + + it('returns the base for a cwd outside every folder', () => { + expect(folderOfCwd('D:\\elsewhere', BASE, entry)).toBe(BASE) + }) + + it('does not treat a name prefix as an ancestor', () => { + expect(folderOfCwd('C:\\work\\extrabonus', BASE, entry)).toBe(BASE) + }) + + it('matches the folder itself', () => { + expect(folderOfCwd('C:\\WORK\\EXTRA', BASE, entry)).toBe(EXTRA) + }) +}) + +describe('addFolder / removeFolder / setRoot', () => { + it('adds an extra folder and keeps the root', () => { + const next = addFolder({ folders: [EXTRA], root: EXTRA }, 'D:\\other') + expect(next).toEqual({ folders: [EXTRA, 'D:\\other'], root: EXTRA }) + }) + + it('is idempotent and trims', () => { + expect(addFolder({ folders: ['D:\\other'] }, ' D:\\other ')).toEqual({ folders: ['D:\\other'] }) + expect(addFolder(undefined, EXTRA)).toEqual({ folders: [EXTRA] }) + }) + + it('never mutates the input entry', () => { + const entry: WorkspaceFolderEntry = { folders: [EXTRA] } + addFolder(entry, 'D:\\other') + expect(entry).toEqual({ folders: [EXTRA] }) + }) + + it('drops a folder and clears a root pointing at it', () => { + expect(removeFolder({ folders: [EXTRA], root: EXTRA }, EXTRA)).toEqual({ folders: [] }) + expect(removeFolder({ folders: [EXTRA, 'D:\\other'], root: 'D:\\other' }, EXTRA)) + .toEqual({ folders: ['D:\\other'], root: 'D:\\other' }) + }) + + it('stores the root only for an extra folder', () => { + expect(setRoot({ folders: [EXTRA] }, EXTRA)).toEqual({ folders: [EXTRA], root: EXTRA }) + expect(setRoot({ folders: [EXTRA], root: EXTRA }, BASE)).toEqual({ folders: [EXTRA] }) + expect(setRoot(undefined, BASE)).toEqual({ folders: [] }) + }) +}) + +describe('validateFoldersDocument', () => { + const valid = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } } + + it('accepts a valid document', () => { + expect(validateFoldersDocument(valid)).toEqual(valid) + }) + + it('rejects a wrong version', () => { + expect(() => validateFoldersDocument({ version: 2, workspaces: {} })).toThrow(/version/) + }) + + it('rejects a non-object document', () => { + expect(() => validateFoldersDocument([])).toThrow(/mapping/) + expect(() => validateFoldersDocument('nope')).toThrow(/mapping/) + }) + + it('rejects a relative folder path', () => { + expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders: ['work'] } } })) + .toThrow(/absolute/) + }) + + it('rejects case-insensitive duplicates', () => { + expect(() => validateFoldersDocument({ + version: 1, + workspaces: { 'ws-1': { folders: [EXTRA, 'c:\\WORK\\extra'] } }, + })).toThrow(/duplicate/) + }) + + it('rejects a root that is not one of the folders', () => { + expect(() => validateFoldersDocument({ + version: 1, + workspaces: { 'ws-1': { folders: [EXTRA], root: 'D:\\other' } }, + })).toThrow(/root/) + }) + + it('rejects a NUL byte and an over-long path', () => { + expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\a\u0000b'] } } })) + .toThrow(/NUL/) + expect(() => validateFoldersDocument({ + version: 1, + workspaces: { 'ws-1': { folders: ['C:\\' + 'a'.repeat(1100)] } }, + })).toThrow(/1024/) + }) + + it('rejects more than 32 folders', () => { + const folders = Array.from({ length: 33 }, (_, index) => `C:\\w\\${index}`) + expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders } } })) + .toThrow(/32/) + }) + + it('rejects an over-long workspace id', () => { + expect(() => validateFoldersDocument({ + version: 1, + workspaces: { ['w'.repeat(201)]: { folders: [EXTRA] } }, + })).toThrow(/200/) + }) +}) + +describe('parseFoldersDocument (tolerant read)', () => { + it('returns the empty document for junk instead of throwing', () => { + expect(parseFoldersDocument(undefined)).toEqual({ version: 1, workspaces: {} }) + expect(parseFoldersDocument(null)).toEqual({ version: 1, workspaces: {} }) + expect(parseFoldersDocument([])).toEqual({ version: 1, workspaces: {} }) + expect(parseFoldersDocument({ version: 7, workspaces: {} })).toEqual({ version: 1, workspaces: {} }) + }) + + it('drops bad folders, duplicates and dangling roots', () => { + const parsed = parseFoldersDocument({ + version: 1, + workspaces: { + 'ws-1': { folders: [EXTRA, 'relative', 42, 'c:\\WORK\\extra', ''] , root: 'D:\\gone' }, + '': { folders: [EXTRA] }, + 'ws-2': 'nope', + }, + }) + expect(parsed).toEqual({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } }) + }) + + it('keeps a valid root and tolerates a dangling workspace id', () => { + const parsed = parseFoldersDocument({ + version: 1, + workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } }, + }) + expect(parsed.workspaces['ws-1']).toEqual({ folders: [EXTRA], root: EXTRA }) + }) +}) + +describe('readFoldersDocument / writeFoldersDocument', () => { + it('reads a missing file as the empty document', async () => { + const dir = await mkdtemp(join(tmpdir(), 'wg-folders-')) + try { + expect(await readFoldersDocument(join(dir, 'missing.json'))).toEqual({ version: 1, workspaces: {} }) + await writeFile(join(dir, 'junk.json'), '{not json', 'utf8') + expect(await readFoldersDocument(join(dir, 'junk.json'))).toEqual({ version: 1, workspaces: {} }) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) + + it('round-trips a document through the atomic write', async () => { + const dir = await mkdtemp(join(tmpdir(), 'wg-folders-')) + const path = join(dir, 'nested', 'workspace-groups.folders.json') + const document: FoldersDocument = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } } + try { + await writeFoldersDocument(path, document) + expect(await readFoldersDocument(path)).toEqual(document) + } finally { + await rm(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/tools/verify-folders.mjs b/tools/verify-folders.mjs new file mode 100644 index 0000000..a1cb6d0 --- /dev/null +++ b/tools/verify-folders.mjs @@ -0,0 +1,146 @@ +/** + * Standalone verifier for the per-workspace folder layer. + * + * vitest cannot spawn in this sandbox (EPERM), so this script runs the same + * critical assertions under plain Node 24 type-stripping: + * node tools/verify-folders.mjs + * + * It imports the pure module (`src/core/folders.ts`) and the host overlay + * (`src/host-folders.ts`, Node built-ins only), exercises the root/cwd rules and + * the strict-write / tolerant-read boundary, then prints exactly one line. + */ +import assert from 'node:assert/strict' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' + +const coreUrl = new URL('../src/core/folders.ts', import.meta.url) +const hostUrl = new URL('../src/host-folders.ts', import.meta.url) + +const { + addFolder, + effectiveFolders, + entryFor, + folderOfCwd, + removeFolder, + rootOf, + samePath, + setRoot, +} = await import(coreUrl.href) +const { + parseFoldersDocument, + readFoldersDocument, + validateFoldersDocument, + writeFoldersDocument, +} = await import(hostUrl.href) + +const BASE = 'C:\\work\\project' +const EXTRA = 'C:\\work\\extra' +let checks = 0 +const check = (condition, message) => { + checks += 1 + assert.ok(condition, message) +} +const equal = (actual, expected, message) => { + checks += 1 + assert.deepEqual(actual, expected, message) +} + +// --- path identity ----------------------------------------------------------- +check(samePath('C:\\Work\\Project', 'c:\\work\\project'), 'samePath is case-insensitive for Windows paths') +check(samePath('C:\\work\\project\\', 'C:\\work\\project'), 'samePath ignores a trailing separator') +check(samePath('C:/work/project', 'C:\\work\\project'), 'samePath folds separators on Windows paths') +check(!samePath('/home/me/Project', '/home/me/project'), 'POSIX paths stay case-sensitive') +check(!samePath('/home/me/project', '/home/me/projectfile'), 'a name prefix is not the same path') + +// --- effective folders / root ------------------------------------------------ +equal(effectiveFolders(BASE, undefined), [BASE], 'base folder is effective without an entry') +equal(effectiveFolders(BASE, { folders: [EXTRA] }), [BASE, EXTRA], 'base comes first, extras keep order') +equal( + effectiveFolders(BASE, { folders: [' ', BASE, 'C:\\WORK\\EXTRA', EXTRA, EXTRA] }), + [BASE, 'C:\\WORK\\EXTRA'], + 'blank, self-referencing and duplicate extras are dropped (first spelling wins)', +) +equal(rootOf(BASE, undefined), BASE, 'root defaults to the workspace path') +equal(rootOf(BASE, { folders: [EXTRA] }), BASE, 'root stays the workspace path when omitted') +equal(rootOf(BASE, { folders: [EXTRA], root: EXTRA }), EXTRA, 'stored root wins') +equal(rootOf(BASE, { folders: [EXTRA], root: 'D:\\gone' }), BASE, 'dangling root falls back to the base') +equal(entryFor({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } }, 'ws-1'), { folders: [EXTRA] }, 'entryFor reads by id') +equal(entryFor({ version: 1, workspaces: {} }, 'ws-2'), undefined, 'entryFor misses cleanly') + +// --- cwd ownership ----------------------------------------------------------- +const entry = { folders: [EXTRA, 'C:\\work\\extra\\nested'] } +equal(folderOfCwd(undefined, BASE, entry), BASE, 'undefined cwd owns the base') +equal(folderOfCwd('C:\\work\\project\\src', BASE, entry), BASE, 'a workspace cwd owns the base') +equal(folderOfCwd('C:\\work\\extra\\src', BASE, entry), EXTRA, 'an extra folder cwd owns that folder') +equal(folderOfCwd('C:\\work\\extra\\nested\\deep', BASE, entry), 'C:\\work\\extra\\nested', 'the most specific folder wins') +equal(folderOfCwd('D:\\elsewhere', BASE, entry), BASE, 'an outside cwd falls back to the base') +equal(folderOfCwd('C:\\work\\extrabonus', BASE, entry), BASE, 'a name prefix is not an ancestor') +equal(folderOfCwd('C:\\WORK\\EXTRA', BASE, entry), EXTRA, 'cwd matching is case-insensitive') + +// --- entry editing (pure, never mutating) ------------------------------------ +const before = { folders: [EXTRA] } +const added = addFolder(before, 'D:\\other') +equal(added, { folders: [EXTRA, 'D:\\other'] }, 'addFolder appends') +equal(before, { folders: [EXTRA] }, 'addFolder does not mutate its input') +equal(addFolder({ folders: ['D:\\other'] }, ' D:\\other '), { folders: ['D:\\other'] }, 'addFolder is idempotent and trims') +equal(addFolder(undefined, EXTRA), { folders: [EXTRA] }, 'addFolder creates an entry') +equal(removeFolder({ folders: [EXTRA], root: EXTRA }, EXTRA), { folders: [] }, 'removeFolder clears a root pointing at it') +equal( + removeFolder({ folders: [EXTRA, 'D:\\other'], root: 'D:\\other' }, EXTRA), + { folders: ['D:\\other'], root: 'D:\\other' }, + 'removeFolder keeps an unrelated root', +) +equal(setRoot({ folders: [EXTRA] }, EXTRA), { folders: [EXTRA], root: EXTRA }, 'setRoot stores an extra folder') +equal(setRoot({ folders: [EXTRA], root: EXTRA }, BASE), { folders: [EXTRA] }, 'setRoot on the base clears the root') +equal(setRoot(undefined, BASE), { folders: [] }, 'setRoot without extras yields an empty entry') + +// --- strict write validation ------------------------------------------------- +const valid = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } } +equal(validateFoldersDocument(valid), valid, 'a valid document round-trips validation') +const rejects = (value, pattern) => { + checks += 1 + assert.throws(() => validateFoldersDocument(value), pattern) +} +rejects({ version: 2, workspaces: {} }, /version/) +rejects([], /mapping/) +rejects('nope', /mapping/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: ['work'] } } }, /absolute/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA, 'c:\\WORK\\extra'] } } }, /duplicate/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: 'D:\\other' } } }, /root/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\a\u0000b'] } } }, /NUL/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\' + 'a'.repeat(1100)] } } }, /1024/) +rejects({ version: 1, workspaces: { 'ws-1': { folders: Array.from({ length: 33 }, (_, i) => `C:\\w\\${i}`) } } }, /32/) +rejects({ version: 1, workspaces: { ['w'.repeat(201)]: { folders: [EXTRA] } } }, /200/) + +// --- tolerant read ----------------------------------------------------------- +equal(parseFoldersDocument(undefined), { version: 1, workspaces: {} }, 'undefined parses empty') +equal(parseFoldersDocument({ version: 7, workspaces: {} }), { version: 1, workspaces: {} }, 'a bad version parses empty') +equal( + parseFoldersDocument({ + version: 1, + workspaces: { + 'ws-1': { folders: [EXTRA, 'relative', 42, 'c:\\WORK\\extra', ''], root: 'D:\\gone' }, + '': { folders: [EXTRA] }, + 'ws-2': 'nope', + }, + }), + { version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } }, + 'tolerant parse drops junk instead of throwing', +) + +// --- file round-trip --------------------------------------------------------- +const dir = await mkdtemp(join(tmpdir(), 'wg-folders-verify-')) +try { + equal(await readFoldersDocument(join(dir, 'missing.json')), { version: 1, workspaces: {} }, 'a missing file reads empty') + await writeFile(join(dir, 'junk.json'), '{not json', 'utf8') + equal(await readFoldersDocument(join(dir, 'junk.json')), { version: 1, workspaces: {} }, 'unreadable JSON reads empty') + const path = join(dir, 'nested', 'workspace-groups.folders.json') + await writeFoldersDocument(path, valid) + equal(await readFoldersDocument(path), valid, 'atomic write round-trips through the reader') +} finally { + await rm(dir, { recursive: true, force: true }) +} + +// Success is a single machine-checkable line: the harness pastes this output. +process.stdout.write('folders: all assertions passed\n')