feat(sidebar): multi-root workspaces (extra folders + one root per project)
A DSH workspace owns exactly one canonical directory, so the folder layer is a plugin-side overlay instead of a core change: \/workspace-groups.folders.json stores extra folders and the chosen root per workspace id (strict on write, tolerant on read). The tree gains a folder row only when a project actually has extras, and sessions are partitioned by their recorded cwd with the most specific folder winning. A folder row can start a session in its own directory through sessions.create({workspaceId, cwd}); the base folder keeps the platform gesture so repeated clicks reuse the blank session. Folders start expanded so attaching one never hides rows that were already visible.
This commit is contained in:
parent
15976d7e51
commit
0db6e06ccf
|
|
@ -34,9 +34,10 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
|
|||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 条路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual` |
|
||||
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT /workspace-groups/folders` |
|
||||
| `src/host-config.ts` | 读用户 YAML 分类规则(默认 `~/.dsh/workspace-groups.yaml`),校验后以 JSON 下发 |
|
||||
| `src/host-manual.ts` | 运行期分组覆盖(手动分组 + 单工作区归类覆盖),落 `$DSH_HOME/workspace-groups.manual.json` |
|
||||
| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容) |
|
||||
| `src/host-tabs.ts` | 会话标签条的宿主侧持久化。放在宿主是因为**浏览器存储按 origin 隔离,而 origin 含端口**,`dsh web`/测试/桌面壳端口各不相同 |
|
||||
| `src/context-types.ts` | 本插件消费的 cordis 服务结构类型(第三方插件拿不到 monorepo 内的 `declare module` 合并) |
|
||||
|
||||
|
|
@ -46,6 +47,7 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
|
|||
| --- | --- |
|
||||
| `src/core/types.ts` | 规则配置类型,零运行时依赖 |
|
||||
| `src/core/matcher.ts` | 归类与排序的纯函数:工作区归哪个分类、分类/工作区怎么排。宿主校验与客户端建树共用,语义不会漂移 |
|
||||
| `src/core/folders.ts` | 多文件夹的纯函数:有效文件夹列表、根目录解析、cwd 归属(最具体优先)。宿主校验与客户端建树共用 |
|
||||
|
||||
浏览器半边(`src/client/`,输出 CJS 闭包工厂):
|
||||
|
||||
|
|
@ -55,7 +57,8 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
|
|||
| `contract.ts` | 注入共享契约(`GroupsBrowserInjected`),镜像官方 ui-workspace 的注入形状 |
|
||||
| `GroupsBrowser.tsx` | 主 UI:分区头(标题/搜索/新建分组/添加工作区)+ 三级树 + 分组/工作区/会话对话框 |
|
||||
| `rows.tsx` | 树的行组件(行内菜单、状态点、图标),对话框挂在 browser root 以免折叠时卸载 |
|
||||
| `tree.ts` | 纯派生:分类文件夹 → 项目文件夹 → 会话行;可见性规则对齐官方树 |
|
||||
| `tree.ts` | 纯派生:分类文件夹 → 项目文件夹 →(可选)文件夹行 → 会话行;可见性规则对齐官方树 |
|
||||
| `folders-persist.ts` | 文件夹 overlay 的客户端侧,读写宿主 `/workspace-groups/folders` |
|
||||
| `locales.ts` | `workspaceGroups` 命名空间词典(zh/en + key 联合类型) |
|
||||
| `styles.css` | 全部样式,`?inline` 导入后由构建期 lightningcss 压缩内联 |
|
||||
| `branch.ts` / `FlowerBranch.tsx` | 侧栏当前行的「花朵」标记(几何计算在 `branch.ts`,仍由单测覆盖;连线与逐行圆点已移除,只画花朵) |
|
||||
|
|
@ -71,7 +74,8 @@ git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30
|
|||
| `stores.ts` | 视图 store 工厂(展开状态,独立持久化 key,不碰官方 `dsh.workspace.view.v5`) |
|
||||
| `store-hook.ts` | 面向 store 实例的框架形状选择器 hook(`useSyncExternalStoreWithSelector`) |
|
||||
|
||||
其它:`tests/*.test.ts`(vitest,覆盖 core matcher/tree/store),`cordis.patch.yml`
|
||||
其它:`tests/*.test.ts`(vitest,覆盖 core matcher/tree/store/tabs/folders),
|
||||
`tools/verify-folders.mjs`(沙箱内 vitest 起不来时的等价纯 node 断言),`cordis.patch.yml`
|
||||
(cordis 插件补丁层),`scripts/verify-groups.mjs`,`workspace-groups.example.yaml`。
|
||||
|
||||
## 3. 构建 / 校验 / 装回去
|
||||
|
|
|
|||
42
README.md
42
README.md
|
|
@ -78,6 +78,23 @@
|
|||
skipped for large subtrees, during drag folding, and under `prefers-reduced-motion`
|
||||
- Stored in the overlay's `appearance` map — **never in the rule YAML** (see below)
|
||||
|
||||
### Multiple folders per workspace (multi-root)
|
||||
- **Attach extra folders to a project**: the project row's `⋯` menu opens **文件夹…**
|
||||
(`Folders…`), which lists the project's own directory as the **base folder** (always folder
|
||||
#0, never removable) plus any extra folders you pick
|
||||
- **One root folder per project**: the radio column in that dialog and the folder row's
|
||||
`⋯ → 设为根目录` choose which folder new sessions default to; the root row is hoisted to the
|
||||
top of the folder list and carries a ★ badge
|
||||
- **Sessions partition by their own cwd**: a project with extra folders shows a folder row
|
||||
above its sessions, and each session drops into the folder that contains its working
|
||||
directory (most specific folder wins, case-insensitive on Windows). Projects without extra
|
||||
folders keep the flat two-level shape — nothing changes for them
|
||||
- **Start a session in a specific folder**: the hover `+` on a folder row opens a session whose
|
||||
cwd is that folder; the base folder keeps the platform's own "new session" gesture so
|
||||
clicking it twice reuses the blank session instead of stacking empty ones
|
||||
- Folders start expanded, so attaching one never hides sessions that were already visible;
|
||||
collapse state is per-view and intentionally not persisted
|
||||
|
||||
### Search & operations
|
||||
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
|
||||
session), matched rows highlighted with a content snippet, 250ms debounce
|
||||
|
|
@ -88,7 +105,9 @@
|
|||
- Every manual action (groups, grouping, ordering, rename, hide) is written to the plugin's own
|
||||
overlay (`~/.dsh/workspace-groups.manual.json`), validated by the host and **written
|
||||
atomically** (a malformed write returns 400 and keeps the previous file); the tab strip gets
|
||||
the same treatment in its own file (`~/.dsh/workspace-groups.tabs.json`)
|
||||
the same treatment in its own file (`~/.dsh/workspace-groups.tabs.json`), and so do the
|
||||
extra folders / root choice of a project (`~/.dsh/workspace-groups.folders.json`, strict on
|
||||
write, tolerant on read — unknown or vanished folders are dropped instead of breaking the tree)
|
||||
- **Zero intrusion**: never touches `~/.dsh/storages/workspace.json`, session on-disk
|
||||
structures, or the official `@deepseek-ai/dsh-client-ui-workspace` package; the rule YAML
|
||||
is never rewritten
|
||||
|
|
@ -307,20 +326,29 @@ Artifact contract (mirrors the official client packages):
|
|||
|
||||
```
|
||||
src/
|
||||
index.ts # host half: config snapshot route + manual write route
|
||||
index.ts # host half: config snapshot route + manual / tabs / folders write routes
|
||||
host-config.ts # sidecar YAML reading/validation
|
||||
host-manual.ts # runtime overlay read/write/validation (atomic publish)
|
||||
host-folders.ts # per-workspace extra folders + root overlay (strict write, tolerant read)
|
||||
host-tabs.ts # session tab strip persistence (atomic publish)
|
||||
context-types.ts # host-side cordis service structure types
|
||||
core/
|
||||
types.ts # config types (shared by both halves)
|
||||
matcher.ts # classification + manual override priority + ordering pure functions (shared)
|
||||
folders.ts # multi-root pure logic: effective folders / root / cwd ownership (shared)
|
||||
client/
|
||||
index.ts # apply: registers sidebar.workspaces (priority -1)
|
||||
contract.ts # injected surface types
|
||||
stores.ts # expansion-state store (persist: dsh.workspace.groups.view.v1)
|
||||
tree.ts # three-level tree derivation + tree search derivation
|
||||
GroupsBrowser.tsx # browser region component (group dialogs + drag grouping/ordering + insertion indicator)
|
||||
rows.tsx # category/project/session/search-result rows (drag sources/targets)
|
||||
tree.ts # three-level tree derivation + folder partition + tree search derivation
|
||||
GroupsBrowser.tsx # browser region component (group dialogs + folder dialog + drag grouping/ordering)
|
||||
rows.tsx # category/project/folder/session/search-result rows (drag sources/targets)
|
||||
SessionTabs.tsx # tab strip (pin / drag reorder / context menu / inline rename)
|
||||
tab-store.ts # tab strip store (order, pin, title override)
|
||||
tab-persist.ts # tab strip wire calls (GET/PUT /workspace-groups/tabs)
|
||||
folders-persist.ts # folder overlay wire calls (GET/PUT /workspace-groups/folders)
|
||||
FlowerBranch.tsx # bloom marker on the active row (geometry in branch.ts)
|
||||
branch.ts # flower geometry pure functions (unit tested)
|
||||
locales.ts # zh/en copy
|
||||
styles.css # inline styles
|
||||
tests/
|
||||
|
|
@ -328,6 +356,10 @@ tests/
|
|||
manual.test.ts # overlay validation + atomic file round-trip
|
||||
tree.test.ts # tree derivation rendering contract (manual group empty render / override priority)
|
||||
store.test.ts # expansion semantics (collapse writes false, never deletes the key)
|
||||
tabs.test.ts # tab strip pure logic (append/remove/ordered/restore/indicator)
|
||||
folders.test.ts # multi-root pure logic + strict/tolerant overlay parsing
|
||||
tools/
|
||||
verify-folders.mjs # plain-node verifier for the folder layer (vitest cannot spawn in the sandbox)
|
||||
scripts/
|
||||
verify-groups.mjs # real-browser CDP verification (self-spawns headless Chrome, auto-restores the scene)
|
||||
```
|
||||
|
|
|
|||
17
README_ZH.md
17
README_ZH.md
|
|
@ -65,6 +65,19 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
|||
花不会滞后于所在行;大树、拖动折叠中、`prefers-reduced-motion` 下自动跳过动画
|
||||
- 存放在 overlay 的 `appearance` 里,**绝不写进规则 YAML**
|
||||
|
||||
### 一个工作区多个文件夹(multi-root)
|
||||
- **给项目挂多个文件夹**:项目行的 `⋯` 菜单里点 **文件夹…**,弹窗第一行是项目自带的
|
||||
目录(**基础文件夹**,永远是 #0,不可移除),下面是你自己加的额外文件夹
|
||||
- **每个项目一个根目录**:弹窗里的单选列,或文件夹行的 `⋯ → 设为根目录`,决定“新建会话”
|
||||
默认落在哪个文件夹;根目录那一行会被提到最前面并带 ★ 标记
|
||||
- **会话按自己的 cwd 归位**:项目一旦有额外文件夹,会话上方会多出文件夹行,每条会话按
|
||||
自己记录的 cwd 落进所属文件夹(最具体的文件夹优先,Windows 下大小写不敏感);没有额外
|
||||
文件夹的项目保持原来的两层扁平结构,行为完全不变
|
||||
- **在指定文件夹里开会话**:文件夹行悬停的 `+` 会以该文件夹为 cwd 新建会话;基础文件夹
|
||||
沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话
|
||||
- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态,
|
||||
故意不持久化
|
||||
|
||||
### 搜索与操作
|
||||
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
|
||||
内容摘要,防抖 250ms
|
||||
|
|
@ -74,7 +87,9 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
|||
### 持久化与零侵入
|
||||
- 所有手动操作(分组、归类、排序、改名、隐藏)写入插件自有 overlay
|
||||
(`~/.dsh/workspace-groups.manual.json`),host 校验后**原子写入**(写坏返回 400 并
|
||||
保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json`
|
||||
保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json`;项目的
|
||||
额外文件夹与根目录选择也一样,独立文件 `~/.dsh/workspace-groups.folders.json`
|
||||
(写时严格、读时宽容 —— 不认识的文件夹直接丢弃,不会把树弄坏)
|
||||
- **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、不修改官方
|
||||
`@deepseek-ai/dsh-client-ui-workspace` 包;规则 YAML 永不改写
|
||||
- **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本
|
||||
|
|
|
|||
1017
lib/client.js
1017
lib/client.js
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
298
lib/index.js
298
lib/index.js
|
|
@ -2897,6 +2897,255 @@ function documentForTabs(state) {
|
|||
};
|
||||
}
|
||||
//#endregion
|
||||
//#region src/core/folders.ts
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
const EMPTY_FOLDERS_DOCUMENT = {
|
||||
version: 1,
|
||||
workspaces: {}
|
||||
};
|
||||
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
|
||||
const WINDOWS_DRIVE$1 = /^[A-Za-z]:[\\/]/u;
|
||||
/** `\\server\share` — a Windows UNC path. */
|
||||
const WINDOWS_UNC$1 = /^\\\\/u;
|
||||
/** True for both Windows path spellings accepted by the write validator. */
|
||||
function isWindowsStyle(path) {
|
||||
return WINDOWS_DRIVE$1.test(path) || WINDOWS_UNC$1.test(path);
|
||||
}
|
||||
/**
|
||||
* Comparison form of one path: trimmed, separator-normalized and, for Windows
|
||||
* spellings, lower-cased (drive letters and file names are case-insensitive
|
||||
* there). Trailing separators are dropped except for a drive/UNC/root prefix.
|
||||
* @param path - raw path as stored or picked.
|
||||
* @returns the canonical comparison form.
|
||||
*/
|
||||
function canonicalPath(path) {
|
||||
const trimmed = path.trim();
|
||||
if (isWindowsStyle(trimmed)) {
|
||||
let value = trimmed.replaceAll("/", "\\").toLowerCase();
|
||||
while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1);
|
||||
return value;
|
||||
}
|
||||
let value = trimmed;
|
||||
while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1);
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Path equality: case-insensitive for Windows-style paths, tolerant of
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
function samePath(a, b) {
|
||||
return canonicalPath(a) === canonicalPath(b);
|
||||
}
|
||||
//#endregion
|
||||
//#region src/host-folders.ts
|
||||
/**
|
||||
* Folder overlay for @dsh-xhl/workspace-groups: the per-workspace list of
|
||||
* EXTRA folders plus the designated root folder. Stored in a plugin-owned JSON
|
||||
* sidecar (`$DSH_HOME/workspace-groups.folders.json`), next to the manual
|
||||
* grouping overlay, because neither DSH core nor the YAML rule source knows
|
||||
* about folders: core gives a workspace exactly one canonical directory and the
|
||||
* YAML stays the classification source.
|
||||
*
|
||||
* Writes are strict (the browser PUT route validates the whole document before
|
||||
* replacing it, atomically: temp file + fsync + rename) and reads tolerate
|
||||
* hand-edited content (junk entries are dropped instead of thrown), for the
|
||||
* same reason the manual overlay does: a stale or malformed sidecar must never
|
||||
* freeze the tree.
|
||||
*/
|
||||
/** File name of the folder sidecar (also the stable error-text prefix). */
|
||||
const FOLDERS_FILE_NAME = "workspace-groups.folders.json";
|
||||
const FOLDER_PATH_LIMIT = 1024;
|
||||
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
|
||||
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u;
|
||||
/** `\\server\share` — a Windows UNC path. */
|
||||
const WINDOWS_UNC = /^\\\\/u;
|
||||
/** `/…` — a POSIX absolute path. */
|
||||
const POSIX_ABSOLUTE = /^\//u;
|
||||
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
|
||||
function defaultFoldersPath() {
|
||||
const home = process.env.DSH_HOME !== void 0 && process.env.DSH_HOME !== "" ? process.env.DSH_HOME : resolve(homedir(), ".dsh");
|
||||
return resolve(home, FOLDERS_FILE_NAME);
|
||||
}
|
||||
/**
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
function isAbsoluteFolderPath(path) {
|
||||
return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path);
|
||||
}
|
||||
/** Reject helper carrying the stable file-scoped message prefix. */
|
||||
function invalid(detail) {
|
||||
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`);
|
||||
}
|
||||
/**
|
||||
* Parse one workspace entry.
|
||||
* @param value - raw entry from the document.
|
||||
* @param workspaceId - owning workspace id (used in messages).
|
||||
* @param strict - throw on the first problem, or drop junk and return undefined.
|
||||
* @returns the normalized entry, or undefined when nothing usable remains.
|
||||
*/
|
||||
function parseFolderEntry(value, workspaceId, strict) {
|
||||
const fail = (detail) => {
|
||||
if (strict) invalid(`workspace "${workspaceId}": ${detail}`);
|
||||
};
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
fail("entry must be an object");
|
||||
return;
|
||||
}
|
||||
const source = value;
|
||||
if (source.folders === void 0) {
|
||||
fail("folders is required");
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(source.folders)) {
|
||||
fail("folders must be a list");
|
||||
return;
|
||||
}
|
||||
if (strict && source.folders.length > 32) invalid(`workspace "${workspaceId}": at most 32 folders`);
|
||||
const folders = [];
|
||||
for (const candidate of source.folders) {
|
||||
if (typeof candidate !== "string") {
|
||||
fail("folder paths must be strings");
|
||||
continue;
|
||||
}
|
||||
const path = candidate.trim();
|
||||
if (path === "") {
|
||||
fail("folder paths must be non-empty");
|
||||
continue;
|
||||
}
|
||||
if (path.includes("\0")) {
|
||||
fail(`folder path "${path}" contains a NUL character`);
|
||||
continue;
|
||||
}
|
||||
if (path.length > 1024) {
|
||||
fail(`folder path exceeds ${FOLDER_PATH_LIMIT} characters`);
|
||||
continue;
|
||||
}
|
||||
if (!isAbsoluteFolderPath(path)) {
|
||||
fail(`folder path "${path}" must be absolute`);
|
||||
continue;
|
||||
}
|
||||
if (folders.some((existing) => samePath(existing, path))) {
|
||||
fail(`duplicate folder path "${path}"`);
|
||||
continue;
|
||||
}
|
||||
if (folders.length >= 32) {
|
||||
fail(`at most 32 folders`);
|
||||
break;
|
||||
}
|
||||
folders.push(path);
|
||||
}
|
||||
let root;
|
||||
if (source.root !== void 0) {
|
||||
if (typeof source.root !== "string") fail("root must be a string");
|
||||
else {
|
||||
const candidate = source.root.trim();
|
||||
const member = folders.find((folder) => samePath(folder, candidate));
|
||||
if (member === void 0) fail(`root "${candidate}" must name one of folders`);
|
||||
else root = member;
|
||||
}
|
||||
}
|
||||
if (folders.length === 0 && root === void 0) return void 0;
|
||||
return {
|
||||
folders,
|
||||
...root === void 0 ? {} : { root }
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
||||
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
function parseFoldersDocument(raw) {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return EMPTY_FOLDERS_DOCUMENT;
|
||||
const source = raw;
|
||||
if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT;
|
||||
if (typeof source.workspaces !== "object" || source.workspaces === null || Array.isArray(source.workspaces)) return {
|
||||
version: 1,
|
||||
workspaces: {}
|
||||
};
|
||||
const workspaces = {};
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === "" || workspaceId.length > 200) continue;
|
||||
const entry = parseFolderEntry(value, workspaceId, false);
|
||||
if (entry !== void 0) workspaces[workspaceId] = entry;
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
workspaces
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Strict writer-side validation. Every rule is enforced and the first problem
|
||||
* throws, so the PUT route rejects instead of persisting a half-valid file.
|
||||
* @param raw - parsed JSON value from the request body.
|
||||
* @returns the normalized document to save.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
function validateFoldersDocument(raw) {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) invalid("top-level value must be a mapping");
|
||||
const source = raw;
|
||||
if (source.version !== 1) invalid("version must be 1");
|
||||
if (typeof source.workspaces !== "object" || source.workspaces === null || Array.isArray(source.workspaces)) invalid("workspaces must be a mapping");
|
||||
const workspaces = {};
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === "" || workspaceId.length > 200) invalid(`workspace ids must be non-empty strings of at most 200 characters`);
|
||||
const entry = parseFolderEntry(value, workspaceId, true);
|
||||
if (entry !== void 0) workspaces[workspaceId] = entry;
|
||||
}
|
||||
return {
|
||||
version: 1,
|
||||
workspaces
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
async function readFoldersDocument(path) {
|
||||
try {
|
||||
const text = await readFile(path, "utf8");
|
||||
return parseFoldersDocument(JSON.parse(text));
|
||||
} catch {
|
||||
return EMPTY_FOLDERS_DOCUMENT;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
async function writeFoldersDocument(path, document) {
|
||||
const json = `${JSON.stringify(document, null, 2)}\n`;
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
|
||||
const handle = await open(tmp, "w");
|
||||
try {
|
||||
await handle.writeFile(json, "utf8");
|
||||
await handle.sync();
|
||||
} catch (error) {
|
||||
await handle.close().catch(() => {});
|
||||
await unlink(tmp).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
await handle.close();
|
||||
try {
|
||||
await rename(tmp, path);
|
||||
} catch (error) {
|
||||
await unlink(tmp).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
//#endregion
|
||||
//#region src/index.ts
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
const name = "@dsh-xhl/workspace-groups";
|
||||
|
|
@ -2965,6 +3214,7 @@ function apply(ctx) {
|
|||
const configPath = defaultConfigPath();
|
||||
const manualPath = defaultManualPath();
|
||||
const tabsPath = defaultTabsPath();
|
||||
const foldersPath = defaultFoldersPath();
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/workspace-groups/config",
|
||||
|
|
@ -3084,6 +3334,54 @@ function apply(ctx) {
|
|||
res.end(body);
|
||||
}
|
||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/manual route");
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: "exact",
|
||||
path: "/workspace-groups/folders",
|
||||
handler: async (req, res) => {
|
||||
if (req.method === "GET" || req.method === "HEAD") {
|
||||
const document = await readFoldersDocument(foldersPath);
|
||||
const body = JSON.stringify(document);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Length": Buffer.byteLength(body)
|
||||
});
|
||||
res.end(req.method === "HEAD" ? void 0 : body);
|
||||
return;
|
||||
}
|
||||
if (req.method !== "PUT") {
|
||||
writeError(res, 405, "method not allowed");
|
||||
return;
|
||||
}
|
||||
let raw;
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
|
||||
} catch (error) {
|
||||
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
let document;
|
||||
try {
|
||||
document = validateFoldersDocument(raw);
|
||||
} catch (error) {
|
||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await writeFoldersDocument(foldersPath, document);
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write folder overlay: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
const body = JSON.stringify(document);
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Length": Buffer.byteLength(body)
|
||||
});
|
||||
res.end(body);
|
||||
}
|
||||
}), "@dsh-xhl/workspace-groups: /workspace-groups/folders route");
|
||||
}
|
||||
//#endregion
|
||||
export { apply, inject, name };
|
||||
|
|
|
|||
|
|
@ -30,4 +30,4 @@ export type DragIndicator = {
|
|||
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||
* @returns the region element tree.
|
||||
*/
|
||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
|
|
|
|||
|
|
@ -30,6 +30,11 @@ export type GroupsBrowserInjected = {
|
|||
};
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/**
|
||||
* Create a real Session in one folder of a Workspace and open it. `cwd` is
|
||||
* omitted for the base folder (the Workspace's own canonical directory).
|
||||
*/
|
||||
createSessionIn: (workspaceId: WorkspaceId, cwd?: string) => Promise<SessionId>;
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void;
|
||||
/** Search current visible conversation messages. */
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
/**
|
||||
* Client side of the per-workspace folder list, talking to
|
||||
* `GET|PUT /workspace-groups/folders` on the host.
|
||||
*
|
||||
* The document is the host's JSON sidecar verbatim (`version` + `workspaces`),
|
||||
* so the client and the host agree on one shape: `folders` holds EXTRA folders
|
||||
* only — the workspace's canonical directory is implicit folder #0 — and
|
||||
* `root` names one of those extras (absent means "the workspace itself").
|
||||
*
|
||||
* Reads are best-effort, like the manual overlay and the tab strip: a failed
|
||||
* read means "no extra folders". A failed write, however, rejects so the caller
|
||||
* can say so — a folder row that silently forgot its edit would be worse than
|
||||
* the toast.
|
||||
*/
|
||||
import { type FoldersDocument } from '../core/folders.ts';
|
||||
/** Host route holding the folder overlay. */
|
||||
export declare const FOLDERS_ROUTE = "/workspace-groups/folders";
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the document; the empty document on any failure.
|
||||
*/
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersDocument>;
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
*
|
||||
* Unlike the tab strip this does NOT swallow failures: folder edits are explicit
|
||||
* row/dialog actions, so the caller turns a rejection into a toast instead of
|
||||
* leaving the user with a row that silently forgot its folder.
|
||||
* @param document - the client's current document.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<void>;
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@
|
|||
import { type DragEvent, type ReactNode } from 'react';
|
||||
import { type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
|
||||
import type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
|
||||
type T = TranslateNS<'workspaceGroups'>;
|
||||
/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */
|
||||
export declare const DND_WORKSPACE_TYPE = "application/x-dsh-workspace-groups";
|
||||
|
|
@ -65,7 +65,7 @@ export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, onT
|
|||
onDragStartCategory?: (event: DragEvent) => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, onManageFolders, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
|
|
@ -75,6 +75,8 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename
|
|||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean;
|
||||
onMoveOut?: () => void;
|
||||
/** Open the folder-management dialog (extra folders + root). */
|
||||
onManageFolders?: () => void;
|
||||
/**
|
||||
* Open the project directory in the host's file manager. Omitted when the
|
||||
* host resolved no folder application (no capability, or a remote launch),
|
||||
|
|
@ -86,6 +88,28 @@ export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename
|
|||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
onDragStartExtra?: () => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/**
|
||||
* One folder row under a project: the base directory (folder #0) plus every
|
||||
* extra folder of that workspace. Sits at the session indent level so the
|
||||
* 42/58/74 ladder is preserved, and its own session rows indent one step
|
||||
* deeper (see `.wgSessionNested`).
|
||||
*
|
||||
* Deliberately NOT a drag source or drop target: folders are a fixed,
|
||||
* host-ordered list; reordering them would need a write path this feature does
|
||||
* not have.
|
||||
*/
|
||||
export declare function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating }: {
|
||||
node: FolderNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
onNewSession: () => void;
|
||||
onSetRoot: () => void;
|
||||
onRemove: () => void;
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: () => void;
|
||||
/** A session is being created here: the hover + stays disabled. */
|
||||
creating?: boolean;
|
||||
}): import("react").JSX.Element;
|
||||
/**
|
||||
* Children container for one folder's rows.
|
||||
*
|
||||
|
|
@ -119,7 +143,7 @@ export declare function RowGroup({ expanded, className, animate, children }: {
|
|||
children: ReactNode;
|
||||
}): JSX.Element | null;
|
||||
/** One session leaf row. */
|
||||
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested }: {
|
||||
node: SessionNode;
|
||||
currentId: string | undefined;
|
||||
now: number;
|
||||
|
|
@ -128,5 +152,7 @@ export declare function SessionRow({ node, currentId, now, t, onOpen, onRename,
|
|||
onRename: (id: SessionNode['id'], currentTitle: string) => void;
|
||||
onFork: (id: SessionNode['id']) => void;
|
||||
onArchive: (id: SessionNode['id']) => void;
|
||||
/** Rendered under a folder row: one indent step deeper than a plain session. */
|
||||
nested?: boolean;
|
||||
}): import("react").JSX.Element;
|
||||
export type { T };
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh
|
|||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import { type FoldersDocument } from '../core/folders.ts';
|
||||
import { type CategoryAppearance, type GroupsConfig, type ManualGroups } from '../core/types.ts';
|
||||
/** Pending interaction kinds with dedicated Workspace-row presentation. */
|
||||
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question';
|
||||
|
|
@ -42,6 +43,20 @@ export interface SessionNode {
|
|||
/** Content-match snippet from the Host search (search mode only). */
|
||||
snippet?: string;
|
||||
}
|
||||
/** One folder row inside a workspace folder (base or extra). */
|
||||
export interface FolderNode {
|
||||
/** Absolute folder path. */
|
||||
path: string;
|
||||
/** Display label: last path segment, or the whole path for drive roots. */
|
||||
label: string;
|
||||
/** The workspace's default target for new sessions (★). */
|
||||
isRoot: boolean;
|
||||
expanded: boolean;
|
||||
/** The workspace's own canonical directory (folder #0); cannot be removed. */
|
||||
isBase: boolean;
|
||||
/** Visible sessions whose recorded cwd lives inside this folder. */
|
||||
sessions: readonly SessionNode[];
|
||||
}
|
||||
/** One workspace folder row inside a category folder. */
|
||||
export interface WorkspaceGroupNode {
|
||||
workspaceId: WorkspaceId;
|
||||
|
|
@ -51,13 +66,19 @@ export interface WorkspaceGroupNode {
|
|||
label: string;
|
||||
/** Workspace creation time (epoch ms). */
|
||||
createdAt: number;
|
||||
/** Total visible sessions in the folder. */
|
||||
/** Total visible sessions in the folder (every folder included). */
|
||||
sessionCount: number;
|
||||
expanded: boolean;
|
||||
/** The folder contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean;
|
||||
/** Visible session rows (empty while the folder is folded). */
|
||||
/** Base-owned visible session rows (empty while the folder is folded). */
|
||||
sessions: readonly SessionNode[];
|
||||
/**
|
||||
* Folder rows, present only when the workspace carries at least one extra
|
||||
* folder: root first, then stored order, base included. Absent means "this
|
||||
* workspace has exactly one directory", the plain pre-folders node shape.
|
||||
*/
|
||||
folders?: readonly FolderNode[];
|
||||
}
|
||||
/** One category folder at the top of the tree. */
|
||||
export interface CategoryNode {
|
||||
|
|
@ -77,11 +98,25 @@ export interface CategoryNode {
|
|||
export interface GroupsTreeView {
|
||||
expandedCategories: readonly string[];
|
||||
expandedWorkspaces: readonly string[];
|
||||
/**
|
||||
* Collapsed folder rows, keyed by `folderKey(workspaceId, path)`. Folders are
|
||||
* expanded by default: adding a folder must never hide the sessions that used
|
||||
* to show flat under the project.
|
||||
*/
|
||||
collapsedFolders?: readonly string[];
|
||||
}
|
||||
/** Key of the uncategorized bucket (matches the config fallback label). */
|
||||
export declare const UNCATEGORIZED_KEY = "\u672A\u5206\u7C7B";
|
||||
/** Directory display label: basename of the path (both separators accepted). */
|
||||
export declare function workspaceLabel(cwd: string | undefined): string;
|
||||
/**
|
||||
* Display label of one folder: the last path segment. A drive root (`C:\`) or
|
||||
* the POSIX root has no segment, so the whole path is the honest label.
|
||||
* @param path - absolute folder path.
|
||||
*/
|
||||
export declare function folderLabel(path: string): string;
|
||||
/** Stable identity of one folder row (same path may live under two workspaces). */
|
||||
export declare function folderKey(workspaceId: WorkspaceId, path: string): string;
|
||||
/**
|
||||
* Derive the three-level tree.
|
||||
* @param list - sessions list snapshot (`current` feeds containsCurrent).
|
||||
|
|
@ -93,11 +128,14 @@ export declare function workspaceLabel(cwd: string | undefined): string;
|
|||
* manual override wins over rule classification; removing it reverts to rules.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root. A workspace with extras
|
||||
* gains folder rows and its extra-folder sessions move under them; a workspace
|
||||
* without extras keeps exactly the pre-folders node shape.
|
||||
* @returns category sections in render order (rule categories first, then
|
||||
* manual-only ones, uncategorized last). Manual groups render even while
|
||||
* empty; empty rule buckets stay hidden.
|
||||
*/
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses): CategoryNode[];
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): CategoryNode[];
|
||||
/**
|
||||
* Top-level (ungrouped) workspace rows: workspaces resolving to no category
|
||||
* (no manual override and no matching rule, or a forced `null` override).
|
||||
|
|
@ -105,7 +143,7 @@ export declare function deriveGroups(list: SessionListState, workspaces: readonl
|
|||
* folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`),
|
||||
* falling back to host registration order.
|
||||
*/
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses): WorkspaceGroupNode[];
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode[];
|
||||
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
|
||||
export interface SearchMatchSet {
|
||||
/** Session ids that matched (local metadata hits + Host content hits). */
|
||||
|
|
@ -147,8 +185,10 @@ export interface SearchTree {
|
|||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root, so a hit inside an extra
|
||||
* folder surfaces under that folder instead of flat under the project.
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>, statuses?: SessionStatuses): SearchTree;
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>, statuses?: SessionStatuses, folders?: FoldersDocument): SearchTree;
|
||||
export {};
|
||||
|
|
|
|||
|
|
@ -0,0 +1,91 @@
|
|||
/**
|
||||
* Pure folder-list logic for per-workspace multi-root folders.
|
||||
*
|
||||
* DSH core gives a workspace exactly ONE canonical directory
|
||||
* (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA
|
||||
* folders on top of it, plus one designated root folder per workspace:
|
||||
*
|
||||
* - the canonical directory is always folder #0 (the "base"); it cannot be
|
||||
* removed and may be the root;
|
||||
* - `root` is stored only when it names an EXTRA folder — "base is the root"
|
||||
* is expressed by omitting the key, so the base path is never duplicated
|
||||
* into the sidecar;
|
||||
* - a session whose recorded `cwd` lives inside an extra folder belongs to
|
||||
* that folder, not to the project row.
|
||||
*
|
||||
* Everything here is pure and platform-agnostic: it imports no React, no DOM
|
||||
* and no cordis so plain Node (the verifier, the host route) can load it.
|
||||
*/
|
||||
/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */
|
||||
export interface WorkspaceFolderEntry {
|
||||
readonly folders: readonly string[];
|
||||
readonly root?: string;
|
||||
}
|
||||
/** The whole `workspace-groups.folders.json` document. */
|
||||
export interface FoldersDocument {
|
||||
readonly version: 1;
|
||||
readonly workspaces: Readonly<Record<string, WorkspaceFolderEntry>>;
|
||||
}
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
export declare const EMPTY_FOLDERS_DOCUMENT: FoldersDocument;
|
||||
/**
|
||||
* Path equality: case-insensitive for Windows-style paths, tolerant of
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
export declare function samePath(a: string, b: string): boolean;
|
||||
/**
|
||||
* Look up the folder entry saved for one workspace.
|
||||
* @param doc - folders document.
|
||||
* @param workspaceId - host workspace id.
|
||||
* @returns the entry, or undefined when the workspace has none.
|
||||
*/
|
||||
export declare function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined;
|
||||
/**
|
||||
* The workspace's effective folder list, base first. The base cannot be
|
||||
* duplicated and blank extra entries are dropped.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
*/
|
||||
export declare function effectiveFolders(workspacePath: string, entry: WorkspaceFolderEntry | undefined): readonly string[];
|
||||
/**
|
||||
* The folder new sessions start in by default.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the stored root when it names an effective extra folder, else the
|
||||
* workspace's own directory.
|
||||
*/
|
||||
export declare function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string;
|
||||
/**
|
||||
* Owning folder of a session cwd: the most specific (longest) effective folder
|
||||
* that equals the cwd or is a proper path ancestor of it.
|
||||
* @param cwd - recorded session cwd; undefined means "the workspace itself".
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the owning folder, or the workspace path when nothing matches.
|
||||
*/
|
||||
export declare function folderOfCwd(cwd: string | undefined, workspacePath: string, entry: WorkspaceFolderEntry | undefined): string;
|
||||
/**
|
||||
* Append an extra folder. Idempotent under `samePath`, and the stored root (if
|
||||
* any) survives untouched.
|
||||
* @param entry - current entry, or undefined for a workspace with no extras.
|
||||
* @param path - folder path to append.
|
||||
*/
|
||||
export declare function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
/**
|
||||
* Drop an extra folder. A root that pointed at it is cleared, so the workspace
|
||||
* falls back to its own directory instead of referencing a folder it no longer
|
||||
* has.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder path to drop.
|
||||
*/
|
||||
export declare function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
/**
|
||||
* Designate the root folder. Only an extra folder can be stored: naming the
|
||||
* base directory means "no explicit root", which is represented by clearing
|
||||
* the key.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder to make the root.
|
||||
*/
|
||||
export declare function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
import { type FoldersDocument } from './core/folders.ts';
|
||||
/** File name of the folder sidecar (also the stable error-text prefix). */
|
||||
export declare const FOLDERS_FILE_NAME = "workspace-groups.folders.json";
|
||||
/** Hard limits enforced at the write boundary. */
|
||||
export declare const FOLDERS_PER_WORKSPACE_LIMIT = 32;
|
||||
export declare const WORKSPACE_ID_LIMIT = 200;
|
||||
export declare const FOLDER_PATH_LIMIT = 1024;
|
||||
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
|
||||
export declare function defaultFoldersPath(): string;
|
||||
/**
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
export declare function isAbsoluteFolderPath(path: string): boolean;
|
||||
/**
|
||||
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
||||
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
export declare function parseFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* Strict writer-side validation. Every rule is enforced and the first problem
|
||||
* throws, so the PUT route rejects instead of persisting a half-valid file.
|
||||
* @param raw - parsed JSON value from the request body.
|
||||
* @returns the normalized document to save.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
export declare function validateFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
export declare function readFoldersDocument(path: string): Promise<FoldersDocument>;
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
/**
|
||||
* The workspace-groups browsing region filling the sidebar shell's
|
||||
* `sidebar.workspaces` hole: section header (title + right-aligned search +
|
||||
* new-group + add workspace), the three-level tree (category → workspace →
|
||||
* new-group + add workspace), the three-level tree (category — workspace —
|
||||
* session), group management dialogs, and the workspace/session dialogs. Wide
|
||||
* state renders the full browser; rail state renders the two region icons
|
||||
* (search / add workspace) as 36px controls on the shell's shared rail entry
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
IconFolderOpenOutlineRegular,
|
||||
IconProjectAddOutlineRegular,
|
||||
IconSearchOutlineRegular,
|
||||
IconTrashOutlineRegular,
|
||||
IconWarningOutlineRegular,
|
||||
Modal,
|
||||
Toast,
|
||||
|
|
@ -51,9 +52,11 @@ import {
|
|||
type ManualGroups,
|
||||
} from '../core/types.ts'
|
||||
import type { GroupsBrowserProps } from './contract.ts'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, currentSessionId, folderKey, folderLabel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||
import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, FolderRow, hasPluginDragType, RowGroup, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import type { WorkspaceGroupsKey } from './locales.ts'
|
||||
import { EMPTY_FOLDERS_DOCUMENT, addFolder, effectiveFolders, entryFor, removeFolder, rootOf, samePath, setRoot, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
|
||||
import { loadFolders, saveFolders } from './folders-persist.ts'
|
||||
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
|
||||
import { QuickPanel } from './QuickPanel.tsx'
|
||||
import { SessionTabs } from './SessionTabs.tsx'
|
||||
|
|
@ -101,7 +104,7 @@ function categoryRowCount(category: CategoryNode): number {
|
|||
return category.workspaces.reduce((total, workspace) => total + 1 + (workspace.expanded ? workspace.sessions.length : 0), 0)
|
||||
}
|
||||
|
||||
/** Palette id → i18n key for the colour picker (keeps literal key types intact). */
|
||||
/** Palette id — i18n key for the colour picker (keeps literal key types intact). */
|
||||
const COLOR_LABEL_KEYS: Record<GroupColor, WorkspaceGroupsKey> = {
|
||||
red: 'color.red',
|
||||
orange: 'color.orange',
|
||||
|
|
@ -205,6 +208,7 @@ export function GroupsBrowser({
|
|||
useStore,
|
||||
actions,
|
||||
startSession,
|
||||
createSessionIn,
|
||||
open,
|
||||
renameSession,
|
||||
forkSession,
|
||||
|
|
@ -265,6 +269,30 @@ export function GroupsBrowser({
|
|||
const [manualError, setManualError] = useState<string | null>(null)
|
||||
const [manualSaving, setManualSaving] = useState(false)
|
||||
|
||||
// ---- Per-workspace folders (multi-root) -------------------------------------
|
||||
//
|
||||
// A second host sidecar (`/workspace-groups/folders`) lists each workspace's
|
||||
// extra folders plus the optional root folder. It is read once per mount and
|
||||
// written back whole, like the manual overlay above; a failed write is a
|
||||
// toast rather than a banner because every edit here is a one-off row action.
|
||||
const [foldersDoc, setFoldersDoc] = useState<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
|
||||
// Folder collapse is component state, not store state: it is a transient view
|
||||
// of the row list, like the quick panel, so it is deliberately NOT persisted
|
||||
// with the category/workspace expansion keys. Folders start expanded, so
|
||||
// attaching a folder never hides sessions the user could already see.
|
||||
const [collapsedFolderKeys, setCollapsedFolderKeys] = useState<readonly string[]>([])
|
||||
const [foldersTarget, setFoldersTarget] = useState<WorkspaceId | null>(null)
|
||||
const [foldersBusy, setFoldersBusy] = useState(false)
|
||||
const [creatingSessionIn, setCreatingSessionIn] = useState<string | null>(null)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void loadFolders().then((document) => {
|
||||
if (cancelled) return
|
||||
setFoldersDoc(document)
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
|
||||
const workspaces = useWorkspaces(state => state.items)
|
||||
const workspacePhase = useWorkspaces(state => state.phase)
|
||||
const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)
|
||||
|
|
@ -393,16 +421,18 @@ export function GroupsBrowser({
|
|||
() => deriveGroups(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}, manual, statuses),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],
|
||||
collapsedFolders: collapsedFolderKeys,
|
||||
}, manual, statuses, foldersDoc),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc],
|
||||
)
|
||||
// Top-level (ungrouped) workspace rows, rendered after the group folders.
|
||||
const topLevel = useMemo(
|
||||
() => deriveTopLevel(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}, manual, statuses),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces],
|
||||
collapsedFolders: collapsedFolderKeys,
|
||||
}, manual, statuses, foldersDoc),
|
||||
[list, workspaces, archivedSessionIds, config, manual, statuses, expandedCategories, expandedWorkspaces, collapsedFolderKeys, foldersDoc],
|
||||
)
|
||||
// Quick panel (Ctrl+R): category label per grouped workspace id (the tree
|
||||
// derivation already resolved grouping; top-level workspaces stay absent).
|
||||
|
|
@ -548,6 +578,108 @@ export function GroupsBrowser({
|
|||
})
|
||||
}
|
||||
|
||||
// ---- Folder overlay editing -------------------------------------------------
|
||||
|
||||
const notifyFolder = (text: string): void => {
|
||||
setFolderError({ id: Date.now(), text })
|
||||
}
|
||||
|
||||
const persistFolders = (next: FoldersDocument): void => {
|
||||
setFoldersDoc(next)
|
||||
saveFolders(next).catch((reason: unknown) => {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.saveError')}: ${detail}`)
|
||||
})
|
||||
}
|
||||
|
||||
/** Write one workspace's entry; zero extra folders removes the key entirely. */
|
||||
const writeFolderEntry = (workspaceId: WorkspaceId, entry: WorkspaceFolderEntry): void => {
|
||||
const next: Record<string, WorkspaceFolderEntry> = { ...foldersDoc.workspaces }
|
||||
const key = workspaceId as string
|
||||
if (entry.folders.length === 0) delete next[key]
|
||||
else next[key] = entry
|
||||
persistFolders({ version: 1, workspaces: next })
|
||||
}
|
||||
|
||||
const toggleFolder = (workspaceId: WorkspaceId, path: string): void => {
|
||||
const key = folderKey(workspaceId, path)
|
||||
setCollapsedFolderKeys(keys => (keys.includes(key) ? keys.filter(k => k !== key) : [...keys, key]))
|
||||
}
|
||||
|
||||
const addFolderTo = async (workspaceId: WorkspaceId): Promise<void> => {
|
||||
if (foldersBusy) return
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
if (workspace === undefined) return
|
||||
setFoldersBusy(true)
|
||||
try {
|
||||
const path = await pickDirectory()
|
||||
if (path === null) return // cancelled
|
||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
|
||||
notifyFolder(t('folder.duplicate'))
|
||||
return
|
||||
}
|
||||
writeFolderEntry(workspaceId, addFolder(entry, path))
|
||||
} catch (reason) {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.addError')}: ${detail}`)
|
||||
} finally {
|
||||
setFoldersBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
|
||||
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))
|
||||
}
|
||||
|
||||
const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => {
|
||||
writeFolderEntry(workspaceId, removeFolder(entryFor(foldersDoc, workspaceId as string), path))
|
||||
}
|
||||
|
||||
/**
|
||||
* "New session here": an extra folder's own directory becomes the Session cwd.
|
||||
* The base folder keeps the platform's own gesture instead, because that one
|
||||
* reuses the blank session it already opened; creating a fresh Session on
|
||||
* every click would pile up empty sessions. One creation in flight at a time;
|
||||
* a rejection surfaces the failure and creates nothing else.
|
||||
*/
|
||||
const startSessionInFolder = (workspaceId: WorkspaceId, path: string, isBase: boolean): void => {
|
||||
if (isBase) {
|
||||
startSession(workspaceId)
|
||||
return
|
||||
}
|
||||
if (creatingSessionIn !== null) return
|
||||
setCreatingSessionIn(folderKey(workspaceId, path))
|
||||
createSessionIn(workspaceId, path).catch((reason: unknown) => {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.sessionError')}: ${detail}`)
|
||||
}).finally(() => {
|
||||
setCreatingSessionIn(null)
|
||||
})
|
||||
}
|
||||
|
||||
/** A project row's plus button — starts in that workspace's root folder. */
|
||||
const startSessionAtRoot = (workspaceId?: WorkspaceId): void => {
|
||||
const workspace = workspaceId === undefined ? undefined : workspaces.find(w => w.workspaceId === workspaceId)
|
||||
if (workspace === undefined) {
|
||||
startSession(workspaceId)
|
||||
return
|
||||
}
|
||||
const root = rootOf(workspace.path, entryFor(foldersDoc, workspaceId as string))
|
||||
startSessionInFolder(workspaceId as WorkspaceId, root, samePath(root, workspace.path))
|
||||
}
|
||||
|
||||
// Absent when the host offers no folder application: folder rows then drop
|
||||
// their "open folder" entry instead of failing at the click.
|
||||
const openFolderPath = folderApp === undefined
|
||||
? undefined
|
||||
: (path: string): void => {
|
||||
openPathInApp(folderApp, path).catch((reason: unknown) => {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('workspace.openInFolderError')}: ${detail}`)
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Runtime group management ----------------------------------------------
|
||||
|
||||
const [groupDialog, setGroupDialog] = useState<GroupDialogState>(null)
|
||||
|
|
@ -634,7 +766,7 @@ export function GroupsBrowser({
|
|||
const name = groupDeleteTarget
|
||||
const originalRule = originalRuleNameForDisplay(config.categories, manual, name)
|
||||
|
||||
// Every project currently in the group goes to 未分类 (forced, not rule-
|
||||
// Every project currently in the group goes to the uncategorized bucket (forced, not rule-
|
||||
// reclassified), regardless of how it landed there.
|
||||
const assignments = { ...manual.assignments }
|
||||
for (const workspace of workspaces) {
|
||||
|
|
@ -681,7 +813,7 @@ export function GroupsBrowser({
|
|||
const [dragIndicator, setDragIndicator] = useState<DragIndicator>(null)
|
||||
|
||||
// Expansion state taken at dragstart; dragend restores it so the folding
|
||||
// caused by a drag is always undone afterwards ("结束后恢复").
|
||||
// caused by a drag is always undone afterwards.
|
||||
const expansionSnapshot = useRef<{ categories: Record<string, boolean>; workspaces: Record<string, boolean> } | null>(null)
|
||||
// Live expansion state for the dragend restore (the document-level listener
|
||||
// is registered once, so it must read current values through a ref).
|
||||
|
|
@ -760,7 +892,7 @@ export function GroupsBrowser({
|
|||
}
|
||||
}
|
||||
|
||||
/** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (未分类 target = append). */
|
||||
/** Reorder groups: move `draggedKey` before `beforeKey` or after `afterKey` (no target = append). */
|
||||
const moveCategory = async (draggedKey: string, beforeKey?: string, afterKey?: string): Promise<void> => {
|
||||
if (manualSaving || draggedKey === beforeKey || draggedKey === afterKey) return
|
||||
setManualSaving(true)
|
||||
|
|
@ -929,9 +1061,9 @@ export function GroupsBrowser({
|
|||
}
|
||||
|
||||
/**
|
||||
* Drag over the TOP-LEVEL AREA's blank space (not on a row — rows stop
|
||||
* propagation). An insertion line shows the landing spot: empty top level →
|
||||
* a standalone line under the last group; non-empty → a line below the last
|
||||
* Drag over the TOP-LEVEL AREA's blank space (not on a row ???rows stop
|
||||
* propagation). An insertion line shows the landing spot: empty top level —
|
||||
* a standalone line under the last group; non-empty — a line below the last
|
||||
* top-level row (end of the list).
|
||||
*/
|
||||
const onDragOverTopLevelArea = (event: DragEvent): void => {
|
||||
|
|
@ -1111,6 +1243,7 @@ export function GroupsBrowser({
|
|||
now={now}
|
||||
open={open}
|
||||
manual={manual}
|
||||
folders={foldersDoc}
|
||||
t={t}
|
||||
/>
|
||||
) : (
|
||||
|
|
@ -1139,8 +1272,15 @@ export function GroupsBrowser({
|
|||
onDragStartWorkspace={onDragStartWorkspace}
|
||||
onToggleCategory={() => { actions.setCategoryExpanded(category.key, !category.expanded) }}
|
||||
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
|
||||
onNewSession={startSession}
|
||||
onNewSession={startSessionAtRoot}
|
||||
onOpen={open}
|
||||
onToggleFolder={toggleFolder}
|
||||
onFolderNewSession={startSessionInFolder}
|
||||
onFolderSetRoot={setFolderRoot}
|
||||
onFolderRemove={removeFolderFrom}
|
||||
onOpenFolderPath={openFolderPath}
|
||||
onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}
|
||||
creatingFolderKey={creatingSessionIn}
|
||||
onRenameRequest={(workspaceId, title) => {
|
||||
setRenameTarget({ workspaceId, currentTitle: title })
|
||||
setRenameDraft(title)
|
||||
|
|
@ -1172,7 +1312,7 @@ export function GroupsBrowser({
|
|||
onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}
|
||||
onOpenInFolder={openInFolder}
|
||||
canMoveOut={(workspaceId) => {
|
||||
// The menu "移出分组" is offered for any project that
|
||||
// The menu "Move out of group" is offered for any project that
|
||||
// currently sits inside a group (rule-classified or manual) —
|
||||
// not just overridden ones. Top-level projects
|
||||
// (resolveCategory === undefined) don't need it.
|
||||
|
|
@ -1201,8 +1341,15 @@ export function GroupsBrowser({
|
|||
onDropRow={onDropRow}
|
||||
onDragStartWorkspace={onDragStartWorkspace}
|
||||
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
|
||||
onNewSession={startSession}
|
||||
onNewSession={startSessionAtRoot}
|
||||
onOpen={open}
|
||||
onToggleFolder={toggleFolder}
|
||||
onFolderNewSession={startSessionInFolder}
|
||||
onFolderSetRoot={setFolderRoot}
|
||||
onFolderRemove={removeFolderFrom}
|
||||
onOpenFolderPath={openFolderPath}
|
||||
onManageFolders={(workspaceId) => { setFoldersTarget(workspaceId) }}
|
||||
creatingFolderKey={creatingSessionIn}
|
||||
onRenameRequest={(workspaceId, title) => {
|
||||
setRenameTarget({ workspaceId, currentTitle: title })
|
||||
setRenameDraft(title)
|
||||
|
|
@ -1371,6 +1518,27 @@ export function GroupsBrowser({
|
|||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Per-workspace folders dialog: base + extra folders, root radio,
|
||||
open/remove per row. Mounted only while a project row asked for it. */}
|
||||
{foldersTarget !== null && (() => {
|
||||
const workspace = workspaces.find(w => w.workspaceId === foldersTarget)
|
||||
if (workspace === undefined) return null
|
||||
return (
|
||||
<FoldersDialog
|
||||
workspace={workspace}
|
||||
entry={entryFor(foldersDoc, foldersTarget as string)}
|
||||
t={t}
|
||||
busy={foldersBusy}
|
||||
canOpen={openFolderPath !== undefined}
|
||||
onClose={() => { setFoldersTarget(null) }}
|
||||
onAdd={() => { void addFolderTo(foldersTarget) }}
|
||||
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
|
||||
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
|
||||
onOpenFolder={(path) => { openFolderPath?.(path) }}
|
||||
/>
|
||||
)
|
||||
})()}
|
||||
|
||||
{/* Workspace rename dialog */}
|
||||
<Modal
|
||||
open={renameTarget !== null}
|
||||
|
|
@ -1494,8 +1662,104 @@ function categoriesForCurrent(
|
|||
return resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
}
|
||||
|
||||
/**
|
||||
* The expanded session rows of one project. Workspaces with extra folders get
|
||||
* one folder row per folder (root first) and hang their sessions off that
|
||||
* folder; a workspace without extra folders renders today's flat list, so the
|
||||
* common case is unchanged row-for-row.
|
||||
*/
|
||||
function WorkspaceSubtree({ workspace, current, now, t, animate, onOpen, onSessionRename, onSessionArchive, onFork, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, creatingFolderKey }: {
|
||||
workspace: WorkspaceGroupNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
t: GroupsBrowserProps['t']
|
||||
animate: boolean
|
||||
onOpen: (sessionId: SessionId) => void
|
||||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
onSessionArchive: (sessionId: SessionId) => void
|
||||
onFork: (sessionId: SessionId) => void
|
||||
onToggleFolder: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void
|
||||
onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderRemove: (workspaceId: WorkspaceId, path: string) => void
|
||||
onOpenFolderPath?: ((path: string) => void) | undefined
|
||||
creatingFolderKey: string | null
|
||||
}) {
|
||||
const folders = workspace.folders
|
||||
if (folders === undefined) {
|
||||
return (
|
||||
<RowGroup
|
||||
expanded={workspace.expanded}
|
||||
className="wgTreeChildren"
|
||||
animate={animate && workspace.sessions.length <= ANIMATION_ROW_CAP}
|
||||
>
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</RowGroup>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<RowGroup
|
||||
expanded={workspace.expanded}
|
||||
className="wgTreeChildren"
|
||||
animate={animate && folders.length + workspace.sessions.length <= ANIMATION_ROW_CAP}
|
||||
>
|
||||
{folders.map((folder) => {
|
||||
const key = folderKey(workspace.workspaceId, folder.path)
|
||||
return (
|
||||
<div key={key} role="group">
|
||||
<FolderRow
|
||||
node={folder}
|
||||
t={t}
|
||||
creating={creatingFolderKey === key}
|
||||
onToggle={() => { onToggleFolder(workspace.workspaceId, folder.path) }}
|
||||
onNewSession={() => { onFolderNewSession(workspace.workspaceId, folder.path, folder.isBase) }}
|
||||
onSetRoot={() => { onFolderSetRoot(workspace.workspaceId, folder.path) }}
|
||||
onRemove={() => { onFolderRemove(workspace.workspaceId, folder.path) }}
|
||||
{...(onOpenFolderPath !== undefined
|
||||
? { onOpenInFolder: () => { onOpenFolderPath(folder.path) } }
|
||||
: {})}
|
||||
/>
|
||||
<RowGroup
|
||||
expanded={folder.expanded}
|
||||
className="wgTreeChildren"
|
||||
animate={animate && folder.sessions.length <= ANIMATION_ROW_CAP}
|
||||
>
|
||||
{folder.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
nested
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</RowGroup>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</RowGroup>
|
||||
)
|
||||
}
|
||||
|
||||
/** One category section: header row + expanded workspace folders. */
|
||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder }: {
|
||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onGroupTogglePin, onGroupAppearance, animate, onMoveOut, canMoveOut, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {
|
||||
category: CategoryNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
|
|
@ -1526,8 +1790,17 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
onGroupAppearance: () => void
|
||||
onMoveOut: (workspaceId: WorkspaceId) => void
|
||||
canMoveOut: (workspaceId: WorkspaceId) => boolean
|
||||
onToggleFolder: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void
|
||||
onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderRemove: (workspaceId: WorkspaceId, path: string) => void
|
||||
onManageFolders: (workspaceId: WorkspaceId) => void
|
||||
/** Creation in flight, keyed by `folderKey`; disables the row's controls */
|
||||
creatingFolderKey: string | null
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenFolderPath?: ((path: string) => void) | undefined
|
||||
}) {
|
||||
const categoryLine = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'category' && dragIndicator.row.key === category.key
|
||||
? (dragIndicator.before ? 'before' : 'after')
|
||||
|
|
@ -1577,26 +1850,25 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
onRowDragLeave={onDragLeaveRow}
|
||||
onRowDrop={onDropRow(category.key, { kind: 'workspace', key: workspace.workspaceId })}
|
||||
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
|
||||
onManageFolders={() => { onManageFolders(workspace.workspaceId) }}
|
||||
/>
|
||||
<WorkspaceSubtree
|
||||
workspace={workspace}
|
||||
current={current}
|
||||
now={now}
|
||||
t={t}
|
||||
animate={animate}
|
||||
onOpen={onOpen}
|
||||
onSessionRename={onSessionRename}
|
||||
onSessionArchive={onSessionArchive}
|
||||
onFork={onFork}
|
||||
onToggleFolder={onToggleFolder}
|
||||
onFolderNewSession={onFolderNewSession}
|
||||
onFolderSetRoot={onFolderSetRoot}
|
||||
onFolderRemove={onFolderRemove}
|
||||
onOpenFolderPath={onOpenFolderPath}
|
||||
creatingFolderKey={creatingFolderKey}
|
||||
/>
|
||||
<RowGroup
|
||||
expanded={workspace.expanded}
|
||||
className="wgTreeChildren"
|
||||
animate={animate && workspace.sessions.length <= ANIMATION_ROW_CAP}
|
||||
>
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</RowGroup>
|
||||
</div>
|
||||
))}
|
||||
</RowGroup>
|
||||
|
|
@ -1613,7 +1885,7 @@ function CategorySection({ category, current, now, t, dragIndicator, onDragOverR
|
|||
* last row);
|
||||
* - an empty top level shows a standalone line under the last group folder.
|
||||
*/
|
||||
function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder }: {
|
||||
function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, topLevelRef, onDragOverRow, onDragOverTopLevelArea, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onOpenInFolder, onToggleFolder, onFolderNewSession, onFolderSetRoot, onFolderRemove, onOpenFolderPath, onManageFolders, creatingFolderKey }: {
|
||||
topLevel: readonly WorkspaceGroupNode[]
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
|
|
@ -1635,8 +1907,16 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
onSessionArchive: (sessionId: SessionId) => void
|
||||
onFork: (sessionId: SessionId) => void
|
||||
onToggleFolder: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderNewSession: (workspaceId: WorkspaceId, path: string, isBase: boolean) => void
|
||||
onFolderSetRoot: (workspaceId: WorkspaceId, path: string) => void
|
||||
onFolderRemove: (workspaceId: WorkspaceId, path: string) => void
|
||||
onManageFolders: (workspaceId: WorkspaceId) => void
|
||||
creatingFolderKey: string | null
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: ((workspaceId: WorkspaceId) => void) | undefined
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenFolderPath?: ((path: string) => void) | undefined
|
||||
}) {
|
||||
const emptyLineActive = dragIndicator?.mode === 'line' && dragIndicator.row.kind === 'topLevel' && dragIndicator.row.key === topLevelRef.key
|
||||
return (
|
||||
|
|
@ -1679,26 +1959,91 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
onRowDragLeave={onDragLeaveRow}
|
||||
onRowDrop={onDropRow(UNCATEGORIZED_KEY, { kind: 'topLevel', key: workspace.workspaceId })}
|
||||
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
|
||||
onManageFolders={() => { onManageFolders(workspace.workspaceId) }}
|
||||
/>
|
||||
<RowGroup
|
||||
expanded={workspace.expanded}
|
||||
className="wgTreeChildren"
|
||||
animate={!dragging && workspace.sessions.length <= ANIMATION_ROW_CAP}
|
||||
>
|
||||
{workspace.sessions.map((session) => (
|
||||
<WorkspaceSubtree
|
||||
workspace={workspace}
|
||||
current={current}
|
||||
now={now}
|
||||
t={t}
|
||||
animate={!dragging}
|
||||
onOpen={onOpen}
|
||||
onSessionRename={onSessionRename}
|
||||
onSessionArchive={onSessionArchive}
|
||||
onFork={onFork}
|
||||
onToggleFolder={onToggleFolder}
|
||||
onFolderNewSession={onFolderNewSession}
|
||||
onFolderSetRoot={onFolderSetRoot}
|
||||
onFolderRemove={onFolderRemove}
|
||||
onOpenFolderPath={onOpenFolderPath}
|
||||
creatingFolderKey={creatingFolderKey}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search hits inside one project. When the project owns extra folders the hits
|
||||
* keep their folder row (all expanded, since search prunes to matches) so a
|
||||
* match never loses the folder it came from.
|
||||
*/
|
||||
function SearchSubtree({ workspace, current, now, open, t }: {
|
||||
workspace: WorkspaceGroupNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
open: (sessionId: SessionId) => void
|
||||
t: GroupsBrowserProps['t']
|
||||
}) {
|
||||
const folders = workspace.folders
|
||||
if (folders === undefined) {
|
||||
return (
|
||||
<div role="group">
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div role="group">
|
||||
{folders.map((folder) => (
|
||||
<div key={folderKey(workspace.workspaceId, folder.path)} role="group">
|
||||
<FolderRow
|
||||
node={folder}
|
||||
t={t}
|
||||
onToggle={() => {}}
|
||||
onNewSession={() => {}}
|
||||
onSetRoot={() => {}}
|
||||
onRemove={() => {}}
|
||||
/>
|
||||
<div role="group">
|
||||
{folder.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
nested
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</RowGroup>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -1707,10 +2052,10 @@ function TopLevelSection({ topLevel, current, now, t, dragging, dragIndicator, t
|
|||
|
||||
/**
|
||||
* Search body rendered as a three-level tree pruned to matched branches:
|
||||
* 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as
|
||||
* Only branches that contain a hit are rendered, which keeps a long list short. Reuses the same row components as
|
||||
* the idle tree, so search keeps the same folder hierarchy the user is used to.
|
||||
*/
|
||||
function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, t }: {
|
||||
function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, query, remote, resultLimit, current, now, open, manual, folders, t }: {
|
||||
list: SessionListState
|
||||
workspaces: readonly WorkspaceView[]
|
||||
config: GroupsConfig
|
||||
|
|
@ -1723,6 +2068,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
|
|||
now: number
|
||||
open: (sessionId: SessionId) => void
|
||||
manual: ManualGroups
|
||||
folders: FoldersDocument
|
||||
t: GroupsBrowserProps['t']
|
||||
}) {
|
||||
const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }
|
||||
|
|
@ -1731,8 +2077,8 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
|
|||
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
|
||||
)
|
||||
const searchTree = useMemo(
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses),
|
||||
[list, workspaces, config, matches, archivedSessionIds, manual, statuses],
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession, statuses, folders),
|
||||
[list, workspaces, config, matches, archivedSessionIds, manual, statuses, folders],
|
||||
)
|
||||
const groups = searchTree.categories
|
||||
const searchTopLevel = searchTree.topLevel
|
||||
|
|
@ -1754,21 +2100,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
|
|||
onRename={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
<div role="group">
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<SearchSubtree workspace={workspace} current={current} now={now} open={open} t={t} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -1785,21 +2117,7 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
|
|||
onRename={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
<div role="group">
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<SearchSubtree workspace={workspace} current={current} now={now} open={open} t={t} />
|
||||
</div>
|
||||
))}
|
||||
{pending && <div className="wgSearchStatus" role="status">{t('search.pending')}</div>}
|
||||
|
|
@ -1813,3 +2131,84 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, statuses, qu
|
|||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Folder list dialog for one workspace: the base folder first, then every extra
|
||||
* folder in stored order. The radio column chooses the root (the folder new
|
||||
* sessions default to); open/remove act per row, and removing the base folder is
|
||||
* never offered because the workspace's canonical directory cannot be dropped.
|
||||
*/
|
||||
function FoldersDialog({ workspace, entry, t, busy, canOpen, onClose, onAdd, onSetRoot, onRemove, onOpenFolder }: {
|
||||
workspace: WorkspaceView
|
||||
entry: WorkspaceFolderEntry | undefined
|
||||
t: GroupsBrowserProps['t']
|
||||
busy: boolean
|
||||
canOpen: boolean
|
||||
onClose: () => void
|
||||
onAdd: () => void
|
||||
onSetRoot: (path: string) => void
|
||||
onRemove: (path: string) => void
|
||||
onOpenFolder: (path: string) => void
|
||||
}) {
|
||||
const folders = effectiveFolders(workspace.path, entry)
|
||||
const root = rootOf(workspace.path, entry)
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
closeLabel={t('close')}
|
||||
title={t('folder.title')}
|
||||
footer={(
|
||||
<Button variant="primary" onClick={onClose}>{t('folder.done')}</Button>
|
||||
)}
|
||||
>
|
||||
<div className="wgFolderList" role="list" aria-label={t('folder.listAria')}>
|
||||
{folders.map((path, index) => {
|
||||
const isBase = index === 0
|
||||
const isRoot = samePath(path, root)
|
||||
const label = folderLabel(path)
|
||||
return (
|
||||
<div key={path} className="wgFolderListRow" role="listitem">
|
||||
<input
|
||||
type="radio"
|
||||
className="wgFolderRadio"
|
||||
name="wg-folder-root"
|
||||
checked={isRoot}
|
||||
aria-label={`${t('folder.rootBadge')} ${label}`}
|
||||
onChange={() => { onSetRoot(path) }}
|
||||
/>
|
||||
<span className="wgFolderListLabel" title={path}>{label}</span>
|
||||
{isBase && <span className="wgFolderListTag">{t('folder.base')}</span>}
|
||||
{isRoot && <span className="wgFolderListTag">{t('folder.rootBadge')}</span>}
|
||||
<span className="wgFolderListActions">
|
||||
{canOpen && (
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={`${t('workspace.openInFolder')} ${label}`}
|
||||
onClick={() => { onOpenFolder(path) }}
|
||||
>
|
||||
<IconFolderOpenOutlineRegular size={16} />
|
||||
</button>
|
||||
)}
|
||||
{!isBase && (
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={`${t('folder.remove')} ${label}`}
|
||||
onClick={() => { onRemove(path) }}
|
||||
>
|
||||
<IconTrashOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className="wgFolderListFooter">
|
||||
<Button variant="outline" disabled={busy} onClick={onAdd}>{t('folder.add')}</Button>
|
||||
</div>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ export type GroupsBrowserInjected = {
|
|||
};
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/**
|
||||
* Create a real Session in one folder of a Workspace and open it. `cwd` is
|
||||
* omitted for the base folder (the Workspace's own canonical directory).
|
||||
*/
|
||||
createSessionIn: (workspaceId: WorkspaceId, cwd?: string) => Promise<SessionId>;
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void;
|
||||
/** Search current visible conversation messages. */
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
/**
|
||||
* Client side of the per-workspace folder list, talking to
|
||||
* `GET|PUT /workspace-groups/folders` on the host.
|
||||
*
|
||||
* The document is the host's JSON sidecar verbatim (`version` + `workspaces`),
|
||||
* so the client and the host agree on one shape: `folders` holds EXTRA folders
|
||||
* only — the workspace's canonical directory is implicit folder #0 — and
|
||||
* `root` names one of those extras (absent means "the workspace itself").
|
||||
*
|
||||
* Reads are best-effort, like the manual overlay and the tab strip: a failed
|
||||
* read means "no extra folders". A failed write, however, rejects so the caller
|
||||
* can say so — a folder row that silently forgot its edit would be worse than
|
||||
* the toast.
|
||||
*/
|
||||
import {
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from '../core/folders.ts'
|
||||
|
||||
/** Host route holding the folder overlay. */
|
||||
export const FOLDERS_ROUTE = '/workspace-groups/folders'
|
||||
|
||||
/**
|
||||
* Read one workspace entry off the wire, dropping the entry when it is
|
||||
* unusable.
|
||||
* @param value - one value of the stored `workspaces` mapping.
|
||||
* @returns the entry, or null for a malformed one.
|
||||
*/
|
||||
function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
|
||||
const row = value as Record<string, unknown>
|
||||
if (!Array.isArray(row.folders)) return null
|
||||
const folders: string[] = []
|
||||
for (const candidate of row.folders) {
|
||||
if (typeof candidate !== 'string' || candidate.trim() === '') continue
|
||||
folders.push(candidate)
|
||||
}
|
||||
const root = typeof row.root === 'string' && row.root.trim() !== '' ? row.root : undefined
|
||||
return { folders, ...(root === undefined ? {} : { root }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the document; the empty document on any failure.
|
||||
*/
|
||||
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersDocument> {
|
||||
try {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'GET',
|
||||
// Folders are user state; a cached response would show stale rows.
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!response.ok) return EMPTY_FOLDERS_DOCUMENT
|
||||
const body: unknown = await response.json()
|
||||
if (typeof body !== 'object' || body === null) return EMPTY_FOLDERS_DOCUMENT
|
||||
const source = body as Record<string, unknown>
|
||||
if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT
|
||||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
return { version: 1, workspaces: {} }
|
||||
}
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
const entry = parseWireEntry(value)
|
||||
if (entry !== null) workspaces[workspaceId] = entry
|
||||
}
|
||||
return { version: 1, workspaces }
|
||||
} catch {
|
||||
return EMPTY_FOLDERS_DOCUMENT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
*
|
||||
* Unlike the tab strip this does NOT swallow failures: folder edits are explicit
|
||||
* row/dialog actions, so the caller turns a rejection into a toast instead of
|
||||
* leaving the user with a row that silently forgot its folder.
|
||||
* @param document - the client's current document.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export async function saveFolders(
|
||||
document: FoldersDocument,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<void> {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(document),
|
||||
cache: 'no-store',
|
||||
// The write is idempotent, so surviving a navigation with keepalive is
|
||||
// safe and avoids losing the just-added folder.
|
||||
keepalive: true,
|
||||
})
|
||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
||||
}
|
||||
|
|
@ -166,6 +166,17 @@ export function apply(ctx: Context): void {
|
|||
// retained `mainView` selection, supersession and pending-navigation
|
||||
// cancellation (0.1.6 moved them out of `ctx.sessions`).
|
||||
startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },
|
||||
// Folder rows create a real Session rooted in that folder. `cwd` stays out
|
||||
// of the call for the base folder (the Workspace's canonical directory),
|
||||
// where the controller already defaults to `WorkspaceView.path`.
|
||||
createSessionIn: async (workspaceId, cwd) => {
|
||||
const sessionId = await ctx.sessions.create({
|
||||
workspaceId,
|
||||
...(cwd === undefined ? {} : { cwd }),
|
||||
})
|
||||
ctx.uiWorkspace.openSession(sessionId)
|
||||
return sessionId
|
||||
},
|
||||
open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },
|
||||
forkSession: (sessionId) => {
|
||||
ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {
|
||||
|
|
|
|||
|
|
@ -34,6 +34,19 @@ export type WorkspaceGroupsKey =
|
|||
| 'workspace.moveOutOfGroup'
|
||||
| 'workspace.openInFolder'
|
||||
| 'workspace.openInFolderError'
|
||||
| 'folder.title'
|
||||
| 'folder.manage'
|
||||
| 'folder.listAria'
|
||||
| 'folder.base'
|
||||
| 'folder.setRoot'
|
||||
| 'folder.rootBadge'
|
||||
| 'folder.remove'
|
||||
| 'folder.add'
|
||||
| 'folder.done'
|
||||
| 'folder.duplicate'
|
||||
| 'folder.addError'
|
||||
| 'folder.sessionError'
|
||||
| 'folder.saveError'
|
||||
| 'group.create'
|
||||
| 'group.createTitle'
|
||||
| 'group.createPlaceholder'
|
||||
|
|
@ -149,6 +162,19 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'workspace.moveOutOfGroup': '移出分组',
|
||||
'workspace.openInFolder': '在文件夹中打开',
|
||||
'workspace.openInFolderError': '打开文件夹失败',
|
||||
'folder.title': '文件夹',
|
||||
'folder.manage': '文件夹…',
|
||||
'folder.listAria': '工作区文件夹',
|
||||
'folder.base': '基础文件夹',
|
||||
'folder.setRoot': '设为根目录',
|
||||
'folder.rootBadge': '根目录',
|
||||
'folder.remove': '从工作区移除',
|
||||
'folder.add': '添加文件夹',
|
||||
'folder.done': '完成',
|
||||
'folder.duplicate': '该文件夹已在此工作区中',
|
||||
'folder.addError': '添加文件夹失败',
|
||||
'folder.sessionError': '新建会话失败',
|
||||
'folder.saveError': '文件夹保存失败',
|
||||
'group.create': '新建分组',
|
||||
'group.createTitle': '新建分组',
|
||||
'group.createPlaceholder': '分组名称',
|
||||
|
|
@ -263,6 +289,19 @@ export const en: WorkspaceGroupsDict = {
|
|||
'workspace.moveOutOfGroup': 'Move out of group',
|
||||
'workspace.openInFolder': 'Open in folder',
|
||||
'workspace.openInFolderError': 'Could not open the folder',
|
||||
'folder.title': 'Folders',
|
||||
'folder.manage': 'Folders…',
|
||||
'folder.listAria': 'Workspace folders',
|
||||
'folder.base': 'Base folder',
|
||||
'folder.setRoot': 'Set as root',
|
||||
'folder.rootBadge': 'Root',
|
||||
'folder.remove': 'Remove from workspace',
|
||||
'folder.add': 'Add folder',
|
||||
'folder.done': 'Done',
|
||||
'folder.duplicate': 'That folder is already in this workspace',
|
||||
'folder.addError': 'Could not add the folder',
|
||||
'folder.sessionError': 'Could not start a session',
|
||||
'folder.saveError': 'Could not save folders',
|
||||
'group.create': 'New group',
|
||||
'group.createTitle': 'New group',
|
||||
'group.createPlaceholder': 'Group name',
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ import {
|
|||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { WorkspaceGroupsKey } from './locales.ts'
|
||||
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'
|
||||
import type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts'
|
||||
|
||||
type T = TranslateNS<'workspaceGroups'>
|
||||
|
||||
|
|
@ -271,7 +271,7 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, onTogglePin
|
|||
}
|
||||
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, onManageFolders, onOpenInFolder, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
|
|
@ -281,6 +281,8 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean
|
||||
onMoveOut?: () => void
|
||||
/** Open the folder-management dialog (extra folders + root). */
|
||||
onManageFolders?: () => void
|
||||
/**
|
||||
* Open the project directory in the host's file manager. Omitted when the
|
||||
* host resolved no folder application (no capability, or a remote launch),
|
||||
|
|
@ -293,13 +295,16 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
onDragStartExtra?: () => void
|
||||
} & RowDropProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const menuItems = [
|
||||
const menuItems: MenuEntry[] = [
|
||||
...(onOpenInFolder !== undefined
|
||||
? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: <IconFolderOpenOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
...(canMoveOut && onMoveOut !== undefined
|
||||
? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: <IconRightUpOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
...(onManageFolders !== undefined
|
||||
? [{ id: 'folders', label: t('folder.manage'), icon: <IconFolderOpenOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutlineRegular /> },
|
||||
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutlineRegular />, danger: true },
|
||||
]
|
||||
|
|
@ -348,6 +353,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
setMenuOpen(false)
|
||||
if (id === 'openInFolder') onOpenInFolder?.()
|
||||
if (id === 'moveOut') onMoveOut?.()
|
||||
if (id === 'folders') onManageFolders?.()
|
||||
if (id === 'rename') onRename()
|
||||
if (id === 'delete') onDelete()
|
||||
}}
|
||||
|
|
@ -379,6 +385,110 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* One folder row under a project: the base directory (folder #0) plus every
|
||||
* extra folder of that workspace. Sits at the session indent level so the
|
||||
* 42/58/74 ladder is preserved, and its own session rows indent one step
|
||||
* deeper (see `.wgSessionNested`).
|
||||
*
|
||||
* Deliberately NOT a drag source or drop target: folders are a fixed,
|
||||
* host-ordered list; reordering them would need a write path this feature does
|
||||
* not have.
|
||||
*/
|
||||
export function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating = false }: {
|
||||
node: FolderNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
onNewSession: () => void
|
||||
onSetRoot: () => void
|
||||
onRemove: () => void
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: () => void
|
||||
/** A session is being created here: the hover + stays disabled. */
|
||||
creating?: boolean
|
||||
}) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const menuItems: MenuEntry[] = [
|
||||
{ id: 'newSession', label: t('session.new'), icon: <IconPlusOutlineRegular /> },
|
||||
...(onOpenInFolder !== undefined
|
||||
? [{ id: 'openInFolder', label: t('workspace.openInFolder'), icon: <IconFolderOpenOutlineRegular size={16} /> }]
|
||||
: []),
|
||||
...(node.isRoot
|
||||
? []
|
||||
: [{ id: 'setRoot', label: t('folder.setRoot'), icon: <IconPinOutlineRegular /> }]),
|
||||
...(node.isBase
|
||||
? []
|
||||
: [
|
||||
{ type: 'separator' as const, id: 'folder-menu-separator' },
|
||||
{ id: 'remove', label: t('folder.remove'), icon: <IconTrashOutlineRegular />, danger: true },
|
||||
]),
|
||||
]
|
||||
return (
|
||||
<div
|
||||
className={`wgFolderRow${node.isRoot ? ' wgFolderRooted' : ''}${node.isBase ? ' wgFolderBase' : ''}`}
|
||||
role="treeitem"
|
||||
aria-expanded={node.expanded}
|
||||
aria-label={node.label}
|
||||
data-wg-row-folder=""
|
||||
data-wg-folder={node.path}
|
||||
{...(node.isRoot ? { 'data-wg-folder-root': '' } : {})}
|
||||
/* Branch hook only (no group): a folder is a leaf branch point, its
|
||||
sessions hang off it like a project's do. */
|
||||
data-wg-branch-row=""
|
||||
onClick={onToggle}
|
||||
>
|
||||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFillMedium />
|
||||
</span>
|
||||
<span className="wgCategoryIcon" data-wg-row-icon="folder">
|
||||
{node.expanded ? <IconFolderOpenMedium /> : <IconFolderCloseMedium />}
|
||||
</span>
|
||||
<span className="wgFolderLabel" title={node.path}>{node.label}</span>
|
||||
{node.isRoot && (
|
||||
<span className="wgFolderRoot" title={t('folder.rootBadge')} aria-label={t('folder.rootBadge')}>★</span>
|
||||
)}
|
||||
<span className="wgFolderCount">{node.sessions.length}</span>
|
||||
<span className="wgRowActions">
|
||||
<Menu
|
||||
open={menuOpen}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
items={menuItems}
|
||||
onSelect={(id) => {
|
||||
setMenuOpen(false)
|
||||
if (id === 'newSession') onNewSession()
|
||||
if (id === 'openInFolder') onOpenInFolder?.()
|
||||
if (id === 'setRoot') onSetRoot()
|
||||
if (id === 'remove') onRemove()
|
||||
}}
|
||||
portal
|
||||
closeOnPointerLeave
|
||||
anchor={(
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
draggable={false}
|
||||
aria-label={`${t('folder.title')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
draggable={false}
|
||||
disabled={creating}
|
||||
aria-label={`${t('session.new')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); onNewSession() }}
|
||||
>
|
||||
<IconPlusOutlineRegular />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Children container for one folder's rows.
|
||||
*
|
||||
|
|
@ -476,7 +586,7 @@ export function RowGroup({ expanded, className, animate = true, children }: {
|
|||
}
|
||||
|
||||
/** One session leaf row. */
|
||||
export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested = false }: {
|
||||
node: SessionNode
|
||||
currentId: string | undefined
|
||||
now: number
|
||||
|
|
@ -485,6 +595,8 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
|
|||
onRename: (id: SessionNode['id'], currentTitle: string) => void
|
||||
onFork: (id: SessionNode['id']) => void
|
||||
onArchive: (id: SessionNode['id']) => void
|
||||
/** Rendered under a folder row: one indent step deeper than a plain session. */
|
||||
nested?: boolean
|
||||
}) {
|
||||
const selected = node.id === currentId
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
|
|
@ -502,7 +614,7 @@ export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork,
|
|||
]
|
||||
return (
|
||||
<div
|
||||
className={`wgSessionRow${selected ? ' wgSelected' : ''}${node.matched === true ? ' wgMatched' : ''}`}
|
||||
className={`wgSessionRow${nested ? ' wgSessionNested' : ''}${selected ? ' wgSelected' : ''}${node.matched === true ? ' wgMatched' : ''}`}
|
||||
role="treeitem"
|
||||
aria-selected={selected}
|
||||
data-wg-branch-row=""
|
||||
|
|
|
|||
|
|
@ -299,6 +299,66 @@
|
|||
opacity:1;
|
||||
}
|
||||
|
||||
/* Folder rows (multi-root workspaces): one row per folder under a project. The
|
||||
folder label lands on the session indent (74) and the folder's own sessions
|
||||
step one further (90), so the ladder reads 42 → 58 → 74 → 90 on the same
|
||||
16px step the group/project/session rows already use. */
|
||||
.wgFolderRow {
|
||||
cursor:pointer;
|
||||
user-select:none;
|
||||
border-radius:6px;
|
||||
align-items:center;
|
||||
gap:4px;
|
||||
height:28px;
|
||||
padding:0 4px 0 38px;
|
||||
display:flex;
|
||||
position:relative;
|
||||
}
|
||||
|
||||
.wgFolderRow:hover {
|
||||
background:var(--dsw-bg-hover,#7f7f7f1f);
|
||||
}
|
||||
|
||||
.wgFolderRow:hover .wgRowActions,.wgFolderRow:focus-within .wgRowActions {
|
||||
opacity:1;
|
||||
}
|
||||
|
||||
.wgFolderLabel {
|
||||
text-overflow:ellipsis;
|
||||
white-space:nowrap;
|
||||
min-width:0;
|
||||
color:var(--dsw-alias-label-primary,var(--dsw-fg-1,inherit));
|
||||
font-size:12px;
|
||||
font-weight:500;
|
||||
flex:1;
|
||||
overflow:hidden;
|
||||
}
|
||||
|
||||
/* The base folder is the workspace's own directory: slightly stronger weight so
|
||||
the implicit folder #0 stays distinguishable from the extras. */
|
||||
.wgFolderBase .wgFolderLabel {
|
||||
font-weight:600;
|
||||
}
|
||||
|
||||
.wgFolderRoot {
|
||||
color:var(--dsw-accent,#4a90d9);
|
||||
flex:none;
|
||||
font-size:11px;
|
||||
line-height:1;
|
||||
}
|
||||
|
||||
.wgFolderCount {
|
||||
color:var(--dsw-fg-3,#7f7f7fcc);
|
||||
flex:none;
|
||||
font-size:11px;
|
||||
}
|
||||
|
||||
/* Sessions hanging off a folder row: one indent step deeper than a plain
|
||||
session title (74 → 90). */
|
||||
.wgSessionNested {
|
||||
padding-left:70px;
|
||||
}
|
||||
|
||||
.wgTreeWrap {
|
||||
position:relative;
|
||||
}
|
||||
|
|
@ -533,6 +593,58 @@
|
|||
border-color:var(--dsw-accent,#4a90d9);
|
||||
}
|
||||
|
||||
/* Folder list dialog: one row per folder (base first), radio picks the root. */
|
||||
.wgFolderList {
|
||||
display:flex;
|
||||
flex-direction:column;
|
||||
gap:4px;
|
||||
}
|
||||
|
||||
.wgFolderListRow {
|
||||
border-radius:6px;
|
||||
align-items:center;
|
||||
gap:6px;
|
||||
padding:4px 4px 4px 2px;
|
||||
display:flex;
|
||||
}
|
||||
|
||||
.wgFolderListRow:hover {
|
||||
background:var(--dsw-bg-hover,#7f7f7f1f);
|
||||
}
|
||||
|
||||
.wgFolderRadio {
|
||||
flex:none;
|
||||
accent-color:var(--dsw-accent,#4a90d9);
|
||||
margin:0;
|
||||
}
|
||||
|
||||
.wgFolderListLabel {
|
||||
text-overflow:ellipsis;
|
||||
white-space:nowrap;
|
||||
min-width:0;
|
||||
color:var(--dsw-fg-1,inherit);
|
||||
font-size:12px;
|
||||
flex:1;
|
||||
overflow:hidden;
|
||||
}
|
||||
|
||||
.wgFolderListTag {
|
||||
color:var(--dsw-fg-3,#7f7f7fcc);
|
||||
flex:none;
|
||||
font-size:11px;
|
||||
}
|
||||
|
||||
.wgFolderListActions {
|
||||
flex:none;
|
||||
align-items:center;
|
||||
gap:2px;
|
||||
display:inline-flex;
|
||||
}
|
||||
|
||||
.wgFolderListFooter {
|
||||
margin-top:8px;
|
||||
}
|
||||
|
||||
/* Appearance dialog: colour swatches, icon picker grid, pin toggle. */
|
||||
.wgAppearanceSection {
|
||||
display:flex;
|
||||
|
|
|
|||
|
|
@ -17,6 +17,16 @@ import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-clie
|
|||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { indexSubagentDescendants, type SubagentDescendantSummary } from './subagent-lineage.ts'
|
||||
import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCategory } from '../core/matcher.ts'
|
||||
import {
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
effectiveFolders,
|
||||
entryFor,
|
||||
folderOfCwd,
|
||||
rootOf,
|
||||
samePath,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from '../core/folders.ts'
|
||||
import {
|
||||
TOP_LEVEL_ORDER_KEY,
|
||||
UNCATEGORIZED_LABEL,
|
||||
|
|
@ -76,6 +86,21 @@ export interface SessionNode {
|
|||
snippet?: string
|
||||
}
|
||||
|
||||
/** One folder row inside a workspace folder (base or extra). */
|
||||
export interface FolderNode {
|
||||
/** Absolute folder path. */
|
||||
path: string
|
||||
/** Display label: last path segment, or the whole path for drive roots. */
|
||||
label: string
|
||||
/** The workspace's default target for new sessions (★). */
|
||||
isRoot: boolean
|
||||
expanded: boolean
|
||||
/** The workspace's own canonical directory (folder #0); cannot be removed. */
|
||||
isBase: boolean
|
||||
/** Visible sessions whose recorded cwd lives inside this folder. */
|
||||
sessions: readonly SessionNode[]
|
||||
}
|
||||
|
||||
/** One workspace folder row inside a category folder. */
|
||||
export interface WorkspaceGroupNode {
|
||||
workspaceId: WorkspaceId
|
||||
|
|
@ -85,13 +110,19 @@ export interface WorkspaceGroupNode {
|
|||
label: string
|
||||
/** Workspace creation time (epoch ms). */
|
||||
createdAt: number
|
||||
/** Total visible sessions in the folder. */
|
||||
/** Total visible sessions in the folder (every folder included). */
|
||||
sessionCount: number
|
||||
expanded: boolean
|
||||
/** The folder contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean
|
||||
/** Visible session rows (empty while the folder is folded). */
|
||||
/** Base-owned visible session rows (empty while the folder is folded). */
|
||||
sessions: readonly SessionNode[]
|
||||
/**
|
||||
* Folder rows, present only when the workspace carries at least one extra
|
||||
* folder: root first, then stored order, base included. Absent means "this
|
||||
* workspace has exactly one directory", the plain pre-folders node shape.
|
||||
*/
|
||||
folders?: readonly FolderNode[]
|
||||
}
|
||||
|
||||
/** One category folder at the top of the tree. */
|
||||
|
|
@ -113,6 +144,12 @@ export interface CategoryNode {
|
|||
export interface GroupsTreeView {
|
||||
expandedCategories: readonly string[]
|
||||
expandedWorkspaces: readonly string[]
|
||||
/**
|
||||
* Collapsed folder rows, keyed by `folderKey(workspaceId, path)`. Folders are
|
||||
* expanded by default: adding a folder must never hide the sessions that used
|
||||
* to show flat under the project.
|
||||
*/
|
||||
collapsedFolders?: readonly string[]
|
||||
}
|
||||
|
||||
/** Key of the uncategorized bucket (matches the config fallback label). */
|
||||
|
|
@ -180,6 +217,87 @@ function workspaceSessions(
|
|||
return nodes
|
||||
}
|
||||
|
||||
/**
|
||||
* Display label of one folder: the last path segment. A drive root (`C:\`) or
|
||||
* the POSIX root has no segment, so the whole path is the honest label.
|
||||
* @param path - absolute folder path.
|
||||
*/
|
||||
export function folderLabel(path: string): string {
|
||||
const trimmed = path.replace(/[/\\]+$/u, '')
|
||||
if (trimmed === '' || /^[A-Za-z]:$/u.test(trimmed)) return path
|
||||
const base = trimmed.split(/[/\\]/u).pop()
|
||||
return base !== undefined && base !== '' ? base : path
|
||||
}
|
||||
|
||||
/** Stable identity of one folder row (same path may live under two workspaces). */
|
||||
export function folderKey(workspaceId: WorkspaceId, path: string): string {
|
||||
return `${workspaceId}\u0000${path}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a workspace's visible sessions between its base directory and its extra
|
||||
* folders. Sessions keep the order they already had inside their owner, and a
|
||||
* workspace with no extra folder returns its sessions untouched — the pre-
|
||||
* folders node shape (no `folders` key at all).
|
||||
* @param workspaceId - owning workspace.
|
||||
* @param workspacePath - canonical directory (folder #0).
|
||||
* @param sessions - every visible session of the workspace, in host order.
|
||||
* @param list - sessions list snapshot (records each session's cwd).
|
||||
* @param entry - saved extra folders + root for this workspace.
|
||||
* @param collapsedFolders - collapsed folder-row keys. Undefined means "nothing
|
||||
* is collapsed", which is both the default view and what search uses so every
|
||||
* hit is visible without another click.
|
||||
*/
|
||||
function applyFolders(
|
||||
workspaceId: WorkspaceId,
|
||||
workspacePath: string,
|
||||
sessions: readonly SessionNode[],
|
||||
list: SessionListState,
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
collapsedFolders: ReadonlySet<string> | undefined,
|
||||
): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {
|
||||
const extras = effectiveFolders(workspacePath, entry).slice(1)
|
||||
if (extras.length === 0) return { sessions }
|
||||
const root = rootOf(workspacePath, entry)
|
||||
const base: SessionNode[] = []
|
||||
const byFolder = new Map<string, SessionNode[]>()
|
||||
for (const node of sessions) {
|
||||
const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry)
|
||||
if (samePath(owner, workspacePath)) {
|
||||
base.push(node)
|
||||
continue
|
||||
}
|
||||
const bucket = byFolder.get(owner)
|
||||
if (bucket === undefined) byFolder.set(owner, [node])
|
||||
else bucket.push(node)
|
||||
}
|
||||
const folderNode = (path: string, isBase: boolean): FolderNode => {
|
||||
const owned = isBase ? base : (byFolder.get(path) ?? [])
|
||||
return {
|
||||
path,
|
||||
label: folderLabel(path),
|
||||
isRoot: samePath(path, root),
|
||||
expanded: collapsedFolders === undefined || !collapsedFolders.has(folderKey(workspaceId, path)),
|
||||
isBase,
|
||||
// Every owned session is kept on the node so the row's count stays honest
|
||||
// while the folder is collapsed; the RowGroup does the hiding.
|
||||
sessions: owned,
|
||||
}
|
||||
}
|
||||
const folders: FolderNode[] = [
|
||||
folderNode(workspacePath, true),
|
||||
...extras.map(path => folderNode(path, false)),
|
||||
]
|
||||
// Root first, then stored order: moving the root row to the front keeps the
|
||||
// remaining rows (base included) in their stored order.
|
||||
const rootIndex = folders.findIndex(folder => folder.isRoot)
|
||||
if (rootIndex > 0) {
|
||||
const [rootFolder] = folders.splice(rootIndex, 1)
|
||||
if (rootFolder !== undefined) folders.unshift(rootFolder)
|
||||
}
|
||||
return { sessions: base, folders }
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the three-level tree.
|
||||
* @param list - sessions list snapshot (`current` feeds containsCurrent).
|
||||
|
|
@ -191,6 +309,9 @@ function workspaceSessions(
|
|||
* manual override wins over rule classification; removing it reverts to rules.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root. A workspace with extras
|
||||
* gains folder rows and its extra-folder sessions move under them; a workspace
|
||||
* without extras keeps exactly the pre-folders node shape.
|
||||
* @returns category sections in render order (rule categories first, then
|
||||
* manual-only ones, uncategorized last). Manual groups render even while
|
||||
* empty; empty rule buckets stay hidden.
|
||||
|
|
@ -203,10 +324,12 @@ export function deriveGroups(
|
|||
view: GroupsTreeView,
|
||||
manual: ManualGroups,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
|
||||
): CategoryNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedCategories = new Set(view.expandedCategories)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const collapsedFolders = new Set(view.collapsedFolders ?? [])
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const current = currentSessionId(list)
|
||||
|
||||
|
|
@ -245,6 +368,14 @@ export function deriveGroups(
|
|||
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
|
||||
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
|
||||
const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId
|
||||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
collapsedFolders,
|
||||
)
|
||||
if (wsContainsCurrent) containsCurrent = true
|
||||
workspaceNodes.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
|
|
@ -254,7 +385,8 @@ export function deriveGroups(
|
|||
sessionCount: sessions.length,
|
||||
expanded: wsExpanded,
|
||||
containsCurrent: wsContainsCurrent,
|
||||
sessions: wsExpanded ? sessions : [],
|
||||
sessions: wsExpanded ? partitioned.sessions : [],
|
||||
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
|
||||
})
|
||||
}
|
||||
const appearance = categoryAppearance(manual, key)
|
||||
|
|
@ -285,9 +417,11 @@ export function deriveTopLevel(
|
|||
view: GroupsTreeView,
|
||||
manual: ManualGroups,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
|
||||
): WorkspaceGroupNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const collapsedFolders = new Set(view.collapsedFolders ?? [])
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const current = currentSessionId(list)
|
||||
const currentWorkspaceId = current === undefined
|
||||
|
|
@ -305,6 +439,14 @@ export function deriveTopLevel(
|
|||
if (workspace === undefined) continue
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants, statuses, current)
|
||||
const wsExpanded = expandedWorkspaces.has(workspaceId)
|
||||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspaceId),
|
||||
collapsedFolders,
|
||||
)
|
||||
nodes.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
|
|
@ -313,7 +455,8 @@ export function deriveTopLevel(
|
|||
sessionCount: sessions.length,
|
||||
expanded: wsExpanded,
|
||||
containsCurrent: workspace.workspaceId === currentWorkspaceId,
|
||||
sessions: wsExpanded ? sessions : [],
|
||||
sessions: wsExpanded ? partitioned.sessions : [],
|
||||
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
|
||||
})
|
||||
}
|
||||
return nodes
|
||||
|
|
@ -426,6 +569,8 @@ export interface SearchTree {
|
|||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root, so a hit inside an extra
|
||||
* folder surfaces under that folder instead of flat under the project.
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
|
|
@ -438,6 +583,7 @@ export function deriveSearchGroups(
|
|||
manual: ManualGroups,
|
||||
snippetsBySession?: ReadonlyMap<SessionId, string>,
|
||||
statuses: SessionStatuses = new Map(),
|
||||
folders: FoldersDocument = EMPTY_FOLDERS_DOCUMENT,
|
||||
): SearchTree {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
|
@ -464,6 +610,14 @@ export function deriveSearchGroups(
|
|||
}
|
||||
if (nodes.length === 0) continue
|
||||
|
||||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
nodes,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
undefined,
|
||||
)
|
||||
const node: WorkspaceGroupNode = {
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
|
|
@ -472,7 +626,8 @@ export function deriveSearchGroups(
|
|||
sessionCount: nodes.length,
|
||||
expanded: true,
|
||||
containsCurrent: false,
|
||||
sessions: nodes,
|
||||
sessions: partitioned.sessions,
|
||||
...(partitioned.folders === undefined ? {} : { folders: partitioned.folders }),
|
||||
}
|
||||
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
if (key === undefined) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,196 @@
|
|||
/**
|
||||
* Pure folder-list logic for per-workspace multi-root folders.
|
||||
*
|
||||
* DSH core gives a workspace exactly ONE canonical directory
|
||||
* (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA
|
||||
* folders on top of it, plus one designated root folder per workspace:
|
||||
*
|
||||
* - the canonical directory is always folder #0 (the "base"); it cannot be
|
||||
* removed and may be the root;
|
||||
* - `root` is stored only when it names an EXTRA folder — "base is the root"
|
||||
* is expressed by omitting the key, so the base path is never duplicated
|
||||
* into the sidecar;
|
||||
* - a session whose recorded `cwd` lives inside an extra folder belongs to
|
||||
* that folder, not to the project row.
|
||||
*
|
||||
* Everything here is pure and platform-agnostic: it imports no React, no DOM
|
||||
* and no cordis so plain Node (the verifier, the host route) can load it.
|
||||
*/
|
||||
|
||||
/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */
|
||||
export interface WorkspaceFolderEntry {
|
||||
readonly folders: readonly string[]
|
||||
readonly root?: string
|
||||
}
|
||||
|
||||
/** The whole `workspace-groups.folders.json` document. */
|
||||
export interface FoldersDocument {
|
||||
readonly version: 1
|
||||
readonly workspaces: Readonly<Record<string, WorkspaceFolderEntry>>
|
||||
}
|
||||
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
export const EMPTY_FOLDERS_DOCUMENT: FoldersDocument = { version: 1, workspaces: {} }
|
||||
|
||||
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
|
||||
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u
|
||||
|
||||
/** `\\server\share` — a Windows UNC path. */
|
||||
const WINDOWS_UNC = /^\\\\/u
|
||||
|
||||
/** True for both Windows path spellings accepted by the write validator. */
|
||||
function isWindowsStyle(path: string): boolean {
|
||||
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparison form of one path: trimmed, separator-normalized and, for Windows
|
||||
* spellings, lower-cased (drive letters and file names are case-insensitive
|
||||
* there). Trailing separators are dropped except for a drive/UNC/root prefix.
|
||||
* @param path - raw path as stored or picked.
|
||||
* @returns the canonical comparison form.
|
||||
*/
|
||||
function canonicalPath(path: string): string {
|
||||
const trimmed = path.trim()
|
||||
if (isWindowsStyle(trimmed)) {
|
||||
let value = trimmed.replaceAll('/', '\\').toLowerCase()
|
||||
// `C:\` is three characters and already a root; `\\srv\share\` keeps its
|
||||
// trailing separator only while a further segment remains.
|
||||
while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1)
|
||||
return value
|
||||
}
|
||||
let value = trimmed
|
||||
while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Path equality: case-insensitive for Windows-style paths, tolerant of
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
export function samePath(a: string, b: string): boolean {
|
||||
return canonicalPath(a) === canonicalPath(b)
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up the folder entry saved for one workspace.
|
||||
* @param doc - folders document.
|
||||
* @param workspaceId - host workspace id.
|
||||
* @returns the entry, or undefined when the workspace has none.
|
||||
*/
|
||||
export function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined {
|
||||
return doc.workspaces[workspaceId]
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace's effective folder list, base first. The base cannot be
|
||||
* duplicated and blank extra entries are dropped.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
*/
|
||||
export function effectiveFolders(
|
||||
workspacePath: string,
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
): readonly string[] {
|
||||
const extras: string[] = []
|
||||
for (const folder of entry?.folders ?? []) {
|
||||
if (folder.trim() === '') continue
|
||||
if (samePath(folder, workspacePath)) continue
|
||||
if (extras.some(existing => samePath(existing, folder))) continue
|
||||
extras.push(folder)
|
||||
}
|
||||
return [workspacePath, ...extras]
|
||||
}
|
||||
|
||||
/**
|
||||
* The folder new sessions start in by default.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the stored root when it names an effective extra folder, else the
|
||||
* workspace's own directory.
|
||||
*/
|
||||
export function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string {
|
||||
const root = entry?.root
|
||||
if (root === undefined) return workspacePath
|
||||
const folders = effectiveFolders(workspacePath, entry)
|
||||
return folders.find(folder => samePath(folder, root)) ?? workspacePath
|
||||
}
|
||||
|
||||
/**
|
||||
* Owning folder of a session cwd: the most specific (longest) effective folder
|
||||
* that equals the cwd or is a proper path ancestor of it.
|
||||
* @param cwd - recorded session cwd; undefined means "the workspace itself".
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the owning folder, or the workspace path when nothing matches.
|
||||
*/
|
||||
export function folderOfCwd(
|
||||
cwd: string | undefined,
|
||||
workspacePath: string,
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
): string {
|
||||
if (cwd === undefined) return workspacePath
|
||||
const target = canonicalPath(cwd)
|
||||
let best: string | undefined
|
||||
let bestLength = -1
|
||||
for (const folder of effectiveFolders(workspacePath, entry)) {
|
||||
const root = canonicalPath(folder)
|
||||
if (root === '') continue
|
||||
const separator = isWindowsStyle(root) ? '\\' : '/'
|
||||
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
|
||||
if (target !== root && !target.startsWith(prefix)) continue
|
||||
if (root.length > bestLength) {
|
||||
best = folder
|
||||
bestLength = root.length
|
||||
}
|
||||
}
|
||||
return best ?? workspacePath
|
||||
}
|
||||
|
||||
/**
|
||||
* Append an extra folder. Idempotent under `samePath`, and the stored root (if
|
||||
* any) survives untouched.
|
||||
* @param entry - current entry, or undefined for a workspace with no extras.
|
||||
* @param path - folder path to append.
|
||||
*/
|
||||
export function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
|
||||
const folders = entry?.folders ?? []
|
||||
const root = entry?.root
|
||||
const trimmed = path.trim()
|
||||
const keepRoot = root === undefined ? {} : { root }
|
||||
if (trimmed === '' || folders.some(folder => samePath(folder, trimmed))) {
|
||||
return { folders: [...folders], ...keepRoot }
|
||||
}
|
||||
return { folders: [...folders, trimmed], ...keepRoot }
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop an extra folder. A root that pointed at it is cleared, so the workspace
|
||||
* falls back to its own directory instead of referencing a folder it no longer
|
||||
* has.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder path to drop.
|
||||
*/
|
||||
export function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
|
||||
const folders = entry?.folders ?? []
|
||||
const remaining = folders.filter(folder => !samePath(folder, path))
|
||||
const root = entry?.root
|
||||
const keepRoot = root !== undefined && !samePath(root, path)
|
||||
return { folders: remaining, ...(keepRoot ? { root } : {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Designate the root folder. Only an extra folder can be stored: naming the
|
||||
* base directory means "no explicit root", which is represented by clearing
|
||||
* the key.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder to make the root.
|
||||
*/
|
||||
export function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry {
|
||||
const folders = entry?.folders ?? []
|
||||
const match = folders.find(folder => samePath(folder, path))
|
||||
if (match === undefined) return { folders: [...folders] }
|
||||
return { folders: [...folders], root: match }
|
||||
}
|
||||
|
|
@ -0,0 +1,240 @@
|
|||
/**
|
||||
* Folder overlay for @dsh-xhl/workspace-groups: the per-workspace list of
|
||||
* EXTRA folders plus the designated root folder. Stored in a plugin-owned JSON
|
||||
* sidecar (`$DSH_HOME/workspace-groups.folders.json`), next to the manual
|
||||
* grouping overlay, because neither DSH core nor the YAML rule source knows
|
||||
* about folders: core gives a workspace exactly one canonical directory and the
|
||||
* YAML stays the classification source.
|
||||
*
|
||||
* Writes are strict (the browser PUT route validates the whole document before
|
||||
* replacing it, atomically: temp file + fsync + rename) and reads tolerate
|
||||
* hand-edited content (junk entries are dropped instead of thrown), for the
|
||||
* same reason the manual overlay does: a stale or malformed sidecar must never
|
||||
* freeze the tree.
|
||||
*/
|
||||
import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import {
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
samePath,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from './core/folders.ts'
|
||||
|
||||
/** File name of the folder sidecar (also the stable error-text prefix). */
|
||||
export const FOLDERS_FILE_NAME = 'workspace-groups.folders.json'
|
||||
|
||||
/** Hard limits enforced at the write boundary. */
|
||||
export const FOLDERS_PER_WORKSPACE_LIMIT = 32
|
||||
export const WORKSPACE_ID_LIMIT = 200
|
||||
export const FOLDER_PATH_LIMIT = 1024
|
||||
|
||||
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
|
||||
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u
|
||||
|
||||
/** `\\server\share` — a Windows UNC path. */
|
||||
const WINDOWS_UNC = /^\\\\/u
|
||||
|
||||
/** `/…` — a POSIX absolute path. */
|
||||
const POSIX_ABSOLUTE = /^\//u
|
||||
|
||||
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
|
||||
export function defaultFoldersPath(): string {
|
||||
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
|
||||
? process.env.DSH_HOME
|
||||
: resolve(homedir(), '.dsh')
|
||||
return resolve(home, FOLDERS_FILE_NAME)
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
export function isAbsoluteFolderPath(path: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
|
||||
: POSIX_ABSOLUTE.test(path)
|
||||
}
|
||||
|
||||
/** Reject helper carrying the stable file-scoped message prefix. */
|
||||
function invalid(detail: string): never {
|
||||
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one workspace entry.
|
||||
* @param value - raw entry from the document.
|
||||
* @param workspaceId - owning workspace id (used in messages).
|
||||
* @param strict - throw on the first problem, or drop junk and return undefined.
|
||||
* @returns the normalized entry, or undefined when nothing usable remains.
|
||||
*/
|
||||
function parseFolderEntry(
|
||||
value: unknown,
|
||||
workspaceId: string,
|
||||
strict: boolean,
|
||||
): WorkspaceFolderEntry | undefined {
|
||||
const fail = (detail: string): void => {
|
||||
if (strict) invalid(`workspace "${workspaceId}": ${detail}`)
|
||||
}
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
fail('entry must be an object')
|
||||
return undefined
|
||||
}
|
||||
const source = value as Record<string, unknown>
|
||||
if (source.folders === undefined) {
|
||||
fail('folders is required')
|
||||
return undefined
|
||||
}
|
||||
if (!Array.isArray(source.folders)) {
|
||||
fail('folders must be a list')
|
||||
return undefined
|
||||
}
|
||||
if (strict && source.folders.length > FOLDERS_PER_WORKSPACE_LIMIT) {
|
||||
invalid(`workspace "${workspaceId}": at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`)
|
||||
}
|
||||
|
||||
const folders: string[] = []
|
||||
for (const candidate of source.folders) {
|
||||
if (typeof candidate !== 'string') {
|
||||
fail('folder paths must be strings')
|
||||
continue
|
||||
}
|
||||
const path = candidate.trim()
|
||||
if (path === '') {
|
||||
fail('folder paths must be non-empty')
|
||||
continue
|
||||
}
|
||||
if (path.includes('\u0000')) {
|
||||
fail(`folder path "${path}" contains a NUL character`)
|
||||
continue
|
||||
}
|
||||
if (path.length > FOLDER_PATH_LIMIT) {
|
||||
fail(`folder path exceeds ${FOLDER_PATH_LIMIT} characters`)
|
||||
continue
|
||||
}
|
||||
if (!isAbsoluteFolderPath(path)) {
|
||||
fail(`folder path "${path}" must be absolute`)
|
||||
continue
|
||||
}
|
||||
if (folders.some(existing => samePath(existing, path))) {
|
||||
fail(`duplicate folder path "${path}"`)
|
||||
continue
|
||||
}
|
||||
if (folders.length >= FOLDERS_PER_WORKSPACE_LIMIT) {
|
||||
fail(`at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`)
|
||||
break
|
||||
}
|
||||
folders.push(path)
|
||||
}
|
||||
|
||||
let root: string | undefined
|
||||
if (source.root !== undefined) {
|
||||
if (typeof source.root !== 'string') {
|
||||
fail('root must be a string')
|
||||
} else {
|
||||
const candidate = source.root.trim()
|
||||
const member = folders.find(folder => samePath(folder, candidate))
|
||||
if (member === undefined) fail(`root "${candidate}" must name one of folders`)
|
||||
else root = member
|
||||
}
|
||||
}
|
||||
|
||||
if (folders.length === 0 && root === undefined) return undefined
|
||||
return { folders, ...(root === undefined ? {} : { root }) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
||||
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
export function parseFoldersDocument(raw: unknown): FoldersDocument {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return EMPTY_FOLDERS_DOCUMENT
|
||||
const source = raw as Record<string, unknown>
|
||||
if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT
|
||||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
return { version: 1, workspaces: {} }
|
||||
}
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT) continue
|
||||
const entry = parseFolderEntry(value, workspaceId, false)
|
||||
if (entry !== undefined) workspaces[workspaceId] = entry
|
||||
}
|
||||
return { version: 1, workspaces }
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict writer-side validation. Every rule is enforced and the first problem
|
||||
* throws, so the PUT route rejects instead of persisting a half-valid file.
|
||||
* @param raw - parsed JSON value from the request body.
|
||||
* @returns the normalized document to save.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
export function validateFoldersDocument(raw: unknown): FoldersDocument {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
||||
invalid('top-level value must be a mapping')
|
||||
}
|
||||
const source = raw as Record<string, unknown>
|
||||
if (source.version !== 1) invalid('version must be 1')
|
||||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
invalid('workspaces must be a mapping')
|
||||
}
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT) {
|
||||
invalid(`workspace ids must be non-empty strings of at most ${WORKSPACE_ID_LIMIT} characters`)
|
||||
}
|
||||
const entry = parseFolderEntry(value, workspaceId, true)
|
||||
if (entry !== undefined) workspaces[workspaceId] = entry
|
||||
}
|
||||
return { version: 1, workspaces }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
export async function readFoldersDocument(path: string): Promise<FoldersDocument> {
|
||||
try {
|
||||
const text = await readFile(path, 'utf8')
|
||||
return parseFoldersDocument(JSON.parse(text))
|
||||
} catch {
|
||||
return EMPTY_FOLDERS_DOCUMENT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
export async function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void> {
|
||||
const json = `${JSON.stringify(document, null, 2)}\n`
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
|
||||
const handle = await open(tmp, 'w')
|
||||
try {
|
||||
await handle.writeFile(json, 'utf8')
|
||||
await handle.sync()
|
||||
} catch (error) {
|
||||
await handle.close().catch(() => {})
|
||||
await unlink(tmp).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
await handle.close()
|
||||
try {
|
||||
await rename(tmp, path)
|
||||
} catch (error) {
|
||||
await unlink(tmp).catch(() => {})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
66
src/index.ts
66
src/index.ts
|
|
@ -12,6 +12,11 @@
|
|||
* - `PUT /workspace-groups/manual` — replace the whole manual overlay
|
||||
* (manual groups + per-workspace overrides). Validated against the current
|
||||
* rule categories, written atomically to the plugin-owned JSON sidecar.
|
||||
* - `GET /workspace-groups/folders` — the per-workspace extra-folder overlay
|
||||
* plus each workspace's root folder.
|
||||
* - `PUT /workspace-groups/folders` — replace the folder overlay whole.
|
||||
* Strictly validated (absolute paths, no duplicates, root membership) and
|
||||
* written atomically; the saved document is echoed back.
|
||||
*
|
||||
* Core workspace.json / session storage is never touched.
|
||||
*/
|
||||
|
|
@ -34,6 +39,12 @@ import {
|
|||
type PersistedTab,
|
||||
type TabsDocument,
|
||||
} from './host-tabs.ts'
|
||||
import {
|
||||
defaultFoldersPath,
|
||||
readFoldersDocument,
|
||||
validateFoldersDocument,
|
||||
writeFoldersDocument,
|
||||
} from './host-folders.ts'
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = '@dsh-xhl/workspace-groups'
|
||||
|
|
@ -104,6 +115,7 @@ export function apply(ctx: GroupsContext): void {
|
|||
const configPath = defaultConfigPath()
|
||||
const manualPath = defaultManualPath()
|
||||
const tabsPath = defaultTabsPath()
|
||||
const foldersPath = defaultFoldersPath()
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
|
|
@ -230,4 +242,58 @@ export function apply(ctx: GroupsContext): void {
|
|||
res.end(body)
|
||||
},
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/manual route')
|
||||
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/workspace-groups/folders',
|
||||
handler: async (req, res) => {
|
||||
if (req.method === 'GET' || req.method === 'HEAD') {
|
||||
// The reader is tolerant by construction (a missing or torn sidecar is
|
||||
// the empty document), so it cannot fail a GET.
|
||||
const document = await readFoldersDocument(foldersPath)
|
||||
const body = JSON.stringify(document)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(req.method === 'HEAD' ? undefined : body)
|
||||
return
|
||||
}
|
||||
if (req.method !== 'PUT') {
|
||||
writeError(res, 405, 'method not allowed')
|
||||
return
|
||||
}
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
||||
} catch (error) {
|
||||
const status = error instanceof HttpError ? error.status : 400
|
||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
let document
|
||||
try {
|
||||
document = validateFoldersDocument(raw)
|
||||
} catch (error) {
|
||||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
try {
|
||||
await writeFoldersDocument(foldersPath, document)
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write folder overlay: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
// Echo the normalized document: the client renders exactly what the host
|
||||
// accepted, not its own (possibly trimmed) guess.
|
||||
const body = JSON.stringify(document)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
},
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/folders route')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,254 @@
|
|||
/**
|
||||
* Per-workspace folder tests: the pure folder logic (path identity, root
|
||||
* resolution, cwd ownership, entry editing) plus the host overlay's strict
|
||||
* write validation and tolerant read, including the atomic file round-trip.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import {
|
||||
addFolder,
|
||||
effectiveFolders,
|
||||
entryFor,
|
||||
folderOfCwd,
|
||||
removeFolder,
|
||||
rootOf,
|
||||
samePath,
|
||||
setRoot,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from '../src/core/folders.ts'
|
||||
import {
|
||||
parseFoldersDocument,
|
||||
readFoldersDocument,
|
||||
validateFoldersDocument,
|
||||
writeFoldersDocument,
|
||||
} from '../src/host-folders.ts'
|
||||
|
||||
const BASE = 'C:\\work\\project'
|
||||
const EXTRA = 'C:\\work\\extra'
|
||||
|
||||
describe('samePath', () => {
|
||||
it('is case-insensitive for Windows-style paths', () => {
|
||||
expect(samePath('C:\\Work\\Project', 'c:\\work\\project')).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores trailing separators', () => {
|
||||
expect(samePath('C:\\work\\project\\', 'C:\\work\\project')).toBe(true)
|
||||
expect(samePath('/home/me/project/', '/home/me/project')).toBe(true)
|
||||
})
|
||||
|
||||
it('treats both separators as equal on Windows-style paths', () => {
|
||||
expect(samePath('C:/work/project', 'C:\\work\\project')).toBe(true)
|
||||
})
|
||||
|
||||
it('distinguishes different POSIX paths case-sensitively', () => {
|
||||
expect(samePath('/home/me/Project', '/home/me/project')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('effectiveFolders / rootOf / entryFor', () => {
|
||||
it('puts the workspace path first', () => {
|
||||
expect(effectiveFolders(BASE, undefined)).toEqual([BASE])
|
||||
expect(effectiveFolders(BASE, { folders: [EXTRA] })).toEqual([BASE, EXTRA])
|
||||
})
|
||||
|
||||
it('drops blank, self-referencing and duplicate extras', () => {
|
||||
expect(effectiveFolders(BASE, { folders: [' ', BASE, 'C:\\WORK\\EXTRA', EXTRA, EXTRA] }))
|
||||
.toEqual([BASE, 'C:\\WORK\\EXTRA'])
|
||||
})
|
||||
|
||||
it('falls back to the workspace path when no root is stored', () => {
|
||||
expect(rootOf(BASE, undefined)).toBe(BASE)
|
||||
expect(rootOf(BASE, { folders: [EXTRA] })).toBe(BASE)
|
||||
})
|
||||
|
||||
it('returns the stored root', () => {
|
||||
expect(rootOf(BASE, { folders: [EXTRA], root: EXTRA })).toBe(EXTRA)
|
||||
})
|
||||
|
||||
it('ignores a dangling root that names no effective folder', () => {
|
||||
expect(rootOf(BASE, { folders: [EXTRA], root: 'D:\\gone' })).toBe(BASE)
|
||||
})
|
||||
|
||||
it('reads entries by workspace id', () => {
|
||||
const document: FoldersDocument = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } }
|
||||
expect(entryFor(document, 'ws-1')).toEqual({ folders: [EXTRA] })
|
||||
expect(entryFor(document, 'ws-2')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('folderOfCwd', () => {
|
||||
const entry: WorkspaceFolderEntry = { folders: [EXTRA, 'C:\\work\\extra\\nested'] }
|
||||
|
||||
it('returns the workspace path for an undefined cwd', () => {
|
||||
expect(folderOfCwd(undefined, BASE, entry)).toBe(BASE)
|
||||
})
|
||||
|
||||
it('returns the base for a cwd inside the workspace', () => {
|
||||
expect(folderOfCwd('C:\\work\\project\\src', BASE, entry)).toBe(BASE)
|
||||
})
|
||||
|
||||
it('returns the owning extra folder', () => {
|
||||
expect(folderOfCwd('C:\\work\\extra\\src', BASE, entry)).toBe(EXTRA)
|
||||
})
|
||||
|
||||
it('returns the most specific folder for a nested folder', () => {
|
||||
expect(folderOfCwd('C:\\work\\extra\\nested\\deep', BASE, entry)).toBe('C:\\work\\extra\\nested')
|
||||
})
|
||||
|
||||
it('returns the base for a cwd outside every folder', () => {
|
||||
expect(folderOfCwd('D:\\elsewhere', BASE, entry)).toBe(BASE)
|
||||
})
|
||||
|
||||
it('does not treat a name prefix as an ancestor', () => {
|
||||
expect(folderOfCwd('C:\\work\\extrabonus', BASE, entry)).toBe(BASE)
|
||||
})
|
||||
|
||||
it('matches the folder itself', () => {
|
||||
expect(folderOfCwd('C:\\WORK\\EXTRA', BASE, entry)).toBe(EXTRA)
|
||||
})
|
||||
})
|
||||
|
||||
describe('addFolder / removeFolder / setRoot', () => {
|
||||
it('adds an extra folder and keeps the root', () => {
|
||||
const next = addFolder({ folders: [EXTRA], root: EXTRA }, 'D:\\other')
|
||||
expect(next).toEqual({ folders: [EXTRA, 'D:\\other'], root: EXTRA })
|
||||
})
|
||||
|
||||
it('is idempotent and trims', () => {
|
||||
expect(addFolder({ folders: ['D:\\other'] }, ' D:\\other ')).toEqual({ folders: ['D:\\other'] })
|
||||
expect(addFolder(undefined, EXTRA)).toEqual({ folders: [EXTRA] })
|
||||
})
|
||||
|
||||
it('never mutates the input entry', () => {
|
||||
const entry: WorkspaceFolderEntry = { folders: [EXTRA] }
|
||||
addFolder(entry, 'D:\\other')
|
||||
expect(entry).toEqual({ folders: [EXTRA] })
|
||||
})
|
||||
|
||||
it('drops a folder and clears a root pointing at it', () => {
|
||||
expect(removeFolder({ folders: [EXTRA], root: EXTRA }, EXTRA)).toEqual({ folders: [] })
|
||||
expect(removeFolder({ folders: [EXTRA, 'D:\\other'], root: 'D:\\other' }, EXTRA))
|
||||
.toEqual({ folders: ['D:\\other'], root: 'D:\\other' })
|
||||
})
|
||||
|
||||
it('stores the root only for an extra folder', () => {
|
||||
expect(setRoot({ folders: [EXTRA] }, EXTRA)).toEqual({ folders: [EXTRA], root: EXTRA })
|
||||
expect(setRoot({ folders: [EXTRA], root: EXTRA }, BASE)).toEqual({ folders: [EXTRA] })
|
||||
expect(setRoot(undefined, BASE)).toEqual({ folders: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateFoldersDocument', () => {
|
||||
const valid = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
|
||||
it('accepts a valid document', () => {
|
||||
expect(validateFoldersDocument(valid)).toEqual(valid)
|
||||
})
|
||||
|
||||
it('rejects a wrong version', () => {
|
||||
expect(() => validateFoldersDocument({ version: 2, workspaces: {} })).toThrow(/version/)
|
||||
})
|
||||
|
||||
it('rejects a non-object document', () => {
|
||||
expect(() => validateFoldersDocument([])).toThrow(/mapping/)
|
||||
expect(() => validateFoldersDocument('nope')).toThrow(/mapping/)
|
||||
})
|
||||
|
||||
it('rejects a relative folder path', () => {
|
||||
expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders: ['work'] } } }))
|
||||
.toThrow(/absolute/)
|
||||
})
|
||||
|
||||
it('rejects case-insensitive duplicates', () => {
|
||||
expect(() => validateFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: { 'ws-1': { folders: [EXTRA, 'c:\\WORK\\extra'] } },
|
||||
})).toThrow(/duplicate/)
|
||||
})
|
||||
|
||||
it('rejects a root that is not one of the folders', () => {
|
||||
expect(() => validateFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: { 'ws-1': { folders: [EXTRA], root: 'D:\\other' } },
|
||||
})).toThrow(/root/)
|
||||
})
|
||||
|
||||
it('rejects a NUL byte and an over-long path', () => {
|
||||
expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\a\u0000b'] } } }))
|
||||
.toThrow(/NUL/)
|
||||
expect(() => validateFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: { 'ws-1': { folders: ['C:\\' + 'a'.repeat(1100)] } },
|
||||
})).toThrow(/1024/)
|
||||
})
|
||||
|
||||
it('rejects more than 32 folders', () => {
|
||||
const folders = Array.from({ length: 33 }, (_, index) => `C:\\w\\${index}`)
|
||||
expect(() => validateFoldersDocument({ version: 1, workspaces: { 'ws-1': { folders } } }))
|
||||
.toThrow(/32/)
|
||||
})
|
||||
|
||||
it('rejects an over-long workspace id', () => {
|
||||
expect(() => validateFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: { ['w'.repeat(201)]: { folders: [EXTRA] } },
|
||||
})).toThrow(/200/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseFoldersDocument (tolerant read)', () => {
|
||||
it('returns the empty document for junk instead of throwing', () => {
|
||||
expect(parseFoldersDocument(undefined)).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument(null)).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument([])).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument({ version: 7, workspaces: {} })).toEqual({ version: 1, workspaces: {} })
|
||||
})
|
||||
|
||||
it('drops bad folders, duplicates and dangling roots', () => {
|
||||
const parsed = parseFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: {
|
||||
'ws-1': { folders: [EXTRA, 'relative', 42, 'c:\\WORK\\extra', ''] , root: 'D:\\gone' },
|
||||
'': { folders: [EXTRA] },
|
||||
'ws-2': 'nope',
|
||||
},
|
||||
})
|
||||
expect(parsed).toEqual({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } })
|
||||
})
|
||||
|
||||
it('keeps a valid root and tolerates a dangling workspace id', () => {
|
||||
const parsed = parseFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } },
|
||||
})
|
||||
expect(parsed.workspaces['ws-1']).toEqual({ folders: [EXTRA], root: EXTRA })
|
||||
})
|
||||
})
|
||||
|
||||
describe('readFoldersDocument / writeFoldersDocument', () => {
|
||||
it('reads a missing file as the empty document', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wg-folders-'))
|
||||
try {
|
||||
expect(await readFoldersDocument(join(dir, 'missing.json'))).toEqual({ version: 1, workspaces: {} })
|
||||
await writeFile(join(dir, 'junk.json'), '{not json', 'utf8')
|
||||
expect(await readFoldersDocument(join(dir, 'junk.json'))).toEqual({ version: 1, workspaces: {} })
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('round-trips a document through the atomic write', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wg-folders-'))
|
||||
const path = join(dir, 'nested', 'workspace-groups.folders.json')
|
||||
const document: FoldersDocument = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
try {
|
||||
await writeFoldersDocument(path, document)
|
||||
expect(await readFoldersDocument(path)).toEqual(document)
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,146 @@
|
|||
/**
|
||||
* Standalone verifier for the per-workspace folder layer.
|
||||
*
|
||||
* vitest cannot spawn in this sandbox (EPERM), so this script runs the same
|
||||
* critical assertions under plain Node 24 type-stripping:
|
||||
* node tools/verify-folders.mjs
|
||||
*
|
||||
* It imports the pure module (`src/core/folders.ts`) and the host overlay
|
||||
* (`src/host-folders.ts`, Node built-ins only), exercises the root/cwd rules and
|
||||
* the strict-write / tolerant-read boundary, then prints exactly one line.
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
const coreUrl = new URL('../src/core/folders.ts', import.meta.url)
|
||||
const hostUrl = new URL('../src/host-folders.ts', import.meta.url)
|
||||
|
||||
const {
|
||||
addFolder,
|
||||
effectiveFolders,
|
||||
entryFor,
|
||||
folderOfCwd,
|
||||
removeFolder,
|
||||
rootOf,
|
||||
samePath,
|
||||
setRoot,
|
||||
} = await import(coreUrl.href)
|
||||
const {
|
||||
parseFoldersDocument,
|
||||
readFoldersDocument,
|
||||
validateFoldersDocument,
|
||||
writeFoldersDocument,
|
||||
} = await import(hostUrl.href)
|
||||
|
||||
const BASE = 'C:\\work\\project'
|
||||
const EXTRA = 'C:\\work\\extra'
|
||||
let checks = 0
|
||||
const check = (condition, message) => {
|
||||
checks += 1
|
||||
assert.ok(condition, message)
|
||||
}
|
||||
const equal = (actual, expected, message) => {
|
||||
checks += 1
|
||||
assert.deepEqual(actual, expected, message)
|
||||
}
|
||||
|
||||
// --- path identity -----------------------------------------------------------
|
||||
check(samePath('C:\\Work\\Project', 'c:\\work\\project'), 'samePath is case-insensitive for Windows paths')
|
||||
check(samePath('C:\\work\\project\\', 'C:\\work\\project'), 'samePath ignores a trailing separator')
|
||||
check(samePath('C:/work/project', 'C:\\work\\project'), 'samePath folds separators on Windows paths')
|
||||
check(!samePath('/home/me/Project', '/home/me/project'), 'POSIX paths stay case-sensitive')
|
||||
check(!samePath('/home/me/project', '/home/me/projectfile'), 'a name prefix is not the same path')
|
||||
|
||||
// --- effective folders / root ------------------------------------------------
|
||||
equal(effectiveFolders(BASE, undefined), [BASE], 'base folder is effective without an entry')
|
||||
equal(effectiveFolders(BASE, { folders: [EXTRA] }), [BASE, EXTRA], 'base comes first, extras keep order')
|
||||
equal(
|
||||
effectiveFolders(BASE, { folders: [' ', BASE, 'C:\\WORK\\EXTRA', EXTRA, EXTRA] }),
|
||||
[BASE, 'C:\\WORK\\EXTRA'],
|
||||
'blank, self-referencing and duplicate extras are dropped (first spelling wins)',
|
||||
)
|
||||
equal(rootOf(BASE, undefined), BASE, 'root defaults to the workspace path')
|
||||
equal(rootOf(BASE, { folders: [EXTRA] }), BASE, 'root stays the workspace path when omitted')
|
||||
equal(rootOf(BASE, { folders: [EXTRA], root: EXTRA }), EXTRA, 'stored root wins')
|
||||
equal(rootOf(BASE, { folders: [EXTRA], root: 'D:\\gone' }), BASE, 'dangling root falls back to the base')
|
||||
equal(entryFor({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } }, 'ws-1'), { folders: [EXTRA] }, 'entryFor reads by id')
|
||||
equal(entryFor({ version: 1, workspaces: {} }, 'ws-2'), undefined, 'entryFor misses cleanly')
|
||||
|
||||
// --- cwd ownership -----------------------------------------------------------
|
||||
const entry = { folders: [EXTRA, 'C:\\work\\extra\\nested'] }
|
||||
equal(folderOfCwd(undefined, BASE, entry), BASE, 'undefined cwd owns the base')
|
||||
equal(folderOfCwd('C:\\work\\project\\src', BASE, entry), BASE, 'a workspace cwd owns the base')
|
||||
equal(folderOfCwd('C:\\work\\extra\\src', BASE, entry), EXTRA, 'an extra folder cwd owns that folder')
|
||||
equal(folderOfCwd('C:\\work\\extra\\nested\\deep', BASE, entry), 'C:\\work\\extra\\nested', 'the most specific folder wins')
|
||||
equal(folderOfCwd('D:\\elsewhere', BASE, entry), BASE, 'an outside cwd falls back to the base')
|
||||
equal(folderOfCwd('C:\\work\\extrabonus', BASE, entry), BASE, 'a name prefix is not an ancestor')
|
||||
equal(folderOfCwd('C:\\WORK\\EXTRA', BASE, entry), EXTRA, 'cwd matching is case-insensitive')
|
||||
|
||||
// --- entry editing (pure, never mutating) ------------------------------------
|
||||
const before = { folders: [EXTRA] }
|
||||
const added = addFolder(before, 'D:\\other')
|
||||
equal(added, { folders: [EXTRA, 'D:\\other'] }, 'addFolder appends')
|
||||
equal(before, { folders: [EXTRA] }, 'addFolder does not mutate its input')
|
||||
equal(addFolder({ folders: ['D:\\other'] }, ' D:\\other '), { folders: ['D:\\other'] }, 'addFolder is idempotent and trims')
|
||||
equal(addFolder(undefined, EXTRA), { folders: [EXTRA] }, 'addFolder creates an entry')
|
||||
equal(removeFolder({ folders: [EXTRA], root: EXTRA }, EXTRA), { folders: [] }, 'removeFolder clears a root pointing at it')
|
||||
equal(
|
||||
removeFolder({ folders: [EXTRA, 'D:\\other'], root: 'D:\\other' }, EXTRA),
|
||||
{ folders: ['D:\\other'], root: 'D:\\other' },
|
||||
'removeFolder keeps an unrelated root',
|
||||
)
|
||||
equal(setRoot({ folders: [EXTRA] }, EXTRA), { folders: [EXTRA], root: EXTRA }, 'setRoot stores an extra folder')
|
||||
equal(setRoot({ folders: [EXTRA], root: EXTRA }, BASE), { folders: [EXTRA] }, 'setRoot on the base clears the root')
|
||||
equal(setRoot(undefined, BASE), { folders: [] }, 'setRoot without extras yields an empty entry')
|
||||
|
||||
// --- strict write validation -------------------------------------------------
|
||||
const valid = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
equal(validateFoldersDocument(valid), valid, 'a valid document round-trips validation')
|
||||
const rejects = (value, pattern) => {
|
||||
checks += 1
|
||||
assert.throws(() => validateFoldersDocument(value), pattern)
|
||||
}
|
||||
rejects({ version: 2, workspaces: {} }, /version/)
|
||||
rejects([], /mapping/)
|
||||
rejects('nope', /mapping/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: ['work'] } } }, /absolute/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA, 'c:\\WORK\\extra'] } } }, /duplicate/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: 'D:\\other' } } }, /root/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\a\u0000b'] } } }, /NUL/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: ['C:\\' + 'a'.repeat(1100)] } } }, /1024/)
|
||||
rejects({ version: 1, workspaces: { 'ws-1': { folders: Array.from({ length: 33 }, (_, i) => `C:\\w\\${i}`) } } }, /32/)
|
||||
rejects({ version: 1, workspaces: { ['w'.repeat(201)]: { folders: [EXTRA] } } }, /200/)
|
||||
|
||||
// --- tolerant read -----------------------------------------------------------
|
||||
equal(parseFoldersDocument(undefined), { version: 1, workspaces: {} }, 'undefined parses empty')
|
||||
equal(parseFoldersDocument({ version: 7, workspaces: {} }), { version: 1, workspaces: {} }, 'a bad version parses empty')
|
||||
equal(
|
||||
parseFoldersDocument({
|
||||
version: 1,
|
||||
workspaces: {
|
||||
'ws-1': { folders: [EXTRA, 'relative', 42, 'c:\\WORK\\extra', ''], root: 'D:\\gone' },
|
||||
'': { folders: [EXTRA] },
|
||||
'ws-2': 'nope',
|
||||
},
|
||||
}),
|
||||
{ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } },
|
||||
'tolerant parse drops junk instead of throwing',
|
||||
)
|
||||
|
||||
// --- file round-trip ---------------------------------------------------------
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wg-folders-verify-'))
|
||||
try {
|
||||
equal(await readFoldersDocument(join(dir, 'missing.json')), { version: 1, workspaces: {} }, 'a missing file reads empty')
|
||||
await writeFile(join(dir, 'junk.json'), '{not json', 'utf8')
|
||||
equal(await readFoldersDocument(join(dir, 'junk.json')), { version: 1, workspaces: {} }, 'unreadable JSON reads empty')
|
||||
const path = join(dir, 'nested', 'workspace-groups.folders.json')
|
||||
await writeFoldersDocument(path, valid)
|
||||
equal(await readFoldersDocument(path), valid, 'atomic write round-trips through the reader')
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
// Success is a single machine-checkable line: the harness pastes this output.
|
||||
process.stdout.write('folders: all assertions passed\n')
|
||||
Loading…
Reference in New Issue