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.
This commit is contained in:
qyh15 2026-11-07 17:29:57 +08:00
parent efac404c1a
commit 36b9cb2bc0
29 changed files with 3137 additions and 665 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,56 @@
# 更新日志
## 未发布 — 文件夹管理安全性与一致性修复(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`。
### 测试与工程
- 新增 `tests/folders-cas.test.ts`、`tests/folders-persist.test.ts`、`tests/remote-paths.test.ts`
覆盖上述回归点;`tsc -p tsconfig.json` / `tsconfig.client.json` 与 288 个 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` 漏带就等于重启丢配置)。

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 it is too large Load Diff

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 { 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,47 @@ 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/index.ts
@ -3321,8 +3543,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 +3611,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 +3804,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,31 +3825,37 @@ 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");
}

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, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t'];
@ -10,13 +10,18 @@ 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;
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => 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.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

@ -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.
*/

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

@ -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, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
@ -52,13 +46,18 @@ 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
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void
@ -72,6 +71,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 +84,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 +107,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 +126,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 +158,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 +198,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 +234,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) }}
>
@ -266,7 +280,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 +293,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 +323,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 +338,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 +353,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 +362,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,8 +56,8 @@ 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 { QuickPanel } from './QuickPanel.tsx'
@ -329,10 +329,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 +360,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 +784,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 +856,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 +922,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 +951,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 +969,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 +982,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 +1013,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 +1075,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 +1096,11 @@ 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))
}
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 +1123,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 +1139,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 +2161,13 @@ 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}
onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}

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,14 @@ 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.notReady'
| 'folder.remoteSessionUnsupported'
| 'folder.remoteHint'
@ -230,6 +238,14 @@ 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.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',
'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',
'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',
@ -408,6 +424,14 @@ 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.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

@ -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)}`
}

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,10 +13,14 @@
* (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.
*
@ -46,12 +50,14 @@ import {
} from './host-tabs.ts'
import {
defaultFoldersPath,
defaultRemoteMirrorBase,
hasRemoteMarkerHint,
readFoldersDocument,
readFoldersState,
remoteMirrorBaseDiagnostic,
replaceFoldersDocument,
validateFoldersDocument,
validateRemoteHintPath,
writeFoldersDocument,
type FoldersState,
type RemoteMirrorBaseDiagnostic,
} from './host-folders.ts'
/** Plugin identity for cordis.yml rows. */
@ -60,9 +66,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 +135,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 +351,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 +378,47 @@ 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')
}

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

@ -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: {