Compare commits
5 Commits
| Author | SHA1 | Date |
|---|---|---|
|
|
637c62f1f3 | |
|
|
9448886ea3 | |
|
|
c67fee3d40 | |
|
|
9eb8c90280 | |
|
|
b514a8b0f2 |
14
CHANGELOG.md
|
|
@ -1,5 +1,19 @@
|
||||||
# 更新日志
|
# 更新日志
|
||||||
|
|
||||||
|
## 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.2 — 2026-11-13
|
||||||
|
|
||||||
- 总目录操作明确为新增独立工作区:执行前展示确认,说明不会迁移会话或移除旧入口,避免被误解为原位合并。
|
- 总目录操作明确为新增独立工作区:执行前展示确认,说明不会迁移会话或移除旧入口,避免被误解为原位合并。
|
||||||
|
|
|
||||||
14
README.md
|
|
@ -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.
|
`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
|
### Install / migrate
|
||||||
|
|
||||||
1. Remove the two old bundles from the profile (`workspace-groups-local` and `@zhangfengshun/dsh-remote-ssh`).
|
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
|
### 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
|
## Preview
|
||||||
|
|
||||||
|
|
|
||||||
14
README_ZH.md
|
|
@ -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 覆盖。
|
`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`)。
|
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`)。宿主补丁脚本同样带锚点断言,上游改动锚点代码时会直接报错。
|
||||||
|
|
||||||
## 预览
|
## 预览
|
||||||
|
|
||||||
|
|
|
||||||
2582
lib/client.js
|
|
@ -10,11 +10,18 @@
|
||||||
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
||||||
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
||||||
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
||||||
* strips that registration wrapper and re-exports the bare factory, which
|
* strips that registration wrapper, re-exports the bare factory and applies
|
||||||
|
* two anchor-asserted transforms (root label, settings face). The factory
|
||||||
* is invoked here with this bundle's own require (its only requires are
|
* is invoked here with this bundle's own require (its only requires are
|
||||||
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
||||||
* modules) and applied alongside the groups client.
|
* modules) and applied alongside the groups client.
|
||||||
*
|
*
|
||||||
|
* The settings page itself is NOT the vendored compiled component: the factory
|
||||||
|
* receives `remoteSshCompose`, whose `createSettingsSection` builds the
|
||||||
|
* maintainable React section from src/client/rssh-settings. Its dictionary
|
||||||
|
* namespace and CSS live in this entry because the merged package owns them
|
||||||
|
* (the vendored half only knows its upstream keys/styles).
|
||||||
|
*
|
||||||
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
||||||
* are a subset of the groups list).
|
* are a subset of the groups list).
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,206 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings face — wire contract.
|
||||||
|
*
|
||||||
|
* The settings section is produced by this module and registered into the
|
||||||
|
* shell's `settings.section` slot by the vendored remote-ssh client (see
|
||||||
|
* scripts/build-remote-ssh-client.mjs). The module talks to the Host through
|
||||||
|
* the SAME `/remote-ssh/api/*` JSON-RPC the vendored client uses: the merged
|
||||||
|
* entry hands it the vendored client's own `api()` wrapper, so endpoint
|
||||||
|
* names, envelopes and semantics stay byte-identical to upstream.
|
||||||
|
*
|
||||||
|
* Types below mirror the Host implementations in
|
||||||
|
* vendor/dsh-remote-ssh/lib/index.js (api object around line 4641) and the
|
||||||
|
* redacted profile projection (`publicProfiles`, line 37). They are a
|
||||||
|
* compile-time description only; nothing here changes runtime behaviour.
|
||||||
|
*/
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
/** Redacted connection profile (`publicProfiles`: password stripped, boolean kept). */
|
||||||
|
export interface RemoteSshProfile {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
host: string;
|
||||||
|
port?: number;
|
||||||
|
user: string;
|
||||||
|
authMethod?: 'key' | 'password';
|
||||||
|
keyPath?: string;
|
||||||
|
remoteRoot?: string;
|
||||||
|
proxyJump?: string;
|
||||||
|
passwordConfigured?: boolean;
|
||||||
|
}
|
||||||
|
/** One persisted remote workspace record (settingsFace.workspaces entry). */
|
||||||
|
export interface RemoteSshWorkspace {
|
||||||
|
id: string;
|
||||||
|
profileId: string;
|
||||||
|
title?: string;
|
||||||
|
remotePath?: string;
|
||||||
|
mirrorPath?: string;
|
||||||
|
shellWorkspaceId?: string;
|
||||||
|
writeBack?: boolean;
|
||||||
|
writeBackExclude?: string[];
|
||||||
|
syncPaths?: string[];
|
||||||
|
syncExclude?: string[];
|
||||||
|
syncMaxBytes?: number;
|
||||||
|
}
|
||||||
|
/** One `~/.ssh/config` host entry (listSshConfigHosts projection). */
|
||||||
|
export interface SshConfigHost {
|
||||||
|
name: string;
|
||||||
|
hostName: string;
|
||||||
|
port?: number;
|
||||||
|
user?: string;
|
||||||
|
identityFile?: string;
|
||||||
|
proxyJump?: string;
|
||||||
|
}
|
||||||
|
/** Global preferences as rendered by the Host (getPrefs/savePrefs.prefs). */
|
||||||
|
export interface RemoteSshPrefs {
|
||||||
|
nodePath?: string;
|
||||||
|
writeBackFailure?: string;
|
||||||
|
writeBackFreshness?: boolean;
|
||||||
|
defaultSyncPaths?: string[];
|
||||||
|
defaultSyncExclude?: string[];
|
||||||
|
defaultSyncMaxBytes?: number;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* saveProfile body. Every field the vendored settings face sent is kept:
|
||||||
|
* `name`, `host`, `port`, `user`, `authMethod`, `keyPath`, `password`,
|
||||||
|
* `remoteRoot`, `proxyJump`. `port` is already an integer here (the form
|
||||||
|
* rejects invalid values instead of letting the Host fall back to 22).
|
||||||
|
*/
|
||||||
|
export interface SaveProfilePayload {
|
||||||
|
name: string;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user: string;
|
||||||
|
authMethod: 'key' | 'password';
|
||||||
|
keyPath: string;
|
||||||
|
password: string;
|
||||||
|
remoteRoot: string;
|
||||||
|
proxyJump: string;
|
||||||
|
}
|
||||||
|
/** updateWorkspaceGuards body: per-workspace write-back and sync scope. */
|
||||||
|
export interface UpdateWorkspaceGuardsPayload {
|
||||||
|
id: string;
|
||||||
|
writeBack: boolean;
|
||||||
|
writeBackExclude: string[];
|
||||||
|
syncPaths: string[];
|
||||||
|
syncExclude: string[];
|
||||||
|
/** Bytes; 0 = Host built-in default cap (the old face always sent this). */
|
||||||
|
syncMaxBytes: number;
|
||||||
|
}
|
||||||
|
/** savePrefs body: global terminal / write-back / new-workspace defaults. */
|
||||||
|
export interface SavePrefsPayload {
|
||||||
|
nodePath: string;
|
||||||
|
writeBackFailure: 'error' | 'log';
|
||||||
|
writeBackFreshness: boolean;
|
||||||
|
defaultSyncPaths: string[];
|
||||||
|
defaultSyncExclude: string[];
|
||||||
|
defaultSyncMaxBytes: number;
|
||||||
|
}
|
||||||
|
export interface ListProfilesResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
profiles?: RemoteSshProfile[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface SaveProfileResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
id?: string;
|
||||||
|
profiles?: RemoteSshProfile[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface TestConnectionResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
warning?: string;
|
||||||
|
stdout?: string;
|
||||||
|
stderr?: string;
|
||||||
|
error?: string;
|
||||||
|
exitCode?: number;
|
||||||
|
truncated?: boolean;
|
||||||
|
}
|
||||||
|
export interface DeleteProfileResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
profiles?: RemoteSshProfile[];
|
||||||
|
workspaces?: RemoteSshWorkspace[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface ListSshConfigHostsResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
hosts?: SshConfigHost[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface ListWorkspacesResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
workspaces?: RemoteSshWorkspace[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface UpdateWorkspaceGuardsResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
workspaces?: RemoteSshWorkspace[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface SyncResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface DeleteWorkspaceResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
workspaces?: RemoteSshWorkspace[];
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface GetPrefsResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
prefs?: RemoteSshPrefs;
|
||||||
|
deleteSync?: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
export interface SavePrefsResponse {
|
||||||
|
ok?: boolean;
|
||||||
|
prefs?: RemoteSshPrefs;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Typed view of the vendored client's `api(method, args)` wrapper. The
|
||||||
|
* wrapper resolves to the Host's `value` object (which always carries its
|
||||||
|
* own `ok` flag) or `{ ok: false, error }` for transport failures.
|
||||||
|
*/
|
||||||
|
export interface RemoteSshApi {
|
||||||
|
(method: 'listProfiles'): Promise<ListProfilesResponse>;
|
||||||
|
(method: 'saveProfile', args: SaveProfilePayload): Promise<SaveProfileResponse>;
|
||||||
|
(method: 'testConnection', args: {
|
||||||
|
id: string;
|
||||||
|
}): Promise<TestConnectionResponse>;
|
||||||
|
(method: 'deleteProfile', args: {
|
||||||
|
id: string;
|
||||||
|
}): Promise<DeleteProfileResponse>;
|
||||||
|
(method: 'listSshConfigHosts'): Promise<ListSshConfigHostsResponse>;
|
||||||
|
(method: 'listWorkspaces'): Promise<ListWorkspacesResponse>;
|
||||||
|
(method: 'updateWorkspaceGuards', args: UpdateWorkspaceGuardsPayload): Promise<UpdateWorkspaceGuardsResponse>;
|
||||||
|
(method: 'syncDown', args: {
|
||||||
|
id: string;
|
||||||
|
}): Promise<SyncResponse>;
|
||||||
|
(method: 'syncUp', args: {
|
||||||
|
id: string;
|
||||||
|
}): Promise<SyncResponse>;
|
||||||
|
(method: 'deleteWorkspace', args: {
|
||||||
|
id: string;
|
||||||
|
}): Promise<DeleteWorkspaceResponse>;
|
||||||
|
(method: 'getPrefs'): Promise<GetPrefsResponse>;
|
||||||
|
(method: 'savePrefs', args: SavePrefsPayload): Promise<SavePrefsResponse>;
|
||||||
|
}
|
||||||
|
/** Bind of the settings dictionary namespace (typed keys, `{name}` params). */
|
||||||
|
export type SettingsTranslate = (key: string, params?: Record<string, string | number>) => string;
|
||||||
|
/** Props the shell's `settings.section` renderer injects (locale `t` seat). */
|
||||||
|
export interface SettingsSectionProps {
|
||||||
|
t?: SettingsTranslate;
|
||||||
|
}
|
||||||
|
/** Registration shape accepted by the slot renderer (function component). */
|
||||||
|
export type SettingsSectionComponent = (props: SettingsSectionProps) => ReactNode;
|
||||||
|
/** Runtime facts the merged client entry hands to the extracted factory. */
|
||||||
|
export interface RemoteSshClientCompose {
|
||||||
|
/** Dictionary namespace the settings entry declares (`locale:` in the slot def). */
|
||||||
|
readonly settingsNamespace: string;
|
||||||
|
/** Build the settings section component around the vendored client's `api`. */
|
||||||
|
createSettingsSection(deps: SettingsSectionDeps): SettingsSectionComponent;
|
||||||
|
}
|
||||||
|
/** Injected runtime services for the section (the vendored client's api wrapper). */
|
||||||
|
export interface SettingsSectionDeps {
|
||||||
|
api: RemoteSshApi;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,170 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings dictionary.
|
||||||
|
*
|
||||||
|
* The section registers its OWN namespace `dsh-remote-ssh-settings` through
|
||||||
|
* the shell locale service (the merged client entry calls
|
||||||
|
* {@link registerSettingsLocale} inside `ctx.effect`). Registering a separate
|
||||||
|
* namespace — instead of appending keys to the vendored plugin's
|
||||||
|
* `dsh-remote-ssh` dictionaries at build time — keeps all new copy in source,
|
||||||
|
* type-checked by the `SettingsKey` union, and lets the slot machinery inject
|
||||||
|
* a typed `t` seat into the component (declared as `locale:` in the slot
|
||||||
|
* registration). Existing upstream keys/namespace are untouched.
|
||||||
|
*/
|
||||||
|
import type { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client';
|
||||||
|
/** Namespace owned by this settings face. */
|
||||||
|
export declare const SETTINGS_NS = "dsh-remote-ssh-settings";
|
||||||
|
/** Chinese dictionary — the key set below is the single source of truth. */
|
||||||
|
export declare const zh: {
|
||||||
|
readonly 'page.title': "Remote SSH";
|
||||||
|
readonly 'page.subtitle': "管理远程连接与同步设置";
|
||||||
|
readonly 'connection.sectionTitle': "我的连接";
|
||||||
|
readonly 'connection.sectionSummary': "测试连接、查看当前连接的诊断信息";
|
||||||
|
readonly 'connection.count': "{n} 个连接";
|
||||||
|
readonly 'connection.empty': "还没有连接配置。在下方「添加连接」中新增。";
|
||||||
|
readonly 'connection.test': "测试连接";
|
||||||
|
readonly 'connection.testing': "测试中…";
|
||||||
|
readonly 'connection.delete': "删除";
|
||||||
|
readonly 'connection.authKey': "密钥认证";
|
||||||
|
readonly 'connection.authPassword': "密码认证";
|
||||||
|
readonly 'connection.passwordConfigured': "已保存密码";
|
||||||
|
readonly 'connection.testOk': "连接成功";
|
||||||
|
readonly 'connection.testWarn': "连接成功,但有警告:";
|
||||||
|
readonly 'connection.testFail': "连接失败";
|
||||||
|
readonly 'connection.diagnostics': "诊断输出";
|
||||||
|
readonly 'connection.deleteTitle': "删除连接「{name}」?";
|
||||||
|
readonly 'connection.deleteBody': "将同时移除该连接下的远程工作区条目和本地镜像映射;不会删除服务器上的文件。";
|
||||||
|
readonly 'connection.deleted': "已删除连接「{name}」";
|
||||||
|
readonly 'connection.deleteFail': "删除失败";
|
||||||
|
readonly 'add.sectionTitle': "添加连接";
|
||||||
|
readonly 'add.sectionSummary': "从系统 SSH 配置导入,或手动填写";
|
||||||
|
readonly 'add.import': "从系统 SSH 配置导入…";
|
||||||
|
readonly 'add.divider': "或手动添加";
|
||||||
|
readonly 'add.name': "名称";
|
||||||
|
readonly 'add.namePlaceholder': "如:我的超算";
|
||||||
|
readonly 'add.host': "主机";
|
||||||
|
readonly 'add.hostPlaceholder': "login.example.com";
|
||||||
|
readonly 'add.port': "端口";
|
||||||
|
readonly 'add.user': "用户名";
|
||||||
|
readonly 'add.userPlaceholder': "your-username";
|
||||||
|
readonly 'add.auth': "认证方式";
|
||||||
|
readonly 'add.authKey': "SSH 密钥";
|
||||||
|
readonly 'add.authPassword': "密码";
|
||||||
|
readonly 'add.keyPath': "私钥路径";
|
||||||
|
readonly 'add.keyPathPlaceholder': "~/.ssh/id_rsa(留空则使用 ssh-agent 或 SSH 配置)";
|
||||||
|
readonly 'add.password': "密码";
|
||||||
|
readonly 'add.passwordPlaceholder': "输入密码(不会写回浏览器存储)";
|
||||||
|
readonly 'add.remoteRoot': "远程根目录";
|
||||||
|
readonly 'add.remoteRootPlaceholder': "~/project";
|
||||||
|
readonly 'add.moreOptions': "更多连接选项";
|
||||||
|
readonly 'add.moreOptionsSummary': "跳板机 ProxyJump";
|
||||||
|
readonly 'add.proxyJump': "跳板机 ProxyJump";
|
||||||
|
readonly 'add.proxyJumpPlaceholder': "bastion.example.com";
|
||||||
|
readonly 'add.submit': "添加连接";
|
||||||
|
readonly 'add.submitting': "添加中…";
|
||||||
|
readonly 'add.errHost': "请填写主机";
|
||||||
|
readonly 'add.errUser': "请填写用户名";
|
||||||
|
readonly 'add.errPort': "端口必须是 1–65535 的整数";
|
||||||
|
readonly 'add.ok': "已添加连接「{name}」";
|
||||||
|
readonly 'add.fail': "添加失败";
|
||||||
|
readonly 'import.title': "从系统 SSH 配置导入";
|
||||||
|
readonly 'import.loading': "正在读取 ~/.ssh/config…";
|
||||||
|
readonly 'import.readFail': "读取 ~/.ssh/config 失败";
|
||||||
|
readonly 'import.empty': "未在 ~/.ssh/config 中发现可用主机";
|
||||||
|
readonly 'import.note': "仅列出 ~/.ssh/config 中带 HostName 的条目;这不是完整的 OpenSSH 配置语义。";
|
||||||
|
readonly 'import.selectAll': "全选";
|
||||||
|
readonly 'import.clearAll': "取消全选";
|
||||||
|
readonly 'import.selectedCount': "已选 {n} / {total}";
|
||||||
|
readonly 'import.submit': "导入所选连接";
|
||||||
|
readonly 'import.importing': "导入中…({done}/{total})";
|
||||||
|
readonly 'import.progress': "正在导入「{name}」…";
|
||||||
|
readonly 'import.resultAllOk': "已导入 {ok} 个连接";
|
||||||
|
readonly 'import.resultPartial': "成功 {ok} 个,失败 {fail} 个";
|
||||||
|
readonly 'import.resultAllFail': "全部失败({fail} 个)";
|
||||||
|
readonly 'import.failedIntro': "以下主机未导入:";
|
||||||
|
readonly 'import.noResult': "保存接口未返回结果";
|
||||||
|
readonly 'import.retryFailed': "仅重试失败项({n})";
|
||||||
|
readonly 'import.retrying': "重试中…({done}/{total})";
|
||||||
|
readonly 'import.noneSelected': "请至少选择一个主机";
|
||||||
|
readonly 'import.proxyJump': "跳板机 {target}";
|
||||||
|
readonly 'import.close': "关闭";
|
||||||
|
readonly 'import.authNote': "导入的连接固定使用密钥认证、远程根目录 ~;可在手动表单中补充密码或其它字段。";
|
||||||
|
readonly 'workspace.sectionTitle': "远程工作区";
|
||||||
|
readonly 'workspace.sectionSummary': "独立写回与同步配置";
|
||||||
|
readonly 'workspace.empty': "还没有远程工作区。可在「添加工作区」中选择「远程目录」创建。";
|
||||||
|
readonly 'workspace.expand': "展开配置";
|
||||||
|
readonly 'workspace.collapse': "收起配置";
|
||||||
|
readonly 'workspace.connection': "所属连接";
|
||||||
|
readonly 'workspace.remotePath': "远程路径";
|
||||||
|
readonly 'workspace.writeBack': "启用写回(把 agent 的 write/edit 同步到远端)";
|
||||||
|
readonly 'workspace.writeBackExclude': "写回排除(逗号或换行分隔)";
|
||||||
|
readonly 'workspace.writeBackExcludeHint': "这些路径的本地改动不会推回远端,例如 _patch/, *.log。";
|
||||||
|
readonly 'workspace.syncPaths': "同步范围(逗号或换行分隔,留空 = 整树)";
|
||||||
|
readonly 'workspace.syncPathsHint': "只同步这些子路径,例如 .dsh;留空 = 整树。";
|
||||||
|
readonly 'workspace.syncExclude': "同步排除(逗号或换行分隔)";
|
||||||
|
readonly 'workspace.syncExcludeHint': "拉取和推送时跳过这些路径,例如 data/, *.log;与写回排除用途不同。";
|
||||||
|
readonly 'workspace.syncMaxBytes': "同步体积上限(GiB,留空 = 默认 2 GiB)";
|
||||||
|
readonly 'workspace.unsaved': "未保存";
|
||||||
|
readonly 'workspace.save': "保存该工作区设置";
|
||||||
|
readonly 'workspace.saving': "保存中…";
|
||||||
|
readonly 'workspace.saved': "该工作区设置已保存";
|
||||||
|
readonly 'workspace.saveFail': "保存失败";
|
||||||
|
readonly 'workspace.syncBlocked': "有未保存的设置,请先保存再拉取或推送。";
|
||||||
|
readonly 'workspace.syncDown': "拉取";
|
||||||
|
readonly 'workspace.syncUp': "推送";
|
||||||
|
readonly 'workspace.syncing': "拉取中…";
|
||||||
|
readonly 'workspace.pushing': "推送中…";
|
||||||
|
readonly 'workspace.syncDone': "拉取完成";
|
||||||
|
readonly 'workspace.syncFail': "拉取失败";
|
||||||
|
readonly 'workspace.pushDone': "推送完成";
|
||||||
|
readonly 'workspace.pushFail': "推送失败";
|
||||||
|
readonly 'workspace.deleteTitle': "移除远程工作区「{title}」?";
|
||||||
|
readonly 'workspace.deleteBody': "只移除本地记录与镜像映射,不会删除服务器上的目录或文件。";
|
||||||
|
readonly 'workspace.deleted': "已移除远程工作区「{title}」";
|
||||||
|
readonly 'workspace.deleteFail': "删除失败";
|
||||||
|
readonly 'workspace.unknownProfile': "未知连接";
|
||||||
|
readonly 'advanced.sectionTitle': "高级设置";
|
||||||
|
readonly 'advanced.sectionSummary': "终端与写回、新工作区同步默认值";
|
||||||
|
readonly 'advanced.terminalGroup': "终端与写回";
|
||||||
|
readonly 'advanced.nodePath': "Node 绝对路径";
|
||||||
|
readonly 'advanced.nodePathHint': "终端起不来时填写;留空自动解析。";
|
||||||
|
readonly 'advanced.nodePathPlaceholder': "C:\\Program Files\\nodejs\\node.exe";
|
||||||
|
readonly 'advanced.writeBackFailure': "写回推送失败时";
|
||||||
|
readonly 'advanced.wbError': "让模型看见,工具报错";
|
||||||
|
readonly 'advanced.wbLog': "只写日志";
|
||||||
|
readonly 'advanced.writeBackFreshness': "推送前检查远端是否被改过(发现被改过就不推并报告)";
|
||||||
|
readonly 'advanced.syncDefaultsGroup': "新工作区同步默认值";
|
||||||
|
readonly 'advanced.syncDefaultsHint': "仅影响之后新建的远程工作区,不会覆盖已有工作区的独立设置。";
|
||||||
|
readonly 'advanced.defaultSyncPaths': "默认同步范围(逗号或换行分隔,留空 = 整树)";
|
||||||
|
readonly 'advanced.defaultSyncExclude': "默认同步排除(逗号或换行分隔)";
|
||||||
|
readonly 'advanced.defaultSyncMaxBytes': "默认同步体积上限(GiB,留空 = 内置 2 GiB)";
|
||||||
|
readonly 'advanced.save': "保存设置";
|
||||||
|
readonly 'advanced.saving': "保存中…";
|
||||||
|
readonly 'advanced.saved': "设置已保存";
|
||||||
|
readonly 'advanced.saveFail': "保存失败";
|
||||||
|
readonly 'common.cancel': "取消";
|
||||||
|
readonly 'common.close': "关闭";
|
||||||
|
readonly 'common.confirmDelete': "确认删除";
|
||||||
|
readonly 'common.retry': "重试";
|
||||||
|
readonly 'common.loading': "加载中…";
|
||||||
|
readonly 'common.save': "保存";
|
||||||
|
readonly 'common.error': "错误:";
|
||||||
|
readonly 'common.warning': "警告:";
|
||||||
|
readonly 'common.unknownError': "未知错误";
|
||||||
|
readonly 'common.expand': "展开";
|
||||||
|
readonly 'common.collapse': "收起";
|
||||||
|
};
|
||||||
|
/** Chinese key set; every call site is checked against it. */
|
||||||
|
export type SettingsKey = keyof typeof zh;
|
||||||
|
/** English dictionary — complete mirror of the Chinese key set. */
|
||||||
|
export declare const en: Record<SettingsKey, string>;
|
||||||
|
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||||
|
interface LocaleNamespaceMap {
|
||||||
|
'dsh-remote-ssh-settings': SettingsKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Register both dictionaries for this namespace on the shell locale service.
|
||||||
|
* Call inside `ctx.effect(...)` so the registration is disposed with the
|
||||||
|
* plugin fiber. The typed `register` overload enforces zh/en key parity.
|
||||||
|
*/
|
||||||
|
export declare function registerSettingsLocale(locale: LocaleRuntime): () => void;
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
import type { RemoteSshApi, SettingsSectionComponent } from './contract.ts';
|
||||||
|
/** Options handed to the extracted factory by the merged client entry. */
|
||||||
|
export interface CreateSettingsSectionOptions {
|
||||||
|
api: RemoteSshApi;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Build the settings section component around the injected API.
|
||||||
|
* The returned component matches the shell's `settings.section` renderer
|
||||||
|
* signature `(props: { t? }) => ReactNode`.
|
||||||
|
*/
|
||||||
|
export declare function createSettingsSection(options: CreateSettingsSectionOptions): SettingsSectionComponent;
|
||||||
|
|
@ -0,0 +1,198 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — pure model.
|
||||||
|
*
|
||||||
|
* Everything here is plain data transformation (no React, no DOM, no
|
||||||
|
* imports from other plugin sources), so the real behaviour can be covered
|
||||||
|
* by unit tests without mounting the shell:
|
||||||
|
*
|
||||||
|
* - connection form validation and the exact `saveProfile` payload
|
||||||
|
* - `~/.ssh/config` import mapping, per-item outcomes, partial-failure counts
|
||||||
|
* and failed-only retry merges (the old face reported the selection size as
|
||||||
|
* "imported" regardless of each save result)
|
||||||
|
* - per-workspace guard drafts, dirty detection, reload reconciliation and the
|
||||||
|
* exact `updateWorkspaceGuards` payload
|
||||||
|
* - global preferences draft/payload/dirty/reconcile
|
||||||
|
*
|
||||||
|
* Field semantics and unit conversions are copied from the vendored client
|
||||||
|
* (`splitList`, `bytesToGibText`, `gibTextToBytes`, `prefsForUi`) so the face
|
||||||
|
* keeps the existing Host contract: lists accept comma/newline/semicolon,
|
||||||
|
* the size cap is edited in GiB and stored in bytes, empty = Host default.
|
||||||
|
*/
|
||||||
|
import type { RemoteSshPrefs, RemoteSshProfile, RemoteSshWorkspace, SavePrefsPayload, SaveProfilePayload, SshConfigHost, TestConnectionResponse, UpdateWorkspaceGuardsPayload } from './contract.ts';
|
||||||
|
/** Controlled draft of the "add connection" form (all fields are strings). */
|
||||||
|
export interface ConnectionForm {
|
||||||
|
name: string;
|
||||||
|
host: string;
|
||||||
|
port: string;
|
||||||
|
user: string;
|
||||||
|
authMethod: 'key' | 'password';
|
||||||
|
keyPath: string;
|
||||||
|
password: string;
|
||||||
|
remoteRoot: string;
|
||||||
|
proxyJump: string;
|
||||||
|
}
|
||||||
|
/** Values the vendored client used when opening/clearing the form. */
|
||||||
|
export declare const EMPTY_CONNECTION_FORM: ConnectionForm;
|
||||||
|
/** Fresh copy (never share the frozen constant with component state). */
|
||||||
|
export declare function emptyConnectionForm(): ConnectionForm;
|
||||||
|
/** Field-level issue; the component maps `messageKey` through `t`. */
|
||||||
|
export interface FormIssue {
|
||||||
|
field: 'host' | 'user' | 'port';
|
||||||
|
messageKey: 'add.errHost' | 'add.errUser' | 'add.errPort';
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Validate exactly what the Host requires (`host` + `user`) plus a real port
|
||||||
|
* range. The Host would otherwise `parseInt(port) || 22`, silently turning a
|
||||||
|
* typo into 22; the UI refuses it instead. Aliases, empty key paths and the
|
||||||
|
* reliance on ssh-agent / ~/.ssh/config stay legal (the backend accepts them).
|
||||||
|
*/
|
||||||
|
export declare function validateConnectionForm(form: ConnectionForm): FormIssue[];
|
||||||
|
/** Whether the form can be submitted (callers still re-check on submit). */
|
||||||
|
export declare function isConnectionFormValid(form: ConnectionForm): boolean;
|
||||||
|
/**
|
||||||
|
* Exact `saveProfile` body. Fields are passed through as typed by the user
|
||||||
|
* (the Host trims/derives where it always did: name falls back to host, port
|
||||||
|
* parsing is already done here, password only persists for password auth).
|
||||||
|
*/
|
||||||
|
export declare function toSaveProfilePayload(form: ConnectionForm): SaveProfilePayload;
|
||||||
|
/** `user@host:port` summary used by connection cards. */
|
||||||
|
export declare function profileSummary(profile: RemoteSshProfile): string;
|
||||||
|
/** Display name with the upstream `name || host` fallback. */
|
||||||
|
export declare function profileName(profile: RemoteSshProfile): string;
|
||||||
|
/** "comma or newline (or semicolon) separated" text → trimmed non-empty list. */
|
||||||
|
export declare function splitList(value: string | null | undefined): string[];
|
||||||
|
/** Byte count → GiB text (empty = Host built-in default cap). */
|
||||||
|
export declare function bytesToGibText(bytes: number | null | undefined): string;
|
||||||
|
/** GiB text → bytes; empty/invalid → 0 (= Host built-in default cap). */
|
||||||
|
export declare function gibTextToBytes(text: string | number | null | undefined): number;
|
||||||
|
/** Trimmed error text from an API envelope, else the caller's fallback. */
|
||||||
|
export declare function apiErrorMessage(value: {
|
||||||
|
error?: string;
|
||||||
|
} | null | undefined, fallback: string): string;
|
||||||
|
export type TestStatus = 'success' | 'warning' | 'error';
|
||||||
|
/** Rendered shape of one connection test result. */
|
||||||
|
export interface ConnectionTestView {
|
||||||
|
status: TestStatus;
|
||||||
|
/** Localized status line (caller resolves the keys). */
|
||||||
|
titleKey: 'connection.testOk' | 'connection.testWarn' | 'connection.testFail';
|
||||||
|
/** Raw warning returned by the Host (successful connect with degraded key path). */
|
||||||
|
warning: string;
|
||||||
|
/** stdout for success, stderr/error text for failure. */
|
||||||
|
detail: string;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Map `testConnection` output to the card feedback. A successful probe that
|
||||||
|
* carries `warning` stays a warning (never collapsed into a plain success).
|
||||||
|
*/
|
||||||
|
export declare function connectionTestView(result: TestConnectionResponse | null | undefined): ConnectionTestView;
|
||||||
|
/** Stable row key; same spelling the vendored importer used for selection. */
|
||||||
|
export declare function importHostKey(host: SshConfigHost): string;
|
||||||
|
/** Default selection: every discovered host (upstream opened all checked). */
|
||||||
|
export declare function selectAllHosts(hosts: SshConfigHost[]): Record<string, boolean>;
|
||||||
|
/** Toggle one selection key without mutating the previous map. */
|
||||||
|
export declare function toggleHostSelection(selected: Record<string, boolean>, key: string): Record<string, boolean>;
|
||||||
|
/** Selected hosts, in discovery order (never trusts map iteration order). */
|
||||||
|
export declare function selectedHosts(hosts: SshConfigHost[], selected: Record<string, boolean>): SshConfigHost[];
|
||||||
|
/** Count of checked rows. */
|
||||||
|
export declare function countSelected(selected: Record<string, boolean>): number;
|
||||||
|
/**
|
||||||
|
* Exact import mapping kept from the vendored face: name, host, port, user,
|
||||||
|
* keyPath (identityFile), proxyJump; key auth, empty password, remoteRoot ~.
|
||||||
|
*/
|
||||||
|
export declare function importProfilePayload(host: SshConfigHost): SaveProfilePayload;
|
||||||
|
/** One save attempt inside an import run. */
|
||||||
|
export interface ImportItemOutcome {
|
||||||
|
key: string;
|
||||||
|
name: string;
|
||||||
|
hostName: string;
|
||||||
|
ok: boolean;
|
||||||
|
/** Host/transport error text (absent when ok). */
|
||||||
|
error?: string;
|
||||||
|
/** Synthesized reason when the call resolved without an envelope. */
|
||||||
|
errorCode?: 'no-result';
|
||||||
|
}
|
||||||
|
/** Aggregated per-run statistics (never "selected size" as success count). */
|
||||||
|
export interface ImportSummary {
|
||||||
|
outcomes: ImportItemOutcome[];
|
||||||
|
okCount: number;
|
||||||
|
failCount: number;
|
||||||
|
failedHosts: SshConfigHost[];
|
||||||
|
}
|
||||||
|
/** Injected `saveProfile` port (the vendored api wrapper satisfies this). */
|
||||||
|
export type SaveProfileCall = (payload: SaveProfilePayload) => Promise<{
|
||||||
|
ok?: boolean;
|
||||||
|
error?: string;
|
||||||
|
} | null | undefined>;
|
||||||
|
/**
|
||||||
|
* Import hosts one by one. Each item is checked individually:
|
||||||
|
* - `ok: true` counts as success;
|
||||||
|
* - `ok: false` (or any thrown request error) counts as failure with its reason;
|
||||||
|
* - a missing envelope counts as failure (`errorCode: 'no-result'`) so a
|
||||||
|
* silent transport layer can never be reported as imported.
|
||||||
|
*
|
||||||
|
* Sequential on purpose: profile saves rewrite one settings table, and the
|
||||||
|
* calls are cheap compared to SSH; this also keeps progress deterministic.
|
||||||
|
*/
|
||||||
|
export declare function runImport(hosts: SshConfigHost[], saveProfile: SaveProfileCall, options?: {
|
||||||
|
onProgress?: (done: number, total: number, host: SshConfigHost) => void;
|
||||||
|
}): Promise<ImportSummary>;
|
||||||
|
/**
|
||||||
|
* Fold a failed-only retry run into the previous summary: previously
|
||||||
|
* successful items stay successes (they are never resubmitted), failed items
|
||||||
|
* take the retry outcome.
|
||||||
|
*/
|
||||||
|
export declare function mergeImportRetry(previous: ImportSummary, retry: ImportSummary): ImportSummary;
|
||||||
|
/** Controlled draft of one workspace's write-back / sync settings. */
|
||||||
|
export interface GuardDraft {
|
||||||
|
writeBack: boolean;
|
||||||
|
writeBackExclude: string;
|
||||||
|
syncPaths: string;
|
||||||
|
syncExclude: string;
|
||||||
|
syncMaxBytes: string;
|
||||||
|
}
|
||||||
|
/** Draft initialized from a persisted record (defaults match the Host). */
|
||||||
|
export declare function guardDraftFromWorkspace(workspace: RemoteSshWorkspace): GuardDraft;
|
||||||
|
/** Drafts + baselines keyed by workspace id. */
|
||||||
|
export declare function guardsFromWorkspaces(workspaces: RemoteSshWorkspace[]): Record<string, GuardDraft>;
|
||||||
|
/** Canonical signature: list formatting / "2" vs "2.0" must not look dirty. */
|
||||||
|
export declare function guardDraftSignature(draft: GuardDraft): string;
|
||||||
|
/** Whether the draft differs semantically from the persisted baseline. */
|
||||||
|
export declare function isGuardDraftDirty(draft: GuardDraft, baseline: GuardDraft): boolean;
|
||||||
|
/** Exact `updateWorkspaceGuards` body — always carries the target workspace id. */
|
||||||
|
export declare function toUpdateWorkspaceGuardsPayload(workspaceId: string, draft: GuardDraft): UpdateWorkspaceGuardsPayload;
|
||||||
|
/**
|
||||||
|
* Reconcile drafts with a freshly persisted list. Dirty drafts survive a
|
||||||
|
* reload (their baseline moves to the new server truth); clean drafts adopt
|
||||||
|
* it. Records removed on the Host disappear. A draft with no baseline is
|
||||||
|
* treated as dirty so an unrelated refresh can never wipe typed text.
|
||||||
|
*/
|
||||||
|
export declare function reconcileGuards(previousDrafts: Record<string, GuardDraft>, previousBaselines: Record<string, GuardDraft>, workspaces: RemoteSshWorkspace[]): {
|
||||||
|
drafts: Record<string, GuardDraft>;
|
||||||
|
baselines: Record<string, GuardDraft>;
|
||||||
|
};
|
||||||
|
/** Controlled draft of the advanced section. */
|
||||||
|
export interface PrefsDraft {
|
||||||
|
nodePath: string;
|
||||||
|
writeBackFailure: 'error' | 'log';
|
||||||
|
writeBackFreshness: boolean;
|
||||||
|
defaultSyncPaths: string;
|
||||||
|
defaultSyncExclude: string;
|
||||||
|
defaultSyncMaxBytes: string;
|
||||||
|
}
|
||||||
|
/** Host preferences → draft (same projection the vendored face used). */
|
||||||
|
export declare function prefsDraftFromApi(prefs: RemoteSshPrefs | null | undefined): PrefsDraft;
|
||||||
|
/** Canonical preference signature for dirty detection. */
|
||||||
|
export declare function prefsDraftSignature(draft: PrefsDraft): string;
|
||||||
|
/** Whether the advanced draft differs from the saved preferences. */
|
||||||
|
export declare function isPrefsDraftDirty(draft: PrefsDraft, baseline: PrefsDraft): boolean;
|
||||||
|
/** Exact `savePrefs` body (array conversions + GiB → bytes). */
|
||||||
|
export declare function toSavePrefsPayload(draft: PrefsDraft): SavePrefsPayload;
|
||||||
|
/**
|
||||||
|
* Reconcile the advanced draft with a fresh `getPrefs` read: unsaved edits
|
||||||
|
* survive, clean drafts adopt server truth. Baselines always follow the
|
||||||
|
* server so the dirty badge compares against what is actually stored.
|
||||||
|
*/
|
||||||
|
export declare function reconcilePrefs(previousDraft: PrefsDraft | null, previousBaseline: PrefsDraft | null, serverDraft: PrefsDraft): {
|
||||||
|
draft: PrefsDraft;
|
||||||
|
baseline: PrefsDraft;
|
||||||
|
};
|
||||||
|
|
@ -0,0 +1 @@
|
||||||
|
export declare const SETTINGS_CSS: string;
|
||||||
|
|
@ -0,0 +1,88 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — presentational atoms.
|
||||||
|
*
|
||||||
|
* Every atom here is stateless: drafts, busy flags, confirmations and results
|
||||||
|
* live in the root component (`index.tsx`), which keeps folding reversible and
|
||||||
|
* guarantees that a collapse/refresh can never drop typed input.
|
||||||
|
*
|
||||||
|
* The atoms only use native elements plus React; the sole UI primitive this
|
||||||
|
* face consumes is `Modal` (in `index.tsx`). Styling comes from
|
||||||
|
* `.rsui-*` classes in `settings.css` (DSH theme tokens, light/dark aware).
|
||||||
|
*/
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
/** Disclosure chevron; the rotation is a restrained CSS transition. */
|
||||||
|
export declare function ChevronIcon({ open }: {
|
||||||
|
open: boolean;
|
||||||
|
}): import("react").JSX.Element;
|
||||||
|
/**
|
||||||
|
* Feedback glyph. Icons never carry the only error signal: every feedback
|
||||||
|
* block also renders a localized textual prefix (`common.error` /
|
||||||
|
* `common.warning`) so colour-blind users get the same information.
|
||||||
|
*/
|
||||||
|
export declare function StatusIcon({ status }: {
|
||||||
|
status: 'success' | 'warning' | 'error' | 'info';
|
||||||
|
}): import("react").JSX.Element;
|
||||||
|
export interface FieldProps {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
onBlur?: (() => void) | undefined;
|
||||||
|
placeholder?: string | undefined;
|
||||||
|
type?: 'text' | 'password' | undefined;
|
||||||
|
autoComplete?: string | undefined;
|
||||||
|
inputMode?: 'text' | 'numeric' | undefined;
|
||||||
|
/** `data-rsui-field` hook consumed by preview/acceptance scripts. */
|
||||||
|
dataField?: string | undefined;
|
||||||
|
hint?: string | undefined;
|
||||||
|
error?: string | undefined;
|
||||||
|
mono?: boolean | undefined;
|
||||||
|
}
|
||||||
|
export declare function Field({ id, label, value, onChange, onBlur, placeholder, type, autoComplete, inputMode, dataField, hint, error, mono }: FieldProps): import("react").JSX.Element;
|
||||||
|
export interface TextAreaFieldProps {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
placeholder?: string | undefined;
|
||||||
|
dataField?: string | undefined;
|
||||||
|
hint?: string | undefined;
|
||||||
|
rows?: number | undefined;
|
||||||
|
}
|
||||||
|
export declare function TextAreaField({ id, label, value, onChange, placeholder, dataField, hint, rows }: TextAreaFieldProps): import("react").JSX.Element;
|
||||||
|
export interface CheckFieldProps {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
checked: boolean;
|
||||||
|
onChange: (checked: boolean) => void;
|
||||||
|
dataField?: string | undefined;
|
||||||
|
}
|
||||||
|
export declare function CheckField({ id, label, checked, onChange, dataField }: CheckFieldProps): import("react").JSX.Element;
|
||||||
|
export interface SelectFieldProps {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
options: ReadonlyArray<{
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
}>;
|
||||||
|
onChange: (value: string) => void;
|
||||||
|
dataField?: string | undefined;
|
||||||
|
hint?: string | undefined;
|
||||||
|
}
|
||||||
|
export declare function SelectField({ id, label, value, options, onChange, dataField, hint }: SelectFieldProps): import("react").JSX.Element;
|
||||||
|
export type NoticeTone = 'success' | 'warning' | 'error' | 'info';
|
||||||
|
export interface NoticeProps {
|
||||||
|
tone?: NoticeTone | undefined;
|
||||||
|
title: string;
|
||||||
|
/** Localized textual prefix, e.g. `common.error` / `common.warning`. */
|
||||||
|
prefix?: string | undefined;
|
||||||
|
detail?: string | undefined;
|
||||||
|
action?: ReactNode;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Generic status/alert block. `role` follows the tone (`alert` for errors,
|
||||||
|
* `status` otherwise) so screen readers announce failures without relying on
|
||||||
|
* the red colour alone.
|
||||||
|
*/
|
||||||
|
export declare function Notice({ tone, title, prefix, detail, action }: NoticeProps): import("react").JSX.Element;
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "workspace-groups-remote",
|
"name": "workspace-groups-remote",
|
||||||
"version": "1.2.2",
|
"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.",
|
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"dsh",
|
"dsh",
|
||||||
|
|
|
||||||
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 270 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 148 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 241 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 138 KiB |
|
|
@ -0,0 +1,97 @@
|
||||||
|
{
|
||||||
|
"isolatedPreview": true,
|
||||||
|
"note": "真实组件 + 假 /remote-ssh/api 数据,在 headless Chrome 中渲染截图;不是 AI 效果图,未修改 DSH GUI / daily profile / node_modules。",
|
||||||
|
"component": "src/client/rssh-settings/index.tsx",
|
||||||
|
"screenshots": [
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/01-default.png",
|
||||||
|
"scene": "default",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x1605",
|
||||||
|
"durationMs": 1003,
|
||||||
|
"description": "默认(高级设置收起)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/02-expanded.png",
|
||||||
|
"scene": "expanded",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x3529",
|
||||||
|
"durationMs": 2163,
|
||||||
|
"description": "全部展开(字段可核对)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/03-import-dialog.png",
|
||||||
|
"scene": "import-ready",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "viewport",
|
||||||
|
"size": "1280x900",
|
||||||
|
"durationMs": 1297,
|
||||||
|
"description": "SSH 导入弹窗(列表 / 已选数量)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/04-import-partial.png",
|
||||||
|
"scene": "import-partial",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "viewport",
|
||||||
|
"size": "1280x900",
|
||||||
|
"durationMs": 2224,
|
||||||
|
"description": "导入部分失败结果 + 仅重试失败项"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/05-workspaces.png",
|
||||||
|
"scene": "workspaces",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x2861",
|
||||||
|
"durationMs": 1541,
|
||||||
|
"description": "远程工作区独立配置展开 + 未保存徽标"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/06-password-auth.png",
|
||||||
|
"scene": "password",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x1605",
|
||||||
|
"durationMs": 1564,
|
||||||
|
"description": "密码认证表单"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/07-dark.png",
|
||||||
|
"scene": "expanded",
|
||||||
|
"theme": "dark",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x3529",
|
||||||
|
"durationMs": 2127,
|
||||||
|
"description": "深色模式(全部展开)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/08-narrow.png",
|
||||||
|
"scene": "default",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 480,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "480x1890",
|
||||||
|
"durationMs": 1313,
|
||||||
|
"description": "窄屏约 480px 单列"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"file": "screenshots/remote-ssh-settings/09-test-failure.png",
|
||||||
|
"scene": "test-failure",
|
||||||
|
"theme": "light",
|
||||||
|
"viewportWidth": 1280,
|
||||||
|
"capture": "full",
|
||||||
|
"size": "1280x1769",
|
||||||
|
"durationMs": 1395,
|
||||||
|
"description": "连接测试失败诊断"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
@ -195,13 +195,83 @@ const occurrences = body.split(ROOT_LABEL_OLD).length - 1
|
||||||
if (occurrences !== 1) throw new Error('remote-ssh client: root-label block anchor found ' + occurrences + ' times')
|
if (occurrences !== 1) throw new Error('remote-ssh client: root-label block anchor found ' + occurrences + ' times')
|
||||||
body = body.replace(ROOT_LABEL_OLD, ROOT_LABEL_NEW)
|
body = body.replace(ROOT_LABEL_OLD, ROOT_LABEL_NEW)
|
||||||
|
|
||||||
|
// [workspace-groups-remote patch] Settings face replacement.
|
||||||
|
// Upstream's settings face (SettingsSection, ~280 lines of compiled JS) is
|
||||||
|
// replaced at build time by the maintainable source component in
|
||||||
|
// src/client/rssh-settings. The merged client entry passes a `compose` object
|
||||||
|
// into this factory (createSettingsSection + dictionary namespace); the
|
||||||
|
// vendored component stays as a fallback for a factory invoked without one
|
||||||
|
// (older entry, verification harness). Anchor-asserted like every other
|
||||||
|
// patch: an upstream change fails the build loudly instead of silently
|
||||||
|
// shipping the old face.
|
||||||
|
const SETTINGS_REGISTRATION_OLD = ` slots.inject("settings.section", function () {
|
||||||
|
return slots.register({
|
||||||
|
name: "settings.section",
|
||||||
|
id: "remote-ssh",
|
||||||
|
order: 200,
|
||||||
|
label: function () { return i18n.t("settings.nav"); },
|
||||||
|
locale: NS
|
||||||
|
}, SettingsSection);
|
||||||
|
});`
|
||||||
|
|
||||||
|
const SETTINGS_REGISTRATION_NEW = ` // [workspace-groups-remote patch] Settings face replacement:
|
||||||
|
// the maintainable source component (src/client/rssh-settings) owns
|
||||||
|
// the page; allocate it once per registration and keep upstream's
|
||||||
|
// SettingsSection as the fallback when compose is absent. The
|
||||||
|
// dictionary namespace comes from compose so the slot renderer
|
||||||
|
// injects the component's typed \`t\` seat from this bundle's own
|
||||||
|
// locale registration.
|
||||||
|
slots.inject("settings.section", function () {
|
||||||
|
var settingsComponent = SettingsSection;
|
||||||
|
var settingsLocale = NS;
|
||||||
|
try {
|
||||||
|
if (compose && typeof compose.createSettingsSection === "function") {
|
||||||
|
settingsComponent = compose.createSettingsSection({ api: api });
|
||||||
|
if (compose.settingsNamespace) settingsLocale = String(compose.settingsNamespace);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
settingsComponent = SettingsSection;
|
||||||
|
settingsLocale = NS;
|
||||||
|
}
|
||||||
|
return slots.register({
|
||||||
|
name: "settings.section",
|
||||||
|
id: "remote-ssh",
|
||||||
|
order: 200,
|
||||||
|
label: function () { return i18n.t("settings.nav"); },
|
||||||
|
locale: settingsLocale
|
||||||
|
}, settingsComponent);
|
||||||
|
});`
|
||||||
|
|
||||||
|
const settingsOccurrences = body.split(SETTINGS_REGISTRATION_OLD).length - 1
|
||||||
|
if (settingsOccurrences !== 1) {
|
||||||
|
throw new Error('remote-ssh client: settings registration anchor found ' + settingsOccurrences + ' times — upstream changed, re-check the transform')
|
||||||
|
}
|
||||||
|
body = body.replace(SETTINGS_REGISTRATION_OLD, SETTINGS_REGISTRATION_NEW)
|
||||||
|
|
||||||
const out = header
|
const out = header
|
||||||
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
|
+ '// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---\n'
|
||||||
+ '// Upstream registers this factory under its own package id; the merged\n'
|
+ '// Upstream registers this factory under its own package id; the merged\n'
|
||||||
+ '// package registers ONE client row, so the factory is exported instead\n'
|
+ '// package registers ONE client row, so the factory is exported instead\n'
|
||||||
+ '// and applied by src/client/index.ts. Body below is upstream-verbatim.\n'
|
+ '// and applied by src/client/index.ts. Body below is upstream-verbatim\n'
|
||||||
+ 'export default (require) => {'
|
+ '// apart from anchor-asserted patches (root label, settings face).\n'
|
||||||
|
+ '// The second argument is the merged entry\'s compose seam:\n'
|
||||||
|
+ '// compose.settingsNamespace + compose.createSettingsSection(deps)\n'
|
||||||
|
+ 'export default (require, compose) => {'
|
||||||
+ body
|
+ body
|
||||||
+ '\n}\n'
|
+ '\n}\n'
|
||||||
|
|
||||||
|
// Post-conditions: the vulnerable/old forms must be gone and the compose
|
||||||
|
// seam present, so a successful build can never silently keep the old face.
|
||||||
|
if (out.includes('}, SettingsSection);')) {
|
||||||
|
throw new Error('remote-ssh client: the upstream settings registration survived the transform')
|
||||||
|
}
|
||||||
|
for (const required of [
|
||||||
|
'export default (require, compose) => {',
|
||||||
|
'compose.createSettingsSection({ api: api })',
|
||||||
|
'var settingsComponent = SettingsSection;',
|
||||||
|
'locale: settingsLocale',
|
||||||
|
]) {
|
||||||
|
if (!out.includes(required)) throw new Error('remote-ssh client: expected transformed form missing: ' + required)
|
||||||
|
}
|
||||||
writeFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), out)
|
writeFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), out)
|
||||||
console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs')
|
console.log('remote-ssh client factory -> src/client/remote-ssh-factory.generated.mjs')
|
||||||
|
|
|
||||||
|
|
@ -381,5 +381,22 @@ console.log('patch hygiene')
|
||||||
check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)')
|
check(!vendorSrc.includes('resolveRemoteCanonical'), 'vendor tree stays pristine (no patch markers)')
|
||||||
check(src.includes('resolveRemoteCanonical'), 'built artifact carries the patch')
|
check(src.includes('resolveRemoteCanonical'), 'built artifact carries the patch')
|
||||||
|
|
||||||
|
// --- client transform: settings face replacement ---------------------------
|
||||||
|
// scripts/build-remote-ssh-client.mjs replaces the vendored settings face
|
||||||
|
// with the maintainable source component and exports the factory with the
|
||||||
|
// merged entry's compose seam. Assert the generated source rather than only
|
||||||
|
// the built bundle, so an upstream anchor drift is caught here too.
|
||||||
|
console.log('client factory transform (settings face)')
|
||||||
|
{
|
||||||
|
const generated = readFileSync(join(root, 'src/client/remote-ssh-factory.generated.mjs'), 'utf8')
|
||||||
|
check(generated.includes('export default (require, compose) => {'), 'generated factory accepts the compose seam')
|
||||||
|
check(generated.includes('compose.createSettingsSection({ api: api })'), 'settings registration builds the source component')
|
||||||
|
check(generated.includes('settingsComponent = SettingsSection;'), 'vendored settings face stays as the fallback')
|
||||||
|
check(!generated.includes('}, SettingsSection);'), 'upstream registration is gone from the generated factory')
|
||||||
|
check(generated.includes('locale: settingsLocale'), 'settings entry declares the compose-provided namespace')
|
||||||
|
const vendoredClient = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/client.js'), 'utf8')
|
||||||
|
check(!vendoredClient.includes('compose.createSettingsSection'), 'vendored client stays pristine')
|
||||||
|
}
|
||||||
|
|
||||||
console.log('\n' + pass + ' passed, ' + fail + ' failed')
|
console.log('\n' + pass + ' passed, ' + fail + ' failed')
|
||||||
process.exit(fail === 0 ? 0 : 1)
|
process.exit(fail === 0 ? 0 : 1)
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,8 @@ check('client has exactly one module-loader registration', client.split('__Modul
|
||||||
check('client row id is the package name', client.includes(`id: "${pkg.name}"`) || client.includes(`id:"${pkg.name}"`) || client.includes(`id: '${pkg.name}'`))
|
check('client row id is the package name', client.includes(`id: "${pkg.name}"`) || client.includes(`id:"${pkg.name}"`) || client.includes(`id: '${pkg.name}'`))
|
||||||
check('client contains the groups half', client.includes('workspaceGroups'))
|
check('client contains the groups half', client.includes('workspaceGroups'))
|
||||||
check('client contains the remote-ssh half', client.includes('remssh'))
|
check('client contains the remote-ssh half', client.includes('remssh'))
|
||||||
|
check('client ships the maintainable remote-ssh settings face', client.includes('dsh-remote-ssh-settings') && client.includes('rsui-root'))
|
||||||
|
check('client carries the settings-face compose seam', client.includes('createSettingsSection') && client.includes('settingsNamespace'))
|
||||||
|
|
||||||
const remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
|
const remoteHost = readFileSync(join(root, 'lib/remote-ssh/index.js'), 'utf8')
|
||||||
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')
|
const vendorHost = readFileSync(join(root, 'vendor/dsh-remote-ssh/lib/index.js'), 'utf8')
|
||||||
|
|
|
||||||
|
|
@ -10,26 +10,63 @@
|
||||||
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
||||||
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
||||||
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
||||||
* strips that registration wrapper and re-exports the bare factory, which
|
* strips that registration wrapper, re-exports the bare factory and applies
|
||||||
|
* two anchor-asserted transforms (root label, settings face). The factory
|
||||||
* is invoked here with this bundle's own require (its only requires are
|
* is invoked here with this bundle's own require (its only requires are
|
||||||
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
||||||
* modules) and applied alongside the groups client.
|
* modules) and applied alongside the groups client.
|
||||||
*
|
*
|
||||||
|
* The settings page itself is NOT the vendored compiled component: the factory
|
||||||
|
* receives `remoteSshCompose`, whose `createSettingsSection` builds the
|
||||||
|
* maintainable React section from src/client/rssh-settings. Its dictionary
|
||||||
|
* namespace and CSS live in this entry because the merged package owns them
|
||||||
|
* (the vendored half only knows its upstream keys/styles).
|
||||||
|
*
|
||||||
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
||||||
* are a subset of the groups list).
|
* are a subset of the groups list).
|
||||||
*/
|
*/
|
||||||
import type { Context } from '@deepseek-ai/cordis'
|
import type { Context } from '@deepseek-ai/cordis'
|
||||||
import * as groupsClient from './groups-client.ts'
|
import * as groupsClient from './groups-client.ts'
|
||||||
import remoteSshFactory from './remote-ssh-factory.generated.mjs'
|
import remoteSshFactory from './remote-ssh-factory.generated.mjs'
|
||||||
|
import { SETTINGS_NS, registerSettingsLocale } from './rssh-settings/i18n.ts'
|
||||||
|
import { createSettingsSection } from './rssh-settings/index.tsx'
|
||||||
|
import { SETTINGS_CSS } from './rssh-settings/styles.ts'
|
||||||
|
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
|
||||||
|
|
||||||
/** Services required before mounting (union of both client halves). */
|
/** Services required before mounting (union of both client halves). */
|
||||||
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
|
export const inject = ['slots', 'sessions', 'workspaces', 'uiWorkspace', 'locale']
|
||||||
|
|
||||||
|
/** Seam handed to the extracted vendored factory (settings face replacement). */
|
||||||
|
const remoteSshCompose: RemoteSshClientCompose = {
|
||||||
|
settingsNamespace: SETTINGS_NS,
|
||||||
|
createSettingsSection: (deps) => createSettingsSection({ api: deps.api }),
|
||||||
|
}
|
||||||
|
|
||||||
/** Instantiate the vendored remote-ssh client plugin exactly once. */
|
/** Instantiate the vendored remote-ssh client plugin exactly once. */
|
||||||
const remoteSshClient = remoteSshFactory(id => require(id))
|
const remoteSshClient = remoteSshFactory(id => require(id), remoteSshCompose)
|
||||||
|
|
||||||
/** Plugin body: apply both client halves on this bundle's fiber. */
|
/** Plugin body: apply both client halves on this bundle's fiber. */
|
||||||
export function apply(ctx: Context): void {
|
export function apply(ctx: Context): void {
|
||||||
|
// The settings section declares `locale: SETTINGS_NS`, so the dictionary
|
||||||
|
// face must be installed before the vendored half registers that slot entry.
|
||||||
|
// (Slot rendering requires an installed locale face; registration also bumps
|
||||||
|
// the revision so an already-mounted settings page picks the texts up.)
|
||||||
|
ctx.effect(
|
||||||
|
() => registerSettingsLocale(ctx.locale),
|
||||||
|
'workspace-groups-remote: remote-ssh settings dictionaries',
|
||||||
|
)
|
||||||
|
|
||||||
|
// Section styles: injected once, scoped under `.rsui-root` (no global
|
||||||
|
// selectors), removed with the fiber. `?inline` is compiled by tsdown.
|
||||||
|
ctx.effect(() => {
|
||||||
|
if (SETTINGS_CSS.trim() === '') return () => {}
|
||||||
|
const style = document.createElement('style')
|
||||||
|
style.setAttribute('data-plugin', 'workspace-groups-remote/remote-ssh-settings')
|
||||||
|
style.textContent = SETTINGS_CSS
|
||||||
|
document.head.appendChild(style)
|
||||||
|
return () => { style.remove() }
|
||||||
|
}, 'workspace-groups-remote: remote-ssh settings styles')
|
||||||
|
|
||||||
groupsClient.apply(ctx)
|
groupsClient.apply(ctx)
|
||||||
remoteSshClient.apply(ctx)
|
remoteSshClient.apply(ctx)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import type { Context } from '@deepseek-ai/cordis'
|
import type { Context } from '@deepseek-ai/cordis'
|
||||||
|
import type { RemoteSshClientCompose } from './rssh-settings/contract.ts'
|
||||||
|
|
||||||
/** The plugin object the vendored dsh-remote-ssh client factory returns. */
|
/** The plugin object the vendored dsh-remote-ssh client factory returns. */
|
||||||
export interface RemoteSshClientPlugin {
|
export interface RemoteSshClientPlugin {
|
||||||
|
|
@ -7,10 +8,15 @@ export interface RemoteSshClientPlugin {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Upstream factory shape: the module-loader factory from
|
* Merged-bundle factory shape: the module-loader factory from
|
||||||
* vendor/dsh-remote-ssh/lib/client.js, re-exported by
|
* vendor/dsh-remote-ssh/lib/client.js, re-exported by
|
||||||
* scripts/build-remote-ssh-client.mjs as remote-ssh-factory.generated.mjs.
|
* scripts/build-remote-ssh-client.mjs as remote-ssh-factory.generated.mjs.
|
||||||
|
*
|
||||||
|
* `compose` is the merged entry's seam (settings namespace + settings section
|
||||||
|
* component factory). Omit it and the factory falls back to the vendored
|
||||||
|
* settings face — the transform keeps that path for harnesses and old entries.
|
||||||
*/
|
*/
|
||||||
export default function remoteSshClientFactory(
|
export default function remoteSshClientFactory(
|
||||||
require: (id: string) => unknown,
|
require: (id: string) => unknown,
|
||||||
|
compose?: RemoteSshClientCompose,
|
||||||
): RemoteSshClientPlugin
|
): RemoteSshClientPlugin
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,11 @@
|
||||||
// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---
|
// --- merged-bundle transform (scripts/build-remote-ssh-client.mjs) ---
|
||||||
// Upstream registers this factory under its own package id; the merged
|
// Upstream registers this factory under its own package id; the merged
|
||||||
// package registers ONE client row, so the factory is exported instead
|
// package registers ONE client row, so the factory is exported instead
|
||||||
// and applied by src/client/index.ts. Body below is upstream-verbatim.
|
// and applied by src/client/index.ts. Body below is upstream-verbatim
|
||||||
export default (require) => {
|
// apart from anchor-asserted patches (root label, settings face).
|
||||||
|
// The second argument is the merged entry's compose seam:
|
||||||
|
// compose.settingsNamespace + compose.createSettingsSection(deps)
|
||||||
|
export default (require, compose) => {
|
||||||
var module = { exports: {} };
|
var module = { exports: {} };
|
||||||
var exports = module.exports;
|
var exports = module.exports;
|
||||||
var React = require("react");
|
var React = require("react");
|
||||||
|
|
@ -1956,14 +1959,32 @@ export default (require) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
if (slots) {
|
if (slots) {
|
||||||
|
// [workspace-groups-remote patch] Settings face replacement:
|
||||||
|
// the maintainable source component (src/client/rssh-settings) owns
|
||||||
|
// the page; allocate it once per registration and keep upstream's
|
||||||
|
// SettingsSection as the fallback when compose is absent. The
|
||||||
|
// dictionary namespace comes from compose so the slot renderer
|
||||||
|
// injects the component's typed `t` seat from this bundle's own
|
||||||
|
// locale registration.
|
||||||
slots.inject("settings.section", function () {
|
slots.inject("settings.section", function () {
|
||||||
|
var settingsComponent = SettingsSection;
|
||||||
|
var settingsLocale = NS;
|
||||||
|
try {
|
||||||
|
if (compose && typeof compose.createSettingsSection === "function") {
|
||||||
|
settingsComponent = compose.createSettingsSection({ api: api });
|
||||||
|
if (compose.settingsNamespace) settingsLocale = String(compose.settingsNamespace);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
settingsComponent = SettingsSection;
|
||||||
|
settingsLocale = NS;
|
||||||
|
}
|
||||||
return slots.register({
|
return slots.register({
|
||||||
name: "settings.section",
|
name: "settings.section",
|
||||||
id: "remote-ssh",
|
id: "remote-ssh",
|
||||||
order: 200,
|
order: 200,
|
||||||
label: function () { return i18n.t("settings.nav"); },
|
label: function () { return i18n.t("settings.nav"); },
|
||||||
locale: NS
|
locale: settingsLocale
|
||||||
}, SettingsSection);
|
}, settingsComponent);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 接管原生「添加工作区」流程:用明显更低的优先级覆盖内置的本地目录选择器,
|
// 接管原生「添加工作区」流程:用明显更低的优先级覆盖内置的本地目录选择器,
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,236 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings face — wire contract.
|
||||||
|
*
|
||||||
|
* The settings section is produced by this module and registered into the
|
||||||
|
* shell's `settings.section` slot by the vendored remote-ssh client (see
|
||||||
|
* scripts/build-remote-ssh-client.mjs). The module talks to the Host through
|
||||||
|
* the SAME `/remote-ssh/api/*` JSON-RPC the vendored client uses: the merged
|
||||||
|
* entry hands it the vendored client's own `api()` wrapper, so endpoint
|
||||||
|
* names, envelopes and semantics stay byte-identical to upstream.
|
||||||
|
*
|
||||||
|
* Types below mirror the Host implementations in
|
||||||
|
* vendor/dsh-remote-ssh/lib/index.js (api object around line 4641) and the
|
||||||
|
* redacted profile projection (`publicProfiles`, line 37). They are a
|
||||||
|
* compile-time description only; nothing here changes runtime behaviour.
|
||||||
|
*/
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Host data shapes (as returned by /remote-ssh/api/*) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Redacted connection profile (`publicProfiles`: password stripped, boolean kept). */
|
||||||
|
export interface RemoteSshProfile {
|
||||||
|
id: string
|
||||||
|
name?: string
|
||||||
|
host: string
|
||||||
|
port?: number
|
||||||
|
user: string
|
||||||
|
authMethod?: 'key' | 'password'
|
||||||
|
keyPath?: string
|
||||||
|
remoteRoot?: string
|
||||||
|
proxyJump?: string
|
||||||
|
passwordConfigured?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One persisted remote workspace record (settingsFace.workspaces entry). */
|
||||||
|
export interface RemoteSshWorkspace {
|
||||||
|
id: string
|
||||||
|
profileId: string
|
||||||
|
title?: string
|
||||||
|
remotePath?: string
|
||||||
|
mirrorPath?: string
|
||||||
|
shellWorkspaceId?: string
|
||||||
|
writeBack?: boolean
|
||||||
|
writeBackExclude?: string[]
|
||||||
|
syncPaths?: string[]
|
||||||
|
syncExclude?: string[]
|
||||||
|
syncMaxBytes?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One `~/.ssh/config` host entry (listSshConfigHosts projection). */
|
||||||
|
export interface SshConfigHost {
|
||||||
|
name: string
|
||||||
|
hostName: string
|
||||||
|
port?: number
|
||||||
|
user?: string
|
||||||
|
identityFile?: string
|
||||||
|
proxyJump?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Global preferences as rendered by the Host (getPrefs/savePrefs.prefs). */
|
||||||
|
export interface RemoteSshPrefs {
|
||||||
|
nodePath?: string
|
||||||
|
writeBackFailure?: string
|
||||||
|
writeBackFreshness?: boolean
|
||||||
|
defaultSyncPaths?: string[]
|
||||||
|
defaultSyncExclude?: string[]
|
||||||
|
defaultSyncMaxBytes?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Request payloads (unchanged Host contract) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* saveProfile body. Every field the vendored settings face sent is kept:
|
||||||
|
* `name`, `host`, `port`, `user`, `authMethod`, `keyPath`, `password`,
|
||||||
|
* `remoteRoot`, `proxyJump`. `port` is already an integer here (the form
|
||||||
|
* rejects invalid values instead of letting the Host fall back to 22).
|
||||||
|
*/
|
||||||
|
export interface SaveProfilePayload {
|
||||||
|
name: string
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
user: string
|
||||||
|
authMethod: 'key' | 'password'
|
||||||
|
keyPath: string
|
||||||
|
password: string
|
||||||
|
remoteRoot: string
|
||||||
|
proxyJump: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** updateWorkspaceGuards body: per-workspace write-back and sync scope. */
|
||||||
|
export interface UpdateWorkspaceGuardsPayload {
|
||||||
|
id: string
|
||||||
|
writeBack: boolean
|
||||||
|
writeBackExclude: string[]
|
||||||
|
syncPaths: string[]
|
||||||
|
syncExclude: string[]
|
||||||
|
/** Bytes; 0 = Host built-in default cap (the old face always sent this). */
|
||||||
|
syncMaxBytes: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/** savePrefs body: global terminal / write-back / new-workspace defaults. */
|
||||||
|
export interface SavePrefsPayload {
|
||||||
|
nodePath: string
|
||||||
|
writeBackFailure: 'error' | 'log'
|
||||||
|
writeBackFreshness: boolean
|
||||||
|
defaultSyncPaths: string[]
|
||||||
|
defaultSyncExclude: string[]
|
||||||
|
defaultSyncMaxBytes: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Response shapes */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export interface ListProfilesResponse {
|
||||||
|
ok?: boolean
|
||||||
|
profiles?: RemoteSshProfile[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SaveProfileResponse {
|
||||||
|
ok?: boolean
|
||||||
|
id?: string
|
||||||
|
profiles?: RemoteSshProfile[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TestConnectionResponse {
|
||||||
|
ok?: boolean
|
||||||
|
warning?: string
|
||||||
|
stdout?: string
|
||||||
|
stderr?: string
|
||||||
|
error?: string
|
||||||
|
exitCode?: number
|
||||||
|
truncated?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteProfileResponse {
|
||||||
|
ok?: boolean
|
||||||
|
profiles?: RemoteSshProfile[]
|
||||||
|
workspaces?: RemoteSshWorkspace[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListSshConfigHostsResponse {
|
||||||
|
ok?: boolean
|
||||||
|
hosts?: SshConfigHost[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ListWorkspacesResponse {
|
||||||
|
ok?: boolean
|
||||||
|
workspaces?: RemoteSshWorkspace[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpdateWorkspaceGuardsResponse {
|
||||||
|
ok?: boolean
|
||||||
|
workspaces?: RemoteSshWorkspace[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SyncResponse {
|
||||||
|
ok?: boolean
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DeleteWorkspaceResponse {
|
||||||
|
ok?: boolean
|
||||||
|
workspaces?: RemoteSshWorkspace[]
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GetPrefsResponse {
|
||||||
|
ok?: boolean
|
||||||
|
prefs?: RemoteSshPrefs
|
||||||
|
deleteSync?: boolean
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SavePrefsResponse {
|
||||||
|
ok?: boolean
|
||||||
|
prefs?: RemoteSshPrefs
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Typed view of the vendored client's `api(method, args)` wrapper. The
|
||||||
|
* wrapper resolves to the Host's `value` object (which always carries its
|
||||||
|
* own `ok` flag) or `{ ok: false, error }` for transport failures.
|
||||||
|
*/
|
||||||
|
export interface RemoteSshApi {
|
||||||
|
(method: 'listProfiles'): Promise<ListProfilesResponse>
|
||||||
|
(method: 'saveProfile', args: SaveProfilePayload): Promise<SaveProfileResponse>
|
||||||
|
(method: 'testConnection', args: { id: string }): Promise<TestConnectionResponse>
|
||||||
|
(method: 'deleteProfile', args: { id: string }): Promise<DeleteProfileResponse>
|
||||||
|
(method: 'listSshConfigHosts'): Promise<ListSshConfigHostsResponse>
|
||||||
|
(method: 'listWorkspaces'): Promise<ListWorkspacesResponse>
|
||||||
|
(method: 'updateWorkspaceGuards', args: UpdateWorkspaceGuardsPayload): Promise<UpdateWorkspaceGuardsResponse>
|
||||||
|
(method: 'syncDown', args: { id: string }): Promise<SyncResponse>
|
||||||
|
(method: 'syncUp', args: { id: string }): Promise<SyncResponse>
|
||||||
|
(method: 'deleteWorkspace', args: { id: string }): Promise<DeleteWorkspaceResponse>
|
||||||
|
(method: 'getPrefs'): Promise<GetPrefsResponse>
|
||||||
|
(method: 'savePrefs', args: SavePrefsPayload): Promise<SavePrefsResponse>
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Translation + registration */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Bind of the settings dictionary namespace (typed keys, `{name}` params). */
|
||||||
|
export type SettingsTranslate = (key: string, params?: Record<string, string | number>) => string
|
||||||
|
|
||||||
|
/** Props the shell's `settings.section` renderer injects (locale `t` seat). */
|
||||||
|
export interface SettingsSectionProps {
|
||||||
|
t?: SettingsTranslate
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Registration shape accepted by the slot renderer (function component). */
|
||||||
|
export type SettingsSectionComponent = (props: SettingsSectionProps) => ReactNode
|
||||||
|
|
||||||
|
/** Runtime facts the merged client entry hands to the extracted factory. */
|
||||||
|
export interface RemoteSshClientCompose {
|
||||||
|
/** Dictionary namespace the settings entry declares (`locale:` in the slot def). */
|
||||||
|
readonly settingsNamespace: string
|
||||||
|
/** Build the settings section component around the vendored client's `api`. */
|
||||||
|
createSettingsSection(deps: SettingsSectionDeps): SettingsSectionComponent
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Injected runtime services for the section (the vendored client's api wrapper). */
|
||||||
|
export interface SettingsSectionDeps {
|
||||||
|
api: RemoteSshApi
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,328 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings dictionary.
|
||||||
|
*
|
||||||
|
* The section registers its OWN namespace `dsh-remote-ssh-settings` through
|
||||||
|
* the shell locale service (the merged client entry calls
|
||||||
|
* {@link registerSettingsLocale} inside `ctx.effect`). Registering a separate
|
||||||
|
* namespace — instead of appending keys to the vendored plugin's
|
||||||
|
* `dsh-remote-ssh` dictionaries at build time — keeps all new copy in source,
|
||||||
|
* type-checked by the `SettingsKey` union, and lets the slot machinery inject
|
||||||
|
* a typed `t` seat into the component (declared as `locale:` in the slot
|
||||||
|
* registration). Existing upstream keys/namespace are untouched.
|
||||||
|
*/
|
||||||
|
import type { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||||
|
|
||||||
|
/** Namespace owned by this settings face. */
|
||||||
|
export const SETTINGS_NS = 'dsh-remote-ssh-settings'
|
||||||
|
|
||||||
|
/** Chinese dictionary — the key set below is the single source of truth. */
|
||||||
|
export const zh = {
|
||||||
|
'page.title': 'Remote SSH',
|
||||||
|
'page.subtitle': '管理远程连接与同步设置',
|
||||||
|
|
||||||
|
'connection.sectionTitle': '我的连接',
|
||||||
|
'connection.sectionSummary': '测试连接、查看当前连接的诊断信息',
|
||||||
|
'connection.count': '{n} 个连接',
|
||||||
|
'connection.empty': '还没有连接配置。在下方「添加连接」中新增。',
|
||||||
|
'connection.test': '测试连接',
|
||||||
|
'connection.testing': '测试中…',
|
||||||
|
'connection.delete': '删除',
|
||||||
|
'connection.authKey': '密钥认证',
|
||||||
|
'connection.authPassword': '密码认证',
|
||||||
|
'connection.passwordConfigured': '已保存密码',
|
||||||
|
'connection.testOk': '连接成功',
|
||||||
|
'connection.testWarn': '连接成功,但有警告:',
|
||||||
|
'connection.testFail': '连接失败',
|
||||||
|
'connection.diagnostics': '诊断输出',
|
||||||
|
'connection.deleteTitle': '删除连接「{name}」?',
|
||||||
|
'connection.deleteBody': '将同时移除该连接下的远程工作区条目和本地镜像映射;不会删除服务器上的文件。',
|
||||||
|
'connection.deleted': '已删除连接「{name}」',
|
||||||
|
'connection.deleteFail': '删除失败',
|
||||||
|
|
||||||
|
'add.sectionTitle': '添加连接',
|
||||||
|
'add.sectionSummary': '从系统 SSH 配置导入,或手动填写',
|
||||||
|
'add.import': '从系统 SSH 配置导入…',
|
||||||
|
'add.divider': '或手动添加',
|
||||||
|
'add.name': '名称',
|
||||||
|
'add.namePlaceholder': '如:我的超算',
|
||||||
|
'add.host': '主机',
|
||||||
|
'add.hostPlaceholder': 'login.example.com',
|
||||||
|
'add.port': '端口',
|
||||||
|
'add.user': '用户名',
|
||||||
|
'add.userPlaceholder': 'your-username',
|
||||||
|
'add.auth': '认证方式',
|
||||||
|
'add.authKey': 'SSH 密钥',
|
||||||
|
'add.authPassword': '密码',
|
||||||
|
'add.keyPath': '私钥路径',
|
||||||
|
'add.keyPathPlaceholder': '~/.ssh/id_rsa(留空则使用 ssh-agent 或 SSH 配置)',
|
||||||
|
'add.password': '密码',
|
||||||
|
'add.passwordPlaceholder': '输入密码(不会写回浏览器存储)',
|
||||||
|
'add.remoteRoot': '远程根目录',
|
||||||
|
'add.remoteRootPlaceholder': '~/project',
|
||||||
|
'add.moreOptions': '更多连接选项',
|
||||||
|
'add.moreOptionsSummary': '跳板机 ProxyJump',
|
||||||
|
'add.proxyJump': '跳板机 ProxyJump',
|
||||||
|
'add.proxyJumpPlaceholder': 'bastion.example.com',
|
||||||
|
'add.submit': '添加连接',
|
||||||
|
'add.submitting': '添加中…',
|
||||||
|
'add.errHost': '请填写主机',
|
||||||
|
'add.errUser': '请填写用户名',
|
||||||
|
'add.errPort': '端口必须是 1–65535 的整数',
|
||||||
|
'add.ok': '已添加连接「{name}」',
|
||||||
|
'add.fail': '添加失败',
|
||||||
|
|
||||||
|
'import.title': '从系统 SSH 配置导入',
|
||||||
|
'import.loading': '正在读取 ~/.ssh/config…',
|
||||||
|
'import.readFail': '读取 ~/.ssh/config 失败',
|
||||||
|
'import.empty': '未在 ~/.ssh/config 中发现可用主机',
|
||||||
|
'import.note': '仅列出 ~/.ssh/config 中带 HostName 的条目;这不是完整的 OpenSSH 配置语义。',
|
||||||
|
'import.selectAll': '全选',
|
||||||
|
'import.clearAll': '取消全选',
|
||||||
|
'import.selectedCount': '已选 {n} / {total}',
|
||||||
|
'import.submit': '导入所选连接',
|
||||||
|
'import.importing': '导入中…({done}/{total})',
|
||||||
|
'import.progress': '正在导入「{name}」…',
|
||||||
|
'import.resultAllOk': '已导入 {ok} 个连接',
|
||||||
|
'import.resultPartial': '成功 {ok} 个,失败 {fail} 个',
|
||||||
|
'import.resultAllFail': '全部失败({fail} 个)',
|
||||||
|
'import.failedIntro': '以下主机未导入:',
|
||||||
|
'import.noResult': '保存接口未返回结果',
|
||||||
|
'import.retryFailed': '仅重试失败项({n})',
|
||||||
|
'import.retrying': '重试中…({done}/{total})',
|
||||||
|
'import.noneSelected': '请至少选择一个主机',
|
||||||
|
'import.proxyJump': '跳板机 {target}',
|
||||||
|
'import.close': '关闭',
|
||||||
|
'import.authNote': '导入的连接固定使用密钥认证、远程根目录 ~;可在手动表单中补充密码或其它字段。',
|
||||||
|
|
||||||
|
'workspace.sectionTitle': '远程工作区',
|
||||||
|
'workspace.sectionSummary': '独立写回与同步配置',
|
||||||
|
'workspace.empty': '还没有远程工作区。可在「添加工作区」中选择「远程目录」创建。',
|
||||||
|
'workspace.expand': '展开配置',
|
||||||
|
'workspace.collapse': '收起配置',
|
||||||
|
'workspace.connection': '所属连接',
|
||||||
|
'workspace.remotePath': '远程路径',
|
||||||
|
'workspace.writeBack': '启用写回(把 agent 的 write/edit 同步到远端)',
|
||||||
|
'workspace.writeBackExclude': '写回排除(逗号或换行分隔)',
|
||||||
|
'workspace.writeBackExcludeHint': '这些路径的本地改动不会推回远端,例如 _patch/, *.log。',
|
||||||
|
'workspace.syncPaths': '同步范围(逗号或换行分隔,留空 = 整树)',
|
||||||
|
'workspace.syncPathsHint': '只同步这些子路径,例如 .dsh;留空 = 整树。',
|
||||||
|
'workspace.syncExclude': '同步排除(逗号或换行分隔)',
|
||||||
|
'workspace.syncExcludeHint': '拉取和推送时跳过这些路径,例如 data/, *.log;与写回排除用途不同。',
|
||||||
|
'workspace.syncMaxBytes': '同步体积上限(GiB,留空 = 默认 2 GiB)',
|
||||||
|
'workspace.unsaved': '未保存',
|
||||||
|
'workspace.save': '保存该工作区设置',
|
||||||
|
'workspace.saving': '保存中…',
|
||||||
|
'workspace.saved': '该工作区设置已保存',
|
||||||
|
'workspace.saveFail': '保存失败',
|
||||||
|
'workspace.syncBlocked': '有未保存的设置,请先保存再拉取或推送。',
|
||||||
|
'workspace.syncDown': '拉取',
|
||||||
|
'workspace.syncUp': '推送',
|
||||||
|
'workspace.syncing': '拉取中…',
|
||||||
|
'workspace.pushing': '推送中…',
|
||||||
|
'workspace.syncDone': '拉取完成',
|
||||||
|
'workspace.syncFail': '拉取失败',
|
||||||
|
'workspace.pushDone': '推送完成',
|
||||||
|
'workspace.pushFail': '推送失败',
|
||||||
|
'workspace.deleteTitle': '移除远程工作区「{title}」?',
|
||||||
|
'workspace.deleteBody': '只移除本地记录与镜像映射,不会删除服务器上的目录或文件。',
|
||||||
|
'workspace.deleted': '已移除远程工作区「{title}」',
|
||||||
|
'workspace.deleteFail': '删除失败',
|
||||||
|
'workspace.unknownProfile': '未知连接',
|
||||||
|
|
||||||
|
'advanced.sectionTitle': '高级设置',
|
||||||
|
'advanced.sectionSummary': '终端与写回、新工作区同步默认值',
|
||||||
|
'advanced.terminalGroup': '终端与写回',
|
||||||
|
'advanced.nodePath': 'Node 绝对路径',
|
||||||
|
'advanced.nodePathHint': '终端起不来时填写;留空自动解析。',
|
||||||
|
'advanced.nodePathPlaceholder': 'C:\\Program Files\\nodejs\\node.exe',
|
||||||
|
'advanced.writeBackFailure': '写回推送失败时',
|
||||||
|
'advanced.wbError': '让模型看见,工具报错',
|
||||||
|
'advanced.wbLog': '只写日志',
|
||||||
|
'advanced.writeBackFreshness': '推送前检查远端是否被改过(发现被改过就不推并报告)',
|
||||||
|
'advanced.syncDefaultsGroup': '新工作区同步默认值',
|
||||||
|
'advanced.syncDefaultsHint': '仅影响之后新建的远程工作区,不会覆盖已有工作区的独立设置。',
|
||||||
|
'advanced.defaultSyncPaths': '默认同步范围(逗号或换行分隔,留空 = 整树)',
|
||||||
|
'advanced.defaultSyncExclude': '默认同步排除(逗号或换行分隔)',
|
||||||
|
'advanced.defaultSyncMaxBytes': '默认同步体积上限(GiB,留空 = 内置 2 GiB)',
|
||||||
|
'advanced.save': '保存设置',
|
||||||
|
'advanced.saving': '保存中…',
|
||||||
|
'advanced.saved': '设置已保存',
|
||||||
|
'advanced.saveFail': '保存失败',
|
||||||
|
|
||||||
|
'common.cancel': '取消',
|
||||||
|
'common.close': '关闭',
|
||||||
|
'common.confirmDelete': '确认删除',
|
||||||
|
'common.retry': '重试',
|
||||||
|
'common.loading': '加载中…',
|
||||||
|
'common.save': '保存',
|
||||||
|
'common.error': '错误:',
|
||||||
|
'common.warning': '警告:',
|
||||||
|
'common.unknownError': '未知错误',
|
||||||
|
'common.expand': '展开',
|
||||||
|
'common.collapse': '收起',
|
||||||
|
} as const
|
||||||
|
|
||||||
|
/** Chinese key set; every call site is checked against it. */
|
||||||
|
export type SettingsKey = keyof typeof zh
|
||||||
|
|
||||||
|
/** English dictionary — complete mirror of the Chinese key set. */
|
||||||
|
export const en: Record<SettingsKey, string> = {
|
||||||
|
'page.title': 'Remote SSH',
|
||||||
|
'page.subtitle': 'Manage remote connections and sync settings',
|
||||||
|
|
||||||
|
'connection.sectionTitle': 'My connections',
|
||||||
|
'connection.sectionSummary': 'Test connections and inspect diagnostics',
|
||||||
|
'connection.count': '{n} connection(s)',
|
||||||
|
'connection.empty': 'No connections yet. Add one below.',
|
||||||
|
'connection.test': 'Test connection',
|
||||||
|
'connection.testing': 'Testing…',
|
||||||
|
'connection.delete': 'Delete',
|
||||||
|
'connection.authKey': 'SSH key',
|
||||||
|
'connection.authPassword': 'Password',
|
||||||
|
'connection.passwordConfigured': 'Password saved',
|
||||||
|
'connection.testOk': 'Connection succeeded',
|
||||||
|
'connection.testWarn': 'Connected with a warning:',
|
||||||
|
'connection.testFail': 'Connection failed',
|
||||||
|
'connection.diagnostics': 'Diagnostics',
|
||||||
|
'connection.deleteTitle': 'Delete connection "{name}"?',
|
||||||
|
'connection.deleteBody': 'This also removes the connection\'s remote workspace entries and local mirror mapping; server files are not deleted.',
|
||||||
|
'connection.deleted': 'Deleted connection "{name}"',
|
||||||
|
'connection.deleteFail': 'Delete failed',
|
||||||
|
|
||||||
|
'add.sectionTitle': 'Add connection',
|
||||||
|
'add.sectionSummary': 'Import from the system SSH config, or fill in manually',
|
||||||
|
'add.import': 'Import from system SSH config…',
|
||||||
|
'add.divider': 'or add manually',
|
||||||
|
'add.name': 'Name',
|
||||||
|
'add.namePlaceholder': 'e.g. My HPC',
|
||||||
|
'add.host': 'Host',
|
||||||
|
'add.hostPlaceholder': 'login.example.com',
|
||||||
|
'add.port': 'Port',
|
||||||
|
'add.user': 'User',
|
||||||
|
'add.userPlaceholder': 'your-username',
|
||||||
|
'add.auth': 'Authentication',
|
||||||
|
'add.authKey': 'SSH key',
|
||||||
|
'add.authPassword': 'Password',
|
||||||
|
'add.keyPath': 'Private key path',
|
||||||
|
'add.keyPathPlaceholder': '~/.ssh/id_rsa (empty = ssh-agent or SSH config)',
|
||||||
|
'add.password': 'Password',
|
||||||
|
'add.passwordPlaceholder': 'Enter password (never written to browser storage)',
|
||||||
|
'add.remoteRoot': 'Remote root',
|
||||||
|
'add.remoteRootPlaceholder': '~/project',
|
||||||
|
'add.moreOptions': 'More connection options',
|
||||||
|
'add.moreOptionsSummary': 'Jump host ProxyJump',
|
||||||
|
'add.proxyJump': 'Jump host ProxyJump',
|
||||||
|
'add.proxyJumpPlaceholder': 'bastion.example.com',
|
||||||
|
'add.submit': 'Add connection',
|
||||||
|
'add.submitting': 'Adding…',
|
||||||
|
'add.errHost': 'Host is required',
|
||||||
|
'add.errUser': 'User is required',
|
||||||
|
'add.errPort': 'Port must be an integer from 1 to 65535',
|
||||||
|
'add.ok': 'Added connection "{name}"',
|
||||||
|
'add.fail': 'Add failed',
|
||||||
|
|
||||||
|
'import.title': 'Import from system SSH config',
|
||||||
|
'import.loading': 'Reading ~/.ssh/config…',
|
||||||
|
'import.readFail': 'Failed to read ~/.ssh/config',
|
||||||
|
'import.empty': 'No usable hosts found in ~/.ssh/config',
|
||||||
|
'import.note': 'Only entries with HostName are listed; this is not full OpenSSH config semantics.',
|
||||||
|
'import.selectAll': 'Select all',
|
||||||
|
'import.clearAll': 'Clear selection',
|
||||||
|
'import.selectedCount': '{n} / {total} selected',
|
||||||
|
'import.submit': 'Import selected connections',
|
||||||
|
'import.importing': 'Importing… ({done}/{total})',
|
||||||
|
'import.progress': 'Importing "{name}"…',
|
||||||
|
'import.resultAllOk': 'Imported {ok} connection(s)',
|
||||||
|
'import.resultPartial': '{ok} succeeded, {fail} failed',
|
||||||
|
'import.resultAllFail': 'All {fail} failed',
|
||||||
|
'import.failedIntro': 'These hosts were not imported:',
|
||||||
|
'import.noResult': 'The save endpoint returned no result',
|
||||||
|
'import.retryFailed': 'Retry failed only ({n})',
|
||||||
|
'import.retrying': 'Retrying… ({done}/{total})',
|
||||||
|
'import.noneSelected': 'Select at least one host',
|
||||||
|
'import.proxyJump': 'Jump host {target}',
|
||||||
|
'import.close': 'Close',
|
||||||
|
'import.authNote': 'Imported connections always use key authentication and remote root ~; add a password or other fields in the manual form.',
|
||||||
|
|
||||||
|
'workspace.sectionTitle': 'Remote workspaces',
|
||||||
|
'workspace.sectionSummary': 'Independent write-back and sync settings',
|
||||||
|
'workspace.empty': 'No remote workspaces yet. Create one via "Add workspace" → "Remote directory".',
|
||||||
|
'workspace.expand': 'Expand settings',
|
||||||
|
'workspace.collapse': 'Collapse settings',
|
||||||
|
'workspace.connection': 'Connection',
|
||||||
|
'workspace.remotePath': 'Remote path',
|
||||||
|
'workspace.writeBack': 'Enable write-back (push agent writes/edits to the remote)',
|
||||||
|
'workspace.writeBackExclude': 'Write-back exclude (comma or newline separated)',
|
||||||
|
'workspace.writeBackExcludeHint': 'Local changes under these paths are not pushed, e.g. _patch/, *.log.',
|
||||||
|
'workspace.syncPaths': 'Sync scope (comma or newline separated, empty = whole tree)',
|
||||||
|
'workspace.syncPathsHint': 'Only these sub-paths are synced, e.g. .dsh; empty = whole tree.',
|
||||||
|
'workspace.syncExclude': 'Sync exclude (comma or newline separated)',
|
||||||
|
'workspace.syncExcludeHint': 'Pull/push skip these paths, e.g. data/, *.log; different from write-back exclude.',
|
||||||
|
'workspace.syncMaxBytes': 'Sync size cap (GiB, empty = default 2 GiB)',
|
||||||
|
'workspace.unsaved': 'Unsaved',
|
||||||
|
'workspace.save': 'Save workspace settings',
|
||||||
|
'workspace.saving': 'Saving…',
|
||||||
|
'workspace.saved': 'Workspace settings saved',
|
||||||
|
'workspace.saveFail': 'Save failed',
|
||||||
|
'workspace.syncBlocked': 'Unsaved settings — save before pulling or pushing.',
|
||||||
|
'workspace.syncDown': 'Pull',
|
||||||
|
'workspace.syncUp': 'Push',
|
||||||
|
'workspace.syncing': 'Pulling…',
|
||||||
|
'workspace.pushing': 'Pushing…',
|
||||||
|
'workspace.syncDone': 'Pull finished',
|
||||||
|
'workspace.syncFail': 'Pull failed',
|
||||||
|
'workspace.pushDone': 'Push finished',
|
||||||
|
'workspace.pushFail': 'Push failed',
|
||||||
|
'workspace.deleteTitle': 'Remove remote workspace "{title}"?',
|
||||||
|
'workspace.deleteBody': 'Only the local record and mirror mapping are removed; server files and directories are untouched.',
|
||||||
|
'workspace.deleted': 'Removed remote workspace "{title}"',
|
||||||
|
'workspace.deleteFail': 'Delete failed',
|
||||||
|
'workspace.unknownProfile': 'Unknown connection',
|
||||||
|
|
||||||
|
'advanced.sectionTitle': 'Advanced settings',
|
||||||
|
'advanced.sectionSummary': 'Terminal and write-back, new-workspace sync defaults',
|
||||||
|
'advanced.terminalGroup': 'Terminal and write-back',
|
||||||
|
'advanced.nodePath': 'Node absolute path',
|
||||||
|
'advanced.nodePathHint': 'Fill in when the terminal cannot start; empty resolves automatically.',
|
||||||
|
'advanced.nodePathPlaceholder': 'C:\\Program Files\\nodejs\\node.exe',
|
||||||
|
'advanced.writeBackFailure': 'When a write-back push fails',
|
||||||
|
'advanced.wbError': 'Surface to the model (tool error)',
|
||||||
|
'advanced.wbLog': 'Log only',
|
||||||
|
'advanced.writeBackFreshness': 'Check the remote for changes before pushing (skip and report when changed)',
|
||||||
|
'advanced.syncDefaultsGroup': 'New workspace sync defaults',
|
||||||
|
'advanced.syncDefaultsHint': 'Affects only remote workspaces created later; existing workspace settings are untouched.',
|
||||||
|
'advanced.defaultSyncPaths': 'Default sync scope (comma or newline separated, empty = whole tree)',
|
||||||
|
'advanced.defaultSyncExclude': 'Default sync exclude (comma or newline separated)',
|
||||||
|
'advanced.defaultSyncMaxBytes': 'Default sync size cap (GiB, empty = built-in 2 GiB)',
|
||||||
|
'advanced.save': 'Save settings',
|
||||||
|
'advanced.saving': 'Saving…',
|
||||||
|
'advanced.saved': 'Settings saved',
|
||||||
|
'advanced.saveFail': 'Save failed',
|
||||||
|
|
||||||
|
'common.cancel': 'Cancel',
|
||||||
|
'common.close': 'Close',
|
||||||
|
'common.confirmDelete': 'Confirm delete',
|
||||||
|
'common.retry': 'Retry',
|
||||||
|
'common.loading': 'Loading…',
|
||||||
|
'common.save': 'Save',
|
||||||
|
'common.error': 'Error: ',
|
||||||
|
'common.warning': 'Warning: ',
|
||||||
|
'common.unknownError': 'Unknown error',
|
||||||
|
'common.expand': 'Expand',
|
||||||
|
'common.collapse': 'Collapse',
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||||
|
interface LocaleNamespaceMap {
|
||||||
|
'dsh-remote-ssh-settings': SettingsKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register both dictionaries for this namespace on the shell locale service.
|
||||||
|
* Call inside `ctx.effect(...)` so the registration is disposed with the
|
||||||
|
* plugin fiber. The typed `register` overload enforces zh/en key parity.
|
||||||
|
*/
|
||||||
|
export function registerSettingsLocale(locale: LocaleRuntime): () => void {
|
||||||
|
return locale.register(SETTINGS_NS, { zh, en })
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,510 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — pure model.
|
||||||
|
*
|
||||||
|
* Everything here is plain data transformation (no React, no DOM, no
|
||||||
|
* imports from other plugin sources), so the real behaviour can be covered
|
||||||
|
* by unit tests without mounting the shell:
|
||||||
|
*
|
||||||
|
* - connection form validation and the exact `saveProfile` payload
|
||||||
|
* - `~/.ssh/config` import mapping, per-item outcomes, partial-failure counts
|
||||||
|
* and failed-only retry merges (the old face reported the selection size as
|
||||||
|
* "imported" regardless of each save result)
|
||||||
|
* - per-workspace guard drafts, dirty detection, reload reconciliation and the
|
||||||
|
* exact `updateWorkspaceGuards` payload
|
||||||
|
* - global preferences draft/payload/dirty/reconcile
|
||||||
|
*
|
||||||
|
* Field semantics and unit conversions are copied from the vendored client
|
||||||
|
* (`splitList`, `bytesToGibText`, `gibTextToBytes`, `prefsForUi`) so the face
|
||||||
|
* keeps the existing Host contract: lists accept comma/newline/semicolon,
|
||||||
|
* the size cap is edited in GiB and stored in bytes, empty = Host default.
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
RemoteSshPrefs,
|
||||||
|
RemoteSshProfile,
|
||||||
|
RemoteSshWorkspace,
|
||||||
|
SavePrefsPayload,
|
||||||
|
SaveProfilePayload,
|
||||||
|
SshConfigHost,
|
||||||
|
TestConnectionResponse,
|
||||||
|
UpdateWorkspaceGuardsPayload,
|
||||||
|
} from './contract.ts'
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Connection form */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Controlled draft of the "add connection" form (all fields are strings). */
|
||||||
|
export interface ConnectionForm {
|
||||||
|
name: string
|
||||||
|
host: string
|
||||||
|
port: string
|
||||||
|
user: string
|
||||||
|
authMethod: 'key' | 'password'
|
||||||
|
keyPath: string
|
||||||
|
password: string
|
||||||
|
remoteRoot: string
|
||||||
|
proxyJump: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Values the vendored client used when opening/clearing the form. */
|
||||||
|
export const EMPTY_CONNECTION_FORM: ConnectionForm = {
|
||||||
|
name: '',
|
||||||
|
host: '',
|
||||||
|
port: '22',
|
||||||
|
user: '',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: '',
|
||||||
|
password: '',
|
||||||
|
remoteRoot: '~',
|
||||||
|
proxyJump: '',
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fresh copy (never share the frozen constant with component state). */
|
||||||
|
export function emptyConnectionForm(): ConnectionForm {
|
||||||
|
return { ...EMPTY_CONNECTION_FORM }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Field-level issue; the component maps `messageKey` through `t`. */
|
||||||
|
export interface FormIssue {
|
||||||
|
field: 'host' | 'user' | 'port'
|
||||||
|
messageKey: 'add.errHost' | 'add.errUser' | 'add.errPort'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate exactly what the Host requires (`host` + `user`) plus a real port
|
||||||
|
* range. The Host would otherwise `parseInt(port) || 22`, silently turning a
|
||||||
|
* typo into 22; the UI refuses it instead. Aliases, empty key paths and the
|
||||||
|
* reliance on ssh-agent / ~/.ssh/config stay legal (the backend accepts them).
|
||||||
|
*/
|
||||||
|
export function validateConnectionForm(form: ConnectionForm): FormIssue[] {
|
||||||
|
const issues: FormIssue[] = []
|
||||||
|
if (!form.host.trim()) issues.push({ field: 'host', messageKey: 'add.errHost' })
|
||||||
|
if (!form.user.trim()) issues.push({ field: 'user', messageKey: 'add.errUser' })
|
||||||
|
const portText = form.port.trim()
|
||||||
|
const portNumber = Number(portText)
|
||||||
|
if (!/^\d+$/.test(portText) || !Number.isInteger(portNumber) || portNumber < 1 || portNumber > 65535) {
|
||||||
|
issues.push({ field: 'port', messageKey: 'add.errPort' })
|
||||||
|
}
|
||||||
|
return issues
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the form can be submitted (callers still re-check on submit). */
|
||||||
|
export function isConnectionFormValid(form: ConnectionForm): boolean {
|
||||||
|
return validateConnectionForm(form).length === 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exact `saveProfile` body. Fields are passed through as typed by the user
|
||||||
|
* (the Host trims/derives where it always did: name falls back to host, port
|
||||||
|
* parsing is already done here, password only persists for password auth).
|
||||||
|
*/
|
||||||
|
export function toSaveProfilePayload(form: ConnectionForm): SaveProfilePayload {
|
||||||
|
return {
|
||||||
|
name: form.name,
|
||||||
|
host: form.host,
|
||||||
|
port: Number(form.port),
|
||||||
|
user: form.user,
|
||||||
|
authMethod: form.authMethod,
|
||||||
|
keyPath: form.keyPath,
|
||||||
|
password: form.password,
|
||||||
|
remoteRoot: form.remoteRoot,
|
||||||
|
proxyJump: form.proxyJump,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `user@host:port` summary used by connection cards. */
|
||||||
|
export function profileSummary(profile: RemoteSshProfile): string {
|
||||||
|
return `${profile.user || ''}@${profile.host || ''}:${profile.port || 22}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Display name with the upstream `name || host` fallback. */
|
||||||
|
export function profileName(profile: RemoteSshProfile): string {
|
||||||
|
return profile.name || profile.host
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Shared conversion helpers (copied from the vendored client) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** "comma or newline (or semicolon) separated" text → trimmed non-empty list. */
|
||||||
|
export function splitList(value: string | null | undefined): string[] {
|
||||||
|
return String(value == null ? '' : value)
|
||||||
|
.split(/[\n,;]/)
|
||||||
|
.map(item => item.trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Byte count → GiB text (empty = Host built-in default cap). */
|
||||||
|
export function bytesToGibText(bytes: number | null | undefined): string {
|
||||||
|
const n = Number(bytes) || 0
|
||||||
|
if (!n) return ''
|
||||||
|
return String(Math.round((n / 1073741824) * 100) / 100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GiB text → bytes; empty/invalid → 0 (= Host built-in default cap). */
|
||||||
|
export function gibTextToBytes(text: string | number | null | undefined): number {
|
||||||
|
const n = parseFloat(String(text == null ? '' : text).replace(/[^0-9.]/g, ''))
|
||||||
|
if (!Number.isFinite(n) || n <= 0) return 0
|
||||||
|
return Math.round(n * 1073741824)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Trimmed error text from an API envelope, else the caller's fallback. */
|
||||||
|
export function apiErrorMessage(
|
||||||
|
value: { error?: string } | null | undefined,
|
||||||
|
fallback: string,
|
||||||
|
): string {
|
||||||
|
const text = value && typeof value.error === 'string' ? value.error.trim() : ''
|
||||||
|
return text || fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Connection test feedback */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export type TestStatus = 'success' | 'warning' | 'error'
|
||||||
|
|
||||||
|
/** Rendered shape of one connection test result. */
|
||||||
|
export interface ConnectionTestView {
|
||||||
|
status: TestStatus
|
||||||
|
/** Localized status line (caller resolves the keys). */
|
||||||
|
titleKey: 'connection.testOk' | 'connection.testWarn' | 'connection.testFail'
|
||||||
|
/** Raw warning returned by the Host (successful connect with degraded key path). */
|
||||||
|
warning: string
|
||||||
|
/** stdout for success, stderr/error text for failure. */
|
||||||
|
detail: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map `testConnection` output to the card feedback. A successful probe that
|
||||||
|
* carries `warning` stays a warning (never collapsed into a plain success).
|
||||||
|
*/
|
||||||
|
export function connectionTestView(
|
||||||
|
result: TestConnectionResponse | null | undefined,
|
||||||
|
): ConnectionTestView {
|
||||||
|
const warning = String(result?.warning || '').trim()
|
||||||
|
if (result?.ok) {
|
||||||
|
return {
|
||||||
|
status: warning ? 'warning' : 'success',
|
||||||
|
titleKey: warning ? 'connection.testWarn' : 'connection.testOk',
|
||||||
|
warning,
|
||||||
|
detail: String(result.stdout || '').trim(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const detail = [result?.error, result?.stderr].filter(Boolean).join('\n').trim()
|
||||||
|
return {
|
||||||
|
status: 'error',
|
||||||
|
titleKey: 'connection.testFail',
|
||||||
|
warning,
|
||||||
|
detail,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* SSH config import */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Stable row key; same spelling the vendored importer used for selection. */
|
||||||
|
export function importHostKey(host: SshConfigHost): string {
|
||||||
|
return `${host.name}|${host.hostName}`
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Default selection: every discovered host (upstream opened all checked). */
|
||||||
|
export function selectAllHosts(hosts: SshConfigHost[]): Record<string, boolean> {
|
||||||
|
const selected: Record<string, boolean> = {}
|
||||||
|
for (const host of hosts) selected[importHostKey(host)] = true
|
||||||
|
return selected
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Toggle one selection key without mutating the previous map. */
|
||||||
|
export function toggleHostSelection(
|
||||||
|
selected: Record<string, boolean>,
|
||||||
|
key: string,
|
||||||
|
): Record<string, boolean> {
|
||||||
|
return { ...selected, [key]: !selected[key] }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Selected hosts, in discovery order (never trusts map iteration order). */
|
||||||
|
export function selectedHosts(
|
||||||
|
hosts: SshConfigHost[],
|
||||||
|
selected: Record<string, boolean>,
|
||||||
|
): SshConfigHost[] {
|
||||||
|
return hosts.filter(host => selected[importHostKey(host)])
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Count of checked rows. */
|
||||||
|
export function countSelected(selected: Record<string, boolean>): number {
|
||||||
|
return Object.keys(selected).filter(key => selected[key]).length
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exact import mapping kept from the vendored face: name, host, port, user,
|
||||||
|
* keyPath (identityFile), proxyJump; key auth, empty password, remoteRoot ~.
|
||||||
|
*/
|
||||||
|
export function importProfilePayload(host: SshConfigHost): SaveProfilePayload {
|
||||||
|
return {
|
||||||
|
name: host.name,
|
||||||
|
host: host.hostName,
|
||||||
|
port: Number(host.port) || 22,
|
||||||
|
user: host.user || '',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: host.identityFile || '',
|
||||||
|
password: '',
|
||||||
|
remoteRoot: '~',
|
||||||
|
proxyJump: host.proxyJump || '',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One save attempt inside an import run. */
|
||||||
|
export interface ImportItemOutcome {
|
||||||
|
key: string
|
||||||
|
name: string
|
||||||
|
hostName: string
|
||||||
|
ok: boolean
|
||||||
|
/** Host/transport error text (absent when ok). */
|
||||||
|
error?: string
|
||||||
|
/** Synthesized reason when the call resolved without an envelope. */
|
||||||
|
errorCode?: 'no-result'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Aggregated per-run statistics (never "selected size" as success count). */
|
||||||
|
export interface ImportSummary {
|
||||||
|
outcomes: ImportItemOutcome[]
|
||||||
|
okCount: number
|
||||||
|
failCount: number
|
||||||
|
failedHosts: SshConfigHost[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Injected `saveProfile` port (the vendored api wrapper satisfies this). */
|
||||||
|
export type SaveProfileCall = (
|
||||||
|
payload: SaveProfilePayload,
|
||||||
|
) => Promise<{ ok?: boolean; error?: string } | null | undefined>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import hosts one by one. Each item is checked individually:
|
||||||
|
* - `ok: true` counts as success;
|
||||||
|
* - `ok: false` (or any thrown request error) counts as failure with its reason;
|
||||||
|
* - a missing envelope counts as failure (`errorCode: 'no-result'`) so a
|
||||||
|
* silent transport layer can never be reported as imported.
|
||||||
|
*
|
||||||
|
* Sequential on purpose: profile saves rewrite one settings table, and the
|
||||||
|
* calls are cheap compared to SSH; this also keeps progress deterministic.
|
||||||
|
*/
|
||||||
|
export async function runImport(
|
||||||
|
hosts: SshConfigHost[],
|
||||||
|
saveProfile: SaveProfileCall,
|
||||||
|
options: {
|
||||||
|
onProgress?: (done: number, total: number, host: SshConfigHost) => void
|
||||||
|
} = {},
|
||||||
|
): Promise<ImportSummary> {
|
||||||
|
const outcomes: ImportItemOutcome[] = []
|
||||||
|
const failedHosts: SshConfigHost[] = []
|
||||||
|
let okCount = 0
|
||||||
|
let failCount = 0
|
||||||
|
|
||||||
|
for (let index = 0; index < hosts.length; index += 1) {
|
||||||
|
const host = hosts[index] as SshConfigHost
|
||||||
|
options.onProgress?.(index, hosts.length, host)
|
||||||
|
const outcome: ImportItemOutcome = {
|
||||||
|
key: importHostKey(host),
|
||||||
|
name: host.name,
|
||||||
|
hostName: host.hostName,
|
||||||
|
ok: false,
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const result = await saveProfile(importProfilePayload(host))
|
||||||
|
if (result && result.ok === true) {
|
||||||
|
outcome.ok = true
|
||||||
|
okCount += 1
|
||||||
|
} else {
|
||||||
|
const error = result && typeof result.error === 'string' ? result.error.trim() : ''
|
||||||
|
if (error) outcome.error = error
|
||||||
|
else outcome.errorCode = 'no-result'
|
||||||
|
failCount += 1
|
||||||
|
failedHosts.push(host)
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
outcome.error = error instanceof Error ? error.message : String(error)
|
||||||
|
failCount += 1
|
||||||
|
failedHosts.push(host)
|
||||||
|
}
|
||||||
|
outcomes.push(outcome)
|
||||||
|
}
|
||||||
|
const lastHost = hosts[hosts.length - 1]
|
||||||
|
if (lastHost) options.onProgress?.(hosts.length, hosts.length, lastHost)
|
||||||
|
return { outcomes, okCount, failCount, failedHosts }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fold a failed-only retry run into the previous summary: previously
|
||||||
|
* successful items stay successes (they are never resubmitted), failed items
|
||||||
|
* take the retry outcome.
|
||||||
|
*/
|
||||||
|
export function mergeImportRetry(
|
||||||
|
previous: ImportSummary,
|
||||||
|
retry: ImportSummary,
|
||||||
|
): ImportSummary {
|
||||||
|
const kept = previous.outcomes.filter(outcome => outcome.ok)
|
||||||
|
const outcomes = [...kept, ...retry.outcomes]
|
||||||
|
const okCount = kept.length + retry.okCount
|
||||||
|
const failCount = retry.failCount
|
||||||
|
return { outcomes, okCount, failCount, failedHosts: retry.failedHosts }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Per-workspace guards */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Controlled draft of one workspace's write-back / sync settings. */
|
||||||
|
export interface GuardDraft {
|
||||||
|
writeBack: boolean
|
||||||
|
writeBackExclude: string
|
||||||
|
syncPaths: string
|
||||||
|
syncExclude: string
|
||||||
|
syncMaxBytes: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draft initialized from a persisted record (defaults match the Host). */
|
||||||
|
export function guardDraftFromWorkspace(workspace: RemoteSshWorkspace): GuardDraft {
|
||||||
|
return {
|
||||||
|
writeBack: workspace.writeBack !== false,
|
||||||
|
writeBackExclude: (workspace.writeBackExclude || []).join(', '),
|
||||||
|
syncPaths: (workspace.syncPaths || []).join(', '),
|
||||||
|
syncExclude: (workspace.syncExclude || []).join(', '),
|
||||||
|
syncMaxBytes: bytesToGibText(workspace.syncMaxBytes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drafts + baselines keyed by workspace id. */
|
||||||
|
export function guardsFromWorkspaces(
|
||||||
|
workspaces: RemoteSshWorkspace[],
|
||||||
|
): Record<string, GuardDraft> {
|
||||||
|
const drafts: Record<string, GuardDraft> = {}
|
||||||
|
for (const workspace of workspaces) drafts[workspace.id] = guardDraftFromWorkspace(workspace)
|
||||||
|
return drafts
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Canonical signature: list formatting / "2" vs "2.0" must not look dirty. */
|
||||||
|
export function guardDraftSignature(draft: GuardDraft): string {
|
||||||
|
return [
|
||||||
|
draft.writeBack ? '1' : '0',
|
||||||
|
splitList(draft.writeBackExclude).join('\u0000'),
|
||||||
|
splitList(draft.syncPaths).join('\u0000'),
|
||||||
|
splitList(draft.syncExclude).join('\u0000'),
|
||||||
|
String(gibTextToBytes(draft.syncMaxBytes)),
|
||||||
|
].join('\u0001')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the draft differs semantically from the persisted baseline. */
|
||||||
|
export function isGuardDraftDirty(draft: GuardDraft, baseline: GuardDraft): boolean {
|
||||||
|
return guardDraftSignature(draft) !== guardDraftSignature(baseline)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exact `updateWorkspaceGuards` body — always carries the target workspace id. */
|
||||||
|
export function toUpdateWorkspaceGuardsPayload(
|
||||||
|
workspaceId: string,
|
||||||
|
draft: GuardDraft,
|
||||||
|
): UpdateWorkspaceGuardsPayload {
|
||||||
|
return {
|
||||||
|
id: workspaceId,
|
||||||
|
writeBack: draft.writeBack !== false,
|
||||||
|
writeBackExclude: splitList(draft.writeBackExclude),
|
||||||
|
syncPaths: splitList(draft.syncPaths),
|
||||||
|
syncExclude: splitList(draft.syncExclude),
|
||||||
|
syncMaxBytes: gibTextToBytes(draft.syncMaxBytes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconcile drafts with a freshly persisted list. Dirty drafts survive a
|
||||||
|
* reload (their baseline moves to the new server truth); clean drafts adopt
|
||||||
|
* it. Records removed on the Host disappear. A draft with no baseline is
|
||||||
|
* treated as dirty so an unrelated refresh can never wipe typed text.
|
||||||
|
*/
|
||||||
|
export function reconcileGuards(
|
||||||
|
previousDrafts: Record<string, GuardDraft>,
|
||||||
|
previousBaselines: Record<string, GuardDraft>,
|
||||||
|
workspaces: RemoteSshWorkspace[],
|
||||||
|
): { drafts: Record<string, GuardDraft>; baselines: Record<string, GuardDraft> } {
|
||||||
|
const baselines: Record<string, GuardDraft> = guardsFromWorkspaces(workspaces)
|
||||||
|
const drafts: Record<string, GuardDraft> = {}
|
||||||
|
for (const [id, baseline] of Object.entries(baselines)) {
|
||||||
|
const previousDraft = previousDrafts[id]
|
||||||
|
const previousBaseline = previousBaselines[id]
|
||||||
|
const dirty = previousDraft !== undefined
|
||||||
|
&& (previousBaseline === undefined || isGuardDraftDirty(previousDraft, previousBaseline))
|
||||||
|
drafts[id] = dirty ? previousDraft : baseline
|
||||||
|
}
|
||||||
|
return { drafts, baselines }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Global preferences */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Controlled draft of the advanced section. */
|
||||||
|
export interface PrefsDraft {
|
||||||
|
nodePath: string
|
||||||
|
writeBackFailure: 'error' | 'log'
|
||||||
|
writeBackFreshness: boolean
|
||||||
|
defaultSyncPaths: string
|
||||||
|
defaultSyncExclude: string
|
||||||
|
defaultSyncMaxBytes: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Host preferences → draft (same projection the vendored face used). */
|
||||||
|
export function prefsDraftFromApi(prefs: RemoteSshPrefs | null | undefined): PrefsDraft {
|
||||||
|
const value = prefs || {}
|
||||||
|
return {
|
||||||
|
nodePath: String(value.nodePath || ''),
|
||||||
|
writeBackFailure: String(value.writeBackFailure || 'error') === 'log' ? 'log' : 'error',
|
||||||
|
writeBackFreshness: value.writeBackFreshness !== false,
|
||||||
|
defaultSyncPaths: (value.defaultSyncPaths || []).join(', '),
|
||||||
|
defaultSyncExclude: (value.defaultSyncExclude || []).join(', '),
|
||||||
|
defaultSyncMaxBytes: bytesToGibText(value.defaultSyncMaxBytes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Canonical preference signature for dirty detection. */
|
||||||
|
export function prefsDraftSignature(draft: PrefsDraft): string {
|
||||||
|
return [
|
||||||
|
draft.nodePath.trim(),
|
||||||
|
draft.writeBackFailure === 'log' ? 'log' : 'error',
|
||||||
|
draft.writeBackFreshness === false ? '0' : '1',
|
||||||
|
splitList(draft.defaultSyncPaths).join('\u0000'),
|
||||||
|
splitList(draft.defaultSyncExclude).join('\u0000'),
|
||||||
|
String(gibTextToBytes(draft.defaultSyncMaxBytes)),
|
||||||
|
].join('\u0001')
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the advanced draft differs from the saved preferences. */
|
||||||
|
export function isPrefsDraftDirty(draft: PrefsDraft, baseline: PrefsDraft): boolean {
|
||||||
|
return prefsDraftSignature(draft) !== prefsDraftSignature(baseline)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Exact `savePrefs` body (array conversions + GiB → bytes). */
|
||||||
|
export function toSavePrefsPayload(draft: PrefsDraft): SavePrefsPayload {
|
||||||
|
return {
|
||||||
|
nodePath: draft.nodePath.trim(),
|
||||||
|
writeBackFailure: draft.writeBackFailure === 'log' ? 'log' : 'error',
|
||||||
|
writeBackFreshness: draft.writeBackFreshness !== false,
|
||||||
|
defaultSyncPaths: splitList(draft.defaultSyncPaths),
|
||||||
|
defaultSyncExclude: splitList(draft.defaultSyncExclude),
|
||||||
|
defaultSyncMaxBytes: gibTextToBytes(draft.defaultSyncMaxBytes),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reconcile the advanced draft with a fresh `getPrefs` read: unsaved edits
|
||||||
|
* survive, clean drafts adopt server truth. Baselines always follow the
|
||||||
|
* server so the dirty badge compares against what is actually stored.
|
||||||
|
*/
|
||||||
|
export function reconcilePrefs(
|
||||||
|
previousDraft: PrefsDraft | null,
|
||||||
|
previousBaseline: PrefsDraft | null,
|
||||||
|
serverDraft: PrefsDraft,
|
||||||
|
): { draft: PrefsDraft; baseline: PrefsDraft } {
|
||||||
|
if (previousDraft && previousBaseline && isPrefsDraftDirty(previousDraft, previousBaseline)) {
|
||||||
|
return { draft: previousDraft, baseline: serverDraft }
|
||||||
|
}
|
||||||
|
return { draft: serverDraft, baseline: serverDraft }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
/**
|
||||||
|
* Compiled-at-build CSS for the Remote-SSH settings face.
|
||||||
|
*
|
||||||
|
* `settings.css?inline` is resolved by tsdown's virtual CSS module (see
|
||||||
|
* `tsdown.config.ts`: lightningcss minification, no CSS Modules hashing), so
|
||||||
|
* the whole stylesheet arrives as a string. The merged client entry imports
|
||||||
|
* `SETTINGS_CSS` and injects it through `ctx.effect` beside the vendored
|
||||||
|
* client's own `<style>` element. No other file may import the stylesheet.
|
||||||
|
*/
|
||||||
|
import css from './settings.css?inline'
|
||||||
|
|
||||||
|
export const SETTINGS_CSS: string = css
|
||||||
|
|
@ -0,0 +1,237 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — presentational atoms.
|
||||||
|
*
|
||||||
|
* Every atom here is stateless: drafts, busy flags, confirmations and results
|
||||||
|
* live in the root component (`index.tsx`), which keeps folding reversible and
|
||||||
|
* guarantees that a collapse/refresh can never drop typed input.
|
||||||
|
*
|
||||||
|
* The atoms only use native elements plus React; the sole UI primitive this
|
||||||
|
* face consumes is `Modal` (in `index.tsx`). Styling comes from
|
||||||
|
* `.rsui-*` classes in `settings.css` (DSH theme tokens, light/dark aware).
|
||||||
|
*/
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Icons (inline SVG — never emoji) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/** Disclosure chevron; the rotation is a restrained CSS transition. */
|
||||||
|
export function ChevronIcon({ open }: { open: boolean }) {
|
||||||
|
return (
|
||||||
|
<span className={`rsui-chevron${open ? ' rsui-chevron-open' : ''}`} aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||||
|
<path d="M4.5 6.25 8 9.75l3.5-3.5" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feedback glyph. Icons never carry the only error signal: every feedback
|
||||||
|
* block also renders a localized textual prefix (`common.error` /
|
||||||
|
* `common.warning`) so colour-blind users get the same information.
|
||||||
|
*/
|
||||||
|
export function StatusIcon({ status }: { status: 'success' | 'warning' | 'error' | 'info' }) {
|
||||||
|
if (status === 'success') {
|
||||||
|
return (
|
||||||
|
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||||
|
<circle cx="8" cy="8" r="6.25" />
|
||||||
|
<path d="m5 8.2 2.1 2.1L11.2 6" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (status === 'warning') {
|
||||||
|
return (
|
||||||
|
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||||
|
<path d="M8 2.4 14.4 13.6H1.6L8 2.4Z" />
|
||||||
|
<path d="M8 6.4v3.2" />
|
||||||
|
<circle cx="8" cy="11.6" r="0.6" fill="currentColor" stroke="none" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span className="rsui-feedback-icon" aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}>
|
||||||
|
<circle cx="8" cy="8" r="6.25" />
|
||||||
|
<path d="M8 4.6v4.2" />
|
||||||
|
<circle cx="8" cy="11.4" r="0.6" fill="currentColor" stroke="none" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Form controls */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export interface FieldProps {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
onBlur?: (() => void) | undefined
|
||||||
|
placeholder?: string | undefined
|
||||||
|
type?: 'text' | 'password' | undefined
|
||||||
|
autoComplete?: string | undefined
|
||||||
|
inputMode?: 'text' | 'numeric' | undefined
|
||||||
|
/** `data-rsui-field` hook consumed by preview/acceptance scripts. */
|
||||||
|
dataField?: string | undefined
|
||||||
|
hint?: string | undefined
|
||||||
|
error?: string | undefined
|
||||||
|
mono?: boolean | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Field({ id, label, value, onChange, onBlur, placeholder, type, autoComplete, inputMode, dataField, hint, error, mono }: FieldProps) {
|
||||||
|
const errorId = `${id}-error`
|
||||||
|
const hintId = `${id}-hint`
|
||||||
|
const describedBy = [error ? errorId : null, hint ? hintId : null].filter(Boolean).join(' ') || undefined
|
||||||
|
return (
|
||||||
|
<div className="rsui-field">
|
||||||
|
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||||
|
<input
|
||||||
|
id={id}
|
||||||
|
className={`rsui-input${mono ? ' rsui-input-mono' : ''}${error ? ' rsui-input-invalid' : ''}`}
|
||||||
|
type={type ?? 'text'}
|
||||||
|
value={value}
|
||||||
|
placeholder={placeholder}
|
||||||
|
autoComplete={autoComplete}
|
||||||
|
inputMode={inputMode}
|
||||||
|
data-rsui-field={dataField}
|
||||||
|
aria-invalid={error ? true : undefined}
|
||||||
|
aria-describedby={describedBy}
|
||||||
|
onChange={event => onChange(event.currentTarget.value)}
|
||||||
|
onBlur={onBlur === undefined ? undefined : () => onBlur()}
|
||||||
|
/>
|
||||||
|
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||||
|
{error ? <p className="rsui-error-text" id={errorId}>{error}</p> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TextAreaFieldProps {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
onChange: (value: string) => void
|
||||||
|
placeholder?: string | undefined
|
||||||
|
dataField?: string | undefined
|
||||||
|
hint?: string | undefined
|
||||||
|
rows?: number | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TextAreaField({ id, label, value, onChange, placeholder, dataField, hint, rows }: TextAreaFieldProps) {
|
||||||
|
const hintId = `${id}-hint`
|
||||||
|
return (
|
||||||
|
<div className="rsui-field">
|
||||||
|
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||||
|
<textarea
|
||||||
|
id={id}
|
||||||
|
className="rsui-textarea"
|
||||||
|
value={value}
|
||||||
|
rows={rows ?? 2}
|
||||||
|
placeholder={placeholder}
|
||||||
|
data-rsui-field={dataField}
|
||||||
|
aria-describedby={hint ? hintId : undefined}
|
||||||
|
onChange={event => onChange(event.currentTarget.value)}
|
||||||
|
/>
|
||||||
|
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CheckFieldProps {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
checked: boolean
|
||||||
|
onChange: (checked: boolean) => void
|
||||||
|
dataField?: string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CheckField({ id, label, checked, onChange, dataField }: CheckFieldProps) {
|
||||||
|
return (
|
||||||
|
<div className="rsui-check">
|
||||||
|
<input
|
||||||
|
id={id}
|
||||||
|
className="rsui-check-input"
|
||||||
|
type="checkbox"
|
||||||
|
checked={checked}
|
||||||
|
data-rsui-field={dataField}
|
||||||
|
onChange={event => onChange(event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
<label className="rsui-check-label" htmlFor={id}>{label}</label>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SelectFieldProps {
|
||||||
|
id: string
|
||||||
|
label: string
|
||||||
|
value: string
|
||||||
|
options: ReadonlyArray<{ value: string; label: string }>
|
||||||
|
onChange: (value: string) => void
|
||||||
|
dataField?: string | undefined
|
||||||
|
hint?: string | undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SelectField({ id, label, value, options, onChange, dataField, hint }: SelectFieldProps) {
|
||||||
|
const hintId = `${id}-hint`
|
||||||
|
return (
|
||||||
|
<div className="rsui-field">
|
||||||
|
<label className="rsui-label" htmlFor={id}>{label}</label>
|
||||||
|
<select
|
||||||
|
id={id}
|
||||||
|
className="rsui-select"
|
||||||
|
value={value}
|
||||||
|
data-rsui-field={dataField}
|
||||||
|
aria-describedby={hint ? hintId : undefined}
|
||||||
|
onChange={event => onChange(event.currentTarget.value)}
|
||||||
|
>
|
||||||
|
{options.map(option => (
|
||||||
|
<option key={option.value} value={option.value}>{option.label}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{hint ? <p className="rsui-hint" id={hintId}>{hint}</p> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Feedback blocks */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
export type NoticeTone = 'success' | 'warning' | 'error' | 'info'
|
||||||
|
|
||||||
|
export interface NoticeProps {
|
||||||
|
tone?: NoticeTone | undefined
|
||||||
|
title: string
|
||||||
|
/** Localized textual prefix, e.g. `common.error` / `common.warning`. */
|
||||||
|
prefix?: string | undefined
|
||||||
|
detail?: string | undefined
|
||||||
|
action?: ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generic status/alert block. `role` follows the tone (`alert` for errors,
|
||||||
|
* `status` otherwise) so screen readers announce failures without relying on
|
||||||
|
* the red colour alone.
|
||||||
|
*/
|
||||||
|
export function Notice({ tone, title, prefix, detail, action }: NoticeProps) {
|
||||||
|
const kind = tone ?? 'info'
|
||||||
|
return (
|
||||||
|
<div className={`rsui-feedback rsui-feedback-${kind}`} role={kind === 'error' ? 'alert' : 'status'}>
|
||||||
|
<StatusIcon status={kind} />
|
||||||
|
<div className="rsui-feedback-body">
|
||||||
|
<div className="rsui-feedback-title">
|
||||||
|
{prefix ? <span className="rsui-feedback-prefix">{prefix}</span> : null}
|
||||||
|
<span>{title}</span>
|
||||||
|
</div>
|
||||||
|
{detail ? <pre className="rsui-feedback-pre">{detail}</pre> : null}
|
||||||
|
{action ? <div className="rsui-feedback-actions">{action}</div> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,742 @@
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — pure-model behaviour.
|
||||||
|
*
|
||||||
|
* These tests pin the real semantics the new settings face relies on:
|
||||||
|
* the exact Host payloads, per-item import outcomes (never "selected size"
|
||||||
|
* reported as success), GiB/bytes conversion with the empty = Host-default
|
||||||
|
* convention, unsaved-draft reconciliation, and the connection-test verdict
|
||||||
|
* that keeps a successful probe with a warning as a warning.
|
||||||
|
*/
|
||||||
|
import { describe, expect, it, vi } from 'vitest'
|
||||||
|
import type { GuardDraft, ImportSummary, PrefsDraft } from '../src/client/rssh-settings/model.ts'
|
||||||
|
import type { RemoteSshWorkspace, SshConfigHost } from '../src/client/rssh-settings/contract.ts'
|
||||||
|
import {
|
||||||
|
apiErrorMessage,
|
||||||
|
bytesToGibText,
|
||||||
|
connectionTestView,
|
||||||
|
countSelected,
|
||||||
|
emptyConnectionForm,
|
||||||
|
gibTextToBytes,
|
||||||
|
guardDraftFromWorkspace,
|
||||||
|
guardDraftSignature,
|
||||||
|
guardsFromWorkspaces,
|
||||||
|
importHostKey,
|
||||||
|
importProfilePayload,
|
||||||
|
isConnectionFormValid,
|
||||||
|
isGuardDraftDirty,
|
||||||
|
isPrefsDraftDirty,
|
||||||
|
mergeImportRetry,
|
||||||
|
prefsDraftFromApi,
|
||||||
|
reconcileGuards,
|
||||||
|
reconcilePrefs,
|
||||||
|
runImport,
|
||||||
|
selectAllHosts,
|
||||||
|
selectedHosts,
|
||||||
|
splitList,
|
||||||
|
toSavePrefsPayload,
|
||||||
|
toSaveProfilePayload,
|
||||||
|
toUpdateWorkspaceGuardsPayload,
|
||||||
|
toggleHostSelection,
|
||||||
|
validateConnectionForm,
|
||||||
|
} from '../src/client/rssh-settings/model.ts'
|
||||||
|
import type { SaveProfilePayload } from '../src/client/rssh-settings/contract.ts'
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Fixtures */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const HOSTS: SshConfigHost[] = [
|
||||||
|
{
|
||||||
|
name: 'alpha',
|
||||||
|
hostName: 'alpha.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'alice',
|
||||||
|
identityFile: '~/.ssh/alpha',
|
||||||
|
proxyJump: 'bastion.example.com',
|
||||||
|
},
|
||||||
|
{ name: 'beta', hostName: 'beta.example.com', user: 'bob' },
|
||||||
|
{ name: 'gamma', hostName: 'gamma.example.com' },
|
||||||
|
]
|
||||||
|
|
||||||
|
function hostSummary(hosts: SshConfigHost[]): string[] {
|
||||||
|
return hosts.map(importHostKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSaveProfile(
|
||||||
|
results: Array<{ ok?: boolean; error?: string } | null | undefined | Error>,
|
||||||
|
) {
|
||||||
|
return vi.fn(async (_payload: SaveProfilePayload) => {
|
||||||
|
const next = results.shift()
|
||||||
|
if (next instanceof Error) throw next
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const WS: RemoteSshWorkspace = {
|
||||||
|
id: 'ws-1',
|
||||||
|
profileId: 'p-1',
|
||||||
|
title: 'Alpha',
|
||||||
|
remotePath: '~/project',
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: ['_patch/', '*.log'],
|
||||||
|
syncPaths: ['.dsh'],
|
||||||
|
syncExclude: ['data/'],
|
||||||
|
syncMaxBytes: 2147483648,
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Connection form → saveProfile payload */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('connection form validation and saveProfile payload', () => {
|
||||||
|
it('accepts the default form: empty keyPath is legal (ssh-agent / ~/.ssh/config)', () => {
|
||||||
|
const form = emptyConnectionForm()
|
||||||
|
form.host = 'login.example.com'
|
||||||
|
form.user = 'alice'
|
||||||
|
expect(validateConnectionForm(form)).toEqual([])
|
||||||
|
expect(isConnectionFormValid(form)).toBe(true)
|
||||||
|
|
||||||
|
const payload = toSaveProfilePayload(form)
|
||||||
|
expect(payload.keyPath).toBe('')
|
||||||
|
expect(payload.port).toBe(22)
|
||||||
|
expect(payload.authMethod).toBe('key')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('rejects an invalid port instead of silently falling back to 22', () => {
|
||||||
|
for (const port of ['', 'abc', '0', '65536', '-1', '22.5', '22abc']) {
|
||||||
|
const form = { ...emptyConnectionForm(), host: 'h', user: 'u', port }
|
||||||
|
const issues = validateConnectionForm(form)
|
||||||
|
expect(issues, `port=${JSON.stringify(port)}`).toContainEqual({
|
||||||
|
field: 'port',
|
||||||
|
messageKey: 'add.errPort',
|
||||||
|
})
|
||||||
|
expect(isConnectionFormValid(form), `port=${JSON.stringify(port)}`).toBe(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
const form = { ...emptyConnectionForm(), host: 'h', user: 'u', port: ' 22 ' }
|
||||||
|
expect(validateConnectionForm(form)).toEqual([])
|
||||||
|
expect(toSaveProfilePayload(form).port).toBe(22)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports host and user as required, together with the port issue', () => {
|
||||||
|
const form = { ...emptyConnectionForm(), host: ' ', user: '', port: 'x' }
|
||||||
|
expect(validateConnectionForm(form)).toEqual([
|
||||||
|
{ field: 'host', messageKey: 'add.errHost' },
|
||||||
|
{ field: 'user', messageKey: 'add.errUser' },
|
||||||
|
{ field: 'port', messageKey: 'add.errPort' },
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps both draft fields across key/password auth switching (same form state)', () => {
|
||||||
|
const keyForm = {
|
||||||
|
...emptyConnectionForm(),
|
||||||
|
host: 'h',
|
||||||
|
user: 'u',
|
||||||
|
authMethod: 'key' as const,
|
||||||
|
keyPath: '~/.ssh/id_ed25519',
|
||||||
|
password: 'hunter2',
|
||||||
|
}
|
||||||
|
const keyPayload = toSaveProfilePayload(keyForm)
|
||||||
|
expect(keyPayload.authMethod).toBe('key')
|
||||||
|
expect(keyPayload.keyPath).toBe('~/.ssh/id_ed25519')
|
||||||
|
expect(keyPayload.password).toBe('hunter2')
|
||||||
|
|
||||||
|
const passwordForm = { ...keyForm, authMethod: 'password' as const }
|
||||||
|
const passwordPayload = toSaveProfilePayload(passwordForm)
|
||||||
|
expect(passwordPayload.authMethod).toBe('password')
|
||||||
|
expect(passwordPayload.keyPath).toBe('~/.ssh/id_ed25519')
|
||||||
|
expect(passwordPayload.password).toBe('hunter2')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('carries every saveProfile field, including proxyJump and a real numeric port', () => {
|
||||||
|
const form = {
|
||||||
|
name: 'HPC',
|
||||||
|
host: 'login.example.com',
|
||||||
|
port: '2222',
|
||||||
|
user: 'alice',
|
||||||
|
authMethod: 'password' as const,
|
||||||
|
keyPath: '',
|
||||||
|
password: 'secret',
|
||||||
|
remoteRoot: '~/project',
|
||||||
|
proxyJump: 'bastion.example.com:22',
|
||||||
|
}
|
||||||
|
expect(toSaveProfilePayload(form)).toEqual({
|
||||||
|
name: 'HPC',
|
||||||
|
host: 'login.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'alice',
|
||||||
|
authMethod: 'password',
|
||||||
|
keyPath: '',
|
||||||
|
password: 'secret',
|
||||||
|
remoteRoot: '~/project',
|
||||||
|
proxyJump: 'bastion.example.com:22',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* SSH config import */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('SSH config import — per-item outcomes', () => {
|
||||||
|
it('maps a discovered host to the exact saveProfile payload (incl. proxyJump)', () => {
|
||||||
|
expect(importProfilePayload(HOSTS[0] as SshConfigHost)).toEqual({
|
||||||
|
name: 'alpha',
|
||||||
|
host: 'alpha.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'alice',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: '~/.ssh/alpha',
|
||||||
|
password: '',
|
||||||
|
remoteRoot: '~',
|
||||||
|
proxyJump: 'bastion.example.com',
|
||||||
|
})
|
||||||
|
expect(importProfilePayload(HOSTS[2] as SshConfigHost)).toMatchObject({
|
||||||
|
port: 22,
|
||||||
|
user: '',
|
||||||
|
keyPath: '',
|
||||||
|
proxyJump: '',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('counts every success only when every save resolves ok', async () => {
|
||||||
|
const save = makeSaveProfile([{ ok: true }, { ok: true }, { ok: true }])
|
||||||
|
const summary = await runImport(HOSTS, save)
|
||||||
|
|
||||||
|
expect(save).toHaveBeenCalledTimes(3)
|
||||||
|
expect(save.mock.calls.map(call => call[0].name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||||
|
expect(summary.okCount).toBe(3)
|
||||||
|
expect(summary.failCount).toBe(0)
|
||||||
|
expect(summary.failedHosts).toEqual([])
|
||||||
|
expect(summary.outcomes.every(outcome => outcome.ok)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports real partial failures (ok:false + error text), never the selection size', async () => {
|
||||||
|
const save = makeSaveProfile([
|
||||||
|
{ ok: true },
|
||||||
|
{ ok: false, error: ' duplicate host ' },
|
||||||
|
{ ok: false, error: 'boom' },
|
||||||
|
])
|
||||||
|
const summary = await runImport(HOSTS, save)
|
||||||
|
|
||||||
|
expect(summary.okCount).toBe(1)
|
||||||
|
expect(summary.failCount).toBe(2)
|
||||||
|
expect(summary.outcomes.map(outcome => outcome.ok)).toEqual([true, false, false])
|
||||||
|
expect(summary.outcomes[1]?.error).toBe('duplicate host')
|
||||||
|
expect(summary.outcomes[2]?.error).toBe('boom')
|
||||||
|
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary([HOSTS[1]!, HOSTS[2]!]))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports every failure when all saves fail', async () => {
|
||||||
|
const save = makeSaveProfile([
|
||||||
|
{ ok: false, error: 'one' },
|
||||||
|
{ ok: false, error: 'two' },
|
||||||
|
{ ok: false, error: 'three' },
|
||||||
|
])
|
||||||
|
const summary = await runImport(HOSTS, save)
|
||||||
|
|
||||||
|
expect(summary.okCount).toBe(0)
|
||||||
|
expect(summary.failCount).toBe(3)
|
||||||
|
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary(HOSTS))
|
||||||
|
expect(summary.outcomes.map(outcome => outcome.error)).toEqual(['one', 'two', 'three'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('turns thrown request errors into failures with the thrown message', async () => {
|
||||||
|
const save = makeSaveProfile([{ ok: true }, new Error('network down'), { ok: false, error: 'denied' }])
|
||||||
|
const summary = await runImport(HOSTS, save)
|
||||||
|
|
||||||
|
expect(summary.okCount).toBe(1)
|
||||||
|
expect(summary.failCount).toBe(2)
|
||||||
|
expect(summary.outcomes[1]?.ok).toBe(false)
|
||||||
|
expect(summary.outcomes[1]?.error).toBe('network down')
|
||||||
|
expect(hostSummary(summary.failedHosts)).toEqual(hostSummary([HOSTS[1]!, HOSTS[2]!]))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats an undefined/null save result as failure (no-result), never as imported', async () => {
|
||||||
|
const save = makeSaveProfile([undefined, null])
|
||||||
|
const summary = await runImport(HOSTS.slice(0, 2), save)
|
||||||
|
|
||||||
|
expect(save).toHaveBeenCalledTimes(2)
|
||||||
|
expect(summary.okCount).toBe(0)
|
||||||
|
expect(summary.failCount).toBe(2)
|
||||||
|
expect(summary.outcomes.map(outcome => outcome.ok)).toEqual([false, false])
|
||||||
|
expect(summary.outcomes.map(outcome => outcome.errorCode)).toEqual(['no-result', 'no-result'])
|
||||||
|
expect(summary.outcomes.every(outcome => outcome.error === undefined)).toBe(true)
|
||||||
|
expect(summary.failedHosts).toHaveLength(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats ok:false without error text as a failure too', async () => {
|
||||||
|
const summary = await runImport([HOSTS[1] as SshConfigHost], makeSaveProfile([{ ok: false }]))
|
||||||
|
expect(summary.okCount).toBe(0)
|
||||||
|
expect(summary.failCount).toBe(1)
|
||||||
|
expect(summary.outcomes[0]?.errorCode).toBe('no-result')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an empty selection imports nothing and calls no endpoint', async () => {
|
||||||
|
const save = makeSaveProfile([])
|
||||||
|
const summary = await runImport([], save)
|
||||||
|
expect(save).not.toHaveBeenCalled()
|
||||||
|
expect(summary).toEqual({ outcomes: [], okCount: 0, failCount: 0, failedHosts: [] })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reports progress per host only through the injected callback', async () => {
|
||||||
|
const progress: string[] = []
|
||||||
|
const summary = await runImport(HOSTS.slice(0, 2), makeSaveProfile([{ ok: true }, { ok: false }]), {
|
||||||
|
onProgress: (done, total, host) => progress.push(`${done}/${total}:${host.name}`),
|
||||||
|
})
|
||||||
|
expect(progress).toEqual(['0/2:alpha', '1/2:beta', '2/2:beta'])
|
||||||
|
expect(summary.failCount).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('failed-only retry merge', () => {
|
||||||
|
it('does not resubmit successful items and keeps their success count', async () => {
|
||||||
|
const firstSave = makeSaveProfile([{ ok: true }, { ok: false, error: 'timeout' }, { ok: false, error: 'x' }])
|
||||||
|
const first = await runImport(HOSTS, firstSave)
|
||||||
|
|
||||||
|
const retrySave = makeSaveProfile([{ ok: true }, { ok: true }])
|
||||||
|
const retry = await runImport(first.failedHosts, retrySave)
|
||||||
|
|
||||||
|
expect(retrySave).toHaveBeenCalledTimes(2)
|
||||||
|
expect(retrySave.mock.calls.map(call => call[0].name)).toEqual(['beta', 'gamma'])
|
||||||
|
expect(firstSave).toHaveBeenCalledTimes(3)
|
||||||
|
expect(firstSave.mock.calls.map(call => call[0].name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||||
|
|
||||||
|
const merged = mergeImportRetry(first, retry)
|
||||||
|
expect(merged.okCount).toBe(3)
|
||||||
|
expect(merged.failCount).toBe(0)
|
||||||
|
expect(merged.failedHosts).toEqual([])
|
||||||
|
expect(merged.outcomes).toHaveLength(3)
|
||||||
|
expect(merged.outcomes.every(outcome => outcome.ok)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps a still-failing retry item as failed with its retry reason', async () => {
|
||||||
|
const first = await runImport(
|
||||||
|
HOSTS,
|
||||||
|
makeSaveProfile([{ ok: true }, { ok: false, error: 'timeout' }, { ok: false, error: 'nope' }]),
|
||||||
|
)
|
||||||
|
const retry = await runImport(first.failedHosts, makeSaveProfile([{ ok: false, error: 'still bad' }, { ok: true }]))
|
||||||
|
|
||||||
|
const merged = mergeImportRetry(first, retry)
|
||||||
|
expect(merged.okCount).toBe(2)
|
||||||
|
expect(merged.failCount).toBe(1)
|
||||||
|
expect(hostSummary(merged.failedHosts)).toEqual(hostSummary([HOSTS[1] as SshConfigHost]))
|
||||||
|
expect(merged.outcomes).toHaveLength(3)
|
||||||
|
expect(merged.outcomes.filter(outcome => !outcome.ok)[0]?.error).toBe('still bad')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a fully failed retry keeps the merged summary fully failed', () => {
|
||||||
|
const previous: ImportSummary = {
|
||||||
|
outcomes: [
|
||||||
|
{ key: 'a|h', name: 'a', hostName: 'h', ok: false, error: 'first' },
|
||||||
|
{ key: 'b|h2', name: 'b', hostName: 'h2', ok: false, error: 'second' },
|
||||||
|
],
|
||||||
|
okCount: 0,
|
||||||
|
failCount: 2,
|
||||||
|
failedHosts: [HOSTS[0] as SshConfigHost, HOSTS[1] as SshConfigHost],
|
||||||
|
}
|
||||||
|
const retry: ImportSummary = {
|
||||||
|
outcomes: [
|
||||||
|
{ key: 'a|h', name: 'a', hostName: 'h', ok: false, errorCode: 'no-result' },
|
||||||
|
{ key: 'b|h2', name: 'b', hostName: 'h2', ok: false, error: 'second' },
|
||||||
|
],
|
||||||
|
okCount: 0,
|
||||||
|
failCount: 2,
|
||||||
|
failedHosts: [HOSTS[0] as SshConfigHost, HOSTS[1] as SshConfigHost],
|
||||||
|
}
|
||||||
|
const merged = mergeImportRetry(previous, retry)
|
||||||
|
expect(merged.okCount).toBe(0)
|
||||||
|
expect(merged.failCount).toBe(2)
|
||||||
|
expect(merged.failedHosts).toHaveLength(2)
|
||||||
|
expect(merged.outcomes.every(outcome => !outcome.ok)).toBe(true)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('host selection', () => {
|
||||||
|
it('selects nothing when every row is unchecked', () => {
|
||||||
|
const selected = { [importHostKey(HOSTS[0]!)]: false, [importHostKey(HOSTS[1]!)]: false }
|
||||||
|
expect(selectedHosts(HOSTS, selected)).toEqual([])
|
||||||
|
expect(countSelected(selected)).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('selects all discovered hosts by default and counts only checked rows', () => {
|
||||||
|
const selected = selectAllHosts(HOSTS)
|
||||||
|
expect(countSelected(selected)).toBe(3)
|
||||||
|
expect(hostSummary(selectedHosts(HOSTS, selected))).toEqual(hostSummary(HOSTS))
|
||||||
|
|
||||||
|
const toggled = toggleHostSelection(selected, importHostKey(HOSTS[1]!))
|
||||||
|
expect(toggled[importHostKey(HOSTS[1]!)]).toBe(false)
|
||||||
|
expect(countSelected(toggled)).toBe(2)
|
||||||
|
expect(hostSummary(selectedHosts(HOSTS, toggled))).toEqual(
|
||||||
|
hostSummary([HOSTS[0] as SshConfigHost, HOSTS[2] as SshConfigHost]),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats an empty selection map as no selection', () => {
|
||||||
|
expect(selectedHosts(HOSTS, {})).toEqual([])
|
||||||
|
expect(countSelected({})).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* GiB ↔ bytes */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('sync size unit conversion and empty-value semantics', () => {
|
||||||
|
it('bytesToGibText: empty input means "use the Host default"', () => {
|
||||||
|
expect(bytesToGibText(0)).toBe('')
|
||||||
|
expect(bytesToGibText(0)).toBe('')
|
||||||
|
expect(bytesToGibText(null)).toBe('')
|
||||||
|
expect(bytesToGibText(undefined)).toBe('')
|
||||||
|
expect(bytesToGibText(Number.NaN)).toBe('')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('bytesToGibText: tiny byte counts collapse to "0", GiB values round to 2 decimals', () => {
|
||||||
|
expect(bytesToGibText(2)).toBe('0')
|
||||||
|
expect(bytesToGibText(1073741824)).toBe('1')
|
||||||
|
expect(bytesToGibText(2 * 1073741824)).toBe('2')
|
||||||
|
expect(bytesToGibText(1.5 * 1073741824)).toBe('1.5')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gibTextToBytes: empty / zero / invalid all mean 0 (Host default)', () => {
|
||||||
|
expect(gibTextToBytes('')).toBe(0)
|
||||||
|
expect(gibTextToBytes('0')).toBe(0)
|
||||||
|
expect(gibTextToBytes('0.0')).toBe(0)
|
||||||
|
expect(gibTextToBytes('abc')).toBe(0)
|
||||||
|
expect(gibTextToBytes(null)).toBe(0)
|
||||||
|
expect(gibTextToBytes(undefined)).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('gibTextToBytes: "2" and "2.0" both mean 2 GiB = 2147483648 bytes', () => {
|
||||||
|
expect(gibTextToBytes(2)).toBe(2147483648)
|
||||||
|
expect(gibTextToBytes('2')).toBe(2147483648)
|
||||||
|
expect(gibTextToBytes('2.0')).toBe(2147483648)
|
||||||
|
expect(gibTextToBytes('2.5')).toBe(2684354560)
|
||||||
|
expect(gibTextToBytes('2 GiB')).toBe(2147483648)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('round-trips the default 2 GiB cap', () => {
|
||||||
|
expect(gibTextToBytes(bytesToGibText(2147483648))).toBe(2147483648)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('list splitting', () => {
|
||||||
|
it('accepts commas, newlines and semicolons, trimming and dropping empty entries', () => {
|
||||||
|
expect(splitList('a, b\nc; d')).toEqual(['a', 'b', 'c', 'd'])
|
||||||
|
expect(splitList('a,, b, ,\n')).toEqual(['a', 'b'])
|
||||||
|
expect(splitList('')).toEqual([])
|
||||||
|
expect(splitList(null)).toEqual([])
|
||||||
|
expect(splitList(undefined)).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Workspace guard drafts */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('workspace guard drafts', () => {
|
||||||
|
it('builds a draft from a persisted record (defaults match the Host)', () => {
|
||||||
|
expect(guardDraftFromWorkspace(WS)).toEqual({
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: '_patch/, *.log',
|
||||||
|
syncPaths: '.dsh',
|
||||||
|
syncExclude: 'data/',
|
||||||
|
syncMaxBytes: '2',
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(guardDraftFromWorkspace({ id: 'w2', profileId: 'p' })).toEqual({
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: '',
|
||||||
|
syncPaths: '',
|
||||||
|
syncExclude: '',
|
||||||
|
syncMaxBytes: '',
|
||||||
|
})
|
||||||
|
expect(guardDraftFromWorkspace({ id: 'w3', profileId: 'p', writeBack: false })).toMatchObject({
|
||||||
|
writeBack: false,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not call formatting-only differences dirty', () => {
|
||||||
|
const baseline = guardDraftFromWorkspace(WS)
|
||||||
|
expect(isGuardDraftDirty(baseline, baseline)).toBe(false)
|
||||||
|
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, writeBackExclude: '_patch/,\n*.log' }, baseline)).toBe(false)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncPaths: ' .dsh ' }, baseline)).toBe(false)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '2.0' }, baseline)).toBe(false)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: ' 2 ' }, baseline)).toBe(false)
|
||||||
|
expect(guardDraftSignature({ ...baseline, syncMaxBytes: '2.0' })).toBe(guardDraftSignature(baseline))
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks real edits dirty', () => {
|
||||||
|
const baseline = guardDraftFromWorkspace(WS)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, writeBackExclude: '_patch/, *.log, tmp/' }, baseline)).toBe(true)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncPaths: '.dsh, ..' }, baseline)).toBe(true)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, writeBack: false }, baseline)).toBe(true)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '3' }, baseline)).toBe(true)
|
||||||
|
expect(isGuardDraftDirty({ ...baseline, syncMaxBytes: '' }, baseline)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('produces the exact updateWorkspaceGuards payload for the target workspace id', () => {
|
||||||
|
const draft: GuardDraft = {
|
||||||
|
writeBack: false,
|
||||||
|
writeBackExclude: '_patch/, *.log',
|
||||||
|
syncPaths: '.dsh\nsrc',
|
||||||
|
syncExclude: 'data/, *.tmp',
|
||||||
|
syncMaxBytes: '2',
|
||||||
|
}
|
||||||
|
expect(toUpdateWorkspaceGuardsPayload('ws-1', draft)).toEqual({
|
||||||
|
id: 'ws-1',
|
||||||
|
writeBack: false,
|
||||||
|
writeBackExclude: ['_patch/', '*.log'],
|
||||||
|
syncPaths: ['.dsh', 'src'],
|
||||||
|
syncExclude: ['data/', '*.tmp'],
|
||||||
|
syncMaxBytes: 2147483648,
|
||||||
|
})
|
||||||
|
expect(toUpdateWorkspaceGuardsPayload('ws-1', { ...draft, syncMaxBytes: '' }).syncMaxBytes).toBe(0)
|
||||||
|
expect(toUpdateWorkspaceGuardsPayload('ws-1', { ...draft, syncMaxBytes: '2.0' }).syncMaxBytes).toBe(2147483648)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('reconcileGuards', () => {
|
||||||
|
it('keeps a dirty draft across an unrelated reload and moves its baseline to server truth', () => {
|
||||||
|
const previousDrafts = guardsFromWorkspaces([WS])
|
||||||
|
const previousBaselines = guardsFromWorkspaces([WS])
|
||||||
|
const dirtyDraft: GuardDraft = { ...previousDrafts['ws-1']!, writeBackExclude: '_patch/, *.log, tmp/' }
|
||||||
|
previousDrafts['ws-1'] = dirtyDraft
|
||||||
|
|
||||||
|
const serverWorkspace: RemoteSshWorkspace = { ...WS, writeBackExclude: ['server/'] }
|
||||||
|
const result = reconcileGuards(previousDrafts, previousBaselines, [serverWorkspace])
|
||||||
|
|
||||||
|
expect(result.drafts['ws-1']).toBe(dirtyDraft)
|
||||||
|
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||||
|
expect(isGuardDraftDirty(result.drafts['ws-1']!, result.baselines['ws-1']!)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('adopts server truth for a clean draft', () => {
|
||||||
|
const previousDrafts = guardsFromWorkspaces([WS])
|
||||||
|
const previousBaselines = guardsFromWorkspaces([WS])
|
||||||
|
const serverWorkspace: RemoteSshWorkspace = { ...WS, writeBack: false, syncPaths: [] }
|
||||||
|
const result = reconcileGuards(previousDrafts, previousBaselines, [serverWorkspace])
|
||||||
|
|
||||||
|
expect(result.drafts['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||||
|
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(serverWorkspace))
|
||||||
|
expect(isGuardDraftDirty(result.drafts['ws-1']!, result.baselines['ws-1']!)).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('drops drafts and baselines for records deleted on the Host', () => {
|
||||||
|
const previousDrafts = guardsFromWorkspaces([WS, { id: 'ws-2', profileId: 'p-2' }])
|
||||||
|
const previousBaselines = guardsFromWorkspaces([WS, { id: 'ws-2', profileId: 'p-2' }])
|
||||||
|
const result = reconcileGuards(previousDrafts, previousBaselines, [WS])
|
||||||
|
|
||||||
|
expect(Object.keys(result.drafts)).toEqual(['ws-1'])
|
||||||
|
expect(Object.keys(result.baselines)).toEqual(['ws-1'])
|
||||||
|
expect(result.drafts['ws-2']).toBeUndefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('treats a draft without a previous baseline as dirty so a refresh cannot wipe typed text', () => {
|
||||||
|
const typed: GuardDraft = {
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: 'tmp/',
|
||||||
|
syncPaths: '',
|
||||||
|
syncExclude: '',
|
||||||
|
syncMaxBytes: '',
|
||||||
|
}
|
||||||
|
const result = reconcileGuards({ 'ws-1': typed }, {}, [WS])
|
||||||
|
expect(result.drafts['ws-1']).toEqual(typed)
|
||||||
|
expect(result.baselines['ws-1']).toEqual(guardDraftFromWorkspace(WS))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Global preferences */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const PREFS: PrefsDraft = {
|
||||||
|
nodePath: '/usr/local/bin/node',
|
||||||
|
writeBackFailure: 'log',
|
||||||
|
writeBackFreshness: false,
|
||||||
|
defaultSyncPaths: '.dsh, src',
|
||||||
|
defaultSyncExclude: 'data/',
|
||||||
|
defaultSyncMaxBytes: '2',
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('global preferences draft', () => {
|
||||||
|
it('projects Host preferences with the upstream defaults', () => {
|
||||||
|
expect(prefsDraftFromApi({})).toEqual({
|
||||||
|
nodePath: '',
|
||||||
|
writeBackFailure: 'error',
|
||||||
|
writeBackFreshness: true,
|
||||||
|
defaultSyncPaths: '',
|
||||||
|
defaultSyncExclude: '',
|
||||||
|
defaultSyncMaxBytes: '',
|
||||||
|
})
|
||||||
|
expect(prefsDraftFromApi({ nodePath: '/opt/node', writeBackFailure: 'log', writeBackFreshness: false, defaultSyncPaths: ['a', 'b'], defaultSyncMaxBytes: 2147483648 })).toEqual({
|
||||||
|
nodePath: '/opt/node',
|
||||||
|
writeBackFailure: 'log',
|
||||||
|
writeBackFreshness: false,
|
||||||
|
defaultSyncPaths: 'a, b',
|
||||||
|
defaultSyncExclude: '',
|
||||||
|
defaultSyncMaxBytes: '2',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('does not call formatting-only differences dirty', () => {
|
||||||
|
expect(isPrefsDraftDirty(PREFS, PREFS)).toBe(false)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncPaths: '.dsh\nsrc' }, PREFS)).toBe(false)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncMaxBytes: '2.0' }, PREFS)).toBe(false)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, nodePath: ' /usr/local/bin/node ' }, PREFS)).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('marks real edits dirty', () => {
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncPaths: '.dsh, src, tests' }, PREFS)).toBe(true)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, writeBackFailure: 'error' }, PREFS)).toBe(true)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, writeBackFreshness: true }, PREFS)).toBe(true)
|
||||||
|
expect(isPrefsDraftDirty({ ...PREFS, defaultSyncMaxBytes: '3' }, PREFS)).toBe(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('produces the exact savePrefs payload', () => {
|
||||||
|
expect(toSavePrefsPayload(PREFS)).toEqual({
|
||||||
|
nodePath: '/usr/local/bin/node',
|
||||||
|
writeBackFailure: 'log',
|
||||||
|
writeBackFreshness: false,
|
||||||
|
defaultSyncPaths: ['.dsh', 'src'],
|
||||||
|
defaultSyncExclude: ['data/'],
|
||||||
|
defaultSyncMaxBytes: 2147483648,
|
||||||
|
})
|
||||||
|
expect(toSavePrefsPayload({ ...PREFS, nodePath: ' ', defaultSyncMaxBytes: '' })).toMatchObject({
|
||||||
|
nodePath: '',
|
||||||
|
defaultSyncMaxBytes: 0,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps an unsaved preferences draft on refresh and adopts server truth for a clean one', () => {
|
||||||
|
const serverDraft: PrefsDraft = { ...PREFS, nodePath: '/server/node' }
|
||||||
|
const dirty: PrefsDraft = { ...PREFS, nodePath: '/typed/node' }
|
||||||
|
|
||||||
|
const kept = reconcilePrefs(dirty, PREFS, serverDraft)
|
||||||
|
expect(kept.draft).toEqual(dirty)
|
||||||
|
expect(kept.baseline).toEqual(serverDraft)
|
||||||
|
|
||||||
|
const clean = reconcilePrefs(PREFS, PREFS, serverDraft)
|
||||||
|
expect(clean.draft).toEqual(serverDraft)
|
||||||
|
expect(clean.baseline).toEqual(serverDraft)
|
||||||
|
|
||||||
|
const firstLoad = reconcilePrefs(null, null, serverDraft)
|
||||||
|
expect(firstLoad.draft).toEqual(serverDraft)
|
||||||
|
expect(firstLoad.baseline).toEqual(serverDraft)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Guards ↔ prefs independence */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('workspace guards and global preferences never overwrite each other', () => {
|
||||||
|
it('their payload shapes stay disjoint', () => {
|
||||||
|
const guardsPayload = toUpdateWorkspaceGuardsPayload('ws-1', guardDraftFromWorkspace(WS))
|
||||||
|
const prefsPayload = toSavePrefsPayload(prefsDraftFromApi({ nodePath: '/node', defaultSyncPaths: ['a'] }))
|
||||||
|
|
||||||
|
expect(Object.keys(guardsPayload).sort()).toEqual(
|
||||||
|
['id', 'syncExclude', 'syncMaxBytes', 'syncPaths', 'writeBack', 'writeBackExclude'].sort(),
|
||||||
|
)
|
||||||
|
expect(Object.keys(prefsPayload).sort()).toEqual(
|
||||||
|
['defaultSyncExclude', 'defaultSyncMaxBytes', 'defaultSyncPaths', 'nodePath', 'writeBackFailure', 'writeBackFreshness'].sort(),
|
||||||
|
)
|
||||||
|
expect(guardsPayload).not.toHaveProperty('nodePath')
|
||||||
|
expect(guardsPayload).not.toHaveProperty('writeBackFailure')
|
||||||
|
expect(prefsPayload).not.toHaveProperty('id')
|
||||||
|
expect(prefsPayload).not.toHaveProperty('writeBack')
|
||||||
|
expect(prefsPayload).not.toHaveProperty('syncPaths')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('reconcileGuards and reconcilePrefs keep their own dirty drafts independently', () => {
|
||||||
|
const guards = guardsFromWorkspaces([WS])
|
||||||
|
const dirtyGuard: GuardDraft = { ...guards['ws-1']!, syncPaths: '.dsh, extra' }
|
||||||
|
const dirtyPrefs: PrefsDraft = { ...PREFS, nodePath: '/typed/node' }
|
||||||
|
|
||||||
|
const guardResult = reconcileGuards({ 'ws-1': dirtyGuard }, guards, [{ ...WS, syncPaths: ['server'] }])
|
||||||
|
const prefsResult = reconcilePrefs(dirtyPrefs, PREFS, { ...PREFS, nodePath: '/server/node' })
|
||||||
|
|
||||||
|
expect(guardResult.drafts['ws-1']).toEqual(dirtyGuard)
|
||||||
|
expect(prefsResult.draft).toEqual(dirtyPrefs)
|
||||||
|
// Never imported across the boundary: a guard draft has no prefs keys and vice versa.
|
||||||
|
expect(guardResult.drafts['ws-1']).not.toHaveProperty('nodePath')
|
||||||
|
expect(prefsResult.draft).not.toHaveProperty('syncMaxBytes')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a guard save baseline update does not touch the prefs draft', () => {
|
||||||
|
const before = toSavePrefsPayload(PREFS)
|
||||||
|
const result = reconcileGuards(guardsFromWorkspaces([WS]), guardsFromWorkspaces([WS]), [
|
||||||
|
{ ...WS, writeBackExclude: ['server/'] },
|
||||||
|
])
|
||||||
|
expect(result.drafts['ws-1']?.writeBackExclude).toBe('server/')
|
||||||
|
expect(toSavePrefsPayload(PREFS)).toEqual(before)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Connection test feedback */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('connectionTestView', () => {
|
||||||
|
it('plain success shows the success status and stdout detail', () => {
|
||||||
|
expect(connectionTestView({ ok: true, stdout: ' connected \n' })).toEqual({
|
||||||
|
status: 'success',
|
||||||
|
titleKey: 'connection.testOk',
|
||||||
|
warning: '',
|
||||||
|
detail: 'connected',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a successful probe carrying a warning stays a warning, never a plain success', () => {
|
||||||
|
const view = connectionTestView({ ok: true, warning: ' key path not found, using agent ', stdout: 'ok' })
|
||||||
|
expect(view.status).toBe('warning')
|
||||||
|
expect(view.titleKey).toBe('connection.testWarn')
|
||||||
|
expect(view.warning).toBe('key path not found, using agent')
|
||||||
|
expect(view.detail).toBe('ok')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('failure joins error and stderr into pre-wrap diagnostics', () => {
|
||||||
|
const view = connectionTestView({
|
||||||
|
ok: false,
|
||||||
|
error: 'connect failed',
|
||||||
|
stderr: 'ssh: Could not resolve hostname',
|
||||||
|
exitCode: 255,
|
||||||
|
})
|
||||||
|
expect(view).toEqual({
|
||||||
|
status: 'error',
|
||||||
|
titleKey: 'connection.testFail',
|
||||||
|
warning: '',
|
||||||
|
detail: 'connect failed\nssh: Could not resolve hostname',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('failure with only stderr, only error, or no envelope still yields the failure status', () => {
|
||||||
|
expect(connectionTestView({ ok: false, stderr: 'stderr only' }).detail).toBe('stderr only')
|
||||||
|
expect(connectionTestView({ ok: false, error: 'error only' }).detail).toBe('error only')
|
||||||
|
|
||||||
|
for (const empty of [undefined, null, {}, { ok: false }]) {
|
||||||
|
const view = connectionTestView(empty)
|
||||||
|
expect(view.status).toBe('error')
|
||||||
|
expect(view.titleKey).toBe('connection.testFail')
|
||||||
|
expect(view.detail).toBe('')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a failure that also carries a warning keeps both the failure status and the warning text', () => {
|
||||||
|
const view = connectionTestView({ ok: false, warning: 'identity ignored', error: 'denied' })
|
||||||
|
expect(view.status).toBe('error')
|
||||||
|
expect(view.warning).toBe('identity ignored')
|
||||||
|
expect(view.detail).toBe('denied')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('apiErrorMessage', () => {
|
||||||
|
it('trims the Host error and falls back when the envelope has none', () => {
|
||||||
|
expect(apiErrorMessage({ error: ' denied ' }, 'fallback')).toBe('denied')
|
||||||
|
expect(apiErrorMessage({ error: ' ' }, 'fallback')).toBe('fallback')
|
||||||
|
expect(apiErrorMessage({}, 'fallback')).toBe('fallback')
|
||||||
|
expect(apiErrorMessage(null, 'fallback')).toBe('fallback')
|
||||||
|
expect(apiErrorMessage({ error: 42 as unknown as string }, 'fallback')).toBe('fallback')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,714 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
|
/**
|
||||||
|
* Remote-SSH settings — rendered UI behaviour.
|
||||||
|
*
|
||||||
|
* These mount the real `createSettingsSection` component in jsdom with a fake
|
||||||
|
* `api` and a dictionary-backed `t`, then drive the DOM through the documented
|
||||||
|
* `data-rsui-*` hooks. They assert behaviour (drafts survive collapsing, the
|
||||||
|
* right workspace id is saved with GiB→bytes, dirty drafts block sync, failed
|
||||||
|
* imports are reported per host and can be retried alone) rather than styles.
|
||||||
|
*/
|
||||||
|
import React, { act } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
import { createRoot, type Root } from 'react-dom/client'
|
||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { createSettingsSection } from '../src/client/rssh-settings/index.tsx'
|
||||||
|
import { zh } from '../src/client/rssh-settings/i18n.ts'
|
||||||
|
import type {
|
||||||
|
RemoteSshApi,
|
||||||
|
RemoteSshPrefs,
|
||||||
|
RemoteSshProfile,
|
||||||
|
RemoteSshWorkspace,
|
||||||
|
SavePrefsPayload,
|
||||||
|
SaveProfilePayload,
|
||||||
|
SshConfigHost,
|
||||||
|
UpdateWorkspaceGuardsPayload,
|
||||||
|
SettingsTranslate,
|
||||||
|
} from '../src/client/rssh-settings/contract.ts'
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Primitive mock (the face only relies on Modal/Button from primitives) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({
|
||||||
|
Modal: (props: {
|
||||||
|
open?: boolean
|
||||||
|
title?: ReactNode
|
||||||
|
closeLabel?: string
|
||||||
|
className?: string
|
||||||
|
children?: ReactNode
|
||||||
|
footer?: ReactNode
|
||||||
|
[key: string]: unknown
|
||||||
|
}) => {
|
||||||
|
if (props.open === false) return null
|
||||||
|
const { open: _open, onClose: _onClose, title, closeLabel: _closeLabel, footer, ...rest } = props
|
||||||
|
const passThrough: Record<string, unknown> = {}
|
||||||
|
for (const [key, value] of Object.entries(rest)) {
|
||||||
|
if (key.startsWith('data-') || key === 'className' || key === 'role' || key === 'aria-label') {
|
||||||
|
passThrough[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return React.createElement(
|
||||||
|
'div',
|
||||||
|
passThrough as React.HTMLAttributes<HTMLDivElement>,
|
||||||
|
title ? React.createElement('div', null, title) : null,
|
||||||
|
props.children,
|
||||||
|
footer ? React.createElement('div', null, footer) : null,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
Button: (props: { children?: ReactNode; variant?: unknown; size?: unknown; [key: string]: unknown }) => {
|
||||||
|
const { children, variant: _variant, size: _size, ...rest } = props
|
||||||
|
return React.createElement('button', rest as React.ButtonHTMLAttributes<HTMLButtonElement>, children)
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
Object.assign(globalThis, { React, IS_REACT_ACT_ENVIRONMENT: true })
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Translation dictionary */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const ZH = zh as Record<string, string>
|
||||||
|
const t: SettingsTranslate = (key, params) => {
|
||||||
|
const template = ZH[key] ?? key
|
||||||
|
if (!params) return template
|
||||||
|
return template.replace(/\{(\w+)\}/g, (_match, name: string) => String(params[name] ?? ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Fixtures */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const PROFILE: RemoteSshProfile = {
|
||||||
|
id: 'p-1',
|
||||||
|
name: 'Alpha HPC',
|
||||||
|
host: 'alpha.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'alice',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: '~/.ssh/alpha',
|
||||||
|
remoteRoot: '~/project',
|
||||||
|
passwordConfigured: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
const WORKSPACES: RemoteSshWorkspace[] = [
|
||||||
|
{
|
||||||
|
id: 'ws-a',
|
||||||
|
profileId: 'p-1',
|
||||||
|
title: 'Alpha workspace',
|
||||||
|
remotePath: '~/alpha',
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: ['_patch/', '*.log'],
|
||||||
|
syncPaths: ['.dsh'],
|
||||||
|
syncExclude: ['data/'],
|
||||||
|
syncMaxBytes: 2147483648,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ws-b',
|
||||||
|
profileId: 'p-1',
|
||||||
|
title: 'Beta workspace',
|
||||||
|
remotePath: '~/beta',
|
||||||
|
writeBack: false,
|
||||||
|
writeBackExclude: [],
|
||||||
|
syncPaths: [],
|
||||||
|
syncExclude: [],
|
||||||
|
syncMaxBytes: 0,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const SSH_HOSTS: SshConfigHost[] = [
|
||||||
|
{ name: 'alpha', hostName: 'alpha.example.com', user: 'alice', identityFile: '~/.ssh/alpha' },
|
||||||
|
{ name: 'beta', hostName: 'beta.example.com', user: 'bob' },
|
||||||
|
{ name: 'gamma', hostName: 'gamma.example.com' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const PREFS: RemoteSshPrefs = {
|
||||||
|
nodePath: '',
|
||||||
|
writeBackFailure: 'error',
|
||||||
|
writeBackFreshness: true,
|
||||||
|
defaultSyncPaths: [],
|
||||||
|
defaultSyncExclude: [],
|
||||||
|
defaultSyncMaxBytes: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Fake api */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
type Handler = (args: unknown, index: number) => unknown
|
||||||
|
|
||||||
|
interface InitialData {
|
||||||
|
profiles?: RemoteSshProfile[]
|
||||||
|
workspaces?: RemoteSshWorkspace[]
|
||||||
|
prefs?: RemoteSshPrefs
|
||||||
|
hosts?: SshConfigHost[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function defaultResponse(method: string, initial: InitialData): unknown {
|
||||||
|
switch (method) {
|
||||||
|
case 'listProfiles':
|
||||||
|
return { ok: true, profiles: initial.profiles ?? [PROFILE] }
|
||||||
|
case 'listWorkspaces':
|
||||||
|
return { ok: true, workspaces: initial.workspaces ?? WORKSPACES }
|
||||||
|
case 'getPrefs':
|
||||||
|
return { ok: true, prefs: initial.prefs ?? PREFS }
|
||||||
|
case 'listSshConfigHosts':
|
||||||
|
return { ok: true, hosts: initial.hosts ?? SSH_HOSTS }
|
||||||
|
case 'saveProfile':
|
||||||
|
return { ok: true, id: 'p-new', profiles: initial.profiles ?? [PROFILE] }
|
||||||
|
case 'updateWorkspaceGuards':
|
||||||
|
return { ok: true, workspaces: initial.workspaces ?? WORKSPACES }
|
||||||
|
case 'savePrefs':
|
||||||
|
return { ok: true }
|
||||||
|
case 'testConnection':
|
||||||
|
return { ok: true, stdout: 'connected' }
|
||||||
|
case 'syncDown':
|
||||||
|
case 'syncUp':
|
||||||
|
return { ok: true }
|
||||||
|
case 'deleteProfile':
|
||||||
|
return { ok: true, profiles: [], workspaces: [] }
|
||||||
|
case 'deleteWorkspace':
|
||||||
|
return { ok: true, workspaces: [] }
|
||||||
|
default:
|
||||||
|
return { ok: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Harness {
|
||||||
|
api: RemoteSshApi
|
||||||
|
mock: ReturnType<typeof vi.fn>
|
||||||
|
/** Argument objects of every call to one api method (in order). */
|
||||||
|
calls: (method: string) => unknown[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFakeApi(options: { initial?: InitialData; handlers?: Record<string, Handler> } = {}): Harness {
|
||||||
|
const initial = options.initial ?? {}
|
||||||
|
const counters: Record<string, number> = {}
|
||||||
|
const mock = vi.fn(async (method: string, args?: unknown) => {
|
||||||
|
const index = counters[method] ?? 0
|
||||||
|
counters[method] = index + 1
|
||||||
|
const handler = options.handlers?.[method]
|
||||||
|
if (handler) return await handler(args, index)
|
||||||
|
return defaultResponse(method, initial)
|
||||||
|
})
|
||||||
|
return {
|
||||||
|
api: mock as unknown as RemoteSshApi,
|
||||||
|
mock,
|
||||||
|
calls: (method: string) => mock.mock.calls.filter(call => call[0] === method).map(call => call[1]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Mounting + DOM helpers */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
interface Mounted {
|
||||||
|
root: Root
|
||||||
|
container: HTMLDivElement
|
||||||
|
}
|
||||||
|
|
||||||
|
let mounted: Mounted[] = []
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
act(() => {
|
||||||
|
for (const entry of mounted) entry.root.unmount()
|
||||||
|
})
|
||||||
|
for (const entry of mounted) entry.container.remove()
|
||||||
|
mounted = []
|
||||||
|
})
|
||||||
|
|
||||||
|
async function flush(): Promise<void> {
|
||||||
|
await act(async () => {
|
||||||
|
await new Promise<void>(resolve => setTimeout(resolve, 0))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function settle(rounds = 4): Promise<void> {
|
||||||
|
for (let i = 0; i < rounds; i += 1) await flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitFor(predicate: () => boolean, label: string): Promise<void> {
|
||||||
|
for (let i = 0; i < 40; i += 1) {
|
||||||
|
if (predicate()) return
|
||||||
|
await flush()
|
||||||
|
}
|
||||||
|
throw new Error(`timed out waiting for ${label}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function q(container: ParentNode, selector: string): HTMLElement | null {
|
||||||
|
return container.querySelector(selector) as HTMLElement | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function need(container: ParentNode, selector: string): HTMLElement {
|
||||||
|
const el = q(container, selector)
|
||||||
|
if (!el) throw new Error(`missing element: ${selector}`)
|
||||||
|
return el
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(container: ParentNode): string {
|
||||||
|
return container.textContent ?? ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set a controlled input/textarea/select the way a user would type. */
|
||||||
|
function setValue(el: HTMLElement, value: string): void {
|
||||||
|
const proto = Object.getPrototypeOf(el) as object
|
||||||
|
const descriptor = Object.getOwnPropertyDescriptor(proto, 'value')
|
||||||
|
if (!descriptor?.set) throw new Error(`element ${el.tagName} has no value setter`)
|
||||||
|
act(() => {
|
||||||
|
descriptor.set!.call(el, value)
|
||||||
|
el.dispatchEvent(new Event(el.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true }))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function clickSync(el: Element | null | undefined): void {
|
||||||
|
if (!el) throw new Error('click target missing')
|
||||||
|
act(() => {
|
||||||
|
;(el as HTMLElement).click()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async function click(el: Element | null | undefined): Promise<void> {
|
||||||
|
clickSync(el)
|
||||||
|
await settle()
|
||||||
|
}
|
||||||
|
|
||||||
|
function value(el: HTMLElement): string {
|
||||||
|
return (el as HTMLInputElement | HTMLTextAreaElement).value
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVisiblyHidden(el: HTMLElement | null): boolean {
|
||||||
|
if (!el) return true
|
||||||
|
let node: HTMLElement | null = el
|
||||||
|
while (node) {
|
||||||
|
if (node.hasAttribute('hidden') || node.getAttribute('aria-hidden') === 'true') return true
|
||||||
|
node = node.parentElement
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The labelled control inside a card/section (spec: every input has label htmlFor). */
|
||||||
|
function controlByLabel(scope: ParentNode, labelPart: string): HTMLInputElement | HTMLTextAreaElement {
|
||||||
|
const labels = Array.from(scope.querySelectorAll('label'))
|
||||||
|
const label = labels.find(candidate => (candidate.textContent ?? '').includes(labelPart))
|
||||||
|
if (!label) throw new Error(`no label containing "${labelPart}"`)
|
||||||
|
const id = label.htmlFor
|
||||||
|
const byId = id ? (document.getElementById(id) as HTMLElement | null) : null
|
||||||
|
if (byId) return byId as HTMLInputElement | HTMLTextAreaElement
|
||||||
|
const sibling = label.nextElementSibling
|
||||||
|
if (sibling && /^(INPUT|TEXTAREA|SELECT)$/.test(sibling.tagName)) {
|
||||||
|
return sibling as HTMLInputElement | HTMLTextAreaElement
|
||||||
|
}
|
||||||
|
throw new Error(`label for "${labelPart}" is not associated with a control`)
|
||||||
|
}
|
||||||
|
|
||||||
|
function workspaceCard(section: ParentNode, id: string): HTMLElement {
|
||||||
|
return need(section, `[data-rsui-workspace][data-workspace-id="${id}"]`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function expandWorkspacesSection(root: HTMLElement): Promise<void> {
|
||||||
|
const toggle = need(root, '[data-rsui-toggle-workspaces]')
|
||||||
|
if (toggle.getAttribute('aria-expanded') !== 'true') await click(toggle)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MountOptions {
|
||||||
|
initial?: InitialData
|
||||||
|
handlers?: Record<string, Handler>
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mount(options: MountOptions = {}): Promise<Harness & { container: HTMLDivElement }> {
|
||||||
|
const harness = createFakeApi(options)
|
||||||
|
const Section = createSettingsSection({ api: harness.api })
|
||||||
|
const container = document.createElement('div')
|
||||||
|
document.body.append(container)
|
||||||
|
const root = createRoot(container)
|
||||||
|
mounted.push({ root, container })
|
||||||
|
await act(async () => {
|
||||||
|
root.render(React.createElement(Section, { t }))
|
||||||
|
})
|
||||||
|
await settle(6)
|
||||||
|
return { ...harness, container }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Collapsing must never drop drafts */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('collapsible sections keep their drafts', () => {
|
||||||
|
it('collapsing and re-expanding "add connection" keeps host and proxyJump', async () => {
|
||||||
|
const { container } = await mount()
|
||||||
|
expect(need(container, '[data-rsui-field="host"]')).toBeTruthy()
|
||||||
|
|
||||||
|
setValue(need(container, '[data-rsui-field="host"]'), 'draft.example.com')
|
||||||
|
await click(need(container, '[data-rsui-toggle-more]'))
|
||||||
|
setValue(need(container, '[data-rsui-field="proxyJump"]'), 'bastion.example.com')
|
||||||
|
await click(need(container, '[data-rsui-toggle-more]'))
|
||||||
|
|
||||||
|
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(false)
|
||||||
|
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||||
|
expect(value(need(container, '[data-rsui-field="proxyJump"]'))).toBe('bastion.example.com')
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-add]'))
|
||||||
|
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(true)
|
||||||
|
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-add]'))
|
||||||
|
expect(isVisiblyHidden(q(container, '[data-rsui-field="host"]'))).toBe(false)
|
||||||
|
expect(value(need(container, '[data-rsui-field="host"]'))).toBe('draft.example.com')
|
||||||
|
expect(value(need(container, '[data-rsui-field="proxyJump"]'))).toBe('bastion.example.com')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('collapsing the remote-workspace section keeps the workspace field draft', async () => {
|
||||||
|
const { container } = await mount()
|
||||||
|
await expandWorkspacesSection(container)
|
||||||
|
|
||||||
|
const card = workspaceCard(container, 'ws-a')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
|
||||||
|
const writeBackExclude = controlByLabel(card, '写回排除')
|
||||||
|
setValue(writeBackExclude, '_patch/, *.log, tmp/')
|
||||||
|
const syncMaxBytes = controlByLabel(card, '同步体积上限')
|
||||||
|
setValue(syncMaxBytes, '3')
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-workspaces]'))
|
||||||
|
expect(isVisiblyHidden(q(card, '[data-rsui-ws-save]'))).toBe(true)
|
||||||
|
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, *.log, tmp/')
|
||||||
|
expect(value(controlByLabel(card, '同步体积上限'))).toBe('3')
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-workspaces]'))
|
||||||
|
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, *.log, tmp/')
|
||||||
|
expect(value(controlByLabel(card, '同步体积上限'))).toBe('3')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('advanced settings start collapsed with the save button hidden, and keep nodePath', async () => {
|
||||||
|
const { container } = await mount()
|
||||||
|
|
||||||
|
const content = need(container, '[data-rsui-advanced-content]')
|
||||||
|
expect(isVisiblyHidden(content)).toBe(true)
|
||||||
|
const save = q(container, '[data-rsui-prefs-save]')
|
||||||
|
expect(save).not.toBeNull()
|
||||||
|
expect(isVisiblyHidden(save)).toBe(true)
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||||
|
expect(isVisiblyHidden(need(container, '[data-rsui-advanced-content]'))).toBe(false)
|
||||||
|
expect(isVisiblyHidden(q(container, '[data-rsui-prefs-save]'))).toBe(false)
|
||||||
|
|
||||||
|
const nodePath = need(container, '[data-rsui-field="nodePath"]')
|
||||||
|
setValue(nodePath, '/custom/node.exe')
|
||||||
|
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||||
|
expect(isVisiblyHidden(need(container, '[data-rsui-advanced-content]'))).toBe(true)
|
||||||
|
expect(value(need(container, '[data-rsui-field="nodePath"]'))).toBe('/custom/node.exe')
|
||||||
|
|
||||||
|
await click(need(container, '[data-rsui-toggle-advanced]'))
|
||||||
|
expect(value(need(container, '[data-rsui-field="nodePath"]'))).toBe('/custom/node.exe')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Per-workspace guards */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('workspace guard saving', () => {
|
||||||
|
it('saves the right workspace id with GiB→bytes and no global fields', async () => {
|
||||||
|
const updated = WORKSPACES.map(workspace =>
|
||||||
|
workspace.id === 'ws-b' ? { ...workspace, syncMaxBytes: 3 * 1073741824, writeBackExclude: ['tmp/'] } : workspace,
|
||||||
|
)
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
updateWorkspaceGuards: () => ({ ok: true, workspaces: updated }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await expandWorkspacesSection(harness.container)
|
||||||
|
|
||||||
|
const card = workspaceCard(harness.container, 'ws-b')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
const syncMaxBytes = controlByLabel(card, '同步体积上限')
|
||||||
|
setValue(syncMaxBytes, '3')
|
||||||
|
const writeBackExclude = controlByLabel(card, '写回排除')
|
||||||
|
setValue(writeBackExclude, 'tmp/')
|
||||||
|
|
||||||
|
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||||
|
|
||||||
|
await click(need(card, '[data-rsui-ws-save]'))
|
||||||
|
await waitFor(() => harness.calls('updateWorkspaceGuards').length === 1, 'updateWorkspaceGuards call')
|
||||||
|
|
||||||
|
const payload = harness.calls('updateWorkspaceGuards')[0] as UpdateWorkspaceGuardsPayload
|
||||||
|
expect(payload).toEqual({
|
||||||
|
id: 'ws-b',
|
||||||
|
writeBack: false,
|
||||||
|
writeBackExclude: ['tmp/'],
|
||||||
|
syncPaths: [],
|
||||||
|
syncExclude: [],
|
||||||
|
syncMaxBytes: 3221225472,
|
||||||
|
})
|
||||||
|
expect(payload).not.toHaveProperty('proxyJump')
|
||||||
|
expect(payload).not.toHaveProperty('nodePath')
|
||||||
|
expect(harness.calls('savePrefs')).toHaveLength(0)
|
||||||
|
|
||||||
|
// Successful save recalculates the baseline: the dirty badge disappears.
|
||||||
|
await settle()
|
||||||
|
expect(q(card, '[data-rsui-ws-dirty]')).toBeNull()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a failed save keeps the typed draft and shows the error', async () => {
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
updateWorkspaceGuards: () => ({ ok: false, error: 'guards denied' }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await expandWorkspacesSection(harness.container)
|
||||||
|
|
||||||
|
const card = workspaceCard(harness.container, 'ws-a')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
setValue(controlByLabel(card, '写回排除'), '_patch/, tmp/')
|
||||||
|
|
||||||
|
await click(need(card, '[data-rsui-ws-save]'))
|
||||||
|
await waitFor(() => text(card).includes('guards denied'), 'save error text')
|
||||||
|
|
||||||
|
expect(value(controlByLabel(card, '写回排除'))).toBe('_patch/, tmp/')
|
||||||
|
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||||
|
expect(value(controlByLabel(card, '同步体积上限'))).toBe('2')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('pull / push gating', () => {
|
||||||
|
it('a dirty workspace refuses pull and push and asks for a save first', async () => {
|
||||||
|
const harness = await mount()
|
||||||
|
await expandWorkspacesSection(harness.container)
|
||||||
|
const card = workspaceCard(harness.container, 'ws-a')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-sync]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
|
||||||
|
setValue(controlByLabel(card, '写回排除'), '_patch/, typed/')
|
||||||
|
expect(q(card, '[data-rsui-ws-dirty]')).not.toBeNull()
|
||||||
|
|
||||||
|
await click(need(card, '[data-rsui-ws-sync]'))
|
||||||
|
expect(harness.calls('syncDown')).toHaveLength(0)
|
||||||
|
expect(text(card)).toContain(zh['workspace.syncBlocked'])
|
||||||
|
|
||||||
|
await click(need(card, '[data-rsui-ws-push]'))
|
||||||
|
expect(harness.calls('syncUp')).toHaveLength(0)
|
||||||
|
expect(text(card)).toContain(zh['workspace.syncBlocked'])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('after saving, pull runs with the workspace id', async () => {
|
||||||
|
const updated = WORKSPACES.map(workspace =>
|
||||||
|
workspace.id === 'ws-a' ? { ...workspace, writeBackExclude: ['_patch/', 'typed/'] } : workspace,
|
||||||
|
)
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
updateWorkspaceGuards: () => ({ ok: true, workspaces: updated }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await expandWorkspacesSection(harness.container)
|
||||||
|
const card = workspaceCard(harness.container, 'ws-a')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-save]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
|
||||||
|
setValue(controlByLabel(card, '写回排除'), '_patch/, typed/')
|
||||||
|
await click(need(card, '[data-rsui-ws-save]'))
|
||||||
|
await waitFor(() => harness.calls('updateWorkspaceGuards').length === 1, 'guard save')
|
||||||
|
await settle()
|
||||||
|
expect(q(card, '[data-rsui-ws-dirty]')).toBeNull()
|
||||||
|
|
||||||
|
await click(need(card, '[data-rsui-ws-sync]'))
|
||||||
|
await waitFor(() => harness.calls('syncDown').length === 1, 'syncDown')
|
||||||
|
expect(harness.calls('syncDown')[0]).toEqual({ id: 'ws-a' })
|
||||||
|
expect(text(card)).toContain(zh['workspace.syncDone'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('sync failure recovery', () => {
|
||||||
|
it('clears the busy state after a failed sync so the action can be retried', async () => {
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
syncDown: (_args, index) => (index === 0 ? { ok: false, error: 'sync exploded' } : { ok: true }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await expandWorkspacesSection(harness.container)
|
||||||
|
const card = workspaceCard(harness.container, 'ws-a')
|
||||||
|
if (isVisiblyHidden(q(card, '[data-rsui-ws-sync]'))) await click(need(card, '[data-rsui-ws-expand]'))
|
||||||
|
const otherCard = workspaceCard(harness.container, 'ws-b')
|
||||||
|
if (isVisiblyHidden(q(otherCard, '[data-rsui-ws-sync]'))) await click(need(otherCard, '[data-rsui-ws-expand]'))
|
||||||
|
|
||||||
|
const sync = need(card, '[data-rsui-ws-sync]') as HTMLButtonElement
|
||||||
|
await click(sync)
|
||||||
|
await waitFor(() => text(card).includes('sync exploded'), 'sync failure text')
|
||||||
|
|
||||||
|
expect(sync.disabled).toBe(false)
|
||||||
|
expect(sync.getAttribute('aria-busy')).not.toBe('true')
|
||||||
|
expect(text(card)).not.toContain(zh['workspace.syncing'])
|
||||||
|
const otherSync = need(otherCard, '[data-rsui-ws-sync]') as HTMLButtonElement
|
||||||
|
expect(otherSync.disabled).toBe(false)
|
||||||
|
|
||||||
|
await click(sync)
|
||||||
|
await waitFor(() => harness.calls('syncDown').length === 2, 'second syncDown')
|
||||||
|
expect(text(card)).toContain(zh['workspace.syncDone'])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Import dialog */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('SSH config import feedback', () => {
|
||||||
|
it('reports partial failures per host, never "all imported", and retries only failures', async () => {
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
saveProfile: (args, index) => {
|
||||||
|
const name = (args as SaveProfilePayload).name
|
||||||
|
if (index === 0) return { ok: true }
|
||||||
|
if (index === 1) return { ok: false, error: 'duplicate host' }
|
||||||
|
if (index === 2) throw new Error('network down')
|
||||||
|
// retry calls (only the failed hosts are resubmitted)
|
||||||
|
return { ok: true, name }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-import-open]'))
|
||||||
|
await waitFor(
|
||||||
|
() => harness.container.querySelectorAll('[data-rsui-import-row]').length === SSH_HOSTS.length,
|
||||||
|
'import host rows',
|
||||||
|
)
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-import-submit]'))
|
||||||
|
await waitFor(() => q(harness.container, '[data-rsui-import-result]') !== null, 'import result')
|
||||||
|
|
||||||
|
const result = need(harness.container, '[data-rsui-import-result]')
|
||||||
|
const resultText = text(result)
|
||||||
|
expect(resultText).toContain('成功 1 个,失败 2 个')
|
||||||
|
expect(resultText).not.toContain('已导入')
|
||||||
|
expect(resultText).toContain('beta')
|
||||||
|
expect(resultText).toContain('gamma')
|
||||||
|
expect(resultText).toContain('duplicate host')
|
||||||
|
expect(resultText).toContain('network down')
|
||||||
|
|
||||||
|
const retry = q(harness.container, '[data-rsui-import-retry]')
|
||||||
|
expect(retry, 'retry-failed button').not.toBeNull()
|
||||||
|
expect(text(retry as HTMLElement)).toContain('仅重试失败项')
|
||||||
|
expect(text(retry as HTMLElement)).toContain('2')
|
||||||
|
|
||||||
|
const saveCalls = () => harness.calls('saveProfile') as SaveProfilePayload[]
|
||||||
|
expect(saveCalls().map(payload => payload.name)).toEqual(['alpha', 'beta', 'gamma'])
|
||||||
|
|
||||||
|
await click(retry)
|
||||||
|
await waitFor(() => saveCalls().length === 5, 'retried saves')
|
||||||
|
expect(saveCalls().map(payload => payload.name)).toEqual(['alpha', 'beta', 'gamma', 'beta', 'gamma'])
|
||||||
|
expect(saveCalls().filter(payload => payload.name === 'alpha')).toHaveLength(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('shows a successful retry as fully imported', async () => {
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: {
|
||||||
|
saveProfile: (_args, index) => (index === 0 ? { ok: false, error: 'denied' } : { ok: true }),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await click(need(harness.container, '[data-rsui-import-open]'))
|
||||||
|
await waitFor(
|
||||||
|
() => harness.container.querySelectorAll('[data-rsui-import-row]').length === SSH_HOSTS.length,
|
||||||
|
'import host rows',
|
||||||
|
)
|
||||||
|
// Select a single host only, so a retry of that host fully succeeds.
|
||||||
|
await click(need(harness.container, '[data-rsui-import-clear]'))
|
||||||
|
const firstRow = need(harness.container, '[data-rsui-import-row]')
|
||||||
|
const checkbox = firstRow.querySelector('input[type="checkbox"]')
|
||||||
|
expect(checkbox).not.toBeNull()
|
||||||
|
await click(checkbox)
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-import-submit]'))
|
||||||
|
await waitFor(() => q(harness.container, '[data-rsui-import-result]') !== null, 'import result')
|
||||||
|
expect(text(need(harness.container, '[data-rsui-import-result]'))).toContain('全部失败')
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-import-retry]'))
|
||||||
|
await waitFor(() => harness.calls('saveProfile').length === 2, 'retry save')
|
||||||
|
await settle()
|
||||||
|
expect(text(need(harness.container, '[data-rsui-import-result]'))).toContain('已导入 1 个连接')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Add connection */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('add connection form', () => {
|
||||||
|
function fillConnection(container: HTMLElement, fields: Partial<Record<'name' | 'host' | 'user' | 'port', string>>): void {
|
||||||
|
for (const [field, fieldValue] of Object.entries(fields)) {
|
||||||
|
setValue(need(container, `[data-rsui-field="${field}"]`), fieldValue as string)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
it('a successful add resets the form and reports the added name', async () => {
|
||||||
|
const harness = await mount()
|
||||||
|
fillConnection(harness.container, { name: 'New HPC', host: 'new.example.com', user: 'alice', port: '2222' })
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||||
|
await waitFor(() => harness.calls('saveProfile').length === 1, 'saveProfile')
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
const payload = harness.calls('saveProfile')[0] as SaveProfilePayload
|
||||||
|
expect(payload).toMatchObject({
|
||||||
|
name: 'New HPC',
|
||||||
|
host: 'new.example.com',
|
||||||
|
user: 'alice',
|
||||||
|
port: 2222,
|
||||||
|
authMethod: 'key',
|
||||||
|
})
|
||||||
|
expect(harness.container.textContent).toContain('已添加连接「New HPC」')
|
||||||
|
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="host"]'))).toBe('')
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="user"]'))).toBe('')
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="port"]'))).toBe('22')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a failed add keeps the input and shows the error', async () => {
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: { saveProfile: () => ({ ok: false, error: 'profile denied' }) },
|
||||||
|
})
|
||||||
|
fillConnection(harness.container, { host: 'keep.example.com', user: 'alice' })
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||||
|
await waitFor(() => text(harness.container).includes('profile denied'), 'add error')
|
||||||
|
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="host"]'))).toBe('keep.example.com')
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="user"]'))).toBe('alice')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('an invalid port blocks submission instead of posting 22', async () => {
|
||||||
|
const harness = await mount()
|
||||||
|
fillConnection(harness.container, { host: 'port.example.com', user: 'alice', port: 'abc' })
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-add-submit]'))
|
||||||
|
await settle()
|
||||||
|
|
||||||
|
expect(harness.calls('saveProfile')).toHaveLength(0)
|
||||||
|
expect(text(harness.container)).toContain(zh['add.errPort'])
|
||||||
|
expect(value(need(harness.container, '[data-rsui-field="port"]'))).toBe('abc')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Global preferences */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
describe('global preferences', () => {
|
||||||
|
it('saving prefs posts the prefs payload and never writes workspace guards', async () => {
|
||||||
|
const saved: RemoteSshPrefs = { ...PREFS, nodePath: '/custom/node.exe' }
|
||||||
|
const harness = await mount({
|
||||||
|
handlers: { savePrefs: () => ({ ok: true, prefs: saved }) },
|
||||||
|
})
|
||||||
|
|
||||||
|
await click(need(harness.container, '[data-rsui-toggle-advanced]'))
|
||||||
|
setValue(need(harness.container, '[data-rsui-field="nodePath"]'), ' /custom/node.exe ')
|
||||||
|
await click(need(harness.container, '[data-rsui-prefs-save]'))
|
||||||
|
await waitFor(() => harness.calls('savePrefs').length === 1, 'savePrefs')
|
||||||
|
|
||||||
|
const payload = harness.calls('savePrefs')[0] as SavePrefsPayload
|
||||||
|
expect(payload.nodePath).toBe('/custom/node.exe')
|
||||||
|
expect(payload.writeBackFailure).toBe('error')
|
||||||
|
expect(payload.writeBackFreshness).toBe(true)
|
||||||
|
expect(payload.defaultSyncPaths).toEqual([])
|
||||||
|
expect(payload.defaultSyncMaxBytes).toBe(0)
|
||||||
|
|
||||||
|
expect(harness.calls('updateWorkspaceGuards')).toHaveLength(0)
|
||||||
|
expect(text(harness.container)).toContain(zh['advanced.saved'])
|
||||||
|
expect(q(harness.container, '[data-rsui-ws-dirty]')).toBeNull()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,396 @@
|
||||||
|
/**
|
||||||
|
* Fake `/remote-ssh/api/*` data layer for the ISOLATED preview.
|
||||||
|
*
|
||||||
|
* This never talks to the real Host. Every response is local, deterministic
|
||||||
|
* and in-memory, so the preview screenshots show the real component rendered
|
||||||
|
* against controlled data (including the failure states the real API can
|
||||||
|
* produce). No real password or private key ever exists here: password
|
||||||
|
* profiles only carry `passwordConfigured: true` (the redacted projection the
|
||||||
|
* Host actually returns).
|
||||||
|
*/
|
||||||
|
import type {
|
||||||
|
DeleteProfileResponse,
|
||||||
|
DeleteWorkspaceResponse,
|
||||||
|
GetPrefsResponse,
|
||||||
|
ListProfilesResponse,
|
||||||
|
ListSshConfigHostsResponse,
|
||||||
|
ListWorkspacesResponse,
|
||||||
|
RemoteSshApi,
|
||||||
|
RemoteSshPrefs,
|
||||||
|
RemoteSshProfile,
|
||||||
|
RemoteSshWorkspace,
|
||||||
|
SavePrefsPayload,
|
||||||
|
SavePrefsResponse,
|
||||||
|
SaveProfilePayload,
|
||||||
|
SaveProfileResponse,
|
||||||
|
SshConfigHost,
|
||||||
|
SyncResponse,
|
||||||
|
TestConnectionResponse,
|
||||||
|
UpdateWorkspaceGuardsPayload,
|
||||||
|
UpdateWorkspaceGuardsResponse,
|
||||||
|
} from '../../src/client/rssh-settings/contract.ts'
|
||||||
|
|
||||||
|
export type PreviewScene =
|
||||||
|
| 'default'
|
||||||
|
| 'expanded'
|
||||||
|
| 'import-ready'
|
||||||
|
| 'import-partial'
|
||||||
|
| 'workspaces'
|
||||||
|
| 'password'
|
||||||
|
| 'test-failure'
|
||||||
|
|
||||||
|
export const PREVIEW_SCENES: readonly PreviewScene[] = [
|
||||||
|
'default',
|
||||||
|
'expanded',
|
||||||
|
'import-ready',
|
||||||
|
'import-partial',
|
||||||
|
'workspaces',
|
||||||
|
'password',
|
||||||
|
'test-failure',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
export function isPreviewScene(value: string): value is PreviewScene {
|
||||||
|
return (PREVIEW_SCENES as readonly string[]).includes(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Deterministic latency so busy states appear, then settle (no polling of a clock). */
|
||||||
|
const API_LATENCY_MS = 130
|
||||||
|
|
||||||
|
const delay = (ms: number): Promise<void> =>
|
||||||
|
new Promise<void>(resolve => {
|
||||||
|
setTimeout(resolve, ms)
|
||||||
|
})
|
||||||
|
|
||||||
|
/** Approximates the Host's redacted profile projection (no secrets). */
|
||||||
|
const BASE_PROFILES: RemoteSshProfile[] = [
|
||||||
|
{
|
||||||
|
id: 'conn-hpc',
|
||||||
|
name: '超算集群',
|
||||||
|
host: 'login.hpc.example.com',
|
||||||
|
port: 22,
|
||||||
|
user: 'demo-user',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: '~/.ssh/id_ed25519',
|
||||||
|
remoteRoot: '~/project',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'conn-lab',
|
||||||
|
name: '实验室工作站',
|
||||||
|
host: 'workstation.lab.example.com',
|
||||||
|
port: 22,
|
||||||
|
user: 'lab-user',
|
||||||
|
authMethod: 'password',
|
||||||
|
passwordConfigured: true,
|
||||||
|
remoteRoot: '/home/lab-user/work',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'conn-gpu',
|
||||||
|
name: 'GPU 节点',
|
||||||
|
host: 'gpu-node-01.cluster.internal.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'gpu-user',
|
||||||
|
authMethod: 'key',
|
||||||
|
keyPath: '~/.ssh/id_ed25519_gpu',
|
||||||
|
remoteRoot: '~/scratch',
|
||||||
|
proxyJump: 'bastion.example.com',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const BASE_WORKSPACES: RemoteSshWorkspace[] = [
|
||||||
|
{
|
||||||
|
id: 'ws-hpc',
|
||||||
|
profileId: 'conn-hpc',
|
||||||
|
title: '项目 A',
|
||||||
|
remotePath: '/home/demo-user/project-a',
|
||||||
|
mirrorPath: 'C:\\Users\\demo\\remote-mirrors\\project-a',
|
||||||
|
writeBack: true,
|
||||||
|
writeBackExclude: ['data/', '*.log', '_patch/'],
|
||||||
|
syncPaths: ['.dsh', 'src'],
|
||||||
|
syncExclude: ['data/', 'node_modules/'],
|
||||||
|
syncMaxBytes: 2 * 1024 * 1024 * 1024,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'ws-gpu',
|
||||||
|
profileId: 'conn-gpu',
|
||||||
|
title: '训练任务',
|
||||||
|
remotePath: '/home/gpu-user/scratch/long-experiment-directory-name-for-wrapping-check',
|
||||||
|
mirrorPath: 'C:\\Users\\demo\\remote-mirrors\\gpu-run',
|
||||||
|
writeBack: false,
|
||||||
|
writeBackExclude: ['runs/'],
|
||||||
|
syncPaths: ['.dsh', 'configs'],
|
||||||
|
syncExclude: ['runs/', '*.pt'],
|
||||||
|
syncMaxBytes: 4 * 1024 * 1024 * 1024,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const BASE_PREFS: RemoteSshPrefs = {
|
||||||
|
nodePath: '',
|
||||||
|
writeBackFailure: 'error',
|
||||||
|
writeBackFreshness: true,
|
||||||
|
defaultSyncPaths: ['.dsh'],
|
||||||
|
defaultSyncExclude: ['node_modules/', '*.log'],
|
||||||
|
defaultSyncMaxBytes: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `~/.ssh/config` entries used by the import dialog scenarios. */
|
||||||
|
const SSH_CONFIG_HOSTS: SshConfigHost[] = [
|
||||||
|
{
|
||||||
|
name: 'hpc-login',
|
||||||
|
hostName: 'login.hpc.example.com',
|
||||||
|
port: 22,
|
||||||
|
user: 'demo-user',
|
||||||
|
identityFile: '~/.ssh/id_ed25519',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'gpu-lab',
|
||||||
|
hostName: 'gpu-node-01.cluster.internal.example.com',
|
||||||
|
port: 2222,
|
||||||
|
user: 'gpu-user',
|
||||||
|
identityFile: '~/.ssh/id_ed25519_gpu',
|
||||||
|
proxyJump: 'bastion.example.com',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'bastion',
|
||||||
|
hostName: 'bastion.example.com',
|
||||||
|
user: 'jump-user',
|
||||||
|
identityFile: '~/.ssh/id_ed25519',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'mirror',
|
||||||
|
hostName: 'mirror.example.org',
|
||||||
|
port: 2222,
|
||||||
|
user: 'mirror-user',
|
||||||
|
identityFile: '',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'broken-host',
|
||||||
|
hostName: 'broken.example.net',
|
||||||
|
user: '',
|
||||||
|
identityFile: '',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
/** Hosts the `import-partial` scenario refuses to save on the first attempt. */
|
||||||
|
const PARTIAL_IMPORT_FAILURES: Record<string, string> = {
|
||||||
|
'mirror.example.org': '保存失败:设置表写入被拒绝(示例错误)',
|
||||||
|
'broken.example.net': '保存失败:主机条目缺少有效用户,Host 拒绝该配置(示例错误)',
|
||||||
|
}
|
||||||
|
|
||||||
|
const cloneProfiles = (profiles: RemoteSshProfile[]): RemoteSshProfile[] =>
|
||||||
|
profiles.map(profile => ({ ...profile }))
|
||||||
|
|
||||||
|
const cloneWorkspaces = (workspaces: RemoteSshWorkspace[]): RemoteSshWorkspace[] =>
|
||||||
|
workspaces.map(workspace => ({
|
||||||
|
...workspace,
|
||||||
|
writeBackExclude: workspace.writeBackExclude ? [...workspace.writeBackExclude] : undefined,
|
||||||
|
syncPaths: workspace.syncPaths ? [...workspace.syncPaths] : undefined,
|
||||||
|
syncExclude: workspace.syncExclude ? [...workspace.syncExclude] : undefined,
|
||||||
|
}))
|
||||||
|
|
||||||
|
/** Expose scenario/step counters for the screenshot script's assertions. */
|
||||||
|
interface FakeApiState {
|
||||||
|
scene: PreviewScene
|
||||||
|
calls: string[]
|
||||||
|
mutations: number
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
__RSH_PREVIEW_API__?: FakeApiState
|
||||||
|
__RSH_PREVIEW_IDLE__?: boolean
|
||||||
|
__RSH_PREVIEW_READY__?: boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the fake typed API. Individual endpoints behave like the Host:
|
||||||
|
* `ok` flags, redacted profiles, per-item import failures, tests that can fail
|
||||||
|
* with diagnostics, and preference/workspace mutations that persist in memory.
|
||||||
|
*/
|
||||||
|
export function createFakeApi(scene: PreviewScene): RemoteSshApi {
|
||||||
|
const state: FakeApiState = { scene, calls: [], mutations: 0 }
|
||||||
|
if (typeof window !== 'undefined') {
|
||||||
|
window.__RSH_PREVIEW_API__ = state
|
||||||
|
window.__RSH_PREVIEW_IDLE__ = true
|
||||||
|
}
|
||||||
|
|
||||||
|
let profiles = cloneProfiles(BASE_PROFILES)
|
||||||
|
let workspaces = cloneWorkspaces(BASE_WORKSPACES)
|
||||||
|
let prefs: RemoteSshPrefs = { ...BASE_PREFS }
|
||||||
|
/** First attempt of each imported host (used by partial-import + retry). */
|
||||||
|
const importAttempts = new Map<string, number>()
|
||||||
|
|
||||||
|
let pending = 0
|
||||||
|
let idleTimer: ReturnType<typeof setTimeout> | undefined
|
||||||
|
|
||||||
|
const markBusy = (): void => {
|
||||||
|
pending += 1
|
||||||
|
if (typeof window !== 'undefined') window.__RSH_PREVIEW_IDLE__ = false
|
||||||
|
if (idleTimer) clearTimeout(idleTimer)
|
||||||
|
idleTimer = undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const markSettled = (): void => {
|
||||||
|
pending = Math.max(0, pending - 1)
|
||||||
|
if (pending > 0) return
|
||||||
|
if (idleTimer) clearTimeout(idleTimer)
|
||||||
|
idleTimer = setTimeout(() => {
|
||||||
|
idleTimer = undefined
|
||||||
|
if (pending === 0 && typeof window !== 'undefined') window.__RSH_PREVIEW_IDLE__ = true
|
||||||
|
}, 260)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handle = async (method: string, args?: unknown): Promise<unknown> => {
|
||||||
|
state.calls.push(method)
|
||||||
|
markBusy()
|
||||||
|
try {
|
||||||
|
await delay(API_LATENCY_MS)
|
||||||
|
switch (method) {
|
||||||
|
case 'listProfiles': {
|
||||||
|
const response: ListProfilesResponse = { ok: true, profiles: cloneProfiles(profiles) }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'saveProfile': {
|
||||||
|
const payload = args as SaveProfilePayload
|
||||||
|
const failingReason =
|
||||||
|
scene === 'import-partial' && PARTIAL_IMPORT_FAILURES[payload.host] !== undefined
|
||||||
|
? PARTIAL_IMPORT_FAILURES[payload.host]
|
||||||
|
: undefined
|
||||||
|
if (payload.host in PARTIAL_IMPORT_FAILURES) {
|
||||||
|
const attempts = (importAttempts.get(payload.host) || 0) + 1
|
||||||
|
importAttempts.set(payload.host, attempts)
|
||||||
|
if (attempts === 1 && failingReason) {
|
||||||
|
const failed: SaveProfileResponse = { ok: false, error: failingReason }
|
||||||
|
return failed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.mutations += 1
|
||||||
|
const saved: RemoteSshProfile = {
|
||||||
|
id: `import-${profiles.length + 1}`,
|
||||||
|
name: payload.name || payload.host,
|
||||||
|
host: payload.host,
|
||||||
|
port: payload.port,
|
||||||
|
user: payload.user,
|
||||||
|
authMethod: payload.authMethod,
|
||||||
|
keyPath: payload.keyPath || undefined,
|
||||||
|
remoteRoot: payload.remoteRoot || undefined,
|
||||||
|
proxyJump: payload.proxyJump || undefined,
|
||||||
|
passwordConfigured: payload.authMethod === 'password' ? Boolean(payload.password) : undefined,
|
||||||
|
}
|
||||||
|
profiles = [...profiles, saved]
|
||||||
|
const response: SaveProfileResponse = {
|
||||||
|
ok: true,
|
||||||
|
id: saved.id,
|
||||||
|
profiles: cloneProfiles(profiles),
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'testConnection': {
|
||||||
|
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||||
|
const profile = profiles.find(item => item.id === id) || profiles[0]
|
||||||
|
if (scene === 'test-failure') {
|
||||||
|
const failed: TestConnectionResponse = {
|
||||||
|
ok: false,
|
||||||
|
error: `ssh: connect to host ${profile?.host || 'login.hpc.example.com'} port ${
|
||||||
|
profile?.port || 22
|
||||||
|
}: Connection timed out`,
|
||||||
|
stderr:
|
||||||
|
`ssh: connect to host ${profile?.host || 'login.hpc.example.com'} port ${
|
||||||
|
profile?.port || 22
|
||||||
|
}: Connection timed out\n` +
|
||||||
|
'kex_exchange_identification: Connection closed by remote host\n' +
|
||||||
|
'Connection closed by 203.0.113.10 port 22',
|
||||||
|
exitCode: 255,
|
||||||
|
}
|
||||||
|
return failed
|
||||||
|
}
|
||||||
|
const ok: TestConnectionResponse = {
|
||||||
|
ok: true,
|
||||||
|
stdout: `Connected to ${profile?.host || 'login.hpc.example.com'} (${profile?.user || 'demo-user'})`,
|
||||||
|
exitCode: 0,
|
||||||
|
}
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
case 'deleteProfile': {
|
||||||
|
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||||
|
profiles = profiles.filter(item => item.id !== id)
|
||||||
|
workspaces = workspaces.filter(item => item.profileId !== id)
|
||||||
|
state.mutations += 1
|
||||||
|
const response: DeleteProfileResponse = {
|
||||||
|
ok: true,
|
||||||
|
profiles: cloneProfiles(profiles),
|
||||||
|
workspaces: cloneWorkspaces(workspaces),
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'listSshConfigHosts': {
|
||||||
|
const response: ListSshConfigHostsResponse = { ok: true, hosts: SSH_CONFIG_HOSTS.map(host => ({ ...host })) }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'listWorkspaces': {
|
||||||
|
const response: ListWorkspacesResponse = { ok: true, workspaces: cloneWorkspaces(workspaces) }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'updateWorkspaceGuards': {
|
||||||
|
const payload = args as UpdateWorkspaceGuardsPayload
|
||||||
|
workspaces = workspaces.map(workspace =>
|
||||||
|
workspace.id === payload.id
|
||||||
|
? {
|
||||||
|
...workspace,
|
||||||
|
writeBack: payload.writeBack,
|
||||||
|
writeBackExclude: [...payload.writeBackExclude],
|
||||||
|
syncPaths: [...payload.syncPaths],
|
||||||
|
syncExclude: [...payload.syncExclude],
|
||||||
|
syncMaxBytes: payload.syncMaxBytes,
|
||||||
|
}
|
||||||
|
: workspace,
|
||||||
|
)
|
||||||
|
state.mutations += 1
|
||||||
|
const response: UpdateWorkspaceGuardsResponse = {
|
||||||
|
ok: true,
|
||||||
|
workspaces: cloneWorkspaces(workspaces),
|
||||||
|
}
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'syncDown':
|
||||||
|
case 'syncUp': {
|
||||||
|
state.mutations += 1
|
||||||
|
const response: SyncResponse = { ok: true }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'deleteWorkspace': {
|
||||||
|
const id = String((args as { id?: string } | undefined)?.id || '')
|
||||||
|
workspaces = workspaces.filter(item => item.id !== id)
|
||||||
|
state.mutations += 1
|
||||||
|
const response: DeleteWorkspaceResponse = { ok: true, workspaces: cloneWorkspaces(workspaces) }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'getPrefs': {
|
||||||
|
const response: GetPrefsResponse = { ok: true, prefs: { ...prefs, defaultSyncPaths: [...(prefs.defaultSyncPaths || [])], defaultSyncExclude: [...(prefs.defaultSyncExclude || [])] }, deleteSync: true }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
case 'savePrefs': {
|
||||||
|
const payload = args as SavePrefsPayload
|
||||||
|
prefs = {
|
||||||
|
nodePath: payload.nodePath,
|
||||||
|
writeBackFailure: payload.writeBackFailure,
|
||||||
|
writeBackFreshness: payload.writeBackFreshness,
|
||||||
|
defaultSyncPaths: [...payload.defaultSyncPaths],
|
||||||
|
defaultSyncExclude: [...payload.defaultSyncExclude],
|
||||||
|
defaultSyncMaxBytes: payload.defaultSyncMaxBytes,
|
||||||
|
}
|
||||||
|
state.mutations += 1
|
||||||
|
const response: SavePrefsResponse = { ok: true, prefs: { ...prefs } }
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
return { ok: false, error: `fake api: unknown method ${method}` }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
markSettled()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return handle as RemoteSshApi
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,128 @@
|
||||||
|
/**
|
||||||
|
* Entry of the ISOLATED Remote-SSH settings preview.
|
||||||
|
*
|
||||||
|
* Renders the REAL built section (`src/client/rssh-settings/index.tsx` →
|
||||||
|
* `createSettingsSection({ api })`) under a stand-in DSH settings panel,
|
||||||
|
* against the fake `/remote-ssh/api` layer. Nothing here touches the running
|
||||||
|
* DSH GUI, the daily profile or node_modules.
|
||||||
|
*
|
||||||
|
* URL query:
|
||||||
|
* ?scene=default|expanded|import-ready|import-partial|workspaces|password|test-failure
|
||||||
|
* &theme=light|dark
|
||||||
|
* &width=narrow (viewport width is still set by the screenshot script)
|
||||||
|
*/
|
||||||
|
import { useEffect } from 'react'
|
||||||
|
import { createRoot } from 'react-dom/client'
|
||||||
|
import { createSettingsSection } from '#rssh-settings'
|
||||||
|
import { SETTINGS_CSS } from '../../src/client/rssh-settings/styles.ts'
|
||||||
|
import previewCss from './preview.css?inline'
|
||||||
|
import { createFakeApi, isPreviewScene } from './fake-api.ts'
|
||||||
|
import { EXPECTED_MOUNT_TEXT, makeT } from './translate.ts'
|
||||||
|
import type { PreviewScene } from './fake-api.ts'
|
||||||
|
|
||||||
|
const params = new URLSearchParams(window.location.search)
|
||||||
|
const sceneParam = params.get('scene') || 'default'
|
||||||
|
const scene: PreviewScene = isPreviewScene(sceneParam) ? sceneParam : 'default'
|
||||||
|
const theme = params.get('theme') === 'dark' ? 'dark' : 'light'
|
||||||
|
const width = params.get('width') === 'narrow' ? 'narrow' : 'wide'
|
||||||
|
|
||||||
|
document.documentElement.dataset.theme = theme
|
||||||
|
document.documentElement.dataset.width = width
|
||||||
|
document.documentElement.dataset.previewScene = scene
|
||||||
|
document.documentElement.dataset.isolatedPreview = '1'
|
||||||
|
|
||||||
|
// The real section only ships CSS as a string (`styles.ts`); the shell normally
|
||||||
|
// injects it beside the vendored client's stylesheet. The preview stands in for
|
||||||
|
// that shell injection, then adds its own panel/token styles afterwards.
|
||||||
|
const settingsStyle = document.createElement('style')
|
||||||
|
settingsStyle.id = 'rssh-settings-css'
|
||||||
|
settingsStyle.textContent = SETTINGS_CSS
|
||||||
|
document.head.appendChild(settingsStyle)
|
||||||
|
|
||||||
|
const style = document.createElement('style')
|
||||||
|
style.id = 'preview-shell-css'
|
||||||
|
style.textContent = previewCss
|
||||||
|
document.head.appendChild(style)
|
||||||
|
|
||||||
|
const previewWindow = window as unknown as Record<string, unknown>
|
||||||
|
previewWindow.__RSH_PREVIEW_SCENE__ = scene
|
||||||
|
previewWindow.__RSH_PREVIEW_THEME__ = theme
|
||||||
|
previewWindow.__RSH_PREVIEW_WIDTH__ = width
|
||||||
|
previewWindow.__RSH_PREVIEW_EXPECTED_TEXT__ = EXPECTED_MOUNT_TEXT
|
||||||
|
|
||||||
|
const api = createFakeApi(scene)
|
||||||
|
const t = makeT()
|
||||||
|
|
||||||
|
let SettingsSection: ReturnType<typeof createSettingsSection> | null = null
|
||||||
|
let createError = ''
|
||||||
|
try {
|
||||||
|
SettingsSection = createSettingsSection({ api })
|
||||||
|
} catch (error) {
|
||||||
|
createError = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
|
||||||
|
console.error('[preview] createSettingsSection threw', error)
|
||||||
|
}
|
||||||
|
|
||||||
|
const sceneLabel: Record<PreviewScene, string> = {
|
||||||
|
default: '默认(高级设置收起)',
|
||||||
|
expanded: '全部展开',
|
||||||
|
'import-ready': '导入弹窗(全部可导入)',
|
||||||
|
'import-partial': '导入部分失败',
|
||||||
|
workspaces: '远程工作区配置',
|
||||||
|
password: '密码认证表单',
|
||||||
|
'test-failure': '连接测试失败',
|
||||||
|
}
|
||||||
|
|
||||||
|
function PreviewApp() {
|
||||||
|
useEffect(() => {
|
||||||
|
const markReady = (): void => {
|
||||||
|
previewWindow.__RSH_PREVIEW_READY__ = true
|
||||||
|
document.documentElement.dataset.previewReady = '1'
|
||||||
|
}
|
||||||
|
const afterFonts = (): void => {
|
||||||
|
requestAnimationFrame(() => requestAnimationFrame(markReady))
|
||||||
|
}
|
||||||
|
const fonts = (document as unknown as { fonts?: { ready?: Promise<unknown> } }).fonts
|
||||||
|
if (fonts?.ready) {
|
||||||
|
fonts.ready.then(afterFonts).catch(afterFonts)
|
||||||
|
} else {
|
||||||
|
setTimeout(afterFonts, 0)
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="preview-page">
|
||||||
|
<div className="preview-shell">
|
||||||
|
<header className="preview-banner" data-preview-banner="isolated">
|
||||||
|
<span className="preview-banner__tag">隔离预览</span>
|
||||||
|
<span className="preview-banner__text">
|
||||||
|
真实组件 + 本地假 API 渲染 · 未接入当前 DSH GUI、未修改 daily profile · 场景:
|
||||||
|
{sceneLabel[scene]} · 主题:{theme === 'dark' ? '深色' : '浅色'} · 宽度:{width === 'narrow' ? '窄屏' : '宽屏'}
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main className="preview-panel" aria-label="DSH 设置面板容器(预览替身)">
|
||||||
|
<div className="preview-panel__bar">
|
||||||
|
<span className="preview-panel__crumb">设置 / 插件 / Remote SSH</span>
|
||||||
|
<span className="preview-panel__chip">隔离预览容器</span>
|
||||||
|
</div>
|
||||||
|
<div className="preview-panel__body" id="settings-mount">
|
||||||
|
{createError ? (
|
||||||
|
<div role="alert" className="preview-fallback" data-preview-create-error="1">
|
||||||
|
<h1>组件创建失败</h1>
|
||||||
|
<p>{createError}</p>
|
||||||
|
</div>
|
||||||
|
) : SettingsSection ? (
|
||||||
|
<SettingsSection t={t} />
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<footer className="preview-footer">
|
||||||
|
本页为隔离预览:数据全部来自 tools/preview/fake-api.ts,仅用于视觉核对;不含真实密码、私钥或真实主机凭据,不写入任何浏览器存储。
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById('preview-root') as HTMLElement).render(<PreviewApp />)
|
||||||
|
|
@ -0,0 +1,82 @@
|
||||||
|
/**
|
||||||
|
* Modal stub for the isolated preview.
|
||||||
|
*
|
||||||
|
* The real component imports `Modal` from
|
||||||
|
* `@deepseek-ai/dsh-client-ui-primitives`; the preview bundle aliases that
|
||||||
|
* package to this stub so the section renders without the shell. Props match
|
||||||
|
* the primitives contract: open / onClose / title / closeLabel / className /
|
||||||
|
* children. Focus management is intentionally minimal — the preview only
|
||||||
|
* needs a stable, visually faithful dialog shell.
|
||||||
|
*/
|
||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
import type { ReactNode } from 'react'
|
||||||
|
|
||||||
|
export interface ModalStubProps {
|
||||||
|
open?: boolean
|
||||||
|
onClose?: () => void
|
||||||
|
title?: ReactNode
|
||||||
|
closeLabel?: string
|
||||||
|
className?: string
|
||||||
|
children?: ReactNode
|
||||||
|
/** Any other primitive props are accepted and ignored (preview only). */
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Modal({
|
||||||
|
open = false,
|
||||||
|
onClose,
|
||||||
|
title,
|
||||||
|
closeLabel = '关闭',
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
}: ModalStubProps): ReactNode {
|
||||||
|
const dialogRef = useRef<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (open) dialogRef.current?.focus()
|
||||||
|
}, [open])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || typeof document === 'undefined') return undefined
|
||||||
|
const onKeyDown = (event: KeyboardEvent): void => {
|
||||||
|
if (event.key === 'Escape') onClose?.()
|
||||||
|
}
|
||||||
|
document.addEventListener('keydown', onKeyDown)
|
||||||
|
return () => document.removeEventListener('keydown', onKeyDown)
|
||||||
|
}, [open, onClose])
|
||||||
|
|
||||||
|
if (!open) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="preview-modal" data-preview-modal="1">
|
||||||
|
<div className="preview-modal__backdrop" onClick={() => onClose?.()} />
|
||||||
|
<div
|
||||||
|
ref={dialogRef}
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label={typeof title === 'string' ? title : undefined}
|
||||||
|
tabIndex={-1}
|
||||||
|
className={['preview-modal__panel', className].filter(Boolean).join(' ')}
|
||||||
|
>
|
||||||
|
{(title !== undefined || onClose) && (
|
||||||
|
<header className="preview-modal__header">
|
||||||
|
{title !== undefined && <span className="preview-modal__title">{title}</span>}
|
||||||
|
{onClose && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="preview-modal__close"
|
||||||
|
aria-label={closeLabel}
|
||||||
|
onClick={() => onClose()}
|
||||||
|
>
|
||||||
|
×
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
)}
|
||||||
|
<div className="preview-modal__body">{children}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default Modal
|
||||||
|
|
@ -0,0 +1,323 @@
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Isolated preview shell — DSH settings-panel stand-in + theme tokens */
|
||||||
|
/* */
|
||||||
|
/* Real DSH theme tokens are not available outside the shell, so the */
|
||||||
|
/* preview defines the same token names with representative light/ */
|
||||||
|
/* dark values. The component itself is rendered unmodified. */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
*,
|
||||||
|
*::before,
|
||||||
|
*::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme='light'] {
|
||||||
|
color-scheme: light;
|
||||||
|
|
||||||
|
--dsw-alias-label-primary: #1f2329;
|
||||||
|
--dsw-alias-label-secondary: #4e5969;
|
||||||
|
--dsw-alias-label-tertiary: #86909c;
|
||||||
|
--dsw-alias-label-caption: #a7adb8;
|
||||||
|
--dsw-alias-border-l1: rgba(15, 23, 42, 0.1);
|
||||||
|
--dsw-alias-border-l2: rgba(15, 23, 42, 0.16);
|
||||||
|
--dsw-alias-bg-layer-2: #ffffff;
|
||||||
|
--dsw-specific-input-major: #f2f3f5;
|
||||||
|
--dsw-alias-button-ghost-active-fill: rgba(15, 23, 42, 0.06);
|
||||||
|
--dsw-alias-button-ghost-active-hover: rgba(15, 23, 42, 0.09);
|
||||||
|
--dsw-alias-interactive-bg-hover: rgba(15, 23, 42, 0.05);
|
||||||
|
--dsw-alias-state-business-primary: #2f6bff;
|
||||||
|
--dsw-alias-state-success-primary: #12b76a;
|
||||||
|
--dsw-alias-state-error-primary: #e5484d;
|
||||||
|
--dsw-alias-markdown-code-block: #f4f5f7;
|
||||||
|
|
||||||
|
--preview-page-bg: #eef0f3;
|
||||||
|
--preview-page-pattern: rgba(15, 23, 42, 0.035);
|
||||||
|
--preview-panel-bg: #ffffff;
|
||||||
|
--preview-panel-shadow: 0 18px 40px rgba(15, 23, 42, 0.12);
|
||||||
|
--preview-banner-bg: #fff6e0;
|
||||||
|
--preview-banner-border: #f3c96b;
|
||||||
|
--preview-banner-text: #7a5200;
|
||||||
|
--preview-chip-bg: rgba(47, 107, 255, 0.1);
|
||||||
|
--preview-chip-text: #2450b8;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme='dark'] {
|
||||||
|
color-scheme: dark;
|
||||||
|
|
||||||
|
--dsw-alias-label-primary: #e9eaec;
|
||||||
|
--dsw-alias-label-secondary: #b6bac3;
|
||||||
|
--dsw-alias-label-tertiary: #8b909a;
|
||||||
|
--dsw-alias-label-caption: #6f747d;
|
||||||
|
--dsw-alias-border-l1: rgba(255, 255, 255, 0.12);
|
||||||
|
--dsw-alias-border-l2: rgba(255, 255, 255, 0.2);
|
||||||
|
--dsw-alias-bg-layer-2: #1e2024;
|
||||||
|
--dsw-specific-input-major: #2a2d33;
|
||||||
|
--dsw-alias-button-ghost-active-fill: rgba(255, 255, 255, 0.1);
|
||||||
|
--dsw-alias-button-ghost-active-hover: rgba(255, 255, 255, 0.14);
|
||||||
|
--dsw-alias-interactive-bg-hover: rgba(255, 255, 255, 0.08);
|
||||||
|
--dsw-alias-state-business-primary: #6f92ff;
|
||||||
|
--dsw-alias-state-success-primary: #34c77b;
|
||||||
|
--dsw-alias-state-error-primary: #ff6b70;
|
||||||
|
--dsw-alias-markdown-code-block: #16181c;
|
||||||
|
|
||||||
|
--preview-page-bg: #101114;
|
||||||
|
--preview-page-pattern: rgba(255, 255, 255, 0.045);
|
||||||
|
--preview-panel-bg: #1a1c20;
|
||||||
|
--preview-panel-shadow: 0 18px 40px rgba(0, 0, 0, 0.55);
|
||||||
|
--preview-banner-bg: #3a2d10;
|
||||||
|
--preview-banner-border: #8a6a1f;
|
||||||
|
--preview-banner-text: #ffdf9e;
|
||||||
|
--preview-chip-bg: rgba(111, 146, 255, 0.16);
|
||||||
|
--preview-chip-text: #b9cbff;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', 'Microsoft YaHei', 'PingFang SC', 'Noto Sans CJK SC', 'Noto Sans SC',
|
||||||
|
system-ui, sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
background-color: var(--preview-page-bg);
|
||||||
|
background-image:
|
||||||
|
linear-gradient(var(--preview-page-pattern) 1px, transparent 1px),
|
||||||
|
linear-gradient(90deg, var(--preview-page-pattern) 1px, transparent 1px);
|
||||||
|
background-size: 24px 24px;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-page {
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 28px 32px 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-shell {
|
||||||
|
width: min(980px, 100%);
|
||||||
|
margin: 0 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-banner {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--preview-banner-border);
|
||||||
|
background: var(--preview-banner-bg);
|
||||||
|
color: var(--preview-banner-text);
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-banner__tag {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--preview-banner-border);
|
||||||
|
background: rgba(255, 255, 255, 0.45);
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-theme='dark'] .preview-banner__tag {
|
||||||
|
background: rgba(0, 0, 0, 0.28);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-banner__text {
|
||||||
|
min-width: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-panel {
|
||||||
|
border-radius: 18px;
|
||||||
|
border: 1px solid var(--dsw-alias-border-l1);
|
||||||
|
background: var(--preview-panel-bg);
|
||||||
|
box-shadow: var(--preview-panel-shadow);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-panel__bar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 14px 22px;
|
||||||
|
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||||
|
background: var(--dsw-alias-bg-layer-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-panel__crumb {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.01em;
|
||||||
|
color: var(--dsw-alias-label-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-panel__chip {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
padding: 2px 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--preview-chip-bg);
|
||||||
|
color: var(--preview-chip-text);
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-panel__body {
|
||||||
|
padding: 26px 30px 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-footer {
|
||||||
|
margin: 0 auto;
|
||||||
|
max-width: 980px;
|
||||||
|
color: var(--dsw-alias-label-tertiary);
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Narrow variant: the shell behaves like a phone-width settings sheet. */
|
||||||
|
html[data-width='narrow'] .preview-page {
|
||||||
|
padding: 14px 12px 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
html[data-width='narrow'] .preview-panel__bar,
|
||||||
|
html[data-width='narrow'] .preview-panel__body {
|
||||||
|
padding-left: 16px;
|
||||||
|
padding-right: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Modal stub (aliased @deepseek-ai/dsh-client-ui-primitives Modal) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
.preview-modal {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 40;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__backdrop {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(8, 10, 14, 0.55);
|
||||||
|
backdrop-filter: blur(1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__panel {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: min(680px, 100%);
|
||||||
|
max-height: min(82vh, 760px);
|
||||||
|
border-radius: 16px;
|
||||||
|
border: 1px solid var(--dsw-alias-border-l2);
|
||||||
|
background: var(--dsw-alias-bg-layer-2);
|
||||||
|
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35);
|
||||||
|
overflow: hidden;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border-bottom: 1px solid var(--dsw-alias-border-l1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__title {
|
||||||
|
font-size: 15px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__close {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--dsw-alias-label-secondary);
|
||||||
|
font-size: 18px;
|
||||||
|
line-height: 1;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__close:hover {
|
||||||
|
background: var(--dsw-alias-interactive-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__close:focus-visible {
|
||||||
|
outline: 2px solid var(--dsw-alias-state-business-primary);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-modal__body {
|
||||||
|
padding: 18px 20px 20px;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
/* Smoke-test fallback component (only used with --smoke) */
|
||||||
|
/* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
.preview-fallback {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-fallback h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-fallback p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--dsw-alias-label-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-fallback section {
|
||||||
|
border: 1px solid var(--dsw-alias-border-l1);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-fallback button,
|
||||||
|
.preview-fallback input,
|
||||||
|
.preview-fallback select,
|
||||||
|
.preview-fallback textarea {
|
||||||
|
font: inherit;
|
||||||
|
color: var(--dsw-alias-label-primary);
|
||||||
|
background: var(--dsw-specific-input-major);
|
||||||
|
border: 1px solid var(--dsw-alias-border-l1);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 4px 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview-fallback label {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
margin: 6px 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--dsw-alias-label-secondary);
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
@echo off
|
||||||
|
rem Run the isolated Remote-SSH settings preview screenshots from a NORMAL user
|
||||||
|
rem terminal (not from inside a constrained / Low-integrity sandbox job).
|
||||||
|
rem Chromium cannot start its internal named-pipe IPC inside that sandbox.
|
||||||
|
setlocal
|
||||||
|
cd /d "%~dp0..\.."
|
||||||
|
"C:\Users\qyh15\.dsh\dsh-runtimes\dsh-primary-runtime\dependencies\node\bin\node.exe" "tools\preview-rssh-settings.mjs" %*
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
|
|
@ -0,0 +1,302 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* tools/preview/smoke-render.mjs
|
||||||
|
*
|
||||||
|
* Headless DOM smoke test for the isolated preview WITHOUT a browser: builds
|
||||||
|
* the same preview bundle (IIFE) and mounts the REAL
|
||||||
|
* `createSettingsSection({ api })` component inside jsdom, then replays the
|
||||||
|
* same interactions the screenshot script drives (expand, import, dirty badge,
|
||||||
|
* password auth, test failure). This catches React/render/selector breakage in
|
||||||
|
* environments where Chromium cannot start (Low-integrity sandbox job).
|
||||||
|
*
|
||||||
|
* Usage: node tools/preview/smoke-render.mjs
|
||||||
|
* Exit 0 when every scene renders and every assertion passes.
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs/promises'
|
||||||
|
import { existsSync } from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const ROOT = path.resolve(HERE, '..', '..')
|
||||||
|
const COMPONENT = path.join(ROOT, 'src', 'client', 'rssh-settings', 'index.tsx')
|
||||||
|
const MODAL_STUB = path.join(HERE, 'modal-stub.tsx')
|
||||||
|
const TEMP = path.join(os.tmpdir(), `rssh-preview-jsdom-${process.pid}`)
|
||||||
|
const BUNDLE = path.join(TEMP, 'preview.iife.js')
|
||||||
|
|
||||||
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||||
|
const log = message => console.log(`[jsdom-smoke] ${message}`)
|
||||||
|
|
||||||
|
async function buildBundle() {
|
||||||
|
if (!existsSync(COMPONENT)) throw new Error(`component missing: ${COMPONENT}`)
|
||||||
|
await fs.mkdir(TEMP, { recursive: true })
|
||||||
|
const { build } = await import('vite')
|
||||||
|
await build({
|
||||||
|
configFile: false,
|
||||||
|
root: HERE,
|
||||||
|
mode: 'production',
|
||||||
|
logLevel: 'error',
|
||||||
|
publicDir: false,
|
||||||
|
resolve: {
|
||||||
|
alias: [
|
||||||
|
{ find: /^#rssh-settings$/, replacement: COMPONENT },
|
||||||
|
{ find: /^@deepseek-ai\/dsh-client-ui-primitives$/, replacement: MODAL_STUB },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
esbuild: { jsx: 'automatic' },
|
||||||
|
build: {
|
||||||
|
outDir: TEMP,
|
||||||
|
emptyOutDir: true,
|
||||||
|
target: 'chrome120',
|
||||||
|
minify: false,
|
||||||
|
write: true,
|
||||||
|
lib: {
|
||||||
|
entry: path.join(HERE, 'main.tsx'),
|
||||||
|
formats: ['iife'],
|
||||||
|
name: 'RsshPreview',
|
||||||
|
fileName: () => 'preview.iife.js',
|
||||||
|
},
|
||||||
|
rollupOptions: { output: { inlineDynamicImports: true } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const code = await fs.readFile(BUNDLE, 'utf8')
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
|
||||||
|
async function mountScene(code, query) {
|
||||||
|
const { JSDOM } = await import('jsdom')
|
||||||
|
const dom = new JSDOM('<!doctype html><html><head></head><body><div id="preview-root"></div></body></html>', {
|
||||||
|
url: `http://127.0.0.1/index.html?${new URLSearchParams(query).toString()}`,
|
||||||
|
runScripts: 'dangerously',
|
||||||
|
pretendToBeVisual: true,
|
||||||
|
})
|
||||||
|
const errors = []
|
||||||
|
dom.window.addEventListener('error', event => errors.push(String(event.error || event.message)))
|
||||||
|
// Vite's production React bundle may still reference process.env when it is
|
||||||
|
// evaluated outside a bundler-tooled module; give the jsdom window a shim.
|
||||||
|
dom.window.process = { env: { NODE_ENV: 'production' } }
|
||||||
|
dom.window.eval(code)
|
||||||
|
return { dom, window: dom.window, document: dom.window.document, errors }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function waitFor(window, predicate, label, timeoutMs = 8000) {
|
||||||
|
const deadline = Date.now() + timeoutMs
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
try {
|
||||||
|
if (predicate(window)) return true
|
||||||
|
} catch {
|
||||||
|
/* DOM not ready yet */
|
||||||
|
}
|
||||||
|
await sleep(40)
|
||||||
|
}
|
||||||
|
throw new Error(`timeout waiting for ${label}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const queryOf = scene => `scene=${encodeURIComponent(scene)}&theme=light&width=wide`
|
||||||
|
|
||||||
|
const mountAndSettle = async (code, scene) => {
|
||||||
|
const mounted = await mountScene(code, { scene, theme: 'light', width: 'wide' })
|
||||||
|
await waitFor(mounted.window, w => w.__RSH_PREVIEW_READY__ === true, `${scene}: ready flag`)
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-root]'), `${scene}: root mounted`)
|
||||||
|
await waitFor(mounted.window, w => w.__RSH_PREVIEW_IDLE__ !== false, `${scene}: fake api idle`)
|
||||||
|
await sleep(400)
|
||||||
|
await waitFor(mounted.window, w => w.document.body.textContent.includes('我的连接'), `${scene}: section title`)
|
||||||
|
return mounted
|
||||||
|
}
|
||||||
|
|
||||||
|
const click = async (mounted, selector) => {
|
||||||
|
const element = mounted.document.querySelector(selector)
|
||||||
|
if (!element) throw new Error(`missing click target ${selector}`)
|
||||||
|
element.click()
|
||||||
|
await sleep(120)
|
||||||
|
}
|
||||||
|
|
||||||
|
const setValue = async (mounted, selector, value) => {
|
||||||
|
const element = mounted.document.querySelector(selector)
|
||||||
|
if (!element) throw new Error(`missing value target ${selector}`)
|
||||||
|
const control = element.matches('input,textarea,select') ? element : element.querySelector('input,textarea,select')
|
||||||
|
if (!control) throw new Error(`no control inside ${selector}`)
|
||||||
|
const proto =
|
||||||
|
control.tagName === 'SELECT'
|
||||||
|
? mounted.window.HTMLSelectElement.prototype
|
||||||
|
: control.tagName === 'TEXTAREA'
|
||||||
|
? mounted.window.HTMLTextAreaElement.prototype
|
||||||
|
: mounted.window.HTMLInputElement.prototype
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set
|
||||||
|
setter.call(control, value)
|
||||||
|
control.dispatchEvent(new mounted.window.Event('input', { bubbles: true }))
|
||||||
|
control.dispatchEvent(new mounted.window.Event('change', { bubbles: true }))
|
||||||
|
await sleep(120)
|
||||||
|
return control
|
||||||
|
}
|
||||||
|
|
||||||
|
const assert = (condition, label) => {
|
||||||
|
if (!condition) throw new Error(`assertion failed: ${label}`)
|
||||||
|
log(` ok: ${label}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runDefault(code) {
|
||||||
|
const mounted = await mountAndSettle(code, 'default')
|
||||||
|
try {
|
||||||
|
const root = mounted.document.querySelector('[data-rsui-root]')
|
||||||
|
assert(root, 'root has data-rsui-root')
|
||||||
|
assert(mounted.document.querySelectorAll('[data-rsui-connection]').length === 3, '3 connection cards')
|
||||||
|
assert(mounted.document.querySelectorAll('[data-rsui-workspace]').length === 2, '2 workspace cards')
|
||||||
|
const advanced = mounted.document.querySelector('[data-rsui-advanced-content]')
|
||||||
|
assert(advanced, 'advanced content mounted')
|
||||||
|
assert(advanced.hidden === true, 'advanced content collapsed (hidden)')
|
||||||
|
const addRegion = mounted.document.querySelector('[data-rsui-toggle-add]')?.getAttribute('aria-expanded')
|
||||||
|
assert(addRegion === 'true', 'add section initially expanded')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-field="port"]')?.value === '22', 'port defaults to 22')
|
||||||
|
assert(!mounted.document.querySelector('[data-rsui-import-dialog]'), 'import dialog closed')
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runExpanded(code) {
|
||||||
|
const mounted = await mountAndSettle(code, 'expanded')
|
||||||
|
try {
|
||||||
|
await click(mounted, '[data-rsui-toggle-advanced]')
|
||||||
|
const advanced = mounted.document.querySelector('[data-rsui-advanced-content]')
|
||||||
|
assert(advanced.hidden === false, 'advanced content expanded')
|
||||||
|
await click(mounted, '[data-rsui-toggle-workspaces]')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-toggle-workspaces]').getAttribute('aria-expanded') === 'true', 'workspaces expanded')
|
||||||
|
const expandButtons = [...mounted.document.querySelectorAll('[data-rsui-ws-expand]')]
|
||||||
|
assert(expandButtons.length === 2, 'two workspace expand buttons')
|
||||||
|
for (const button of expandButtons) {
|
||||||
|
button.click()
|
||||||
|
await sleep(120)
|
||||||
|
}
|
||||||
|
assert([...mounted.document.querySelectorAll('[data-rsui-ws-expand]')].every(button => button.getAttribute('aria-expanded') === 'true'), 'all workspace settings expanded')
|
||||||
|
await click(mounted, '[data-rsui-toggle-more]')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-field="proxyJump"]'), 'proxyJump field mounted')
|
||||||
|
await setValue(mounted, '[data-rsui-field="name"]', '超算集群(测试)')
|
||||||
|
await setValue(mounted, '[data-rsui-field="host"]', 'login.hpc.example.com')
|
||||||
|
await setValue(mounted, '[data-rsui-field="user"]', 'demo-user')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-field="host"]').value === 'login.hpc.example.com', 'host field controlled value updated')
|
||||||
|
assert(mounted.document.body.textContent.includes('高级设置'), 'advanced copy rendered')
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runImport(code, scene) {
|
||||||
|
const mounted = await mountAndSettle(code, scene)
|
||||||
|
try {
|
||||||
|
await click(mounted, '[data-rsui-import-open]')
|
||||||
|
await waitFor(mounted.window, w => w.document.querySelectorAll('[data-rsui-import-row]').length === 5, `${scene}: 5 import rows`)
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-import-dialog]'), 'import dialog rendered')
|
||||||
|
assert(/已选\s*5\s*\/\s*5/.test(mounted.document.body.textContent), 'selected count 5/5')
|
||||||
|
if (scene === 'import-partial') {
|
||||||
|
await click(mounted, '[data-rsui-import-submit]')
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-import-result]'), 'import result', 15000)
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-import-retry]'), 'retry button', 15000)
|
||||||
|
const text = mounted.document.querySelector('[data-rsui-import-result]').textContent
|
||||||
|
assert(/成功\s*3\s*个/.test(text), 'partial result reports 3 succeeded')
|
||||||
|
assert(/失败\s*2\s*个/.test(text), 'partial result reports 2 failed')
|
||||||
|
assert(text.includes('mirror.example.org') && text.includes('broken.example.net'), 'failed hosts listed with hostnames')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-import-retry]').textContent.includes('重试失败项'), 'retry-only button present')
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runWorkspaces(code) {
|
||||||
|
const mounted = await mountAndSettle(code, 'workspaces')
|
||||||
|
try {
|
||||||
|
await click(mounted, '[data-rsui-toggle-workspaces]')
|
||||||
|
for (const button of [...mounted.document.querySelectorAll('[data-rsui-ws-expand]')]) {
|
||||||
|
button.click()
|
||||||
|
await sleep(120)
|
||||||
|
}
|
||||||
|
const card = mounted.document.querySelector('[data-rsui-workspace]')
|
||||||
|
const textarea = card.querySelector('textarea')
|
||||||
|
assert(textarea, 'workspace textarea mounted')
|
||||||
|
const proto = mounted.window.HTMLTextAreaElement.prototype
|
||||||
|
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set
|
||||||
|
setter.call(textarea, `${textarea.value}\n_patch/`)
|
||||||
|
textarea.dispatchEvent(new mounted.window.Event('input', { bubbles: true }))
|
||||||
|
textarea.dispatchEvent(new mounted.window.Event('change', { bubbles: true }))
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-ws-dirty]'), 'unsaved badge')
|
||||||
|
assert(mounted.document.querySelector('[data-rsui-ws-dirty]').textContent.includes('未保存'), 'unsaved badge copy')
|
||||||
|
const bodyText = mounted.document.body.textContent
|
||||||
|
assert(bodyText.includes('与写回排除用途不同'), 'sync-exclude hint explains the difference from write-back exclude')
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runPassword(code) {
|
||||||
|
const mounted = await mountAndSettle(code, 'password')
|
||||||
|
try {
|
||||||
|
const select = await setValue(mounted, '[data-rsui-field="authMethod"]', 'password')
|
||||||
|
assert(select.value === 'password', 'auth method switched to password')
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-field="password"]'), 'password field')
|
||||||
|
const password = mounted.document.querySelector('[data-rsui-field="password"]')
|
||||||
|
assert(password.type === 'password', 'password input is masked')
|
||||||
|
assert(password.getAttribute('autocomplete') === 'new-password', 'password autocomplete=new-password')
|
||||||
|
await setValue(mounted, '[data-rsui-field="name"]', '实验室工作站(测试)')
|
||||||
|
assert(mounted.document.body.textContent.includes('已保存密码'), 'configured password badge rendered')
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runTestFailure(code) {
|
||||||
|
const mounted = await mountAndSettle(code, 'test-failure')
|
||||||
|
try {
|
||||||
|
await click(mounted, '[data-rsui-test]')
|
||||||
|
await waitFor(mounted.window, w => !!w.document.querySelector('[data-rsui-test-result][data-status="error"]'), 'error test result', 8000)
|
||||||
|
const result = mounted.document.querySelector('[data-rsui-test-result]')
|
||||||
|
assert(result.getAttribute('data-status') === 'error', 'test result status=error')
|
||||||
|
const text = result.textContent
|
||||||
|
assert(text.includes('连接失败'), 'failure title shown')
|
||||||
|
assert(text.includes('Connection timed out'), 'diagnostic stderr shown')
|
||||||
|
} finally {
|
||||||
|
mounted.dom.window.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
await fs.rm(TEMP, { recursive: true, force: true })
|
||||||
|
log('building IIFE preview bundle with vite')
|
||||||
|
const code = await buildBundle()
|
||||||
|
log(`bundle: ${BUNDLE} (${(code.length / 1024).toFixed(0)} KiB)`)
|
||||||
|
|
||||||
|
const cases = [
|
||||||
|
['01-default', runDefault],
|
||||||
|
['02-expanded', runExpanded],
|
||||||
|
['03-import-dialog', mountedCode => runImport(mountedCode, 'import-ready')],
|
||||||
|
['04-import-partial', mountedCode => runImport(mountedCode, 'import-partial')],
|
||||||
|
['05-workspaces', runWorkspaces],
|
||||||
|
['06-password-auth', runPassword],
|
||||||
|
['09-test-failure', runTestFailure],
|
||||||
|
]
|
||||||
|
const failures = []
|
||||||
|
for (const [name, runner] of cases) {
|
||||||
|
log(`scene ${name}`)
|
||||||
|
try {
|
||||||
|
await runner(code)
|
||||||
|
log(`scene ${name}: PASS`)
|
||||||
|
} catch (error) {
|
||||||
|
failures.push(`${name}: ${error.message}`)
|
||||||
|
log(`scene ${name}: FAIL — ${error.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log(failures.length ? `${failures.length} scene(s) failed` : 'all scenes passed')
|
||||||
|
return failures.length ? 1 : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
let exitCode = 1
|
||||||
|
try {
|
||||||
|
exitCode = await main()
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`[jsdom-smoke][error] ${error && error.stack ? error.stack : error}`)
|
||||||
|
exitCode = 1
|
||||||
|
} finally {
|
||||||
|
await fs.rm(TEMP, { recursive: true, force: true }).catch(() => {})
|
||||||
|
}
|
||||||
|
process.exit(exitCode)
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
/**
|
||||||
|
* Deterministic `t` seat for the isolated preview.
|
||||||
|
*
|
||||||
|
* The real section receives the shell locale service's bind. The preview has
|
||||||
|
* no shell, so it resolves the SAME dictionary the section registers
|
||||||
|
* (`zh` from `src/client/rssh-settings/i18n.ts`, single source of truth)
|
||||||
|
* with `{name}` interpolation. Identical input → identical text, every run.
|
||||||
|
*/
|
||||||
|
import type { SettingsTranslate } from '../../src/client/rssh-settings/contract.ts'
|
||||||
|
import { zh } from '../../src/client/rssh-settings/i18n.ts'
|
||||||
|
|
||||||
|
const DICTIONARY: Record<string, string> = zh as unknown as Record<string, string>
|
||||||
|
|
||||||
|
export const makeT = (): SettingsTranslate => {
|
||||||
|
return (key: string, params?: Record<string, string | number>): string => {
|
||||||
|
const template = DICTIONARY[key]
|
||||||
|
const raw = template === undefined ? key : template
|
||||||
|
if (!params) return raw
|
||||||
|
return raw.replace(/\{(\w+)\}/g, (match, name: string) => {
|
||||||
|
const value = params[name]
|
||||||
|
return value === undefined ? match : String(value)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Text the screenshot script expects to see once the section is mounted. */
|
||||||
|
export const EXPECTED_MOUNT_TEXT = DICTIONARY['connection.sectionTitle'] as string
|
||||||
|
|
@ -3,6 +3,6 @@ import { defineConfig } from 'vitest/config'
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
test: {
|
test: {
|
||||||
environment: 'node',
|
environment: 'node',
|
||||||
include: ['tests/**/*.test.ts'],
|
include: ['tests/**/*.test.ts', 'tests/**/*.test.tsx'],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
|
||||||