Compare commits

...

10 Commits

Author SHA1 Message Date
qyh15 edc5054503 fix(sidebar): suppress injected remote SSH globe badges in grouped tree 2026-11-12 09:40:19 +08:00
qyh15 262fdc4ad4 fix(sidebar): replace expansion icons with plain CSS triangles 2026-11-12 09:31:31 +08:00
lead 308a790412 fix(sidebar): keep the chevron slot to a single clipped glyph
A second shape was painting itself over the disclosure triangle on one project
row, so the marker read as a mush of two glyphs. Clip the 14px slot and drop any
svg that is not its first child.
2026-11-08 15:32:32 +08:00
lead 34a41d70b9 fix(sidebar): render project row glyph at a fixed 16px slot with medium stroke
The project row was the only row kind drawing a 1px Regular artwork inside a
size-less flex slot, so the folder+plus glyph got squashed into an unreadable
grey blob. Give .wgCategoryIcon an explicit 16x16 box and switch the glyph to
IconProjectAddOutlineMedium, matching every other row icon.
2026-11-08 15:27:46 +08:00
qyh15 dcc47fc0b6 feat(farm): gather a project's folders into one workspace
A session can only reach its own workspace directory, so folders spread over
several places could not be read and written by one session. The new farm
route builds one real directory whose entries are links to the user's folders
(junction on Windows, directory symlink elsewhere) and registers it as a
workspace.

Nothing is copied or moved. Removal unlinks entries only and aborts as soon as
it meets a real directory, so a farm can never take a user's folder with it.
2026-11-07 18:08:27 +08:00
qyh15 bc6a427dfe feat(tree): one row per project — folders no longer own session lists
Extra folders were rendered as their own rows with their own sessions, so a
project that carried a second directory split into two session lists. On a
cloud workspace the base row also exposed the local mirror id
(`wmvl31c7ilkuc`) as a folder name, which read as a project nested inside
itself.

Folders are now extra DIRECTORIES of one project: `applyFolders` returns the
workspace's sessions untouched, so the owner row and every member workspace
share a single list. Folders stay manageable from the workspace menu
(⋯ → 管理文件夹) where they can still be added, rooted, opened or removed.

Drops the now-unused folder-label/label-matching helpers, updates the
regression test to assert one merged row, and rewrites the CHANGELOG entry.
typecheck 0 errors, 290 tests pass, all three verifiers pass.
2026-11-07 17:53:22 +08:00
qyh15 571638b836 fix(tree): stop rendering the base directory as a folder row
A workspace with extra folders used to grow one folder row per directory,
including its own base directory. For a cloud workspace the base is the
locally generated mirror (`wmvl31c7ilkuc`), so the sidebar showed that id as
a folder name and hid every session owned by the workspace inside it — one
cloud project read as a project nested inside itself.

The base directory is now the workspace row itself: `nodes[].sessions` keeps
its sessions and only real extras become folder rows. `folderNode` no longer
takes `isBase`, so a mirror id can never be labelled as a folder again, and a
workspace without extras keeps the exact pre-folders node shape.

Adds a regression test covering the mirror case (extra folder only, base
sessions on the workspace, no `wmvl31c7ilkuc` label) and documents the change
in CHANGELOG. typecheck 0 errors, 290 tests pass.
2026-11-07 17:46:32 +08:00
qyh15 36b9cb2bc0 fix(folders): make the folder overlay crash-safe and consistent
The folder sidecar was written as a whole document with no concurrency
control, and any read failure silently degraded to an empty document, so a
later edit could erase every workspace's folder configuration. Rework the
read/write path end to end:

- Agent side: expose a content revision, require If-Match on PUT, answer
  409 with the current document, serialise read-compare-write, and fail the
  GET loudly instead of serving an empty overlay. Unknown schema versions
  are reported and never downgraded back to v1.
- Client: load/save report failure instead of fabricating an empty
  document, edits go through one serial queue with optimistic update,
  rollback on error, and reload on conflict. Editing is blocked while the
  overlay cannot be read. Creating a workspace is compensated when the
  follow-up save fails, so no orphan workspace is left behind.
- Paths: normalise NFC and lexically fold "." and "..", decide
  absoluteness by spelling instead of process.platform, share one
  implementation between core and host, and keep an existing root when a
  member is re-registered at the same path.
- Remote folders: resolve the owner root from the SSH probe instead of the
  "~" alias, and make "subfolder of this project" versus "register a new
  cloud workspace" an explicit choice in the dialog.
- Stop shipping the client source map, which embedded the full TypeScript
  sources in the published package.
- Track the SSH integration plan and cover the new behaviour with tests
  (CAS, persistence, remote path parsing).

Verification: both tsconfigs typecheck clean, 288 tests pass, build
succeeds, and all three ad-hoc verifiers pass.
2026-11-07 17:29:57 +08:00
qyh15 efac404c1a chore(release): 1.3.0 2026-10-31 19:25:14 +08:00
qyh15 2386f8b912 chore(release): 1.1.0 2026-10-31 17:54:30 +08:00
43 changed files with 4315 additions and 1672 deletions

12
.gitignore vendored
View File

@ -2,6 +2,14 @@ node_modules/
*.log
.DS_Store
# 开发工程文件:docs 五级文档框架不进项目 git 仓库
docs/
# Build / test byproducts. The published client bundle must NOT ship a
# sourcemap: tsdown now builds with sourcemap:false (see tsdown.config.ts).
*.map
*.tsbuildinfo
dist/
coverage/
tools/_tmp/
# Local-only agent instructions. Project design docs under docs/ ARE tracked:
# remote-ssh-integration-plan.md documents the two open task-board cards.
AGENTS.md

View File

@ -1,5 +1,79 @@
# 更新日志
## 未发布 — 一个工作区收拢多个文件夹(2026-11-07)
会话的文件范围就是它所在的工作区目录,所以分散在不同位置的文件夹无法被同一个会话同时读写。
新增「合并成一个总文件夹」:在 `$DSH_HOME/workspace-groups/farms/<名称>/` 建一个真实目录,
用链接(Windows junction / POSIX 目录符号链接)把该项目的每个文件夹放进去,再注册成一个工作区。
不复制、不移动、不改动原文件夹。
- 新增宿主路由 `POST /workspace-groups/farm` 与 `DELETE /workspace-groups/farm?path=`。宿主只接受绝对路径,
不存在的目录直接拒绝,已存在的农场拒绝复用(避免静默合并到别人建的目录)。
- 删除只解链接:遇到真实目录立刻中止,绝不递归删除,避免顺链接删掉用户的真实文件夹。
- 侧栏「管理文件夹」对话框在该工作区有 2 个及以上文件夹时显示该操作;成功后提示新工作区路径。
- 新增 `tests/farm.test.ts`(11 项):写入穿透链接落到真实文件夹、同名文件夹去重命名、相对/缺失目录拒绝、
重复农场拒绝、删除后原文件夹内容不变、农场根外路径拒绝、农场内真实目录拒绝删除。
## 未发布 — 文件夹管理安全性与一致性修复(2026-11-07)
针对「工作区内的文件夹管理」扫描发现的 10 类问题做的一次集中修复。本次只改本插件,
未触碰核心 workspace.json / session 存储;`lib/` 已重新构建,Source map 不再随包发布。
### 数据完整性(高危)
- 读取 `workspace-groups.folders.json` 失败(EACCES / EISDIR / JSON 损坏)现在返回 HTTP 500,
不再伪装成「空文档」;客户端 loadFolders 改为 `ok:false` 并禁用全部编辑,杜绝「读失败 → 下次 PUT
写回空文档 → 所有工作区文件夹永久清空」。
- 新增基于文件内容的 `revision`(sha256 前 16 位)+ `ETag` / `If-Match` 乐观并发:PUT 不匹配返回
409 并携带服务端最新文档;宿主侧 read→compare→write 串行化,客户端写操作排队、失败回滚、
409 自动重载。多窗口不再静默互相覆盖。
- 未知 schema 版本只报告 `schemaWarning` 并禁用编辑,绝不降级写回 v1。
- PUT body 上限从 64KB 提到 1MB(合法文档上限约 92KB 曾永远 413);保存请求去掉 `keepalive`
并加 15 秒超时,避免大文档被静默截断。
### 路径与远程判定
- `canonicalPath` 增加 NFC 归一与词法 `.` / `..` 折叠;`isAbsoluteFolderPath` 改为按路径拼写判定,
宿主与客户端共用同一函数,不再因 `process.platform` 漂移而丢弃跨平台 sidecar 条目。
- `defaultRemoteMirrorBase` 硬编码 `~/.dsh/remote-workspaces` 的问题改为显式诊断:
`$DSH_HOME` 与硬编码根不一致时 GET 返回 `remoteBaseWarning` 并在界面显示。
- 宿主写校验现在强制 `kind:'remote'` 的 member.path 必须位于镜像根内,并拒绝 `..` 段;
镜像归属不再只靠浏览器自觉。
- `subfolderOf` 用浏览器返回的绝对 `resolved` 路径比较(`~` 别名由 `openFoldersFor` 先解析),
分隔符归一;云端输入框改为显式「本项目子目录 / 独立云端工作区」二选一,消除一个输入框两种语义。
### 会话与孤儿工作区
- 创建会话前必须等文件夹 overlay 落盘成功;原生工作区创建失败可补偿注销,远程文件夹创建有
pending 复用,避免重复建镜像。
- `addMember` 同路径重注册时保留 `root`;`isDefaultWorkspace` 改为路径判据优先;
跨 entry 拒绝「member.workspaceId 同时是 owner」,宽容读会丢弃这类旧数据。
- `parseFolderEntry` 允许缺 `folders` 字段(不再连带丢掉 members),`remoteSubpath` 与
`joinSubpath` 对绝对/盘符/UNC 输入的判定统一;`joinSubpath` 额外拒绝 `C:foo`。
### 侧栏文件夹行
- 一个项目只占一行。此前工作区挂上额外文件夹后,每个文件夹都会变成一条带自己会话列表的行;
云端工作区的路径是本地镜像目录,于是侧栏出现 `wmvl31c7ilkuc` 这种内部 id,项目自身的
会话又被藏进那一行,看起来像「一个项目套在它自己里面」。
- 现在不再渲染文件夹行:工作区自己的目录和所有额外文件夹共用同一个会话列表,全部列在
工作区标题下面。文件夹仍然可以在工作区的「⋯ → 管理文件夹」里增删、设根、打开,
只是不再各自分裂出一套会话。
- 工作区没有额外文件夹时,节点形状与引入文件夹功能之前完全一致。
### 测试与工程
- 新增 `tests/folders-cas.test.ts`、`tests/folders-persist.test.ts`、`tests/remote-paths.test.ts`
覆盖上述回归点;`tsc -p tsconfig.json` / `tsconfig.client.json` 与 290 个 vitest 用例全部通过。
- `tsdown.config.ts` 关闭客户端 sourcemap,`lib/client.js.map`(内嵌完整源码)已从构建产物移除;
`.gitignore` 补 `*.map` / `*.tsbuildinfo` / `dist/` / `coverage/` / `tools/_tmp/`,并取消对
`docs/` 的忽略,把 `remote-ssh-integration-plan.md` 纳入版本控制。
- 工作区根目录新增 README 说明目录职责;`dsh-workspace-groups-0.4.2/` 与 `tools/` 各加说明,
标明 0.4.2 是**有意保留的重建基线,不可删除**。未删除/移动任何既有目录或文件。
### 仍未处理(需另行确认)
- `lib/` 里历史遗留的其它 37 个 tracked 文件是构建产物,未做 `git rm --cached`;若要改为
构建时再生成,需要同步调整发布流程。
- `iggfeed.yaml` 与 `tools/fetch_clash_sub.py` 含本机代理地址/订阅 URL,仅在工作区 README 中提示,
未改动。
- remote-ssh 2.4.40 的远程子目录会话限制、SSH 能力完整内置、会话拆分仍是
`docs/remote-ssh-integration-plan.md` 与任务板里的独立待办,本次未动。
## 1.0.0 — 2026-10-28
首个本地稳定版本,包名 `workspace-groups-local`。基于原项目扩展,保留原 MIT 许可证与版权声明。

View File

@ -162,12 +162,25 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
## 6. 已知坑
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM),在普通 PowerShell 终端里跑。
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM);需 `danger-full-access`
或在普通 PowerShell 终端里跑。pnpm 的 hoisted 布局偶尔缺 `@vitest/*` 顶层链接,
这时用 `node_modules/.pnpm/vitest@*/node_modules/vitest/vitest.mjs` 加一个不 import
`vitest/config` 的纯 JS 配置即可绕过。
- **`node_modules/.bin/*.CMD` 直调会挂**:pnpm 里嵌套的 pnpm 脚本在 DSH 沙箱下会
`Could not determine executable`,统一用 `node <pnpm.cjs> <script>` 形式。
- **单测覆盖不齐**:`tests/` 是早期版本写的,现已补 `tests/tabs.test.ts`(标签条纯逻辑:
固定区不变量、拖动夹紧、关闭其他/右侧、持久化恢复);**快切面板
(`quick.ts` / `QuickPanel.tsx`)与分组外观仍无单测**,改到这些区域时补。
`Could not determine executable`,统一用 `node <pnpm.cjs> <script>` 形式;跑 build/test
前先把 `.../dependencies/node/bin` 加进 PATH,否则脚本里的 `node` 找不到。
- **`lib/` 是实际被加载的产物**:改完 `src/` 必须 `pnpm build`。`tsdown.config.ts`
已关闭客户端 sourcemap,发布包不再内嵌完整 TS 源码。
- **单测覆盖**:`tests/` 现含 `tabs.test.ts`(标签条)、`folders.test.ts`(纯逻辑/宿主校验)、
`folders-cas.test.ts`(HTTP 500/409/CAS/未知 schema/路径归一)、
`folders-persist.test.ts`(客户端 fail-closed 与 If-Match)、
`remote-paths.test.ts`(别名 vs 绝对路径)。**快切面板(`quick.ts` /
`QuickPanel.tsx`)与分组外观仍无单测**,改到这些区域时补。
- **文件夹 overlay 是 CAS 协议,不再是「全量 GET → 改 → 全量 PUT」**:host GET 返回
`revision` + `ETag`,PUT 必须带 `If-Match`,不匹配回 409 + 服务端最新文档;读失败一律
500 且客户端禁用编辑。任何新增写路径都要走 `GroupsBrowser.tsx` 的
`editFolderEntry` 队列(串行、乐观更新、失败回滚、冲突重载),**不要直接调 `saveFolders`**;
新建原生/远程工作区的副作用必须等 overlay 落盘成功才算完成,失败要补偿或 pending 复用。
- **改持久化格式一律「严格写、宽容读」**:新增字段必须是可选的,旧文件读不进来不算
错;悬挂键(如已删除的分类/会话)不得拒写,否则用户会卡在 400 上再也保存不了;
新字段在 `restore*` 里必须原样带过去(`pinned`/`title` 漏带就等于重启丢配置)。

460
README.md
View File

@ -4,459 +4,49 @@
# dsh-better-workspace-group
![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
![Fork of z-col/dsh-workspace-groups](https://img.shields.io/badge/fork-z--col%2Fdsh--workspace--groups-blueviolet.svg)
![DSH](https://img.shields.io/badge/DSH-0.1.1--rc.2-purple.svg)
<img src="https://img.shields.io/badge/DeepSeek%20Harness-plugin-202724" alt="DeepSeek Harness plugin">
A workspace grouping plugin for DeepSeek Harness. Built on [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups), it keeps workspaces, folders, and sessions easier to organize and use from the sidebar.
> **Fork of [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups).**
> The three-level tree, drag-and-drop grouping, sidecar rules and session tab strip are the
> original author's work (MIT); this fork keeps them and adds a research-glyph icon set, a
> pinned default-workspace bar and a unified trailing row slot — see
> [Credit & upstream](#credit--upstream).
## Preview
> **A DeepSeek Harness (DSH) web client plugin: a complete workspace grouping manager.**
> Turns the GUI sidebar's two-level workspace list (Projects → Sessions) into a
> three-level **Category folder → Project folder → Session** tree, backed by full
> group-management capabilities: manual group creation, rename/delete of any group,
> drag-and-drop grouping, free ordering of projects and groups, rule-based
> auto-classification, and tree-shaped search. Every action takes effect
> **immediately and persists**, with **zero intrusion** on official data.
<img src="screenshot.png" alt="Workspace grouping plugin preview" width="280" />
## Implemented features
## Screenshot
- **Workspace groups**: browse by group → project → session, with group creation, renaming, deletion, folding, and pinning.
- **Drag-and-drop organization**: move projects into or out of groups and reorder groups and projects.
- **Group appearance**: set group colors and icons, including a new Materials & Lab section for lab work, material structures, characterization, and functional devices.
- **Multiple folders per project**: attach extra folders, choose the default root, and place sessions under the folder that matches their working directory.
- **Local and remote directories**: create folders in local workspaces and registered SSH remote workspaces without falling back to a local mirror when a remote operation fails.
- **Session tabs**: open, switch, pin, rename, reorder, and close tabs, including closing other tabs or tabs to the right.
- **Sidebar refinements**: keep the default workspace pinned at the bottom, align row metadata and actions consistently, and scroll long appearance dialogs.
- **Search and persistence**: search sessions without losing their group context and keep groups, ordering, tabs, and folder settings across refreshes and restarts.
<img src="screenshot.png" alt="dsh-workspace-groups workspace grouping manager" width="280" />
## Install
## Features
### Grouped tree browsing
- **Group folder → project folder → session row**, both levels collapsible; expansion state
persists independently (`dsh.workspace.groups.view.v1`, survives refresh/restart)
- **Top-level project rows**: ungrouped projects (matching no rule, dragged out of a group,
or returned by a group delete) render as plain rows right after the group folders, at the
same level — **there is no "未分类" bucket**
### Group management (full lifecycle)
- **Create groups manually**: the "新建分组" button in the section header shows the group
immediately (empty groups render too)
- **Rename / delete any group**: every group row (**rule categories included**) has a hover
`⋯` menu; deleting a group sends all of its projects back to the **top level**;
rule-category rename/delete rides the overlay (`renamed` / `hidden`),
**the rule YAML stays untouched**
- **Rule-based auto-classification**: the sidecar YAML declares category rules (`pathPrefix` /
`pathExact` / `nameContains` / `basenameContains`); edit the config to adjust grouping
without touching code
### Drag-and-drop grouping + ordering
- **Drag projects into groups**: drop on any group row or on a project row inside a group
(cross-group move = overrides the rule classification)
- **Drag projects OUT of a group**: the **entire top-level area** is the move-out drop
target while dragging, shown with an **insertion line** (not a highlight box) — drop on
any top-level row (reorder before/after it), on the blank space below the last row
(append), or, when the top level is empty, a standalone line under the last group
folder; grouped projects also have a "移出分组" menu item (rule-classified ones included)
- **Reorder projects inside a group**: top half of a project row = insert before it,
bottom half = insert after it
- **Reorder top-level projects**: top-level rows are draggable too — top half = insert
before, bottom half = insert after; the top-level order persists under
`workspaceOrder["__topLevel__"]`
- **Reorder groups**: group rows are draggable — top half of another group row = move before it,
bottom half = move after it
- **Insertion position indicator**: a 2px line (above/below the row) shows the exact drop
point while dragging — what you see is where it lands
- **Level-aware folding, auto-restored**: dragging a project folds every project row
(grouped AND top-level; group rows stay expanded); dragging a group folds every group
(project rows keep their expansion) — dragend restores the pre-drag expansion snapshot
- **Distinct row icons**: group rows use a folder glyph, project rows a project glyph
(same as the official workspace browser) — groups and projects are easy to tell apart
### Group appearance (color / icon / pin)
- **Per-group colour**: ten palette accents, painted as a 2px inset bar on the group row
together with a tinted folder glyph
- **Per-group icon**: twenty built-in glyphs taken from the DSH icon set, or a 1–4 character
custom glyph (emoji or latin) — an unknown value falls back to the folder icon instead of
erroring, so data and client versions can move independently
- **Pin groups**: pinned groups sort to the front of the tree; dragging a group across the pin
boundary re-pins it in the same write, so the drop lands where the indicator showed it
- **Animated folding**: expanding/collapsing a group or project animates rows and hides the
flower marker while they move, so the bloom never lags behind its row; animation is
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
- **Unified Create folder**: enter one child name in either workspace type. Local workspaces
call DSH `uiWorkspace.createDirectory`; registered SSH mirrors call the SSH-owned
`/remote-ssh/api/mkdir` with the profile and mapped remote path. SSH is optional for local use.
Remote mkdir is recursive/idempotent (existing remote directories are reused), unlike the
native local operation. Failures do not fall back to creating local mirror directories.
- SSH recognition uses `listWorkspaces`, including non-default mirror locations. A missing
plugin or unregistered default mirror fails closed; malformed catalogs and overlapping roots
are rejected. The existing local folder picker remains available for attaching local folders.
- **SSH subdirectory sessions are not fully supported by remote-ssh 2.4.40**. Creation is
blocked with an explanation; open a session at the registered remote workspace root instead.
A separate remote root should be registered through the SSH plugin. Folder creation itself
does not create or change any SSH registration.
- **No child `.remote-ssh.json` is written**. The old marker POST returns 410. Child markers do
not establish model-tool context and can bypass parent write-back exclusions. Previously
created markers are NOT automatically deleted; review them before using old subdirectory
sessions. Root SSH markers remain owned by the SSH plugin.
- Verification uses mocked APIs plus host route fixtures; live SSH/terminal/UI behavior still
requires an integration test before publishing.
### Search & operations
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
session), matched rows highlighted with a content snippet, 250ms debounce
- **No regression on workspace/session actions**: Add Workspace, project rename/delete,
session new/open/rename/fork/archive
### Persistence & zero intrusion
- 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`), 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
- **Self-contained artifact**: `lib/` is prebuilt and shipped with the repo — installing from
Git runs no dependency scripts
## How it works
- The plugin is a **client plugin** registered into the official sidebar shell's
`sidebar.workspaces` slot (`kind: 'single'`) at `priority: -1`, replacing the official
WorkspaceBrowser (registered at priority 0; lowest priority wins in a single slot).
- All data comes from the runtime API: the `useWorkspaces` / `useSessions` global hooks and
`ctx.workspaces.*` / `ctx.sessions.*` — grouping is purely a **presentation-layer transform**.
- The host half does two things: parses the sidecar YAML and merges it with the runtime
overlay, served to the client via `GET /workspace-groups/config` (`Cache-Control: no-cache`);
and `PUT /workspace-groups/manual` accepts the full overlay (manual groups, per-workspace
grouping overrides, group/project ordering, rule-category renames and hides), validates it
and writes it atomically to `$DSH_HOME/workspace-groups.manual.json`.
- **Classification priority**: manual override (written by drag/menu; `null` = forced
top-level, rules ignored) → YAML rule classification (hidden rule categories are inert)
→ **top level** (ungrouped projects render as top-level rows). The YAML is never
rewritten.
## Install (GitHub distribution)
> Prerequisite: [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
> installed (`dsh` available) with a target profile initialized (e.g. the built-in `web`).
For the Desktop profile:
```sh
dsh plugin --profile web add github:newbieQQ/dsh-better-workspace-group
dsh plugin --profile desktop add github:newbieQQ/dsh-better-workspace-group
```
This automatically:
For Web, replace `desktop` with `web`. Fully restart DSH or the corresponding Web profile after installation.
1. Adds `"workspace-groups-local": "github:newbieQQ/dsh-better-workspace-group"` (pinned to
version/commit) to `dependencies` in `~/.dsh/profiles/web/package.json`
2. Appends `"workspace-groups-local"` to `dsh.profile.bundles`
3. Runs pnpm install and validates the bundle layer
## Basic use
**Restart the web profile after installing** (both the bundle and the host half only load
on restart):
1. Click **New Group** in the workspace header, then drag projects into it.
2. Use the `⋯` menu on a project or group to manage grouping, appearance, and folders.
3. Open **Folders…** on a project to attach folders or choose its default root.
```sh
# Stop the running dsh web process and start it again, e.g.:
dsh web
```
Verify the install:
```sh
dsh --profile web --dump-config | grep -A3 workspace-groups
# expect: - id: workspace-groups / name: workspace-groups-local / config: {}
curl http://127.0.0.1:3080/workspace-groups/config
# expect: the sidecar YAML parsed as JSON
```
For automatic grouping by path or name, see [workspace-groups.example.yaml](./workspace-groups.example.yaml) and configure `~/.dsh/workspace-groups.yaml`. Manual grouping works without this file.
## Uninstall
```sh
dsh plugin --profile web remove workspace-groups-local
dsh plugin --profile desktop remove workspace-groups-local
```
This removes the dependency from `dependencies` and the matching line from
`dsh.profile.bundles`. A **web profile restart** is required for it to take effect.
## Credit and license
> Manual equivalent (pick one, don't repeat): edit `~/.dsh/profiles/web/package.json`,
> remove the `dsh-workspace-groups` line from `dependencies` and `"dsh-workspace-groups"`
> from `dsh.profile.bundles`, then run `pnpm install` in that directory.
The original project was created by [zcol](https://github.com/z-col) under the MIT License. This fork adds Materials & Lab icons, the bottom default-workspace bar, consistent row actions, remote-workspace folders, and other refinements.
## Classification config (sidecar)
Default location `~/.dsh/workspace-groups.yaml` (override the home dir with the
`$DSH_HOME` env var). Template: `workspace-groups.example.yaml` at the repo root.
```yaml
categories:
- name: DSH 插件
rules:
- pathPrefix: /Users/zcol/Project/SkillsManagePlugins
- nameContains: 插件
- basenameContains: plugin
- name: 个人项目
rules:
- pathPrefix: /Users/zcol/Project/yeluzi
```
Rule fields (each rule is an OR — any match classifies; categories are matched in order,
first match wins):
| Field | Meaning |
|---|---|
| `pathPrefix` | Project absolute path prefix |
| `pathExact` | Project absolute path exact match |
| `nameContains` | Project display title contains (case-insensitive) |
| `basenameContains` | Project directory name contains (case-insensitive) |
Projects matching no category — or moved out of a group — render as **top-level project
rows** (same level as the group folders), never hidden.
## Manual groups & drag-and-drop grouping (runtime overlay)
Besides the rule YAML there is a plugin-owned runtime overlay, **recording only manual
UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/workspace-groups.manual.json`):
```json
{
"categories": ["临时", "归档"],
"assignments": {
"a1b2c3d4-e5f6-7890-abcd-ef1234567890": "临时",
"a1b2c3d4-e5f6-7890-abcd-ef1234567891": null
},
"categoryOrder": ["临时", "DSH 插件"],
"workspaceOrder": { "临时": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"] },
"renamed": { "DSH 插件": "插件集" },
"hidden": ["文档"],
"appearance": {
"插件集": { "color": "blue", "icon": "code", "pinned": true },
"临时": { "color": "amber" }
}
}
```
- `categories` — manually created group names (no rules; empty groups render too).
- `assignments` — workspace → group classification overrides keyed by the stable workspace id
(renames don't affect it). **Takes precedence over YAML rules**; a value of `null` means
**forced top-level** (even when a rule would match).
- `categoryOrder` — group display order (top-level rows are not listed here; they always
render after the group folders).
- `workspaceOrder` — per-group manual ordering of projects (written by drag ordering).
- `renamed` / `hidden` — UI rename/delete of rule categories (a hidden category's rules become
inert and its matches go top-level); the rule YAML stays untouched.
- `appearance` — per-group presentation keyed by **display name** (same key space as
`categoryOrder`): `color` (one of `red`/`orange`/`amber`/`green`/`teal`/`blue`/`indigo`/
`purple`/`pink`/`gray`), `icon` (a built-in icon id or a 1–4 character glyph) and
`pinned` (sort before unpinned groups). Every sub-field is optional and empty values are
dropped on write, so un-styling a group removes the entry instead of storing `false`/`''`.
A key whose category no longer exists is **tolerated on read and on write** — otherwise
deleting one YAML category would make every later save fail with 400. Colours/icons live
here only: `parseGroupsConfig` drops unknown YAML keys, so a `color:` in the sidecar is
silently ignored.
- **Downgrade note**: an older build rewrites the whole overlay and would drop the
`appearance` map on its next save (same class of risk as `categoryOrder`). Copy
`workspace-groups.manual.json` aside before rolling the plugin back.
- The file is written in full by the browser UI (`PUT /workspace-groups/manual`, atomic
replace); manual edits also take effect on next load. A malformed write returns 400 and
keeps the previous file — the rule YAML is never at risk.
| Action | How |
|---|---|
| Create group | "新建分组" button in the section header (folder icon), enter a name in the dialog |
| Rename/delete group | hover `⋯` menu on **any** group (rule categories included); deleting sends its projects back to the top level |
| Style a group | `⋯` menu → "颜色与图标…": colour palette, icon grid and a custom-glyph field; every click is written immediately (no OK button) |
| Pin a group | `⋯` menu → "置顶分组" / "取消置顶"; dragging a group across the pin boundary flips it in the same write |
| Drag project into group | drag a project row onto a target group row / any project row inside a group, release to move |
| Reorder projects | drag a project row onto another project row in the same group: **top half = insert before, bottom half = insert after** (indicator shows the spot); all project rows fold while dragging and restore on dragend |
| Reorder top-level projects | drag a top-level row onto another top-level row: **top half = insert before, bottom half = insert after**; order persists under `workspaceOrder["__topLevel__"]` |
| Move out of a group | drop anywhere on the **top-level area** (an insertion line shows the spot — reorder before/after a top-level row, or append below the last row; when the top level is empty a line shows under the last group), or the project row's "移出分组" menu (forced top-level) |
| Reorder groups | drag a group row onto another group row: **top half = move before, bottom half = move after** (indicator shows the spot; all groups fold while dragging, restored on dragend) |
## Session tabs (tab strip)
A horizontal tab strip is seated above the tree — one chip per session you have opened, each
showing its project name and tab label:
- **Open / activate / close**: opening a session adds a chip at the end of the strip; click a
chip to make that session the open one; the `×` closes it.
- **Middle-click** a chip to close it; **drag** a chip to reorder the strip. Pinned chips stay
in the leading pinned block, and a drag never crosses that boundary.
- **Rename a tab**: double-click a chip to give the tab its own label (blank restores the
session title). Renaming the session itself stays in the context menu, so a tab label never
rewrites the session title.
- **Context menu**: pin/unpin, rename tab, rename session, close, **close others** and
**close tabs to the right**. "Close others" always keeps pinned chips.
- **Persisted**: the strip is stored in `$DSH_HOME/workspace-groups.tabs.json` via the host
routes `GET/PUT /workspace-groups/tabs`. A strip stored by an older build (no pin/label
fields) upgrades transparently — absent fields simply read as "unpinned, no custom label".
## Topics
This repo targets automatic discovery by the DSH plugin ecosystem (community marketplaces
scan GitHub topics). Already set:
- `dsh-plugin` (core tag; [1024Store](https://github.com/imsai-sh/awesome-deepseek-harness-plugins)
and similar marketplaces discover by this topic periodically, validating
`package.json` + the plugin bundle manifest (`cordis.patch.yml`))
- `deepseek-harness` / `deepseek-harness-plugin` / `dsh`
- `sidebar` / `workspace` / `workspace-groups`
`package.json` also provides `keywords` for npm/search indexing.
## Development
```sh
pnpm install
pnpm typecheck # host + client dual-program type checking
pnpm test # core rules, overlay, tree derivation unit tests
pnpm build # build lib/ (node half + client bundle)
pnpm watch # tsdown watch (client HMR)
node scripts/verify-groups.mjs # real-browser CDP verification (host restarted; self-spawns a headless Chrome, auto-restores the scene)
```
Artifact contract (mirrors the official client packages):
- `lib/index.js` — host half (ESM; reads the sidecar + `/workspace-groups/config` route;
js-yaml inlined, no runtime dependencies)
- `lib/client.js` — browser half (`window.__ModuleLoader__.load({id, factory})`; only
requires platform seeds: react / react/jsx-runtime / @deepseek-ai/dsh-client-runtime/client /
@deepseek-ai/dsh-client-ui-primitives; cross-plugin value imports are rejected at build
time by the purity gate)
- `lib/types/**` — declaration files
> Release strategy: `lib/` build artifacts are committed (no `prepare` script), so
> `dsh plugin add github:...` never runs third-party build scripts — install and use.
## Repository layout
```
src/
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 + 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/
core.test.ts # classification rules + override priority + moveBefore/moveAfter + config parsing
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)
```
> Development docs (`docs/` five-level framework and `AGENTS.md`) are engineering files for
> development, **not shipped with the repo** (excluded via `.gitignore`).
## Verification record
- v0.1/v0.2 real-combination verification (headless Chrome + CDP): three-level tree takeover,
correct classification, expansion persistence, search keeps workspace membership;
`workspace.json` / session on-disk / official store: zero intrusion.
- v0.3 real-browser verification 24/24 (`scripts/verify-groups.mjs`: create group / drag /
order / collapse / rule-category menu / rename / delete-back-to-top-level /
scene restore; zero-intrusion assertions).
- v0.4 real-browser verification 30/30 (added: insertion indicator, project/group
**downward drag** (bottom half → insert after the target), group upward drag (top half →
move before the target); scene restored).
- v0.4.1 real-browser verification 34/34 (added: dragging projects OUT of a group —
top-level drop zone / top-level rows = forced top-level; grouped projects get the
"移出分组" menu item).
- v0.5 real-browser verification 35/35 (model change: **no "未分类" bucket** — top-level
project rows, group delete returns members to the top level, drag/menu move-out to the
top level, no uncategorized bucket anywhere in the tree; scene restored).
- v0.6 real-browser verification 40/40 (added: **level-aware folding** — dragging a project
folds project rows only (group rows stay open), dragging a group folds group rows only;
dragend restores the pre-drag expansion snapshot).
- v0.6.1 real-browser verification 42/42 (added: the whole top-level area as the move-out
drop target with a visible landing highlight; distinct folder-vs-project row icons;
scene restored).
- v0.7 real-browser verification 46/46 (added: top-level landing shown with an **insertion
line** instead of a highlight box — reorder before/after a top-level row, append below
the last row, or a standalone line when the top level is empty; **top-level projects are
reorderable** with their order persisted under `workspaceOrder["__topLevel__"]`; also
fixed a host validation bug that rejected `__topLevel__` and a drop-positioning bug where
dropping between two top-level rows landed above the first; scene restored).
- 66 unit tests green (vitest: `core` / `manual` / `tree` / `store`).
- Reproducible automated verification: `node scripts/verify-groups.mjs` (host restarted).
## Credit & upstream
This repository is a **fork** of [**z-col/dsh-workspace-groups**](https://github.com/z-col/dsh-workspace-groups),
created and maintained by [**zcol**](https://github.com/z-col) (297114876@qq.com), and released
under the MIT License. The three-level category → project → session tree, drag-and-drop grouping,
the sidecar YAML rules, the runtime overlay, the top-level ordering and the session tab strip are
the original author's design and implementation. This fork would not exist without that work —
thank you.
Upstream stays the canonical project: please report bugs that also exist there to the upstream
issue tracker, and treat this repository's history (`upstream` remote) as its origin.
Changes carried by this fork (on top of upstream `release: workspace-groups-local 1.0.0`):
- **Materials & lab icon section** in the appearance picker: 28 hand-drawn 16×16 line glyphs
(lab operations, material structures, characterization, functional devices) beside the existing
50 host icons and 16 emoji, with bilingual tooltips; old ids, custom short glyphs and the
"restore default" behaviour are untouched
- the **appearance dialog scrolls inside the host modal**, so the grown icon grid can never push
the "done" footer or the pin button out of reach, in either theme
- **one right-aligned trailing slot on every row kind**: the member count (or a session's relative
time) sits flush with the row's right edge and yields to the `+` / `⋯` buttons on hover or
keyboard focus without any reflow; every row orders them `+` then `⋯`
- the host **default workspace** is pinned to its own **bottom bar** (above it a rule, always
visible while the tree scrolls), keeps every workspace-row capability (expand, new session,
rename, delete, `⋯` menu, folder management, appearance), and is deduplicated out of groups,
the top level and search results — identified from host workspace data, never from a hardcoded
directory name alone
- `tools/verify-row-layout.mjs`: assertions over the stylesheet and the row markup, added because
vitest cannot start in the author's checkout (missing `@vitest/utils`, `std-env`)
## License
MIT — original work © 2026 zcol ([z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups));
modifications in this fork © 2026 newbieQQ. See [LICENSE](./LICENSE) and
[NOTICE.md](./NOTICE.md) for the full attribution and open-source statement.
Original work © 2026 zcol; modifications © 2026 newbieQQ. See [LICENSE](./LICENSE) and [NOTICE.md](./NOTICE.md).

View File

@ -4,391 +4,49 @@
# dsh-better-workspace-group
![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
![Fork of z-col/dsh-workspace-groups](https://img.shields.io/badge/fork-z--col%2Fdsh--workspace--groups-blueviolet.svg)
![DSH](https://img.shields.io/badge/DSH-0.1.1--rc.2-purple.svg)
<img src="https://img.shields.io/badge/DeepSeek%20Harness-plugin-202724" alt="DeepSeek Harness plugin">
DeepSeek Harness 工作区分组插件。基于 [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups) 二次开发,让工作区、文件夹和会话在侧栏里更容易整理和使用。
> **本仓库是 [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups) 的 fork。**
> 三层树、拖拽归类、sidecar 规则与会话标签栏均为原作者设计实现(MIT);本 fork 在其之上
> 增加了科研图标分区、固定在底部的默认工作区栏、以及统一的右侧尾槽——详见
> [鸣谢与上游](#鸣谢与上游)。
## 预览
> **DeepSeek Harness(DSH)Web 客户端插件:完整的工作区分组管理工具。**
> 把 GUI 侧边栏的工作区列表从两层「项目 → 会话」升级为三层
> **「分类文件夹 → 项目文件夹 → 会话」**,并围绕它提供完整的分组管理能力——
> 手动建组、重命名/删除分组、拖拽归类、项目与分组的自由排序、规则自动归类、
> 树形搜索。所有操作**即时生效并持久化**,对官方数据**零侵入**。
<img src="screenshot.png" alt="工作区分组插件预览" width="280" />
典型场景:多个 DSH 插件项目(SkillsManagePlugins / Documentation-Driven AI Coding /
DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点开是各项目,再点开是各自会话;
临时项目随手建个「临时」分组拖进去,用完删除分组,项目全部回归**顶层**。
## 已实现的功能
## 截图
- **工作区分组**:按「分组 → 项目 → 会话」浏览,支持新建、重命名、删除、折叠和置顶分组。
- **拖拽整理**:把项目拖入或移出分组,并调整分组、项目的显示顺序。
- **分组外观**:设置分组颜色和图标;新增「材料与实验」图标分区,包含实验操作、材料结构、表征测试和功能器件图标。
- **一个项目多个文件夹**:为项目添加额外文件夹、选择默认根目录,会话会按工作目录归入对应文件夹。
- **本地与远程目录**:本地工作区和已注册的 SSH 远程工作区都可以创建文件夹;远程操作失败时不会误建到本地镜像。
- **会话标签栏**:打开、切换、固定、重命名、拖动排序和关闭会话标签,支持关闭其他标签及右侧标签。
- **侧栏布局优化**:默认工作区固定在底部;各行的数量、时间和操作按钮统一右对齐;外观弹窗内容可滚动。
- **搜索与保存**:保留分组层级搜索会话,分组、排序、标签和文件夹设置都会保存,刷新或重启后仍然有效。
<img src="screenshot.png" alt="dsh-workspace-groups 工作区分组管理" width="280" />
## 安装
## 特性
### 分组树浏览
- **分组文件夹 → 项目文件夹 → 会话行**,分组/项目均可折叠;展开状态独立持久化
(`dsh.workspace.groups.view.v1`,刷新/重启保留)
- **顶层项目行**:不归组的项目(不匹配任何规则、被移出分组、删除分组后回归的)
直接显示在分组列表之后,与分组平级——**没有「未分类」桶**
### 分组管理(完整生命周期)
- **手动新建分组**:区头「新建分组」按钮即建即显,空分组也渲染
- **重命名 / 删除任意分组**:每个分组行(**含规则分类**)悬停 `⋯` 菜单;
删除分组后组内所有项目回到**顶层**;规则分类的改名/删除经 overlay 生效
(`renamed` / `hidden`),**规则 YAML 原样保留**
- **规则自动归类**:sidecar YAML 声明分类规则(`pathPrefix` / `pathExact` /
`nameContains` / `basenameContains`),改配置即可调整归类,无需改代码
### 拖拽归类 + 排序
- **拖项目进分组**:拖到任意分组行 / 分组内项目行即移入(跨组移动 = 覆盖规则归类)
- **从分组拖出**:拖动时**整个顶层区域都是移出落点**,用**插入横线**指示(非高亮框)——
拖到任意顶层项目行(插到它前/后)、拖到最后一行下方空白(追加末尾)、顶层为空时
在最后一个分组行下方显示独立横线 = 移出分组;分组内项目行的菜单「移出分组」
(规则归类项目也有)
- **项目组内排序**:拖到项目行上半 = 插到它前面、下半 = 插到它后面
- **顶层项目排序**:顶层项目行也可拖拽排序(上半 = 插到它前、下半 = 插到它后),
顺序持久化在 `workspaceOrder["__topLevel__"]`
- **分组排序**:分组行可拖动,拖到另一分组行上半 = 移到它前面、下半 = 移到它后面
- **插入位置指示线**:拖动中实时显示 2px 指示线(行上/下方),松手落点所见即所得
- **按级别收起 + 结束后恢复**:拖项目只收起项目行(分组内 + 顶层,分组行不收);
拖分组只收起分组行(项目行不收);dragend 自动恢复拖动前的展开状态
- **行图标可区分**:分组行是文件夹图标、项目行是项目符号图标(官方同款),
分组与项目一眼可分
### 分组外观(颜色 / 图标 / 置顶)
- **分组配色**:10 种主题色,在分组行左侧画 2px 内嵌色条,并把文件夹图标染色
- **分组图标**:20 个内置图标(取自 DSH 图标集),或 1–4 个字符的自定义字形(emoji/拉丁);
未知值降级为默认文件夹图标而不是报错,数据与客户端版本因此可以各自演进
- **置顶分组**:置顶分组排到树的最前面;把分组拖过置顶边界时会在同一次写入里翻转
置顶状态,落点就是指示线显示的位置
- **折叠动画**:展开/收起分组或项目时行高与透明度过渡,动画期间隐藏花朵标记,
花不会滞后于所在行;大树、拖动折叠中、`prefers-reduced-motion` 下自动跳过动画
- 存放在 overlay 的 `appearance` 里,**绝不写进规则 YAML**
### 一个工作区多个文件夹(multi-root)
- **给项目挂多个文件夹**:项目行的 `⋯` 菜单里点 **文件夹…**,弹窗第一行是项目自带的
目录(**基础文件夹**,永远是 #0,不可移除),下面是你自己加的额外文件夹
- **每个项目一个根目录**:弹窗里的单选列,或文件夹行的 `⋯ → 设为根目录`,决定“新建会话”
默认落在哪个文件夹;根目录那一行会被提到最前面并带 ★ 标记
- **会话按自己的 cwd 归位**:项目一旦有额外文件夹,会话上方会多出文件夹行,每条会话按
自己记录的 cwd 落进所属文件夹(最具体的文件夹优先,Windows 下大小写不敏感);没有额外
文件夹的项目保持原来的两层扁平结构,行为完全不变
- **在指定文件夹里开会话**:文件夹行悬停的 `+` 会以该文件夹为 cwd 新建会话;基础文件夹
沿用平台自己的“新建会话”手势,连点两次会复用已打开的空白会话,而不是堆一堆空会话
- 文件夹默认展开,挂上新文件夹不会把本来能看到的会话藏起来;折叠状态只是当前视图状态,
故意不持久化
- **统一“创建文件夹”**:输入一个子目录名,本地调用 DSH 原生 `uiWorkspace.createDirectory`;
已注册的远程镜像调用 SSH 专属 `/remote-ssh/api/mkdir`,传连接 ID 和映射后的远端路径。
本地功能不依赖 SSH 插件。远端接口为 `mkdir -p`,同名目录存在时复用;本地沿用原生行为。
SSH 不可用或请求失败时绝不降级为镜像里的本地创建。普通本地目录仍可用“添加文件夹”选取。
- 通过 SSH 的 `listWorkspaces` 识别已注册镜像,支持非默认镜像位置;重叠注册根、坏响应、
未注册的默认镜像路径会报错。此功能不另建 SSH 工作区,也不改动它的连接配置。
- **remote-ssh 2.4.40 不完整支持子目录会话**:新建此类会话暂时阻断并提示从注册的远程工作区根
打开。创建远端文件夹本身不受此限制;另一个远端根请通过 SSH 插件注册。
- **不再复制 `.remote-ssh.json` 到子目录**,旧 POST 接口返回 410。复制标记不能修复模型工具
上下文,还可能绕过父工作区写回限制。历史子目录标记不会自动删除,应审查后再使用旧会话;
工作区根标记仍由 SSH 插件管理。此前“子标记永远不会同步”的说明不成立,已撤回。
- 自动验证使用模拟 API 和临时目录;真实 SSH、终端和界面尚需发布前联调。
### 搜索与操作
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
内容摘要,防抖 250ms
- **工作区/会话操作不退化**:Add Workspace、项目重命名/删除、新建/打开/重命名/
派生/归档会话
### 持久化与零侵入
- 所有手动操作(分组、归类、排序、改名、隐藏)写入插件自有 overlay
(`~/.dsh/workspace-groups.manual.json`),host 校验后**原子写入**(写坏返回 400 并
保留原文件);标签栏同样处理,独立文件 `~/.dsh/workspace-groups.tabs.json`;项目的
额外文件夹与根目录选择也一样,独立文件 `~/.dsh/workspace-groups.folders.json`
(写时严格、读时宽容 —— 不认识的文件夹直接丢弃,不会把树弄坏)
- **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、不修改官方
`@deepseek-ai/dsh-client-ui-workspace` 包;规则 YAML 永不改写
- **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本
## 工作原理
- 本插件是 **client 插件**,注册进官方 sidebar shell 声明的 `sidebar.workspaces`
slot(`kind: 'single'`),以 `priority: -1` 顶替官方默认 WorkspaceBrowser
(官方以 priority 0 注册;single 槽位最低 priority 胜出)。
- 数据源全部复用运行时 API:`useWorkspaces` / `useSessions` 全局 hooks 与
`ctx.workspaces.*` / `ctx.sessions.*`,分类只是**展示层变换**。
- host 半做两件事:把 sidecar YAML 解析为 JSON 与运行时 overlay 合并,经
`GET /workspace-groups/config` 路由(`Cache-Control: no-cache`)供 client 获取;
`PUT /workspace-groups/manual` 接收整份 overlay(手动分组、每工作区归类覆盖、
分组/项目排序、规则分类改名与隐藏),校验后原子写入
`$DSH_HOME/workspace-groups.manual.json`。
- **归类优先级**:手动覆盖(拖拽/菜单写入;`null` = 强制顶层、规则匹配也无效)→
YAML 规则自动归类(被隐藏的规则分类失效)→ **顶层**(不归组的项目显示为顶层行)。
YAML 永不改写。
## 安装(GitHub 分发)
> 前置:已安装 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
> (`dsh` 命令可用),并已初始化好目标 profile(如内置 `web`)。
Desktop 环境:
```sh
dsh plugin --profile web add github:newbieQQ/dsh-better-workspace-group
dsh plugin --profile desktop add github:newbieQQ/dsh-better-workspace-group
```
这会自动:
Web 环境将 `desktop` 改为 `web`。安装完成后,完全重启 DSH 或对应的 Web profile。
1. 在 `~/.dsh/profiles/web/package.json` 的 `dependencies` 加入
`"workspace-groups-local": "github:newbieQQ/dsh-better-workspace-group"`(含版本/commit)
2. 在 `dsh.profile.bundles` 末尾追加 `"workspace-groups-local"`
3. 运行 pnpm 安装并校验 bundle 层
## 基本使用
**安装后重启 web profile**(bundle 与 host 半只有在重启后才会被加载):
1. 点击工作区标题栏的「新建分组」,再把项目拖进去。
2. 在项目或分组的 `⋯` 菜单中管理分组、外观和文件夹。
3. 在项目的「文件夹…」弹窗中添加文件夹或选择默认根目录。
```sh
# 停止现有 dsh web 进程后重新启动,例如:
dsh web
```
验证安装:
```sh
dsh --profile web --dump-config | grep -A3 workspace-groups
# 应出现 - id: workspace-groups / name: workspace-groups-local / config: {}
curl http://127.0.0.1:3080/workspace-groups/config
# 应返回 sidecar YAML 解析后的 JSON
```
需要按路径或名称自动分组时,可参考 [workspace-groups.example.yaml](./workspace-groups.example.yaml) 配置 `~/.dsh/workspace-groups.yaml`。不配置也不影响手动分组。
## 卸载
```sh
dsh plugin --profile web remove workspace-groups-local
dsh plugin --profile desktop remove workspace-groups-local
```
这会自动从 `dependencies` 删除该依赖并从 `dsh.profile.bundles` 移除对应行。
同样需要**重启 web profile** 后生效。
## 致谢与许可
> 手动等价做法(任选其一,不要重复):编辑 `~/.dsh/profiles/web/package.json`,
> 从 `dependencies` 删除 `workspace-groups-local` 行、从 `dsh.profile.bundles`
> 删除 `"workspace-groups-local"`,然后在该目录 `pnpm install`。
原项目由 [zcol](https://github.com/z-col) 开发并以 MIT 许可发布。本仓库在其基础上增加了材料与实验图标、底部默认工作区、统一行尾布局、远程工作区文件夹等功能。
## 分类配置(sidecar)
默认位置 `~/.dsh/workspace-groups.yaml`(也可用 `$DSH_HOME` 环境变量覆盖家目录)。
模板见仓库根目录 `workspace-groups.example.yaml`。
```yaml
categories:
- name: DSH 插件
rules:
- pathPrefix: /Users/zcol/Project/SkillsManagePlugins
- nameContains: 插件
- basenameContains: plugin
- name: 个人项目
rules:
- pathPrefix: /Users/zcol/Project/yeluzi
```
规则字段(每个 rule 是 OR 关系,任一命中即归类;分类按序匹配,先到先得):
| 字段 | 含义 |
|---|---|
| `pathPrefix` | 项目绝对路径前缀 |
| `pathExact` | 项目绝对路径精确匹配 |
| `nameContains` | 项目显示标题包含(忽略大小写) |
| `basenameContains` | 项目目录名包含(忽略大小写) |
未命中任何分类、或被移出分组的项目显示为**顶层项目行**(与分组平级),不会被隐藏。
## 手动分组与拖拽归类(runtime overlay)
规则 YAML 之外,还有一份插件自有的运行时 overlay,**只记录 UI 里的手动操作**,
默认位置 `$DSH_HOME/workspace-groups.manual.json`(例如 `~/.dsh/workspace-groups.manual.json`):
```json
{
"categories": ["临时", "归档"],
"assignments": {
"a1b2c3d4-e5f6-7890-abcd-ef1234567890": "临时",
"a1b2c3d4-e5f6-7890-abcd-ef1234567891": null
},
"categoryOrder": ["临时", "DSH 插件"],
"workspaceOrder": { "临时": ["a1b2c3d4-e5f6-7890-abcd-ef1234567890"] },
"renamed": { "DSH 插件": "插件集" },
"hidden": ["文档"],
"appearance": {
"插件集": { "color": "blue", "icon": "code", "pinned": true },
"临时": { "color": "amber" }
}
}
```
- `categories` —— 手动新建的分组名(无规则,空分组也渲染)。
- `assignments` —— 工作区 → 分组的归类覆盖,键是稳定的工作区 id(重命名不影响)。
**优先级高于 YAML 规则**;值为 `null` 表示**强制移到顶层**(即使规则能匹配)。
- `categoryOrder` —— 分组显示顺序(顶层项目不在此列,恒显示在分组之后)。
- `workspaceOrder` —— 每个分组内项目的手动排序(拖拽排序写入)。
- `renamed` / `hidden` —— 规则分类的 UI 改名/删除(隐藏后其规则失效,匹配项目
变顶层);规则 YAML 原样保留。
- `appearance` —— 按**显示名**(与 `categoryOrder` 同一键空间)记录分组外观:
`color`(`red`/`orange`/`amber`/`green`/`teal`/`blue`/`indigo`/`purple`/`pink`/`gray`)、
`icon`(内置图标 id 或 1–4 个字符的字形)、`pinned`(排到未置顶分组之前)。三个字段
都可选,写回时会把空值删掉,所以「取消设置」表现为字段消失,而不是存 `false`/`''`。
指向**已不存在分类**的键在读写两侧都被容忍——否则删掉一条 YAML 分类后每次保存都会
400。**颜色/图标只存在这里**:`parseGroupsConfig` 会丢弃 YAML 的未知键,所以在
sidecar 里写 `color:` 会被静默忽略。
- **降级提醒**:旧版本会整文件覆盖 overlay,下一次保存就会丢掉 `appearance`
(与 `categoryOrder` 同级别风险)。回退插件版本前请先备份
`workspace-groups.manual.json`。
- 文件由浏览器 UI 全量写入(`PUT /workspace-groups/manual`,原子替换),手工编辑
同样生效(下次加载时读取);写坏会返回 400 并保留原文件,不会破坏规则 YAML。
| 操作 | 入口 |
|---|---|
| 新建分组 | 区头「新建分组」按钮(文件夹图标),弹窗输入名称 |
| 重命名/删除分组 | **任意分组**(含规则分类)悬停 `⋯` 菜单;删除后组内项目回顶层 |
| 设置分组外观 | `⋯` 菜单「颜色与图标…」:色板、图标网格、自定义字形;每次点击立即写入(没有「确定」按钮) |
| 置顶分组 | `⋯` 菜单「置顶分组」/「取消置顶」;把分组拖过置顶边界时会在同一次写入里自动翻转 |
| 拖项目进分组 | 拖动项目行到目标分组行 / 分组内任意项目行,松手即移入 |
| 项目排序 | 拖动项目行到同组另一项目行:**上半 = 插到它前、下半 = 插到它后**(指示线显示落点);拖动时所有项目行收起、dragend 恢复 |
| 顶层排序 | 拖动顶层项目行到另一顶层行:**上半 = 插到它前、下半 = 插到它后**;顺序持久化 `workspaceOrder["__topLevel__"]` |
| 移出分组 | 拖到**顶层区域任意位置**(用插入横线指示落点——拖到顶层行前/后、最后一行下方追加、顶层为空时最后分组行下方独立横线),或项目行菜单「移出分组」(强制移到顶层) |
| 分组排序 | 拖动分组行到另一分组行:**上半 = 移到它前、下半 = 移到它后**(指示线显示落点;拖动时所有分组收起、dragend 恢复) |
## 会话标签栏(tab strip)
侧栏树上方常驻一条横向标签栏,每个「打开过的会话」对应一个标签,显示项目名 + 标签名:
- **打开 / 切换 / 关闭**:打开一个会话即在标签栏尾部新增一个标签;点击标签切换会话,
点击 `×` 关闭该标签。
- **中键单击**标签直接关闭;**拖动**标签可调整顺序。固定标签始终留在前部的固定区,
拖动不会跨越该边界。
- **重命名标签**:双击标签即可给标签单独起名(留空恢复为会话标题)。真正的会话改名
仍在右键菜单里,标签名不会改写会话标题。
- **右键菜单**:固定/取消固定、重命名标签、重命名会话、关闭、**关闭其他标签**、
**关闭右侧标签**。「关闭其他标签」始终保留已固定的标签。
- **持久化**:标签栏写入 `$DSH_HOME/workspace-groups.tabs.json`,走宿主路由
`GET/PUT /workspace-groups/tabs`;旧版本写下的标签栏(没有固定/自定义名
字段)可无缝升级——缺字段按「未固定、无自定义名」读取。
## 收录标签(topics)
本仓库面向 DSH 插件生态的自动收录(社区市场靠 GitHub topic 扫描发现),已设置:
- `dsh-plugin`(核心标签,[1024Store](https://github.com/imsai-sh/awesome-deepseek-harness-plugins)
等市场定时按此 topic 自动发现,并校验 `package.json` + 插件 bundle 清单
(`cordis.patch.yml`))
- `deepseek-harness` / `deepseek-harness-plugin` / `dsh`
- `sidebar` / `workspace` / `workspace-groups`
`package.json` 同时提供 `keywords` 便于 npm/搜索索引。
## 开发
```sh
pnpm install
pnpm typecheck # host + client 双 program 类型检查
pnpm test # 核心规则、overlay、树派生单测
pnpm build # 构建 lib/(node 半 + client bundle)
pnpm watch # tsdown 监听(client HMR)
node scripts/verify-groups.mjs # 真机 CDP 验证(host 已重启时;自启独立 headless Chrome,自动恢复现场)
```
产物契约(与官方 client 包一致):
- `lib/index.js` —— host 半(ESM;读取 sidecar + `/workspace-groups/config` 路由,
js-yaml 已内联,无运行时依赖)
- `lib/client.js` —— browser 半(`window.__ModuleLoader__.load({id, factory})`;
仅 require 平台 seed:react / react/jsx-runtime / @deepseek-ai/dsh-client-runtime/client /
@deepseek-ai/dsh-client-ui-primitives;跨插件值 import 在构建期被 purity 门拒绝)
- `lib/types/**` —— 声明文件
> 发布策略说明:`lib/` 构建产物随仓库提交(无 `prepare` 脚本),因此
> `dsh plugin add github:...` 全程无需执行第三方构建脚本,安装即用。
## 目录结构
```
src/
index.ts # host 半:config 快照路由 + manual 写路由
host-config.ts # sidecar YAML 读取/校验
host-manual.ts # runtime overlay 读写/校验(原子发布)
context-types.ts # host 侧 cordis 服务结构类型
core/
types.ts # 配置类型(两半共享)
matcher.ts # 分类规则 + 手动覆盖优先级 + 排序纯函数(两半共享)
client/
index.ts # apply:注册 sidebar.workspaces(priority -1)
contract.ts # 注入面类型
stores.ts # 展开状态 store(persist: dsh.workspace.groups.view.v1)
tree.ts # 三层树派生 + 树形搜索派生
GroupsBrowser.tsx # 浏览区域组件(分组弹窗 + 拖拽归类/排序 + 插入指示线)
rows.tsx # 分类/项目/会话/搜索结果行(拖拽源/目标)
locales.ts # 中英文案
styles.css # 内联样式
tests/
core.test.ts # 分类规则 + 手动覆盖优先级 + moveBefore/moveAfter + 配置解析
manual.test.ts # overlay 校验 + 文件原子往返
tree.test.ts # 树派生渲染契约(手动分组空渲染/覆盖优先)
store.test.ts # 展开状态语义(折叠写 false 不删 key)
scripts/
verify-groups.mjs # 真机 CDP 验证(自启 headless Chrome,自动恢复现场)
```
> 开发文档(`docs/` 五级框架与 `AGENTS.md`)是开发用工程文件,**不随仓库分发**
> (已在 `.gitignore` 排除)。
## 验证记录
- v0.1/v0.2 真实组合验证(headless Chrome + CDP 实操):三层树顶替生效、分类正确、
展开持久化、搜索保留归属;`workspace.json` / 会话落盘 / 官方 store 零侵入。
- v0.3 真机验证 24/24(`scripts/verify-groups.mjs`:建组/拖拽/排序/收起/规则分类
菜单/重命名/删除回顶层/现场恢复,零侵入断言)。
- v0.4 真机验证 30/30(新增:插入指示线、项目/分组**向下拖**(行下半 → 插到目标
之后)、分组向上拖(行上半 → 移到目标之前);现场恢复通过)。
- v0.4.1 真机验证 34/34(新增:**从分组拖出**——顶层落点区/顶层行 drop =
强制顶层;分组内项目行菜单「移出分组」)。
- v0.5 真机验证 35/35(模型变更:**无「未分类」桶**——顶层项目行、删除分组成员
回顶层、拖拽/菜单移出到顶层、树中不存在未分类桶;现场恢复)。
- v0.6 真机验证 40/40(新增:**按级别收起**——拖项目只收起项目行(分组行不收)、
拖分组只收起分组行(项目行不收);dragend 还原拖动前展开快照)。
- v0.6.1 真机验证 42/42(新增:**整个顶层区域为移出落点**且拖拽中有可见高亮提示;
分组/项目行图标区分;现场恢复)。
- v0.7 真机验证 46/46(新增:顶层落点改用**插入横线**(非高亮框)——拖到顶层行前/后、
最后一行下方追加、顶层为空时独立横线;**顶层项目可排序**,顺序持久化
`workspaceOrder["__topLevel__"]`;并修复 host 校验拒绝 `__topLevel__` 与
「拖到两行之间却落在上一行上面」的落点定位 bug;现场恢复)。
- 单测 66 用例全绿(vitest:`core` / `manual` / `tree` / `store`)。
- 可复跑的自动化真机验证:`node scripts/verify-groups.mjs`(需 host 已重启)。
## 鸣谢与上游
本仓库是 [**z-col/dsh-workspace-groups**](https://github.com/z-col/dsh-workspace-groups) 的
**fork**,原作者为 [**zcol**](https://github.com/z-col)(297114876@qq.com),以 MIT 许可发布。
三层「分类 → 项目 → 会话」树、拖拽归类、sidecar YAML 规则、runtime overlay、顶层排序与
会话标签栏,均出自原作者的设计与实现——没有这些工作就没有本仓库,在此致谢。
上游仍是本项目的正源:若某个问题在上游同样存在,请提交到上游仓库的 issue tracker;
本仓库以 `upstream` remote 指向它作为来源。
本 fork 在上游 `release: workspace-groups-local 1.0.0` 之上新增/调整的内容:
- 外观弹窗新增 **「材料与实验」图标分区**:28 个统一规格的 16×16 手绘线条字形
(实验操作、材料结构、表征测试、功能器件),与原有 50 个宿主图标、16 个 Emoji 并列,
带中英双语悬停提示;旧图标 ID、自定义短字形与「恢复默认」行为完全不变
- **外观弹窗在宿主 Modal 内滚动**:图标区变大后既不会把「完成」按钮挤出视野,也不会让
默认图标输入框的聚焦边框贴住「置顶分组」按钮,浅/深主题一致
- **所有行统一一个右对齐尾槽**:成员数(会话行则是相对时间)贴着行右边界,悬停或键盘
聚焦时让位给「+」「⋯」按钮,零重排;每行都按「+」在前、「⋯」在后排列
- 宿主的**默认工作区被固定在侧栏底部独立一栏**(上方分隔线,树滚动时始终可见),保留
工作区行的全部能力(展开、新建会话、重命名、删除、`⋯` 菜单、文件夹管理、外观入口),
并从分组、顶层与搜索结果中去除重复——识别依据来自宿主工作区数据,而不是只认目录名
- `tools/verify-row-layout.mjs`:针对样式表与行结构的断言;因为作者本机的 vitest 缺
`@vitest/utils`、`std-env` 无法启动,改用零依赖脚本做等价验证
## License
MIT——原始作品 © 2026 zcol([z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups));
本 fork 的修改 © 2026 newbieQQ。完整的署名与开源声明见 [LICENSE](./LICENSE) 与
[NOTICE.md](./NOTICE.md)。
原始作品 © 2026 zcol;本仓库修改 © 2026 newbieQQ。详见 [LICENSE](./LICENSE) 和 [NOTICE.md](./NOTICE.md)。

View File

@ -0,0 +1,350 @@
# 内置 SSH 与远程文件夹实施方案(审阅稿)
日期:2026-11-03
仓库:`dsh-workspace-groups`(`workspace-groups-local@1.3.0`)
目标:不再把 `@zhangfengshun/dsh-remote-ssh` 作为运行依赖,由本插件自己提供 SSH 连接、远程目录、远程文件夹工作区和文件/终端能力。
---
## 0. 结论先行
1. **传输层用系统 OpenSSH,不自写 SSH 协议。** 继续用 `ssh` / `sftp` 这套已验证的客户端,保留 `~/.ssh/config`、ProxyJump、known_hosts、密钥代理、老 HPC 算法和 2FA 兼容性;插件自己负责连接管理、文件操作、镜像工作区和 UI。这样“内置”指**不依赖 Remote-SSH 插件**,不是“不依赖系统 ssh”。
2. **远程文件夹仍然使用 mirror-backed 原生 Workspace。** 浏览器只看到本地镜像路径,Host 用 `.workspace-groups-remote.json` 把它映射到远端;原生 Workspace 身份和已有会话不重建。
3. **先做可替换的最小闭环,再补完整工具面。** 先完成“连接配置 → 远程选目录 → 建远程文件夹 → 重启后仍可用 → 删除/迁移”,再接文件写回、终端、exec、glob/grep、同步。不要一开始就重写 13 个工具。
> 关键限制先说清楚:DSH 的通用 bash/终端执行仍以本地 Workspace 的 `cwd` 为准。内置 SSH 能做到“远程文件夹 + 显式远程工具 + 远程终端”,**不能仅靠插件让 Agent 的所有 bash 命令在 HPC 上执行**;后者需要 DSH 平台提供远程执行层。若你的预期是后者,这份方案的边界需要先扩大。
---
## 1. 目标与非目标
### 1.1 目标
- 卸载 `@zhangfengshun/dsh-remote-ssh` 后,分组、文件夹、远程目录选择、远程工作区创建仍可用。
- Host 端持有 SSH 配置、密钥路径、连接池、超时/重连、SFTP/命令执行;浏览器端不接触私钥内容和密码。
- 远程目录选择、远程文件夹创建、删除、重新打开、离线提示完整。
- 远程写入失败**硬失败**,绝不静默写本地镜像;读缓存明确标记“离线副本”。
- 兼容现有 `~/.dsh/remote-workspaces` 镜像和旧 Remote-SSH 记录,可回滚。
- Windows 本地 + Linux/macOS 远程;Unicode、空格、单引号路径可用。
### 1.2 非目标(v1 不做)
- 不做远程 Windows 主机(Remote-SSH 当前也主要按 POSIX 远程设计)。
- 不把 SSH 私钥、密码、passphrase 写入浏览器 bundle、URL、日志、marker 或普通配置文件。
- 不做跨设备云同步;镜像仍是本机缓存。
- 不在本方案里顺手修“本地/云端会话拆分”和“图标分类”,它们独立跟踪;但会预留 project identity 接口,避免再次写死。
---
## 2. 现状与约束
### 2.1 当前调用链
```text
GroupsBrowser / FoldersDialog
-> src/client/folder-directory.ts
POST /remote-ssh/api/{listProfiles,listDir,remoteExec,createRemoteWorkspace,listWorkspaces,mkdir}
-> @zhangfengshun/dsh-remote-ssh (Host)
OpenSSH CLI + 连接池 + 镜像 + workspaceRegistry
-> ctx.workspaceRegistry.create(mirrorDir, title)
```
唯一远程 seam 是 `src/client/folder-directory.ts:30-53`;`remoteExec("cd ... && pwd -P")` 在 `:141`。当前 Host 只 `inject = ['webServer']`(`src/index.ts:57-61`),路由在 `:122-348`。
### 2.2 关键事实
- Remote-SSH 2.4.41 已安装,MIT,只发布 `lib/index.js` / `lib/client.js`,**没有源码**;不能可靠地 fork/vendor 维护。
- 它用 `ctx.subprocess`、`ctx.workspaceRegistry`,底层是系统 `ssh`,不是 ssh2。
- 远程工作区本质是 `workspaceRegistry.create(mirrorDir, title)` 注册的本地镜像目录;会话 `cwd` 指向镜像。
- 现有镜像 marker 是 `.remote-ssh.json`,里面含 `keyPath`;新方案不能继续把密钥路径写进工作区可见文件。
- 现有测试:`tests/folders.test.ts`、`tests/tree.test.ts`、`tests/core.test.ts`、`tools/verify-folders.mjs`、`tools/verify-folder-directory.mjs`(mock)、`tools/verify-directory-flow.mjs`、`scripts/verify-groups.mjs`(CDP 真机)。
- 构建:Host ESM + client CJS(`tsdown.config.ts:82-136`),浏览器包不能 import Node builtins。
---
## 3. 传输层选型
| 维度 | 系统 OpenSSH(推荐) | ssh2 / node-ssh |
|---|---|---|
| 配置兼容 | 原生读 `~/.ssh/config`、ProxyJump、Match、Include | 要自己解析,容易漏 |
| 认证 | key、agent、password、keyboard-interactive/2FA 都由 ssh 处理 | 要自己实现 askpass/2FA 流程 |
| 老 HPC 算法 | 跟随系统 ssh,兼容性最好 | 受库的算法列表限制 |
| 文件操作 | 需要 shell/SFTP 组合,需严格转义 | SFTP 原生、结构化、最稳 |
| 依赖 | 系统需有 `ssh`(Windows 可选功能) | 纯 JS,但 ssh2 有可选原生依赖 |
| 安全边界 | 复用成熟客户端;参数数组调用,不拼 shell | 自己处理 host key、超时、通道,代码面更大 |
| 迁移风险 | 与现有 Remote-SSH 行为最接近 | 需重新验证跳板、密码、算法、终端 |
**决定:v1 用系统 OpenSSH。**
理由:当前插件的行为基线就是 OpenSSH;用户环境已能连 HPC;换成 ssh2 会把“替换插件”变成“重写 SSH 客户端”,风险和工作量都更高。
本机已确认 `C:\Windows\System32\OpenSSH\ssh.exe` 与 `sftp.exe` 存在(PATH 中另有 OpenSSH_10.5p1),v1 不需要额外安装依赖。
保留后路:`SshTransport` 做成接口;如果未来要求“零系统依赖”,再加 `ssh2` 实现,不动上层。
---
## 4. 目标架构
```text
Browser (React)
├─ SSH 设置 / 连接测试 / 远程目录选择器
├─ 只知道 profileId、displayName、目录项;不知道 keyPath/password
└─ fetch /workspace-groups/ssh/*
│
Host (Node ESM)
├─ SshProfileStore ~/.dsh/workspace-groups/ssh-profiles.json (0600)
├─ SecretVault 仅内存;密码/passphrase,重启即清
├─ SshTransport ctx.subprocess + ssh/sftp;超时、取消、重连、并发上限
├─ RemoteFs stat/list/read/write/mkdir/rename/delete/glob/grep
├─ RemoteWorkspaceService 镜像目录 + marker + workspaceRegistry.create/delete
├─ Migrator 旧 Remote-SSH 记录/镜像一次性导入
└─ RemoteTools 远程 exec/read/write/...(Host 工具,不经浏览器)
│
ctx.workspaceRegistry.create(mirrorDir, title)
│
~/.dsh/remote-workspaces/<recordId>/ ← 原生 Workspace 的 cwd
```
### 4.1 新增/修改文件
| 文件 | 作用 |
|---|---|
| `src/host-ssh/profiles.ts` | profile CRUD、校验、0600 原子写、导入 `~/.ssh/config` |
| `src/host-ssh/transport.ts` | 连接测试、命令执行、超时/取消、并发池、host key 策略 |
| `src/host-ssh/files.ts` | 远程文件操作、路径规范化、原子写、大小上限 |
| `src/host-ssh/workspaces.ts` | 镜像、marker、workspaceRegistry 注册/清理、幂等 |
| `src/host-ssh/migrate.ts` | 旧记录/旧镜像导入、双读、回滚 |
| `src/host-ssh/tools.ts` | Host 侧 `remote_*` 工具注册(M2 起) |
| `src/client/ssh-settings.tsx` | 连接管理 UI;密码只提交到 Host,不回显 |
| `src/client/remote-picker.tsx` | 远程目录浏览;复用现有目录选择器样式 |
| `src/client/folder-directory.ts` | 把 `/remote-ssh/api/*` 换成 `/workspace-groups/ssh/*`;保留六种操作 DTO,删掉 generic `remoteExec` |
| `src/index.ts` | 注入 `workspaceRegistry`;注册 SSH 路由;统一错误 envelope |
| `src/host-folders.ts` | remote marker 只做 fail-closed;新增我们自己的 marker 校验 |
| `src/client/folders-persist.ts` | 创建失败回滚,保证 members round-trip |
| `cordis.patch.yml` | 如接终端 wrapper,补 terminal-controller 补丁;M2 再做 |
### 4.2 Host 路由(示意)
```text
GET /workspace-groups/ssh/profiles
POST /workspace-groups/ssh/profiles
PATCH /workspace-groups/ssh/profiles/:id
DELETE /workspace-groups/ssh/profiles/:id
POST /workspace-groups/ssh/profiles/:id/test
POST /workspace-groups/ssh/profiles/:id/list
POST /workspace-groups/ssh/profiles/:id/mkdir
POST /workspace-groups/ssh/workspaces
GET /workspace-groups/ssh/workspaces
DELETE /workspace-groups/ssh/workspaces/:recordId
POST /workspace-groups/ssh/workspaces/:recordId/sync
```
响应统一 `{ ok: true, value }` / `{ ok: false, error: { code, message } }`;沿用当前 `HttpError` 和请求体上限,不引入新的网络暴露面。
---
## 5. 数据模型
### 5.1 Profile
```ts
type SshAuth =
| { kind: 'key'; keyPath: string } // 仅 Host 可读;浏览器只看到 basename
| { kind: 'agent' }
| { kind: 'password' } // 密码不落盘,仅 SecretVault
interface SshProfile {
id: string // crypto.randomUUID()
name: string
host: string
port: number // 默认 22
user: string
auth: SshAuth
proxyJump?: string
remoteRoot: string // 默认 '~';文件操作必须落在此根下
connectTimeoutMs: number // 默认 15000
keepaliveSeconds: number // 默认 30
}
```
- 存储:`~/.dsh/workspace-groups/ssh-profiles.json`,权限 `0600`,原子 rename。
- 不存密码/passphrase;`SecretVault` 以 `profileId` 为键存在 Host 内存,重启清空。
- 导入 `~/.ssh/config` 只复制 host/user/port/keyPath/proxyJump,不复制密码。
### 5.2 远程工作区记录
```ts
interface RemoteWorkspaceRecord {
id: string // 稳定 recordId,不用时间戳拼
profileId: string
title: string
remotePath: string // 用户看到的绝对路径
mirrorPath: string // 本地绝对路径
workspaceId: string // 原生 workspaceRegistry id
createdAt: string
schemaVersion: 1
}
```
Marker:`<mirror>/.workspace-groups-remote.json`
```json
{"schemaVersion":1,"recordId":"...","profileId":"...","remotePath":"/home/u/proj"}
```
**不写** host/user/keyPath/proxyJump;这些只在 Host profile store。旧 `.remote-ssh.json` 只读,不修改。
### 5.3 FolderMember
沿用 `src/core/folders.ts:20-68` 的 `FolderMember`,不新增必填字段;可选加:
```ts
remoteRecordId?: string // 只做诊断/迁移,不参与归属
```
`workspaceId` 仍是唯一权威;`path` 仍是镜像路径。不要用标题或 host 反推归属。
---
## 6. 安全不变量
| # | 不变量 | 验证 |
|---|---|---|
| S1 | 私钥内容永不进入 Host 响应、浏览器 bundle、日志、marker | 构建产物 grep `BEGIN OPENSSH PRIVATE KEY`;路由快照断言无 keyPath |
| S2 | keyPath 只在 Host profile store;浏览器只拿 basename | API 单测 |
| S3 | password/passphrase 只存内存,响应不回显,日志脱敏 | 重启后连接需重输;日志 grep |
| S4 | host key 默认 `StrictHostKeyChecking=yes`,使用应用私有 known_hosts;首次连接显示指纹并要求确认 | 中间人测试:换 key 必须失败 |
| S5 | 远程路径必须落在 profile `remoteRoot` 内,`realpath -m` 后校验;拒绝 `..`、NUL、换行 | 路径穿越测试 |
| S6 | 所有进程用 argv 数组调用,禁止 `shell: true`;远程命令参数用 POSIX 单引号 + base64 | 注入测试(`'`, `$(...)`, 空格, 中文) |
| S7 | 写文件先写同目录临时文件,再 `mv` 原子替换;失败保留原文件 | 断连/磁盘满测试 |
| S8 | 远程写失败绝不回落本地镜像;读缓存只读并标 `offline` | 断网测试:镜像 mtime 不变,UI 明确报错 |
| S9 | 单命令/单文件有超时与大小上限;可取消;输出截断 | 大文件、`sleep 999`、`kill` |
| S10 | 删除远程文件夹只删本地记录/镜像,**不删远端目录**;删除远端目录需单独确认 | UI 文案 + 测试 |
补充:
- 使用应用私有 known_hosts:`~/.dsh/workspace-groups/known_hosts`,提供“从 `~/.ssh/known_hosts` 导入”按钮;不静默接受新主机。
- 密码认证只在回环/受信 Host 上可用;若 GUI 通过局域网访问,提示改用密钥。
- 命令输出做 secret redaction;`ssh -v` 诊断只保留认证相关行,其他丢弃。
---
## 7. 远程工作区生命周期
### 7.1 创建
1. 校验 profile + `remotePath`,`cd <path> && pwd -P` 解析绝对路径;不存在则按用户选择 `mkdir -p`。
2. 按 `profileId + remotePath` 查重;已存在则复用 record,不新建。
3. 生成稳定 `recordId`;镜像目录沿用 `~/.dsh/remote-workspaces/<recordId>`。
4. 创建镜像目录,写 marker(不含密钥信息),写一份只读 `README.md` 说明“这是远程镜像,写操作请走远程工具”。
5. `ctx.workspaceRegistry.create(mirrorPath, title)`;若已有同路径原生 Workspace,复用其 id 并 `setTitle`。
6. 保存 record;返回 `{mirrorPath, workspaceId, recordId, remotePath, profileId, reused}`。
7. 任一步失败:回滚已创建的原生 Workspace / 镜像;**不写 folders overlay**。客户端只有在拿到完整返回后才 PUT members。
### 7.2 删除
- 从 folders overlay 移除 member;
- 若无其他 member 引用同一 `workspaceId`,删除原生 Workspace 记录和镜像;
- **不执行远端 `rm -rf`**;UI 明确写“只移除本地映射,不会删除服务器文件”。
### 7.3 重开/离线
- 启动时只读 marker + record,不自动连 SSH;目录行显示“远程(离线)”状态。
- 用户点开或执行操作时才连接;失败显示具体阶段(DNS/TCP/认证/host key/权限),不把本地镜像伪装成远端成功。
---
## 8. 从 Remote-SSH 迁移
原则:**先双读,后切换,可回滚;不重建原生 Workspace,不丢已有会话。**
1. 一次性读取旧插件 `listWorkspaces`(若仍安装)或扫描 `~/.dsh/remote-workspaces/*/.remote-ssh.json`。
2. 按 `host + user + port + keyPath basename` 匹配/创建新 profile;密码不迁移,要求重输。
3. 复用旧 `mirrorPath` 和 `shellWorkspaceId`(旧记录里有);生成我们的 record + marker。
4. 迁移 `FolderMember` 时保留 `workspaceId`,只补 `remoteRecordId`;不按标题合并。
5. 旧插件仍保留安装但禁用;新插件通过 feature flag 接管。验收通过后再卸载旧插件。
6. 回滚:保留旧 `.remote-ssh.json` 和旧设置不动;关闭新 backend 即可回到旧插件。
---
## 9. 会话拆分问题(独立小任务)
用户看到的“同一项目在本地文件夹和云端文件夹分成两个会话列表”,根因大概率不是 SSH 传输,而是**每个远程文件夹注册了不同的原生 Workspace,Session 的 `workspaceId` 不同**。本方案只做两件事,避免加重问题:
- 创建远程文件夹时优先复用同一逻辑项目的 owner/member 归属,不产生新的顶层项目行。
- 预留 `projectKey` 投影接口;后续用“canonical project”聚合会话,不直接改写 Session 归属。
需要一次平台能力验证(Phase 0):
> 能否在 owner Workspace 下创建 `cwd = 远程镜像` 的 Session?
> - 能:远程文件夹不新建 Workspace,会话天然统一,这是最优解。
> - 不能:保留 mirror-backed Workspace,另做 UI 投影聚合。
在验证前不承诺“合并历史会话”。
---
## 10. 分阶段实施
| 阶段 | 内容 | 交付/验收 | 预估 |
|---|---|---|---|
| P0 决策与探针 | 确认传输选型;验证 owner Workspace + mirror cwd 是否可行;冻结六种 DTO 和错误码 | 一页探针结论;不写生产代码 | 0.5–1 天 |
| P1 连接与目录 | profiles、连接测试、known_hosts、远程 list/mkdir、SSH 设置页 | 不装 Remote-SSH 也能连 HPC、浏览目录 | 3–5 天 |
| P2 远程文件夹闭环 | 镜像、marker、workspaceRegistry、创建/删除/重开、folders 回滚、迁移 | 建远程文件夹,重启后仍在;删记录不删远端 | 3–5 天 |
| P3 文件与终端 | read/write/stat/rename/delete/glob/grep、原子写、离线态、终端 wrapper | 远程改文件失败不落本地;终端进 HPC | 4–7 天 |
| P4 工具面/同步 | exec 超时/取消、sync/push、上传、13 工具对齐、并发池 | 与旧插件功能对照表全绿 | 4–8 天 |
| P5 加固发布 | 安全测试、Unicode/空格/引号、大文件、断网、CDP 真机、文档与迁移说明 | 验收清单全过;可卸载旧插件 | 3–5 天 |
**总计约 15–30 个工作日**(单人;不含会话合并和图标分类)。如果只做 P1–P2,约 7–11 天,就能先摆脱“建远程文件夹必须装 Remote-SSH”。
---
## 11. 验收清单
### 功能
- [ ] 全新 profile:密钥、agent、密码(内存)三种认证都能连。
- [ ] ProxyJump / `~/.ssh/config` 的 Host 别名可用。
- [ ] 远程目录浏览支持 `~`、绝对路径、空格/中文/单引号目录。
- [ ] 创建远程文件夹后,原生 Workspace 的 `cwd` 是镜像路径,标题正确。
- [ ] 重启 DSH 后,远程文件夹仍在,能重新打开。
- [ ] 删除远程文件夹只删本地映射,远端目录和文件不变。
- [ ] 旧 Remote-SSH 记录迁移后,已有会话仍挂在原 Workspace 下。
### 安全/失败
- [ ] 构建产物和 API 响应中搜不到私钥内容、密码、完整 keyPath。
- [ ] host key 变化时连接失败,不自动接受。
- [ ] 远程路径 `../../etc`、symlink 逃逸被拒绝。
- [ ] `$(touch /tmp/pwned)`、反引号、换行注入不执行。
- [ ] 断网写文件:报错,镜像文件字节不变。
- [ ] 命令超时/取消后子进程被 kill,无孤儿 ssh。
- [ ] 日志不含 Authorization、密码、passphrase。
### 兼容
- [ ] Windows 本地 + Linux 远程;macOS 本地 smoke。
- [ ] 远程 Unicode 文件名 round-trip。
- [ ] 大文件超过上限时明确拒绝,不截断后写回。
- [ ] 卸载 Remote-SSH 后,P1–P4 功能不回退。
---
## 12. 风险与待确认
1. **“完整内置”的边界**:如果要求 Agent 的普通 bash 也在 HPC 执行,这不是本插件能单独完成的,需要 DSH 平台远程执行层;本方案只能做到显式远程工具 + 远程终端。
2. **系统 OpenSSH 依赖**:Windows 需启用 OpenSSH Client;安装页要检测 `ssh -V` 并给出一键说明。若你要求零系统依赖,需改 ssh2,工期和兼容风险上升。
3. **密码/2FA**:v1 密码只存内存,重启要重输;keyboard-interactive 先走终端,Host 工具面后补。若必须持久化,需要接 OS 凭据库(DPAPI/Keychain/libsecret),单独评估。
4. **远程 Windows 主机**:v1 不做;POSIX shell 假设(`sh`、`base64`、`find`、`grep`)。
5. **终端 wrapper**:需要 `nodePath` 逃生舱(旧插件已有同类问题);Desktop 的 Host node 不一定在 PATH。
6. **会话拆分**:见第 9 节,先探针后承诺。
7. **图标分类**:与 SSH 无关,独立处理;当前通用 50 个图标未分节,材料 28 个已分 4 节。
---
## 13. 需要你拍板的三件事
1. **传输层**:系统 OpenSSH(推荐,兼容最好)还是纯 JS `ssh2`(零系统依赖,但重写配置/跳板/2FA)?
2. **首期范围**:只做 P1–P2(远程文件夹闭环,最快摆脱 Remote-SSH),还是一次做到 P4(完整工具面)?
3. **密码策略**:只存内存、重启重输(推荐,安全)还是接 OS 凭据库持久化?
确认后我再动代码;当前仓库工作树干净,未改任何实现文件。

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,7 @@
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, stat, symlink, unlink } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { homedir } from "node:os";
import { createHash } from "node:crypto";
//#region node_modules/.pnpm/js-yaml@4.3.1/node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
@ -2904,12 +2905,26 @@ const EMPTY_FOLDERS_DOCUMENT = {
workspaces: {}
};
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
const WINDOWS_DRIVE$1 = /^[A-Za-z]:[\\/]/u;
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u;
/** `\\server\share` — a Windows UNC path. */
const WINDOWS_UNC$1 = /^\\\\/u;
const WINDOWS_UNC = /^\\\\/u;
const BACKSLASH = "\\";
const SLASH = "/";
/** 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);
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path);
}
/**
* Absolute-path test by SPELLING, not by the current platform.
*
* The host write validator and this module must agree on exactly one rule.
* Earlier the host branched on `process.platform`, so a sidecar written on
* one platform was silently truncated when read on another (and then written
* back truncated). Accepting every spelling here keeps both sides consistent.
* @param path - raw path as stored or picked.
*/
function isAbsoluteFolderPath$1(path) {
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) || path.startsWith(SLASH);
}
/**
* One path with trailing separators removed, spelling preserved (no case
@ -2918,35 +2933,85 @@ function isWindowsStyle(path) {
*/
function withoutTrailingSeparator(path) {
if (isWindowsStyle(path)) {
let value = path.replaceAll("/", "\\");
while (value.length > 3 && value.endsWith("\\")) value = value.slice(0, -1);
let value = path.replaceAll(SLASH, BACKSLASH);
while (value.length > 3 && value.endsWith(BACKSLASH)) value = value.slice(0, -1);
return value;
}
let value = path;
while (value.length > 1 && value.endsWith("/")) value = value.slice(0, -1);
while (value.length > 1 && value.endsWith(SLASH)) value = value.slice(0, -1);
return value;
}
/**
* 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.
* Lexically collapse `.` and `..` segments without touching the filesystem.
*
* A `..` that would climb above the root is dropped rather than escaping it,
* so `C:\a\..\b` and `C:\b` (or `/a/../b` and `/b`) compare equal. This is a
* pure string operation: symlinks and realpath are deliberately out of scope,
* but the previous behaviour — treating every spelling as unrelated — made
* session grouping and de-duplication silently wrong.
* @param value - separator-normalized path with trailing separators removed.
* @param windows - whether the spelling is Windows-style.
*/
function collapseSegments(value, windows) {
let leading = "";
if (windows) {
const drive = /^[A-Za-z]:\\/u.exec(value);
if (drive !== null) leading = drive[0];
else if (value.startsWith("\\\\")) leading = "\\\\";
} else if (value.startsWith(SLASH)) leading = SLASH;
const out = [];
for (const segment of value.slice(leading.length).split(windows ? /[\\/]+/u : /\/+/u)) {
if (segment === "" || segment === ".") continue;
if (segment === "..") {
if (out.length > 0) out.pop();
continue;
}
out.push(segment);
}
return leading + out.join(windows ? BACKSLASH : SLASH);
}
/**
* Comparison form of one path: trimmed, Unicode-normalized (NFC), lexically
* dot-collapsed, separator-normalized and, for Windows spellings, lower-cased
* (drive letters and file names are case-insensitive there).
*
* NFC matters on macOS/APFS, where `Café` and `Cafe\u0301` name the same
* directory; without it they became two folder rows.
* @param path - raw path as stored or picked.
* @returns the canonical comparison form.
*/
function canonicalPath(path) {
const trimmed = path.trim();
const value = withoutTrailingSeparator(trimmed);
return isWindowsStyle(trimmed) ? value.toLowerCase() : value;
const trimmed = path.trim().normalize("NFC");
const windows = isWindowsStyle(trimmed);
const value = collapseSegments(withoutTrailingSeparator(trimmed), windows);
return windows ? value.toLowerCase() : value;
}
/**
* Path equality: case-insensitive for Windows-style paths, tolerant of
* trailing separators, exact for POSIX paths.
* trailing separators, `.`/`..` segments and Unicode normalization, exact for
* POSIX paths.
* @param a - first path.
* @param b - second path.
*/
function samePath(a, b) {
return canonicalPath(a) === canonicalPath(b);
}
/**
* True when `path` is `base` itself or lives somewhere below it, with the same
* separator and case rules as {@link samePath}. `..` segments are collapsed on
* both sides first, so a traversal spelling cannot fake containment.
* @param path - candidate path.
* @param base - containing directory.
*/
function isUnderBase(path, base) {
const root = canonicalPath(base);
const target = canonicalPath(path);
if (root === "" || target === "") return false;
if (target === root) return true;
const separator = isWindowsStyle(root) ? BACKSLASH : SLASH;
const prefix = root.endsWith(separator) ? root : `${root}${separator}`;
return target.startsWith(prefix);
}
//#endregion
//#region src/host-folders.ts
/**
@ -2958,21 +3023,21 @@ function samePath(a, b) {
* 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.
* replacing it, atomically: temp file + fsync + rename), and reads tolerate
* hand-edited content (junk entries are dropped instead of thrown) — BUT a
* read that cannot even open or parse the file is now an ERROR, not an empty
* document. Previously `readFoldersDocument` swallowed EACCES/EISDIR/EBUSY and
* bad JSON; the browser then PUT the empty document back and erased every
* workspace's folders with no warning.
*
* Concurrency: every write is guarded by `If-Match: <revision>` (a hash of the
* exact bytes on disk) and serialized through a module-level promise chain, so
* two windows cannot silently overwrite each other (lost update).
*/
/** 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;
const REMOTE_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");
@ -2988,23 +3053,46 @@ function defaultFoldersPath() {
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
* The path is hardcoded in that plugin (it does NOT read `DSH_HOME`), so it is
* hardcoded here too. A custom `DSH_HOME` therefore makes PATH-BASED detection
* unreliable: `remoteMirrorBaseDiagnostic()` surfaces that explicitly, and
* write operations must still treat the SSH catalogue as authoritative.
*/
function defaultRemoteMirrorBase() {
return resolve(homedir(), ".dsh", "remote-workspaces");
}
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.
* Report a mismatch between `$DSH_HOME` and the hard-coded remote-ssh mirror
* root. Silently returning a wrong base used to disable remote/local detection
* with no symptom at all; the UI now shows `warning` instead.
*/
function remoteMirrorBaseDiagnostic() {
const base = defaultRemoteMirrorBase();
const home = process.env.DSH_HOME;
if (home === void 0 || home === "") return { base };
if (resolve(home) === resolve(homedir(), ".dsh")) return { base };
return {
base,
warning: `DSH_HOME is "${home}" but the remote-ssh mirror root is hard-coded to "${base}". Path-based remote detection is unreliable; SSH catalogue lookups remain authoritative.`
};
}
/**
* Absolute-path test for SIDECAR data: delegated to `core/folders.ts` so the
* host validator and the browser tree use exactly one spelling-based rule.
* A sidecar may hold Windows and POSIX spellings at once (WSL, synced config,
* a Windows client with a POSIX mirror), so `process.platform` must not decide.
* @param path - candidate path.
*/
function isAbsoluteFolderPath(path) {
return process.platform === "win32" ? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) : POSIX_ABSOLUTE.test(path);
return isAbsoluteFolderPath$1(path);
}
/** Platform-specific test for a LOCAL path used by the remote-hint endpoint. */
function isAbsoluteHostPath(path) {
return process.platform === "win32" ? /^[A-Za-z]:[\\/]/u.test(path) || path.startsWith("\\\\") : path.startsWith("/");
}
/** Validate a local path for the read-only remote hint endpoint. */
function validateRemoteHintPath(path) {
if (typeof path !== "string" || path.length === 0 || path.length > 1024 || path.includes("\0") || !isAbsoluteFolderPath(path)) throw new Error("remote hint path must be an absolute host path without NUL, at most 1024 characters");
if (typeof path !== "string" || path.length === 0 || path.length > 1024 || path.includes("\0") || !isAbsoluteHostPath(path)) throw new Error("remote hint path must be an absolute host path without NUL, at most 1024 characters");
return path;
}
/**
@ -3031,7 +3119,18 @@ async function hasRemoteMarkerHint(path) {
function invalid(detail) {
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`);
}
/** Trim one optional free-form string field, dropping it when unusable. */
/** True when a path contains a `..` segment that would need resolving. */
function hasTraversalSegment(path) {
return path.split(/[\\/]+/u).includes("..");
}
/**
* Trim one optional free-form string field.
*
* Invalid values now call `fail` instead of being silently dropped: in strict
* (PUT) mode that is a 400, in tolerant (read) mode the field is dropped. The
* old asymmetry — a bad TYPE rejected the whole PUT while an over-long value
* returned 200 with the field quietly deleted — is gone.
*/
function optionalText(value, limit, fail) {
if (value === void 0) return void 0;
if (typeof value !== "string") {
@ -3039,7 +3138,10 @@ function optionalText(value, limit, fail) {
return;
}
const text = value.trim();
if (text === "" || text.length > limit || text.includes("\0")) return void 0;
if (text === "" || text.length > limit || text.includes("\0")) {
fail(`member text fields must be 1-${limit} characters without NUL`);
return;
}
return text;
}
/**
@ -3052,10 +3154,12 @@ function optionalText(value, limit, fail) {
* @param workspaceId - owning workspace id (used in messages and as a guard).
* @param folders - plain folder paths already accepted for this workspace.
* @param members - member folders already accepted for this workspace.
* @param strict - enforce the mirror-containment invariant on writes.
* @param remoteBase - the local mirror root, for the containment check.
* @param fail - strict-mode reporter (throws) / tolerant no-op.
* @returns the normalized member, or undefined when unusable.
*/
function parseMember(value, workspaceId, folders, members, fail) {
function parseMember(value, workspaceId, folders, members, strict, remoteBase, fail) {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
fail("member folders must be objects");
return;
@ -3075,6 +3179,10 @@ function parseMember(value, workspaceId, folders, members, fail) {
fail(`member folder path "${path}" must be absolute`);
return;
}
if (hasTraversalSegment(path)) {
fail(`member folder path "${path}" must not contain ".." segments`);
return;
}
if (folders.some((folder) => samePath(folder, path)) || members.some((member) => samePath(member.path, path))) {
fail(`duplicate folder path "${path}"`);
return;
@ -3100,6 +3208,10 @@ function parseMember(value, workspaceId, folders, members, fail) {
}
const title = optionalText(source.title, FOLDER_PATH_LIMIT, fail);
const keepTitle = title === void 0 ? {} : { title };
if (strict && kind === "remote" && !isUnderBase(path, remoteBase)) {
fail(`remote member path "${path}" must be inside the mirror base "${remoteBase}"`);
return;
}
if (kind === "local") return {
path,
workspaceId: memberWorkspaceId,
@ -3139,12 +3251,18 @@ function parseMember(value, workspaceId, folders, members, fail) {
}
/**
* Parse one workspace entry.
*
* A missing `folders` key is treated as an empty list: older sidecars and
* hand-edited files carry only `members`, and the old "folders is required"
* check discarded the WHOLE entry (including every member) — which the next
* full-document PUT then wrote back, permanently erasing those folders.
* @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.
* @param remoteBase - the local mirror root, for remote member containment.
* @returns the normalized entry, or undefined when nothing usable remains.
*/
function parseFolderEntry(value, workspaceId, strict) {
function parseFolderEntry(value, workspaceId, strict, remoteBase) {
const fail = (detail) => {
if (strict) invalid(`workspace "${workspaceId}": ${detail}`);
};
@ -3153,17 +3271,14 @@ function parseFolderEntry(value, workspaceId, strict) {
return;
}
const source = value;
if (source.folders === void 0) {
fail("folders is required");
return;
}
if (!Array.isArray(source.folders)) {
if (source.folders !== void 0 && !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 rawFolders = Array.isArray(source.folders) ? source.folders : [];
if (strict && rawFolders.length > 32) invalid(`workspace "${workspaceId}": at most 32 folders`);
const folders = [];
for (const candidate of source.folders) {
for (const candidate of rawFolders) {
if (typeof candidate !== "string") {
fail("folder paths must be strings");
continue;
@ -3185,6 +3300,10 @@ function parseFolderEntry(value, workspaceId, strict) {
fail(`folder path "${path}" must be absolute`);
continue;
}
if (hasTraversalSegment(path)) {
fail(`folder path "${path}" must not contain ".." segments`);
continue;
}
if (folders.some((existing) => samePath(existing, path))) {
fail(`duplicate folder path "${path}"`);
continue;
@ -3201,7 +3320,7 @@ function parseFolderEntry(value, workspaceId, strict) {
else {
if (strict && source.members.length > 16) invalid(`workspace "${workspaceId}": at most 16 member folders`);
for (const candidate of source.members) {
const member = parseMember(candidate, workspaceId, folders, members, fail);
const member = parseMember(candidate, workspaceId, folders, members, strict, remoteBase, fail);
if (member !== void 0) members.push(member);
if (members.length >= 16) break;
}
@ -3225,9 +3344,40 @@ function parseFolderEntry(value, workspaceId, strict) {
};
}
/**
* Drop members that point at a workspace which is itself an owner (or at the
* owner itself). Such a workspace keeps its own sidebar row AND appeared as a
* folder row of the other owner — two independent session lists for one
* project. Strict writes reject them outright (see `validateFoldersDocument`);
* this keeps old sidecars readable without showing the duplicate.
*/
function dropNestedMembers(doc) {
const owners = new Set(Object.keys(doc.workspaces));
let changed = false;
const workspaces = {};
for (const [workspaceId, entry] of Object.entries(doc.workspaces)) {
const members = entry.members ?? [];
const kept = members.filter((member) => member.workspaceId !== workspaceId && !owners.has(member.workspaceId));
if (kept.length !== members.length) changed = true;
if (kept.length === 0 && entry.folders.length === 0 && entry.root === void 0) {
changed = true;
continue;
}
workspaces[workspaceId] = {
...entry,
...kept.length === 0 ? {} : { members: kept }
};
}
return changed ? {
version: 1,
workspaces
} : doc;
}
/**
* 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.
* unknown-version document yields the empty document — but ONLY when the file
* could actually be read and parsed; `readFoldersState` is responsible for
* reporting a read/parse failure as an error.
* @param raw - parsed JSON value.
*/
function parseFoldersDocument(raw) {
@ -3238,64 +3388,95 @@ function parseFoldersDocument(raw) {
version: 1,
workspaces: {}
};
const remoteBase = defaultRemoteMirrorBase();
const workspaces = {};
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
if (workspaceId.trim() === "" || workspaceId.length > 200) continue;
const entry = parseFolderEntry(value, workspaceId, false);
for (const [rawId, value] of Object.entries(source.workspaces)) {
const workspaceId = rawId.trim();
if (workspaceId === "" || rawId.length > 200) continue;
const entry = parseFolderEntry(value, workspaceId, false, remoteBase);
if (entry !== void 0) workspaces[workspaceId] = entry;
}
return {
return dropNestedMembers({
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.
* @param remoteBase - mirror root used to constrain remote members.
* @returns the normalized document to save.
* @throws when version, workspace ids, folder paths, duplicates or the root
* membership are wrong.
* @throws when version, workspace ids, folder paths, duplicates, the root
* membership or cross-workspace references are wrong.
*/
function validateFoldersDocument(raw) {
function validateFoldersDocument(raw, remoteBase = defaultRemoteMirrorBase()) {
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);
for (const [rawId, value] of Object.entries(source.workspaces)) {
const workspaceId = rawId.trim();
if (workspaceId === "" || rawId.length > 200) invalid(`workspace ids must be non-empty strings of at most 200 characters`);
if (workspaces[workspaceId] !== void 0) invalid(`duplicate workspace id "${workspaceId}"`);
const entry = parseFolderEntry(value, workspaceId, true, remoteBase);
if (entry !== void 0) workspaces[workspaceId] = entry;
}
const owners = new Set(Object.keys(workspaces));
for (const [workspaceId, entry] of Object.entries(workspaces)) for (const member of entry.members ?? []) if (owners.has(member.workspaceId)) invalid(`workspace "${workspaceId}": member "${member.workspaceId}" is itself a folder owner`);
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;
}
/** Non-fatal diagnostic when the on-disk schema is newer than this build. */
function detectSchemaWarning(raw) {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
const version = raw.version;
return version === 1 ? void 0 : `unknown folders schema version ${String(version)}; editing is disabled to avoid downgrading the file`;
}
/** Hash the exact text so the ETag changes on every real write. */
function revisionOf(text) {
return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
}
/**
* 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.
* Read the sidecar WITHOUT swallowing real I/O errors.
*
* ENOENT means "no overlay yet" and is a legitimate empty document. EACCES,
* EISDIR, EBUSY and invalid JSON are errors: returning an empty document for
* them was the root cause of the whole-overlay wipe, because the browser would
* PUT the empty result back on the next edit.
* @param path - overlay file path.
*/
async function writeFoldersDocument(path, document) {
const json = `${JSON.stringify(document, null, 2)}\n`;
async function readFoldersState(path) {
let text;
try {
text = await readFile(path, "utf8");
} catch (error) {
if (error.code === "ENOENT") return {
document: EMPTY_FOLDERS_DOCUMENT,
revision: "",
missing: true
};
throw new Error(`${FOLDERS_FILE_NAME}: cannot read overlay: ${error instanceof Error ? error.message : String(error)}`);
}
let raw;
try {
raw = JSON.parse(text);
} catch (error) {
throw new Error(`${FOLDERS_FILE_NAME}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
const schemaWarning = detectSchemaWarning(raw);
return {
document: parseFoldersDocument(raw),
revision: revisionOf(text),
missing: false,
...schemaWarning === void 0 ? {} : { schemaWarning }
};
}
/** Atomically replace `path` with `json` (temp + fsync + rename). */
async function atomicWrite(path, json) {
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");
@ -3314,6 +3495,197 @@ async function writeFoldersDocument(path, document) {
await unlink(tmp).catch(() => {});
throw error;
}
try {
const dir = await open(dirname(path), "r");
try {
await dir.sync();
} finally {
await dir.close();
}
} catch {}
}
/** Serializes read → compare → write so concurrent PUTs cannot interleave. */
let writeChain = Promise.resolve();
/**
* Compare-and-swap the whole overlay under a per-process write lock.
*
* `expectedRevision` must be the revision the caller's document was derived
* from. A mismatch returns `conflict` with the server's current state; the
* route answers 409 with that document so the client can reload instead of
* overwriting. Omitting If-Match is allowed only when the sidecar does not
* exist yet (first write).
* @param path - overlay file path.
* @param expectedRevision - `If-Match` value, or undefined.
* @param document - already validated document to persist.
*/
async function replaceFoldersDocument(path, expectedRevision, document) {
const task = async () => {
const current = await readFoldersState(path);
if (!current.missing && (current.schemaWarning !== void 0 || expectedRevision !== current.revision)) return {
ok: false,
kind: "conflict",
state: current
};
const json = `${JSON.stringify(document, null, 2)}\n`;
await atomicWrite(path, json);
return {
ok: true,
revision: revisionOf(json)
};
};
const run = writeChain.then(task, task);
writeChain = run.catch(() => void 0);
return run;
}
//#endregion
//#region src/host-farm.ts
/**
* A farm gathers several project folders into one real directory, so a single
* session can read and write all of them.
*
* A session's file scope is its workspace directory, so "one project, several
* folders" needs one directory that contains all of them. The farm is that
* directory: every entry is a link (a junction on Windows, a directory symlink
* elsewhere) to a folder the user already owns. Nothing is copied or moved, and
* the user's folders keep their own life.
*
* Deletion is the dangerous half. A recursive delete that followed a link would
* erase the user's real folder, so {@link removeFarm} only ever unlinks entries
* that are links, and refuses as soon as it meets a real directory.
*/
/** Characters Windows refuses in a name, plus control characters. */
const RESERVED_CHARS = /[\u005C\u002F:*?"<>|\u0000-\u001f]/gu;
/** Device names Windows refuses as a whole entry name. */
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu;
const MAX_NAME_LENGTH = 64;
const WINDOWS = process.platform === "win32";
function dshHome() {
const configured = process.env.DSH_HOME;
return configured === void 0 || configured.trim() === "" ? join(homedir(), ".dsh") : configured;
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
function defaultFarmRoot() {
return resolve(dshHome(), "workspace-groups", "farms");
}
/** One directory-safe name for a farm, derived from a workspace title. */
function farmDirectoryName(title) {
const cleaned = title.replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim().replace(/[. ]+$/u, "").slice(0, MAX_NAME_LENGTH).trim().replace(/[. ]+$/u, "");
if (cleaned === "") return "farm";
return RESERVED_NAMES.test(cleaned) ? `_${cleaned}` : cleaned;
}
function linkNameFor(target, taken) {
const raw = basename(target).replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim() || "folder";
const base = RESERVED_NAMES.test(raw) ? `_${raw}` : raw;
let name = base;
let suffix = 2;
while (taken.has(name.toLowerCase())) {
name = `${base} (${suffix})`;
suffix += 1;
}
taken.add(name.toLowerCase());
return name;
}
/**
* Delete one farm entry, and only one.
*
* A junction reports as a symbolic link to `lstat` but is a reparse point that
* `unlink` refuses; a directory symlink on POSIX removes fine with `unlink`. A
* real directory is never touched.
*/
async function unlinkEntry(path) {
const info = await lstat(path);
if (info.isDirectory() && !info.isSymbolicLink()) throw new Error(`farm: refusing to delete a real directory: ${path}`);
try {
await unlink(path);
} catch {
await rmdir(path);
}
}
async function discard(path) {
let entries;
try {
entries = await readdir(path);
} catch {
return;
}
for (const entry of entries) try {
await unlinkEntry(join(path, entry));
} catch {}
try {
await rmdir(path);
} catch {}
}
/** Resolve and validate one folder the user asked to gather. */
async function resolveFolder(raw) {
if (typeof raw !== "string" || raw.trim() === "") throw new Error("farm: empty folder path");
if (!isAbsolute(raw)) throw new Error(`farm: folder must be an absolute path: ${raw}`);
let real;
try {
real = await realpath(raw);
} catch {
throw new Error(`farm: folder does not exist: ${raw}`);
}
if (!(await stat(real)).isDirectory()) throw new Error(`farm: not a directory: ${raw}`);
return real;
}
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
async function buildFarm(input) {
const seen = /* @__PURE__ */ new Set();
const targets = [];
for (const raw of input.folders) {
const target = await resolveFolder(raw);
const key = WINDOWS ? target.toLowerCase() : target;
if (seen.has(key)) continue;
seen.add(key);
targets.push(target);
}
if (targets.length < 2) throw new Error("farm: needs at least two distinct folders");
const root = defaultFarmRoot();
const path = join(root, farmDirectoryName(String(input.name)));
await mkdir(root, { recursive: true });
try {
await mkdir(path);
} catch (error) {
if (error.code === "EEXIST") throw new Error(`farm: already exists, remove it first: ${path}`);
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`);
}
const taken = /* @__PURE__ */ new Set();
const links = [];
try {
for (const target of targets) {
const name = linkNameFor(target, taken);
await symlink(target, join(path, name), WINDOWS ? "junction" : "dir");
links.push({
name,
target
});
}
} catch (error) {
await discard(path);
throw new Error(`farm: cannot link into ${path}: ${error instanceof Error ? error.message : String(error)}`);
}
return {
path,
links
};
}
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
async function removeFarm(farmPath) {
const root = defaultFarmRoot();
const target = resolve(farmPath);
const inside = relative(root, target);
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) throw new Error(`farm: not a farm directory: ${farmPath}`);
const entries = await readdir(target);
for (const entry of entries) await unlinkEntry(join(target, entry));
await rmdir(target);
}
//#endregion
//#region src/index.ts
@ -3321,8 +3693,18 @@ async function writeFoldersDocument(path, document) {
const name = "workspace-groups-local";
/** Services required before mounting: the webserver route. */
const inject = ["webServer"];
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
/** Cap on the manual/tabs PUT body: those overlays are tiny. */
const MAX_MANUAL_BODY_BYTES = 65536;
/**
* Cap on the folder PUT body.
*
* This must NOT reuse `MAX_MANUAL_BODY_BYTES`: the folder validator allows up
* to 32 folders and 16 members per workspace, each with up to 1024-character
* paths, so a single perfectly legal workspace can exceed 64 KiB. A 64 KiB cap
* meant that once a document grew past it, every further edit returned 413 and
* the overlay became un-editable. 1 MiB is still a hard bound against abuse.
*/
const MAX_FOLDERS_BODY_BYTES = 1048576;
/** Error with an HTTP status, mapped to a plain-text 4xx/5xx response. */
var HttpError = class extends Error {
status;
@ -3379,6 +3761,38 @@ async function readBody(req, limit) {
if (chunks.length === 0) throw new HttpError(400, "empty request body");
return Buffer.concat(chunks).toString("utf8");
}
/**
* The one response envelope shared by GET, PUT echo and 409.
*
* GET and PUT used to disagree: GET added `remoteBase`, PUT echoed only the
* document. A client that replaced its state with the PUT response lost
* `remoteBase` until the next reload. Both now carry the same diagnostics plus
* the exact revision, so the client can render what the host accepted AND keep
* its optimistic-concurrency token.
*/
function foldersEnvelope(state, diagnostic, revision = state.revision) {
return {
...state.document,
remoteBase: diagnostic.base,
...diagnostic.warning === void 0 ? {} : { remoteBaseWarning: diagnostic.warning },
...state.schemaWarning === void 0 ? {} : { schemaWarning: state.schemaWarning },
revision
};
}
/** Turn an HTTP If-Match value (possibly quoted / weak) into a bare revision. */
function normalizeEtag(value) {
return value.trim().replace(/^W\//u, "").replace(/^"|"$/gu, "");
}
/** Send a JSON folder envelope with the standard no-store headers. */
function sendFolders(res, status, body, revision, method) {
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"ETag": `"${revision}"`,
"Content-Length": Buffer.byteLength(body)
});
res.end(method === "HEAD" ? void 0 : body);
}
/** Plugin body: mount the config snapshot route and the overlay write route. */
function apply(ctx) {
const configPath = defaultConfigPath();
@ -3540,17 +3954,15 @@ function apply(ctx) {
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,
remoteBase: defaultRemoteMirrorBase()
});
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);
let state;
try {
state = await readFoldersState(foldersPath);
} catch (error) {
writeError(res, 500, `workspace-groups: cannot read folder overlay: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const diagnostic = remoteMirrorBaseDiagnostic();
sendFolders(res, 200, JSON.stringify(foldersEnvelope(state, diagnostic)), state.revision, req.method);
return;
}
if (req.method === "POST") {
@ -3563,33 +3975,99 @@ function apply(ctx) {
}
let raw;
try {
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES));
} catch (error) {
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const diagnostic = remoteMirrorBaseDiagnostic();
let document;
try {
document = validateFoldersDocument(raw);
document = validateFoldersDocument(raw, diagnostic.base);
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const ifMatch = req.headers?.["if-match"];
const expectedRevision = typeof ifMatch === "string" ? normalizeEtag(ifMatch) : void 0;
let result;
try {
await writeFoldersDocument(foldersPath, document);
result = await replaceFoldersDocument(foldersPath, expectedRevision, 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);
if (!result.ok) {
sendFolders(res, 409, JSON.stringify(foldersEnvelope(result.state, diagnostic)), result.state.revision);
return;
}
sendFolders(res, 200, JSON.stringify(foldersEnvelope({
document,
revision: result.revision,
missing: false
}, diagnostic)), result.revision);
}
}), "@dsh-xhl/workspace-groups: /workspace-groups/folders route");
ctx.effect(() => ctx.webServer.register({
kind: "exact",
path: "/workspace-groups/farm",
handler: async (req, res) => {
if (req.method === "POST") {
let raw;
try {
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES));
} catch (error) {
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const body = raw;
if (body === null || typeof body !== "object" || !Array.isArray(body.folders)) {
writeError(res, 400, "workspace-groups: farm needs { name, folders: string[] }");
return;
}
let result;
try {
result = await buildFarm({
name: typeof body.name === "string" ? body.name : "farm",
folders: body.folders
});
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify(result);
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
if (req.method === "DELETE") {
const target = new URL(req.url ?? "/", "http://localhost").searchParams.get("path");
if (target === null || target.trim() === "") {
writeError(res, 400, "workspace-groups: farm needs ?path=");
return;
}
try {
await removeFarm(target);
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify({ ok: true });
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
writeError(res, 405, "method not allowed");
}
}), "@dsh-xhl/workspace-groups: /workspace-groups/farm route");
}
//#endregion
export { apply, inject, name };

View File

@ -2,7 +2,7 @@ import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/cl
import { type WorkspaceFolderEntry } from '../core/folders.ts';
import type { GroupsBrowserProps } from './contract.ts';
import { type RemoteProfileSummary } from './folder-directory.ts';
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t'];
@ -10,14 +10,24 @@ export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remo
canOpen: boolean;
/** Remote (mirror-backed) workspace: extra folders can also be typed subpaths. */
remote: boolean;
/** Remote root of a cloud owner, so a browsed subdirectory joins as a subfolder. */
/** Absolute remote root of a cloud owner, so a browsed child joins as a subfolder. */
ownerRemotePath: string | null;
/** SSH connections, `null` while loading or when the remote-ssh plugin is absent. */
profiles: readonly RemoteProfileSummary[] | null;
profilesError: string | null;
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[];
/** Non-null when the overlay could not be read or has an unknown schema: editing is disabled. */
blockedReason: string | null;
/** Non-fatal host diagnostics (e.g. a mismatched remote mirror base). */
warnings: readonly string[];
onReload: () => void;
onClose: () => void;
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void;
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void;
/** Register one cloud folder: returns true once it is stored. */

24
lib/types/client/folders-farm.d.ts vendored Normal file
View File

@ -0,0 +1,24 @@
/**
* Client side of the farm route.
*
* A farm is one real directory holding a link per project folder, so a session
* can read and write all of them at once. The host owns the filesystem work;
* this module only speaks the two requests, and never assumes success: every
* failure comes back as an Error with the host's own message.
*/
export declare const FARM_ROUTE = "/workspace-groups/farm";
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string;
/** Absolute real path of the folder it points at. */
readonly target: string;
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string;
readonly links: readonly FarmLink[];
}
/** Build a farm for `folders`; the host refuses to reuse an existing one. */
export declare function buildFarm(name: string, folders: readonly string[], fetchImpl?: typeof fetch): Promise<FarmResult>;
/** Remove a farm; only its links are unlinked, never a real folder. */
export declare function removeFarm(farmPath: string, fetchImpl?: typeof fetch): Promise<void>;

View File

@ -7,15 +7,25 @@
* 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.
* SAFETY CONTRACT (this is the fix for the silent whole-document wipe):
*
* - A failed read is NEVER "no extra folders". `loadFolders` returns
* `{ ok: false, error }` and the UI disables every edit. Previously a
* transient EACCES / EBUSY / torn JSON produced an empty document, and the
* next edit PUT that empty document back, erasing every workspace's folders.
* - Every write carries `If-Match: <revision>`. The host compares it with the
* sidecar's current revision and answers 409 on a mismatch, so two windows
* can no longer silently overwrite each other (lost update).
* - `saveFolders` returns the NEW revision. A caller must not issue a second
* write until it has stored it.
* - No `keepalive`: it silently truncates bodies above ~64 KiB, and the folder
* overlay may legitimately be larger than that. An explicit timeout replaces
* it so a hung request fails loudly instead of being dropped on navigation.
*/
import { type FoldersDocument } from '../core/folders.ts';
/** Host route holding the folder overlay. */
export declare const FOLDERS_ROUTE = "/workspace-groups/folders";
/** One successful read: the overlay plus the mirror base the host reported. */
/** One successful read: the overlay plus the host's diagnostics and revision. */
export interface FoldersSnapshot {
readonly document: FoldersDocument;
/**
@ -24,21 +34,53 @@ export interface FoldersSnapshot {
* folders must be subdirectories of that same mirror.
*/
readonly remoteBase?: string;
/** Set when `$DSH_HOME` and the hard-coded remote-ssh mirror root disagree. */
readonly remoteBaseWarning?: string;
/** Set when the sidecar uses a schema version this build cannot safely edit. */
readonly schemaWarning?: string;
/** Content hash of the sidecar this snapshot was built from (ETag value). */
readonly revision?: string;
}
/** Result of a read. `ok: false` means "do not render or write anything". */
export type FoldersLoadResult = {
readonly ok: true;
readonly snapshot: FoldersSnapshot;
} | {
readonly ok: false;
readonly error: string;
};
/** A 409: the caller's baseline is stale; `current` is the server's document. */
export declare class FoldersConflictError extends Error {
readonly current: FoldersSnapshot;
constructor(current: FoldersSnapshot, message?: string);
}
/**
* Fetch the stored folder overlay.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the overlay plus the reported mirror base; the empty document on any
* failure.
*/
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersSnapshot>;
/**
* Store the whole folder overlay.
* Parse the common GET / PUT / 409 response envelope.
*
* 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).
* An unknown `version` does NOT produce an empty document that could be written
* back. It produces `schemaWarning`, which the UI uses to disable editing: a
* future schema must never be downgraded to v1 by this build.
* @param body - decoded JSON response.
* @returns the snapshot, or null when the envelope is unusable.
*/
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<void>;
export declare function parseFoldersSnapshot(body: unknown): FoldersSnapshot | null;
/**
* Fetch the stored folder overlay.
*
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns `{ ok: true, snapshot }` or `{ ok: false, error }`. NEVER an empty
* document on failure: the caller must disable edits instead.
*/
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersLoadResult>;
/**
* Store the whole folder overlay with an optimistic-concurrency check.
*
* @param document - the client's current document.
* @param expectedRevision - revision the document was derived from. Pass
* undefined only for a genuinely new sidecar; the host rejects an omitted
* If-Match when a document already exists.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the new revision from the host's echo.
* @throws {FoldersConflictError} on 409 — `current` holds the latest snapshot.
*/
export declare function saveFolders(document: FoldersDocument, expectedRevision: string | undefined, fetchImpl?: typeof fetch): Promise<string>;

View File

@ -4,7 +4,7 @@
*/
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | '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' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | '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.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.loadError' | 'folder.conflict' | 'folder.retry' | 'folder.reload' | 'folder.addKind' | 'folder.addKindSubfolder' | 'folder.addKindWorkspace' | 'folder.cloudNoteSubfolder' | 'folder.mergeTitle' | 'folder.mergeAction' | 'folder.mergeHint' | 'folder.mergeDone' | 'folder.mergeFailed' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | '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' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | '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;

18
lib/types/client/remote-paths.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
/**
* Pure helpers for comparing remote directory paths.
*
* Kept out of `FoldersDialog.tsx` so the alias-vs-absolute rule can be unit
* tested without mounting React. The remote browser always returns an ABSOLUTE
* path (`pwd -P`), while the SSH catalogue may store `~/projects/app`; comparing
* those two spellings directly is what used to make every browsed subdirectory
* look like a brand-new cloud workspace.
*/
/** Unify separators and drop trailing slashes so two spellings compare equal. */
export declare function normalizeRemotePath(value: string): string;
/**
* Relative path of `picked` inside `root`: '' for the root itself, null outside.
* `root` must be an ABSOLUTE remote path; an alias can never be matched
* reliably against the absolute path the remote browser returns, so we refuse
* to guess rather than misclassifying a child folder.
*/
export declare function subfolderOf(root: string | null, picked: string): string | null;

View File

@ -75,8 +75,10 @@ export interface WorkspaceGroupNode {
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.
* folder: root first, then stored order. The base directory is never a row —
* it is the workspace row itself, and its sessions live in {@link sessions}.
* Absent means "this workspace has exactly one directory", the plain
* pre-folders node shape.
*/
folders?: readonly FolderNode[];
}
@ -131,10 +133,11 @@ export interface MemberWorkspaces {
*/
export declare function memberWorkspaces(workspaces: readonly WorkspaceView[], folders?: FoldersDocument): MemberWorkspaces;
/**
* 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.
* Display label of one folder: the last path segment. A drive root 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;
*/
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;
/**

View File

@ -1,20 +1,21 @@
/**
* Recognising the Host's own default workspace ("默认工作区").
*
* The workspace snapshot carries no `isDefault` flag, so the only Host-owned
* signal is the one the Host itself uses: the registry title. Its
* `workspaceDisplayTitle()` treats a title equal to `DEFAULT_WORKSPACE_DIRECTORY`
* as "the default workspace" and swaps in a localized label. That constant lives
* in the workspace-controller package, which this plugin must not import at
* runtime (it is a client bundle), so the string is mirrored here.
* The workspace snapshot carries no `isDefault` flag, so we mirror the two
* Host-owned signals here (the registry title and the Host's own directory
* layout); the constants live in the workspace-controller package, which this
* plugin must not import at runtime because it is a client bundle.
*
* Two Host signals are combined:
* - the registry title (primary: exactly what the Host substitutes for);
* - the Host's own directory layout (`<Documents>/deepseek-harness/default-workspace`),
* which still identifies the workspace after the user renames it.
* A user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT treated as the default workspace, and no single
* directory name is used as the sole test.
* The PATH is the primary signal: `<Documents>/deepseek-harness/default-workspace`
* still identifies the default workspace after the user renames it, and a
* user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT the Host default workspace. The TITLE is only
* a fallback for snapshots that carry no usable path at all.
*
* (An earlier version checked the title FIRST and returned true immediately.
* That silently re-classified any workspace the user renamed to
* "default-workspace" as the Host default, hiding it from the sidebar, and
* contradicted the guarantee in the comment above.)
*/
/** Directory name the Host uses for its default workspace (host mirror). */
export declare const DEFAULT_WORKSPACE_TITLE = "default-workspace";
@ -27,6 +28,7 @@ export interface DefaultWorkspaceIdentity {
}
/**
* Whether a workspace snapshot is the Host's default workspace.
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
* @param workspace - workspace snapshot (path is primary, title is a fallback
* for path-less snapshots).
*/
export declare function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean;

View File

@ -15,6 +15,12 @@
*
* 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.
*
* Path rules are deliberately SHARED with the host validator. Both sides
* import from this module instead of re-deriving platform-dependent rules:
* a sidecar can legitimately hold Windows and POSIX spellings at once (a
* Windows client with a POSIX remote mirror, WSL, or a synced config), so
* absolute-path tests are made by SPELLING, never by `process.platform`.
*/
/** Kind of a member folder: a plain local directory, or an SSH-mirrored one. */
export type FolderMemberKind = 'local' | 'remote';
@ -64,9 +70,33 @@ export interface FoldersDocument {
}
/** Canonical empty document, shared so callers need not allocate one each time. */
export declare const EMPTY_FOLDERS_DOCUMENT: FoldersDocument;
/** True for both Windows path spellings accepted by the write validator. */
export declare function isWindowsStyle(path: string): boolean;
/**
* Absolute-path test by SPELLING, not by the current platform.
*
* The host write validator and this module must agree on exactly one rule.
* Earlier the host branched on `process.platform`, so a sidecar written on
* one platform was silently truncated when read on another (and then written
* back truncated). Accepting every spelling here keeps both sides consistent.
* @param path - raw path as stored or picked.
*/
export declare function isAbsoluteFolderPath(path: string): boolean;
/**
* Comparison form of one path: trimmed, Unicode-normalized (NFC), lexically
* dot-collapsed, separator-normalized and, for Windows spellings, lower-cased
* (drive letters and file names are case-insensitive there).
*
* NFC matters on macOS/APFS, where `Café` and `Cafe\u0301` name the same
* directory; without it they became two folder rows.
* @param path - raw path as stored or picked.
* @returns the canonical comparison form.
*/
export declare function canonicalPath(path: string): string;
/**
* Path equality: case-insensitive for Windows-style paths, tolerant of
* trailing separators, exact for POSIX paths.
* trailing separators, `.`/`..` segments and Unicode normalization, exact for
* POSIX paths.
* @param a - first path.
* @param b - second path.
*/
@ -97,6 +127,18 @@ export declare function memberOf(entry: WorkspaceFolderEntry | undefined, path:
* @param ownerWorkspaceId - workspace the members hang off.
*/
export declare function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[];
/**
* Members that are safe to render under an owner.
*
* A member whose `workspaceId` is itself an owner (has its own entry) used to
* be skipped by {@link absorbedWorkspaceIds} but still rendered as a folder
* row by {@link effectiveFolders}: the same project appeared twice, with two
* independent session lists. The host write validator rejects such members;
* this helper makes the read side equally defensive for old sidecars.
* @param doc - folders document.
* @param ownerWorkspaceId - workspace the members hang off.
*/
export declare function validMembers(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[];
/**
* Member workspace id → owning workspace id.
*
@ -124,6 +166,9 @@ export declare function rootOf(workspacePath: string, entry: WorkspaceFolderEntr
/**
* Owning folder of a session cwd: the most specific (longest) effective folder
* that equals the cwd or is a proper path ancestor of it.
*
* Both sides are {@link canonicalPath}-normalized, so `..` segments and mixed
* separator spellings no longer mis-group a session into the project base.
* @param cwd - recorded session cwd; undefined means "the workspace itself".
* @param workspacePath - canonical directory of the workspace.
* @param entry - saved folder entry, if any.
@ -141,6 +186,11 @@ export declare function addFolder(entry: WorkspaceFolderEntry | undefined, path:
* Append a workspace-backed folder. Idempotent under `samePath`: a later call
* for the same path replaces the stored member (so a re-registered workspace id
* wins) instead of stacking a duplicate row.
*
* Unlike an earlier version, re-registering a member does NOT clear a `root`
* that points at the same path: the folder still exists and still resolves in
* {@link rootOf}, so silently resetting the default session directory would
* change behaviour the user never asked for.
* @param entry - current entry, or undefined for a workspace with no extras.
* @param member - member record to store.
*/
@ -149,6 +199,9 @@ export declare function addMember(entry: WorkspaceFolderEntry | undefined, membe
* Drop an extra folder, plain or workspace-backed. 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.
*
* Note: this is a pure data edit. Unregistering the native workspace behind a
* member is a side effect the caller must perform (and undo on a failed save).
* @param entry - current entry, or undefined.
* @param path - folder path to drop.
*/
@ -163,7 +216,8 @@ export declare function removeFolder(entry: WorkspaceFolderEntry | undefined, pa
export declare function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
/**
* True when `path` is `base` itself or lives somewhere below it, with the same
* separator and case rules as {@link samePath}.
* separator and case rules as {@link samePath}. `..` segments are collapsed on
* both sides first, so a traversal spelling cannot fake containment.
* @param path - candidate path.
* @param base - containing directory.
*/

30
lib/types/host-farm.d.ts vendored Normal file
View File

@ -0,0 +1,30 @@
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string;
/** Absolute real path of the folder it points at. */
readonly target: string;
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string;
readonly links: readonly FarmLink[];
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
export declare function defaultFarmRoot(): string;
/** One directory-safe name for a farm, derived from a workspace title. */
export declare function farmDirectoryName(title: string): string;
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
export declare function buildFarm(input: {
name: string;
folders: readonly unknown[];
}): Promise<FarmResult>;
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
export declare function removeFarm(farmPath: string): Promise<void>;

View File

@ -19,13 +19,28 @@ export declare function defaultFoldersPath(): string;
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
* The path is hardcoded in that plugin (it does NOT read `DSH_HOME`), so it is
* hardcoded here too. A custom `DSH_HOME` therefore makes PATH-BASED detection
* unreliable: `remoteMirrorBaseDiagnostic()` surfaces that explicitly, and
* write operations must still treat the SSH catalogue as authoritative.
*/
export declare function defaultRemoteMirrorBase(): string;
/** Mirror base plus a non-fatal diagnostic when it cannot be trusted. */
export interface RemoteMirrorBaseDiagnostic {
readonly base: string;
readonly warning?: string;
}
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.
* Report a mismatch between `$DSH_HOME` and the hard-coded remote-ssh mirror
* root. Silently returning a wrong base used to disable remote/local detection
* with no symptom at all; the UI now shows `warning` instead.
*/
export declare function remoteMirrorBaseDiagnostic(): RemoteMirrorBaseDiagnostic;
/**
* Absolute-path test for SIDECAR data: delegated to `core/folders.ts` so the
* host validator and the browser tree use exactly one spelling-based rule.
* A sidecar may hold Windows and POSIX spellings at once (WSL, synced config,
* a Windows client with a POSIX mirror), so `process.platform` must not decide.
* @param path - candidate path.
*/
export declare function isAbsoluteFolderPath(path: string): boolean;
@ -41,7 +56,9 @@ export declare function hasRemoteMarkerHint(path: string): Promise<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.
* unknown-version document yields the empty document — but ONLY when the file
* could actually be read and parsed; `readFoldersState` is responsible for
* reporting a read/parse failure as an error.
* @param raw - parsed JSON value.
*/
export declare function parseFoldersDocument(raw: unknown): FoldersDocument;
@ -49,33 +66,79 @@ 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.
* @param remoteBase - mirror root used to constrain remote members.
* @returns the normalized document to save.
* @throws when version, workspace ids, folder paths, duplicates or the root
* membership are wrong.
* @throws when version, workspace ids, folder paths, duplicates, the root
* membership or cross-workspace references are wrong.
*/
export declare function validateFoldersDocument(raw: unknown): FoldersDocument;
export declare function validateFoldersDocument(raw: unknown, remoteBase?: string): FoldersDocument;
/** Exact state of the sidecar, including the revision used by `If-Match`. */
export interface FoldersState {
readonly document: FoldersDocument;
/** First 16 hex chars of sha256 over the exact on-disk bytes; '' when missing. */
readonly revision: string;
/** True when the file does not exist (a legitimate empty overlay). */
readonly missing: boolean;
readonly schemaWarning?: string;
}
/**
* 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.
* Read the sidecar WITHOUT swallowing real I/O errors.
*
* ENOENT means "no overlay yet" and is a legitimate empty document. EACCES,
* EISDIR, EBUSY and invalid JSON are errors: returning an empty document for
* them was the root cause of the whole-overlay wipe, because the browser would
* PUT the empty result back on the next edit.
* @param path - overlay file path.
*/
export declare function readFoldersState(path: string): Promise<FoldersState>;
/**
* Legacy tolerant reader kept for the verifier scripts. New code must use
* `readFoldersState` so a read failure is not mistaken for an empty overlay.
* @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).
* Atomically replace the overlay file. Kept as the public single-document
* writer used by the verifier scripts; the HTTP route uses
* `replaceFoldersDocument` instead, which adds the CAS guard.
* @param path - target file path.
* @param document - validated document to persist.
*/
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
/** Outcome of a guarded replace. */
export type FoldersReplaceResult = {
readonly ok: true;
readonly revision: string;
} | {
readonly ok: false;
readonly kind: 'conflict';
readonly state: FoldersState;
};
/**
* Compare-and-swap the whole overlay under a per-process write lock.
*
* `expectedRevision` must be the revision the caller's document was derived
* from. A mismatch returns `conflict` with the server's current state; the
* route answers 409 with that document so the client can reload instead of
* overwriting. Omitting If-Match is allowed only when the sidecar does not
* exist yet (first write).
* @param path - overlay file path.
* @param expectedRevision - `If-Match` value, or undefined.
* @param document - already validated document to persist.
*/
export declare function replaceFoldersDocument(path: string, expectedRevision: string | undefined, document: FoldersDocument): Promise<FoldersReplaceResult>;
/**
* Join a remote path with a mirror-relative subpath.
*
* The remote path is POSIX (the server's), so this never uses `node:path`:
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
*
* Absolute inputs (POSIX `/…`, Windows drive `C:…`, UNC `\\…`) are rejected,
* matching `core/folders.ts:joinSubpath`. The old version stripped leading
* slashes, so `/etc/x` became `etc/x` on the remote while the local mirror
* side rejected it — the two sides disagreed about the same folder.
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
* @param relativePath - subpath inside the mirror, either separator style.
* @returns the remote counterpart, or null for an empty or escaping subpath.
* @returns the remote counterpart, or null for an empty, absolute or escaping subpath.
*/
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;

View File

@ -1,6 +1,6 @@
{
"name": "workspace-groups-local",
"version": "1.2.0",
"version": "1.3.0",
"description": "Complete workspace grouping manager for the DSH web sidebar: category -> project -> session three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping and ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
"keywords": [
"dsh",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 233 KiB

View File

@ -24,6 +24,7 @@ import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/cl
import { effectiveFolders, memberOf, rootOf, samePath, type WorkspaceFolderEntry } from '../core/folders.ts'
import type { GroupsBrowserProps } from './contract.ts'
import { folderLabel } from './tree.ts'
import { subfolderOf } from './remote-paths.ts'
import {
listRemoteDirectory,
remoteDirJoin,
@ -34,17 +35,10 @@ import {
/** Which kind of folder the add area currently offers. */
type AddMode = 'local' | 'cloud'
/** What a typed value in the cloud field means. Explicit, never inferred. */
type AddKind = 'subfolder' | 'workspace'
/** Relative path of `picked` inside `root`: '' for the root itself, null outside. */
function subfolderOf(root: string | null, picked: string): string | null {
if (root === null) return null
const base = root.trim().replace(/\/+$/u, '')
if (base === '') return null
if (picked === base) return ''
return picked.startsWith(`${base}/`) ? picked.slice(base.length + 1) : null
}
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
@ -52,14 +46,24 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
canOpen: boolean
/** Remote (mirror-backed) workspace: extra folders can also be typed subpaths. */
remote: boolean
/** Remote root of a cloud owner, so a browsed subdirectory joins as a subfolder. */
/** Absolute remote root of a cloud owner, so a browsed child joins as a subfolder. */
ownerRemotePath: string | null
/** SSH connections, `null` while loading or when the remote-ssh plugin is absent. */
profiles: readonly RemoteProfileSummary[] | null
profilesError: string | null
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[]
/** Non-null when the overlay could not be read or has an unknown schema: editing is disabled. */
blockedReason: string | null
/** Non-fatal host diagnostics (e.g. a mismatched remote mirror base). */
warnings: readonly string[]
onReload: () => void
onClose: () => void
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void
/** Register one cloud folder: returns true once it is stored. */
@ -72,6 +76,9 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
const folders = effectiveFolders(workspace.path, entry)
const root = rootOf(workspace.path, entry)
const [addMode, setAddMode] = useState<AddMode>('local')
// An explicit choice replaces the old "bare name vs. path with a slash"
// guess, which turned a browsed subdirectory into a second cloud workspace.
const [addKind, setAddKind] = useState<AddKind>(remote ? 'subfolder' : 'workspace')
const [profileId, setProfileId] = useState('')
const [remotePath, setRemotePath] = useState('')
const [browsing, setBrowsing] = useState(false)
@ -82,14 +89,11 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
? profileId
: (profileChoices[0]?.id ?? '')
const currentProfile = profileChoices.find(profile => profile.id === selectedProfile)
/** One field, two shapes: a bare name creates a subdirectory inside THIS
* project's remote root, anything with a separator registers a new cloud
* workspace. Keeping them in one field removed a whole extra row from a
* ~330px wide dialog. */
const typed = remotePath.trim()
const asSubfolder = remote && typed !== '' && !/[/\\~]/u.test(typed)
const asSubfolder = remote && addKind === 'subfolder'
const editBlocked = blockedReason !== null
const submitAdd = (): void => {
if (typed === '' || busy) return
if (typed === '' || busy || editBlocked) return
if (asSubfolder) {
void onAddSubpath(typed).then(success => { if (success) setRemotePath('') })
return
@ -108,7 +112,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
profile={currentProfile}
startPath={remotePath.trim() === '' ? (ownerRemotePath ?? currentProfile.remoteRoot) : remotePath.trim()}
t={t}
busy={busy}
busy={busy || editBlocked}
onPick={(picked) => {
const relative = subfolderOf(ownerRemotePath, picked)
if (relative === '' && ownerRemotePath !== null) {
@ -127,6 +131,9 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
})
return
}
// Outside the owner's root: genuinely a separate cloud workspace.
// Make the intent explicit so the typed field is never ambiguous.
setAddKind('workspace')
setRemotePath(picked)
setBrowsing(false)
}}
@ -156,6 +163,16 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
<code className="wgFolderHeadPath" title={ownerPath}>{ownerPath}</code>
</header>
{blockedReason !== null && (
<div className="wgFolderNote" role="alert" data-tone="danger">
<p>{blockedReason}</p>
<Button variant="outline" onClick={onReload}>{t('folder.reload')}</Button>
</div>
)}
{warnings.map((warning, index) => (
<p key={index} className="wgFolderNote" role="status">{warning}</p>
))}
<section className="wgFolderSection">
<div className="wgFolderSectionTitle">{t('folder.sectionList')}</div>
<div className="wgFolderList" role="list" aria-label={t('folder.listAria')}>
@ -186,6 +203,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
className="wgFolderRadio"
name="wg-folder-root"
checked={isRoot}
disabled={editBlocked}
aria-label={`${t('folder.rootBadge')} ${label}`}
onChange={() => { onSetRoot(path) }}
/>
@ -221,6 +239,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
<button
type="button"
className="wgIconButton"
disabled={editBlocked}
aria-label={`${t('folder.remove')} ${label}`}
onClick={() => { onRemove(path) }}
>
@ -235,6 +254,20 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
{!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>}
</section>
{extraFolders && (
<section className="wgFolderMerge">
<div className="wgFolderSectionTitle">{t('folder.mergeTitle')}</div>
{/* A session's file scope is its workspace directory, so folders in
different places are unreachable from one session. A farm puts
them side by side as links; nothing is copied or moved. */}
<button type="button" className="wgFolderPick" disabled={busy || editBlocked} onClick={onBuildFarm}>
<span className="wgFolderPickPlus" aria-hidden>⇄</span>
<span>{t('folder.mergeAction')}</span>
</button>
<p className="wgFolderHint">{t('folder.mergeHint')}</p>
</section>
)}
<section className="wgFolderAdd">
<div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div>
<div className="wgFolderSegmented" role="tablist" aria-label={t('folder.addAria')}>
@ -266,7 +299,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
<div className="wgFolderLocalPane">
{/* Full width, own line: the action used to share a row with the
consequence text and the label wrapped onto two lines. */}
<button type="button" className="wgFolderPick" disabled={busy} onClick={onAddFolder}>
<button type="button" className="wgFolderPick" disabled={busy || editBlocked} onClick={onAddFolder}>
<span className="wgFolderPickPlus" aria-hidden>+</span>
<span>{t('folder.pickLocal')}</span>
</button>
@ -279,6 +312,28 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
profile select, a path field and a labelled button cannot share
a row without squeezing one of them. Browsing therefore docks
into the path field as an icon instead of its own button. */}
{remote && (
<div className="wgFolderSegmented" role="radiogroup" aria-label={t('folder.addKind')}>
<button
type="button"
role="radio"
aria-checked={addKind === 'subfolder'}
className="wgFolderTab"
onClick={() => { setAddKind('subfolder'); setNotice(null) }}
>
{t('folder.addKindSubfolder')}
</button>
<button
type="button"
role="radio"
aria-checked={addKind === 'workspace'}
className="wgFolderTab"
onClick={() => { setAddKind('workspace'); setNotice(null) }}
>
{t('folder.addKindWorkspace')}
</button>
</div>
)}
<div className="wgFolderStack">
{profileChoices.length === 0
? <p className="wgFolderNote">{t('folder.noProfiles')}</p>
@ -287,7 +342,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
className="wgFolderSubpathInput wgFolderSelect"
value={selectedProfile}
aria-label={t('folder.profileLabel')}
disabled={busy}
disabled={busy || editBlocked}
onChange={event => setProfileId(event.target.value)}
>
{profileChoices.map(profile => (
@ -302,9 +357,9 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
type="text"
className="wgFolderSubpathInput wgFolderFieldInput"
value={remotePath}
placeholder={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathPlaceholder')}
aria-label={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathLabel')}
disabled={busy}
placeholder={t(asSubfolder ? 'folder.subpathPlaceholder' : 'folder.remotePathPlaceholder')}
aria-label={t(asSubfolder ? 'folder.subpathLabel' : 'folder.remotePathLabel')}
disabled={busy || editBlocked}
onChange={event => setRemotePath(event.target.value)}
onKeyDown={(event) => {
if (event.key !== 'Enter') return
@ -317,7 +372,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
className="wgFolderFieldAction"
title={t('folder.browse')}
aria-label={t('folder.browse')}
disabled={busy || currentProfile === undefined}
disabled={busy || editBlocked || currentProfile === undefined}
onClick={() => { setBrowsing(true) }}
>
<IconFolderOpenOutlineRegular size={15} />
@ -326,14 +381,14 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
<div className="wgFolderActions">
<Button
variant="primary"
disabled={busy || typed === '' || (!asSubfolder && selectedProfile === '')}
disabled={busy || editBlocked || typed === '' || (!asSubfolder && selectedProfile === '')}
onClick={submitAdd}
>
{t(asSubfolder ? 'folder.createAndAdd' : 'folder.addRemote')}
</Button>
</div>
</div>
<p className="wgFolderHint">{t(remote ? 'folder.cloudNoteBoth' : 'folder.cloudNote')}</p>
<p className="wgFolderHint">{t(asSubfolder ? 'folder.cloudNoteSubfolder' : 'folder.cloudNote')}</p>
</>
)}
{profilesError !== null && (

View File

@ -56,10 +56,11 @@ import type { WorkspaceGroupsKey } from './locales.ts'
import { GROUP_EMOJI_ICONS, GROUP_ICON_LABELS } from './group-icon-labels.ts'
import { SCIENCE_ICON_IDS, SCIENCE_ICON_SECTIONS } from './group-icons-science.tsx'
import { EMPTY_FOLDERS_DOCUMENT, addFolder, addMember, effectiveFolders, entryFor, isEmptyEntry, isUnderBase, memberOf, removeFolder, rootOf, samePath, setRoot, type FolderMember, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
import { loadFolders, saveFolders } from './folders-persist.ts'
import { createRemoteFolder, createWorkspaceDirectory, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
import { FoldersConflictError, loadFolders, saveFolders, type FoldersSnapshot } from './folders-persist.ts'
import { createRemoteFolder, createWorkspaceDirectory, listRemoteDirectory, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { FoldersDialog } from './FoldersDialog.tsx'
import { buildFarm } from './folders-farm.ts'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
import css from './styles.css?inline'
@ -329,10 +330,23 @@ export function GroupsBrowser({
// ---- 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.
// extra folders plus the optional root folder. The host sends an ETag-style
// revision with every read; the client sends it back as If-Match so a stale
// window can never overwrite a newer document. A failed read DISABLES editing
// rather than presenting an empty document: an empty document written back
// whole would erase every other workspace's folders for good.
const [foldersDoc, setFoldersDoc] = useState<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
// Refs are the write-side source of truth. React state is a render snapshot;
// a queued edit must see the document left by the previous edit, not the one
// from the render that scheduled it.
const foldersDocRef = useRef<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
const foldersRevisionRef = useRef<string | undefined>(undefined)
const foldersQueueRef = useRef<Promise<unknown>>(Promise.resolve())
const foldersEditBlockedRef = useRef(true)
const foldersBlockedMessageRef = useRef<string | null>(null)
// A remote workspace already created by the SSH plugin but not yet recorded
// in the overlay. Reuse it on retry instead of creating a second mirror.
const createdRemotePendingSave = useRef<{ key: string; member: FolderMember } | null>(null)
// 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
@ -347,15 +361,39 @@ export function GroupsBrowser({
// a mirror of one remote root, so extra folders must be subdirectories of that
// mirror —anything else would exist on this machine only.
const [foldersRemoteBase, setFoldersRemoteBase] = useState<string | null>(null)
useEffect(() => {
let cancelled = false
void loadFolders().then((snapshot) => {
if (cancelled) return
setFoldersDoc(snapshot.document)
setFoldersRemoteBase(snapshot.remoteBase ?? null)
const [foldersLoadError, setFoldersLoadError] = useState<string | null>(null)
const [foldersSchemaWarning, setFoldersSchemaWarning] = useState<string | null>(null)
const [foldersRemoteBaseWarning, setFoldersRemoteBaseWarning] = useState<string | null>(null)
/** Adopt a host snapshot (initial load, reload, or the body of a 409). */
const acceptFoldersSnapshot = (snapshot: FoldersSnapshot): void => {
foldersDocRef.current = snapshot.document
setFoldersDoc(snapshot.document)
foldersRevisionRef.current = snapshot.revision
// A conflict body always carries remoteBase; keep the last known value when
// a response omits it so remote detection does not silently switch off.
if (snapshot.remoteBase !== undefined) setFoldersRemoteBase(snapshot.remoteBase)
setFoldersSchemaWarning(snapshot.schemaWarning ?? null)
setFoldersRemoteBaseWarning(snapshot.remoteBaseWarning ?? null)
const blocked = snapshot.schemaWarning !== undefined
foldersEditBlockedRef.current = blocked
foldersBlockedMessageRef.current = snapshot.schemaWarning ?? null
setFoldersLoadError(null)
}
const reloadFolders = (): void => {
void loadFolders().then((result) => {
if (!result.ok) {
foldersEditBlockedRef.current = true
foldersBlockedMessageRef.current = `${t('folder.loadError')}: ${result.error}`
setFoldersLoadError(result.error)
return
}
acceptFoldersSnapshot(result.snapshot)
})
return () => { cancelled = true }
}, [])
}
useEffect(() => { reloadFolders() }, [])
const workspaces = useWorkspaces(state => state.items)
const workspacePhase = useWorkspaces(state => state.phase)
@ -747,22 +785,63 @@ export function GroupsBrowser({
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}`)
})
/**
* Serialize every folder write. The transform is evaluated against the LIVE
* document when the queued task runs, so two edits scheduled in one tick
* compose instead of the second silently overwriting the first. A failed
* write restores the exact prior document; a 409 adopts the server's newer
* snapshot so the user can retry against the truth.
*/
const queueFolderWrite = (transform: (doc: FoldersDocument) => FoldersDocument): Promise<boolean> => {
const task = async (): Promise<boolean> => {
if (foldersEditBlockedRef.current) {
notifyFolder(foldersBlockedMessageRef.current ?? t('folder.notReady'))
return false
}
const before = foldersDocRef.current
const next = transform(before)
if (next === before) return true
foldersDocRef.current = next
setFoldersDoc(next)
try {
const revision = await saveFolders(next, foldersRevisionRef.current)
foldersRevisionRef.current = revision
return true
} catch (reason) {
if (reason instanceof FoldersConflictError) {
acceptFoldersSnapshot(reason.current)
notifyFolder(`${t('folder.conflict')} ${t('folder.retry')}`)
return false
}
// Roll back to the exact document that was current when this write was
// queued; the optimistic render must never survive a rejected save.
foldersDocRef.current = before
setFoldersDoc(before)
notifyFolder(`${t('folder.saveError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
return false
}
}
const run = foldersQueueRef.current.then(task, task)
foldersQueueRef.current = run.catch(() => undefined)
return run
}
/** Write one workspace's entry; an entry with nothing attached removes the key. */
const writeFolderEntry = (workspaceId: WorkspaceId, entry: WorkspaceFolderEntry): void => {
const next: Record<string, WorkspaceFolderEntry> = { ...foldersDoc.workspaces }
/** Replace one workspace's entry; an empty entry removes its key entirely. */
const editFolderEntry = (
workspaceId: WorkspaceId,
transform: (entry: WorkspaceFolderEntry | undefined) => WorkspaceFolderEntry | undefined,
): Promise<boolean> => queueFolderWrite((doc) => {
const key = workspaceId as string
if (isEmptyEntry(entry)) delete next[key]
else next[key] = entry
persistFolders({ version: 1, workspaces: next })
}
const current = entryFor(doc, key)
const entry = transform(current)
// Returning undefined or the same reference means "no change" (e.g. a
// duplicate check inside the transform) and must not trigger a PUT.
if (entry === undefined || entry === current) return doc
const workspaces: Record<string, WorkspaceFolderEntry> = { ...doc.workspaces }
if (isEmptyEntry(entry)) delete workspaces[key]
else workspaces[key] = entry
return { version: 1, workspaces }
})
const toggleFolder = (workspaceId: WorkspaceId, path: string): void => {
const key = folderKey(workspaceId, path)
@ -778,20 +857,33 @@ export function GroupsBrowser({
const [foldersOwnerRemote, setFoldersOwnerRemote] = useState<string | null>(null)
const foldersOwnerRequest = useRef('')
/** Open the folder dialog and learn the owner's remote root (cloud owners only). */
/**
* Open the folder dialog and learn the owner's remote root (cloud owners
* only). The SSH catalog may store `~/projects/app`; the remote browser works
* in absolute paths (`/home/me/projects/app`). Resolve the alias once so a
* picked subdirectory can be compared against the same absolute base —
* otherwise every browsed child looks like it lies OUTSIDE the project and
* is wrongly offered as a brand-new cloud workspace.
*/
const openFoldersFor = (workspaceId: string): void => {
foldersOwnerRequest.current = workspaceId
setFoldersTarget(workspaceId as WorkspaceId)
setFoldersOwnerRemote(null)
const workspace = workspaces.find(row => (row.workspaceId as string) === workspaceId)
if (workspace === undefined || !isRemoteWorkspace(workspace) || foldersRemoteBase === null) return
void remoteFolderWorkspace(workspace.path, foldersRemoteBase).then(
(record) => {
if (foldersOwnerRequest.current !== workspaceId) return
setFoldersOwnerRemote(record === null ? null : record.remotePath)
},
() => { if (foldersOwnerRequest.current === workspaceId) setFoldersOwnerRemote(null) },
)
void remoteFolderWorkspace(workspace.path, foldersRemoteBase)
.then(async (record) => {
if (record === null) return null
const listing = await listRemoteDirectory(record.profileId, record.remotePath)
return listing.resolved === '' ? record.remotePath : listing.resolved
})
.then(
(resolved) => {
if (foldersOwnerRequest.current !== workspaceId) return
setFoldersOwnerRemote(resolved)
},
() => { if (foldersOwnerRequest.current === workspaceId) setFoldersOwnerRemote(null) },
)
}
/** The overlay record for a picked path that the SSH plugin already mirrors. */
@ -831,16 +923,24 @@ export function GroupsBrowser({
* instead of forked; one that owns folders of its own is refused, because
* nesting a folder tree inside another would hide the inner folders' sessions.
*/
const memberWorkspaceFor = async (workspaceId: WorkspaceId, path: string): Promise<FolderMember> => {
const memberWorkspaceFor = async (
workspaceId: WorkspaceId, path: string,
): Promise<{ member: FolderMember; created: boolean }> => {
const existing = workspaces.find(w => samePath(w.path, path) && w.workspaceId !== workspaceId)
if (existing !== undefined) {
if (!isEmptyEntry(entryFor(foldersDoc, existing.workspaceId as string))) {
if (!isEmptyEntry(entryFor(foldersDocRef.current, existing.workspaceId as string))) {
throw new Error(t('folder.memberNested'))
}
return { path, workspaceId: existing.workspaceId as string, kind: 'local' }
return { member: { path, workspaceId: existing.workspaceId as string, kind: 'local' }, created: false }
}
const created = await createWorkspace({ path })
return { path, workspaceId: created.workspaceId as string, kind: 'local' }
return { member: { path, workspaceId: created.workspaceId as string, kind: 'local' }, created: true }
}
/** Undo a native workspace we created but failed to record in the overlay. */
const undoCreatedMember = async (member: FolderMember, created: boolean): Promise<void> => {
if (!created) return
try { await deleteWorkspace(member.workspaceId as WorkspaceId) } catch { /* best effort */ }
}
const addFolderTo = async (workspaceId: WorkspaceId): Promise<void> => {
@ -852,8 +952,13 @@ export function GroupsBrowser({
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
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))) {
// Checked again inside the queued transform so a concurrent edit cannot
// slip a duplicate in between the check and the write. The early check
// also avoids creating a native workspace that we would only have to undo.
const isDuplicate = (entry: WorkspaceFolderEntry | undefined): boolean => (
effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))
)
if (isDuplicate(entryFor(foldersDocRef.current, workspaceId as string))) {
notifyFolder(t('folder.duplicate'))
return
}
@ -865,7 +970,9 @@ export function GroupsBrowser({
if (target !== null) {
if (samePath(target.mirrorPath, path) && target.workspaceId !== ''
&& target.workspaceId !== (workspaceId as string)) {
writeFolderEntry(workspaceId, addMember(entry, remoteMember(target)))
await editFolderEntry(workspaceId, (current) => (
isDuplicate(current) ? current : addMember(current, remoteMember(target))
))
return
}
notifyFolder(t('folder.remoteNeedsSubpath'))
@ -876,10 +983,16 @@ export function GroupsBrowser({
// there then runs natively with no cross-workspace cwd. Folders along the
// tree stay plain — one cheap cwd gesture, grouped under this project.
if (!isUnderBase(path, workspace.path)) {
writeFolderEntry(workspaceId, addMember(entry, await memberWorkspaceFor(workspaceId, path)))
const { member, created } = await memberWorkspaceFor(workspaceId, path)
const ok = await editFolderEntry(workspaceId, (current) => (
isDuplicate(current) ? current : addMember(current, member)
))
if (!ok) await undoCreatedMember(member, created)
return
}
writeFolderEntry(workspaceId, addFolder(entry, path))
await editFolderEntry(workspaceId, (current) => (
isDuplicate(current) ? current : addFolder(current, path)
))
} catch (reason) {
const detail = reason instanceof Error ? reason.message : String(reason)
notifyFolder(`${t('folder.addError')}: ${detail}`)
@ -901,28 +1014,47 @@ export function GroupsBrowser({
if (owner === undefined) return false
setFoldersBusy(true)
try {
const created = await createRemoteFolder(profileId, remotePath)
if (created.workspaceId === (workspaceId as string)) throw new Error(t('folder.duplicate'))
const entry = entryFor(foldersDoc, workspaceId as string)
if (effectiveFolders(owner.path, entry).some(folder => samePath(folder, created.path))) {
throw new Error(t('folder.duplicate'))
const key = `${workspaceId as string}|${profileId}|${remotePath}`
const pending = createdRemotePendingSave.current
const existingEntry = entryFor(foldersDocRef.current, workspaceId as string)
// Reject a duplicate before asking the SSH plugin to create anything:
// an already-registered remote root, or a retry from a failed overlay save.
const alreadyRegistered = (existingEntry?.members ?? []).some(member => (
member.kind === 'remote' && member.profileId === profileId && member.remotePath === remotePath
))
if (alreadyRegistered || (pending?.key === key
&& effectiveFolders(owner.path, existingEntry).some(folder => samePath(folder, pending.member.path)))) {
notifyFolder(t('folder.duplicate'))
createdRemotePendingSave.current = null
return false
}
const member: FolderMember = {
path: created.path,
workspaceId: created.workspaceId,
kind: 'remote',
remotePath: created.remotePath,
profileId: created.profileId,
title: created.title,
...(created.recordId === '' ? {} : { recordId: created.recordId }),
let member: FolderMember
if (pending?.key === key) {
// The SSH plugin already created the mirror last time; the overlay save
// failed then, so reuse it instead of creating a second remote folder.
member = pending.member
} else {
const created = await createRemoteFolder(profileId, remotePath)
if (created.workspaceId === (workspaceId as string)) throw new Error(t('folder.duplicate'))
member = {
path: created.path,
workspaceId: created.workspaceId,
kind: 'remote',
remotePath: created.remotePath,
profileId: created.profileId,
title: created.title,
...(created.recordId === '' ? {} : { recordId: created.recordId }),
}
}
const next: FoldersDocument = {
version: 1,
workspaces: { ...foldersDoc.workspaces, [workspaceId]: addMember(entry, member) },
}
// Like the subpath field: report success only once the overlay is durable.
await saveFolders(next)
setFoldersDoc(next)
// Keep the pending record until the overlay write is durable: a failed
// save must not leave an untracked native workspace behind on retry.
createdRemotePendingSave.current = { key, member }
const ok = await editFolderEntry(workspaceId, (current) => {
if (effectiveFolders(owner.path, current).some(folder => samePath(folder, member.path))) return current
return addMember(current, member)
})
if (!ok) return false
createdRemotePendingSave.current = null
return true
} catch (reason) {
notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
@ -944,13 +1076,16 @@ export function GroupsBrowser({
const created = pending?.workspaceId === workspaceId && pending.name === name
? pending
: await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory)
createdFolderPendingSave.current = { workspaceId, name, path: created.path }
const entry = addFolder(entryFor(foldersDoc, workspaceId as string), created.path)
const next: FoldersDocument = { version: 1, workspaces: { ...foldersDoc.workspaces, [workspaceId]: entry } }
// Do not report success or clear the input until both operations succeed.
// A failed overlay save does NOT delete the newly created user directory.
await saveFolders(next)
setFoldersDoc(next)
// A failed overlay save does NOT delete the newly created user directory;
// keeping the pending record lets a retry reuse it instead of mkdir twice.
createdFolderPendingSave.current = { workspaceId, name, path: created.path }
const ok = await editFolderEntry(workspaceId, (current) => (
effectiveFolders(workspace.path, current).some(folder => samePath(folder, created.path))
? current
: addFolder(current, created.path)
))
if (!ok) return false
createdFolderPendingSave.current = null
return true
} catch (reason) {
@ -962,11 +1097,39 @@ export function GroupsBrowser({
}
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))
void editFolderEntry(workspaceId, (current) => setRoot(current, path))
}
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so one session reaches all of them. The folders themselves are
* never copied, moved or deleted; the farm holds links only.
*/
const buildFarmFor = async (workspaceId: WorkspaceId): Promise<void> => {
if (foldersBusy) return
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (workspace === undefined) return
const folders = effectiveFolders(workspace.path, entryFor(foldersDocRef.current, workspaceId))
if (folders.length < 2) {
notifyFolder(t('folder.emptyHint'))
return
}
setFoldersBusy(true)
try {
const farm = await buildFarm(workspace.title, folders)
// Registering the farm is a separate step: a created directory without a
// workspace is harmless, and the error still names what already exists.
await createWorkspace({ path: farm.path })
notifyFolder(`${t('folder.mergeDone')} ${farm.path}`)
} catch (reason) {
notifyFolder(`${t('folder.mergeFailed')}: ${reason instanceof Error ? reason.message : String(reason)}`)
} finally {
setFoldersBusy(false)
}
}
const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => {
writeFolderEntry(workspaceId, removeFolder(entryFor(foldersDoc, workspaceId as string), path))
void editFolderEntry(workspaceId, (current) => removeFolder(current, path))
}
/**
@ -989,7 +1152,7 @@ export function GroupsBrowser({
void (async () => {
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
if (!workspace) throw new Error('Workspace not found')
const member = memberOf(entryFor(foldersDoc, workspaceId as string), path)
const member = memberOf(entryFor(foldersDocRef.current, workspaceId as string), path)
if (member !== undefined) {
// The member's own workspace is what runs the session; if the user deleted
// it outside this overlay, say so instead of failing inside the platform.
@ -1005,9 +1168,14 @@ export function GroupsBrowser({
// this project's root — so the agent would open the folder and see nothing.
// Register the member now and run the session inside it.
if (!isUnderBase(path, workspace.path)) {
const entry = entryFor(foldersDoc, workspaceId as string)
const attached = await memberWorkspaceFor(workspaceId, path)
writeFolderEntry(workspaceId, addMember(entry, attached))
const { member: attached, created } = await memberWorkspaceFor(workspaceId, path)
// A session must NEVER be created until the overlay is durable: the
// member's own workspace is the only thing that makes it addressable.
const ok = await editFolderEntry(workspaceId, (current) => addMember(current, attached))
if (!ok) {
await undoCreatedMember(attached, created)
throw new Error(t('folder.saveError'))
}
await createSessionIn(attached.workspaceId as WorkspaceId)
return
}
@ -2022,6 +2190,14 @@ export function GroupsBrowser({
profiles={remoteProfiles}
profilesError={remoteProfilesError}
knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)}
blockedReason={foldersLoadError !== null
? `${t('folder.loadError')}: ${foldersLoadError}`
: foldersSchemaWarning}
warnings={[
...(foldersRemoteBaseWarning === null ? [] : [foldersRemoteBaseWarning]),
]}
onReload={reloadFolders}
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}

View File

@ -0,0 +1,87 @@
/**
* Client side of the farm route.
*
* A farm is one real directory holding a link per project folder, so a session
* can read and write all of them at once. The host owns the filesystem work;
* this module only speaks the two requests, and never assumes success: every
* failure comes back as an Error with the host's own message.
*/
export const FARM_ROUTE = '/workspace-groups/farm'
const FARM_TIMEOUT_MS = 20_000
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string
/** Absolute real path of the folder it points at. */
readonly target: string
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string
readonly links: readonly FarmLink[]
}
function hostMessage(body: unknown, fallback: string): string {
if (typeof body === 'object' && body !== null) {
const message = (body as { error?: unknown }).error
if (typeof message === 'string' && message !== '') return message
}
return fallback
}
async function failure(response: Response, action: string): Promise<Error> {
let body: unknown
try {
body = await response.json()
} catch {
body = null
}
return new Error(hostMessage(body, `${action}: HTTP ${response.status}`))
}
function parseFarm(body: unknown): FarmResult | null {
if (typeof body !== 'object' || body === null) return null
const source = body as { path?: unknown; links?: unknown }
if (typeof source.path !== 'string' || source.path === '') return null
if (!Array.isArray(source.links)) return null
const links: FarmLink[] = []
for (const entry of source.links) {
if (typeof entry !== 'object' || entry === null) return null
const link = entry as { name?: unknown; target?: unknown }
if (typeof link.name !== 'string' || link.name === '') return null
if (typeof link.target !== 'string' || link.target === '') return null
links.push({ name: link.name, target: link.target })
}
return { path: source.path, links }
}
/** Build a farm for `folders`; the host refuses to reuse an existing one. */
export async function buildFarm(
name: string,
folders: readonly string[],
fetchImpl: typeof fetch = fetch,
): Promise<FarmResult> {
const response = await fetchImpl(FARM_ROUTE, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, folders }),
signal: AbortSignal.timeout(FARM_TIMEOUT_MS),
})
if (!response.ok) throw await failure(response, 'POST /workspace-groups/farm')
const parsed = parseFarm(await response.json())
if (parsed === null) throw new Error('POST /workspace-groups/farm: malformed response')
return parsed
}
/** Remove a farm; only its links are unlinked, never a real folder. */
export async function removeFarm(
farmPath: string,
fetchImpl: typeof fetch = fetch,
): Promise<void> {
const response = await fetchImpl(`${FARM_ROUTE}?path=${encodeURIComponent(farmPath)}`, {
method: 'DELETE',
signal: AbortSignal.timeout(FARM_TIMEOUT_MS),
})
if (!response.ok) throw await failure(response, 'DELETE /workspace-groups/farm')
}

View File

@ -7,10 +7,20 @@
* 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.
* SAFETY CONTRACT (this is the fix for the silent whole-document wipe):
*
* - A failed read is NEVER "no extra folders". `loadFolders` returns
* `{ ok: false, error }` and the UI disables every edit. Previously a
* transient EACCES / EBUSY / torn JSON produced an empty document, and the
* next edit PUT that empty document back, erasing every workspace's folders.
* - Every write carries `If-Match: <revision>`. The host compares it with the
* sidecar's current revision and answers 409 on a mismatch, so two windows
* can no longer silently overwrite each other (lost update).
* - `saveFolders` returns the NEW revision. A caller must not issue a second
* write until it has stored it.
* - No `keepalive`: it silently truncates bodies above ~64 KiB, and the folder
* overlay may legitimately be larger than that. An explicit timeout replaces
* it so a hung request fails loudly instead of being dropped on navigation.
*/
import {
EMPTY_FOLDERS_DOCUMENT,
@ -22,7 +32,10 @@ import {
/** Host route holding the folder overlay. */
export const FOLDERS_ROUTE = '/workspace-groups/folders'
/** One successful read: the overlay plus the mirror base the host reported. */
/** Give a write enough time to finish, but never let it hang forever. */
const SAVE_TIMEOUT_MS = 15_000
/** One successful read: the overlay plus the host's diagnostics and revision. */
export interface FoldersSnapshot {
readonly document: FoldersDocument
/**
@ -31,6 +44,28 @@ export interface FoldersSnapshot {
* folders must be subdirectories of that same mirror.
*/
readonly remoteBase?: string
/** Set when `$DSH_HOME` and the hard-coded remote-ssh mirror root disagree. */
readonly remoteBaseWarning?: string
/** Set when the sidecar uses a schema version this build cannot safely edit. */
readonly schemaWarning?: string
/** Content hash of the sidecar this snapshot was built from (ETag value). */
readonly revision?: string
}
/** Result of a read. `ok: false` means "do not render or write anything". */
export type FoldersLoadResult =
| { readonly ok: true; readonly snapshot: FoldersSnapshot }
| { readonly ok: false; readonly error: string }
/** A 409: the caller's baseline is stale; `current` is the server's document. */
export class FoldersConflictError extends Error {
constructor(
readonly current: FoldersSnapshot,
message = 'workspace-groups: folders changed on another client',
) {
super(message)
this.name = 'FoldersConflictError'
}
}
/** One non-empty string field, or undefined when it is absent or blank. */
@ -69,13 +104,14 @@ function parseWireMember(value: unknown): FolderMember | null {
}
/**
* Read one workspace entry off the wire, dropping the entry when it is
* unusable.
* Read one workspace entry off the wire, dropping the entry only when it is
* truly empty.
*
* `members` must survive this round trip: the client owns the whole document
* (the PUT sends it back verbatim), so an entry parsed without its members is
* not merely a display gap — the next folder edit would rewrite the sidecar and
* erase every member-backed folder for good.
* erase every member-backed folder for good. An entry with only a `root` is
* likewise kept (the host accepts it), instead of being dropped as before.
* @param value - one value of the stored `workspaces` mapping.
* @returns the entry, or null for a malformed one.
*/
@ -96,8 +132,10 @@ function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
if (member !== null) members.push(member)
}
}
if (folders.length === 0 && members.length === 0) return null
const root = wireText(row.root)
// An entry whose `folders` key is missing still carries its members: older
// sidecars and hand-edited files use that shape. Only drop a truly empty one.
if (folders.length === 0 && members.length === 0 && root === undefined) return null
return {
folders,
...(members.length === 0 ? {} : { members }),
@ -106,62 +144,127 @@ function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
}
/**
* Fetch the stored folder overlay.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the overlay plus the reported mirror base; the empty document on any
* failure.
* Parse the common GET / PUT / 409 response envelope.
*
* An unknown `version` does NOT produce an empty document that could be written
* back. It produces `schemaWarning`, which the UI uses to disable editing: a
* future schema must never be downgraded to v1 by this build.
* @param body - decoded JSON response.
* @returns the snapshot, or null when the envelope is unusable.
*/
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersSnapshot> {
export function parseFoldersSnapshot(body: unknown): FoldersSnapshot | null {
if (typeof body !== 'object' || body === null || Array.isArray(body)) return null
const source = body as Record<string, unknown>
const remoteBase = wireText(source.remoteBase)
const remoteBaseWarning = wireText(source.remoteBaseWarning)
const schemaWarning = wireText(source.schemaWarning)
const revision = wireText(source.revision)
const diagnostics = {
...(remoteBase === undefined ? {} : { remoteBase }),
...(remoteBaseWarning === undefined ? {} : { remoteBaseWarning }),
...(schemaWarning === undefined ? {} : { schemaWarning }),
...(revision === undefined ? {} : { revision }),
}
if (source.version !== 1) {
return {
document: EMPTY_FOLDERS_DOCUMENT,
...diagnostics,
schemaWarning: schemaWarning ?? `unknown folders schema version ${String(source.version)}`,
}
}
if (typeof source.workspaces !== 'object' || source.workspaces === null
|| Array.isArray(source.workspaces)) {
return { document: EMPTY_FOLDERS_DOCUMENT, ...diagnostics }
}
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 { document: { version: 1, workspaces }, ...diagnostics }
}
/**
* Fetch the stored folder overlay.
*
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns `{ ok: true, snapshot }` or `{ ok: false, error }`. NEVER an empty
* document on failure: the caller must disable edits instead.
*/
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersLoadResult> {
let response: Response
try {
const response = await fetchImpl(FOLDERS_ROUTE, {
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 { document: EMPTY_FOLDERS_DOCUMENT }
const body: unknown = await response.json()
if (typeof body !== 'object' || body === null) return { document: EMPTY_FOLDERS_DOCUMENT }
const source = body as Record<string, unknown>
const remoteBase = typeof source.remoteBase === 'string' && source.remoteBase.trim() !== ''
? source.remoteBase.trim()
: undefined
const base = remoteBase === undefined ? {} : { remoteBase }
if (source.version !== 1) return { document: EMPTY_FOLDERS_DOCUMENT, ...base }
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
return { document: { version: 1, workspaces: {} }, ...base }
}
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 { document: { version: 1, workspaces }, ...base }
} catch {
return { document: EMPTY_FOLDERS_DOCUMENT }
} catch (error) {
return { ok: false, error: `GET ${FOLDERS_ROUTE}: ${error instanceof Error ? error.message : String(error)}` }
}
if (!response.ok) return { ok: false, error: `GET ${FOLDERS_ROUTE}: ${response.status}` }
let body: unknown
try {
body = await response.json()
} catch (error) {
return { ok: false, error: `GET ${FOLDERS_ROUTE}: invalid JSON: ${error instanceof Error ? error.message : String(error)}` }
}
const snapshot = parseFoldersSnapshot(body)
if (snapshot === null) return { ok: false, error: `GET ${FOLDERS_ROUTE}: unexpected response shape` }
return { ok: true, snapshot }
}
/** Build a bounded abort signal when the runtime supports it. */
function saveSignal(): AbortSignal | undefined {
if (typeof AbortSignal === 'undefined' || typeof AbortSignal.timeout !== 'function') return undefined
return AbortSignal.timeout(SAVE_TIMEOUT_MS)
}
/**
* Store the whole folder overlay.
* Store the whole folder overlay with an optimistic-concurrency check.
*
* 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 expectedRevision - revision the document was derived from. Pass
* undefined only for a genuinely new sidecar; the host rejects an omitted
* If-Match when a document already exists.
* @param fetchImpl - fetch implementation (injectable for tests).
* @returns the new revision from the host's echo.
* @throws {FoldersConflictError} on 409 — `current` holds the latest snapshot.
*/
export async function saveFolders(
document: FoldersDocument,
expectedRevision: string | undefined,
fetchImpl: typeof fetch = fetch,
): Promise<void> {
): Promise<string> {
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (expectedRevision !== undefined) headers['If-Match'] = expectedRevision
const signal = saveSignal()
const response = await fetchImpl(FOLDERS_ROUTE, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
headers,
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,
...(signal === undefined ? {} : { signal }),
})
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
if (!response.ok) {
if (response.status === 409) {
let current: FoldersSnapshot
try {
const parsed = parseFoldersSnapshot(await response.json())
current = parsed ?? { document: EMPTY_FOLDERS_DOCUMENT }
} catch {
current = { document: EMPTY_FOLDERS_DOCUMENT }
}
throw new FoldersConflictError(current)
}
throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
}
let body: unknown
try {
body = await response.json()
} catch {
body = undefined
}
const echoed = parseFoldersSnapshot(body)
return echoed?.revision ?? expectedRevision ?? ''
}

View File

@ -51,6 +51,19 @@ export type WorkspaceGroupsKey =
| 'folder.addError'
| 'folder.sessionError'
| 'folder.saveError'
| 'folder.loadError'
| 'folder.conflict'
| 'folder.retry'
| 'folder.reload'
| 'folder.addKind'
| 'folder.addKindSubfolder'
| 'folder.addKindWorkspace'
| 'folder.cloudNoteSubfolder'
| 'folder.mergeTitle'
| 'folder.mergeAction'
| 'folder.mergeHint'
| 'folder.mergeDone'
| 'folder.mergeFailed'
| 'folder.notReady'
| 'folder.remoteSessionUnsupported'
| 'folder.remoteHint'
@ -230,6 +243,19 @@ export const zh: WorkspaceGroupsDict = {
'folder.addError': '添加文件夹失败',
'folder.sessionError': '新建会话失败',
'folder.saveError': '文件夹保存失败',
'folder.loadError': '无法读取文件夹配置,已暂时禁用编辑以免覆盖其它工作区',
'folder.conflict': '文件夹配置已被另一个窗口更新,已载入最新版本。',
'folder.retry': '请确认后重试刚才的操作。',
'folder.reload': '重新加载',
'folder.addKind': '云端添加方式',
'folder.addKindSubfolder': '本项目子目录',
'folder.addKindWorkspace': '独立云端工作区',
'folder.cloudNoteSubfolder': '会在项目云端根目录下新建该目录并挂进来;不会注册第二个镜像工作区',
'folder.mergeTitle': '合并成一个总文件夹',
'folder.mergeAction': '生成总文件夹并添加为工作区',
'folder.mergeHint': '在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。',
'folder.mergeDone': '已生成总文件夹:',
'folder.mergeFailed': '生成总文件夹失败',
'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',
'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',
'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',
@ -408,6 +434,19 @@ export const en: WorkspaceGroupsDict = {
'folder.addError': 'Could not add the folder',
'folder.sessionError': 'Could not start a session',
'folder.saveError': 'Could not save folders',
'folder.loadError': 'Could not read the folder overlay. Editing is disabled so a failed read cannot overwrite every other workspace.',
'folder.conflict': 'Another window updated the folder overlay; the newest version has been loaded.',
'folder.retry': 'Please check it and retry the operation.',
'folder.reload': 'Reload',
'folder.addKind': 'Cloud add mode',
'folder.addKindSubfolder': 'Subfolder of this project',
'folder.addKindWorkspace': 'Standalone cloud workspace',
'folder.cloudNoteSubfolder': 'Creates that directory under this project’s remote root and attaches it; no second mirror workspace is registered',
'folder.mergeTitle': 'Merge into one folder',
'folder.mergeAction': 'Create the merged folder as a workspace',
'folder.mergeHint': 'Builds one directory that links these folders side by side and registers it as a workspace. Nothing is copied or moved; sessions in that workspace can read and write all of them.',
'folder.mergeDone': 'Merged folder created: ',
'folder.mergeFailed': 'Could not build the merged folder',
'folder.notReady': 'Directory safety information is not loaded. Restart DSH and refresh the page before retrying.',
'folder.remoteSessionUnsupported': 'This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.',
'folder.remoteHint': 'Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.',

View File

@ -0,0 +1,36 @@
/**
* Pure helpers for comparing remote directory paths.
*
* Kept out of `FoldersDialog.tsx` so the alias-vs-absolute rule can be unit
* tested without mounting React. The remote browser always returns an ABSOLUTE
* path (`pwd -P`), while the SSH catalogue may store `~/projects/app`; comparing
* those two spellings directly is what used to make every browsed subdirectory
* look like a brand-new cloud workspace.
*/
/** Unify separators and drop trailing slashes so two spellings compare equal. */
export function normalizeRemotePath(value: string): string {
let result = value.trim().replaceAll('\\', '/')
while (result.length > 1 && result.endsWith('/')) result = result.slice(0, -1)
return result
}
/**
* Relative path of `picked` inside `root`: '' for the root itself, null outside.
* `root` must be an ABSOLUTE remote path; an alias can never be matched
* reliably against the absolute path the remote browser returns, so we refuse
* to guess rather than misclassifying a child folder.
*/
export function subfolderOf(root: string | null, picked: string): string | null {
if (root === null) return null
const base = normalizeRemotePath(root)
const target = normalizeRemotePath(picked)
if (base === '' || target === '') return null
if (base === '~' || base.startsWith('~/')) return null
if (base === target) return ''
if (!target.startsWith(`${base}/`)) return null
const relative = target.slice(base.length + 1)
if (relative === '') return null
if (relative.split('/').some(segment => segment === '' || segment === '.' || segment === '..')) return null
return relative
}

View File

@ -63,14 +63,13 @@ import {
IconPinOutlineRegular,
IconPlanOutlineMedium,
IconPlusOutlineRegular,
IconProjectAddOutlineRegular,
IconProjectAddOutlineMedium,
IconRightUpOutlineRegular,
IconShieldOutlineMedium,
IconSkillOutlineMedium,
IconSlidersTwoOutlineRegular,
IconSparkleMedium,
IconTreeCornerMedium,
IconTriangleRightFillMedium,
IconTrashOutlineRegular,
IconUsersOutlineMedium,
IconWorkspaceTreeOutlineMedium,
@ -298,7 +297,7 @@ export function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace
onDrop={onRowDrop}
>
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
<IconTriangleRightFillMedium />
<span aria-hidden="true" style={{ display: 'block', width: 0, height: 0, borderTop: '4px solid transparent', borderBottom: '4px solid transparent', borderLeft: '5px solid currentColor' }} />
</span>
<span className="wgCategoryIcon" data-wg-row-icon="group">
<CategoryGlyph
@ -426,12 +425,14 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
onDrop={onRowDrop}
>
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
<IconTriangleRightFillMedium />
<span aria-hidden="true" style={{ display: 'block', width: 0, height: 0, borderTop: '4px solid transparent', borderBottom: '4px solid transparent', borderLeft: '5px solid currentColor' }} />
</span>
<span className="wgCategoryIcon" data-wg-row-icon="project">
{/* Project rows use the project glyph (same as the official workspace
browser) so groups (folder glyph) and projects stay distinguishable. */}
<IconProjectAddOutlineRegular />
browser) so groups (folder glyph) and projects stay distinguishable.
Medium stroke like every other row glyph: the thin Regular artwork
turns into a grey blob once the sidebar shrinks it. */}
<IconProjectAddOutlineMedium size={16} />
</span>
<span className="wgProjectLabel" title={node.path}>{node.label}</span>
{/* Same trailing-slot contract as groups and folders: the count and the
@ -536,7 +537,7 @@ export function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove
onClick={onToggle}
>
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
<IconTriangleRightFillMedium />
<span aria-hidden="true" style={{ display: 'block', width: 0, height: 0, borderTop: '4px solid transparent', borderBottom: '4px solid transparent', borderLeft: '5px solid currentColor' }} />
</span>
<span className="wgCategoryIcon" data-wg-row-icon="folder">
{node.expanded ? <IconFolderOpenMedium /> : <IconFolderCloseMedium />}

View File

@ -9,6 +9,14 @@
overflow:hidden;
}
/* Remote SSH's legacy title matcher appends a globe to the first SVG it
finds. Our row starts with a disclosure slot, so the badge can land on the
wrong icon. Suppress only that injected decoration within this tree; keep
the node in place so the remote plugin's observer does not reinsert it. */
.wgRoot [data-rssh-globe] {
display:none !important;
}
.wgSectionHeader {
flex:none;
align-items:center;
@ -274,6 +282,15 @@
align-items:center;
transition:transform .12s;
display:inline-flex;
/* The slot owns exactly ONE glyph. Clip it so nothing that lands here from
another layer (an overlay, a duplicated svg) can paint a second shape on top
of the triangle — that stray shape reads as a broken, mushy icon. */
overflow:hidden;
}
/* Keep only the first svg in the slot; a second one is never part of a row. */
.wgChevron > svg:not(:first-child) {
display:none;
}
.wgChevronOpen {
@ -286,6 +303,17 @@
justify-content:center;
align-items:center;
display:inline-flex;
/* Fixed 16px slot: without an explicit box the glyph was free to be squashed
by the row's flex track, which turned the project folder into a grey blob. */
width:16px;
height:16px;
}
.wgCategoryIcon > svg {
display:block;
width:16px;
height:16px;
flex:none;
}
.wgCategoryLabel {

View File

@ -21,11 +21,7 @@ import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCa
import {
absorbedWorkspaceIds,
EMPTY_FOLDERS_DOCUMENT,
effectiveFolders,
entryFor,
folderOfCwd,
rootOf,
samePath,
type FoldersDocument,
type WorkspaceFolderEntry,
} from '../core/folders.ts'
@ -121,8 +117,10 @@ export interface WorkspaceGroupNode {
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.
* folder: root first, then stored order. The base directory is never a row —
* it is the workspace row itself, and its sessions live in {@link sessions}.
* Absent means "this workspace has exactly one directory", the plain
* pre-folders node shape.
*/
folders?: readonly FolderNode[]
}
@ -312,14 +310,16 @@ function projectHoldsSession(
return members.some(member => member.sessionIds.includes(sessionId))
}
/**
* 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.
* Display label of one folder: the last path segment. A drive root 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, '')
*/
export function folderLabel(path: string): string {
const trimmed = path.replace(/[/\u005C]+$/u, '')
if (trimmed === '' || /^[A-Za-z]:$/u.test(trimmed)) return path
const base = trimmed.split(/[/\\]/u).pop()
const base = trimmed.split(/[/\u005C]/u).pop()
return base !== undefined && base !== '' ? base : path
}
@ -329,87 +329,22 @@ export function folderKey(workspaceId: WorkspaceId, path: string): string {
}
/**
* Display labels for member folders.
*
* A cloud member's directory is a locally generated mirror id (`wabc123`), which
* says nothing to the user: its REMOTE path or title is the honest label. Local
* members keep the last path segment, like every other folder.
* @param folders - per-workspace folders + members.
*/
function memberFolderLabels(entry: WorkspaceFolderEntry | undefined): Map<string, string> {
const labels = new Map<string, string>()
for (const member of entry?.members ?? []) {
const label = member.kind === 'remote'
? (member.title ?? folderLabel(member.remotePath ?? member.path))
: folderLabel(member.path)
if (label !== '') labels.set(member.path, label)
}
return labels
}
/**
* 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.
* A workspace's extra folders are extra DIRECTORIES of the same project, not
* extra session lists: every visible session of the workspace and of its member
* workspaces renders on the one workspace row. Folder rows were removed on
* request — a project reads as one row, and a cloud workspace's mirror id
* (`wmvl31c7ilkuc`) never surfaces as a folder name.
* @param sessions - every visible session of the workspace + its members.
*/
function applyFolders(
workspaceId: WorkspaceId,
workspacePath: string,
_workspaceId: WorkspaceId,
_workspacePath: string,
sessions: readonly SessionNode[],
list: SessionListState,
entry: WorkspaceFolderEntry | undefined,
collapsedFolders: ReadonlySet<string> | undefined,
_list: SessionListState,
_entry: WorkspaceFolderEntry | undefined,
_collapsedFolders: ReadonlySet<string> | undefined,
): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {
const labels = memberFolderLabels(entry)
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: labels.get(path) ?? 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 }
return { sessions }
}
/**

View File

@ -1,20 +1,21 @@
/**
* Recognising the Host's own default workspace ("默认工作区").
*
* The workspace snapshot carries no `isDefault` flag, so the only Host-owned
* signal is the one the Host itself uses: the registry title. Its
* `workspaceDisplayTitle()` treats a title equal to `DEFAULT_WORKSPACE_DIRECTORY`
* as "the default workspace" and swaps in a localized label. That constant lives
* in the workspace-controller package, which this plugin must not import at
* runtime (it is a client bundle), so the string is mirrored here.
* The workspace snapshot carries no `isDefault` flag, so we mirror the two
* Host-owned signals here (the registry title and the Host's own directory
* layout); the constants live in the workspace-controller package, which this
* plugin must not import at runtime because it is a client bundle.
*
* Two Host signals are combined:
* - the registry title (primary: exactly what the Host substitutes for);
* - the Host's own directory layout (`<Documents>/deepseek-harness/default-workspace`),
* which still identifies the workspace after the user renames it.
* A user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT treated as the default workspace, and no single
* directory name is used as the sole test.
* The PATH is the primary signal: `<Documents>/deepseek-harness/default-workspace`
* still identifies the default workspace after the user renames it, and a
* user-created directory that merely happens to be called "default-workspace"
* somewhere else on disk is NOT the Host default workspace. The TITLE is only
* a fallback for snapshots that carry no usable path at all.
*
* (An earlier version checked the title FIRST and returned true immediately.
* That silently re-classified any workspace the user renamed to
* "default-workspace" as the Host default, hiding it from the sidebar, and
* contradicted the guarantee in the comment above.)
*/
/** Directory name the Host uses for its default workspace (host mirror). */
@ -33,14 +34,16 @@ export interface DefaultWorkspaceIdentity {
/**
* Whether a workspace snapshot is the Host's default workspace.
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
* @param workspace - workspace snapshot (path is primary, title is a fallback
* for path-less snapshots).
*/
export function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean {
if (workspace.title?.trim().toLowerCase() === DEFAULT_WORKSPACE_TITLE) return true
const path = (workspace.path ?? '').replace(/[/\\]+$/u, '')
if (path === '') return false
const segments = path.split(/[/\\]+/u)
const base = segments[segments.length - 1]?.toLowerCase()
return base === DEFAULT_WORKSPACE_TITLE
&& segments.some(segment => segment.toLowerCase() === HOST_STATE_DIRECTORY)
if (path !== '') {
const segments = path.split(/[/\\]+/u)
const base = segments[segments.length - 1]?.toLowerCase()
return base === DEFAULT_WORKSPACE_TITLE
&& segments.some(segment => segment.toLowerCase() === HOST_STATE_DIRECTORY)
}
return workspace.title?.trim().toLowerCase() === DEFAULT_WORKSPACE_TITLE
}

View File

@ -15,6 +15,12 @@
*
* 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.
*
* Path rules are deliberately SHARED with the host validator. Both sides
* import from this module instead of re-deriving platform-dependent rules:
* a sidecar can legitimately hold Windows and POSIX spellings at once (a
* Windows client with a POSIX remote mirror, WSL, or a synced config), so
* absolute-path tests are made by SPELLING, never by `process.platform`.
*/
/** Kind of a member folder: a plain local directory, or an SSH-mirrored one. */
@ -76,11 +82,30 @@ const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u
/** `\\server\share` — a Windows UNC path. */
const WINDOWS_UNC = /^\\\\/u
/** A drive-relative spelling (`C:foo`) that is NOT an absolute path. */
const WINDOWS_DRIVE_RELATIVE = /^[A-Za-z]:/u
const BACKSLASH = '\\'
const SLASH = '/'
/** True for both Windows path spellings accepted by the write validator. */
function isWindowsStyle(path: string): boolean {
export function isWindowsStyle(path: string): boolean {
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
}
/**
* Absolute-path test by SPELLING, not by the current platform.
*
* The host write validator and this module must agree on exactly one rule.
* Earlier the host branched on `process.platform`, so a sidecar written on
* one platform was silently truncated when read on another (and then written
* back truncated). Accepting every spelling here keeps both sides consistent.
* @param path - raw path as stored or picked.
*/
export function isAbsoluteFolderPath(path: string): boolean {
return WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path) || path.startsWith(SLASH)
}
/**
* One path with trailing separators removed, spelling preserved (no case
* folding) — the form to STORE. A drive/UNC/root prefix keeps its separator.
@ -88,31 +113,68 @@ function isWindowsStyle(path: string): boolean {
*/
function withoutTrailingSeparator(path: string): string {
if (isWindowsStyle(path)) {
let value = path.replaceAll('/', '\\')
while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1)
let value = path.replaceAll(SLASH, BACKSLASH)
while (value.length > 3 && value.endsWith(BACKSLASH)) value = value.slice(0, -1)
return value
}
let value = path
while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
while (value.length > 1 && value.endsWith(SLASH)) value = value.slice(0, -1)
return value
}
/**
* 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.
* Lexically collapse `.` and `..` segments without touching the filesystem.
*
* A `..` that would climb above the root is dropped rather than escaping it,
* so `C:\a\..\b` and `C:\b` (or `/a/../b` and `/b`) compare equal. This is a
* pure string operation: symlinks and realpath are deliberately out of scope,
* but the previous behaviour — treating every spelling as unrelated — made
* session grouping and de-duplication silently wrong.
* @param value - separator-normalized path with trailing separators removed.
* @param windows - whether the spelling is Windows-style.
*/
function collapseSegments(value: string, windows: boolean): string {
let leading = ''
if (windows) {
const drive = /^[A-Za-z]:\\/u.exec(value)
if (drive !== null) leading = drive[0]
else if (value.startsWith('\\\\')) leading = '\\\\'
} else if (value.startsWith(SLASH)) {
leading = SLASH
}
const out: string[] = []
for (const segment of value.slice(leading.length).split(windows ? /[\\/]+/u : /\/+/u)) {
if (segment === '' || segment === '.') continue
if (segment === '..') {
if (out.length > 0) out.pop()
continue
}
out.push(segment)
}
return leading + out.join(windows ? BACKSLASH : SLASH)
}
/**
* Comparison form of one path: trimmed, Unicode-normalized (NFC), lexically
* dot-collapsed, separator-normalized and, for Windows spellings, lower-cased
* (drive letters and file names are case-insensitive there).
*
* NFC matters on macOS/APFS, where `Café` and `Cafe\u0301` name the same
* directory; without it they became two folder rows.
* @param path - raw path as stored or picked.
* @returns the canonical comparison form.
*/
function canonicalPath(path: string): string {
const trimmed = path.trim()
const value = withoutTrailingSeparator(trimmed)
return isWindowsStyle(trimmed) ? value.toLowerCase() : value
export function canonicalPath(path: string): string {
const trimmed = path.trim().normalize('NFC')
const windows = isWindowsStyle(trimmed)
const value = collapseSegments(withoutTrailingSeparator(trimmed), windows)
return windows ? value.toLowerCase() : value
}
/**
* Path equality: case-insensitive for Windows-style paths, tolerant of
* trailing separators, exact for POSIX paths.
* trailing separators, `.`/`..` segments and Unicode normalization, exact for
* POSIX paths.
* @param a - first path.
* @param b - second path.
*/
@ -172,6 +234,25 @@ export function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): reado
return entryFor(doc, ownerWorkspaceId)?.members ?? []
}
/**
* Members that are safe to render under an owner.
*
* A member whose `workspaceId` is itself an owner (has its own entry) used to
* be skipped by {@link absorbedWorkspaceIds} but still rendered as a folder
* row by {@link effectiveFolders}: the same project appeared twice, with two
* independent session lists. The host write validator rejects such members;
* this helper makes the read side equally defensive for old sidecars.
* @param doc - folders document.
* @param ownerWorkspaceId - workspace the members hang off.
*/
export function validMembers(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[] {
const owners = new Set(Object.keys(doc.workspaces))
return membersOf(doc, ownerWorkspaceId).filter(member =>
member.workspaceId !== ''
&& member.workspaceId !== ownerWorkspaceId
&& !owners.has(member.workspaceId))
}
/**
* Member workspace id → owning workspace id.
*
@ -182,12 +263,9 @@ export function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): reado
* @param doc - folders document.
*/
export function absorbedWorkspaceIds(doc: FoldersDocument): ReadonlyMap<string, string> {
const owners = new Set(Object.keys(doc.workspaces))
const absorbed = new Map<string, string>()
for (const [ownerId, entry] of Object.entries(doc.workspaces)) {
for (const member of entry.members ?? []) {
if (member.workspaceId === '' || member.workspaceId === ownerId) continue
if (owners.has(member.workspaceId)) continue
for (const [ownerId] of Object.entries(doc.workspaces)) {
for (const member of validMembers(doc, ownerId)) {
if (!absorbed.has(member.workspaceId)) absorbed.set(member.workspaceId, ownerId)
}
}
@ -220,6 +298,9 @@ export function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | unde
/**
* Owning folder of a session cwd: the most specific (longest) effective folder
* that equals the cwd or is a proper path ancestor of it.
*
* Both sides are {@link canonicalPath}-normalized, so `..` segments and mixed
* separator spellings no longer mis-group a session into the project base.
* @param cwd - recorded session cwd; undefined means "the workspace itself".
* @param workspacePath - canonical directory of the workspace.
* @param entry - saved folder entry, if any.
@ -237,7 +318,7 @@ export function folderOfCwd(
for (const folder of effectiveFolders(workspacePath, entry)) {
const root = canonicalPath(folder)
if (root === '') continue
const separator = isWindowsStyle(root) ? '\\' : '/'
const separator = isWindowsStyle(root) ? BACKSLASH : SLASH
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
if (target !== root && !target.startsWith(prefix)) continue
if (root.length > bestLength) {
@ -272,6 +353,11 @@ export function addFolder(entry: WorkspaceFolderEntry | undefined, path: string)
* Append a workspace-backed folder. Idempotent under `samePath`: a later call
* for the same path replaces the stored member (so a re-registered workspace id
* wins) instead of stacking a duplicate row.
*
* Unlike an earlier version, re-registering a member does NOT clear a `root`
* that points at the same path: the folder still exists and still resolves in
* {@link rootOf}, so silently resetting the default session directory would
* change behaviour the user never asked for.
* @param entry - current entry, or undefined for a workspace with no extras.
* @param member - member record to store.
*/
@ -279,7 +365,7 @@ export function addMember(entry: WorkspaceFolderEntry | undefined, member: Folde
const folders = (entry?.folders ?? []).filter(folder => !samePath(folder, member.path))
const members = (entry?.members ?? []).filter(existing => !samePath(existing.path, member.path))
const root = entry?.root
const keepRoot = root === undefined || samePath(root, member.path) ? {} : { root }
const keepRoot = root === undefined ? {} : { root }
return { folders: [...folders], members: [...members, member], ...keepRoot }
}
@ -287,6 +373,9 @@ export function addMember(entry: WorkspaceFolderEntry | undefined, member: Folde
* Drop an extra folder, plain or workspace-backed. 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.
*
* Note: this is a pure data edit. Unregistering the native workspace behind a
* member is a side effect the caller must perform (and undo on a failed save).
* @param entry - current entry, or undefined.
* @param path - folder path to drop.
*/
@ -318,7 +407,8 @@ export function setRoot(entry: WorkspaceFolderEntry | undefined, path: string):
/**
* True when `path` is `base` itself or lives somewhere below it, with the same
* separator and case rules as {@link samePath}.
* separator and case rules as {@link samePath}. `..` segments are collapsed on
* both sides first, so a traversal spelling cannot fake containment.
* @param path - candidate path.
* @param base - containing directory.
*/
@ -327,7 +417,7 @@ export function isUnderBase(path: string, base: string): boolean {
const target = canonicalPath(path)
if (root === '' || target === '') return false
if (target === root) return true
const separator = isWindowsStyle(root) ? '\\' : '/'
const separator = isWindowsStyle(root) ? BACKSLASH : SLASH
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
return target.startsWith(prefix)
}
@ -349,11 +439,12 @@ export function joinSubpath(base: string, relative: string): string | null {
const root = base.trim()
const raw = relative.trim()
if (root === '' || raw === '') return null
if (WINDOWS_DRIVE.test(raw) || WINDOWS_UNC.test(raw) || raw.startsWith('/')) return null
if (WINDOWS_DRIVE.test(raw) || WINDOWS_DRIVE_RELATIVE.test(raw)
|| WINDOWS_UNC.test(raw) || raw.startsWith(SLASH)) return null
const segments = raw.split(/[\\/]+/u).filter(segment => segment !== '' && segment !== '.')
if (segments.length === 0) return null
if (segments.includes('..')) return null
const windows = isWindowsStyle(root)
const separator = windows ? '\\' : '/'
const separator = windows ? BACKSLASH : SLASH
return `${withoutTrailingSeparator(root)}${separator}${segments.join(separator)}`
}

194
src/host-farm.ts Normal file
View File

@ -0,0 +1,194 @@
/**
* A farm gathers several project folders into one real directory, so a single
* session can read and write all of them.
*
* A session's file scope is its workspace directory, so "one project, several
* folders" needs one directory that contains all of them. The farm is that
* directory: every entry is a link (a junction on Windows, a directory symlink
* elsewhere) to a folder the user already owns. Nothing is copied or moved, and
* the user's folders keep their own life.
*
* Deletion is the dangerous half. A recursive delete that followed a link would
* erase the user's real folder, so {@link removeFarm} only ever unlinks entries
* that are links, and refuses as soon as it meets a real directory.
*/
import { lstat, mkdir, readdir, realpath, rmdir, stat, symlink, unlink } from 'node:fs/promises'
import { homedir } from 'node:os'
import { basename, isAbsolute, join, relative as relativePath, resolve } from 'node:path'
/** Characters Windows refuses in a name, plus control characters. */
// \u005C is a backslash and \u002F a slash: written this way so this file holds
// no literal backslash at all.
const RESERVED_CHARS = /[\u005C\u002F:*?"<>|\u0000-\u001f]/gu
/** Device names Windows refuses as a whole entry name. */
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu
const MAX_NAME_LENGTH = 64
const WINDOWS = process.platform === 'win32'
export interface FarmLink {
/** Entry name inside the farm directory. */
readonly name: string
/** Absolute real path of the folder it points at. */
readonly target: string
}
export interface FarmResult {
/** Absolute path of the farm directory. */
readonly path: string
readonly links: readonly FarmLink[]
}
function dshHome(): string {
const configured = process.env.DSH_HOME
return configured === undefined || configured.trim() === '' ? join(homedir(), '.dsh') : configured
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
export function defaultFarmRoot(): string {
return resolve(dshHome(), 'workspace-groups', 'farms')
}
/** One directory-safe name for a farm, derived from a workspace title. */
export function farmDirectoryName(title: string): string {
const cleaned = title
.replace(RESERVED_CHARS, ' ')
.replace(/\s+/gu, ' ')
.trim()
.replace(/[. ]+$/u, '')
.slice(0, MAX_NAME_LENGTH)
.trim()
.replace(/[. ]+$/u, '')
if (cleaned === '') return 'farm'
return RESERVED_NAMES.test(cleaned) ? `_${cleaned}` : cleaned
}
function linkNameFor(target: string, taken: Set<string>): string {
const raw = basename(target).replace(RESERVED_CHARS, ' ').replace(/\s+/gu, ' ').trim() || 'folder'
const base = RESERVED_NAMES.test(raw) ? `_${raw}` : raw
let name = base
let suffix = 2
while (taken.has(name.toLowerCase())) {
name = `${base} (${suffix})`
suffix += 1
}
taken.add(name.toLowerCase())
return name
}
/**
* Delete one farm entry, and only one.
*
* A junction reports as a symbolic link to `lstat` but is a reparse point that
* `unlink` refuses; a directory symlink on POSIX removes fine with `unlink`. A
* real directory is never touched.
*/
async function unlinkEntry(path: string): Promise<void> {
const info = await lstat(path)
if (info.isDirectory() && !info.isSymbolicLink()) {
throw new Error(`farm: refusing to delete a real directory: ${path}`)
}
try {
await unlink(path)
} catch {
// Windows junction: unlink is EPERM, rmdir removes the reparse point only.
await rmdir(path)
}
}
async function discard(path: string): Promise<void> {
let entries: string[]
try {
entries = await readdir(path)
} catch {
return
}
for (const entry of entries) {
try {
await unlinkEntry(join(path, entry))
} catch {
// Best effort: a half-built farm is still better than a thrown rollback.
}
}
try {
await rmdir(path)
} catch {
// Leave it: an empty directory is harmless and the next build reports it.
}
}
/** Resolve and validate one folder the user asked to gather. */
async function resolveFolder(raw: unknown): Promise<string> {
if (typeof raw !== 'string' || raw.trim() === '') throw new Error('farm: empty folder path')
if (!isAbsolute(raw)) throw new Error(`farm: folder must be an absolute path: ${raw}`)
let real: string
try {
real = await realpath(raw)
} catch {
throw new Error(`farm: folder does not exist: ${raw}`)
}
const info = await stat(real)
if (!info.isDirectory()) throw new Error(`farm: not a directory: ${raw}`)
return real
}
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
export async function buildFarm(input: { name: string; folders: readonly unknown[] }): Promise<FarmResult> {
const seen = new Set<string>()
const targets: string[] = []
for (const raw of input.folders) {
const target = await resolveFolder(raw)
const key = WINDOWS ? target.toLowerCase() : target
if (seen.has(key)) continue
seen.add(key)
targets.push(target)
}
if (targets.length < 2) throw new Error('farm: needs at least two distinct folders')
const root = defaultFarmRoot()
const path = join(root, farmDirectoryName(String(input.name)))
await mkdir(root, { recursive: true })
try {
await mkdir(path)
} catch (error) {
const code = (error as { code?: string }).code
if (code === 'EEXIST') throw new Error(`farm: already exists, remove it first: ${path}`)
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`)
}
const taken = new Set<string>()
const links: FarmLink[] = []
try {
for (const target of targets) {
const name = linkNameFor(target, taken)
await symlink(target, join(path, name), WINDOWS ? 'junction' : 'dir')
links.push({ name, target })
}
} catch (error) {
await discard(path)
throw new Error(`farm: cannot link into ${path}: ${error instanceof Error ? error.message : String(error)}`)
}
return { path, links }
}
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
export async function removeFarm(farmPath: string): Promise<void> {
const root = defaultFarmRoot()
const target = resolve(farmPath)
const inside = relativePath(root, target)
if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) {
throw new Error(`farm: not a farm directory: ${farmPath}`)
}
const entries = await readdir(target)
for (const entry of entries) {
await unlinkEntry(join(target, entry))
}
await rmdir(target)
}

View File

@ -7,16 +7,25 @@
* 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.
* replacing it, atomically: temp file + fsync + rename), and reads tolerate
* hand-edited content (junk entries are dropped instead of thrown) — BUT a
* read that cannot even open or parse the file is now an ERROR, not an empty
* document. Previously `readFoldersDocument` swallowed EACCES/EISDIR/EBUSY and
* bad JSON; the browser then PUT the empty document back and erased every
* workspace's folders with no warning.
*
* Concurrency: every write is guarded by `If-Match: <revision>` (a hash of the
* exact bytes on disk) and serialized through a module-level promise chain, so
* two windows cannot silently overwrite each other (lost update).
*/
import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises'
import { createHash } from 'node:crypto'
import { dirname, resolve } from 'node:path'
import { homedir } from 'node:os'
import {
EMPTY_FOLDERS_DOCUMENT,
isAbsoluteFolderPath as isAbsoluteFolderPathCore,
isUnderBase,
samePath,
type FolderMember,
type FoldersDocument,
@ -33,15 +42,6 @@ export const WORKSPACE_ID_LIMIT = 200
export const FOLDER_PATH_LIMIT = 1024
export const REMOTE_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 !== ''
@ -60,28 +60,59 @@ export function defaultFoldersPath(): string {
* folders must be subdirectories of the mirror, because only those also exist on
* the remote side.
*
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
* here too — a mismatch would silently disable the distinction.
* The path is hardcoded in that plugin (it does NOT read `DSH_HOME`), so it is
* hardcoded here too. A custom `DSH_HOME` therefore makes PATH-BASED detection
* unreliable: `remoteMirrorBaseDiagnostic()` surfaces that explicitly, and
* write operations must still treat the SSH catalogue as authoritative.
*/
export function defaultRemoteMirrorBase(): string {
return resolve(homedir(), '.dsh', 'remote-workspaces')
}
/** Mirror base plus a non-fatal diagnostic when it cannot be trusted. */
export interface RemoteMirrorBaseDiagnostic {
readonly base: string
readonly warning?: string
}
/**
* True when `path` is absolute in the host platform's spelling: a drive
* letter or UNC prefix on Windows, a leading slash elsewhere.
* Report a mismatch between `$DSH_HOME` and the hard-coded remote-ssh mirror
* root. Silently returning a wrong base used to disable remote/local detection
* with no symptom at all; the UI now shows `warning` instead.
*/
export function remoteMirrorBaseDiagnostic(): RemoteMirrorBaseDiagnostic {
const base = defaultRemoteMirrorBase()
const home = process.env.DSH_HOME
if (home === undefined || home === '') return { base }
if (resolve(home) === resolve(homedir(), '.dsh')) return { base }
return {
base,
warning: `DSH_HOME is "${home}" but the remote-ssh mirror root is hard-coded to "${base}". Path-based remote detection is unreliable; SSH catalogue lookups remain authoritative.`,
}
}
/**
* Absolute-path test for SIDECAR data: delegated to `core/folders.ts` so the
* host validator and the browser tree use exactly one spelling-based rule.
* A sidecar may hold Windows and POSIX spellings at once (WSL, synced config,
* a Windows client with a POSIX mirror), so `process.platform` must not decide.
* @param path - candidate path.
*/
export function isAbsoluteFolderPath(path: string): boolean {
return isAbsoluteFolderPathCore(path)
}
/** Platform-specific test for a LOCAL path used by the remote-hint endpoint. */
function isAbsoluteHostPath(path: string): boolean {
return process.platform === 'win32'
? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
: POSIX_ABSOLUTE.test(path)
? /^[A-Za-z]:[\\/]/u.test(path) || path.startsWith('\\\\')
: path.startsWith('/')
}
/** Validate a local path for the read-only remote hint endpoint. */
export function validateRemoteHintPath(path: unknown): string {
if (typeof path !== 'string' || path.length === 0 || path.length > FOLDER_PATH_LIMIT
|| path.includes('\u0000') || !isAbsoluteFolderPath(path)) {
|| path.includes('\u0000') || !isAbsoluteHostPath(path)) {
throw new Error('remote hint path must be an absolute host path without NUL, at most 1024 characters')
}
return path
@ -113,7 +144,19 @@ function invalid(detail: string): never {
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
}
/** Trim one optional free-form string field, dropping it when unusable. */
/** True when a path contains a `..` segment that would need resolving. */
function hasTraversalSegment(path: string): boolean {
return path.split(/[\\/]+/u).includes('..')
}
/**
* Trim one optional free-form string field.
*
* Invalid values now call `fail` instead of being silently dropped: in strict
* (PUT) mode that is a 400, in tolerant (read) mode the field is dropped. The
* old asymmetry — a bad TYPE rejected the whole PUT while an over-long value
* returned 200 with the field quietly deleted — is gone.
*/
function optionalText(value: unknown, limit: number, fail: (detail: string) => void): string | undefined {
if (value === undefined) return undefined
if (typeof value !== 'string') {
@ -121,7 +164,10 @@ function optionalText(value: unknown, limit: number, fail: (detail: string) => v
return undefined
}
const text = value.trim()
if (text === '' || text.length > limit || text.includes('\u0000')) return undefined
if (text === '' || text.length > limit || text.includes('\u0000')) {
fail(`member text fields must be 1-${limit} characters without NUL`)
return undefined
}
return text
}
@ -135,6 +181,8 @@ function optionalText(value: unknown, limit: number, fail: (detail: string) => v
* @param workspaceId - owning workspace id (used in messages and as a guard).
* @param folders - plain folder paths already accepted for this workspace.
* @param members - member folders already accepted for this workspace.
* @param strict - enforce the mirror-containment invariant on writes.
* @param remoteBase - the local mirror root, for the containment check.
* @param fail - strict-mode reporter (throws) / tolerant no-op.
* @returns the normalized member, or undefined when unusable.
*/
@ -143,6 +191,8 @@ function parseMember(
workspaceId: string,
folders: readonly string[],
members: readonly FolderMember[],
strict: boolean,
remoteBase: string,
fail: (detail: string) => void,
): FolderMember | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
@ -164,6 +214,10 @@ function parseMember(
fail(`member folder path "${path}" must be absolute`)
return undefined
}
if (hasTraversalSegment(path)) {
fail(`member folder path "${path}" must not contain ".." segments`)
return undefined
}
if (folders.some(folder => samePath(folder, path)) || members.some(member => samePath(member.path, path))) {
fail(`duplicate folder path "${path}"`)
return undefined
@ -190,6 +244,16 @@ function parseMember(
}
const title = optionalText(source.title, FOLDER_PATH_LIMIT, fail)
const keepTitle = title === undefined ? {} : { title }
// A remote member's LOCAL path must be a directory inside the mirror base.
// This is the host-side backstop for "never let a remote project point at an
// unrelated local directory" (DEVELOPMENT.md / CHANGELOG.md). It is enforced
// on writes only, so older sidecars stay readable.
if (strict && kind === 'remote' && !isUnderBase(path, remoteBase)) {
fail(`remote member path "${path}" must be inside the mirror base "${remoteBase}"`)
return undefined
}
if (kind === 'local') return { path, workspaceId: memberWorkspaceId, kind, ...keepTitle }
const rawRemote = source.remotePath
@ -226,15 +290,22 @@ function parseMember(
/**
* Parse one workspace entry.
*
* A missing `folders` key is treated as an empty list: older sidecars and
* hand-edited files carry only `members`, and the old "folders is required"
* check discarded the WHOLE entry (including every member) — which the next
* full-document PUT then wrote back, permanently erasing those folders.
* @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.
* @param remoteBase - the local mirror root, for remote member containment.
* @returns the normalized entry, or undefined when nothing usable remains.
*/
function parseFolderEntry(
value: unknown,
workspaceId: string,
strict: boolean,
remoteBase: string,
): WorkspaceFolderEntry | undefined {
const fail = (detail: string): void => {
if (strict) invalid(`workspace "${workspaceId}": ${detail}`)
@ -244,20 +315,17 @@ function parseFolderEntry(
return undefined
}
const source = value as Record<string, unknown>
if (source.folders === undefined) {
fail('folders is required')
return undefined
}
if (!Array.isArray(source.folders)) {
if (source.folders !== undefined && !Array.isArray(source.folders)) {
fail('folders must be a list')
return undefined
}
if (strict && source.folders.length > FOLDERS_PER_WORKSPACE_LIMIT) {
const rawFolders: readonly unknown[] = Array.isArray(source.folders) ? source.folders : []
if (strict && rawFolders.length > FOLDERS_PER_WORKSPACE_LIMIT) {
invalid(`workspace "${workspaceId}": at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`)
}
const folders: string[] = []
for (const candidate of source.folders) {
for (const candidate of rawFolders) {
if (typeof candidate !== 'string') {
fail('folder paths must be strings')
continue
@ -279,6 +347,10 @@ function parseFolderEntry(
fail(`folder path "${path}" must be absolute`)
continue
}
if (hasTraversalSegment(path)) {
fail(`folder path "${path}" must not contain ".." segments`)
continue
}
if (folders.some(existing => samePath(existing, path))) {
fail(`duplicate folder path "${path}"`)
continue
@ -299,7 +371,7 @@ function parseFolderEntry(
invalid(`workspace "${workspaceId}": at most ${MEMBERS_PER_WORKSPACE_LIMIT} member folders`)
}
for (const candidate of source.members) {
const member = parseMember(candidate, workspaceId, folders, members, fail)
const member = parseMember(candidate, workspaceId, folders, members, strict, remoteBase, fail)
if (member !== undefined) members.push(member)
if (members.length >= MEMBERS_PER_WORKSPACE_LIMIT) break
}
@ -323,10 +395,40 @@ function parseFolderEntry(
return { folders, ...(members.length === 0 ? {} : { members }), ...(root === undefined ? {} : { root }) }
}
/**
* Drop members that point at a workspace which is itself an owner (or at the
* owner itself). Such a workspace keeps its own sidebar row AND appeared as a
* folder row of the other owner — two independent session lists for one
* project. Strict writes reject them outright (see `validateFoldersDocument`);
* this keeps old sidecars readable without showing the duplicate.
*/
function dropNestedMembers(doc: FoldersDocument): FoldersDocument {
const owners = new Set(Object.keys(doc.workspaces))
let changed = false
const workspaces: Record<string, WorkspaceFolderEntry> = {}
for (const [workspaceId, entry] of Object.entries(doc.workspaces)) {
const members = entry.members ?? []
const kept = members.filter(member =>
member.workspaceId !== workspaceId && !owners.has(member.workspaceId))
if (kept.length !== members.length) changed = true
if (kept.length === 0 && entry.folders.length === 0 && entry.root === undefined) {
changed = true
continue
}
workspaces[workspaceId] = {
...entry,
...(kept.length === 0 ? {} : { members: kept }),
}
}
return changed ? { version: 1, workspaces } : doc
}
/**
* 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.
* unknown-version document yields the empty document — but ONLY when the file
* could actually be read and parsed; `readFoldersState` is responsible for
* reporting a read/parse failure as an error.
* @param raw - parsed JSON value.
*/
export function parseFoldersDocument(raw: unknown): FoldersDocument {
@ -336,24 +438,27 @@ export function parseFoldersDocument(raw: unknown): FoldersDocument {
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
return { version: 1, workspaces: {} }
}
const remoteBase = defaultRemoteMirrorBase()
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)
for (const [rawId, value] of Object.entries(source.workspaces)) {
const workspaceId = rawId.trim()
if (workspaceId === '' || rawId.length > WORKSPACE_ID_LIMIT) continue
const entry = parseFolderEntry(value, workspaceId, false, remoteBase)
if (entry !== undefined) workspaces[workspaceId] = entry
}
return { version: 1, workspaces }
return dropNestedMembers({ 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.
* @param remoteBase - mirror root used to constrain remote members.
* @returns the normalized document to save.
* @throws when version, workspace ids, folder paths, duplicates or the root
* membership are wrong.
* @throws when version, workspace ids, folder paths, duplicates, the root
* membership or cross-workspace references are wrong.
*/
export function validateFoldersDocument(raw: unknown): FoldersDocument {
export function validateFoldersDocument(raw: unknown, remoteBase = defaultRemoteMirrorBase()): FoldersDocument {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
invalid('top-level value must be a mapping')
}
@ -363,40 +468,101 @@ export function validateFoldersDocument(raw: unknown): FoldersDocument {
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) {
for (const [rawId, value] of Object.entries(source.workspaces)) {
const workspaceId = rawId.trim()
if (workspaceId === '' || rawId.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 (workspaces[workspaceId] !== undefined) invalid(`duplicate workspace id "${workspaceId}"`)
const entry = parseFolderEntry(value, workspaceId, true, remoteBase)
if (entry !== undefined) workspaces[workspaceId] = entry
}
// Cross-entry referential integrity: a member that is itself an owner would
// be rendered twice (see dropNestedMembers). Reject it on write.
const owners = new Set(Object.keys(workspaces))
for (const [workspaceId, entry] of Object.entries(workspaces)) {
for (const member of entry.members ?? []) {
if (owners.has(member.workspaceId)) {
invalid(`workspace "${workspaceId}": member "${member.workspaceId}" is itself a folder owner`)
}
}
}
return { version: 1, workspaces }
}
/** Non-fatal diagnostic when the on-disk schema is newer than this build. */
function detectSchemaWarning(raw: unknown): string | undefined {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
const version = (raw as Record<string, unknown>).version
return version === 1
? undefined
: `unknown folders schema version ${String(version)}; editing is disabled to avoid downgrading the file`
}
/** Exact state of the sidecar, including the revision used by `If-Match`. */
export interface FoldersState {
readonly document: FoldersDocument
/** First 16 hex chars of sha256 over the exact on-disk bytes; '' when missing. */
readonly revision: string
/** True when the file does not exist (a legitimate empty overlay). */
readonly missing: boolean
readonly schemaWarning?: string
}
/** Hash the exact text so the ETag changes on every real write. */
function revisionOf(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16)
}
/**
* 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.
* Read the sidecar WITHOUT swallowing real I/O errors.
*
* ENOENT means "no overlay yet" and is a legitimate empty document. EACCES,
* EISDIR, EBUSY and invalid JSON are errors: returning an empty document for
* them was the root cause of the whole-overlay wipe, because the browser would
* PUT the empty result back on the next edit.
* @param path - overlay file path.
*/
export async function readFoldersState(path: string): Promise<FoldersState> {
let text: string
try {
text = await readFile(path, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { document: EMPTY_FOLDERS_DOCUMENT, revision: '', missing: true }
}
throw new Error(`${FOLDERS_FILE_NAME}: cannot read overlay: ${error instanceof Error ? error.message : String(error)}`)
}
let raw: unknown
try {
raw = JSON.parse(text)
} catch (error) {
throw new Error(`${FOLDERS_FILE_NAME}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`)
}
const schemaWarning = detectSchemaWarning(raw)
return {
document: parseFoldersDocument(raw),
revision: revisionOf(text),
missing: false,
...(schemaWarning === undefined ? {} : { schemaWarning }),
}
}
/**
* Legacy tolerant reader kept for the verifier scripts. New code must use
* `readFoldersState` so a read failure is not mistaken for an empty overlay.
* @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))
return (await readFoldersState(path)).document
} 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`
/** Atomically replace `path` with `json` (temp + fsync + rename). */
async function atomicWrite(path: string, json: string): Promise<void> {
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')
@ -415,6 +581,65 @@ export async function writeFoldersDocument(path: string, document: FoldersDocume
await unlink(tmp).catch(() => {})
throw error
}
// fsync the parent directory so the rename itself survives a crash.
// Best-effort: Windows and some filesystems reject opening a directory.
try {
const dir = await open(dirname(path), 'r')
try { await dir.sync() } finally { await dir.close() }
} catch { /* not supported on this filesystem */ }
}
/**
* Atomically replace the overlay file. Kept as the public single-document
* writer used by the verifier scripts; the HTTP route uses
* `replaceFoldersDocument` instead, which adds the CAS guard.
* @param path - target file path.
* @param document - validated document to persist.
*/
export async function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void> {
await atomicWrite(path, `${JSON.stringify(document, null, 2)}\n`)
}
/** Outcome of a guarded replace. */
export type FoldersReplaceResult =
| { readonly ok: true; readonly revision: string }
| { readonly ok: false; readonly kind: 'conflict'; readonly state: FoldersState }
/** Serializes read → compare → write so concurrent PUTs cannot interleave. */
let writeChain: Promise<unknown> = Promise.resolve()
/**
* Compare-and-swap the whole overlay under a per-process write lock.
*
* `expectedRevision` must be the revision the caller's document was derived
* from. A mismatch returns `conflict` with the server's current state; the
* route answers 409 with that document so the client can reload instead of
* overwriting. Omitting If-Match is allowed only when the sidecar does not
* exist yet (first write).
* @param path - overlay file path.
* @param expectedRevision - `If-Match` value, or undefined.
* @param document - already validated document to persist.
*/
export async function replaceFoldersDocument(
path: string,
expectedRevision: string | undefined,
document: FoldersDocument,
): Promise<FoldersReplaceResult> {
const task = async (): Promise<FoldersReplaceResult> => {
const current = await readFoldersState(path)
// An unknown on-disk schema must never be downgraded to v1, even when the
// caller somehow holds a matching revision. Report it as a conflict so the
// client reloads, sees schemaWarning and keeps editing disabled.
if (!current.missing && (current.schemaWarning !== undefined || expectedRevision !== current.revision)) {
return { ok: false, kind: 'conflict', state: current }
}
const json = `${JSON.stringify(document, null, 2)}\n`
await atomicWrite(path, json)
return { ok: true, revision: revisionOf(json) }
}
const run = writeChain.then(task, task)
writeChain = run.catch(() => undefined)
return run
}
// Do not copy remote-ssh records into subdirectories. Remote-ssh 2.4.40
@ -427,12 +652,20 @@ export async function writeFoldersDocument(path: string, document: FoldersDocume
*
* The remote path is POSIX (the server's), so this never uses `node:path`:
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
*
* Absolute inputs (POSIX `/…`, Windows drive `C:…`, UNC `\\…`) are rejected,
* matching `core/folders.ts:joinSubpath`. The old version stripped leading
* slashes, so `/etc/x` became `etc/x` on the remote while the local mirror
* side rejected it — the two sides disagreed about the same folder.
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
* @param relativePath - subpath inside the mirror, either separator style.
* @returns the remote counterpart, or null for an empty or escaping subpath.
* @returns the remote counterpart, or null for an empty, absolute or escaping subpath.
*/
export function remoteSubpath(remotePath: string, relativePath: string): string | null {
const rel = relativePath.trim().replace(/\\/gu, '/').replace(/^\/+|\/+$/gu, '')
const raw = relativePath.trim()
if (raw === '') return null
if (/^[A-Za-z]:/u.test(raw) || raw.startsWith('\\') || raw.startsWith('/')) return null
const rel = raw.replace(/\\/gu, '/').replace(/^\/+|\/+$/gu, '')
if (rel === '') return null
if (rel.split('/').some(segment => segment === '..' || segment === '.')) return null
const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '')

View File

@ -13,15 +13,23 @@
* (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.
* plus each workspace's root folder, a `revision` (ETag) and remote-mirror
* diagnostics. A read/parse failure is a 500, never an empty document.
* - `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.
* Strictly validated (absolute paths, no duplicates, root membership,
* remote-mirror containment), guarded by `If-Match: <revision>` and written
* atomically under a serialized compare-and-swap. A stale revision returns
* 409 with the current document; the accepted document and new revision are
* echoed back.
* - `POST /workspace-groups/folders` — deprecated; returns 410 without reading
* the payload or touching remote-ssh records.
*
* - `GET /workspace-groups/remote-hint?path=...` — presence-only marker hint
* at the requested absolute path or ancestors; never returns marker content.
* at the requested absolute path or ancestors; never returns marker content;
* - `POST /workspace-groups/farm` — gather several folders into one real
* directory of links, so a single session can reach all of them;
* - `DELETE /workspace-groups/farm?path=...` — remove such a farm; only links
* are unlinked, meeting a real directory aborts.
*
* Core workspace.json / session storage is never touched.
*/
@ -46,13 +54,16 @@ import {
} from './host-tabs.ts'
import {
defaultFoldersPath,
defaultRemoteMirrorBase,
hasRemoteMarkerHint,
readFoldersDocument,
readFoldersState,
remoteMirrorBaseDiagnostic,
replaceFoldersDocument,
validateFoldersDocument,
validateRemoteHintPath,
writeFoldersDocument,
type FoldersState,
type RemoteMirrorBaseDiagnostic,
} from './host-folders.ts'
import { buildFarm, removeFarm } from './host-farm.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'workspace-groups-local'
@ -60,9 +71,20 @@ export const name = 'workspace-groups-local'
/** Services required before mounting: the webserver route. */
export const inject = ['webServer']
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
/** Cap on the manual/tabs PUT body: those overlays are tiny. */
const MAX_MANUAL_BODY_BYTES = 64 * 1024
/**
* Cap on the folder PUT body.
*
* This must NOT reuse `MAX_MANUAL_BODY_BYTES`: the folder validator allows up
* to 32 folders and 16 members per workspace, each with up to 1024-character
* paths, so a single perfectly legal workspace can exceed 64 KiB. A 64 KiB cap
* meant that once a document grew past it, every further edit returned 413 and
* the overlay became un-editable. 1 MiB is still a hard bound against abuse.
*/
const MAX_FOLDERS_BODY_BYTES = 1024 * 1024
/** Error with an HTTP status, mapped to a plain-text 4xx/5xx response. */
class HttpError extends Error {
constructor(readonly status: number, message: string) {
@ -118,6 +140,51 @@ async function readBody(req: IncomingMessage, limit: number): Promise<string> {
return Buffer.concat(chunks).toString('utf8')
}
/**
* The one response envelope shared by GET, PUT echo and 409.
*
* GET and PUT used to disagree: GET added `remoteBase`, PUT echoed only the
* document. A client that replaced its state with the PUT response lost
* `remoteBase` until the next reload. Both now carry the same diagnostics plus
* the exact revision, so the client can render what the host accepted AND keep
* its optimistic-concurrency token.
*/
function foldersEnvelope(
state: FoldersState,
diagnostic: RemoteMirrorBaseDiagnostic,
revision = state.revision,
): Record<string, unknown> {
return {
...state.document,
remoteBase: diagnostic.base,
...(diagnostic.warning === undefined ? {} : { remoteBaseWarning: diagnostic.warning }),
...(state.schemaWarning === undefined ? {} : { schemaWarning: state.schemaWarning }),
revision,
}
}
/** Turn an HTTP If-Match value (possibly quoted / weak) into a bare revision. */
function normalizeEtag(value: string): string {
return value.trim().replace(/^W\//u, '').replace(/^"|"$/gu, '')
}
/** Send a JSON folder envelope with the standard no-store headers. */
function sendFolders(
res: ServerResponse,
status: number,
body: string,
revision: string,
method?: string,
): void {
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'ETag': `"${revision}"`,
'Content-Length': Buffer.byteLength(body),
})
res.end(method === 'HEAD' ? undefined : body)
}
/** Plugin body: mount the config snapshot route and the overlay write route. */
export function apply(ctx: GroupsContext): void {
const configPath = defaultConfigPath()
@ -289,18 +356,19 @@ export function apply(ctx: GroupsContext): void {
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. `remoteBase` rides along
// so the browser knows which projects are remote-ssh mirrors and must
// only accept subdirectories of their own mirror as extra folders.
const document = await readFoldersDocument(foldersPath)
const body = JSON.stringify({ ...document, remoteBase: defaultRemoteMirrorBase() })
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)
// A read failure is an ERROR, never an empty document. The old reader
// swallowed EACCES / EISDIR / EBUSY / torn JSON and returned 200 + {},
// which the browser then PUT back, erasing every workspace's folders.
// `revision` is the ETag that PUT must echo in If-Match.
let state: FoldersState
try {
state = await readFoldersState(foldersPath)
} catch (error) {
writeError(res, 500, `workspace-groups: cannot read folder overlay: ${error instanceof Error ? error.message : String(error)}`)
return
}
const diagnostic = remoteMirrorBaseDiagnostic()
sendFolders(res, 200, JSON.stringify(foldersEnvelope(state, diagnostic)), state.revision, req.method)
return
}
if (req.method === 'POST') {
@ -315,34 +383,113 @@ export function apply(ctx: GroupsContext): void {
}
let raw: unknown
try {
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES))
} catch (error) {
const status = error instanceof HttpError ? error.status : 400
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const diagnostic = remoteMirrorBaseDiagnostic()
let document
try {
document = validateFoldersDocument(raw)
// The host is the final trust boundary: remote members must stay inside
// the mirror base, not just in the browser's own checks.
document = validateFoldersDocument(raw, diagnostic.base)
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const ifMatch = req.headers?.['if-match']
const expectedRevision = typeof ifMatch === 'string' ? normalizeEtag(ifMatch) : undefined
let result
try {
await writeFoldersDocument(foldersPath, document)
// Serialized read -> compare -> write. A concurrent second writer either
// wins first and this one sees a changed revision (409), or waits.
result = await replaceFoldersDocument(foldersPath, expectedRevision, 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)
if (!result.ok) {
// 409 carries the CURRENT server document so the client can reload and
// re-apply its change instead of silently overwriting it.
const body = JSON.stringify(foldersEnvelope(result.state, diagnostic))
sendFolders(res, 409, body, result.state.revision)
return
}
// Echo the normalized document AND the new revision: the client renders
// exactly what the host accepted and chains the next write from it.
const body = JSON.stringify(foldersEnvelope(
{ document, revision: result.revision, missing: false },
diagnostic,
))
sendFolders(res, 200, body, result.revision)
},
}), '@dsh-xhl/workspace-groups: /workspace-groups/folders route')
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/workspace-groups/farm',
handler: async (req, res) => {
if (req.method === 'POST') {
let raw: unknown
try {
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES))
} catch (error) {
const status = error instanceof HttpError ? error.status : 400
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const body = raw as { name?: unknown; folders?: unknown } | null
if (body === null || typeof body !== 'object' || !Array.isArray(body.folders)) {
writeError(res, 400, 'workspace-groups: farm needs { name, folders: string[] }')
return
}
let result
try {
// Nothing is copied: every entry is a link to a folder the user owns.
result = await buildFarm({
name: typeof body.name === 'string' ? body.name : 'farm',
folders: body.folders,
})
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify(result)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
if (req.method === 'DELETE') {
const url = new URL(req.url ?? '/', 'http://localhost')
const target = url.searchParams.get('path')
if (target === null || target.trim() === '') {
writeError(res, 400, 'workspace-groups: farm needs ?path=')
return
}
try {
// Unlinks entries only; a real directory inside aborts the removal
// instead of being deleted with everything under it.
await removeFarm(target)
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify({ ok: true })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
writeError(res, 405, 'method not allowed')
},
}), '@dsh-xhl/workspace-groups: /workspace-groups/farm route')
}

151
tests/farm.test.ts Normal file
View File

@ -0,0 +1,151 @@
/**
* A farm is the only supported way to put several folders inside one workspace,
* so these tests pin its two dangerous properties: the folders themselves are
* never written to, and removal never deletes anything but links.
*/
import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { buildFarm, defaultFarmRoot, farmDirectoryName, removeFarm } from '../src/host-farm.ts'
const previousHome = process.env.DSH_HOME
let scratch = ''
beforeEach(async () => {
scratch = await mkdtemp(join(tmpdir(), 'wg-farm-'))
process.env.DSH_HOME = join(scratch, 'dsh-home')
await mkdir(process.env.DSH_HOME, { recursive: true })
})
afterEach(async () => {
// Remove farms first: their entries are links, and a recursive delete that
// walked into one would erase the fixture folders of another test.
try {
for (const name of await readdir(defaultFarmRoot())) {
try {
await removeFarm(join(defaultFarmRoot(), name))
} catch {
// A deliberately planted real directory: the scratch delete below is
// safe because it holds no links any more.
}
}
} catch {
// No farm root: nothing was built.
}
if (previousHome === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previousHome
await rm(scratch, { recursive: true, force: true })
})
async function folder(...segments: string[]): Promise<string> {
const path = join(scratch, ...segments)
await mkdir(path, { recursive: true })
return path
}
describe('farm directory', () => {
it('gathers every folder into one directory of links', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'demo', folders: [alpha, beta] })
expect(farm.path).toBe(join(defaultFarmRoot(), 'demo'))
expect(farm.links.map(link => link.name)).toEqual(['alpha', 'beta'])
expect(farm.links.map(link => link.target)).toEqual([alpha, beta])
// A write through the farm lands in the real folder: that is the whole
// point of the feature, so it is asserted rather than assumed.
await writeFile(join(farm.path, 'alpha', 'note.txt'), 'hello', 'utf8')
expect(await readFile(join(alpha, 'note.txt'), 'utf8')).toBe('hello')
})
it('keeps two folders that share a name apart', async () => {
const one = await folder('x', 'project')
const two = await folder('y', 'project')
const farm = await buildFarm({ name: 'dup', folders: [one, two] })
expect(farm.links.map(link => link.name)).toEqual(['project', 'project (2)'])
expect(farm.links.map(link => link.target)).toEqual([one, two])
})
it('ignores the same folder named twice', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'twice', folders: [alpha, beta, alpha] })
expect(farm.links).toHaveLength(2)
})
})
describe('farm validation', () => {
it('refuses fewer than two distinct folders', async () => {
const alpha = await folder('alpha')
await expect(buildFarm({ name: 'solo', folders: [alpha] })).rejects.toThrow(/at least two/u)
})
it('refuses a relative path', async () => {
await expect(buildFarm({ name: 'rel', folders: ['alpha', 'beta'] }))
.rejects.toThrow(/absolute/u)
})
it('refuses a folder that does not exist', async () => {
const alpha = await folder('alpha')
await expect(buildFarm({ name: 'gone', folders: [alpha, join(scratch, 'missing')] }))
.rejects.toThrow(/does not exist/u)
})
it('refuses to reuse an existing farm', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
await buildFarm({ name: 'same', folders: [alpha, beta] })
await expect(buildFarm({ name: 'same', folders: [alpha, beta] }))
.rejects.toThrow(/already exists/u)
})
})
describe('farm removal', () => {
it('unlinks the farm but leaves the folders untouched', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
await writeFile(join(alpha, 'marker.txt'), 'keep', 'utf8')
const farm = await buildFarm({ name: 'remove', folders: [alpha, beta] })
await removeFarm(farm.path)
await expect(stat(farm.path)).rejects.toThrow()
expect(await readFile(join(alpha, 'marker.txt'), 'utf8')).toBe('keep')
expect((await stat(beta)).isDirectory()).toBe(true)
})
it('refuses a directory outside the farm root', async () => {
const elsewhere = await folder('elsewhere')
await expect(removeFarm(elsewhere)).rejects.toThrow(/not a farm directory/u)
expect((await stat(elsewhere)).isDirectory()).toBe(true)
})
it('refuses to delete a real directory planted inside a farm', async () => {
const alpha = await folder('alpha')
const beta = await folder('beta')
const farm = await buildFarm({ name: 'guard', folders: [alpha, beta] })
const real = join(farm.path, 'real')
await mkdir(real)
await expect(removeFarm(farm.path)).rejects.toThrow(/real directory/u)
expect((await stat(real)).isDirectory()).toBe(true)
})
})
describe('farm naming', () => {
it('turns a workspace title into one safe directory name', () => {
expect(farmDirectoryName('云端记忆系统(云端)')).toBe('云端记忆系统(云端)')
expect(farmDirectoryName('a/b:c')).toBe('a b c')
expect(farmDirectoryName(' ')).toBe('farm')
expect(farmDirectoryName('CON')).toBe('_CON')
expect(farmDirectoryName('trailing. ')).toBe('trailing')
})
})

296
tests/folders-cas.test.ts Normal file
View File

@ -0,0 +1,296 @@
/**
* Host-side regressions for the folder overlay's safety contract:
*
* - a real read error must produce HTTP 500, never `200 + empty document`;
* - a stale writer must get 409 with the CURRENT document, never a lost update;
* - an unknown on-disk schema must never be downgraded to v1;
* - the host must reject a remote member whose path escapes the mirror base;
* - path identity is lexical-normalized, platform-independent, and preserves
* the root when a member is re-registered.
*/
import { describe, expect, it } from 'vitest'
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { Readable } from 'node:stream'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { apply } from '../src/index.ts'
import type { GroupsContext, GroupsWebRoute } from '../src/context-types.ts'
import {
FOLDERS_FILE_NAME,
parseFoldersDocument,
readFoldersState,
remoteMirrorBaseDiagnostic,
replaceFoldersDocument,
validateFoldersDocument,
} from '../src/host-folders.ts'
import {
addMember,
canonicalPath,
isAbsoluteFolderPath,
isUnderBase,
joinSubpath,
samePath,
validMembers,
type FolderMember,
type FoldersDocument,
} from '../src/core/folders.ts'
import { isDefaultWorkspace } from '../src/core/default-workspace.ts'
type RequestResult = { status: number; text: string | undefined }
async function routeHarness(): Promise<{
home: string
request: (method: string, body?: string, headers?: Record<string, string>) => Promise<RequestResult>
restore: () => Promise<void>
}> {
const home = await mkdtemp(join(tmpdir(), 'wg-cas-'))
const previous = process.env.DSH_HOME
process.env.DSH_HOME = home
const routes: GroupsWebRoute[] = []
apply({
effect: (callback: () => unknown) => callback(),
webServer: { register: (route: GroupsWebRoute) => { routes.push(route); return () => {} } },
} as unknown as GroupsContext)
const route = routes.find(item => item.path === '/workspace-groups/folders')!
const request = async (
method: string, body?: string, headers: Record<string, string> = {},
): Promise<RequestResult> => {
const req = Readable.from(body === undefined ? [] : [body]) as IncomingMessage
req.method = method
req.headers = headers
let status = 0
let text: string | undefined
await route.handler(req, {
writeHead: (code: number) => { status = code },
end: (value?: string) => { text = value },
} as unknown as ServerResponse)
return { status, text }
}
return {
home,
request,
restore: async () => {
if (previous === undefined) delete process.env.DSH_HOME
else process.env.DSH_HOME = previous
await rm(home, { recursive: true, force: true })
},
}
}
const firstDocument: FoldersDocument = {
version: 1,
workspaces: { 'project-a': { folders: ['/work/extra-a'] } },
}
describe('folder overlay HTTP contract', () => {
it('answers 500 (not an empty document) when the overlay cannot be read', async () => {
const harness = await routeHarness()
try {
// A directory where the JSON file should be makes readFile fail with EISDIR.
await mkdir(join(harness.home, FOLDERS_FILE_NAME), { recursive: true })
const response = await harness.request('GET')
expect(response.status).toBe(500)
expect(response.text).toContain('cannot read folder overlay')
} finally {
await harness.restore()
}
})
it('rejects a stale If-Match with 409 and echoes the current document', async () => {
const harness = await routeHarness()
try {
const first = await harness.request('PUT', JSON.stringify(firstDocument))
expect(first.status).toBe(200)
const revision = (JSON.parse(first.text!) as { revision: string }).revision
expect(revision).toMatch(/^[0-9a-f]{16}$/u)
const stale = await harness.request(
'PUT',
JSON.stringify({ version: 1, workspaces: { 'project-b': { folders: ['/work/extra-b'] } } }),
{ 'if-match': 'deadbeefdeadbeef' },
)
expect(stale.status).toBe(409)
const conflict = JSON.parse(stale.text!) as Record<string, unknown>
expect(conflict.workspaces).toEqual(firstDocument.workspaces)
expect(typeof conflict.revision).toBe('string')
expect(conflict.remoteBase).toBe(remoteMirrorBaseDiagnostic().base)
const changed = { version: 1, workspaces: { 'project-a': { folders: ['/work/extra-a', '/work/extra-c'] } } }
const accepted = await harness.request('PUT', JSON.stringify(changed), { 'if-match': revision })
expect(accepted.status).toBe(200)
expect((JSON.parse(accepted.text!) as { revision: string }).revision).not.toBe(revision)
} finally {
await harness.restore()
}
})
it('serializes concurrent writes so only one wins', async () => {
const harness = await routeHarness()
try {
const first = await harness.request('PUT', JSON.stringify(firstDocument))
const revision = (JSON.parse(first.text!) as { revision: string }).revision
const a = { version: 1, workspaces: { a: { folders: ['/work/a'] } } }
const b = { version: 1, workspaces: { b: { folders: ['/work/b'] } } }
const results = await Promise.all([
harness.request('PUT', JSON.stringify(a), { 'if-match': revision }),
harness.request('PUT', JSON.stringify(b), { 'if-match': revision }),
])
expect(results.filter(result => result.status === 200)).toHaveLength(1)
expect(results.filter(result => result.status === 409)).toHaveLength(1)
} finally {
await harness.restore()
}
})
it('refuses to downgrade an unknown on-disk schema to v1', async () => {
const harness = await routeHarness()
try {
const path = join(harness.home, FOLDERS_FILE_NAME)
const future = { version: 2, workspaces: { 'project-a': { folders: ['/work/extra-a'] } } }
await writeFile(path, JSON.stringify(future), 'utf8')
const state = await readFoldersState(path)
const get = await harness.request('GET')
expect(get.status).toBe(200)
const body = JSON.parse(get.text!) as Record<string, unknown>
expect(body.schemaWarning).toContain('version 2')
expect(body.revision).toBe(state.revision)
const put = await harness.request('PUT', JSON.stringify(firstDocument), { 'if-match': state.revision })
expect(put.status).toBe(409)
expect(JSON.parse(await readFile(path, 'utf8')).version).toBe(2)
} finally {
await harness.restore()
}
})
it('keeps remoteBase in both GET and PUT echoes', async () => {
const harness = await routeHarness()
try {
const get = await harness.request('GET')
const put = await harness.request('PUT', JSON.stringify(firstDocument))
expect(JSON.parse(get.text!).remoteBase).toBe(remoteMirrorBaseDiagnostic().base)
expect(JSON.parse(put.text!).remoteBase).toBe(remoteMirrorBaseDiagnostic().base)
} finally {
await harness.restore()
}
})
})
describe('host validation hardening', () => {
it('rejects a remote member whose path escapes the mirror base', () => {
const base = join(tmpdir(), 'wg-mirror-root')
const outside: FolderMember = {
path: join(tmpdir(), 'wg-not-a-mirror', 'app'),
workspaceId: 'ws-app',
kind: 'remote',
remotePath: '/srv/app',
profileId: 'profile-1',
}
expect(() => validateFoldersDocument({
version: 1,
workspaces: { owner: { folders: [], members: [outside] } },
}, base)).toThrow()
const inside: FolderMember = { ...outside, path: join(base, 'app') }
expect(() => validateFoldersDocument({
version: 1,
workspaces: { owner: { folders: [], members: [inside] } },
}, base)).not.toThrow()
})
it('rejects a member that is also an owner workspace', () => {
expect(() => validateFoldersDocument({
version: 1,
workspaces: {
owner: { folders: ['/work/a'] },
child: {
folders: [],
members: [{ path: '/work/child', workspaceId: 'owner', kind: 'local' }],
},
},
})).toThrow()
})
it('keeps an entry whose folders key is missing but has members', () => {
const parsed = parseFoldersDocument({
version: 1,
workspaces: {
owner: { members: [{ path: '/srv/app', workspaceId: 'ws-app', kind: 'remote', remotePath: '/srv/app', profileId: 'p' }] },
},
})
expect(parsed.workspaces.owner?.members).toHaveLength(1)
})
it('rejects a traversal segment in a stored path', () => {
expect(() => validateFoldersDocument({
version: 1,
workspaces: { owner: { folders: ['/work/a/../secret'] } },
})).toThrow()
})
it('replaceFoldersDocument reports a conflict instead of throwing on a read error', async () => {
const home = await mkdtemp(join(tmpdir(), 'wg-cas-state-'))
try {
const path = join(home, FOLDERS_FILE_NAME)
await writeFile(path, '{not json', 'utf8')
await expect(readFoldersState(path)).rejects.toThrow('invalid JSON')
await expect(replaceFoldersDocument(path, 'r1', firstDocument)).rejects.toThrow('invalid JSON')
} finally {
await rm(home, { recursive: true, force: true })
}
})
})
describe('core path and identity hardening', () => {
it('collapses dot segments so a traversal cannot dodge folder ownership', () => {
expect(canonicalPath('C:\\work\\a\\..\\b')).toBe(canonicalPath('C:\\work\\b'))
expect(canonicalPath('/srv/a/../b')).toBe('/srv/b')
expect(samePath('C:\\work\\a\\..\\b', 'C:\\work\\b')).toBe(true)
expect(isUnderBase('/srv/root/../root/data', '/srv/root')).toBe(true)
})
it('normalizes Unicode to NFC', () => {
expect(canonicalPath('/work/Cafe\u0301')).toBe(canonicalPath('/work/Caf\u00e9'))
})
it('judges absolute paths by spelling, not by the host platform', () => {
expect(isAbsoluteFolderPath('C:\\work')).toBe(true)
expect(isAbsoluteFolderPath('/srv/work')).toBe(true)
expect(isAbsoluteFolderPath('relative/work')).toBe(false)
})
it('rejects drive-relative and absolute inputs in joinSubpath', () => {
expect(joinSubpath('/srv/root', 'C:foo')).toBeNull()
expect(joinSubpath('/srv/root', '/etc')).toBeNull()
expect(joinSubpath('/srv/root', '../escape')).toBeNull()
expect(joinSubpath('/srv/root', 'data')).not.toBeNull()
})
it('keeps the root when a member is re-registered at the same path', () => {
const member: FolderMember = { path: '/srv/mirror/app', workspaceId: 'ws-app', kind: 'remote', remotePath: '/srv/app', profileId: 'p' }
const withRoot = addMember({ folders: [], members: [], root: '/srv/mirror/app' }, member)
const reAdded = addMember(withRoot, { ...member, title: 'renamed' })
expect(reAdded.root).toBe('/srv/mirror/app')
})
it('drops a member that points at another owner workspace', () => {
const doc: FoldersDocument = {
version: 1,
workspaces: {
owner: { folders: [], members: [{ path: '/srv/child', workspaceId: 'child-owner', kind: 'local' }] },
'child-owner': { folders: ['/srv/child'] },
},
}
expect(validMembers(doc, 'owner')).toHaveLength(0)
})
})
describe('isDefaultWorkspace', () => {
it('does not treat an unrelated workspace merely named default-workspace as the host default', () => {
expect(isDefaultWorkspace({ path: 'C:\\my\\projects\\default-workspace', title: 'default-workspace' })).toBe(false)
})
it('still recognises the host state directory layout', () => {
expect(isDefaultWorkspace({ path: 'C:\\Users\\me\\deepseek-harness\\default-workspace', title: 'anything' })).toBe(true)
})
})

View File

@ -0,0 +1,129 @@
/**
* Client persistence contract: a failed read must never become a writable
* empty document, every write must carry an If-Match revision, and a 409 must
* surface the server's newest snapshot instead of silently retrying.
*/
import { describe, expect, it } from 'vitest'
import {
FoldersConflictError,
loadFolders,
parseFoldersSnapshot,
saveFolders,
} from '../src/client/folders-persist.ts'
import type { FoldersDocument } from '../src/core/folders.ts'
type FetchCall = { url: string; init: RequestInit | undefined }
function fakeFetch(body: unknown, status = 200): { fetchImpl: typeof fetch; calls: FetchCall[] } {
const calls: FetchCall[] = []
const response = {
ok: status >= 200 && status < 300,
status,
json: async () => body,
}
const fetchImpl = ((url: string, init?: RequestInit) => {
calls.push({ url, init })
return Promise.resolve(response)
}) as unknown as typeof fetch
return { fetchImpl, calls }
}
const document: FoldersDocument = {
version: 1,
workspaces: { 'project-a': { folders: ['C:\\work\\extra'] } },
}
describe('loadFolders', () => {
it('returns a snapshot with the host revision on success', async () => {
const { fetchImpl } = fakeFetch({ version: 1, workspaces: {}, remoteBase: '/mirror', revision: 'abc123' })
const result = await loadFolders(fetchImpl)
expect(result.ok).toBe(true)
if (!result.ok) return
expect(result.snapshot.revision).toBe('abc123')
expect(result.snapshot.remoteBase).toBe('/mirror')
})
it('fails closed on a network error instead of returning an empty document', async () => {
const fetchImpl = (() => Promise.reject(new Error('ECONNRESET'))) as unknown as typeof fetch
const result = await loadFolders(fetchImpl)
expect(result.ok).toBe(false)
if (result.ok) return
expect(result.error).toContain('ECONNRESET')
})
it('fails closed on a 500 instead of returning an empty document', async () => {
const { fetchImpl } = fakeFetch({ error: 'EACCES' }, 500)
const result = await loadFolders(fetchImpl)
expect(result.ok).toBe(false)
})
it('fails closed on malformed JSON', async () => {
const fetchImpl = (() => Promise.resolve({
ok: true, status: 200, json: async () => { throw new SyntaxError('bad json') },
})) as unknown as typeof fetch
const result = await loadFolders(fetchImpl)
expect(result.ok).toBe(false)
})
})
describe('parseFoldersSnapshot', () => {
it('keeps an entry whose folders key is missing but that has members', () => {
const snapshot = parseFoldersSnapshot({
version: 1,
revision: 'r1',
workspaces: {
'project-a': {
members: [{ path: '/srv/mirror/app', workspaceId: 'ws-app', kind: 'remote' }],
},
},
})
expect(snapshot).not.toBeNull()
expect(snapshot!.document.workspaces['project-a']?.members).toHaveLength(1)
})
it('keeps an entry that carries only a root', () => {
const snapshot = parseFoldersSnapshot({
version: 1,
workspaces: { 'project-a': { root: '/work/extra' } },
})
expect(snapshot!.document.workspaces['project-a']?.root).toBe('/work/extra')
})
it('never returns a writable empty document for an unknown schema', () => {
const snapshot = parseFoldersSnapshot({ version: 2, workspaces: {}, revision: 'r9' })
expect(snapshot!.document.workspaces).toEqual({})
expect(snapshot!.schemaWarning).toContain('version 2')
expect(snapshot!.revision).toBe('r9')
})
})
describe('saveFolders', () => {
it('sends If-Match and returns the new revision', async () => {
const { fetchImpl, calls } = fakeFetch({ version: 1, workspaces: {}, revision: 'new-rev' })
const revision = await saveFolders(document, 'old-rev', fetchImpl)
expect(revision).toBe('new-rev')
expect(calls[0]!.init?.method).toBe('PUT')
expect((calls[0]!.init?.headers as Record<string, string>)['If-Match']).toBe('old-rev')
expect((calls[0]!.init as RequestInit & { keepalive?: boolean }).keepalive).toBeUndefined()
})
it('throws FoldersConflictError with the server snapshot on 409', async () => {
const serverDocument = { version: 1, workspaces: { other: { folders: ['/elsewhere'] } }, revision: 'server-rev' }
const { fetchImpl } = fakeFetch(serverDocument, 409)
await expect(saveFolders(document, 'stale-rev', fetchImpl)).rejects.toMatchObject({
name: 'FoldersConflictError',
})
try {
await saveFolders(document, 'stale-rev', fetchImpl)
} catch (error) {
expect(error).toBeInstanceOf(FoldersConflictError)
expect((error as FoldersConflictError).current.revision).toBe('server-rev')
expect((error as FoldersConflictError).current.document.workspaces.other).toBeDefined()
}
})
it('throws a plain error on a non-409 failure', async () => {
const { fetchImpl } = fakeFetch({ error: 'disk full' }, 500)
await expect(saveFolders(document, 'r1', fetchImpl)).rejects.toThrow('PUT /workspace-groups/folders: 500')
})
})

View File

@ -52,9 +52,10 @@ describe('deprecated remote marker route', () => {
} as unknown as GroupsContext)
const route = routes.find(item => item.path === '/workspace-groups/folders')!
expect(route).toBeDefined()
const request = async (method: string, body?: string) => {
const request = async (method: string, body?: string, headers: Record<string, string> = {}) => {
const req = Readable.from(body === undefined ? [] : [body]) as IncomingMessage
req.method = method
req.headers = headers
let status = 0
let text: string | undefined
await route.handler(req, {
@ -85,10 +86,16 @@ describe('deprecated remote marker route', () => {
expect(await readFile(join(existing, '.remote-ssh.json'), 'utf8')).toBe(childMarker)
expect(await readdir(home)).toEqual(['mirror'])
const document = { version: 1, workspaces: { test: { folders: [existing] } } }
expect((await request('PUT', JSON.stringify(document))).status).toBe(200)
const put = await request('PUT', JSON.stringify(document))
expect(put.status).toBe(200)
const accepted = JSON.parse(put.text!) as Record<string, unknown>
expect(accepted).toMatchObject(document)
expect(typeof accepted.revision).toBe('string')
const response = await request('GET')
expect(response.status).toBe(200)
expect(JSON.parse(response.text!)).toEqual({ ...document, remoteBase: hostFolders.defaultRemoteMirrorBase() })
const served = JSON.parse(response.text!) as Record<string, unknown>
expect(served).toMatchObject({ ...document, remoteBase: hostFolders.defaultRemoteMirrorBase() })
expect(served.revision).toBe(accepted.revision)
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')!
expect(hintRoute).toBeDefined()

View File

@ -0,0 +1,50 @@
/**
* The alias-vs-absolute comparison that decides whether a browsed remote
* directory is a subfolder of THIS project or a brand-new cloud workspace.
*/
import { describe, expect, it } from 'vitest'
import { normalizeRemotePath, subfolderOf } from '../src/client/remote-paths.ts'
describe('normalizeRemotePath', () => {
it('unifies separators and strips trailing slashes', () => {
expect(normalizeRemotePath(' /home/me/app\\ ')).toBe('/home/me/app')
expect(normalizeRemotePath('/home/me/app///')).toBe('/home/me/app')
expect(normalizeRemotePath('/')).toBe('/')
expect(normalizeRemotePath(' ')).toBe('')
})
})
describe('subfolderOf', () => {
it('recognises an absolute child of the owner root', () => {
expect(subfolderOf('/home/me/projects/app', '/home/me/projects/app/data')).toBe('data')
expect(subfolderOf('/home/me/projects/app', '/home/me/projects/app/data/raw')).toBe('data/raw')
// Windows-style separators on either side must compare equal.
expect(subfolderOf('/home/me/projects/app\\', '/home/me/projects/app\\data')).toBe('data')
})
it('returns the empty string for the root itself', () => {
expect(subfolderOf('/home/me/projects/app', '/home/me/projects/app/')).toBe('')
})
it('refuses to guess when the owner root is still a ~ alias', () => {
expect(subfolderOf('~/projects/app', '/home/me/projects/app/data')).toBeNull()
expect(subfolderOf('~', '/home/me/data')).toBeNull()
})
it('returns null for a directory outside the owner root', () => {
expect(subfolderOf('/home/me/projects/app', '/home/me/other')).toBeNull()
expect(subfolderOf('/home/me/projects/app', '/home/me/projects/application/data')).toBeNull()
})
it('rejects traversal and empty segments', () => {
expect(subfolderOf('/srv/app', '/srv/app/../escape')).toBeNull()
expect(subfolderOf('/srv/app', '/srv/app/a/../b')).toBeNull()
expect(subfolderOf('/srv/app', '/srv/app//data')).toBeNull()
})
it('returns null for missing or blank inputs', () => {
expect(subfolderOf(null, '/srv/app/data')).toBeNull()
expect(subfolderOf('', '/srv/app/data')).toBeNull()
expect(subfolderOf('/srv/app', ' ')).toBeNull()
})
})

View File

@ -13,6 +13,7 @@ import { describe, expect, it } from 'vitest'
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
import { deriveGroups, deriveSearchGroups, deriveTopLevel } from '../src/client/tree.ts'
import type { FoldersDocument } from '../src/core/folders.ts'
import type { GroupsConfig, ManualGroups } from '../src/core/types.ts'
const CONFIG: GroupsConfig = {
@ -215,3 +216,58 @@ describe('deriveTopLevel', () => {
expect(top.map(w => w.workspaceId)).toEqual(['ws-c', 'ws-a', 'ws-b'])
})
})
/**
* A project renders as ONE row: its own directory and every extra folder share
* that workspace's session list, so a cloud project never reads as a project
* nested inside itself and its mirror id never surfaces as a folder name.
*/
describe('a project renders as one row', () => {
const MIRROR = 'C:/Users/zcol/.dsh/remote-workspaces/wmvl31c7ilkuc'
const LOCAL = 'C:/Users/zcol/云端记忆系统'
function sessionIn(id: string, cwd: string): SessionSummary {
return { ...session(id, `会话-${id}`), cwd } as unknown as SessionSummary
}
const workspaces = [
workspace('ws-o', MIRROR, '插件项目', ['s-cloud']),
workspace('ws-m', LOCAL, '云端记忆系统', ['s-local']),
]
const folders: FoldersDocument = {
version: 1,
workspaces: {
'ws-o': { folders: [], members: [{ path: LOCAL, workspaceId: 'ws-m', kind: 'local' }] },
},
}
const list = {
ids: ['s-cloud', 's-local'],
byId: {
's-cloud': sessionIn('s-cloud', `${MIRROR}/src`),
's-local': sessionIn('s-local', `${LOCAL}/docs`),
},
current: undefined,
phase: 'ready',
subagentsByParent: {},
} as unknown as SessionListState
const noManual: ManualGroups = { categories: [], assignments: {} }
const view = { expandedCategories: [], expandedWorkspaces: ['ws-o'] }
it('merges owner and member sessions and emits no folder rows', () => {
const groups = deriveGroups(list, workspaces, [], CONFIG, view, noManual, new Map(), folders)
const node = groups.flatMap(group => group.workspaces).find(w => w.workspaceId === 'ws-o')
expect(node).toBeDefined()
expect(node!.folders).toBeUndefined()
expect(node!.sessions.map(s => s.id)).toEqual(['s-cloud', 's-local'])
})
it('keeps the pre-folders node shape without extras', () => {
const groups = deriveGroups(list, workspaces, [], CONFIG, view, noManual, new Map(), {
version: 1,
workspaces: {},
})
const node = groups.flatMap(group => group.workspaces).find(w => w.workspaceId === 'ws-o')
expect(node?.folders).toBeUndefined()
expect(node?.sessions.map(s => s.id)).toEqual(['s-cloud'])
})
})

View File

@ -239,7 +239,11 @@ check(!('readRemoteMarker' in host), 'no remote connection record reader remains
equal((await request('PUT', JSON.stringify(document))).status, 200, 'normal folder PUT remains available')
const response = await request('GET')
equal(response.status, 200, 'normal folder GET remains available')
equal(JSON.parse(response.text), { ...document, remoteBase: defaultRemoteMirrorBase() }, 'GET preserves saved folders and remote mirror base')
const getBody = JSON.parse(response.text)
equal(getBody.version, 1, 'GET keeps the schema version')
equal(JSON.stringify(getBody.workspaces), JSON.stringify(document.workspaces), 'GET preserves saved folders')
equal(getBody.remoteBase, defaultRemoteMirrorBase(), 'GET reports the remote mirror base')
check(/^[0-9a-f]{16}$/u.test(getBody.revision ?? ''), 'GET reports a revision for optimistic concurrency')
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')
check(hintRoute !== undefined, 'remote hint route is registered')

View File

@ -112,7 +112,10 @@ function clientConfig(): UserConfig {
format: 'cjs',
platform: 'browser',
target: 'es2022',
sourcemap: true,
// The browser bundle used to ship `lib/client.js.map` with full
// `sourcesContent`: the entire TypeScript source went out inside the npm
// package. Plugin users never need a client sourcemap, so do not emit it.
sourcemap: false,
dts: false,
clean: false,
deps: {