Compare commits

..

14 Commits

Author SHA1 Message Date
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
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
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
64 changed files with 12582 additions and 160 deletions

View File

@ -1,5 +1,40 @@
# 更新日志
## 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
### 修复

View File

@ -20,7 +20,7 @@ Upstream's `createRemoteWorkspace` matched existing records by the raw `remotePa
- **Host (build-time patch, `scripts/patch-remote-ssh.mjs`)**: registration compares light-normalized spellings first; on a miss it resolves the path once over SSH (`pwd -P` + `$HOME`) and compares canonical forms, storing the canonical spelling. Resolution failures are fail-open (creation proceeds as upstream). Behavior is covered by `npm run test:patch`; the vendored tree stays pristine, so upstream updates still drop in.
- **Client (groups)**: adding a cloud folder also refuses when an existing member is backed by the same workspace, or names the same connection + remote directory, regardless of mirror paths.
Already-duplicated projects are not merged automatically (sessions belong to their workspace); remove the duplicate member from the folder dialog once its session is no longer needed — that deletes the duplicate record with it.
Already-duplicated projects are not merged automatically (sessions belong to their workspace). Detaching a member keeps its backing workspace. Deleting the duplicate remote record requires the separate explicit “Delete workspace too” choice; review the affected entry before using it.
### Security hardening (also in the patch set)
@ -34,6 +34,18 @@ Fixes from a 2026-11-11 audit, all applied by the same build-time patch script (
`lib/index.js` (source: `bundle/index.js`) is composition only — it applies both plugins on one fiber. `cordis.patch.yml` inserts a single row for this package and carries remote-ssh's `better-sidebar` / `terminal-controller` shell overrides over verbatim.
### Remote-SSH settings page (1.3.0)
The settings page is a maintainable source component in this repository (`src/client/rssh-settings/`). At build time `scripts/build-remote-ssh-client.mjs` replaces the vendored compiled settings section with it through anchor assertions, so the vendor tree stays pristine. The page has four regions — My connections / Add connection / Remote workspaces / Advanced settings. Remote workspaces and Advanced settings start collapsed; collapsing only changes visibility, never clears drafts or triggers a save, and the collapsed Advanced region shows no inner save button.
- **My connections**: each card tests independently (success, connected-with-warning, failure and diagnostics are shown separately); delete asks for confirmation in-card, naming the connection and its effect.
- **Add connection**: every field and conditional display is kept (key auth shows the private key path; password auth shows a masked input and hides the key path); an invalid port is rejected with a clear error instead of silently falling back to 22; ProxyJump lives in the collapsed “More connection options”.
- **Import from the system SSH config**: a multi-select dialog that checks every save result, counts real successes/failures separately, and can retry failed entries only (successful ones are never resubmitted).
- **Remote workspaces**: per-workspace write-back, write-back exclude, sync scope, sync exclude and size cap (GiB), saved by workspace id; pull/push are blocked with a “save first” notice while a draft is unsaved.
- **Advanced settings**: terminal node path, write-back policy and new-workspace sync defaults; read and written separately from per-workspace settings, so neither overwrites the other.
New copy uses its own `dsh-remote-ssh-settings` locale namespace (Chinese + English); CSS is scoped under `.rsui-root` and does not leak into other plugins.
### Install / migrate
1. Remove the two old bundles from the profile (`workspace-groups-local` and `@zhangfengshun/dsh-remote-ssh`).
@ -60,7 +72,7 @@ The vendored upstream suite also runs in place once its dependencies resolve —
### Maintenance
The vendored code is not a fork: to update remote-ssh, replace `vendor/dsh-remote-ssh/` with the new upstream tree, run `npm run vendor:manifest` to re-record its sha256 manifest, and rebuild — the client transform asserts its anchors and fails loudly if upstream changes its bundle wrapper shape. 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.
The vendored code is not a fork: to update remote-ssh, replace `vendor/dsh-remote-ssh/` with the new upstream tree, run `npm run vendor:manifest` to re-record its sha256 manifest, and rebuild — the client transform asserts its anchors and fails loudly if upstream changes its bundle wrapper shape. The settings-face replacement is anchor-asserted as well: if upstream changes the settings section structure, the build fails instead of silently keeping the old page. Local changes outside the vendor tree: `src/client/GroupsBrowser.tsx` narrows a possibly-null ref explicitly (`pending !== null && ...`) because the fork's `tsc` types step rejected the optional-chain form (semantics unchanged), and the duplicate-folder guards described above (`src/core/folders.ts`, `addRemoteFolderTo`). The host patch script likewise asserts its anchors and fails loudly if upstream changes the anchored code.
## Preview
@ -93,6 +105,10 @@ For Web, replace `desktop` with `web`. Fully restart DSH or the corresponding We
2. Use the `⋯` menu on a project or group to manage grouping, appearance, and folders.
3. Open **Folders…** on a project to attach folders or choose its default root.
**Add a linked-folder workspace** creates a separate entry after confirmation. Existing workspaces and sessions stay in place; it does not migrate sessions or remove old entries. If registration fails after the directory is created, the error identifies that directory; retrying with the same name and folders reuses its verified links.
Detaching a member folder keeps its backing workspace and sessions, so that workspace can appear independently again, even when empty. Both the sidebar and folder dialog ask for this decision. No automatic cleanup is inferred from an empty sidebar count: existing records do not reliably distinguish plugin-created members from independently registered workspaces. Remote record deletion remains a separate explicit choice; it attempts to clean up an unshared local mirror and registration, while session files and the original server directory remain.
For automatic grouping by path or name, see [workspace-groups.example.yaml](./workspace-groups.example.yaml) and configure `~/.dsh/workspace-groups.yaml`. Manual grouping works without this file.
## Uninstall

View File

@ -20,7 +20,7 @@ DeepSeek Harness 工作区分组插件。基于 [z-col/dsh-workspace-groups](htt
- **宿主侧(构建时补丁,`scripts/patch-remote-ssh.mjs`)**:注册时先比轻度规范化后的写法;对不上时走一次 SSH 把路径解析成规范形式(`pwd -P` + `$HOME`)再比对,存入的也用规范写法。解析失败不拦创建(退回上游行为)。补丁行为由 `npm run test:patch` 覆盖;vendor 树保持原样,上游更新仍可直接替换。
- **客户端(分组侧)**:添加云端文件夹时,若已有成员由同一工作区支撑、或指向同一连接 + 同一远程目录,一律拒绝,不再只看镜像路径。
已经产生的重复不会自动合并(会话归属各自的工作区);等那条成员里的会话不再需要时,在文件夹管理里移除该成员即可,它背后的重复记录会一并删除。
已经产生的重复不会自动合并(会话归属各自的工作区)。解除成员关联会保留其工作区;删除重复远程记录需要单独明确选择「连工作区一起删」,操作前请核对目标入口。
### 安全加固(同一组补丁)
@ -34,6 +34,18 @@ DeepSeek Harness 工作区分组插件。基于 [z-col/dsh-workspace-groups](htt
`lib/index.js`(源文件 `bundle/index.js`)只做组合:在同一 fiber 上加载两个插件。`cordis.patch.yml` 只插入一行,并原样保留 remote-ssh 对 `better-sidebar` / `terminal-controller` 的 shell 覆盖。
### Remote-SSH 设置页(1.3.0)
设置页由本仓库可维护源码组件提供(`src/client/rssh-settings/`),构建期由 `scripts/build-remote-ssh-client.mjs` 按锚点断言替换上游编译产物中的设置小节,vendor 树保持原样。页面为「我的连接 / 添加连接 / 远程工作区 / 高级设置」四个分区;远程工作区与高级设置默认收起,折叠只改变可见性,不清空草稿、不触发保存,收起的高级设置不显示内部保存按钮。
- **我的连接**:每卡独立测试(成功 / 成功带 warning / 失败与诊断分别显示),删除前卡内确认并明确连接名与影响范围。
- **添加连接**:保留全部字段与条件显示(密钥显示私钥路径、密码显示遮罩输入并隐藏私钥路径),端口非法明确报错而不是静默回退 22;ProxyJump 收进默认收起的「更多连接选项」。
- **从系统 SSH 配置导入**:多选弹窗,逐项检查保存结果,分别统计成功 / 失败,部分失败可只重试失败项(成功项不重复提交)。
- **远程工作区**:每个工作区独立写回、写回排除、同步范围、同步排除与体积上限(GiB),按工作区 ID 保存;有未保存设置时拉取 / 推送会被阻止并提示先保存。
- **高级设置**:终端 node 路径、写回策略与新工作区同步默认值;与工作区独立配置分开读写,互不覆盖。
新文案使用独立的 `dsh-remote-ssh-settings` 命名空间(中英文),样式限定在 `.rsui-root` 之下,不污染其它插件。
### 安装 / 迁移
1. 从 profile 里移除旧的两个 bundle(`workspace-groups-local` 与 `@zhangfengshun/dsh-remote-ssh`)。
@ -60,7 +72,7 @@ vendor 里的上游测试也能原地跑(需先让其依赖可解析:在仓
### 维护
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`)。宿主补丁脚本同样带锚点断言,上游改动锚点代码时会直接报错。
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`)。宿主补丁脚本同样带锚点断言,上游改动锚点代码时会直接报错。
## 预览
@ -93,6 +105,10 @@ Web 环境将 `desktop` 改为 `web`。安装完成后,完全重启 DSH 或对
2. 在项目或分组的 `⋯` 菜单中管理分组、外观和文件夹。
3. 在项目的「文件夹…」弹窗中添加文件夹或选择默认根目录。
「新增总目录工作区」经确认后添加独立入口。旧工作区和会话仍在原处,不会迁移会话或删除旧入口。如果总目录创建成功但注册失败,提示会列出已创建的路径;保持名称和文件夹不变重试会复用经校验的链接。
解除 member 文件夹关联会保留其工作区和会话,因此该工作区可能重新独立显示,即使它是空入口。侧栏和文件夹弹窗都先让用户确认此结果。不会根据侧栏会话数自动清理:既有记录无法可靠区分插件新建的 member 和用户独立注册的工作区。删除远程记录仍是单独的明确选择,会尝试清理未共用的本地镜像与注册;聊天文件及服务器上的原目录保留。
需要按路径或名称自动分组时,可参考 [workspace-groups.example.yaml](./workspace-groups.example.yaml) 配置 `~/.dsh/workspace-groups.yaml`。不配置也不影响手动分组。
## 卸载

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 { dirname, resolve } from "node:path";
import { lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, stat, symlink, unlink } from "node:fs/promises";
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { homedir } from "node:os";
// node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
function getDefaultExportFromCjs(x) {
@ -3345,6 +3345,163 @@ async function writeFoldersDocument(path, document) {
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
/** Plugin identity for cordis.yml rows. */
const name = "workspace-groups-local";
@ -3660,5 +3817,65 @@ function apply(ctx) {
res.end(body);
}
}), "@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 };

View File

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

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

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
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
* strips that registration wrapper 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
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
* 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`
* are a subset of the groups list).
*/

View File

@ -4,7 +4,7 @@
*/
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.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'>;
/** Simplified Chinese dictionary. */
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",
"version": "1.1.0",
"version": "1.3.0",
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
"keywords": [
"dsh",

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')
body = body.replace(ROOT_LABEL_OLD, ROOT_LABEL_NEW)
// [workspace-groups-remote patch] Settings face replacement.
// Upstream's settings face (SettingsSection, ~280 lines of compiled JS) is
// replaced at build time by the maintainable source component in
// src/client/rssh-settings. The merged client entry passes a `compose` object
// into this factory (createSettingsSection + dictionary namespace); the
// vendored component stays as a fallback for a factory invoked without one
// (older entry, verification harness). Anchor-asserted like every other
// patch: an upstream change fails the build loudly instead of silently
// shipping the old face.
const SETTINGS_REGISTRATION_OLD = ` slots.inject("settings.section", function () {
return slots.register({
name: "settings.section",
id: "remote-ssh",
order: 200,
label: function () { return i18n.t("settings.nav"); },
locale: NS
}, SettingsSection);
});`
const SETTINGS_REGISTRATION_NEW = ` // [workspace-groups-remote patch] Settings face replacement:
// the maintainable source component (src/client/rssh-settings) owns
// the page; allocate it once per registration and keep upstream's
// SettingsSection as the fallback when compose is absent. The
// dictionary namespace comes from compose so the slot renderer
// injects the component's typed \`t\` seat from this bundle's own
// locale registration.
slots.inject("settings.section", function () {
var settingsComponent = SettingsSection;
var settingsLocale = NS;
try {
if (compose && typeof compose.createSettingsSection === "function") {
settingsComponent = compose.createSettingsSection({ api: api });
if (compose.settingsNamespace) settingsLocale = String(compose.settingsNamespace);
}
} catch (error) {
settingsComponent = SettingsSection;
settingsLocale = NS;
}
return slots.register({
name: "settings.section",
id: "remote-ssh",
order: 200,
label: function () { return i18n.t("settings.nav"); },
locale: settingsLocale
}, settingsComponent);
});`
const settingsOccurrences = body.split(SETTINGS_REGISTRATION_OLD).length - 1
if (settingsOccurrences !== 1) {
throw new Error('remote-ssh client: settings registration anchor found ' + settingsOccurrences + ' times — upstream changed, re-check the transform')
}
body = body.replace(SETTINGS_REGISTRATION_OLD, SETTINGS_REGISTRATION_NEW)
const out = header
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
+ '// Upstream registers this factory under its own package id; the merged\n'
+ '// package registers ONE client row, so the factory is exported instead\n'
+ '// and applied by src/client/index.ts. Body below is upstream-verbatim.\n'
+ 'export default (require) => {'
+ '// and applied by src/client/index.ts. Body below is upstream-verbatim\n'
+ '// apart from anchor-asserted patches (root label, settings face).\n'
+ '// The second argument is the merged entry\'s compose seam:\n'
+ '// compose.settingsNamespace + compose.createSettingsSection(deps)\n'
+ 'export default (require, compose) => {'
+ body
+ '\n}\n'
// Post-conditions: the vulnerable/old forms must be gone and the compose
// seam present, so a successful build can never silently keep the old face.
if (out.includes('}, SettingsSection);')) {
throw new Error('remote-ssh client: the upstream settings registration survived the transform')
}
for (const required of [
'export default (require, compose) => {',
'compose.createSettingsSection({ api: api })',
'var settingsComponent = SettingsSection;',
'locale: settingsLocale',
]) {
if (!out.includes(required)) throw new Error('remote-ssh client: expected transformed form missing: ' + required)
}
writeFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), out)
console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs')

View File

@ -381,5 +381,22 @@ console.log('patch hygiene')
check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)')
check(src.includes('resolveRemoteCanonical'), 'built artifact carries the patch')
// --- client transform: settings face replacement ---------------------------
// scripts/build-remote-ssh-client.mjs replaces the vendored settings face
// with the maintainable source component and exports the factory with the
// merged entry's compose seam. Assert the generated source rather than only
// the built bundle, so an upstream anchor drift is caught here too.
console.log('client factory transform (settings face)')
{
const generated = readFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), 'utf8')
check(generated.includes('export default (require, compose) => {'), 'generated factory accepts the compose seam')
check(generated.includes('compose.createSettingsSection({ api: api })'), 'settings registration builds the source component')
check(generated.includes('settingsComponent = SettingsSection;'), 'vendored settings face stays as the fallback')
check(!generated.includes('}, SettingsSection);'), 'upstream registration is gone from the generated factory')
check(generated.includes('locale: settingsLocale'), 'settings entry declares the compose-provided namespace')
const vendoredClient = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/client.js'), 'utf8')
check(!vendoredClient.includes('compose.createSettingsSection'), 'vendored client stays pristine')
}
console.log('\n' + pass + ' passed, ' + fail + ' failed')
process.exit(fail === 0 ? 0 : 1)

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 contains the groups half', client.includes('workspaceGroups'))
check('client contains the remote-ssh half', client.includes('remssh'))
check('client ships the maintainable remote-ssh settings face', client.includes('dsh-remote-ssh-settings') && client.includes('rsui-root'))
check('client carries the settings-face compose seam', client.includes('createSettingsSection') && client.includes('settingsNamespace'))
const remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')

View File

@ -13,7 +13,7 @@
* swaps to the remote tree, so no stacked overlays are needed and the current
* location stays readable at the top.
*/
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import {
Button,
IconFolderOpenOutlineRegular,
@ -44,7 +44,7 @@ function subfolderOf(root: string | null, picked: string): string | 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
entry: WorkspaceFolderEntry | undefined
t: GroupsBrowserProps['t']
@ -59,7 +59,14 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
profilesError: string | null
/** Live workspace ids, so a member whose workspace is gone can say so. */
knownWorkspaceIds: readonly string[]
/** Sidebar removal opens this same confirmation instead of bypassing it. */
initialRemovePath?: string | null
onClose: () => void
/**
* Gather this project's folders into one link directory and register it as a
* workspace, so a single session can read and write all of them.
*/
onBuildFarm: () => void
/** Pick any directory (local or an already-mirrored cloud folder). */
onAddFolder: () => void
/** Register one cloud folder: returns true once it is stored. */
@ -72,8 +79,11 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
const folders = effectiveFolders(workspace.path, entry)
const root = rootOf(workspace.path, entry)
const [addMode, setAddMode] = useState<AddMode>('local')
// Path of the remote member whose removal awaits the delete-record choice.
const [confirmRemovePath, setConfirmRemovePath] = useState<string | null>(null)
// All members keep their workspace when detached, including local members.
const [confirmRemovePath, setConfirmRemovePath] = useState<string | null>(initialRemovePath ?? null)
const [confirmFarm, setConfirmFarm] = useState(false)
const farmConfirmation = useRef(false)
useEffect(() => { setConfirmRemovePath(initialRemovePath ?? null) }, [initialRemovePath])
const [profileId, setProfileId] = useState('')
const [remotePath, setRemotePath] = useState('')
const [browsing, setBrowsing] = useState(false)
@ -227,9 +237,8 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
className="wgIconButton"
aria-label={`${t('folder.remove')} ${label}`}
onClick={() => {
// A remote member can take its backing workspace
// with it; ask which removal the user means first.
if (canDeleteRecord) setConfirmRemovePath(path)
// Detaching exposes the backing workspace as its own row.
if (member !== undefined) setConfirmRemovePath(path)
else onRemove(path, false)
}}
>
@ -240,16 +249,17 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
</div>
{confirmRemovePath === path && (
<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">
<button
{canDeleteRecord && <button
type="button"
className="wgFolderConfirmButton"
data-tone="danger"
onClick={() => { setConfirmRemovePath(null); onRemove(path, true) }}
>
{t('folder.removeRemoteDelete')}
</button>
</button>}
<button
type="button"
className="wgFolderConfirmButton"
@ -274,6 +284,38 @@ export function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, owne
{!extraFolders && <p className="wgFolderEmpty">{t('folder.emptyHint')}</p>}
</section>
{extraFolders && (
<section className="wgFolderMerge">
<div className="wgFolderSectionTitle">{t('folder.mergeTitle')}</div>
{/* A session's file scope is its workspace directory, so folders in
different places are unreachable from one session. A farm puts
them side by side as links; nothing is copied or moved. */}
<button type="button" className="wgFolderPick" disabled={busy} 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">
<div className="wgFolderSectionTitle">{t('folder.sectionAdd')}</div>
<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 { fetchOpenInApps, folderAppId, openPathInApp } from './open-folder.ts'
import { FoldersDialog } from './FoldersDialog.tsx'
import { buildFarm } from './folders-farm.ts'
import { QuickPanel } from './QuickPanel.tsx'
import { SessionTabs } from './SessionTabs.tsx'
import css from './styles.css?inline'
@ -931,7 +932,9 @@ export function GroupsBrowser({
const foldersOwnerRequest = useRef('')
/** Open the folder dialog and learn the owner's remote root (cloud owners only). */
const [folderRemovalPath, setFolderRemovalPath] = useState<string | null>(null)
const openFoldersFor = (workspaceId: string): void => {
setFolderRemovalPath(null)
foldersOwnerRequest.current = workspaceId
setFoldersTarget(workspaceId as WorkspaceId)
setFoldersOwnerRemote(null)
@ -1147,17 +1150,58 @@ export function GroupsBrowser({
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
* folder dialog offers it, behind an explicit confirm — a remote member's
* backing record is deleted through the SSH plugin as well (record, native
* workspace and mirror go away, sessions included); without it the removal
* backing record is deleted through the SSH plugin as well (unshared native
* registration and local mirror cleanup is attempted; session files remain).
* Without it the removal
* is overlay-only and the workspace survives as its own project. If the
* record deletion fails, the member stays so the user can retry.
*/
const removeFolderFrom = (workspaceId: WorkspaceId, path: string, deleteRecord = false): void => {
const removeFolderFrom = (workspaceId: WorkspaceId, path: string, deleteRecord = false, confirmed = false): void => {
const entry = entryFor(foldersDoc, workspaceId as string)
const member = memberOf(entry, path)
if (member !== undefined && !confirmed) {
openFoldersFor(workspaceId as string)
setFolderRemovalPath(path)
return
}
if (deleteRecord && member?.kind === 'remote' && member.recordId !== undefined && member.recordId !== '') {
const recordId = member.recordId
void (async () => {
@ -2255,16 +2299,18 @@ export function GroupsBrowser({
t={t}
busy={foldersBusy}
canOpen={openFolderPath !== undefined}
onBuildFarm={() => { void buildFarmFor(foldersTarget) }}
remote={isRemoteWorkspace(workspace)}
ownerRemotePath={foldersOwnerRemote}
profiles={remoteProfiles}
profilesError={remoteProfilesError}
knownWorkspaceIds={workspaces.map(w => w.workspaceId as string)}
initialRemovePath={folderRemovalPath}
onAddFolder={() => { void addFolderTo(foldersTarget) }}
onAddRemote={(profileId, remotePath) => addRemoteFolderTo(foldersTarget, profileId, remotePath)}
onAddSubpath={(relative) => addSubpathTo(foldersTarget, relative)}
onSetRoot={(path) => { setFolderRoot(foldersTarget, path) }}
onRemove={(path, deleteRecord) => { removeFolderFrom(foldersTarget, path, deleteRecord) }}
onRemove={(path, deleteRecord) => { removeFolderFrom(foldersTarget, path, deleteRecord, true) }}
onOpenFolder={(path) => { openFolderPath?.(path) }}
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
* record, unregisters the native workspace behind it (that workspace's
* sessions go with it) and cleans up the mirror — the counterpart of
* {@link createRemoteFolder}, for when a member folder is removed for good.
* record and attempts to unregister its native workspace and clean up its
* local mirror unless shared by another record. Session files and the original
* remote directory remain; unregistering may hide sessions from the sidebar.
* @param recordId - remote-ssh record id stored on the member.
* @param fetchImpl - fetch implementation (tests inject one).
*/

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
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
* strips that registration wrapper 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
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
* 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`
* are a subset of the groups list).
*/
import type { Context } from '@deepseek-ai/cordis'
import * as groupsClient from './groups-client.ts'
import remoteSshFactory from './remote-ssh-factory.generated.mjs'
import { SETTINGS_NS, registerSettingsLocale } from './rssh-settings/i18n.ts'
import { createSettingsSection } from './rssh-settings/index.tsx'
import { SETTINGS_CSS } from './rssh-settings/styles.ts'
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
/** Services required before mounting (union of both client halves). */
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. */
const remoteSshClient = remoteSshFactory(id => require(id))
const remoteSshClient = remoteSshFactory(id => require(id), remoteSshCompose)
/** Plugin body: apply both client halves on this bundle's fiber. */
export function apply(ctx: Context): void {
// The settings section declares `locale: SETTINGS_NS`, so the dictionary
// face must be installed before the vendored half registers that slot entry.
// (Slot rendering requires an installed locale face; registration also bumps
// the revision so an already-mounted settings page picks the texts up.)
ctx.effect(
() => registerSettingsLocale(ctx.locale),
'workspace-groups-remote: remote-ssh settings dictionaries',
)
// Section styles: injected once, scoped under `.rsui-root` (no global
// selectors), removed with the fiber. `?inline` is compiled by tsdown.
ctx.effect(() => {
if (SETTINGS_CSS.trim() === '') return () => {}
const style = document.createElement('style')
style.setAttribute('data-plugin', 'workspace-groups-remote/remote-ssh-settings')
style.textContent = SETTINGS_CSS
document.head.appendChild(style)
return () => { style.remove() }
}, 'workspace-groups-remote: remote-ssh settings styles')
groupsClient.apply(ctx)
remoteSshClient.apply(ctx)
}

View File

@ -41,6 +41,15 @@ export type WorkspaceGroupsKey =
| 'folder.sectionList'
| 'folder.sectionAdd'
| 'folder.emptyHint'
| 'folder.mergeTitle'
| 'folder.mergeAction'
| 'folder.mergeHint'
| 'folder.mergeDone'
| 'folder.mergeConfirm'
| 'folder.mergeRegistrationFailed'
| 'folder.removeMemberPrompt'
| 'folder.removeMissingPrompt'
| 'folder.mergeFailed'
| 'folder.base'
| 'folder.setRoot'
| 'folder.rootBadge'
@ -233,6 +242,15 @@ export const zh: WorkspaceGroupsDict = {
'folder.sectionList': '项目文件夹',
'folder.sectionAdd': '添加文件夹',
'folder.emptyHint': '还没有额外文件夹。下面挂一个目录,它的会话会独立运行,模型也能直接读到里面的文件。',
'folder.mergeTitle': '新增总目录工作区',
'folder.mergeAction': '新增总目录入口',
'folder.mergeHint': '为上方文件夹创建链接总目录,并新增一个独立工作区入口。原文件夹、旧工作区和原会话均保留;不会迁移会话或删除旧入口。',
'folder.mergeConfirm': '确认将上方列出的文件夹链接到总目录,并注册为独立工作区?旧工作区及会话仍在原处,新入口不包含旧会话。',
'folder.mergeDone': '总目录工作区已就绪;旧工作区和会话保留在原处:',
'folder.mergeRegistrationFailed': '总目录已创建,但工作区注册失败。保持名称和文件夹不变重试将复用该目录,不会迁移或删除旧工作区:',
'folder.removeMemberPrompt': '解除关联后,此文件夹的工作区和会话会保留,并可重新作为独立入口显示(即使没有会话)。不会删除目录或迁移会话。',
'folder.removeMissingPrompt': '仅移除此处的失效关联,不会重建工作区,也不会删除目录或会话。',
'folder.mergeFailed': '生成总文件夹失败',
'folder.base': '基础文件夹',
'folder.setRoot': '设为根目录',
'folder.rootBadge': '根目录',
@ -242,9 +260,9 @@ export const zh: WorkspaceGroupsDict = {
'folder.duplicate': '该文件夹已在此工作区中',
'folder.conflict': '文件夹已被另一个窗口修改,已同步为最新状态,本次修改未保存,请重试',
'folder.removeError': '远程工作区删除失败',
'folder.removeRemotePrompt': '这个云端文件夹背后有一个工作区,移除时要连它一起删掉吗?删掉后它里面的会话也会消失。',
'folder.removeRemotePrompt': '“连工作区一起删”会删除远程记录,并尝试清理未被其他记录共用的工作区注册和本地镜像。会话可能从侧栏隐藏,聊天文件保留;不删除服务器上的原目录。',
'folder.removeRemoteDelete': '连工作区一起删',
'folder.removeRemoteOnly': '只移除文件夹',
'folder.removeRemoteOnly': '解除关联,保留工作区',
'folder.addError': '添加文件夹失败',
'folder.sessionError': '新建会话失败',
'folder.saveError': '文件夹保存失败',
@ -424,6 +442,15 @@ export const en: WorkspaceGroupsDict = {
'folder.sectionList': 'Project folders',
'folder.sectionAdd': 'Add a folder',
'folder.emptyHint': 'No extra folders yet. A folder added below runs its sessions on its own, so the agent can read the files inside it directly.',
'folder.mergeTitle': 'Add a linked-folder workspace',
'folder.mergeAction': 'Add a separate workspace entry',
'folder.mergeHint': 'Links the folders above into one directory and adds a separate workspace entry. Original folders, workspaces and sessions stay in place; sessions are not migrated and old entries are not deleted.',
'folder.mergeConfirm': 'Link the folders listed above into one directory and register a separate workspace? Existing workspaces and sessions stay in place. The new entry does not contain the old sessions.',
'folder.mergeDone': 'Linked-folder workspace ready; existing workspaces and sessions stay in place: ',
'folder.mergeRegistrationFailed': 'The linked directory was created, but workspace registration failed. Retrying with the same name and folders reuses it without migrating or deleting existing workspaces: ',
'folder.removeMemberPrompt': 'Detaching keeps this folder’s workspace and sessions. It can appear as a separate entry again, even with no sessions. No directory is deleted and no sessions are migrated.',
'folder.removeMissingPrompt': 'Remove only this stale association. This does not recreate the workspace or delete directories or sessions.',
'folder.mergeFailed': 'Could not build the merged folder',
'folder.base': 'Base folder',
'folder.setRoot': 'Set as root',
'folder.rootBadge': 'Root',
@ -433,9 +460,9 @@ export const en: WorkspaceGroupsDict = {
'folder.duplicate': 'That folder is already in this workspace',
'folder.conflict': 'Folders changed in another window; synced to the latest state, this edit was not saved — please retry',
'folder.removeError': 'Could not delete the remote workspace',
'folder.removeRemotePrompt': '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.removeRemoteOnly': 'Remove folder only',
'folder.removeRemoteOnly': 'Detach and keep workspace',
'folder.addError': 'Could not add the folder',
'folder.sessionError': 'Could not start a session',
'folder.saveError': 'Could not save folders',

View File

@ -1,4 +1,5 @@
import type { Context } from '@deepseek-ai/cordis'
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
/** The plugin object the vendored dsh-remote-ssh client factory returns. */
export interface RemoteSshClientPlugin {
@ -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
* scripts/build-remote-ssh-client.mjs as remote-ssh-factory.generated.mjs.
*
* `compose` is the merged entry's seam (settings namespace + settings section
* component factory). Omit it and the factory falls back to the vendored
* settings face — the transform keeps that path for harnesses and old entries.
*/
export default function remoteSshClientFactory(
require: (id: string) => unknown,
compose?: RemoteSshClientCompose,
): RemoteSshClientPlugin

View File

@ -13,8 +13,11 @@
// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---
// Upstream registers this factory under its own package id; the merged
// package registers ONE client row, so the factory is exported instead
// and applied by src/client/index.ts. Body below is upstream-verbatim.
export default (require) => {
// and applied by src/client/index.ts. Body below is upstream-verbatim
// 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 exports = module.exports;
var React = require("react");
@ -1956,14 +1959,32 @@ export default (require) => {
});
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 () {
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: NS
}, SettingsSection);
locale: settingsLocale
}, 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

@ -376,27 +376,14 @@ function applyFolders(
// remains the directory identity for file access; only the LABEL changes.
const title = workspaceTitle.trim()
if (title !== '') labels.set(workspacePath, title)
// A member whose name is the same project (allowing a qualifier such as
// "(云端)") is the same folder from the user's point of view. Fold its
// sessions into the base row instead of painting a second folder row.
const nameOf = (value: string): string => value.replace(/[((][^))]*[))]/gu, '').trim()
const baseName = nameOf(title)
const memberPaths = new Set((entry?.members ?? []).map(member => member.path))
const mergedMembers = new Set<string>()
if (baseName !== '') {
for (const member of entry?.members ?? []) {
if (nameOf(labels.get(member.path) ?? folderLabel(member.path)) === baseName) mergedMembers.add(member.path)
}
}
const isMergedMember = (path: string): boolean => [...mergedMembers].some(member => samePath(member, path))
const extras = effectiveFolders(workspacePath, entry).slice(1).filter(path => !isMergedMember(path))
const extras = effectiveFolders(workspacePath, entry).slice(1)
if (extras.length === 0) return { sessions }
const root = rootOf(workspacePath, entry)
const base: SessionNode[] = []
const byFolder = new Map<string, SessionNode[]>()
for (const node of sessions) {
const owner = folderOfCwd(list.byId[node.id]?.cwd, workspacePath, entry)
if (samePath(owner, workspacePath) || isMergedMember(owner)) {
if (samePath(owner, workspacePath)) {
base.push(node)
continue
}

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,
writeFoldersDocument,
} from './host-folders.ts'
import { buildFarm, removeFarm } from './host-farm.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'workspace-groups-local'
@ -381,4 +382,70 @@ export function apply(ctx: GroupsContext): void {
res.end(body)
},
}), '@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()
})
})

View File

@ -181,38 +181,6 @@ describe('category appearance on the tree nodes', () => {
})
describe('folder rows use confirmed display names', () => {
it('folds a same-name local member into the base row instead of a second folder', () => {
const owner = workspace('ws-remote', 'C:/mirror/w123', '云端记忆系统(云端)', ['s1'])
const member = workspace('ws-local', 'C:/Users/qyh15/云端记忆系统', '云端记忆系统', ['s2'])
const list = {
ids: ['s1', 's2'],
byId: {
s1: { ...session('s1', 'remote'), cwd: 'C:/mirror/w123' },
s2: { ...session('s2', 'local'), cwd: 'C:/Users/qyh15/云端记忆系统' },
},
current: 's1',
phase: 'ready',
subagentsByParent: {},
} as unknown as SessionListState
const folders: FoldersDocument = {
version: 1,
revision: 1,
workspaces: {
'ws-remote': {
folders: [],
members: [{ path: 'C:/Users/qyh15/云端记忆系统', workspaceId: 'ws-local', kind: 'local' }],
},
},
}
const view = { expandedCategories: [], expandedWorkspaces: ['ws-remote'] }
const top = deriveTopLevel(list, [owner, member], [], CONFIG, view, { categories: [], assignments: {} }, new Map(), folders)
const node = top.find(item => item.workspaceId === 'ws-remote')
expect(node).toBeDefined()
// The member row is gone; both sessions live on the single base row.
expect(node?.folders).toBeUndefined()
expect(node?.sessions.map(item => item.id)).toEqual(['s1', 's2'])
})
it('base row shows the project title, not the local mirror basename', () => {
const ws = workspace('ws-remote', 'C:/mirror/w123', '远程项目', ['s1'])
const folders: FoldersDocument = {

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

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