Compare commits
No commits in common. "feat/base-0.4.2" and "main" have entirely different histories.
feat/base-
...
main
|
|
@ -1,15 +1,9 @@
|
|||
node_modules/
|
||||
package-lock.json
|
||||
.lib-backup/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# 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.
|
||||
# 开发工程文件:docs 五级文档框架不进项目 git 仓库
|
||||
docs/
|
||||
AGENTS.md
|
||||
|
|
|
|||
97
CHANGELOG.md
|
|
@ -1,78 +1,49 @@
|
|||
# 更新日志
|
||||
|
||||
## 未发布 — 一个工作区收拢多个文件夹(2026-11-07)
|
||||
## 1.3.0 — 2026-11-13
|
||||
|
||||
会话的文件范围就是它所在的工作区目录,所以分散在不同位置的文件夹无法被同一个会话同时读写。
|
||||
新增「合并成一个总文件夹」:在 `$DSH_HOME/workspace-groups/farms/<名称>/` 建一个真实目录,
|
||||
用链接(Windows junction / POSIX 目录符号链接)把该项目的每个文件夹放进去,再注册成一个工作区。
|
||||
不复制、不移动、不改动原文件夹。
|
||||
### 新增 / 重构
|
||||
- **Remote-SSH 设置页重做**:统一圆角卡片与分区、页头(Remote SSH / 管理远程连接与同步设置)、折叠式「添加连接」「远程工作区」「高级设置」;「高级设置」默认收起,收起时不显示内部保存按钮,折叠只改变可见性、不清空草稿也不触发保存。
|
||||
- **我的连接**:每张卡片独立测试状态(不再因一个测试锁死全部操作),成功 / 成功但带 warning / 失败与 ssh 诊断就地显示;删除改为卡片内轻量确认并明确连接名与影响范围(复用原 `deleteProfile` 接口,不删服务器文件)。
|
||||
- **添加连接**:保留名称 / 主机 / 端口 / 用户名 / 认证方式 / 私钥路径 / 密码 / 远程根目录全部字段与条件显示;端口非法时明确报错并阻止提交(不再静默回退 22);密钥 / 密码切换保留草稿;ProxyJump 收进默认收起的「更多连接选项」(标题摘要明确提示)。
|
||||
- **从系统 SSH 配置导入**:多选弹窗(主机列表、别名 / 地址 / 用户 / 端口 / 跳板机摘要、全选 / 取消全选、已选数量、导入中 / 读取中 / 空列表 / 失败状态),保留原导入映射;修复「逐项保存未检查结果、按选择数量上报已导入」的统计错误:逐项检查返回与异常,分别统计成功 / 失败,失败项保留主机与原因,部分失败不再显示全部成功,支持仅重试失败项(成功项不重复提交),导入结束刷新连接列表,无选中禁用导入。
|
||||
- **远程工作区恢复独立配置区**:按工作区 ID 保存 `writeBack` / `writeBackExclude` / `syncPaths` / `syncExclude` / `syncMaxBytes`(界面 GiB,正确字节换算);未保存徽标;存在未保存设置时拉取 / 推送被阻止并提示先保存;拉取、推送保持既有互斥,失败后恢复可操作;删除沿用既有语义(只删本地记录与镜像映射,不删远端);无工作区显示简短空状态并指向既有创建入口。
|
||||
- **高级设置两组**:终端与写回(`nodePath` / `writeBackFailure` error|log / `writeBackFreshness`);新工作区同步默认值(`defaultSyncPaths` / `defaultSyncExclude` / `defaultSyncMaxBytes`,只影响新工作区,不覆盖已有独立配置);保存仅在展开内容中,成功 / 失败有明确反馈且失败保留草稿。
|
||||
|
||||
- 新增宿主路由 `POST /workspace-groups/farm` 与 `DELETE /workspace-groups/farm?path=`。宿主只接受绝对路径,
|
||||
不存在的目录直接拒绝,已存在的农场拒绝复用(避免静默合并到别人建的目录)。
|
||||
- 删除只解链接:遇到真实目录立刻中止,绝不递归删除,避免顺链接删掉用户的真实文件夹。
|
||||
- 侧栏「管理文件夹」对话框在该工作区有 2 个及以上文件夹时显示该操作;成功后提示新工作区路径。
|
||||
- 新增 `tests/farm.test.ts`(11 项):写入穿透链接落到真实文件夹、同名文件夹去重命名、相对/缺失目录拒绝、
|
||||
重复农场拒绝、删除后原文件夹内容不变、农场根外路径拒绝、农场内真实目录拒绝删除。
|
||||
### 实现
|
||||
- 新增 `src/client/rssh-settings/`(契约、纯逻辑模型、独立 locale 命名空间、组件与样式)。上游设置页由 `scripts/build-remote-ssh-client.mjs` 以锚点断言在构建期替换为上述源码组件,vendor 树保持原样;`verify:bundle` 与 `test:patch` 增加设置页替换、locale 命名空间与 compose 接缝的断言。
|
||||
- 全局默认配置与工作区独立配置分别读写各自接口(`savePrefs` vs `updateWorkspaceGuards`),互不覆盖。
|
||||
|
||||
## 未发布 — 文件夹管理安全性与一致性修复(2026-11-07)
|
||||
## 1.2.2 — 2026-11-13
|
||||
|
||||
针对「工作区内的文件夹管理」扫描发现的 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 秒超时,避免大文档被静默截断。
|
||||
## 1.2.1 — 2026-11-12
|
||||
|
||||
### 路径与远程判定
|
||||
- `canonicalPath` 增加 NFC 归一与词法 `.` / `..` 折叠;`isAbsoluteFolderPath` 改为按路径拼写判定,
|
||||
宿主与客户端共用同一函数,不再因 `process.platform` 漂移而丢弃跨平台 sidecar 条目。
|
||||
- `defaultRemoteMirrorBase` 硬编码 `~/.dsh/remote-workspaces` 的问题改为显式诊断:
|
||||
`$DSH_HOME` 与硬编码根不一致时 GET 返回 `remoteBaseWarning` 并在界面显示。
|
||||
- 宿主写校验现在强制 `kind:'remote'` 的 member.path 必须位于镜像根内,并拒绝 `..` 段;
|
||||
镜像归属不再只靠浏览器自觉。
|
||||
- `subfolderOf` 用浏览器返回的绝对 `resolved` 路径比较(`~` 别名由 `openFoldersFor` 先解析),
|
||||
分隔符归一;云端输入框改为显式「本项目子目录 / 独立云端工作区」二选一,消除一个输入框两种语义。
|
||||
- Farm 创建改为幂等:同一组文件夹再次执行时复用已有 farm,不再返回 HTTP 400;文件夹不同仍明确冲突,防止误合并。
|
||||
- 冲突提示改为 `already exists with different folders`,便于区分“已成功”和“配置变了”。
|
||||
|
||||
### 会话与孤儿工作区
|
||||
- 创建会话前必须等文件夹 overlay 落盘成功;原生工作区创建失败可补偿注销,远程文件夹创建有
|
||||
pending 复用,避免重复建镜像。
|
||||
- `addMember` 同路径重注册时保留 `root`;`isDefaultWorkspace` 改为路径判据优先;
|
||||
跨 entry 拒绝「member.workspaceId 同时是 owner」,宽容读会丢弃这类旧数据。
|
||||
- `parseFolderEntry` 允许缺 `folders` 字段(不再连带丢掉 members),`remoteSubpath` 与
|
||||
`joinSubpath` 对绝对/盘符/UNC 输入的判定统一;`joinSubpath` 额外拒绝 `C:foo`。
|
||||
## 1.2.0 — 2026-11-12
|
||||
|
||||
### 侧栏文件夹行
|
||||
- 一个项目只占一行。此前工作区挂上额外文件夹后,每个文件夹都会变成一条带自己会话列表的行;
|
||||
云端工作区的路径是本地镜像目录,于是侧栏出现 `wmvl31c7ilkuc` 这种内部 id,项目自身的
|
||||
会话又被藏进那一行,看起来像「一个项目套在它自己里面」。
|
||||
- 现在不再渲染文件夹行:工作区自己的目录和所有额外文件夹共用同一个会话列表,全部列在
|
||||
工作区标题下面。文件夹仍然可以在工作区的「⋯ → 管理文件夹」里增删、设根、打开,
|
||||
只是不再各自分裂出一套会话。
|
||||
- 工作区没有额外文件夹时,节点形状与引入文件夹功能之前完全一致。
|
||||
### 新增
|
||||
- **Farm 合并工作区**:把同一项目的多个文件夹(含远程镜像与本地目录)在 `$DSH_HOME/workspace-groups/farms/<名称>/` 下用 junction/目录符号链接并排挂起,再注册为一个新工作区。一个会话即可同时读取和改写这些文件夹,不复制、不移动原目录。
|
||||
- 删除 farm 只 unlink 链接,遇到真实目录立即中止,绝不递归删除用户文件夹。
|
||||
|
||||
### 测试与工程
|
||||
- 新增 `tests/folders-cas.test.ts`、`tests/folders-persist.test.ts`、`tests/remote-paths.test.ts`
|
||||
覆盖上述回归点;`tsc -p tsconfig.json` / `tsconfig.client.json` 与 290 个 vitest 用例全部通过。
|
||||
- `tsdown.config.ts` 关闭客户端 sourcemap,`lib/client.js.map`(内嵌完整源码)已从构建产物移除;
|
||||
`.gitignore` 补 `*.map` / `*.tsbuildinfo` / `dist/` / `coverage/` / `tools/_tmp/`,并取消对
|
||||
`docs/` 的忽略,把 `remote-ssh-integration-plan.md` 纳入版本控制。
|
||||
- 工作区根目录新增 README 说明目录职责;`dsh-workspace-groups-0.4.2/` 与 `tools/` 各加说明,
|
||||
标明 0.4.2 是**有意保留的重建基线,不可删除**。未删除/移动任何既有目录或文件。
|
||||
### 修复
|
||||
- 侧栏底部 `未归类` / `默认工作区` 在宿主 `[data-sidebar-scrollport]` 中占用剩余高度,真正固定在侧栏底部。
|
||||
- 撤销 1.1.1 的“同名 member 仅视觉合并”:那只是把两个 workspace 的会话画在一起,不能解决一个项目同时读写多个根目录。
|
||||
|
||||
### 仍未处理(需另行确认)
|
||||
- `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.1.0 — 2026-11-12
|
||||
|
||||
### 修复
|
||||
- 文件夹配置读取区分 loading / ready / error:HTTP 503、非成功状态与解析异常不再伪装成空分组;首次失败只显示错误与重试,已有确认数据时保留并提示刷新失败;自动重试有界退避,网络恢复后重新读取。
|
||||
- 文件夹保存改为串行队列:保存期间保留上一次服务端确认状态,成功后采用宿主回包,失败回滚;409 冲突同时保留服务端版本与未保存草稿,可显式重放,绝不静默覆盖。
|
||||
- 基础目录行使用工作区确认标题(自定义名/远程目录名),不再把本地镜像 basename(如 `w123`)当远程工作区名称;成员行优先远程目录名;路径身份不变。
|
||||
- 右侧文件树根标签改为按完整 `title` 路径精确匹配镜像路径,移除 basename + `padding-left:6px` 的脆弱 DOM 猜测;同名本地目录不会被误改。
|
||||
- 远程路径防重:新输入与历史记录都走同一规范化(`~`/相对路径/绝对路径 + 远端 `pwd -P`);目录身份包含连接 ID;SSH 解析失败时明确报“无法确认是否重复”并拒绝创建,不再 fail-open 制造重复。
|
||||
- 复用已有远程记录时保留用户自定义标题,不被新输入的路径段覆盖。
|
||||
|
||||
## 1.0.0 — 2026-10-28
|
||||
|
||||
|
|
|
|||
|
|
@ -162,25 +162,12 @@ $installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspa
|
|||
|
||||
## 6. 已知坑
|
||||
|
||||
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM);需 `danger-full-access`
|
||||
或在普通 PowerShell 终端里跑。pnpm 的 hoisted 布局偶尔缺 `@vitest/*` 顶层链接,
|
||||
这时用 `node_modules/.pnpm/vitest@*/node_modules/vitest/vitest.mjs` 加一个不 import
|
||||
`vitest/config` 的纯 JS 配置即可绕过。
|
||||
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM),在普通 PowerShell 终端里跑。
|
||||
- **`node_modules/.bin/*.CMD` 直调会挂**:pnpm 里嵌套的 pnpm 脚本在 DSH 沙箱下会
|
||||
`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 复用。
|
||||
`Could not determine executable`,统一用 `node <pnpm.cjs> <script>` 形式。
|
||||
- **单测覆盖不齐**:`tests/` 是早期版本写的,现已补 `tests/tabs.test.ts`(标签条纯逻辑:
|
||||
固定区不变量、拖动夹紧、关闭其他/右侧、持久化恢复);**快切面板
|
||||
(`quick.ts` / `QuickPanel.tsx`)与分组外观仍无单测**,改到这些区域时补。
|
||||
- **改持久化格式一律「严格写、宽容读」**:新增字段必须是可选的,旧文件读不进来不算
|
||||
错;悬挂键(如已删除的分类/会话)不得拒写,否则用户会卡在 400 上再也保存不了;
|
||||
新字段在 `restore*` 里必须原样带过去(`pinned`/`title` 漏带就等于重启丢配置)。
|
||||
|
|
|
|||
26
NOTICE.md
|
|
@ -80,3 +80,29 @@ tree search. **Those designs and implementations are the original author's work.
|
|||
project exist only for attribution and provenance.
|
||||
- Upstream remains the canonical project. Issues that exist there should be reported to the
|
||||
upstream issue tracker; this fork claims no ownership of upstream.
|
||||
|
||||
---
|
||||
|
||||
## 合并 vendored 组件:dsh-remote-ssh / Vendored component: dsh-remote-ssh
|
||||
|
||||
自 `workspace-groups-remote` 1.0.0 起,本仓库以 vendor 方式原样收录下列作品,
|
||||
与分组插件合并为同一个可安装 bundle:
|
||||
|
||||
- **项目**:https://github.com/ZhangFengshun/dsh-remote-ssh(npm 包名 `@zhangfengshun/dsh-remote-ssh`,收录版本 2.4.45)
|
||||
- **作者**:ZhangFengshun
|
||||
- **许可**:MIT License(完整文本见 `vendor/dsh-remote-ssh/LICENSE`)
|
||||
|
||||
收录范围为上游仓库的完整树(`vendor/dsh-remote-ssh/`),代码未作修改;
|
||||
合并只发生在包级别:宿主入口组合加载、客户端工厂提取、补丁行合并,
|
||||
细节见 README 的 “Merged bundle” 一节。
|
||||
|
||||
Since `workspace-groups-remote` 1.0.0 this repository vendors the work above
|
||||
verbatim under `vendor/dsh-remote-ssh/` and ships it merged with the
|
||||
workspace-groups plugin as a single installable bundle. The vendored code is
|
||||
unmodified; the merge is package-level composition (host entry, client
|
||||
factory extraction, patch rows) plus a small set of build-time patches to the shipped
|
||||
host artifact (canonical remote-path identity in createRemoteWorkspace;
|
||||
ssh argv hardening; terminal-wrapper trust tightening — all applied by
|
||||
scripts/patch-remote-ssh.mjs; the vendored tree itself is untouched),
|
||||
as documented in the README.
|
||||
|
||||
|
|
|
|||
72
README.md
|
|
@ -6,6 +6,74 @@
|
|||
|
||||
A workspace grouping plugin for DeepSeek Harness. Built on [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups), it keeps workspaces, folders, and sessions easier to organize and use from the sidebar.
|
||||
|
||||
## Merged bundle: workspace-groups-remote
|
||||
|
||||
This tree merges two DSH plugins into **one installable bundle** (package `workspace-groups-remote`):
|
||||
|
||||
- **workspace-groups** (this repository's original content): the sidebar grouping manager and session tab strip. Its host half builds from `src/` to `lib/groups.js`; its client half lives in `src/client/groups-client.ts`.
|
||||
- **@zhangfengshun/dsh-remote-ssh** 2.4.45 (MIT, © ZhangFengshun): vendored verbatim under `vendor/dsh-remote-ssh/`. Its host half ships **unbundled** as `lib/remote-ssh/index.js` — it must resolve `@deepseek-ai/schemastery` from the host's module table, because its Config schema relies on the DSH-branch schemastery `.volatile()` marker. The shipped host artifact carries **a small local patch set**, applied at build time by `scripts/patch-remote-ssh.mjs` with the vendor tree kept pristine (see "Duplicate remote folders" and "Security hardening" below). Its client ships upstream as a self-registering module-loader bundle; `scripts/build-remote-ssh-client.mjs` extracts the bare factory at build time and the merged client entry (`src/client/index.ts`) applies it next to the groups client.
|
||||
|
||||
### Duplicate remote folders — fixed in this bundle
|
||||
|
||||
Upstream's `createRemoteWorkspace` matched existing records by the raw `remotePath` string, so the same remote directory spelled two ways (`~/proj` vs `/home/u/proj` vs `proj/`) registered a **second workspace record, local mirror and native workspace** — visible as two folder rows for one remote project. This bundle fixes it in two layers:
|
||||
|
||||
- **Host (build-time patch, `scripts/patch-remote-ssh.mjs`)**: registration compares light-normalized spellings first; on a miss it resolves the path once over SSH (`pwd -P` + `$HOME`) and compares canonical forms, storing the canonical spelling. Resolution failures are fail-open (creation proceeds as upstream). Behavior is covered by `npm run test:patch`; the vendored tree stays pristine, so upstream updates still drop in.
|
||||
- **Client (groups)**: adding a cloud folder also refuses when an existing member is backed by the same workspace, or names the same connection + remote directory, regardless of mirror paths.
|
||||
|
||||
Already-duplicated projects are not merged automatically (sessions belong to their workspace). Detaching a member keeps its backing workspace. Deleting the duplicate remote record requires the separate explicit “Delete workspace too” choice; review the affected entry before using it.
|
||||
|
||||
### Security hardening (also in the patch set)
|
||||
|
||||
Fixes from a 2026-11-11 audit, all applied by the same build-time patch script (behavior covered by `npm run test:patch`, including end-to-end runs of the generated terminal wrapper):
|
||||
|
||||
- **ssh option injection**: every internal connection is built by `sshArgv`, which now inserts `--` before the `user@host` target, so a user/host value starting with `-` (e.g. `-oProxyCommand=...`, reachable via the remote_ssh tools' inline arguments) can no longer be parsed as an ssh option and execute local commands. The terminal wrapper's own argv gets the same `--`.
|
||||
- **POSIX password handling**: `sshpass -p` (password visible in the process list to every local user) becomes `sshpass -e`, with the password passed via the `SSHPASS` environment variable — matching the Windows env-based path.
|
||||
- **Terminal wrapper trust**: the generated `dsh-remote-shell` previously honored a `.remote-ssh.json` in ANY directory with host-key checking fully off. It now only honors the marker when the cwd is a registered mirror root (a direct child of `~/.dsh/remote-workspaces`, exactly where the host writes it), uses `StrictHostKeyChecking=accept-new`, and passes `remotePath` to the remote shell base64-encoded so quotes/`$()` in a directory name stay inert data.
|
||||
- **Remote path escape**: `localToRemote` now folds `.`/`..` segments lexically and refuses a path whose `..` would climb above the mirror root, instead of mapping fs requests outside the remote workspace root.
|
||||
- **Write-back guard fails closed**: if the workspace settings cannot be read, the write-back push is skipped (and surfaced through the `writeBackFailure` channel) instead of pushing with the `writeBack` / `writeBackExclude` guard never evaluated.
|
||||
|
||||
`lib/index.js` (source: `bundle/index.js`) is composition only — it applies both plugins on one fiber. `cordis.patch.yml` inserts a single row for this package and carries remote-ssh's `better-sidebar` / `terminal-controller` shell overrides over verbatim.
|
||||
|
||||
### Remote-SSH settings page (1.3.0)
|
||||
|
||||
The settings page is a maintainable source component in this repository (`src/client/rssh-settings/`). At build time `scripts/build-remote-ssh-client.mjs` replaces the vendored compiled settings section with it through anchor assertions, so the vendor tree stays pristine. The page has four regions — My connections / Add connection / Remote workspaces / Advanced settings. Remote workspaces and Advanced settings start collapsed; collapsing only changes visibility, never clears drafts or triggers a save, and the collapsed Advanced region shows no inner save button.
|
||||
|
||||
- **My connections**: each card tests independently (success, connected-with-warning, failure and diagnostics are shown separately); delete asks for confirmation in-card, naming the connection and its effect.
|
||||
- **Add connection**: every field and conditional display is kept (key auth shows the private key path; password auth shows a masked input and hides the key path); an invalid port is rejected with a clear error instead of silently falling back to 22; ProxyJump lives in the collapsed “More connection options”.
|
||||
- **Import from the system SSH config**: a multi-select dialog that checks every save result, counts real successes/failures separately, and can retry failed entries only (successful ones are never resubmitted).
|
||||
- **Remote workspaces**: per-workspace write-back, write-back exclude, sync scope, sync exclude and size cap (GiB), saved by workspace id; pull/push are blocked with a “save first” notice while a draft is unsaved.
|
||||
- **Advanced settings**: terminal node path, write-back policy and new-workspace sync defaults; read and written separately from per-workspace settings, so neither overwrites the other.
|
||||
|
||||
New copy uses its own `dsh-remote-ssh-settings` locale namespace (Chinese + English); CSS is scoped under `.rsui-root` and does not leak into other plugins.
|
||||
|
||||
### Install / migrate
|
||||
|
||||
1. Remove the two old bundles from the profile (`workspace-groups-local` and `@zhangfengshun/dsh-remote-ssh`).
|
||||
2. Add this package instead and fully restart DSH.
|
||||
|
||||
Stored data is untouched by the merge: `~/.dsh/workspace-groups.yaml` and the `$DSH_HOME` sidecars, the `dsh-remote-ssh` settings namespace, and `~/.dsh/remote-ssh/` all keep working. If you ever set remote-ssh options in its old bundle row, they now nest: `config: { remoteSsh: { ... } }` (connection profiles live in DSH settings either way).
|
||||
|
||||
### Verify
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run build
|
||||
npm run verify:bundle # composition checks over the built artifacts, incl. vendor integrity + an executable client smoke
|
||||
npm run verify # everything: tsc + vitest + verify:bundle + patch behavior tests
|
||||
```
|
||||
|
||||
The vendored upstream suite also runs in place once its dependencies resolve — from the repo root: `ln -s ../../node_modules vendor/dsh-remote-ssh/node_modules`, then `node tests/run-all.mjs` inside `vendor/dsh-remote-ssh`. Known pre-existing failures off Windows: 6 groups folders tests use `C:\` paths, and a few remote-ssh suites assume WSL / Windows path semantics; both fail identically in the unmerged upstreams.
|
||||
|
||||
### Known trade-offs
|
||||
|
||||
- **Load coupling**: the two halves load as one bundle, so if either half ever fails to import, the whole package fails — grouping included. That is the price of the single install entry; splitting failure domains would need the host to support lazy per-half loading, which it does not promise today.
|
||||
- **Shell overrides apply to every install**: the bundle carries remote-ssh's `better-sidebar` / `terminal-controller` shell overrides, so installing this package also replaces the profile's terminal shell integration (that is what makes mirror terminals auto-connect). What the host's patch engine does when an override target is absent from a future host version is not verified — it is on the real-machine checklist.
|
||||
- **First connection to a new SSH host is not fingerprint-confirmed** (`accept-new`, the same default as VS Code Remote-SSH): the internal channel trusts a host key on first sight and fails loudly if it changes afterwards. The terminal wrapper was raised from `no` to the same `accept-new` level by the patch set.
|
||||
|
||||
### Maintenance
|
||||
|
||||
The vendored code is not a fork: to update remote-ssh, replace `vendor/dsh-remote-ssh/` with the new upstream tree, run `npm run vendor:manifest` to re-record its sha256 manifest, and rebuild — the client transform asserts its anchors and fails loudly if upstream changes its bundle wrapper shape. The settings-face replacement is anchor-asserted as well: if upstream changes the settings section structure, the build fails instead of silently keeping the old page. Local changes outside the vendor tree: `src/client/GroupsBrowser.tsx` narrows a possibly-null ref explicitly (`pending !== null && ...`) because the fork's `tsc` types step rejected the optional-chain form (semantics unchanged), and the duplicate-folder guards described above (`src/core/folders.ts`, `addRemoteFolderTo`). The host patch script likewise asserts its anchors and fails loudly if upstream changes the anchored code.
|
||||
|
||||
## Preview
|
||||
|
||||
<img src="screenshot.png" alt="Workspace grouping plugin preview" width="280" />
|
||||
|
|
@ -37,6 +105,10 @@ For Web, replace `desktop` with `web`. Fully restart DSH or the corresponding We
|
|||
2. Use the `⋯` menu on a project or group to manage grouping, appearance, and folders.
|
||||
3. Open **Folders…** on a project to attach folders or choose its default root.
|
||||
|
||||
**Add a linked-folder workspace** creates a separate entry after confirmation. Existing workspaces and sessions stay in place; it does not migrate sessions or remove old entries. If registration fails after the directory is created, the error identifies that directory; retrying with the same name and folders reuses its verified links.
|
||||
|
||||
Detaching a member folder keeps its backing workspace and sessions, so that workspace can appear independently again, even when empty. Both the sidebar and folder dialog ask for this decision. No automatic cleanup is inferred from an empty sidebar count: existing records do not reliably distinguish plugin-created members from independently registered workspaces. Remote record deletion remains a separate explicit choice; it attempts to clean up an unshared local mirror and registration, while session files and the original server directory remain.
|
||||
|
||||
For automatic grouping by path or name, see [workspace-groups.example.yaml](./workspace-groups.example.yaml) and configure `~/.dsh/workspace-groups.yaml`. Manual grouping works without this file.
|
||||
|
||||
## Uninstall
|
||||
|
|
|
|||
72
README_ZH.md
|
|
@ -6,6 +6,74 @@
|
|||
|
||||
DeepSeek Harness 工作区分组插件。基于 [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups) 二次开发,让工作区、文件夹和会话在侧栏里更容易整理和使用。
|
||||
|
||||
## 合并包:workspace-groups-remote
|
||||
|
||||
本仓库已把两个 DSH 插件合并为**一个可安装的 bundle**(包名 `workspace-groups-remote`):
|
||||
|
||||
- **workspace-groups**(本仓库原有内容):侧边栏分组管理 + 会话标签条。宿主半边由 `src/` 构建为 `lib/groups.js`,客户端半边在 `src/client/groups-client.ts`。
|
||||
- **@zhangfengshun/dsh-remote-ssh** 2.4.45(MIT,© ZhangFengshun):原样收录于 `vendor/dsh-remote-ssh/`。其宿主半边**不打包**、以 `lib/remote-ssh/index.js` 文件形式发布——它必须从宿主模块表解析 `@deepseek-ai/schemastery`(其 Config 依赖 DSH 分支 schemastery 的 `.volatile()`)。发布出的宿主文件带**一组本地补丁**,构建时由 `scripts/patch-remote-ssh.mjs` 打上,vendor 树保持原样(见下文「重复的远程文件夹」「安全加固」)。其客户端在上游是自注册的模块加载器 bundle,构建时由 `scripts/build-remote-ssh-client.mjs` 提取出工厂函数,由合并后的客户端入口(`src/client/index.ts`)与分组客户端一并应用。
|
||||
|
||||
### 重复的远程文件夹——本合并包已修复
|
||||
|
||||
上游的 `createRemoteWorkspace` 按 `remotePath` 原始字符串比对已有记录,同一个远程目录换个写法(`~/proj` 与 `/home/u/proj` 与 `proj/`)就会再注册**一条工作区记录、一个本地镜像、一个原生工作区**,界面上就是同一个远程项目出现两个文件夹行。本包分两层修复:
|
||||
|
||||
- **宿主侧(构建时补丁,`scripts/patch-remote-ssh.mjs`)**:注册时先比轻度规范化后的写法;对不上时走一次 SSH 把路径解析成规范形式(`pwd -P` + `$HOME`)再比对,存入的也用规范写法。解析失败不拦创建(退回上游行为)。补丁行为由 `npm run test:patch` 覆盖;vendor 树保持原样,上游更新仍可直接替换。
|
||||
- **客户端(分组侧)**:添加云端文件夹时,若已有成员由同一工作区支撑、或指向同一连接 + 同一远程目录,一律拒绝,不再只看镜像路径。
|
||||
|
||||
已经产生的重复不会自动合并(会话归属各自的工作区)。解除成员关联会保留其工作区;删除重复远程记录需要单独明确选择「连工作区一起删」,操作前请核对目标入口。
|
||||
|
||||
### 安全加固(同一组补丁)
|
||||
|
||||
2026-11-11 审查发现的问题,同样由构建时补丁修复,行为由 `npm run test:patch` 覆盖(含把生成的终端 wrapper 真跑起来的端到端用例):
|
||||
|
||||
- **ssh 选项注入**:所有内部连接都经 `sshArgv` 构建,现已在 `user@host` 目标前插入 `--`,以 `-` 开头的用户名/主机名(如 `-oProxyCommand=...`,可经 remote_ssh 工具的内联参数到达)不再会被 ssh 当成选项在本机执行命令。终端 wrapper 自建的参数同样加了 `--`。
|
||||
- **POSIX 密码传递**:`sshpass -p`(密码出现在进程列表里,同机所有用户可见)改为 `sshpass -e`,密码走 `SSHPASS` 环境变量,与 Windows 侧口径一致。
|
||||
- **终端 wrapper 的信任域**:生成的 `dsh-remote-shell` 原先认任意目录下的 `.remote-ssh.json` 且完全关闭主机密钥校验;现只认当前目录确为已注册镜像根(`~/.dsh/remote-workspaces` 的直接子目录,正是宿主自己写标记的位置)时才自动连接,校验改为 `accept-new`,且 remotePath 以 base64 编码传给远端 shell,目录名里的引号/`$()` 只作数据、不再能逃逸成命令。
|
||||
- **远端路径越界**:`localToRemote` 现会先把 `.`/`..` 段按字面折叠,`..` 爬出镜像根的路径直接拒绝,不再把 fs 请求映射到远端工作区之外。
|
||||
- **写回护栏 fail-closed**:读不到工作区设置时本次不推送(并经 `writeBackFailure` 通道报错),不再在护栏(`writeBack` / `writeBackExclude`)根本没被评估的情况下照推。
|
||||
|
||||
`lib/index.js`(源文件 `bundle/index.js`)只做组合:在同一 fiber 上加载两个插件。`cordis.patch.yml` 只插入一行,并原样保留 remote-ssh 对 `better-sidebar` / `terminal-controller` 的 shell 覆盖。
|
||||
|
||||
### Remote-SSH 设置页(1.3.0)
|
||||
|
||||
设置页由本仓库可维护源码组件提供(`src/client/rssh-settings/`),构建期由 `scripts/build-remote-ssh-client.mjs` 按锚点断言替换上游编译产物中的设置小节,vendor 树保持原样。页面为「我的连接 / 添加连接 / 远程工作区 / 高级设置」四个分区;远程工作区与高级设置默认收起,折叠只改变可见性,不清空草稿、不触发保存,收起的高级设置不显示内部保存按钮。
|
||||
|
||||
- **我的连接**:每卡独立测试(成功 / 成功带 warning / 失败与诊断分别显示),删除前卡内确认并明确连接名与影响范围。
|
||||
- **添加连接**:保留全部字段与条件显示(密钥显示私钥路径、密码显示遮罩输入并隐藏私钥路径),端口非法明确报错而不是静默回退 22;ProxyJump 收进默认收起的「更多连接选项」。
|
||||
- **从系统 SSH 配置导入**:多选弹窗,逐项检查保存结果,分别统计成功 / 失败,部分失败可只重试失败项(成功项不重复提交)。
|
||||
- **远程工作区**:每个工作区独立写回、写回排除、同步范围、同步排除与体积上限(GiB),按工作区 ID 保存;有未保存设置时拉取 / 推送会被阻止并提示先保存。
|
||||
- **高级设置**:终端 node 路径、写回策略与新工作区同步默认值;与工作区独立配置分开读写,互不覆盖。
|
||||
|
||||
新文案使用独立的 `dsh-remote-ssh-settings` 命名空间(中英文),样式限定在 `.rsui-root` 之下,不污染其它插件。
|
||||
|
||||
### 安装 / 迁移
|
||||
|
||||
1. 从 profile 里移除旧的两个 bundle(`workspace-groups-local` 与 `@zhangfengshun/dsh-remote-ssh`)。
|
||||
2. 改装本包,并完全重启 DSH。
|
||||
|
||||
已有数据不受影响:`~/.dsh/workspace-groups.yaml` 与 `$DSH_HOME` 下的 sidecar、`dsh-remote-ssh` 设置命名空间、`~/.dsh/remote-ssh/` 都照常工作。若以前在 remote-ssh 的 bundle 行里写过配置,现在改为嵌套写法 `config: { remoteSsh: { ... } }`(连接配置本来就存在 DSH 设置里,不受影响)。
|
||||
|
||||
### 验证
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm run build
|
||||
npm run verify:bundle # 对构建产物做组合检查(含 vendor 完整性指纹 + 客户端真执行冒烟)
|
||||
npm run verify # 全套:tsc + vitest + verify:bundle + 补丁行为测试
|
||||
```
|
||||
|
||||
vendor 里的上游测试也能原地跑(需先让其依赖可解析:在仓库根执行 `ln -s ../../node_modules vendor/dsh-remote-ssh/node_modules`,再在 `vendor/dsh-remote-ssh` 里运行 `node tests/run-all.mjs`)。已知的非 Windows 环境既存失败:分组插件有 6 个 folders 测试使用 `C:\` 路径、remote-ssh 有几个套件假设 WSL / Windows 路径语义——在未合并的上游里同样失败,与合并无关。
|
||||
|
||||
### 已知取舍
|
||||
|
||||
- **加载耦合**:两半作为一个包加载,任一半导入失败,整包(含分组)都会起不来。这是「只装一个包」的代价;要隔离失败域需要宿主支持按半懒加载,目前没有这个承诺。
|
||||
- **shell 覆盖对所有安装生效**:合并包带着 remote-ssh 对 `better-sidebar` / `terminal-controller` 的 shell 覆盖,装这个包等于同时接管 profile 的终端 shell 集成(镜像终端自动连接靠的就是它)。宿主补丁引擎在未来版本里遇到覆盖目标不存在时如何处理,未验证——已列入真机清单。
|
||||
- **首次连接新 SSH 主机不做指纹确认**(`accept-new`,与 VS Code Remote-SSH 相同的默认):内部通道首次连接即信任主机密钥,之后密钥变化会大声失败。终端 wrapper 已由补丁从 `no` 提升到同一 `accept-new` 口径。
|
||||
|
||||
### 维护
|
||||
|
||||
vendor 代码不是 fork:更新 remote-ssh 时,把 `vendor/dsh-remote-ssh/` 换成新版上游树,跑 `npm run vendor:manifest` 重新记录其 sha256 指纹清单,再重新构建;客户端提取脚本带锚点断言,上游若改了 bundle 包裹形式会直接报错。设置页替换同样带锚点断言:上游设置小节的结构一旦变化,构建会失败而不是静默沿用旧界面。vendor 之外的本地改动:`src/client/GroupsBrowser.tsx` 把可空 ref 的判断改成显式写法(`pending !== null && ...`),因为 fork 的 `tsc` 类型步骤不接受可选链写法,语义不变;以及上文的防重复成员检查(`src/core/folders.ts`、`addRemoteFolderTo`)。宿主补丁脚本同样带锚点断言,上游改动锚点代码时会直接报错。
|
||||
|
||||
## 预览
|
||||
|
||||
<img src="screenshot.png" alt="工作区分组插件预览" width="280" />
|
||||
|
|
@ -37,6 +105,10 @@ Web 环境将 `desktop` 改为 `web`。安装完成后,完全重启 DSH 或对
|
|||
2. 在项目或分组的 `⋯` 菜单中管理分组、外观和文件夹。
|
||||
3. 在项目的「文件夹…」弹窗中添加文件夹或选择默认根目录。
|
||||
|
||||
「新增总目录工作区」经确认后添加独立入口。旧工作区和会话仍在原处,不会迁移会话或删除旧入口。如果总目录创建成功但注册失败,提示会列出已创建的路径;保持名称和文件夹不变重试会复用经校验的链接。
|
||||
|
||||
解除 member 文件夹关联会保留其工作区和会话,因此该工作区可能重新独立显示,即使它是空入口。侧栏和文件夹弹窗都先让用户确认此结果。不会根据侧栏会话数自动清理:既有记录无法可靠区分插件新建的 member 和用户独立注册的工作区。删除远程记录仍是单独的明确选择,会尝试清理未共用的本地镜像与注册;聊天文件及服务器上的原目录保留。
|
||||
|
||||
需要按路径或名称自动分组时,可参考 [workspace-groups.example.yaml](./workspace-groups.example.yaml) 配置 `~/.dsh/workspace-groups.yaml`。不配置也不影响手动分组。
|
||||
|
||||
## 卸载
|
||||
|
|
|
|||
|
|
@ -0,0 +1,60 @@
|
|||
/**
|
||||
* workspace-groups-remote — merged bundle host entry (composition only).
|
||||
*
|
||||
* Applies the two co-resident plugins on this bundle's fiber so a single
|
||||
* install row loads both:
|
||||
*
|
||||
* - workspace-groups (./groups.js): the grouped workspace browser's host
|
||||
* half — serves /workspace-groups/* config routes. Built from src/ by
|
||||
* tsdown; its code is unchanged from the standalone package.
|
||||
* - dsh-remote-ssh (./remote-ssh/index.js): the SSH remote-development
|
||||
* host half, vendored byte-identical from vendor/dsh-remote-ssh. It is
|
||||
* deliberately NOT bundled: it must resolve @deepseek-ai/schemastery
|
||||
* (and dsh-tools) from the host's module table — its Config schema
|
||||
* relies on the DSH-branch schemastery `.volatile()` marker, which a
|
||||
* bundled private copy would not share with the Loader.
|
||||
*
|
||||
* The bundle row's config IS the remote-ssh prefs object: the composed
|
||||
* plugin exports remote-ssh's Config schema (below), so this row owns the
|
||||
* settings entry the remote-ssh settings face reads and writes (its entry
|
||||
* id resolves to this bundle's row — see the settings patch in
|
||||
* scripts/patch-remote-ssh.mjs). The groups half takes no row config.
|
||||
* (Pre-1.0.2 the row config nested under a `remoteSsh` key and the face
|
||||
* looked for a `dsh-remote-ssh` entry that a merged install does not
|
||||
* have, so saving any connection failed with "No configurable plugin
|
||||
* entry". No bundle-era data was ever stored in the nested shape —
|
||||
* saving was impossible — so flattening loses nothing.)
|
||||
*/
|
||||
import * as groups from './groups.js'
|
||||
import * as remoteSsh from './remote-ssh/index.js'
|
||||
|
||||
const groupsPlugin = { name: groups.name, inject: groups.inject, apply: groups.apply }
|
||||
// NOTE (1.0.3): the child plugin object must NOT carry its own Config.
|
||||
// When both this composed plugin (top-level `export const Config` below)
|
||||
// and the child declare the same schemastery Config, the child's fiber
|
||||
// silently never applies on DSH 0.2.2-rc.2 — the remote half stays dead
|
||||
// (no wrapper write, no /remote-ssh/api routes) while groups works.
|
||||
// Verified by A/B on a clean profile: 1.0.1 (no top-level Config) fine,
|
||||
// 1.0.2 (both Configs) remote dead, top-level-only Config fine — and the
|
||||
// settings face only needs the ENTRY, which the top-level export owns;
|
||||
// it resolves the entry id to this bundle's row (patch 11), never to the
|
||||
// child's own Cordis config.
|
||||
const remoteSshPlugin = { name: remoteSsh.name, inject: remoteSsh.inject, apply: remoteSsh.apply }
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = 'workspace-groups-remote'
|
||||
|
||||
/** Services required before mounting (union of both halves). */
|
||||
export const inject = ['webServer', 'subprocess', 'tools', 'workspaceRegistry']
|
||||
|
||||
/** The row's settings schema: remote-ssh's own Config (prefs object). */
|
||||
export const Config = remoteSsh.Config
|
||||
|
||||
/** Plugin body: mount both halves on this fiber. */
|
||||
export function apply(ctx, config = {}) {
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
throw new Error('workspace-groups-remote: the row config must be an object (it is the @zhangfengshun/dsh-remote-ssh prefs object)')
|
||||
}
|
||||
ctx.plugin(groupsPlugin)
|
||||
ctx.plugin(remoteSshPlugin, config)
|
||||
}
|
||||
|
|
@ -1,9 +1,46 @@
|
|||
# workspace-groups-local bundle patch
|
||||
# workspace-groups-remote bundle patch
|
||||
#
|
||||
# Local-only build: this package is never published, so the row below is the
|
||||
# ONLY way the plugin reaches the profile tree. The host Loader resolves the
|
||||
# row name as a package from the profile node_modules.
|
||||
# Merged bundle: workspace-groups + @zhangfengshun/dsh-remote-ssh in one
|
||||
# package. The single insert row below loads the package entry, which
|
||||
# composes both plugins. Migration: remove the two old bundles
|
||||
# (workspace-groups-local, @zhangfengshun/dsh-remote-ssh) from the profile
|
||||
# and add this one instead; stored data (workspace-groups.yaml sidecars,
|
||||
# the `dsh-remote-ssh` settings namespace, ~/.dsh/remote-ssh/) is kept.
|
||||
- insert:
|
||||
- id: workspace-groups-local
|
||||
name: 'workspace-groups-local'
|
||||
- id: workspace-groups-remote
|
||||
name: 'workspace-groups-remote'
|
||||
config: {}
|
||||
# 自动覆盖 better-sidebar 的 shell 配置,指向本插件生成的 shell wrapper。
|
||||
# wrapper 脚本在插件 apply() 时写入 ~/.dsh/remote-ssh/dsh-remote-shell[.cmd]:
|
||||
# - 远程工作区(cwd 含 .remote-ssh.json 且 keyPath 非空)→ ssh -tt 连远程
|
||||
# - 本地工作区 → 照常启动本地 shell
|
||||
# 路径用 !!js 动态计算,适配不同平台和用户主目录。
|
||||
- id: better-sidebar
|
||||
config:
|
||||
shell: !!js |
|
||||
(() => {
|
||||
var homedir = process.env.USERPROFILE || process.env.HOME || process.env.HOMEDRIVE + process.env.HOMEPATH;
|
||||
var isWin = process.platform === 'win32';
|
||||
var sep = isWin ? '\\' : '/';
|
||||
var dir = homedir + sep + '.dsh' + sep + 'remote-ssh';
|
||||
return isWin ? dir + sep + 'dsh-remote-shell.cmd' : dir + sep + 'dsh-remote-shell';
|
||||
})()
|
||||
# DSH 0.1.7-rc.2 起,侧边栏终端改由宿主原生的 `terminal-controller`
|
||||
# (@deepseek-ai/dsh-api-terminal-controller)管理,它只读自己的 `config.shell`
|
||||
# ({ path, name, args }),不再读 better-sidebar 的 shell 配置 —— 因此远程工作区
|
||||
# 会静默打开本地 shell。这里把**同一个 wrapper** 也交给原生终端。
|
||||
# 旧版 DSH 没有该 entry,patch 目标不存在时会被忽略(无害)。
|
||||
- id: terminal-controller
|
||||
config:
|
||||
shell: !!js |
|
||||
(() => {
|
||||
var homedir = process.env.USERPROFILE || process.env.HOME || process.env.HOMEDRIVE + process.env.HOMEPATH;
|
||||
var isWin = process.platform === 'win32';
|
||||
var sep = isWin ? '\\' : '/';
|
||||
var dir = homedir + sep + '.dsh' + sep + 'remote-ssh';
|
||||
return {
|
||||
path: isWin ? dir + sep + 'dsh-remote-shell.cmd' : dir + sep + 'dsh-remote-shell',
|
||||
name: 'Auto SSH / Local',
|
||||
args: []
|
||||
};
|
||||
})()
|
||||
|
|
|
|||
|
|
@ -1,350 +0,0 @@
|
|||
# 内置 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 凭据库持久化?
|
||||
|
||||
确认后我再动代码;当前仓库工作树干净,未改任何实现文件。
|
||||
6238
lib/client.js
4127
lib/index.js
|
|
@ -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, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
|
||||
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, initialRemovePath, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
|
||||
workspace: WorkspaceView;
|
||||
entry: WorkspaceFolderEntry | undefined;
|
||||
t: GroupsBrowserProps['t'];
|
||||
|
|
@ -10,18 +10,15 @@ 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;
|
||||
/** Absolute remote root of a cloud owner, so a browsed child joins as a subfolder. */
|
||||
/** Remote root of a cloud owner, so a browsed subdirectory 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;
|
||||
/** Sidebar removal opens this same confirmation instead of bypassing it. */
|
||||
initialRemovePath?: string | null;
|
||||
onClose: () => void;
|
||||
/**
|
||||
* Gather this project's folders into one link directory and register it as a
|
||||
|
|
@ -34,6 +31,6 @@ export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remo
|
|||
onAddRemote: (profileId: string, remotePath: string) => Promise<boolean>;
|
||||
onAddSubpath: (relative: string) => Promise<boolean>;
|
||||
onSetRoot: (path: string) => void;
|
||||
onRemove: (path: string) => void;
|
||||
onRemove: (path: string, deleteRecord: boolean) => void;
|
||||
onOpenFolder: (path: string) => void;
|
||||
}): import("react").JSX.Element;
|
||||
|
|
|
|||
|
|
@ -74,6 +74,15 @@ export declare function listRemoteProfiles(fetchImpl?: typeof fetch): Promise<Re
|
|||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function createRemoteFolder(profileId: string, remotePath: string, title?: string, fetchImpl?: typeof fetch): Promise<CreatedRemoteFolder>;
|
||||
/**
|
||||
* Delete one remote workspace record through the SSH plugin: it removes the
|
||||
* record and attempts to unregister its native workspace and clean up its
|
||||
* local mirror unless shared by another record. Session files and the original
|
||||
* remote directory remain; unregistering may hide sessions from the sidebar.
|
||||
* @param recordId - remote-ssh record id stored on the member.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function deleteRemoteWorkspaceRecord(recordId: string, fetchImpl?: typeof fetch): Promise<void>;
|
||||
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||
export declare function remoteFolderWorkspace(path: string, remoteBase: string | null, fetchImpl?: typeof fetch): Promise<RemoteFolderWorkspace | null>;
|
||||
/** Single-segment names match DSH createDirectory(path, name). */
|
||||
|
|
|
|||
|
|
@ -7,25 +7,15 @@
|
|||
* only — the workspace's canonical directory is implicit folder #0 — and
|
||||
* `root` names one of those extras (absent means "the workspace itself").
|
||||
*
|
||||
* 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.
|
||||
* Reads are best-effort, like the manual overlay and the tab strip: a failed
|
||||
* read means "no extra folders". A failed write, however, rejects so the caller
|
||||
* can say so — a folder row that silently forgot its edit would be worse than
|
||||
* the toast.
|
||||
*/
|
||||
import { type FoldersDocument } from '../core/folders.ts';
|
||||
/** Host route holding the folder overlay. */
|
||||
export declare const FOLDERS_ROUTE = "/workspace-groups/folders";
|
||||
/** One successful read: the overlay plus the host's diagnostics and revision. */
|
||||
/** One successful read: the overlay plus the mirror base the host reported. */
|
||||
export interface FoldersSnapshot {
|
||||
readonly document: FoldersDocument;
|
||||
/**
|
||||
|
|
@ -34,53 +24,52 @@ 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);
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* One folder-overlay read result. A failed read must never masquerade as the
|
||||
* empty document: the browser uses `ok` to keep the last confirmed rows and
|
||||
* show a retryable error instead of rendering every member as a duplicate.
|
||||
*/
|
||||
export declare function parseFoldersSnapshot(body: unknown): FoldersSnapshot | null;
|
||||
export interface FoldersLoadResult extends FoldersSnapshot {
|
||||
readonly ok: boolean;
|
||||
/** Human-readable failure reason; absent on success. */
|
||||
readonly error?: string;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
*
|
||||
* A non-2xx response, a malformed body or a transport error is returned as
|
||||
* `ok:false` with the reason. The empty document is still present for callers
|
||||
* that only need a safe value, but `ok` is the authority: the browser must not
|
||||
* treat a failed read as "no folders".
|
||||
* @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.
|
||||
* @param signal - optional cancellation for a superseded read/retry.
|
||||
*/
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch): Promise<FoldersLoadResult>;
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch, signal?: AbortSignal): 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.
|
||||
* Read a whole folder document off the wire (GET response, PUT echo or the
|
||||
* 409 conflict body), or null when it is not a version-1 document.
|
||||
* @param source - parsed JSON body.
|
||||
*/
|
||||
export declare function saveFolders(document: FoldersDocument, expectedRevision: string | undefined, fetchImpl?: typeof fetch): Promise<string>;
|
||||
export declare function parseWireDocument(source: Record<string, unknown>): FoldersDocument | null;
|
||||
/**
|
||||
* A save rejected because another window wrote first (HTTP 409). Carries the
|
||||
* host's current document so the caller can adopt it and resync its state
|
||||
* instead of leaving the user looking at a phantom edit.
|
||||
*/
|
||||
export declare class FoldersConflictError extends Error {
|
||||
readonly current: FoldersDocument;
|
||||
/** The unsaved document the failed PUT attempted to write. */
|
||||
readonly attempted: FoldersDocument;
|
||||
constructor(current: FoldersDocument, attempted?: FoldersDocument);
|
||||
}
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
*
|
||||
* Unlike the tab strip this does NOT swallow failures: folder edits are explicit
|
||||
* row/dialog actions, so the caller turns a rejection into a toast instead of
|
||||
* leaving the user with a row that silently forgot its folder.
|
||||
* @param document - the client's current document.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<FoldersDocument>;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,65 @@
|
|||
/**
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
*
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import { type WorkspaceGroupsKey } from './locales.ts';
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey;
|
||||
}
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
export declare const inject: string[];
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export declare function apply(ctx: Context): void;
|
||||
|
|
@ -1,65 +1,32 @@
|
|||
/**
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
* workspace-groups-remote — merged client entry.
|
||||
*
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
* One package gets exactly one client row in the DSH web shell (the module
|
||||
* loader keys graph rows by package name), so this entry composes the two
|
||||
* client halves on one fiber:
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
* - groupsClient: the workspace-groups browser + session tab strip
|
||||
* (groups-client.ts, formerly this file).
|
||||
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
||||
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
||||
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
||||
* strips that registration wrapper, re-exports the bare factory and applies
|
||||
* two anchor-asserted transforms (root label, settings face). The factory
|
||||
* is invoked here with this bundle's own require (its only requires are
|
||||
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
||||
* modules) and applied alongside the groups client.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
* The settings page itself is NOT the vendored compiled component: the factory
|
||||
* receives `remoteSshCompose`, whose `createSettingsSection` builds the
|
||||
* maintainable React section from src/client/rssh-settings. Its dictionary
|
||||
* namespace and CSS live in this entry because the merged package owns them
|
||||
* (the vendored half only knows its upstream keys/styles).
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
||||
* are a subset of the groups list).
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import { type WorkspaceGroupsKey } from './locales.ts';
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey;
|
||||
}
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
/** Services required before mounting (union of both client halves). */
|
||||
export declare const inject: string[];
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
/** Plugin body: apply both client halves on this bundle's fiber. */
|
||||
export declare function apply(ctx: Context): void;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.loadError' | 'folder.conflict' | 'folder.retry' | 'folder.reload' | 'folder.addKind' | 'folder.addKindSubfolder' | 'folder.addKindWorkspace' | 'folder.cloudNoteSubfolder' | 'folder.mergeTitle' | 'folder.mergeAction' | 'folder.mergeHint' | 'folder.mergeDone' | 'folder.mergeFailed' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type 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.mergeTitle' | 'folder.mergeAction' | 'folder.mergeHint' | 'folder.mergeDone' | 'folder.mergeConfirm' | 'folder.mergeRegistrationFailed' | 'folder.removeMemberPrompt' | 'folder.removeMissingPrompt' | 'folder.mergeFailed' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | '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.loadingState' | 'folder.loadError' | 'folder.refreshError' | 'folder.retry' | 'folder.retryDraft' | 'folder.discardDraft' | 'folder.conflictDetail' | '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' | 'manual.conflict' | '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;
|
||||
|
|
|
|||
|
|
@ -1,18 +0,0 @@
|
|||
/**
|
||||
* 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;
|
||||
|
|
@ -0,0 +1,206 @@
|
|||
/**
|
||||
* Remote-SSH settings face — wire contract.
|
||||
*
|
||||
* The settings section is produced by this module and registered into the
|
||||
* shell's `settings.section` slot by the vendored remote-ssh client (see
|
||||
* scripts/build-remote-ssh-client.mjs). The module talks to the Host through
|
||||
* the SAME `/remote-ssh/api/*` JSON-RPC the vendored client uses: the merged
|
||||
* entry hands it the vendored client's own `api()` wrapper, so endpoint
|
||||
* names, envelopes and semantics stay byte-identical to upstream.
|
||||
*
|
||||
* Types below mirror the Host implementations in
|
||||
* vendor/dsh-remote-ssh/lib/index.js (api object around line 4641) and the
|
||||
* redacted profile projection (`publicProfiles`, line 37). They are a
|
||||
* compile-time description only; nothing here changes runtime behaviour.
|
||||
*/
|
||||
import type { ReactNode } from 'react';
|
||||
/** Redacted connection profile (`publicProfiles`: password stripped, boolean kept). */
|
||||
export interface RemoteSshProfile {
|
||||
id: string;
|
||||
name?: string;
|
||||
host: string;
|
||||
port?: number;
|
||||
user: string;
|
||||
authMethod?: 'key' | 'password';
|
||||
keyPath?: string;
|
||||
remoteRoot?: string;
|
||||
proxyJump?: string;
|
||||
passwordConfigured?: boolean;
|
||||
}
|
||||
/** One persisted remote workspace record (settingsFace.workspaces entry). */
|
||||
export interface RemoteSshWorkspace {
|
||||
id: string;
|
||||
profileId: string;
|
||||
title?: string;
|
||||
remotePath?: string;
|
||||
mirrorPath?: string;
|
||||
shellWorkspaceId?: string;
|
||||
writeBack?: boolean;
|
||||
writeBackExclude?: string[];
|
||||
syncPaths?: string[];
|
||||
syncExclude?: string[];
|
||||
syncMaxBytes?: number;
|
||||
}
|
||||
/** One `~/.ssh/config` host entry (listSshConfigHosts projection). */
|
||||
export interface SshConfigHost {
|
||||
name: string;
|
||||
hostName: string;
|
||||
port?: number;
|
||||
user?: string;
|
||||
identityFile?: string;
|
||||
proxyJump?: string;
|
||||
}
|
||||
/** Global preferences as rendered by the Host (getPrefs/savePrefs.prefs). */
|
||||
export interface RemoteSshPrefs {
|
||||
nodePath?: string;
|
||||
writeBackFailure?: string;
|
||||
writeBackFreshness?: boolean;
|
||||
defaultSyncPaths?: string[];
|
||||
defaultSyncExclude?: string[];
|
||||
defaultSyncMaxBytes?: number;
|
||||
}
|
||||
/**
|
||||
* saveProfile body. Every field the vendored settings face sent is kept:
|
||||
* `name`, `host`, `port`, `user`, `authMethod`, `keyPath`, `password`,
|
||||
* `remoteRoot`, `proxyJump`. `port` is already an integer here (the form
|
||||
* rejects invalid values instead of letting the Host fall back to 22).
|
||||
*/
|
||||
export interface SaveProfilePayload {
|
||||
name: string;
|
||||
host: string;
|
||||
port: number;
|
||||
user: string;
|
||||
authMethod: 'key' | 'password';
|
||||
keyPath: string;
|
||||
password: string;
|
||||
remoteRoot: string;
|
||||
proxyJump: string;
|
||||
}
|
||||
/** updateWorkspaceGuards body: per-workspace write-back and sync scope. */
|
||||
export interface UpdateWorkspaceGuardsPayload {
|
||||
id: string;
|
||||
writeBack: boolean;
|
||||
writeBackExclude: string[];
|
||||
syncPaths: string[];
|
||||
syncExclude: string[];
|
||||
/** Bytes; 0 = Host built-in default cap (the old face always sent this). */
|
||||
syncMaxBytes: number;
|
||||
}
|
||||
/** savePrefs body: global terminal / write-back / new-workspace defaults. */
|
||||
export interface SavePrefsPayload {
|
||||
nodePath: string;
|
||||
writeBackFailure: 'error' | 'log';
|
||||
writeBackFreshness: boolean;
|
||||
defaultSyncPaths: string[];
|
||||
defaultSyncExclude: string[];
|
||||
defaultSyncMaxBytes: number;
|
||||
}
|
||||
export interface ListProfilesResponse {
|
||||
ok?: boolean;
|
||||
profiles?: RemoteSshProfile[];
|
||||
error?: string;
|
||||
}
|
||||
export interface SaveProfileResponse {
|
||||
ok?: boolean;
|
||||
id?: string;
|
||||
profiles?: RemoteSshProfile[];
|
||||
error?: string;
|
||||
}
|
||||
export interface TestConnectionResponse {
|
||||
ok?: boolean;
|
||||
warning?: string;
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
error?: string;
|
||||
exitCode?: number;
|
||||
truncated?: boolean;
|
||||
}
|
||||
export interface DeleteProfileResponse {
|
||||
ok?: boolean;
|
||||
profiles?: RemoteSshProfile[];
|
||||
workspaces?: RemoteSshWorkspace[];
|
||||
error?: string;
|
||||
}
|
||||
export interface ListSshConfigHostsResponse {
|
||||
ok?: boolean;
|
||||
hosts?: SshConfigHost[];
|
||||
error?: string;
|
||||
}
|
||||
export interface ListWorkspacesResponse {
|
||||
ok?: boolean;
|
||||
workspaces?: RemoteSshWorkspace[];
|
||||
error?: string;
|
||||
}
|
||||
export interface UpdateWorkspaceGuardsResponse {
|
||||
ok?: boolean;
|
||||
workspaces?: RemoteSshWorkspace[];
|
||||
error?: string;
|
||||
}
|
||||
export interface SyncResponse {
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
export interface DeleteWorkspaceResponse {
|
||||
ok?: boolean;
|
||||
workspaces?: RemoteSshWorkspace[];
|
||||
error?: string;
|
||||
}
|
||||
export interface GetPrefsResponse {
|
||||
ok?: boolean;
|
||||
prefs?: RemoteSshPrefs;
|
||||
deleteSync?: boolean;
|
||||
error?: string;
|
||||
}
|
||||
export interface SavePrefsResponse {
|
||||
ok?: boolean;
|
||||
prefs?: RemoteSshPrefs;
|
||||
error?: string;
|
||||
}
|
||||
/**
|
||||
* Typed view of the vendored client's `api(method, args)` wrapper. The
|
||||
* wrapper resolves to the Host's `value` object (which always carries its
|
||||
* own `ok` flag) or `{ ok: false, error }` for transport failures.
|
||||
*/
|
||||
export interface RemoteSshApi {
|
||||
(method: 'listProfiles'): Promise<ListProfilesResponse>;
|
||||
(method: 'saveProfile', args: SaveProfilePayload): Promise<SaveProfileResponse>;
|
||||
(method: 'testConnection', args: {
|
||||
id: string;
|
||||
}): Promise<TestConnectionResponse>;
|
||||
(method: 'deleteProfile', args: {
|
||||
id: string;
|
||||
}): Promise<DeleteProfileResponse>;
|
||||
(method: 'listSshConfigHosts'): Promise<ListSshConfigHostsResponse>;
|
||||
(method: 'listWorkspaces'): Promise<ListWorkspacesResponse>;
|
||||
(method: 'updateWorkspaceGuards', args: UpdateWorkspaceGuardsPayload): Promise<UpdateWorkspaceGuardsResponse>;
|
||||
(method: 'syncDown', args: {
|
||||
id: string;
|
||||
}): Promise<SyncResponse>;
|
||||
(method: 'syncUp', args: {
|
||||
id: string;
|
||||
}): Promise<SyncResponse>;
|
||||
(method: 'deleteWorkspace', args: {
|
||||
id: string;
|
||||
}): Promise<DeleteWorkspaceResponse>;
|
||||
(method: 'getPrefs'): Promise<GetPrefsResponse>;
|
||||
(method: 'savePrefs', args: SavePrefsPayload): Promise<SavePrefsResponse>;
|
||||
}
|
||||
/** Bind of the settings dictionary namespace (typed keys, `{name}` params). */
|
||||
export type SettingsTranslate = (key: string, params?: Record<string, string | number>) => string;
|
||||
/** Props the shell's `settings.section` renderer injects (locale `t` seat). */
|
||||
export interface SettingsSectionProps {
|
||||
t?: SettingsTranslate;
|
||||
}
|
||||
/** Registration shape accepted by the slot renderer (function component). */
|
||||
export type SettingsSectionComponent = (props: SettingsSectionProps) => ReactNode;
|
||||
/** Runtime facts the merged client entry hands to the extracted factory. */
|
||||
export interface RemoteSshClientCompose {
|
||||
/** Dictionary namespace the settings entry declares (`locale:` in the slot def). */
|
||||
readonly settingsNamespace: string;
|
||||
/** Build the settings section component around the vendored client's `api`. */
|
||||
createSettingsSection(deps: SettingsSectionDeps): SettingsSectionComponent;
|
||||
}
|
||||
/** Injected runtime services for the section (the vendored client's api wrapper). */
|
||||
export interface SettingsSectionDeps {
|
||||
api: RemoteSshApi;
|
||||
}
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
/**
|
||||
* Remote-SSH settings dictionary.
|
||||
*
|
||||
* The section registers its OWN namespace `dsh-remote-ssh-settings` through
|
||||
* the shell locale service (the merged client entry calls
|
||||
* {@link registerSettingsLocale} inside `ctx.effect`). Registering a separate
|
||||
* namespace — instead of appending keys to the vendored plugin's
|
||||
* `dsh-remote-ssh` dictionaries at build time — keeps all new copy in source,
|
||||
* type-checked by the `SettingsKey` union, and lets the slot machinery inject
|
||||
* a typed `t` seat into the component (declared as `locale:` in the slot
|
||||
* registration). Existing upstream keys/namespace are untouched.
|
||||
*/
|
||||
import type { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client';
|
||||
/** Namespace owned by this settings face. */
|
||||
export declare const SETTINGS_NS = "dsh-remote-ssh-settings";
|
||||
/** Chinese dictionary — the key set below is the single source of truth. */
|
||||
export declare const zh: {
|
||||
readonly 'page.title': "Remote SSH";
|
||||
readonly 'page.subtitle': "管理远程连接与同步设置";
|
||||
readonly 'connection.sectionTitle': "我的连接";
|
||||
readonly 'connection.sectionSummary': "测试连接、查看当前连接的诊断信息";
|
||||
readonly 'connection.count': "{n} 个连接";
|
||||
readonly 'connection.empty': "还没有连接配置。在下方「添加连接」中新增。";
|
||||
readonly 'connection.test': "测试连接";
|
||||
readonly 'connection.testing': "测试中…";
|
||||
readonly 'connection.delete': "删除";
|
||||
readonly 'connection.authKey': "密钥认证";
|
||||
readonly 'connection.authPassword': "密码认证";
|
||||
readonly 'connection.passwordConfigured': "已保存密码";
|
||||
readonly 'connection.testOk': "连接成功";
|
||||
readonly 'connection.testWarn': "连接成功,但有警告:";
|
||||
readonly 'connection.testFail': "连接失败";
|
||||
readonly 'connection.diagnostics': "诊断输出";
|
||||
readonly 'connection.deleteTitle': "删除连接「{name}」?";
|
||||
readonly 'connection.deleteBody': "将同时移除该连接下的远程工作区条目和本地镜像映射;不会删除服务器上的文件。";
|
||||
readonly 'connection.deleted': "已删除连接「{name}」";
|
||||
readonly 'connection.deleteFail': "删除失败";
|
||||
readonly 'add.sectionTitle': "添加连接";
|
||||
readonly 'add.sectionSummary': "从系统 SSH 配置导入,或手动填写";
|
||||
readonly 'add.import': "从系统 SSH 配置导入…";
|
||||
readonly 'add.divider': "或手动添加";
|
||||
readonly 'add.name': "名称";
|
||||
readonly 'add.namePlaceholder': "如:我的超算";
|
||||
readonly 'add.host': "主机";
|
||||
readonly 'add.hostPlaceholder': "login.example.com";
|
||||
readonly 'add.port': "端口";
|
||||
readonly 'add.user': "用户名";
|
||||
readonly 'add.userPlaceholder': "your-username";
|
||||
readonly 'add.auth': "认证方式";
|
||||
readonly 'add.authKey': "SSH 密钥";
|
||||
readonly 'add.authPassword': "密码";
|
||||
readonly 'add.keyPath': "私钥路径";
|
||||
readonly 'add.keyPathPlaceholder': "~/.ssh/id_rsa(留空则使用 ssh-agent 或 SSH 配置)";
|
||||
readonly 'add.password': "密码";
|
||||
readonly 'add.passwordPlaceholder': "输入密码(不会写回浏览器存储)";
|
||||
readonly 'add.remoteRoot': "远程根目录";
|
||||
readonly 'add.remoteRootPlaceholder': "~/project";
|
||||
readonly 'add.moreOptions': "更多连接选项";
|
||||
readonly 'add.moreOptionsSummary': "跳板机 ProxyJump";
|
||||
readonly 'add.proxyJump': "跳板机 ProxyJump";
|
||||
readonly 'add.proxyJumpPlaceholder': "bastion.example.com";
|
||||
readonly 'add.submit': "添加连接";
|
||||
readonly 'add.submitting': "添加中…";
|
||||
readonly 'add.errHost': "请填写主机";
|
||||
readonly 'add.errUser': "请填写用户名";
|
||||
readonly 'add.errPort': "端口必须是 1–65535 的整数";
|
||||
readonly 'add.ok': "已添加连接「{name}」";
|
||||
readonly 'add.fail': "添加失败";
|
||||
readonly 'import.title': "从系统 SSH 配置导入";
|
||||
readonly 'import.loading': "正在读取 ~/.ssh/config…";
|
||||
readonly 'import.readFail': "读取 ~/.ssh/config 失败";
|
||||
readonly 'import.empty': "未在 ~/.ssh/config 中发现可用主机";
|
||||
readonly 'import.note': "仅列出 ~/.ssh/config 中带 HostName 的条目;这不是完整的 OpenSSH 配置语义。";
|
||||
readonly 'import.selectAll': "全选";
|
||||
readonly 'import.clearAll': "取消全选";
|
||||
readonly 'import.selectedCount': "已选 {n} / {total}";
|
||||
readonly 'import.submit': "导入所选连接";
|
||||
readonly 'import.importing': "导入中…({done}/{total})";
|
||||
readonly 'import.progress': "正在导入「{name}」…";
|
||||
readonly 'import.resultAllOk': "已导入 {ok} 个连接";
|
||||
readonly 'import.resultPartial': "成功 {ok} 个,失败 {fail} 个";
|
||||
readonly 'import.resultAllFail': "全部失败({fail} 个)";
|
||||
readonly 'import.failedIntro': "以下主机未导入:";
|
||||
readonly 'import.noResult': "保存接口未返回结果";
|
||||
readonly 'import.retryFailed': "仅重试失败项({n})";
|
||||
readonly 'import.retrying': "重试中…({done}/{total})";
|
||||
readonly 'import.noneSelected': "请至少选择一个主机";
|
||||
readonly 'import.proxyJump': "跳板机 {target}";
|
||||
readonly 'import.close': "关闭";
|
||||
readonly 'import.authNote': "导入的连接固定使用密钥认证、远程根目录 ~;可在手动表单中补充密码或其它字段。";
|
||||
readonly 'workspace.sectionTitle': "远程工作区";
|
||||
readonly 'workspace.sectionSummary': "独立写回与同步配置";
|
||||
readonly 'workspace.empty': "还没有远程工作区。可在「添加工作区」中选择「远程目录」创建。";
|
||||
readonly 'workspace.expand': "展开配置";
|
||||
readonly 'workspace.collapse': "收起配置";
|
||||
readonly 'workspace.connection': "所属连接";
|
||||
readonly 'workspace.remotePath': "远程路径";
|
||||
readonly 'workspace.writeBack': "启用写回(把 agent 的 write/edit 同步到远端)";
|
||||
readonly 'workspace.writeBackExclude': "写回排除(逗号或换行分隔)";
|
||||
readonly 'workspace.writeBackExcludeHint': "这些路径的本地改动不会推回远端,例如 _patch/, *.log。";
|
||||
readonly 'workspace.syncPaths': "同步范围(逗号或换行分隔,留空 = 整树)";
|
||||
readonly 'workspace.syncPathsHint': "只同步这些子路径,例如 .dsh;留空 = 整树。";
|
||||
readonly 'workspace.syncExclude': "同步排除(逗号或换行分隔)";
|
||||
readonly 'workspace.syncExcludeHint': "拉取和推送时跳过这些路径,例如 data/, *.log;与写回排除用途不同。";
|
||||
readonly 'workspace.syncMaxBytes': "同步体积上限(GiB,留空 = 默认 2 GiB)";
|
||||
readonly 'workspace.unsaved': "未保存";
|
||||
readonly 'workspace.save': "保存该工作区设置";
|
||||
readonly 'workspace.saving': "保存中…";
|
||||
readonly 'workspace.saved': "该工作区设置已保存";
|
||||
readonly 'workspace.saveFail': "保存失败";
|
||||
readonly 'workspace.syncBlocked': "有未保存的设置,请先保存再拉取或推送。";
|
||||
readonly 'workspace.syncDown': "拉取";
|
||||
readonly 'workspace.syncUp': "推送";
|
||||
readonly 'workspace.syncing': "拉取中…";
|
||||
readonly 'workspace.pushing': "推送中…";
|
||||
readonly 'workspace.syncDone': "拉取完成";
|
||||
readonly 'workspace.syncFail': "拉取失败";
|
||||
readonly 'workspace.pushDone': "推送完成";
|
||||
readonly 'workspace.pushFail': "推送失败";
|
||||
readonly 'workspace.deleteTitle': "移除远程工作区「{title}」?";
|
||||
readonly 'workspace.deleteBody': "只移除本地记录与镜像映射,不会删除服务器上的目录或文件。";
|
||||
readonly 'workspace.deleted': "已移除远程工作区「{title}」";
|
||||
readonly 'workspace.deleteFail': "删除失败";
|
||||
readonly 'workspace.unknownProfile': "未知连接";
|
||||
readonly 'advanced.sectionTitle': "高级设置";
|
||||
readonly 'advanced.sectionSummary': "终端与写回、新工作区同步默认值";
|
||||
readonly 'advanced.terminalGroup': "终端与写回";
|
||||
readonly 'advanced.nodePath': "Node 绝对路径";
|
||||
readonly 'advanced.nodePathHint': "终端起不来时填写;留空自动解析。";
|
||||
readonly 'advanced.nodePathPlaceholder': "C:\\Program Files\\nodejs\\node.exe";
|
||||
readonly 'advanced.writeBackFailure': "写回推送失败时";
|
||||
readonly 'advanced.wbError': "让模型看见,工具报错";
|
||||
readonly 'advanced.wbLog': "只写日志";
|
||||
readonly 'advanced.writeBackFreshness': "推送前检查远端是否被改过(发现被改过就不推并报告)";
|
||||
readonly 'advanced.syncDefaultsGroup': "新工作区同步默认值";
|
||||
readonly 'advanced.syncDefaultsHint': "仅影响之后新建的远程工作区,不会覆盖已有工作区的独立设置。";
|
||||
readonly 'advanced.defaultSyncPaths': "默认同步范围(逗号或换行分隔,留空 = 整树)";
|
||||
readonly 'advanced.defaultSyncExclude': "默认同步排除(逗号或换行分隔)";
|
||||
readonly 'advanced.defaultSyncMaxBytes': "默认同步体积上限(GiB,留空 = 内置 2 GiB)";
|
||||
readonly 'advanced.save': "保存设置";
|
||||
readonly 'advanced.saving': "保存中…";
|
||||
readonly 'advanced.saved': "设置已保存";
|
||||
readonly 'advanced.saveFail': "保存失败";
|
||||
readonly 'common.cancel': "取消";
|
||||
readonly 'common.close': "关闭";
|
||||
readonly 'common.confirmDelete': "确认删除";
|
||||
readonly 'common.retry': "重试";
|
||||
readonly 'common.loading': "加载中…";
|
||||
readonly 'common.save': "保存";
|
||||
readonly 'common.error': "错误:";
|
||||
readonly 'common.warning': "警告:";
|
||||
readonly 'common.unknownError': "未知错误";
|
||||
readonly 'common.expand': "展开";
|
||||
readonly 'common.collapse': "收起";
|
||||
};
|
||||
/** Chinese key set; every call site is checked against it. */
|
||||
export type SettingsKey = keyof typeof zh;
|
||||
/** English dictionary — complete mirror of the Chinese key set. */
|
||||
export declare const en: Record<SettingsKey, string>;
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
'dsh-remote-ssh-settings': SettingsKey;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Register both dictionaries for this namespace on the shell locale service.
|
||||
* Call inside `ctx.effect(...)` so the registration is disposed with the
|
||||
* plugin fiber. The typed `register` overload enforces zh/en key parity.
|
||||
*/
|
||||
export declare function registerSettingsLocale(locale: LocaleRuntime): () => void;
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
import type { RemoteSshApi, SettingsSectionComponent } from './contract.ts';
|
||||
/** Options handed to the extracted factory by the merged client entry. */
|
||||
export interface CreateSettingsSectionOptions {
|
||||
api: RemoteSshApi;
|
||||
}
|
||||
/**
|
||||
* Build the settings section component around the injected API.
|
||||
* The returned component matches the shell's `settings.section` renderer
|
||||
* signature `(props: { t? }) => ReactNode`.
|
||||
*/
|
||||
export declare function createSettingsSection(options: CreateSettingsSectionOptions): SettingsSectionComponent;
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
/**
|
||||
* Remote-SSH settings — pure model.
|
||||
*
|
||||
* Everything here is plain data transformation (no React, no DOM, no
|
||||
* imports from other plugin sources), so the real behaviour can be covered
|
||||
* by unit tests without mounting the shell:
|
||||
*
|
||||
* - connection form validation and the exact `saveProfile` payload
|
||||
* - `~/.ssh/config` import mapping, per-item outcomes, partial-failure counts
|
||||
* and failed-only retry merges (the old face reported the selection size as
|
||||
* "imported" regardless of each save result)
|
||||
* - per-workspace guard drafts, dirty detection, reload reconciliation and the
|
||||
* exact `updateWorkspaceGuards` payload
|
||||
* - global preferences draft/payload/dirty/reconcile
|
||||
*
|
||||
* Field semantics and unit conversions are copied from the vendored client
|
||||
* (`splitList`, `bytesToGibText`, `gibTextToBytes`, `prefsForUi`) so the face
|
||||
* keeps the existing Host contract: lists accept comma/newline/semicolon,
|
||||
* the size cap is edited in GiB and stored in bytes, empty = Host default.
|
||||
*/
|
||||
import type { RemoteSshPrefs, RemoteSshProfile, RemoteSshWorkspace, SavePrefsPayload, SaveProfilePayload, SshConfigHost, TestConnectionResponse, UpdateWorkspaceGuardsPayload } from './contract.ts';
|
||||
/** Controlled draft of the "add connection" form (all fields are strings). */
|
||||
export interface ConnectionForm {
|
||||
name: string;
|
||||
host: string;
|
||||
port: string;
|
||||
user: string;
|
||||
authMethod: 'key' | 'password';
|
||||
keyPath: string;
|
||||
password: string;
|
||||
remoteRoot: string;
|
||||
proxyJump: string;
|
||||
}
|
||||
/** Values the vendored client used when opening/clearing the form. */
|
||||
export declare const EMPTY_CONNECTION_FORM: ConnectionForm;
|
||||
/** Fresh copy (never share the frozen constant with component state). */
|
||||
export declare function emptyConnectionForm(): ConnectionForm;
|
||||
/** Field-level issue; the component maps `messageKey` through `t`. */
|
||||
export interface FormIssue {
|
||||
field: 'host' | 'user' | 'port';
|
||||
messageKey: 'add.errHost' | 'add.errUser' | 'add.errPort';
|
||||
}
|
||||
/**
|
||||
* Validate exactly what the Host requires (`host` + `user`) plus a real port
|
||||
* range. The Host would otherwise `parseInt(port) || 22`, silently turning a
|
||||
* typo into 22; the UI refuses it instead. Aliases, empty key paths and the
|
||||
* reliance on ssh-agent / ~/.ssh/config stay legal (the backend accepts them).
|
||||
*/
|
||||
export declare function validateConnectionForm(form: ConnectionForm): FormIssue[];
|
||||
/** Whether the form can be submitted (callers still re-check on submit). */
|
||||
export declare function isConnectionFormValid(form: ConnectionForm): boolean;
|
||||
/**
|
||||
* Exact `saveProfile` body. Fields are passed through as typed by the user
|
||||
* (the Host trims/derives where it always did: name falls back to host, port
|
||||
* parsing is already done here, password only persists for password auth).
|
||||
*/
|
||||
export declare function toSaveProfilePayload(form: ConnectionForm): SaveProfilePayload;
|
||||
/** `user@host:port` summary used by connection cards. */
|
||||
export declare function profileSummary(profile: RemoteSshProfile): string;
|
||||
/** Display name with the upstream `name || host` fallback. */
|
||||
export declare function profileName(profile: RemoteSshProfile): string;
|
||||
/** "comma or newline (or semicolon) separated" text → trimmed non-empty list. */
|
||||
export declare function splitList(value: string | null | undefined): string[];
|
||||
/** Byte count → GiB text (empty = Host built-in default cap). */
|
||||
export declare function bytesToGibText(bytes: number | null | undefined): string;
|
||||
/** GiB text → bytes; empty/invalid → 0 (= Host built-in default cap). */
|
||||
export declare function gibTextToBytes(text: string | number | null | undefined): number;
|
||||
/** Trimmed error text from an API envelope, else the caller's fallback. */
|
||||
export declare function apiErrorMessage(value: {
|
||||
error?: string;
|
||||
} | null | undefined, fallback: string): string;
|
||||
export type TestStatus = 'success' | 'warning' | 'error';
|
||||
/** Rendered shape of one connection test result. */
|
||||
export interface ConnectionTestView {
|
||||
status: TestStatus;
|
||||
/** Localized status line (caller resolves the keys). */
|
||||
titleKey: 'connection.testOk' | 'connection.testWarn' | 'connection.testFail';
|
||||
/** Raw warning returned by the Host (successful connect with degraded key path). */
|
||||
warning: string;
|
||||
/** stdout for success, stderr/error text for failure. */
|
||||
detail: string;
|
||||
}
|
||||
/**
|
||||
* Map `testConnection` output to the card feedback. A successful probe that
|
||||
* carries `warning` stays a warning (never collapsed into a plain success).
|
||||
*/
|
||||
export declare function connectionTestView(result: TestConnectionResponse | null | undefined): ConnectionTestView;
|
||||
/** Stable row key; same spelling the vendored importer used for selection. */
|
||||
export declare function importHostKey(host: SshConfigHost): string;
|
||||
/** Default selection: every discovered host (upstream opened all checked). */
|
||||
export declare function selectAllHosts(hosts: SshConfigHost[]): Record<string, boolean>;
|
||||
/** Toggle one selection key without mutating the previous map. */
|
||||
export declare function toggleHostSelection(selected: Record<string, boolean>, key: string): Record<string, boolean>;
|
||||
/** Selected hosts, in discovery order (never trusts map iteration order). */
|
||||
export declare function selectedHosts(hosts: SshConfigHost[], selected: Record<string, boolean>): SshConfigHost[];
|
||||
/** Count of checked rows. */
|
||||
export declare function countSelected(selected: Record<string, boolean>): number;
|
||||
/**
|
||||
* Exact import mapping kept from the vendored face: name, host, port, user,
|
||||
* keyPath (identityFile), proxyJump; key auth, empty password, remoteRoot ~.
|
||||
*/
|
||||
export declare function importProfilePayload(host: SshConfigHost): SaveProfilePayload;
|
||||
/** One save attempt inside an import run. */
|
||||
export interface ImportItemOutcome {
|
||||
key: string;
|
||||
name: string;
|
||||
hostName: string;
|
||||
ok: boolean;
|
||||
/** Host/transport error text (absent when ok). */
|
||||
error?: string;
|
||||
/** Synthesized reason when the call resolved without an envelope. */
|
||||
errorCode?: 'no-result';
|
||||
}
|
||||
/** Aggregated per-run statistics (never "selected size" as success count). */
|
||||
export interface ImportSummary {
|
||||
outcomes: ImportItemOutcome[];
|
||||
okCount: number;
|
||||
failCount: number;
|
||||
failedHosts: SshConfigHost[];
|
||||
}
|
||||
/** Injected `saveProfile` port (the vendored api wrapper satisfies this). */
|
||||
export type SaveProfileCall = (payload: SaveProfilePayload) => Promise<{
|
||||
ok?: boolean;
|
||||
error?: string;
|
||||
} | null | undefined>;
|
||||
/**
|
||||
* Import hosts one by one. Each item is checked individually:
|
||||
* - `ok: true` counts as success;
|
||||
* - `ok: false` (or any thrown request error) counts as failure with its reason;
|
||||
* - a missing envelope counts as failure (`errorCode: 'no-result'`) so a
|
||||
* silent transport layer can never be reported as imported.
|
||||
*
|
||||
* Sequential on purpose: profile saves rewrite one settings table, and the
|
||||
* calls are cheap compared to SSH; this also keeps progress deterministic.
|
||||
*/
|
||||
export declare function runImport(hosts: SshConfigHost[], saveProfile: SaveProfileCall, options?: {
|
||||
onProgress?: (done: number, total: number, host: SshConfigHost) => void;
|
||||
}): Promise<ImportSummary>;
|
||||
/**
|
||||
* Fold a failed-only retry run into the previous summary: previously
|
||||
* successful items stay successes (they are never resubmitted), failed items
|
||||
* take the retry outcome.
|
||||
*/
|
||||
export declare function mergeImportRetry(previous: ImportSummary, retry: ImportSummary): ImportSummary;
|
||||
/** Controlled draft of one workspace's write-back / sync settings. */
|
||||
export interface GuardDraft {
|
||||
writeBack: boolean;
|
||||
writeBackExclude: string;
|
||||
syncPaths: string;
|
||||
syncExclude: string;
|
||||
syncMaxBytes: string;
|
||||
}
|
||||
/** Draft initialized from a persisted record (defaults match the Host). */
|
||||
export declare function guardDraftFromWorkspace(workspace: RemoteSshWorkspace): GuardDraft;
|
||||
/** Drafts + baselines keyed by workspace id. */
|
||||
export declare function guardsFromWorkspaces(workspaces: RemoteSshWorkspace[]): Record<string, GuardDraft>;
|
||||
/** Canonical signature: list formatting / "2" vs "2.0" must not look dirty. */
|
||||
export declare function guardDraftSignature(draft: GuardDraft): string;
|
||||
/** Whether the draft differs semantically from the persisted baseline. */
|
||||
export declare function isGuardDraftDirty(draft: GuardDraft, baseline: GuardDraft): boolean;
|
||||
/** Exact `updateWorkspaceGuards` body — always carries the target workspace id. */
|
||||
export declare function toUpdateWorkspaceGuardsPayload(workspaceId: string, draft: GuardDraft): UpdateWorkspaceGuardsPayload;
|
||||
/**
|
||||
* Reconcile drafts with a freshly persisted list. Dirty drafts survive a
|
||||
* reload (their baseline moves to the new server truth); clean drafts adopt
|
||||
* it. Records removed on the Host disappear. A draft with no baseline is
|
||||
* treated as dirty so an unrelated refresh can never wipe typed text.
|
||||
*/
|
||||
export declare function reconcileGuards(previousDrafts: Record<string, GuardDraft>, previousBaselines: Record<string, GuardDraft>, workspaces: RemoteSshWorkspace[]): {
|
||||
drafts: Record<string, GuardDraft>;
|
||||
baselines: Record<string, GuardDraft>;
|
||||
};
|
||||
/** Controlled draft of the advanced section. */
|
||||
export interface PrefsDraft {
|
||||
nodePath: string;
|
||||
writeBackFailure: 'error' | 'log';
|
||||
writeBackFreshness: boolean;
|
||||
defaultSyncPaths: string;
|
||||
defaultSyncExclude: string;
|
||||
defaultSyncMaxBytes: string;
|
||||
}
|
||||
/** Host preferences → draft (same projection the vendored face used). */
|
||||
export declare function prefsDraftFromApi(prefs: RemoteSshPrefs | null | undefined): PrefsDraft;
|
||||
/** Canonical preference signature for dirty detection. */
|
||||
export declare function prefsDraftSignature(draft: PrefsDraft): string;
|
||||
/** Whether the advanced draft differs from the saved preferences. */
|
||||
export declare function isPrefsDraftDirty(draft: PrefsDraft, baseline: PrefsDraft): boolean;
|
||||
/** Exact `savePrefs` body (array conversions + GiB → bytes). */
|
||||
export declare function toSavePrefsPayload(draft: PrefsDraft): SavePrefsPayload;
|
||||
/**
|
||||
* Reconcile the advanced draft with a fresh `getPrefs` read: unsaved edits
|
||||
* survive, clean drafts adopt server truth. Baselines always follow the
|
||||
* server so the dirty badge compares against what is actually stored.
|
||||
*/
|
||||
export declare function reconcilePrefs(previousDraft: PrefsDraft | null, previousBaseline: PrefsDraft | null, serverDraft: PrefsDraft): {
|
||||
draft: PrefsDraft;
|
||||
baseline: PrefsDraft;
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
export declare const SETTINGS_CSS: string;
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
/**
|
||||
* Remote-SSH settings — presentational atoms.
|
||||
*
|
||||
* Every atom here is stateless: drafts, busy flags, confirmations and results
|
||||
* live in the root component (`index.tsx`), which keeps folding reversible and
|
||||
* guarantees that a collapse/refresh can never drop typed input.
|
||||
*
|
||||
* The atoms only use native elements plus React; the sole UI primitive this
|
||||
* face consumes is `Modal` (in `index.tsx`). Styling comes from
|
||||
* `.rsui-*` classes in `settings.css` (DSH theme tokens, light/dark aware).
|
||||
*/
|
||||
import type { ReactNode } from 'react';
|
||||
/** Disclosure chevron; the rotation is a restrained CSS transition. */
|
||||
export declare function ChevronIcon({ open }: {
|
||||
open: boolean;
|
||||
}): import("react").JSX.Element;
|
||||
/**
|
||||
* Feedback glyph. Icons never carry the only error signal: every feedback
|
||||
* block also renders a localized textual prefix (`common.error` /
|
||||
* `common.warning`) so colour-blind users get the same information.
|
||||
*/
|
||||
export declare function StatusIcon({ status }: {
|
||||
status: 'success' | 'warning' | 'error' | 'info';
|
||||
}): import("react").JSX.Element;
|
||||
export interface FieldProps {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onBlur?: (() => void) | undefined;
|
||||
placeholder?: string | undefined;
|
||||
type?: 'text' | 'password' | undefined;
|
||||
autoComplete?: string | undefined;
|
||||
inputMode?: 'text' | 'numeric' | undefined;
|
||||
/** `data-rsui-field` hook consumed by preview/acceptance scripts. */
|
||||
dataField?: string | undefined;
|
||||
hint?: string | undefined;
|
||||
error?: string | undefined;
|
||||
mono?: boolean | undefined;
|
||||
}
|
||||
export declare function Field({ id, label, value, onChange, onBlur, placeholder, type, autoComplete, inputMode, dataField, hint, error, mono }: FieldProps): import("react").JSX.Element;
|
||||
export interface TextAreaFieldProps {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string | undefined;
|
||||
dataField?: string | undefined;
|
||||
hint?: string | undefined;
|
||||
rows?: number | undefined;
|
||||
}
|
||||
export declare function TextAreaField({ id, label, value, onChange, placeholder, dataField, hint, rows }: TextAreaFieldProps): import("react").JSX.Element;
|
||||
export interface CheckFieldProps {
|
||||
id: string;
|
||||
label: string;
|
||||
checked: boolean;
|
||||
onChange: (checked: boolean) => void;
|
||||
dataField?: string | undefined;
|
||||
}
|
||||
export declare function CheckField({ id, label, checked, onChange, dataField }: CheckFieldProps): import("react").JSX.Element;
|
||||
export interface SelectFieldProps {
|
||||
id: string;
|
||||
label: string;
|
||||
value: string;
|
||||
options: ReadonlyArray<{
|
||||
value: string;
|
||||
label: string;
|
||||
}>;
|
||||
onChange: (value: string) => void;
|
||||
dataField?: string | undefined;
|
||||
hint?: string | undefined;
|
||||
}
|
||||
export declare function SelectField({ id, label, value, options, onChange, dataField, hint }: SelectFieldProps): import("react").JSX.Element;
|
||||
export type NoticeTone = 'success' | 'warning' | 'error' | 'info';
|
||||
export interface NoticeProps {
|
||||
tone?: NoticeTone | undefined;
|
||||
title: string;
|
||||
/** Localized textual prefix, e.g. `common.error` / `common.warning`. */
|
||||
prefix?: string | undefined;
|
||||
detail?: string | undefined;
|
||||
action?: ReactNode;
|
||||
}
|
||||
/**
|
||||
* Generic status/alert block. `role` follows the tone (`alert` for errors,
|
||||
* `status` otherwise) so screen readers announce failures without relying on
|
||||
* the red colour alone.
|
||||
*/
|
||||
export declare function Notice({ tone, title, prefix, detail, action }: NoticeProps): import("react").JSX.Element;
|
||||
|
|
@ -75,10 +75,8 @@ export interface WorkspaceGroupNode {
|
|||
sessions: readonly SessionNode[];
|
||||
/**
|
||||
* Folder rows, present only when the workspace carries at least one extra
|
||||
* folder: root first, then stored order. The base directory is never a row —
|
||||
* it is the workspace row itself, and its sessions live in {@link sessions}.
|
||||
* Absent means "this workspace has exactly one directory", the plain
|
||||
* pre-folders node shape.
|
||||
* folder: root first, then stored order, base included. Absent means "this
|
||||
* workspace has exactly one directory", the plain pre-folders node shape.
|
||||
*/
|
||||
folders?: readonly FolderNode[];
|
||||
}
|
||||
|
|
@ -133,11 +131,10 @@ export interface MemberWorkspaces {
|
|||
*/
|
||||
export declare function memberWorkspaces(workspaces: readonly WorkspaceView[], folders?: FoldersDocument): MemberWorkspaces;
|
||||
/**
|
||||
* Display label of one folder: the last path segment. A drive root or the
|
||||
* POSIX root has no segment, so the whole path is the honest label.
|
||||
* Display label of one folder: the last path segment. A drive root (`C:\`) or
|
||||
* the POSIX root has no segment, so the whole path is the honest label.
|
||||
* @param path - absolute folder path.
|
||||
*/
|
||||
export declare function folderLabel(path: string): string;
|
||||
*/ export declare function folderLabel(path: string): string;
|
||||
/** Stable identity of one folder row (same path may live under two workspaces). */
|
||||
export declare function folderKey(workspaceId: WorkspaceId, path: string): string;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,21 +1,20 @@
|
|||
/**
|
||||
* Recognising the Host's own default workspace ("默认工作区").
|
||||
*
|
||||
* 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.
|
||||
* 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 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.)
|
||||
* 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.
|
||||
*/
|
||||
/** Directory name the Host uses for its default workspace (host mirror). */
|
||||
export declare const DEFAULT_WORKSPACE_TITLE = "default-workspace";
|
||||
|
|
@ -28,7 +27,6 @@ export interface DefaultWorkspaceIdentity {
|
|||
}
|
||||
/**
|
||||
* Whether a workspace snapshot is the Host's default workspace.
|
||||
* @param workspace - workspace snapshot (path is primary, title is a fallback
|
||||
* for path-less snapshots).
|
||||
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
|
||||
*/
|
||||
export declare function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean;
|
||||
|
|
|
|||
|
|
@ -15,12 +15,6 @@
|
|||
*
|
||||
* 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';
|
||||
|
|
@ -66,37 +60,20 @@ export interface WorkspaceFolderEntry {
|
|||
/** The whole `workspace-groups.folders.json` document. */
|
||||
export interface FoldersDocument {
|
||||
readonly version: 1;
|
||||
/**
|
||||
* Monotonic write counter, owned by the host: every accepted PUT bumps it
|
||||
* and a PUT whose revision does not match the stored one is rejected
|
||||
* (409), so two windows can no longer silently overwrite each other's
|
||||
* edits. Absent in documents written before revisions existed — read as 0.
|
||||
*/
|
||||
readonly revision?: number;
|
||||
readonly workspaces: Readonly<Record<string, WorkspaceFolderEntry>>;
|
||||
}
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
export declare const EMPTY_FOLDERS_DOCUMENT: FoldersDocument;
|
||||
/** 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, `.`/`..` segments and Unicode normalization, exact for
|
||||
* POSIX paths.
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
|
|
@ -121,24 +98,40 @@ export declare function effectiveFolders(workspacePath: string, entry: Workspace
|
|||
* @param path - folder path as stored.
|
||||
*/
|
||||
export declare function memberOf(entry: WorkspaceFolderEntry | undefined, path: string): FolderMember | undefined;
|
||||
/**
|
||||
* Light canonical form of a REMOTE path (POSIX — the server's filesystem):
|
||||
* trimmed, trailing slashes removed. Deliberately string-only: the client
|
||||
* cannot resolve `~` or symlinks; the remote-ssh host canonicalizes fully
|
||||
* at registration time. This is the second line of defense, catching the
|
||||
* spelling variants a user can type into the add-cloud-folder dialog.
|
||||
* @param raw - remote path as typed or as stored.
|
||||
*/
|
||||
export declare function lightRemotePath(raw: string): string;
|
||||
/**
|
||||
* Whether two remote paths name the same directory under {@link lightRemotePath}.
|
||||
* @param a - first remote path.
|
||||
* @param b - second remote path.
|
||||
*/
|
||||
export declare function sameRemotePath(a: string, b: string): boolean;
|
||||
/**
|
||||
* The member backed by one native workspace id, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param workspaceId - native workspace id backing the member.
|
||||
*/
|
||||
export declare function memberByWorkspaceId(entry: WorkspaceFolderEntry | undefined, workspaceId: string): FolderMember | undefined;
|
||||
/**
|
||||
* The remote member for one connection + remote directory, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param profileId - remote-ssh connection id.
|
||||
* @param remotePath - remote directory to look up.
|
||||
*/
|
||||
export declare function findRemoteMember(entry: WorkspaceFolderEntry | undefined, profileId: string, remotePath: string): FolderMember | undefined;
|
||||
/**
|
||||
* Every member folder of one owner workspace, in stored order.
|
||||
* @param doc - folders document.
|
||||
* @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.
|
||||
*
|
||||
|
|
@ -166,9 +159,6 @@ 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.
|
||||
|
|
@ -186,11 +176,6 @@ 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.
|
||||
*/
|
||||
|
|
@ -199,9 +184,6 @@ 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.
|
||||
*/
|
||||
|
|
@ -216,8 +198,7 @@ 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}. `..` segments are collapsed on
|
||||
* both sides first, so a traversal spelling cannot fake containment.
|
||||
* separator and case rules as {@link samePath}.
|
||||
* @param path - candidate path.
|
||||
* @param base - containing directory.
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -69,6 +69,13 @@ export interface GroupsConfig {
|
|||
* `appearance` (group color / icon / pin) is lost after a downgrade.
|
||||
*/
|
||||
export interface ManualGroups {
|
||||
/**
|
||||
* Monotonic write counter, owned by the host (same contract as the folder
|
||||
* overlay): a PUT whose revision does not match the stored one is
|
||||
* rejected with 409 instead of silently overwriting another window's
|
||||
* edits. Absent in files written before revisions existed — read as 0.
|
||||
*/
|
||||
revision?: number;
|
||||
/**
|
||||
* Manually created category folder names. These have no rules — they render
|
||||
* even while empty (a new group appears before anything is dragged into
|
||||
|
|
|
|||
|
|
@ -19,28 +19,13 @@ 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 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.
|
||||
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
|
||||
* here too — a mismatch would silently disable the distinction.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
export declare function isAbsoluteFolderPath(path: string): boolean;
|
||||
|
|
@ -56,89 +41,48 @@ 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 — but ONLY when the file
|
||||
* could actually be read and parsed; `readFoldersState` is responsible for
|
||||
* reporting a read/parse failure as an error.
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
export declare function parseFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* The document's write counter: a non-negative safe integer, else 0. Tolerant
|
||||
* on purpose — reads must survive hand-edited sidecars; the strict writer
|
||||
* below rejects bad values instead of letting them through.
|
||||
* @param value - the raw `revision` field.
|
||||
*/
|
||||
export declare function readRevision(value: unknown): number;
|
||||
/**
|
||||
* 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, the root
|
||||
* membership or cross-workspace references are wrong.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
export declare function validateFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* 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.
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
export declare function readFoldersDocument(path: string): Promise<FoldersDocument>;
|
||||
/**
|
||||
* Atomically replace the overlay file. Kept as the public single-document
|
||||
* writer used by the verifier scripts; the HTTP route uses
|
||||
* `replaceFoldersDocument` instead, which adds the CAS guard.
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
||||
/** 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, absolute or escaping subpath.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;
|
||||
|
|
|
|||
45
package.json
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "workspace-groups-local",
|
||||
"name": "workspace-groups-remote",
|
||||
"version": "1.3.0",
|
||||
"description": "Complete workspace grouping manager for the DSH web sidebar: category -> project -> session three-level tree with optional per-project folders (multi-root), manual group create/rename/delete, drag-and-drop grouping and ordering with insertion indicator, rule-based auto-classification, tree search, group colour/icon/pin, plus the session tab strip seated in the conversation column head. Sidecar YAML + runtime overlays, zero core-storage intrusion.",
|
||||
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"deepseek-harness",
|
||||
|
|
@ -11,21 +11,16 @@
|
|||
"sidebar",
|
||||
"workspace",
|
||||
"workspace-groups",
|
||||
"client-plugin"
|
||||
"client-plugin",
|
||||
"ssh",
|
||||
"remote-ssh",
|
||||
"remote-development"
|
||||
],
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/newbieQQ/dsh-better-workspace-group"
|
||||
},
|
||||
"homepage": "https://github.com/newbieQQ/dsh-better-workspace-group",
|
||||
"bugs": {
|
||||
"url": "https://github.com/newbieQQ/dsh-better-workspace-group/issues"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
|
|
@ -42,11 +37,11 @@
|
|||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"!lib/**/*.map",
|
||||
"cordis.patch.yml",
|
||||
"README.md",
|
||||
"README_ZH.md",
|
||||
"NOTICE.md",
|
||||
"screenshot.png",
|
||||
"workspace-groups.example.yaml"
|
||||
],
|
||||
"engines": {
|
||||
|
|
@ -68,17 +63,24 @@
|
|||
"@deepseek-ai/dsh-client-ui-renderer",
|
||||
"@deepseek-ai/dsh-client-ui-session",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar",
|
||||
"@deepseek-ai/dsh-client-ui-workspace"
|
||||
"@deepseek-ai/dsh-client-ui-workspace",
|
||||
"@deepseek-ai/dsh-client-modules",
|
||||
"@deepseek-ai/dsh-client-ui-primitives",
|
||||
"@deepseek-ai/dsh-client-ui-slots"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\" && tsc -p tsconfig.build.json --noEmit false --declaration --emitDeclarationOnly --outDir lib/types && tsdown",
|
||||
"build": "node scripts/build-safe.mjs",
|
||||
"build:inner": "node scripts/build-remote-ssh-client.mjs && node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\" && tsc -p tsconfig.build.json --noEmit false --declaration --emitDeclarationOnly --outDir lib/types && tsdown && node scripts/build-bundle.mjs",
|
||||
"build:types": "tsc -p tsconfig.build.json --noEmit false --declaration --emitDeclarationOnly --outDir lib/types",
|
||||
"watch": "tsdown --watch",
|
||||
"watch": "node scripts/watch.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
|
||||
"verify": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit && vitest run",
|
||||
"test": "vitest run"
|
||||
"verify": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit && npm run verify:bundle && npm run test:patch && vitest run",
|
||||
"vendor:manifest": "node scripts/vendor-manifest.mjs --write",
|
||||
"test": "vitest run",
|
||||
"verify:bundle": "node scripts/verify-bundle.mjs",
|
||||
"test:patch": "node scripts/test-remote-ssh-patch.mjs"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.2",
|
||||
|
|
@ -95,7 +97,8 @@
|
|||
"@deepseek-ai/dsh-host-webserver": ">=0.1.7-rc.2 <0.3.0",
|
||||
"@deepseek-ai/dsh-session": ">=0.1.7-rc.2 <0.3.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
"react-dom": "^18.2.0",
|
||||
"@deepseek-ai/dsh-tools": "^0.1.0-rc.6 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1 || ^0.2.1-rc.1"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
|
|
@ -103,7 +106,9 @@
|
|||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
"js-yaml": "^4.1.0",
|
||||
"@deepseek-ai/schemastery": "^3.18.4",
|
||||
"yaml": "^2.9.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.4",
|
||||
|
|
@ -136,4 +141,4 @@
|
|||
"vitest": "4.1.8",
|
||||
"zustand": "^5.0.15"
|
||||
}
|
||||
}
|
||||
}
|
||||
1781
pnpm-lock.yaml
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 138 KiB |
|
|
@ -0,0 +1,97 @@
|
|||
{
|
||||
"isolatedPreview": true,
|
||||
"note": "真实组件 + 假 /remote-ssh/api 数据,在 headless Chrome 中渲染截图;不是 AI 效果图,未修改 DSH GUI / daily profile / node_modules。",
|
||||
"component": "src/client/rssh-settings/index.tsx",
|
||||
"screenshots": [
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/01-default.png",
|
||||
"scene": "default",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x1605",
|
||||
"durationMs": 1003,
|
||||
"description": "默认(高级设置收起)"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/02-expanded.png",
|
||||
"scene": "expanded",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x3529",
|
||||
"durationMs": 2163,
|
||||
"description": "全部展开(字段可核对)"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/03-import-dialog.png",
|
||||
"scene": "import-ready",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "viewport",
|
||||
"size": "1280x900",
|
||||
"durationMs": 1297,
|
||||
"description": "SSH 导入弹窗(列表 / 已选数量)"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/04-import-partial.png",
|
||||
"scene": "import-partial",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "viewport",
|
||||
"size": "1280x900",
|
||||
"durationMs": 2224,
|
||||
"description": "导入部分失败结果 + 仅重试失败项"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/05-workspaces.png",
|
||||
"scene": "workspaces",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x2861",
|
||||
"durationMs": 1541,
|
||||
"description": "远程工作区独立配置展开 + 未保存徽标"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/06-password-auth.png",
|
||||
"scene": "password",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x1605",
|
||||
"durationMs": 1564,
|
||||
"description": "密码认证表单"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/07-dark.png",
|
||||
"scene": "expanded",
|
||||
"theme": "dark",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x3529",
|
||||
"durationMs": 2127,
|
||||
"description": "深色模式(全部展开)"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/08-narrow.png",
|
||||
"scene": "default",
|
||||
"theme": "light",
|
||||
"viewportWidth": 480,
|
||||
"capture": "full",
|
||||
"size": "480x1890",
|
||||
"durationMs": 1313,
|
||||
"description": "窄屏约 480px 单列"
|
||||
},
|
||||
{
|
||||
"file": "screenshots/remote-ssh-settings/09-test-failure.png",
|
||||
"scene": "test-failure",
|
||||
"theme": "light",
|
||||
"viewportWidth": 1280,
|
||||
"capture": "full",
|
||||
"size": "1280x1769",
|
||||
"durationMs": 1395,
|
||||
"description": "连接测试失败诊断"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
// Build step (runs last, after tsdown): assemble the merged host artifact.
|
||||
// - lib/groups.js + lib/client.js come from tsdown.
|
||||
// - lib/remote-ssh/index.js is the vendored upstream host half with the
|
||||
// bundle's one local patch applied at build time (it must stay unbundled
|
||||
// — see bundle/index.js — and the vendor tree stays pristine; see
|
||||
// scripts/patch-remote-ssh.mjs).
|
||||
// - lib/index.js is the composition entry from bundle/index.js.
|
||||
import { copyFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { writePatchedRemoteSsh } from './patch-remote-ssh.mjs'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
writePatchedRemoteSsh(root)
|
||||
copyFileSync(join(root, 'bundle/index.js'), join(root, 'lib/index.js'))
|
||||
console.log('bundle assembled: lib/index.js (composition) + lib/groups.js + lib/remote-ssh/index.js (patched) + lib/client.js')
|
||||
|
|
@ -0,0 +1,277 @@
|
|||
// Build step: turn the vendored dsh-remote-ssh client bundle into an
|
||||
// importable factory module for the merged client entry.
|
||||
//
|
||||
// Upstream ships lib/client.js as a self-registering module-loader bundle:
|
||||
// window.__ModuleLoader__.load({ id: "@zhangfengshun/dsh-remote-ssh",
|
||||
// factory: (require) => { ... } })
|
||||
// A DSH package gets exactly ONE client row (keyed by package name), so the
|
||||
// merged package cannot ship that file as-is. This script strips the
|
||||
// registration wrapper and re-exports the factory itself; the merged client
|
||||
// entry invokes it with the bundle's own require and applies the result
|
||||
// next to the workspace-groups client. The factory body is byte-identical
|
||||
// to upstream — only the two wrapper lines change.
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const source = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/client.js'), 'utf8')
|
||||
|
||||
const LOAD = 'window.__ModuleLoader__.load({'
|
||||
if (source.split(LOAD).length - 1 !== 1) throw new Error('remote-ssh client: expected exactly one __ModuleLoader__.load call')
|
||||
const loadAt = source.indexOf(LOAD)
|
||||
const header = source.slice(0, loadAt)
|
||||
const rest = source.slice(loadAt + LOAD.length)
|
||||
|
||||
const ID_LINE = '\n id: "@zhangfengshun/dsh-remote-ssh",'
|
||||
if (!rest.startsWith(ID_LINE)) throw new Error('remote-ssh client: id line anchor mismatch')
|
||||
const FACTORY_LINE = '\n factory: (require) => {'
|
||||
const afterId = rest.slice(ID_LINE.length)
|
||||
if (!afterId.startsWith(FACTORY_LINE)) throw new Error('remote-ssh client: factory line anchor mismatch')
|
||||
let body = afterId.slice(FACTORY_LINE.length)
|
||||
|
||||
const TAIL = '\n }\n});'
|
||||
if (body.endsWith(TAIL + '\n')) body = body.slice(0, -(TAIL.length + 1))
|
||||
else if (body.endsWith(TAIL)) body = body.slice(0, -TAIL.length)
|
||||
else throw new Error('remote-ssh client: tail anchor mismatch')
|
||||
|
||||
// [workspace-groups-remote patch] Replace the upstream root-label heuristic
|
||||
// (basename + inline padding-left:6px) with an exact full-path identity match.
|
||||
// better-sidebar's RootRow carries the complete directory in `title`; only an
|
||||
// element whose title equals a remote workspace's mirrorPath is rewritten, so
|
||||
// a same-named local directory can never be relabelled by mistake. If a future
|
||||
// shell drops that attribute nothing is changed (safe degradation).
|
||||
const ROOT_LABEL_OLD = ` // ---- 文件树根标签:显示远程目录名,而不是本地镜像目录 ID(issue #9)----
|
||||
// better-sidebar「文件」页签的树根标签取自会话 cwd(= 本地镜像路径)的 basename,
|
||||
// 于是显示成镜像目录 ID(如 wmirror3)。这条链路不经过任何 fs.* 路由,
|
||||
// 而 Host 侧 session.cwd 虽然已返回 root 字段,客户端只消费 cwd
|
||||
// (client-registry 的 api.sessionCwd(...).then(r => setFetchedCwd(r.cwd)),
|
||||
// 另有 useSessionCwd 直接读客户端会话列表的 cwd),因此只能在渲染层替换文本。
|
||||
// 定位不依赖构建期哈希类名:根行是树里唯一带内联 padding-left:6px 的行,
|
||||
// 仅当该行内的纯文本节点 === 某远程工作区的镜像 basename 时才替换(幂等、可自愈)。
|
||||
var watchedRootLabels = []; // 已替换的标签元素:1s 幂等复检,抵消 React 重渲染
|
||||
function refreshRootLabels(workspaces) {
|
||||
var next = {};
|
||||
for (var i = 0; i < (workspaces || []).length; i++) {
|
||||
var w = workspaces[i] || {};
|
||||
var mirror = String(w.mirrorPath || "").replace(/[\\\\/]+$/, "");
|
||||
var remote = String(w.remotePath || "").replace(/[\\\\/]+$/, "");
|
||||
if (!mirror || !remote) continue;
|
||||
var mb = mirror.split(/[\\\\/]/).pop();
|
||||
var rb = remote.split(/[\\\\/]/).pop();
|
||||
if (mb && rb && mb !== rb) next[mb] = { label: rb, remotePath: remote };
|
||||
}
|
||||
rootLabels = next;
|
||||
}
|
||||
/** 根行判据:自身或 ≤3 层祖先带内联 padding-left:6px(better-sidebar 根行样式)。 */
|
||||
function isRootRow(el) {
|
||||
var node = el;
|
||||
for (var hop = 0; hop < 3 && node; hop++) {
|
||||
var style = node.getAttribute ? node.getAttribute("style") : null;
|
||||
if (style && /padding-left:\\s*6px/i.test(String(style))) return true;
|
||||
node = node.parentElement;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** 单个标签替换:纯文本 + 命中镜像 basename + 位于根行 → 换成远程目录名。 */
|
||||
function fixRootLabel(el) {
|
||||
var text = (el.textContent || "").trim();
|
||||
if (!text) return false;
|
||||
var hit = rootLabels[text];
|
||||
if (hit === undefined) {
|
||||
// 文本已是远程目录名(上一轮替换过)→ 幂等成功;否则与本插件无关
|
||||
return el.getAttribute && el.getAttribute("data-rssh-root-label") === "1";
|
||||
}
|
||||
if (el.childElementCount > 0) return false; // 只改纯文本节点
|
||||
if (!isRootRow(el)) return false; // 非根行(例如同名子条目)不动
|
||||
el.textContent = hit.label;
|
||||
if (el.setAttribute) {
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
}
|
||||
watchRootLabel(el);
|
||||
return true;
|
||||
}
|
||||
function watchRootLabel(el) {
|
||||
for (var i = 0; i < watchedRootLabels.length; i++) { if (watchedRootLabels[i] === el) return; }
|
||||
watchedRootLabels.push(el);
|
||||
}
|
||||
function recheckRootLabels() {
|
||||
for (var i = watchedRootLabels.length - 1; i >= 0; i--) {
|
||||
var el = watchedRootLabels[i];
|
||||
if (!el || !el.isConnected) { watchedRootLabels.splice(i, 1); continue; }
|
||||
fixRootLabel(el);
|
||||
}
|
||||
}
|
||||
function applyRootLabelsIn(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
try {
|
||||
var nodes = root.querySelectorAll("span,div");
|
||||
for (var i = 0; i < nodes.length; i++) fixRootLabel(nodes[i]);
|
||||
if (root.nodeType === 1) fixRootLabel(root);
|
||||
} catch (e) {}
|
||||
}`
|
||||
|
||||
const ROOT_LABEL_NEW = ` // ---- 文件树根标签:按完整镜像路径精确认行(issue #9)----
|
||||
// better-sidebar 的根行 title 是完整目录路径(RootRow title={path})。
|
||||
// 只在该 title 精确等于某个远程工作区的 mirrorPath 时才改写名称:不再
|
||||
// 按 basename 或内联 padding-left 猜测目录身份,因此同名本地目录不会
|
||||
// 被误改;属性缺席时保持原样(安全降级)。
|
||||
var watchedRootLabels = []; // 已替换的标签元素:1s 幂等复检,抵消 React 重渲染
|
||||
var rootLabels = {};
|
||||
function normRemotePath(value) {
|
||||
return String(value == null ? "" : value).replace(/[\\\\/]+$/, "");
|
||||
}
|
||||
function refreshRootLabels(workspaces) {
|
||||
var next = {};
|
||||
for (var i = 0; i < (workspaces || []).length; i++) {
|
||||
var w = workspaces[i] || {};
|
||||
var mirror = normRemotePath(w.mirrorPath);
|
||||
var remote = normRemotePath(w.remotePath);
|
||||
if (!mirror || !remote) continue;
|
||||
var title = normTitle(w.title);
|
||||
var label = title || remote.split(/[\\\\/]/).pop();
|
||||
if (label) next[mirror] = { label: label, remotePath: remote, mirrorPath: mirror };
|
||||
}
|
||||
rootLabels = next;
|
||||
}
|
||||
/** The root row's own full path, from the explicit attributes only. */
|
||||
function rootPathOf(el) {
|
||||
var explicit = el && el.getAttribute ? el.getAttribute("data-rssh-root-mirror") : null;
|
||||
if (explicit) return normRemotePath(explicit);
|
||||
var title = el && el.getAttribute ? el.getAttribute("title") : null;
|
||||
return title ? normRemotePath(title) : "";
|
||||
}
|
||||
/** Direct leaf <span> that prints the folder name (no nested markup). */
|
||||
function rootLabelSpanOf(el) {
|
||||
var children = el && el.children ? el.children : [];
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
if (String(children[i].tagName || "").toLowerCase() === "span" && children[i].childElementCount === 0) return children[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Exact full-path hit → replace only the leaf name span. */
|
||||
function fixRootLabel(el) {
|
||||
if (!el || !el.getAttribute) return false;
|
||||
var path = rootPathOf(el);
|
||||
if (!path) return false;
|
||||
var hit = rootLabels[path];
|
||||
if (hit === undefined) return false;
|
||||
var span = rootLabelSpanOf(el);
|
||||
if (!span) return false;
|
||||
var base = path.split(/[\\\\/]/).pop();
|
||||
var text = normTitle(span.textContent);
|
||||
if (text !== base && el.getAttribute("data-rssh-root-label") !== "1") return false;
|
||||
span.textContent = hit.label;
|
||||
el.setAttribute("data-rssh-root-label", "1");
|
||||
el.setAttribute("data-rssh-root-mirror", hit.mirrorPath);
|
||||
el.setAttribute("title", hit.remotePath); // 悬停可见完整远程路径
|
||||
watchRootLabel(el);
|
||||
return true;
|
||||
}
|
||||
function watchRootLabel(el) {
|
||||
for (var i = 0; i < watchedRootLabels.length; i++) { if (watchedRootLabels[i] === el) return; }
|
||||
watchedRootLabels.push(el);
|
||||
}
|
||||
function recheckRootLabels() {
|
||||
for (var i = watchedRootLabels.length - 1; i >= 0; i--) {
|
||||
var el = watchedRootLabels[i];
|
||||
if (!el || !el.isConnected) { watchedRootLabels.splice(i, 1); continue; }
|
||||
fixRootLabel(el);
|
||||
}
|
||||
}
|
||||
function applyRootLabelsIn(root) {
|
||||
if (!root || !root.querySelectorAll) return;
|
||||
try {
|
||||
// Only elements carrying the full path title are candidates; no
|
||||
// text/basename or inline-style scan.
|
||||
var nodes = root.querySelectorAll("[title]");
|
||||
for (var i = 0; i < nodes.length; i++) fixRootLabel(nodes[i]);
|
||||
if (root.nodeType === 1) fixRootLabel(root);
|
||||
} catch (e) {}
|
||||
}`
|
||||
|
||||
const occurrences = body.split(ROOT_LABEL_OLD).length - 1
|
||||
if (occurrences !== 1) throw new Error('remote-ssh client: root-label block anchor found ' + occurrences + ' times')
|
||||
body = body.replace(ROOT_LABEL_OLD, ROOT_LABEL_NEW)
|
||||
|
||||
// [workspace-groups-remote patch] Settings face replacement.
|
||||
// Upstream's settings face (SettingsSection, ~280 lines of compiled JS) is
|
||||
// replaced at build time by the maintainable source component in
|
||||
// src/client/rssh-settings. The merged client entry passes a `compose` object
|
||||
// into this factory (createSettingsSection + dictionary namespace); the
|
||||
// vendored component stays as a fallback for a factory invoked without one
|
||||
// (older entry, verification harness). Anchor-asserted like every other
|
||||
// patch: an upstream change fails the build loudly instead of silently
|
||||
// shipping the old face.
|
||||
const SETTINGS_REGISTRATION_OLD = ` slots.inject("settings.section", function () {
|
||||
return slots.register({
|
||||
name: "settings.section",
|
||||
id: "remote-ssh",
|
||||
order: 200,
|
||||
label: function () { return i18n.t("settings.nav"); },
|
||||
locale: NS
|
||||
}, SettingsSection);
|
||||
});`
|
||||
|
||||
const SETTINGS_REGISTRATION_NEW = ` // [workspace-groups-remote patch] Settings face replacement:
|
||||
// the maintainable source component (src/client/rssh-settings) owns
|
||||
// the page; allocate it once per registration and keep upstream's
|
||||
// SettingsSection as the fallback when compose is absent. The
|
||||
// dictionary namespace comes from compose so the slot renderer
|
||||
// injects the component's typed \`t\` seat from this bundle's own
|
||||
// locale registration.
|
||||
slots.inject("settings.section", function () {
|
||||
var settingsComponent = SettingsSection;
|
||||
var settingsLocale = NS;
|
||||
try {
|
||||
if (compose && typeof compose.createSettingsSection === "function") {
|
||||
settingsComponent = compose.createSettingsSection({ api: api });
|
||||
if (compose.settingsNamespace) settingsLocale = String(compose.settingsNamespace);
|
||||
}
|
||||
} catch (error) {
|
||||
settingsComponent = SettingsSection;
|
||||
settingsLocale = NS;
|
||||
}
|
||||
return slots.register({
|
||||
name: "settings.section",
|
||||
id: "remote-ssh",
|
||||
order: 200,
|
||||
label: function () { return i18n.t("settings.nav"); },
|
||||
locale: settingsLocale
|
||||
}, settingsComponent);
|
||||
});`
|
||||
|
||||
const settingsOccurrences = body.split(SETTINGS_REGISTRATION_OLD).length - 1
|
||||
if (settingsOccurrences !== 1) {
|
||||
throw new Error('remote-ssh client: settings registration anchor found ' + settingsOccurrences + ' times — upstream changed, re-check the transform')
|
||||
}
|
||||
body = body.replace(SETTINGS_REGISTRATION_OLD, SETTINGS_REGISTRATION_NEW)
|
||||
|
||||
const out = header
|
||||
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
|
||||
+ '// Upstream registers this factory under its own package id; the merged\n'
|
||||
+ '// package registers ONE client row, so the factory is exported instead\n'
|
||||
+ '// and applied by src/client/index.ts. Body below is upstream-verbatim\n'
|
||||
+ '// apart from anchor-asserted patches (root label, settings face).\n'
|
||||
+ '// The second argument is the merged entry\'s compose seam:\n'
|
||||
+ '// compose.settingsNamespace + compose.createSettingsSection(deps)\n'
|
||||
+ 'export default (require, compose) => {'
|
||||
+ body
|
||||
+ '\n}\n'
|
||||
|
||||
// Post-conditions: the vulnerable/old forms must be gone and the compose
|
||||
// seam present, so a successful build can never silently keep the old face.
|
||||
if (out.includes('}, SettingsSection);')) {
|
||||
throw new Error('remote-ssh client: the upstream settings registration survived the transform')
|
||||
}
|
||||
for (const required of [
|
||||
'export default (require, compose) => {',
|
||||
'compose.createSettingsSection({ api: api })',
|
||||
'var settingsComponent = SettingsSection;',
|
||||
'locale: settingsLocale',
|
||||
]) {
|
||||
if (!out.includes(required)) throw new Error('remote-ssh client: expected transformed form missing: ' + required)
|
||||
}
|
||||
writeFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), out)
|
||||
console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs')
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
// Build with a safety net: snapshot lib/ first, and if any build step
|
||||
// fails, restore the previous artifacts — a failed build must never leave
|
||||
// a half-built lib/ behind for the next install to pick up.
|
||||
import { cpSync, existsSync, rmSync } from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const lib = join(root, 'lib')
|
||||
const backup = join(root, '.lib-backup')
|
||||
|
||||
rmSync(backup, { recursive: true, force: true })
|
||||
const hadLib = existsSync(lib)
|
||||
if (hadLib) cpSync(lib, backup, { recursive: true })
|
||||
|
||||
const run = spawnSync('npm', ['run', 'build:inner'], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
shell: process.platform === 'win32',
|
||||
})
|
||||
if (run.status !== 0) {
|
||||
if (hadLib) {
|
||||
rmSync(lib, { recursive: true, force: true })
|
||||
cpSync(backup, lib, { recursive: true })
|
||||
console.error('build-safe: build failed — the previous lib/ has been restored')
|
||||
} else {
|
||||
console.error('build-safe: build failed (no previous lib/ to restore)')
|
||||
}
|
||||
rmSync(backup, { recursive: true, force: true })
|
||||
process.exit(run.status ?? 1)
|
||||
}
|
||||
rmSync(backup, { recursive: true, force: true })
|
||||
|
|
@ -0,0 +1,412 @@
|
|||
// Build step for the merged bundle: produce lib/remote-ssh/index.js from the
|
||||
// vendored upstream host half (vendor/dsh-remote-ssh/lib/index.js, kept
|
||||
// pristine) with the bundle's local patch set applied. Every edit is
|
||||
// anchor-asserted: if upstream changes the anchored code, the build fails
|
||||
// loudly instead of silently shipping an unpatched file.
|
||||
//
|
||||
// Patch 1 — canonical remote-path identity in createRemoteWorkspace:
|
||||
// upstream's issue-#32 reuse lookup compares remotePath as a raw string, so
|
||||
// the same remote directory spelled two ways (~/proj vs /home/u/proj vs
|
||||
// proj/) registers a second workspace record, a second local mirror and a
|
||||
// second native workspace — the "duplicate folder" bug. The patch compares
|
||||
// light-normalized spellings first; on a miss it resolves the path once
|
||||
// over SSH (pwd -P + $HOME) and compares canonical forms, storing the
|
||||
// canonical spelling so records converge. Resolution failures are
|
||||
// fail-open: creation proceeds with the light form, exactly as upstream,
|
||||
// never blocked.
|
||||
//
|
||||
// Patch 2 — ssh argv hardening in sshArgv (the single constructor every
|
||||
// internal connection flows through):
|
||||
// a) "--" is inserted before the user@host target. Profile fields reach
|
||||
// this point from settings, ~/.ssh/config imports and the remote_ssh
|
||||
// tools' inline arguments; a user/host value starting with "-" (e.g.
|
||||
// -oProxyCommand=...) would otherwise be parsed as an ssh option and
|
||||
// execute LOCAL commands, breaking the tools' "remote only" boundary.
|
||||
// b) POSIX password auth uses `sshpass -e` (password via the SSHPASS
|
||||
// environment variable, merged into the spawn env by the caller)
|
||||
// instead of `sshpass -p`, which leaves the password in the process
|
||||
// list, readable by every local user via ps / /proc/<pid>/cmdline —
|
||||
// on the shared login nodes this plugin targets, that is everyone.
|
||||
// (The Windows path already passes its password via env.)
|
||||
//
|
||||
// Patch 3 — the generated terminal shell wrapper (dsh-remote-shell):
|
||||
// a) The marker file .remote-ssh.json is honored only when the cwd IS a
|
||||
// direct child of the mirror base ~/.dsh/remote-workspaces — exactly
|
||||
// where the host itself writes it. A marker planted in a cloned repo
|
||||
// or any other directory must never auto-connect the user's terminal
|
||||
// to an attacker's server.
|
||||
// b) StrictHostKeyChecking=no becomes accept-new (aligning with the
|
||||
// internal channel): a changed host key fails loudly.
|
||||
// c) "--" before the user@host target, same as patch 2a.
|
||||
// d) remotePath reaches the remote shell base64-encoded and is decoded
|
||||
// there, so its content is data, never shell syntax: quotes, $() and
|
||||
// backticks in a directory name can no longer break out. (~ still
|
||||
// expands on the remote side; a remote without base64 falls back to
|
||||
// $HOME exactly as the old code did when cd failed.)
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HELPERS = `// ---------------------------------------------------------------------------
|
||||
// [workspace-groups-remote local patch] Canonical remote-path identity.
|
||||
// See scripts/patch-remote-ssh.mjs in the merged bundle for the rationale.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Light canonical form of a remote path: trimmed, trailing slashes removed. */
|
||||
function lightRemotePath(raw) {
|
||||
let s = String(raw == null ? "" : raw).trim();
|
||||
if (s.length > 1) s = s.replace(/\\/+$/, "");
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Expand a leading ~ or ~/ with the remote home directory, when known. */
|
||||
function expandRemoteHome(path, home) {
|
||||
const h = String(home == null ? "" : home).replace(/\\/+$/, "");
|
||||
if (!h) return path;
|
||||
if (path === "~") return h;
|
||||
if (path.startsWith("~/")) return h + path.slice(1);
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a remote path to its canonical absolute identity through one SSH
|
||||
* round trip (also learns the remote $HOME). Returns a discriminated result:
|
||||
* ok:false is NOT "not a duplicate" — the caller must refuse to create
|
||||
* because it cannot prove the path is distinct.
|
||||
*/
|
||||
async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
||||
const light = lightRemotePath(rawPath);
|
||||
if (!light) return { ok: false, error: "remotePath 为空", home: "" };
|
||||
try {
|
||||
const cmd = "printf '__DSH_HOME__%s\\n' \\"$HOME\\"; cd " + shellQuotePath(light) + " 2>/dev/null && pwd -P";
|
||||
const r = await runRemote(subprocess, p, cmd, undefined, 64 * 1024, undefined, 15000);
|
||||
if (!r || !r.ok) {
|
||||
return { ok: false, error: String((r && (r.error || r.stderr)) || "SSH 解析失败").trim() || "SSH 解析失败", home: "" };
|
||||
}
|
||||
let home = "";
|
||||
let resolved = "";
|
||||
const lines = String(r.stdout).split("\\n");
|
||||
for (const line of lines) {
|
||||
const t = line.trim();
|
||||
if (t.startsWith("__DSH_HOME__")) home = t.slice("__DSH_HOME__".length).trim();
|
||||
else if (t.startsWith("/")) resolved = t;
|
||||
}
|
||||
if (!resolved) {
|
||||
// cd failed (missing directory / permission / shell error): identity is
|
||||
// unknown, never silently treated as a new directory.
|
||||
return { ok: false, error: "无法解析远端目录(不存在或不可访问):" + light, home: home };
|
||||
}
|
||||
return { ok: true, canonical: lightRemotePath(resolved), home: home };
|
||||
} catch (e) {
|
||||
return { ok: false, error: String(e && e.message ? e.message : e), home: "" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* First symlink under the given root whose target resolves outside it, else null.
|
||||
* The sync-down tar stream is remote-controlled: an escaping link extracted
|
||||
* into the temp tree would be followed by the copy/swap that lands the tree
|
||||
* in the mirror, writing outside it. Bounded walk (directory pops capped).
|
||||
*/
|
||||
function findEscapingLink(root) {
|
||||
const base = resolvePath(root);
|
||||
const stack = [base];
|
||||
let guard = 0;
|
||||
while (stack.length > 0 && guard++ < 20000) {
|
||||
const dir = stack.pop();
|
||||
let entries;
|
||||
try { entries = readdirSync(dir, { withFileTypes: true }); } catch (e) { continue; }
|
||||
for (const entry of entries) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isSymbolicLink()) {
|
||||
let target;
|
||||
try { target = readlinkSync(full); } catch (e) { continue; }
|
||||
const resolved = resolvePath(dir, target);
|
||||
if (resolved !== base && !resolved.startsWith(base + "/") && !resolved.startsWith(base + "\\\\")) return full;
|
||||
} else if (entry.isDirectory()) {
|
||||
stack.push(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
`
|
||||
|
||||
const RUNREMOTE_ANCHOR = 'async function runRemote(subprocess, p, remoteCmd, stdinData, maxBytes, extraOpts, timeoutMs, signal) {'
|
||||
|
||||
// Load-time self-check inserted with the helpers: the canonical-path patch
|
||||
// calls upstream internals (runRemote / shellQuotePath) from inside a
|
||||
// fail-open try/catch, so an upstream rename would otherwise degrade
|
||||
// silently to unpatched behavior. Fail loudly at module load instead.
|
||||
const SELF_CHECK = `// [workspace-groups-remote patch] Load-time self-check: if upstream renames
|
||||
// the internals the canonical-path patch relies on, fail loudly HERE rather
|
||||
// than silently degrading inside the fail-open resolution path.
|
||||
if (typeof runRemote !== 'function' || typeof shellQuotePath !== 'function') {
|
||||
throw new Error('[workspace-groups-remote] patched remote-ssh: upstream internals changed (runRemote / shellQuotePath not found) — the bundle patch needs re-checking')
|
||||
}
|
||||
|
||||
`
|
||||
|
||||
const FIND_ANCHOR = ' const existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && String(w.remotePath) === String(a.remotePath));'
|
||||
|
||||
const FIND_REPLACEMENT = ` // [workspace-groups-remote patch] Canonical-path reuse: resolve the new
|
||||
// spelling once over SSH and resolve every existing record of the same
|
||||
// connection with the same rule (light form + remote $HOME + pwd -P),
|
||||
// so relative/~, trailing-slash and symlink spellings converge on one
|
||||
// directory identity. A resolution failure is NOT "not a duplicate":
|
||||
// creation is refused with an actionable error instead of silently
|
||||
// registering a second workspace.
|
||||
const targetResolved = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
if (targetResolved.ok !== true) {
|
||||
return { ok: false, error: "无法确认远端路径是否重复:" + targetResolved.error + ";未创建新工作区" };
|
||||
}
|
||||
const sameProfile = prefsNow.workspaces.filter((w) => w && w.profileId === a.profileId && typeof w.remotePath === "string");
|
||||
let existing = undefined;
|
||||
for (const record of sameProfile) {
|
||||
const light = lightRemotePath(record.remotePath);
|
||||
// Fast path: the spelling expands to exactly the resolved target.
|
||||
if (expandRemoteHome(light, targetResolved.home) === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
// Slow path: resolve the old record with the SAME rules. This catches
|
||||
// relative paths, symlinks and historical spellings the old partial
|
||||
// expansion missed. A failure aborts instead of assuming uniqueness.
|
||||
const candidate = await resolveRemoteCanonical(subprocess, p, record.remotePath);
|
||||
if (candidate.ok !== true) {
|
||||
return { ok: false, error: "无法确认是否与已有远程工作区「" + String(record.title || record.id) + "」重复:" + candidate.error + ";未创建新工作区" };
|
||||
}
|
||||
if (candidate.canonical === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
}
|
||||
a.remotePath = existing ? String(existing.remotePath) : targetResolved.canonical;`
|
||||
|
||||
// Each entry: [label, anchor, replacement]. Anchors are exact byte strings
|
||||
// from the vendored file; every one must occur exactly once.
|
||||
const TRANSFORMS = [
|
||||
['patch 11: settings entry id falls back to the bundle row',
|
||||
'const entryId = ownEntryId(ctx, name) || NS;',
|
||||
`// [workspace-groups-remote patch] Inside the merged bundle there is no
|
||||
// loader row named dsh-remote-ssh: the settings entry lives on the
|
||||
// bundle's own row, whose composed plugin exports this plugin's Config.
|
||||
// Resolve that row before falling back to the standalone namespace.
|
||||
const entryId = ownEntryId(ctx, name) || ownEntryId(ctx, "workspace-groups-remote") || NS;`],
|
||||
|
||||
['patch 2a: sshArgv "--" before target',
|
||||
' const argv = head.concat(opts, [target]);',
|
||||
` // [workspace-groups-remote patch] "--" ends ssh option parsing: a
|
||||
// user/host value starting with "-" (e.g. -oProxyCommand=...) must never
|
||||
// be parsed as an ssh option — that would execute local commands.
|
||||
const argv = head.concat(opts, ["--", target]);`],
|
||||
['patch 2b: sshpass -e instead of -p',
|
||||
' head = ["sshpass", "-p", String(p.password)];',
|
||||
` // [workspace-groups-remote patch] sshpass -e: the password travels
|
||||
// via the SSHPASS env var (passwordEnv below is merged into the spawn
|
||||
// env by the caller), not via argv, where any local user could read
|
||||
// it from the process list. Mirrors the Windows env-based path.
|
||||
head = ["sshpass", "-e"];
|
||||
passwordEnv = { SSHPASS: String(p.password) };`],
|
||||
['patch 3a: wrapper requires the os module',
|
||||
' "const { spawn } = require(\'child_process\');",',
|
||||
` "const { spawn } = require('child_process');",
|
||||
"const os = require('os');",`],
|
||||
['patch 3a: wrapper only trusts mirror-root marker files',
|
||||
' " if (fs.existsSync(info)) {",',
|
||||
` " // [workspace-groups-remote patch] Only a registered mirror root may",
|
||||
" // trigger an automatic connection: the marker file counts solely when",
|
||||
" // the cwd IS a direct child of the mirror base — exactly where the",
|
||||
" // host itself writes it. A .remote-ssh.json planted in a cloned repo",
|
||||
" // or any other directory must never auto-connect the user's terminal.",
|
||||
" const inMirrorRoot = path.dirname(process.cwd()) === path.join(os.homedir(), '.dsh', 'remote-workspaces');",
|
||||
" if (inMirrorRoot && fs.existsSync(info)) {",`],
|
||||
['patch 3b: wrapper host key checking accept-new',
|
||||
' " const args = [\'-tt\', \'-o\', \'StrictHostKeyChecking=no\', \'-o\', \'ExitOnForwardFailure=no\'];",',
|
||||
` " // [workspace-groups-remote patch] accept-new, never 'no': a changed",
|
||||
" // host key must fail loudly instead of being silently trusted.",
|
||||
" const args = ['-tt', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'ExitOnForwardFailure=no'];",`],
|
||||
['patch 3c: wrapper "--" before target',
|
||||
' " args.push(\'-p\', String(port), \'-i\', j.keyPath, j.user + \'@\' + j.host);",',
|
||||
` " // [workspace-groups-remote patch] '--' ends option parsing, so a",
|
||||
" // user/host value starting with '-' can never become an ssh option.",
|
||||
" args.push('-p', String(port), '-i', j.keyPath, '--', j.user + '@' + j.host);",`],
|
||||
['patch 4: localToRemote folds dot segments, refuses root escape',
|
||||
` if (rel.startsWith("/")) rel = rel.slice(1);
|
||||
if (!rel) return remoteBase;
|
||||
// 拼接远程路径`,
|
||||
` if (rel.startsWith("/")) rel = rel.slice(1);
|
||||
if (!rel) return remoteBase;
|
||||
// [workspace-groups-remote patch] Fold "." / ".." segments lexically:
|
||||
// a ".." climbing above the mirror root would map the request OUTSIDE
|
||||
// the remote workspace (e.g. <mirror>/../../etc/passwd) — refuse
|
||||
// instead of silently following it.
|
||||
const foldedParts = [];
|
||||
for (const seg of rel.split("/")) {
|
||||
if (seg === "" || seg === ".") continue;
|
||||
if (seg === "..") {
|
||||
if (foldedParts.length === 0) throw new Error("remote path escapes the workspace root: " + localPath);
|
||||
foldedParts.pop();
|
||||
continue;
|
||||
}
|
||||
foldedParts.push(seg);
|
||||
}
|
||||
rel = foldedParts.join("/");
|
||||
if (!rel) return remoteBase;
|
||||
// 拼接远程路径`],
|
||||
['patch 5a: writeBack settings comment (fail-closed)',
|
||||
' // 工作区设置(按镜像目录匹配);读不到设置时按默认(推、无排除)处理',
|
||||
' // 工作区设置(按镜像目录匹配);读不到设置时不推(fail-closed —— 见下方 catch 的 PATCH 说明)'],
|
||||
['patch 5b: writeBack settings-read failure fails closed',
|
||||
` } catch (e) {}
|
||||
// ---- 护栏 B(issue #24 第二轮):推之前先看远端这一份有没有被别的写入者改过 ----`,
|
||||
` } catch (e) {
|
||||
// [workspace-groups-remote patch] Fail CLOSED: the old empty catch let
|
||||
// a settings-read failure push anyway, with the writeBack guard
|
||||
// (writeBack=false / writeBackExclude) never evaluated. Skip the push
|
||||
// and surface it through the same writeBackFailure channel as a
|
||||
// failed push: "error" throws to the caller, "log" warns, "silent"
|
||||
// stays quiet.
|
||||
const mode = writeBackFailureMode();
|
||||
if (mode !== "silent") {
|
||||
try { ctx.logger?.warn?.("[dsh-remote-ssh] 读不到工作区设置,写回护栏无法确认,本次不推送: " + String(absPath)); } catch (e2) {}
|
||||
}
|
||||
if (mode === "error") {
|
||||
throw new Error("无法读取工作区设置,写回护栏(writeBack / writeBackExclude)未能确认,本次写入未同步到远端: " + remoteFile);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ---- 护栏 B(issue #24 第二轮):推之前先看远端这一份有没有被别的写入者改过 ----`],
|
||||
['patch 6: fs imports for the link scan + atomic rename',
|
||||
'import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync } from "node:fs";',
|
||||
'import { existsSync, readFileSync, writeFileSync, readdirSync, mkdirSync, lstatSync, readlinkSync, renameSync } from "node:fs";'],
|
||||
['patch 7: freshness state written atomically',
|
||||
` writeFileSync(file, JSON.stringify(data), "utf8");
|
||||
freshnessCache = { file: file, data: data };`,
|
||||
` // [workspace-groups-remote patch] Write-then-rename: a crash mid-write
|
||||
// must not leave a torn state file behind.
|
||||
const tmpFile = file + ".tmp-" + process.pid;
|
||||
writeFileSync(tmpFile, JSON.stringify(data), "utf8");
|
||||
renameSync(tmpFile, file);
|
||||
freshnessCache = { file: file, data: data };`],
|
||||
['patch 8a: remote stat at nanosecond resolution',
|
||||
' try { r = await runner(p, "stat -c\'%s %Y\' " + shellQuotePath(remotePath), undefined, 65536, false); } catch (e) {',
|
||||
' try { r = await runner(p, "stat -c\'%s %Y %N\' " + shellQuotePath(remotePath), undefined, 65536, false); } catch (e) {'],
|
||||
['patch 8b: stamp carries the nanosecond fraction',
|
||||
` const m = /^(\\d+)\\s+(\\d+)$/.exec(out);
|
||||
if (r && r.ok && m) return { ok: true, exists: true, stamp: m[1] + ":" + m[2], err: "" };`,
|
||||
` const m = /^(\\d+)\\s+(\\d+)(?:\\s+(\\d+))?$/.exec(out);
|
||||
if (r && r.ok && m) return { ok: true, exists: true, stamp: m[1] + ":" + m[2] + (m[3] ? "." + m[3] : ""), err: "" };`],
|
||||
['patch 8c: verdict tolerates pre-upgrade second-resolution stamps',
|
||||
` if (before && before.ok && before.exists) {
|
||||
if (String(before.stamp) === prev) return { changed: false, unknown: false, why: "" };`,
|
||||
` if (before && before.ok && before.exists) {
|
||||
if (String(before.stamp) === prev) return { changed: false, unknown: false, why: "" };
|
||||
// [workspace-groups-remote patch] Stamps recorded before the nanosecond
|
||||
// upgrade carry no fraction — compare those at second precision instead
|
||||
// of reporting a phantom change on every tracked file.
|
||||
if (!prev.includes(".") && String(before.stamp).startsWith(prev + ".")) return { changed: false, unknown: false, why: "" };`],
|
||||
['patch 9: matchRemoteWorkspace folds case only on Windows',
|
||||
' const norm = (p) => String(p || "").replace(/\\\\/g, "/").replace(/\\/+$/, "").toLowerCase();',
|
||||
` // [workspace-groups-remote patch] Fold case only where the filesystem
|
||||
// is case-insensitive (Windows); on POSIX a fold can match a DIFFERENT
|
||||
// workspace whose mirror differs only by letter case.
|
||||
const foldCase = process.platform === "win32";
|
||||
const norm = (p) => { const v = String(p || "").replace(/\\\\/g, "/").replace(/\\/+$/, ""); return foldCase ? v.toLowerCase() : v; };`],
|
||||
['patch 10: findMirrorRoot trusts markers only at a real mirror root',
|
||||
' if (info && info.host && info.user && info.remotePath) return { root: dir, info: info };',
|
||||
` // [workspace-groups-remote patch] Trust a marker only at a real
|
||||
// mirror root — a directory directly under the mirror base, exactly
|
||||
// where the host writes it. The walk passes through arbitrary
|
||||
// parent directories; a marker planted there must not steer
|
||||
// write-back to an attacker's host.
|
||||
if (info && info.host && info.user && info.remotePath && dirname(dir) === join(homedir(), ".dsh", "remote-workspaces")) return { root: dir, info: info };`],
|
||||
['patch 11: sync-down refuses escaping links before the tree lands',
|
||||
` const pipe = await runTarPipe(sshH, tarH, o.timeoutMs, { label: "同步", a: "ssh", b: "tar" }, signal);
|
||||
if (!pipe.ok) {
|
||||
try { await rm(tmpDir, { recursive: true, force: true }); } catch (e) {}
|
||||
return { ok: false, error: pipe.error + "(本地镜像未改动,已丢弃本次拉取的内容)" };
|
||||
}`,
|
||||
` const pipe = await runTarPipe(sshH, tarH, o.timeoutMs, { label: "同步", a: "ssh", b: "tar" }, signal);
|
||||
if (!pipe.ok) {
|
||||
try { await rm(tmpDir, { recursive: true, force: true }); } catch (e) {}
|
||||
return { ok: false, error: pipe.error + "(本地镜像未改动,已丢弃本次拉取的内容)" };
|
||||
}
|
||||
// [workspace-groups-remote patch] The tar stream is remote-controlled:
|
||||
// refuse the sync when the extracted tree holds a symlink pointing
|
||||
// outside the extraction dir — the copy/swap below would follow it and
|
||||
// land content outside the mirror.
|
||||
const escapee = findEscapingLink(tmpDir);
|
||||
if (escapee) {
|
||||
try { await rm(tmpDir, { recursive: true, force: true }); } catch (e) {}
|
||||
return { ok: false, error: "已拒绝同步:远端内容包含指向镜像之外的符号链接(" + escapee + "),本地镜像未改动。" };
|
||||
}`],
|
||||
['patch 3d: wrapper remotePath base64-encoded',
|
||||
' " const expanded = remotePath === \'~\' ? \'$HOME\' : (remotePath.indexOf(\'~/\') === 0 ? \'$HOME/\' + remotePath.slice(2) : remotePath);",',
|
||||
` " // [workspace-groups-remote patch] The path reaches the remote",
|
||||
" // shell base64-encoded and is decoded there: its content is data,",
|
||||
" // never shell syntax, so quotes, $() and backticks in a directory",
|
||||
" // name can no longer break out. (~ still expands remotely.)",
|
||||
" const b64 = (s) => Buffer.from(String(s), 'utf8').toString('base64');",
|
||||
" const expanded = remotePath === '~' ? '$HOME' : (remotePath.indexOf('~/') === 0 ? '$HOME/$(printf %s \\\\'' + b64(remotePath.slice(2)) + '\\\\' | base64 -d)' : '$(printf %s \\\\'' + b64(remotePath) + '\\\\' | base64 -d)');",`],
|
||||
['patch 12: reusing a record keeps its existing title',
|
||||
' const lastSeg = String(a.remotePath).replace(/\\/+$/, "").split("/").pop();\n const title = a.title || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));',
|
||||
` // [workspace-groups-remote patch] Reuse keeps the user's existing
|
||||
// title; only a new record (or an explicit a.title) derives one from
|
||||
// the path. Otherwise "reuse" could silently rename a custom workspace.
|
||||
const lastSeg = String(a.remotePath).replace(/\\/+$/, "").split("/").pop();
|
||||
const title = a.title || (existing && existing.title) || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));`],
|
||||
]
|
||||
|
||||
function countOccurrences(text, needle) {
|
||||
let count = 0
|
||||
let at = text.indexOf(needle)
|
||||
while (at !== -1) { count += 1; at = text.indexOf(needle, at + needle.length) }
|
||||
return count
|
||||
}
|
||||
|
||||
function applyPatch(source) {
|
||||
if (countOccurrences(source, RUNREMOTE_ANCHOR) !== 1) {
|
||||
throw new Error('patch-remote-ssh: runRemote anchor not found exactly once — upstream changed, re-check the patch')
|
||||
}
|
||||
if (countOccurrences(source, FIND_ANCHOR) !== 1) {
|
||||
throw new Error('patch-remote-ssh: createRemoteWorkspace reuse-lookup anchor not found exactly once — upstream changed, re-check the patch')
|
||||
}
|
||||
let out = source.replace(RUNREMOTE_ANCHOR, HELPERS + SELF_CHECK + RUNREMOTE_ANCHOR)
|
||||
out = out.replace(FIND_ANCHOR, FIND_REPLACEMENT)
|
||||
for (const [label, anchor, replacement] of TRANSFORMS) {
|
||||
if (countOccurrences(out, anchor) !== 1) {
|
||||
throw new Error('patch-remote-ssh: anchor for ' + label + ' not found exactly once — upstream changed, re-check the patch')
|
||||
}
|
||||
out = out.replace(anchor, replacement)
|
||||
}
|
||||
// Post-conditions: the vulnerable code forms must be gone, the fixed
|
||||
// forms present. (A historical comment mentioning StrictHostKeyChecking=no
|
||||
// remains in the source; only the executable code form is asserted here.)
|
||||
const gone = ['head.concat(opts, [target])', '["sshpass", "-p"', "'StrictHostKeyChecking=no', '-o', 'ExitOnForwardFailure=no'", 'lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath)']
|
||||
for (const bad of gone) {
|
||||
if (out.includes(bad)) throw new Error('patch-remote-ssh: vulnerable form still present after patching: ' + bad)
|
||||
}
|
||||
const present = ['resolveRemoteCanonical', 'targetResolved.ok', '无法确认远端路径是否重复', 'existing && existing.title', 'head.concat(opts, ["--", target])', '"sshpass", "-e"', 'StrictHostKeyChecking=accept-new', 'inMirrorRoot', 'base64 -d', 'foldedParts', '写回护栏无法确认,本次不推送', 'upstream internals changed (runRemote / shellQuotePath not found)', 'findEscapingLink', 'renameSync(tmpFile, file)', "%s %Y %N", 'startsWith(prev + ".")', 'foldCase', 'dirname(dir) === join(homedir()']
|
||||
for (const good of present) {
|
||||
if (!out.includes(good)) throw new Error('patch-remote-ssh: expected patched form missing: ' + good)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function writePatchedRemoteSsh(root) {
|
||||
const sourcePath = join(root, 'vendor/dsh-remote-ssh/lib/index.js')
|
||||
const targetPath = join(root, 'lib/remote-ssh/index.js')
|
||||
const patched = applyPatch(readFileSync(sourcePath, 'utf8'))
|
||||
mkdirSync(dirname(targetPath), { recursive: true })
|
||||
writeFileSync(targetPath, patched)
|
||||
return targetPath
|
||||
}
|
||||
|
||||
const invokedDirectly = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1]
|
||||
if (invokedDirectly) {
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const target = writePatchedRemoteSsh(root)
|
||||
console.log('patch-remote-ssh: wrote ' + target)
|
||||
}
|
||||
|
|
@ -0,0 +1,402 @@
|
|||
// Behavior test for the bundle's remote-ssh canonical-path patch
|
||||
// (scripts/patch-remote-ssh.mjs), run against the BUILT artifact
|
||||
// lib/remote-ssh/index.js. Uses the same source-grab technique as the
|
||||
// vendored upstream tests: extract the patched functions from the artifact
|
||||
// and drive them with stubbed services — no SSH server needed; the stub
|
||||
// emulates the one resolution round trip (printf $HOME; cd …; pwd -P).
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { dirname } from 'node:path'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const src = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
|
||||
const vendorSrc = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')
|
||||
|
||||
let pass = 0, fail = 0
|
||||
const check = (cond, label) => { if (cond) { pass++; console.log(' ok ' + label) } else { fail++; console.log(' FAIL: ' + label) } }
|
||||
|
||||
/**
|
||||
* Index just past the closing brace that matches the `{` at openIndex.
|
||||
* String-, comment- and template-aware: braces inside '...', "...", `...`
|
||||
* (including ${ } nesting), // and block comments do not move the depth —
|
||||
* the naive counter this replaces would cut a function short the day an
|
||||
* upstream string literal gained a brace.
|
||||
*/
|
||||
function matchingBrace(text, openIndex) {
|
||||
const stack = [] // 'brace' | 'template'
|
||||
let mode = 'code'
|
||||
let depth = 0
|
||||
for (let i = openIndex; i < text.length; i++) {
|
||||
const ch = text[i]
|
||||
const next = text[i + 1]
|
||||
if (mode === 'code') {
|
||||
if (ch === '{') { depth++; stack.push('brace') } else if (ch === '}') {
|
||||
depth--
|
||||
if (stack[stack.length - 1] === 'template-expr') { stack.pop(); mode = 'template' } else stack.pop()
|
||||
if (depth === 0) return i
|
||||
} else if (ch === "'") mode = 'single'
|
||||
else if (ch === '"') mode = 'double'
|
||||
else if (ch === '`') { stack.push('template'); mode = 'template' }
|
||||
else if (ch === '/' && next === '/') { mode = 'line'; i++ }
|
||||
else if (ch === '/' && next === '*') { mode = 'block'; i++ }
|
||||
} else if (mode === 'single') {
|
||||
if (ch === '\\') i++
|
||||
else if (ch === "'") mode = 'code'
|
||||
} else if (mode === 'double') {
|
||||
if (ch === '\\') i++
|
||||
else if (ch === '"') mode = 'code'
|
||||
} else if (mode === 'template') {
|
||||
if (ch === '\\') i++
|
||||
else if (ch === '`') { stack.pop(); mode = 'code' }
|
||||
else if (ch === '$' && next === '{') { stack.push('template-expr'); depth++; mode = 'code'; i++ }
|
||||
} else if (mode === 'line') {
|
||||
if (ch === '\n') mode = 'code'
|
||||
} else if (mode === 'block') {
|
||||
if (ch === '*' && next === '/') { mode = 'code'; i++ }
|
||||
}
|
||||
}
|
||||
throw new Error('matchingBrace: unbalanced input')
|
||||
}
|
||||
|
||||
function grabFunction(name) {
|
||||
const at = src.indexOf('function ' + name)
|
||||
if (at < 0) throw new Error(name + ' not found in patched artifact')
|
||||
const start = src.lastIndexOf('\n', at) + 1 // keep a leading `async ` on the declaration line
|
||||
const open = src.indexOf('{', start)
|
||||
return src.slice(start, matchingBrace(src, open) + 1)
|
||||
}
|
||||
|
||||
function grabHandler() {
|
||||
const marker = 'createRemoteWorkspace: async'
|
||||
const start = src.indexOf(marker)
|
||||
if (start < 0) throw new Error('createRemoteWorkspace handler not found')
|
||||
const fnStart = src.indexOf('async', start)
|
||||
const open = src.indexOf('{', fnStart)
|
||||
return src.slice(fnStart, matchingBrace(src, open) + 1)
|
||||
}
|
||||
|
||||
// --- scope: real helpers from the artifact, stubbed transport -------------
|
||||
const shellQuote = new Function(grabFunction('shellQuote') + '\nreturn shellQuote;')()
|
||||
const shellQuotePath = new Function('shellQuote', grabFunction('shellQuotePath') + '\nreturn shellQuotePath;')(shellQuote)
|
||||
const lightRemotePath = new Function(grabFunction('lightRemotePath') + '\nreturn lightRemotePath;')()
|
||||
const expandRemoteHome = new Function(grabFunction('expandRemoteHome') + '\nreturn expandRemoteHome;')()
|
||||
|
||||
const HOME = '/home/u'
|
||||
const SYMLINKS = { '/home/u/link': '/srv/real' }
|
||||
let sshCalls = 0
|
||||
let sshFails = false
|
||||
function fakeRunRemote(subprocess, p, cmd) {
|
||||
sshCalls += 1
|
||||
if (sshFails) return Promise.resolve({ ok: false, error: 'stubbed failure' })
|
||||
// Emulate: printf '__DSH_HOME__%s\n' "$HOME"; cd '<path>' && pwd -P
|
||||
const m = /cd (.+) 2>\/dev\/null/.exec(cmd)
|
||||
let target = m ? m[1].trim() : ''
|
||||
if (target.startsWith('~/')) target = target.slice(2).replace(/^'(.*)'$/, '$1')
|
||||
else target = target.replace(/^'(.*)'$/, '$1')
|
||||
const absolute = (target.startsWith('/') ? target : HOME + '/' + target).replace(/\/+$/, '')
|
||||
const resolved = SYMLINKS[absolute] || absolute
|
||||
return Promise.resolve({ ok: true, stdout: '__DSH_HOME__' + HOME + '\n' + resolved + '\n' })
|
||||
}
|
||||
const resolveRemoteCanonical = new Function('shellQuotePath', 'runRemote', 'lightRemotePath', 'expandRemoteHome',
|
||||
grabFunction('resolveRemoteCanonical') + '\nreturn resolveRemoteCanonical;')(shellQuotePath, fakeRunRemote, lightRemotePath, expandRemoteHome)
|
||||
|
||||
// --- pure helpers ----------------------------------------------------------
|
||||
console.log('helpers')
|
||||
check(lightRemotePath('/home/u/proj/') === '/home/u/proj', 'light: trailing slash dropped')
|
||||
check(lightRemotePath(' ~/proj ') === '~/proj', 'light: trimmed')
|
||||
check(lightRemotePath('/') === '/', 'light: root kept')
|
||||
check(expandRemoteHome('~/proj', HOME) === '/home/u/proj', 'expand: ~/ with home')
|
||||
check(expandRemoteHome('/abs', HOME) === '/abs', 'expand: absolute untouched')
|
||||
check(expandRemoteHome('~/proj', '') === '~/proj', 'expand: no home, untouched')
|
||||
|
||||
console.log('resolveRemoteCanonical')
|
||||
{
|
||||
const r = await resolveRemoteCanonical({}, {}, '~/proj/')
|
||||
check(r.ok === true && r.canonical === '/home/u/proj' && r.home === HOME, 'resolves ~/proj/ to the absolute canonical path')
|
||||
sshFails = true
|
||||
const f = await resolveRemoteCanonical({}, {}, '~/proj')
|
||||
check(f.ok === false && /stubbed failure/.test(f.error), 'SSH failure is fail-closed (no canonical fallback)')
|
||||
sshFails = false
|
||||
}
|
||||
|
||||
// --- the patched handler ----------------------------------------------------
|
||||
function fakeSettings(seed) {
|
||||
const state = { workspaces: seed.map(w => ({ ...w })) }
|
||||
return {
|
||||
state,
|
||||
face: {
|
||||
read: () => ({ workspaces: state.workspaces.map(w => ({ ...w })), defaultSyncPaths: [], defaultSyncExclude: [], defaultSyncMaxBytes: 0 }),
|
||||
updateWorkspaces: async (list) => { state.workspaces = list },
|
||||
},
|
||||
}
|
||||
}
|
||||
function makeHandler(face) {
|
||||
const deps = {
|
||||
getProfile: (id) => id === 'prof-1' ? { id: 'prof-1', name: 'lab', host: 'h', user: 'u', port: 22, keyPath: '', proxyJump: '' } : undefined,
|
||||
settingsFace: face,
|
||||
subprocess: {},
|
||||
lightRemotePath,
|
||||
expandRemoteHome,
|
||||
resolveRemoteCanonical,
|
||||
join,
|
||||
mkdir: async () => {},
|
||||
writeFile: async () => {},
|
||||
mirrorBaseDir: () => '/mirrors',
|
||||
remoteWorkspaceReadme: () => 'readme',
|
||||
workspaceRegistry: { create: async (path, title) => ({ id: 'native:' + path, title, setTitle: async () => {} }) },
|
||||
normalizeSyncList: (v) => Array.isArray(v) ? v : [],
|
||||
parseSyncMaxBytes: () => null,
|
||||
}
|
||||
const names = Object.keys(deps)
|
||||
const factory = new Function(...names, 'return (' + grabHandler() + ')')
|
||||
return factory(...names.map(n => deps[n]))
|
||||
}
|
||||
const seedRecord = { id: 'wOLD', profileId: 'prof-1', title: 'proj', remotePath: '~/proj', mirrorPath: '/mirrors/wOLD', syncPaths: [], syncExclude: [] }
|
||||
|
||||
console.log('createRemoteWorkspace (patched)')
|
||||
{
|
||||
const { face, state } = fakeSettings([seedRecord])
|
||||
const handler = makeHandler(face)
|
||||
sshCalls = 0
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj' })
|
||||
check(r.ok === true && r.reused === true, 'A: absolute spelling reuses the ~-spelled record')
|
||||
check(state.workspaces.length === 1 && state.workspaces[0].id === 'wOLD', 'A: still exactly one record')
|
||||
check(r.mirrorPath === '/mirrors/wOLD', 'A: original mirror kept (local edits preserved)')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, remotePath: '/home/u/proj' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '~/proj/' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'B: ~-spelling with trailing slash reuses the absolute record')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '~/newdir' })
|
||||
check(r.ok === true && r.reused === false, 'C: genuinely new directory creates a record')
|
||||
check(state.workspaces.length === 1 && state.workspaces[0].remotePath === '/home/u/newdir', 'C: new record stores the canonical spelling')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([seedRecord])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj/' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'E: trailing-slash variant reuses')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, remotePath: 'proj' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '~/proj/' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'H: relative record spelling resolves to the same directory')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, remotePath: '/home/u/link' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/srv/real' })
|
||||
check(r.ok === true && r.reused === true && state.workspaces.length === 1, 'I: symlink and pwd -P form count as one directory')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([{ ...seedRecord, profileId: 'prof-2' }])
|
||||
const handler = makeHandler(face)
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj' })
|
||||
check(r.ok === true && r.reused === false && state.workspaces.length === 2, 'J: same path on another connection is not merged')
|
||||
}
|
||||
{
|
||||
const { face, state } = fakeSettings([seedRecord])
|
||||
const handler = makeHandler(face)
|
||||
sshFails = true
|
||||
const r = await handler({ profileId: 'prof-1', remotePath: '/home/u/proj' })
|
||||
sshFails = false
|
||||
check(r.ok === false && /无法确认远端路径是否重复/.test(String(r.error)), 'D: SSH down refuses creation instead of silently duplicating')
|
||||
check(state.workspaces.length === 1, 'D: no second record is written when identity cannot be confirmed')
|
||||
}
|
||||
|
||||
|
||||
// --- sshArgv hardening (patch 2) -------------------------------------------
|
||||
const sshArgv = new Function('sshExecutablePath', 'expandSshPath', 'ensureWindowsAskpass',
|
||||
grabFunction('sshArgv') + '\nreturn sshArgv;')(() => 'ssh', (x) => x, () => ({ ascii: true, file: 'C:/tmp/askpass.cmd' }))
|
||||
|
||||
console.log('sshArgv (patched)')
|
||||
{
|
||||
const evil = { user: '-oProxyCommand=touch /tmp/pwn', host: 'example.com', port: 22, authMethod: 'key', keyPath: '/k' }
|
||||
const { argv } = sshArgv(evil, undefined, false)
|
||||
const target = '-oProxyCommand=touch /tmp/pwn@example.com'
|
||||
check(argv[argv.indexOf(target) - 1] === '--', 'F: option-like user value stays positional behind --')
|
||||
}
|
||||
{
|
||||
const { argv } = sshArgv({ user: 'u', host: 'h', port: 22, authMethod: 'key', keyPath: '/k' }, 'echo hi', false)
|
||||
check(argv[argv.indexOf('u@h') - 1] === '--' && argv[argv.length - 1] === 'echo hi', 'F2: normal profile: -- before target, command after')
|
||||
}
|
||||
{
|
||||
const { argv, env } = sshArgv({ user: 'u', host: 'h', port: 22, authMethod: 'password', password: 's3cret-value' }, undefined, false)
|
||||
if (process.platform === 'win32') {
|
||||
check(!argv.includes('sshpass'), 'G: Windows password auth does not use sshpass')
|
||||
check(env !== undefined && env.SSH_ASKPASS === 'C:/tmp/askpass.cmd' && env.RSSH_ASKPASS_PW === 's3cret-value', 'G: Windows password travels via SSH_ASKPASS env')
|
||||
} else {
|
||||
check(argv[0] === 'sshpass' && argv[1] === '-e', 'G: POSIX password auth uses sshpass -e')
|
||||
check(env !== undefined && env.SSHPASS === 's3cret-value', 'G: password travels via the SSHPASS env var')
|
||||
}
|
||||
check(!argv.some(a => String(a).includes('s3cret-value')), 'G: password is not in argv')
|
||||
}
|
||||
|
||||
// --- terminal wrapper (patch 3) ----------------------------------------------
|
||||
function extractWrapperSource() {
|
||||
const lines = src.split('\n')
|
||||
const start = lines.findIndex(l => l.includes('const wrapperJs = ['))
|
||||
if (start < 0) throw new Error('wrapperJs not found in patched artifact')
|
||||
let end = start + 1
|
||||
while (end < lines.length && !lines[end].trim().startsWith('].join')) end += 1
|
||||
const arrayText = lines.slice(start, end + 1).join('\n').replace(/^\s*const wrapperJs = /, '').replace(/\]\.join\([\s\S]*$/, ']')
|
||||
return new Function('return (' + arrayText + ')')().join('\n')
|
||||
}
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
console.log('terminal wrapper (patched): skipped on win32 (POSIX /bin/sh fixtures)')
|
||||
} else {
|
||||
console.log('terminal wrapper (patched)')
|
||||
{
|
||||
const sandbox = mkdtempSync(join(tmpdir(), 'wg-remote-wrapper-'))
|
||||
const fakeHome = join(sandbox, 'home')
|
||||
const binDir = join(sandbox, 'bin')
|
||||
mkdirSync(join(fakeHome, '.dsh', 'remote-workspaces', 'wTEST'), { recursive: true })
|
||||
mkdirSync(binDir, { recursive: true })
|
||||
const sshCapture = join(sandbox, 'ssh-argv.txt')
|
||||
const shellCapture = join(sandbox, 'shell.txt')
|
||||
writeFileSync(join(binDir, 'ssh'), '#!/bin/sh\n: > "$SSH_CAPTURE"\nfor a in "$@"; do printf \'%s\\n\' "$a" >> "$SSH_CAPTURE"; done\nexit 0\n')
|
||||
writeFileSync(join(binDir, 'fakeshell'), '#!/bin/sh\necho local-shell >> "$SHELL_CAPTURE"\npwd\nexit 0\n')
|
||||
chmodSync(join(binDir, 'ssh'), 0o755)
|
||||
chmodSync(join(binDir, 'fakeshell'), 0o755)
|
||||
const wrapperPath = join(sandbox, 'dsh-remote-shell.js')
|
||||
writeFileSync(wrapperPath, extractWrapperSource())
|
||||
const baseEnv = { ...process.env, HOME: fakeHome, PATH: binDir + ':' + process.env.PATH, SHELL: join(binDir, 'fakeshell'), SSH_CAPTURE: sshCapture, SHELL_CAPTURE: shellCapture }
|
||||
const runWrapper = (cwd) => spawnSync('node', [wrapperPath], { cwd, env: baseEnv, encoding: 'utf8' })
|
||||
const marker = (fields) => JSON.stringify({ keyPath: '/keys/id_rsa', host: 'lab.example', user: 'u', port: 22, ...fields })
|
||||
|
||||
// A marker planted OUTSIDE the mirror base must not connect at all.
|
||||
const evilDir = join(sandbox, 'cloned-repo')
|
||||
mkdirSync(evilDir, { recursive: true })
|
||||
writeFileSync(join(evilDir, '.remote-ssh.json'), marker({ remotePath: '/srv/x' }))
|
||||
runWrapper(evilDir)
|
||||
check(!existsSync(sshCapture), 'W1: marker in a random directory does not trigger ssh')
|
||||
check(existsSync(shellCapture), 'W1: terminal falls back to the local shell')
|
||||
|
||||
// A marker in a real mirror root connects, hardened.
|
||||
const mirrorDir = join(fakeHome, '.dsh', 'remote-workspaces', 'wTEST')
|
||||
writeFileSync(join(mirrorDir, '.remote-ssh.json'), marker({ remotePath: '/srv/proj' }))
|
||||
runWrapper(mirrorDir)
|
||||
const wArgv = readFileSync(sshCapture, 'utf8').split('\n')
|
||||
check(wArgv.includes('StrictHostKeyChecking=accept-new') && !wArgv.includes('StrictHostKeyChecking=no'), 'W2: host key checking is accept-new, never no')
|
||||
check(wArgv[wArgv.indexOf('u@lab.example') - 1] === '--', 'W2: -- before the target')
|
||||
|
||||
// A command-injection payload in remotePath stays inert data.
|
||||
const pwn = join(sandbox, 'pwned')
|
||||
writeFileSync(join(mirrorDir, '.remote-ssh.json'), marker({ remotePath: '/tmp/$(touch ' + pwn + ')' }))
|
||||
runWrapper(mirrorDir)
|
||||
const remoteCmd = readFileSync(sshCapture, 'utf8').split('\n').filter(Boolean).pop()
|
||||
spawnSync('bash', ['-c', remoteCmd], { env: { ...baseEnv, SHELL: join(binDir, 'fakeshell') }, encoding: 'utf8' })
|
||||
check(!existsSync(pwn), 'W3: $() payload in remotePath is not executed by the remote shell')
|
||||
|
||||
// A legitimate path with spaces, a quote and a $() round-trips exactly.
|
||||
const weird = join(fakeHome, 'my proj $(x) "q"')
|
||||
mkdirSync(weird, { recursive: true })
|
||||
writeFileSync(join(mirrorDir, '.remote-ssh.json'), marker({ remotePath: weird }))
|
||||
runWrapper(mirrorDir)
|
||||
const remoteCmd2 = readFileSync(sshCapture, 'utf8').split('\n').filter(Boolean).pop()
|
||||
const out = spawnSync('bash', ['-c', remoteCmd2], { env: { ...baseEnv, SHELL: join(binDir, 'fakeshell') }, encoding: 'utf8' })
|
||||
check(out.stdout.trim().endsWith(weird), 'W4: weird-but-legit path lands in the right directory')
|
||||
}
|
||||
}
|
||||
|
||||
console.log('localToRemote dot-segment folding')
|
||||
{
|
||||
const localToRemote = new Function(grabFunction('localToRemote') + '\nreturn localToRemote;')()
|
||||
check(localToRemote('/mirror/root/sub/file.txt', '/mirror/root', '/srv/proj') === '/srv/proj/sub/file.txt',
|
||||
'L1: plain subpath maps under the remote root')
|
||||
check(localToRemote('/mirror/root', '/mirror/root', '/srv/proj') === '/srv/proj',
|
||||
'L2: the mirror root maps to the remote root')
|
||||
check(localToRemote('/mirror/root/a/../b.txt', '/mirror/root', '/srv/proj') === '/srv/proj/b.txt',
|
||||
'L3: an in-tree ".." folds without escaping')
|
||||
check(localToRemote('/mirror/root/a/./b.txt', '/mirror/root', '/srv/proj') === '/srv/proj/a/b.txt',
|
||||
'L4: "." segments fold away')
|
||||
let threw = false
|
||||
try { localToRemote('/mirror/root/../../etc/passwd', '/mirror/root', '/srv/proj') } catch { threw = true }
|
||||
check(threw, 'L5: a ".." climbing above the mirror root is refused')
|
||||
threw = false
|
||||
try { localToRemote('/mirror/root/a/../../../etc/passwd', '/mirror/root', '/srv/proj') } catch { threw = true }
|
||||
check(threw, 'L6: a buried escape attempt is refused')
|
||||
}
|
||||
|
||||
console.log('freshness: nanosecond stamps + legacy tolerance + escaping links')
|
||||
{
|
||||
const verdict = new Function(grabFunction('freshnessVerdict') + '\nreturn freshnessVerdict;')()
|
||||
check(verdict('10:100', { ok: true, exists: true, stamp: '10:100.123456789' }).changed === false,
|
||||
'F1: a pre-upgrade second-resolution stamp still matches at second precision')
|
||||
check(verdict('10:100', { ok: true, exists: true, stamp: '10:101.000000000' }).changed === true,
|
||||
'F2: a genuinely different second still reads as changed')
|
||||
check(verdict('10:100.5', { ok: true, exists: true, stamp: '10:100.500000000' }).changed === true,
|
||||
'F3: a fractional recorded stamp compares exactly (no false tolerance)')
|
||||
|
||||
const syncErrText = new Function(grabFunction('syncErrText') + '\nreturn syncErrText;')()
|
||||
const remoteMtimeInfo = new Function('shellQuotePath', 'syncErrText',
|
||||
grabFunction('remoteMtimeInfo') + '\nreturn remoteMtimeInfo;')(shellQuotePath, syncErrText)
|
||||
const runnerNs = async () => ({ ok: true, stdout: '10 100 123456789\n', stderr: '', error: '' })
|
||||
const infoNs = await remoteMtimeInfo(runnerNs, {}, '/srv/f')
|
||||
check(infoNs.ok && infoNs.stamp === '10:100.123456789', 'F4: remote stat carries nanoseconds into the stamp')
|
||||
let statCmd = ''
|
||||
const runnerCap = async (p, cmd) => { statCmd = cmd; return { ok: true, stdout: '1 2 3\n', stderr: '', error: '' } }
|
||||
await remoteMtimeInfo(runnerCap, {}, '/srv/f')
|
||||
check(statCmd.includes("%s %Y %N"), 'F5: the stat command asks for the nanosecond field')
|
||||
|
||||
const findEscapingLink = new Function('resolvePath', 'readdirSync', 'readlinkSync', 'join',
|
||||
grabFunction('findEscapingLink') + '\nreturn findEscapingLink;')(
|
||||
(await import('node:path')).resolve,
|
||||
(await import('node:fs')).readdirSync,
|
||||
(await import('node:fs')).readlinkSync,
|
||||
(await import('node:path')).join)
|
||||
const tree = mkdtempSync(join(tmpdir(), 'wg-links-'))
|
||||
try {
|
||||
mkdirSync(join(tree, 'sub'), { recursive: true })
|
||||
writeFileSync(join(tree, 'sub', 'f.txt'), 'x')
|
||||
let linksAvailable = true
|
||||
try {
|
||||
symlinkSync(join(tree, 'sub', 'f.txt'), join(tree, 'inner-link'))
|
||||
} catch (error) {
|
||||
if (error?.code !== 'EPERM') throw error
|
||||
linksAvailable = false
|
||||
console.log(' skip F6/F7: symlink creation not permitted in this environment')
|
||||
}
|
||||
if (linksAvailable) {
|
||||
check(findEscapingLink(tree) === null, 'F6: an in-tree symlink is fine')
|
||||
symlinkSync('/etc', join(tree, 'sub', 'escape-link'))
|
||||
check(String(findEscapingLink(tree)).endsWith('escape-link'), 'F7: a symlink escaping the tree is found')
|
||||
}
|
||||
} finally {
|
||||
rmSync(tree, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
console.log('patch hygiene')
|
||||
check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)')
|
||||
check(src.includes('resolveRemoteCanonical'), 'built artifact carries the patch')
|
||||
|
||||
// --- client transform: settings face replacement ---------------------------
|
||||
// scripts/build-remote-ssh-client.mjs replaces the vendored settings face
|
||||
// with the maintainable source component and exports the factory with the
|
||||
// merged entry's compose seam. Assert the generated source rather than only
|
||||
// the built bundle, so an upstream anchor drift is caught here too.
|
||||
console.log('client factory transform (settings face)')
|
||||
{
|
||||
const generated = readFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), 'utf8')
|
||||
check(generated.includes('export default (require, compose) => {'), 'generated factory accepts the compose seam')
|
||||
check(generated.includes('compose.createSettingsSection({ api: api })'), 'settings registration builds the source component')
|
||||
check(generated.includes('settingsComponent = SettingsSection;'), 'vendored settings face stays as the fallback')
|
||||
check(!generated.includes('}, SettingsSection);'), 'upstream registration is gone from the generated factory')
|
||||
check(generated.includes('locale: settingsLocale'), 'settings entry declares the compose-provided namespace')
|
||||
const vendoredClient = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/client.js'), 'utf8')
|
||||
check(!vendoredClient.includes('compose.createSettingsSection'), 'vendored client stays pristine')
|
||||
}
|
||||
|
||||
console.log('\n' + pass + ' passed, ' + fail + ' failed')
|
||||
process.exit(fail === 0 ? 0 : 1)
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
{
|
||||
"algorithm": "sha256",
|
||||
"files": {
|
||||
".gitattributes": "0ceb307415416b037b12bde72ed20da5a06cad855e4e0d2f5eeb26b6f63b34a0",
|
||||
".github/workflows/tests.yml": "b5032e00f1a2975652a61f3c3483bdbb768cb4deebad89507f3fcc7d389dc307",
|
||||
".github/workflows/upstream-drift.yml": "e40844ef32067ebf0a7201de725808b9c52fef90522c940e45e5cf08cbf4513e",
|
||||
".gitignore": "94a031b77723976c776f08a27f1612b96f7d8adc5355938231eb0d84efd1b213",
|
||||
"CHANGELOG.md": "ee480c10bdd289c722ea65c71cf24ffcab03ae859d44828ada39c994dbcb98bb",
|
||||
"LICENSE": "f0de3a316a701d1d09ce801adb17bf73dea3bce7c994fd1bb056f8d4eefb3684",
|
||||
"MAINTENANCE.md": "731b8143b25372ece19793809f65a0c5d97b9ad2b081317d90565608a85935da",
|
||||
"README.md": "5e248328dc0c5350e81992dd5e6dbfdb9f4167ed35c2d2a6a6b56d5d50aa39d3",
|
||||
"README_EN.md": "e0ca42e3dda2b42b5f1f4467a575bb10c2cd992b45e3759291174e14272fe063",
|
||||
"assets/remote-files-tab.webp": "28c9a7ed8365298362d7b36ddcabf0c0eee15fb15d0cfed8a090433b827d28ea",
|
||||
"assets/remote-terminal.webp": "8a2018761c6d48e8572adfb8b5744a23943bcb16f9cbf49e02dec6347e7b8e66",
|
||||
"assets/settings-remote-connections.png": "254440d0dbfb477eb2790f8204e4ae55930854c2c6b000f9991c6938d0cadee2",
|
||||
"cordis.patch.yml": "63e679202250d612a97d1f4d64cb9350ffbf77a9892d90b2edf4711e6ccf8145",
|
||||
"lib/client.js": "d6efeb58be3725f4006964c718729a0e3c0eff730bf1945bad22986178ee69b9",
|
||||
"lib/index.js": "3e810063af728efe463b0c60c52c42f78999bb64652b7a00bc2afaa26a510ce7",
|
||||
"package.json": "0aaac33400508c49df667eb0ff98e82e0dc59cd6baa7afceeb599b9efd148e41",
|
||||
"screenshots.json": "2b1f360217e98c8bea5cdc820a37085237d253ab0eaa53874556c1d617b9bde1",
|
||||
"scripts/verify-remote-history-script.mjs": "366b148b497612b7bf941519bc85efa3ae93fe0fb949dd0c2c2fa2d050ac888b",
|
||||
"scripts/verify-remote-hup-group.mjs": "94df2b559a71e47cfe0142e7eda465bf6ab59484d523b58de896081e2dcd7f67",
|
||||
"scripts/verify-remote-status-script.mjs": "1fa3fc14fb27243c86e5436a87d1951e980b7b11d5a3d58dcb981b2fc1be80c3",
|
||||
"scripts/verify-remote-write-route.mjs": "3e41790ab599fcd9824c300c424223b54b577c2d0b792b8a7f88807b93159818",
|
||||
"tests/askpass-ascii.test.mjs": "55c34146a6e9f70e1eb26696175974918bb480d5f041c04b9c250feb2eb227ce",
|
||||
"tests/auth-error-diagnostics.test.mjs": "8d9c96b2126bd30be89ee2e457546527a80a145adeff52dc9772ad29b0b016ec",
|
||||
"tests/cancel.test.mjs": "d3cdd12f231f7c4c56f584bcee39e57fc97b87a5781e9fd8168951b5e761ae7d",
|
||||
"tests/client-optional-deps.test.mjs": "fae0606f8563b94101557f5dbff598933edff265920c5303dd2357dc122f1485",
|
||||
"tests/dir-picker-newdir.test.mjs": "59005410b0ff6b9c7376775a44952de8b6ccce670fe922d55f54ffc418fbf830",
|
||||
"tests/file-references-truncation.test.mjs": "0a614118341cbb1a9b8ae8b172540528a26cda18390d3c642cc0cb4116f991d2",
|
||||
"tests/file-references.test.mjs": "b288b1c47b7f0bb89aab05d2be3beb7fc608206aea930a7f0a90a9979e09e222",
|
||||
"tests/fs-read-bridge.test.mjs": "d9459099913442b5a0ef67dd09b9c8a62b74ae9a295e238b326fe29275661f72",
|
||||
"tests/fs-read-page.test.mjs": "3a4887b0d5b4e89eed0b98edb76371826ae9b57938ea45ef334038fe4ba07599",
|
||||
"tests/fs-search-contract.test.mjs": "250560221180b6eb11ae6aeddb03325a8f51ef2c712063fced4eff669a271937",
|
||||
"tests/fs-trees-contract.test.mjs": "54ffc9e396b2279b85b4a9c339ede229580c105963af34c095e0472dba2c9c56",
|
||||
"tests/fs-write-bridge.test.mjs": "668dc23297a163441c9b0ad1a64614ce33334cdca461e36ff4ec59f9ef5c56d0",
|
||||
"tests/manifest-compat.test.mjs": "440771136e501dcac48ec26be35b761fc08ab42f4bf5bae3be220d63ba1f45b8",
|
||||
"tests/module-load.test.mjs": "180bc1e366ed6cd0ac2e8b3e7959a631aa7e986c645996c78d658c3e2e72621c",
|
||||
"tests/open-external-contract.test.mjs": "f7ef27960a761b95991a9d5ac36f128d8657d3bfe4183f79a0341d84de9c74cd",
|
||||
"tests/password-auth.test.mjs": "1d923750cbf712402d481e87f764c075b0a9873282061ea3431e3b1e08477da8",
|
||||
"tests/perf-remote-open-2433.test.mjs": "4a469f654fe20c772fc662727a68f1ac2869d844622e40df3621dafcba9e2e22",
|
||||
"tests/remote-hup.test.mjs": "8cd1c10b8acbd516ab844e864e94b74ef4e435f9d592bc96c7cbf93dc6452b8e",
|
||||
"tests/remote-search.test.mjs": "8c9eaaf4cbce161cbc5a31a62db53f594d0be8b00105bbad3463cb9ea0ab32fe",
|
||||
"tests/remote-workspace-root.test.mjs": "1d4e08d38b1e20d72c5a1b2082895578f44f77cc5d07ea2a232f44e910e1e84f",
|
||||
"tests/request-path-ownership.test.mjs": "b1762a81c00ca0df7f6123e26e3ba19e77519e1bf4ace88de071f39fc1a260b2",
|
||||
"tests/run-all.mjs": "01b7d516a629f766a639aa84a342328157c4fd1c50dd8336e6ce69af22715648",
|
||||
"tests/session-path.test.mjs": "7a23fc0ea82f2731c8d162f631589f2de0c5abf21f1541b6e781b5b9ab7496b4",
|
||||
"tests/settings-api-mode.test.mjs": "884dc8896273f5b88c8471eb2a61d0f2183daf59f2e66766276716f2888a446a",
|
||||
"tests/settings-compat.test.mjs": "9ead66e4cf2651152139b1727cf381d1c1ba6feca7d4a481a3a5658cbebfcc8d",
|
||||
"tests/settings-sync-scope-ui.test.mjs": "64764509bb4465c67ddf44304d8a9b4195fb9810b79c29d4b8bfeb6e86e6e544",
|
||||
"tests/settings-ui-reachability.test.mjs": "7e451f5a82cc7ff022560ab4423ffdfd883e3bf624939f7991c7275efbc1cf13",
|
||||
"tests/sidebar-0250-endpoints.test.mjs": "05f2f4dcb20625b8cc81c0c34b2bae89c568af61a79529517e9779c59cb891c4",
|
||||
"tests/sidebar-0280-git-graph.test.mjs": "2a4350fbb452e45ef68ef87cef794d0049df40b4eef56a174684a94b472dc9bf",
|
||||
"tests/sidebar-0280-git-status.test.mjs": "0ea11a382217c35cf1604274316f548114797f16d7f2a70a57ef843a8ac08826",
|
||||
"tests/sidebar-0282-history.test.mjs": "4f5cee8a51a7156455a92db35b008087ea3ad304d3464e9550b67ae188977d1f",
|
||||
"tests/sidebar-write-route.test.mjs": "26692937e5e80e2267c20bc01e72b2885b385fc9233f2a0576eccf8f7e033887",
|
||||
"tests/sync-safety.test.mjs": "b7b23cb6344e45d3f64349392dfd72b7f52f6b3c87ec1cd0a3386b9f72c09ad2",
|
||||
"tests/terminal-integration.test.mjs": "576887fab51c5d86875bab493fe945c5ecf71ef63ccd8d33169e0beb74526c5b",
|
||||
"tests/timeout.test.mjs": "e4408ee33d30d7c8020efb1f385c21347cd70026035d2bda49bc628720f75189",
|
||||
"tests/tool-output-schema.test.mjs": "c0b555dab324bed9340430864df34fbac229083762e543d108ce93d8292dcded",
|
||||
"tests/tree-root-label.test.mjs": "dcaee622c52750922f1048be6fbd6038ddb67abf9236ce3a937da5bb05059159",
|
||||
"tests/trust-fence.test.mjs": "bb3b8e02d28e28e123d767c4d8dbffcaec9cc6fde31ae56940deef06d679bf7c",
|
||||
"tests/unicode-names.test.mjs": "959182c9ef7e1cb3e65cf7ac2161f915ecfff2d818e91feacb8d1cdc349bbcfe",
|
||||
"tests/workspace-delete-sync.test.mjs": "2aa94e468a56407e119969e8eaf42ff944fe4268da4778b34f91651a6d138d24",
|
||||
"tests/workspace-globe-rowkey.test.mjs": "89affb1f78c16ec4bc6c57569fb3fef561798249110bd1194e83183d4387f4d9",
|
||||
"tests/workspace-globe.test.mjs": "f34a82a86592f2eb1583c7299db7f2e47fba07e6e386088df7e765419036a2c2",
|
||||
"tests/workspace-shell-id.test.mjs": "bef01077c65dd8d79585df09f5c85902b26fdce78196f6cda5b408569de45a91",
|
||||
"tests/wrapper-terminal.test.mjs": "5b1c87f774f2c61c30ce3469484da34df6deb28f179b8b5e3605e3bc38ca764e"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
// Vendor integrity manifest: sha256 of every file under
|
||||
// vendor/dsh-remote-ssh/, recorded in scripts/vendor-manifest.json.
|
||||
// The vendor tree is supposed to be byte-identical to the upstream release;
|
||||
// the merge layer's build-time patch is the ONLY sanctioned deviation, and
|
||||
// it never writes into vendor/. verify-bundle recomputes the manifest and
|
||||
// fails on any drift (edited, added or missing files), so an accidental
|
||||
// vendor edit or a botched upstream refresh cannot slip through silently.
|
||||
// Regenerate after an intentional upstream update: npm run vendor:manifest
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, join, relative, sep } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const MANIFEST_PATH = 'scripts/vendor-manifest.json'
|
||||
const VENDOR_DIR = 'vendor/dsh-remote-ssh'
|
||||
|
||||
/** sha256 of every vendored file, keyed by POSIX-style relative path. */
|
||||
export function computeVendorManifest(root) {
|
||||
const base = join(root, VENDOR_DIR)
|
||||
const files = {}
|
||||
const walk = (dir) => {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === 'node_modules') continue // local test scaffolding, never vendored content
|
||||
const path = join(dir, entry.name)
|
||||
if (entry.isDirectory()) { walk(path); continue }
|
||||
if (!entry.isFile()) continue
|
||||
const rel = relative(base, path).split(sep).join('/')
|
||||
files[rel] = createHash('sha256').update(readFileSync(path)).digest('hex')
|
||||
}
|
||||
}
|
||||
walk(base)
|
||||
return files
|
||||
}
|
||||
|
||||
/** Compare the on-disk vendor tree with the recorded manifest. Returns a list of problems ([] = clean). */
|
||||
export function checkVendorManifest(root) {
|
||||
let recorded
|
||||
try {
|
||||
recorded = JSON.parse(readFileSync(join(root, MANIFEST_PATH), 'utf8')).files
|
||||
} catch {
|
||||
return ['vendor manifest missing or unreadable: ' + MANIFEST_PATH]
|
||||
}
|
||||
const current = computeVendorManifest(root)
|
||||
const problems = []
|
||||
for (const [rel, hash] of Object.entries(current)) {
|
||||
if (!(rel in recorded)) problems.push('unrecorded vendor file: ' + rel)
|
||||
else if (recorded[rel] !== hash) problems.push('vendor file changed: ' + rel)
|
||||
}
|
||||
for (const rel of Object.keys(recorded)) {
|
||||
if (!(rel in current)) problems.push('vendor file missing: ' + rel)
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
const invokedDirectly = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1]
|
||||
if (invokedDirectly) {
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
if (process.argv.includes('--write')) {
|
||||
const files = computeVendorManifest(root)
|
||||
writeFileSync(join(root, MANIFEST_PATH), JSON.stringify({ algorithm: 'sha256', files }, null, 2) + '\n')
|
||||
console.log('vendor manifest written: ' + Object.keys(files).length + ' files')
|
||||
} else {
|
||||
const problems = checkVendorManifest(root)
|
||||
if (problems.length > 0) { console.error(problems.join('\n')); process.exit(1) }
|
||||
console.log('vendor manifest OK')
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
// Merged-bundle composition checks (run after `npm install` + `npm run build`).
|
||||
// Verifies the assembled artifacts, not a live DSH host:
|
||||
// 1. lib/index.js loads and exports the bundle identity + inject union.
|
||||
// 2. Its apply() composes exactly the two original plugins, under their
|
||||
// original names, with the remote-ssh Config schema attached.
|
||||
// 3. lib/client.js registers exactly one module-loader row, keyed by this
|
||||
// package's name, and contains code from both client halves.
|
||||
// 4. cordis.patch.yml carries the single insert row plus remote-ssh's two
|
||||
// shell overrides (better-sidebar / terminal-controller).
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { dirname, join } from 'node:path'
|
||||
import vm from 'node:vm'
|
||||
import { checkVendorManifest } from './vendor-manifest.mjs'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
|
||||
let failures = 0
|
||||
const check = (label, ok) => { console.log(`${ok ? '✓' : '✗ FAIL'} ${label}`); if (!ok) failures++ }
|
||||
|
||||
const host = await import(pathToFileURL(join(root, 'lib/index.js')).href)
|
||||
check('host name is the package name', host.name === pkg.name)
|
||||
check('host exports the remote-ssh Config at top level (owns the settings entry)', !!host.Config)
|
||||
check('host inject is the union', JSON.stringify(host.inject) === JSON.stringify(['webServer', 'subprocess', 'tools', 'workspaceRegistry']))
|
||||
const applied = []
|
||||
host.apply({ plugin: (plugin, config) => applied.push({ plugin, config }) }, {})
|
||||
check('apply composes exactly two plugins', applied.length === 2)
|
||||
check('groups half keeps its name/inject', applied[0]?.plugin.name === 'workspace-groups-local' && JSON.stringify(applied[0]?.plugin.inject) === '["webServer"]')
|
||||
// 1.0.3: the child must NOT declare Config — with the same Config on both the
|
||||
// composed plugin and the child, the child's fiber silently never applies on
|
||||
// DSH 0.2.2-rc.2 (remote half dead). The settings entry is owned by the
|
||||
// composed plugin's top-level Config export instead (checked in the repo
|
||||
// source test below via lib/index.js re-export).
|
||||
check('remote-ssh half keeps its name/inject and declares NO Config', applied[1]?.plugin.name === '@zhangfengshun/dsh-remote-ssh' && !('Config' in (applied[1]?.plugin ?? {})))
|
||||
check('remote-ssh receives the nested row config', JSON.stringify(applied[1]?.config) === '{}')
|
||||
|
||||
const client = readFileSync(join(root, 'lib/client.js'), 'utf8')
|
||||
check('client has exactly one module-loader registration', client.split('__ModuleLoader__').length - 1 === 1)
|
||||
check('client row id is the package name', client.includes(`id: "${pkg.name}"`) || client.includes(`id:"${pkg.name}"`) || client.includes(`id: '${pkg.name}'`))
|
||||
check('client contains the groups half', client.includes('workspaceGroups'))
|
||||
check('client contains the remote-ssh half', client.includes('remssh'))
|
||||
check('client ships the maintainable remote-ssh settings face', client.includes('dsh-remote-ssh-settings') && client.includes('rsui-root'))
|
||||
check('client carries the settings-face compose seam', client.includes('createSettingsSection') && client.includes('settingsNamespace'))
|
||||
|
||||
const remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
|
||||
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')
|
||||
check('remote-ssh host artifact carries the canonical-path patch', remoteHost.includes('resolveRemoteCanonical') && remoteHost.includes('targetResolved.ok') && remoteHost.includes('无法确认远端路径是否重复'))
|
||||
check('vendored upstream host stays pristine', !vendorHost.includes('resolveRemoteCanonical'))
|
||||
check('remote-ssh host artifact carries the ssh hardening patches', remoteHost.includes('head.concat(opts, ["--", target])') && remoteHost.includes('"sshpass", "-e"') && remoteHost.includes('inMirrorRoot'))
|
||||
check('remote-ssh host artifact has no vulnerable code forms', !remoteHost.includes('["sshpass", "-p"') && !remoteHost.includes("'StrictHostKeyChecking=no', '-o', 'ExitOnForwardFailure=no'"))
|
||||
|
||||
check('remote-ssh host artifact carries the path-escape and write-back patches', remoteHost.includes('foldedParts') && remoteHost.includes('写回护栏无法确认,本次不推送'))
|
||||
check('remote-ssh host artifact carries the load-time patch self-check', remoteHost.includes('upstream internals changed (runRemote / shellQuotePath not found)'))
|
||||
|
||||
const vendorProblems = checkVendorManifest(root)
|
||||
check('vendor tree matches its sha256 manifest', vendorProblems.length === 0)
|
||||
for (const problem of vendorProblems) console.log(' ' + problem)
|
||||
|
||||
// Executable client smoke: the static string checks above cannot see a
|
||||
// factory cut at the wrong brace or an apply() that throws on first contact.
|
||||
// Evaluate the real bundle against a fake module loader, invoke the factory
|
||||
// with a universal stub require, and run apply() against a stub context —
|
||||
// any structural break in either client half fails here.
|
||||
{
|
||||
const registrations = []
|
||||
const fakeWindow = { __ModuleLoader__: { load: (def) => registrations.push(def) } }
|
||||
const sandbox = { window: fakeWindow, console, setTimeout, clearTimeout }
|
||||
vm.createContext(sandbox)
|
||||
let plugin
|
||||
try {
|
||||
vm.runInContext(client, sandbox)
|
||||
const stub = () => stubCache
|
||||
const stubCache = new Proxy(function () {}, {
|
||||
get: (target, key) => {
|
||||
if (key === Symbol.toPrimitive) return () => ''
|
||||
if (key === Symbol.iterator) return function* () {}
|
||||
if (key === 'prototype') return {}
|
||||
return stubCache
|
||||
},
|
||||
apply: stub,
|
||||
construct: stub,
|
||||
})
|
||||
plugin = registrations[0]?.factory(() => stubCache)
|
||||
plugin.apply(stubCache)
|
||||
} catch (error) {
|
||||
console.log(' client smoke error: ' + (error instanceof Error ? error.message : String(error)))
|
||||
plugin = undefined
|
||||
}
|
||||
check('client bundle evaluates, registers one row and applies cleanly', registrations.length === 1 && plugin !== undefined && typeof plugin.apply === 'function')
|
||||
check('client inject is the union of both halves', JSON.stringify(plugin?.inject) === JSON.stringify(['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']))
|
||||
}
|
||||
|
||||
const patch = readFileSync(join(root, 'cordis.patch.yml'), 'utf8')
|
||||
check('patch inserts the merged bundle once', patch.includes(`name: '${pkg.name}'`))
|
||||
check('patch keeps the better-sidebar shell override', patch.includes('- id: better-sidebar'))
|
||||
check('patch keeps the terminal-controller shell override', patch.includes('- id: terminal-controller'))
|
||||
|
||||
console.log(failures === 0 ? '\nBUNDLE OK' : `\n${failures} check(s) failed`)
|
||||
process.exit(failures === 0 ? 0 : 1)
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
// Watch mode for the merged bundle. `tsdown --watch` alone rebuilds only
|
||||
// the groups host + client; the composition entry, the patched remote-ssh
|
||||
// host and the extracted client factory are separate build steps whose
|
||||
// outputs would silently go stale. This wrapper runs tsdown --watch AND
|
||||
// re-runs the bundle steps (debounced) whenever their inputs change.
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { watch } from 'node:fs'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
const tsdown = spawn('npx', ['tsdown', '--watch'], {
|
||||
cwd: root,
|
||||
stdio: 'inherit',
|
||||
shell: process.platform === 'win32',
|
||||
})
|
||||
tsdown.on('exit', (code) => process.exit(code ?? 0))
|
||||
|
||||
let timer = null
|
||||
const rebuild = () => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => {
|
||||
for (const script of ['scripts/build-remote-ssh-client.mjs', 'scripts/build-bundle.mjs']) {
|
||||
const run = spawnSync('node', [script], { cwd: root, stdio: 'inherit' })
|
||||
if (run.status !== 0) { console.error('watch: ' + script + ' failed'); break }
|
||||
}
|
||||
}, 200)
|
||||
}
|
||||
watch(join(root, 'bundle'), { recursive: true }, rebuild)
|
||||
watch(join(root, 'vendor/dsh-remote-ssh/lib'), { recursive: true }, rebuild)
|
||||
watch(join(root, 'scripts/patch-remote-ssh.mjs'), rebuild)
|
||||
console.log('watch: tsdown --watch + bundle steps on bundle/, vendor host and patch-script changes')
|
||||
|
|
@ -13,7 +13,7 @@
|
|||
* swaps to the remote tree, so no stacked overlays are needed and the current
|
||||
* location stays readable at the top.
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
Button,
|
||||
IconFolderOpenOutlineRegular,
|
||||
|
|
@ -24,7 +24,6 @@ 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,
|
||||
|
|
@ -35,10 +34,17 @@ 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'
|
||||
|
||||
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, blockedReason, warnings, onReload, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
|
||||
/** 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, initialRemovePath, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
|
||||
workspace: WorkspaceView
|
||||
entry: WorkspaceFolderEntry | undefined
|
||||
t: GroupsBrowserProps['t']
|
||||
|
|
@ -46,18 +52,15 @@ 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
|
||||
/** Absolute remote root of a cloud owner, so a browsed child joins as a subfolder. */
|
||||
/** Remote root of a cloud owner, so a browsed subdirectory 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
|
||||
/** Sidebar removal opens this same confirmation instead of bypassing it. */
|
||||
initialRemovePath?: string | null
|
||||
onClose: () => void
|
||||
/**
|
||||
* Gather this project's folders into one link directory and register it as a
|
||||
|
|
@ -70,15 +73,17 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
onAddRemote: (profileId: string, remotePath: string) => Promise<boolean>
|
||||
onAddSubpath: (relative: string) => Promise<boolean>
|
||||
onSetRoot: (path: string) => void
|
||||
onRemove: (path: string) => void
|
||||
onRemove: (path: string, deleteRecord: boolean) => void
|
||||
onOpenFolder: (path: string) => void
|
||||
}) {
|
||||
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')
|
||||
// All members keep their workspace when detached, including local members.
|
||||
const [confirmRemovePath, setConfirmRemovePath] = useState<string | null>(initialRemovePath ?? null)
|
||||
const [confirmFarm, setConfirmFarm] = useState(false)
|
||||
const farmConfirmation = useRef(false)
|
||||
useEffect(() => { setConfirmRemovePath(initialRemovePath ?? null) }, [initialRemovePath])
|
||||
const [profileId, setProfileId] = useState('')
|
||||
const [remotePath, setRemotePath] = useState('')
|
||||
const [browsing, setBrowsing] = useState(false)
|
||||
|
|
@ -89,11 +94,14 @@ 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 && addKind === 'subfolder'
|
||||
const editBlocked = blockedReason !== null
|
||||
const asSubfolder = remote && typed !== '' && !/[/\\~]/u.test(typed)
|
||||
const submitAdd = (): void => {
|
||||
if (typed === '' || busy || editBlocked) return
|
||||
if (typed === '' || busy) return
|
||||
if (asSubfolder) {
|
||||
void onAddSubpath(typed).then(success => { if (success) setRemotePath('') })
|
||||
return
|
||||
|
|
@ -112,7 +120,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 || editBlocked}
|
||||
busy={busy}
|
||||
onPick={(picked) => {
|
||||
const relative = subfolderOf(ownerRemotePath, picked)
|
||||
if (relative === '' && ownerRemotePath !== null) {
|
||||
|
|
@ -131,9 +139,6 @@ 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)
|
||||
}}
|
||||
|
|
@ -163,16 +168,6 @@ 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')}>
|
||||
|
|
@ -195,15 +190,16 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
// overlay, or an SSH record the plugin dropped) keeps its row so the
|
||||
// user can still remove it, but says that it cannot run sessions.
|
||||
const memberGone = member !== undefined && !knownIds.has(member.workspaceId)
|
||||
const canDeleteRecord = member?.kind === 'remote' && member.recordId !== undefined && member.recordId !== ''
|
||||
return (
|
||||
<div key={path} className="wgFolderListRow" role="listitem" data-active={isRoot}>
|
||||
<div key={path}>
|
||||
<div className="wgFolderListRow" role="listitem" data-active={isRoot}>
|
||||
<label className="wgFolderRootPick" title={t('folder.rootBadge')}>
|
||||
<input
|
||||
type="radio"
|
||||
className="wgFolderRadio"
|
||||
name="wg-folder-root"
|
||||
checked={isRoot}
|
||||
disabled={editBlocked}
|
||||
aria-label={`${t('folder.rootBadge')} ${label}`}
|
||||
onChange={() => { onSetRoot(path) }}
|
||||
/>
|
||||
|
|
@ -239,15 +235,49 @@ 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) }}
|
||||
onClick={() => {
|
||||
// Detaching exposes the backing workspace as its own row.
|
||||
if (member !== undefined) setConfirmRemovePath(path)
|
||||
else onRemove(path, false)
|
||||
}}
|
||||
>
|
||||
<IconTrashOutlineRegular />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
{confirmRemovePath === path && (
|
||||
<div className="wgFolderConfirm" role="alert">
|
||||
<span className="wgFolderConfirmText">{t(memberGone ? 'folder.removeMissingPrompt' : 'folder.removeMemberPrompt')}</span>
|
||||
{canDeleteRecord && <span className="wgFolderConfirmText">{t('folder.removeRemotePrompt')}</span>}
|
||||
<span className="wgFolderConfirmActions">
|
||||
{canDeleteRecord && <button
|
||||
type="button"
|
||||
className="wgFolderConfirmButton"
|
||||
data-tone="danger"
|
||||
onClick={() => { setConfirmRemovePath(null); onRemove(path, true) }}
|
||||
>
|
||||
{t('folder.removeRemoteDelete')}
|
||||
</button>}
|
||||
<button
|
||||
type="button"
|
||||
className="wgFolderConfirmButton"
|
||||
onClick={() => { setConfirmRemovePath(null); onRemove(path, false) }}
|
||||
>
|
||||
{t('folder.removeRemoteOnly')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wgFolderConfirmButton"
|
||||
onClick={() => { setConfirmRemovePath(null) }}
|
||||
>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
|
@ -260,11 +290,29 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
{/* A session's file scope is its workspace directory, so folders in
|
||||
different places are unreachable from one session. A farm puts
|
||||
them side by side as links; nothing is copied or moved. */}
|
||||
<button type="button" className="wgFolderPick" disabled={busy || editBlocked} onClick={onBuildFarm}>
|
||||
<button type="button" className="wgFolderPick" disabled={busy} onClick={() => { farmConfirmation.current = true; setConfirmFarm(true) }}>
|
||||
<span className="wgFolderPickPlus" aria-hidden>⇄</span>
|
||||
<span>{t('folder.mergeAction')}</span>
|
||||
</button>
|
||||
<p className="wgFolderHint">{t('folder.mergeHint')}</p>
|
||||
{confirmFarm && (
|
||||
<div className="wgFolderConfirm" role="alert">
|
||||
<span className="wgFolderConfirmText">{t('folder.mergeConfirm')}</span>
|
||||
<span className="wgFolderConfirmActions">
|
||||
<button type="button" className="wgFolderConfirmButton" disabled={busy}
|
||||
onClick={() => {
|
||||
if (!farmConfirmation.current || busy) return
|
||||
farmConfirmation.current = false
|
||||
setConfirmFarm(false)
|
||||
onBuildFarm()
|
||||
}}>
|
||||
{t('folder.mergeAction')}
|
||||
</button>
|
||||
<button type="button" className="wgFolderConfirmButton" disabled={busy}
|
||||
onClick={() => { farmConfirmation.current = false; setConfirmFarm(false) }}>{t('cancel')}</button>
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
|
|
@ -299,7 +347,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 || editBlocked} onClick={onAddFolder}>
|
||||
<button type="button" className="wgFolderPick" disabled={busy} onClick={onAddFolder}>
|
||||
<span className="wgFolderPickPlus" aria-hidden>+</span>
|
||||
<span>{t('folder.pickLocal')}</span>
|
||||
</button>
|
||||
|
|
@ -312,28 +360,6 @@ 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>
|
||||
|
|
@ -342,7 +368,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
className="wgFolderSubpathInput wgFolderSelect"
|
||||
value={selectedProfile}
|
||||
aria-label={t('folder.profileLabel')}
|
||||
disabled={busy || editBlocked}
|
||||
disabled={busy}
|
||||
onChange={event => setProfileId(event.target.value)}
|
||||
>
|
||||
{profileChoices.map(profile => (
|
||||
|
|
@ -357,9 +383,9 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
type="text"
|
||||
className="wgFolderSubpathInput wgFolderFieldInput"
|
||||
value={remotePath}
|
||||
placeholder={t(asSubfolder ? 'folder.subpathPlaceholder' : 'folder.remotePathPlaceholder')}
|
||||
aria-label={t(asSubfolder ? 'folder.subpathLabel' : 'folder.remotePathLabel')}
|
||||
disabled={busy || editBlocked}
|
||||
placeholder={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathPlaceholder')}
|
||||
aria-label={t(remote ? 'folder.remotePathOrName' : 'folder.remotePathLabel')}
|
||||
disabled={busy}
|
||||
onChange={event => setRemotePath(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== 'Enter') return
|
||||
|
|
@ -372,7 +398,7 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
className="wgFolderFieldAction"
|
||||
title={t('folder.browse')}
|
||||
aria-label={t('folder.browse')}
|
||||
disabled={busy || editBlocked || currentProfile === undefined}
|
||||
disabled={busy || currentProfile === undefined}
|
||||
onClick={() => { setBrowsing(true) }}
|
||||
>
|
||||
<IconFolderOpenOutlineRegular size={15} />
|
||||
|
|
@ -381,14 +407,14 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
|
|||
<div className="wgFolderActions">
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={busy || editBlocked || typed === '' || (!asSubfolder && selectedProfile === '')}
|
||||
disabled={busy || typed === '' || (!asSubfolder && selectedProfile === '')}
|
||||
onClick={submitAdd}
|
||||
>
|
||||
{t(asSubfolder ? 'folder.createAndAdd' : 'folder.addRemote')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="wgFolderHint">{t(asSubfolder ? 'folder.cloudNoteSubfolder' : 'folder.cloudNote')}</p>
|
||||
<p className="wgFolderHint">{t(remote ? 'folder.cloudNoteBoth' : 'folder.cloudNote')}</p>
|
||||
</>
|
||||
)}
|
||||
{profilesError !== null && (
|
||||
|
|
|
|||
|
|
@ -55,9 +55,9 @@ import { CategoryGlyph, CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, Fold
|
|||
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 { FoldersConflictError, loadFolders, saveFolders, type FoldersSnapshot } from './folders-persist.ts'
|
||||
import { createRemoteFolder, createWorkspaceDirectory, listRemoteDirectory, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
|
||||
import { EMPTY_FOLDERS_DOCUMENT, addFolder, addMember, effectiveFolders, entryFor, isEmptyEntry, isUnderBase, memberByWorkspaceId, memberOf, findRemoteMember, removeFolder, rootOf, samePath, setRoot, type FolderMember, type FoldersDocument, type WorkspaceFolderEntry } from '../core/folders.ts'
|
||||
import { FoldersConflictError, loadFolders, saveFolders } from './folders-persist.ts'
|
||||
import { createRemoteFolder, createWorkspaceDirectory, deleteRemoteWorkspaceRecord, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
|
||||
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
|
||||
import { FoldersDialog } from './FoldersDialog.tsx'
|
||||
import { buildFarm } from './folders-farm.ts'
|
||||
|
|
@ -72,12 +72,14 @@ const SEARCH_QUERY_MAX_CODE_UNITS = 500
|
|||
type NormalizedManual = Required<ManualGroups>
|
||||
|
||||
const EMPTY_MANUAL: NormalizedManual = {
|
||||
revision: 0,
|
||||
categories: [], assignments: {}, categoryOrder: [], workspaceOrder: {}, renamed: {}, hidden: [], appearance: {},
|
||||
}
|
||||
|
||||
/** Materialize optional overlay fields so every update is a plain object edit. */
|
||||
function normalizeManual(manual: ManualGroups): NormalizedManual {
|
||||
return {
|
||||
revision: manual.revision ?? 0,
|
||||
categories: manual.categories,
|
||||
assignments: manual.assignments,
|
||||
categoryOrder: manual.categoryOrder ?? [],
|
||||
|
|
@ -208,13 +210,35 @@ async function fetchGroupsConfig(): Promise<{ config: GroupsConfig; manual: Norm
|
|||
return { config, manual: isManualGroups(body.manual) ? normalizeManual(body.manual) : EMPTY_MANUAL }
|
||||
}
|
||||
|
||||
/** Persist the whole runtime overlay (idempotent; the host validates + writes). */
|
||||
async function saveManualOverlay(manual: ManualGroups): Promise<void> {
|
||||
/** A manual-overlay save rejected because another window wrote first (HTTP 409). */
|
||||
class ManualConflictError extends Error {
|
||||
readonly current: ManualGroups
|
||||
constructor(current: ManualGroups, message = 'group changes changed in another window') {
|
||||
super(message)
|
||||
this.name = 'ManualConflictError'
|
||||
this.current = current
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the whole runtime overlay (idempotent; the host validates + writes).
|
||||
* Resolves with the overlay as stored (host echo, revision bumped) so callers
|
||||
* adopt it instead of their own pre-save copy; a stale write rejects with
|
||||
* {@link ManualConflictError} carrying the host's current overlay.
|
||||
*/
|
||||
async function saveManualOverlay(manual: ManualGroups): Promise<ManualGroups> {
|
||||
const response = await fetch('/workspace-groups/manual', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(manual),
|
||||
})
|
||||
if (response.status === 409) {
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
const current = typeof body === 'object' && body !== null && isManualGroups((body as { manual?: unknown }).manual)
|
||||
? (body as { manual: ManualGroups }).manual
|
||||
: { categories: [], assignments: {} }
|
||||
throw new ManualConflictError(current)
|
||||
}
|
||||
if (!response.ok) {
|
||||
let message = `manual save failed: ${response.status}`
|
||||
try {
|
||||
|
|
@ -223,6 +247,11 @@ async function saveManualOverlay(manual: ManualGroups): Promise<void> {
|
|||
} catch { /* keep the fallback message */ }
|
||||
throw new Error(message)
|
||||
}
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
const stored = typeof body === 'object' && body !== null && isManualGroups((body as { manual?: unknown }).manual)
|
||||
? (body as { manual: ManualGroups }).manual
|
||||
: null
|
||||
return stored ?? manual
|
||||
}
|
||||
|
||||
/** One group-management dialog state: create, or rename an existing group. */
|
||||
|
|
@ -330,23 +359,18 @@ 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. 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.
|
||||
// extra folders plus the optional root folder. Reads carry an explicit
|
||||
// loading/ready/error phase: an HTTP failure must never be rendered as "no
|
||||
// folders", because that makes every member reappear as a duplicate row.
|
||||
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)
|
||||
const [foldersPhase, setFoldersPhase] = useState<'loading' | 'ready' | 'error'>('loading')
|
||||
const [foldersError, setFoldersError] = useState<string | null>(null)
|
||||
const [foldersRetryToken, setFoldersRetryToken] = useState(0)
|
||||
const [foldersConflict, setFoldersConflict] = useState<{ current: FoldersDocument; draft: FoldersDocument } | null>(null)
|
||||
const foldersConfirmedRef = useRef<FoldersDocument>(EMPTY_FOLDERS_DOCUMENT)
|
||||
const foldersHasDataRef = useRef(false)
|
||||
const foldersPendingRef = useRef<FoldersDocument | null>(null)
|
||||
const foldersSavingRef = useRef(false)
|
||||
// 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
|
||||
|
|
@ -361,39 +385,55 @@ 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)
|
||||
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)
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | null = null
|
||||
let retries = 0
|
||||
const attempt = async (): Promise<void> => {
|
||||
const snapshot = await loadFolders(fetch, controller.signal)
|
||||
if (cancelled) return
|
||||
if (snapshot.error === 'aborted') return
|
||||
if (snapshot.ok) {
|
||||
foldersConfirmedRef.current = snapshot.document
|
||||
foldersHasDataRef.current = true
|
||||
setFoldersDoc(snapshot.document)
|
||||
setFoldersRemoteBase(snapshot.remoteBase ?? null)
|
||||
setFoldersPhase('ready')
|
||||
setFoldersError(null)
|
||||
return
|
||||
}
|
||||
acceptFoldersSnapshot(result.snapshot)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => { reloadFolders() }, [])
|
||||
const reason = snapshot.error ?? 'unknown error'
|
||||
if (foldersHasDataRef.current) {
|
||||
// Keep the last confirmed rows and mark the refresh as failed; never
|
||||
// replace them with an empty document.
|
||||
setFoldersPhase('ready')
|
||||
setFoldersError(reason)
|
||||
} else {
|
||||
setFoldersPhase('error')
|
||||
setFoldersError(reason)
|
||||
}
|
||||
// Bounded exponential backoff (1s, 2s, 4s, 8s, 15s). The timer is
|
||||
// cancelled on unmount; an online event or the Retry button resets it.
|
||||
if (retries < 5) {
|
||||
const delay = Math.min(15_000, 1_000 * 2 ** retries)
|
||||
retries += 1
|
||||
timer = setTimeout(() => { void attempt() }, delay)
|
||||
}
|
||||
}
|
||||
void attempt()
|
||||
const onOnline = (): void => {
|
||||
retries = 0
|
||||
void attempt()
|
||||
}
|
||||
window.addEventListener('online', onOnline)
|
||||
return () => {
|
||||
cancelled = true
|
||||
controller.abort()
|
||||
if (timer !== null) clearTimeout(timer)
|
||||
window.removeEventListener('online', onOnline)
|
||||
}
|
||||
}, [foldersRetryToken])
|
||||
|
||||
const workspaces = useWorkspaces(state => state.items)
|
||||
const workspacePhase = useWorkspaces(state => state.phase)
|
||||
|
|
@ -659,8 +699,7 @@ export function GroupsBrowser({
|
|||
const next = { ...latest.manual, assignments: { ...latest.manual.assignments, [workspaceId]: categoryKey }, workspaceOrder }
|
||||
setManualSaving(true)
|
||||
try {
|
||||
await saveManualOverlay(next)
|
||||
setManual(next)
|
||||
await persistManual(next)
|
||||
actions.setCategoryExpanded(categoryKey, true)
|
||||
} finally {
|
||||
setManualSaving(false)
|
||||
|
|
@ -786,62 +825,97 @@ export function GroupsBrowser({
|
|||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Serialize folder saves. A save always sends the LAST confirmed revision and
|
||||
* the latest pending document; a newer edit made while a request is in flight
|
||||
* is coalesced and sent only after the previous result settles. This keeps an
|
||||
* older response from ever overwriting a newer state.
|
||||
*/
|
||||
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
|
||||
const drainFolders = async (): Promise<void> => {
|
||||
if (foldersSavingRef.current) return
|
||||
foldersSavingRef.current = true
|
||||
try {
|
||||
while (foldersPendingRef.current !== null) {
|
||||
const draft = foldersPendingRef.current
|
||||
foldersPendingRef.current = null
|
||||
const payload: FoldersDocument = {
|
||||
...draft,
|
||||
revision: foldersConfirmedRef.current.revision ?? 0,
|
||||
}
|
||||
try {
|
||||
const stored = await saveFolders(payload)
|
||||
foldersConfirmedRef.current = stored
|
||||
setFoldersError(null)
|
||||
if (foldersPendingRef.current === null) setFoldersDoc(stored)
|
||||
} catch (reason) {
|
||||
if (reason instanceof FoldersConflictError) {
|
||||
// Keep the server state visible AND remember the user's unsaved
|
||||
// draft; never silently overwrite the draft or claim success.
|
||||
foldersConfirmedRef.current = reason.current
|
||||
setFoldersDoc(reason.current)
|
||||
setFoldersConflict({ current: reason.current, draft: reason.attempted ?? draft })
|
||||
notifyFolder(t('folder.conflict'))
|
||||
} else {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
setFoldersDoc(foldersConfirmedRef.current)
|
||||
notifyFolder(`${t('folder.saveError')}: ${detail}`)
|
||||
}
|
||||
// A failed base makes every queued follow-up stale; stop here and let
|
||||
// the user retry the draft explicitly.
|
||||
foldersPendingRef.current = null
|
||||
break
|
||||
}
|
||||
// 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
|
||||
}
|
||||
} finally {
|
||||
foldersSavingRef.current = false
|
||||
if (foldersPendingRef.current !== null) void drainFolders()
|
||||
}
|
||||
const run = foldersQueueRef.current.then(task, task)
|
||||
foldersQueueRef.current = run.catch(() => undefined)
|
||||
return run
|
||||
}
|
||||
|
||||
/** 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 persistFolders = (next: FoldersDocument): void => {
|
||||
if (foldersPhase !== 'ready') {
|
||||
notifyFolder(t('folder.notReady'))
|
||||
return
|
||||
}
|
||||
foldersPendingRef.current = next
|
||||
setFoldersDoc(next)
|
||||
void drainFolders()
|
||||
}
|
||||
|
||||
const retryFolderConflict = (): void => {
|
||||
if (foldersConflict === null) return
|
||||
const draft = foldersConflict.draft
|
||||
setFoldersConflict(null)
|
||||
persistFolders({ ...draft, revision: foldersConflict.current.revision ?? 0 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the manual overlay and adopt the host's stored version (revision
|
||||
* bumped). On a conflict the host's current overlay is adopted instead, so
|
||||
* the tree resyncs to what is actually stored, and the caller still sees a
|
||||
* (localized) rejection it can surface in its own error area.
|
||||
*/
|
||||
const persistManual = async (next: ManualGroups): Promise<ManualGroups> => {
|
||||
try {
|
||||
const stored = await saveManualOverlay(next)
|
||||
setManual(normalizeManual(stored))
|
||||
return stored
|
||||
} catch (reason) {
|
||||
if (reason instanceof ManualConflictError) {
|
||||
setManual(normalizeManual(reason.current))
|
||||
throw new ManualConflictError(reason.current, t('manual.conflict'))
|
||||
}
|
||||
throw reason
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 }
|
||||
const key = workspaceId as string
|
||||
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 }
|
||||
})
|
||||
if (isEmptyEntry(entry)) delete next[key]
|
||||
else next[key] = entry
|
||||
persistFolders({ version: 1, revision: foldersDoc.revision ?? 0, workspaces: next })
|
||||
}
|
||||
|
||||
const toggleFolder = (workspaceId: WorkspaceId, path: string): void => {
|
||||
const key = folderKey(workspaceId, path)
|
||||
|
|
@ -857,33 +931,22 @@ 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). 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.
|
||||
*/
|
||||
/** Open the folder dialog and learn the owner's remote root (cloud owners only). */
|
||||
const [folderRemovalPath, setFolderRemovalPath] = useState<string | null>(null)
|
||||
const openFoldersFor = (workspaceId: string): void => {
|
||||
setFolderRemovalPath(null)
|
||||
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(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) },
|
||||
)
|
||||
void remoteFolderWorkspace(workspace.path, foldersRemoteBase).then(
|
||||
(record) => {
|
||||
if (foldersOwnerRequest.current !== workspaceId) return
|
||||
setFoldersOwnerRemote(record === null ? null : record.remotePath)
|
||||
},
|
||||
() => { if (foldersOwnerRequest.current === workspaceId) setFoldersOwnerRemote(null) },
|
||||
)
|
||||
}
|
||||
|
||||
/** The overlay record for a picked path that the SSH plugin already mirrors. */
|
||||
|
|
@ -923,25 +986,31 @@ 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<{ member: FolderMember; created: boolean }> => {
|
||||
const memberWorkspaceFor = async (workspaceId: WorkspaceId, path: string): Promise<FolderMember> => {
|
||||
const existing = workspaces.find(w => samePath(w.path, path) && w.workspaceId !== workspaceId)
|
||||
if (existing !== undefined) {
|
||||
if (!isEmptyEntry(entryFor(foldersDocRef.current, existing.workspaceId as string))) {
|
||||
if (!isEmptyEntry(entryFor(foldersDoc, existing.workspaceId as string))) {
|
||||
throw new Error(t('folder.memberNested'))
|
||||
}
|
||||
return { member: { path, workspaceId: existing.workspaceId as string, kind: 'local' }, created: false }
|
||||
return { path, workspaceId: existing.workspaceId as string, kind: 'local' }
|
||||
}
|
||||
const created = await createWorkspace({ path })
|
||||
return { member: { path, workspaceId: created.workspaceId as string, kind: 'local' }, created: true }
|
||||
return { path, workspaceId: created.workspaceId as string, kind: 'local' }
|
||||
}
|
||||
|
||||
/** 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 */ }
|
||||
}
|
||||
/**
|
||||
* Whether an entry already holds a member backed by this workspace, or a
|
||||
* remote member naming the same connection + remote directory. Both add
|
||||
* flows (pick a local directory, create a cloud folder) run this check —
|
||||
* the remote-ssh side now reuses same-directory records, so the member
|
||||
* layer must refuse the second row itself.
|
||||
*/
|
||||
const hasMemberClash = (
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
candidate: { workspaceId: string; profileId?: string; remotePath?: string },
|
||||
): boolean => memberByWorkspaceId(entry, candidate.workspaceId) !== undefined
|
||||
|| (candidate.profileId !== undefined && candidate.remotePath !== undefined
|
||||
&& findRemoteMember(entry, candidate.profileId, candidate.remotePath) !== undefined)
|
||||
|
||||
const addFolderTo = async (workspaceId: WorkspaceId): Promise<void> => {
|
||||
if (foldersBusy) return
|
||||
|
|
@ -952,13 +1021,8 @@ export function GroupsBrowser({
|
|||
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
|
||||
const path = await pickDirectory()
|
||||
if (path === null) return // cancelled
|
||||
// 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))) {
|
||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||
if (effectiveFolders(workspace.path, entry).some(folder => samePath(folder, path))) {
|
||||
notifyFolder(t('folder.duplicate'))
|
||||
return
|
||||
}
|
||||
|
|
@ -970,9 +1034,11 @@ export function GroupsBrowser({
|
|||
if (target !== null) {
|
||||
if (samePath(target.mirrorPath, path) && target.workspaceId !== ''
|
||||
&& target.workspaceId !== (workspaceId as string)) {
|
||||
await editFolderEntry(workspaceId, (current) => (
|
||||
isDuplicate(current) ? current : addMember(current, remoteMember(target))
|
||||
))
|
||||
if (hasMemberClash(entry, target)) {
|
||||
notifyFolder(t('folder.duplicate'))
|
||||
return
|
||||
}
|
||||
writeFolderEntry(workspaceId, addMember(entry, remoteMember(target)))
|
||||
return
|
||||
}
|
||||
notifyFolder(t('folder.remoteNeedsSubpath'))
|
||||
|
|
@ -983,16 +1049,10 @@ 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)) {
|
||||
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)
|
||||
writeFolderEntry(workspaceId, addMember(entry, await memberWorkspaceFor(workspaceId, path)))
|
||||
return
|
||||
}
|
||||
await editFolderEntry(workspaceId, (current) => (
|
||||
isDuplicate(current) ? current : addFolder(current, path)
|
||||
))
|
||||
writeFolderEntry(workspaceId, addFolder(entry, path))
|
||||
} catch (reason) {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.addError')}: ${detail}`)
|
||||
|
|
@ -1014,49 +1074,38 @@ export function GroupsBrowser({
|
|||
if (owner === undefined) return false
|
||||
setFoldersBusy(true)
|
||||
try {
|
||||
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 created = await createRemoteFolder(profileId, remotePath)
|
||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||
// Duplicate defenses. The first two compare identities the SSH plugin
|
||||
// returns; they only hold when it reuses the existing record for the
|
||||
// same remote directory (its host canonicalizes the path at
|
||||
// registration). The member checks below do not depend on that: a
|
||||
// folder for the same connection + remote directory, or backed by the
|
||||
// same workspace, is a duplicate no matter which mirror it points at.
|
||||
if (created.workspaceId === (workspaceId as string)) throw new Error(t('folder.duplicate'))
|
||||
if (hasMemberClash(entry, created)) throw new Error(t('folder.duplicate'))
|
||||
if (effectiveFolders(owner.path, entry).some(folder => samePath(folder, created.path))) {
|
||||
throw new Error(t('folder.duplicate'))
|
||||
}
|
||||
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 member: FolderMember = {
|
||||
path: created.path,
|
||||
workspaceId: created.workspaceId,
|
||||
kind: 'remote',
|
||||
remotePath: created.remotePath,
|
||||
profileId: created.profileId,
|
||||
title: created.title,
|
||||
...(created.recordId === '' ? {} : { recordId: created.recordId }),
|
||||
}
|
||||
// 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
|
||||
const next: FoldersDocument = {
|
||||
version: 1,
|
||||
revision: foldersDoc.revision ?? 0,
|
||||
workspaces: { ...foldersDoc.workspaces, [workspaceId]: addMember(entry, member) },
|
||||
}
|
||||
// Like the subpath field: report success only once the overlay is durable.
|
||||
setFoldersDoc(await saveFolders(next))
|
||||
return true
|
||||
} catch (reason) {
|
||||
if (reason instanceof FoldersConflictError) setFoldersDoc(reason.current)
|
||||
notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
|
||||
return false
|
||||
} finally {
|
||||
|
|
@ -1073,22 +1122,23 @@ export function GroupsBrowser({
|
|||
try {
|
||||
if (foldersRemoteBase === null) throw new Error(t('folder.notReady'))
|
||||
const pending = createdFolderPendingSave.current
|
||||
const created = pending?.workspaceId === workspaceId && pending.name === name
|
||||
const created = pending !== null && pending.workspaceId === workspaceId && pending.name === name
|
||||
? pending
|
||||
: await createWorkspaceDirectory(workspace.path, name, foldersRemoteBase, createDirectory)
|
||||
// Do not report success or clear the input until both operations succeed.
|
||||
// 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
|
||||
const entry = addFolder(entryFor(foldersDoc, workspaceId as string), created.path)
|
||||
const next: FoldersDocument = {
|
||||
version: 1,
|
||||
revision: foldersDoc.revision ?? 0,
|
||||
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.
|
||||
setFoldersDoc(await saveFolders(next))
|
||||
createdFolderPendingSave.current = null
|
||||
return true
|
||||
} catch (reason) {
|
||||
if (reason instanceof FoldersConflictError) setFoldersDoc(reason.current)
|
||||
notifyFolder(`${t('folder.addError')}: ${reason instanceof Error ? reason.message : String(reason)}`)
|
||||
return false
|
||||
} finally {
|
||||
|
|
@ -1097,7 +1147,7 @@ export function GroupsBrowser({
|
|||
}
|
||||
|
||||
const setFolderRoot = (workspaceId: WorkspaceId, path: string): void => {
|
||||
void editFolderEntry(workspaceId, (current) => setRoot(current, path))
|
||||
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1105,31 +1155,68 @@ export function GroupsBrowser({
|
|||
* workspace, so one session reaches all of them. The folders themselves are
|
||||
* never copied, moved or deleted; the farm holds links only.
|
||||
*/
|
||||
const farmCreating = useRef(false)
|
||||
const buildFarmFor = async (workspaceId: WorkspaceId): Promise<void> => {
|
||||
if (foldersBusy) return
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
if (foldersBusy || farmCreating.current) return
|
||||
const workspace = workspaces.find(item => item.workspaceId === workspaceId)
|
||||
if (workspace === undefined) return
|
||||
const folders = effectiveFolders(workspace.path, entryFor(foldersDocRef.current, workspaceId))
|
||||
const folders = effectiveFolders(workspace.path, entryFor(foldersDoc, workspaceId as string))
|
||||
if (folders.length < 2) {
|
||||
notifyFolder(t('folder.emptyHint'))
|
||||
return
|
||||
}
|
||||
farmCreating.current = true
|
||||
setFoldersBusy(true)
|
||||
try {
|
||||
const farm = await buildFarm(workspace.title, folders)
|
||||
// Registering the farm is a separate step: a created directory without a
|
||||
// workspace is harmless, and the error still names what already exists.
|
||||
await createWorkspace({ path: farm.path })
|
||||
try {
|
||||
await createWorkspace({ path: farm.path })
|
||||
} catch (reason) {
|
||||
// Keep the verified links: the host reuses the same farm on retry.
|
||||
notifyFolder(`${t('folder.mergeRegistrationFailed')} ${farm.path}: ${reason instanceof Error ? reason.message : String(reason)}`)
|
||||
return
|
||||
}
|
||||
notifyFolder(`${t('folder.mergeDone')} ${farm.path}`)
|
||||
} catch (reason) {
|
||||
notifyFolder(`${t('folder.mergeFailed')}: ${reason instanceof Error ? reason.message : String(reason)}`)
|
||||
} finally {
|
||||
farmCreating.current = false
|
||||
setFoldersBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const removeFolderFrom = (workspaceId: WorkspaceId, path: string): void => {
|
||||
void editFolderEntry(workspaceId, (current) => removeFolder(current, path))
|
||||
/**
|
||||
* Remove one folder from a project. With `deleteRecord` set — only the
|
||||
* folder dialog offers it, behind an explicit confirm — a remote member's
|
||||
* backing record is deleted through the SSH plugin as well (unshared native
|
||||
* registration and local mirror cleanup is attempted; session files remain).
|
||||
* Without it the removal
|
||||
* is overlay-only and the workspace survives as its own project. If the
|
||||
* record deletion fails, the member stays so the user can retry.
|
||||
*/
|
||||
const removeFolderFrom = (workspaceId: WorkspaceId, path: string, deleteRecord = false, confirmed = false): void => {
|
||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||
const member = memberOf(entry, path)
|
||||
if (member !== undefined && !confirmed) {
|
||||
openFoldersFor(workspaceId as string)
|
||||
setFolderRemovalPath(path)
|
||||
return
|
||||
}
|
||||
if (deleteRecord && member?.kind === 'remote' && member.recordId !== undefined && member.recordId !== '') {
|
||||
const recordId = member.recordId
|
||||
void (async () => {
|
||||
try {
|
||||
await deleteRemoteWorkspaceRecord(recordId)
|
||||
} catch (reason) {
|
||||
const detail = reason instanceof Error ? reason.message : String(reason)
|
||||
notifyFolder(`${t('folder.removeError')}: ${detail}`)
|
||||
return
|
||||
}
|
||||
writeFolderEntry(workspaceId, removeFolder(entry, path))
|
||||
})()
|
||||
return
|
||||
}
|
||||
writeFolderEntry(workspaceId, removeFolder(entry, path))
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1152,7 +1239,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(foldersDocRef.current, workspaceId as string), path)
|
||||
const member = memberOf(entryFor(foldersDoc, 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.
|
||||
|
|
@ -1168,14 +1255,9 @@ 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 { 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'))
|
||||
}
|
||||
const entry = entryFor(foldersDoc, workspaceId as string)
|
||||
const attached = await memberWorkspaceFor(workspaceId, path)
|
||||
writeFolderEntry(workspaceId, addMember(entry, attached))
|
||||
await createSessionIn(attached.workspaceId as WorkspaceId)
|
||||
return
|
||||
}
|
||||
|
|
@ -1280,8 +1362,7 @@ export function GroupsBrowser({
|
|||
|
||||
setGroupBusy(true)
|
||||
setGroupError(null)
|
||||
saveManualOverlay(next).then(() => {
|
||||
setManual(next)
|
||||
persistManual(next).then(() => {
|
||||
setManualError(null)
|
||||
setGroupBusy(false)
|
||||
setGroupDialog(null)
|
||||
|
|
@ -1330,8 +1411,7 @@ export function GroupsBrowser({
|
|||
|
||||
setGroupDeleting(true)
|
||||
setGroupDeleteError(null)
|
||||
saveManualOverlay(next).then(() => {
|
||||
setManual(next)
|
||||
persistManual(next).then(() => {
|
||||
setManualError(null)
|
||||
setGroupDeleting(false)
|
||||
setGroupDeleteTarget(null)
|
||||
|
|
@ -1414,8 +1494,7 @@ export function GroupsBrowser({
|
|||
}
|
||||
next = { ...manual, assignments, workspaceOrder }
|
||||
}
|
||||
await saveManualOverlay(next)
|
||||
setManual(next)
|
||||
await persistManual(next)
|
||||
setManualError(null)
|
||||
if (categoryKey !== UNCATEGORIZED_KEY) actions.setCategoryExpanded(categoryKey, true)
|
||||
} catch (reason) {
|
||||
|
|
@ -1450,8 +1529,7 @@ export function GroupsBrowser({
|
|||
else appearance[draggedKey] = cleaned
|
||||
}
|
||||
const next: NormalizedManual = { ...manual, categoryOrder, appearance }
|
||||
await saveManualOverlay(next)
|
||||
setManual(next)
|
||||
await persistManual(next)
|
||||
setManualError(null)
|
||||
} catch (reason) {
|
||||
setManualError(reason instanceof Error ? reason.message : String(reason))
|
||||
|
|
@ -1477,10 +1555,12 @@ export function GroupsBrowser({
|
|||
else appearance[key] = cleaned
|
||||
const next: NormalizedManual = { ...manual, appearance }
|
||||
setManual(next)
|
||||
await saveManualOverlay(next)
|
||||
await persistManual(next)
|
||||
setManualError(null)
|
||||
} catch (reason) {
|
||||
setManual(previous)
|
||||
// On a conflict persistManual already adopted the host's current
|
||||
// overlay; rolling back to `previous` would resurrect the stale copy.
|
||||
if (!(reason instanceof ManualConflictError)) setManual(previous)
|
||||
setManualError(reason instanceof Error ? reason.message : String(reason))
|
||||
} finally {
|
||||
setManualSaving(false)
|
||||
|
|
@ -1860,13 +1940,47 @@ export function GroupsBrowser({
|
|||
)}
|
||||
|
||||
<div className="wgTreeBody">
|
||||
{foldersPhase === 'loading' && (
|
||||
<div className="wgSearchStatus" role="status">{t('folder.loadingState')}</div>
|
||||
)}
|
||||
{foldersPhase === 'error' && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">
|
||||
{t('folder.loadError')}:{foldersError}
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersRetryToken(value => value + 1) }}>
|
||||
{t('folder.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{foldersPhase === 'ready' && foldersError !== null && (
|
||||
<div className="wgSearchStatus" role="status">
|
||||
{t('folder.refreshError')}:{foldersError}
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersRetryToken(value => value + 1) }}>
|
||||
{t('folder.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{foldersConflict !== null && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">
|
||||
<div>{t('folder.conflictDetail')}</div>
|
||||
<div style={{ marginTop: '4px', fontSize: '10.5px' }}>
|
||||
server revision {foldersConflict.current.revision ?? 0} · draft revision {foldersConflict.draft.revision ?? 0}
|
||||
</div>
|
||||
<div style={{ marginTop: '4px' }}>
|
||||
<button type="button" className="wgSmallAction" onClick={retryFolderConflict}>{t('folder.retryDraft')}</button>
|
||||
{' '}
|
||||
<button type="button" className="wgSmallAction" onClick={() => { setFoldersConflict(null) }}>{t('folder.discardDraft')}</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{configError !== null && (
|
||||
<div className="wgSearchStatus" role="status">{t('configUnavailable')}</div>
|
||||
)}
|
||||
{manualError !== null && (
|
||||
<div className="wgSearchStatus wgManualError" role="alert">{t('manual.saveError')}: {manualError}</div>
|
||||
)}
|
||||
{wide && normalizedQuery !== '' && searchTreeForBody !== undefined && searchMatches !== undefined ? (
|
||||
{foldersPhase !== 'ready' ? null : wide && normalizedQuery !== '' && searchTreeForBody !== undefined && searchMatches !== undefined ? (
|
||||
<SearchBody
|
||||
tree={searchTreeForBody}
|
||||
matches={searchMatches}
|
||||
|
|
@ -2185,24 +2299,18 @@ export function GroupsBrowser({
|
|||
t={t}
|
||||
busy={foldersBusy}
|
||||
canOpen={openFolderPath !== undefined}
|
||||
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
|
||||
remote={isRemoteWorkspace(workspace)}
|
||||
ownerRemotePath={foldersOwnerRemote}
|
||||
profiles={remoteProfiles}
|
||||
profilesError={remoteProfilesError}
|
||||
knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)}
|
||||
blockedReason={foldersLoadError !== null
|
||||
? `${t('folder.loadError')}: ${foldersLoadError}`
|
||||
: foldersSchemaWarning}
|
||||
warnings={[
|
||||
...(foldersRemoteBaseWarning === null ? [] : [foldersRemoteBaseWarning]),
|
||||
]}
|
||||
onReload={reloadFolders}
|
||||
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
|
||||
initialRemovePath={folderRemovalPath}
|
||||
onAddFolder={() => { void addFolderTo(foldersTarget) }}
|
||||
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
|
||||
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}
|
||||
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
|
||||
onRemove={(path) => { removeFolderFrom(foldersTarget, path) }}
|
||||
onRemove={(path, deleteRecord) => { removeFolderFrom(foldersTarget, path, deleteRecord, true) }}
|
||||
onOpenFolder={(path) => { openFolderPath?.(path) }}
|
||||
onClose={() => { foldersOwnerRequest.current = ''; setFoldersTarget(null) }}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -239,6 +239,23 @@ export async function createRemoteFolder(
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete one remote workspace record through the SSH plugin: it removes the
|
||||
* record and attempts to unregister its native workspace and clean up its
|
||||
* local mirror unless shared by another record. Session files and the original
|
||||
* remote directory remain; unregistering may hide sessions from the sidebar.
|
||||
* @param recordId - remote-ssh record id stored on the member.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export async function deleteRemoteWorkspaceRecord(
|
||||
recordId: string,
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
): Promise<void> {
|
||||
if (recordId.trim() === '') throw new Error('No remote workspace record to delete')
|
||||
const value = await rpc('deleteWorkspace', { id: recordId }, fetchImpl)
|
||||
if (value === null) throw new Error('The SSH plugin is unavailable; cannot delete the remote workspace')
|
||||
}
|
||||
|
||||
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||
export async function remoteFolderWorkspace(
|
||||
path: string, remoteBase: string | null, fetchImpl: typeof fetch = fetch,
|
||||
|
|
|
|||
|
|
@ -7,20 +7,10 @@
|
|||
* only — the workspace's canonical directory is implicit folder #0 — and
|
||||
* `root` names one of those extras (absent means "the workspace itself").
|
||||
*
|
||||
* 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.
|
||||
* Reads are best-effort, like the manual overlay and the tab strip: a failed
|
||||
* read means "no extra folders". A failed write, however, rejects so the caller
|
||||
* can say so — a folder row that silently forgot its edit would be worse than
|
||||
* the toast.
|
||||
*/
|
||||
import {
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
|
|
@ -32,10 +22,7 @@ import {
|
|||
/** Host route holding the folder overlay. */
|
||||
export const FOLDERS_ROUTE = '/workspace-groups/folders'
|
||||
|
||||
/** 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. */
|
||||
/** One successful read: the overlay plus the mirror base the host reported. */
|
||||
export interface FoldersSnapshot {
|
||||
readonly document: FoldersDocument
|
||||
/**
|
||||
|
|
@ -44,28 +31,17 @@ 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 folder-overlay read result. A failed read must never masquerade as the
|
||||
* empty document: the browser uses `ok` to keep the last confirmed rows and
|
||||
* show a retryable error instead of rendering every member as a duplicate.
|
||||
*/
|
||||
export interface FoldersLoadResult extends FoldersSnapshot {
|
||||
readonly ok: boolean
|
||||
/** Human-readable failure reason; absent on success. */
|
||||
readonly error?: string
|
||||
}
|
||||
|
||||
/** One non-empty string field, or undefined when it is absent or blank. */
|
||||
|
|
@ -104,14 +80,13 @@ function parseWireMember(value: unknown): FolderMember | null {
|
|||
}
|
||||
|
||||
/**
|
||||
* Read one workspace entry off the wire, dropping the entry only when it is
|
||||
* truly empty.
|
||||
* Read one workspace entry off the wire, dropping the entry when it is
|
||||
* unusable.
|
||||
*
|
||||
* `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. An entry with only a `root` is
|
||||
* likewise kept (the host accepts it), instead of being dropped as before.
|
||||
* erase every member-backed folder for good.
|
||||
* @param value - one value of the stored `workspaces` mapping.
|
||||
* @returns the entry, or null for a malformed one.
|
||||
*/
|
||||
|
|
@ -132,10 +107,8 @@ 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 }),
|
||||
|
|
@ -143,128 +116,130 @@ function parseWireEntry(value: unknown): WorkspaceFolderEntry | null {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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.
|
||||
*
|
||||
* A non-2xx response, a malformed body or a transport error is returned as
|
||||
* `ok:false` with the reason. The empty document is still present for callers
|
||||
* that only need a safe value, but `ok` is the authority: the browser must not
|
||||
* treat a failed read as "no folders".
|
||||
* @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.
|
||||
* @param signal - optional cancellation for a superseded read/retry.
|
||||
*/
|
||||
export async function loadFolders(fetchImpl: typeof fetch = fetch): Promise<FoldersLoadResult> {
|
||||
let response: Response
|
||||
export async function loadFolders(
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
signal?: AbortSignal,
|
||||
): Promise<FoldersLoadResult> {
|
||||
try {
|
||||
response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'GET',
|
||||
// Folders are user state; a cached response would show stale rows.
|
||||
cache: 'no-store',
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: `HTTP ${response.status}` }
|
||||
}
|
||||
const body: unknown = await response.json()
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: '响应不是 JSON 对象' }
|
||||
}
|
||||
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 }
|
||||
const document = parseWireDocument(source)
|
||||
if (document === null) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, ...base, error: '文件夹文档格式无效' }
|
||||
}
|
||||
return { ok: true, document, ...base }
|
||||
} catch (error) {
|
||||
return { ok: false, error: `GET ${FOLDERS_ROUTE}: ${error instanceof Error ? error.message : String(error)}` }
|
||||
if (signal?.aborted === true) {
|
||||
return { ok: false, document: EMPTY_FOLDERS_DOCUMENT, error: 'aborted' }
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
document: EMPTY_FOLDERS_DOCUMENT,
|
||||
error: 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 with an optimistic-concurrency check.
|
||||
* Read a whole folder document off the wire (GET response, PUT echo or the
|
||||
* 409 conflict body), or null when it is not a version-1 document.
|
||||
* @param source - parsed JSON body.
|
||||
*/
|
||||
export function parseWireDocument(source: Record<string, unknown>): FoldersDocument | null {
|
||||
if (source.version !== 1) return null
|
||||
const revision = typeof source.revision === 'number' && Number.isSafeInteger(source.revision) && source.revision >= 0
|
||||
? source.revision
|
||||
: 0
|
||||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
return { version: 1, revision, workspaces: {} }
|
||||
}
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId === '__proto__') continue // assigning it would mutate the record's prototype
|
||||
const entry = parseWireEntry(value)
|
||||
if (entry !== null) workspaces[workspaceId] = entry
|
||||
}
|
||||
return { version: 1, revision, workspaces }
|
||||
}
|
||||
|
||||
/**
|
||||
* A save rejected because another window wrote first (HTTP 409). Carries the
|
||||
* host's current document so the caller can adopt it and resync its state
|
||||
* instead of leaving the user looking at a phantom edit.
|
||||
*/
|
||||
export class FoldersConflictError extends Error {
|
||||
readonly current: FoldersDocument
|
||||
/** The unsaved document the failed PUT attempted to write. */
|
||||
readonly attempted: FoldersDocument
|
||||
constructor(current: FoldersDocument, attempted: FoldersDocument = current) {
|
||||
super('folder overlay changed in another window')
|
||||
this.name = 'FoldersConflictError'
|
||||
this.current = current
|
||||
this.attempted = attempted
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
*
|
||||
* Unlike the tab strip this does NOT swallow failures: folder edits are explicit
|
||||
* row/dialog actions, so the caller turns a rejection into a toast instead of
|
||||
* leaving the user with a row that silently forgot its folder.
|
||||
* @param document - the client's current document.
|
||||
* @param 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<string> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
|
||||
if (expectedRevision !== undefined) headers['If-Match'] = expectedRevision
|
||||
const signal = saveSignal()
|
||||
): Promise<FoldersDocument> {
|
||||
const response = await fetchImpl(FOLDERS_ROUTE, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(document),
|
||||
cache: 'no-store',
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
// The write is idempotent, so surviving a navigation with keepalive is
|
||||
// safe and avoids losing the just-added folder.
|
||||
keepalive: true,
|
||||
})
|
||||
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}`)
|
||||
if (response.status === 409) {
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
const current = typeof body === 'object' && body !== null
|
||||
? parseWireDocument(body as Record<string, unknown>)
|
||||
: null
|
||||
throw new FoldersConflictError(current ?? EMPTY_FOLDERS_DOCUMENT, document)
|
||||
}
|
||||
let body: unknown
|
||||
try {
|
||||
body = await response.json()
|
||||
} catch {
|
||||
body = undefined
|
||||
}
|
||||
const echoed = parseFoldersSnapshot(body)
|
||||
return echoed?.revision ?? expectedRevision ?? ''
|
||||
if (!response.ok) throw new Error(`PUT ${FOLDERS_ROUTE}: ${response.status}`)
|
||||
// Adopt the host's echo: it is the normalized document (with the bumped
|
||||
// revision) that was actually stored.
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
const stored = typeof body === 'object' && body !== null
|
||||
? parseWireDocument(body as Record<string, unknown>)
|
||||
: null
|
||||
return stored ?? document
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,268 @@
|
|||
/**
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
*
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
// Type-only service merges: sessions/workspaces controllers, the ui-workspace
|
||||
// navigation service face (ctx.uiWorkspace), locale dictionary seat, the
|
||||
// SlotRegistry, and the sidebar SlotMap.
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// `useWorkspaces` is contributed by the ui-workspace browser domain (same
|
||||
// declaration as the official ui-workspace client half).
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { GroupsBrowserInjected } from './contract.ts'
|
||||
import { createGroupsViewStore } from './stores.ts'
|
||||
import { createSessionTabsStore } from './tab-store.ts'
|
||||
import { loadTabs, saveTabs } from './tab-persist.ts'
|
||||
import { createStoreHook } from './store-hook.ts'
|
||||
import { shouldOpenTab, type TabOpenMode } from './tabs.ts'
|
||||
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
||||
import { directoryFlowFromEntry } from './directory-flow.ts'
|
||||
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey
|
||||
}
|
||||
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>
|
||||
}
|
||||
}
|
||||
|
||||
/** Dictionary namespace owned by this plugin. */
|
||||
const NS = 'workspaceGroups'
|
||||
|
||||
/**
|
||||
* Tab visibility policy. `auto` is the behaviour the feature was asked for —
|
||||
* opening a session that has no tab yet adds one at the front of the strip;
|
||||
* `manual` leaves the strip to callers that drive `openTab` themselves.
|
||||
*/
|
||||
const TAB_OPEN_MODE: TabOpenMode = 'auto'
|
||||
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
|
||||
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), '@dsh-xhl/workspace-groups: dictionaries')
|
||||
|
||||
// ONE store, ONE scope. The tab store is seated only by the
|
||||
// `sidebar.workspaces` entry below (scope root); the strip reads it as a
|
||||
// plain prop because it renders as a CHILD of that entry through a DOM
|
||||
// portal, not as a second slot occupant. Seating the same handle under a
|
||||
// session-scoped slot as well throws inside the registry
|
||||
// (one handle, one scope) and would abort this whole apply().
|
||||
const tabsStore = createSessionTabsStore()
|
||||
const tabInstance = tabsStore.create()
|
||||
const tabWrites = tabInstance.actions
|
||||
|
||||
// Persist the strip on the HOST, not in browser storage: the origin includes
|
||||
// the port and every launch picks a new one, so localStorage/sessionStorage
|
||||
// both start empty next time.
|
||||
//
|
||||
// Writes are GATED until the initial restore has settled. The store starts
|
||||
// empty and the browser's own effects run before the host read resolves, so an
|
||||
// ungated subscriber would write that empty state over the stored tabs —
|
||||
// erasing exactly what it was supposed to restore. `hydrated` is the latch.
|
||||
let hydrated = false
|
||||
ctx.effect(() => {
|
||||
const stop = tabInstance.subscribe(() => {
|
||||
if (!hydrated) return
|
||||
void saveTabs({
|
||||
order: tabInstance.getSnapshot().order,
|
||||
tabs: tabInstance.getSnapshot().tabs,
|
||||
})
|
||||
})
|
||||
return () => { stop() }
|
||||
}, '@dsh-xhl/workspace-groups: tab persistence')
|
||||
|
||||
// Hydrate once from the host, then open the write gate.
|
||||
//
|
||||
// `restore` is a no-op if the user already opened a tab while this was in
|
||||
// flight, so a slow response cannot discard live work. The settle deliberately
|
||||
// does NOT write: writing the strip here would erase the stored tabs whenever
|
||||
// the read came back empty for a transient reason (host still booting, a
|
||||
// dropped request). Only a real state CHANGE persists, via the subscriber.
|
||||
ctx.effect(() => {
|
||||
let cancelled = false
|
||||
void loadTabs().then((tabs) => {
|
||||
if (cancelled) return
|
||||
if (tabs.length > 0) {
|
||||
tabWrites.restore(tabs.map(tab => ({
|
||||
sessionId: tab.sessionId as SessionId,
|
||||
order: tab.order,
|
||||
...(tab.pinned === true ? { pinned: true } : {}),
|
||||
...(tab.title !== undefined ? { title: tab.title } : {}),
|
||||
})))
|
||||
}
|
||||
hydrated = true
|
||||
}).catch(() => {
|
||||
// The read failed; leave the gate open so the user's own actions persist,
|
||||
// but never write on the strength of a failed read.
|
||||
if (!cancelled) hydrated = true
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, '@dsh-xhl/workspace-groups: tab restore')
|
||||
|
||||
const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {
|
||||
const result = await ctx.sessions.search(query, signal)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
return result.value
|
||||
}
|
||||
|
||||
const browserInjected = (): GroupsBrowserInjected => ({
|
||||
// Navigation verbs belong to the shipped ui-workspace service: it owns the
|
||||
// retained `mainView` selection, supersession and pending-navigation
|
||||
// cancellation (0.1.6 moved them out of `ctx.sessions`).
|
||||
startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },
|
||||
// Folder rows create a real Session rooted in that folder. `cwd` stays out
|
||||
// of the call for the base folder (the Workspace's canonical directory),
|
||||
// where the controller already defaults to `WorkspaceView.path`.
|
||||
createSessionIn: async (workspaceId, cwd) => {
|
||||
const sessionId = await ctx.sessions.create({
|
||||
workspaceId,
|
||||
...(cwd === undefined ? {} : { cwd }),
|
||||
})
|
||||
ctx.uiWorkspace.openSession(sessionId)
|
||||
return sessionId
|
||||
},
|
||||
open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },
|
||||
forkSession: (sessionId) => {
|
||||
ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {
|
||||
console.warn('fork session failed:', reason)
|
||||
})
|
||||
},
|
||||
archiveSession: async (sessionId) => {
|
||||
await ctx.uiWorkspace.archiveSession(sessionId)
|
||||
// The tab is deliberately LEFT ALONE. Archiving hides the session from the
|
||||
// grouped surfaces, but a tab is something the user opened, and the rule
|
||||
// for this strip is that only they close one — an automatic close here
|
||||
// would silently drop work they were keeping an eye on. The chip keeps
|
||||
// rendering (falling back to the session id when the title no longer
|
||||
// resolves).
|
||||
},
|
||||
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
||||
// Our shadow entry cannot own/render the official browser's child slot.
|
||||
// Reuse the elected self-contained picker and its actual injected services.
|
||||
getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot('sidebar.workspaces.directoryFlow')[0]),
|
||||
createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name),
|
||||
searchSessions,
|
||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||
// Directory-flow hole occupancy. The official ui-workspace browser gates
|
||||
// its "Add workspace…" affordance on the hole being occupied (the shipped
|
||||
// picker package's client half fills it); this browser drives the picker
|
||||
// itself through `pickDirectory`, so it must keep the hole occupied or the
|
||||
// official entry (still live at priority 0) would silently withdraw the
|
||||
// affordance.
|
||||
hooks: {
|
||||
directoryFlow: {
|
||||
getSnapshot: () => true,
|
||||
subscribe: () => () => {},
|
||||
},
|
||||
},
|
||||
// Data-only verbs stay on the controllers.
|
||||
renameSession: async (sessionId, title) => {
|
||||
const session = ctx.sessions.binding(sessionId)?.session
|
||||
if (session === undefined) throw new Error(`unknown session "${sessionId}"`)
|
||||
const result = await session.rename(title)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
},
|
||||
renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },
|
||||
deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },
|
||||
insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
|
||||
await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)
|
||||
},
|
||||
insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {
|
||||
await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)
|
||||
},
|
||||
createWorkspace: input => ctx.workspaces.create(input),
|
||||
// "Show a tab for what I just opened" — but only while it is actually in
|
||||
// play. The browser decides per session (see `shouldOpenTab`): a draft that
|
||||
// has not been talked to, and settled history, both stay out of the strip.
|
||||
// The status arrives from the caller because it is a live UI fact read
|
||||
// through a hook, which this (non-React) factory cannot reach.
|
||||
openTab: (sessionId, status) => {
|
||||
const summary = ctx.sessions.list.getSnapshot().byId[sessionId]
|
||||
if (shouldOpenTab(TAB_OPEN_MODE, summary, status)) tabWrites.touch(sessionId)
|
||||
},
|
||||
// The strip rides this entry's own store seat, so it needs both faces
|
||||
// explicitly: a selector hook over the one live instance, and the baked
|
||||
// writes. Both come from the same instance the browser writes through.
|
||||
useTabs: createStoreHook(tabInstance),
|
||||
tabActions: tabWrites,
|
||||
})
|
||||
|
||||
// priority: -1 — lower than the official browser's default 0, so the
|
||||
// single-slot shadow rule elects this entry. No children declaration: the
|
||||
// official entry already owns `sidebar.workspaces.directoryFlow`.
|
||||
//
|
||||
// The official WorkspaceBrowser entry is NEVER disposed — shadowing only
|
||||
// changes which entry renders (activation just bumps the store's mount
|
||||
// count). Both entries live at the same cell, so if this one ever throws
|
||||
// during render the slot core retires it for the rest of its registration's
|
||||
// life and silently falls back to the official browser. Anything that can
|
||||
// throw belongs outside the hot path.
|
||||
ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(
|
||||
{
|
||||
name: 'sidebar.workspaces',
|
||||
priority: -1,
|
||||
store: createGroupsViewStore(),
|
||||
inject: browserInjected,
|
||||
locale: NS,
|
||||
registrant: 'workspace-groups-local',
|
||||
},
|
||||
GroupsBrowser,
|
||||
))
|
||||
}
|
||||
|
|
@ -1,268 +1,72 @@
|
|||
/**
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
* workspace-groups-remote — merged client entry.
|
||||
*
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* shadowing the official ui-workspace browser.
|
||||
* One package gets exactly one client row in the DSH web shell (the module
|
||||
* loader keys graph rows by package name), so this entry composes the two
|
||||
* client halves on one fiber:
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
* - groupsClient: the workspace-groups browser + session tab strip
|
||||
* (groups-client.ts, formerly this file).
|
||||
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
||||
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
||||
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
||||
* strips that registration wrapper, re-exports the bare factory and applies
|
||||
* two anchor-asserted transforms (root label, settings face). The factory
|
||||
* is invoked here with this bundle's own require (its only requires are
|
||||
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
||||
* modules) and applied alongside the groups client.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
* The settings page itself is NOT the vendored compiled component: the factory
|
||||
* receives `remoteSshCompose`, whose `createSettingsSection` builds the
|
||||
* maintainable React section from src/client/rssh-settings. Its dictionary
|
||||
* namespace and CSS live in this entry because the merged package owns them
|
||||
* (the vendored half only knows its upstream keys/styles).
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
||||
* are a subset of the groups list).
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
// Type-only service merges: sessions/workspaces controllers, the ui-workspace
|
||||
// navigation service face (ctx.uiWorkspace), locale dictionary seat, the
|
||||
// SlotRegistry, and the sidebar SlotMap.
|
||||
import type {} from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// `useWorkspaces` is contributed by the ui-workspace browser domain (same
|
||||
// declaration as the official ui-workspace client half).
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { GroupsBrowserInjected } from './contract.ts'
|
||||
import { createGroupsViewStore } from './stores.ts'
|
||||
import { createSessionTabsStore } from './tab-store.ts'
|
||||
import { loadTabs, saveTabs } from './tab-persist.ts'
|
||||
import { createStoreHook } from './store-hook.ts'
|
||||
import { shouldOpenTab, type TabOpenMode } from './tabs.ts'
|
||||
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
||||
import { directoryFlowFromEntry } from './directory-flow.ts'
|
||||
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
||||
import * as groupsClient from './groups-client.ts'
|
||||
import remoteSshFactory from './remote-ssh-factory.generated.mjs'
|
||||
import { SETTINGS_NS, registerSettingsLocale } from './rssh-settings/i18n.ts'
|
||||
import { createSettingsSection } from './rssh-settings/index.tsx'
|
||||
import { SETTINGS_CSS } from './rssh-settings/styles.ts'
|
||||
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey
|
||||
}
|
||||
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>
|
||||
}
|
||||
}
|
||||
|
||||
/** Dictionary namespace owned by this plugin. */
|
||||
const NS = 'workspaceGroups'
|
||||
|
||||
/**
|
||||
* Tab visibility policy. `auto` is the behaviour the feature was asked for —
|
||||
* opening a session that has no tab yet adds one at the front of the strip;
|
||||
* `manual` leaves the strip to callers that drive `openTab` themselves.
|
||||
*/
|
||||
const TAB_OPEN_MODE: TabOpenMode = 'auto'
|
||||
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
/** Services required before mounting (union of both client halves). */
|
||||
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
|
||||
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), '@dsh-xhl/workspace-groups: dictionaries')
|
||||
|
||||
// ONE store, ONE scope. The tab store is seated only by the
|
||||
// `sidebar.workspaces` entry below (scope root); the strip reads it as a
|
||||
// plain prop because it renders as a CHILD of that entry through a DOM
|
||||
// portal, not as a second slot occupant. Seating the same handle under a
|
||||
// session-scoped slot as well throws inside the registry
|
||||
// (one handle, one scope) and would abort this whole apply().
|
||||
const tabsStore = createSessionTabsStore()
|
||||
const tabInstance = tabsStore.create()
|
||||
const tabWrites = tabInstance.actions
|
||||
|
||||
// Persist the strip on the HOST, not in browser storage: the origin includes
|
||||
// the port and every launch picks a new one, so localStorage/sessionStorage
|
||||
// both start empty next time.
|
||||
//
|
||||
// Writes are GATED until the initial restore has settled. The store starts
|
||||
// empty and the browser's own effects run before the host read resolves, so an
|
||||
// ungated subscriber would write that empty state over the stored tabs —
|
||||
// erasing exactly what it was supposed to restore. `hydrated` is the latch.
|
||||
let hydrated = false
|
||||
ctx.effect(() => {
|
||||
const stop = tabInstance.subscribe(() => {
|
||||
if (!hydrated) return
|
||||
void saveTabs({
|
||||
order: tabInstance.getSnapshot().order,
|
||||
tabs: tabInstance.getSnapshot().tabs,
|
||||
})
|
||||
})
|
||||
return () => { stop() }
|
||||
}, '@dsh-xhl/workspace-groups: tab persistence')
|
||||
|
||||
// Hydrate once from the host, then open the write gate.
|
||||
//
|
||||
// `restore` is a no-op if the user already opened a tab while this was in
|
||||
// flight, so a slow response cannot discard live work. The settle deliberately
|
||||
// does NOT write: writing the strip here would erase the stored tabs whenever
|
||||
// the read came back empty for a transient reason (host still booting, a
|
||||
// dropped request). Only a real state CHANGE persists, via the subscriber.
|
||||
ctx.effect(() => {
|
||||
let cancelled = false
|
||||
void loadTabs().then((tabs) => {
|
||||
if (cancelled) return
|
||||
if (tabs.length > 0) {
|
||||
tabWrites.restore(tabs.map(tab => ({
|
||||
sessionId: tab.sessionId as SessionId,
|
||||
order: tab.order,
|
||||
...(tab.pinned === true ? { pinned: true } : {}),
|
||||
...(tab.title !== undefined ? { title: tab.title } : {}),
|
||||
})))
|
||||
}
|
||||
hydrated = true
|
||||
}).catch(() => {
|
||||
// The read failed; leave the gate open so the user's own actions persist,
|
||||
// but never write on the strength of a failed read.
|
||||
if (!cancelled) hydrated = true
|
||||
})
|
||||
return () => { cancelled = true }
|
||||
}, '@dsh-xhl/workspace-groups: tab restore')
|
||||
|
||||
const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {
|
||||
const result = await ctx.sessions.search(query, signal)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
return result.value
|
||||
}
|
||||
|
||||
const browserInjected = (): GroupsBrowserInjected => ({
|
||||
// Navigation verbs belong to the shipped ui-workspace service: it owns the
|
||||
// retained `mainView` selection, supersession and pending-navigation
|
||||
// cancellation (0.1.6 moved them out of `ctx.sessions`).
|
||||
startSession: (workspaceId) => { ctx.uiWorkspace.startSession(workspaceId) },
|
||||
// Folder rows create a real Session rooted in that folder. `cwd` stays out
|
||||
// of the call for the base folder (the Workspace's canonical directory),
|
||||
// where the controller already defaults to `WorkspaceView.path`.
|
||||
createSessionIn: async (workspaceId, cwd) => {
|
||||
const sessionId = await ctx.sessions.create({
|
||||
workspaceId,
|
||||
...(cwd === undefined ? {} : { cwd }),
|
||||
})
|
||||
ctx.uiWorkspace.openSession(sessionId)
|
||||
return sessionId
|
||||
},
|
||||
open: (sessionId) => { ctx.uiWorkspace.openSession(sessionId) },
|
||||
forkSession: (sessionId) => {
|
||||
ctx.uiWorkspace.forkSession(sessionId).catch((reason: unknown) => {
|
||||
console.warn('fork session failed:', reason)
|
||||
})
|
||||
},
|
||||
archiveSession: async (sessionId) => {
|
||||
await ctx.uiWorkspace.archiveSession(sessionId)
|
||||
// The tab is deliberately LEFT ALONE. Archiving hides the session from the
|
||||
// grouped surfaces, but a tab is something the user opened, and the rule
|
||||
// for this strip is that only they close one — an automatic close here
|
||||
// would silently drop work they were keeping an eye on. The chip keeps
|
||||
// rendering (falling back to the session id when the title no longer
|
||||
// resolves).
|
||||
},
|
||||
pickDirectory: () => ctx.uiWorkspace.pickDirectory(),
|
||||
// Our shadow entry cannot own/render the official browser's child slot.
|
||||
// Reuse the elected self-contained picker and its actual injected services.
|
||||
getDirectoryFlow: () => directoryFlowFromEntry(ctx.slots.entriesOfSlot('sidebar.workspaces.directoryFlow')[0]),
|
||||
createDirectory: (path, name) => ctx.uiWorkspace.createDirectory(path, name),
|
||||
searchSessions,
|
||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||
// Directory-flow hole occupancy. The official ui-workspace browser gates
|
||||
// its "Add workspace…" affordance on the hole being occupied (the shipped
|
||||
// picker package's client half fills it); this browser drives the picker
|
||||
// itself through `pickDirectory`, so it must keep the hole occupied or the
|
||||
// official entry (still live at priority 0) would silently withdraw the
|
||||
// affordance.
|
||||
hooks: {
|
||||
directoryFlow: {
|
||||
getSnapshot: () => true,
|
||||
subscribe: () => () => {},
|
||||
},
|
||||
},
|
||||
// Data-only verbs stay on the controllers.
|
||||
renameSession: async (sessionId, title) => {
|
||||
const session = ctx.sessions.binding(sessionId)?.session
|
||||
if (session === undefined) throw new Error(`unknown session "${sessionId}"`)
|
||||
const result = await session.rename(title)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
},
|
||||
renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },
|
||||
deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },
|
||||
insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
|
||||
await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)
|
||||
},
|
||||
insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {
|
||||
await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)
|
||||
},
|
||||
createWorkspace: input => ctx.workspaces.create(input),
|
||||
// "Show a tab for what I just opened" — but only while it is actually in
|
||||
// play. The browser decides per session (see `shouldOpenTab`): a draft that
|
||||
// has not been talked to, and settled history, both stay out of the strip.
|
||||
// The status arrives from the caller because it is a live UI fact read
|
||||
// through a hook, which this (non-React) factory cannot reach.
|
||||
openTab: (sessionId, status) => {
|
||||
const summary = ctx.sessions.list.getSnapshot().byId[sessionId]
|
||||
if (shouldOpenTab(TAB_OPEN_MODE, summary, status)) tabWrites.touch(sessionId)
|
||||
},
|
||||
// The strip rides this entry's own store seat, so it needs both faces
|
||||
// explicitly: a selector hook over the one live instance, and the baked
|
||||
// writes. Both come from the same instance the browser writes through.
|
||||
useTabs: createStoreHook(tabInstance),
|
||||
tabActions: tabWrites,
|
||||
})
|
||||
|
||||
// priority: -1 — lower than the official browser's default 0, so the
|
||||
// single-slot shadow rule elects this entry. No children declaration: the
|
||||
// official entry already owns `sidebar.workspaces.directoryFlow`.
|
||||
//
|
||||
// The official WorkspaceBrowser entry is NEVER disposed — shadowing only
|
||||
// changes which entry renders (activation just bumps the store's mount
|
||||
// count). Both entries live at the same cell, so if this one ever throws
|
||||
// during render the slot core retires it for the rest of its registration's
|
||||
// life and silently falls back to the official browser. Anything that can
|
||||
// throw belongs outside the hot path.
|
||||
ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(
|
||||
{
|
||||
name: 'sidebar.workspaces',
|
||||
priority: -1,
|
||||
store: createGroupsViewStore(),
|
||||
inject: browserInjected,
|
||||
locale: NS,
|
||||
registrant: 'workspace-groups-local',
|
||||
},
|
||||
GroupsBrowser,
|
||||
))
|
||||
/** Seam handed to the extracted vendored factory (settings face replacement). */
|
||||
const remoteSshCompose: RemoteSshClientCompose = {
|
||||
settingsNamespace: SETTINGS_NS,
|
||||
createSettingsSection: (deps) => createSettingsSection({ api: deps.api }),
|
||||
}
|
||||
|
||||
/** Instantiate the vendored remote-ssh client plugin exactly once. */
|
||||
const remoteSshClient = remoteSshFactory(id => require(id), remoteSshCompose)
|
||||
|
||||
/** Plugin body: apply both client halves on this bundle's fiber. */
|
||||
export function apply(ctx: Context): void {
|
||||
// The settings section declares `locale: SETTINGS_NS`, so the dictionary
|
||||
// face must be installed before the vendored half registers that slot entry.
|
||||
// (Slot rendering requires an installed locale face; registration also bumps
|
||||
// the revision so an already-mounted settings page picks the texts up.)
|
||||
ctx.effect(
|
||||
() => registerSettingsLocale(ctx.locale),
|
||||
'workspace-groups-remote: remote-ssh settings dictionaries',
|
||||
)
|
||||
|
||||
// Section styles: injected once, scoped under `.rsui-root` (no global
|
||||
// selectors), removed with the fiber. `?inline` is compiled by tsdown.
|
||||
ctx.effect(() => {
|
||||
if (SETTINGS_CSS.trim() === '') return () => {}
|
||||
const style = document.createElement('style')
|
||||
style.setAttribute('data-plugin', 'workspace-groups-remote/remote-ssh-settings')
|
||||
style.textContent = SETTINGS_CSS
|
||||
document.head.appendChild(style)
|
||||
return () => { style.remove() }
|
||||
}, 'workspace-groups-remote: remote-ssh settings styles')
|
||||
|
||||
groupsClient.apply(ctx)
|
||||
remoteSshClient.apply(ctx)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,6 +41,15 @@ export type WorkspaceGroupsKey =
|
|||
| 'folder.sectionList'
|
||||
| 'folder.sectionAdd'
|
||||
| 'folder.emptyHint'
|
||||
| 'folder.mergeTitle'
|
||||
| 'folder.mergeAction'
|
||||
| 'folder.mergeHint'
|
||||
| 'folder.mergeDone'
|
||||
| 'folder.mergeConfirm'
|
||||
| 'folder.mergeRegistrationFailed'
|
||||
| 'folder.removeMemberPrompt'
|
||||
| 'folder.removeMissingPrompt'
|
||||
| 'folder.mergeFailed'
|
||||
| 'folder.base'
|
||||
| 'folder.setRoot'
|
||||
| 'folder.rootBadge'
|
||||
|
|
@ -48,22 +57,14 @@ export type WorkspaceGroupsKey =
|
|||
| 'folder.add'
|
||||
| 'folder.done'
|
||||
| 'folder.duplicate'
|
||||
| 'folder.conflict'
|
||||
| 'folder.removeError'
|
||||
| 'folder.removeRemotePrompt'
|
||||
| 'folder.removeRemoteDelete'
|
||||
| 'folder.removeRemoteOnly'
|
||||
| 'folder.addError'
|
||||
| 'folder.sessionError'
|
||||
| 'folder.saveError'
|
||||
| 'folder.loadError'
|
||||
| 'folder.conflict'
|
||||
| 'folder.retry'
|
||||
| 'folder.reload'
|
||||
| 'folder.addKind'
|
||||
| 'folder.addKindSubfolder'
|
||||
| 'folder.addKindWorkspace'
|
||||
| 'folder.cloudNoteSubfolder'
|
||||
| 'folder.mergeTitle'
|
||||
| 'folder.mergeAction'
|
||||
| 'folder.mergeHint'
|
||||
| 'folder.mergeDone'
|
||||
| 'folder.mergeFailed'
|
||||
| 'folder.notReady'
|
||||
| 'folder.remoteSessionUnsupported'
|
||||
| 'folder.remoteHint'
|
||||
|
|
@ -104,6 +105,13 @@ export type WorkspaceGroupsKey =
|
|||
| 'folder.home'
|
||||
| 'folder.refresh'
|
||||
| 'folder.loading'
|
||||
| 'folder.loadingState'
|
||||
| 'folder.loadError'
|
||||
| 'folder.refreshError'
|
||||
| 'folder.retry'
|
||||
| 'folder.retryDraft'
|
||||
| 'folder.discardDraft'
|
||||
| 'folder.conflictDetail'
|
||||
| 'folder.emptyDir'
|
||||
| 'group.create'
|
||||
| 'group.createTitle'
|
||||
|
|
@ -150,6 +158,7 @@ export type WorkspaceGroupsKey =
|
|||
| 'section.topLevel'
|
||||
| 'section.defaultWorkspace'
|
||||
| 'manual.saveError'
|
||||
| 'manual.conflict'
|
||||
| 'session.new'
|
||||
| 'session.rename'
|
||||
| 'session.archive'
|
||||
|
|
@ -233,6 +242,15 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'folder.sectionList': '项目文件夹',
|
||||
'folder.sectionAdd': '添加文件夹',
|
||||
'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。',
|
||||
'folder.mergeTitle': '新增总目录工作区',
|
||||
'folder.mergeAction': '新增总目录入口',
|
||||
'folder.mergeHint': '为上方文件夹创建链接总目录,并新增一个独立工作区入口。原文件夹、旧工作区和原会话均保留;不会迁移会话或删除旧入口。',
|
||||
'folder.mergeConfirm': '确认将上方列出的文件夹链接到总目录,并注册为独立工作区?旧工作区及会话仍在原处,新入口不包含旧会话。',
|
||||
'folder.mergeDone': '总目录工作区已就绪;旧工作区和会话保留在原处:',
|
||||
'folder.mergeRegistrationFailed': '总目录已创建,但工作区注册失败。保持名称和文件夹不变重试将复用该目录,不会迁移或删除旧工作区:',
|
||||
'folder.removeMemberPrompt': '解除关联后,此文件夹的工作区和会话会保留,并可重新作为独立入口显示(即使没有会话)。不会删除目录或迁移会话。',
|
||||
'folder.removeMissingPrompt': '仅移除此处的失效关联,不会重建工作区,也不会删除目录或会话。',
|
||||
'folder.mergeFailed': '生成总文件夹失败',
|
||||
'folder.base': '基础文件夹',
|
||||
'folder.setRoot': '设为根目录',
|
||||
'folder.rootBadge': '根目录',
|
||||
|
|
@ -240,22 +258,14 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'folder.add': '添加文件夹',
|
||||
'folder.done': '完成',
|
||||
'folder.duplicate': '该文件夹已在此工作区中',
|
||||
'folder.conflict': '文件夹已被另一个窗口修改,已同步为最新状态,本次修改未保存,请重试',
|
||||
'folder.removeError': '远程工作区删除失败',
|
||||
'folder.removeRemotePrompt': '“连工作区一起删”会删除远程记录,并尝试清理未被其他记录共用的工作区注册和本地镜像。会话可能从侧栏隐藏,聊天文件保留;不删除服务器上的原目录。',
|
||||
'folder.removeRemoteDelete': '连工作区一起删',
|
||||
'folder.removeRemoteOnly': '解除关联,保留工作区',
|
||||
'folder.addError': '添加文件夹失败',
|
||||
'folder.sessionError': '新建会话失败',
|
||||
'folder.saveError': '文件夹保存失败',
|
||||
'folder.loadError': '无法读取文件夹配置,已暂时禁用编辑以免覆盖其它工作区',
|
||||
'folder.conflict': '文件夹配置已被另一个窗口更新,已载入最新版本。',
|
||||
'folder.retry': '请确认后重试刚才的操作。',
|
||||
'folder.reload': '重新加载',
|
||||
'folder.addKind': '云端添加方式',
|
||||
'folder.addKindSubfolder': '本项目子目录',
|
||||
'folder.addKindWorkspace': '独立云端工作区',
|
||||
'folder.cloudNoteSubfolder': '会在项目云端根目录下新建该目录并挂进来;不会注册第二个镜像工作区',
|
||||
'folder.mergeTitle': '合并成一个总文件夹',
|
||||
'folder.mergeAction': '生成总文件夹并添加为工作区',
|
||||
'folder.mergeHint': '在旁边建一个目录,用链接把这些文件夹放进去,再注册成工作区。不复制、不移动原文件夹;之后在这个工作区里的会话可以同时读写它们。',
|
||||
'folder.mergeDone': '已生成总文件夹:',
|
||||
'folder.mergeFailed': '生成总文件夹失败',
|
||||
'folder.notReady': '目录安全信息尚未加载,请重启 DSH 并刷新页面后重试',
|
||||
'folder.remoteSessionUnsupported': '当前 SSH 插件不完整支持子目录会话,请从远程工作区根目录打开会话。不会退回本地终端。',
|
||||
'folder.remoteHint': '输入一个文件夹名:本地使用 DSH 目录接口;远程使用 SSH 创建目录接口(远端同名目录已存在时复用)。SSH 不可用时不会在镜像里创建本地目录。',
|
||||
|
|
@ -296,6 +306,13 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'folder.home': '主目录',
|
||||
'folder.refresh': '刷新',
|
||||
'folder.loading': '正在读取远端目录…',
|
||||
'folder.loadingState': '正在读取文件夹配置…',
|
||||
'folder.loadError': '文件夹配置读取失败(未显示为空分组)',
|
||||
'folder.refreshError': '文件夹配置刷新失败,继续显示上次确认的配置',
|
||||
'folder.retry': '重试',
|
||||
'folder.retryDraft': '重新应用我的修改',
|
||||
'folder.discardDraft': '保留服务端版本',
|
||||
'folder.conflictDetail': '文件夹已被另一个窗口修改:下面是服务端当前版本;你未保存的修改仍保留在此处,可重新应用。',
|
||||
'folder.emptyDir': '这个目录下没有子目录',
|
||||
'group.create': '新建分组',
|
||||
'group.createTitle': '新建分组',
|
||||
|
|
@ -342,6 +359,7 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'section.topLevel': '顶层项目',
|
||||
'section.defaultWorkspace': '默认工作区',
|
||||
'manual.saveError': '分组变更保存失败',
|
||||
'manual.conflict': '分组已被另一个窗口修改,已同步为最新状态,本次修改未保存,请重试',
|
||||
'session.new': '新建会话',
|
||||
'session.rename': '重命名会话',
|
||||
'session.archive': '归档',
|
||||
|
|
@ -424,6 +442,15 @@ export const en: WorkspaceGroupsDict = {
|
|||
'folder.sectionList': 'Project folders',
|
||||
'folder.sectionAdd': 'Add a folder',
|
||||
'folder.emptyHint': 'No extra folders yet. A folder added below runs its sessions on its own, so the agent can read the files inside it directly.',
|
||||
'folder.mergeTitle': 'Add a linked-folder workspace',
|
||||
'folder.mergeAction': 'Add a separate workspace entry',
|
||||
'folder.mergeHint': 'Links the folders above into one directory and adds a separate workspace entry. Original folders, workspaces and sessions stay in place; sessions are not migrated and old entries are not deleted.',
|
||||
'folder.mergeConfirm': 'Link the folders listed above into one directory and register a separate workspace? Existing workspaces and sessions stay in place. The new entry does not contain the old sessions.',
|
||||
'folder.mergeDone': 'Linked-folder workspace ready; existing workspaces and sessions stay in place: ',
|
||||
'folder.mergeRegistrationFailed': 'The linked directory was created, but workspace registration failed. Retrying with the same name and folders reuses it without migrating or deleting existing workspaces: ',
|
||||
'folder.removeMemberPrompt': 'Detaching keeps this folder’s workspace and sessions. It can appear as a separate entry again, even with no sessions. No directory is deleted and no sessions are migrated.',
|
||||
'folder.removeMissingPrompt': 'Remove only this stale association. This does not recreate the workspace or delete directories or sessions.',
|
||||
'folder.mergeFailed': 'Could not build the merged folder',
|
||||
'folder.base': 'Base folder',
|
||||
'folder.setRoot': 'Set as root',
|
||||
'folder.rootBadge': 'Root',
|
||||
|
|
@ -431,22 +458,14 @@ export const en: WorkspaceGroupsDict = {
|
|||
'folder.add': 'Add folder',
|
||||
'folder.done': 'Done',
|
||||
'folder.duplicate': 'That folder is already in this workspace',
|
||||
'folder.conflict': 'Folders changed in another window; synced to the latest state, this edit was not saved — please retry',
|
||||
'folder.removeError': 'Could not delete the remote workspace',
|
||||
'folder.removeRemotePrompt': '“Delete workspace too” deletes the remote record and attempts to clean up its workspace registration and local mirror unless shared by other records. Sessions may disappear from the sidebar, but chat files remain. The original directory on the server is not deleted.',
|
||||
'folder.removeRemoteDelete': 'Delete workspace too',
|
||||
'folder.removeRemoteOnly': 'Detach and keep workspace',
|
||||
'folder.addError': 'Could not add the folder',
|
||||
'folder.sessionError': 'Could not start a session',
|
||||
'folder.saveError': 'Could not save folders',
|
||||
'folder.loadError': 'Could not read the folder overlay. Editing is disabled so a failed read cannot overwrite every other workspace.',
|
||||
'folder.conflict': 'Another window updated the folder overlay; the newest version has been loaded.',
|
||||
'folder.retry': 'Please check it and retry the operation.',
|
||||
'folder.reload': 'Reload',
|
||||
'folder.addKind': 'Cloud add mode',
|
||||
'folder.addKindSubfolder': 'Subfolder of this project',
|
||||
'folder.addKindWorkspace': 'Standalone cloud workspace',
|
||||
'folder.cloudNoteSubfolder': 'Creates that directory under this project’s remote root and attaches it; no second mirror workspace is registered',
|
||||
'folder.mergeTitle': 'Merge into one folder',
|
||||
'folder.mergeAction': 'Create the merged folder as a workspace',
|
||||
'folder.mergeHint': 'Builds one directory that links these folders side by side and registers it as a workspace. Nothing is copied or moved; sessions in that workspace can read and write all of them.',
|
||||
'folder.mergeDone': 'Merged folder created: ',
|
||||
'folder.mergeFailed': 'Could not build the merged folder',
|
||||
'folder.notReady': 'Directory safety information is not loaded. Restart DSH and refresh the page before retrying.',
|
||||
'folder.remoteSessionUnsupported': 'This SSH plugin does not fully support subdirectory sessions. Start from the remote workspace root instead; no local terminal fallback is allowed.',
|
||||
'folder.remoteHint': 'Enter one folder name. Local workspaces use DSH; remote workspaces use SSH mkdir (existing remote directories are reused). Missing SSH never falls back to a local mirror write.',
|
||||
|
|
@ -487,6 +506,13 @@ export const en: WorkspaceGroupsDict = {
|
|||
'folder.home': 'Home',
|
||||
'folder.refresh': 'Refresh',
|
||||
'folder.loading': 'Reading the remote directory…',
|
||||
'folder.loadingState': 'Reading folder configuration…',
|
||||
'folder.loadError': 'Could not read folder configuration (not shown as an empty grouping)',
|
||||
'folder.refreshError': 'Could not refresh folder configuration; showing the last confirmed state',
|
||||
'folder.retry': 'Retry',
|
||||
'folder.retryDraft': 'Reapply my changes',
|
||||
'folder.discardDraft': 'Keep server version',
|
||||
'folder.conflictDetail': 'Folders changed in another window. The server version is shown below; your unsaved changes are kept here and can be reapplied.',
|
||||
'folder.emptyDir': 'No subdirectories here',
|
||||
'group.create': 'New group',
|
||||
'group.createTitle': 'New group',
|
||||
|
|
@ -533,6 +559,7 @@ export const en: WorkspaceGroupsDict = {
|
|||
'section.topLevel': 'Top-level projects',
|
||||
'section.defaultWorkspace': 'Default workspace',
|
||||
'manual.saveError': 'Could not save group changes',
|
||||
'manual.conflict': 'Groups changed in another window; synced to the latest state, this edit was not saved — please retry',
|
||||
'session.new': 'New Session',
|
||||
'session.rename': 'Rename session',
|
||||
'session.archive': 'Archive',
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
/**
|
||||
* 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
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
|
||||
|
||||
/** The plugin object the vendored dsh-remote-ssh client factory returns. */
|
||||
export interface RemoteSshClientPlugin {
|
||||
apply(ctx: Context): void
|
||||
inject?: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Merged-bundle factory shape: the module-loader factory from
|
||||
* vendor/dsh-remote-ssh/lib/client.js, re-exported by
|
||||
* scripts/build-remote-ssh-client.mjs as remote-ssh-factory.generated.mjs.
|
||||
*
|
||||
* `compose` is the merged entry's seam (settings namespace + settings section
|
||||
* component factory). Omit it and the factory falls back to the vendored
|
||||
* settings face — the transform keeps that path for harnesses and old entries.
|
||||
*/
|
||||
export default function remoteSshClientFactory(
|
||||
require: (id: string) => unknown,
|
||||
compose?: RemoteSshClientCompose,
|
||||
): RemoteSshClientPlugin
|
||||
|
|
@ -0,0 +1,236 @@
|
|||
/**
|
||||
* Remote-SSH settings face — wire contract.
|
||||
*
|
||||
* The settings section is produced by this module and registered into the
|
||||
* shell's `settings.section` slot by the vendored remote-ssh client (see
|
||||
* scripts/build-remote-ssh-client.mjs). The module talks to the Host through
|
||||
* the SAME `/remote-ssh/api/*` JSON-RPC the vendored client uses: the merged
|
||||
* entry hands it the vendored client's own `api()` wrapper, so endpoint
|
||||
* names, envelopes and semantics stay byte-identical to upstream.
|
||||
*
|
||||
* Types below mirror the Host implementations in
|
||||
* vendor/dsh-remote-ssh/lib/index.js (api object around line 4641) and the
|
||||
* redacted profile projection (`publicProfiles`, line 37). They are a
|
||||
* compile-time description only; nothing here changes runtime behaviour.
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Host data shapes (as returned by /remote-ssh/api/*) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Redacted connection profile (`publicProfiles`: password stripped, boolean kept). */
|
||||
export interface RemoteSshProfile {
|
||||
id: string
|
||||
name?: string
|
||||
host: string
|
||||
port?: number
|
||||
user: string
|
||||
authMethod?: 'key' | 'password'
|
||||
keyPath?: string
|
||||
remoteRoot?: string
|
||||
proxyJump?: string
|
||||
passwordConfigured?: boolean
|
||||
}
|
||||
|
||||
/** One persisted remote workspace record (settingsFace.workspaces entry). */
|
||||
export interface RemoteSshWorkspace {
|
||||
id: string
|
||||
profileId: string
|
||||
title?: string
|
||||
remotePath?: string
|
||||
mirrorPath?: string
|
||||
shellWorkspaceId?: string
|
||||
writeBack?: boolean
|
||||
writeBackExclude?: string[]
|
||||
syncPaths?: string[]
|
||||
syncExclude?: string[]
|
||||
syncMaxBytes?: number
|
||||
}
|
||||
|
||||
/** One `~/.ssh/config` host entry (listSshConfigHosts projection). */
|
||||
export interface SshConfigHost {
|
||||
name: string
|
||||
hostName: string
|
||||
port?: number
|
||||
user?: string
|
||||
identityFile?: string
|
||||
proxyJump?: string
|
||||
}
|
||||
|
||||
/** Global preferences as rendered by the Host (getPrefs/savePrefs.prefs). */
|
||||
export interface RemoteSshPrefs {
|
||||
nodePath?: string
|
||||
writeBackFailure?: string
|
||||
writeBackFreshness?: boolean
|
||||
defaultSyncPaths?: string[]
|
||||
defaultSyncExclude?: string[]
|
||||
defaultSyncMaxBytes?: number
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Request payloads (unchanged Host contract) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/**
|
||||
* saveProfile body. Every field the vendored settings face sent is kept:
|
||||
* `name`, `host`, `port`, `user`, `authMethod`, `keyPath`, `password`,
|
||||
* `remoteRoot`, `proxyJump`. `port` is already an integer here (the form
|
||||
* rejects invalid values instead of letting the Host fall back to 22).
|
||||
*/
|
||||
export interface SaveProfilePayload {
|
||||
name: string
|
||||
host: string
|
||||
port: number
|
||||
user: string
|
||||
authMethod: 'key' | 'password'
|
||||
keyPath: string
|
||||
password: string
|
||||
remoteRoot: string
|
||||
proxyJump: string
|
||||
}
|
||||
|
||||
/** updateWorkspaceGuards body: per-workspace write-back and sync scope. */
|
||||
export interface UpdateWorkspaceGuardsPayload {
|
||||
id: string
|
||||
writeBack: boolean
|
||||
writeBackExclude: string[]
|
||||
syncPaths: string[]
|
||||
syncExclude: string[]
|
||||
/** Bytes; 0 = Host built-in default cap (the old face always sent this). */
|
||||
syncMaxBytes: number
|
||||
}
|
||||
|
||||
/** savePrefs body: global terminal / write-back / new-workspace defaults. */
|
||||
export interface SavePrefsPayload {
|
||||
nodePath: string
|
||||
writeBackFailure: 'error' | 'log'
|
||||
writeBackFreshness: boolean
|
||||
defaultSyncPaths: string[]
|
||||
defaultSyncExclude: string[]
|
||||
defaultSyncMaxBytes: number
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Response shapes */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface ListProfilesResponse {
|
||||
ok?: boolean
|
||||
profiles?: RemoteSshProfile[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface SaveProfileResponse {
|
||||
ok?: boolean
|
||||
id?: string
|
||||
profiles?: RemoteSshProfile[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface TestConnectionResponse {
|
||||
ok?: boolean
|
||||
warning?: string
|
||||
stdout?: string
|
||||
stderr?: string
|
||||
error?: string
|
||||
exitCode?: number
|
||||
truncated?: boolean
|
||||
}
|
||||
|
||||
export interface DeleteProfileResponse {
|
||||
ok?: boolean
|
||||
profiles?: RemoteSshProfile[]
|
||||
workspaces?: RemoteSshWorkspace[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ListSshConfigHostsResponse {
|
||||
ok?: boolean
|
||||
hosts?: SshConfigHost[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ListWorkspacesResponse {
|
||||
ok?: boolean
|
||||
workspaces?: RemoteSshWorkspace[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface UpdateWorkspaceGuardsResponse {
|
||||
ok?: boolean
|
||||
workspaces?: RemoteSshWorkspace[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface SyncResponse {
|
||||
ok?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface DeleteWorkspaceResponse {
|
||||
ok?: boolean
|
||||
workspaces?: RemoteSshWorkspace[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface GetPrefsResponse {
|
||||
ok?: boolean
|
||||
prefs?: RemoteSshPrefs
|
||||
deleteSync?: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface SavePrefsResponse {
|
||||
ok?: boolean
|
||||
prefs?: RemoteSshPrefs
|
||||
error?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Typed view of the vendored client's `api(method, args)` wrapper. The
|
||||
* wrapper resolves to the Host's `value` object (which always carries its
|
||||
* own `ok` flag) or `{ ok: false, error }` for transport failures.
|
||||
*/
|
||||
export interface RemoteSshApi {
|
||||
(method: 'listProfiles'): Promise<ListProfilesResponse>
|
||||
(method: 'saveProfile', args: SaveProfilePayload): Promise<SaveProfileResponse>
|
||||
(method: 'testConnection', args: { id: string }): Promise<TestConnectionResponse>
|
||||
(method: 'deleteProfile', args: { id: string }): Promise<DeleteProfileResponse>
|
||||
(method: 'listSshConfigHosts'): Promise<ListSshConfigHostsResponse>
|
||||
(method: 'listWorkspaces'): Promise<ListWorkspacesResponse>
|
||||
(method: 'updateWorkspaceGuards', args: UpdateWorkspaceGuardsPayload): Promise<UpdateWorkspaceGuardsResponse>
|
||||
(method: 'syncDown', args: { id: string }): Promise<SyncResponse>
|
||||
(method: 'syncUp', args: { id: string }): Promise<SyncResponse>
|
||||
(method: 'deleteWorkspace', args: { id: string }): Promise<DeleteWorkspaceResponse>
|
||||
(method: 'getPrefs'): Promise<GetPrefsResponse>
|
||||
(method: 'savePrefs', args: SavePrefsPayload): Promise<SavePrefsResponse>
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Translation + registration */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Bind of the settings dictionary namespace (typed keys, `{name}` params). */
|
||||
export type SettingsTranslate = (key: string, params?: Record<string, string | number>) => string
|
||||
|
||||
/** Props the shell's `settings.section` renderer injects (locale `t` seat). */
|
||||
export interface SettingsSectionProps {
|
||||
t?: SettingsTranslate
|
||||
}
|
||||
|
||||
/** Registration shape accepted by the slot renderer (function component). */
|
||||
export type SettingsSectionComponent = (props: SettingsSectionProps) => ReactNode
|
||||
|
||||
/** Runtime facts the merged client entry hands to the extracted factory. */
|
||||
export interface RemoteSshClientCompose {
|
||||
/** Dictionary namespace the settings entry declares (`locale:` in the slot def). */
|
||||
readonly settingsNamespace: string
|
||||
/** Build the settings section component around the vendored client's `api`. */
|
||||
createSettingsSection(deps: SettingsSectionDeps): SettingsSectionComponent
|
||||
}
|
||||
|
||||
/** Injected runtime services for the section (the vendored client's api wrapper). */
|
||||
export interface SettingsSectionDeps {
|
||||
api: RemoteSshApi
|
||||
}
|
||||
|
|
@ -0,0 +1,328 @@
|
|||
/**
|
||||
* Remote-SSH settings dictionary.
|
||||
*
|
||||
* The section registers its OWN namespace `dsh-remote-ssh-settings` through
|
||||
* the shell locale service (the merged client entry calls
|
||||
* {@link registerSettingsLocale} inside `ctx.effect`). Registering a separate
|
||||
* namespace — instead of appending keys to the vendored plugin's
|
||||
* `dsh-remote-ssh` dictionaries at build time — keeps all new copy in source,
|
||||
* type-checked by the `SettingsKey` union, and lets the slot machinery inject
|
||||
* a typed `t` seat into the component (declared as `locale:` in the slot
|
||||
* registration). Existing upstream keys/namespace are untouched.
|
||||
*/
|
||||
import type { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
|
||||
/** Namespace owned by this settings face. */
|
||||
export const SETTINGS_NS = 'dsh-remote-ssh-settings'
|
||||
|
||||
/** Chinese dictionary — the key set below is the single source of truth. */
|
||||
export const zh = {
|
||||
'page.title': 'Remote SSH',
|
||||
'page.subtitle': '管理远程连接与同步设置',
|
||||
|
||||
'connection.sectionTitle': '我的连接',
|
||||
'connection.sectionSummary': '测试连接、查看当前连接的诊断信息',
|
||||
'connection.count': '{n} 个连接',
|
||||
'connection.empty': '还没有连接配置。在下方「添加连接」中新增。',
|
||||
'connection.test': '测试连接',
|
||||
'connection.testing': '测试中…',
|
||||
'connection.delete': '删除',
|
||||
'connection.authKey': '密钥认证',
|
||||
'connection.authPassword': '密码认证',
|
||||
'connection.passwordConfigured': '已保存密码',
|
||||
'connection.testOk': '连接成功',
|
||||
'connection.testWarn': '连接成功,但有警告:',
|
||||
'connection.testFail': '连接失败',
|
||||
'connection.diagnostics': '诊断输出',
|
||||
'connection.deleteTitle': '删除连接「{name}」?',
|
||||
'connection.deleteBody': '将同时移除该连接下的远程工作区条目和本地镜像映射;不会删除服务器上的文件。',
|
||||
'connection.deleted': '已删除连接「{name}」',
|
||||
'connection.deleteFail': '删除失败',
|
||||
|
||||
'add.sectionTitle': '添加连接',
|
||||
'add.sectionSummary': '从系统 SSH 配置导入,或手动填写',
|
||||
'add.import': '从系统 SSH 配置导入…',
|
||||
'add.divider': '或手动添加',
|
||||
'add.name': '名称',
|
||||
'add.namePlaceholder': '如:我的超算',
|
||||
'add.host': '主机',
|
||||
'add.hostPlaceholder': 'login.example.com',
|
||||
'add.port': '端口',
|
||||
'add.user': '用户名',
|
||||
'add.userPlaceholder': 'your-username',
|
||||
'add.auth': '认证方式',
|
||||
'add.authKey': 'SSH 密钥',
|
||||
'add.authPassword': '密码',
|
||||
'add.keyPath': '私钥路径',
|
||||
'add.keyPathPlaceholder': '~/.ssh/id_rsa(留空则使用 ssh-agent 或 SSH 配置)',
|
||||
'add.password': '密码',
|
||||
'add.passwordPlaceholder': '输入密码(不会写回浏览器存储)',
|
||||
'add.remoteRoot': '远程根目录',
|
||||
'add.remoteRootPlaceholder': '~/project',
|
||||
'add.moreOptions': '更多连接选项',
|
||||
'add.moreOptionsSummary': '跳板机 ProxyJump',
|
||||
'add.proxyJump': '跳板机 ProxyJump',
|
||||
'add.proxyJumpPlaceholder': 'bastion.example.com',
|
||||
'add.submit': '添加连接',
|
||||
'add.submitting': '添加中…',
|
||||
'add.errHost': '请填写主机',
|
||||
'add.errUser': '请填写用户名',
|
||||
'add.errPort': '端口必须是 1–65535 的整数',
|
||||
'add.ok': '已添加连接「{name}」',
|
||||
'add.fail': '添加失败',
|
||||
|
||||
'import.title': '从系统 SSH 配置导入',
|
||||
'import.loading': '正在读取 ~/.ssh/config…',
|
||||
'import.readFail': '读取 ~/.ssh/config 失败',
|
||||
'import.empty': '未在 ~/.ssh/config 中发现可用主机',
|
||||
'import.note': '仅列出 ~/.ssh/config 中带 HostName 的条目;这不是完整的 OpenSSH 配置语义。',
|
||||
'import.selectAll': '全选',
|
||||
'import.clearAll': '取消全选',
|
||||
'import.selectedCount': '已选 {n} / {total}',
|
||||
'import.submit': '导入所选连接',
|
||||
'import.importing': '导入中…({done}/{total})',
|
||||
'import.progress': '正在导入「{name}」…',
|
||||
'import.resultAllOk': '已导入 {ok} 个连接',
|
||||
'import.resultPartial': '成功 {ok} 个,失败 {fail} 个',
|
||||
'import.resultAllFail': '全部失败({fail} 个)',
|
||||
'import.failedIntro': '以下主机未导入:',
|
||||
'import.noResult': '保存接口未返回结果',
|
||||
'import.retryFailed': '仅重试失败项({n})',
|
||||
'import.retrying': '重试中…({done}/{total})',
|
||||
'import.noneSelected': '请至少选择一个主机',
|
||||
'import.proxyJump': '跳板机 {target}',
|
||||
'import.close': '关闭',
|
||||
'import.authNote': '导入的连接固定使用密钥认证、远程根目录 ~;可在手动表单中补充密码或其它字段。',
|
||||
|
||||
'workspace.sectionTitle': '远程工作区',
|
||||
'workspace.sectionSummary': '独立写回与同步配置',
|
||||
'workspace.empty': '还没有远程工作区。可在「添加工作区」中选择「远程目录」创建。',
|
||||
'workspace.expand': '展开配置',
|
||||
'workspace.collapse': '收起配置',
|
||||
'workspace.connection': '所属连接',
|
||||
'workspace.remotePath': '远程路径',
|
||||
'workspace.writeBack': '启用写回(把 agent 的 write/edit 同步到远端)',
|
||||
'workspace.writeBackExclude': '写回排除(逗号或换行分隔)',
|
||||
'workspace.writeBackExcludeHint': '这些路径的本地改动不会推回远端,例如 _patch/, *.log。',
|
||||
'workspace.syncPaths': '同步范围(逗号或换行分隔,留空 = 整树)',
|
||||
'workspace.syncPathsHint': '只同步这些子路径,例如 .dsh;留空 = 整树。',
|
||||
'workspace.syncExclude': '同步排除(逗号或换行分隔)',
|
||||
'workspace.syncExcludeHint': '拉取和推送时跳过这些路径,例如 data/, *.log;与写回排除用途不同。',
|
||||
'workspace.syncMaxBytes': '同步体积上限(GiB,留空 = 默认 2 GiB)',
|
||||
'workspace.unsaved': '未保存',
|
||||
'workspace.save': '保存该工作区设置',
|
||||
'workspace.saving': '保存中…',
|
||||
'workspace.saved': '该工作区设置已保存',
|
||||
'workspace.saveFail': '保存失败',
|
||||
'workspace.syncBlocked': '有未保存的设置,请先保存再拉取或推送。',
|
||||
'workspace.syncDown': '拉取',
|
||||
'workspace.syncUp': '推送',
|
||||
'workspace.syncing': '拉取中…',
|
||||
'workspace.pushing': '推送中…',
|
||||
'workspace.syncDone': '拉取完成',
|
||||
'workspace.syncFail': '拉取失败',
|
||||
'workspace.pushDone': '推送完成',
|
||||
'workspace.pushFail': '推送失败',
|
||||
'workspace.deleteTitle': '移除远程工作区「{title}」?',
|
||||
'workspace.deleteBody': '只移除本地记录与镜像映射,不会删除服务器上的目录或文件。',
|
||||
'workspace.deleted': '已移除远程工作区「{title}」',
|
||||
'workspace.deleteFail': '删除失败',
|
||||
'workspace.unknownProfile': '未知连接',
|
||||
|
||||
'advanced.sectionTitle': '高级设置',
|
||||
'advanced.sectionSummary': '终端与写回、新工作区同步默认值',
|
||||
'advanced.terminalGroup': '终端与写回',
|
||||
'advanced.nodePath': 'Node 绝对路径',
|
||||
'advanced.nodePathHint': '终端起不来时填写;留空自动解析。',
|
||||
'advanced.nodePathPlaceholder': 'C:\\Program Files\\nodejs\\node.exe',
|
||||
'advanced.writeBackFailure': '写回推送失败时',
|
||||
'advanced.wbError': '让模型看见,工具报错',
|
||||
'advanced.wbLog': '只写日志',
|
||||
'advanced.writeBackFreshness': '推送前检查远端是否被改过(发现被改过就不推并报告)',
|
||||
'advanced.syncDefaultsGroup': '新工作区同步默认值',
|
||||
'advanced.syncDefaultsHint': '仅影响之后新建的远程工作区,不会覆盖已有工作区的独立设置。',
|
||||
'advanced.defaultSyncPaths': '默认同步范围(逗号或换行分隔,留空 = 整树)',
|
||||
'advanced.defaultSyncExclude': '默认同步排除(逗号或换行分隔)',
|
||||
'advanced.defaultSyncMaxBytes': '默认同步体积上限(GiB,留空 = 内置 2 GiB)',
|
||||
'advanced.save': '保存设置',
|
||||
'advanced.saving': '保存中…',
|
||||
'advanced.saved': '设置已保存',
|
||||
'advanced.saveFail': '保存失败',
|
||||
|
||||
'common.cancel': '取消',
|
||||
'common.close': '关闭',
|
||||
'common.confirmDelete': '确认删除',
|
||||
'common.retry': '重试',
|
||||
'common.loading': '加载中…',
|
||||
'common.save': '保存',
|
||||
'common.error': '错误:',
|
||||
'common.warning': '警告:',
|
||||
'common.unknownError': '未知错误',
|
||||
'common.expand': '展开',
|
||||
'common.collapse': '收起',
|
||||
} as const
|
||||
|
||||
/** Chinese key set; every call site is checked against it. */
|
||||
export type SettingsKey = keyof typeof zh
|
||||
|
||||
/** English dictionary — complete mirror of the Chinese key set. */
|
||||
export const en: Record<SettingsKey, string> = {
|
||||
'page.title': 'Remote SSH',
|
||||
'page.subtitle': 'Manage remote connections and sync settings',
|
||||
|
||||
'connection.sectionTitle': 'My connections',
|
||||
'connection.sectionSummary': 'Test connections and inspect diagnostics',
|
||||
'connection.count': '{n} connection(s)',
|
||||
'connection.empty': 'No connections yet. Add one below.',
|
||||
'connection.test': 'Test connection',
|
||||
'connection.testing': 'Testing…',
|
||||
'connection.delete': 'Delete',
|
||||
'connection.authKey': 'SSH key',
|
||||
'connection.authPassword': 'Password',
|
||||
'connection.passwordConfigured': 'Password saved',
|
||||
'connection.testOk': 'Connection succeeded',
|
||||
'connection.testWarn': 'Connected with a warning:',
|
||||
'connection.testFail': 'Connection failed',
|
||||
'connection.diagnostics': 'Diagnostics',
|
||||
'connection.deleteTitle': 'Delete connection "{name}"?',
|
||||
'connection.deleteBody': 'This also removes the connection\'s remote workspace entries and local mirror mapping; server files are not deleted.',
|
||||
'connection.deleted': 'Deleted connection "{name}"',
|
||||
'connection.deleteFail': 'Delete failed',
|
||||
|
||||
'add.sectionTitle': 'Add connection',
|
||||
'add.sectionSummary': 'Import from the system SSH config, or fill in manually',
|
||||
'add.import': 'Import from system SSH config…',
|
||||
'add.divider': 'or add manually',
|
||||
'add.name': 'Name',
|
||||
'add.namePlaceholder': 'e.g. My HPC',
|
||||
'add.host': 'Host',
|
||||
'add.hostPlaceholder': 'login.example.com',
|
||||
'add.port': 'Port',
|
||||
'add.user': 'User',
|
||||
'add.userPlaceholder': 'your-username',
|
||||
'add.auth': 'Authentication',
|
||||
'add.authKey': 'SSH key',
|
||||
'add.authPassword': 'Password',
|
||||
'add.keyPath': 'Private key path',
|
||||
'add.keyPathPlaceholder': '~/.ssh/id_rsa (empty = ssh-agent or SSH config)',
|
||||
'add.password': 'Password',
|
||||
'add.passwordPlaceholder': 'Enter password (never written to browser storage)',
|
||||
'add.remoteRoot': 'Remote root',
|
||||
'add.remoteRootPlaceholder': '~/project',
|
||||
'add.moreOptions': 'More connection options',
|
||||
'add.moreOptionsSummary': 'Jump host ProxyJump',
|
||||
'add.proxyJump': 'Jump host ProxyJump',
|
||||
'add.proxyJumpPlaceholder': 'bastion.example.com',
|
||||
'add.submit': 'Add connection',
|
||||
'add.submitting': 'Adding…',
|
||||
'add.errHost': 'Host is required',
|
||||
'add.errUser': 'User is required',
|
||||
'add.errPort': 'Port must be an integer from 1 to 65535',
|
||||
'add.ok': 'Added connection "{name}"',
|
||||
'add.fail': 'Add failed',
|
||||
|
||||
'import.title': 'Import from system SSH config',
|
||||
'import.loading': 'Reading ~/.ssh/config…',
|
||||
'import.readFail': 'Failed to read ~/.ssh/config',
|
||||
'import.empty': 'No usable hosts found in ~/.ssh/config',
|
||||
'import.note': 'Only entries with HostName are listed; this is not full OpenSSH config semantics.',
|
||||
'import.selectAll': 'Select all',
|
||||
'import.clearAll': 'Clear selection',
|
||||
'import.selectedCount': '{n} / {total} selected',
|
||||
'import.submit': 'Import selected connections',
|
||||
'import.importing': 'Importing… ({done}/{total})',
|
||||
'import.progress': 'Importing "{name}"…',
|
||||
'import.resultAllOk': 'Imported {ok} connection(s)',
|
||||
'import.resultPartial': '{ok} succeeded, {fail} failed',
|
||||
'import.resultAllFail': 'All {fail} failed',
|
||||
'import.failedIntro': 'These hosts were not imported:',
|
||||
'import.noResult': 'The save endpoint returned no result',
|
||||
'import.retryFailed': 'Retry failed only ({n})',
|
||||
'import.retrying': 'Retrying… ({done}/{total})',
|
||||
'import.noneSelected': 'Select at least one host',
|
||||
'import.proxyJump': 'Jump host {target}',
|
||||
'import.close': 'Close',
|
||||
'import.authNote': 'Imported connections always use key authentication and remote root ~; add a password or other fields in the manual form.',
|
||||
|
||||
'workspace.sectionTitle': 'Remote workspaces',
|
||||
'workspace.sectionSummary': 'Independent write-back and sync settings',
|
||||
'workspace.empty': 'No remote workspaces yet. Create one via "Add workspace" → "Remote directory".',
|
||||
'workspace.expand': 'Expand settings',
|
||||
'workspace.collapse': 'Collapse settings',
|
||||
'workspace.connection': 'Connection',
|
||||
'workspace.remotePath': 'Remote path',
|
||||
'workspace.writeBack': 'Enable write-back (push agent writes/edits to the remote)',
|
||||
'workspace.writeBackExclude': 'Write-back exclude (comma or newline separated)',
|
||||
'workspace.writeBackExcludeHint': 'Local changes under these paths are not pushed, e.g. _patch/, *.log.',
|
||||
'workspace.syncPaths': 'Sync scope (comma or newline separated, empty = whole tree)',
|
||||
'workspace.syncPathsHint': 'Only these sub-paths are synced, e.g. .dsh; empty = whole tree.',
|
||||
'workspace.syncExclude': 'Sync exclude (comma or newline separated)',
|
||||
'workspace.syncExcludeHint': 'Pull/push skip these paths, e.g. data/, *.log; different from write-back exclude.',
|
||||
'workspace.syncMaxBytes': 'Sync size cap (GiB, empty = default 2 GiB)',
|
||||
'workspace.unsaved': 'Unsaved',
|
||||
'workspace.save': 'Save workspace settings',
|
||||
'workspace.saving': 'Saving…',
|
||||
'workspace.saved': 'Workspace settings saved',
|
||||
'workspace.saveFail': 'Save failed',
|
||||
'workspace.syncBlocked': 'Unsaved settings — save before pulling or pushing.',
|
||||
'workspace.syncDown': 'Pull',
|
||||
'workspace.syncUp': 'Push',
|
||||
'workspace.syncing': 'Pulling…',
|
||||
'workspace.pushing': 'Pushing…',
|
||||
'workspace.syncDone': 'Pull finished',
|
||||
'workspace.syncFail': 'Pull failed',
|
||||
'workspace.pushDone': 'Push finished',
|
||||
'workspace.pushFail': 'Push failed',
|
||||
'workspace.deleteTitle': 'Remove remote workspace "{title}"?',
|
||||
'workspace.deleteBody': 'Only the local record and mirror mapping are removed; server files and directories are untouched.',
|
||||
'workspace.deleted': 'Removed remote workspace "{title}"',
|
||||
'workspace.deleteFail': 'Delete failed',
|
||||
'workspace.unknownProfile': 'Unknown connection',
|
||||
|
||||
'advanced.sectionTitle': 'Advanced settings',
|
||||
'advanced.sectionSummary': 'Terminal and write-back, new-workspace sync defaults',
|
||||
'advanced.terminalGroup': 'Terminal and write-back',
|
||||
'advanced.nodePath': 'Node absolute path',
|
||||
'advanced.nodePathHint': 'Fill in when the terminal cannot start; empty resolves automatically.',
|
||||
'advanced.nodePathPlaceholder': 'C:\\Program Files\\nodejs\\node.exe',
|
||||
'advanced.writeBackFailure': 'When a write-back push fails',
|
||||
'advanced.wbError': 'Surface to the model (tool error)',
|
||||
'advanced.wbLog': 'Log only',
|
||||
'advanced.writeBackFreshness': 'Check the remote for changes before pushing (skip and report when changed)',
|
||||
'advanced.syncDefaultsGroup': 'New workspace sync defaults',
|
||||
'advanced.syncDefaultsHint': 'Affects only remote workspaces created later; existing workspace settings are untouched.',
|
||||
'advanced.defaultSyncPaths': 'Default sync scope (comma or newline separated, empty = whole tree)',
|
||||
'advanced.defaultSyncExclude': 'Default sync exclude (comma or newline separated)',
|
||||
'advanced.defaultSyncMaxBytes': 'Default sync size cap (GiB, empty = built-in 2 GiB)',
|
||||
'advanced.save': 'Save settings',
|
||||
'advanced.saving': 'Saving…',
|
||||
'advanced.saved': 'Settings saved',
|
||||
'advanced.saveFail': 'Save failed',
|
||||
|
||||
'common.cancel': 'Cancel',
|
||||
'common.close': 'Close',
|
||||
'common.confirmDelete': 'Confirm delete',
|
||||
'common.retry': 'Retry',
|
||||
'common.loading': 'Loading…',
|
||||
'common.save': 'Save',
|
||||
'common.error': 'Error: ',
|
||||
'common.warning': 'Warning: ',
|
||||
'common.unknownError': 'Unknown error',
|
||||
'common.expand': 'Expand',
|
||||
'common.collapse': 'Collapse',
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
'dsh-remote-ssh-settings': SettingsKey
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register both dictionaries for this namespace on the shell locale service.
|
||||
* Call inside `ctx.effect(...)` so the registration is disposed with the
|
||||
* plugin fiber. The typed `register` overload enforces zh/en key parity.
|
||||
*/
|
||||
export function registerSettingsLocale(locale: LocaleRuntime): () => void {
|
||||
return locale.register(SETTINGS_NS, { zh, en })
|
||||
}
|
||||
|
|
@ -0,0 +1,510 @@
|
|||
/**
|
||||
* Remote-SSH settings — pure model.
|
||||
*
|
||||
* Everything here is plain data transformation (no React, no DOM, no
|
||||
* imports from other plugin sources), so the real behaviour can be covered
|
||||
* by unit tests without mounting the shell:
|
||||
*
|
||||
* - connection form validation and the exact `saveProfile` payload
|
||||
* - `~/.ssh/config` import mapping, per-item outcomes, partial-failure counts
|
||||
* and failed-only retry merges (the old face reported the selection size as
|
||||
* "imported" regardless of each save result)
|
||||
* - per-workspace guard drafts, dirty detection, reload reconciliation and the
|
||||
* exact `updateWorkspaceGuards` payload
|
||||
* - global preferences draft/payload/dirty/reconcile
|
||||
*
|
||||
* Field semantics and unit conversions are copied from the vendored client
|
||||
* (`splitList`, `bytesToGibText`, `gibTextToBytes`, `prefsForUi`) so the face
|
||||
* keeps the existing Host contract: lists accept comma/newline/semicolon,
|
||||
* the size cap is edited in GiB and stored in bytes, empty = Host default.
|
||||
*/
|
||||
import type {
|
||||
RemoteSshPrefs,
|
||||
RemoteSshProfile,
|
||||
RemoteSshWorkspace,
|
||||
SavePrefsPayload,
|
||||
SaveProfilePayload,
|
||||
SshConfigHost,
|
||||
TestConnectionResponse,
|
||||
UpdateWorkspaceGuardsPayload,
|
||||
} from './contract.ts'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Connection form */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Controlled draft of the "add connection" form (all fields are strings). */
|
||||
export interface ConnectionForm {
|
||||
name: string
|
||||
host: string
|
||||
port: string
|
||||
user: string
|
||||
authMethod: 'key' | 'password'
|
||||
keyPath: string
|
||||
password: string
|
||||
remoteRoot: string
|
||||
proxyJump: string
|
||||
}
|
||||
|
||||
/** Values the vendored client used when opening/clearing the form. */
|
||||
export const EMPTY_CONNECTION_FORM: ConnectionForm = {
|
||||
name: '',
|
||||
host: '',
|
||||
port: '22',
|
||||
user: '',
|
||||
authMethod: 'key',
|
||||
keyPath: '',
|
||||
password: '',
|
||||
remoteRoot: '~',
|
||||
proxyJump: '',
|
||||
}
|
||||
|
||||
/** Fresh copy (never share the frozen constant with component state). */
|
||||
export function emptyConnectionForm(): ConnectionForm {
|
||||
return { ...EMPTY_CONNECTION_FORM }
|
||||
}
|
||||
|
||||
/** Field-level issue; the component maps `messageKey` through `t`. */
|
||||
export interface FormIssue {
|
||||
field: 'host' | 'user' | 'port'
|
||||
messageKey: 'add.errHost' | 'add.errUser' | 'add.errPort'
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate exactly what the Host requires (`host` + `user`) plus a real port
|
||||
* range. The Host would otherwise `parseInt(port) || 22`, silently turning a
|
||||
* typo into 22; the UI refuses it instead. Aliases, empty key paths and the
|
||||
* reliance on ssh-agent / ~/.ssh/config stay legal (the backend accepts them).
|
||||
*/
|
||||
export function validateConnectionForm(form: ConnectionForm): FormIssue[] {
|
||||
const issues: FormIssue[] = []
|
||||
if (!form.host.trim()) issues.push({ field: 'host', messageKey: 'add.errHost' })
|
||||
if (!form.user.trim()) issues.push({ field: 'user', messageKey: 'add.errUser' })
|
||||
const portText = form.port.trim()
|
||||
const portNumber = Number(portText)
|
||||
if (!/^\d+$/.test(portText) || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
|
||||
issues.push({ field: 'port', messageKey: 'add.errPort' })
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
/** Whether the form can be submitted (callers still re-check on submit). */
|
||||
export function isConnectionFormValid(form: ConnectionForm): boolean {
|
||||
return validateConnectionForm(form).length === 0
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact `saveProfile` body. Fields are passed through as typed by the user
|
||||
* (the Host trims/derives where it always did: name falls back to host, port
|
||||
* parsing is already done here, password only persists for password auth).
|
||||
*/
|
||||
export function toSaveProfilePayload(form: ConnectionForm): SaveProfilePayload {
|
||||
return {
|
||||
name: form.name,
|
||||
host: form.host,
|
||||
port: Number(form.port),
|
||||
user: form.user,
|
||||
authMethod: form.authMethod,
|
||||
keyPath: form.keyPath,
|
||||
password: form.password,
|
||||
remoteRoot: form.remoteRoot,
|
||||
proxyJump: form.proxyJump,
|
||||
}
|
||||
}
|
||||
|
||||
/** `user@host:port` summary used by connection cards. */
|
||||
export function profileSummary(profile: RemoteSshProfile): string {
|
||||
return `${profile.user || ''}@${profile.host || ''}:${profile.port || 22}`
|
||||
}
|
||||
|
||||
/** Display name with the upstream `name || host` fallback. */
|
||||
export function profileName(profile: RemoteSshProfile): string {
|
||||
return profile.name || profile.host
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Shared conversion helpers (copied from the vendored client) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** "comma or newline (or semicolon) separated" text → trimmed non-empty list. */
|
||||
export function splitList(value: string | null | undefined): string[] {
|
||||
return String(value == null ? '' : value)
|
||||
.split(/[\n,;]/)
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
/** Byte count → GiB text (empty = Host built-in default cap). */
|
||||
export function bytesToGibText(bytes: number | null | undefined): string {
|
||||
const n = Number(bytes) || 0
|
||||
if (!n) return ''
|
||||
return String(Math.round((n / 1073741824) * 100) / 100)
|
||||
}
|
||||
|
||||
/** GiB text → bytes; empty/invalid → 0 (= Host built-in default cap). */
|
||||
export function gibTextToBytes(text: string | number | null | undefined): number {
|
||||
const n = parseFloat(String(text == null ? '' : text).replace(/[^0-9.]/g, ''))
|
||||
if (!Number.isFinite(n) || n <= 0) return 0
|
||||
return Math.round(n * 1073741824)
|
||||
}
|
||||
|
||||
/** Trimmed error text from an API envelope, else the caller's fallback. */
|
||||
export function apiErrorMessage(
|
||||
value: { error?: string } | null | undefined,
|
||||
fallback: string,
|
||||
): string {
|
||||
const text = value && typeof value.error === 'string' ? value.error.trim() : ''
|
||||
return text || fallback
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Connection test feedback */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export type TestStatus = 'success' | 'warning' | 'error'
|
||||
|
||||
/** Rendered shape of one connection test result. */
|
||||
export interface ConnectionTestView {
|
||||
status: TestStatus
|
||||
/** Localized status line (caller resolves the keys). */
|
||||
titleKey: 'connection.testOk' | 'connection.testWarn' | 'connection.testFail'
|
||||
/** Raw warning returned by the Host (successful connect with degraded key path). */
|
||||
warning: string
|
||||
/** stdout for success, stderr/error text for failure. */
|
||||
detail: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Map `testConnection` output to the card feedback. A successful probe that
|
||||
* carries `warning` stays a warning (never collapsed into a plain success).
|
||||
*/
|
||||
export function connectionTestView(
|
||||
result: TestConnectionResponse | null | undefined,
|
||||
): ConnectionTestView {
|
||||
const warning = String(result?.warning || '').trim()
|
||||
if (result?.ok) {
|
||||
return {
|
||||
status: warning ? 'warning' : 'success',
|
||||
titleKey: warning ? 'connection.testWarn' : 'connection.testOk',
|
||||
warning,
|
||||
detail: String(result.stdout || '').trim(),
|
||||
}
|
||||
}
|
||||
const detail = [result?.error, result?.stderr].filter(Boolean).join('\n').trim()
|
||||
return {
|
||||
status: 'error',
|
||||
titleKey: 'connection.testFail',
|
||||
warning,
|
||||
detail,
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* SSH config import */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Stable row key; same spelling the vendored importer used for selection. */
|
||||
export function importHostKey(host: SshConfigHost): string {
|
||||
return `${host.name}|${host.hostName}`
|
||||
}
|
||||
|
||||
/** Default selection: every discovered host (upstream opened all checked). */
|
||||
export function selectAllHosts(hosts: SshConfigHost[]): Record<string, boolean> {
|
||||
const selected: Record<string, boolean> = {}
|
||||
for (const host of hosts) selected[importHostKey(host)] = true
|
||||
return selected
|
||||
}
|
||||
|
||||
/** Toggle one selection key without mutating the previous map. */
|
||||
export function toggleHostSelection(
|
||||
selected: Record<string, boolean>,
|
||||
key: string,
|
||||
): Record<string, boolean> {
|
||||
return { ...selected, [key]: !selected[key] }
|
||||
}
|
||||
|
||||
/** Selected hosts, in discovery order (never trusts map iteration order). */
|
||||
export function selectedHosts(
|
||||
hosts: SshConfigHost[],
|
||||
selected: Record<string, boolean>,
|
||||
): SshConfigHost[] {
|
||||
return hosts.filter(host => selected[importHostKey(host)])
|
||||
}
|
||||
|
||||
/** Count of checked rows. */
|
||||
export function countSelected(selected: Record<string, boolean>): number {
|
||||
return Object.keys(selected).filter(key => selected[key]).length
|
||||
}
|
||||
|
||||
/**
|
||||
* Exact import mapping kept from the vendored face: name, host, port, user,
|
||||
* keyPath (identityFile), proxyJump; key auth, empty password, remoteRoot ~.
|
||||
*/
|
||||
export function importProfilePayload(host: SshConfigHost): SaveProfilePayload {
|
||||
return {
|
||||
name: host.name,
|
||||
host: host.hostName,
|
||||
port: Number(host.port) || 22,
|
||||
user: host.user || '',
|
||||
authMethod: 'key',
|
||||
keyPath: host.identityFile || '',
|
||||
password: '',
|
||||
remoteRoot: '~',
|
||||
proxyJump: host.proxyJump || '',
|
||||
}
|
||||
}
|
||||
|
||||
/** One save attempt inside an import run. */
|
||||
export interface ImportItemOutcome {
|
||||
key: string
|
||||
name: string
|
||||
hostName: string
|
||||
ok: boolean
|
||||
/** Host/transport error text (absent when ok). */
|
||||
error?: string
|
||||
/** Synthesized reason when the call resolved without an envelope. */
|
||||
errorCode?: 'no-result'
|
||||
}
|
||||
|
||||
/** Aggregated per-run statistics (never "selected size" as success count). */
|
||||
export interface ImportSummary {
|
||||
outcomes: ImportItemOutcome[]
|
||||
okCount: number
|
||||
failCount: number
|
||||
failedHosts: SshConfigHost[]
|
||||
}
|
||||
|
||||
/** Injected `saveProfile` port (the vendored api wrapper satisfies this). */
|
||||
export type SaveProfileCall = (
|
||||
payload: SaveProfilePayload,
|
||||
) => Promise<{ ok?: boolean; error?: string } | null | undefined>
|
||||
|
||||
/**
|
||||
* Import hosts one by one. Each item is checked individually:
|
||||
* - `ok: true` counts as success;
|
||||
* - `ok: false` (or any thrown request error) counts as failure with its reason;
|
||||
* - a missing envelope counts as failure (`errorCode: 'no-result'`) so a
|
||||
* silent transport layer can never be reported as imported.
|
||||
*
|
||||
* Sequential on purpose: profile saves rewrite one settings table, and the
|
||||
* calls are cheap compared to SSH; this also keeps progress deterministic.
|
||||
*/
|
||||
export async function runImport(
|
||||
hosts: SshConfigHost[],
|
||||
saveProfile: SaveProfileCall,
|
||||
options: {
|
||||
onProgress?: (done: number, total: number, host: SshConfigHost) => void
|
||||
} = {},
|
||||
): Promise<ImportSummary> {
|
||||
const outcomes: ImportItemOutcome[] = []
|
||||
const failedHosts: SshConfigHost[] = []
|
||||
let okCount = 0
|
||||
let failCount = 0
|
||||
|
||||
for (let index = 0; index < hosts.length; index += 1) {
|
||||
const host = hosts[index] as SshConfigHost
|
||||
options.onProgress?.(index, hosts.length, host)
|
||||
const outcome: ImportItemOutcome = {
|
||||
key: importHostKey(host),
|
||||
name: host.name,
|
||||
hostName: host.hostName,
|
||||
ok: false,
|
||||
}
|
||||
try {
|
||||
const result = await saveProfile(importProfilePayload(host))
|
||||
if (result && result.ok === true) {
|
||||
outcome.ok = true
|
||||
okCount += 1
|
||||
} else {
|
||||
const error = result && typeof result.error === 'string' ? result.error.trim() : ''
|
||||
if (error) outcome.error = error
|
||||
else outcome.errorCode = 'no-result'
|
||||
failCount += 1
|
||||
failedHosts.push(host)
|
||||
}
|
||||
} catch (error) {
|
||||
outcome.error = error instanceof Error ? error.message : String(error)
|
||||
failCount += 1
|
||||
failedHosts.push(host)
|
||||
}
|
||||
outcomes.push(outcome)
|
||||
}
|
||||
const lastHost = hosts[hosts.length - 1]
|
||||
if (lastHost) options.onProgress?.(hosts.length, hosts.length, lastHost)
|
||||
return { outcomes, okCount, failCount, failedHosts }
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold a failed-only retry run into the previous summary: previously
|
||||
* successful items stay successes (they are never resubmitted), failed items
|
||||
* take the retry outcome.
|
||||
*/
|
||||
export function mergeImportRetry(
|
||||
previous: ImportSummary,
|
||||
retry: ImportSummary,
|
||||
): ImportSummary {
|
||||
const kept = previous.outcomes.filter(outcome => outcome.ok)
|
||||
const outcomes = [...kept, ...retry.outcomes]
|
||||
const okCount = kept.length + retry.okCount
|
||||
const failCount = retry.failCount
|
||||
return { outcomes, okCount, failCount, failedHosts: retry.failedHosts }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Per-workspace guards */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Controlled draft of one workspace's write-back / sync settings. */
|
||||
export interface GuardDraft {
|
||||
writeBack: boolean
|
||||
writeBackExclude: string
|
||||
syncPaths: string
|
||||
syncExclude: string
|
||||
syncMaxBytes: string
|
||||
}
|
||||
|
||||
/** Draft initialized from a persisted record (defaults match the Host). */
|
||||
export function guardDraftFromWorkspace(workspace: RemoteSshWorkspace): GuardDraft {
|
||||
return {
|
||||
writeBack: workspace.writeBack !== false,
|
||||
writeBackExclude: (workspace.writeBackExclude || []).join(', '),
|
||||
syncPaths: (workspace.syncPaths || []).join(', '),
|
||||
syncExclude: (workspace.syncExclude || []).join(', '),
|
||||
syncMaxBytes: bytesToGibText(workspace.syncMaxBytes),
|
||||
}
|
||||
}
|
||||
|
||||
/** Drafts + baselines keyed by workspace id. */
|
||||
export function guardsFromWorkspaces(
|
||||
workspaces: RemoteSshWorkspace[],
|
||||
): Record<string, GuardDraft> {
|
||||
const drafts: Record<string, GuardDraft> = {}
|
||||
for (const workspace of workspaces) drafts[workspace.id] = guardDraftFromWorkspace(workspace)
|
||||
return drafts
|
||||
}
|
||||
|
||||
/** Canonical signature: list formatting / "2" vs "2.0" must not look dirty. */
|
||||
export function guardDraftSignature(draft: GuardDraft): string {
|
||||
return [
|
||||
draft.writeBack ? '1' : '0',
|
||||
splitList(draft.writeBackExclude).join('\u0000'),
|
||||
splitList(draft.syncPaths).join('\u0000'),
|
||||
splitList(draft.syncExclude).join('\u0000'),
|
||||
String(gibTextToBytes(draft.syncMaxBytes)),
|
||||
].join('\u0001')
|
||||
}
|
||||
|
||||
/** Whether the draft differs semantically from the persisted baseline. */
|
||||
export function isGuardDraftDirty(draft: GuardDraft, baseline: GuardDraft): boolean {
|
||||
return guardDraftSignature(draft) !== guardDraftSignature(baseline)
|
||||
}
|
||||
|
||||
/** Exact `updateWorkspaceGuards` body — always carries the target workspace id. */
|
||||
export function toUpdateWorkspaceGuardsPayload(
|
||||
workspaceId: string,
|
||||
draft: GuardDraft,
|
||||
): UpdateWorkspaceGuardsPayload {
|
||||
return {
|
||||
id: workspaceId,
|
||||
writeBack: draft.writeBack !== false,
|
||||
writeBackExclude: splitList(draft.writeBackExclude),
|
||||
syncPaths: splitList(draft.syncPaths),
|
||||
syncExclude: splitList(draft.syncExclude),
|
||||
syncMaxBytes: gibTextToBytes(draft.syncMaxBytes),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile drafts with a freshly persisted list. Dirty drafts survive a
|
||||
* reload (their baseline moves to the new server truth); clean drafts adopt
|
||||
* it. Records removed on the Host disappear. A draft with no baseline is
|
||||
* treated as dirty so an unrelated refresh can never wipe typed text.
|
||||
*/
|
||||
export function reconcileGuards(
|
||||
previousDrafts: Record<string, GuardDraft>,
|
||||
previousBaselines: Record<string, GuardDraft>,
|
||||
workspaces: RemoteSshWorkspace[],
|
||||
): { drafts: Record<string, GuardDraft>; baselines: Record<string, GuardDraft> } {
|
||||
const baselines: Record<string, GuardDraft> = guardsFromWorkspaces(workspaces)
|
||||
const drafts: Record<string, GuardDraft> = {}
|
||||
for (const [id, baseline] of Object.entries(baselines)) {
|
||||
const previousDraft = previousDrafts[id]
|
||||
const previousBaseline = previousBaselines[id]
|
||||
const dirty = previousDraft !== undefined
|
||||
&& (previousBaseline === undefined || isGuardDraftDirty(previousDraft, previousBaseline))
|
||||
drafts[id] = dirty ? previousDraft : baseline
|
||||
}
|
||||
return { drafts, baselines }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Global preferences */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Controlled draft of the advanced section. */
|
||||
export interface PrefsDraft {
|
||||
nodePath: string
|
||||
writeBackFailure: 'error' | 'log'
|
||||
writeBackFreshness: boolean
|
||||
defaultSyncPaths: string
|
||||
defaultSyncExclude: string
|
||||
defaultSyncMaxBytes: string
|
||||
}
|
||||
|
||||
/** Host preferences → draft (same projection the vendored face used). */
|
||||
export function prefsDraftFromApi(prefs: RemoteSshPrefs | null | undefined): PrefsDraft {
|
||||
const value = prefs || {}
|
||||
return {
|
||||
nodePath: String(value.nodePath || ''),
|
||||
writeBackFailure: String(value.writeBackFailure || 'error') === 'log' ? 'log' : 'error',
|
||||
writeBackFreshness: value.writeBackFreshness !== false,
|
||||
defaultSyncPaths: (value.defaultSyncPaths || []).join(', '),
|
||||
defaultSyncExclude: (value.defaultSyncExclude || []).join(', '),
|
||||
defaultSyncMaxBytes: bytesToGibText(value.defaultSyncMaxBytes),
|
||||
}
|
||||
}
|
||||
|
||||
/** Canonical preference signature for dirty detection. */
|
||||
export function prefsDraftSignature(draft: PrefsDraft): string {
|
||||
return [
|
||||
draft.nodePath.trim(),
|
||||
draft.writeBackFailure === 'log' ? 'log' : 'error',
|
||||
draft.writeBackFreshness === false ? '0' : '1',
|
||||
splitList(draft.defaultSyncPaths).join('\u0000'),
|
||||
splitList(draft.defaultSyncExclude).join('\u0000'),
|
||||
String(gibTextToBytes(draft.defaultSyncMaxBytes)),
|
||||
].join('\u0001')
|
||||
}
|
||||
|
||||
/** Whether the advanced draft differs from the saved preferences. */
|
||||
export function isPrefsDraftDirty(draft: PrefsDraft, baseline: PrefsDraft): boolean {
|
||||
return prefsDraftSignature(draft) !== prefsDraftSignature(baseline)
|
||||
}
|
||||
|
||||
/** Exact `savePrefs` body (array conversions + GiB → bytes). */
|
||||
export function toSavePrefsPayload(draft: PrefsDraft): SavePrefsPayload {
|
||||
return {
|
||||
nodePath: draft.nodePath.trim(),
|
||||
writeBackFailure: draft.writeBackFailure === 'log' ? 'log' : 'error',
|
||||
writeBackFreshness: draft.writeBackFreshness !== false,
|
||||
defaultSyncPaths: splitList(draft.defaultSyncPaths),
|
||||
defaultSyncExclude: splitList(draft.defaultSyncExclude),
|
||||
defaultSyncMaxBytes: gibTextToBytes(draft.defaultSyncMaxBytes),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile the advanced draft with a fresh `getPrefs` read: unsaved edits
|
||||
* survive, clean drafts adopt server truth. Baselines always follow the
|
||||
* server so the dirty badge compares against what is actually stored.
|
||||
*/
|
||||
export function reconcilePrefs(
|
||||
previousDraft: PrefsDraft | null,
|
||||
previousBaseline: PrefsDraft | null,
|
||||
serverDraft: PrefsDraft,
|
||||
): { draft: PrefsDraft; baseline: PrefsDraft } {
|
||||
if (previousDraft && previousBaseline && isPrefsDraftDirty(previousDraft, previousBaseline)) {
|
||||
return { draft: previousDraft, baseline: serverDraft }
|
||||
}
|
||||
return { draft: serverDraft, baseline: serverDraft }
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
/**
|
||||
* Compiled-at-build CSS for the Remote-SSH settings face.
|
||||
*
|
||||
* `settings.css?inline` is resolved by tsdown's virtual CSS module (see
|
||||
* `tsdown.config.ts`: lightningcss minification, no CSS Modules hashing), so
|
||||
* the whole stylesheet arrives as a string. The merged client entry imports
|
||||
* `SETTINGS_CSS` and injects it through `ctx.effect` beside the vendored
|
||||
* client's own `<style>` element. No other file may import the stylesheet.
|
||||
*/
|
||||
import css from './settings.css?inline'
|
||||
|
||||
export const SETTINGS_CSS: string = css
|
||||
|
|
@ -0,0 +1,237 @@
|
|||
/**
|
||||
* Remote-SSH settings — presentational atoms.
|
||||
*
|
||||
* Every atom here is stateless: drafts, busy flags, confirmations and results
|
||||
* live in the root component (`index.tsx`), which keeps folding reversible and
|
||||
* guarantees that a collapse/refresh can never drop typed input.
|
||||
*
|
||||
* The atoms only use native elements plus React; the sole UI primitive this
|
||||
* face consumes is `Modal` (in `index.tsx`). Styling comes from
|
||||
* `.rsui-*` classes in `settings.css` (DSH theme tokens, light/dark aware).
|
||||
*/
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Icons (inline SVG — never emoji) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Disclosure chevron; the rotation is a restrained CSS transition. */
|
||||
export function ChevronIcon({ open }: { open: boolean }) {
|
||||
return (
|
||||
<span className={`rsui-chevron${open ? ' rsui-chevron-open' : ''}`} aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||
<path d="M4.5 6.25 8 9.75l3.5-3.5" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Feedback glyph. Icons never carry the only error signal: every feedback
|
||||
* block also renders a localized textual prefix (`common.error` /
|
||||
* `common.warning`) so colour-blind users get the same information.
|
||||
*/
|
||||
export function StatusIcon({ status }: { status: 'success' | 'warning' | 'error' | 'info' }) {
|
||||
if (status === 'success') {
|
||||
return (
|
||||
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||
<circle cx="8" cy="8" r="6.25" />
|
||||
<path d="m5 8.2 2.1 2.1L11.2 6" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (status === 'warning') {
|
||||
return (
|
||||
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||
<path d="M8 2.4 14.4 13.6H1.6L8 2.4Z" />
|
||||
<path d="M8 6.4v3.2" />
|
||||
<circle cx="8" cy="11.6" r="0.6" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||
<circle cx="8" cy="8" r="6.25" />
|
||||
<path d="M8 4.6v4.2" />
|
||||
<circle cx="8" cy="11.4" r="0.6" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Form controls */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export interface FieldProps {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
onBlur?: (() => void) | undefined
|
||||
placeholder?: string | undefined
|
||||
type?: 'text' | 'password' | undefined
|
||||
autoComplete?: string | undefined
|
||||
inputMode?: 'text' | 'numeric' | undefined
|
||||
/** `data-rsui-field` hook consumed by preview/acceptance scripts. */
|
||||
dataField?: string | undefined
|
||||
hint?: string | undefined
|
||||
error?: string | undefined
|
||||
mono?: boolean | undefined
|
||||
}
|
||||
|
||||
export function Field({ id, label, value, onChange, onBlur, placeholder, type, autoComplete, inputMode, dataField, hint, error, mono }: FieldProps) {
|
||||
const errorId = `${id}-error`
|
||||
const hintId = `${id}-hint`
|
||||
const describedBy = [error ? errorId : null, hint ? hintId : null].filter(Boolean).join(' ') || undefined
|
||||
return (
|
||||
<div className="rsui-field">
|
||||
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||
<input
|
||||
id={id}
|
||||
className={`rsui-input${mono ? ' rsui-input-mono' : ''}${error ? ' rsui-input-invalid' : ''}`}
|
||||
type={type ?? 'text'}
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
autoComplete={autoComplete}
|
||||
inputMode={inputMode}
|
||||
data-rsui-field={dataField}
|
||||
aria-invalid={error ? true : undefined}
|
||||
aria-describedby={describedBy}
|
||||
onChange={event => onChange(event.currentTarget.value)}
|
||||
onBlur={onBlur === undefined ? undefined : () => onBlur()}
|
||||
/>
|
||||
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||
{error ? <p className="rsui-error-text" id={errorId}>{error}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface TextAreaFieldProps {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
placeholder?: string | undefined
|
||||
dataField?: string | undefined
|
||||
hint?: string | undefined
|
||||
rows?: number | undefined
|
||||
}
|
||||
|
||||
export function TextAreaField({ id, label, value, onChange, placeholder, dataField, hint, rows }: TextAreaFieldProps) {
|
||||
const hintId = `${id}-hint`
|
||||
return (
|
||||
<div className="rsui-field">
|
||||
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||
<textarea
|
||||
id={id}
|
||||
className="rsui-textarea"
|
||||
value={value}
|
||||
rows={rows ?? 2}
|
||||
placeholder={placeholder}
|
||||
data-rsui-field={dataField}
|
||||
aria-describedby={hint ? hintId : undefined}
|
||||
onChange={event => onChange(event.currentTarget.value)}
|
||||
/>
|
||||
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface CheckFieldProps {
|
||||
id: string
|
||||
label: string
|
||||
checked: boolean
|
||||
onChange: (checked: boolean) => void
|
||||
dataField?: string | undefined
|
||||
}
|
||||
|
||||
export function CheckField({ id, label, checked, onChange, dataField }: CheckFieldProps) {
|
||||
return (
|
||||
<div className="rsui-check">
|
||||
<input
|
||||
id={id}
|
||||
className="rsui-check-input"
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
data-rsui-field={dataField}
|
||||
onChange={event => onChange(event.currentTarget.checked)}
|
||||
/>
|
||||
<label className="rsui-check-label" htmlFor={id}>{label}</label>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export interface SelectFieldProps {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
options: ReadonlyArray<{ value: string; label: string }>
|
||||
onChange: (value: string) => void
|
||||
dataField?: string | undefined
|
||||
hint?: string | undefined
|
||||
}
|
||||
|
||||
export function SelectField({ id, label, value, options, onChange, dataField, hint }: SelectFieldProps) {
|
||||
const hintId = `${id}-hint`
|
||||
return (
|
||||
<div className="rsui-field">
|
||||
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||
<select
|
||||
id={id}
|
||||
className="rsui-select"
|
||||
value={value}
|
||||
data-rsui-field={dataField}
|
||||
aria-describedby={hint ? hintId : undefined}
|
||||
onChange={event => onChange(event.currentTarget.value)}
|
||||
>
|
||||
{options.map(option => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Feedback blocks */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export type NoticeTone = 'success' | 'warning' | 'error' | 'info'
|
||||
|
||||
export interface NoticeProps {
|
||||
tone?: NoticeTone | undefined
|
||||
title: string
|
||||
/** Localized textual prefix, e.g. `common.error` / `common.warning`. */
|
||||
prefix?: string | undefined
|
||||
detail?: string | undefined
|
||||
action?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic status/alert block. `role` follows the tone (`alert` for errors,
|
||||
* `status` otherwise) so screen readers announce failures without relying on
|
||||
* the red colour alone.
|
||||
*/
|
||||
export function Notice({ tone, title, prefix, detail, action }: NoticeProps) {
|
||||
const kind = tone ?? 'info'
|
||||
return (
|
||||
<div className={`rsui-feedback rsui-feedback-${kind}`} role={kind === 'error' ? 'alert' : 'status'}>
|
||||
<StatusIcon status={kind} />
|
||||
<div className="rsui-feedback-body">
|
||||
<div className="rsui-feedback-title">
|
||||
{prefix ? <span className="rsui-feedback-prefix">{prefix}</span> : null}
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
{detail ? <pre className="rsui-feedback-pre">{detail}</pre> : null}
|
||||
{action ? <div className="rsui-feedback-actions">{action}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -3,12 +3,31 @@
|
|||
flex-direction:column;
|
||||
flex:1;
|
||||
width:100%;
|
||||
height:100%;
|
||||
max-height:100%;
|
||||
min-width:0;
|
||||
min-height:0;
|
||||
display:flex;
|
||||
overflow:hidden;
|
||||
}
|
||||
|
||||
/* The host sidebar scrollport lays its workspace region out as a max-content
|
||||
grid row. That makes the whole sidebar scroll as one block, so the plugin's
|
||||
own .wgRoot height cannot fill the viewport and the bottom dock ends up
|
||||
right after the tree instead of pinned to the sidebar bottom. Only when our
|
||||
tree is mounted, give the workspace region the remaining row; the tree body
|
||||
then owns the scrolling and .wgDock stays outside it. */
|
||||
[data-sidebar-scrollport]:has([class*="regionArea"] .wgRoot) {
|
||||
grid-template-rows:8px max-content 2px minmax(0, 1fr);
|
||||
align-content:stretch;
|
||||
overflow-y:hidden;
|
||||
}
|
||||
|
||||
[data-sidebar-scrollport] > [class*="regionArea"]:has(.wgRoot) {
|
||||
min-height:0;
|
||||
overflow:hidden;
|
||||
}
|
||||
|
||||
/* Remote SSH's legacy title matcher appends a globe to the first SVG it
|
||||
finds. Our row starts with a disclosure slot, so the badge can land on the
|
||||
wrong icon. Suppress only that injected decoration within this tree; keep
|
||||
|
|
@ -705,6 +724,22 @@
|
|||
word-break:break-word;
|
||||
}
|
||||
|
||||
.wgSmallAction {
|
||||
border:1px solid var(--dsw-border-1,#7f7f7f55);
|
||||
border-radius:4px;
|
||||
background:transparent;
|
||||
color:inherit;
|
||||
font:inherit;
|
||||
font-size:10.5px;
|
||||
line-height:1;
|
||||
padding:3px 6px;
|
||||
cursor:pointer;
|
||||
}
|
||||
|
||||
.wgSmallAction:hover {
|
||||
border-color:var(--dsw-accent,#4c8dff);
|
||||
}
|
||||
|
||||
.wgRail {
|
||||
flex-direction:column;
|
||||
align-items:center;
|
||||
|
|
@ -972,6 +1007,45 @@
|
|||
opacity:.75;
|
||||
}
|
||||
|
||||
/* Inline confirm shown when removing a remote member: the removal can take
|
||||
the backing workspace (and its sessions) with it, so the choice is explicit. */
|
||||
.wgFolderConfirm {
|
||||
display:flex;
|
||||
flex-wrap:wrap;
|
||||
align-items:center;
|
||||
gap:6px 10px;
|
||||
margin:4px 0 6px;
|
||||
padding:8px 10px;
|
||||
border:1px solid var(--dsw-alias-border-l2,#7f7f7f40);
|
||||
border-radius:8px;
|
||||
font-size:11.5px;
|
||||
line-height:1.5;
|
||||
}
|
||||
|
||||
.wgFolderConfirmText {
|
||||
flex:1 1 220px;
|
||||
}
|
||||
|
||||
.wgFolderConfirmActions {
|
||||
display:flex;
|
||||
gap:6px;
|
||||
}
|
||||
|
||||
.wgFolderConfirmButton {
|
||||
padding:3px 9px;
|
||||
border:1px solid var(--dsw-alias-border-l2,#7f7f7f40);
|
||||
border-radius:6px;
|
||||
background:transparent;
|
||||
color:inherit;
|
||||
font:inherit;
|
||||
cursor:pointer;
|
||||
}
|
||||
|
||||
.wgFolderConfirmButton[data-tone="danger"] {
|
||||
color:var(--dsw-alias-status-danger,#d13438);
|
||||
border-color:var(--dsw-alias-status-danger,#d13438);
|
||||
}
|
||||
|
||||
/* Add area: a segmented switch chooses local directory or cloud directory; the
|
||||
chosen action then owns its own row so nothing competes for its width. */
|
||||
.wgFolderAdd {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,11 @@ import { categoryAppearance, effectiveCategories, orderedWorkspaceIds, resolveCa
|
|||
import {
|
||||
absorbedWorkspaceIds,
|
||||
EMPTY_FOLDERS_DOCUMENT,
|
||||
effectiveFolders,
|
||||
entryFor,
|
||||
folderOfCwd,
|
||||
rootOf,
|
||||
samePath,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from '../core/folders.ts'
|
||||
|
|
@ -117,10 +121,8 @@ export interface WorkspaceGroupNode {
|
|||
sessions: readonly SessionNode[]
|
||||
/**
|
||||
* Folder rows, present only when the workspace carries at least one extra
|
||||
* folder: root first, then stored order. The base directory is never a row —
|
||||
* it is the workspace row itself, and its sessions live in {@link sessions}.
|
||||
* Absent means "this workspace has exactly one directory", the plain
|
||||
* pre-folders node shape.
|
||||
* folder: root first, then stored order, base included. Absent means "this
|
||||
* workspace has exactly one directory", the plain pre-folders node shape.
|
||||
*/
|
||||
folders?: readonly FolderNode[]
|
||||
}
|
||||
|
|
@ -310,16 +312,14 @@ function projectHoldsSession(
|
|||
return members.some(member => member.sessionIds.includes(sessionId))
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Display label of one folder: the last path segment. A drive root or the
|
||||
* POSIX root has no segment, so the whole path is the honest label.
|
||||
* Display label of one folder: the last path segment. A drive root (`C:\`) or
|
||||
* the POSIX root has no segment, so the whole path is the honest label.
|
||||
* @param path - absolute folder path.
|
||||
*/
|
||||
export function folderLabel(path: string): string {
|
||||
const trimmed = path.replace(/[/\u005C]+$/u, '')
|
||||
*/export function folderLabel(path: string): string {
|
||||
const trimmed = path.replace(/[/\\]+$/u, '')
|
||||
if (trimmed === '' || /^[A-Za-z]:$/u.test(trimmed)) return path
|
||||
const base = trimmed.split(/[/\u005C]/u).pop()
|
||||
const base = trimmed.split(/[/\\]/u).pop()
|
||||
return base !== undefined && base !== '' ? base : path
|
||||
}
|
||||
|
||||
|
|
@ -329,22 +329,93 @@ export function folderKey(workspaceId: WorkspaceId, path: string): string {
|
|||
}
|
||||
|
||||
/**
|
||||
* A workspace's extra folders are extra DIRECTORIES of the same project, not
|
||||
* extra session lists: every visible session of the workspace and of its member
|
||||
* workspaces renders on the one workspace row. Folder rows were removed on
|
||||
* request — a project reads as one row, and a cloud workspace's mirror id
|
||||
* (`wmvl31c7ilkuc`) never surfaces as a folder name.
|
||||
* @param sessions - every visible session of the workspace + its members.
|
||||
* Display labels for member folders.
|
||||
*
|
||||
* A cloud member's directory is a locally generated mirror id (`wabc123`), which
|
||||
* says nothing to the user: its REMOTE path or title is the honest label. Local
|
||||
* members keep the last path segment, like every other folder.
|
||||
* @param folders - per-workspace folders + members.
|
||||
*/
|
||||
function memberFolderLabels(entry: WorkspaceFolderEntry | undefined): Map<string, string> {
|
||||
const labels = new Map<string, string>()
|
||||
for (const member of entry?.members ?? []) {
|
||||
const label = member.kind === 'remote'
|
||||
? (member.title ?? folderLabel(member.remotePath ?? member.path))
|
||||
: folderLabel(member.path)
|
||||
if (label !== '') labels.set(member.path, label)
|
||||
}
|
||||
return labels
|
||||
}
|
||||
|
||||
/**
|
||||
* Split a workspace's visible sessions between its base directory and its extra
|
||||
* folders. Sessions keep the order they already had inside their owner, and a
|
||||
* workspace with no extra folder returns its sessions untouched — the pre-
|
||||
* folders node shape (no `folders` key at all).
|
||||
* @param workspaceId - owning workspace.
|
||||
* @param workspacePath - canonical directory (folder #0).
|
||||
* @param sessions - every visible session of the workspace, in host order.
|
||||
* @param list - sessions list snapshot (records each session's cwd).
|
||||
* @param entry - saved extra folders + root for this workspace.
|
||||
* @param collapsedFolders - collapsed folder-row keys. Undefined means "nothing
|
||||
* is collapsed", which is both the default view and what search uses so every
|
||||
* hit is visible without another click.
|
||||
*/
|
||||
function applyFolders(
|
||||
_workspaceId: WorkspaceId,
|
||||
_workspacePath: string,
|
||||
workspaceId: WorkspaceId,
|
||||
workspacePath: string,
|
||||
workspaceTitle: string,
|
||||
sessions: readonly SessionNode[],
|
||||
_list: SessionListState,
|
||||
_entry: WorkspaceFolderEntry | undefined,
|
||||
_collapsedFolders: ReadonlySet<string> | undefined,
|
||||
list: SessionListState,
|
||||
entry: WorkspaceFolderEntry | undefined,
|
||||
collapsedFolders: ReadonlySet<string> | undefined,
|
||||
): { sessions: readonly SessionNode[]; folders?: readonly FolderNode[] } {
|
||||
return { sessions }
|
||||
const labels = memberFolderLabels(entry)
|
||||
// The base row shows the project's confirmed display title (custom name or
|
||||
// remote directory name) instead of the local mirror basename. The path
|
||||
// remains the directory identity for file access; only the LABEL changes.
|
||||
const title = workspaceTitle.trim()
|
||||
if (title !== '') labels.set(workspacePath, title)
|
||||
const extras = effectiveFolders(workspacePath, entry).slice(1)
|
||||
if (extras.length === 0) return { sessions }
|
||||
const root = rootOf(workspacePath, entry)
|
||||
const base: SessionNode[] = []
|
||||
const byFolder = new Map<string, SessionNode[]>()
|
||||
for (const node of sessions) {
|
||||
const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry)
|
||||
if (samePath(owner, workspacePath)) {
|
||||
base.push(node)
|
||||
continue
|
||||
}
|
||||
const bucket = byFolder.get(owner)
|
||||
if (bucket === undefined) byFolder.set(owner, [node])
|
||||
else bucket.push(node)
|
||||
}
|
||||
const folderNode = (path: string, isBase: boolean): FolderNode => {
|
||||
const owned = isBase ? base : (byFolder.get(path) ?? [])
|
||||
return {
|
||||
path,
|
||||
label: labels.get(path) ?? folderLabel(path),
|
||||
isRoot: samePath(path, root),
|
||||
expanded: collapsedFolders === undefined || !collapsedFolders.has(folderKey(workspaceId, path)),
|
||||
isBase,
|
||||
// Every owned session is kept on the node so the row's count stays honest
|
||||
// while the folder is collapsed; the RowGroup does the hiding.
|
||||
sessions: owned,
|
||||
}
|
||||
}
|
||||
const folders: FolderNode[] = [
|
||||
folderNode(workspacePath, true),
|
||||
...extras.map(path => folderNode(path, false)),
|
||||
]
|
||||
// Root first, then stored order: moving the root row to the front keeps the
|
||||
// remaining rows (base included) in their stored order.
|
||||
const rootIndex = folders.findIndex(folder => folder.isRoot)
|
||||
if (rootIndex > 0) {
|
||||
const [rootFolder] = folders.splice(rootIndex, 1)
|
||||
if (rootFolder !== undefined) folders.unshift(rootFolder)
|
||||
}
|
||||
return { sessions: base, folders }
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -427,6 +498,7 @@ export function deriveGroups(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
@ -503,6 +575,7 @@ export function deriveTopLevel(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspaceId),
|
||||
|
|
@ -562,6 +635,7 @@ export function deriveDefaultWorkspace(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
sessions,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
@ -754,6 +828,7 @@ export function deriveSearchGroups(
|
|||
const partitioned = applyFolders(
|
||||
workspace.workspaceId,
|
||||
workspace.path,
|
||||
workspace.title,
|
||||
nodes,
|
||||
list,
|
||||
entryFor(folders, workspace.workspaceId as string),
|
||||
|
|
|
|||
|
|
@ -1,21 +1,20 @@
|
|||
/**
|
||||
* Recognising the Host's own default workspace ("默认工作区").
|
||||
*
|
||||
* 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.
|
||||
* 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 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.)
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/** Directory name the Host uses for its default workspace (host mirror). */
|
||||
|
|
@ -34,16 +33,14 @@ export interface DefaultWorkspaceIdentity {
|
|||
|
||||
/**
|
||||
* Whether a workspace snapshot is the Host's default workspace.
|
||||
* @param workspace - workspace snapshot (path is primary, title is a fallback
|
||||
* for path-less snapshots).
|
||||
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
|
||||
*/
|
||||
export function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean {
|
||||
if (workspace.title?.trim().toLowerCase() === DEFAULT_WORKSPACE_TITLE) return true
|
||||
const path = (workspace.path ?? '').replace(/[/\\]+$/u, '')
|
||||
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
|
||||
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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,12 +15,6 @@
|
|||
*
|
||||
* 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. */
|
||||
|
|
@ -70,11 +64,18 @@ export interface WorkspaceFolderEntry {
|
|||
/** The whole `workspace-groups.folders.json` document. */
|
||||
export interface FoldersDocument {
|
||||
readonly version: 1
|
||||
/**
|
||||
* Monotonic write counter, owned by the host: every accepted PUT bumps it
|
||||
* and a PUT whose revision does not match the stored one is rejected
|
||||
* (409), so two windows can no longer silently overwrite each other's
|
||||
* edits. Absent in documents written before revisions existed — read as 0.
|
||||
*/
|
||||
readonly revision?: number
|
||||
readonly workspaces: Readonly<Record<string, WorkspaceFolderEntry>>
|
||||
}
|
||||
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
export const EMPTY_FOLDERS_DOCUMENT: FoldersDocument = { version: 1, workspaces: {} }
|
||||
export const EMPTY_FOLDERS_DOCUMENT: FoldersDocument = { version: 1, revision: 0, workspaces: {} }
|
||||
|
||||
/** `C:\…` or `C:/…` — a drive-rooted Windows path. */
|
||||
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/u
|
||||
|
|
@ -82,30 +83,11 @@ 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. */
|
||||
export function isWindowsStyle(path: string): boolean {
|
||||
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.
|
||||
|
|
@ -113,68 +95,31 @@ export function isAbsoluteFolderPath(path: string): boolean {
|
|||
*/
|
||||
function withoutTrailingSeparator(path: string): string {
|
||||
if (isWindowsStyle(path)) {
|
||||
let value = path.replaceAll(SLASH, BACKSLASH)
|
||||
while (value.length > 3 && value.endsWith(BACKSLASH)) value = value.slice(0, -1)
|
||||
let value = path.replaceAll('/', '\\')
|
||||
while (value.length > 3 && value.endsWith('\\')) value = value.slice(0, -1)
|
||||
return value
|
||||
}
|
||||
let value = path
|
||||
while (value.length > 1 && value.endsWith(SLASH)) value = value.slice(0, -1)
|
||||
while (value.length > 1 && value.endsWith('/')) value = value.slice(0, -1)
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Comparison form of one path: trimmed, separator-normalized and, for Windows
|
||||
* spellings, lower-cased (drive letters and file names are case-insensitive
|
||||
* there). Trailing separators are dropped except for a drive/UNC/root prefix.
|
||||
* @param path - raw path as stored or picked.
|
||||
* @returns the canonical comparison form.
|
||||
*/
|
||||
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
|
||||
function canonicalPath(path: string): string {
|
||||
const trimmed = path.trim()
|
||||
const value = withoutTrailingSeparator(trimmed)
|
||||
return isWindowsStyle(trimmed) ? value.toLowerCase() : value
|
||||
}
|
||||
|
||||
/**
|
||||
* Path equality: case-insensitive for Windows-style paths, tolerant of
|
||||
* trailing separators, `.`/`..` segments and Unicode normalization, exact for
|
||||
* POSIX paths.
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
|
|
@ -225,6 +170,51 @@ export function memberOf(entry: WorkspaceFolderEntry | undefined, path: string):
|
|||
return (entry?.members ?? []).find(member => samePath(member.path, path))
|
||||
}
|
||||
|
||||
/**
|
||||
* Light canonical form of a REMOTE path (POSIX — the server's filesystem):
|
||||
* trimmed, trailing slashes removed. Deliberately string-only: the client
|
||||
* cannot resolve `~` or symlinks; the remote-ssh host canonicalizes fully
|
||||
* at registration time. This is the second line of defense, catching the
|
||||
* spelling variants a user can type into the add-cloud-folder dialog.
|
||||
* @param raw - remote path as typed or as stored.
|
||||
*/
|
||||
export function lightRemotePath(raw: string): string {
|
||||
const trimmed = raw.trim()
|
||||
return trimmed.length > 1 ? trimmed.replace(/\/+$/, '') : trimmed
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two remote paths name the same directory under {@link lightRemotePath}.
|
||||
* @param a - first remote path.
|
||||
* @param b - second remote path.
|
||||
*/
|
||||
export function sameRemotePath(a: string, b: string): boolean {
|
||||
return lightRemotePath(a) === lightRemotePath(b)
|
||||
}
|
||||
|
||||
/**
|
||||
* The member backed by one native workspace id, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param workspaceId - native workspace id backing the member.
|
||||
*/
|
||||
export function memberByWorkspaceId(entry: WorkspaceFolderEntry | undefined, workspaceId: string): FolderMember | undefined {
|
||||
return (entry?.members ?? []).find(member => member.workspaceId === workspaceId)
|
||||
}
|
||||
|
||||
/**
|
||||
* The remote member for one connection + remote directory, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param profileId - remote-ssh connection id.
|
||||
* @param remotePath - remote directory to look up.
|
||||
*/
|
||||
export function findRemoteMember(entry: WorkspaceFolderEntry | undefined, profileId: string, remotePath: string): FolderMember | undefined {
|
||||
return (entry?.members ?? []).find(member =>
|
||||
member.kind === 'remote'
|
||||
&& member.profileId === profileId
|
||||
&& member.remotePath !== undefined
|
||||
&& sameRemotePath(member.remotePath, remotePath))
|
||||
}
|
||||
|
||||
/**
|
||||
* Every member folder of one owner workspace, in stored order.
|
||||
* @param doc - folders document.
|
||||
|
|
@ -234,25 +224,6 @@ 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.
|
||||
*
|
||||
|
|
@ -263,9 +234,12 @@ export function validMembers(doc: FoldersDocument, ownerWorkspaceId: string): re
|
|||
* @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] of Object.entries(doc.workspaces)) {
|
||||
for (const member of validMembers(doc, ownerId)) {
|
||||
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
|
||||
if (!absorbed.has(member.workspaceId)) absorbed.set(member.workspaceId, ownerId)
|
||||
}
|
||||
}
|
||||
|
|
@ -298,9 +272,6 @@ 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.
|
||||
|
|
@ -318,7 +289,7 @@ export function folderOfCwd(
|
|||
for (const folder of effectiveFolders(workspacePath, entry)) {
|
||||
const root = canonicalPath(folder)
|
||||
if (root === '') continue
|
||||
const separator = isWindowsStyle(root) ? BACKSLASH : SLASH
|
||||
const separator = isWindowsStyle(root) ? '\\' : '/'
|
||||
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
|
||||
if (target !== root && !target.startsWith(prefix)) continue
|
||||
if (root.length > bestLength) {
|
||||
|
|
@ -353,11 +324,6 @@ 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.
|
||||
*/
|
||||
|
|
@ -365,6 +331,9 @@ 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
|
||||
// The root survives even when it names the member's own path: the member
|
||||
// replaces the plain folder at that path, so the root still resolves —
|
||||
// dropping it would silently change where new sessions start.
|
||||
const keepRoot = root === undefined ? {} : { root }
|
||||
return { folders: [...folders], members: [...members, member], ...keepRoot }
|
||||
}
|
||||
|
|
@ -373,9 +342,6 @@ 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.
|
||||
*/
|
||||
|
|
@ -407,8 +373,7 @@ 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}. `..` segments are collapsed on
|
||||
* both sides first, so a traversal spelling cannot fake containment.
|
||||
* separator and case rules as {@link samePath}.
|
||||
* @param path - candidate path.
|
||||
* @param base - containing directory.
|
||||
*/
|
||||
|
|
@ -417,7 +382,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) ? BACKSLASH : SLASH
|
||||
const separator = isWindowsStyle(root) ? '\\' : '/'
|
||||
const prefix = root.endsWith(separator) ? root : `${root}${separator}`
|
||||
return target.startsWith(prefix)
|
||||
}
|
||||
|
|
@ -439,12 +404,11 @@ 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_DRIVE_RELATIVE.test(raw)
|
||||
|| WINDOWS_UNC.test(raw) || raw.startsWith(SLASH)) return null
|
||||
if (WINDOWS_DRIVE.test(raw) || WINDOWS_UNC.test(raw) || raw.startsWith('/')) 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 ? BACKSLASH : SLASH
|
||||
const separator = windows ? '\\' : '/'
|
||||
return `${withoutTrailingSeparator(root)}${separator}${segments.join(separator)}`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -103,6 +103,13 @@ export interface GroupsConfig {
|
|||
* `appearance` (group color / icon / pin) is lost after a downgrade.
|
||||
*/
|
||||
export interface ManualGroups {
|
||||
/**
|
||||
* Monotonic write counter, owned by the host (same contract as the folder
|
||||
* overlay): a PUT whose revision does not match the stored one is
|
||||
* rejected with 409 instead of silently overwriting another window's
|
||||
* edits. Absent in files written before revisions existed — read as 0.
|
||||
*/
|
||||
revision?: number
|
||||
/**
|
||||
* Manually created category folder names. These have no rules — they render
|
||||
* even while empty (a new group appears before anything is dragged into
|
||||
|
|
|
|||
|
|
@ -151,22 +151,38 @@ export async function buildFarm(input: { name: string; folders: readonly unknown
|
|||
|
||||
const root = defaultFarmRoot()
|
||||
const path = join(root, farmDirectoryName(String(input.name)))
|
||||
const taken = new Set<string>()
|
||||
const links: FarmLink[] = targets.map(target => ({ name: linkNameFor(target, taken), target }))
|
||||
await mkdir(root, { recursive: true })
|
||||
try {
|
||||
await mkdir(path)
|
||||
} catch (error) {
|
||||
const code = (error as { code?: string }).code
|
||||
if (code === 'EEXIST') throw new Error(`farm: already exists, remove it first: ${path}`)
|
||||
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
if (code !== 'EEXIST') {
|
||||
throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
// Repeating the same gather is harmless: the workspace may already own this
|
||||
// farm. Reuse it only when every entry is the same link; anything else is a
|
||||
// real conflict and must not be silently merged into.
|
||||
const existing = (await readdir(path)).sort()
|
||||
const expected = links.map(link => link.name).sort()
|
||||
if (existing.length !== expected.length || existing.some((name, index) => name !== expected[index])) {
|
||||
throw new Error(`farm: already exists with different folders: ${path}`)
|
||||
}
|
||||
for (const link of links) {
|
||||
const entryPath = join(path, link.name)
|
||||
const info = await lstat(entryPath)
|
||||
if (!info.isSymbolicLink()) throw new Error(`farm: already exists, entry is not a link: ${entryPath}`)
|
||||
const actual = await realpath(entryPath)
|
||||
const same = WINDOWS ? actual.toLowerCase() === link.target.toLowerCase() : actual === link.target
|
||||
if (!same) throw new Error(`farm: already exists, link points elsewhere: ${entryPath}`)
|
||||
}
|
||||
return { path, links }
|
||||
}
|
||||
|
||||
const taken = new Set<string>()
|
||||
const links: FarmLink[] = []
|
||||
try {
|
||||
for (const target of targets) {
|
||||
const name = linkNameFor(target, taken)
|
||||
await symlink(target, join(path, name), WINDOWS ? 'junction' : 'dir')
|
||||
links.push({ name, target })
|
||||
for (const link of links) {
|
||||
await symlink(link.target, join(path, link.name), WINDOWS ? 'junction' : 'dir')
|
||||
}
|
||||
} catch (error) {
|
||||
await discard(path)
|
||||
|
|
|
|||
|
|
@ -7,25 +7,16 @@
|
|||
* 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) — 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).
|
||||
* replacing it, atomically: temp file + fsync + rename) and reads tolerate
|
||||
* hand-edited content (junk entries are dropped instead of thrown), for the
|
||||
* same reason the manual overlay does: a stale or malformed sidecar must never
|
||||
* freeze the tree.
|
||||
*/
|
||||
import { 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,
|
||||
|
|
@ -42,6 +33,15 @@ 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,59 +60,34 @@ export function defaultFoldersPath(): string {
|
|||
* folders must be subdirectories of the mirror, because only those also exist on
|
||||
* the remote side.
|
||||
*
|
||||
* 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.
|
||||
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
|
||||
* here too — a mismatch would silently disable the distinction.
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
export function isAbsoluteFolderPath(path: string): boolean {
|
||||
return isAbsoluteFolderPathCore(path)
|
||||
}
|
||||
|
||||
/** Platform-specific test for a LOCAL path used by the remote-hint endpoint. */
|
||||
function isAbsoluteHostPath(path: string): boolean {
|
||||
return process.platform === 'win32'
|
||||
? /^[A-Za-z]:[\\/]/u.test(path) || path.startsWith('\\\\')
|
||||
: path.startsWith('/')
|
||||
? WINDOWS_DRIVE.test(path) || WINDOWS_UNC.test(path)
|
||||
: POSIX_ABSOLUTE.test(path)
|
||||
}
|
||||
|
||||
/** Validate a local path for the read-only remote hint endpoint. */
|
||||
export function validateRemoteHintPath(path: unknown): string {
|
||||
// A UNC path (\\server\share) would make the lstat walk below reach out
|
||||
// over SMB to a machine the caller named — a local hint check must stay
|
||||
// local, so this rejection comes before the shape checks.
|
||||
if (typeof path === 'string' && path.startsWith('\\\\')) {
|
||||
throw new Error('remote hint path must not be a UNC path')
|
||||
}
|
||||
if (typeof path !== 'string' || path.length === 0 || path.length > FOLDER_PATH_LIMIT
|
||||
|| path.includes('\u0000') || !isAbsoluteHostPath(path)) {
|
||||
|| path.includes('\u0000') || !isAbsoluteFolderPath(path)) {
|
||||
throw new Error('remote hint path must be an absolute host path without NUL, at most 1024 characters')
|
||||
}
|
||||
return path
|
||||
|
|
@ -144,19 +119,7 @@ function invalid(detail: string): never {
|
|||
throw new Error(`${FOLDERS_FILE_NAME}: ${detail}`)
|
||||
}
|
||||
|
||||
/** 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.
|
||||
*/
|
||||
/** Trim one optional free-form string field, dropping it when unusable. */
|
||||
function optionalText(value: unknown, limit: number, fail: (detail: string) => void): string | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (typeof value !== 'string') {
|
||||
|
|
@ -164,10 +127,7 @@ function optionalText(value: unknown, limit: number, fail: (detail: string) => v
|
|||
return undefined
|
||||
}
|
||||
const text = value.trim()
|
||||
if (text === '' || text.length > limit || text.includes('\u0000')) {
|
||||
fail(`member text fields must be 1-${limit} characters without NUL`)
|
||||
return undefined
|
||||
}
|
||||
if (text === '' || text.length > limit || text.includes('\u0000')) return undefined
|
||||
return text
|
||||
}
|
||||
|
||||
|
|
@ -181,8 +141,6 @@ 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.
|
||||
*/
|
||||
|
|
@ -191,8 +149,6 @@ 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)) {
|
||||
|
|
@ -214,8 +170,8 @@ function parseMember(
|
|||
fail(`member folder path "${path}" must be absolute`)
|
||||
return undefined
|
||||
}
|
||||
if (hasTraversalSegment(path)) {
|
||||
fail(`member folder path "${path}" must not contain ".." segments`)
|
||||
if (path.split(/[\\/]/).some(segment => segment === '.' || segment === '..')) {
|
||||
fail(`member folder path "${path}" must not contain "." or ".." segments`)
|
||||
return undefined
|
||||
}
|
||||
if (folders.some(folder => samePath(folder, path)) || members.some(member => samePath(member.path, path))) {
|
||||
|
|
@ -244,16 +200,6 @@ 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
|
||||
|
|
@ -290,22 +236,15 @@ 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}`)
|
||||
|
|
@ -315,17 +254,20 @@ function parseFolderEntry(
|
|||
return undefined
|
||||
}
|
||||
const source = value as Record<string, unknown>
|
||||
if (source.folders !== undefined && !Array.isArray(source.folders)) {
|
||||
if (source.folders === undefined) {
|
||||
fail('folders is required')
|
||||
return undefined
|
||||
}
|
||||
if (!Array.isArray(source.folders)) {
|
||||
fail('folders must be a list')
|
||||
return undefined
|
||||
}
|
||||
const rawFolders: readonly unknown[] = Array.isArray(source.folders) ? source.folders : []
|
||||
if (strict && rawFolders.length > FOLDERS_PER_WORKSPACE_LIMIT) {
|
||||
if (strict && source.folders.length > FOLDERS_PER_WORKSPACE_LIMIT) {
|
||||
invalid(`workspace "${workspaceId}": at most ${FOLDERS_PER_WORKSPACE_LIMIT} folders`)
|
||||
}
|
||||
|
||||
const folders: string[] = []
|
||||
for (const candidate of rawFolders) {
|
||||
for (const candidate of source.folders) {
|
||||
if (typeof candidate !== 'string') {
|
||||
fail('folder paths must be strings')
|
||||
continue
|
||||
|
|
@ -347,8 +289,8 @@ function parseFolderEntry(
|
|||
fail(`folder path "${path}" must be absolute`)
|
||||
continue
|
||||
}
|
||||
if (hasTraversalSegment(path)) {
|
||||
fail(`folder path "${path}" must not contain ".." segments`)
|
||||
if (path.split(/[\\/]/).some(segment => segment === '.' || segment === '..')) {
|
||||
fail(`folder path "${path}" must not contain "." or ".." segments`)
|
||||
continue
|
||||
}
|
||||
if (folders.some(existing => samePath(existing, path))) {
|
||||
|
|
@ -371,7 +313,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, strict, remoteBase, fail)
|
||||
const member = parseMember(candidate, workspaceId, folders, members, fail)
|
||||
if (member !== undefined) members.push(member)
|
||||
if (members.length >= MEMBERS_PER_WORKSPACE_LIMIT) break
|
||||
}
|
||||
|
|
@ -395,70 +337,51 @@ 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 — but ONLY when the file
|
||||
* could actually be read and parsed; `readFoldersState` is responsible for
|
||||
* reporting a read/parse failure as an error.
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
export function parseFoldersDocument(raw: unknown): FoldersDocument {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return EMPTY_FOLDERS_DOCUMENT
|
||||
const source = raw as Record<string, unknown>
|
||||
if (source.version !== 1) return EMPTY_FOLDERS_DOCUMENT
|
||||
const revision = readRevision(source.revision)
|
||||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
return { version: 1, workspaces: {} }
|
||||
return { version: 1, revision, workspaces: {} }
|
||||
}
|
||||
const remoteBase = defaultRemoteMirrorBase()
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
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)
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT) continue
|
||||
// "__proto__" assigned onto a plain record would mutate its prototype
|
||||
// instead of storing an entry — never let it become a key.
|
||||
if (workspaceId === '__proto__') continue
|
||||
const entry = parseFolderEntry(value, workspaceId, false)
|
||||
if (entry !== undefined) workspaces[workspaceId] = entry
|
||||
}
|
||||
return dropNestedMembers({ version: 1, workspaces })
|
||||
return { version: 1, revision, workspaces }
|
||||
}
|
||||
|
||||
/**
|
||||
* The document's write counter: a non-negative safe integer, else 0. Tolerant
|
||||
* on purpose — reads must survive hand-edited sidecars; the strict writer
|
||||
* below rejects bad values instead of letting them through.
|
||||
* @param value - the raw `revision` field.
|
||||
*/
|
||||
export function readRevision(value: unknown): number {
|
||||
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, the root
|
||||
* membership or cross-workspace references are wrong.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
export function validateFoldersDocument(raw: unknown, remoteBase = defaultRemoteMirrorBase()): FoldersDocument {
|
||||
export function validateFoldersDocument(raw: unknown): FoldersDocument {
|
||||
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
||||
invalid('top-level value must be a mapping')
|
||||
}
|
||||
|
|
@ -467,102 +390,45 @@ export function validateFoldersDocument(raw: unknown, remoteBase = defaultRemote
|
|||
if (typeof source.workspaces !== 'object' || source.workspaces === null || Array.isArray(source.workspaces)) {
|
||||
invalid('workspaces must be a mapping')
|
||||
}
|
||||
if (source.revision !== undefined
|
||||
&& (typeof source.revision !== 'number' || !Number.isSafeInteger(source.revision) || source.revision < 0)) {
|
||||
invalid('revision must be a non-negative integer')
|
||||
}
|
||||
const workspaces: Record<string, WorkspaceFolderEntry> = {}
|
||||
for (const [rawId, value] of Object.entries(source.workspaces)) {
|
||||
const workspaceId = rawId.trim()
|
||||
if (workspaceId === '' || rawId.length > WORKSPACE_ID_LIMIT) {
|
||||
for (const [workspaceId, value] of Object.entries(source.workspaces)) {
|
||||
if (workspaceId.trim() === '' || workspaceId.length > WORKSPACE_ID_LIMIT || workspaceId === '__proto__') {
|
||||
invalid(`workspace ids must be non-empty strings of at most ${WORKSPACE_ID_LIMIT} characters`)
|
||||
}
|
||||
if (workspaces[workspaceId] !== undefined) invalid(`duplicate workspace id "${workspaceId}"`)
|
||||
const entry = parseFolderEntry(value, workspaceId, true, remoteBase)
|
||||
const entry = parseFolderEntry(value, workspaceId, true)
|
||||
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)
|
||||
return { version: 1, revision: readRevision(source.revision), workspaces }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
export async function readFoldersDocument(path: string): Promise<FoldersDocument> {
|
||||
try {
|
||||
return (await readFoldersState(path)).document
|
||||
const text = await readFile(path, 'utf8')
|
||||
return parseFoldersDocument(JSON.parse(text))
|
||||
} catch {
|
||||
return EMPTY_FOLDERS_DOCUMENT
|
||||
}
|
||||
}
|
||||
|
||||
/** Atomically replace `path` with `json` (temp + fsync + rename). */
|
||||
async function atomicWrite(path: string, json: string): Promise<void> {
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
export async function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void> {
|
||||
const json = `${JSON.stringify(document, null, 2)}\n`
|
||||
await mkdir(dirname(path), { recursive: true })
|
||||
const tmp = `${path}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`
|
||||
const handle = await open(tmp, 'w')
|
||||
|
|
@ -581,65 +447,6 @@ async function atomicWrite(path: string, json: string): Promise<void> {
|
|||
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
|
||||
|
|
@ -652,20 +459,12 @@ export async function replaceFoldersDocument(
|
|||
*
|
||||
* 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, absolute or escaping subpath.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
export function remoteSubpath(remotePath: string, relativePath: string): string | null {
|
||||
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, '')
|
||||
const rel = relativePath.trim().replace(/\\/gu, '/').replace(/^\/+|\/+$/gu, '')
|
||||
if (rel === '') return null
|
||||
if (rel.split('/').some(segment => segment === '..' || segment === '.')) return null
|
||||
const base = remotePath === '~' ? '~' : remotePath.replace(/\/+$/u, '')
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ export function parseManualGroups(raw: unknown): ManualGroups {
|
|||
throw new Error('workspace-groups.manual.json: assignments must be a mapping')
|
||||
}
|
||||
for (const [workspaceId, category] of Object.entries(source.assignments)) {
|
||||
if (workspaceId === '__proto__') continue // assigning it would mutate the record's prototype
|
||||
if (workspaceId.trim() === '') {
|
||||
throw new Error('workspace-groups.manual.json: assignment keys must be non-empty')
|
||||
}
|
||||
|
|
@ -90,6 +91,9 @@ export function parseManualGroups(raw: unknown): ManualGroups {
|
|||
}
|
||||
|
||||
const manual: ManualGroups = { categories, assignments }
|
||||
if (typeof source.revision === 'number' && Number.isSafeInteger(source.revision) && source.revision >= 0) {
|
||||
manual.revision = source.revision
|
||||
}
|
||||
|
||||
if (source.categoryOrder !== undefined) {
|
||||
manual.categoryOrder = parseStringList(source.categoryOrder, 'categoryOrder', true)
|
||||
|
|
@ -103,6 +107,7 @@ export function parseManualGroups(raw: unknown): ManualGroups {
|
|||
}
|
||||
const renamed: Record<string, string> = {}
|
||||
for (const [original, display] of Object.entries(source.renamed)) {
|
||||
if (original === '__proto__') continue // assigning it would mutate the record's prototype
|
||||
if (original.trim() === '') throw new Error('workspace-groups.manual.json: renamed keys must be non-empty')
|
||||
if (typeof display !== 'string' || display.trim() === '') {
|
||||
throw new Error(`workspace-groups.manual.json: renamed "${original}" must be a non-empty string`)
|
||||
|
|
@ -117,6 +122,7 @@ export function parseManualGroups(raw: unknown): ManualGroups {
|
|||
}
|
||||
const appearance: Record<string, CategoryAppearance> = {}
|
||||
for (const [key, value] of Object.entries(source.appearance)) {
|
||||
if (key === '__proto__') continue // assigning it would mutate the record's prototype
|
||||
if (key.trim() === '') throw new Error('workspace-groups.manual.json: appearance keys must be non-empty')
|
||||
const parsed = parseAppearance(value, key)
|
||||
if (parsed !== undefined) appearance[key.trim()] = parsed
|
||||
|
|
@ -129,6 +135,7 @@ export function parseManualGroups(raw: unknown): ManualGroups {
|
|||
}
|
||||
const workspaceOrder: Record<string, string[]> = {}
|
||||
for (const [categoryKey, ids] of Object.entries(source.workspaceOrder)) {
|
||||
if (categoryKey === '__proto__') continue // assigning it would mutate the record's prototype
|
||||
if (categoryKey.trim() === '') {
|
||||
throw new Error('workspace-groups.manual.json: workspaceOrder keys must be non-empty')
|
||||
}
|
||||
|
|
|
|||
186
src/index.ts
|
|
@ -13,23 +13,15 @@
|
|||
* (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, a `revision` (ETag) and remote-mirror
|
||||
* diagnostics. A read/parse failure is a 500, never an empty document.
|
||||
* plus each workspace's root folder.
|
||||
* - `PUT /workspace-groups/folders` — replace the folder overlay whole.
|
||||
* 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.
|
||||
* Strictly validated (absolute paths, no duplicates, root membership) and
|
||||
* written atomically; the saved document is echoed back.
|
||||
* - `POST /workspace-groups/folders` — deprecated; returns 410 without reading
|
||||
* the payload or touching remote-ssh records.
|
||||
*
|
||||
* - `GET /workspace-groups/remote-hint?path=...` — presence-only marker hint
|
||||
* at the requested absolute path or ancestors; never returns marker content;
|
||||
* - `POST /workspace-groups/farm` — gather several folders into one real
|
||||
* directory of links, so a single session can reach all of them;
|
||||
* - `DELETE /workspace-groups/farm?path=...` — remove such a farm; only links
|
||||
* are unlinked, meeting a real directory aborts.
|
||||
* at the requested absolute path or ancestors; never returns marker content.
|
||||
*
|
||||
* Core workspace.json / session storage is never touched.
|
||||
*/
|
||||
|
|
@ -54,14 +46,12 @@ import {
|
|||
} from './host-tabs.ts'
|
||||
import {
|
||||
defaultFoldersPath,
|
||||
defaultRemoteMirrorBase,
|
||||
hasRemoteMarkerHint,
|
||||
readFoldersState,
|
||||
remoteMirrorBaseDiagnostic,
|
||||
replaceFoldersDocument,
|
||||
readFoldersDocument,
|
||||
validateFoldersDocument,
|
||||
validateRemoteHintPath,
|
||||
type FoldersState,
|
||||
type RemoteMirrorBaseDiagnostic,
|
||||
writeFoldersDocument,
|
||||
} from './host-folders.ts'
|
||||
import { buildFarm, removeFarm } from './host-farm.ts'
|
||||
|
||||
|
|
@ -71,20 +61,9 @@ export const name = 'workspace-groups-local'
|
|||
/** Services required before mounting: the webserver route. */
|
||||
export const inject = ['webServer']
|
||||
|
||||
/** Cap on the manual/tabs PUT body: those overlays are tiny. */
|
||||
/** Cap on the PUT body: the overlay is tiny; anything bigger is a client bug. */
|
||||
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) {
|
||||
|
|
@ -140,51 +119,6 @@ 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()
|
||||
|
|
@ -302,13 +236,33 @@ export function apply(ctx: GroupsContext): void {
|
|||
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
// Optimistic concurrency, same contract as the folder overlay: a stale
|
||||
// writer gets the current overlay back with 409 instead of silently
|
||||
// overwriting another window's edits.
|
||||
let current
|
||||
try {
|
||||
await writeManualGroups(manualPath, manual)
|
||||
current = await readManualGroups(manualPath)
|
||||
} catch {
|
||||
current = { categories: [], assignments: {} }
|
||||
}
|
||||
if ((manual.revision ?? 0) !== (current.revision ?? 0)) {
|
||||
const body = JSON.stringify({ manual: current })
|
||||
res.writeHead(409, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
return
|
||||
}
|
||||
const stored = { ...manual, revision: (current.revision ?? 0) + 1 }
|
||||
try {
|
||||
await writeManualGroups(manualPath, stored)
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write manual overlay: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const body = JSON.stringify({ ok: true })
|
||||
const body = JSON.stringify({ ok: true, manual: stored })
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
|
|
@ -356,19 +310,18 @@ export function apply(ctx: GroupsContext): void {
|
|||
path: '/workspace-groups/folders',
|
||||
handler: async (req, res) => {
|
||||
if (req.method === 'GET' || req.method === 'HEAD') {
|
||||
// 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)
|
||||
// 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)
|
||||
return
|
||||
}
|
||||
if (req.method === 'POST') {
|
||||
|
|
@ -383,47 +336,50 @@ export function apply(ctx: GroupsContext): void {
|
|||
}
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES))
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
||||
} catch (error) {
|
||||
const status = error instanceof HttpError ? error.status : 400
|
||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const diagnostic = remoteMirrorBaseDiagnostic()
|
||||
let document
|
||||
try {
|
||||
// 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)
|
||||
document = validateFoldersDocument(raw)
|
||||
} 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
|
||||
// Optimistic concurrency: the write must build on the current stored
|
||||
// revision. A stale writer (a second window holding an older document)
|
||||
// gets the current document back with 409 instead of silently
|
||||
// overwriting the other window's edits.
|
||||
const current = await readFoldersDocument(foldersPath)
|
||||
if ((document.revision ?? 0) !== (current.revision ?? 0)) {
|
||||
const body = JSON.stringify(current)
|
||||
res.writeHead(409, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
return
|
||||
}
|
||||
const stored = { ...document, revision: (current.revision ?? 0) + 1 }
|
||||
try {
|
||||
// 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)
|
||||
await writeFoldersDocument(foldersPath, stored)
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to write folder overlay: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
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)
|
||||
// Echo the normalized document: the client renders exactly what the host
|
||||
// accepted, not its own (possibly trimmed) guess.
|
||||
const body = JSON.stringify(stored)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(body)
|
||||
},
|
||||
}), '@dsh-xhl/workspace-groups: /workspace-groups/folders route')
|
||||
|
||||
|
|
@ -434,7 +390,7 @@ export function apply(ctx: GroupsContext): void {
|
|||
if (req.method === 'POST') {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(await readBody(req, MAX_FOLDERS_BODY_BYTES))
|
||||
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES))
|
||||
} catch (error) {
|
||||
const status = error instanceof HttpError ? error.status : 400
|
||||
writeError(res, status, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
|
||||
|
|
|
|||
|
|
@ -98,13 +98,24 @@ describe('farm validation', () => {
|
|||
.rejects.toThrow(/does not exist/u)
|
||||
})
|
||||
|
||||
it('refuses to reuse an existing farm', async () => {
|
||||
it('reuses an existing farm with the same folders', async () => {
|
||||
const alpha = await folder('alpha')
|
||||
const beta = await folder('beta')
|
||||
await buildFarm({ name: 'same', folders: [alpha, beta] })
|
||||
const first = await buildFarm({ name: 'same', folders: [alpha, beta] })
|
||||
|
||||
await expect(buildFarm({ name: 'same', folders: [alpha, beta] }))
|
||||
.rejects.toThrow(/already exists/u)
|
||||
const again = await buildFarm({ name: 'same', folders: [alpha, beta] })
|
||||
expect(again.path).toBe(first.path)
|
||||
expect(again.links).toEqual(first.links)
|
||||
})
|
||||
|
||||
it('refuses to reuse a farm whose folders changed', async () => {
|
||||
const alpha = await folder('alpha')
|
||||
const beta = await folder('beta')
|
||||
const gamma = await folder('gamma')
|
||||
await buildFarm({ name: 'same-different', folders: [alpha, beta] })
|
||||
|
||||
await expect(buildFarm({ name: 'same-different', folders: [alpha, gamma] }))
|
||||
.rejects.toThrow(/different folders/u)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,296 +0,0 @@
|
|||
/**
|
||||
* 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)
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
// @vitest-environment jsdom
|
||||
import React, { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ComponentProps, ReactNode } from 'react'
|
||||
import { FoldersDialog } from '../src/client/FoldersDialog.tsx'
|
||||
import { zh } from '../src/client/locales.ts'
|
||||
|
||||
vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({
|
||||
Button: ({ children, variant: _variant, ...props }: any) => React.createElement('button', props, children),
|
||||
Modal: ({ children, footer }: { children: ReactNode; footer: ReactNode }) => React.createElement('div', null, children, footer),
|
||||
IconFolderOpenOutlineRegular: () => null,
|
||||
IconTrashOutlineRegular: () => null,
|
||||
}))
|
||||
|
||||
Object.assign(globalThis, { React, IS_REACT_ACT_ENVIRONMENT: true })
|
||||
let root: Root | undefined
|
||||
let container: HTMLDivElement
|
||||
const memberPath = 'C:\\other'
|
||||
function mount(overrides: Partial<ComponentProps<typeof FoldersDialog>> = {}) {
|
||||
container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
root = createRoot(container)
|
||||
const props = {
|
||||
workspace: { workspaceId: 'owner', title: 'Owner', path: 'C:\\owner' },
|
||||
entry: { folders: [], members: [{ path: memberPath, workspaceId: 'member', kind: 'local' }] },
|
||||
t: (key: keyof typeof zh) => zh[key], busy: false, canOpen: false, remote: false,
|
||||
ownerRemotePath: null, profiles: null, profilesError: null, knownWorkspaceIds: ['owner', 'member'],
|
||||
onClose: vi.fn(), onBuildFarm: vi.fn(), onAddFolder: vi.fn(), onAddRemote: vi.fn(),
|
||||
onAddSubpath: vi.fn(), onSetRoot: vi.fn(), onRemove: vi.fn(), onOpenFolder: vi.fn(),
|
||||
...overrides,
|
||||
} as unknown as ComponentProps<typeof FoldersDialog>
|
||||
act(() => { root!.render(React.createElement(FoldersDialog, props)) })
|
||||
return props
|
||||
}
|
||||
function button(text: string, parent: ParentNode = container): HTMLButtonElement {
|
||||
const found = [...parent.querySelectorAll('button')].find(b => b.textContent?.endsWith(text))
|
||||
expect(found, text).toBeDefined()
|
||||
return found!
|
||||
}
|
||||
function click(element: HTMLElement) { act(() => { element.click() }) }
|
||||
function removeButton() { return container.querySelector<HTMLButtonElement>('button[aria-label^="从工作区移除"]')! }
|
||||
afterEach(() => { act(() => { root?.unmount() }); container?.remove(); root = undefined })
|
||||
|
||||
describe('folder lifecycle decisions', () => {
|
||||
it('farm preview and cancel perform no creation or removal', () => {
|
||||
const props = mount()
|
||||
click(button(zh['folder.mergeAction']))
|
||||
expect(container.textContent).toContain(zh['folder.mergeConfirm'])
|
||||
expect(container.textContent).toContain(memberPath)
|
||||
expect(props.onBuildFarm).not.toHaveBeenCalled()
|
||||
click(button(zh.cancel, container.querySelector('[role="alert"]')!))
|
||||
expect(props.onBuildFarm).not.toHaveBeenCalled()
|
||||
expect(props.onRemove).not.toHaveBeenCalled()
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('double confirmation in the same render creates only once', () => {
|
||||
const props = mount()
|
||||
click(button(zh['folder.mergeAction']))
|
||||
const confirm = button(zh['folder.mergeAction'], container.querySelector('[role="alert"]')!)
|
||||
act(() => { confirm.click(); confirm.click() })
|
||||
expect(props.onBuildFarm).toHaveBeenCalledTimes(1)
|
||||
expect(props.onRemove).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('local member cancellation keeps the association, confirmation only detaches', () => {
|
||||
const props = mount()
|
||||
click(removeButton())
|
||||
expect(container.textContent).toContain(zh['folder.removeMemberPrompt'])
|
||||
expect(container.textContent).not.toContain(zh['folder.removeRemoteDelete'])
|
||||
click(button(zh.cancel))
|
||||
expect(props.onRemove).not.toHaveBeenCalled()
|
||||
click(removeButton())
|
||||
click(button(zh['folder.removeRemoteOnly']))
|
||||
expect(props.onRemove).toHaveBeenCalledExactlyOnceWith(memberPath, false)
|
||||
})
|
||||
|
||||
it('sidebar initial removal uses the same confirmation and preserves remote workspace by default', () => {
|
||||
const props = mount({ initialRemovePath: memberPath, entry: { folders: [], members: [{
|
||||
path: memberPath, workspaceId: 'member', kind: 'remote', remotePath: '/srv/project',
|
||||
profileId: 'ssh', recordId: 'record',
|
||||
}] } })
|
||||
expect(container.textContent).toContain(zh['folder.removeMemberPrompt'])
|
||||
expect(container.textContent).toContain(zh['folder.removeRemotePrompt'])
|
||||
expect(props.onRemove).not.toHaveBeenCalled()
|
||||
click(button(zh['folder.removeRemoteOnly']))
|
||||
expect(props.onRemove).toHaveBeenCalledExactlyOnceWith(memberPath, false)
|
||||
})
|
||||
|
||||
it('missing member does not promise a recreated independent entry', () => {
|
||||
const props = mount({ initialRemovePath: memberPath, knownWorkspaceIds: ['owner'] })
|
||||
expect(container.textContent).toContain(zh['folder.removeMissingPrompt'])
|
||||
expect(container.textContent).not.toContain(zh['folder.removeMemberPrompt'])
|
||||
click(button(zh['folder.removeRemoteOnly']))
|
||||
expect(props.onRemove).toHaveBeenCalledExactlyOnceWith(memberPath, false)
|
||||
})
|
||||
|
||||
it('plain subfolder removal needs no workspace decision', () => {
|
||||
const props = mount({ entry: { folders: ['C:\\owner\\child'] } })
|
||||
click(removeButton())
|
||||
expect(props.onRemove).toHaveBeenCalledExactlyOnceWith('C:\\owner\\child', false)
|
||||
})
|
||||
})
|
||||
|
|
@ -1,129 +1,76 @@
|
|||
/**
|
||||
* 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.
|
||||
* Client persist-layer tests: the wire document carries the host-owned
|
||||
* revision, a successful save adopts the host echo, a stale save surfaces a
|
||||
* typed conflict with the host's current document, and the remote-record
|
||||
* deletion helper speaks the SSH plugin's RPC shape.
|
||||
*/
|
||||
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'
|
||||
import { FoldersConflictError, loadFolders, saveFolders } from '../src/client/folders-persist.ts'
|
||||
import { deleteRemoteWorkspaceRecord } from '../src/client/folder-directory.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)
|
||||
function stubFetch(status: number, body: unknown, capture?: (url: string, init?: RequestInit) => void): typeof fetch {
|
||||
return (async (url: string, init?: RequestInit) => {
|
||||
capture?.(url, init)
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: async () => body,
|
||||
} as unknown as 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')
|
||||
describe('loadFolders revision', () => {
|
||||
it('carries the stored revision, defaulting an absent one to 0', async () => {
|
||||
const withRevision = await loadFolders(stubFetch(200, { version: 1, revision: 7, workspaces: {} }))
|
||||
expect(withRevision.ok).toBe(true)
|
||||
expect(withRevision.document.revision).toBe(7)
|
||||
const without = await loadFolders(stubFetch(200, { version: 1, workspaces: {} }))
|
||||
expect(without.ok).toBe(true)
|
||||
expect(without.document.revision).toBe(0)
|
||||
})
|
||||
|
||||
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')
|
||||
it('does not turn HTTP 503 or malformed JSON into a successful empty document', async () => {
|
||||
const unavailable = await loadFolders(stubFetch(503, {}))
|
||||
expect(unavailable.ok).toBe(false)
|
||||
expect(unavailable.error).toContain('503')
|
||||
const malformed = await loadFolders(stubFetch(200, { version: 2, workspaces: {} }))
|
||||
expect(malformed.ok).toBe(false)
|
||||
expect(malformed.error).toContain('格式无效')
|
||||
})
|
||||
})
|
||||
|
||||
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('resolves with the host echo (bumped revision)', async () => {
|
||||
const echo = { version: 1, revision: 3, workspaces: { a: { folders: ['/x'] } } }
|
||||
const stored = await saveFolders({ version: 1, revision: 2, workspaces: { a: { folders: ['/x'] } } }, stubFetch(200, echo))
|
||||
expect(stored).toEqual(echo)
|
||||
})
|
||||
|
||||
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')
|
||||
it('rejects with FoldersConflictError carrying the current document on 409', async () => {
|
||||
const current = { version: 1, revision: 5, workspaces: {} }
|
||||
const attempted = { version: 1, revision: 2, workspaces: { a: { folders: ['/x'] } } }
|
||||
const failure = await saveFolders(attempted, stubFetch(409, current)).catch((e: unknown) => e)
|
||||
expect(failure).toBeInstanceOf(FoldersConflictError)
|
||||
expect((failure as FoldersConflictError).current).toEqual(current)
|
||||
expect((failure as FoldersConflictError).attempted).toEqual(attempted)
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteRemoteWorkspaceRecord', () => {
|
||||
it('posts deleteWorkspace with the record id and resolves on the ok envelope', async () => {
|
||||
let url = ''
|
||||
let body: unknown
|
||||
await deleteRemoteWorkspaceRecord('rec-1', stubFetch(200, { ok: true, value: { ok: true } }, (u, init) => {
|
||||
url = u
|
||||
body = JSON.parse(String(init?.body))
|
||||
}))
|
||||
expect(url).toBe('/remote-ssh/api/deleteWorkspace')
|
||||
expect(body).toEqual({ id: 'rec-1' })
|
||||
})
|
||||
it('rejects when the plugin reports an error', async () => {
|
||||
await expect(deleteRemoteWorkspaceRecord('rec-1', stubFetch(200, { ok: true, value: { ok: false, error: 'no such workspace' } })))
|
||||
.rejects.toThrow(/no such workspace/)
|
||||
})
|
||||
it('rejects an empty record id without calling the plugin', async () => {
|
||||
await expect(deleteRemoteWorkspaceRecord(' ', stubFetch(200, { ok: true, value: { ok: true } }))).rejects.toThrow(/No remote/)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -14,13 +14,19 @@ import { join } from 'node:path'
|
|||
import { tmpdir } from 'node:os'
|
||||
import {
|
||||
addFolder,
|
||||
addMember,
|
||||
effectiveFolders,
|
||||
entryFor,
|
||||
folderOfCwd,
|
||||
lightRemotePath,
|
||||
memberByWorkspaceId,
|
||||
findRemoteMember,
|
||||
removeFolder,
|
||||
rootOf,
|
||||
samePath,
|
||||
sameRemotePath,
|
||||
setRoot,
|
||||
type FolderMember,
|
||||
type FoldersDocument,
|
||||
type WorkspaceFolderEntry,
|
||||
} from '../src/core/folders.ts'
|
||||
|
|
@ -52,10 +58,9 @@ 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, headers: Record<string, string> = {}) => {
|
||||
const request = async (method: string, body?: 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, {
|
||||
|
|
@ -86,16 +91,10 @@ 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] } } }
|
||||
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')
|
||||
expect((await request('PUT', JSON.stringify(document))).status).toBe(200)
|
||||
const response = await request('GET')
|
||||
expect(response.status).toBe(200)
|
||||
const served = JSON.parse(response.text!) as Record<string, unknown>
|
||||
expect(served).toMatchObject({ ...document, remoteBase: hostFolders.defaultRemoteMirrorBase() })
|
||||
expect(served.revision).toBe(accepted.revision)
|
||||
expect(JSON.parse(response.text!)).toEqual({ ...document, revision: 1, remoteBase: hostFolders.defaultRemoteMirrorBase() })
|
||||
|
||||
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')!
|
||||
expect(hintRoute).toBeDefined()
|
||||
|
|
@ -158,6 +157,50 @@ describe('samePath', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('remote member duplicate guards', () => {
|
||||
const remote = (over: Partial<FolderMember>): FolderMember => ({
|
||||
path: '/mirrors/w1', workspaceId: 'ws-1', kind: 'remote',
|
||||
remotePath: '/home/u/proj', profileId: 'prof-1', ...over,
|
||||
})
|
||||
const entry = (members: readonly FolderMember[]): WorkspaceFolderEntry => ({ members })
|
||||
|
||||
it('lightRemotePath trims and drops trailing slashes', () => {
|
||||
expect(lightRemotePath(' ~/proj/ ')).toBe('~/proj')
|
||||
expect(lightRemotePath('/home/u/proj//')).toBe('/home/u/proj')
|
||||
expect(lightRemotePath('/')).toBe('/')
|
||||
expect(lightRemotePath('~')).toBe('~')
|
||||
})
|
||||
|
||||
it('sameRemotePath equates spelling variants but not different dirs', () => {
|
||||
expect(sameRemotePath('/home/u/proj', '/home/u/proj/')).toBe(true)
|
||||
expect(sameRemotePath('~/proj', '~/proj')).toBe(true)
|
||||
expect(sameRemotePath('~/proj', '/home/u/proj')).toBe(false)
|
||||
expect(sameRemotePath('/home/u/proj', '/home/u/other')).toBe(false)
|
||||
})
|
||||
|
||||
it('memberByWorkspaceId finds the member backed by a workspace', () => {
|
||||
const e = entry([remote({})])
|
||||
expect(memberByWorkspaceId(e, 'ws-1')?.path).toBe('/mirrors/w1')
|
||||
expect(memberByWorkspaceId(e, 'ws-2')).toBeUndefined()
|
||||
expect(memberByWorkspaceId(undefined, 'ws-1')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('findRemoteMember matches connection + remote directory across spellings', () => {
|
||||
const e = entry([remote({ remotePath: '/home/u/proj/' })])
|
||||
expect(findRemoteMember(e, 'prof-1', '/home/u/proj')?.workspaceId).toBe('ws-1')
|
||||
expect(findRemoteMember(e, 'prof-2', '/home/u/proj')).toBeUndefined()
|
||||
expect(findRemoteMember(e, 'prof-1', '/home/u/other')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('findRemoteMember ignores local members and members without a remote path', () => {
|
||||
const e = entry([
|
||||
remote({ kind: 'local', workspaceId: 'ws-9' }),
|
||||
remote({ remotePath: undefined, workspaceId: 'ws-8' }),
|
||||
])
|
||||
expect(findRemoteMember(e, 'prof-1', '/home/u/proj')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('effectiveFolders / rootOf / entryFor', () => {
|
||||
it('puts the workspace path first', () => {
|
||||
expect(effectiveFolders(BASE, undefined)).toEqual([BASE])
|
||||
|
|
@ -252,7 +295,7 @@ describe('addFolder / removeFolder / setRoot', () => {
|
|||
})
|
||||
|
||||
describe('validateFoldersDocument', () => {
|
||||
const valid = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
const valid = { version: 1, revision: 0, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
|
||||
it('accepts a valid document', () => {
|
||||
expect(validateFoldersDocument(valid)).toEqual(valid)
|
||||
|
|
@ -311,10 +354,10 @@ describe('validateFoldersDocument', () => {
|
|||
|
||||
describe('parseFoldersDocument (tolerant read)', () => {
|
||||
it('returns the empty document for junk instead of throwing', () => {
|
||||
expect(parseFoldersDocument(undefined)).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument(null)).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument([])).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument({ version: 7, workspaces: {} })).toEqual({ version: 1, workspaces: {} })
|
||||
expect(parseFoldersDocument(undefined)).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
expect(parseFoldersDocument(null)).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
expect(parseFoldersDocument([])).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
expect(parseFoldersDocument({ version: 7, workspaces: {} })).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
})
|
||||
|
||||
it('drops bad folders, duplicates and dangling roots', () => {
|
||||
|
|
@ -326,7 +369,7 @@ describe('parseFoldersDocument (tolerant read)', () => {
|
|||
'ws-2': 'nope',
|
||||
},
|
||||
})
|
||||
expect(parsed).toEqual({ version: 1, workspaces: { 'ws-1': { folders: [EXTRA] } } })
|
||||
expect(parsed).toEqual({ version: 1, revision: 0, workspaces: { 'ws-1': { folders: [EXTRA] } } })
|
||||
})
|
||||
|
||||
it('keeps a valid root and tolerates a dangling workspace id', () => {
|
||||
|
|
@ -342,9 +385,9 @@ describe('readFoldersDocument / writeFoldersDocument', () => {
|
|||
it('reads a missing file as the empty document', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wg-folders-'))
|
||||
try {
|
||||
expect(await readFoldersDocument(join(dir, 'missing.json'))).toEqual({ version: 1, workspaces: {} })
|
||||
expect(await readFoldersDocument(join(dir, 'missing.json'))).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
await writeFile(join(dir, 'junk.json'), '{not json', 'utf8')
|
||||
expect(await readFoldersDocument(join(dir, 'junk.json'))).toEqual({ version: 1, workspaces: {} })
|
||||
expect(await readFoldersDocument(join(dir, 'junk.json'))).toEqual({ version: 1, revision: 0, workspaces: {} })
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true })
|
||||
}
|
||||
|
|
@ -353,7 +396,7 @@ describe('readFoldersDocument / writeFoldersDocument', () => {
|
|||
it('round-trips a document through the atomic write', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'wg-folders-'))
|
||||
const path = join(dir, 'nested', 'workspace-groups.folders.json')
|
||||
const document: FoldersDocument = { version: 1, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
const document: FoldersDocument = { version: 1, revision: 0, workspaces: { 'ws-1': { folders: [EXTRA], root: EXTRA } } }
|
||||
try {
|
||||
await writeFoldersDocument(path, document)
|
||||
expect(await readFoldersDocument(path)).toEqual(document)
|
||||
|
|
@ -362,3 +405,104 @@ describe('readFoldersDocument / writeFoldersDocument', () => {
|
|||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('folders revision guard (route)', () => {
|
||||
it('bumps the revision on write, rejects a stale writer with the current document', async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'wg-folders-revision-'))
|
||||
const previousHome = process.env.DSH_HOME
|
||||
process.env.DSH_HOME = home
|
||||
try {
|
||||
const routes: GroupsWebRoute[] = []
|
||||
apply({
|
||||
effect: (callback: () => unknown) => callback(),
|
||||
webServer: { register: (route: GroupsWebRoute) => { routes.push(route); return () => {} } },
|
||||
} as unknown as GroupsContext)
|
||||
const route = routes.find(item => item.path === '/workspace-groups/folders')!
|
||||
const request = async (method: string, body?: string) => {
|
||||
const req = Readable.from(body === undefined ? [] : [body]) as IncomingMessage
|
||||
req.method = method
|
||||
let status = 0
|
||||
let text: string | undefined
|
||||
await route.handler(req, {
|
||||
writeHead: (code: number) => { status = code },
|
||||
end: (value?: string) => { text = value },
|
||||
} as unknown as ServerResponse)
|
||||
return { status, text }
|
||||
}
|
||||
const rootA = process.platform === 'win32' ? 'C:\\x' : '/x'
|
||||
const rootB = process.platform === 'win32' ? 'C:\\y' : '/y'
|
||||
const first = { version: 1, revision: 0, workspaces: { a: { folders: [rootA] } } }
|
||||
const accepted = await request('PUT', JSON.stringify(first))
|
||||
expect(accepted.status).toBe(200)
|
||||
expect(JSON.parse(accepted.text!)).toEqual({ ...first, revision: 1 })
|
||||
// The same (now stale) write again: rejected, current document returned.
|
||||
const stale = await request('PUT', JSON.stringify(first))
|
||||
expect(stale.status).toBe(409)
|
||||
expect(JSON.parse(stale.text!)).toEqual({ ...first, revision: 1 })
|
||||
// Building on the current revision works and bumps again.
|
||||
const second = { version: 1, revision: 1, workspaces: { a: { folders: [rootA, rootB] } } }
|
||||
const accepted2 = await request('PUT', JSON.stringify(second))
|
||||
expect(accepted2.status).toBe(200)
|
||||
expect(JSON.parse(accepted2.text!).revision).toBe(2)
|
||||
const got = await request('GET')
|
||||
expect(JSON.parse(got.text!).revision).toBe(2)
|
||||
} finally {
|
||||
if (previousHome === undefined) delete process.env.DSH_HOME
|
||||
else process.env.DSH_HOME = previousHome
|
||||
await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('folders revision (validation + tolerant read)', () => {
|
||||
it('validateFoldersDocument carries a valid revision and rejects bad ones', () => {
|
||||
expect(hostFolders.validateFoldersDocument({ version: 1, revision: 3, workspaces: {} }).revision).toBe(3)
|
||||
expect(hostFolders.validateFoldersDocument({ version: 1, workspaces: {} }).revision).toBe(0)
|
||||
expect(() => hostFolders.validateFoldersDocument({ version: 1, revision: -1, workspaces: {} })).toThrow(/revision/)
|
||||
expect(() => hostFolders.validateFoldersDocument({ version: 1, revision: 1.5, workspaces: {} })).toThrow(/revision/)
|
||||
})
|
||||
it('parseFoldersDocument carries a valid revision and defaults a bad one to 0', () => {
|
||||
expect(hostFolders.parseFoldersDocument({ version: 1, revision: 9, workspaces: {} }).revision).toBe(9)
|
||||
expect(hostFolders.parseFoldersDocument({ version: 1, revision: 'x', workspaces: {} }).revision).toBe(0)
|
||||
expect(hostFolders.parseFoldersDocument({ version: 1, workspaces: {} }).revision).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('write-boundary hardening (dot segments, __proto__, UNC hints)', () => {
|
||||
it('validateFoldersDocument rejects dot segments in folder and member paths', () => {
|
||||
const badFolder = process.platform === 'win32' ? 'C:\\x\\..\\y' : '/x/../y'
|
||||
const badMember = process.platform === 'win32' ? 'C:\\x\\.\\y' : '/x/./y'
|
||||
expect(() => hostFolders.validateFoldersDocument({
|
||||
version: 1, workspaces: { a: { folders: [badFolder] } },
|
||||
})).toThrow(/"\.\." segments/)
|
||||
expect(() => hostFolders.validateFoldersDocument({
|
||||
version: 1, workspaces: { a: { folders: [], members: [{ path: badMember, workspaceId: 'b', kind: 'local' }] } },
|
||||
})).toThrow(/"\.\." segments/)
|
||||
})
|
||||
it('validateFoldersDocument rejects a __proto__ workspace id; the tolerant read skips it', () => {
|
||||
const doc: Record<string, unknown> = Object.create(null)
|
||||
doc.version = 1
|
||||
const workspaces: Record<string, unknown> = Object.create(null)
|
||||
workspaces['__proto__'] = { folders: [process.platform === 'win32' ? 'C:\\x' : '/x'] }
|
||||
workspaces.ok = { folders: [process.platform === 'win32' ? 'C:\\y' : '/y'] }
|
||||
doc.workspaces = workspaces
|
||||
expect(() => hostFolders.validateFoldersDocument(doc)).toThrow(/workspace ids/)
|
||||
const parsed = hostFolders.parseFoldersDocument(doc)
|
||||
expect(Object.keys(parsed.workspaces)).toEqual(['ok'])
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
})
|
||||
it('validateRemoteHintPath rejects UNC paths', () => {
|
||||
expect(() => hostFolders.validateRemoteHintPath(String.raw`\\server\share\dir`)).toThrow(/UNC/)
|
||||
expect(hostFolders.validateRemoteHintPath(process.platform === 'win32' ? 'C:\\home\\u\\proj' : '/home/u/proj'))
|
||||
.toBe(process.platform === 'win32' ? 'C:\\home\\u\\proj' : '/home/u/proj')
|
||||
})
|
||||
it('addMember keeps a root that names the member path', () => {
|
||||
const entry = addMember(
|
||||
{ folders: ['/proj/extra'], root: '/proj/extra' },
|
||||
{ path: '/proj/extra', workspaceId: 'ws-member', kind: 'local' },
|
||||
)
|
||||
expect(entry.root).toBe('/proj/extra')
|
||||
expect(entry.folders).toEqual([])
|
||||
expect(entry.members?.[0]?.workspaceId).toBe('ws-member')
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,6 +13,10 @@ import {
|
|||
writeManualGroups,
|
||||
} from '../src/host-manual.ts'
|
||||
import { UNCATEGORIZED_LABEL, type ManualGroups } from '../src/core/types.ts'
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import { Readable } from 'node:stream'
|
||||
import { apply } from '../src/index.ts'
|
||||
import type { GroupsContext, GroupsWebRoute } from '../src/context-types.ts'
|
||||
|
||||
const RULE_NAMES = ['DSH 插件', '个人项目']
|
||||
|
||||
|
|
@ -231,3 +235,63 @@ describe('manual file round-trip', () => {
|
|||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('manual revision guard (route)', () => {
|
||||
it('bumps on write, rejects a stale writer with the current overlay', async () => {
|
||||
const home = await mkdtemp(join(tmpdir(), 'wg-manual-revision-'))
|
||||
const previousHome = process.env.DSH_HOME
|
||||
process.env.DSH_HOME = home
|
||||
try {
|
||||
const routes: GroupsWebRoute[] = []
|
||||
apply({
|
||||
effect: (callback: () => unknown) => callback(),
|
||||
webServer: { register: (route: GroupsWebRoute) => { routes.push(route); return () => {} } },
|
||||
} as unknown as GroupsContext)
|
||||
const route = routes.find(item => item.path === '/workspace-groups/manual')!
|
||||
const request = async (body: unknown) => {
|
||||
const req = Readable.from([JSON.stringify(body)]) as IncomingMessage
|
||||
req.method = 'PUT'
|
||||
let status = 0
|
||||
let text: string | undefined
|
||||
await route.handler(req, {
|
||||
writeHead: (code: number) => { status = code },
|
||||
end: (value?: string) => { text = value },
|
||||
} as unknown as ServerResponse)
|
||||
return { status, text }
|
||||
}
|
||||
const first = { categories: ['项目组'], assignments: {} }
|
||||
const accepted = await request(first)
|
||||
expect(accepted.status).toBe(200)
|
||||
expect(JSON.parse(accepted.text!)).toEqual({ ok: true, manual: { ...first, revision: 1 } })
|
||||
const stale = await request(first)
|
||||
expect(stale.status).toBe(409)
|
||||
expect(JSON.parse(stale.text!)).toEqual({ manual: { ...first, revision: 1 } })
|
||||
const second = { categories: ['项目组'], assignments: {}, revision: 1 }
|
||||
const accepted2 = await request(second)
|
||||
expect(accepted2.status).toBe(200)
|
||||
expect(JSON.parse(accepted2.text!).manual.revision).toBe(2)
|
||||
} finally {
|
||||
if (previousHome === undefined) delete process.env.DSH_HOME
|
||||
else process.env.DSH_HOME = previousHome
|
||||
await rm(home, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
it('parseManualGroups carries a valid revision and drops a bad one', () => {
|
||||
expect(parseManualGroups({ categories: [], assignments: {}, revision: 4 }).revision).toBe(4)
|
||||
expect(parseManualGroups({ categories: [], assignments: {}, revision: -2 }).revision).toBeUndefined()
|
||||
expect(parseManualGroups({ categories: [], assignments: {} }).revision).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseManualGroups __proto__ keys', () => {
|
||||
it('skips __proto__ keys instead of mutating record prototypes', () => {
|
||||
const parsed = parseManualGroups({
|
||||
categories: [],
|
||||
assignments: { ['__proto__']: 'x', ws1: null },
|
||||
renamed: { ['__proto__']: 'y', a: 'b' },
|
||||
})
|
||||
expect(Object.keys(parsed.assignments)).toEqual(['ws1'])
|
||||
expect(Object.keys(parsed.renamed ?? {})).toEqual(['a'])
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,50 +0,0 @@
|
|||
/**
|
||||
* 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()
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,742 @@
|
|||
/**
|
||||
* Remote-SSH settings — pure-model behaviour.
|
||||
*
|
||||
* These tests pin the real semantics the new settings face relies on:
|
||||
* the exact Host payloads, per-item import outcomes (never "selected size"
|
||||
* reported as success), GiB/bytes conversion with the empty = Host-default
|
||||
* convention, unsaved-draft reconciliation, and the connection-test verdict
|
||||
* that keeps a successful probe with a warning as a warning.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { GuardDraft, ImportSummary, PrefsDraft } from '../src/client/rssh-settings/model.ts'
|
||||
import type { RemoteSshWorkspace, SshConfigHost } from '../src/client/rssh-settings/contract.ts'
|
||||
import {
|
||||
apiErrorMessage,
|
||||
bytesToGibText,
|
||||
connectionTestView,
|
||||
countSelected,
|
||||
emptyConnectionForm,
|
||||
gibTextToBytes,
|
||||
guardDraftFromWorkspace,
|
||||
guardDraftSignature,
|
||||
guardsFromWorkspaces,
|
||||
importHostKey,
|
||||
importProfilePayload,
|
||||
isConnectionFormValid,
|
||||
isGuardDraftDirty,
|
||||
isPrefsDraftDirty,
|
||||
mergeImportRetry,
|
||||
prefsDraftFromApi,
|
||||
reconcileGuards,
|
||||
reconcilePrefs,
|
||||
runImport,
|
||||
selectAllHosts,
|
||||
selectedHosts,
|
||||
splitList,
|
||||
toSavePrefsPayload,
|
||||
toSaveProfilePayload,
|
||||
toUpdateWorkspaceGuardsPayload,
|
||||
toggleHostSelection,
|
||||
validateConnectionForm,
|
||||
} from '../src/client/rssh-settings/model.ts'
|
||||
import type { SaveProfilePayload } from '../src/client/rssh-settings/contract.ts'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Fixtures */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const HOSTS: SshConfigHost[] = [
|
||||
{
|
||||
name: 'alpha',
|
||||
hostName: 'alpha.example.com',
|
||||
port: 2222,
|
||||
user: 'alice',
|
||||
identityFile: '~/.ssh/alpha',
|
||||
proxyJump: 'bastion.example.com',
|
||||
},
|
||||
{ name: 'beta', hostName: 'beta.example.com', user: 'bob' },
|
||||
{ name: 'gamma', hostName: 'gamma.example.com' },
|
||||
]
|
||||
|
||||
function hostSummary(hosts: SshConfigHost[]): string[] {
|
||||
return hosts.map(importHostKey)
|
||||
}
|
||||
|
||||
function makeSaveProfile(
|
||||
results: Array<{ ok?: boolean; error?: string } | null | undefined | Error>,
|
||||
) {
|
||||
return vi.fn(async (_payload: SaveProfilePayload) => {
|
||||
const next = results.shift()
|
||||
if (next instanceof Error) throw next
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const WS: RemoteSshWorkspace = {
|
||||
id: 'ws-1',
|
||||
profileId: 'p-1',
|
||||
title: 'Alpha',
|
||||
remotePath: '~/project',
|
||||
writeBack: true,
|
||||
writeBackExclude: ['_patch/', '*.log'],
|
||||
syncPaths: ['.dsh'],
|
||||
syncExclude: ['data/'],
|
||||
syncMaxBytes: 2147483648,
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Connection form → saveProfile payload */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('connection form validation and saveProfile payload', () => {
|
||||
it('accepts the default form: empty keyPath is legal (ssh-agent / ~/.ssh/config)', () => {
|
||||
const form = emptyConnectionForm()
|
||||
form.host = 'login.example.com'
|
||||
form.user = 'alice'
|
||||
expect(validateConnectionForm(form)).toEqual([])
|
||||
expect(isConnectionFormValid(form)).toBe(true)
|
||||
|
||||
const payload = toSaveProfilePayload(form)
|
||||
expect(payload.keyPath).toBe('')
|
||||
expect(payload.port).toBe(22)
|
||||
expect(payload.authMethod).toBe('key')
|
||||
})
|
||||
|
||||
it('rejects an invalid port instead of silently falling back to 22', () => {
|
||||
for (const port of ['', 'abc', '0', '65536', '-1', '22.5', '22abc']) {
|
||||
const form = { ...emptyConnectionForm(), host: 'h', user: 'u', port }
|
||||
const issues = validateConnectionForm(form)
|
||||
expect(issues, `port=${JSON.stringify(port)}`).toContainEqual({
|
||||
field: 'port',
|
||||
messageKey: 'add.errPort',
|
||||
})
|
||||
expect(isConnectionFormValid(form), `port=${JSON.stringify(port)}`).toBe(false)
|
||||
}
|
||||
|
||||
const form = { ...emptyConnectionForm(), host: 'h', user: 'u', port: ' 22 ' }
|
||||
expect(validateConnectionForm(form)).toEqual([])
|
||||
expect(toSaveProfilePayload(form).port).toBe(22)
|
||||
})
|
||||
|
||||
it('reports host and user as required, together with the port issue', () => {
|
||||
const form = { ...emptyConnectionForm(), host: ' ', user: '', port: 'x' }
|
||||
expect(validateConnectionForm(form)).toEqual([
|
||||
{ field: 'host', messageKey: 'add.errHost' },
|
||||
{ field: 'user', messageKey: 'add.errUser' },
|
||||
{ field: 'port', messageKey: 'add.errPort' },
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps both draft fields across key/password auth switching (same form state)', () => {
|
||||
const keyForm = {
|
||||
...emptyConnectionForm(),
|
||||
host: 'h',
|
||||
user: 'u',
|
||||
authMethod: 'key' as const,
|
||||
keyPath: '~/.ssh/id_ed25519',
|
||||
password: 'hunter2',
|
||||
}
|
||||
const keyPayload = toSaveProfilePayload(keyForm)
|
||||
expect(keyPayload.authMethod).toBe('key')
|
||||
expect(keyPayload.keyPath).toBe('~/.ssh/id_ed25519')
|
||||
expect(keyPayload.password).toBe('hunter2')
|
||||
|
||||
const passwordForm = { ...keyForm, authMethod: 'password' as const }
|
||||
const passwordPayload = toSaveProfilePayload(passwordForm)
|
||||
expect(passwordPayload.authMethod).toBe('password')
|
||||
expect(passwordPayload.keyPath).toBe('~/.ssh/id_ed25519')
|
||||
expect(passwordPayload.password).toBe('hunter2')
|
||||
})
|
||||
|
||||
it('carries every saveProfile field, including proxyJump and a real numeric port', () => {
|
||||
const form = {
|
||||
name: 'HPC',
|
||||
host: 'login.example.com',
|
||||
port: '2222',
|
||||
user: 'alice',
|
||||
authMethod: 'password' as const,
|
||||
keyPath: '',
|
||||
password: 'secret',
|
||||
remoteRoot: '~/project',
|
||||
proxyJump: 'bastion.example.com:22',
|
||||
}
|
||||
expect(toSaveProfilePayload(form)).toEqual({
|
||||
name: 'HPC',
|
||||
host: 'login.example.com',
|
||||
port: 2222,
|
||||
user: 'alice',
|
||||
authMethod: 'password',
|
||||
keyPath: '',
|
||||
password: 'secret',
|
||||
remoteRoot: '~/project',
|
||||
proxyJump: 'bastion.example.com:22',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* SSH config import */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('SSH config import — per-item outcomes', () => {
|
||||
it('maps a discovered host to the exact saveProfile payload (incl. proxyJump)', () => {
|
||||
expect(importProfilePayload(HOSTS[0] as SshConfigHost)).toEqual({
|
||||
name: 'alpha',
|
||||
host: 'alpha.example.com',
|
||||
port: 2222,
|
||||
user: 'alice',
|
||||
authMethod: 'key',
|
||||
keyPath: '~/.ssh/alpha',
|
||||
password: '',
|
||||
remoteRoot: '~',
|
||||
proxyJump: 'bastion.example.com',
|
||||
})
|
||||
expect(importProfilePayload(HOSTS[2] as SshConfigHost)).toMatchObject({
|
||||
port: 22,
|
||||
user: '',
|
||||
keyPath: '',
|
||||
proxyJump: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('counts every success only when every save resolves ok', async () => {
|
||||
const save = makeSaveProfile([{ ok: true }, { ok: true }, { ok: true }])
|
||||
const summary = await runImport(HOSTS, save)
|
||||
|
||||
expect(save).toHaveBeenCalledTimes(3)
|
||||
expect(save.mock.calls.map(call => call[0].name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||
expect(summary.okCount).toBe(3)
|
||||
expect(summary.failCount).toBe(0)
|
||||
expect(summary.failedHosts).toEqual([])
|
||||
expect(summary.outcomes.every(outcome => outcome.ok)).toBe(true)
|
||||
})
|
||||
|
||||
it('reports real partial failures (ok:false + error text), never the selection size', async () => {
|
||||
const save = makeSaveProfile([
|
||||
{ ok: true },
|
||||
{ ok: false, error: ' duplicate host ' },
|
||||
{ ok: false, error: 'boom' },
|
||||
])
|
||||
const summary = await runImport(HOSTS, save)
|
||||
|
||||
expect(summary.okCount).toBe(1)
|
||||
expect(summary.failCount).toBe(2)
|
||||
expect(summary.outcomes.map(outcome => outcome.ok)).toEqual([true, false, false])
|
||||
expect(summary.outcomes[1]?.error).toBe('duplicate host')
|
||||
expect(summary.outcomes[2]?.error).toBe('boom')
|
||||
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary([HOSTS[1]!, HOSTS[2]!]))
|
||||
})
|
||||
|
||||
it('reports every failure when all saves fail', async () => {
|
||||
const save = makeSaveProfile([
|
||||
{ ok: false, error: 'one' },
|
||||
{ ok: false, error: 'two' },
|
||||
{ ok: false, error: 'three' },
|
||||
])
|
||||
const summary = await runImport(HOSTS, save)
|
||||
|
||||
expect(summary.okCount).toBe(0)
|
||||
expect(summary.failCount).toBe(3)
|
||||
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary(HOSTS))
|
||||
expect(summary.outcomes.map(outcome => outcome.error)).toEqual(['one', 'two', 'three'])
|
||||
})
|
||||
|
||||
it('turns thrown request errors into failures with the thrown message', async () => {
|
||||
const save = makeSaveProfile([{ ok: true }, new Error('network down'), { ok: false, error: 'denied' }])
|
||||
const summary = await runImport(HOSTS, save)
|
||||
|
||||
expect(summary.okCount).toBe(1)
|
||||
expect(summary.failCount).toBe(2)
|
||||
expect(summary.outcomes[1]?.ok).toBe(false)
|
||||
expect(summary.outcomes[1]?.error).toBe('network down')
|
||||
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary([HOSTS[1]!, HOSTS[2]!]))
|
||||
})
|
||||
|
||||
it('treats an undefined/null save result as failure (no-result), never as imported', async () => {
|
||||
const save = makeSaveProfile([undefined, null])
|
||||
const summary = await runImport(HOSTS.slice(0, 2), save)
|
||||
|
||||
expect(save).toHaveBeenCalledTimes(2)
|
||||
expect(summary.okCount).toBe(0)
|
||||
expect(summary.failCount).toBe(2)
|
||||
expect(summary.outcomes.map(outcome => outcome.ok)).toEqual([false, false])
|
||||
expect(summary.outcomes.map(outcome => outcome.errorCode)).toEqual(['no-result', 'no-result'])
|
||||
expect(summary.outcomes.every(outcome => outcome.error === undefined)).toBe(true)
|
||||
expect(summary.failedHosts).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('treats ok:false without error text as a failure too', async () => {
|
||||
const summary = await runImport([HOSTS[1] as SshConfigHost], makeSaveProfile([{ ok: false }]))
|
||||
expect(summary.okCount).toBe(0)
|
||||
expect(summary.failCount).toBe(1)
|
||||
expect(summary.outcomes[0]?.errorCode).toBe('no-result')
|
||||
})
|
||||
|
||||
it('an empty selection imports nothing and calls no endpoint', async () => {
|
||||
const save = makeSaveProfile([])
|
||||
const summary = await runImport([], save)
|
||||
expect(save).not.toHaveBeenCalled()
|
||||
expect(summary).toEqual({ outcomes: [], okCount: 0, failCount: 0, failedHosts: [] })
|
||||
})
|
||||
|
||||
it('reports progress per host only through the injected callback', async () => {
|
||||
const progress: string[] = []
|
||||
const summary = await runImport(HOSTS.slice(0, 2), makeSaveProfile([{ ok: true }, { ok: false }]), {
|
||||
onProgress: (done, total, host) => progress.push(`${done}/${total}:${host.name}`),
|
||||
})
|
||||
expect(progress).toEqual(['0/2:alpha', '1/2:beta', '2/2:beta'])
|
||||
expect(summary.failCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('failed-only retry merge', () => {
|
||||
it('does not resubmit successful items and keeps their success count', async () => {
|
||||
const firstSave = makeSaveProfile([{ ok: true }, { ok: false, error: 'timeout' }, { ok: false, error: 'x' }])
|
||||
const first = await runImport(HOSTS, firstSave)
|
||||
|
||||
const retrySave = makeSaveProfile([{ ok: true }, { ok: true }])
|
||||
const retry = await runImport(first.failedHosts, retrySave)
|
||||
|
||||
expect(retrySave).toHaveBeenCalledTimes(2)
|
||||
expect(retrySave.mock.calls.map(call => call[0].name)).toEqual(['beta', 'gamma'])
|
||||
expect(firstSave).toHaveBeenCalledTimes(3)
|
||||
expect(firstSave.mock.calls.map(call => call[0].name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||
|
||||
const merged = mergeImportRetry(first, retry)
|
||||
expect(merged.okCount).toBe(3)
|
||||
expect(merged.failCount).toBe(0)
|
||||
expect(merged.failedHosts).toEqual([])
|
||||
expect(merged.outcomes).toHaveLength(3)
|
||||
expect(merged.outcomes.every(outcome => outcome.ok)).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps a still-failing retry item as failed with its retry reason', async () => {
|
||||
const first = await runImport(
|
||||
HOSTS,
|
||||
makeSaveProfile([{ ok: true }, { ok: false, error: 'timeout' }, { ok: false, error: 'nope' }]),
|
||||
)
|
||||
const retry = await runImport(first.failedHosts, makeSaveProfile([{ ok: false, error: 'still bad' }, { ok: true }]))
|
||||
|
||||
const merged = mergeImportRetry(first, retry)
|
||||
expect(merged.okCount).toBe(2)
|
||||
expect(merged.failCount).toBe(1)
|
||||
expect(hostSummary(merged.failedHosts)).toEqual(hostSummary([HOSTS[1] as SshConfigHost]))
|
||||
expect(merged.outcomes).toHaveLength(3)
|
||||
expect(merged.outcomes.filter(outcome => !outcome.ok)[0]?.error).toBe('still bad')
|
||||
})
|
||||
|
||||
it('a fully failed retry keeps the merged summary fully failed', () => {
|
||||
const previous: ImportSummary = {
|
||||
outcomes: [
|
||||
{ key: 'a|h', name: 'a', hostName: 'h', ok: false, error: 'first' },
|
||||
{ key: 'b|h2', name: 'b', hostName: 'h2', ok: false, error: 'second' },
|
||||
],
|
||||
okCount: 0,
|
||||
failCount: 2,
|
||||
failedHosts: [HOSTS[0] as SshConfigHost, HOSTS[1] as SshConfigHost],
|
||||
}
|
||||
const retry: ImportSummary = {
|
||||
outcomes: [
|
||||
{ key: 'a|h', name: 'a', hostName: 'h', ok: false, errorCode: 'no-result' },
|
||||
{ key: 'b|h2', name: 'b', hostName: 'h2', ok: false, error: 'second' },
|
||||
],
|
||||
okCount: 0,
|
||||
failCount: 2,
|
||||
failedHosts: [HOSTS[0] as SshConfigHost, HOSTS[1] as SshConfigHost],
|
||||
}
|
||||
const merged = mergeImportRetry(previous, retry)
|
||||
expect(merged.okCount).toBe(0)
|
||||
expect(merged.failCount).toBe(2)
|
||||
expect(merged.failedHosts).toHaveLength(2)
|
||||
expect(merged.outcomes.every(outcome => !outcome.ok)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('host selection', () => {
|
||||
it('selects nothing when every row is unchecked', () => {
|
||||
const selected = { [importHostKey(HOSTS[0]!)]: false, [importHostKey(HOSTS[1]!)]: false }
|
||||
expect(selectedHosts(HOSTS, selected)).toEqual([])
|
||||
expect(countSelected(selected)).toBe(0)
|
||||
})
|
||||
|
||||
it('selects all discovered hosts by default and counts only checked rows', () => {
|
||||
const selected = selectAllHosts(HOSTS)
|
||||
expect(countSelected(selected)).toBe(3)
|
||||
expect(hostSummary(selectedHosts(HOSTS, selected))).toEqual(hostSummary(HOSTS))
|
||||
|
||||
const toggled = toggleHostSelection(selected, importHostKey(HOSTS[1]!))
|
||||
expect(toggled[importHostKey(HOSTS[1]!)]).toBe(false)
|
||||
expect(countSelected(toggled)).toBe(2)
|
||||
expect(hostSummary(selectedHosts(HOSTS, toggled))).toEqual(
|
||||
hostSummary([HOSTS[0] as SshConfigHost, HOSTS[2] as SshConfigHost]),
|
||||
)
|
||||
})
|
||||
|
||||
it('treats an empty selection map as no selection', () => {
|
||||
expect(selectedHosts(HOSTS, {})).toEqual([])
|
||||
expect(countSelected({})).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* GiB ↔ bytes */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('sync size unit conversion and empty-value semantics', () => {
|
||||
it('bytesToGibText: empty input means "use the Host default"', () => {
|
||||
expect(bytesToGibText(0)).toBe('')
|
||||
expect(bytesToGibText(0)).toBe('')
|
||||
expect(bytesToGibText(null)).toBe('')
|
||||
expect(bytesToGibText(undefined)).toBe('')
|
||||
expect(bytesToGibText(Number.NaN)).toBe('')
|
||||
})
|
||||
|
||||
it('bytesToGibText: tiny byte counts collapse to "0", GiB values round to 2 decimals', () => {
|
||||
expect(bytesToGibText(2)).toBe('0')
|
||||
expect(bytesToGibText(1073741824)).toBe('1')
|
||||
expect(bytesToGibText(2 * 1073741824)).toBe('2')
|
||||
expect(bytesToGibText(1.5 * 1073741824)).toBe('1.5')
|
||||
})
|
||||
|
||||
it('gibTextToBytes: empty / zero / invalid all mean 0 (Host default)', () => {
|
||||
expect(gibTextToBytes('')).toBe(0)
|
||||
expect(gibTextToBytes('0')).toBe(0)
|
||||
expect(gibTextToBytes('0.0')).toBe(0)
|
||||
expect(gibTextToBytes('abc')).toBe(0)
|
||||
expect(gibTextToBytes(null)).toBe(0)
|
||||
expect(gibTextToBytes(undefined)).toBe(0)
|
||||
})
|
||||
|
||||
it('gibTextToBytes: "2" and "2.0" both mean 2 GiB = 2147483648 bytes', () => {
|
||||
expect(gibTextToBytes(2)).toBe(2147483648)
|
||||
expect(gibTextToBytes('2')).toBe(2147483648)
|
||||
expect(gibTextToBytes('2.0')).toBe(2147483648)
|
||||
expect(gibTextToBytes('2.5')).toBe(2684354560)
|
||||
expect(gibTextToBytes('2 GiB')).toBe(2147483648)
|
||||
})
|
||||
|
||||
it('round-trips the default 2 GiB cap', () => {
|
||||
expect(gibTextToBytes(bytesToGibText(2147483648))).toBe(2147483648)
|
||||
})
|
||||
})
|
||||
|
||||
describe('list splitting', () => {
|
||||
it('accepts commas, newlines and semicolons, trimming and dropping empty entries', () => {
|
||||
expect(splitList('a, b\nc; d')).toEqual(['a', 'b', 'c', 'd'])
|
||||
expect(splitList('a,, b, ,\n')).toEqual(['a', 'b'])
|
||||
expect(splitList('')).toEqual([])
|
||||
expect(splitList(null)).toEqual([])
|
||||
expect(splitList(undefined)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Workspace guard drafts */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('workspace guard drafts', () => {
|
||||
it('builds a draft from a persisted record (defaults match the Host)', () => {
|
||||
expect(guardDraftFromWorkspace(WS)).toEqual({
|
||||
writeBack: true,
|
||||
writeBackExclude: '_patch/, *.log',
|
||||
syncPaths: '.dsh',
|
||||
syncExclude: 'data/',
|
||||
syncMaxBytes: '2',
|
||||
})
|
||||
|
||||
expect(guardDraftFromWorkspace({ id: 'w2', profileId: 'p' })).toEqual({
|
||||
writeBack: true,
|
||||
writeBackExclude: '',
|
||||
syncPaths: '',
|
||||
syncExclude: '',
|
||||
syncMaxBytes: '',
|
||||
})
|
||||
expect(guardDraftFromWorkspace({ id: 'w3', profileId: 'p', writeBack: false })).toMatchObject({
|
||||
writeBack: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('does not call formatting-only differences dirty', () => {
|
||||
const baseline = guardDraftFromWorkspace(WS)
|
||||
expect(isGuardDraftDirty(baseline, baseline)).toBe(false)
|
||||
|
||||
expect(isGuardDraftDirty({ ...baseline, writeBackExclude: '_patch/,\n*.log' }, baseline)).toBe(false)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncPaths: ' .dsh ' }, baseline)).toBe(false)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '2.0' }, baseline)).toBe(false)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: ' 2 ' }, baseline)).toBe(false)
|
||||
expect(guardDraftSignature({ ...baseline, syncMaxBytes: '2.0' })).toBe(guardDraftSignature(baseline))
|
||||
})
|
||||
|
||||
it('marks real edits dirty', () => {
|
||||
const baseline = guardDraftFromWorkspace(WS)
|
||||
expect(isGuardDraftDirty({ ...baseline, writeBackExclude: '_patch/, *.log, tmp/' }, baseline)).toBe(true)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncPaths: '.dsh, ..' }, baseline)).toBe(true)
|
||||
expect(isGuardDraftDirty({ ...baseline, writeBack: false }, baseline)).toBe(true)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '3' }, baseline)).toBe(true)
|
||||
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '' }, baseline)).toBe(true)
|
||||
})
|
||||
|
||||
it('produces the exact updateWorkspaceGuards payload for the target workspace id', () => {
|
||||
const draft: GuardDraft = {
|
||||
writeBack: false,
|
||||
writeBackExclude: '_patch/, *.log',
|
||||
syncPaths: '.dsh\nsrc',
|
||||
syncExclude: 'data/, *.tmp',
|
||||
syncMaxBytes: '2',
|
||||
}
|
||||
expect(toUpdateWorkspaceGuardsPayload('ws-1', draft)).toEqual({
|
||||
id: 'ws-1',
|
||||
writeBack: false,
|
||||
writeBackExclude: ['_patch/', '*.log'],
|
||||
syncPaths: ['.dsh', 'src'],
|
||||
syncExclude: ['data/', '*.tmp'],
|
||||
syncMaxBytes: 2147483648,
|
||||
})
|
||||
expect(toUpdateWorkspaceGuardsPayload('ws-1', { ...draft, syncMaxBytes: '' }).syncMaxBytes).toBe(0)
|
||||
expect(toUpdateWorkspaceGuardsPayload('ws-1', { ...draft, syncMaxBytes: '2.0' }).syncMaxBytes).toBe(2147483648)
|
||||
})
|
||||
})
|
||||
|
||||
describe('reconcileGuards', () => {
|
||||
it('keeps a dirty draft across an unrelated reload and moves its baseline to server truth', () => {
|
||||
const previousDrafts = guardsFromWorkspaces([WS])
|
||||
const previousBaselines = guardsFromWorkspaces([WS])
|
||||
const dirtyDraft: GuardDraft = { ...previousDrafts['ws-1']!, writeBackExclude: '_patch/, *.log, tmp/' }
|
||||
previousDrafts['ws-1'] = dirtyDraft
|
||||
|
||||
const serverWorkspace: RemoteSshWorkspace = { ...WS, writeBackExclude: ['server/'] }
|
||||
const result = reconcileGuards(previousDrafts, previousBaselines, [serverWorkspace])
|
||||
|
||||
expect(result.drafts['ws-1']).toBe(dirtyDraft)
|
||||
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||
expect(isGuardDraftDirty(result.drafts['ws-1']!, result.baselines['ws-1']!)).toBe(true)
|
||||
})
|
||||
|
||||
it('adopts server truth for a clean draft', () => {
|
||||
const previousDrafts = guardsFromWorkspaces([WS])
|
||||
const previousBaselines = guardsFromWorkspaces([WS])
|
||||
const serverWorkspace: RemoteSshWorkspace = { ...WS, writeBack: false, syncPaths: [] }
|
||||
const result = reconcileGuards(previousDrafts, previousBaselines, [serverWorkspace])
|
||||
|
||||
expect(result.drafts['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||
expect(isGuardDraftDirty(result.drafts['ws-1']!, result.baselines['ws-1']!)).toBe(false)
|
||||
})
|
||||
|
||||
it('drops drafts and baselines for records deleted on the Host', () => {
|
||||
const previousDrafts = guardsFromWorkspaces([WS, { id: 'ws-2', profileId: 'p-2' }])
|
||||
const previousBaselines = guardsFromWorkspaces([WS, { id: 'ws-2', profileId: 'p-2' }])
|
||||
const result = reconcileGuards(previousDrafts, previousBaselines, [WS])
|
||||
|
||||
expect(Object.keys(result.drafts)).toEqual(['ws-1'])
|
||||
expect(Object.keys(result.baselines)).toEqual(['ws-1'])
|
||||
expect(result.drafts['ws-2']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats a draft without a previous baseline as dirty so a refresh cannot wipe typed text', () => {
|
||||
const typed: GuardDraft = {
|
||||
writeBack: true,
|
||||
writeBackExclude: 'tmp/',
|
||||
syncPaths: '',
|
||||
syncExclude: '',
|
||||
syncMaxBytes: '',
|
||||
}
|
||||
const result = reconcileGuards({ 'ws-1': typed }, {}, [WS])
|
||||
expect(result.drafts['ws-1']).toEqual(typed)
|
||||
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(WS))
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Global preferences */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const PREFS: PrefsDraft = {
|
||||
nodePath: '/usr/local/bin/node',
|
||||
writeBackFailure: 'log',
|
||||
writeBackFreshness: false,
|
||||
defaultSyncPaths: '.dsh, src',
|
||||
defaultSyncExclude: 'data/',
|
||||
defaultSyncMaxBytes: '2',
|
||||
}
|
||||
|
||||
describe('global preferences draft', () => {
|
||||
it('projects Host preferences with the upstream defaults', () => {
|
||||
expect(prefsDraftFromApi({})).toEqual({
|
||||
nodePath: '',
|
||||
writeBackFailure: 'error',
|
||||
writeBackFreshness: true,
|
||||
defaultSyncPaths: '',
|
||||
defaultSyncExclude: '',
|
||||
defaultSyncMaxBytes: '',
|
||||
})
|
||||
expect(prefsDraftFromApi({ nodePath: '/opt/node', writeBackFailure: 'log', writeBackFreshness: false, defaultSyncPaths: ['a', 'b'], defaultSyncMaxBytes: 2147483648 })).toEqual({
|
||||
nodePath: '/opt/node',
|
||||
writeBackFailure: 'log',
|
||||
writeBackFreshness: false,
|
||||
defaultSyncPaths: 'a, b',
|
||||
defaultSyncExclude: '',
|
||||
defaultSyncMaxBytes: '2',
|
||||
})
|
||||
})
|
||||
|
||||
it('does not call formatting-only differences dirty', () => {
|
||||
expect(isPrefsDraftDirty(PREFS, PREFS)).toBe(false)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncPaths: '.dsh\nsrc' }, PREFS)).toBe(false)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncMaxBytes: '2.0' }, PREFS)).toBe(false)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, nodePath: ' /usr/local/bin/node ' }, PREFS)).toBe(false)
|
||||
})
|
||||
|
||||
it('marks real edits dirty', () => {
|
||||
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncPaths: '.dsh, src, tests' }, PREFS)).toBe(true)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, writeBackFailure: 'error' }, PREFS)).toBe(true)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, writeBackFreshness: true }, PREFS)).toBe(true)
|
||||
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncMaxBytes: '3' }, PREFS)).toBe(true)
|
||||
})
|
||||
|
||||
it('produces the exact savePrefs payload', () => {
|
||||
expect(toSavePrefsPayload(PREFS)).toEqual({
|
||||
nodePath: '/usr/local/bin/node',
|
||||
writeBackFailure: 'log',
|
||||
writeBackFreshness: false,
|
||||
defaultSyncPaths: ['.dsh', 'src'],
|
||||
defaultSyncExclude: ['data/'],
|
||||
defaultSyncMaxBytes: 2147483648,
|
||||
})
|
||||
expect(toSavePrefsPayload({ ...PREFS, nodePath: ' ', defaultSyncMaxBytes: '' })).toMatchObject({
|
||||
nodePath: '',
|
||||
defaultSyncMaxBytes: 0,
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an unsaved preferences draft on refresh and adopts server truth for a clean one', () => {
|
||||
const serverDraft: PrefsDraft = { ...PREFS, nodePath: '/server/node' }
|
||||
const dirty: PrefsDraft = { ...PREFS, nodePath: '/typed/node' }
|
||||
|
||||
const kept = reconcilePrefs(dirty, PREFS, serverDraft)
|
||||
expect(kept.draft).toEqual(dirty)
|
||||
expect(kept.baseline).toEqual(serverDraft)
|
||||
|
||||
const clean = reconcilePrefs(PREFS, PREFS, serverDraft)
|
||||
expect(clean.draft).toEqual(serverDraft)
|
||||
expect(clean.baseline).toEqual(serverDraft)
|
||||
|
||||
const firstLoad = reconcilePrefs(null, null, serverDraft)
|
||||
expect(firstLoad.draft).toEqual(serverDraft)
|
||||
expect(firstLoad.baseline).toEqual(serverDraft)
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Guards ↔ prefs independence */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('workspace guards and global preferences never overwrite each other', () => {
|
||||
it('their payload shapes stay disjoint', () => {
|
||||
const guardsPayload = toUpdateWorkspaceGuardsPayload('ws-1', guardDraftFromWorkspace(WS))
|
||||
const prefsPayload = toSavePrefsPayload(prefsDraftFromApi({ nodePath: '/node', defaultSyncPaths: ['a'] }))
|
||||
|
||||
expect(Object.keys(guardsPayload).sort()).toEqual(
|
||||
['id', 'syncExclude', 'syncMaxBytes', 'syncPaths', 'writeBack', 'writeBackExclude'].sort(),
|
||||
)
|
||||
expect(Object.keys(prefsPayload).sort()).toEqual(
|
||||
['defaultSyncExclude', 'defaultSyncMaxBytes', 'defaultSyncPaths', 'nodePath', 'writeBackFailure', 'writeBackFreshness'].sort(),
|
||||
)
|
||||
expect(guardsPayload).not.toHaveProperty('nodePath')
|
||||
expect(guardsPayload).not.toHaveProperty('writeBackFailure')
|
||||
expect(prefsPayload).not.toHaveProperty('id')
|
||||
expect(prefsPayload).not.toHaveProperty('writeBack')
|
||||
expect(prefsPayload).not.toHaveProperty('syncPaths')
|
||||
})
|
||||
|
||||
it('reconcileGuards and reconcilePrefs keep their own dirty drafts independently', () => {
|
||||
const guards = guardsFromWorkspaces([WS])
|
||||
const dirtyGuard: GuardDraft = { ...guards['ws-1']!, syncPaths: '.dsh, extra' }
|
||||
const dirtyPrefs: PrefsDraft = { ...PREFS, nodePath: '/typed/node' }
|
||||
|
||||
const guardResult = reconcileGuards({ 'ws-1': dirtyGuard }, guards, [{ ...WS, syncPaths: ['server'] }])
|
||||
const prefsResult = reconcilePrefs(dirtyPrefs, PREFS, { ...PREFS, nodePath: '/server/node' })
|
||||
|
||||
expect(guardResult.drafts['ws-1']).toEqual(dirtyGuard)
|
||||
expect(prefsResult.draft).toEqual(dirtyPrefs)
|
||||
// Never imported across the boundary: a guard draft has no prefs keys and vice versa.
|
||||
expect(guardResult.drafts['ws-1']).not.toHaveProperty('nodePath')
|
||||
expect(prefsResult.draft).not.toHaveProperty('syncMaxBytes')
|
||||
})
|
||||
|
||||
it('a guard save baseline update does not touch the prefs draft', () => {
|
||||
const before = toSavePrefsPayload(PREFS)
|
||||
const result = reconcileGuards(guardsFromWorkspaces([WS]), guardsFromWorkspaces([WS]), [
|
||||
{ ...WS, writeBackExclude: ['server/'] },
|
||||
])
|
||||
expect(result.drafts['ws-1']?.writeBackExclude).toBe('server/')
|
||||
expect(toSavePrefsPayload(PREFS)).toEqual(before)
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Connection test feedback */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('connectionTestView', () => {
|
||||
it('plain success shows the success status and stdout detail', () => {
|
||||
expect(connectionTestView({ ok: true, stdout: ' connected \n' })).toEqual({
|
||||
status: 'success',
|
||||
titleKey: 'connection.testOk',
|
||||
warning: '',
|
||||
detail: 'connected',
|
||||
})
|
||||
})
|
||||
|
||||
it('a successful probe carrying a warning stays a warning, never a plain success', () => {
|
||||
const view = connectionTestView({ ok: true, warning: ' key path not found, using agent ', stdout: 'ok' })
|
||||
expect(view.status).toBe('warning')
|
||||
expect(view.titleKey).toBe('connection.testWarn')
|
||||
expect(view.warning).toBe('key path not found, using agent')
|
||||
expect(view.detail).toBe('ok')
|
||||
})
|
||||
|
||||
it('failure joins error and stderr into pre-wrap diagnostics', () => {
|
||||
const view = connectionTestView({
|
||||
ok: false,
|
||||
error: 'connect failed',
|
||||
stderr: 'ssh: Could not resolve hostname',
|
||||
exitCode: 255,
|
||||
})
|
||||
expect(view).toEqual({
|
||||
status: 'error',
|
||||
titleKey: 'connection.testFail',
|
||||
warning: '',
|
||||
detail: 'connect failed\nssh: Could not resolve hostname',
|
||||
})
|
||||
})
|
||||
|
||||
it('failure with only stderr, only error, or no envelope still yields the failure status', () => {
|
||||
expect(connectionTestView({ ok: false, stderr: 'stderr only' }).detail).toBe('stderr only')
|
||||
expect(connectionTestView({ ok: false, error: 'error only' }).detail).toBe('error only')
|
||||
|
||||
for (const empty of [undefined, null, {}, { ok: false }]) {
|
||||
const view = connectionTestView(empty)
|
||||
expect(view.status).toBe('error')
|
||||
expect(view.titleKey).toBe('connection.testFail')
|
||||
expect(view.detail).toBe('')
|
||||
}
|
||||
})
|
||||
|
||||
it('a failure that also carries a warning keeps both the failure status and the warning text', () => {
|
||||
const view = connectionTestView({ ok: false, warning: 'identity ignored', error: 'denied' })
|
||||
expect(view.status).toBe('error')
|
||||
expect(view.warning).toBe('identity ignored')
|
||||
expect(view.detail).toBe('denied')
|
||||
})
|
||||
})
|
||||
|
||||
describe('apiErrorMessage', () => {
|
||||
it('trims the Host error and falls back when the envelope has none', () => {
|
||||
expect(apiErrorMessage({ error: ' denied ' }, 'fallback')).toBe('denied')
|
||||
expect(apiErrorMessage({ error: ' ' }, 'fallback')).toBe('fallback')
|
||||
expect(apiErrorMessage({}, 'fallback')).toBe('fallback')
|
||||
expect(apiErrorMessage(null, 'fallback')).toBe('fallback')
|
||||
expect(apiErrorMessage({ error: 42 as unknown as string }, 'fallback')).toBe('fallback')
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,714 @@
|
|||
// @vitest-environment jsdom
|
||||
/**
|
||||
* Remote-SSH settings — rendered UI behaviour.
|
||||
*
|
||||
* These mount the real `createSettingsSection` component in jsdom with a fake
|
||||
* `api` and a dictionary-backed `t`, then drive the DOM through the documented
|
||||
* `data-rsui-*` hooks. They assert behaviour (drafts survive collapsing, the
|
||||
* right workspace id is saved with GiB→bytes, dirty drafts block sync, failed
|
||||
* imports are reported per host and can be retried alone) rather than styles.
|
||||
*/
|
||||
import React, { act } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSettingsSection } from '../src/client/rssh-settings/index.tsx'
|
||||
import { zh } from '../src/client/rssh-settings/i18n.ts'
|
||||
import type {
|
||||
RemoteSshApi,
|
||||
RemoteSshPrefs,
|
||||
RemoteSshProfile,
|
||||
RemoteSshWorkspace,
|
||||
SavePrefsPayload,
|
||||
SaveProfilePayload,
|
||||
SshConfigHost,
|
||||
UpdateWorkspaceGuardsPayload,
|
||||
SettingsTranslate,
|
||||
} from '../src/client/rssh-settings/contract.ts'
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Primitive mock (the face only relies on Modal/Button from primitives) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({
|
||||
Modal: (props: {
|
||||
open?: boolean
|
||||
title?: ReactNode
|
||||
closeLabel?: string
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
footer?: ReactNode
|
||||
[key: string]: unknown
|
||||
}) => {
|
||||
if (props.open === false) return null
|
||||
const { open: _open, onClose: _onClose, title, closeLabel: _closeLabel, footer, ...rest } = props
|
||||
const passThrough: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(rest)) {
|
||||
if (key.startsWith('data-') || key === 'className' || key === 'role' || key === 'aria-label') {
|
||||
passThrough[key] = value
|
||||
}
|
||||
}
|
||||
return React.createElement(
|
||||
'div',
|
||||
passThrough as React.HTMLAttributes<HTMLDivElement>,
|
||||
title ? React.createElement('div', null, title) : null,
|
||||
props.children,
|
||||
footer ? React.createElement('div', null, footer) : null,
|
||||
)
|
||||
},
|
||||
Button: (props: { children?: ReactNode; variant?: unknown; size?: unknown; [key: string]: unknown }) => {
|
||||
const { children, variant: _variant, size: _size, ...rest } = props
|
||||
return React.createElement('button', rest as React.ButtonHTMLAttributes<HTMLButtonElement>, children)
|
||||
},
|
||||
}))
|
||||
|
||||
Object.assign(globalThis, { React, IS_REACT_ACT_ENVIRONMENT: true })
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Translation dictionary */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const ZH = zh as Record<string, string>
|
||||
const t: SettingsTranslate = (key, params) => {
|
||||
const template = ZH[key] ?? key
|
||||
if (!params) return template
|
||||
return template.replace(/\{(\w+)\}/g, (_match, name: string) => String(params[name] ?? ''))
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Fixtures */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
const PROFILE: RemoteSshProfile = {
|
||||
id: 'p-1',
|
||||
name: 'Alpha HPC',
|
||||
host: 'alpha.example.com',
|
||||
port: 2222,
|
||||
user: 'alice',
|
||||
authMethod: 'key',
|
||||
keyPath: '~/.ssh/alpha',
|
||||
remoteRoot: '~/project',
|
||||
passwordConfigured: false,
|
||||
}
|
||||
|
||||
const WORKSPACES: RemoteSshWorkspace[] = [
|
||||
{
|
||||
id: 'ws-a',
|
||||
profileId: 'p-1',
|
||||
title: 'Alpha workspace',
|
||||
remotePath: '~/alpha',
|
||||
writeBack: true,
|
||||
writeBackExclude: ['_patch/', '*.log'],
|
||||
syncPaths: ['.dsh'],
|
||||
syncExclude: ['data/'],
|
||||
syncMaxBytes: 2147483648,
|
||||
},
|
||||
{
|
||||
id: 'ws-b',
|
||||
profileId: 'p-1',
|
||||
title: 'Beta workspace',
|
||||
remotePath: '~/beta',
|
||||
writeBack: false,
|
||||
writeBackExclude: [],
|
||||
syncPaths: [],
|
||||
syncExclude: [],
|
||||
syncMaxBytes: 0,
|
||||
},
|
||||
]
|
||||
|
||||
const SSH_HOSTS: SshConfigHost[] = [
|
||||
{ name: 'alpha', hostName: 'alpha.example.com', user: 'alice', identityFile: '~/.ssh/alpha' },
|
||||
{ name: 'beta', hostName: 'beta.example.com', user: 'bob' },
|
||||
{ name: 'gamma', hostName: 'gamma.example.com' },
|
||||
]
|
||||
|
||||
const PREFS: RemoteSshPrefs = {
|
||||
nodePath: '',
|
||||
writeBackFailure: 'error',
|
||||
writeBackFreshness: true,
|
||||
defaultSyncPaths: [],
|
||||
defaultSyncExclude: [],
|
||||
defaultSyncMaxBytes: 0,
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Fake api */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
type Handler = (args: unknown, index: number) => unknown
|
||||
|
||||
interface InitialData {
|
||||
profiles?: RemoteSshProfile[]
|
||||
workspaces?: RemoteSshWorkspace[]
|
||||
prefs?: RemoteSshPrefs
|
||||
hosts?: SshConfigHost[]
|
||||
}
|
||||
|
||||
function defaultResponse(method: string, initial: InitialData): unknown {
|
||||
switch (method) {
|
||||
case 'listProfiles':
|
||||
return { ok: true, profiles: initial.profiles ?? [PROFILE] }
|
||||
case 'listWorkspaces':
|
||||
return { ok: true, workspaces: initial.workspaces ?? WORKSPACES }
|
||||
case 'getPrefs':
|
||||
return { ok: true, prefs: initial.prefs ?? PREFS }
|
||||
case 'listSshConfigHosts':
|
||||
return { ok: true, hosts: initial.hosts ?? SSH_HOSTS }
|
||||
case 'saveProfile':
|
||||
return { ok: true, id: 'p-new', profiles: initial.profiles ?? [PROFILE] }
|
||||
case 'updateWorkspaceGuards':
|
||||
return { ok: true, workspaces: initial.workspaces ?? WORKSPACES }
|
||||
case 'savePrefs':
|
||||
return { ok: true }
|
||||
case 'testConnection':
|
||||
return { ok: true, stdout: 'connected' }
|
||||
case 'syncDown':
|
||||
case 'syncUp':
|
||||
return { ok: true }
|
||||
case 'deleteProfile':
|
||||
return { ok: true, profiles: [], workspaces: [] }
|
||||
case 'deleteWorkspace':
|
||||
return { ok: true, workspaces: [] }
|
||||
default:
|
||||
return { ok: true }
|
||||
}
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
api: RemoteSshApi
|
||||
mock: ReturnType<typeof vi.fn>
|
||||
/** Argument objects of every call to one api method (in order). */
|
||||
calls: (method: string) => unknown[]
|
||||
}
|
||||
|
||||
function createFakeApi(options: { initial?: InitialData; handlers?: Record<string, Handler> } = {}): Harness {
|
||||
const initial = options.initial ?? {}
|
||||
const counters: Record<string, number> = {}
|
||||
const mock = vi.fn(async (method: string, args?: unknown) => {
|
||||
const index = counters[method] ?? 0
|
||||
counters[method] = index + 1
|
||||
const handler = options.handlers?.[method]
|
||||
if (handler) return await handler(args, index)
|
||||
return defaultResponse(method, initial)
|
||||
})
|
||||
return {
|
||||
api: mock as unknown as RemoteSshApi,
|
||||
mock,
|
||||
calls: (method: string) => mock.mock.calls.filter(call => call[0] === method).map(call => call[1]),
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Mounting + DOM helpers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
interface Mounted {
|
||||
root: Root
|
||||
container: HTMLDivElement
|
||||
}
|
||||
|
||||
let mounted: Mounted[] = []
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
for (const entry of mounted) entry.root.unmount()
|
||||
})
|
||||
for (const entry of mounted) entry.container.remove()
|
||||
mounted = []
|
||||
})
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
await act(async () => {
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0))
|
||||
})
|
||||
}
|
||||
|
||||
async function settle(rounds = 4): Promise<void> {
|
||||
for (let i = 0; i < rounds; i += 1) await flush()
|
||||
}
|
||||
|
||||
async function waitFor(predicate: () => boolean, label: string): Promise<void> {
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
if (predicate()) return
|
||||
await flush()
|
||||
}
|
||||
throw new Error(`timed out waiting for ${label}`)
|
||||
}
|
||||
|
||||
function q(container: ParentNode, selector: string): HTMLElement | null {
|
||||
return container.querySelector(selector) as HTMLElement | null
|
||||
}
|
||||
|
||||
function need(container: ParentNode, selector: string): HTMLElement {
|
||||
const el = q(container, selector)
|
||||
if (!el) throw new Error(`missing element: ${selector}`)
|
||||
return el
|
||||
}
|
||||
|
||||
function text(container: ParentNode): string {
|
||||
return container.textContent ?? ''
|
||||
}
|
||||
|
||||
/** Set a controlled input/textarea/select the way a user would type. */
|
||||
function setValue(el: HTMLElement, value: string): void {
|
||||
const proto = Object.getPrototypeOf(el) as object
|
||||
const descriptor = Object.getOwnPropertyDescriptor(proto, 'value')
|
||||
if (!descriptor?.set) throw new Error(`element ${el.tagName} has no value setter`)
|
||||
act(() => {
|
||||
descriptor.set!.call(el, value)
|
||||
el.dispatchEvent(new Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }))
|
||||
})
|
||||
}
|
||||
|
||||
function clickSync(el: Element | null | undefined): void {
|
||||
if (!el) throw new Error('click target missing')
|
||||
act(() => {
|
||||
;(el as HTMLElement).click()
|
||||
})
|
||||
}
|
||||
|
||||
async function click(el: Element | null | undefined): Promise<void> {
|
||||
clickSync(el)
|
||||
await settle()
|
||||
}
|
||||
|
||||
function value(el: HTMLElement): string {
|
||||
return (el as HTMLInputElement | HTMLTextAreaElement).value
|
||||
}
|
||||
|
||||
function isVisiblyHidden(el: HTMLElement | null): boolean {
|
||||
if (!el) return true
|
||||
let node: HTMLElement | null = el
|
||||
while (node) {
|
||||
if (node.hasAttribute('hidden') || node.getAttribute('aria-hidden') === 'true') return true
|
||||
node = node.parentElement
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** The labelled control inside a card/section (spec: every input has label htmlFor). */
|
||||
function controlByLabel(scope: ParentNode, labelPart: string): HTMLInputElement | HTMLTextAreaElement {
|
||||
const labels = Array.from(scope.querySelectorAll('label'))
|
||||
const label = labels.find(candidate => (candidate.textContent ?? '').includes(labelPart))
|
||||
if (!label) throw new Error(`no label containing "${labelPart}"`)
|
||||
const id = label.htmlFor
|
||||
const byId = id ? (document.getElementById(id) as HTMLElement | null) : null
|
||||
if (byId) return byId as HTMLInputElement | HTMLTextAreaElement
|
||||
const sibling = label.nextElementSibling
|
||||
if (sibling && /^(INPUT|TEXTAREA|SELECT)$/.test(sibling.tagName)) {
|
||||
return sibling as HTMLInputElement | HTMLTextAreaElement
|
||||
}
|
||||
throw new Error(`label for "${labelPart}" is not associated with a control`)
|
||||
}
|
||||
|
||||
function workspaceCard(section: ParentNode, id: string): HTMLElement {
|
||||
return need(section, `[data-rsui-workspace][data-workspace-id="${id}"]`)
|
||||
}
|
||||
|
||||
async function expandWorkspacesSection(root: HTMLElement): Promise<void> {
|
||||
const toggle = need(root, '[data-rsui-toggle-workspaces]')
|
||||
if (toggle.getAttribute('aria-expanded') !== 'true') await click(toggle)
|
||||
}
|
||||
|
||||
interface MountOptions {
|
||||
initial?: InitialData
|
||||
handlers?: Record<string, Handler>
|
||||
}
|
||||
|
||||
async function mount(options: MountOptions = {}): Promise<Harness & { container: HTMLDivElement }> {
|
||||
const harness = createFakeApi(options)
|
||||
const Section = createSettingsSection({ api: harness.api })
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root = createRoot(container)
|
||||
mounted.push({ root, container })
|
||||
await act(async () => {
|
||||
root.render(React.createElement(Section, { t }))
|
||||
})
|
||||
await settle(6)
|
||||
return { ...harness, container }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Collapsing must never drop drafts */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('collapsible sections keep their drafts', () => {
|
||||
it('collapsing and re-expanding "add connection" keeps host and proxyJump', async () => {
|
||||
const { container } = await mount()
|
||||
expect(need(container, '[data-rsui-field="host"]')).toBeTruthy()
|
||||
|
||||
setValue(need(container, '[data-rsui-field="host"]'), 'draft.example.com')
|
||||
await click(need(container, '[data-rsui-toggle-more]'))
|
||||
setValue(need(container, '[data-rsui-field="proxyJump"]'), 'bastion.example.com')
|
||||
await click(need(container, '[data-rsui-toggle-more]'))
|
||||
|
||||
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(false)
|
||||
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||
expect(value(need(container, '[data-rsui-field="proxyJump"]'))).toBe('bastion.example.com')
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-add]'))
|
||||
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(true)
|
||||
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-add]'))
|
||||
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(false)
|
||||
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||
expect(value(need(container, '[data-rsui-field="proxyJump"]'))).toBe('bastion.example.com')
|
||||
})
|
||||
|
||||
it('collapsing the remote-workspace section keeps the workspace field draft', async () => {
|
||||
const { container } = await mount()
|
||||
await expandWorkspacesSection(container)
|
||||
|
||||
const card = workspaceCard(container, 'ws-a')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
|
||||
const writeBackExclude = controlByLabel(card, '写回排除')
|
||||
setValue(writeBackExclude, '_patch/, *.log, tmp/')
|
||||
const syncMaxBytes = controlByLabel(card, '同步体积上限')
|
||||
setValue(syncMaxBytes, '3')
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-workspaces]'))
|
||||
expect(isVisiblyHidden(q(card, '[data-rsui-ws-save]'))).toBe(true)
|
||||
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, *.log, tmp/')
|
||||
expect(value(controlByLabel(card, '同步体积上限'))).toBe('3')
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-workspaces]'))
|
||||
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, *.log, tmp/')
|
||||
expect(value(controlByLabel(card, '同步体积上限'))).toBe('3')
|
||||
})
|
||||
|
||||
it('advanced settings start collapsed with the save button hidden, and keep nodePath', async () => {
|
||||
const { container } = await mount()
|
||||
|
||||
const content = need(container, '[data-rsui-advanced-content]')
|
||||
expect(isVisiblyHidden(content)).toBe(true)
|
||||
const save = q(container, '[data-rsui-prefs-save]')
|
||||
expect(save).not.toBeNull()
|
||||
expect(isVisiblyHidden(save)).toBe(true)
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||
expect(isVisiblyHidden(need(container, '[data-rsui-advanced-content]'))).toBe(false)
|
||||
expect(isVisiblyHidden(q(container, '[data-rsui-prefs-save]'))).toBe(false)
|
||||
|
||||
const nodePath = need(container, '[data-rsui-field="nodePath"]')
|
||||
setValue(nodePath, '/custom/node.exe')
|
||||
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||
expect(isVisiblyHidden(need(container, '[data-rsui-advanced-content]'))).toBe(true)
|
||||
expect(value(need(container, '[data-rsui-field="nodePath"]'))).toBe('/custom/node.exe')
|
||||
|
||||
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||
expect(value(need(container, '[data-rsui-field="nodePath"]'))).toBe('/custom/node.exe')
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Per-workspace guards */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('workspace guard saving', () => {
|
||||
it('saves the right workspace id with GiB→bytes and no global fields', async () => {
|
||||
const updated = WORKSPACES.map(workspace =>
|
||||
workspace.id === 'ws-b' ? { ...workspace, syncMaxBytes: 3 * 1073741824, writeBackExclude: ['tmp/'] } : workspace,
|
||||
)
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
updateWorkspaceGuards: () => ({ ok: true, workspaces: updated }),
|
||||
},
|
||||
})
|
||||
await expandWorkspacesSection(harness.container)
|
||||
|
||||
const card = workspaceCard(harness.container, 'ws-b')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
const syncMaxBytes = controlByLabel(card, '同步体积上限')
|
||||
setValue(syncMaxBytes, '3')
|
||||
const writeBackExclude = controlByLabel(card, '写回排除')
|
||||
setValue(writeBackExclude, 'tmp/')
|
||||
|
||||
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||
|
||||
await click(need(card, '[data-rsui-ws-save]'))
|
||||
await waitFor(() => harness.calls('updateWorkspaceGuards').length === 1, 'updateWorkspaceGuards call')
|
||||
|
||||
const payload = harness.calls('updateWorkspaceGuards')[0] as UpdateWorkspaceGuardsPayload
|
||||
expect(payload).toEqual({
|
||||
id: 'ws-b',
|
||||
writeBack: false,
|
||||
writeBackExclude: ['tmp/'],
|
||||
syncPaths: [],
|
||||
syncExclude: [],
|
||||
syncMaxBytes: 3221225472,
|
||||
})
|
||||
expect(payload).not.toHaveProperty('proxyJump')
|
||||
expect(payload).not.toHaveProperty('nodePath')
|
||||
expect(harness.calls('savePrefs')).toHaveLength(0)
|
||||
|
||||
// Successful save recalculates the baseline: the dirty badge disappears.
|
||||
await settle()
|
||||
expect(q(card, '[data-rsui-ws-dirty]')).toBeNull()
|
||||
})
|
||||
|
||||
it('a failed save keeps the typed draft and shows the error', async () => {
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
updateWorkspaceGuards: () => ({ ok: false, error: 'guards denied' }),
|
||||
},
|
||||
})
|
||||
await expandWorkspacesSection(harness.container)
|
||||
|
||||
const card = workspaceCard(harness.container, 'ws-a')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
setValue(controlByLabel(card, '写回排除'), '_patch/, tmp/')
|
||||
|
||||
await click(need(card, '[data-rsui-ws-save]'))
|
||||
await waitFor(() => text(card).includes('guards denied'), 'save error text')
|
||||
|
||||
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, tmp/')
|
||||
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||
expect(value(controlByLabel(card, '同步体积上限'))).toBe('2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('pull / push gating', () => {
|
||||
it('a dirty workspace refuses pull and push and asks for a save first', async () => {
|
||||
const harness = await mount()
|
||||
await expandWorkspacesSection(harness.container)
|
||||
const card = workspaceCard(harness.container, 'ws-a')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-sync]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
|
||||
setValue(controlByLabel(card, '写回排除'), '_patch/, typed/')
|
||||
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||
|
||||
await click(need(card, '[data-rsui-ws-sync]'))
|
||||
expect(harness.calls('syncDown')).toHaveLength(0)
|
||||
expect(text(card)).toContain(zh['workspace.syncBlocked'])
|
||||
|
||||
await click(need(card, '[data-rsui-ws-push]'))
|
||||
expect(harness.calls('syncUp')).toHaveLength(0)
|
||||
expect(text(card)).toContain(zh['workspace.syncBlocked'])
|
||||
})
|
||||
|
||||
it('after saving, pull runs with the workspace id', async () => {
|
||||
const updated = WORKSPACES.map(workspace =>
|
||||
workspace.id === 'ws-a' ? { ...workspace, writeBackExclude: ['_patch/', 'typed/'] } : workspace,
|
||||
)
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
updateWorkspaceGuards: () => ({ ok: true, workspaces: updated }),
|
||||
},
|
||||
})
|
||||
await expandWorkspacesSection(harness.container)
|
||||
const card = workspaceCard(harness.container, 'ws-a')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
|
||||
setValue(controlByLabel(card, '写回排除'), '_patch/, typed/')
|
||||
await click(need(card, '[data-rsui-ws-save]'))
|
||||
await waitFor(() => harness.calls('updateWorkspaceGuards').length === 1, 'guard save')
|
||||
await settle()
|
||||
expect(q(card, '[data-rsui-ws-dirty]')).toBeNull()
|
||||
|
||||
await click(need(card, '[data-rsui-ws-sync]'))
|
||||
await waitFor(() => harness.calls('syncDown').length === 1, 'syncDown')
|
||||
expect(harness.calls('syncDown')[0]).toEqual({ id: 'ws-a' })
|
||||
expect(text(card)).toContain(zh['workspace.syncDone'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('sync failure recovery', () => {
|
||||
it('clears the busy state after a failed sync so the action can be retried', async () => {
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
syncDown: (_args, index) => (index === 0 ? { ok: false, error: 'sync exploded' } : { ok: true }),
|
||||
},
|
||||
})
|
||||
await expandWorkspacesSection(harness.container)
|
||||
const card = workspaceCard(harness.container, 'ws-a')
|
||||
if (isVisiblyHidden(q(card, '[data-rsui-ws-sync]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||
const otherCard = workspaceCard(harness.container, 'ws-b')
|
||||
if (isVisiblyHidden(q(otherCard, '[data-rsui-ws-sync]'))) await click(need(otherCard, '[data-rsui-ws-expand]'))
|
||||
|
||||
const sync = need(card, '[data-rsui-ws-sync]') as HTMLButtonElement
|
||||
await click(sync)
|
||||
await waitFor(() => text(card).includes('sync exploded'), 'sync failure text')
|
||||
|
||||
expect(sync.disabled).toBe(false)
|
||||
expect(sync.getAttribute('aria-busy')).not.toBe('true')
|
||||
expect(text(card)).not.toContain(zh['workspace.syncing'])
|
||||
const otherSync = need(otherCard, '[data-rsui-ws-sync]') as HTMLButtonElement
|
||||
expect(otherSync.disabled).toBe(false)
|
||||
|
||||
await click(sync)
|
||||
await waitFor(() => harness.calls('syncDown').length === 2, 'second syncDown')
|
||||
expect(text(card)).toContain(zh['workspace.syncDone'])
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Import dialog */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('SSH config import feedback', () => {
|
||||
it('reports partial failures per host, never "all imported", and retries only failures', async () => {
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
saveProfile: (args, index) => {
|
||||
const name = (args as SaveProfilePayload).name
|
||||
if (index === 0) return { ok: true }
|
||||
if (index === 1) return { ok: false, error: 'duplicate host' }
|
||||
if (index === 2) throw new Error('network down')
|
||||
// retry calls (only the failed hosts are resubmitted)
|
||||
return { ok: true, name }
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await click(need(harness.container, '[data-rsui-import-open]'))
|
||||
await waitFor(
|
||||
() => harness.container.querySelectorAll('[data-rsui-import-row]').length === SSH_HOSTS.length,
|
||||
'import host rows',
|
||||
)
|
||||
|
||||
await click(need(harness.container, '[data-rsui-import-submit]'))
|
||||
await waitFor(() => q(harness.container, '[data-rsui-import-result]') !== null, 'import result')
|
||||
|
||||
const result = need(harness.container, '[data-rsui-import-result]')
|
||||
const resultText = text(result)
|
||||
expect(resultText).toContain('成功 1 个,失败 2 个')
|
||||
expect(resultText).not.toContain('已导入')
|
||||
expect(resultText).toContain('beta')
|
||||
expect(resultText).toContain('gamma')
|
||||
expect(resultText).toContain('duplicate host')
|
||||
expect(resultText).toContain('network down')
|
||||
|
||||
const retry = q(harness.container, '[data-rsui-import-retry]')
|
||||
expect(retry, 'retry-failed button').not.toBeNull()
|
||||
expect(text(retry as HTMLElement)).toContain('仅重试失败项')
|
||||
expect(text(retry as HTMLElement)).toContain('2')
|
||||
|
||||
const saveCalls = () => harness.calls('saveProfile') as SaveProfilePayload[]
|
||||
expect(saveCalls().map(payload => payload.name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||
|
||||
await click(retry)
|
||||
await waitFor(() => saveCalls().length === 5, 'retried saves')
|
||||
expect(saveCalls().map(payload => payload.name)).toEqual(['alpha', 'beta', 'gamma', 'beta', 'gamma'])
|
||||
expect(saveCalls().filter(payload => payload.name === 'alpha')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('shows a successful retry as fully imported', async () => {
|
||||
const harness = await mount({
|
||||
handlers: {
|
||||
saveProfile: (_args, index) => (index === 0 ? { ok: false, error: 'denied' } : { ok: true }),
|
||||
},
|
||||
})
|
||||
await click(need(harness.container, '[data-rsui-import-open]'))
|
||||
await waitFor(
|
||||
() => harness.container.querySelectorAll('[data-rsui-import-row]').length === SSH_HOSTS.length,
|
||||
'import host rows',
|
||||
)
|
||||
// Select a single host only, so a retry of that host fully succeeds.
|
||||
await click(need(harness.container, '[data-rsui-import-clear]'))
|
||||
const firstRow = need(harness.container, '[data-rsui-import-row]')
|
||||
const checkbox = firstRow.querySelector('input[type="checkbox"]')
|
||||
expect(checkbox).not.toBeNull()
|
||||
await click(checkbox)
|
||||
|
||||
await click(need(harness.container, '[data-rsui-import-submit]'))
|
||||
await waitFor(() => q(harness.container, '[data-rsui-import-result]') !== null, 'import result')
|
||||
expect(text(need(harness.container, '[data-rsui-import-result]'))).toContain('全部失败')
|
||||
|
||||
await click(need(harness.container, '[data-rsui-import-retry]'))
|
||||
await waitFor(() => harness.calls('saveProfile').length === 2, 'retry save')
|
||||
await settle()
|
||||
expect(text(need(harness.container, '[data-rsui-import-result]'))).toContain('已导入 1 个连接')
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Add connection */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('add connection form', () => {
|
||||
function fillConnection(container: HTMLElement, fields: Partial<Record<'name' | 'host' | 'user' | 'port', string>>): void {
|
||||
for (const [field, fieldValue] of Object.entries(fields)) {
|
||||
setValue(need(container, `[data-rsui-field="${field}"]`), fieldValue as string)
|
||||
}
|
||||
}
|
||||
|
||||
it('a successful add resets the form and reports the added name', async () => {
|
||||
const harness = await mount()
|
||||
fillConnection(harness.container, { name: 'New HPC', host: 'new.example.com', user: 'alice', port: '2222' })
|
||||
|
||||
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||
await waitFor(() => harness.calls('saveProfile').length === 1, 'saveProfile')
|
||||
await settle()
|
||||
|
||||
const payload = harness.calls('saveProfile')[0] as SaveProfilePayload
|
||||
expect(payload).toMatchObject({
|
||||
name: 'New HPC',
|
||||
host: 'new.example.com',
|
||||
user: 'alice',
|
||||
port: 2222,
|
||||
authMethod: 'key',
|
||||
})
|
||||
expect(harness.container.textContent).toContain('已添加连接「New HPC」')
|
||||
|
||||
expect(value(need(harness.container, '[data-rsui-field="host"]'))).toBe('')
|
||||
expect(value(need(harness.container, '[data-rsui-field="user"]'))).toBe('')
|
||||
expect(value(need(harness.container, '[data-rsui-field="port"]'))).toBe('22')
|
||||
})
|
||||
|
||||
it('a failed add keeps the input and shows the error', async () => {
|
||||
const harness = await mount({
|
||||
handlers: { saveProfile: () => ({ ok: false, error: 'profile denied' }) },
|
||||
})
|
||||
fillConnection(harness.container, { host: 'keep.example.com', user: 'alice' })
|
||||
|
||||
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||
await waitFor(() => text(harness.container).includes('profile denied'), 'add error')
|
||||
|
||||
expect(value(need(harness.container, '[data-rsui-field="host"]'))).toBe('keep.example.com')
|
||||
expect(value(need(harness.container, '[data-rsui-field="user"]'))).toBe('alice')
|
||||
})
|
||||
|
||||
it('an invalid port blocks submission instead of posting 22', async () => {
|
||||
const harness = await mount()
|
||||
fillConnection(harness.container, { host: 'port.example.com', user: 'alice', port: 'abc' })
|
||||
|
||||
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||
await settle()
|
||||
|
||||
expect(harness.calls('saveProfile')).toHaveLength(0)
|
||||
expect(text(harness.container)).toContain(zh['add.errPort'])
|
||||
expect(value(need(harness.container, '[data-rsui-field="port"]'))).toBe('abc')
|
||||
})
|
||||
})
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Global preferences */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
describe('global preferences', () => {
|
||||
it('saving prefs posts the prefs payload and never writes workspace guards', async () => {
|
||||
const saved: RemoteSshPrefs = { ...PREFS, nodePath: '/custom/node.exe' }
|
||||
const harness = await mount({
|
||||
handlers: { savePrefs: () => ({ ok: true, prefs: saved }) },
|
||||
})
|
||||
|
||||
await click(need(harness.container, '[data-rsui-toggle-advanced]'))
|
||||
setValue(need(harness.container, '[data-rsui-field="nodePath"]'), ' /custom/node.exe ')
|
||||
await click(need(harness.container, '[data-rsui-prefs-save]'))
|
||||
await waitFor(() => harness.calls('savePrefs').length === 1, 'savePrefs')
|
||||
|
||||
const payload = harness.calls('savePrefs')[0] as SavePrefsPayload
|
||||
expect(payload.nodePath).toBe('/custom/node.exe')
|
||||
expect(payload.writeBackFailure).toBe('error')
|
||||
expect(payload.writeBackFreshness).toBe(true)
|
||||
expect(payload.defaultSyncPaths).toEqual([])
|
||||
expect(payload.defaultSyncMaxBytes).toBe(0)
|
||||
|
||||
expect(harness.calls('updateWorkspaceGuards')).toHaveLength(0)
|
||||
expect(text(harness.container)).toContain(zh['advanced.saved'])
|
||||
expect(q(harness.container, '[data-rsui-ws-dirty]')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -13,8 +13,8 @@ import { describe, expect, it } from 'vitest'
|
|||
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import { deriveGroups, deriveSearchGroups, deriveTopLevel } from '../src/client/tree.ts'
|
||||
import type { FoldersDocument } from '../src/core/folders.ts'
|
||||
import type { GroupsConfig, ManualGroups } from '../src/core/types.ts'
|
||||
import type { FoldersDocument } from '../src/core/folders.ts'
|
||||
|
||||
const CONFIG: GroupsConfig = {
|
||||
categories: [
|
||||
|
|
@ -180,6 +180,39 @@ describe('category appearance on the tree nodes', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('folder rows use confirmed display names', () => {
|
||||
it('base row shows the project title, not the local mirror basename', () => {
|
||||
const ws = workspace('ws-remote', 'C:/mirror/w123', '远程项目', ['s1'])
|
||||
const folders: FoldersDocument = {
|
||||
version: 1,
|
||||
revision: 1,
|
||||
workspaces: {
|
||||
'ws-remote': {
|
||||
folders: ['C:/mirror/w123/extra'],
|
||||
members: [{
|
||||
path: 'C:/mirror/w123/extra',
|
||||
workspaceId: 'ws-extra',
|
||||
kind: 'remote',
|
||||
remotePath: '/srv/proj/extra',
|
||||
profileId: 'prof-1',
|
||||
title: 'extra-remote',
|
||||
}],
|
||||
},
|
||||
},
|
||||
}
|
||||
const view = { expandedCategories: [], expandedWorkspaces: ['ws-remote'] }
|
||||
const top = deriveTopLevel(listState([ws], 's1'), [ws], [], CONFIG, view, { categories: [], assignments: {} }, new Map(), folders)
|
||||
const node = top.find(item => item.workspaceId === 'ws-remote')
|
||||
expect(node).toBeDefined()
|
||||
const base = node?.folders?.find(folder => folder.isBase)
|
||||
const member = node?.folders?.find(folder => !folder.isBase)
|
||||
expect(base?.label).toBe('远程项目')
|
||||
expect(member?.label).toBe('extra-remote')
|
||||
// The underlying path identity is untouched.
|
||||
expect(base?.path).toBe('C:/mirror/w123')
|
||||
})
|
||||
})
|
||||
|
||||
describe('deriveTopLevel', () => {
|
||||
const ws = [
|
||||
workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo'),
|
||||
|
|
@ -216,58 +249,3 @@ describe('deriveTopLevel', () => {
|
|||
expect(top.map(w => w.workspaceId)).toEqual(['ws-c', 'ws-a', 'ws-b'])
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* A project renders as ONE row: its own directory and every extra folder share
|
||||
* that workspace's session list, so a cloud project never reads as a project
|
||||
* nested inside itself and its mirror id never surfaces as a folder name.
|
||||
*/
|
||||
describe('a project renders as one row', () => {
|
||||
const MIRROR = 'C:/Users/zcol/.dsh/remote-workspaces/wmvl31c7ilkuc'
|
||||
const LOCAL = 'C:/Users/zcol/云端记忆系统'
|
||||
|
||||
function sessionIn(id: string, cwd: string): SessionSummary {
|
||||
return { ...session(id, `会话-${id}`), cwd } as unknown as SessionSummary
|
||||
}
|
||||
|
||||
const workspaces = [
|
||||
workspace('ws-o', MIRROR, '插件项目', ['s-cloud']),
|
||||
workspace('ws-m', LOCAL, '云端记忆系统', ['s-local']),
|
||||
]
|
||||
const folders: FoldersDocument = {
|
||||
version: 1,
|
||||
workspaces: {
|
||||
'ws-o': { folders: [], members: [{ path: LOCAL, workspaceId: 'ws-m', kind: 'local' }] },
|
||||
},
|
||||
}
|
||||
const list = {
|
||||
ids: ['s-cloud', 's-local'],
|
||||
byId: {
|
||||
's-cloud': sessionIn('s-cloud', `${MIRROR}/src`),
|
||||
's-local': sessionIn('s-local', `${LOCAL}/docs`),
|
||||
},
|
||||
current: undefined,
|
||||
phase: 'ready',
|
||||
subagentsByParent: {},
|
||||
} as unknown as SessionListState
|
||||
const noManual: ManualGroups = { categories: [], assignments: {} }
|
||||
const view = { expandedCategories: [], expandedWorkspaces: ['ws-o'] }
|
||||
|
||||
it('merges owner and member sessions and emits no folder rows', () => {
|
||||
const groups = deriveGroups(list, workspaces, [], CONFIG, view, noManual, new Map(), folders)
|
||||
const node = groups.flatMap(group => group.workspaces).find(w => w.workspaceId === 'ws-o')
|
||||
expect(node).toBeDefined()
|
||||
expect(node!.folders).toBeUndefined()
|
||||
expect(node!.sessions.map(s => s.id)).toEqual(['s-cloud', 's-local'])
|
||||
})
|
||||
|
||||
it('keeps the pre-folders node shape without extras', () => {
|
||||
const groups = deriveGroups(list, workspaces, [], CONFIG, view, noManual, new Map(), {
|
||||
version: 1,
|
||||
workspaces: {},
|
||||
})
|
||||
const node = groups.flatMap(group => group.workspaces).find(w => w.workspaceId === 'ws-o')
|
||||
expect(node?.folders).toBeUndefined()
|
||||
expect(node?.sessions.map(s => s.id)).toEqual(['s-cloud'])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -0,0 +1,396 @@
|
|||
/**
|
||||
* Fake `/remote-ssh/api/*` data layer for the ISOLATED preview.
|
||||
*
|
||||
* This never talks to the real Host. Every response is local, deterministic
|
||||
* and in-memory, so the preview screenshots show the real component rendered
|
||||
* against controlled data (including the failure states the real API can
|
||||
* produce). No real password or private key ever exists here: password
|
||||
* profiles only carry `passwordConfigured: true` (the redacted projection the
|
||||
* Host actually returns).
|
||||
*/
|
||||
import type {
|
||||
DeleteProfileResponse,
|
||||
DeleteWorkspaceResponse,
|
||||
GetPrefsResponse,
|
||||
ListProfilesResponse,
|
||||
ListSshConfigHostsResponse,
|
||||
ListWorkspacesResponse,
|
||||
RemoteSshApi,
|
||||
RemoteSshPrefs,
|
||||
RemoteSshProfile,
|
||||
RemoteSshWorkspace,
|
||||
SavePrefsPayload,
|
||||
SavePrefsResponse,
|
||||
SaveProfilePayload,
|
||||
SaveProfileResponse,
|
||||
SshConfigHost,
|
||||
SyncResponse,
|
||||
TestConnectionResponse,
|
||||
UpdateWorkspaceGuardsPayload,
|
||||
UpdateWorkspaceGuardsResponse,
|
||||
} from '../../src/client/rssh-settings/contract.ts'
|
||||
|
||||
export type PreviewScene =
|
||||
| 'default'
|
||||
| 'expanded'
|
||||
| 'import-ready'
|
||||
| 'import-partial'
|
||||
| 'workspaces'
|
||||
| 'password'
|
||||
| 'test-failure'
|
||||
|
||||
export const PREVIEW_SCENES: readonly PreviewScene[] = [
|
||||
'default',
|
||||
'expanded',
|
||||
'import-ready',
|
||||
'import-partial',
|
||||
'workspaces',
|
||||
'password',
|
||||
'test-failure',
|
||||
] as const
|
||||
|
||||
export function isPreviewScene(value: string): value is PreviewScene {
|
||||
return (PREVIEW_SCENES as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** Deterministic latency so busy states appear, then settle (no polling of a clock). */
|
||||
const API_LATENCY_MS = 130
|
||||
|
||||
const delay = (ms: number): Promise<void> =>
|
||||
new Promise<void>(resolve => {
|
||||
setTimeout(resolve, ms)
|
||||
})
|
||||
|
||||
/** Approximates the Host's redacted profile projection (no secrets). */
|
||||
const BASE_PROFILES: RemoteSshProfile[] = [
|
||||
{
|
||||
id: 'conn-hpc',
|
||||
name: '超算集群',
|
||||
host: 'login.hpc.example.com',
|
||||
port: 22,
|
||||
user: 'demo-user',
|
||||
authMethod: 'key',
|
||||
keyPath: '~/.ssh/id_ed25519',
|
||||
remoteRoot: '~/project',
|
||||
},
|
||||
{
|
||||
id: 'conn-lab',
|
||||
name: '实验室工作站',
|
||||
host: 'workstation.lab.example.com',
|
||||
port: 22,
|
||||
user: 'lab-user',
|
||||
authMethod: 'password',
|
||||
passwordConfigured: true,
|
||||
remoteRoot: '/home/lab-user/work',
|
||||
},
|
||||
{
|
||||
id: 'conn-gpu',
|
||||
name: 'GPU 节点',
|
||||
host: 'gpu-node-01.cluster.internal.example.com',
|
||||
port: 2222,
|
||||
user: 'gpu-user',
|
||||
authMethod: 'key',
|
||||
keyPath: '~/.ssh/id_ed25519_gpu',
|
||||
remoteRoot: '~/scratch',
|
||||
proxyJump: 'bastion.example.com',
|
||||
},
|
||||
]
|
||||
|
||||
const BASE_WORKSPACES: RemoteSshWorkspace[] = [
|
||||
{
|
||||
id: 'ws-hpc',
|
||||
profileId: 'conn-hpc',
|
||||
title: '项目 A',
|
||||
remotePath: '/home/demo-user/project-a',
|
||||
mirrorPath: 'C:\\Users\\demo\\remote-mirrors\\project-a',
|
||||
writeBack: true,
|
||||
writeBackExclude: ['data/', '*.log', '_patch/'],
|
||||
syncPaths: ['.dsh', 'src'],
|
||||
syncExclude: ['data/', 'node_modules/'],
|
||||
syncMaxBytes: 2 * 1024 * 1024 * 1024,
|
||||
},
|
||||
{
|
||||
id: 'ws-gpu',
|
||||
profileId: 'conn-gpu',
|
||||
title: '训练任务',
|
||||
remotePath: '/home/gpu-user/scratch/long-experiment-directory-name-for-wrapping-check',
|
||||
mirrorPath: 'C:\\Users\\demo\\remote-mirrors\\gpu-run',
|
||||
writeBack: false,
|
||||
writeBackExclude: ['runs/'],
|
||||
syncPaths: ['.dsh', 'configs'],
|
||||
syncExclude: ['runs/', '*.pt'],
|
||||
syncMaxBytes: 4 * 1024 * 1024 * 1024,
|
||||
},
|
||||
]
|
||||
|
||||
const BASE_PREFS: RemoteSshPrefs = {
|
||||
nodePath: '',
|
||||
writeBackFailure: 'error',
|
||||
writeBackFreshness: true,
|
||||
defaultSyncPaths: ['.dsh'],
|
||||
defaultSyncExclude: ['node_modules/', '*.log'],
|
||||
defaultSyncMaxBytes: 0,
|
||||
}
|
||||
|
||||
/** `~/.ssh/config` entries used by the import dialog scenarios. */
|
||||
const SSH_CONFIG_HOSTS: SshConfigHost[] = [
|
||||
{
|
||||
name: 'hpc-login',
|
||||
hostName: 'login.hpc.example.com',
|
||||
port: 22,
|
||||
user: 'demo-user',
|
||||
identityFile: '~/.ssh/id_ed25519',
|
||||
},
|
||||
{
|
||||
name: 'gpu-lab',
|
||||
hostName: 'gpu-node-01.cluster.internal.example.com',
|
||||
port: 2222,
|
||||
user: 'gpu-user',
|
||||
identityFile: '~/.ssh/id_ed25519_gpu',
|
||||
proxyJump: 'bastion.example.com',
|
||||
},
|
||||
{
|
||||
name: 'bastion',
|
||||
hostName: 'bastion.example.com',
|
||||
user: 'jump-user',
|
||||
identityFile: '~/.ssh/id_ed25519',
|
||||
},
|
||||
{
|
||||
name: 'mirror',
|
||||
hostName: 'mirror.example.org',
|
||||
port: 2222,
|
||||
user: 'mirror-user',
|
||||
identityFile: '',
|
||||
},
|
||||
{
|
||||
name: 'broken-host',
|
||||
hostName: 'broken.example.net',
|
||||
user: '',
|
||||
identityFile: '',
|
||||
},
|
||||
]
|
||||
|
||||
/** Hosts the `import-partial` scenario refuses to save on the first attempt. */
|
||||
const PARTIAL_IMPORT_FAILURES: Record<string, string> = {
|
||||
'mirror.example.org': '保存失败:设置表写入被拒绝(示例错误)',
|
||||
'broken.example.net': '保存失败:主机条目缺少有效用户,Host 拒绝该配置(示例错误)',
|
||||
}
|
||||
|
||||
const cloneProfiles = (profiles: RemoteSshProfile[]): RemoteSshProfile[] =>
|
||||
profiles.map(profile => ({ ...profile }))
|
||||
|
||||
const cloneWorkspaces = (workspaces: RemoteSshWorkspace[]): RemoteSshWorkspace[] =>
|
||||
workspaces.map(workspace => ({
|
||||
...workspace,
|
||||
writeBackExclude: workspace.writeBackExclude ? [...workspace.writeBackExclude] : undefined,
|
||||
syncPaths: workspace.syncPaths ? [...workspace.syncPaths] : undefined,
|
||||
syncExclude: workspace.syncExclude ? [...workspace.syncExclude] : undefined,
|
||||
}))
|
||||
|
||||
/** Expose scenario/step counters for the screenshot script's assertions. */
|
||||
interface FakeApiState {
|
||||
scene: PreviewScene
|
||||
calls: string[]
|
||||
mutations: number
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__RSH_PREVIEW_API__?: FakeApiState
|
||||
__RSH_PREVIEW_IDLE__?: boolean
|
||||
__RSH_PREVIEW_READY__?: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the fake typed API. Individual endpoints behave like the Host:
|
||||
* `ok` flags, redacted profiles, per-item import failures, tests that can fail
|
||||
* with diagnostics, and preference/workspace mutations that persist in memory.
|
||||
*/
|
||||
export function createFakeApi(scene: PreviewScene): RemoteSshApi {
|
||||
const state: FakeApiState = { scene, calls: [], mutations: 0 }
|
||||
if (typeof window !== 'undefined') {
|
||||
window.__RSH_PREVIEW_API__ = state
|
||||
window.__RSH_PREVIEW_IDLE__ = true
|
||||
}
|
||||
|
||||
let profiles = cloneProfiles(BASE_PROFILES)
|
||||
let workspaces = cloneWorkspaces(BASE_WORKSPACES)
|
||||
let prefs: RemoteSshPrefs = { ...BASE_PREFS }
|
||||
/** First attempt of each imported host (used by partial-import + retry). */
|
||||
const importAttempts = new Map<string, number>()
|
||||
|
||||
let pending = 0
|
||||
let idleTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const markBusy = (): void => {
|
||||
pending += 1
|
||||
if (typeof window !== 'undefined') window.__RSH_PREVIEW_IDLE__ = false
|
||||
if (idleTimer) clearTimeout(idleTimer)
|
||||
idleTimer = undefined
|
||||
}
|
||||
|
||||
const markSettled = (): void => {
|
||||
pending = Math.max(0, pending - 1)
|
||||
if (pending > 0) return
|
||||
if (idleTimer) clearTimeout(idleTimer)
|
||||
idleTimer = setTimeout(() => {
|
||||
idleTimer = undefined
|
||||
if (pending === 0 && typeof window !== 'undefined') window.__RSH_PREVIEW_IDLE__ = true
|
||||
}, 260)
|
||||
}
|
||||
|
||||
const handle = async (method: string, args?: unknown): Promise<unknown> => {
|
||||
state.calls.push(method)
|
||||
markBusy()
|
||||
try {
|
||||
await delay(API_LATENCY_MS)
|
||||
switch (method) {
|
||||
case 'listProfiles': {
|
||||
const response: ListProfilesResponse = { ok: true, profiles: cloneProfiles(profiles) }
|
||||
return response
|
||||
}
|
||||
case 'saveProfile': {
|
||||
const payload = args as SaveProfilePayload
|
||||
const failingReason =
|
||||
scene === 'import-partial' && PARTIAL_IMPORT_FAILURES[payload.host] !== undefined
|
||||
? PARTIAL_IMPORT_FAILURES[payload.host]
|
||||
: undefined
|
||||
if (payload.host in PARTIAL_IMPORT_FAILURES) {
|
||||
const attempts = (importAttempts.get(payload.host) || 0) + 1
|
||||
importAttempts.set(payload.host, attempts)
|
||||
if (attempts === 1 && failingReason) {
|
||||
const failed: SaveProfileResponse = { ok: false, error: failingReason }
|
||||
return failed
|
||||
}
|
||||
}
|
||||
state.mutations += 1
|
||||
const saved: RemoteSshProfile = {
|
||||
id: `import-${profiles.length + 1}`,
|
||||
name: payload.name || payload.host,
|
||||
host: payload.host,
|
||||
port: payload.port,
|
||||
user: payload.user,
|
||||
authMethod: payload.authMethod,
|
||||
keyPath: payload.keyPath || undefined,
|
||||
remoteRoot: payload.remoteRoot || undefined,
|
||||
proxyJump: payload.proxyJump || undefined,
|
||||
passwordConfigured: payload.authMethod === 'password' ? Boolean(payload.password) : undefined,
|
||||
}
|
||||
profiles = [...profiles, saved]
|
||||
const response: SaveProfileResponse = {
|
||||
ok: true,
|
||||
id: saved.id,
|
||||
profiles: cloneProfiles(profiles),
|
||||
}
|
||||
return response
|
||||
}
|
||||
case 'testConnection': {
|
||||
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||
const profile = profiles.find(item => item.id === id) || profiles[0]
|
||||
if (scene === 'test-failure') {
|
||||
const failed: TestConnectionResponse = {
|
||||
ok: false,
|
||||
error: `ssh: connect to host ${profile?.host || 'login.hpc.example.com'} port ${
|
||||
profile?.port || 22
|
||||
}: Connection timed out`,
|
||||
stderr:
|
||||
`ssh: connect to host ${profile?.host || 'login.hpc.example.com'} port ${
|
||||
profile?.port || 22
|
||||
}: Connection timed out\n` +
|
||||
'kex_exchange_identification: Connection closed by remote host\n' +
|
||||
'Connection closed by 203.0.113.10 port 22',
|
||||
exitCode: 255,
|
||||
}
|
||||
return failed
|
||||
}
|
||||
const ok: TestConnectionResponse = {
|
||||
ok: true,
|
||||
stdout: `Connected to ${profile?.host || 'login.hpc.example.com'} (${profile?.user || 'demo-user'})`,
|
||||
exitCode: 0,
|
||||
}
|
||||
return ok
|
||||
}
|
||||
case 'deleteProfile': {
|
||||
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||
profiles = profiles.filter(item => item.id !== id)
|
||||
workspaces = workspaces.filter(item => item.profileId !== id)
|
||||
state.mutations += 1
|
||||
const response: DeleteProfileResponse = {
|
||||
ok: true,
|
||||
profiles: cloneProfiles(profiles),
|
||||
workspaces: cloneWorkspaces(workspaces),
|
||||
}
|
||||
return response
|
||||
}
|
||||
case 'listSshConfigHosts': {
|
||||
const response: ListSshConfigHostsResponse = { ok: true, hosts: SSH_CONFIG_HOSTS.map(host => ({ ...host })) }
|
||||
return response
|
||||
}
|
||||
case 'listWorkspaces': {
|
||||
const response: ListWorkspacesResponse = { ok: true, workspaces: cloneWorkspaces(workspaces) }
|
||||
return response
|
||||
}
|
||||
case 'updateWorkspaceGuards': {
|
||||
const payload = args as UpdateWorkspaceGuardsPayload
|
||||
workspaces = workspaces.map(workspace =>
|
||||
workspace.id === payload.id
|
||||
? {
|
||||
...workspace,
|
||||
writeBack: payload.writeBack,
|
||||
writeBackExclude: [...payload.writeBackExclude],
|
||||
syncPaths: [...payload.syncPaths],
|
||||
syncExclude: [...payload.syncExclude],
|
||||
syncMaxBytes: payload.syncMaxBytes,
|
||||
}
|
||||
: workspace,
|
||||
)
|
||||
state.mutations += 1
|
||||
const response: UpdateWorkspaceGuardsResponse = {
|
||||
ok: true,
|
||||
workspaces: cloneWorkspaces(workspaces),
|
||||
}
|
||||
return response
|
||||
}
|
||||
case 'syncDown':
|
||||
case 'syncUp': {
|
||||
state.mutations += 1
|
||||
const response: SyncResponse = { ok: true }
|
||||
return response
|
||||
}
|
||||
case 'deleteWorkspace': {
|
||||
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||
workspaces = workspaces.filter(item => item.id !== id)
|
||||
state.mutations += 1
|
||||
const response: DeleteWorkspaceResponse = { ok: true, workspaces: cloneWorkspaces(workspaces) }
|
||||
return response
|
||||
}
|
||||
case 'getPrefs': {
|
||||
const response: GetPrefsResponse = { ok: true, prefs: { ...prefs, defaultSyncPaths: [...(prefs.defaultSyncPaths || [])], defaultSyncExclude: [...(prefs.defaultSyncExclude || [])] }, deleteSync: true }
|
||||
return response
|
||||
}
|
||||
case 'savePrefs': {
|
||||
const payload = args as SavePrefsPayload
|
||||
prefs = {
|
||||
nodePath: payload.nodePath,
|
||||
writeBackFailure: payload.writeBackFailure,
|
||||
writeBackFreshness: payload.writeBackFreshness,
|
||||
defaultSyncPaths: [...payload.defaultSyncPaths],
|
||||
defaultSyncExclude: [...payload.defaultSyncExclude],
|
||||
defaultSyncMaxBytes: payload.defaultSyncMaxBytes,
|
||||
}
|
||||
state.mutations += 1
|
||||
const response: SavePrefsResponse = { ok: true, prefs: { ...prefs } }
|
||||
return response
|
||||
}
|
||||
default: {
|
||||
return { ok: false, error: `fake api: unknown method ${method}` }
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
markSettled()
|
||||
}
|
||||
}
|
||||
|
||||
return handle as RemoteSshApi
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
/**
|
||||
* Entry of the ISOLATED Remote-SSH settings preview.
|
||||
*
|
||||
* Renders the REAL built section (`src/client/rssh-settings/index.tsx` →
|
||||
* `createSettingsSection({ api })`) under a stand-in DSH settings panel,
|
||||
* against the fake `/remote-ssh/api` layer. Nothing here touches the running
|
||||
* DSH GUI, the daily profile or node_modules.
|
||||
*
|
||||
* URL query:
|
||||
* ?scene=default|expanded|import-ready|import-partial|workspaces|password|test-failure
|
||||
* &theme=light|dark
|
||||
* &width=narrow (viewport width is still set by the screenshot script)
|
||||
*/
|
||||
import { useEffect } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { createSettingsSection } from '#rssh-settings'
|
||||
import { SETTINGS_CSS } from '../../src/client/rssh-settings/styles.ts'
|
||||
import previewCss from './preview.css?inline'
|
||||
import { createFakeApi, isPreviewScene } from './fake-api.ts'
|
||||
import { EXPECTED_MOUNT_TEXT, makeT } from './translate.ts'
|
||||
import type { PreviewScene } from './fake-api.ts'
|
||||
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const sceneParam = params.get('scene') || 'default'
|
||||
const scene: PreviewScene = isPreviewScene(sceneParam) ? sceneParam : 'default'
|
||||
const theme = params.get('theme') === 'dark' ? 'dark' : 'light'
|
||||
const width = params.get('width') === 'narrow' ? 'narrow' : 'wide'
|
||||
|
||||
document.documentElement.dataset.theme = theme
|
||||
document.documentElement.dataset.width = width
|
||||
document.documentElement.dataset.previewScene = scene
|
||||
document.documentElement.dataset.isolatedPreview = '1'
|
||||
|
||||
// The real section only ships CSS as a string (`styles.ts`); the shell normally
|
||||
// injects it beside the vendored client's stylesheet. The preview stands in for
|
||||
// that shell injection, then adds its own panel/token styles afterwards.
|
||||
const settingsStyle = document.createElement('style')
|
||||
settingsStyle.id = 'rssh-settings-css'
|
||||
settingsStyle.textContent = SETTINGS_CSS
|
||||
document.head.appendChild(settingsStyle)
|
||||
|
||||
const style = document.createElement('style')
|
||||
style.id = 'preview-shell-css'
|
||||
style.textContent = previewCss
|
||||
document.head.appendChild(style)
|
||||
|
||||
const previewWindow = window as unknown as Record<string, unknown>
|
||||
previewWindow.__RSH_PREVIEW_SCENE__ = scene
|
||||
previewWindow.__RSH_PREVIEW_THEME__ = theme
|
||||
previewWindow.__RSH_PREVIEW_WIDTH__ = width
|
||||
previewWindow.__RSH_PREVIEW_EXPECTED_TEXT__ = EXPECTED_MOUNT_TEXT
|
||||
|
||||
const api = createFakeApi(scene)
|
||||
const t = makeT()
|
||||
|
||||
let SettingsSection: ReturnType<typeof createSettingsSection> | null = null
|
||||
let createError = ''
|
||||
try {
|
||||
SettingsSection = createSettingsSection({ api })
|
||||
} catch (error) {
|
||||
createError = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
|
||||
console.error('[preview] createSettingsSection threw', error)
|
||||
}
|
||||
|
||||
const sceneLabel: Record<PreviewScene, string> = {
|
||||
default: '默认(高级设置收起)',
|
||||
expanded: '全部展开',
|
||||
'import-ready': '导入弹窗(全部可导入)',
|
||||
'import-partial': '导入部分失败',
|
||||
workspaces: '远程工作区配置',
|
||||
password: '密码认证表单',
|
||||
'test-failure': '连接测试失败',
|
||||
}
|
||||
|
||||
function PreviewApp() {
|
||||
useEffect(() => {
|
||||
const markReady = (): void => {
|
||||
previewWindow.__RSH_PREVIEW_READY__ = true
|
||||
document.documentElement.dataset.previewReady = '1'
|
||||
}
|
||||
const afterFonts = (): void => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(markReady))
|
||||
}
|
||||
const fonts = (document as unknown as { fonts?: { ready?: Promise<unknown> } }).fonts
|
||||
if (fonts?.ready) {
|
||||
fonts.ready.then(afterFonts).catch(afterFonts)
|
||||
} else {
|
||||
setTimeout(afterFonts, 0)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="preview-page">
|
||||
<div className="preview-shell">
|
||||
<header className="preview-banner" data-preview-banner="isolated">
|
||||
<span className="preview-banner__tag">隔离预览</span>
|
||||
<span className="preview-banner__text">
|
||||
真实组件 + 本地假 API 渲染 · 未接入当前 DSH GUI、未修改 daily profile · 场景:
|
||||
{sceneLabel[scene]} · 主题:{theme === 'dark' ? '深色' : '浅色'} · 宽度:{width === 'narrow' ? '窄屏' : '宽屏'}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
<main className="preview-panel" aria-label="DSH 设置面板容器(预览替身)">
|
||||
<div className="preview-panel__bar">
|
||||
<span className="preview-panel__crumb">设置 / 插件 / Remote SSH</span>
|
||||
<span className="preview-panel__chip">隔离预览容器</span>
|
||||
</div>
|
||||
<div className="preview-panel__body" id="settings-mount">
|
||||
{createError ? (
|
||||
<div role="alert" className="preview-fallback" data-preview-create-error="1">
|
||||
<h1>组件创建失败</h1>
|
||||
<p>{createError}</p>
|
||||
</div>
|
||||
) : SettingsSection ? (
|
||||
<SettingsSection t={t} />
|
||||
) : null}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer className="preview-footer">
|
||||
本页为隔离预览:数据全部来自 tools/preview/fake-api.ts,仅用于视觉核对;不含真实密码、私钥或真实主机凭据,不写入任何浏览器存储。
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('preview-root') as HTMLElement).render(<PreviewApp />)
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
/**
|
||||
* Modal stub for the isolated preview.
|
||||
*
|
||||
* The real component imports `Modal` from
|
||||
* `@deepseek-ai/dsh-client-ui-primitives`; the preview bundle aliases that
|
||||
* package to this stub so the section renders without the shell. Props match
|
||||
* the primitives contract: open / onClose / title / closeLabel / className /
|
||||
* children. Focus management is intentionally minimal — the preview only
|
||||
* needs a stable, visually faithful dialog shell.
|
||||
*/
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
export interface ModalStubProps {
|
||||
open?: boolean
|
||||
onClose?: () => void
|
||||
title?: ReactNode
|
||||
closeLabel?: string
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
/** Any other primitive props are accepted and ignored (preview only). */
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export function Modal({
|
||||
open = false,
|
||||
onClose,
|
||||
title,
|
||||
closeLabel = '关闭',
|
||||
className,
|
||||
children,
|
||||
}: ModalStubProps): ReactNode {
|
||||
const dialogRef = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) dialogRef.current?.focus()
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || typeof document === 'undefined') return undefined
|
||||
const onKeyDown = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Escape') onClose?.()
|
||||
}
|
||||
document.addEventListener('keydown', onKeyDown)
|
||||
return () => document.removeEventListener('keydown', onKeyDown)
|
||||
}, [open, onClose])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<div className="preview-modal" data-preview-modal="1">
|
||||
<div className="preview-modal__backdrop" onClick={() => onClose?.()} />
|
||||
<div
|
||||
ref={dialogRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={typeof title === 'string' ? title : undefined}
|
||||
tabIndex={-1}
|
||||
className={['preview-modal__panel', className].filter(Boolean).join(' ')}
|
||||
>
|
||||
{(title !== undefined || onClose) && (
|
||||
<header className="preview-modal__header">
|
||||
{title !== undefined && <span className="preview-modal__title">{title}</span>}
|
||||
{onClose && (
|
||||
<button
|
||||
type="button"
|
||||
className="preview-modal__close"
|
||||
aria-label={closeLabel}
|
||||
onClick={() => onClose()}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</header>
|
||||
)}
|
||||
<div className="preview-modal__body">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Modal
|
||||
|
|
@ -0,0 +1,323 @@
|
|||
/* ------------------------------------------------------------------ */
|
||||
/* Isolated preview shell — DSH settings-panel stand-in + theme tokens */
|
||||
/* */
|
||||
/* Real DSH theme tokens are not available outside the shell, so the */
|
||||
/* preview defines the same token names with representative light/ */
|
||||
/* dark values. The component itself is rendered unmodified. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
html[data-theme='light'] {
|
||||
color-scheme: light;
|
||||
|
||||
--dsw-alias-label-primary: #1f2329;
|
||||
--dsw-alias-label-secondary: #4e5969;
|
||||
--dsw-alias-label-tertiary: #86909c;
|
||||
--dsw-alias-label-caption: #a7adb8;
|
||||
--dsw-alias-border-l1: rgba(15, 23, 42, 0.1);
|
||||
--dsw-alias-border-l2: rgba(15, 23, 42, 0.16);
|
||||
--dsw-alias-bg-layer-2: #ffffff;
|
||||
--dsw-specific-input-major: #f2f3f5;
|
||||
--dsw-alias-button-ghost-active-fill: rgba(15, 23, 42, 0.06);
|
||||
--dsw-alias-button-ghost-active-hover: rgba(15, 23, 42, 0.09);
|
||||
--dsw-alias-interactive-bg-hover: rgba(15, 23, 42, 0.05);
|
||||
--dsw-alias-state-business-primary: #2f6bff;
|
||||
--dsw-alias-state-success-primary: #12b76a;
|
||||
--dsw-alias-state-error-primary: #e5484d;
|
||||
--dsw-alias-markdown-code-block: #f4f5f7;
|
||||
|
||||
--preview-page-bg: #eef0f3;
|
||||
--preview-page-pattern: rgba(15, 23, 42, 0.035);
|
||||
--preview-panel-bg: #ffffff;
|
||||
--preview-panel-shadow: 0 18px 40px rgba(15, 23, 42, 0.12);
|
||||
--preview-banner-bg: #fff6e0;
|
||||
--preview-banner-border: #f3c96b;
|
||||
--preview-banner-text: #7a5200;
|
||||
--preview-chip-bg: rgba(47, 107, 255, 0.1);
|
||||
--preview-chip-text: #2450b8;
|
||||
}
|
||||
|
||||
html[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
|
||||
--dsw-alias-label-primary: #e9eaec;
|
||||
--dsw-alias-label-secondary: #b6bac3;
|
||||
--dsw-alias-label-tertiary: #8b909a;
|
||||
--dsw-alias-label-caption: #6f747d;
|
||||
--dsw-alias-border-l1: rgba(255, 255, 255, 0.12);
|
||||
--dsw-alias-border-l2: rgba(255, 255, 255, 0.2);
|
||||
--dsw-alias-bg-layer-2: #1e2024;
|
||||
--dsw-specific-input-major: #2a2d33;
|
||||
--dsw-alias-button-ghost-active-fill: rgba(255, 255, 255, 0.1);
|
||||
--dsw-alias-button-ghost-active-hover: rgba(255, 255, 255, 0.14);
|
||||
--dsw-alias-interactive-bg-hover: rgba(255, 255, 255, 0.08);
|
||||
--dsw-alias-state-business-primary: #6f92ff;
|
||||
--dsw-alias-state-success-primary: #34c77b;
|
||||
--dsw-alias-state-error-primary: #ff6b70;
|
||||
--dsw-alias-markdown-code-block: #16181c;
|
||||
|
||||
--preview-page-bg: #101114;
|
||||
--preview-page-pattern: rgba(255, 255, 255, 0.045);
|
||||
--preview-panel-bg: #1a1c20;
|
||||
--preview-panel-shadow: 0 18px 40px rgba(0, 0, 0, 0.55);
|
||||
--preview-banner-bg: #3a2d10;
|
||||
--preview-banner-border: #8a6a1f;
|
||||
--preview-banner-text: #ffdf9e;
|
||||
--preview-chip-bg: rgba(111, 146, 255, 0.16);
|
||||
--preview-chip-text: #b9cbff;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', 'Microsoft YaHei', 'PingFang SC', 'Noto Sans CJK SC', 'Noto Sans SC',
|
||||
system-ui, sans-serif;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
background-color: var(--preview-page-bg);
|
||||
background-image:
|
||||
linear-gradient(var(--preview-page-pattern) 1px, transparent 1px),
|
||||
linear-gradient(90deg, var(--preview-page-pattern) 1px, transparent 1px);
|
||||
background-size: 24px 24px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
.preview-page {
|
||||
min-height: 100vh;
|
||||
padding: 28px 32px 44px;
|
||||
}
|
||||
|
||||
.preview-shell {
|
||||
width: min(980px, 100%);
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.preview-banner {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--preview-banner-border);
|
||||
background: var(--preview-banner-bg);
|
||||
color: var(--preview-banner-text);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.preview-banner__tag {
|
||||
flex: 0 0 auto;
|
||||
padding: 2px 8px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--preview-banner-border);
|
||||
background: rgba(255, 255, 255, 0.45);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
html[data-theme='dark'] .preview-banner__tag {
|
||||
background: rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
.preview-banner__text {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.preview-panel {
|
||||
border-radius: 18px;
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
background: var(--preview-panel-bg);
|
||||
box-shadow: var(--preview-panel-shadow);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-panel__bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 14px 22px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||
background: var(--dsw-alias-bg-layer-2);
|
||||
}
|
||||
|
||||
.preview-panel__crumb {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.preview-panel__chip {
|
||||
flex: 0 0 auto;
|
||||
padding: 2px 9px;
|
||||
border-radius: 999px;
|
||||
background: var(--preview-chip-bg);
|
||||
color: var(--preview-chip-text);
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.preview-panel__body {
|
||||
padding: 26px 30px 32px;
|
||||
}
|
||||
|
||||
.preview-footer {
|
||||
margin: 0 auto;
|
||||
max-width: 980px;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Narrow variant: the shell behaves like a phone-width settings sheet. */
|
||||
html[data-width='narrow'] .preview-page {
|
||||
padding: 14px 12px 28px;
|
||||
}
|
||||
|
||||
html[data-width='narrow'] .preview-panel__bar,
|
||||
html[data-width='narrow'] .preview-panel__body {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Modal stub (aliased @deepseek-ai/dsh-client-ui-primitives Modal) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
.preview-modal {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.preview-modal__backdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(8, 10, 14, 0.55);
|
||||
backdrop-filter: blur(1px);
|
||||
}
|
||||
|
||||
.preview-modal__panel {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(680px, 100%);
|
||||
max-height: min(82vh, 760px);
|
||||
border-radius: 16px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
background: var(--dsw-alias-bg-layer-2);
|
||||
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
|
||||
overflow: hidden;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.preview-modal__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding: 16px 20px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||
}
|
||||
|
||||
.preview-modal__title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.preview-modal__close {
|
||||
flex: 0 0 auto;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 18px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.preview-modal__close:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
.preview-modal__close:focus-visible {
|
||||
outline: 2px solid var(--dsw-alias-state-business-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.preview-modal__body {
|
||||
padding: 18px 20px 20px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Smoke-test fallback component (only used with --smoke) */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
.preview-fallback {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.preview-fallback h1 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.preview-fallback p {
|
||||
margin: 0;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.preview-fallback section {
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
border-radius: 12px;
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
.preview-fallback button,
|
||||
.preview-fallback input,
|
||||
.preview-fallback select,
|
||||
.preview-fallback textarea {
|
||||
font: inherit;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
background: var(--dsw-specific-input-major);
|
||||
border: 1px solid var(--dsw-alias-border-l1);
|
||||
border-radius: 8px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
.preview-fallback label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin: 6px 0;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
@echo off
|
||||
rem Run the isolated Remote-SSH settings preview screenshots from a NORMAL user
|
||||
rem terminal (not from inside a constrained / Low-integrity sandbox job).
|
||||
rem Chromium cannot start its internal named-pipe IPC inside that sandbox.
|
||||
setlocal
|
||||
cd /d "%~dp0..\.."
|
||||
"C:\Users\qyh15\.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\node\bin\node.exe" "tools\preview-rssh-settings.mjs" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
|
|
@ -0,0 +1,302 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* tools/preview/smoke-render.mjs
|
||||
*
|
||||
* Headless DOM smoke test for the isolated preview WITHOUT a browser: builds
|
||||
* the same preview bundle (IIFE) and mounts the REAL
|
||||
* `createSettingsSection({ api })` component inside jsdom, then replays the
|
||||
* same interactions the screenshot script drives (expand, import, dirty badge,
|
||||
* password auth, test failure). This catches React/render/selector breakage in
|
||||
* environments where Chromium cannot start (Low-integrity sandbox job).
|
||||
*
|
||||
* Usage: node tools/preview/smoke-render.mjs
|
||||
* Exit 0 when every scene renders and every assertion passes.
|
||||
*/
|
||||
import fs from 'node:fs/promises'
|
||||
import { existsSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..', '..')
|
||||
const COMPONENT = path.join(ROOT, 'src', 'client', 'rssh-settings', 'index.tsx')
|
||||
const MODAL_STUB = path.join(HERE, 'modal-stub.tsx')
|
||||
const TEMP = path.join(os.tmpdir(), `rssh-preview-jsdom-${process.pid}`)
|
||||
const BUNDLE = path.join(TEMP, 'preview.iife.js')
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||
const log = message => console.log(`[jsdom-smoke] ${message}`)
|
||||
|
||||
async function buildBundle() {
|
||||
if (!existsSync(COMPONENT)) throw new Error(`component missing: ${COMPONENT}`)
|
||||
await fs.mkdir(TEMP, { recursive: true })
|
||||
const { build } = await import('vite')
|
||||
await build({
|
||||
configFile: false,
|
||||
root: HERE,
|
||||
mode: 'production',
|
||||
logLevel: 'error',
|
||||
publicDir: false,
|
||||
resolve: {
|
||||
alias: [
|
||||
{ find: /^#rssh-settings$/, replacement: COMPONENT },
|
||||
{ find: /^@deepseek-ai\/dsh-client-ui-primitives$/, replacement: MODAL_STUB },
|
||||
],
|
||||
},
|
||||
esbuild: { jsx: 'automatic' },
|
||||
build: {
|
||||
outDir: TEMP,
|
||||
emptyOutDir: true,
|
||||
target: 'chrome120',
|
||||
minify: false,
|
||||
write: true,
|
||||
lib: {
|
||||
entry: path.join(HERE, 'main.tsx'),
|
||||
formats: ['iife'],
|
||||
name: 'RsshPreview',
|
||||
fileName: () => 'preview.iife.js',
|
||||
},
|
||||
rollupOptions: { output: { inlineDynamicImports: true } },
|
||||
},
|
||||
})
|
||||
const code = await fs.readFile(BUNDLE, 'utf8')
|
||||
return code
|
||||
}
|
||||
|
||||
async function mountScene(code, query) {
|
||||
const { JSDOM } = await import('jsdom')
|
||||
const dom = new JSDOM('<!doctype html><html><head></head><body><div id="preview-root"></div></body></html>', {
|
||||
url: `http://127.0.0.1/index.html?${new URLSearchParams(query).toString()}`,
|
||||
runScripts: 'dangerously',
|
||||
pretendToBeVisual: true,
|
||||
})
|
||||
const errors = []
|
||||
dom.window.addEventListener('error', event => errors.push(String(event.error || event.message)))
|
||||
// Vite's production React bundle may still reference process.env when it is
|
||||
// evaluated outside a bundler-tooled module; give the jsdom window a shim.
|
||||
dom.window.process = { env: { NODE_ENV: 'production' } }
|
||||
dom.window.eval(code)
|
||||
return { dom, window: dom.window, document: dom.window.document, errors }
|
||||
}
|
||||
|
||||
async function waitFor(window, predicate, label, timeoutMs = 8000) {
|
||||
const deadline = Date.now() + timeoutMs
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
if (predicate(window)) return true
|
||||
} catch {
|
||||
/* DOM not ready yet */
|
||||
}
|
||||
await sleep(40)
|
||||
}
|
||||
throw new Error(`timeout waiting for ${label}`)
|
||||
}
|
||||
|
||||
const queryOf = scene => `scene=${encodeURIComponent(scene)}&theme=light&width=wide`
|
||||
|
||||
const mountAndSettle = async (code, scene) => {
|
||||
const mounted = await mountScene(code, { scene, theme: 'light', width: 'wide' })
|
||||
await waitFor(mounted.window, w => w.__RSH_PREVIEW_READY__ === true, `${scene}: ready flag`)
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-root]'), `${scene}: root mounted`)
|
||||
await waitFor(mounted.window, w => w.__RSH_PREVIEW_IDLE__ !== false, `${scene}: fake api idle`)
|
||||
await sleep(400)
|
||||
await waitFor(mounted.window, w => w.document.body.textContent.includes('我的连接'), `${scene}: section title`)
|
||||
return mounted
|
||||
}
|
||||
|
||||
const click = async (mounted, selector) => {
|
||||
const element = mounted.document.querySelector(selector)
|
||||
if (!element) throw new Error(`missing click target ${selector}`)
|
||||
element.click()
|
||||
await sleep(120)
|
||||
}
|
||||
|
||||
const setValue = async (mounted, selector, value) => {
|
||||
const element = mounted.document.querySelector(selector)
|
||||
if (!element) throw new Error(`missing value target ${selector}`)
|
||||
const control = element.matches('input,textarea,select') ? element : element.querySelector('input,textarea,select')
|
||||
if (!control) throw new Error(`no control inside ${selector}`)
|
||||
const proto =
|
||||
control.tagName === 'SELECT'
|
||||
? mounted.window.HTMLSelectElement.prototype
|
||||
: control.tagName === 'TEXTAREA'
|
||||
? mounted.window.HTMLTextAreaElement.prototype
|
||||
: mounted.window.HTMLInputElement.prototype
|
||||
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set
|
||||
setter.call(control, value)
|
||||
control.dispatchEvent(new mounted.window.Event('input', { bubbles: true }))
|
||||
control.dispatchEvent(new mounted.window.Event('change', { bubbles: true }))
|
||||
await sleep(120)
|
||||
return control
|
||||
}
|
||||
|
||||
const assert = (condition, label) => {
|
||||
if (!condition) throw new Error(`assertion failed: ${label}`)
|
||||
log(` ok: ${label}`)
|
||||
}
|
||||
|
||||
async function runDefault(code) {
|
||||
const mounted = await mountAndSettle(code, 'default')
|
||||
try {
|
||||
const root = mounted.document.querySelector('[data-rsui-root]')
|
||||
assert(root, 'root has data-rsui-root')
|
||||
assert(mounted.document.querySelectorAll('[data-rsui-connection]').length === 3, '3 connection cards')
|
||||
assert(mounted.document.querySelectorAll('[data-rsui-workspace]').length === 2, '2 workspace cards')
|
||||
const advanced = mounted.document.querySelector('[data-rsui-advanced-content]')
|
||||
assert(advanced, 'advanced content mounted')
|
||||
assert(advanced.hidden === true, 'advanced content collapsed (hidden)')
|
||||
const addRegion = mounted.document.querySelector('[data-rsui-toggle-add]')?.getAttribute('aria-expanded')
|
||||
assert(addRegion === 'true', 'add section initially expanded')
|
||||
assert(mounted.document.querySelector('[data-rsui-field="port"]')?.value === '22', 'port defaults to 22')
|
||||
assert(!mounted.document.querySelector('[data-rsui-import-dialog]'), 'import dialog closed')
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runExpanded(code) {
|
||||
const mounted = await mountAndSettle(code, 'expanded')
|
||||
try {
|
||||
await click(mounted, '[data-rsui-toggle-advanced]')
|
||||
const advanced = mounted.document.querySelector('[data-rsui-advanced-content]')
|
||||
assert(advanced.hidden === false, 'advanced content expanded')
|
||||
await click(mounted, '[data-rsui-toggle-workspaces]')
|
||||
assert(mounted.document.querySelector('[data-rsui-toggle-workspaces]').getAttribute('aria-expanded') === 'true', 'workspaces expanded')
|
||||
const expandButtons = [...mounted.document.querySelectorAll('[data-rsui-ws-expand]')]
|
||||
assert(expandButtons.length === 2, 'two workspace expand buttons')
|
||||
for (const button of expandButtons) {
|
||||
button.click()
|
||||
await sleep(120)
|
||||
}
|
||||
assert([...mounted.document.querySelectorAll('[data-rsui-ws-expand]')].every(button => button.getAttribute('aria-expanded') === 'true'), 'all workspace settings expanded')
|
||||
await click(mounted, '[data-rsui-toggle-more]')
|
||||
assert(mounted.document.querySelector('[data-rsui-field="proxyJump"]'), 'proxyJump field mounted')
|
||||
await setValue(mounted, '[data-rsui-field="name"]', '超算集群(测试)')
|
||||
await setValue(mounted, '[data-rsui-field="host"]', 'login.hpc.example.com')
|
||||
await setValue(mounted, '[data-rsui-field="user"]', 'demo-user')
|
||||
assert(mounted.document.querySelector('[data-rsui-field="host"]').value === 'login.hpc.example.com', 'host field controlled value updated')
|
||||
assert(mounted.document.body.textContent.includes('高级设置'), 'advanced copy rendered')
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runImport(code, scene) {
|
||||
const mounted = await mountAndSettle(code, scene)
|
||||
try {
|
||||
await click(mounted, '[data-rsui-import-open]')
|
||||
await waitFor(mounted.window, w => w.document.querySelectorAll('[data-rsui-import-row]').length === 5, `${scene}: 5 import rows`)
|
||||
assert(mounted.document.querySelector('[data-rsui-import-dialog]'), 'import dialog rendered')
|
||||
assert(/已选\s*5\s*\/\s*5/.test(mounted.document.body.textContent), 'selected count 5/5')
|
||||
if (scene === 'import-partial') {
|
||||
await click(mounted, '[data-rsui-import-submit]')
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-import-result]'), 'import result', 15000)
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-import-retry]'), 'retry button', 15000)
|
||||
const text = mounted.document.querySelector('[data-rsui-import-result]').textContent
|
||||
assert(/成功\s*3\s*个/.test(text), 'partial result reports 3 succeeded')
|
||||
assert(/失败\s*2\s*个/.test(text), 'partial result reports 2 failed')
|
||||
assert(text.includes('mirror.example.org') && text.includes('broken.example.net'), 'failed hosts listed with hostnames')
|
||||
assert(mounted.document.querySelector('[data-rsui-import-retry]').textContent.includes('重试失败项'), 'retry-only button present')
|
||||
}
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runWorkspaces(code) {
|
||||
const mounted = await mountAndSettle(code, 'workspaces')
|
||||
try {
|
||||
await click(mounted, '[data-rsui-toggle-workspaces]')
|
||||
for (const button of [...mounted.document.querySelectorAll('[data-rsui-ws-expand]')]) {
|
||||
button.click()
|
||||
await sleep(120)
|
||||
}
|
||||
const card = mounted.document.querySelector('[data-rsui-workspace]')
|
||||
const textarea = card.querySelector('textarea')
|
||||
assert(textarea, 'workspace textarea mounted')
|
||||
const proto = mounted.window.HTMLTextAreaElement.prototype
|
||||
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set
|
||||
setter.call(textarea, `${textarea.value}\n_patch/`)
|
||||
textarea.dispatchEvent(new mounted.window.Event('input', { bubbles: true }))
|
||||
textarea.dispatchEvent(new mounted.window.Event('change', { bubbles: true }))
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-ws-dirty]'), 'unsaved badge')
|
||||
assert(mounted.document.querySelector('[data-rsui-ws-dirty]').textContent.includes('未保存'), 'unsaved badge copy')
|
||||
const bodyText = mounted.document.body.textContent
|
||||
assert(bodyText.includes('与写回排除用途不同'), 'sync-exclude hint explains the difference from write-back exclude')
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runPassword(code) {
|
||||
const mounted = await mountAndSettle(code, 'password')
|
||||
try {
|
||||
const select = await setValue(mounted, '[data-rsui-field="authMethod"]', 'password')
|
||||
assert(select.value === 'password', 'auth method switched to password')
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-field="password"]'), 'password field')
|
||||
const password = mounted.document.querySelector('[data-rsui-field="password"]')
|
||||
assert(password.type === 'password', 'password input is masked')
|
||||
assert(password.getAttribute('autocomplete') === 'new-password', 'password autocomplete=new-password')
|
||||
await setValue(mounted, '[data-rsui-field="name"]', '实验室工作站(测试)')
|
||||
assert(mounted.document.body.textContent.includes('已保存密码'), 'configured password badge rendered')
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function runTestFailure(code) {
|
||||
const mounted = await mountAndSettle(code, 'test-failure')
|
||||
try {
|
||||
await click(mounted, '[data-rsui-test]')
|
||||
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-test-result][data-status="error"]'), 'error test result', 8000)
|
||||
const result = mounted.document.querySelector('[data-rsui-test-result]')
|
||||
assert(result.getAttribute('data-status') === 'error', 'test result status=error')
|
||||
const text = result.textContent
|
||||
assert(text.includes('连接失败'), 'failure title shown')
|
||||
assert(text.includes('Connection timed out'), 'diagnostic stderr shown')
|
||||
} finally {
|
||||
mounted.dom.window.close()
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await fs.rm(TEMP, { recursive: true, force: true })
|
||||
log('building IIFE preview bundle with vite')
|
||||
const code = await buildBundle()
|
||||
log(`bundle: ${BUNDLE} (${(code.length / 1024).toFixed(0)} KiB)`)
|
||||
|
||||
const cases = [
|
||||
['01-default', runDefault],
|
||||
['02-expanded', runExpanded],
|
||||
['03-import-dialog', mountedCode => runImport(mountedCode, 'import-ready')],
|
||||
['04-import-partial', mountedCode => runImport(mountedCode, 'import-partial')],
|
||||
['05-workspaces', runWorkspaces],
|
||||
['06-password-auth', runPassword],
|
||||
['09-test-failure', runTestFailure],
|
||||
]
|
||||
const failures = []
|
||||
for (const [name, runner] of cases) {
|
||||
log(`scene ${name}`)
|
||||
try {
|
||||
await runner(code)
|
||||
log(`scene ${name}: PASS`)
|
||||
} catch (error) {
|
||||
failures.push(`${name}: ${error.message}`)
|
||||
log(`scene ${name}: FAIL — ${error.message}`)
|
||||
}
|
||||
}
|
||||
log(failures.length ? `${failures.length} scene(s) failed` : 'all scenes passed')
|
||||
return failures.length ? 1 : 0
|
||||
}
|
||||
|
||||
let exitCode = 1
|
||||
try {
|
||||
exitCode = await main()
|
||||
} catch (error) {
|
||||
console.error(`[jsdom-smoke][error] ${error && error.stack ? error.stack : error}`)
|
||||
exitCode = 1
|
||||
} finally {
|
||||
await fs.rm(TEMP, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
process.exit(exitCode)
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
/**
|
||||
* Deterministic `t` seat for the isolated preview.
|
||||
*
|
||||
* The real section receives the shell locale service's bind. The preview has
|
||||
* no shell, so it resolves the SAME dictionary the section registers
|
||||
* (`zh` from `src/client/rssh-settings/i18n.ts`, single source of truth)
|
||||
* with `{name}` interpolation. Identical input → identical text, every run.
|
||||
*/
|
||||
import type { SettingsTranslate } from '../../src/client/rssh-settings/contract.ts'
|
||||
import { zh } from '../../src/client/rssh-settings/i18n.ts'
|
||||
|
||||
const DICTIONARY: Record<string, string> = zh as unknown as Record<string, string>
|
||||
|
||||
export const makeT = (): SettingsTranslate => {
|
||||
return (key: string, params?: Record<string, string | number>): string => {
|
||||
const template = DICTIONARY[key]
|
||||
const raw = template === undefined ? key : template
|
||||
if (!params) return raw
|
||||
return raw.replace(/\{(\w+)\}/g, (match, name: string) => {
|
||||
const value = params[name]
|
||||
return value === undefined ? match : String(value)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** Text the screenshot script expects to see once the section is mounted. */
|
||||
export const EXPECTED_MOUNT_TEXT = DICTIONARY['connection.sectionTitle'] as string
|
||||
|
|
@ -58,6 +58,12 @@ const block = (selector) => {
|
|||
const start = match.index + match[0].length - match[1].length
|
||||
return css.slice(start, css.indexOf('}', start))
|
||||
}
|
||||
assert.match(block('.wgRoot'), /height:100%/, 'the root consumes the sidebar slot height')
|
||||
assert.match(block('.wgRoot'), /max-height:100%/, 'the root cannot grow past its slot')
|
||||
assert.match(block('.wgRoot'), /overflow:hidden/, 'the root clips instead of scrolling the whole sidebar')
|
||||
assert.match(css, /\[data-sidebar-scrollport\]:has\(\[class\*="regionArea"\] \.wgRoot\)/, 'the host scrollport is claimed only when the tree is mounted')
|
||||
assert.match(css, /\[data-sidebar-scrollport\] > \[class\*="regionArea"\]:has\(\.wgRoot\)/, 'the workspace region is allowed to shrink below its content')
|
||||
assert.match(css, /grid-template-rows:8px max-content 2px minmax\(0, 1fr\)/, 'the workspace region takes the remaining row instead of max-content')
|
||||
assert.match(block('.wgDock'), /border-top:1px solid/, 'the dock draws the divider against the tree')
|
||||
assert.match(block('.wgDock'), /max-height:min\(62vh,560px\)/, 'the dock is capped so the tree always keeps room')
|
||||
assert.match(block('.wgDock'), /overflow:hidden/, 'the dock clips its own overflow instead of painting over the tree')
|
||||
|
|
|
|||
|
|
@ -239,11 +239,7 @@ 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')
|
||||
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')
|
||||
equal(JSON.parse(response.text), { ...document, remoteBase: defaultRemoteMirrorBase() }, 'GET preserves saved folders and remote mirror base')
|
||||
|
||||
const hintRoute = routes.find(item => item.path === '/workspace-groups/remote-hint')
|
||||
check(hintRoute !== undefined, 'remote hint route is registered')
|
||||
|
|
|
|||
|
|
@ -83,7 +83,9 @@ function sourceAssetPath(source: string, importer: string): string {
|
|||
function nodeConfig(): UserConfig {
|
||||
return {
|
||||
name: 'dsh-workspace-groups',
|
||||
entry: ['src/index.ts'],
|
||||
// The composition wrapper (bundle/index.js) ships as lib/index.js;
|
||||
// the groups host half builds to lib/groups.js beside it.
|
||||
entry: { groups: 'src/index.ts' },
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
|
|
@ -112,10 +114,7 @@ function clientConfig(): UserConfig {
|
|||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
// 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,
|
||||
sourcemap: true,
|
||||
dts: false,
|
||||
clean: false,
|
||||
deps: {
|
||||
|
|
|
|||