From 2fb87d190460f1da3ae02692f35a4b5a888d8aad Mon Sep 17 00:00:00 2001 From: qyh15 Date: Wed, 28 Oct 2026 18:44:51 +0800 Subject: [PATCH] release: workspace-groups-local 1.0.0 --- CHANGELOG.md | 25 ++ DEVELOPMENT.md | 12 +- README.md | 29 +- README_ZH.md | 20 +- lib/client.js | 375 +++++++++++++++++++------ lib/client.js.map | 2 +- lib/index.js | 178 ++++-------- lib/types/client/GroupsBrowser.d.ts | 2 +- lib/types/client/contract.d.ts | 9 + lib/types/client/directory-flow.d.ts | 4 + lib/types/client/folder-directory.d.ts | 13 + lib/types/client/folders-persist.d.ts | 15 - lib/types/client/locales.d.ts | 2 +- lib/types/client/rows.d.ts | 5 +- lib/types/host-folders.d.ts | 42 +-- package.json | 2 +- src/client/GroupsBrowser.tsx | 179 ++++++++---- src/client/contract.ts | 9 + src/client/directory-flow.ts | 16 ++ src/client/folder-directory.ts | 109 +++++++ src/client/folders-persist.ts | 35 --- src/client/index.ts | 5 + src/client/locales.ts | 22 +- src/client/rows.tsx | 15 +- src/host-folders.ts | 142 +++------- src/index.ts | 81 +++--- tests/folders.test.ts | 105 ++++++- tools/verify-directory-flow.mjs | 17 ++ tools/verify-folder-directory.mjs | 78 +++++ tools/verify-folders.mjs | 148 +++++++--- tsdown.config.ts | 17 +- 31 files changed, 1152 insertions(+), 561 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 lib/types/client/directory-flow.d.ts create mode 100644 lib/types/client/folder-directory.d.ts create mode 100644 src/client/directory-flow.ts create mode 100644 src/client/folder-directory.ts create mode 100644 tools/verify-directory-flow.mjs create mode 100644 tools/verify-folder-directory.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..98e9f35 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,25 @@ +# 更新日志 + +## 1.0.0 — 2026-10-28 + +首个本地稳定版本,包名 `workspace-groups-local`。基于原项目扩展,保留原 MIT 许可证与版权声明。 + +### 功能 +- 工作区分组:颜色、图标、置顶、折叠动画、拖拽归组与排序。 +- 分组行新增工作区入口,创建后自动归组并展开。 +- 会话标签:固定、拖拽排序、中键关闭、右键菜单、双击重命名。 +- 多文件夹与默认根目录配置。 +- 移除侧栏花朵的连线,保留花朵标记。 + +### SSH 兼容与修复 +- 顶部与分组新增工作区入口复用已注册的自包含目录选择窗口,包括 remote-ssh 的本地/远程窗口。 +- 未注册选择窗口时,回退 DSH 原生本地目录选择器;不强制依赖 SSH 插件。 +- 统一创建文件夹入口:本地使用 DSH API,远程使用 SSH 插件接口;远程失败禁止回退本地写入。 +- 停止复制子目录 SSH 标记,旧标记不自动删除。 +- 对需要额外渲染器上下文的第三方选择窗口明确报错,不静默丢弃其上下文。 + +### 验证与限制 +- 类型检查、构建及纯逻辑/模拟接口回归测试通过。 +- 用户已确认本次界面改动可用;未完成卸载 SSH 插件的独立环境测试及所有真实服务器组合测试。 +- remote-ssh 2.4.40 的远程子目录会话路由不一致:暂时阻止从这些子目录新建会话,可在注册的远程工作区根启动。 +- 本次仅本地 Git 提交与版本标记;未发布 npm、GitHub Release 或插件市场。公开发布前需设置自己的仓库元数据并完成安装验证。 diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index c0fd015..8927a97 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -179,7 +179,11 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa 额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让 用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。 真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。 - 另外 `POST /workspace-groups/folders` 会在**镜像内新增的子目录**里补一份 - `.remote-ssh.json`(`remotePath` 拼到对应远端子目录):SSH 插件的 shell wrapper 与 - 部分 fs 桥只在**会话 cwd 本身**找这个标记、不向上遍历,缺了它子目录会话会退化成 - 本地终端。该文件被同步流程永久排除,不会落到服务器。 + `POST /workspace-groups/folders` 已停用(410):禁止复制子 marker,避免绕过父写回规则。 + 统一创建入口在 `src/client/folder-directory.ts`:listWorkspaces 判归属,本地使用 DSH + createDirectory,远端用专属 mkdir API(递归幂等),不走可能降级本地的 sidebar fs.mkdir。 + 缺 SSH 的已知镜像、网络/鉴权失败、坏目录清单和重叠根一律报错。远程子目录会话暂阻断, + 因 remote-ssh 2.4.40 模型工具仍只匹配注册根 cwd。历史 marker 不自动清理。 + 验证:`node tools/verify-folder-directory.mjs`(模拟 API)和 + `node --experimental-transform-types tools/verify-folders.mjs`(含 marker POST 拒绝回归)。 + 不要把静态检查/模拟通过当成实机 SSH 联调通过。 diff --git a/README.md b/README.md index 891bf15..f7344fe 100644 --- a/README.md +++ b/README.md @@ -94,17 +94,24 @@ 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 -- **Remote (SSH) projects are mirror-backed**: `@zhangfengshun/dsh-remote-ssh` registers a - remote workspace as an ordinary workspace whose directory is a LOCAL mirror - (`/.dsh/remote-workspaces/`) of the remote root. For those projects the - dialog swaps the folder picker for a **relative-path field**, so an extra folder is always a - subdirectory of that mirror — i.e. a directory that also exists on the server. Picking an - unrelated local directory is refused, because a session there would never sync: a separate - remote root should be its own workspace (add it with the SSH plugin), grouped next to this one -- Such an extra folder gets a **`.remote-ssh.json` stamped into it** (same connection record, - `remotePath` pointing at the matching remote subdirectory). The SSH plugin reads that record at - the session cwd only, never walking up, so without it a session in the subdirectory would fall - back to a LOCAL terminal. The file is always excluded from sync, so it never reaches the server +- **Unified Create folder**: enter one child name in either workspace type. Local workspaces + call DSH `uiWorkspace.createDirectory`; registered SSH mirrors call the SSH-owned + `/remote-ssh/api/mkdir` with the profile and mapped remote path. SSH is optional for local use. + Remote mkdir is recursive/idempotent (existing remote directories are reused), unlike the + native local operation. Failures do not fall back to creating local mirror directories. +- SSH recognition uses `listWorkspaces`, including non-default mirror locations. A missing + plugin or unregistered default mirror fails closed; malformed catalogs and overlapping roots + are rejected. The existing local folder picker remains available for attaching local folders. +- **SSH subdirectory sessions are not fully supported by remote-ssh 2.4.40**. Creation is + blocked with an explanation; open a session at the registered remote workspace root instead. + A separate remote root should be registered through the SSH plugin. Folder creation itself + does not create or change any SSH registration. +- **No child `.remote-ssh.json` is written**. The old marker POST returns 410. Child markers do + not establish model-tool context and can bypass parent write-back exclusions. Previously + created markers are NOT automatically deleted; review them before using old subdirectory + sessions. Root SSH markers remain owned by the SSH plugin. +- Verification uses mocked APIs plus host route fixtures; live SSH/terminal/UI behavior still + requires an integration test before publishing. ### Search & operations - **Tree-shaped search**: results keep the three-level structure (category → project → matched diff --git a/README_ZH.md b/README_ZH.md index 1474b38..6687bbf 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -77,14 +77,18 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点 沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话 - 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态, 故意不持久化 -- **远程(SSH)项目是镜像式工作区**:`@zhangfengshun/dsh-remote-ssh` 把远程工作区登记成 - 普通工作区,目录是远端根在**本地的镜像**(`/.dsh/remote-workspaces/<工作区id>`)。 - 这类项目里弹窗会把“挑文件夹”换成**相对路径输入框**,额外文件夹只能是该镜像内的子目录 - ——也就是服务器上同样存在的目录;挑一个无关的本地目录会被拒绝,因为那种会话永远不会同步。 - 服务器上另一个不相干的根目录,应该用 SSH 插件单独建成一个工作区,再用分组放到一起 -- 远程项目的额外文件夹会**自动补一个 `.remote-ssh.json`**(连接信息,`remotePath` 指向 - 对应远端子目录)。原因:SSH 插件只在“当前工作目录”读这个标记、不向上找,缺了它这些 - 子目录里的会话会退化成**本地终端**。该文件永远被同步排除,不会推到服务器上 +- **统一“创建文件夹”**:输入一个子目录名,本地调用 DSH 原生 `uiWorkspace.createDirectory`; + 已注册的远程镜像调用 SSH 专属 `/remote-ssh/api/mkdir`,传连接 ID 和映射后的远端路径。 + 本地功能不依赖 SSH 插件。远端接口为 `mkdir -p`,同名目录存在时复用;本地沿用原生行为。 + SSH 不可用或请求失败时绝不降级为镜像里的本地创建。普通本地目录仍可用“添加文件夹”选取。 +- 通过 SSH 的 `listWorkspaces` 识别已注册镜像,支持非默认镜像位置;重叠注册根、坏响应、 + 未注册的默认镜像路径会报错。此功能不另建 SSH 工作区,也不改动它的连接配置。 +- **remote-ssh 2.4.40 不完整支持子目录会话**:新建此类会话暂时阻断并提示从注册的远程工作区根 + 打开。创建远端文件夹本身不受此限制;另一个远端根请通过 SSH 插件注册。 +- **不再复制 `.remote-ssh.json` 到子目录**,旧 POST 接口返回 410。复制标记不能修复模型工具 + 上下文,还可能绕过父工作区写回限制。历史子目录标记不会自动删除,应审查后再使用旧会话; + 工作区根标记仍由 SSH 插件管理。此前“子标记永远不会同步”的说明不成立,已撤回。 +- 自动验证使用模拟 API 和临时目录;真实 SSH、终端和界面尚需发布前联调。 ### 搜索与操作 - **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 + diff --git a/lib/client.js b/lib/client.js index 90a7842..b376bc4 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,5 +1,5 @@ window.__ModuleLoader__.load({ - id: "@dsh-xhl/workspace-groups", + id: "workspace-groups-local", factory: (require) => { var module = { exports: {} }; var exports = module.exports; @@ -1624,7 +1624,7 @@ window.__ModuleLoader__.load({ * groups via overlay renames/hides), draggable source for group reorder and * drop target for both workspace moves and group reorders. */ - function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }) { + function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace = false, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }) { const [menuOpen, setMenuOpen] = (0, react.useState)(false); const count = node.workspaces.length; const manageable = onRename !== void 0 && onDelete !== void 0; @@ -1697,6 +1697,22 @@ window.__ModuleLoader__.load({ "aria-hidden": true, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPinFillMedium, {}) }), + onAddWorkspace !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { + className: "wgRowActions", + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", { + type: "button", + className: "wgIconButton", + draggable: false, + disabled: addingWorkspace, + title: t("workspace.add"), + "aria-label": `${t("workspace.add")} · ${node.label}`, + onClick: (event) => { + event.stopPropagation(); + onAddWorkspace(); + }, + children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutlineRegular, {}) + }) + }), manageable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { className: "wgRowActions", children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, { @@ -2199,38 +2215,103 @@ window.__ModuleLoader__.load({ }); if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`); } - /** - * Ask the host to stamp the remote-ssh connection record into an extra folder of - * a MIRROR workspace. - * - * remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the - * session cwd and never walks up, so a folder below the mirror root would - * otherwise get a local terminal. Best-effort: the folder itself is already - * persisted by the time this runs, and a local workspace answers `marked:false` - * (nothing to stamp) rather than failing. - * @param workspacePath - the workspace's canonical directory (mirror root). - * @param folderPath - the extra folder just added. - * @param fetchImpl - fetch implementation (injectable for tests). - * @returns true when a record was written. + //#endregion + //#region src/client/folder-directory.ts + /** One directory operation for local DSH and optional remote-ssh workspaces. + * Never send remote writes through the sidebar route: without its SSH interceptor + * that route can create a LOCAL directory instead. Use the SSH-owned API instead. */ - async function ensureRemoteFolderMarker(workspacePath, folderPath, fetchImpl = fetch) { - try { - const response = await fetchImpl(FOLDERS_ROUTE, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - workspacePath, - folderPath - }), - cache: "no-store" - }); - if (!response.ok) return false; - const body = await response.json(); - if (typeof body !== "object" || body === null) return false; - return body.marked === true; - } catch { - return false; + function object(value) { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0; + } + function message(value) { + const error = value?.error; + return typeof error === "string" ? error : typeof object(error)?.message === "string" ? String(object(error)?.message) : typeof value?.stderr === "string" && value.stderr !== "" ? value.stderr : "Remote SSH request failed"; + } + async function rpc(method, body, fetchImpl) { + const response = await fetchImpl(`/remote-ssh/api/${method}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Requested-With": "XMLHttpRequest" + }, + body: JSON.stringify(body), + cache: "no-store", + signal: AbortSignal.timeout(3e4) + }); + if (response.status === 404 && method === "listWorkspaces") return null; + if (!response.ok) throw new Error(`Remote SSH ${method}: HTTP ${response.status}`); + const envelope = object(await response.json()); + const value = object(envelope?.value); + if (envelope?.ok !== true || value?.ok !== true) throw new Error(message(value ?? envelope)); + return value; + } + /** A marker is only a refusal hint, never authority to execute remote commands. */ + async function refuseMarkedLocalPath(path, fetchImpl) { + const response = await fetchImpl(`/workspace-groups/remote-hint?path=${encodeURIComponent(path)}`, { + cache: "no-store", + signal: AbortSignal.timeout(1e4) + }); + if (!response.ok) throw new Error(`Cannot verify local directory: HTTP ${response.status}`); + const body = object(await response.json()); + if (typeof body?.remoteHint !== "boolean") throw new Error("Invalid directory safety response"); + if (body.remoteHint) throw new Error("SSH marker detected but no active registered remote workspace; refusing local operation"); + } + /** Resolve against the SSH plugin's registered mirrors, not copied marker files. */ + async function remoteFolderWorkspace(path, remoteBase, fetchImpl = fetch) { + const value = await rpc("listWorkspaces", {}, fetchImpl); + const knownMirror = remoteBase !== null && isUnderBase(path, remoteBase); + if (value === null) { + if (knownMirror) throw new Error("SSH plugin is unavailable; refusing a local operation in a remote mirror"); + await refuseMarkedLocalPath(path, fetchImpl); + return null; } + if (!Array.isArray(value.workspaces)) throw new Error("Invalid SSH workspace catalog"); + const matches = []; + for (const raw of value.workspaces) { + const row = object(raw); + if (!row || typeof row.mirrorPath !== "string" || typeof row.remotePath !== "string" || typeof row.profileId !== "string" || !row.mirrorPath || !row.remotePath || !row.profileId) throw new Error("Invalid SSH workspace entry"); + if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) matches.push({ + mirrorPath: row.mirrorPath, + remotePath: row.remotePath, + profileId: row.profileId + }); + } + if (matches.length > 1) throw new Error("Overlapping SSH workspaces are not supported safely"); + if (matches.length === 1) return matches[0]; + if (knownMirror) throw new Error("Remote mirror is not registered with the SSH plugin"); + await refuseMarkedLocalPath(path, fetchImpl); + return null; + } + /** Single-segment names match DSH createDirectory(path, name). */ + function validateFolderName(raw) { + const name = raw.trim(); + if (!name || name === "." || name === ".." || /[\\/\u0000-\u001f]/u.test(name)) throw new Error("Enter a single folder name, not an absolute path or nested path"); + return name; + } + async function createWorkspaceDirectory(parent, rawName, remoteBase, createLocal, fetchImpl = fetch) { + const name = validateFolderName(rawName); + const path = joinSubpath(parent, name); + if (path === null) throw new Error("Invalid folder name"); + const remote = await remoteFolderWorkspace(parent, remoteBase, fetchImpl); + if (!remote) return { + path: await createLocal(parent, name), + remote: false + }; + if (/[\u0000-\u001f`$"\\]/u.test(name)) throw new Error("Unsupported remote folder name"); + const normalizedParent = parent.trim().replace(/\\/gu, "/").replace(/\/+$/u, ""); + const normalizedRoot = remote.mirrorPath.trim().replace(/\\/gu, "/").replace(/\/+$/u, ""); + const suffix = normalizedParent.slice(normalizedRoot.length).replace(/^\/+/, ""); + if (suffix.split("/").some((part) => part === ".." || part === ".")) throw new Error("Invalid mirror path"); + const remotePath = `${remote.remotePath.replace(/\/+$/u, "")}/${suffix ? `${suffix}/` : ""}${name}`; + await rpc("mkdir", { + profileId: remote.profileId, + path: remotePath + }, fetchImpl); + return { + path, + remote: true + }; } //#endregion //#region src/client/open-folder.ts @@ -3738,7 +3819,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, createSessionIn, 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, getDirectoryFlow, createDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t }) { (0, react.useEffect)(() => { const style = document.createElement("style"); style.setAttribute("data-plugin", "dsh-workspace-groups"); @@ -3781,6 +3862,7 @@ window.__ModuleLoader__.load({ const [collapsedFolderKeys, setCollapsedFolderKeys] = (0, react.useState)([]); const [foldersTarget, setFoldersTarget] = (0, react.useState)(null); const [foldersBusy, setFoldersBusy] = (0, react.useState)(false); + const createdFolderPendingSave = (0, react.useRef)(null); const [creatingSessionIn, setCreatingSessionIn] = (0, react.useState)(null); const [foldersRemoteBase, setFoldersRemoteBase] = (0, react.useState)(null); (0, react.useEffect)(() => { @@ -3953,18 +4035,82 @@ window.__ModuleLoader__.load({ kind: "topLevel", key: UNCATEGORIZED_KEY }; + const [directoryFlowOpen, setDirectoryFlowOpen] = (0, react.useState)(false); + const [directoryFlow, setDirectoryFlow] = (0, react.useState)(null); + const DirectoryFlow = directoryFlow?.component; + const directoryRequest = (0, react.useRef)(null); + const finishDirectoryFlow = (path, error) => { + const pending = directoryRequest.current; + directoryRequest.current = null; + setDirectoryFlowOpen(false); + if (error !== void 0) pending?.reject(new Error(error)); + else pending?.resolve(path); + }; + (0, react.useEffect)(() => () => { + directoryRequest.current?.resolve(null); + directoryRequest.current = null; + }, []); + const pickWorkspaceDirectory = () => { + const flow = getDirectoryFlow(); + if (!flow) return pickDirectory(); + if (directoryRequest.current) return Promise.resolve(null); + setDirectoryFlow(flow); + return new Promise((resolve, reject) => { + directoryRequest.current = { + resolve, + reject + }; + setDirectoryFlowOpen(true); + }); + }; const [adding, setAdding] = (0, react.useState)(false); const [addError, setAddError] = (0, react.useState)(null); const [addErrorOpen, setAddErrorOpen] = (0, react.useState)(false); - const addWorkspace = async () => { - if (adding) return; + const addCategoryRef = (0, react.useRef)(void 0); + const currentGrouping = (0, react.useRef)({ + manual, + groups, + manualSaving + }); + currentGrouping.current = { + manual, + groups, + manualSaving + }; + const addWorkspace = async (categoryKey) => { + if (adding || manualSaving) return; + addCategoryRef.current = categoryKey; setAdding(true); setAddError(null); setAddErrorOpen(false); try { - const path = await pickDirectory(); + const path = await pickWorkspaceDirectory(); if (path === null) return; - startSession((await createWorkspace({ path })).workspaceId); + const workspace = await createWorkspace({ path }); + if (categoryKey !== void 0) { + const latest = currentGrouping.current; + if (latest.manualSaving || !latest.groups.some((group) => group.key === categoryKey)) throw new Error("The group changed while adding the workspace. Please retry from the target group."); + const workspaceId = workspace.workspaceId; + const workspaceOrder = Object.fromEntries(Object.entries(latest.manual.workspaceOrder).map(([key, ids]) => [key, ids.filter((id) => id !== workspaceId)])); + workspaceOrder[categoryKey] = [...workspaceOrder[categoryKey] ?? [], workspaceId]; + const next = { + ...latest.manual, + assignments: { + ...latest.manual.assignments, + [workspaceId]: categoryKey + }, + workspaceOrder + }; + setManualSaving(true); + try { + await saveManualOverlay(next); + setManual(next); + actions.setCategoryExpanded(categoryKey, true); + } finally { + setManualSaving(false); + } + } + startSession(workspace.workspaceId); } catch (reason) { const message = reason instanceof Error ? reason.message : String(reason); setAddError(message); @@ -4097,14 +4243,19 @@ window.__ModuleLoader__.load({ if (foldersBusy) return; const workspace = workspaces.find((w) => w.workspaceId === workspaceId); if (workspace === void 0) return; - if (isRemoteWorkspace(workspace)) { - notifyFolder(t("folder.remoteNeedsSubpath")); - return; - } setFoldersBusy(true); try { + if (foldersRemoteBase === null) throw new Error(t("folder.notReady")); + if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) { + notifyFolder(t("folder.remoteNeedsSubpath")); + return; + } const path = await pickDirectory(); if (path === null) return; + if (await remoteFolderWorkspace(path, foldersRemoteBase)) { + notifyFolder(t("folder.remoteNeedsSubpath")); + return; + } const entry = entryFor(foldersDoc, workspaceId); if (effectiveFolders(workspace.path, entry).some((folder) => samePath(folder, path))) { notifyFolder(t("folder.duplicate")); @@ -4118,28 +4269,39 @@ window.__ModuleLoader__.load({ setFoldersBusy(false); } }; - /** - * Add a folder to a REMOTE workspace by typing a path relative to its mirror. - * The mirror is a copy of the remote root, so `/sub` and remote `sub` - * are the same directory — that is the only way an extra folder can mean - * something on both sides. - */ - const addSubpathTo = (workspaceId, relative) => { - if (foldersBusy) return; + /** The same gesture routes through native local or SSH-owned mkdir APIs. */ + const addSubpathTo = async (workspaceId, name) => { + if (foldersBusy) return false; const workspace = workspaces.find((w) => w.workspaceId === workspaceId); - if (workspace === void 0) return; - const path = joinSubpath(workspace.path, relative); - if (path === null) { - notifyFolder(t("folder.subpathInvalid")); - return; + if (workspace === void 0) return false; + setFoldersBusy(true); + try { + if (foldersRemoteBase === null) throw new Error(t("folder.notReady")); + const pending = createdFolderPendingSave.current; + const created = pending?.workspaceId === workspaceId && pending.name === name ? pending : await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory); + createdFolderPendingSave.current = { + workspaceId, + name, + path: created.path + }; + const entry = addFolder(entryFor(foldersDoc, workspaceId), created.path); + const next = { + version: 1, + workspaces: { + ...foldersDoc.workspaces, + [workspaceId]: entry + } + }; + await saveFolders(next); + setFoldersDoc(next); + createdFolderPendingSave.current = null; + return true; + } catch (reason) { + notifyFolder(`${t("folder.addError")}: ${reason instanceof Error ? reason.message : String(reason)}`); + return false; + } finally { + setFoldersBusy(false); } - 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)); - ensureRemoteFolderMarker(workspace.path, path); }; const setFolderRoot = (workspaceId, path) => { writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId), path)); @@ -4161,7 +4323,15 @@ window.__ModuleLoader__.load({ } if (creatingSessionIn !== null) return; setCreatingSessionIn(folderKey(workspaceId, path)); - createSessionIn(workspaceId, path).catch((reason) => { + (async () => { + const workspace = workspaces.find((w) => w.workspaceId === workspaceId); + if (!workspace) throw new Error("Workspace not found"); + if (foldersRemoteBase === null) throw new Error(t("folder.notReady")); + const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase); + const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase); + if (remote || targetRemote) throw new Error(t("folder.remoteSessionUnsupported")); + await createSessionIn(workspaceId, path); + })().catch((reason) => { const detail = reason instanceof Error ? reason.message : String(reason); notifyFolder(`${t("folder.sessionError")}: ${detail}`); }).finally(() => { @@ -4624,7 +4794,9 @@ window.__ModuleLoader__.load({ className: "wgIconButton", "aria-label": t("workspace.add"), disabled: adding, - onClick: addWorkspace, + onClick: () => { + addWorkspace(); + }, children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconProjectAddOutlineRegular, { size: wide ? 16 : 18 }) }) }) @@ -4739,6 +4911,10 @@ window.__ModuleLoader__.load({ onSessionRename, onSessionArchive, onFork: forkSession, + onAddWorkspace: () => { + addWorkspace(category.key); + }, + addingWorkspace: adding || manualSaving, onGroupRename: () => { setGroupDraft(category.key); setGroupError(null); @@ -5036,9 +5212,7 @@ window.__ModuleLoader__.load({ onAdd: () => { addFolderTo(foldersTarget); }, - onAddSubpath: (relative) => { - addSubpathTo(foldersTarget, relative); - }, + onAddSubpath: (relative) => addSubpathTo(foldersTarget, relative), onSetRoot: (path) => { setFolderRoot(foldersTarget, path); }, @@ -5150,6 +5324,20 @@ window.__ModuleLoader__.load({ children: sessionRenameError })] }), + directoryFlowOpen && DirectoryFlow && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DirectoryFlow, { + ...directoryFlow?.injected, + open: true, + busy: false, + onPicked: (path) => { + finishDirectoryFlow(path); + }, + onCancel: () => { + finishDirectoryFlow(null); + }, + onError: (message) => { + finishDirectoryFlow(null, message); + } + }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Modal, { open: addErrorOpen, onClose: () => { @@ -5165,7 +5353,9 @@ window.__ModuleLoader__.load({ children: t("close") }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { variant: "primary", - onClick: addWorkspace, + onClick: () => { + addWorkspace(addCategoryRef.current); + }, children: t("retry") })] }), children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { @@ -5275,7 +5465,7 @@ window.__ModuleLoader__.load({ }); } /** 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, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }) { + function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onAddWorkspace, addingWorkspace, 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", { @@ -5284,6 +5474,8 @@ window.__ModuleLoader__.load({ node: category, t, onToggle: onToggleCategory, + onAddWorkspace, + addingWorkspace, onRename: onGroupRename, onDelete: onGroupDelete, onTogglePin: onGroupTogglePin, @@ -5610,8 +5802,10 @@ window.__ModuleLoader__.load({ const [subpath, setSubpath] = (0, react.useState)(""); const submitSubpath = () => { if (subpath.trim() === "") return; - onAddSubpath(subpath); - setSubpath(""); + if (busy) return; + onAddSubpath(subpath).then((success) => { + if (success) setSubpath(""); + }); }; return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, { open: true, @@ -5681,9 +5875,9 @@ window.__ModuleLoader__.load({ ] }, path); }) - }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { + }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { className: "wgFolderListFooter", - children: remote ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { + children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { className: "wgFolderHint", children: t("folder.remoteHint") }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { @@ -5707,16 +5901,27 @@ window.__ModuleLoader__.load({ onClick: submitSubpath, children: t("folder.addSubpath") })] - })] }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, { + })] }), !remote && /* @__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/directory-flow.ts + /** Adapt the elected self-contained picker, without stealing its original slot. */ + function directoryFlowFromEntry(entry) { + if (!entry) return null; + if (entry.store || entry.locale || entry.children || typeof entry.component !== "function") throw new Error("This directory picker requires an unsupported renderer context."); + return { + component: entry.component, + injected: entry.inject?.() ?? {} + }; + } + //#endregion //#region src/client/locales.ts /** Simplified Chinese dictionary. */ const zh = { @@ -5761,11 +5966,13 @@ window.__ModuleLoader__.load({ "folder.addError": "添加文件夹失败", "folder.sessionError": "新建会话失败", "folder.saveError": "文件夹保存失败", - "folder.remoteHint": "远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)", + "folder.notReady": "目录安全信息尚未加载,请重启 DSH 并刷新页面后重试", + "folder.remoteSessionUnsupported": "当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。", + "folder.remoteHint": "输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。", "folder.remoteNeedsSubpath": "远程工作区请用子目录方式添加文件夹", - "folder.subpathLabel": "相对路径", - "folder.subpathPlaceholder": "例如 data 或 src/generated", - "folder.addSubpath": "添加子目录", + "folder.subpathLabel": "文件夹名称", + "folder.subpathPlaceholder": "例如 data", + "folder.addSubpath": "创建文件夹", "folder.subpathInvalid": "路径无效:请填工作区内的相对路径,不能用绝对路径或 ..", "group.create": "新建分组", "group.createTitle": "新建分组", @@ -5893,11 +6100,13 @@ window.__ModuleLoader__.load({ "folder.addError": "Could not add the folder", "folder.sessionError": "Could not start a session", "folder.saveError": "Could not save folders", - "folder.remoteHint": "Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root", + "folder.notReady": "Directory safety information is not loaded. Restart DSH and refresh the page before retrying.", + "folder.remoteSessionUnsupported": "This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.", + "folder.remoteHint": "Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.", "folder.remoteNeedsSubpath": "Remote workspaces take a subdirectory, not a picked folder", - "folder.subpathLabel": "Relative path", - "folder.subpathPlaceholder": "e.g. data or src/generated", - "folder.addSubpath": "Add subdirectory", + "folder.subpathLabel": "Folder name", + "folder.subpathPlaceholder": "e.g. data", + "folder.addSubpath": "Create folder", "folder.subpathInvalid": "Invalid path: use a relative path inside the workspace (no absolute paths, no ..)", "group.create": "New group", "group.createTitle": "New group", @@ -6076,6 +6285,8 @@ window.__ModuleLoader__.load({ await ctx.uiWorkspace.archiveSession(sessionId); }, pickDirectory: () => ctx.uiWorkspace.pickDirectory(), + getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot("sidebar.workspaces.directoryFlow")[0]), + createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name), searchSessions, searchResultLimit: ctx.sessions.searchResultLimit, hooks: { directoryFlow: { diff --git a/lib/client.js.map b/lib/client.js.map index dd535e7..796ee63 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","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 * One path with trailing separators removed, spelling preserved (no case\n * folding) — the form to STORE. A drive/UNC/root prefix keeps its separator.\n * @param path - raw path.\n */\nfunction withoutTrailingSeparator(path: string): string {\n if (isWindowsStyle(path)) {\n let value = path.replaceAll('/', '\\\\')\n while (value.length > 3 && value.endsWith('\\\\')) value = value.slice(0, -1)\n return value\n }\n let value = path\n while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)\n return value\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 const value = withoutTrailingSeparator(trimmed)\n return isWindowsStyle(trimmed) ? value.toLowerCase() : 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\n/**\n * True when `path` is `base` itself or lives somewhere below it, with the same\n * separator and case rules as {@link samePath}.\n * @param path - candidate path.\n * @param base - containing directory.\n */\nexport function isUnderBase(path: string, base: string): boolean {\n const root = canonicalPath(base)\n const target = canonicalPath(path)\n if (root === '' || target === '') return false\n if (target === root) return true\n const separator = isWindowsStyle(root) ? '\\\\' : '/'\n const prefix = root.endsWith(separator) ? root : `${root}${separator}`\n return target.startsWith(prefix)\n}\n\n/**\n * Resolve a user-typed SUBPATH against a base directory.\n *\n * This is what remote (mirror-backed) workspaces need: their canonical\n * directory is a local mirror of a remote root, so an extra folder must be a\n * directory INSIDE the mirror — that is the only spelling that also exists on\n * the remote side. Absolute input and `..` escapes are rejected outright so a\n * typo cannot smuggle in an unrelated local directory.\n * @param base - the workspace's canonical directory.\n * @param relative - typed subpath, either separator style.\n * @returns the joined path, or null when the input is empty, absolute, or\n * escapes the base.\n */\nexport function joinSubpath(base: string, relative: string): string | null {\n const root = base.trim()\n const raw = relative.trim()\n if (root === '' || raw === '') return null\n if (WINDOWS_DRIVE.test(raw) || WINDOWS_UNC.test(raw) || raw.startsWith('/')) return null\n const segments = raw.split(/[\\\\/]+/u).filter(segment => segment !== '' && segment !== '.')\n if (segments.length === 0) return null\n if (segments.includes('..')) return null\n const windows = isWindowsStyle(root)\n const separator = windows ? '\\\\' : '/'\n return `${withoutTrailingSeparator(root)}${separator}${segments.join(separator)}`\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/** One successful read: the overlay plus the mirror base the host reported. */\nexport interface FoldersSnapshot {\n readonly document: FoldersDocument\n /**\n * Local mirror root of the remote-ssh plugin, when the host named one.\n * Workspaces whose directory lives below it are remote mirrors, so their extra\n * folders must be subdirectories of that same mirror.\n */\n readonly remoteBase?: string\n}\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 overlay plus the reported mirror base; the empty document on any\n * 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 { document: EMPTY_FOLDERS_DOCUMENT }\n const body: unknown = await response.json()\n if (typeof body !== 'object' || body === null) return { document: EMPTY_FOLDERS_DOCUMENT }\n const source = body as Record\n const remoteBase = typeof source.remoteBase === 'string' && source.remoteBase.trim() !== ''\n ? source.remoteBase.trim()\n : undefined\n const base = remoteBase === undefined ? {} : { remoteBase }\n if (source.version !== 1) return { document: EMPTY_FOLDERS_DOCUMENT, ...base }\n if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {\n return { document: { version: 1, workspaces: {} }, ...base }\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 { document: { version: 1, workspaces }, ...base }\n } catch {\n return { document: 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\n/**\n * Ask the host to stamp the remote-ssh connection record into an extra folder of\n * a MIRROR workspace.\n *\n * remote-ssh decides \"remote backed\" by reading `.remote-ssh.json` at the\n * session cwd and never walks up, so a folder below the mirror root would\n * otherwise get a local terminal. Best-effort: the folder itself is already\n * persisted by the time this runs, and a local workspace answers `marked:false`\n * (nothing to stamp) rather than failing.\n * @param workspacePath - the workspace's canonical directory (mirror root).\n * @param folderPath - the extra folder just added.\n * @param fetchImpl - fetch implementation (injectable for tests).\n * @returns true when a record was written.\n */\nexport async function ensureRemoteFolderMarker(\n workspacePath: string,\n folderPath: string,\n fetchImpl: typeof fetch = fetch,\n): Promise {\n try {\n const response = await fetchImpl(FOLDERS_ROUTE, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ workspacePath, folderPath }),\n cache: 'no-store',\n })\n if (!response.ok) return false\n const body: unknown = await response.json()\n if (typeof body !== 'object' || body === null) return false\n return (body as { marked?: unknown }).marked === true\n } catch {\n return false\n }\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, isUnderBase, joinSubpath, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'\r\nimport { ensureRemoteFolderMarker, 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 // Local mirror root of the remote-ssh plugin, as reported by the host. A\r\n // project whose directory lives below it is a REMOTE workspace: its folder is\r\n // a mirror of one remote root, so extra folders must be subdirectories of that\r\n // mirror — anything else would exist on this machine only.\r\n const [foldersRemoteBase, setFoldersRemoteBase] = useState(null)\r\n useEffect(() => {\r\n let cancelled = false\r\n void loadFolders().then((snapshot) => {\r\n if (cancelled) return\r\n setFoldersDoc(snapshot.document)\r\n setFoldersRemoteBase(snapshot.remoteBase ?? null)\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 isRemoteWorkspace = (workspace: WorkspaceView): boolean => (\r\n foldersRemoteBase !== null && isUnderBase(workspace.path, foldersRemoteBase)\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 // A remote workspace's directory is a local MIRROR of one remote root; the\r\n // native picker would happily return an unrelated local directory that has\r\n // no remote counterpart, so that path is closed off here and the dialog\r\n // takes a subpath instead.\r\n if (isRemoteWorkspace(workspace)) {\r\n notifyFolder(t('folder.remoteNeedsSubpath'))\r\n return\r\n }\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 /**\r\n * Add a folder to a REMOTE workspace by typing a path relative to its mirror.\r\n * The mirror is a copy of the remote root, so `/sub` and remote `sub`\r\n * are the same directory — that is the only way an extra folder can mean\r\n * something on both sides.\r\n */\r\n const addSubpathTo = (workspaceId: WorkspaceId, relative: string): void => {\r\n if (foldersBusy) return\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return\r\n const path = joinSubpath(workspace.path, relative)\r\n if (path === null) {\r\n notifyFolder(t('folder.subpathInvalid'))\r\n return\r\n }\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 // Mirror subdirectory: also stamp the remote-ssh record, otherwise the new\r\n // folder's sessions would lose the remote terminal (remote-ssh reads the\r\n // record at the cwd only). Fire and forget — the folder row already works.\r\n void ensureRemoteFolderMarker(workspace.path, path)\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 onAddSubpath={(relative) => { addSubpathTo(foldersTarget, relative) }}\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, remote, onClose, onAdd, onAddSubpath, 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 /** Remote (mirror-backed) workspace: extra folders are typed subpaths, not picked. */\r\n remote: boolean\r\n onClose: () => void\r\n onAdd: () => void\r\n onAddSubpath: (relative: string) => 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 const [subpath, setSubpath] = useState('')\r\n const submitSubpath = (): void => {\r\n if (subpath.trim() === '') return\r\n onAddSubpath(subpath)\r\n setSubpath('')\r\n }\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 {remote\r\n ? (\r\n <>\r\n

{t('folder.remoteHint')}

\r\n
\r\n setSubpath(event.target.value)}\r\n onKeyDown={(event) => {\r\n if (event.key !== 'Enter') return\r\n event.preventDefault()\r\n submitSubpath()\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 | 'folder.remoteHint'\r\n | 'folder.remoteNeedsSubpath'\r\n | 'folder.subpathLabel'\r\n | 'folder.subpathPlaceholder'\r\n | 'folder.addSubpath'\r\n | 'folder.subpathInvalid'\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 'folder.remoteHint': '远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)',\r\n 'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹',\r\n 'folder.subpathLabel': '相对路径',\r\n 'folder.subpathPlaceholder': '例如 data 或 src/generated',\r\n 'folder.addSubpath': '添加子目录',\r\n 'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',\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 'folder.remoteHint': 'Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root',\r\n 'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder',\r\n 'folder.subpathLabel': 'Relative path',\r\n 'folder.subpathPlaceholder': 'e.g. data or src/generated',\r\n 'folder.addSubpath': 'Add subdirectory',\r\n 'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',\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: 'workspace-groups-local',\r\n },\r\n GroupsBrowser,\r\n ))\r\n}\r\n"],"mapp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AAe,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","IconPlusOutlineRegular","Menu","IconEllipsisOutlineRegular","IconFolderOpenOutlineRegular","IconRightUpOutlineRegular","IconProjectAddOutlineRegular","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/folder-directory.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/directory-flow.ts","../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 * One path with trailing separators removed, spelling preserved (no case\n * folding) — the form to STORE. A drive/UNC/root prefix keeps its separator.\n * @param path - raw path.\n */\nfunction withoutTrailingSeparator(path: string): string {\n if (isWindowsStyle(path)) {\n let value = path.replaceAll('/', '\\\\')\n while (value.length > 3 && value.endsWith('\\\\')) value = value.slice(0, -1)\n return value\n }\n let value = path\n while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)\n return value\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 const value = withoutTrailingSeparator(trimmed)\n return isWindowsStyle(trimmed) ? value.toLowerCase() : 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\n/**\n * True when `path` is `base` itself or lives somewhere below it, with the same\n * separator and case rules as {@link samePath}.\n * @param path - candidate path.\n * @param base - containing directory.\n */\nexport function isUnderBase(path: string, base: string): boolean {\n const root = canonicalPath(base)\n const target = canonicalPath(path)\n if (root === '' || target === '') return false\n if (target === root) return true\n const separator = isWindowsStyle(root) ? '\\\\' : '/'\n const prefix = root.endsWith(separator) ? root : `${root}${separator}`\n return target.startsWith(prefix)\n}\n\n/**\n * Resolve a user-typed SUBPATH against a base directory.\n *\n * This is what remote (mirror-backed) workspaces need: their canonical\n * directory is a local mirror of a remote root, so an extra folder must be a\n * directory INSIDE the mirror — that is the only spelling that also exists on\n * the remote side. Absolute input and `..` escapes are rejected outright so a\n * typo cannot smuggle in an unrelated local directory.\n * @param base - the workspace's canonical directory.\n * @param relative - typed subpath, either separator style.\n * @returns the joined path, or null when the input is empty, absolute, or\n * escapes the base.\n */\nexport function joinSubpath(base: string, relative: string): string | null {\n const root = base.trim()\n const raw = relative.trim()\n if (root === '' || raw === '') return null\n if (WINDOWS_DRIVE.test(raw) || WINDOWS_UNC.test(raw) || raw.startsWith('/')) return null\n const segments = raw.split(/[\\\\/]+/u).filter(segment => segment !== '' && segment !== '.')\n if (segments.length === 0) return null\n if (segments.includes('..')) return null\n const windows = isWindowsStyle(root)\n const separator = windows ? '\\\\' : '/'\n return `${withoutTrailingSeparator(root)}${separator}${segments.join(separator)}`\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, onAddWorkspace, addingWorkspace = false, 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 /** Create and assign a workspace directly to this category. */\r\n onAddWorkspace?: () => void\r\n addingWorkspace?: boolean\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 {onAddWorkspace !== undefined && (\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/** One successful read: the overlay plus the mirror base the host reported. */\nexport interface FoldersSnapshot {\n readonly document: FoldersDocument\n /**\n * Local mirror root of the remote-ssh plugin, when the host named one.\n * Workspaces whose directory lives below it are remote mirrors, so their extra\n * folders must be subdirectories of that same mirror.\n */\n readonly remoteBase?: string\n}\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 overlay plus the reported mirror base; the empty document on any\n * 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 { document: EMPTY_FOLDERS_DOCUMENT }\n const body: unknown = await response.json()\n if (typeof body !== 'object' || body === null) return { document: EMPTY_FOLDERS_DOCUMENT }\n const source = body as Record\n const remoteBase = typeof source.remoteBase === 'string' && source.remoteBase.trim() !== ''\n ? source.remoteBase.trim()\n : undefined\n const base = remoteBase === undefined ? {} : { remoteBase }\n if (source.version !== 1) return { document: EMPTY_FOLDERS_DOCUMENT, ...base }\n if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {\n return { document: { version: 1, workspaces: {} }, ...base }\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 { document: { version: 1, workspaces }, ...base }\n } catch {\n return { document: 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","/** One directory operation for local DSH and optional remote-ssh workspaces.\n * Never send remote writes through the sidebar route: without its SSH interceptor\n * that route can create a LOCAL directory instead. Use the SSH-owned API instead.\n */\nimport { isUnderBase, joinSubpath, samePath } from '../core/folders.ts'\n\nexport interface RemoteFolderWorkspace {\n mirrorPath: string\n remotePath: string\n profileId: string\n}\n\ntype JsonObject = Record\nfunction object(value: unknown): JsonObject | undefined {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? value as JsonObject : undefined\n}\nfunction message(value: JsonObject | undefined): string {\n const error = value?.error\n return typeof error === 'string' ? error\n : typeof object(error)?.message === 'string' ? String(object(error)?.message)\n : typeof value?.stderr === 'string' && value.stderr !== '' ? value.stderr\n : 'Remote SSH request failed'\n}\n\nasync function rpc(method: string, body: JsonObject, fetchImpl: typeof fetch): Promise {\n const response = await fetchImpl(`/remote-ssh/api/${method}`, {\n method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },\n body: JSON.stringify(body), cache: 'no-store', signal: AbortSignal.timeout(30000),\n })\n // Only catalog absence denotes an optional plugin not installed/running.\n if (response.status === 404 && method === 'listWorkspaces') return null\n if (!response.ok) throw new Error(`Remote SSH ${method}: HTTP ${response.status}`)\n const envelope = object(await response.json())\n const value = object(envelope?.value)\n if (envelope?.ok !== true || value?.ok !== true) throw new Error(message(value ?? envelope))\n return value\n}\n\n/** A marker is only a refusal hint, never authority to execute remote commands. */\nasync function refuseMarkedLocalPath(path: string, fetchImpl: typeof fetch): Promise {\n const response = await fetchImpl(`/workspace-groups/remote-hint?path=${encodeURIComponent(path)}`, {\n cache: 'no-store', signal: AbortSignal.timeout(10000),\n })\n if (!response.ok) throw new Error(`Cannot verify local directory: HTTP ${response.status}`)\n const body = object(await response.json())\n if (typeof body?.remoteHint !== 'boolean') throw new Error('Invalid directory safety response')\n if (body.remoteHint) throw new Error('SSH marker detected but no active registered remote workspace; refusing local operation')\n}\n\n/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */\nexport async function remoteFolderWorkspace(\n path: string, remoteBase: string | null, fetchImpl: typeof fetch = fetch,\n): Promise {\n const value = await rpc('listWorkspaces', {}, fetchImpl)\n const knownMirror = remoteBase !== null && isUnderBase(path, remoteBase)\n if (value === null) {\n if (knownMirror) throw new Error('SSH plugin is unavailable; refusing a local operation in a remote mirror')\n await refuseMarkedLocalPath(path, fetchImpl)\n return null\n }\n if (!Array.isArray(value.workspaces)) throw new Error('Invalid SSH workspace catalog')\n const matches: RemoteFolderWorkspace[] = []\n for (const raw of value.workspaces) {\n const row = object(raw)\n if (!row || typeof row.mirrorPath !== 'string' || typeof row.remotePath !== 'string'\n || typeof row.profileId !== 'string' || !row.mirrorPath || !row.remotePath || !row.profileId) {\n throw new Error('Invalid SSH workspace entry')\n }\n if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) {\n matches.push({ mirrorPath: row.mirrorPath, remotePath: row.remotePath, profileId: row.profileId })\n }\n }\n if (matches.length > 1) throw new Error('Overlapping SSH workspaces are not supported safely')\n if (matches.length === 1) return matches[0]!\n if (knownMirror) throw new Error('Remote mirror is not registered with the SSH plugin')\n await refuseMarkedLocalPath(path, fetchImpl)\n return null\n}\n\n/** Single-segment names match DSH createDirectory(path, name). */\nexport function validateFolderName(raw: string): string {\n const name = raw.trim()\n if (!name || name === '.' || name === '..' || /[\\\\/\\u0000-\\u001f]/u.test(name)) {\n throw new Error('Enter a single folder name, not an absolute path or nested path')\n }\n return name\n}\n\nexport async function createWorkspaceDirectory(\n parent: string, rawName: string, remoteBase: string | null,\n createLocal: (path: string, name: string) => Promise, fetchImpl: typeof fetch = fetch,\n): Promise<{ path: string; remote: boolean }> {\n const name = validateFolderName(rawName)\n const path = joinSubpath(parent, name)\n if (path === null) throw new Error('Invalid folder name')\n const remote = await remoteFolderWorkspace(parent, remoteBase, fetchImpl)\n if (!remote) return { path: await createLocal(parent, name), remote: false }\n // Names with shell expansions are rejected defensively for older SSH wrappers.\n if (/[\\u0000-\\u001f`$\"\\\\]/u.test(name)) throw new Error('Unsupported remote folder name')\n const normalizedParent = parent.trim().replace(/\\\\/gu, '/').replace(/\\/+$/u, '')\n const normalizedRoot = remote.mirrorPath.trim().replace(/\\\\/gu, '/').replace(/\\/+$/u, '')\n const suffix = normalizedParent.slice(normalizedRoot.length).replace(/^\\/+/, '')\n if (suffix.split('/').some(part => part === '..' || part === '.')) throw new Error('Invalid mirror path')\n const root = remote.remotePath.replace(/\\/+$/u, '')\n const remotePath = `${root}/${suffix ? `${suffix}/` : ''}${name}`\n await rpc('mkdir', { profileId: remote.profileId, path: remotePath }, fetchImpl)\n return { path, remote: true }\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, isUnderBase, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'\r\nimport { loadFolders, saveFolders } from './folders-persist.ts'\r\nimport { createWorkspaceDirectory, remoteFolderWorkspace } from './folder-directory.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 getDirectoryFlow,\r\n createDirectory,\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 createdFolderPendingSave = useRef<{ workspaceId: WorkspaceId; name: string; path: string } | null>(null)\r\n const [creatingSessionIn, setCreatingSessionIn] = useState(null)\r\n // Local mirror root of the remote-ssh plugin, as reported by the host. A\r\n // project whose directory lives below it is a REMOTE workspace: its folder is\r\n // a mirror of one remote root, so extra folders must be subdirectories of that\r\n // mirror — anything else would exist on this machine only.\r\n const [foldersRemoteBase, setFoldersRemoteBase] = useState(null)\r\n useEffect(() => {\r\n let cancelled = false\r\n void loadFolders().then((snapshot) => {\r\n if (cancelled) return\r\n setFoldersDoc(snapshot.document)\r\n setFoldersRemoteBase(snapshot.remoteBase ?? null)\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 // Use the elected standard flow, including remote-ssh's local/remote picker.\r\n const [directoryFlowOpen, setDirectoryFlowOpen] = useState(false)\r\n const [directoryFlow, setDirectoryFlow] = useState>(null)\r\n const DirectoryFlow = directoryFlow?.component\r\n const directoryRequest = useRef<{\r\n resolve: (path: string | null) => void\r\n reject: (error: Error) => void\r\n } | null>(null)\r\n const finishDirectoryFlow = (path: string | null, error?: string): void => {\r\n const pending = directoryRequest.current\r\n directoryRequest.current = null\r\n setDirectoryFlowOpen(false)\r\n if (error !== undefined) pending?.reject(new Error(error))\r\n else pending?.resolve(path)\r\n }\r\n useEffect(() => () => {\r\n directoryRequest.current?.resolve(null)\r\n directoryRequest.current = null\r\n }, [])\r\n const pickWorkspaceDirectory = (): Promise => {\r\n const flow = getDirectoryFlow()\r\n if (!flow) return pickDirectory()\r\n if (directoryRequest.current) return Promise.resolve(null)\r\n setDirectoryFlow(flow)\r\n return new Promise((resolve, reject) => {\r\n directoryRequest.current = { resolve, reject }\r\n setDirectoryFlowOpen(true)\r\n })\r\n }\r\n const [adding, setAdding] = useState(false)\r\n const [addError, setAddError] = useState(null)\r\n const [addErrorOpen, setAddErrorOpen] = useState(false)\r\n const addCategoryRef = useRef(undefined)\r\n const currentGrouping = useRef({ manual, groups, manualSaving })\r\n currentGrouping.current = { manual, groups, manualSaving }\r\n const addWorkspace = async (categoryKey?: string): Promise => {\r\n if (adding || manualSaving) return\r\n addCategoryRef.current = categoryKey\r\n setAdding(true)\r\n setAddError(null)\r\n setAddErrorOpen(false)\r\n try {\r\n const path = await pickWorkspaceDirectory()\r\n if (path === null) return // cancelled\r\n const workspace = await createWorkspace({ path })\r\n if (categoryKey !== undefined) {\r\n // Use the returned ID: the workspace observable may not have caught up yet.\r\n const latest = currentGrouping.current\r\n if (latest.manualSaving || !latest.groups.some(group => group.key === categoryKey)) {\r\n throw new Error('The group changed while adding the workspace. Please retry from the target group.')\r\n }\r\n const workspaceId = workspace.workspaceId as string\r\n const workspaceOrder = Object.fromEntries(Object.entries(latest.manual.workspaceOrder)\r\n .map(([key, ids]) => [key, ids.filter(id => id !== workspaceId)]))\r\n workspaceOrder[categoryKey] = [...(workspaceOrder[categoryKey] ?? []), workspaceId]\r\n const next = { ...latest.manual, assignments: { ...latest.manual.assignments, [workspaceId]: categoryKey }, workspaceOrder }\r\n setManualSaving(true)\r\n try {\r\n await saveManualOverlay(next)\r\n setManual(next)\r\n actions.setCategoryExpanded(categoryKey, true)\r\n } finally {\r\n setManualSaving(false)\r\n }\r\n }\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 isRemoteWorkspace = (workspace: WorkspaceView): boolean => (\r\n foldersRemoteBase !== null && isUnderBase(workspace.path, foldersRemoteBase)\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 // A remote workspace's directory is a local MIRROR of one remote root; the\r\n // native picker would happily return an unrelated local directory that has\r\n // no remote counterpart, so that path is closed off here and the dialog\r\n // takes a subpath instead.\r\n setFoldersBusy(true)\r\n try {\r\n if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))\r\n if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) {\r\n notifyFolder(t('folder.remoteNeedsSubpath'))\r\n return\r\n }\r\n const path = await pickDirectory()\r\n if (path === null) return // cancelled\r\n if (await remoteFolderWorkspace(path, foldersRemoteBase)) {\r\n notifyFolder(t('folder.remoteNeedsSubpath'))\r\n return\r\n }\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 /** The same gesture routes through native local or SSH-owned mkdir APIs. */\r\n const addSubpathTo = async (workspaceId: WorkspaceId, name: string): Promise => {\r\n if (foldersBusy) return false\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (workspace === undefined) return false\r\n setFoldersBusy(true)\r\n try {\r\n if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))\r\n const pending = createdFolderPendingSave.current\r\n const created = pending?.workspaceId === workspaceId && pending.name === name\r\n ? pending\r\n : await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory)\r\n createdFolderPendingSave.current = { workspaceId, name, path: created.path }\r\n const entry = addFolder(entryFor(foldersDoc, workspaceId as string), created.path)\r\n const next: FoldersDocument = { version: 1, workspaces: { ...foldersDoc.workspaces, [workspaceId]: entry } }\r\n // Do not report success or clear the input until both operations succeed.\r\n // A failed overlay save does NOT delete the newly created user directory.\r\n await saveFolders(next)\r\n setFoldersDoc(next)\r\n createdFolderPendingSave.current = null\r\n return true\r\n } catch (reason) {\r\n notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)\r\n return false\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 void (async () => {\r\n const workspace = workspaces.find(w => w.workspaceId === workspaceId)\r\n if (!workspace) throw new Error('Workspace not found')\r\n if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))\r\n const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase)\r\n const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase)\r\n if (remote || targetRemote) throw new Error(t('folder.remoteSessionUnsupported'))\r\n await createSessionIn(workspaceId, path)\r\n })().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 { void addWorkspace() }}\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 onAddWorkspace={() => { void addWorkspace(category.key) }}\r\n addingWorkspace={adding || manualSaving}\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 onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}\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 {directoryFlowOpen && DirectoryFlow && (\r\n { finishDirectoryFlow(path) }}\r\n onCancel={() => { finishDirectoryFlow(null) }}\r\n onError={message => { finishDirectoryFlow(null, message) }}\r\n />\r\n )}\r\n\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, onAddWorkspace, addingWorkspace, 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 onAddWorkspace: () => void\r\n addingWorkspace: boolean\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, remote, onClose, onAdd, onAddSubpath, 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 /** Remote (mirror-backed) workspace: extra folders are typed subpaths, not picked. */\r\n remote: boolean\r\n onClose: () => void\r\n onAdd: () => void\r\n onAddSubpath: (relative: string) => Promise\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 const [subpath, setSubpath] = useState('')\r\n const submitSubpath = (): void => {\r\n if (subpath.trim() === '') return\r\n if (busy) return\r\n void onAddSubpath(subpath).then(success => { if (success) setSubpath('') })\r\n }\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

{t('folder.remoteHint')}

\r\n
\r\n setSubpath(event.target.value)}\r\n onKeyDown={(event) => {\r\n if (event.key !== 'Enter') return\r\n event.preventDefault()\r\n submitSubpath()\r\n }}\r\n />\r\n \r\n
\r\n \r\n {!remote && }\r\n
\r\n \r\n )\r\n}\r\n","import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'\nimport type { GroupsBrowserInjected } from './contract.ts'\n\n/** Adapt the elected self-contained picker, without stealing its original slot. */\nexport function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType {\n if (!entry) return null\n // Stateful/translated/nested seats need the full original renderer context.\n // Never silently drop them or fall back to a local picker for a remote request.\n if (entry.store || entry.locale || entry.children || typeof entry.component !== 'function') {\n throw new Error('This directory picker requires an unsupported renderer context.')\n }\n return {\n component: entry.component as NonNullable>['component'],\n injected: entry.inject?.() ?? {},\n }\n}\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 | 'folder.notReady'\r\n | 'folder.remoteSessionUnsupported'\r\n | 'folder.remoteHint'\r\n | 'folder.remoteNeedsSubpath'\r\n | 'folder.subpathLabel'\r\n | 'folder.subpathPlaceholder'\r\n | 'folder.addSubpath'\r\n | 'folder.subpathInvalid'\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 'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',\r\n 'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',\r\n 'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',\r\n 'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹',\r\n 'folder.subpathLabel': '文件夹名称',\r\n 'folder.subpathPlaceholder': '例如 data',\r\n 'folder.addSubpath': '创建文件夹',\r\n 'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..',\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 'folder.notReady': 'Directory safety information is not loaded. Restart DSH and refresh the page before retrying.',\r\n 'folder.remoteSessionUnsupported': 'This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.',\r\n 'folder.remoteHint': 'Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.',\r\n 'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder',\r\n 'folder.subpathLabel': 'Folder name',\r\n 'folder.subpathPlaceholder': 'e.g. data',\r\n 'folder.addSubpath': 'Create folder',\r\n 'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)',\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 { directoryFlowFromEntry } from './directory-flow.ts'\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 // Our shadow entry cannot own/render the official browser's child slot.\r\n // Reuse the elected self-contained picker and its actual injected services.\r\n getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot('sidebar.workspaces.directoryFlow')[0]),\r\n createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name),\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: 'workspace-groups-local',\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,CAAC,SAAS,aAAa,SAAS,GAAG,CAAC,CACtF;GACA,MAAM,qBAAqB,OAAO,YAChC,OAAO,QAAQ,MAAM,kBAAkB,CAAC,CAAC,QAAQ,CAAC,SAAS,cAAc,SAAS,GAAG,CAAC,CACxF;EACF;;;;;;;;;;;;;;;;;;;ECZA,SAAgB,wBAA+E;GAC7F,QAAA,GAAOA,8BAAAA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B,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 092d87c..d53cd99 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,5 +1,5 @@ -import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises"; -import { dirname, relative, resolve, sep } from "node:path"; +import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; import { homedir } from "node:os"; //#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs function getDefaultExportFromCjs(x) { @@ -3001,6 +3001,31 @@ function defaultRemoteMirrorBase() { function isAbsoluteFolderPath(path) { return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path); } +/** Validate a local path for the read-only remote hint endpoint. */ +function validateRemoteHintPath(path) { + if (typeof path !== "string" || path.length === 0 || path.length > 1024 || path.includes("\0") || !isAbsoluteFolderPath(path)) throw new Error("remote hint path must be an absolute host path without NUL, at most 1024 characters"); + return path; +} +/** +* Presence-only safety hint, never a trusted SSH connection or registration. +* lstat also treats dangling symlinks as hints without reading their targets. +* Only ENOENT is ignored: permissions and all other inspection failures must +* prevent callers from silently falling back to local operations. +*/ +async function hasRemoteMarkerHint(path) { + let directory = resolve(validateRemoteHintPath(path)); + for (;;) { + try { + await lstat(resolve(directory, ".remote-ssh.json")); + return true; + } catch (error) { + if (error.code !== "ENOENT") throw error; + } + const parent = dirname(directory); + if (parent === directory) return false; + directory = parent; + } +} /** Reject helper carrying the stable file-scoped message prefix. */ function invalid(detail) { throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`); @@ -3170,95 +3195,6 @@ async function writeFoldersDocument(path, document) { throw error; } } -/** Connection record of the remote-ssh plugin at a mirror root. */ -const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json"; -/** -* Read the remote-ssh connection record of a directory. -* @param dir - directory that may hold the record (a mirror root, usually). -* @returns the record, or null when the directory is not remote-backed. -*/ -async function readRemoteMarker(dir) { - let text; - try { - text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), "utf8"); - } catch { - return null; - } - let parsed; - try { - parsed = JSON.parse(text); - } catch { - return null; - } - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null; - const row = parsed; - if (typeof row.host !== "string" || row.host === "") return null; - if (typeof row.user !== "string" || row.user === "") return null; - const port = typeof row.port === "number" && Number.isInteger(row.port) && row.port > 0 ? row.port : 22; - const remotePath = typeof row.remotePath === "string" ? row.remotePath.trim() : ""; - if (remotePath === "") return null; - return { - ...typeof row.profileId === "string" && row.profileId !== "" ? { profileId: row.profileId } : {}, - host: row.host, - port, - user: row.user, - ...typeof row.keyPath === "string" ? { keyPath: row.keyPath } : {}, - ...typeof row.proxyJump === "string" && row.proxyJump !== "" ? { proxyJump: row.proxyJump } : {}, - remotePath - }; -} -/** -* Join a remote path with a mirror-relative subpath. -* -* The remote path is POSIX (the server's), so this never uses `node:path`: -* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell. -* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`). -* @param relativePath - subpath inside the mirror, either separator style. -* @returns the remote counterpart, or null for an empty or escaping subpath. -*/ -function remoteSubpath(remotePath, relativePath) { - const rel = relativePath.trim().replace(/\\/gu, "/").replace(/^\/+|\/+$/gu, ""); - if (rel === "") return null; - if (rel.split("/").some((segment) => segment === ".." || segment === ".")) return null; - const base = remotePath === "~" ? "~" : remotePath.replace(/\/+$/u, ""); - return base === "" ? rel : `${base}/${rel}`; -} -/** -* Stamp the remote-ssh connection record into a subdirectory of a mirror, so -* that sessions started there keep a remote terminal (see the block comment). -* -* A workspace that is not remote-backed is left untouched: no record at the -* workspace root means the plugin has nothing to reproduce. -* @param workspacePath - the workspace's canonical directory (the mirror root). -* @param folderPath - subdirectory added as an extra folder. -* @returns `{ marked: false }` for a local workspace, otherwise the remote path -* written into the subdirectory record. -*/ -async function ensureRemoteMarker(workspacePath, folderPath) { - const base = resolve(workspacePath); - const folder = resolve(folderPath); - const rel = relative(base, folder); - if (rel === "" || rel.startsWith("..")) throw invalid("folder is not inside the workspace directory"); - const marker = await readRemoteMarker(base); - if (marker === null) return { marked: false }; - const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join("/")); - if (remotePath === null) throw invalid("remote subpath is unusable"); - const record = { - ...marker.profileId === void 0 ? {} : { profileId: marker.profileId }, - host: marker.host, - port: marker.port, - user: marker.user, - ...marker.keyPath === void 0 ? {} : { keyPath: marker.keyPath }, - ...marker.proxyJump === void 0 ? {} : { proxyJump: marker.proxyJump }, - remotePath - }; - await mkdir(folder, { recursive: true }); - await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), "utf8"); - return { - marked: true, - remotePath - }; -} //#endregion //#region src/index.ts /** Plugin identity for cordis.yml rows. */ @@ -3448,6 +3384,37 @@ function apply(ctx) { res.end(body); } }), "@dsh-xhl/workspace-groups: /workspace-groups/manual route"); + ctx.effect(() => ctx.webServer.register({ + kind: "exact", + path: "/workspace-groups/remote-hint", + handler: async (req, res) => { + if (req.method !== "GET" && req.method !== "HEAD") { + writeError(res, 405, "method not allowed"); + return; + } + let path; + try { + path = validateRemoteHintPath(new URL(req.url ?? "", "http://localhost").searchParams.get("path")); + } catch { + writeError(res, 400, "workspace-groups: invalid remote hint path"); + return; + } + let remoteHint; + try { + remoteHint = await hasRemoteMarkerHint(path); + } catch { + writeError(res, 500, "workspace-groups: failed to inspect remote hint; local fallback is unsafe"); + return; + } + const body = JSON.stringify({ remoteHint }); + 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); + } + }), "@dsh-xhl/workspace-groups: /workspace-groups/remote-hint route"); ctx.effect(() => ctx.webServer.register({ kind: "exact", path: "/workspace-groups/folders", @@ -3467,34 +3434,7 @@ function apply(ctx) { return; } if (req.method === "POST") { - 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; - } - const payload = typeof raw === "object" && raw !== null ? raw : {}; - const workspacePath = typeof payload.workspacePath === "string" ? payload.workspacePath.trim() : ""; - const folderPath = typeof payload.folderPath === "string" ? payload.folderPath.trim() : ""; - if (workspacePath === "" || folderPath === "") { - writeError(res, 400, "workspace-groups: workspacePath and folderPath are required"); - return; - } - let result; - try { - result = await ensureRemoteMarker(workspacePath, folderPath); - } catch (error) { - writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`); - return; - } - const marked = JSON.stringify(result); - res.writeHead(200, { - "Content-Type": "application/json; charset=utf-8", - "Cache-Control": "no-store", - "Content-Length": Buffer.byteLength(marked) - }); - res.end(marked); + writeError(res, 410, "workspace-groups: remote marker creation is deprecated; use the registered remote workspace root"); return; } if (req.method !== "PUT") { diff --git a/lib/types/client/GroupsBrowser.d.ts b/lib/types/client/GroupsBrowser.d.ts index b0b86e3..c7cbba7 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, createSessionIn, 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, getDirectoryFlow, createDirectory, 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 4e47c19..9022b73 100644 --- a/lib/types/client/contract.d.ts +++ b/lib/types/client/contract.d.ts @@ -7,6 +7,8 @@ * self-contained via `pickDirectory` — and no locale-keyed naming collision. */ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'; +import type { ComponentType } from 'react'; +import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'; import type { SessionId } from '@deepseek-ai/dsh-session/types'; import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'; import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'; @@ -64,6 +66,13 @@ export type GroupsBrowserInjected = { }) => Promise; /** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */ pickDirectory: () => Promise; + /** Snapshot a self-contained standard picker without redeclaring its owned slot. */ + getDirectoryFlow: () => { + component: ComponentType; + injected: Record; + } | null; + /** DSH native local directory creation (SSH routing is owned by our adapter). */ + createDirectory: (path: string, name: string) => Promise; /** * Surface the session-tab strip for a session that is in play (called with the * session the browser itself just opened, and again whenever its status diff --git a/lib/types/client/directory-flow.d.ts b/lib/types/client/directory-flow.d.ts new file mode 100644 index 0000000..31da93e --- /dev/null +++ b/lib/types/client/directory-flow.d.ts @@ -0,0 +1,4 @@ +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'; +import type { GroupsBrowserInjected } from './contract.ts'; +/** Adapt the elected self-contained picker, without stealing its original slot. */ +export declare function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType; diff --git a/lib/types/client/folder-directory.d.ts b/lib/types/client/folder-directory.d.ts new file mode 100644 index 0000000..7e4f8aa --- /dev/null +++ b/lib/types/client/folder-directory.d.ts @@ -0,0 +1,13 @@ +export interface RemoteFolderWorkspace { + mirrorPath: string; + remotePath: string; + profileId: string; +} +/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */ +export declare function remoteFolderWorkspace(path: string, remoteBase: string | null, fetchImpl?: typeof fetch): Promise; +/** Single-segment names match DSH createDirectory(path, name). */ +export declare function validateFolderName(raw: string): string; +export declare function createWorkspaceDirectory(parent: string, rawName: string, remoteBase: string | null, createLocal: (path: string, name: string) => Promise, fetchImpl?: typeof fetch): Promise<{ + path: string; + remote: boolean; +}>; diff --git a/lib/types/client/folders-persist.d.ts b/lib/types/client/folders-persist.d.ts index 4507ba4..ba3adc4 100644 --- a/lib/types/client/folders-persist.d.ts +++ b/lib/types/client/folders-persist.d.ts @@ -42,18 +42,3 @@ export declare function loadFolders(fetchImpl?: typeof fetch): Promise; -/** - * Ask the host to stamp the remote-ssh connection record into an extra folder of - * a MIRROR workspace. - * - * remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the - * session cwd and never walks up, so a folder below the mirror root would - * otherwise get a local terminal. Best-effort: the folder itself is already - * persisted by the time this runs, and a local workspace answers `marked:false` - * (nothing to stamp) rather than failing. - * @param workspacePath - the workspace's canonical directory (mirror root). - * @param folderPath - the extra folder just added. - * @param fetchImpl - fetch implementation (injectable for tests). - * @returns true when a record was written. - */ -export declare function ensureRemoteFolderMarker(workspacePath: string, folderPath: string, fetchImpl?: typeof fetch): Promise; diff --git a/lib/types/client/locales.d.ts b/lib/types/client/locales.d.ts index 06cc482..9823f6e 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' | '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' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | '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' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | '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 2b37e76..9b742be 100644 --- a/lib/types/client/rows.d.ts +++ b/lib/types/client/rows.d.ts @@ -50,10 +50,13 @@ export declare function CategoryGlyph({ icon, fallback }: { * groups via overlay renames/hides), draggable source for group reorder and * drop target for both workspace moves and group reorders. */ -export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: { +export declare function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: { node: CategoryNode; t: T; onToggle: () => void; + /** Create and assign a workspace directly to this category. */ + onAddWorkspace?: () => void; + addingWorkspace?: boolean; /** Rename/delete actions; the hover menu renders only when both provided. */ onRename?: () => void; onDelete?: () => void; diff --git a/lib/types/host-folders.d.ts b/lib/types/host-folders.d.ts index 9acb344..25784fc 100644 --- a/lib/types/host-folders.d.ts +++ b/lib/types/host-folders.d.ts @@ -27,6 +27,15 @@ export declare function defaultRemoteMirrorBase(): string; * @param path - candidate path. */ export declare function isAbsoluteFolderPath(path: string): boolean; +/** Validate a local path for the read-only remote hint endpoint. */ +export declare function validateRemoteHintPath(path: unknown): string; +/** + * Presence-only safety hint, never a trusted SSH connection or registration. + * lstat also treats dangling symlinks as hints without reading their targets. + * Only ENOENT is ignored: permissions and all other inspection failures must + * prevent callers from silently falling back to local operations. + */ +export declare function hasRemoteMarkerHint(path: string): Promise; /** * Tolerant reader: shape-normalizes whatever was on disk and drops unusable * workspaces, folders and roots instead of throwing. A missing, non-mapping or @@ -58,24 +67,6 @@ export declare function readFoldersDocument(path: string): Promise; -/** Connection record of the remote-ssh plugin at a mirror root. */ -export declare const REMOTE_MARKER_FILE_NAME = ".remote-ssh.json"; -/** The subset of that record this plugin needs to reproduce it. */ -export interface RemoteMarker { - readonly profileId?: string; - readonly host: string; - readonly port: number; - readonly user: string; - readonly keyPath?: string; - readonly proxyJump?: string; - readonly remotePath: string; -} -/** - * Read the remote-ssh connection record of a directory. - * @param dir - directory that may hold the record (a mirror root, usually). - * @returns the record, or null when the directory is not remote-backed. - */ -export declare function readRemoteMarker(dir: string): Promise; /** * Join a remote path with a mirror-relative subpath. * @@ -86,18 +77,3 @@ export declare function readRemoteMarker(dir: string): Promise; diff --git a/package.json b/package.json index 057ea7c..575be8a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "workspace-groups-local", - "version": "0.6.2", + "version": "1.0.0", "description": "Complete workspace grouping manager for the DSH web sidebar: category -> project -> session three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping and ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.", "keywords": [ "dsh", diff --git a/src/client/GroupsBrowser.tsx b/src/client/GroupsBrowser.tsx index 539aae5..3d955db 100644 --- a/src/client/GroupsBrowser.tsx +++ b/src/client/GroupsBrowser.tsx @@ -55,8 +55,9 @@ import type { GroupsBrowserProps } from './contract.ts' 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, isUnderBase, joinSubpath, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts' -import { ensureRemoteFolderMarker, loadFolders, saveFolders } from './folders-persist.ts' +import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, isUnderBase, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts' +import { loadFolders, saveFolders } from './folders-persist.ts' +import { createWorkspaceDirectory, remoteFolderWorkspace } from './folder-directory.ts' import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts' import { QuickPanel } from './QuickPanel.tsx' import { SessionTabs } from './SessionTabs.tsx' @@ -219,6 +220,8 @@ export function GroupsBrowser({ insertSessionBefore, createWorkspace, pickDirectory, + getDirectoryFlow, + createDirectory, searchSessions, searchResultLimit, openTab, @@ -283,6 +286,7 @@ export function GroupsBrowser({ const [collapsedFolderKeys, setCollapsedFolderKeys] = useState([]) const [foldersTarget, setFoldersTarget] = useState(null) const [foldersBusy, setFoldersBusy] = useState(false) + const createdFolderPendingSave = useRef<{ workspaceId: WorkspaceId; name: string; path: string } | null>(null) const [creatingSessionIn, setCreatingSessionIn] = useState(null) // Local mirror root of the remote-ssh plugin, as reported by the host. A // project whose directory lives below it is a REMOTE workspace: its folder is @@ -458,19 +462,71 @@ export function GroupsBrowser({ // appends to the end of the list. No whole-area highlight box. const topLevelRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY } - // Add workspace flow: self-contained (no directory-flow hole dependency). + // Use the elected standard flow, including remote-ssh's local/remote picker. + const [directoryFlowOpen, setDirectoryFlowOpen] = useState(false) + const [directoryFlow, setDirectoryFlow] = useState>(null) + const DirectoryFlow = directoryFlow?.component + const directoryRequest = useRef<{ + resolve: (path: string | null) => void + reject: (error: Error) => void + } | null>(null) + const finishDirectoryFlow = (path: string | null, error?: string): void => { + const pending = directoryRequest.current + directoryRequest.current = null + setDirectoryFlowOpen(false) + if (error !== undefined) pending?.reject(new Error(error)) + else pending?.resolve(path) + } + useEffect(() => () => { + directoryRequest.current?.resolve(null) + directoryRequest.current = null + }, []) + const pickWorkspaceDirectory = (): Promise => { + const flow = getDirectoryFlow() + if (!flow) return pickDirectory() + if (directoryRequest.current) return Promise.resolve(null) + setDirectoryFlow(flow) + return new Promise((resolve, reject) => { + directoryRequest.current = { resolve, reject } + setDirectoryFlowOpen(true) + }) + } const [adding, setAdding] = useState(false) const [addError, setAddError] = useState(null) const [addErrorOpen, setAddErrorOpen] = useState(false) - const addWorkspace = async (): Promise => { - if (adding) return + const addCategoryRef = useRef(undefined) + const currentGrouping = useRef({ manual, groups, manualSaving }) + currentGrouping.current = { manual, groups, manualSaving } + const addWorkspace = async (categoryKey?: string): Promise => { + if (adding || manualSaving) return + addCategoryRef.current = categoryKey setAdding(true) setAddError(null) setAddErrorOpen(false) try { - const path = await pickDirectory() + const path = await pickWorkspaceDirectory() if (path === null) return // cancelled const workspace = await createWorkspace({ path }) + if (categoryKey !== undefined) { + // Use the returned ID: the workspace observable may not have caught up yet. + const latest = currentGrouping.current + if (latest.manualSaving || !latest.groups.some(group => group.key === categoryKey)) { + throw new Error('The group changed while adding the workspace. Please retry from the target group.') + } + const workspaceId = workspace.workspaceId as string + const workspaceOrder = Object.fromEntries(Object.entries(latest.manual.workspaceOrder) + .map(([key, ids]) => [key, ids.filter(id => id !== workspaceId)])) + workspaceOrder[categoryKey] = [...(workspaceOrder[categoryKey] ?? []), workspaceId] + const next = { ...latest.manual, assignments: { ...latest.manual.assignments, [workspaceId]: categoryKey }, workspaceOrder } + setManualSaving(true) + try { + await saveManualOverlay(next) + setManual(next) + actions.setCategoryExpanded(categoryKey, true) + } finally { + setManualSaving(false) + } + } startSession(workspace.workspaceId) } catch (reason) { const message = reason instanceof Error ? reason.message : String(reason) @@ -624,14 +680,19 @@ export function GroupsBrowser({ // native picker would happily return an unrelated local directory that has // no remote counterpart, so that path is closed off here and the dialog // takes a subpath instead. - if (isRemoteWorkspace(workspace)) { - notifyFolder(t('folder.remoteNeedsSubpath')) - return - } setFoldersBusy(true) try { + if (foldersRemoteBase === null) throw new Error(t('folder.notReady')) + if (await remoteFolderWorkspace(workspace.path, foldersRemoteBase)) { + notifyFolder(t('folder.remoteNeedsSubpath')) + return + } const path = await pickDirectory() if (path === null) return // cancelled + if (await remoteFolderWorkspace(path, foldersRemoteBase)) { + notifyFolder(t('folder.remoteNeedsSubpath')) + return + } const entry = entryFor(foldersDoc, workspaceId as string) if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) { notifyFolder(t('folder.duplicate')) @@ -646,31 +707,33 @@ export function GroupsBrowser({ } } - /** - * Add a folder to a REMOTE workspace by typing a path relative to its mirror. - * The mirror is a copy of the remote root, so `/sub` and remote `sub` - * are the same directory — that is the only way an extra folder can mean - * something on both sides. - */ - const addSubpathTo = (workspaceId: WorkspaceId, relative: string): void => { - if (foldersBusy) return + /** The same gesture routes through native local or SSH-owned mkdir APIs. */ + const addSubpathTo = async (workspaceId: WorkspaceId, name: string): Promise => { + if (foldersBusy) return false const workspace = workspaces.find(w => w.workspaceId === workspaceId) - if (workspace === undefined) return - const path = joinSubpath(workspace.path, relative) - if (path === null) { - notifyFolder(t('folder.subpathInvalid')) - return + if (workspace === undefined) return false + setFoldersBusy(true) + try { + if (foldersRemoteBase === null) throw new Error(t('folder.notReady')) + const pending = createdFolderPendingSave.current + const created = pending?.workspaceId === workspaceId && pending.name === name + ? pending + : await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory) + createdFolderPendingSave.current = { workspaceId, name, path: created.path } + const entry = addFolder(entryFor(foldersDoc, workspaceId as string), created.path) + const next: FoldersDocument = { version: 1, workspaces: { ...foldersDoc.workspaces, [workspaceId]: entry } } + // Do not report success or clear the input until both operations succeed. + // A failed overlay save does NOT delete the newly created user directory. + await saveFolders(next) + setFoldersDoc(next) + createdFolderPendingSave.current = null + return true + } catch (reason) { + notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`) + return false + } finally { + setFoldersBusy(false) } - 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)) - // Mirror subdirectory: also stamp the remote-ssh record, otherwise the new - // folder's sessions would lose the remote terminal (remote-ssh reads the - // record at the cwd only). Fire and forget — the folder row already works. - void ensureRemoteFolderMarker(workspace.path, path) } const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => { @@ -695,7 +758,15 @@ export function GroupsBrowser({ } if (creatingSessionIn !== null) return setCreatingSessionIn(folderKey(workspaceId, path)) - createSessionIn(workspaceId, path).catch((reason: unknown) => { + void (async () => { + const workspace = workspaces.find(w => w.workspaceId === workspaceId) + if (!workspace) throw new Error('Workspace not found') + if (foldersRemoteBase === null) throw new Error(t('folder.notReady')) + const remote = await remoteFolderWorkspace(workspace.path, foldersRemoteBase) + const targetRemote = await remoteFolderWorkspace(path, foldersRemoteBase) + if (remote || targetRemote) throw new Error(t('folder.remoteSessionUnsupported')) + await createSessionIn(workspaceId, path) + })().catch((reason: unknown) => { const detail = reason instanceof Error ? reason.message : String(reason) notifyFolder(`${t('folder.sessionError')}: ${detail}`) }).finally(() => { @@ -1245,7 +1316,7 @@ export function GroupsBrowser({ className="wgIconButton" aria-label={t('workspace.add')} disabled={adding} - onClick={addWorkspace} + onClick={() => { void addWorkspace() }} > @@ -1338,6 +1409,8 @@ export function GroupsBrowser({ onSessionRename={onSessionRename} onSessionArchive={onSessionArchive} onFork={forkSession} + onAddWorkspace={() => { void addWorkspace(category.key) }} + addingWorkspace={adding || manualSaving} onGroupRename={() => { setGroupDraft(category.key) setGroupError(null) @@ -1578,7 +1651,7 @@ export function GroupsBrowser({ remote={isRemoteWorkspace(workspace)} onClose={() => { setFoldersTarget(null) }} onAdd={() => { void addFolderTo(foldersTarget) }} - onAddSubpath={(relative) => { addSubpathTo(foldersTarget, relative) }} + onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)} onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }} onRemove={(path) => { removeFolderFrom(foldersTarget, path) }} onOpenFolder={(path) => { openFolderPath?.(path) }} @@ -1652,6 +1725,17 @@ export function GroupsBrowser({ {/* Add workspace error dialog */} + {directoryFlowOpen && DirectoryFlow && ( + { finishDirectoryFlow(path) }} + onCancel={() => { finishDirectoryFlow(null) }} + onError={message => { finishDirectoryFlow(null, message) }} + /> + )} + { setAddErrorOpen(false) }} @@ -1660,7 +1744,7 @@ export function GroupsBrowser({ footer={( <> - + )} > @@ -1806,7 +1890,7 @@ function WorkspaceSubtree({ workspace, current, now, t, animate, onOpen, onSessi } /** 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, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: { +function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onAddWorkspace, addingWorkspace, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: { category: CategoryNode current: SessionId | undefined now: number @@ -1829,6 +1913,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR onSessionRename: (sessionId: SessionId, currentTitle: string) => void onSessionArchive: (sessionId: SessionId) => void onFork: (sessionId: SessionId) => void + onAddWorkspace: () => void + addingWorkspace: boolean onGroupRename: () => void onGroupDelete: () => void /** Pin/unpin this group from its row menu. */ @@ -1859,6 +1945,8 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR node={category} t={t} onToggle={onToggleCategory} + onAddWorkspace={onAddWorkspace} + addingWorkspace={addingWorkspace} onRename={onGroupRename} onDelete={onGroupDelete} onTogglePin={onGroupTogglePin} @@ -2195,7 +2283,7 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on remote: boolean onClose: () => void onAdd: () => void - onAddSubpath: (relative: string) => void + onAddSubpath: (relative: string) => Promise onSetRoot: (path: string) => void onRemove: (path: string) => void onOpenFolder: (path: string) => void @@ -2205,8 +2293,8 @@ function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, onClose, on const [subpath, setSubpath] = useState('') const submitSubpath = (): void => { if (subpath.trim() === '') return - onAddSubpath(subpath) - setSubpath('') + if (busy) return + void onAddSubpath(subpath).then(success => { if (success) setSubpath('') }) } return (
- {remote - ? ( - <> + <>

{t('folder.remoteHint')}

- - ) - : } + + {!remote && }
) diff --git a/src/client/contract.ts b/src/client/contract.ts index bcd1692..c7f68c9 100644 --- a/src/client/contract.ts +++ b/src/client/contract.ts @@ -12,6 +12,8 @@ import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, // slot this registrant shadows) and its runtime props. Erased from both the JS // bundle and the emitted .d.ts, so it must stay a bare `import type {}`. import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'; +import type { ComponentType } from 'react'; +import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'; import type { SessionId } from '@deepseek-ai/dsh-session/types'; import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client'; import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client'; @@ -69,6 +71,13 @@ export type GroupsBrowserInjected = { }) => Promise; /** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */ pickDirectory: () => Promise; + /** Snapshot a self-contained standard picker without redeclaring its owned slot. */ + getDirectoryFlow: () => { + component: ComponentType; + injected: Record; + } | null; + /** DSH native local directory creation (SSH routing is owned by our adapter). */ + createDirectory: (path: string, name: string) => Promise; /** * Surface the session-tab strip for a session that is in play (called with the * session the browser itself just opened, and again whenever its status diff --git a/src/client/directory-flow.ts b/src/client/directory-flow.ts new file mode 100644 index 0000000..ec3deca --- /dev/null +++ b/src/client/directory-flow.ts @@ -0,0 +1,16 @@ +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { GroupsBrowserInjected } from './contract.ts' + +/** Adapt the elected self-contained picker, without stealing its original slot. */ +export function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType { + if (!entry) return null + // Stateful/translated/nested seats need the full original renderer context. + // Never silently drop them or fall back to a local picker for a remote request. + if (entry.store || entry.locale || entry.children || typeof entry.component !== 'function') { + throw new Error('This directory picker requires an unsupported renderer context.') + } + return { + component: entry.component as NonNullable>['component'], + injected: entry.inject?.() ?? {}, + } +} diff --git a/src/client/folder-directory.ts b/src/client/folder-directory.ts new file mode 100644 index 0000000..b747f34 --- /dev/null +++ b/src/client/folder-directory.ts @@ -0,0 +1,109 @@ +/** One directory operation for local DSH and optional remote-ssh workspaces. + * Never send remote writes through the sidebar route: without its SSH interceptor + * that route can create a LOCAL directory instead. Use the SSH-owned API instead. + */ +import { isUnderBase, joinSubpath, samePath } from '../core/folders.ts' + +export interface RemoteFolderWorkspace { + mirrorPath: string + remotePath: string + profileId: string +} + +type JsonObject = Record +function object(value: unknown): JsonObject | undefined { + return typeof value === 'object' && value !== null && !Array.isArray(value) + ? value as JsonObject : undefined +} +function message(value: JsonObject | undefined): string { + const error = value?.error + return typeof error === 'string' ? error + : typeof object(error)?.message === 'string' ? String(object(error)?.message) + : typeof value?.stderr === 'string' && value.stderr !== '' ? value.stderr + : 'Remote SSH request failed' +} + +async function rpc(method: string, body: JsonObject, fetchImpl: typeof fetch): Promise { + const response = await fetchImpl(`/remote-ssh/api/${method}`, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }, + body: JSON.stringify(body), cache: 'no-store', signal: AbortSignal.timeout(30000), + }) + // Only catalog absence denotes an optional plugin not installed/running. + if (response.status === 404 && method === 'listWorkspaces') return null + if (!response.ok) throw new Error(`Remote SSH ${method}: HTTP ${response.status}`) + const envelope = object(await response.json()) + const value = object(envelope?.value) + if (envelope?.ok !== true || value?.ok !== true) throw new Error(message(value ?? envelope)) + return value +} + +/** A marker is only a refusal hint, never authority to execute remote commands. */ +async function refuseMarkedLocalPath(path: string, fetchImpl: typeof fetch): Promise { + const response = await fetchImpl(`/workspace-groups/remote-hint?path=${encodeURIComponent(path)}`, { + cache: 'no-store', signal: AbortSignal.timeout(10000), + }) + if (!response.ok) throw new Error(`Cannot verify local directory: HTTP ${response.status}`) + const body = object(await response.json()) + if (typeof body?.remoteHint !== 'boolean') throw new Error('Invalid directory safety response') + if (body.remoteHint) throw new Error('SSH marker detected but no active registered remote workspace; refusing local operation') +} + +/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */ +export async function remoteFolderWorkspace( + path: string, remoteBase: string | null, fetchImpl: typeof fetch = fetch, +): Promise { + const value = await rpc('listWorkspaces', {}, fetchImpl) + const knownMirror = remoteBase !== null && isUnderBase(path, remoteBase) + if (value === null) { + if (knownMirror) throw new Error('SSH plugin is unavailable; refusing a local operation in a remote mirror') + await refuseMarkedLocalPath(path, fetchImpl) + return null + } + if (!Array.isArray(value.workspaces)) throw new Error('Invalid SSH workspace catalog') + const matches: RemoteFolderWorkspace[] = [] + for (const raw of value.workspaces) { + const row = object(raw) + if (!row || typeof row.mirrorPath !== 'string' || typeof row.remotePath !== 'string' + || typeof row.profileId !== 'string' || !row.mirrorPath || !row.remotePath || !row.profileId) { + throw new Error('Invalid SSH workspace entry') + } + if (samePath(path, row.mirrorPath) || isUnderBase(path, row.mirrorPath)) { + matches.push({ mirrorPath: row.mirrorPath, remotePath: row.remotePath, profileId: row.profileId }) + } + } + if (matches.length > 1) throw new Error('Overlapping SSH workspaces are not supported safely') + if (matches.length === 1) return matches[0]! + if (knownMirror) throw new Error('Remote mirror is not registered with the SSH plugin') + await refuseMarkedLocalPath(path, fetchImpl) + return null +} + +/** Single-segment names match DSH createDirectory(path, name). */ +export function validateFolderName(raw: string): string { + const name = raw.trim() + if (!name || name === '.' || name === '..' || /[\\/\u0000-\u001f]/u.test(name)) { + throw new Error('Enter a single folder name, not an absolute path or nested path') + } + return name +} + +export async function createWorkspaceDirectory( + parent: string, rawName: string, remoteBase: string | null, + createLocal: (path: string, name: string) => Promise, fetchImpl: typeof fetch = fetch, +): Promise<{ path: string; remote: boolean }> { + const name = validateFolderName(rawName) + const path = joinSubpath(parent, name) + if (path === null) throw new Error('Invalid folder name') + const remote = await remoteFolderWorkspace(parent, remoteBase, fetchImpl) + if (!remote) return { path: await createLocal(parent, name), remote: false } + // Names with shell expansions are rejected defensively for older SSH wrappers. + if (/[\u0000-\u001f`$"\\]/u.test(name)) throw new Error('Unsupported remote folder name') + const normalizedParent = parent.trim().replace(/\\/gu, '/').replace(/\/+$/u, '') + const normalizedRoot = remote.mirrorPath.trim().replace(/\\/gu, '/').replace(/\/+$/u, '') + const suffix = normalizedParent.slice(normalizedRoot.length).replace(/^\/+/, '') + if (suffix.split('/').some(part => part === '..' || part === '.')) throw new Error('Invalid mirror path') + const root = remote.remotePath.replace(/\/+$/u, '') + const remotePath = `${root}/${suffix ? `${suffix}/` : ''}${name}` + await rpc('mkdir', { profileId: remote.profileId, path: remotePath }, fetchImpl) + return { path, remote: true } +} diff --git a/src/client/folders-persist.ts b/src/client/folders-persist.ts index 5de8a2e..5c415be 100644 --- a/src/client/folders-persist.ts +++ b/src/client/folders-persist.ts @@ -111,38 +111,3 @@ export async function saveFolders( }) if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`) } - -/** - * Ask the host to stamp the remote-ssh connection record into an extra folder of - * a MIRROR workspace. - * - * remote-ssh decides "remote backed" by reading `.remote-ssh.json` at the - * session cwd and never walks up, so a folder below the mirror root would - * otherwise get a local terminal. Best-effort: the folder itself is already - * persisted by the time this runs, and a local workspace answers `marked:false` - * (nothing to stamp) rather than failing. - * @param workspacePath - the workspace's canonical directory (mirror root). - * @param folderPath - the extra folder just added. - * @param fetchImpl - fetch implementation (injectable for tests). - * @returns true when a record was written. - */ -export async function ensureRemoteFolderMarker( - workspacePath: string, - folderPath: string, - fetchImpl: typeof fetch = fetch, -): Promise { - try { - const response = await fetchImpl(FOLDERS_ROUTE, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ workspacePath, folderPath }), - cache: 'no-store', - }) - if (!response.ok) return false - const body: unknown = await response.json() - if (typeof body !== 'object' || body === null) return false - return (body as { marked?: unknown }).marked === true - } catch { - return false - } -} diff --git a/src/client/index.ts b/src/client/index.ts index 8d17412..775d45a 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -58,6 +58,7 @@ import { loadTabs, saveTabs } from './tab-persist.ts' import { createStoreHook } from './store-hook.ts' import { shouldOpenTab, type TabOpenMode } from './tabs.ts' import { GroupsBrowser } from './GroupsBrowser.tsx' +import { directoryFlowFromEntry } from './directory-flow.ts' import { en, zh, type WorkspaceGroupsKey } from './locales.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { @@ -193,6 +194,10 @@ export function apply(ctx: Context): void { // resolves). }, pickDirectory: () => ctx.uiWorkspace.pickDirectory(), + // Our shadow entry cannot own/render the official browser's child slot. + // Reuse the elected self-contained picker and its actual injected services. + getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot('sidebar.workspaces.directoryFlow')[0]), + createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name), searchSessions, searchResultLimit: ctx.sessions.searchResultLimit, // Directory-flow hole occupancy. The official ui-workspace browser gates diff --git a/src/client/locales.ts b/src/client/locales.ts index 4220c92..d796f61 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -47,6 +47,8 @@ export type WorkspaceGroupsKey = | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' + | 'folder.notReady' + | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' @@ -181,11 +183,13 @@ export const zh: WorkspaceGroupsDict = { 'folder.addError': '添加文件夹失败', 'folder.sessionError': '新建会话失败', 'folder.saveError': '文件夹保存失败', - 'folder.remoteHint': '远程(SSH)工作区:本地目录是服务器根目录的镜像,所以这里只能添加镜像内的子目录,填相对路径即可(也会同步到服务器同名目录)', + 'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试', + 'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。', + 'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。', 'folder.remoteNeedsSubpath': '远程工作区请用子目录方式添加文件夹', - 'folder.subpathLabel': '相对路径', - 'folder.subpathPlaceholder': '例如 data 或 src/generated', - 'folder.addSubpath': '添加子目录', + 'folder.subpathLabel': '文件夹名称', + 'folder.subpathPlaceholder': '例如 data', + 'folder.addSubpath': '创建文件夹', 'folder.subpathInvalid': '路径无效:请填工作区内的相对路径,不能用绝对路径或 ..', 'group.create': '新建分组', 'group.createTitle': '新建分组', @@ -314,11 +318,13 @@ export const en: WorkspaceGroupsDict = { 'folder.addError': 'Could not add the folder', 'folder.sessionError': 'Could not start a session', 'folder.saveError': 'Could not save folders', - 'folder.remoteHint': 'Remote (SSH) workspace: the local directory mirrors the server root, so only subdirectories of that mirror can be added here — type a path relative to the workspace root', + 'folder.notReady': 'Directory safety information is not loaded. Restart DSH and refresh the page before retrying.', + 'folder.remoteSessionUnsupported': 'This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.', + 'folder.remoteHint': 'Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.', 'folder.remoteNeedsSubpath': 'Remote workspaces take a subdirectory, not a picked folder', - 'folder.subpathLabel': 'Relative path', - 'folder.subpathPlaceholder': 'e.g. data or src/generated', - 'folder.addSubpath': 'Add subdirectory', + 'folder.subpathLabel': 'Folder name', + 'folder.subpathPlaceholder': 'e.g. data', + 'folder.addSubpath': 'Create folder', 'folder.subpathInvalid': 'Invalid path: use a relative path inside the workspace (no absolute paths, no ..)', 'group.create': 'New group', 'group.createTitle': 'New group', diff --git a/src/client/rows.tsx b/src/client/rows.tsx index 2574af6..b736684 100644 --- a/src/client/rows.tsx +++ b/src/client/rows.tsx @@ -167,10 +167,13 @@ export function CategoryGlyph({ icon, fallback = null }: { icon: string | undefi * groups via overlay renames/hides), draggable source for group reorder and * drop target for both workspace moves and group reorders. */ -export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: { +export function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace = false, onRename, onDelete, onTogglePin, onEditAppearance, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: { node: CategoryNode t: T onToggle: () => void + /** Create and assign a workspace directly to this category. */ + onAddWorkspace?: () => void + addingWorkspace?: boolean /** Rename/delete actions; the hover menu renders only when both provided. */ onRename?: () => void onDelete?: () => void @@ -237,6 +240,16 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin
)} + {onAddWorkspace !== undefined && ( + + + + )} {manageable && ( FOLDER_PATH_LIMIT + || path.includes('\u0000') || !isAbsoluteFolderPath(path)) { + throw new Error('remote hint path must be an absolute host path without NUL, at most 1024 characters') + } + return path +} + +/** + * Presence-only safety hint, never a trusted SSH connection or registration. + * lstat also treats dangling symlinks as hints without reading their targets. + * Only ENOENT is ignored: permissions and all other inspection failures must + * prevent callers from silently falling back to local operations. + */ +export async function hasRemoteMarkerHint(path: string): Promise { + let directory = resolve(validateRemoteHintPath(path)) + for (;;) { + try { + await lstat(resolve(directory, '.remote-ssh.json')) + return true + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error + } + const parent = dirname(directory) + if (parent === directory) return false + directory = parent + } +} + /** Reject helper carrying the stable file-scoped message prefix. */ function invalid(detail: string): never { throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`) @@ -256,71 +286,10 @@ export async function writeFoldersDocument(path: string, document: FoldersDocume } } -// --------------------------------------------------------------------------- -// remote-ssh markers -// -// `@zhangfengshun/dsh-remote-ssh` decides "this directory belongs to a remote -// workspace" by looking for a `.remote-ssh.json` connection record at the -// directory itself (the shell wrapper and several fs bridges read exactly one -// path, they do NOT walk up). Its mirror root carries one; a plain subdirectory -// of the mirror does not, so a session whose cwd is such a subdirectory falls -// back to a LOCAL terminal even though every file under it is remote-backed. -// -// Stamping the record into the subdirectory fixes that: the record holds the -// same connection with `remotePath` adjusted to the matching remote folder, and -// remote-ssh always excludes `.remote-ssh.json` from sync, so it never travels -// to the server. -// --------------------------------------------------------------------------- - -/** Connection record of the remote-ssh plugin at a mirror root. */ -export const REMOTE_MARKER_FILE_NAME = '.remote-ssh.json' - -/** The subset of that record this plugin needs to reproduce it. */ -export interface RemoteMarker { - readonly profileId?: string - readonly host: string - readonly port: number - readonly user: string - readonly keyPath?: string - readonly proxyJump?: string - readonly remotePath: string -} - -/** - * Read the remote-ssh connection record of a directory. - * @param dir - directory that may hold the record (a mirror root, usually). - * @returns the record, or null when the directory is not remote-backed. - */ -export async function readRemoteMarker(dir: string): Promise { - let text: string - try { - text = await readFile(resolve(dir, REMOTE_MARKER_FILE_NAME), 'utf8') - } catch { - return null - } - let parsed: unknown - try { - parsed = JSON.parse(text) - } catch { - return null - } - if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null - const row = parsed as Record - if (typeof row.host !== 'string' || row.host === '') return null - if (typeof row.user !== 'string' || row.user === '') return null - const port = typeof row.port === 'number' && Number.isInteger(row.port) && row.port > 0 ? row.port : 22 - const remotePath = typeof row.remotePath === 'string' ? row.remotePath.trim() : '' - if (remotePath === '') return null - return { - ...(typeof row.profileId === 'string' && row.profileId !== '' ? { profileId: row.profileId } : {}), - host: row.host, - port, - user: row.user, - ...(typeof row.keyPath === 'string' ? { keyPath: row.keyPath } : {}), - ...(typeof row.proxyJump === 'string' && row.proxyJump !== '' ? { proxyJump: row.proxyJump } : {}), - remotePath, - } -} +// Do not copy remote-ssh records into subdirectories. Remote-ssh 2.4.40 +// resolves model-tool context only at registered roots; child records do not +// register a workspace and can bypass the parent's writeBack guard. +// Existing records belong to the user / remote-ssh and are left untouched. /** * Join a remote path with a mirror-relative subpath. @@ -338,42 +307,3 @@ export function remoteSubpath(remotePath: string, relativePath: string): string const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '') return base === '' ? rel : `${base}/${rel}` } - -/** - * Stamp the remote-ssh connection record into a subdirectory of a mirror, so - * that sessions started there keep a remote terminal (see the block comment). - * - * A workspace that is not remote-backed is left untouched: no record at the - * workspace root means the plugin has nothing to reproduce. - * @param workspacePath - the workspace's canonical directory (the mirror root). - * @param folderPath - subdirectory added as an extra folder. - * @returns `{ marked: false }` for a local workspace, otherwise the remote path - * written into the subdirectory record. - */ -export async function ensureRemoteMarker( - workspacePath: string, - folderPath: string, -): Promise<{ marked: boolean; remotePath?: string }> { - const base = resolve(workspacePath) - const folder = resolve(folderPath) - const rel = relative(base, folder) - if (rel === '' || rel.startsWith('..')) { - throw invalid('folder is not inside the workspace directory') - } - const marker = await readRemoteMarker(base) - if (marker === null) return { marked: false } - const remotePath = remoteSubpath(marker.remotePath, rel.split(sep).join('/')) - if (remotePath === null) throw invalid('remote subpath is unusable') - const record: RemoteMarker = { - ...(marker.profileId === undefined ? {} : { profileId: marker.profileId }), - host: marker.host, - port: marker.port, - user: marker.user, - ...(marker.keyPath === undefined ? {} : { keyPath: marker.keyPath }), - ...(marker.proxyJump === undefined ? {} : { proxyJump: marker.proxyJump }), - remotePath, - } - await mkdir(folder, { recursive: true }) - await writeFile(resolve(folder, REMOTE_MARKER_FILE_NAME), JSON.stringify(record, null, 2), 'utf8') - return { marked: true, remotePath } -} diff --git a/src/index.ts b/src/index.ts index 58b5c15..3bb69b1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -17,9 +17,11 @@ * - `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. - * - `POST /workspace-groups/folders` — stamp the remote-ssh connection record - * into an extra folder of a mirror workspace, so sessions started there keep - * a remote terminal (see the mirror block comment in host-folders.ts). + * - `POST /workspace-groups/folders` — deprecated; returns 410 without reading + * the payload or touching remote-ssh records. + * + * - `GET /workspace-groups/remote-hint?path=...` — presence-only marker hint + * at the requested absolute path or ancestors; never returns marker content. * * Core workspace.json / session storage is never touched. */ @@ -45,9 +47,10 @@ import { import { defaultFoldersPath, defaultRemoteMirrorBase, - ensureRemoteMarker, + hasRemoteMarkerHint, readFoldersDocument, validateFoldersDocument, + validateRemoteHintPath, writeFoldersDocument, } from './host-folders.ts' @@ -248,6 +251,39 @@ export function apply(ctx: GroupsContext): void { }, }), '@dsh-xhl/workspace-groups: /workspace-groups/manual route') + ctx.effect(() => ctx.webServer.register({ + kind: 'exact', + path: '/workspace-groups/remote-hint', + handler: async (req, res) => { + if (req.method !== 'GET' && req.method !== 'HEAD') { + writeError(res, 405, 'method not allowed') + return + } + let path: string + try { + const url = new URL(req.url ?? '', 'http://localhost') + path = validateRemoteHintPath(url.searchParams.get('path')) + } catch { + writeError(res, 400, 'workspace-groups: invalid remote hint path') + return + } + let remoteHint: boolean + try { + remoteHint = await hasRemoteMarkerHint(path) + } catch { + writeError(res, 500, 'workspace-groups: failed to inspect remote hint; local fallback is unsafe') + return + } + const body = JSON.stringify({ remoteHint }) + 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) + }, + }), '@dsh-xhl/workspace-groups: /workspace-groups/remote-hint route') + ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/workspace-groups/folders', @@ -268,40 +304,9 @@ export function apply(ctx: GroupsContext): void { return } if (req.method === 'POST') { - // `{ workspacePath, folderPath }` → stamp the remote-ssh connection - // record into an extra folder of a MIRROR workspace. The client sends - // this right after adding such a folder: remote-ssh reads the record at - // the session cwd (it never walks up), so without it a session started - // in `/sub` would silently get a local terminal. - 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 - } - const payload = typeof raw === 'object' && raw !== null ? raw as Record : {} - const workspacePath = typeof payload.workspacePath === 'string' ? payload.workspacePath.trim() : '' - const folderPath = typeof payload.folderPath === 'string' ? payload.folderPath.trim() : '' - if (workspacePath === '' || folderPath === '') { - writeError(res, 400, 'workspace-groups: workspacePath and folderPath are required') - return - } - let result: { marked: boolean; remotePath?: string } - try { - result = await ensureRemoteMarker(workspacePath, folderPath) - } catch (error) { - writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`) - return - } - const marked = JSON.stringify(result) - res.writeHead(200, { - 'Content-Type': 'application/json; charset=utf-8', - 'Cache-Control': 'no-store', - 'Content-Length': Buffer.byteLength(marked), - }) - res.end(marked) + // Child markers neither register model-tool context nor preserve the + // parent's writeBack guard. Never read, write or remove any marker. + writeError(res, 410, 'workspace-groups: remote marker creation is deprecated; use the registered remote workspace root') return } if (req.method !== 'PUT') { diff --git a/tests/folders.test.ts b/tests/folders.test.ts index 8b620fb..995251a 100644 --- a/tests/folders.test.ts +++ b/tests/folders.test.ts @@ -4,7 +4,12 @@ * 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 { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { Readable } from 'node:stream' +import { apply } from '../src/index.ts' +import type { GroupsContext, GroupsWebRoute } from '../src/context-types.ts' +import * as hostFolders from '../src/host-folders.ts' import { join } from 'node:path' import { tmpdir } from 'node:os' import { @@ -29,6 +34,104 @@ import { const BASE = 'C:\\work\\project' const EXTRA = 'C:\\work\\extra' +describe('deprecated remote marker route', () => { + it('exports no marker writer or connection record reader', () => { + expect(hostFolders).not.toHaveProperty('ensureRemoteMarker') + expect(hostFolders).not.toHaveProperty('readRemoteMarker') + }) + + it('returns 410 without creating or changing markers, while GET/PUT still work', async () => { + const home = await mkdtemp(join(tmpdir(), 'wg-deprecated-marker-')) + const previousHome = process.env.DSH_HOME + process.env.DSH_HOME = home + try { + const routes: GroupsWebRoute[] = [] + apply({ + effect: (callback: () => unknown) => callback(), + webServer: { register: (route: GroupsWebRoute) => { routes.push(route); return () => {} } }, + } as unknown as GroupsContext) + const route = routes.find(item => item.path === '/workspace-groups/folders')! + expect(route).toBeDefined() + const request = async (method: string, body?: string) => { + const req = Readable.from(body === undefined ? [] : [body]) as IncomingMessage + req.method = method + let status = 0 + let text: string | undefined + await route.handler(req, { + writeHead: (code: number) => { status = code }, + end: (value?: string) => { text = value }, + } as unknown as ServerResponse) + return { status, text } + } + const mirror = join(home, 'mirror') + const existing = join(mirror, 'existing') + await mkdir(existing, { recursive: true }) + const rootMarker = '{"host":"example.invalid","user":"test","port":22,"remotePath":"/srv/test","writeBack":false}' + const childMarker = '{"keep":"existing user marker"}\n' + await writeFile(join(mirror, '.remote-ssh.json'), rootMarker, 'utf8') + await writeFile(join(existing, '.remote-ssh.json'), childMarker, 'utf8') + for (const body of [ + JSON.stringify({ workspacePath: mirror, folderPath: join(mirror, 'new', 'nested') }), + JSON.stringify({ workspacePath: mirror, folderPath: existing }), + '{invalid json', + undefined, + ]) { + const response = await request('POST', body) + expect(response.status).toBe(410) + expect(response.text).toContain('deprecated') + } + expect(await readdir(mirror)).toEqual(['.remote-ssh.json', 'existing']) + expect(await readFile(join(mirror, '.remote-ssh.json'), 'utf8')).toBe(rootMarker) + expect(await readFile(join(existing, '.remote-ssh.json'), 'utf8')).toBe(childMarker) + expect(await readdir(home)).toEqual(['mirror']) + const document = { version: 1, workspaces: { test: { folders: [existing] } } } + expect((await request('PUT', JSON.stringify(document))).status).toBe(200) + const response = await request('GET') + expect(response.status).toBe(200) + expect(JSON.parse(response.text!)).toEqual({ ...document, remoteBase: hostFolders.defaultRemoteMirrorBase() }) + + const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')! + expect(hintRoute).toBeDefined() + const hintRequest = async (method: string, path?: string) => { + let status = 0 + let text: string | undefined + await hintRoute.handler({ + method, + url: '/workspace-groups/remote-hint' + (path === undefined ? '' : '?path=' + encodeURIComponent(path)), + } as IncomingMessage, { + writeHead: (code: number) => { status = code }, + end: (value?: string) => { text = value }, + } as unknown as ServerResponse) + return { status, text } + } + expect(await hintRequest('GET', join(mirror, 'not-created', 'nested'))).toEqual({ status: 200, text: '{"remoteHint":true}' }) + expect(await hintRequest('GET', existing)).toEqual({ status: 200, text: '{"remoteHint":true}' }) + expect(await hintRequest('GET', home)).toEqual({ status: 200, text: '{"remoteHint":false}' }) + expect(await hintRequest('HEAD', existing)).toEqual({ status: 200, text: undefined }) + expect((await hintRequest('POST', existing)).status).toBe(405) + for (const path of [undefined, '', 'relative', home + '\u0000', home + 'x'.repeat(1025)]) { + expect((await hintRequest('GET', path)).status).toBe(400) + } + expect(await readFile(join(mirror, '.remote-ssh.json'), 'utf8')).toBe(rootMarker) + expect(await readFile(join(existing, '.remote-ssh.json'), 'utf8')).toBe(childMarker) + } finally { + if (previousHome === undefined) delete process.env.DSH_HOME + else process.env.DSH_HOME = previousHome + await rm(home, { recursive: true, force: true }) + } + }) +}) + +describe('remoteSubpath (pure path logic)', () => { + it('joins remote roots with POSIX separators and rejects traversal', () => { + expect(hostFolders.remoteSubpath('~', 'data')).toBe('~/data') + expect(hostFolders.remoteSubpath('/srv/project/', 'a\\b')).toBe('/srv/project/a/b') + expect(hostFolders.remoteSubpath('/srv/project', '../escape')).toBeNull() + expect(hostFolders.remoteSubpath('/srv/project', 'a/../b')).toBeNull() + expect(hostFolders.remoteSubpath('/srv/project', ' ')).toBeNull() + }) +}) + describe('samePath', () => { it('is case-insensitive for Windows-style paths', () => { expect(samePath('C:\\Work\\Project', 'c:\\work\\project')).toBe(true) diff --git a/tools/verify-directory-flow.mjs b/tools/verify-directory-flow.mjs new file mode 100644 index 0000000..1eb0280 --- /dev/null +++ b/tools/verify-directory-flow.mjs @@ -0,0 +1,17 @@ +import assert from 'node:assert/strict' +import { directoryFlowFromEntry } from '../src/client/directory-flow.ts' +assert.equal(directoryFlowFromEntry(undefined), null) +const component = () => null +const workspaces = { create() {} } +let called = 0 +const entry = { component, options: {}, inject: () => { called++; return { workspaces } } } +const flow = directoryFlowFromEntry(entry) +assert.equal(flow.component, component) +assert.equal(flow.injected.workspaces, workspaces) +assert.equal(called, 1) +assert.deepEqual(directoryFlowFromEntry({ component, options: {} }).injected, {}) +for (const extra of [{ locale: 'picker' }, { store: {} }, { children: {} }, { component: null }]) { + assert.throws(() => directoryFlowFromEntry({ ...entry, ...extra }), /unsupported renderer context/) +} +assert.throws(() => directoryFlowFromEntry({ ...entry, inject: () => { throw new Error('service unavailable') } }), /service unavailable/) +console.log('directory flow adapter: all assertions passed') diff --git a/tools/verify-folder-directory.mjs b/tools/verify-folder-directory.mjs new file mode 100644 index 0000000..49edafb --- /dev/null +++ b/tools/verify-folder-directory.mjs @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict' +import { createWorkspaceDirectory, remoteFolderWorkspace, validateFolderName } from '../src/client/folder-directory.ts' + +const mirror = 'C:\\Users\\test\\.dsh\\remote-workspaces\\one' +const base = 'C:\\Users\\test\\.dsh\\remote-workspaces' +const ws = { mirrorPath: mirror, profileId: 'test-profile', remotePath: '~/project' } +const response = value => new Response(JSON.stringify({ ok: true, value }), { status: 200 }) +const catalog = workspaces => response({ ok: true, workspaces }) +let localCalls = 0 +const local = async (path, name) => { localCalls++; return `${path}/${name}` } +const hint = remoteHint => new Response(JSON.stringify({ remoteHint })) +const missing = async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(false) : new Response('', { status: 404 }) +assert.deepEqual(await createWorkspaceDirectory('/tmp/project', 'data', base, local, missing), { path: '/tmp/project/data', remote: false }) +assert.equal(localCalls, 1) +await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, missing), /unavailable/) +assert.equal(localCalls, 1) + +const calls = [] +const ssh = async (url, init) => { + calls.push({ url, body: JSON.parse(init.body), headers: init.headers }) + return url.endsWith('listWorkspaces') ? catalog([ws]) : response({ ok: true, exitCode: 0 }) +} +const created = await createWorkspaceDirectory(mirror, '数据', base, local, ssh) +assert.equal(created.remote, true) +assert.equal(created.path, `${mirror}\\数据`) +assert.deepEqual(calls[1].body, { profileId: 'test-profile', path: '~/project/数据' }) +assert.equal(calls[1].url, '/remote-ssh/api/mkdir') +assert.equal(calls[1].headers['X-Requested-With'], 'XMLHttpRequest') +assert.equal(localCalls, 1) +calls.length = 0 +await createWorkspaceDirectory(`${mirror}\\src`, 'data', base, local, ssh) +assert.equal(calls[1].body.path, '~/project/src/data') +calls.length = 0 +await createWorkspaceDirectory(mirror.toUpperCase().replaceAll('\\', '/') + '/src', 'space name', base, local, ssh) +assert.equal(calls[1].body.path, '~/project/src/space name') +let rootRequest +await createWorkspaceDirectory(mirror, 'data', base, local, async (url, init) => { + if (url.endsWith('listWorkspaces')) return catalog([{ ...ws, remotePath: '/' }]) + rootRequest = JSON.parse(init.body) + return response({ ok: true }) +}) +assert.equal(rootRequest.path, '/data') +// Non-default mirror location is recognized from the registered catalog. +assert.ok(await remoteFolderWorkspace('D:/custom', base, async () => catalog([{ ...ws, mirrorPath: 'D:\\custom' }]))) +assert.equal(await remoteFolderWorkspace(`${mirror}-other`, null, async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(false) : catalog([ws])), null) +// Custom mirrors and even the initial null mirror-base state are guarded by a read-only marker hint. +for (const remoteBase of [null, base]) { + await assert.rejects(createWorkspaceDirectory('D:/custom', 'data', remoteBase, local, + async url => url.startsWith('/workspace-groups/remote-hint?') ? hint(true) : new Response('', { status: 404 })), /marker detected/) +} +await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, + async url => url.startsWith('/workspace-groups/remote-hint?') ? new Response('', { status: 500 }) : new Response('', { status: 404 })), /Cannot verify/) +await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, + async url => url.startsWith('/workspace-groups/remote-hint?') ? new Response('{}') : catalog([])), /Invalid directory/) +await assert.rejects(remoteFolderWorkspace(mirror, base, async () => new Response(JSON.stringify({ ok: false, error: { message: 'denied' } }))), /denied/) +await assert.rejects(remoteFolderWorkspace(mirror, base, async () => catalog([])), /not registered/) +await assert.rejects(remoteFolderWorkspace(`${mirror}\\src`, base, async () => catalog([ws, { ...ws, mirrorPath: `${mirror}\\src` }])), /Overlapping/) +for (const value of [{ ok: true }, { ok: true, workspaces: [null] }, { ok: false, error: 'denied' }]) { + await assert.rejects(remoteFolderWorkspace('/tmp/project', base, async () => response(value))) +} +for (const status of [403, 500]) { + await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => new Response('', { status }))) +} +await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => { throw new Error('network') }), /network/) +await assert.rejects(createWorkspaceDirectory('/tmp/project', 'data', base, local, async () => new Response('not json'))) +for (const status of [404, 403, 500]) { + await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, async url => url.endsWith('listWorkspaces') ? catalog([ws]) : new Response('', { status }))) +} +await assert.rejects(createWorkspaceDirectory(mirror, 'data', base, local, async url => url.endsWith('listWorkspaces') ? catalog([ws]) : response({ ok: false, stderr: 'permission denied' })), /permission denied/) +assert.equal(localCalls, 1, 'Failures must never fall back to local mkdir') +for (const name of ['', '.', '..', '/absolute', 'C:\\drive', 'nested/path', 'nested\\path', '\u0000']) { + assert.throws(() => validateFolderName(name)) +} +for (const name of ['$(whoami)', '`date`', 'a"b']) { + await assert.rejects(createWorkspaceDirectory(mirror, name, base, local, ssh)) +} +assert.equal(validateFolderName(' 中文 '), '中文') +console.log('folder-directory: all assertions passed (mocked APIs, no SSH connection)') diff --git a/tools/verify-folders.mjs b/tools/verify-folders.mjs index 6845c32..6608925 100644 --- a/tools/verify-folders.mjs +++ b/tools/verify-folders.mjs @@ -2,15 +2,19 @@ * 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 + * critical assertions under Node 24 with TypeScript transformation: + * node --experimental-transform-types 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. + * It exercises the pure root/cwd rules, the host overlay's strict-write / + * tolerant-read boundary, and the registered folder route in a fake context. + * All filesystem fixtures use temporary directories, never real profiles. */ import assert from 'node:assert/strict' -import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import fsPromises from 'node:fs/promises' +import { syncBuiltinESMExports } from 'node:module' +import { Readable } from 'node:stream' +import { apply } from '../src/index.ts' import { join } from 'node:path' import { tmpdir } from 'node:os' @@ -29,15 +33,15 @@ const { samePath, setRoot, } = await import(coreUrl.href) +const host = await import(hostUrl.href) const { - ensureRemoteMarker, + defaultRemoteMirrorBase, parseFoldersDocument, readFoldersDocument, - readRemoteMarker, remoteSubpath, validateFoldersDocument, writeFoldersDocument, -} = await import(hostUrl.href) +} = host const BASE = 'C:\\work\\project' const EXTRA = 'C:\\work\\extra' @@ -175,10 +179,7 @@ equal(joinSubpath(MIRROR_WS, './ok'), `${MIRROR_WS}\\ok`, 'a leading dot segment equal(folderOfCwd(`${MIRROR_WS}\\data\\file`, MIRROR_WS, entry), `${MIRROR_WS}\\data`, 'sessions under the mirror subpath belong to it') } -// --- remote-ssh markers ------------------------------------------------------ -// remote-ssh reads `.remote-ssh.json` at the session cwd only (never walking -// up), so an extra folder inside a mirror needs its own record or its sessions -// silently lose the remote terminal. +// --- pure remote path logic (no marker I/O) ---------------------------------- equal(remoteSubpath('~/projects/cloud-memory', 'data'), '~/projects/cloud-memory/data', 'a ~ root joins with a slash') equal(remoteSubpath('~', 'data'), '~/data', 'a bare ~ keeps its home meaning') equal(remoteSubpath('/srv/proj/', 'a/b'), '/srv/proj/a/b', 'an absolute remote root joins with a POSIX slash') @@ -187,45 +188,100 @@ equal(remoteSubpath('/srv/proj', '..'), null, 'a parent traversal never reaches equal(remoteSubpath('/srv/proj', 'a/../b'), null, 'an embedded traversal never reaches the remote shell') equal(remoteSubpath('/srv/proj', ' '), null, 'a blank subpath is refused') +// --- deprecated route: isolated fake context, no server or real profile ------- +check(!('ensureRemoteMarker' in host), 'no exported marker writer remains') +check(!('readRemoteMarker' in host), 'no remote connection record reader remains') { - const mirror = await mkdtemp(join(tmpdir(), 'wg-mirror-verify-')) + const home = await mkdtemp(join(tmpdir(), 'wg-deprecated-marker-')) + const previousHome = process.env.DSH_HOME + process.env.DSH_HOME = home try { - equal(await readRemoteMarker(mirror), null, 'a directory without a record is not remote-backed') - const local = await mkdtemp(join(tmpdir(), 'wg-local-verify-')) - try { - equal( - await ensureRemoteMarker(local, join(local, 'sub')), - { marked: false }, - 'a local workspace is left untouched', - ) - const marker = { - profileId: 'p-1', host: 'qyhhh.top', port: 22, user: 'ubuntu', - keyPath: 'C:\\Users\\me\\.ssh\\id_ed25519', remotePath: '~/projects/cloud-memory', - } - await writeFile(join(mirror, '.remote-ssh.json'), JSON.stringify(marker, null, 2), 'utf8') - equal(await readRemoteMarker(mirror), marker, 'the record round-trips') + const routes = [] + apply({ + effect: callback => callback(), + webServer: { register: route => { routes.push(route); return () => {} } }, + }) + const route = routes.find(item => item.path === '/workspace-groups/folders') + check(route !== undefined, 'folders route remains registered') + const request = async (method, body) => { + const req = Readable.from(body === undefined ? [] : [body]) + req.method = method + let status + let text + await route.handler(req, { + writeHead: code => { status = code }, + end: value => { text = value }, + }) + return { status, text } + } + const mirror = join(home, 'mirror') + const existing = join(mirror, 'existing') + await mkdir(existing, { recursive: true }) + const rootMarker = '{"host":"example.invalid","user":"test","port":22,"remotePath":"/srv/test","writeBack":false}' + const childMarker = '{"keep":"existing user marker"}\n' + await writeFile(join(mirror, '.remote-ssh.json'), rootMarker, 'utf8') + await writeFile(join(existing, '.remote-ssh.json'), childMarker, 'utf8') + for (const body of [ + JSON.stringify({ workspacePath: mirror, folderPath: join(mirror, 'new', 'nested') }), + JSON.stringify({ workspacePath: mirror, folderPath: existing }), + '{invalid json', + undefined, + ]) { + const response = await request('POST', body) + equal(response.status, 410, 'legacy POST is unconditionally gone') + check(response.text.includes('deprecated'), 'legacy POST explains deprecation') + } + equal(await readdir(mirror), ['.remote-ssh.json', 'existing'], 'POST creates no child directories or markers') + equal(await readFile(join(mirror, '.remote-ssh.json'), 'utf8'), rootMarker, 'root marker and writeBack guard stay unchanged') + equal(await readFile(join(existing, '.remote-ssh.json'), 'utf8'), childMarker, 'existing child marker is neither overwritten nor deleted') + equal(await readdir(home), ['mirror'], 'POST writes no overlay either') + const document = { version: 1, workspaces: { test: { folders: [existing] } } } + equal((await request('PUT', JSON.stringify(document))).status, 200, 'normal folder PUT remains available') + const response = await request('GET') + equal(response.status, 200, 'normal folder GET remains available') + equal(JSON.parse(response.text), { ...document, remoteBase: defaultRemoteMirrorBase() }, 'GET preserves saved folders and remote mirror base') - const sub = join(mirror, 'data', 'raw') - equal( - await ensureRemoteMarker(mirror, sub), - { marked: true, remotePath: '~/projects/cloud-memory/data/raw' }, - 'a nested extra folder gets the remote counterpart of its own path', - ) - equal( - await readRemoteMarker(sub), - { ...marker, remotePath: '~/projects/cloud-memory/data/raw' }, - 'the stamped record keeps the connection and only rewrites remotePath', - ) - await assert.rejects( - () => ensureRemoteMarker(mirror, join(mirror, '..', 'outside')), - /folder is not inside the workspace directory/u, - 'a folder outside the mirror is refused, never stamped', - ) + const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint') + check(hintRoute !== undefined, 'remote hint route is registered') + const hintRequest = async (method, path) => { + let status + let text + await hintRoute.handler({ + method, + url: '/workspace-groups/remote-hint' + (path === undefined ? '' : '?path=' + encodeURIComponent(path)), + }, { + writeHead: code => { status = code }, + end: value => { text = value }, + }) + return { status, text } + } + equal(await hintRequest('GET', join(mirror, 'not-created', 'nested')), { status: 200, text: '{"remoteHint":true}' }, 'ancestor marker detects a non-default mirror even for missing descendants') + equal(await hintRequest('GET', existing), { status: 200, text: '{"remoteHint":true}' }, 'marker content need not parse as connection data') + equal(await hintRequest('GET', home), { status: 200, text: '{"remoteHint":false}' }, 'no marker reports false') + equal(await hintRequest('HEAD', existing), { status: 200, text: undefined }, 'HEAD has no response body') + equal((await hintRequest('POST', existing)).status, 405, 'hint endpoint is read-only') + for (const path of [undefined, '', 'relative', home + '\u0000', home + 'x'.repeat(1025)]) { + equal((await hintRequest('GET', path)).status, 400, 'invalid hint paths are rejected') + } + equal(await readFile(join(mirror, '.remote-ssh.json'), 'utf8'), rootMarker, 'hint leaves root marker unchanged') + equal(await readFile(join(existing, '.remote-ssh.json'), 'utf8'), childMarker, 'hint never rewrites malformed marker content') + const originalLstat = fsPromises.lstat + try { + for (const code of ['EACCES', 'EIO', 'ENOTDIR']) { + fsPromises.lstat = async () => { throw Object.assign(new Error('private path must not leak'), { code }) } + syncBuiltinESMExports() + const failed = await hintRequest('GET', existing) + equal(failed.status, 500, 'inspection errors fail closed, never return false') + check(!failed.text.includes('private path'), 'inspection errors do not expose marker details') + } } finally { - await rm(local, { recursive: true, force: true }) + fsPromises.lstat = originalLstat + syncBuiltinESMExports() } } finally { - await rm(mirror, { recursive: true, force: true }) + if (previousHome === undefined) delete process.env.DSH_HOME + else process.env.DSH_HOME = previousHome + await rm(home, { recursive: true, force: true }) } } diff --git a/tsdown.config.ts b/tsdown.config.ts index 5ee2ce2..f45cd1b 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -18,13 +18,26 @@ * * Types ship from lib/types (tsc -p tsconfig.build.json), not from tsdown. */ +import { existsSync, readFileSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { dirname, resolve as resolvePath, isAbsolute } from 'node:path' -import { existsSync } from 'node:fs' +import { fileURLToPath } from 'node:url' import { builtinModules } from 'node:module' import type { UserConfig } from 'tsdown' import { transform } from 'lightningcss' +/** + * The client bundle banner MUST register under the package name: client-modules + * keys its graph rows by package name, so a banner id that differs makes the + * row look unregistered (the row is then re-fetched, hits `register()` a second + * time and throws "duplicate factory registration", failing the whole boot). + * Read the name instead of hardcoding it — the package has been renamed once + * already (`@dsh-xhl/workspace-groups` -> `workspace-groups-local`). + */ +const PACKAGE_NAME: string = ( + JSON.parse(readFileSync(fileURLToPath(new URL('./package.json', import.meta.url)), 'utf8')) as { name: string } +).name + /** Node builtins must never survive into the browser module-loader factory. */ const NODE_BUILTINS = new Set([ ...builtinModules, @@ -147,7 +160,7 @@ function clientConfig(): UserConfig { ], outputOptions: { entryFileNames: 'client.js', - banner: `window.__ModuleLoader__.load({ id: "@dsh-xhl/workspace-groups", factory: (require) => {`, + banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(PACKAGE_NAME)}, factory: (require) => {`, footer: 'return module.exports; } });', intro: 'var module = { exports: {} }; var exports = module.exports;', },