Compare commits

..

17 Commits

Author SHA1 Message Date
newbie 97f4c3e07f release: 1.3.1 — README 重写为清爽入口页并清理开发期文档 2026-11-19 10:16:15 +08:00
QQ 637c62f1f3 Merge pull request 'feat(remote-ssh): 重构设置页并修复批量导入结果统计' (#9) from feat/remote-ssh-settings-ui into main 2026-11-13 11:09:55 +08:00
newbie 9448886ea3 feat(remote-ssh): rebuild settings page and report real import results
Replace the vendored compiled settings face with a maintainable source component (src/client/rssh-settings) registered through an anchor-asserted build transform; the vendor tree stays pristine.

- My connections: per-card test state and diagnostics, in-card delete confirmation with the exact effect (keeps deleteProfile semantics).
- Add connection: every existing field/auth conditional kept, invalid port rejected instead of silently defaulting to 22, ProxyJump inside the collapsed More options section.
- SSH config import: multi-select dialog, per-item save result checks, real success/failure counts, failed-only retry, duplicate-submit guard.
- Remote workspaces: independent writeBack/writeBackExclude/syncPaths/syncExclude/syncMaxBytes (GiB) drafts saved by workspace id, unsaved badges, sync blocked while dirty, failure recovery.
- Advanced settings collapsed by default: terminal/write-back and new-workspace sync defaults, save only inside the expanded content.
- Scoped .rsui-* styling on DSH theme tokens, light/dark, 620px single column, keyboard-accessible disclosures, typed locale namespace zh/en.
- Isolated preview tooling + 9 real headless-Chrome screenshots recorded under screenshots/remote-ssh-settings.
- Tests: 48 model tests + 14 jsdom UI behavior tests; verify:bundle and test:patch assert the new settings seam.
2026-11-13 11:07:36 +08:00
QQ c67fee3d40 Merge pull request 'fix(workspaces): 1.2.2 入口行为确认与重复提交保护' (#8) from fix/workspace-entry-lifecycle into main 2026-11-13 09:38:39 +08:00
newbie 882f604f27 fix(workspaces): clarify entry lifecycle and guard farm creation 2026-11-13 09:36:16 +08:00
QQ 9eb8c90280 Merge pull request 'fix(farm): 重复生成复用已有 farm,不再 HTTP 400' (#7) from feat/farm-mounts into main 2026-11-12 22:41:38 +08:00
newbie 60cbf403b0 fix(farm): make repeated gather idempotent 2026-11-12 22:41:01 +08:00
QQ b514a8b0f2 Merge pull request 'feat(farm): 一个工作区同时挂载多个文件夹' (#6) from feat/farm-mounts into main 2026-11-12 22:21:15 +08:00
newbie 99a8c811a4 feat(farm): mount multiple folders in one workspace; revert visual merge 2026-11-12 22:20:28 +08:00
QQ 5ec9ea5efe Merge pull request 'chore(release): 1.1.1' (#5) from release/1.1.1 into main 2026-11-12 22:05:31 +08:00
newbie 80537fff86 chore(release): 1.1.1 2026-11-12 22:05:02 +08:00
QQ 419b43815f Merge pull request 'feat(sidebar): 同名 member 文件夹合并到 base 一行' (#4) from feat/merge-same-name-members into main 2026-11-12 22:01:18 +08:00
newbie 08a855e6e0 feat(sidebar): fold same-name member folders into the base row 2026-11-12 22:00:33 +08:00
QQ a9d2f88263 Merge pull request 'fix(sidebar): 修正 scrollport 选择器以命中 slot 包装层' (#3) from fix/sidebar-bottom-dock-2 into main 2026-11-12 21:43:41 +08:00
newbie 413a98ba83 fix(sidebar): match the slot wrapper inside the host workspace region 2026-11-12 21:42:31 +08:00
QQ d061e7ce35 Merge pull request 'fix(sidebar): 让未归类与默认工作区真正固定在侧栏底部' (#2) from fix/sidebar-bottom-dock into main 2026-11-12 21:31:48 +08:00
QQ de4ec03cd0 fix: 文件夹状态显式化、保存回滚/冲突、远程显示名与路径防重 2026-11-12 21:02:45 +08:00
65 changed files with 12628 additions and 457 deletions

View File

@ -1,5 +1,46 @@
# 更新日志 # 更新日志
## 1.3.1 — 2026-11-19
### 文档
- README 重写为面向插件市场的清爽入口页(项目介绍 + 主要功能 + 最短安装/上手 + 文档入口)。
- 清理开发期遗留的内部文档。
## 1.3.0 — 2026-11-13
### 新增 / 重构
- **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`,只影响新工作区,不覆盖已有独立配置);保存仅在展开内容中,成功 / 失败有明确反馈且失败保留草稿。
### 实现
- 新增 `src/client/rssh-settings/`(契约、纯逻辑模型、独立 locale 命名空间、组件与样式)。上游设置页由 `scripts/build-remote-ssh-client.mjs` 以锚点断言在构建期替换为上述源码组件,vendor 树保持原样;`verify:bundle` 与 `test:patch` 增加设置页替换、locale 命名空间与 compose 接缝的断言。
- 全局默认配置与工作区独立配置分别读写各自接口(`savePrefs` vs `updateWorkspaceGuards`),互不覆盖。
## 1.2.2 — 2026-11-13
- 总目录操作明确为新增独立工作区:执行前展示确认,说明不会迁移会话或移除旧入口,避免被误解为原位合并。
- 解除成员文件夹关联前明确提示对应工作区将恢复独立显示;侧栏与文件夹管理使用同一确认流程,不自动删除零可见会话的工作区或归档记录。
- 防止总目录操作重复提交;区分总目录已生成但注册工作区失败的状态,并提示重试复用已有目录。
## 1.2.1 — 2026-11-12
- Farm 创建改为幂等:同一组文件夹再次执行时复用已有 farm,不再返回 HTTP 400;文件夹不同仍明确冲突,防止误合并。
- 冲突提示改为 `already exists with different folders`,便于区分“已成功”和“配置变了”。
## 1.2.0 — 2026-11-12
### 新增
- **Farm 合并工作区**:把同一项目的多个文件夹(含远程镜像与本地目录)在 `$DSH_HOME/workspace-groups/farms/<名称>/` 下用 junction/目录符号链接并排挂起,再注册为一个新工作区。一个会话即可同时读取和改写这些文件夹,不复制、不移动原目录。
- 删除 farm 只 unlink 链接,遇到真实目录立即中止,绝不递归删除用户文件夹。
### 修复
- 侧栏底部 `未归类` / `默认工作区` 在宿主 `[data-sidebar-scrollport]` 中占用剩余高度,真正固定在侧栏底部。
- 撤销 1.1.1 的“同名 member 仅视觉合并”:那只是把两个 workspace 的会话画在一起,不能解决一个项目同时读写多个根目录。
## 1.1.0 — 2026-11-12 ## 1.1.0 — 2026-11-12
### 修复 ### 修复

View File

@ -1,189 +0,0 @@
# 开发说明(DEVELOPMENT)
> 面向「在这个仓库上做扩展」的人。仓库是 DeepSeek Harness 插件
> `@dsh-xhl/workspace-groups`:侧栏三级工作区分组浏览器 + 顶部会话标签条
> + Ctrl+R 快切面板。宿主半边(node)负责 sidecar 配置读写,浏览器半边负责 UI。
## 1. 这份工作树的来源
当前分支 `feat/base-0.4.2` 的工作树,是从**用户机器上实际安装运行的那份 0.4.2 构建**
反推重建的,而不是仓库 HEAD 的原样代码:
- 来源:`~/.dsh/profiles/desktop/node_modules/@dsh-xhl/workspace-groups/lib/client.js.map`
(内联 `sourcesContent`,含全部 `src/client/*` 的 TypeScript 源码)
- 仓库 HEAD(`942babe`,package 版本仍写着 `0.1.0`)里只有侧栏分组浏览器,
没有会话标签条 / 快切面板 / 分支视图这些模块,即上游 GitHub 的公开代码落后于
已发布构建。
- 因此重建树 = 安装版 0.4.2 的完整源码,并补齐宿主侧 `src/host-tabs.ts` 与
`/workspace-groups/tabs` 路由。
重建后的对齐校验(可用下面第 3 节的命令复现):
| 产物 | 与安装版对比 |
| --- | --- |
| `lib/index.js`(宿主) | diff 行数 **0**(逐字节) |
| `lib/client.js`(浏览器) | 仅 **1** 行差异:CSS 虚拟模块注释里的构建绝对路径 |
| `lib/types/**/*.d.ts` | **27/27 完全一致** |
git 历史里 `942babe` 及更早的提交原样保留;重建工作作为 `b30f771` 一次提交落在
`feat/base-0.4.2` 分支上。合回 `master` / 推上游前请自行决定如何叙事。
## 2. 目录结构
宿主半边(node,平台 `node`,输出 ESM):
| 文件 | 职责 |
| --- | --- |
| `src/index.ts` | 插件入口。`inject = ['webServer']`,注册 4 组路由:`GET /workspace-groups/config`、`GET|PUT /workspace-groups/tabs`、`PUT /workspace-groups/manual`、`GET|PUT|POST /workspace-groups/folders` |
| `src/host-config.ts` | 读用户 YAML 分类规则(默认 `~/.dsh/workspace-groups.yaml`),校验后以 JSON 下发 |
| `src/host-manual.ts` | 运行期分组覆盖(手动分组 + 单工作区归类覆盖),落 `$DSH_HOME/workspace-groups.manual.json` |
| `src/host-folders.ts` | 每个工作区的额外文件夹 + 根目录,落 `$DSH_HOME/workspace-groups.folders.json`(写时严格、读时宽容)。另提供 `defaultRemoteMirrorBase()`:`~/.dsh/remote-workspaces`,即 `@zhangfengshun/dsh-remote-ssh` 的本地镜像根,GET 时随文档下发 |
| `src/host-tabs.ts` | 会话标签条的宿主侧持久化。放在宿主是因为**浏览器存储按 origin 隔离,而 origin 含端口**,`dsh web`/测试/桌面壳端口各不相同 |
| `src/context-types.ts` | 本插件消费的 cordis 服务结构类型(第三方插件拿不到 monorepo 内的 `declare module` 合并) |
共享纯逻辑(浏览器 / node 两半都编译):
| 文件 | 职责 |
| --- | --- |
| `src/core/types.ts` | 规则配置类型,零运行时依赖 |
| `src/core/matcher.ts` | 归类与排序的纯函数:工作区归哪个分类、分类/工作区怎么排。宿主校验与客户端建树共用,语义不会漂移 |
| `src/core/folders.ts` | 多文件夹的纯函数:有效文件夹列表、根目录解析、cwd 归属(最具体优先)、镜像判定与相对子路径拼装(`isUnderBase` / `joinSubpath`)。宿主校验与客户端建树共用 |
浏览器半边(`src/client/`,输出 CJS 闭包工厂):
| 文件 | 职责 |
| --- | --- |
| `index.ts` | 客户端入口:向 `sidebar.workspaces` 槽注册(priority -1,shadow 官方浏览器)、注册 i18n、绑定各视图 |
| `contract.ts` | 注入共享契约(`GroupsBrowserInjected`),镜像官方 ui-workspace 的注入形状 |
| `GroupsBrowser.tsx` | 主 UI:分区头(标题/搜索/新建分组/添加工作区)+ 三级树 + 分组/工作区/会话对话框 |
| `rows.tsx` | 树的行组件(行内菜单、状态点、图标),对话框挂在 browser root 以免折叠时卸载 |
| `tree.ts` | 纯派生:分类文件夹 → 项目文件夹 →(可选)文件夹行 → 会话行;可见性规则对齐官方树 |
| `folders-persist.ts` | 文件夹 overlay 的客户端侧,读写宿主 `/workspace-groups/folders` |
| `locales.ts` | `workspaceGroups` 命名空间词典(zh/en + key 联合类型) |
| `styles.css` | 全部样式,`?inline` 导入后由构建期 lightningcss 压缩内联 |
| `branch.ts` / `FlowerBranch.tsx` | 侧栏当前行的「花朵」标记(几何计算在 `branch.ts`,仍由单测覆盖;连线与逐行圆点已移除,只画花朵) |
| `tabs.ts` | 标签条**纯**状态:打开顺序、激活项、派生展示 |
| `tab-store.ts` | `defineStore` 绑定(只做绑定,变换留在 `tabs.ts`) |
| `tab-seat.ts` | DOM 挂载点:标签条要贴在会话列顶部(ui-layout `AppFrame` 的 `.centerCol` 是 `pI_x6G_centerCol`,没有对应 slot) |
| `tab-persist.ts` | 标签条持久化的客户端侧,读写宿主 `/workspace-groups/tabs` |
| `SessionTabs.tsx` | 标签条 UI:每个打开的会话一枚 chip |
| `quick.ts` / `QuickPanel.tsx` | Ctrl+R 快切面板(工作区 / 会话两个页签) |
| `open-folder.ts` | 调 `@deepseek-ai/dsh-host-open-in-app` 的宿主路由,打开项目目录 |
| `subagent-lineage.ts` | 子代理后代计数的本地投影(0.1.2 起 runtime 不再提供 `indexSubagentDescendants`) |
| `store-core.ts` | 展开状态的**纯**变换(无运行时 import,便于单测) |
| `stores.ts` | 视图 store 工厂(展开状态,独立持久化 key,不碰官方 `dsh.workspace.view.v5`) |
| `store-hook.ts` | 面向 store 实例的框架形状选择器 hook(`useSyncExternalStoreWithSelector`) |
其它:`tests/*.test.ts`(vitest,覆盖 core matcher/tree/store/tabs/folders),
`tools/verify-folders.mjs`(沙箱内 vitest 起不来时的等价纯 node 断言),`cordis.patch.yml`
(cordis 插件补丁层),`scripts/verify-groups.mjs`,`workspace-groups.example.yaml`。
## 3. 构建 / 校验 / 装回去
本机的 DSH 沙箱里没有把 node/pnpm 放进 PATH,用下面这份绝对路径脚本跑(含备选写法说明):
```powershell
$nodeDir = "C:\Users\qyh15\.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\node\bin"
$pnpm = "C:\Users\qyh15\.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\pnpm\bin\pnpm.cjs"
$env:Path = "$nodeDir;$PWD\node_modules\.bin;" + $env:Path
# 依赖(已装过可跳过)
& "$nodeDir\node.exe" $pnpm install
# 类型检查(tsc 两次:node 半边 + 浏览器半边)
& "$nodeDir\node.exe" $pnpm typecheck
# 构建:先 tsc 出 lib/types,再 tsdown 出 lib/index.js + lib/client.js
& "$nodeDir\node.exe" $pnpm build
# 单测(注意:DSH 沙箱内 vitest 起子进程会被 EPERM 拦掉,用普通终端跑)
& "$nodeDir\node.exe" .\node_modules\vitest\vitest.mjs run
```
对齐校验(重建时用过,改动后也可用来确认没伤到宿主半边):
```powershell
$installed = "C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspace-groups"
& "$nodeDir\node.exe" ..\tools\diff-text.mjs "$installed\lib\index.js" lib\index.js 3
& "$nodeDir\node.exe" ..\tools\compare-types.mjs "$installed\lib\types" lib\types
```
装回正在运行的 DSH 做真机验证:
1. `pnpm build`
2. 把 `lib\`(`index.js`、`client.js`、`client.js.map`、`types\`)覆盖到
`C:\Users\qyh15\.dsh\profiles\desktop\node_modules\@dsh-xhl\workspace-groups\lib\`
3. 重启 DSH(Web GUI 在 `http://127.0.0.1:1282`)
> `lib/` 是**入库**的(上游仓库也这么干),改完源码要记得重新 build 再提交,
> 否则安装方拿到的还是旧产物。
## 4. 扩展时必须知道的三条约束
1. **平台模块表外置,其它一律内联。** `tsdown.config.ts` 的 `CLIENT_EXTERNALS`
只允许 `react`、`react/jsx-runtime`、`react-dom*`、`@deepseek-ai/cordis`、
`dsh-client-ui-slots`、`dsh-client-ui-primitives`、`dsh-client-store`、
`dsh-client-runtime/client`。**任何其它 `@deepseek-ai/*` 值导入都会让构建失败**
(`dsh-workspace-groups-client-purity` 纯净门);跨插件协作只能走 cordis 服务或 slot。
单纯类型导入没问题(会被擦除)。
2. **CSS 走 `?inline` 虚拟模块,前缀名不能改。** `CSS_VIRTUAL_PREFIX` 是
`\0dsh-workspace-groups-inline-css:`,`styles.css` 里的类名会被 lightningcss
压成哈希。加样式直接写 `styles.css`,组件里 `import css from './styles.css?inline'` 即可。
3. **Node 内置模块不许进浏览器包**(`NODE_BUILTINS` 参与判定)。需要 node 能力就往宿主半边加路由。
## 5. 常见扩展动作
- **加一块侧栏 UI / 一个按钮**:`rows.tsx` 加行内动作 →
`GroupsBrowser.tsx` 接 handler;文案加进 `locales.ts` 的 `zh`/`en` 与
`WorkspaceGroupsKey` 联合类型(漏加会被 tsc 抓到)。
- **加一份视图状态**:纯变换写 `store-core.ts`(或新开 `xxx.ts`,保持零运行时 import)
→ `stores.ts` 里 `defineStore` 绑定 → 组件用 `store-hook.ts` 的选择器 hook。
这样单测能直接测语义,不必起浏览器 module loader。
- **加宿主能力**:新建 `src/host-xxx.ts`(读写 sidecar、做校验)→ 在 `src/index.ts`
里用 `ctx.effect(() => ctx.webServer.register({ kind: 'exact', path, handler }), '...')`
挂路由 → 客户端照 `tab-persist.ts` 的 `fetch` 封装去调,注意 `Cache-Control: no-store`。
- **加标签条行为**:状态变换进 `tabs.ts`(纯),store 绑定在 `tab-store.ts`,
渲染在 `SessionTabs.tsx`,落盘走 `tab-persist.ts`;位置模型是「首次入列时定序」,
改动前先读 `tabs.ts` 顶部的 position model 注释。两条不变量:**固定标签恒在未固定
之前**(`moveTab` 在固定区边界夹紧、`togglePinTab` 插到固定区尾/未固定区头),
**标签名与会话标题互不影响**(`renameTab` 只动 `title`)。除 `order` 之外的标签状态
(固定、自定义名)也必须由 `restoreTabsImpl` 原样复原,否则每次重启都丢配置。
- **加一个分组展示元数据(颜色 / 图标 / 置顶等)**:字段进 `types.ts`
(`CategoryAppearance` + `GROUP_COLORS`/`GROUP_ICON_IDS` 白名单)→ 校验进
`host-manual.ts` 的 `parseAppearance`(**严格写、宽容读**:不校验键对应的分类是否
还存在,否则删掉一条 YAML 分类就会让之后每次保存都 400)→ 派生进 `matcher.ts`
(要影响排序就必须放 `effectiveCategories`,只在渲染层排会让拖拽落点与看到的顺序
不一致)→ `tree.ts` 节点带 `appearance` → `rows.tsx` 渲染 → `styles.css` 配色/
动画 → `locales.ts` 双语文案。写路径统一走
`GroupsBrowser.tsx` 的 `updateCategoryAppearance`;**改名要重映射 `appearance` 的键、
删除要清掉**(键空间是 display name,与 `categoryOrder` 一致)。
- **新增平台依赖**:先确认 DSH shell 的 module table 真有那一行,再往
`CLIENT_EXTERNALS` 里加,否则运行时 `require` 会拿不到模块。
## 6. 已知坑
- **沙箱内跑不了 vitest**:`spawn` 被 DSH 沙箱拦(EPERM),在普通 PowerShell 终端里跑。
- **`node_modules/.bin/*.CMD` 直调会挂**:pnpm 里嵌套的 pnpm 脚本在 DSH 沙箱下会
`Could not determine executable`,统一用 `node <pnpm.cjs> <script>` 形式。
- **单测覆盖不齐**:`tests/` 是早期版本写的,现已补 `tests/tabs.test.ts`(标签条纯逻辑:
固定区不变量、拖动夹紧、关闭其他/右侧、持久化恢复);**快切面板
(`quick.ts` / `QuickPanel.tsx`)与分组外观仍无单测**,改到这些区域时补。
- **改持久化格式一律「严格写、宽容读」**:新增字段必须是可选的,旧文件读不进来不算
错;悬挂键(如已删除的分类/会话)不得拒写,否则用户会卡在 400 上再也保存不了;
新字段在 `restore*` 里必须原样带过去(`pinned`/`title` 漏带就等于重启丢配置)。
- **package 版本号语义混乱**:仓库 HEAD 里是 `0.1.0`,但提交里写 `feat(v0.7)`;
重建树统一对齐到安装版的 `0.4.2`。发布前自己定一版号。
- **远程(`@zhangfengshun/dsh-remote-ssh`)工作区是镜像,不是真实远端目录**:它用
`workspaceRegistry.create(mirrorDir)` 把远端根登记成普通工作区,`mirrorDir` 就是
`~/.dsh/remote-workspaces/<workspaceId>`。所以对付这类项目时:
额外文件夹只能是镜像内子目录(用 `joinSubpath` 拼、`isUnderBase` 判定,**绝不要让
用户用原生选择器挑任意本地目录**);`cwd` 分区逻辑照常可用,因为会话本身也在本地跑。
真正"服务器上另一个根目录"应当由 SSH 插件单独建成工作区,再用分组归到一起。
`POST /workspace-groups/folders` 已停用(410):禁止复制子 marker,避免绕过父写回规则。
统一创建入口在 `src/client/folder-directory.ts`:listWorkspaces 判归属,本地使用 DSH
createDirectory,远端用专属 mkdir API(递归幂等),不走可能降级本地的 sidebar fs.mkdir。
缺 SSH 的已知镜像、网络/鉴权失败、坏目录清单和重叠根一律报错。远程子目录会话暂阻断,
因 remote-ssh 2.4.40 模型工具仍只匹配注册根 cwd。历史 marker 不自动清理。
验证:`node tools/verify-folder-directory.mjs`(模拟 API)和
`node --experimental-transform-types tools/verify-folders.mjs`(含 marker POST 拒绝回归)。
不要把静态检查/模拟通过当成实机 SSH 联调通过。

119
README.md
View File

@ -2,107 +2,62 @@
<strong>English</strong> · <a href="./README_ZH.md">简体中文</a> <strong>English</strong> · <a href="./README_ZH.md">简体中文</a>
</p> </p>
# dsh-better-workspace-group <h1 align="center">Workspace Groups · Remote SSH</h1>
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. <p align="center">
<em>One plugin for DeepSeek Harness — organize workspaces, projects and sessions into a clean grouped sidebar, and develop on remote machines over SSH.</em>
</p>
## Merged bundle: workspace-groups-remote <p align="center">
<a href="https://git.qyhhh.top/DeepsSeekHarness/workspace-groups-remote"><img alt="version" src="https://img.shields.io/badge/version-1.3.1-2f6feb"></a>
<img alt="license" src="https://img.shields.io/badge/license-MIT-3fb950">
<img alt="platform" src="https://img.shields.io/badge/platform-DeepSeek%20Harness-5b6bff">
<img alt="node" src="https://img.shields.io/badge/node-%E2%89%A5%2020-339933">
</p>
This tree merges two DSH plugins into **one installable bundle** (package `workspace-groups-remote`): <p align="center">
<img src="./screenshot.png" alt="Workspace Groups preview" width="720">
</p>
- **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`. ## ✨ Features
- **@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 - **Grouped sidebar** — browse by **group → project → session**, with create / rename / delete / fold / pin and drag-and-drop ordering.
- **Group appearance** — colors and icons, including a Materials & Lab set for lab work, material structures and devices.
- **Multiple folders per project** — attach extra folders, pick the default root, and keep each session under the folder that matches its working directory.
- **Remote SSH workspaces** — a VS Code Remote-SSH-like experience: remote workspaces, file access and an integrated terminal, built into the same plugin.
- **Remote-SSH settings page** — connection cards, SSH-key / password auth, import from your system SSH config, per-workspace write-back &amp; sync options. (1.3.0)
- **Duplicate remote folders fixed** — the same remote directory spelled differently no longer registers twice.
- **Session tab strip** — open, switch, pin, rename, reorder and close tabs.
- **Search &amp; persistence** — search sessions in context; groups, order, tabs and folder settings survive refreshes and restarts.
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: ## 🚀 Install
- **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. In DeepSeek Harness open **Discover**, search for **Workspace Groups · Remote SSH** and click **Install**. Or install from the command line:
- **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); remove the duplicate member from the folder dialog once its session is no longer needed — that deletes the duplicate record with 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.
### 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 ```sh
npm install dsh plugin --profile desktop add https://git.qyhhh.top/DeepsSeekHarness/workspace-groups-remote.git
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. Use `web` instead of `desktop` for a Web profile, then fully restart DSH.
### Known trade-offs > **Upgrading from the old two-bundle setup?** Remove `workspace-groups-local` and `@zhangfengshun/dsh-remote-ssh` first, install this single package, and restart. Your existing workspaces, sessions and settings are kept.
- **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. ## 🧭 Quick start
- **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 1. Click **New Group** in the sidebar header, then drag projects into it.
2. Use the `⋯` menu on a project or group to manage grouping, appearance and folders.
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. 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" />
## Implemented features
- **Workspace groups**: browse by group → project → session, with group creation, renaming, deletion, folding, and pinning.
- **Drag-and-drop organization**: move projects into or out of groups and reorder groups and projects.
- **Group appearance**: set group colors and icons, including a new Materials & Lab section for lab work, material structures, characterization, and functional devices.
- **Multiple folders per project**: attach extra folders, choose the default root, and place sessions under the folder that matches their working directory.
- **Local and remote directories**: create folders in local workspaces and registered SSH remote workspaces without falling back to a local mirror when a remote operation fails.
- **Session tabs**: open, switch, pin, rename, reorder, and close tabs, including closing other tabs or tabs to the right.
- **Sidebar refinements**: keep the default workspace pinned at the bottom, align row metadata and actions consistently, and scroll long appearance dialogs.
- **Search and persistence**: search sessions without losing their group context and keep groups, ordering, tabs, and folder settings across refreshes and restarts.
## Install
For the Desktop profile:
```sh
dsh plugin --profile desktop add github:newbieQQ/dsh-better-workspace-group
```
For Web, replace `desktop` with `web`. Fully restart DSH or the corresponding Web profile after installation.
## Basic use
1. Click **New Group** in the workspace header, then drag projects into it.
2. Use the `⋯` menu on a project or group to manage grouping, appearance, and folders.
3. Open **Folders…** on a project to attach folders or choose its default root. 3. Open **Folders…** on a project to attach folders or choose its default root.
4. For remote work: add an SSH connection in the plugin settings, then create a **remote workspace**.
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. Automatic grouping by path or name is optional — see [workspace-groups.example.yaml](./workspace-groups.example.yaml) and configure `~/.dsh/workspace-groups.yaml`.
## Uninstall ## 📚 More
```sh - [Changelog](./CHANGELOG.md)
dsh plugin --profile desktop remove workspace-groups-local - [Example grouping config](./workspace-groups.example.yaml)
```
## Credit and license ## 🙏 Credits &amp; License
The original project was created by [zcol](https://github.com/z-col) under the MIT License. This fork adds Materials & Lab icons, the bottom default-workspace bar, consistent row actions, remote-workspace folders, and other refinements. Built on [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups) (MIT). This package also bundles [@zhangfengshun/dsh-remote-ssh](https://github.com/zhangfengshun) 2.4.45 (MIT, © ZhangFengshun).
Original work © 2026 zcol; modifications © 2026 newbieQQ. See [LICENSE](./LICENSE) and [NOTICE.md](./NOTICE.md). Original work © 2026 zcol; modifications © 2026 newbieQQ. See [LICENSE](./LICENSE) and [NOTICE.md](./NOTICE.md).

View File

@ -2,107 +2,62 @@
<a href="./README.md">English</a> · <strong>简体中文</strong> <a href="./README.md">English</a> · <strong>简体中文</strong>
</p> </p>
# dsh-better-workspace-group <h1 align="center">工作区分组 · 远程 SSH</h1>
DeepSeek Harness 工作区分组插件。基于 [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups) 二次开发,让工作区、文件夹和会话在侧栏里更容易整理和使用。 <p align="center">
<em>DeepSeek Harness 的一个插件 —— 把工作区、项目和会话整理成清爽的分组侧栏,并可通过 SSH 在远程主机上开发。</em>
</p>
## 合并包:workspace-groups-remote <p align="center">
<a href="https://git.qyhhh.top/DeepsSeekHarness/workspace-groups-remote"><img alt="version" src="https://img.shields.io/badge/version-1.3.1-2f6feb"></a>
<img alt="license" src="https://img.shields.io/badge/license-MIT-3fb950">
<img alt="platform" src="https://img.shields.io/badge/platform-DeepSeek%20Harness-5b6bff">
<img alt="node" src="https://img.shields.io/badge/node-%E2%89%A5%2020-339933">
</p>
本仓库已把两个 DSH 插件合并为**一个可安装的 bundle**(包名 `workspace-groups-remote`): <p align="center">
<img src="./screenshot.png" alt="工作区分组插件预览" width="720">
</p>
- **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`)与分组客户端一并应用。
### 重复的远程文件夹——本合并包已修复 - **分组侧栏** —— 按「分组 → 项目 → 会话」浏览;支持新建、重命名、删除、折叠、置顶和拖拽排序。
- **分组外观** —— 颜色与图标;内含「材料与实验」图标集。
- **一个项目多个文件夹** —— 为项目添加额外文件夹、选择默认根目录,会话按工作目录归入对应文件夹。
- **远程 SSH 工作区** —— 类似 VS Code Remote-SSH:远程工作区、文件访问与集成终端,同一个插件内完成。
- **Remote-SSH 设置页** —— 连接卡片、密钥/密码认证、从系统 SSH 配置导入、按工作区的写回与同步设置。(1.3.0)
- **修复重复的远程文件夹** —— 同一远程目录换种写法不再重复注册。
- **会话标签栏** —— 打开、切换、固定、重命名、拖动排序与关闭标签。
- **搜索与保存** —— 保留分组层级搜索会话;分组、排序、标签和文件夹设置刷新或重启后仍生效。
上游的 `createRemoteWorkspace` 按 `remotePath` 原始字符串比对已有记录,同一个远程目录换个写法(`~/proj` 与 `/home/u/proj` 与 `proj/`)就会再注册**一条工作区记录、一个本地镜像、一个原生工作区**,界面上就是同一个远程项目出现两个文件夹行。本包分两层修复: ## 🚀 安装
- **宿主侧(构建时补丁,`scripts/patch-remote-ssh.mjs`)**:注册时先比轻度规范化后的写法;对不上时走一次 SSH 把路径解析成规范形式(`pwd -P` + `$HOME`)再比对,存入的也用规范写法。解析失败不拦创建(退回上游行为)。补丁行为由 `npm run test:patch` 覆盖;vendor 树保持原样,上游更新仍可直接替换。 在 DeepSeek Harness 打开「发现」,搜索「工作区分组 · 远程 SSH」点击安装;或用命令行:
- **客户端(分组侧)**:添加云端文件夹时,若已有成员由同一工作区支撑、或指向同一连接 + 同一远程目录,一律拒绝,不再只看镜像路径。
已经产生的重复不会自动合并(会话归属各自的工作区);等那条成员里的会话不再需要时,在文件夹管理里移除该成员即可,它背后的重复记录会一并删除。
### 安全加固(同一组补丁)
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 覆盖。
### 安装 / 迁移
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 ```sh
npm install dsh plugin --profile desktop add https://git.qyhhh.top/DeepsSeekHarness/workspace-groups-remote.git
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 路径语义——在未合并的上游里同样失败,与合并无关。 Web 环境将 `desktop` 改为 `web`,安装后完全重启 DSH。
### 已知取舍 > **从旧的两个包升级?** 先移除 `workspace-groups-local` 和 `@zhangfengshun/dsh-remote-ssh`,再安装本包并重启。已有工作区、会话和设置都会保留。
- **加载耦合**:两半作为一个包加载,任一半导入失败,整包(含分组)都会起不来。这是「只装一个包」的代价;要隔离失败域需要宿主支持按半懒加载,目前没有这个承诺。 ## 🧭 上手
- **shell 覆盖对所有安装生效**:合并包带着 remote-ssh 对 `better-sidebar` / `terminal-controller` 的 shell 覆盖,装这个包等于同时接管 profile 的终端 shell 集成(镜像终端自动连接靠的就是它)。宿主补丁引擎在未来版本里遇到覆盖目标不存在时如何处理,未验证——已列入真机清单。
- **首次连接新 SSH 主机不做指纹确认**(`accept-new`,与 VS Code Remote-SSH 相同的默认):内部通道首次连接即信任主机密钥,之后密钥变化会大声失败。终端 wrapper 已由补丁从 `no` 提升到同一 `accept-new` 口径。
### 维护 1. 点击侧栏标题栏的「新建分组」,再把项目拖进去。
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" />
## 已实现的功能
- **工作区分组**:按「分组 → 项目 → 会话」浏览,支持新建、重命名、删除、折叠和置顶分组。
- **拖拽整理**:把项目拖入或移出分组,并调整分组、项目的显示顺序。
- **分组外观**:设置分组颜色和图标;新增「材料与实验」图标分区,包含实验操作、材料结构、表征测试和功能器件图标。
- **一个项目多个文件夹**:为项目添加额外文件夹、选择默认根目录,会话会按工作目录归入对应文件夹。
- **本地与远程目录**:本地工作区和已注册的 SSH 远程工作区都可以创建文件夹;远程操作失败时不会误建到本地镜像。
- **会话标签栏**:打开、切换、固定、重命名、拖动排序和关闭会话标签,支持关闭其他标签及右侧标签。
- **侧栏布局优化**:默认工作区固定在底部;各行的数量、时间和操作按钮统一右对齐;外观弹窗内容可滚动。
- **搜索与保存**:保留分组层级搜索会话,分组、排序、标签和文件夹设置都会保存,刷新或重启后仍然有效。
## 安装
Desktop 环境:
```sh
dsh plugin --profile desktop add github:newbieQQ/dsh-better-workspace-group
```
Web 环境将 `desktop` 改为 `web`。安装完成后,完全重启 DSH 或对应的 Web profile。
## 基本使用
1. 点击工作区标题栏的「新建分组」,再把项目拖进去。
2. 在项目或分组的 `⋯` 菜单中管理分组、外观和文件夹。 2. 在项目或分组的 `⋯` 菜单中管理分组、外观和文件夹。
3. 在项目的「文件夹…」弹窗中添加文件夹或选择默认根目录。 3. 在项目的「文件夹…」中添加文件夹或选择默认根目录。
4. 远程开发:在插件设置里添加 SSH 连接,再创建**远程工作区**。
需要按路径或名称自动分组时,可参考 [workspace-groups.example.yaml](./workspace-groups.example.yaml) 配置 `~/.dsh/workspace-groups.yaml`。不配置也不影响手动分组。 需要按路径或名称自动分组时,可参考 [workspace-groups.example.yaml](./workspace-groups.example.yaml) 配置 `~/.dsh/workspace-groups.yaml`;不配置也不影响手动分组。
## 卸载 ## 📚 更多
```sh - [更新日志](./CHANGELOG.md)
dsh plugin --profile desktop remove workspace-groups-local - [自动分组示例](./workspace-groups.example.yaml)
```
## 致谢与许可 ## 🙏 致谢与许可
原项目由 [zcol](https://github.com/z-col) 开发并以 MIT 许可发布。本仓库在其基础上增加了材料与实验图标、底部默认工作区、统一行尾布局、远程工作区文件夹等功能。 基于 [z-col/dsh-workspace-groups](https://github.com/z-col/dsh-workspace-groups)(MIT)二次开发;本包同时内置 [@zhangfengshun/dsh-remote-ssh](https://github.com/zhangfengshun) 2.4.45(MIT,© ZhangFengshun)。
原始作品 © 2026 zcol;本仓库修改 © 2026 newbieQQ。详见 [LICENSE](./LICENSE) 和 [NOTICE.md](./NOTICE.md)。 原始作品 © 2026 zcol;本仓库修改 © 2026 newbieQQ。详见 [LICENSE](./LICENSE) 与 [NOTICE.md](./NOTICE.md)。

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises"; import { lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, stat, symlink, unlink } from "node:fs/promises";
import { dirname, resolve } from "node:path"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { homedir } from "node:os"; import { homedir } from "node:os";
// node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs // node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) { function getDefaultExportFromCjs(x) {
@ -3345,6 +3345,163 @@ async function writeFoldersDocument(path, document) {
throw error; throw error;
} }
} }
// src/host-farm.ts
/**
* A farm gathers several project folders into one real directory, so a single
* session can read and write all of them.
*
* A session's file scope is its workspace directory, so "one project, several
* folders" needs one directory that contains all of them. The farm is that
* directory: every entry is a link (a junction on Windows, a directory symlink
* elsewhere) to a folder the user already owns. Nothing is copied or moved, and
* the user's folders keep their own life.
*
* Deletion is the dangerous half. A recursive delete that followed a link would
* erase the user's real folder, so {@link removeFarm} only ever unlinks entries
* that are links, and refuses as soon as it meets a real directory.
*/
/** Characters Windows refuses in a name, plus control characters. */
const RESERVED_CHARS = /[\u005C\u002F:*?"<>|\u0000-\u001f]/gu;
/** Device names Windows refuses as a whole entry name. */
const RESERVED_NAMES = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu;
const MAX_NAME_LENGTH = 64;
const WINDOWS = process.platform === "win32";
function dshHome() {
const configured = process.env.DSH_HOME;
return configured === void 0 || configured.trim() === "" ? join(homedir(), ".dsh") : configured;
}
/** Root that holds every farm: `$DSH_HOME/workspace-groups/farms`. */
function defaultFarmRoot() {
return resolve(dshHome(), "workspace-groups", "farms");
}
/** One directory-safe name for a farm, derived from a workspace title. */
function farmDirectoryName(title) {
const cleaned = title.replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim().replace(/[. ]+$/u, "").slice(0, MAX_NAME_LENGTH).trim().replace(/[. ]+$/u, "");
if (cleaned === "") return "farm";
return RESERVED_NAMES.test(cleaned) ? `_${cleaned}` : cleaned;
}
function linkNameFor(target, taken) {
const raw = basename(target).replace(RESERVED_CHARS, " ").replace(/\s+/gu, " ").trim() || "folder";
const base = RESERVED_NAMES.test(raw) ? `_${raw}` : raw;
let name = base;
let suffix = 2;
while (taken.has(name.toLowerCase())) {
name = `${base} (${suffix})`;
suffix += 1;
}
taken.add(name.toLowerCase());
return name;
}
/**
* Delete one farm entry, and only one.
*
* A junction reports as a symbolic link to `lstat` but is a reparse point that
* `unlink` refuses; a directory symlink on POSIX removes fine with `unlink`. A
* real directory is never touched.
*/
async function unlinkEntry(path) {
const info = await lstat(path);
if (info.isDirectory() && !info.isSymbolicLink()) throw new Error(`farm: refusing to delete a real directory: ${path}`);
try {
await unlink(path);
} catch {
await rmdir(path);
}
}
async function discard(path) {
let entries;
try {
entries = await readdir(path);
} catch {
return;
}
for (const entry of entries) try {
await unlinkEntry(join(path, entry));
} catch {}
try {
await rmdir(path);
} catch {}
}
/** Resolve and validate one folder the user asked to gather. */
async function resolveFolder(raw) {
if (typeof raw !== "string" || raw.trim() === "") throw new Error("farm: empty folder path");
if (!isAbsolute(raw)) throw new Error(`farm: folder must be an absolute path: ${raw}`);
let real;
try {
real = await realpath(raw);
} catch {
throw new Error(`farm: folder does not exist: ${raw}`);
}
if (!(await stat(real)).isDirectory()) throw new Error(`farm: not a directory: ${raw}`);
return real;
}
/**
* Build a farm for `folders` under `defaultFarmRoot()`.
*
* Refuses to reuse an existing farm directory: a silent merge into a directory
* that already holds links would hide which entries this call owns.
*/
async function buildFarm(input) {
const seen = /* @__PURE__ */ new Set();
const targets = [];
for (const raw of input.folders) {
const target = await resolveFolder(raw);
const key = WINDOWS ? target.toLowerCase() : target;
if (seen.has(key)) continue;
seen.add(key);
targets.push(target);
}
if (targets.length < 2) throw new Error("farm: needs at least two distinct folders");
const root = defaultFarmRoot();
const path = join(root, farmDirectoryName(String(input.name)));
const taken = /* @__PURE__ */ new Set();
const links = targets.map((target) => ({
name: linkNameFor(target, taken),
target
}));
await mkdir(root, { recursive: true });
try {
await mkdir(path);
} catch (error) {
if (error.code !== "EEXIST") throw new Error(`farm: cannot create ${path}: ${error instanceof Error ? error.message : String(error)}`);
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);
if (!(await lstat(entryPath)).isSymbolicLink()) throw new Error(`farm: already exists, entry is not a link: ${entryPath}`);
const actual = await realpath(entryPath);
if (!(WINDOWS ? actual.toLowerCase() === link.target.toLowerCase() : actual === link.target)) throw new Error(`farm: already exists, link points elsewhere: ${entryPath}`);
}
return {
path,
links
};
}
try {
for (const link of links) await symlink(link.target, join(path, link.name), WINDOWS ? "junction" : "dir");
} catch (error) {
await discard(path);
throw new Error(`farm: cannot link into ${path}: ${error instanceof Error ? error.message : String(error)}`);
}
return {
path,
links
};
}
/**
* Remove a farm this module built. Only entries under `defaultFarmRoot()` are
* accepted, and only links are unlinked: a real directory aborts the removal.
*/
async function removeFarm(farmPath) {
const root = defaultFarmRoot();
const target = resolve(farmPath);
const inside = relative(root, target);
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) throw new Error(`farm: not a farm directory: ${farmPath}`);
const entries = await readdir(target);
for (const entry of entries) await unlinkEntry(join(target, entry));
await rmdir(target);
}
// src/index.ts // src/index.ts
/** Plugin identity for cordis.yml rows. */ /** Plugin identity for cordis.yml rows. */
const name = "workspace-groups-local"; const name = "workspace-groups-local";
@ -3660,5 +3817,65 @@ function apply(ctx) {
res.end(body); res.end(body);
} }
}), "@dsh-xhl/workspace-groups: /workspace-groups/folders route"); }), "@dsh-xhl/workspace-groups: /workspace-groups/folders route");
ctx.effect(() => ctx.webServer.register({
kind: "exact",
path: "/workspace-groups/farm",
handler: async (req, res) => {
if (req.method === "POST") {
let raw;
try {
raw = JSON.parse(await readBody(req, MAX_MANUAL_BODY_BYTES));
} catch (error) {
writeError(res, error instanceof HttpError ? error.status : 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const body = raw;
if (body === null || typeof body !== "object" || !Array.isArray(body.folders)) {
writeError(res, 400, "workspace-groups: farm needs { name, folders: string[] }");
return;
}
let result;
try {
result = await buildFarm({
name: typeof body.name === "string" ? body.name : "farm",
folders: body.folders
});
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify(result);
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
if (req.method === "DELETE") {
const target = new URL(req.url ?? "/", "http://localhost").searchParams.get("path");
if (target === null || target.trim() === "") {
writeError(res, 400, "workspace-groups: farm needs ?path=");
return;
}
try {
await removeFarm(target);
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`);
return;
}
const payload = JSON.stringify({ ok: true });
res.writeHead(200, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(payload)
});
res.end(payload);
return;
}
writeError(res, 405, "method not allowed");
}
}), "@dsh-xhl/workspace-groups: /workspace-groups/farm route");
} }
export { apply, inject, name }; export { apply, inject, name };

View File

@ -2,7 +2,7 @@ import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/cl
import { type WorkspaceFolderEntry } from '../core/folders.ts'; import { type WorkspaceFolderEntry } from '../core/folders.ts';
import type { GroupsBrowserProps } from './contract.ts'; import type { GroupsBrowserProps } from './contract.ts';
import { type RemoteProfileSummary } from './folder-directory.ts'; import { type RemoteProfileSummary } from './folder-directory.ts';
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: { export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, initialRemovePath, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView; workspace: WorkspaceView;
entry: WorkspaceFolderEntry | undefined; entry: WorkspaceFolderEntry | undefined;
t: GroupsBrowserProps['t']; t: GroupsBrowserProps['t'];
@ -17,7 +17,14 @@ export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remo
profilesError: string | null; profilesError: string | null;
/** Live workspace ids, so a member whose workspace is gone can say so. */ /** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[]; knownWorkspaceIds: readonly string[];
/** Sidebar removal opens this same confirmation instead of bypassing it. */
initialRemovePath?: string | null;
onClose: () => void; onClose: () => void;
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void;
/** Pick any directory (local or an already-mirrored cloud folder). */ /** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void; onAddFolder: () => void;
/** Register one cloud folder: returns true once it is stored. */ /** Register one cloud folder: returns true once it is stored. */

View File

@ -76,9 +76,9 @@ export declare function listRemoteProfiles(fetchImpl?: typeof fetch): Promise<Re
export declare function createRemoteFolder(profileId: string, remotePath: string, title?: string, fetchImpl?: typeof fetch): Promise<CreatedRemoteFolder>; 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 * Delete one remote workspace record through the SSH plugin: it removes the
* record, unregisters the native workspace behind it (that workspace's * record and attempts to unregister its native workspace and clean up its
* sessions go with it) and cleans up the mirror — the counterpart of * local mirror unless shared by another record. Session files and the original
* {@link createRemoteFolder}, for when a member folder is removed for good. * remote directory remain; unregistering may hide sessions from the sidebar.
* @param recordId - remote-ssh record id stored on the member. * @param recordId - remote-ssh record id stored on the member.
* @param fetchImpl - fetch implementation (tests inject one). * @param fetchImpl - fetch implementation (tests inject one).
*/ */

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

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

View File

@ -10,11 +10,18 @@
* - remoteSshClient: the dsh-remote-ssh client, vendored from * - remoteSshClient: the dsh-remote-ssh client, vendored from
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a * vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs * self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
* strips that registration wrapper and re-exports the bare factory, which * 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 * is invoked here with this bundle's own require (its only requires are
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform * `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
* modules) and applied alongside the groups client. * modules) and applied alongside the groups client.
* *
* 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).
*
* The inject list is the union of both halves (remote-ssh's `slots`/`locale` * The inject list is the union of both halves (remote-ssh's `slots`/`locale`
* are a subset of the groups list). * are a subset of the groups list).
*/ */

View File

@ -4,7 +4,7 @@
*/ */
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'; import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */ /** 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.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 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'>; export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
/** Simplified Chinese dictionary. */ /** Simplified Chinese dictionary. */
export declare const zh: WorkspaceGroupsDict; export declare const zh: WorkspaceGroupsDict;

View File

@ -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;
}

170
lib/types/client/rssh-settings/i18n.d.ts vendored Normal file
View File

@ -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;

View File

@ -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;

View File

@ -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;
};

View File

@ -0,0 +1 @@
export declare const SETTINGS_CSS: string;

88
lib/types/client/rssh-settings/ui.d.ts vendored Normal file
View File

@ -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;

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

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

View File

@ -1,6 +1,6 @@
{ {
"name": "workspace-groups-remote", "name": "workspace-groups-remote",
"version": "1.1.0", "version": "1.3.1",
"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.", "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": [ "keywords": [
"dsh", "dsh",

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

View File

@ -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": "连接测试失败诊断"
}
]
}

View File

@ -195,13 +195,83 @@ 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') 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) 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 const out = header
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n' + '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
+ '// Upstream registers this factory under its own package id; the merged\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' + '// 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' + '// and applied by src/client/index.ts. Body below is upstream-verbatim\n'
+ 'export default (require) => {' + '// 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 + body
+ '\n}\n' + '\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) writeFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), out)
console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs') console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs')

View File

@ -381,5 +381,22 @@ console.log('patch hygiene')
check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)') check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)')
check(src.includes('resolveRemoteCanonical'), 'built artifact carries the patch') 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') console.log('\n' + pass + ' passed, ' + fail + ' failed')
process.exit(fail === 0 ? 0 : 1) process.exit(fail === 0 ? 0 : 1)

View File

@ -39,6 +39,8 @@ check('client has exactly one module-loader registration', client.split('__Modul
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 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 groups half', client.includes('workspaceGroups'))
check('client contains the remote-ssh half', client.includes('remssh')) 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 remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8') const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')

View File

@ -13,7 +13,7 @@
* swaps to the remote tree, so no stacked overlays are needed and the current * swaps to the remote tree, so no stacked overlays are needed and the current
* location stays readable at the top. * location stays readable at the top.
*/ */
import { useEffect, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { import {
Button, Button,
IconFolderOpenOutlineRegular, IconFolderOpenOutlineRegular,
@ -44,7 +44,7 @@ function subfolderOf(root: string | null, picked: string): string | null {
return picked.startsWith(`${base}/`) ? picked.slice(base.length + 1) : null return picked.startsWith(`${base}/`) ? picked.slice(base.length + 1) : null
} }
export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: { export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, initialRemovePath, onClose, onBuildFarm, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
workspace: WorkspaceView workspace: WorkspaceView
entry: WorkspaceFolderEntry | undefined entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t'] t: GroupsBrowserProps['t']
@ -59,7 +59,14 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
profilesError: string | null profilesError: string | null
/** Live workspace ids, so a member whose workspace is gone can say so. */ /** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[] knownWorkspaceIds: readonly string[]
/** Sidebar removal opens this same confirmation instead of bypassing it. */
initialRemovePath?: string | null
onClose: () => void onClose: () => void
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void
/** Pick any directory (local or an already-mirrored cloud folder). */ /** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void onAddFolder: () => void
/** Register one cloud folder: returns true once it is stored. */ /** Register one cloud folder: returns true once it is stored. */
@ -72,8 +79,11 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
const folders = effectiveFolders(workspace.path, entry) const folders = effectiveFolders(workspace.path, entry)
const root = rootOf(workspace.path, entry) const root = rootOf(workspace.path, entry)
const [addMode, setAddMode] = useState<AddMode>('local') const [addMode, setAddMode] = useState<AddMode>('local')
// Path of the remote member whose removal awaits the delete-record choice. // All members keep their workspace when detached, including local members.
const [confirmRemovePath, setConfirmRemovePath] = useState<string | null>(null) 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 [profileId, setProfileId] = useState('')
const [remotePath, setRemotePath] = useState('') const [remotePath, setRemotePath] = useState('')
const [browsing, setBrowsing] = useState(false) const [browsing, setBrowsing] = useState(false)
@ -227,9 +237,8 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
className="wgIconButton" className="wgIconButton"
aria-label={`${t('folder.remove')} ${label}`} aria-label={`${t('folder.remove')} ${label}`}
onClick={() => { onClick={() => {
// A remote member can take its backing workspace // Detaching exposes the backing workspace as its own row.
// with it; ask which removal the user means first. if (member !== undefined) setConfirmRemovePath(path)
if (canDeleteRecord) setConfirmRemovePath(path)
else onRemove(path, false) else onRemove(path, false)
}} }}
> >
@ -240,16 +249,17 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
</div> </div>
{confirmRemovePath === path && ( {confirmRemovePath === path && (
<div className="wgFolderConfirm" role="alert"> <div className="wgFolderConfirm" role="alert">
<span className="wgFolderConfirmText">{t('folder.removeRemotePrompt')}</span> <span className="wgFolderConfirmText">{t(memberGone ? 'folder.removeMissingPrompt' : 'folder.removeMemberPrompt')}</span>
{canDeleteRecord && <span className="wgFolderConfirmText">{t('folder.removeRemotePrompt')}</span>}
<span className="wgFolderConfirmActions"> <span className="wgFolderConfirmActions">
<button {canDeleteRecord && <button
type="button" type="button"
className="wgFolderConfirmButton" className="wgFolderConfirmButton"
data-tone="danger" data-tone="danger"
onClick={() => { setConfirmRemovePath(null); onRemove(path, true) }} onClick={() => { setConfirmRemovePath(null); onRemove(path, true) }}
> >
{t('folder.removeRemoteDelete')} {t('folder.removeRemoteDelete')}
</button> </button>}
<button <button
type="button" type="button"
className="wgFolderConfirmButton" className="wgFolderConfirmButton"
@ -274,6 +284,38 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
{!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>} {!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>}
</section> </section>
{extraFolders && (
<section className="wgFolderMerge">
<div className="wgFolderSectionTitle">{t('folder.mergeTitle')}</div>
{/* A session's file scope is its workspace directory, so folders in
different places are unreachable from one session. A farm puts
them side by side as links; nothing is copied or moved. */}
<button type="button" className="wgFolderPick" disabled={busy} 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>
)}
<section className="wgFolderAdd"> <section className="wgFolderAdd">
<div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div> <div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div>
<div className="wgFolderSegmented" role="tablist" aria-label={t('folder.addAria')}> <div className="wgFolderSegmented" role="tablist" aria-label={t('folder.addAria')}>

View File

@ -60,6 +60,7 @@ import { FoldersConflictError, loadFolders, saveFolders } from './folders-persis
import { createRemoteFolder, createWorkspaceDirectory, deleteRemoteWorkspaceRecord, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts' import { createRemoteFolder, createWorkspaceDirectory, deleteRemoteWorkspaceRecord, listRemoteProfiles, remoteFolderWorkspace, type RemoteFolderWorkspace, type RemoteProfileSummary } from './folder-directory.ts'
import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts' import { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { FoldersDialog } from './FoldersDialog.tsx' import { FoldersDialog } from './FoldersDialog.tsx'
import { buildFarm } from './folders-farm.ts'
import { QuickPanel } from './QuickPanel.tsx' import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx' import { SessionTabs } from './SessionTabs.tsx'
import css from './styles.css?inline' import css from './styles.css?inline'
@ -931,7 +932,9 @@ export function GroupsBrowser({
const foldersOwnerRequest = useRef('') const foldersOwnerRequest = useRef('')
/** Open the folder dialog and learn the owner's remote root (cloud owners only). */ /** Open the folder dialog and learn the owner's remote root (cloud owners only). */
const [folderRemovalPath, setFolderRemovalPath] = useState<string | null>(null)
const openFoldersFor = (workspaceId: string): void => { const openFoldersFor = (workspaceId: string): void => {
setFolderRemovalPath(null)
foldersOwnerRequest.current = workspaceId foldersOwnerRequest.current = workspaceId
setFoldersTarget(workspaceId as WorkspaceId) setFoldersTarget(workspaceId as WorkspaceId)
setFoldersOwnerRemote(null) setFoldersOwnerRemote(null)
@ -1147,17 +1150,58 @@ export function GroupsBrowser({
writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path)) writeFolderEntry(workspaceId, setRoot(entryFor(foldersDoc, workspaceId as string), path))
} }
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so one session reaches all of them. The folders themselves are
* never copied, moved or deleted; the farm holds links only.
*/
const farmCreating = useRef(false)
const buildFarmFor = async (workspaceId: WorkspaceId): Promise<void> => {
if (foldersBusy || farmCreating.current) return
const workspace = workspaces.find(item => item.workspaceId === workspaceId)
if (workspace === undefined) return
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)
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)
}
}
/** /**
* Remove one folder from a project. With `deleteRecord` set — only the * Remove one folder from a project. With `deleteRecord` set — only the
* folder dialog offers it, behind an explicit confirm — a remote member's * folder dialog offers it, behind an explicit confirm — a remote member's
* backing record is deleted through the SSH plugin as well (record, native * backing record is deleted through the SSH plugin as well (unshared native
* workspace and mirror go away, sessions included); without it the removal * 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 * is overlay-only and the workspace survives as its own project. If the
* record deletion fails, the member stays so the user can retry. * record deletion fails, the member stays so the user can retry.
*/ */
const removeFolderFrom = (workspaceId: WorkspaceId, path: string, deleteRecord = false): void => { const removeFolderFrom = (workspaceId: WorkspaceId, path: string, deleteRecord = false, confirmed = false): void => {
const entry = entryFor(foldersDoc, workspaceId as string) const entry = entryFor(foldersDoc, workspaceId as string)
const member = memberOf(entry, path) 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 !== '') { if (deleteRecord && member?.kind === 'remote' && member.recordId !== undefined && member.recordId !== '') {
const recordId = member.recordId const recordId = member.recordId
void (async () => { void (async () => {
@ -2255,16 +2299,18 @@ export function GroupsBrowser({
t={t} t={t}
busy={foldersBusy} busy={foldersBusy}
canOpen={openFolderPath !== undefined} canOpen={openFolderPath !== undefined}
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
remote={isRemoteWorkspace(workspace)} remote={isRemoteWorkspace(workspace)}
ownerRemotePath={foldersOwnerRemote} ownerRemotePath={foldersOwnerRemote}
profiles={remoteProfiles} profiles={remoteProfiles}
profilesError={remoteProfilesError} profilesError={remoteProfilesError}
knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)} knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)}
initialRemovePath={folderRemovalPath}
onAddFolder={() => { void addFolderTo(foldersTarget) }} onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)} onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)} onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }} onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
onRemove={(path, deleteRecord) => { removeFolderFrom(foldersTarget, path, deleteRecord) }} onRemove={(path, deleteRecord) => { removeFolderFrom(foldersTarget, path, deleteRecord, true) }}
onOpenFolder={(path) => { openFolderPath?.(path) }} onOpenFolder={(path) => { openFolderPath?.(path) }}
onClose={() => { foldersOwnerRequest.current = ''; setFoldersTarget(null) }} onClose={() => { foldersOwnerRequest.current = ''; setFoldersTarget(null) }}
/> />

View File

@ -241,9 +241,9 @@ export async function createRemoteFolder(
/** /**
* Delete one remote workspace record through the SSH plugin: it removes the * Delete one remote workspace record through the SSH plugin: it removes the
* record, unregisters the native workspace behind it (that workspace's * record and attempts to unregister its native workspace and clean up its
* sessions go with it) and cleans up the mirror — the counterpart of * local mirror unless shared by another record. Session files and the original
* {@link createRemoteFolder}, for when a member folder is removed for good. * remote directory remain; unregistering may hide sessions from the sidebar.
* @param recordId - remote-ssh record id stored on the member. * @param recordId - remote-ssh record id stored on the member.
* @param fetchImpl - fetch implementation (tests inject one). * @param fetchImpl - fetch implementation (tests inject one).
*/ */

View File

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

View File

@ -10,26 +10,63 @@
* - remoteSshClient: the dsh-remote-ssh client, vendored from * - remoteSshClient: the dsh-remote-ssh client, vendored from
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a * vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs * self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
* strips that registration wrapper and re-exports the bare factory, which * 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 * is invoked here with this bundle's own require (its only requires are
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform * `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
* modules) and applied alongside the groups client. * modules) and applied alongside the groups client.
* *
* 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).
*
* The inject list is the union of both halves (remote-ssh's `slots`/`locale` * The inject list is the union of both halves (remote-ssh's `slots`/`locale`
* are a subset of the groups list). * are a subset of the groups list).
*/ */
import type { Context } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis'
import * as groupsClient from './groups-client.ts' import * as groupsClient from './groups-client.ts'
import remoteSshFactory from './remote-ssh-factory.generated.mjs' 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'
/** Services required before mounting (union of both client halves). */ /** Services required before mounting (union of both client halves). */
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale'] export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
/** 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. */ /** Instantiate the vendored remote-ssh client plugin exactly once. */
const remoteSshClient = remoteSshFactory(id => require(id)) const remoteSshClient = remoteSshFactory(id => require(id), remoteSshCompose)
/** Plugin body: apply both client halves on this bundle's fiber. */ /** Plugin body: apply both client halves on this bundle's fiber. */
export function apply(ctx: Context): void { 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) groupsClient.apply(ctx)
remoteSshClient.apply(ctx) remoteSshClient.apply(ctx)
} }

View File

@ -41,6 +41,15 @@ export type WorkspaceGroupsKey =
| 'folder.sectionList' | 'folder.sectionList'
| 'folder.sectionAdd' | 'folder.sectionAdd'
| 'folder.emptyHint' | 'folder.emptyHint'
| 'folder.mergeTitle'
| 'folder.mergeAction'
| 'folder.mergeHint'
| 'folder.mergeDone'
| 'folder.mergeConfirm'
| 'folder.mergeRegistrationFailed'
| 'folder.removeMemberPrompt'
| 'folder.removeMissingPrompt'
| 'folder.mergeFailed'
| 'folder.base' | 'folder.base'
| 'folder.setRoot' | 'folder.setRoot'
| 'folder.rootBadge' | 'folder.rootBadge'
@ -233,6 +242,15 @@ export const zh: WorkspaceGroupsDict = {
'folder.sectionList': '项目文件夹', 'folder.sectionList': '项目文件夹',
'folder.sectionAdd': '添加文件夹', 'folder.sectionAdd': '添加文件夹',
'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。', 'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。',
'folder.mergeTitle': '新增总目录工作区',
'folder.mergeAction': '新增总目录入口',
'folder.mergeHint': '为上方文件夹创建链接总目录,并新增一个独立工作区入口。原文件夹、旧工作区和原会话均保留;不会迁移会话或删除旧入口。',
'folder.mergeConfirm': '确认将上方列出的文件夹链接到总目录,并注册为独立工作区?旧工作区及会话仍在原处,新入口不包含旧会话。',
'folder.mergeDone': '总目录工作区已就绪;旧工作区和会话保留在原处:',
'folder.mergeRegistrationFailed': '总目录已创建,但工作区注册失败。保持名称和文件夹不变重试将复用该目录,不会迁移或删除旧工作区:',
'folder.removeMemberPrompt': '解除关联后,此文件夹的工作区和会话会保留,并可重新作为独立入口显示(即使没有会话)。不会删除目录或迁移会话。',
'folder.removeMissingPrompt': '仅移除此处的失效关联,不会重建工作区,也不会删除目录或会话。',
'folder.mergeFailed': '生成总文件夹失败',
'folder.base': '基础文件夹', 'folder.base': '基础文件夹',
'folder.setRoot': '设为根目录', 'folder.setRoot': '设为根目录',
'folder.rootBadge': '根目录', 'folder.rootBadge': '根目录',
@ -242,9 +260,9 @@ export const zh: WorkspaceGroupsDict = {
'folder.duplicate': '该文件夹已在此工作区中', 'folder.duplicate': '该文件夹已在此工作区中',
'folder.conflict': '文件夹已被另一个窗口修改,已同步为最新状态,本次修改未保存,请重试', 'folder.conflict': '文件夹已被另一个窗口修改,已同步为最新状态,本次修改未保存,请重试',
'folder.removeError': '远程工作区删除失败', 'folder.removeError': '远程工作区删除失败',
'folder.removeRemotePrompt': '这个云端文件夹背后有一个工作区,移除时要连它一起删掉吗?删掉后它里面的会话也会消失。', 'folder.removeRemotePrompt': '“连工作区一起删”会删除远程记录,并尝试清理未被其他记录共用的工作区注册和本地镜像。会话可能从侧栏隐藏,聊天文件保留;不删除服务器上的原目录。',
'folder.removeRemoteDelete': '连工作区一起删', 'folder.removeRemoteDelete': '连工作区一起删',
'folder.removeRemoteOnly': '只移除文件夹', 'folder.removeRemoteOnly': '解除关联,保留工作区',
'folder.addError': '添加文件夹失败', 'folder.addError': '添加文件夹失败',
'folder.sessionError': '新建会话失败', 'folder.sessionError': '新建会话失败',
'folder.saveError': '文件夹保存失败', 'folder.saveError': '文件夹保存失败',
@ -424,6 +442,15 @@ export const en: WorkspaceGroupsDict = {
'folder.sectionList': 'Project folders', 'folder.sectionList': 'Project folders',
'folder.sectionAdd': 'Add a folder', '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.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.base': 'Base folder',
'folder.setRoot': 'Set as root', 'folder.setRoot': 'Set as root',
'folder.rootBadge': 'Root', 'folder.rootBadge': 'Root',
@ -433,9 +460,9 @@ export const en: WorkspaceGroupsDict = {
'folder.duplicate': 'That folder is already in this workspace', '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.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.removeError': 'Could not delete the remote workspace',
'folder.removeRemotePrompt': 'This cloud folder is backed by its own workspace. Remove the workspace along with it? Its sessions will be deleted too.', '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.removeRemoteDelete': 'Delete workspace too',
'folder.removeRemoteOnly': 'Remove folder only', 'folder.removeRemoteOnly': 'Detach and keep workspace',
'folder.addError': 'Could not add the folder', 'folder.addError': 'Could not add the folder',
'folder.sessionError': 'Could not start a session', 'folder.sessionError': 'Could not start a session',
'folder.saveError': 'Could not save folders', 'folder.saveError': 'Could not save folders',

View File

@ -1,4 +1,5 @@
import type { Context } from '@deepseek-ai/cordis' 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. */ /** The plugin object the vendored dsh-remote-ssh client factory returns. */
export interface RemoteSshClientPlugin { export interface RemoteSshClientPlugin {
@ -7,10 +8,15 @@ export interface RemoteSshClientPlugin {
} }
/** /**
* Upstream factory shape: the module-loader factory from * Merged-bundle factory shape: the module-loader factory from
* vendor/dsh-remote-ssh/lib/client.js, re-exported by * vendor/dsh-remote-ssh/lib/client.js, re-exported by
* scripts/build-remote-ssh-client.mjs as remote-ssh-factory.generated.mjs. * 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( export default function remoteSshClientFactory(
require: (id: string) => unknown, require: (id: string) => unknown,
compose?: RemoteSshClientCompose,
): RemoteSshClientPlugin ): RemoteSshClientPlugin

View File

@ -13,8 +13,11 @@
// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) --- // --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---
// Upstream registers this factory under its own package id; the merged // Upstream registers this factory under its own package id; the merged
// package registers ONE client row, so the factory is exported instead // package registers ONE client row, so the factory is exported instead
// and applied by src/client/index.ts. Body below is upstream-verbatim. // and applied by src/client/index.ts. Body below is upstream-verbatim
export default (require) => { // apart from anchor-asserted patches (root label, settings face).
// The second argument is the merged entry's compose seam:
// compose.settingsNamespace + compose.createSettingsSection(deps)
export default (require, compose) => {
var module = { exports: {} }; var module = { exports: {} };
var exports = module.exports; var exports = module.exports;
var React = require("react"); var React = require("react");
@ -1956,14 +1959,32 @@ export default (require) => {
}); });
if (slots) { if (slots) {
// [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 () { 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({ return slots.register({
name: "settings.section", name: "settings.section",
id: "remote-ssh", id: "remote-ssh",
order: 200, order: 200,
label: function () { return i18n.t("settings.nav"); }, label: function () { return i18n.t("settings.nav"); },
locale: NS locale: settingsLocale
}, SettingsSection); }, settingsComponent);
}); });
// 接管原生「添加工作区」流程:用明显更低的优先级覆盖内置的本地目录选择器, // 接管原生「添加工作区」流程:用明显更低的优先级覆盖内置的本地目录选择器,

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -17,13 +17,13 @@
right after the tree instead of pinned to the sidebar bottom. Only when our 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 tree is mounted, give the workspace region the remaining row; the tree body
then owns the scrolling and .wgDock stays outside it. */ then owns the scrolling and .wgDock stays outside it. */
[data-sidebar-scrollport]:has(> [class*="regionArea"] > .wgRoot) { [data-sidebar-scrollport]:has([class*="regionArea"] .wgRoot) {
grid-template-rows:8px max-content 2px minmax(0, 1fr); grid-template-rows:8px max-content 2px minmax(0, 1fr);
align-content:stretch; align-content:stretch;
overflow-y:hidden; overflow-y:hidden;
} }
[data-sidebar-scrollport] > [class*="regionArea"]:has(> .wgRoot) { [data-sidebar-scrollport] > [class*="regionArea"]:has(.wgRoot) {
min-height:0; min-height:0;
overflow:hidden; overflow:hidden;
} }

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

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

View File

@ -53,6 +53,7 @@ import {
validateRemoteHintPath, validateRemoteHintPath,
writeFoldersDocument, writeFoldersDocument,
} from './host-folders.ts' } from './host-folders.ts'
import { buildFarm, removeFarm } from './host-farm.ts'
/** Plugin identity for cordis.yml rows. */ /** Plugin identity for cordis.yml rows. */
export const name = 'workspace-groups-local' export const name = 'workspace-groups-local'
@ -381,4 +382,70 @@ export function apply(ctx: GroupsContext): void {
res.end(body) res.end(body)
}, },
}), '@dsh-xhl/workspace-groups: /workspace-groups/folders route') }), '@dsh-xhl/workspace-groups: /workspace-groups/folders route')
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/workspace-groups/farm',
handler: async (req, res) => {
if (req.method === 'POST') {
let raw: unknown
try {
raw = JSON.parse(await readBody(req, MAX_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 body = raw as { name?: unknown; folders?: unknown } | null
if (body === null || typeof body !== 'object' || !Array.isArray(body.folders)) {
writeError(res, 400, 'workspace-groups: farm needs { name, folders: string[] }')
return
}
let result
try {
// Nothing is copied: every entry is a link to a folder the user owns.
result = await buildFarm({
name: typeof body.name === 'string' ? body.name : 'farm',
folders: body.folders,
})
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify(result)
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
if (req.method === 'DELETE') {
const url = new URL(req.url ?? '/', 'http://localhost')
const target = url.searchParams.get('path')
if (target === null || target.trim() === '') {
writeError(res, 400, 'workspace-groups: farm needs ?path=')
return
}
try {
// Unlinks entries only; a real directory inside aborts the removal
// instead of being deleted with everything under it.
await removeFarm(target)
} catch (error) {
writeError(res, 400, `workspace-groups: ${error instanceof Error ? error.message : String(error)}`)
return
}
const payload = JSON.stringify({ ok: true })
res.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'Content-Length': Buffer.byteLength(payload),
})
res.end(payload)
return
}
writeError(res, 405, 'method not allowed')
},
}), '@dsh-xhl/workspace-groups: /workspace-groups/farm route')
} }

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

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

396
tools/preview/fake-api.ts Normal file
View File

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

128
tools/preview/main.tsx Normal file
View File

@ -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 />)

View File

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

323
tools/preview/preview.css Normal file
View File

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

View File

@ -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%

View File

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

View File

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

View File

@ -61,7 +61,8 @@ const block = (selector) => {
assert.match(block('.wgRoot'), /height:100%/, 'the root consumes the sidebar slot height') 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'), /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(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\]: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(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'), /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'), /max-height:min\(62vh,560px\)/, 'the dock is capped so the tree always keeps room')

View File

@ -3,6 +3,6 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({ export default defineConfig({
test: { test: {
environment: 'node', environment: 'node',
include: ['tests/**/*.test.ts'], include: ['tests/**/*.test.ts', 'tests/**/*.test.tsx'],
}, },
}) })