Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

refactor(ssh): rebuild dsh-tauri-ssh on the plugin spec (#823)

Mao Mra30a7d08a936
diff --git a/docs/audit/dsh-tauri-ssh.md b/docs/audit/dsh-tauri-ssh.md
new file mode 100644
index 00000000..92fd60cb
--- /dev/null
+++ b/docs/audit/dsh-tauri-ssh.md
@@ -0,0 +1,55 @@
+# ponytail-audit · dsh-tauri-ssh
+
+初审范围:`packages/dsh-tauri-ssh`,121 个 Git 跟踪文件(client 40、host 72、入口/共享/配置等 9;含 32 个测试文件)。以下建议中的行号为初审位置;16 项现已实施,处理与验证结果见末节。未运行插件构建,未读 archive。
+
+口径:逐文件阅读并核对仓内调用方、字符串协议及现有测试;按保守净删减行数排序,计入必要 import、调用点和 mock 改动,不重复计数。保留插件规范要求的分层、公开协议/生成 API、宽容 wire 校验、0600/0700 原子持久化、runtime generation/reconnect 守卫及测试断言。不沿用旧报告中已实施或已撤回的 SSH 建议。
+
+- delete: 关闭状态下的 draft 预填没有消费者:删除 initialized、首次全量 hydration effect、取消后的已保存行回填、添加成功后的 draft 回填;openEditor 始终先复制当前行,保持打开中的编辑缓冲和 secret 清理不变。[machines-section.tsx:652](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L652>)、[machines-section.tsx:682–744](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L682-L744>)。(-13 LOC)
+- shrink: 五个 progress 文案分支收为 ``if (progress !== undefined) return t(`progress.${progress.phase}`).replace('{attempt}', String(progress.attempt ?? '?')).replace('{total}', String(progress.total ?? '?'))``;按链式格式占四行,保留闭集 phase 校验、缺失数字的 `?` 和后续重试倒计时。[machines-section.tsx:499–516](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L499-L516>)。(-12 LOC)
+- shrink: 两份真实 POSIX sh 测试 runner 只差 async 修饰与临时脚本名;将现有 runCommand 提到文件作用域,删除另一份,保持 sandbox HOME、stdout/stderr/退出码归一化和全部用例断言。[bootstrap.test.ts:557–566](<packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts#L557-L566>)、[bootstrap.test.ts:807–816](<packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts#L807-L816>)。(-9 LOC)
+- shrink: SecretField 不需要复合字符串键字典、固定 span 配置和第二份 label JSX;直接传当前已保存行的 hasPassword/hasPassphrase 布尔值,使用 `placeholder={hasSecret ? t('secret.set') : t('secret.unset')}` 与已有 `<Field label={label}>`,删除 secretFlagsOf;保留秘密输入缓冲与实时已设置标记的区别。[machines-section.tsx:155–198](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L155-L198>)、[machines-section.tsx:418–448](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L418-L448>)、[machines-section.tsx:901](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L901>)。(-8 LOC)
+- stdlib: rowsOf 的循环累积改为 `return entriesOf(value).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)`;保留 entriesOf/machineRowOf 的全部信任边界校验、容错及默认值,不删解析器。[parsers.ts:174–182](<packages/dsh-tauri-ssh/src/client/apis/parsers.ts#L174-L182>)。(-6 LOC)
+- delete: Tailwind 迁移后 uiMock 的 cssr import/export 和 mountStyle 空实现已无调用方;直接删除,保留实际使用的 Button/Pill 等 mock,不减少测试场景。[ui-mock.ts:3](<packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts#L3>)、[ui-mock.ts:66–80](<packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts#L66-L80>)。(-6 LOC)
+- yagni: connectedMachinesOf 只是单调用点的拼接过滤包装;在原调用处直接用 `[...machinesState.machines, ...machinesState.discovered].filter(machine => machinesState.statuses[machine.id]?.state === 'connected')`,删除 helper 及不再需要的 MachineRow 类型导入。[sync-panel.tsx:60](<packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx#L60>)、[sync-panel.tsx:385–391](<packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx#L385-L391>)。(-6 LOC)
+- shrink: 自绘 tintBorder 开关和 SWITCH/SWITCH_ON CSS 改用 dsh-tauri-ui/client 已导出的 Switch,传 checked、disabled、label 和 onChange;同时补等价 Switch mock,保持现有颜色/开关测试有意义,净值已扣除 mock 增量。[machines-section.tsx:60–61](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L60-L61>)、[machines-section.tsx:402–412](<packages/dsh-tauri-ssh/src/client/components/machines-section.tsx#L402-L412>)、[共享 Switch 出口:54](<packages/dsh-tauri-ui/src/client/components/official.tsx#L54>)。(-4 LOC)
+- shrink: grantBuildKeys 重复远端白名单读取、合并、按需写回;保留 parseBuildAllowKeys 和空 keys 守卫,改为 `return carryWorkspaceAllowlist(session, profileName, { allowBuilds: Object.fromEntries(keys.map(key => [key, true])), onlyBuiltDependencies: [] })`,复用已存在的 helper。[sync.ts:101–113](<packages/dsh-tauri-ssh/src/host/service/sync.ts#L101-L113>)、[allowlist.ts:158–169](<packages/dsh-tauri-ssh/src/host/utils/allowlist.ts#L158-L169>)。(-4 LOC)
+- stdlib: buildPluginsBundle 手包 execFile Promise 改用 `promisify(execFile)`,保存返回的 pending,执行 `pending.child.stdin?.end()` 后 `const { stdout: tar } = await pending`;保留 encoding buffer、64 MiB maxBuffer、错误传播及 finally 清理,不直接丢掉 stdin EOF。[plugins-sync.ts:94–116](<packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts#L94-L116>)。(-4 LOC)
+- shrink: commitEnabled 与 setEnabled 重复写同样两个状态字段;调用方改用 `setEnabled(enabled, null)`,删除 commitEnabled,测试改调现有 action 而不删断言,保留 beginEnable/endEnable 和 service/store 分层。[machines store:69–80](<packages/dsh-tauri-ssh/src/client/store/modules/machines.ts#L69-L80>)、[machines service:55](<packages/dsh-tauri-ssh/src/client/service/machines.ts#L55>)、[machines store test:119](<packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts#L119>)。(-4 LOC)
+- shrink: mergeSyncResults 的新增/覆盖分支改为 `const key = syncKeyOf(item); const index = at.get(key) ?? merged.length; at.set(key, index); merged[index] = item`;保留索引 Map、root-aware key、原顺序及重复 previous 项行为,不采用会折叠 previous 重复项的整表 Map 替换。[sync.utils.ts:16–30](<packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts#L16-L30>)。(-3 LOC)
+- shrink: planRemoteInstall 已调用 assetMatrixFor 并取得已校验 nodeFilename;删除第二次 nodeFilenameFor 和 undefined 检查,直接用 `filename: matrix.nodeFilename, version: NODE_VERSION`,不删除共享平台校验或资产矩阵。[bootstrap.utils.ts:90–117](<packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts#L90-L117>)、[assets.ts:42–58](<packages/dsh-tauri-ssh/src/host/utils/assets.ts#L42-L58>)。(-3 LOC)
+- shrink: withinButton 手工 querySelectorAll/find/throw 改为已安装且已导入的 Testing Library:`return within(container).getByRole('button', { name: text }) as HTMLButtonElement`;保持同一容器、唯一精确按钮名和所有断言。[machines-section.test.tsx:597–602](<packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx#L597-L602>)。(-3 LOC)
+- yagni: tarPacker 是没有闭包配置的工厂;改为直接 `async function packSkills(dir: string, names: readonly string[]): Promise<Buffer>`,apply 注入函数而不是调用工厂,保留 maxBuffer、windowsHide、buffer 输出和空归档检查;有配置捕获的其他 reader/scanner 工厂不动。[local.ts:90–102](<packages/dsh-tauri-ssh/src/host/utils/local.ts#L90-L102>)、[apply.ts:35](<packages/dsh-tauri-ssh/src/host/apply.ts#L35>)。(-2 LOC)
+- shrink: describeError 与共享 messageOf 实现完全相同;两个 host 消费模块直接 import messageOf,删除内部重复 helper,不加兼容转发;净值已扣除两个 import,不把 route 中另加 import 的同式替换计为收益。[bootstrap.utils.ts:503–505](<packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts#L503-L505>)、[machine.ts:17](<packages/dsh-tauri-ssh/src/host/service/machine.ts#L17>)、[error.ts:1–3](<packages/dsh-tauri-ssh/src/shared/error.ts#L1-L3>)。(-1 LOC)
+
+核实:只读 Node assert 检查通过——merge 分支简化 30 组(含 previous 重复项)、中英 progress 文案 30 组、promisify 的 Buffer 输出与显式 stdin EOF。初审时未运行测试套件;以上净值为建议估算,不是最终 diff。未证明任何运行时依赖可安全移除。没有把大组件机械拆文件、可选 JSX assembler、重写单编辑器状态或删除 snapshot clone 计入净值。
+
+初审估算:net: -88 lines, -0 deps possible.
+
+## 处理结果
+
+- 16/16 项实施,无撤回。保留架构分层、wire 校验、秘密输入/已保存标记区分、快照克隆、权限模式和 runtime cancellation 守卫。
+- 按追加要求,将 SSH 的 61 个命名 Tailwind 字符串和 span 样式表内联到 JSX;保留业务/协议/校验常量,不改其他插件。其他插件多数直接写 className,少数旧组件的样式别名不作为继续保留的理由。
+- 当前 SSH 跟踪 diff:287 行新增、353 行删除;非 `.test.*` 文件净减少 126 行。新增 60 行归档回归测试后,SSH 实际合计净减少 6 行;无依赖变更。净值含共享 Switch mock 和新增断言,不以删测试换收益。
+- Testing Library 的角色查询 `name: string` 已精确匹配;没有 `exact` 选项,最终实现移除该非法选项。
+- 客户端整套:13 文件 / 156 测试通过;父级解析/合并相关 71 测试连续 5 个乱序 seed 通过;组件机器/同步 56 测试连续 5 个乱序 seed 通过,最终 3 组件文件 61 测试通过。
+- Host 便携回归 68/68、完整 machine 92/92 通过。新增归档测试验证 Buffer 输出、64 MiB 上限、stdin EOF 和失败清理;白名单测试保留已有项且避免无效写回。
+- 变异验证:错误 merge 索引使回归变红;改用 draft 的 secret flags 使刷新编辑回归变红,均已恢复。
+- SSH 整包:560 通过、11 失败、4 既有跳过;失败身份与改前 Windows 基线一致(10 个真实 POSIX sh / chmod / GNU tar 场景,1 个部署路径分隔符断言)。未增加跳过、放宽断言或构建插件。
+- 整仓 TypeScript 与 SSH ESLint 通过,diff whitespace 检查通过。
+
+## 追加:壳转发与 React Query
+
+- [请求层](<src/apis/http.ts>) 只将生成 API 的 method/path/payload 转为 `invoke('remote', { method, payload })`;生成 API/类型保留,不再从前端读取 serviceURL 或直接 HTTP 请求 SSH 插件。
+- [Rust remote](<src-tauri/src/bridge/remote.rs>) 严格放行 13 个生成端点,使用当前配置的 loopback 端口,禁用代理与重定向;GET 查询参数/其他方法 JSON body,404/405 与不可达错误区分。注册命令并删除旧 loopback HTTP capability,桌宠 HTTP 不受影响。
+- [useRemote](<src/hooks/use-remote.ts>) 由切换器挂载一次并在内部渲染连接弹窗;只向父层回报隧道 URL 和描边颜色。切换器在安装/恢复页保持挂载但隐藏 UI,保留启动寻址和轮询。查询、轮询、单飞、缓存和失效由 React Query 管理,连接/断开用 mutation;只保留窗口选择、粘性 URL、取消代次和弹窗交互状态。
+- 删除旧 remote store、SshApiClient、refreshing、booted、手写 timer 和测试注入层;既有切换/解析/界面/降级日志断言迁移,不删用例。查询失败保留缓存、缺 API 清空视图、迟到连接不抢切换。
+- Rust:`cargo check --locked --offline` 通过;remote 隔离 loopback 测试 15/15 通过,rustfmt 检查通过。前端相关 7 文件 / 58 测试连续 5 个乱序 seed(301–305)全部通过;变异缺 API 判定时 404/405 回归均失败,恢复后 seed 306 的 58 测试再通过。TypeScript/ESLint 通过。
+- 转发/查询首次实现时全仓 unit 实跑:227 文件通过,3 失败,2 既有跳过;2262 测试通过、13 失败、4 既有跳过。失败为上述 11 个 Windows SSH 基线,加 2 个未构建插件资源闭包用例(缺部署树中的 notification 包);没有新的失败身份。
+
+## 追加:remote 精简复核
+
+- [切换器](<src/layout/components/remote-switcher.tsx#L30-L55>) 直接调用 useRemote 并渲染连接弹窗;Webview/导航栏不再传递整包 Remote。隐藏 UI 不卸载查询,保留远端窗口启动寻址。
+- 删除重复 retry/可见性监听、cancelConnect 包装、未消费 wire 字段和单调用点 helper,保留实际字段校验、取消代次、粘性 URL 及窗口 focus 刷新;生产代码与配置净减少 68 行。
+- 原 14 个切换器用例迁移为真实 hook/QueryClient/弹窗与 native invoke 边界验证,新增 3 个集成回归;原 helper 的色点/描边断言迁入 UI,未弱化。相关 9 文件 / 68 测试在最终恢复后连续 5 个乱序 seed(511–515)通过;TypeScript、范围 ESLint 与 whitespace 检查通过。
+- 变异验证:重新搬运 remotePort 导致解析回归失败;忽略 tintBorder 导致 2 个 UI 回归失败,均已恢复并重验。新增原生 visibilitychange 回归证明 React Query 自带恢复刷新。
+- 本轮全仓 unit:229 文件通过、3 失败、2 既有跳过;2289 测试通过、13 失败、4 既有跳过。失败身份仍为同一 Windows/未构建资源基线;未构建插件、未增加跳过、未改无关 UI 样式。
diff --git a/docs/testing/s5-manual-acceptance.md b/docs/testing/s5-manual-acceptance.md
index 792d8428..7d5d7e07 100644
--- a/docs/testing/s5-manual-acceptance.md
+++ b/docs/testing/s5-manual-acceptance.md
@@ -133,4 +133,4 @@ S5 验收中「数据面全旅程」「壳层命令/单测/lint」「capability
| 3 插件套件 | `dsh-tauri-ssh` 356 过 4 跳过(包内 vitest.config;含 wire 悬空清理/端口等待用例);`dsh-tauri-ssh-ui` 96 过(包内 runner,含 Modal/步骤条/在飞反馈新用例) |
| 4 capability 复核 | `builder.rs security_tests::remote_popup_windows_are_scoped_by_glob_and_stay_loopback`;白名单仅增 `remote_bridge_ping`/`remote_open_window`;命令侧回环 http 校验单测 |
| 5 旧概念残留 | `Setting.remotes`/`remote_machine_*`/`remote-status` 等关键词全仓 grep 零命中(仅余 git-remote 无关词) |
-| 切换器/轮询/着色/降态逻辑 | `src/store/modules/remote/*.test.ts`(23 例)+ `remote-switcher.test.tsx`(9 例) |
+| 切换器/轮询/着色/降态逻辑(当前) | [useRemote 回归](<src/hooks/use-remote.test.ts>)、[切换纯逻辑](<src/hooks/use-remote.logic.test.ts>)、[载荷解析](<src/hooks/use-remote.machines.test.ts>)、[降级日志](<test/remote-poll-logging.test.ts>)、[切换器](<src/layout/components/remote-switcher.test.tsx>)、[连接弹窗](<src/layout/components/connect-dialog.test.tsx>);旧 remote store 已替换为 React Query hook |
diff --git a/docs/testing/s5-ssh-e2e-evidence.md b/docs/testing/s5-ssh-e2e-evidence.md
index 8c36d8f3..4554d043 100644
--- a/docs/testing/s5-ssh-e2e-evidence.md
+++ b/docs/testing/s5-ssh-e2e-evidence.md
@@ -13,7 +13,9 @@
- 本地实例:无头 `dsh web`(DSH_HOME=`~/.dsh.dev`,profile `s5e2e`,端口 3185,
挂载本 worktree 的 `dsh-tauri-ssh` / `dsh-tauri-ssh-ui` link: 包,见下方复现步骤)
- 远端机器:`dev`(Linux 5.4 x86_64,root + 密钥认证,`~/.ssh/config` 别名)
-- 驱动脚本:`scripts/e2e-ssh-data-plane.mjs`(/api-ssh HTTP 信封直驱,退出码 0 = 通过)
+- 驱动脚本:`scripts/e2e-ssh-data-plane.mjs`(REST 直驱 `/api/desktop/dsh-tauri-ssh`;
+ 2026-10 插件重构前的 `/api-ssh` 信封已废弃,脚本相应改写,退出码 0 = 通过)
+- 下方两条转录为改造前的脚本原始输出,保留原样(步骤日志串未变,仍可直接比对)
- 本文档转录的是脚本原始输出(`--out`),未做修饰。
## 结果:ALL STEPS PASSED ✅
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 7ba15482..5ea88c5c 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -20,6 +20,9 @@ export default antfu({
// genapi 产物:格式由生成器(prettier 默认)决定,不由项目 eslint 规约
'packages/*/src/client/apis/index.ts',
'packages/*/src/client/apis/index.type.ts',
+ // 同上:genapi 为应用壳生成的 REST 调用层(同目录的 http.ts 是手写实现,仍需 lint)
+ 'src/apis/remote.ts',
+ 'src/apis/remote.types.ts',
// 插件 Tailwind 产物:由 packages/dsh-tauri-ui/scripts/taiwindcss.ts 生成,转义后的选择器与体积
// 都不适合本仓 lint 规约
'packages/dsh-tauri-ui/src/client/styles/index.ts',
diff --git a/genapi.config.ts b/genapi.config.ts
index cabba2aa..5201ea8e 100644
--- a/genapi.config.ts
+++ b/genapi.config.ts
@@ -16,6 +16,15 @@ const plugins = [
'dsh-tauri-ui',
'dsh-tauri-notification',
'dsh-tauri-worktree',
+ 'dsh-tauri-ssh',
+]
+
+const SHELL_SERVERS = [
+ {
+ input: 'packages/dsh-tauri-ssh/src/host/routes',
+ output: { main: 'src/apis/remote.ts', type: 'src/apis/remote.types.ts' },
+ meta: { baseURL: JSON.stringify('/api/desktop/dsh-tauri-ssh'), import: { http: './http' } },
+ },
]
export default defineConfig({
@@ -23,9 +32,12 @@ export default defineConfig({
meta: { import: { http: 'dsh-tauri/client' } },
// worktree 的根级 routes/post.ts、routes/delete.ts 生成名是 `post` / 保留字 `delete`
patch: { operations: { delete: 'deleteWorktree', post: 'postWorktree' } },
- servers: plugins.map(plugin => ({
- input: `packages/${plugin}/src/host/routes`,
- output: { main: `packages/${plugin}/src/client/apis/index.ts` },
- meta: { baseURL: JSON.stringify(`/api/desktop/${plugin}`) },
- })),
+ servers: [
+ ...plugins.map(plugin => ({
+ input: `packages/${plugin}/src/host/routes`,
+ output: { main: `packages/${plugin}/src/client/apis/index.ts` },
+ meta: { baseURL: JSON.stringify(`/api/desktop/${plugin}`) },
+ })),
+ ...SHELL_SERVERS,
+ ],
})
diff --git a/packages/dsh-tauri-ssh/package.json b/packages/dsh-tauri-ssh/package.json
index 21d479c8..fc147949 100644
--- a/packages/dsh-tauri-ssh/package.json
+++ b/packages/dsh-tauri-ssh/package.json
@@ -2,7 +2,7 @@
"name": "dsh-tauri-ssh",
"type": "module",
"version": "0.6.7",
- "description": "DSH 远程主机宿主插件:SSH 连接管理(TOFU 主机密钥、~/.ssh/config 自动发现)、远程 dsh web 自动启动、回环隧道、同源 /api-ssh 路由,以及机器增删改、连接/测试/断开与一键远程安装的设置页。",
+ "description": "DSH 远程主机宿主插件:SSH 连接管理(TOFU 主机密钥、~/.ssh/config 自动发现)、远程 dsh web 自动启动、回环隧道、/api/desktop/dsh-tauri-ssh REST 路由,以及机器增删改、连接/测试/断开与一键远程安装的设置页。",
"author": "Hairyf <[email protected]>",
"license": "MIT",
"homepage": "https://github.com/dsh-tauri-desk/deepseek-harness-desktop/tree/main/packages/dsh-tauri-ssh",
@@ -38,9 +38,7 @@
"dsh": {
"client": {
"inject": [
- "@deepseek-ai/dsh-client-ui-renderer",
"@deepseek-ai/dsh-client-ui-settings",
- "@deepseek-ai/dsh-client-ui-primitives",
"@deepseek-ai/dsh-client-locale",
"dsh-tauri",
"dsh-tauri-ui"
@@ -72,7 +70,6 @@
"yaml": "catalog:testing"
},
"devDependencies": {
- "@deepseek-ai/dsh-client-ui-primitives": "catalog:dsh",
"@testing-library/dom": "catalog:testing",
"@testing-library/react": "catalog:testing",
"@types/node": "catalog:types",
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.test.ts b/packages/dsh-tauri-ssh/src/client/apis/index.test.ts
new file mode 100644
index 00000000..898ffedb
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/apis/index.test.ts
@@ -0,0 +1,89 @@
+// @vitest-environment node
+import type { MachineRow } from '../types/index'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import * as api from './index'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const API = api.baseURL
+
+const machineA: MachineRow = {
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ hasPassword: true,
+ hasPassphrase: false,
+ remotePort: 3080,
+}
+const saveRow = { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 }
+
+beforeEach(() => {
+ resetWire()
+})
+
+describe('the request layer', () => {
+ it('sends every request to its own REST endpoint', async () => {
+ const table: { run: () => Promise<unknown>, url: string, http: string, body?: Record<string, unknown>, params?: Record<string, unknown>, value: unknown, result: unknown }[] = [
+ { run: () => api.getSettings(), url: '/settings', http: 'GET', value: { enabled: true }, result: { enabled: true } },
+ { run: () => api.postSettings({ enabled: false }), url: '/settings', http: 'POST', body: { enabled: false }, value: { enabled: false }, result: { enabled: false } },
+ { run: () => api.getSessionRole(), url: '/session/role', http: 'GET', value: { role: 'remote', remote: true, origin: 'ops' }, result: { role: 'remote', remote: true, origin: 'ops' } },
+ { run: () => api.getMachines(), url: '/machines', http: 'GET', value: { items: [machineA], discovered: [] }, result: { items: [machineA], discovered: [] } },
+ { run: () => api.getMachinesEvents({ machineId: 'a' }), url: '/machines/events', http: 'GET', params: { machineId: 'a' }, value: { items: [] }, result: { items: [] } },
+ { run: () => api.getMachinesEvents({ machineId: 'a', sinceSeq: 7 }), url: '/machines/events', http: 'GET', params: { machineId: 'a', sinceSeq: 7 }, value: { items: [] }, result: { items: [] } },
+ { run: () => api.postMachinesTest({ machineId: 'a' }), url: '/machines/test', http: 'POST', body: { machineId: 'a' }, value: { ok: true, banner: 'Linux alpha' }, result: { ok: true, banner: 'Linux alpha' } },
+ { run: () => api.postMachinesConnect({ machineId: 'a' }), url: '/machines/connect', http: 'POST', body: { machineId: 'a' }, value: { tunnelBaseUrl: 'http://127.0.0.1:1' }, result: { tunnelBaseUrl: 'http://127.0.0.1:1' } },
+ { run: () => api.postMachinesDisconnect({ machineId: 'a' }), url: '/machines/disconnect', http: 'POST', body: { machineId: 'a' }, value: {}, result: {} },
+ { run: () => api.postMachinesInstall({ machineId: 'a' }), url: '/machines/install', http: 'POST', body: { machineId: 'a' }, value: { dshPath: '/bin/dsh', credentialsCopied: true }, result: { dshPath: '/bin/dsh', credentialsCopied: true } },
+ { run: () => api.postMachines({ machineId: 'a', row: saveRow }), url: '/machines', http: 'POST', body: { machineId: 'a', row: saveRow }, value: {}, result: {} },
+ { run: () => api.deleteMachines({ machineId: 'a' }), url: '/machines', http: 'DELETE', body: { machineId: 'a' }, value: {}, result: {} },
+ { run: () => api.getSyncPreview(), url: '/sync/preview', http: 'GET', value: { plugins: [], skills: [] }, result: { plugins: [], skills: [] } },
+ { run: () => api.postSyncApply({ machineId: 'a', plugins: [], skills: [] }), url: '/sync/apply', http: 'POST', body: { machineId: 'a', plugins: [], skills: [] }, value: { items: [] }, result: { items: [] } },
+ ]
+ for (const entry of table) {
+ resetWire()
+ answer(() => replies.ok(entry.value))
+ await expect(entry.run()).resolves.toEqual(entry.result)
+ expect(sent).toEqual([{
+ url: `${API}${entry.url}`,
+ http: entry.http,
+ body: entry.body ?? {},
+ params: entry.params ?? {},
+ }])
+ }
+ })
+
+ it('hands the decoded body through untouched', async () => {
+ answer(() => replies.ok({ items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' }], discovered: [] }))
+ await expect(api.getMachines()).resolves.toEqual({
+ items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' }],
+ discovered: [],
+ })
+ })
+
+ it('reads a malformed sync payload as null instead of throwing', async () => {
+ answer(() => replies.ok({ plugins: 'nope' }))
+ await expect(api.getSyncPreview()).resolves.toEqual({ plugins: 'nope' })
+ resetWire()
+ answer(() => replies.ok({}))
+ await expect(api.postSyncApply({ machineId: 'a', plugins: [], skills: [] })).resolves.toEqual({})
+ })
+
+ it('surfaces a host-provided failure as its prose', async () => {
+ answer(() => replies.fail('refused'))
+ await expect(api.postMachinesConnect({ machineId: 'a' })).rejects.toThrowError('请求失败 (400): refused')
+ })
+
+ it('reports a missing endpoint with its status', async () => {
+ answer(() => replies.http(405))
+ await expect(api.getSettings()).rejects.toThrowError('请求失败 (405)')
+ })
+
+ it('resolves an empty body as undefined', async () => {
+ answer(() => replies.empty())
+ await expect(api.getSettings()).resolves.toBeUndefined()
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.ts b/packages/dsh-tauri-ssh/src/client/apis/index.ts
new file mode 100644
index 00000000..c5e21ec1
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/apis/index.ts
@@ -0,0 +1,76 @@
+/*
+ * @title dsh-tauri-ssh
+ * @swagger 2.0
+ * @version 0.0.0
+ */
+
+import type { FetchOptions } from "dsh-tauri/client";
+import { ofetch } from "dsh-tauri/client";
+import type * as Types from "./index.type";
+
+export const baseURL = "/api/desktop/dsh-tauri-ssh";
+
+/** @method post */
+export function postMachinesConnect(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshConnectResponse>("/machines/connect", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getMachines(options?: FetchOptions) {
+ return ofetch<Types.SshMachinesResponse>("/machines", { baseURL, method: "get", ...options });
+}
+
+/** @method post */
+export function postMachines(body: Types.SshMachineSaveBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines", { baseURL, method: "post", body, ...options });
+}
+
+/** @method delete */
+export function deleteMachines(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines", { baseURL, method: "delete", body, ...options });
+}
+
+/** @method post */
+export function postMachinesDisconnect(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines/disconnect", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getMachinesEvents(params?: Types.GetMachinesEventsQuery, options?: FetchOptions) {
+ return ofetch<Types.SshMachineEventsResponse>("/machines/events", { baseURL, method: "get", params, ...options });
+}
+
+/** @method post */
+export function postMachinesInstall(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshInstallResponse>("/machines/install", { baseURL, method: "post", body, ...options });
+}
+
+/** @method post */
+export function postMachinesTest(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshTestResponse>("/machines/test", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getSessionRole(options?: FetchOptions) {
+ return ofetch<Types.SshSessionRoleResponse>("/session/role", { baseURL, method: "get", ...options });
+}
+
+/** @method get */
+export function getSettings(options?: FetchOptions) {
+ return ofetch<Types.SshSettingsResponse>("/settings", { baseURL, method: "get", ...options });
+}
+
+/** @method post */
+export function postSettings(body: Types.SshSettingsBody, options?: FetchOptions) {
+ return ofetch<Types.SshSettingsResponse>("/settings", { baseURL, method: "post", body, ...options });
+}
+
+/** @method post */
+export function postSyncApply(body: Types.SyncApplyBody, options?: FetchOptions) {
+ return ofetch<Types.SyncApplyResponse>("/sync/apply", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getSyncPreview(options?: FetchOptions) {
+ return ofetch<Types.SyncPreviewResponse>("/sync/preview", { baseURL, method: "get", ...options });
+}
diff --git a/packages/dsh-tauri-ssh/src/client/apis/index.type.ts b/packages/dsh-tauri-ssh/src/client/apis/index.type.ts
new file mode 100644
index 00000000..ff14c9a8
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/apis/index.type.ts
@@ -0,0 +1,154 @@
+export type SshConnectResponse = {
+ tunnelBaseUrl?: string;
+ error?: string;
+};
+export type SshActionResponse = {
+ error?: string;
+};
+export type SshMachineEventsResponse = {
+ items?: SshMachineEventItem[];
+ nextSeq?: number;
+ error?: string;
+};
+export type SshMachineEventItem = {
+ seq?: number;
+ ts?: string;
+ machineId?: string;
+ stage?: string;
+ line?: string;
+ terminal?: string;
+ reason?: string;
+};
+export type SshMachinesResponse = {
+ enabled?: boolean;
+ items?: SshMachineListItem[];
+ discovered?: SshMachineListItem[];
+ error?: string;
+};
+export type SshMachineListItem = {
+ id?: string;
+ name?: string;
+ host?: string;
+ port?: number;
+ user?: string;
+ hasPassword?: boolean;
+ hasPassphrase?: boolean;
+ remotePort?: number;
+ profileName?: string;
+ startCommand?: string;
+ color?: string;
+ tintBorder?: boolean;
+ state?: SshConnectionState;
+ tunnelBaseUrl?: string;
+ lastError?: string;
+ dshMissing?: boolean;
+ progress?: SshProgress;
+ nextRetryAt?: number;
+ authMethod?: SshAuthMethod;
+};
+export type SshConnectionState = "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up";
+export type SshProgress = {
+ phase: SshProgressPhase;
+ attempt?: number;
+ total?: number;
+ item?: string;
+ log?: string;
+};
+export type SshProgressPhase = "handshake" | "starting" | "probing" | "installing" | "syncing";
+export type SshAuthMethod = "agent" | "key" | "password";
+export type SshInstallResponse = {
+ installed?: string[];
+ dshRef?: string;
+ dshVersion?: string;
+ dshPath?: string;
+ credentialsCopied?: boolean;
+ credentialsError?: string;
+ error?: string;
+};
+export type SshMachineRowBody = {
+ name?: string;
+ host?: string;
+ port?: number;
+ user?: string;
+ remotePort?: number;
+ profileName?: string;
+ startCommand?: string;
+ color?: string;
+ tintBorder?: boolean;
+};
+export type SshMachineSecretsBody = {
+ password?: string;
+ passphrase?: string;
+};
+export type SshTestResponse = {
+ ok?: boolean;
+ banner?: string;
+ message?: string;
+ error?: string;
+};
+export type SshSessionRoleResponse = {
+ role?: string;
+ remote?: boolean;
+ origin?: string;
+ error?: string;
+};
+export type SshSettingsResponse = {
+ enabled?: boolean;
+ error?: string;
+};
+export type SyncPluginRefBody = {
+ name?: string;
+ spec?: string;
+};
+export type SyncSkillRefBody = {
+ name?: string;
+ root?: string;
+};
+export type SyncApplyResponse = {
+ items?: SyncApplyItemResult[];
+ error?: string;
+};
+export type SyncApplyItemResult = {
+ kind?: string;
+ name?: string;
+ root?: string;
+ ok?: boolean;
+ error?: string;
+ log?: string;
+};
+export type SyncPreviewResponse = {
+ plugins?: SyncPreviewPluginItem[];
+ skills?: SyncPreviewSkillItem[];
+ error?: string;
+};
+export type SyncPreviewPluginItem = {
+ name?: string;
+ spec?: string;
+ syncable?: boolean;
+ reason?: string;
+};
+export type SyncPreviewSkillItem = {
+ name?: string;
+ root?: string;
+};
+
+export interface SshMachineIdBody {
+ machineId?: string;
+}
+export interface SshMachineSaveBody {
+ machineId?: string;
+ row?: SshMachineRowBody;
+ secrets?: SshMachineSecretsBody;
+}
+export interface SshSettingsBody {
+ enabled?: boolean;
+}
+export interface SyncApplyBody {
+ machineId?: string;
+ plugins?: SyncPluginRefBody[];
+ skills?: SyncSkillRefBody[];
+}
+export interface GetMachinesEventsQuery {
+ machineId?: string;
+ sinceSeq?: number;
+}
diff --git a/packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts b/packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts
new file mode 100644
index 00000000..deccae89
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/apis/parsers.test.ts
@@ -0,0 +1,296 @@
+import type { MachineRow, MachineStatus } from '../types/index'
+import { describe, expect, it } from 'vitest'
+import {
+ enabledOf,
+ errorMessageOf,
+ installResultOf,
+ isTransportError,
+ machineEventsOf,
+ machineListOf,
+ savePayloadOf,
+ sessionRoleOf,
+ syncApplyResultOf,
+ syncPreviewOf,
+ testResultOf,
+ tunnelUrlOf,
+} from './parsers'
+
+const machineA: MachineRow = {
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ hasPassword: true,
+ hasPassphrase: false,
+ remotePort: 3080,
+}
+const machineB: MachineRow = {
+ ...machineA,
+ id: 'b',
+ name: 'beta',
+ host: '10.0.0.2',
+ port: 2222,
+ user: 'deploy',
+ hasPassword: false,
+ hasPassphrase: true,
+ remotePort: 3000,
+ startCommand: 'dsh web --host 127.0.0.1 --port 3000',
+}
+
+function rowOf(value: unknown): MachineRow | undefined {
+ return machineListOf({ items: [value] }).machines[0]
+}
+
+function stateOf(value: unknown): MachineStatus['state'] | undefined {
+ return machineListOf({ items: [{ id: 'a', state: value }] }).statuses.a?.state
+}
+
+describe('machine rows', () => {
+ it('parses a well-formed redacted row', () => {
+ expect(rowOf(machineA)).toEqual(machineA)
+ expect(rowOf(machineB)).toEqual(machineB)
+ })
+
+ it('rejects malformed rows', () => {
+ expect(rowOf(undefined)).toBeUndefined()
+ expect(rowOf('x')).toBeUndefined()
+ expect(rowOf({ ...machineA, id: '' })).toBeUndefined()
+ expect(rowOf({ ...machineA, id: 5 })).toBeUndefined()
+ expect(rowOf({ ...machineA, name: 5 })).toBeUndefined()
+ expect(rowOf({ ...machineA, host: '' })).toBeUndefined()
+ expect(rowOf({ ...machineA, user: 5 })).toBeUndefined()
+ })
+
+ it('falls back to defaults for absent numeric fields and optional startCommand', () => {
+ const row = rowOf({ ...machineA, port: undefined, remotePort: undefined, startCommand: '', hasPassword: undefined })
+ expect(row).toMatchObject({ port: 22, remotePort: 3080, hasPassword: false })
+ expect(row).not.toHaveProperty('startCommand')
+ })
+
+ it('accepts an empty user (resolved from ~/.ssh config or the OS user)', () => {
+ const row = rowOf({ ...machineA, user: '' })
+ expect(row).toMatchObject({ user: '' })
+ })
+
+ it('keeps only a well-formed profile name and a true tint flag', () => {
+ expect(rowOf({ ...machineA, profileName: ' dev-box ', color: '', tintBorder: false }))
+ .toEqual({ ...machineA, profileName: 'dev-box' })
+ expect(rowOf({ ...machineA, profileName: 'bad name' })).not.toHaveProperty('profileName')
+ expect(rowOf({ ...machineA, profileName: 7 })).not.toHaveProperty('profileName')
+ expect(rowOf({ ...machineA, color: '#ff0000', tintBorder: true }))
+ .toMatchObject({ color: '#ff0000', tintBorder: true })
+ })
+})
+
+describe('savePayloadOf', () => {
+ it('builds the config row and carries only typed secrets', () => {
+ expect(savePayloadOf(machineB, { passphrase: 'PHRASE', password: '' })).toEqual({
+ machineId: 'b',
+ row: {
+ name: 'beta',
+ host: '10.0.0.2',
+ port: 2222,
+ user: 'deploy',
+ remotePort: 3000,
+ startCommand: 'dsh web --host 127.0.0.1 --port 3000',
+ },
+ secrets: { passphrase: 'PHRASE' },
+ })
+ expect(savePayloadOf(machineA, {})).toEqual({
+ machineId: 'a',
+ row: { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },
+ })
+ expect(savePayloadOf({ ...machineA, startCommand: '' }, {})).not.toHaveProperty('row.startCommand')
+ })
+})
+
+describe('machineEventsOf', () => {
+ it('parses well-formed events and drops malformed ones', () => {
+ expect(machineEventsOf({ items: [
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
+ { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
+ { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
+ ] })).toEqual([
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
+ { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
+ { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
+ ])
+ expect(machineEventsOf(undefined)).toEqual([])
+ expect(machineEventsOf({ items: 'nope' })).toEqual([])
+ expect(machineEventsOf({ items: [{ machineId: 'a', line: 'x' }, 'junk'] })).toEqual([])
+ expect(machineEventsOf({ items: [{ seq: 1, ts: 1_700_000_000, machineId: 'a', line: 'x' }] })).toEqual([])
+ expect(machineEventsOf({ items: [{ seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', line: 'x', terminal: true }] })[0]).not.toHaveProperty('terminal')
+ })
+})
+
+describe('machineListOf', () => {
+ it('tolerates a list response without the items key', () => {
+ expect(machineListOf({})).toEqual({ machines: [], discovered: [], statuses: {} })
+ expect(machineListOf(undefined)).toEqual({ machines: [], discovered: [], statuses: {} })
+ })
+
+ it('parses the manual machines, the discovered aliases, and their live statuses', () => {
+ const snapshot = machineListOf({
+ items: [
+ { ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' },
+ { ...machineB, state: 'disconnected', lastError: 'auth failed' },
+ { ...machineA, id: 'c', name: 'gamma', state: 'disconnected' },
+ ],
+ discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root', hasPassword: false, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' }],
+ })
+ expect(snapshot.machines.map(row => row.id)).toEqual(['a', 'b', 'c'])
+ expect(snapshot.discovered.map(row => row.id)).toEqual(['dev'])
+ expect(snapshot.discovered[0]).toMatchObject({ host: 'dev', user: 'root', hasPassword: false, hasPassphrase: false })
+ expect(snapshot.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
+ expect(snapshot.statuses.b).toEqual({ state: 'disconnected', lastError: 'auth failed' })
+ expect(snapshot.statuses.c).toEqual({ state: 'disconnected' })
+ expect(snapshot.statuses.dev).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' })
+ })
+
+ it('reads the C-STATE states, the retry instant, the auth method, the progress, and dshMissing', () => {
+ const snapshot = machineListOf({
+ items: [
+ { ...machineA, state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' },
+ { ...machineA, id: 'b', state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } },
+ { ...machineA, id: 'c', state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true },
+ ],
+ })
+ expect(snapshot.statuses.a).toMatchObject({ state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' })
+ expect(snapshot.statuses.b).toEqual({ state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } })
+ expect(snapshot.statuses.c).toMatchObject({ dshMissing: true, lastError: 'dsh is not installed' })
+ })
+
+ it('drops status entries without an id and reads unknown states as disconnected', () => {
+ const snapshot = machineListOf({ items: [{ ...machineA, id: '', state: 'connected' }, { ...machineA, id: 'a', state: 'warping' }] })
+ expect(snapshot.machines.map(row => row.id)).toEqual(['a'])
+ expect(snapshot.statuses.a?.state).toBe('disconnected')
+ })
+})
+
+describe('machine lifecycle states', () => {
+ it('reads the six C-STATE values and nothing else', () => {
+ for (const state of ['disconnected', 'testing', 'connecting', 'connected', 'reconnecting', 'given-up'])
+ expect(stateOf(state)).toBe(state)
+ expect(stateOf('warping')).toBe('disconnected')
+ expect(stateOf(undefined)).toBe('disconnected')
+ })
+})
+
+describe('syncPreviewOf', () => {
+ it('parses the previewed plugins and skills', () => {
+ expect(syncPreviewOf({
+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }],
+ skills: [{ name: 's', root: 'dsh' }],
+ })).toEqual({
+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }],
+ skills: [{ name: 's', root: 'dsh' }],
+ })
+ })
+
+ it('keeps the unsyncable reason and drops malformed entries', () => {
+ expect(syncPreviewOf({
+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: false, reason: 'local dev link' }, { name: 'x' }, 'junk'],
+ skills: [{ name: 's', root: 'dsh' }, { root: 'dsh' }],
+ })).toEqual({
+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: false, reason: 'local dev link' }],
+ skills: [{ name: 's', root: 'dsh' }],
+ })
+ })
+
+ it('reads a wrong shape as null', () => {
+ expect(syncPreviewOf(undefined)).toBeNull()
+ expect(syncPreviewOf({ plugins: [] })).toBeNull()
+ expect(syncPreviewOf({ plugins: 'nope', skills: [] })).toBeNull()
+ })
+})
+
+describe('syncApplyResultOf', () => {
+ it('parses the per-item results and drops malformed entries', () => {
+ expect(syncApplyResultOf({ items: [
+ { kind: 'plugin', name: 'p', ok: true },
+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1', log: 'boom' },
+ { kind: 'nope', name: 'x', ok: true },
+ { kind: 'plugin', name: 'y' },
+ 'junk',
+ ] })).toEqual({ items: [
+ { kind: 'plugin', name: 'p', ok: true },
+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1', log: 'boom' },
+ ] })
+ })
+
+ it('reads a wrong shape as null', () => {
+ expect(syncApplyResultOf(undefined)).toBeNull()
+ expect(syncApplyResultOf({})).toBeNull()
+ expect(syncApplyResultOf({ items: 'nope' })).toBeNull()
+ })
+})
+
+describe('enabledOf', () => {
+ it('reads a boolean switch and nothing else', () => {
+ expect(enabledOf({ enabled: true })).toBe(true)
+ expect(enabledOf({ enabled: false })).toBe(false)
+ expect(enabledOf({})).toBeUndefined()
+ expect(enabledOf({ enabled: 'yes' })).toBeUndefined()
+ expect(enabledOf(undefined)).toBeUndefined()
+ })
+})
+
+describe('sessionRoleOf', () => {
+ it('reads the remote flag and the originating host', () => {
+ expect(sessionRoleOf({ role: 'remote', remote: true, origin: 'ops' })).toEqual({ remote: true, origin: 'ops' })
+ expect(sessionRoleOf({ role: 'local', remote: false })).toEqual({ remote: false })
+ expect(sessionRoleOf(undefined)).toEqual({ remote: false })
+ expect(sessionRoleOf({ remote: 'yes', origin: '' })).toEqual({ remote: false })
+ })
+})
+
+describe('testResultOf', () => {
+ it('reads the probe verdict and its prose', () => {
+ expect(testResultOf({ ok: true, banner: 'Linux alpha' })).toEqual({ ok: true, banner: 'Linux alpha' })
+ expect(testResultOf({ ok: false, message: 'auth failed' })).toEqual({ ok: false, message: 'auth failed' })
+ expect(testResultOf({ ok: true })).toEqual({ ok: true })
+ expect(testResultOf(undefined)).toEqual({ ok: false })
+ })
+})
+
+describe('tunnelUrlOf', () => {
+ it('reads the tunnel url or nothing at all', () => {
+ expect(tunnelUrlOf({ tunnelBaseUrl: 'http://127.0.0.1:1' })).toBe('http://127.0.0.1:1')
+ expect(tunnelUrlOf({})).toBe('')
+ expect(tunnelUrlOf(undefined)).toBe('')
+ })
+})
+
+describe('installResultOf', () => {
+ it('reads the install outcome and its optional credential error', () => {
+ expect(installResultOf({ dshPath: '/bin/dsh', credentialsCopied: true }))
+ .toEqual({ dshPath: '/bin/dsh', credentialsCopied: true })
+ expect(installResultOf({ credentialsCopied: false, credentialsError: 'disk full' }))
+ .toEqual({ dshPath: '', credentialsCopied: false, credentialsError: 'disk full' })
+ expect(installResultOf(undefined)).toEqual({ dshPath: '', credentialsCopied: false })
+ })
+})
+
+describe('errorMessageOf', () => {
+ it('maps the missing-endpoint statuses to the stable transport code', () => {
+ expect(errorMessageOf(new Error('请求失败 (405)'))).toBe('SSH_API_HTTP_405')
+ expect(errorMessageOf(new Error('请求失败 (404)'))).toBe('SSH_API_HTTP_404')
+ })
+
+ it('keeps the host prose and the unknown transport failures', () => {
+ expect(errorMessageOf(new Error('请求失败 (400): refused'))).toBe('refused')
+ expect(errorMessageOf(new Error('请求失败 (500): boom'))).toBe('boom')
+ expect(errorMessageOf(new Error('请求失败 (500)'))).toBe('请求失败 (500)')
+ expect(errorMessageOf(new Error('auth failed'))).toBe('auth failed')
+ expect(errorMessageOf('thrown prose')).toBe('thrown prose')
+ })
+})
+
+describe('isTransportError', () => {
+ it('separates the transport codes from host-provided prose', () => {
+ expect(isTransportError('SSH_API_HTTP_405')).toBe(true)
+ expect(isTransportError('SSH_API_EMPTY')).toBe(true)
+ expect(isTransportError('auth failed')).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/apis/parsers.ts b/packages/dsh-tauri-ssh/src/client/apis/parsers.ts
new file mode 100644
index 00000000..f5787718
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/apis/parsers.ts
@@ -0,0 +1,288 @@
+import type {
+ InstallResult,
+ MachineListSnapshot,
+ MachineRow,
+ MachineStatus,
+ ProgressPhase,
+ SecretValues,
+ SshMachineEvent,
+ SyncApplyResult,
+ SyncItemResult,
+ SyncPluginItem,
+ SyncPreview,
+ SyncSkillItem,
+} from '../types/index'
+import type { SshMachineSaveBody } from './index.type'
+import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
+import { messageOf } from '../../shared/error'
+import { isLifecycleState } from '../types/index'
+
+export const SSH_API_EMPTY = 'SSH_API_EMPTY'
+
+const MISSING_API_STATUSES: readonly number[] = [404, 405]
+const HTTP_FAILURE = /^请求失败 \((\d{3})\)(?:: )?/
+const PROFILE_NAME = /^[\w-]+$/
+const PROGRESS_PHASES: readonly ProgressPhase[] = ['handshake', 'installing', 'starting', 'probing', 'syncing']
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null
+}
+
+function textOf(value: unknown): string | undefined {
+ return typeof value === 'string' && value !== '' ? value : undefined
+}
+
+function numberOf(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
+}
+
+function entriesOf(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : []
+}
+
+export function isTransportError(message: string): boolean {
+ return message.startsWith('SSH_API_')
+}
+
+export function errorMessageOf(error: unknown): string {
+ const message = messageOf(error)
+ const match = HTTP_FAILURE.exec(message)
+ if (match === null)
+ return message
+ const status = Number(match[1])
+ if (MISSING_API_STATUSES.includes(status))
+ return `SSH_API_HTTP_${status}`
+ return message.slice(match[0].length) || message
+}
+
+export function enabledOf(value: unknown): boolean | undefined {
+ if (!isRecord(value))
+ return undefined
+ return typeof value.enabled === 'boolean' ? value.enabled : undefined
+}
+
+export function sessionRoleOf(value: unknown): { remote: boolean, origin?: string } {
+ const source = isRecord(value) ? value : {}
+ const origin = textOf(source.origin)
+ return {
+ remote: source.remote === true,
+ ...origin === undefined ? {} : { origin },
+ }
+}
+
+export function testResultOf(value: unknown): { ok: boolean, banner?: string, message?: string } {
+ const source = isRecord(value) ? value : {}
+ const banner = textOf(source.banner)
+ const message = textOf(source.message)
+ return {
+ ok: source.ok === true,
+ ...banner === undefined ? {} : { banner },
+ ...message === undefined ? {} : { message },
+ }
+}
+
+export function tunnelUrlOf(value: unknown): string {
+ const source = isRecord(value) ? value : {}
+ return textOf(source.tunnelBaseUrl) ?? ''
+}
+
+export function installResultOf(value: unknown): InstallResult {
+ const source = isRecord(value) ? value : {}
+ const credentialsError = textOf(source.credentialsError)
+ return {
+ dshPath: textOf(source.dshPath) ?? '',
+ credentialsCopied: source.credentialsCopied === true,
+ ...credentialsError === undefined ? {} : { credentialsError },
+ }
+}
+
+function lifecycleStateOf(value: unknown): MachineStatus['state'] {
+ return isLifecycleState(value) ? value : 'disconnected'
+}
+
+function machineRowOf(value: unknown): MachineRow | undefined {
+ if (!isRecord(value))
+ return undefined
+ const id = textOf(value.id)
+ const host = textOf(value.host)
+ if (id === undefined || typeof value.name !== 'string' || host === undefined || typeof value.user !== 'string')
+ return undefined
+ const profileName = typeof value.profileName === 'string' ? value.profileName.trim() : ''
+ const startCommand = textOf(value.startCommand)
+ const color = textOf(value.color)
+ return {
+ id,
+ name: value.name,
+ host,
+ port: numberOf(value.port) ?? DEFAULT_SSH_PORT,
+ user: value.user,
+ hasPassword: value.hasPassword === true,
+ hasPassphrase: value.hasPassphrase === true,
+ remotePort: numberOf(value.remotePort) ?? DEFAULT_REMOTE_PORT,
+ ...PROFILE_NAME.test(profileName) ? { profileName } : {},
+ ...startCommand === undefined ? {} : { startCommand },
+ ...color === undefined ? {} : { color },
+ ...value.tintBorder === true ? { tintBorder: true } : {},
+ }
+}
+
+function progressOf(value: unknown): MachineStatus['progress'] {
+ if (!isRecord(value))
+ return undefined
+ const phase = PROGRESS_PHASES.find(candidate => candidate === value.phase)
+ if (phase === undefined)
+ return undefined
+ const attempt = numberOf(value.attempt)
+ const total = numberOf(value.total)
+ const item = textOf(value.item)
+ const log = textOf(value.log)
+ return {
+ phase,
+ ...attempt === undefined ? {} : { attempt },
+ ...total === undefined ? {} : { total },
+ ...item === undefined ? {} : { item },
+ ...log === undefined ? {} : { log },
+ }
+}
+
+function statusOf(value: unknown): { id: string, status: MachineStatus } | undefined {
+ if (!isRecord(value))
+ return undefined
+ const id = textOf(value.id)
+ if (id === undefined)
+ return undefined
+ const status: MachineStatus = { state: lifecycleStateOf(value.state) }
+ const nextRetryAt = numberOf(value.nextRetryAt)
+ if (nextRetryAt !== undefined)
+ status.nextRetryAt = nextRetryAt
+ if (value.authMethod === 'agent' || value.authMethod === 'key' || value.authMethod === 'password')
+ status.authMethod = value.authMethod
+ const tunnelBaseUrl = textOf(value.tunnelBaseUrl)
+ if (tunnelBaseUrl !== undefined)
+ status.tunnelBaseUrl = tunnelBaseUrl
+ const lastError = textOf(value.lastError)
+ if (lastError !== undefined)
+ status.lastError = lastError
+ if (value.dshMissing === true)
+ status.dshMissing = true
+ const progress = progressOf(value.progress)
+ if (progress !== undefined)
+ status.progress = progress
+ return { id, status }
+}
+
+function rowsOf(value: unknown): MachineRow[] {
+ return entriesOf(value).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)
+}
+
+export function machineListOf(value: unknown): MachineListSnapshot {
+ const source = isRecord(value) ? value : {}
+ const statuses: Record<string, MachineStatus> = {}
+ for (const entry of [...entriesOf(source.items), ...entriesOf(source.discovered)]) {
+ const parsed = statusOf(entry)
+ if (parsed !== undefined)
+ statuses[parsed.id] = parsed.status
+ }
+ return {
+ machines: rowsOf(source.items),
+ discovered: rowsOf(source.discovered),
+ statuses,
+ }
+}
+
+export function savePayloadOf(machine: MachineRow, secrets: SecretValues): SshMachineSaveBody {
+ const profileName = textOf(machine.profileName)?.trim() ?? ''
+ const startCommand = textOf(machine.startCommand)
+ const color = textOf(machine.color)
+ const typed: SecretValues = {}
+ const password = textOf(secrets.password)
+ if (password !== undefined)
+ typed.password = password
+ const passphrase = textOf(secrets.passphrase)
+ if (passphrase !== undefined)
+ typed.passphrase = passphrase
+ return {
+ machineId: machine.id,
+ row: {
+ name: machine.name,
+ host: machine.host,
+ port: machine.port,
+ user: machine.user,
+ remotePort: machine.remotePort,
+ ...PROFILE_NAME.test(profileName) ? { profileName } : {},
+ ...startCommand === undefined ? {} : { startCommand },
+ ...color === undefined ? {} : { color },
+ ...machine.tintBorder === true ? { tintBorder: true } : {},
+ },
+ ...Object.keys(typed).length === 0 ? {} : { secrets: typed },
+ }
+}
+
+export function machineEventsOf(value: unknown): SshMachineEvent[] {
+ const source = isRecord(value) ? value : {}
+ const events: SshMachineEvent[] = []
+ for (const entry of entriesOf(source.items)) {
+ if (!isRecord(entry))
+ continue
+ if (typeof entry.seq !== 'number' || typeof entry.machineId !== 'string' || typeof entry.line !== 'string')
+ continue
+ if (entry.ts !== undefined && typeof entry.ts !== 'string')
+ continue
+ if (entry.stage !== undefined && typeof entry.stage !== 'string')
+ continue
+ events.push({
+ seq: entry.seq,
+ ts: typeof entry.ts === 'string' ? entry.ts : '',
+ machineId: entry.machineId,
+ stage: typeof entry.stage === 'string' ? entry.stage : '',
+ line: entry.line,
+ ...entry.terminal === 'success' || entry.terminal === 'failed' ? { terminal: entry.terminal } : {},
+ ...typeof entry.reason === 'string' ? { reason: entry.reason } : {},
+ })
+ }
+ return events
+}
+
+export function syncPreviewOf(value: unknown): SyncPreview | null {
+ if (!isRecord(value) || !Array.isArray(value.plugins) || !Array.isArray(value.skills))
+ return null
+ const plugins: SyncPluginItem[] = []
+ for (const entry of value.plugins) {
+ if (!isRecord(entry) || typeof entry.name !== 'string' || typeof entry.spec !== 'string')
+ continue
+ plugins.push({
+ name: entry.name,
+ spec: entry.spec,
+ syncable: entry.syncable === true,
+ ...typeof entry.reason === 'string' ? { reason: entry.reason } : {},
+ })
+ }
+ const skills: SyncSkillItem[] = []
+ for (const entry of value.skills) {
+ if (!isRecord(entry) || typeof entry.name !== 'string' || typeof entry.root !== 'string')
+ continue
+ skills.push({ name: entry.name, root: entry.root })
+ }
+ return { plugins, skills }
+}
+
+export function syncApplyResultOf(value: unknown): SyncApplyResult | null {
+ if (!isRecord(value) || !Array.isArray(value.items))
+ return null
+ const items: SyncItemResult[] = []
+ for (const entry of value.items) {
+ if (!isRecord(entry) || typeof entry.name !== 'string' || typeof entry.ok !== 'boolean')
+ continue
+ if (entry.kind !== 'plugin' && entry.kind !== 'skill')
+ continue
+ items.push({
+ kind: entry.kind,
+ name: entry.name,
+ ...typeof entry.root === 'string' ? { root: entry.root } : {},
+ ok: entry.ok,
+ ...typeof entry.error === 'string' ? { error: entry.error } : {},
+ ...typeof entry.log === 'string' ? { log: entry.log } : {},
+ })
+ }
+ return { items }
+}
diff --git a/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx b/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx
index c4c28403..add6f8ec 100644
--- a/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx
@@ -1,43 +1,34 @@
+// @vitest-environment jsdom
import type { SshKey } from '../locales/index'
-import type { FetchFn, MachineRow, SshApiResponse } from '../store/index'
-import type { RemoteBridge } from '../types/index'
+import type { WireCall, WireReply } from '../test-utils/client-mock'
+import type { MachineRow, RemoteBridge } from '../types/index'
import { fireEvent, screen, waitFor, within } from '@testing-library/dom'
import { act, cleanup, render } from '@testing-library/react'
-// @vitest-environment jsdom
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { baseURL } from '../apis/index'
import { en } from '../locales/index'
-import { MachinesStore } from '../store/index'
+import * as service from '../service/machines'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { MachinesSection } from './machines-section'
-// dsh-tauri-ui/client 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器
-// 无法在 node 求值;mock 到同一 cssr 实例的源文件(与 dsh-tauri-panel 同款做法),
-// 组件渲染只消费 cls 字符串,不需要真实样式;通用控件转发官方 primitives 真实实现。
-vi.mock('dsh-tauri-ui/client', async () => {
- const mod = await import('../../../../dsh-tauri-ui/src/client/utils/cssr.ts')
- const primitives = await import('@deepseek-ai/dsh-client-ui-primitives')
- return { cssr: mod.cssr, ...primitives }
-})
+vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
-afterEach(() => {
- cleanup()
- vi.restoreAllMocks()
-})
+interface SavePayload {
+ machineId: string
+ row: Record<string, unknown>
+ secrets?: Record<string, unknown>
+}
const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string
-type FetchMock = ReturnType<typeof vi.fn<FetchFn>>
-
-function fakeFetch(envelope: SshApiResponse): FetchMock {
- return vi.fn<FetchFn>(async () => ({ json: async () => envelope }) as unknown as Response)
-}
-
-/** A bridge whose ping never answers (the pure-web environment). */
const unreachableBridge: RemoteBridge = {
probe: () => Promise.reject(new Error('NODE_NOT_ANSWERED: invoke remote_bridge_ping timed out')),
openWindow: () => Promise.reject(new Error('no bridge')),
}
-/** A bridge whose ping answers; `openWindow` is a spy. */
function desktopBridge(openWindow: RemoteBridge['openWindow'] = vi.fn(async () => undefined)): RemoteBridge {
return { probe: async () => true, openWindow }
}
@@ -53,30 +44,47 @@ const machineA: MachineRow = {
remotePort: 3080,
}
-function mount(overrides: { envelope?: SshApiResponse, bridge?: RemoteBridge } = {}) {
- const fetchFn = fakeFetch(overrides.envelope ?? { ok: true, value: { items: [] } })
- const store = new MachinesStore(fetchFn)
- const view = render(
- <MachinesSection store={store} t={t} {...overrides.bridge === undefined ? {} : { bridge: overrides.bridge }} />,
+let queued: WireReply[] = []
+let route: (call: WireCall) => WireReply = () => replies.ok({ items: [] })
+
+function once(...next: WireReply[]): void {
+ queued.push(...next)
+}
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ queued = []
+ route = () => replies.ok({ items: [] })
+ answer(call => queued.shift() ?? route(call))
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+function mount(overrides: { value?: unknown, bridge?: RemoteBridge, route?: (call: WireCall) => WireReply } = {}) {
+ if (overrides.route !== undefined)
+ route = overrides.route
+ else if (overrides.value !== undefined)
+ route = () => replies.ok(overrides.value)
+ return render(
+ <MachinesSection t={t} {...overrides.bridge === undefined ? {} : { bridge: overrides.bridge }} />,
)
- return { view, store, fetchFn }
}
describe('machinesSection', () => {
it('renders the read-only SSH-in-progress banner on a remote target and hides management', async () => {
- const fetchFn = vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string }
- if (body.method === 'session.role')
- return { json: async () => ({ ok: true, value: { remote: true, origin: 'ops' } }) } as unknown as Response
- return { json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } }) } as unknown as Response
+ mount({
+ route: call => call.url === `${baseURL}/session/role`
+ ? replies.ok({ remote: true, origin: 'ops' })
+ : replies.ok({ items: [{ ...machineA, state: 'disconnected' }] }),
})
- render(<MachinesSection store={new MachinesStore(fetchFn)} t={t} />)
await waitFor(() => expect(screen.getByTestId('remote-session-banner')).toBeTruthy())
expect(screen.getByText('Currently in an SSH session')).toBeTruthy()
expect(screen.getByText(/over SSH from ops/)).toBeTruthy()
- // 告示卡点明回发起端用「同步到远端…」搬插件与 Skill
expect(screen.getByTestId('remote-session-sync-hint').textContent).toContain('Sync to remote')
- // 其余内容整块让位:添加/刷新/说明/机器列表都不渲染
expect(screen.queryByText('Add machine')).toBeNull()
expect(screen.queryByText('Refresh')).toBeNull()
expect(screen.queryByText(/Connect straight through your local/)).toBeNull()
@@ -84,58 +92,52 @@ describe('machinesSection', () => {
})
it('renders the loaded machine cards with statuses', async () => {
- const { fetchFn } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },
+ mount({
+ value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] },
})
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
const card = screen.getByTestId('machine-a')
expect(within(card).getByText('alpha')).toBeTruthy()
expect(screen.getByTestId('status-a').textContent).toContain('Connected')
expect(screen.getByText('http://127.0.0.1:49152')).toBeTruthy()
- // 机密字段在编辑器内(行已显示优先)
fireEvent.click(withinButton(card, 'Edit'))
- const passwordInput = screen.getByPlaceholderText('set')
- expect(passwordInput).toBeTruthy()
- expect(fetchFn).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))
+ expect(screen.getByPlaceholderText('set')).toBeTruthy()
+ expect(sent.some(call => call.url === `${baseURL}/machines` && call.http === 'GET')).toBe(true)
})
it('opens the add dialog and saves the new machine immediately', async () => {
- const { fetchFn } = mount()
+ mount()
await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())
fireEvent.click(screen.getByText('Add machine'))
- // 表单在弹窗里:ID 由主机自动派生,提交即落盘(不需要再点 Save)
await waitFor(() => expect(screen.getByRole('dialog', { name: 'Add machine' })).toBeTruthy())
const dialog = within(screen.getByRole('dialog', { name: 'Add machine' }))
fireEvent.change(dialog.getByLabelText('Host or config alias'), { target: { value: '[email protected]' } })
fireEvent.change(dialog.getByLabelText('Name'), { target: { value: 'newton' } })
fireEvent.change(dialog.getByLabelText('User (optional)'), { target: { value: 'ops' } })
expect(dialog.getByLabelText('ID')).toHaveProperty('value', '10-1-1-1')
- // save 落盘后 store 重新拉列表:依序 mock save 应答与新列表
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
- fetchFn.mockResolvedValueOnce({
- json: async () => ({
- ok: true,
- value: { items: [{ id: '10-1-1-1', name: 'newton', host: '[email protected]', port: 22, user: 'ops', hasPassword: false, hasPassphrase: false, remotePort: 3080, state: 'disconnected' }] },
- }),
- } as unknown as Response)
+ once(replies.ok({}))
+ once(replies.ok({
+ items: [{ id: '10-1-1-1', name: 'newton', host: '[email protected]', port: 22, user: 'ops', hasPassword: false, hasPassphrase: false, remotePort: 3080, state: 'disconnected' }],
+ }))
fireEvent.click(dialog.getByText('Add & save'))
- await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))
- const payload = saveCalls(fetchFn)[0] as { machineId: string, row: Record<string, unknown> }
- expect(payload.machineId).toBe('10-1-1-1')
- expect(payload.row).toMatchObject({ name: 'newton', host: '[email protected]', user: 'ops' })
- await waitFor(() => expect(screen.getByTestId('machine-10-1-1-1')).toBeTruthy())
+ await waitFor(() => expect(savePayloads()).toHaveLength(1))
+ const payload = savePayloads()[0]
+ expect(payload?.machineId).toBe('10-1-1-1')
+ expect(payload?.row).toMatchObject({ name: 'newton', host: '[email protected]', user: 'ops' })
+ const card = await screen.findByTestId('machine-10-1-1-1')
+ expect(screen.queryByRole('dialog', { name: 'Add machine' })).toBeNull()
+ fireEvent.click(withinButton(card, 'Edit'))
+ expect(within(screen.getByTestId('editor-10-1-1-1')).getByLabelText('Name')).toHaveProperty('value', 'newton')
})
it('derives a unique auto id and validates taken ids inline', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
fireEvent.click(screen.getByText('Add machine'))
await waitFor(() => expect(screen.getByRole('dialog', { name: 'Add machine' })).toBeTruthy())
const dialog = within(screen.getByRole('dialog', { name: 'Add machine' }))
- // 自动 ID 从主机派生
fireEvent.change(dialog.getByLabelText('Host or config alias'), { target: { value: 'alpha.internal' } })
expect(dialog.getByLabelText('ID')).toHaveProperty('value', 'alpha-internal')
- // 手改 ID 撞已有:内联报错且提交禁用
fireEvent.change(dialog.getByLabelText('ID'), { target: { value: 'a' } })
await waitFor(() => expect(dialog.getByText('ID already in use')).toBeTruthy())
expect(dialog.getByText('Add & save').closest('button')?.hasAttribute('disabled')).toBe(true)
@@ -152,70 +154,86 @@ describe('machinesSection', () => {
})
it('persists edits through the store', async () => {
- const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
- // 行内编辑:Edit 展开,改动后按行保存(无全局 Save)
const card = screen.getByTestId('machine-a')
fireEvent.click(withinButton(card, 'Edit'))
const editor = screen.getByTestId('editor-a')
fireEvent.change(within(editor).getByLabelText('Name'), { target: { value: 'alpha-2' } })
fireEvent.change(within(editor).getByLabelText('Password (optional)'), { target: { value: 'sekrit' } })
fireEvent.click(within(editor).getByText('Save'))
- await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))
- const payload = saveCalls(fetchFn)[0] as { row: Record<string, unknown>, secrets?: Record<string, unknown> }
- expect(payload.row).toMatchObject({ name: 'alpha-2' })
- expect(payload.secrets).toMatchObject({ password: 'sekrit' })
- // 保存即收起编辑器
+ await waitFor(() => expect(savePayloads()).toHaveLength(1))
+ const payload = savePayloads()[0]
+ expect(payload?.row).toMatchObject({ name: 'alpha-2' })
+ expect(payload?.secrets).toMatchObject({ password: 'sekrit' })
await waitFor(() => expect(screen.queryByTestId('editor-a')).toBeNull())
})
+ it('keeps the open draft across refresh and discards it on cancel before reopening the latest saved row', async () => {
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
+ const card = await screen.findByTestId('machine-a')
+ fireEvent.click(withinButton(card, 'Edit'))
+ const editor = within(screen.getByTestId('editor-a'))
+ fireEvent.change(editor.getByLabelText('Name'), { target: { value: 'unsaved' } })
+ fireEvent.change(editor.getByLabelText('Password (optional)'), { target: { value: 'unsaved-secret' } })
+ fireEvent.change(editor.getByLabelText('Key passphrase (optional)'), { target: { value: 'unsaved-phrase' } })
+
+ route = () => replies.ok({ items: [{ ...machineA, name: 'refreshed', hasPassword: false, hasPassphrase: true, state: 'disconnected' }] })
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh' }))
+ await waitFor(() => expect(within(card).getByText('refreshed')).toBeTruthy())
+ expect(editor.getByLabelText('Name')).toHaveProperty('value', 'unsaved')
+ expect(editor.getByLabelText('Password (optional)')).toHaveProperty('value', 'unsaved-secret')
+ expect(editor.getByLabelText('Password (optional)').getAttribute('placeholder')).toBe('not set')
+ expect(editor.getByLabelText('Key passphrase (optional)')).toHaveProperty('value', 'unsaved-phrase')
+ expect(editor.getByLabelText('Key passphrase (optional)').getAttribute('placeholder')).toBe('set')
+
+ fireEvent.click(editor.getByRole('button', { name: 'Cancel' }))
+ expect(screen.queryByTestId('editor-a')).toBeNull()
+ fireEvent.click(withinButton(card, 'Edit'))
+ const reopened = within(screen.getByTestId('editor-a'))
+ expect(reopened.getByLabelText('Name')).toHaveProperty('value', 'refreshed')
+ expect(reopened.getByLabelText('Password (optional)')).toHaveProperty('value', '')
+ expect(reopened.getByLabelText('Key passphrase (optional)')).toHaveProperty('value', '')
+ expect(savePayloads()).toHaveLength(0)
+ })
+
it('removes a machine immediately through the confirmation modal', async () => {
- const { fetchFn } = mount({
- envelope: {
- ok: true,
- value: { items: [{ ...machineA, state: 'disconnected' }, { ...machineA, id: 'b', name: 'beta', state: 'disconnected' }] },
- },
+ mount({
+ value: { items: [{ ...machineA, state: 'disconnected' }, { ...machineA, id: 'b', name: 'beta', state: 'disconnected' }] },
})
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
const betaCard = screen.getByTestId('machine-b')
fireEvent.click(withinButton(betaCard, 'Remove'))
- // The modal states what is about to be removed; cancel first keeps the row.
await waitFor(() => expect(screen.getByText(/This removes the "beta" machine profile/)).toBeTruthy())
fireEvent.click(screen.getByText('Cancel'))
expect(screen.getByTestId('machine-b')).toBeTruthy()
fireEvent.click(withinButton(betaCard, 'Remove'))
await waitFor(() => expect(screen.getByText('Remove it')).toBeTruthy())
- // remove 落盘后 reload 列表:依序 mock remove 应答与不含 b 的新列表
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } }),
- } as unknown as Response)
+ once(replies.ok({}))
+ once(replies.ok({ items: [{ ...machineA, state: 'disconnected' }] }))
fireEvent.click(screen.getByText('Remove it'))
- // 确认即删除:无需再点保存
- await waitFor(() => expect(removeCalls(fetchFn)).toHaveLength(1))
- expect(removeCalls(fetchFn)[0]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })
+ await waitFor(() => expect(removePayloads()).toHaveLength(1))
+ expect(sent).toContainEqual({ url: `${baseURL}/machines`, http: 'DELETE', body: { machineId: 'b' }, params: {} })
await waitFor(() => expect(screen.queryByTestId('machine-b')).toBeNull())
})
it('tests, connects, opens through the desktop bridge, and disconnects a machine', async () => {
const openWindow = vi.fn(async () => undefined)
- const fetchFn = fakeFetch({ ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } })
- const store = new MachinesStore(fetchFn)
- render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] }, bridge: desktopBridge(openWindow) })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)
+ once(replies.ok({ ok: true, banner: 'Linux alpha' }))
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Test'))
await waitFor(() => expect(screen.getByTestId('notice').textContent).toContain('Linux alpha'))
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)
+ once(replies.ok({ tunnelBaseUrl: 'http://127.0.0.1:49152' }))
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Connect'))
await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Open'))
await waitFor(() => expect(openWindow).toHaveBeenCalledWith('a', 'http://127.0.0.1:49152'))
expect(screen.queryByTestId('bridge-error-a')).toBeNull()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
+ once(replies.ok({}))
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Disconnect'))
await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Connect')).toBeTruthy())
})
@@ -224,9 +242,8 @@ describe('machinesSection', () => {
const openWindow = vi.fn(async () => undefined)
mount({
bridge: unreachableBridge,
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },
+ value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] },
})
- // The rejected probe settles: pure web never shows the popup affordance.
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Connected'))
await waitFor(() => expect(screen.queryByText('Open')).toBeNull())
expect(openWindow).not.toHaveBeenCalled()
@@ -236,7 +253,7 @@ describe('machinesSection', () => {
const openWindow = vi.fn(() => Promise.reject(new Error('window refused')))
mount({
bridge: desktopBridge(openWindow),
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },
+ value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] },
})
fireEvent.click(await screen.findByText('Open'))
await waitFor(() => expect(screen.getByTestId('bridge-error-a').textContent).toContain('window refused'))
@@ -249,48 +266,47 @@ describe('machinesSection', () => {
}))
mount({
bridge: desktopBridge(openWindow),
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] } },
+ value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }] },
})
fireEvent.click(await screen.findByText('Open'))
- // 在飞:按钮换「Opening…」并禁用,杜绝连点
await waitFor(() => expect(screen.getByText('Opening…').closest('button')?.hasAttribute('disabled')).toBe(true))
act(() => release())
await waitFor(() => expect(withinButton(screen.getByTestId('machine-a'), 'Open')).toBeTruthy())
})
it('renders the connecting state with the connect action disabled', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'connecting' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
expect(screen.getByTestId('status-a').textContent).toContain('Connecting')
expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(true)
})
it('renders the testing and reconnecting states with the retry hint', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'testing' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'testing' }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Testing'))
cleanup()
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() + 8_000 }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() + 8_000 }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Reconnecting'))
expect(screen.getByTestId('status-a').textContent).toContain('next retry: in 8s')
expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(true)
})
it('renders a due retry as now instead of a negative countdown', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() - 2_000 }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: Date.now() - 2_000 }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Reconnecting'))
expect(screen.getByTestId('status-a').textContent).toContain('next retry: now')
})
it('renders the given-up state and lets the operator retry the connect', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'given-up', lastError: 'auth failed after 10 tries' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'given-up', lastError: 'auth failed after 10 tries' }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Given up'))
expect(screen.getByText('auth failed after 10 tries')).toBeTruthy()
expect(withinButton(screen.getByTestId('machine-a'), 'Connect').hasAttribute('disabled')).toBe(false)
})
it('edits every config field and falls back on malformed numbers', async () => {
- const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Edit'))
const editor = screen.getByTestId('editor-a')
@@ -299,18 +315,18 @@ describe('machinesSection', () => {
fireEvent.change(within(editor).getByLabelText('Start command (optional)'), { target: { value: 'dsh web --port 3000' } })
fireEvent.change(within(editor).getByLabelText('Key passphrase (optional)'), { target: { value: 'phrase' } })
fireEvent.click(within(editor).getByText('Save'))
- await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))
- const payload = saveCalls(fetchFn)[0] as { row: Record<string, unknown>, secrets?: Record<string, unknown> }
- expect(payload.row).toMatchObject({
+ await waitFor(() => expect(savePayloads()).toHaveLength(1))
+ const payload = savePayloads()[0]
+ expect(payload?.row).toMatchObject({
port: 2222,
remotePort: 3080,
startCommand: 'dsh web --port 3000',
})
- expect(payload.secrets).toMatchObject({ passphrase: 'phrase' })
+ expect(payload?.secrets).toMatchObject({ passphrase: 'phrase' })
})
it('masks the secret inputs and keeps the write-only direction', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
fireEvent.click(withinButton(screen.getByTestId('machine-a'), 'Edit'))
const editor = screen.getByTestId('editor-a')
@@ -318,7 +334,6 @@ describe('machinesSection', () => {
const passphrase = within(editor).getByLabelText('Key passphrase (optional)')
expect(password.getAttribute('type')).toBe('password')
expect(passphrase.getAttribute('type')).toBe('password')
- // Presence flags only: the placeholders report set/unset, never values.
expect(password.getAttribute('placeholder')).toBe('set')
expect(passphrase.getAttribute('placeholder')).toBe('not set')
})
@@ -327,35 +342,37 @@ describe('machinesSection', () => {
const openWindow = vi.fn(async () => undefined)
mount({
bridge: desktopBridge(openWindow),
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected' }] } },
+ value: { items: [{ ...machineA, state: 'connected' }] },
})
fireEvent.click(await screen.findByText('Open'))
expect(openWindow).not.toHaveBeenCalled()
})
it('persists the identity color and the border tint switch', async () => {
- const { fetchFn } = mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
const card = screen.getByTestId('machine-a')
fireEvent.click(withinButton(card, 'Edit'))
const editor = screen.getByTestId('editor-a')
+ const tintSwitch = within(editor).getByRole('switch', { name: 'Also tint the border', checked: false })
+ expect(tintSwitch.hasAttribute('disabled')).toBe(true)
+ fireEvent.click(tintSwitch)
+ expect(tintSwitch.getAttribute('aria-checked')).toBe('false')
fireEvent.click(within(editor).getByLabelText('Color: #4176E6'))
- fireEvent.click(within(editor).getByRole('switch'))
- // 保存后列表回报新外观:tint 色条随已存数据上色
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'disconnected', color: '#4176E6', tintBorder: true }] } }),
- } as unknown as Response)
+ expect(tintSwitch.hasAttribute('disabled')).toBe(false)
+ fireEvent.click(tintSwitch)
+ expect(tintSwitch.getAttribute('aria-checked')).toBe('true')
+ once(replies.ok({}))
+ once(replies.ok({ items: [{ ...machineA, state: 'disconnected', color: '#4176E6', tintBorder: true }] }))
fireEvent.click(within(editor).getByText('Save'))
- await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))
- expect((saveCalls(fetchFn)[0] as { row: Record<string, unknown> }).row)
- .toMatchObject({ color: '#4176E6', tintBorder: true })
+ await waitFor(() => expect(savePayloads()).toHaveLength(1))
+ expect(savePayloads()[0]?.row).toMatchObject({ color: '#4176E6', tintBorder: true })
await waitFor(() => expect(card.style.borderLeftColor).toBe('rgb(65, 118, 230)'))
})
it('resets color and border tint through the default swatch', async () => {
- const { fetchFn } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected', color: '#4176E6', tintBorder: true }] } },
+ mount({
+ value: { items: [{ ...machineA, state: 'disconnected', color: '#4176E6', tintBorder: true }] },
})
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
expect(screen.getByTestId('machine-a').style.borderLeftColor).toBe('rgb(65, 118, 230)')
@@ -363,335 +380,260 @@ describe('machinesSection', () => {
const editor = screen.getByTestId('editor-a')
fireEvent.click(within(editor).getByLabelText('Default'))
fireEvent.click(within(editor).getByText('Save'))
- await waitFor(() => expect(saveCalls(fetchFn)).toHaveLength(1))
- const row = (saveCalls(fetchFn)[0] as { row: Record<string, unknown> }).row
+ await waitFor(() => expect(savePayloads()).toHaveLength(1))
+ const row = savePayloads()[0]?.row ?? {}
expect(row.color).toBeUndefined()
expect(row.tintBorder).toBeUndefined()
})
it('shows the live progress text of an in-flight operation', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Health check 2/30'))
})
it('shows the handshake progress phase', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Connecting over SSH'))
})
it('renders the step rail with the observed phases, latest highlighted', async () => {
- const { store, fetchFn } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] } })
await waitFor(() => expect(screen.getByTestId('step-rail').textContent).toBe('Handshake'))
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 1, total: 3 } }] } }),
- } as unknown as Response)
+ once(replies.ok({ items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 1, total: 3 } }] }))
+ once(replies.ok({ items: [] }))
await act(async () => {
- await store.poll()
+ await service.poll()
})
- // install 未出现就不在轨上;最新阶段收尾
await waitFor(() => expect(screen.getByTestId('step-rail').textContent).toBe('HandshakeProbe'))
- // 操作落定(progress 消失)步骤条收起
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } }),
- } as unknown as Response)
+ once(replies.ok({ items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] }))
+ once(replies.ok({ items: [] }))
await act(async () => {
- await store.poll()
+ await service.poll()
})
await waitFor(() => expect(screen.queryByTestId('step-rail')).toBeNull())
})
- it('falls back to question marks when probing progress has no numbers', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing' } }] } } })
- await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Health check ?/?'))
+ it.each([
+ { phase: 'probing', text: 'Health check ?/?…' },
+ { phase: 'syncing', text: 'Syncing item ?/?…' },
+ ])('falls back to question marks when $phase progress has no numbers', async ({ phase, text }) => {
+ mount({ value: { items: [{ ...machineA, state: 'connecting', progress: { phase } }] } })
+ await waitFor(() => expect(screen.getByTestId('status-a').textContent).toBe(text))
})
it('shows the starting progress phase', async () => {
- mount({ envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } } })
+ mount({ value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } })
await waitFor(() => expect(screen.getByTestId('status-a').textContent).toContain('Starting the remote instance'))
})
it('streams the install log through the unified log surface', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
act(() => {
- store.store.update((state) => {
- state.busy.a = 'install'
- state.statuses.a = {
- state: 'disconnected',
- dshMissing: true,
- progress: { phase: 'installing', log: '==> Checking dependencies\ngit ... ok' },
- }
- })
+ store.machines.busy.a = 'install'
+ store.machines.statuses.a = {
+ state: 'disconnected',
+ dshMissing: true,
+ progress: { phase: 'installing', log: '==> Checking dependencies\ngit ... ok' },
+ }
})
- expect(screen.getAllByText(/Installing dsh/).length).toBeGreaterThan(0)
+ await waitFor(() => expect(screen.getAllByText(/Installing dsh/).length).toBeGreaterThan(0))
const log = screen.getByTestId('machine-log-a')
expect(log.textContent).toContain('==> Checking dependencies')
expect(log.textContent).toContain('git ... ok')
})
it('prefers the machine.events lines over the progress log', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'connecting' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
act(() => {
- store.store.update((state) => {
- state.logs.a = ['[bootstrap] cloning dsh source', '[bootstrap] pnpm install']
- state.statuses.a = { state: 'connecting', progress: { phase: 'starting', log: 'old progress text' } }
- })
+ store.machines.logs.a = ['[bootstrap] cloning dsh source', '[bootstrap] pnpm install']
+ store.machines.statuses.a = { state: 'connecting', progress: { phase: 'starting', log: 'old progress text' } }
})
+ await waitFor(() => expect(screen.getByTestId('machine-log-a').textContent).toContain('[bootstrap] cloning dsh source'))
const log = screen.getByTestId('machine-log-a')
- expect(log.textContent).toContain('[bootstrap] cloning dsh source')
expect(log.textContent).toContain('[bootstrap] pnpm install')
expect(log.textContent).not.toContain('old progress text')
})
- it('polls the host while an operation is in flight and stops when idle', async () => {
- vi.useFakeTimers()
- try {
- const fetchFn = fakeFetch({ ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } })
- const store = new MachinesStore(fetchFn)
- store.store.update((state) => {
- state.status = 'ready'
- state.machines = [machineA]
- state.statuses = { a: { state: 'connecting', progress: { phase: 'handshake' } } }
- })
- render(<MachinesSection store={store} t={t} />)
- const before = fetchFn.mock.calls.length
- await act(async () => vi.advanceTimersByTime(1600))
- // One poll = machine.list + machine.events for the one known machine.
- expect(fetchFn.mock.calls.length).toBe(before + 2)
- // Idle machines stop the polling loop. The flip runs inside act so the
- // interval effect cleans up before the clock advances again; every
- // further call would prove the loop leaked.
- act(() => {
- store.store.update((state) => {
- state.statuses = { a: { state: 'disconnected' } }
- state.busy = {}
- })
- })
- const idle = fetchFn.mock.calls.length
- await act(async () => vi.advanceTimersByTime(3200))
- expect(fetchFn.mock.calls.length).toBe(idle)
- }
- finally {
- vi.useRealTimers()
- }
- })
-
it('shows per-machine failures and the page error banner', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected', lastError: 'auth failed' }] } },
+ mount({
+ value: { items: [{ ...machineA, state: 'disconnected', lastError: 'auth failed' }] },
})
await waitFor(() => expect(screen.getByText('auth failed')).toBeTruthy())
- store.store.update((state) => {
- state.error = 'boom'
+ act(() => {
+ store.machines.error = 'boom'
})
await waitFor(() => expect(screen.getByText(/Error: boom/)).toBeTruthy())
})
it('renders the load-failure state with a retry affordance instead of a blank page', async () => {
- const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'internal', message: 'route down' } }) }) as unknown as Response)
- const store = new MachinesStore(fetchFn)
- render(<MachinesSection store={store} t={t} />)
+ mount({ route: () => replies.fail('route down') })
await waitFor(() => expect(screen.getByText('The panel failed to load.')).toBeTruthy())
expect(screen.getAllByText('Refresh').length).toBeGreaterThan(0)
})
it('renders discovered config aliases as read-only cards with working actions', async () => {
- const fetchFn = fakeFetch({
- ok: true,
+ mount({
value: {
items: [],
discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root', hasPassword: false, state: 'disconnected' }],
},
})
- const store = new MachinesStore(fetchFn)
- render(<MachinesSection store={store} t={t} />)
await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())
expect(screen.getByText('Hosts from ~/.ssh/config')).toBeTruthy()
const card = screen.getByTestId('machine-dev')
- // Read-only: no editable fields, no Remove button, no secrets.
expect(within(card).queryByLabelText('ID')).toBeNull()
expect(within(card).queryByText('Remove')).toBeNull()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux dev' } }) } as unknown as Response)
+ once(replies.ok({ ok: true, banner: 'Linux dev' }))
fireEvent.click(withinButton(card, 'Test'))
await waitFor(() => expect(screen.getByTestId('notice').textContent).toContain('Linux dev'))
})
it('connects and opens a discovered config alias through the bridge', async () => {
const openWindow = vi.fn(async () => undefined)
- const fetchFn = fakeFetch({
- ok: true,
+ mount({
+ bridge: desktopBridge(openWindow),
value: {
items: [],
discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected' }],
},
})
- const store = new MachinesStore(fetchFn)
- render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)
await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)
+ once(replies.ok({ tunnelBaseUrl: 'http://127.0.0.1:49152' }))
fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Connect'))
await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Open')).toBeTruthy())
fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Open'))
await waitFor(() => expect(openWindow).toHaveBeenCalledWith('dev', 'http://127.0.0.1:49152'))
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
+ once(replies.ok({}))
fireEvent.click(withinButton(screen.getByTestId('machine-dev'), 'Disconnect'))
await waitFor(() => expect(withinButton(screen.getByTestId('machine-dev'), 'Connect')).toBeTruthy())
})
it('opens nothing for a discovered card without a tunnel url', async () => {
const openWindow = vi.fn(async () => undefined)
- const fetchFn = fakeFetch({
- ok: true,
+ mount({
+ bridge: desktopBridge(openWindow),
value: { items: [], discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connected' }] },
})
- const store = new MachinesStore(fetchFn)
- render(<MachinesSection store={store} t={t} bridge={desktopBridge(openWindow)} />)
fireEvent.click(await screen.findByText('Open'))
expect(openWindow).not.toHaveBeenCalled()
})
it('disables connect while a discovered alias is connecting', async () => {
- mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connecting' }] } } })
+ mount({ value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'connecting' }] } })
await waitFor(() => expect(screen.getByTestId('status-dev').textContent).toContain('Connecting'))
expect(withinButton(screen.getByTestId('machine-dev'), 'Connect').hasAttribute('disabled')).toBe(true)
})
it('shows a discovered alias failure inline', async () => {
- mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected', lastError: 'auth failed' }] } } })
+ mount({ value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected', lastError: 'auth failed' }] } })
await waitFor(() => expect(screen.getByText('auth failed')).toBeTruthy())
})
it('shows the empty state only when no manual or discovered machines exist', async () => {
- mount({ envelope: { ok: true, value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', state: 'disconnected' }] } } })
+ mount({ value: { discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())
expect(screen.queryByText(/No SSH machines yet/)).toBeNull()
})
it('refreshes on demand', async () => {
- const { store } = mount()
+ mount()
await waitFor(() => expect(screen.getByText(/No SSH machines yet/)).toBeTruthy())
- const load = vi.spyOn(store, 'load').mockResolvedValue(undefined)
+ const before = listCalls()
fireEvent.click(screen.getByText('Refresh'))
- expect(load).toHaveBeenCalled()
+ await waitFor(() => expect(listCalls()).toBe(before + 1))
})
it('shows the one-click install surface when dsh is missing and installs on click', async () => {
- const { fetchFn } = mount({
- envelope: {
- ok: true,
- value: { items: [{ ...machineA, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true }] },
- },
+ mount({
+ value: { items: [{ ...machineA, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true }] },
})
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
expect(screen.getByText(/No dsh found on the remote/)).toBeTruthy()
expect(screen.getByText('Install dsh')).toBeTruthy()
+ once(replies.ok({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }))
+ once(replies.ok({ items: [{ ...machineA, state: 'disconnected', dshMissing: false }] }))
fireEvent.click(screen.getByText('Install dsh'))
- await waitFor(() => {
- expect(fetchFn.mock.calls.some(([_url, init]) =>
- String(init.body).includes('machine.install'))).toBe(true)
- })
+ await waitFor(() => expect(installPayloads()).toHaveLength(1))
+ expect(installPayloads()[0]).toEqual({ machineId: 'a' })
})
it('shows the install outcome note under the card', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } })
await waitFor(() => expect(screen.getByTestId('machine-a')).toBeTruthy())
act(() => {
- store.store.update((state) => {
- state.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }
- })
+ store.machines.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }
})
- expect(screen.getByTestId('install-note-a').textContent).toContain('API key was copied')
+ await waitFor(() => expect(screen.getByTestId('install-note-a').textContent).toContain('API key was copied'))
})
it('shows the install note when no local key exists', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
act(() => {
- store.store.update((state) => {
- state.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: false }
- })
+ store.machines.installResults.a = { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: false }
})
- expect(screen.getByTestId('install-note-a').textContent).toContain('No DEEPSEEK_API_KEY found locally')
+ await waitFor(() => expect(screen.getByTestId('install-note-a').textContent).toContain('No DEEPSEEK_API_KEY found locally'))
})
it('shows the install note with a credentials copy failure', async () => {
- const { store } = mount({
- envelope: { ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } },
- })
+ mount({ value: { items: [{ ...machineA, state: 'disconnected' }] } })
await waitFor(() => expect(screen.getByText('alpha')).toBeTruthy())
act(() => {
- store.store.update((state) => {
- state.installResults.a = {
- dshPath: '/home/root/.local/bin/dsh',
- credentialsCopied: false,
- credentialsError: 'disk full',
- }
- })
+ store.machines.installResults.a = {
+ dshPath: '/home/root/.local/bin/dsh',
+ credentialsCopied: false,
+ credentialsError: 'disk full',
+ }
})
- expect(screen.getByTestId('install-note-a').textContent).toContain('disk full')
+ await waitFor(() => expect(screen.getByTestId('install-note-a').textContent).toContain('disk full'))
})
it('offers the one-click install on a discovered alias too', async () => {
- const { fetchFn } = mount({
- envelope: {
- ok: true,
- value: {
- discovered: [{
- id: 'dev',
- name: 'dev',
- host: 'dev',
- port: 22,
- user: 'root',
- hasPassword: false,
- hasPassphrase: false,
- remotePort: 3080,
- state: 'disconnected',
- dshMissing: true,
- lastError: 'dsh is not installed',
- }],
- },
+ mount({
+ value: {
+ discovered: [{
+ id: 'dev',
+ name: 'dev',
+ host: 'dev',
+ port: 22,
+ user: 'root',
+ hasPassword: false,
+ hasPassphrase: false,
+ remotePort: 3080,
+ state: 'disconnected',
+ dshMissing: true,
+ lastError: 'dsh is not installed',
+ }],
},
})
await waitFor(() => expect(screen.getByText('dev')).toBeTruthy())
expect(screen.getByText(/No dsh found on the remote/)).toBeTruthy()
+ once(replies.ok({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true }))
+ once(replies.ok({ discovered: [{ id: 'dev', name: 'dev', host: 'dev', port: 22, user: 'root', hasPassword: false, hasPassphrase: false, remotePort: 3080, state: 'disconnected' }] }))
fireEvent.click(screen.getByText('Install dsh'))
- await waitFor(() => {
- expect(fetchFn.mock.calls.some(([_url, init]) =>
- String(init.body).includes('machine.install'))).toBe(true)
- })
+ await waitFor(() => expect(installPayloads()).toHaveLength(1))
+ expect(installPayloads()[0]).toEqual({ machineId: 'dev' })
})
})
-/** The machine.save request bodies the fake fetch received. */
-function saveCalls(fetchFn: ReturnType<typeof vi.fn>): unknown[] {
- return fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: unknown })
- .filter(call => call.method === 'machine.save')
- .map(call => call.payload)
+function listCalls(): number {
+ return sent.filter(call => call.url === `${baseURL}/machines` && call.http === 'GET').length
+}
+
+function savePayloads(): SavePayload[] {
+ return sent.filter(call => call.url === `${baseURL}/machines` && call.http === 'POST').map(call => call.body as unknown as SavePayload)
+}
+
+function removePayloads(): Array<{ machineId: string }> {
+ return sent.filter(call => call.url === `${baseURL}/machines` && call.http === 'DELETE').map(call => call.body as unknown as { machineId: string })
}
-/** The machine.remove request bodies the fake fetch received. */
-function removeCalls(fetchFn: ReturnType<typeof vi.fn>): Array<{ method: string, payload: Record<string, unknown> }> {
- return fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })
- .filter(call => call.method === 'machine.remove')
+function installPayloads(): Array<{ machineId: string }> {
+ return sent.filter(call => call.url === `${baseURL}/machines/install`).map(call => call.body as unknown as { machineId: string })
}
-/** Find one button by its accessible text inside a container. */
function withinButton(container: HTMLElement, text: string): HTMLButtonElement {
- const button = [...container.querySelectorAll('button')].find(candidate => candidate.textContent === text)
- if (button === undefined)
- throw new Error(`no button "${text}"`)
- return button as HTMLButtonElement
+ return within(container).getByRole('button', { name: text }) as HTMLButtonElement
}
diff --git a/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx b/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx
index ea6241e5..83dac152 100644
--- a/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/machines-section.tsx
@@ -1,19 +1,20 @@
import type { CSSProperties, ReactNode } from 'react'
import type { SshKey } from '../locales/index'
-import type { InstallResult, MachineRow, MachinesNotice, MachinesStore, MachineStatus, ProgressPhase, SecretValues } from '../store/index'
-import type { MachineLifecycleState, RemoteBridge } from '../types/index'
-import { Button, Input, Modal, StateDot } from 'dsh-tauri-ui/client'
-import { useEffect, useState, useSyncExternalStore } from 'react'
+import type { MachinesNotice } from '../store/modules/machines.types'
+import type { InstallResult, MachineLifecycleState, MachineRow, MachineStatus, ProgressPhase, RemoteBridge, SecretValues } from '../types/index'
+import { Button, Input, Modal, StateDot, Switch } from 'dsh-tauri-ui/client'
+import { cn, useStore } from 'dsh-tauri/client'
+import { useEffect, useState } from 'react'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
import { messageOf } from '../../shared/error'
-import { cls } from '../styles/index'
+import { desktopBridge } from '../service/bridge'
+import * as service from '../service/machines'
+import { store } from '../store/index'
import { errorTextOf } from '../utils/error'
import { retrySecondsOf } from '../utils/retry'
-/** The StateDot vocabulary the connection states map onto ('idle' is hollow). */
type DotState = 'done' | 'ongoing' | 'error' | 'idle'
-/** The identity-color palette (fits the DSH status hue family). */
const COLOR_CHOICES = [
'#4176E6',
'#0EA5E9',
@@ -25,44 +26,28 @@ const COLOR_CHOICES = [
'#A855F7',
]
-/** One in-edit draft of a manual machine row (keyed by row id). */
interface Draft {
key: string
row: MachineRow
}
-/** Per-row typed secrets the editor holds (write-only; keyed by row id). */
type DirtySecrets = Record<string, SecretValues>
-/** Which secret fields exist (the write-only sidecar keys). */
-export type SecretFieldName = 'password' | 'passphrase'
+type SecretFieldName = 'password' | 'passphrase'
-/** Injected dependencies (the app binds the real store/bridge; tests pass fakes). */
-export interface MachinesSectionInjected {
- store: MachinesStore
- /** Desktop bridge; absent (or unanswered probe) means pure web. */
- bridge?: RemoteBridge | undefined
-}
-
-export interface MachinesSectionProps extends MachinesSectionInjected {
+interface MachinesSectionProps {
t: (key: SshKey) => string
+ bridge?: RemoteBridge | undefined
}
-/** The remove-confirm target: which row is about to be deleted. */
interface RemoveTarget {
key: string
id: string
name: string
}
-/** The id charset mirrors the host-side MachineId guard. */
const ID_PATTERN = /^[a-z0-9][a-z0-9-]*$/u
-/**
- * Derive the machine id from a host: lowercase alnum-dash slug of the part
- * after the last `@` (so `[email protected]` → `10.1.1.1` → `10-1-1-1`); empty
- * when the host has no usable characters.
- */
function slugOf(host: string): string {
return host
.trim()
@@ -72,7 +57,6 @@ function slugOf(host: string): string {
.replace(/^-+|-+$/gu, '')
}
-/** Pick the first free id: the slug itself, else slug-2, slug-3, … */
function freeIdOf(base: string, taken: ReadonlySet<string>): string {
if (!taken.has(base))
return base
@@ -83,16 +67,9 @@ function freeIdOf(base: string, taken: ReadonlySet<string>): string {
}
}
-/**
- * The shared machine row shell: identity (state dot + optional color pip +
- * name + host tag), live status text with the step rail, and the trailing
- * action cluster. Manual and discovered rows differ only in their action
- * set and whether an editor can expand below.
- */
function RowShell({ id, name, tag, tintColor, tintBorder, status, trail, actions, t, children }: {
id: string
name: string
- /** The muted identity suffix (host for manual rows, the config tag for discovered). */
tag: string
tintColor: string | undefined
tintBorder: boolean
@@ -104,37 +81,33 @@ function RowShell({ id, name, tag, tintColor, tintBorder, status, trail, actions
}): ReactNode {
return (
<li
- className={cls.rowCard}
+ className="flex flex-col gap-[8px] border-l-2 border-l-transparent px-[14px] py-[10px] [&+&]:border-t [&+&]:border-t-border-l2"
data-testid={`machine-${id}`}
style={tintBorder && tintColor !== undefined ? { borderLeftColor: tintColor } : undefined}
>
- <div className={cls.rowHead}>
- <span className={cls.rowIdentity}>
+ <div className="flex items-center gap-[10px]">
+ <span className="inline-flex min-w-0 items-center gap-[6px]">
<StateDotOf status={status} />
{tintColor !== undefined
- ? <span className={cls.colorPip} style={{ background: tintColor }} aria-hidden="true" />
+ ? <span className="inline-block h-[10px] w-[10px] shrink-0 rounded-full shadow-[inset_0_0_0_1px_rgba(0,0,0,0.12)]" style={{ background: tintColor }} aria-hidden="true" />
: null}
- <span className={cls.rowName}>{name}</span>
- <span className={cls.rowTag}>{tag}</span>
- <span className={cls.status} data-testid={`status-${id}`}>{statusTextOf(status, t)}</span>
+ <span className="text-[14px] leading-[22px] font-medium text-primary">{name}</span>
+ <span className="shrink-0 rounded-full border-0 bg-module-platform px-[8px] py-[2px] text-[11px] leading-[16px] text-secondary">{tag}</span>
+ <span className="text-[12px] leading-[18px] text-tertiary" data-testid={`status-${id}`}>{statusTextOf(status, t)}</span>
<StepRail trail={trail} t={t} />
</span>
- <span className={cls.rowActions}>{actions}</span>
+ <span className="ml-auto inline-flex items-center gap-[4px]">{actions}</span>
</div>
{children}
</li>
)
}
-/**
- * The inline editor of one manual machine: connection fields, write-only
- * secrets and the appearance row. Saving applies immediately for this row
- * alone (other rows are untouched); cancel discards the buffer.
- */
-function EditPanel({ draft, t, secretSet, dirty, saving, onChange, onSecret, onSave, onCancel }: {
+function EditPanel({ draft, t, hasPassword, hasPassphrase, dirty, saving, onChange, onSecret, onSave, onCancel }: {
draft: Draft
t: (key: SshKey) => string
- secretSet: Record<string, boolean>
+ hasPassword: boolean
+ hasPassphrase: boolean
dirty: SecretValues
saving: boolean
onChange: (key: string, patch: Partial<MachineRow>) => void
@@ -145,42 +118,40 @@ function EditPanel({ draft, t, secretSet, dirty, saving, onChange, onSecret, onS
const { row } = draft
const invalid = row.id === '' || row.name === '' || row.host === ''
return (
- <div className={cls.editor} data-testid={`editor-${row.id}`}>
- {/* 12 栅格显式分组:第 1 行 = ID / 名称 / 主机(3+4+5),
- 第 2 行 = 端口 / 用户 / 远端端口 / 远端档案(3×4),启动命令独占整行 */}
- <div className={cls.grid}>
+ <div className="mx-0 mb-[4px] mt-[2px] flex flex-col gap-[12px] border-t border-t-border-l2 pt-[12px]" data-testid={`editor-${row.id}`}>
+ <div className="grid grid-cols-[repeat(12,minmax(0,1fr))] gap-[10px_12px] max-[760px]:grid-cols-[repeat(6,minmax(0,1fr))]">
<Field label={t('field.id')} span={3}>
- <Input className={cls.fieldInput} value={row.id} disabled />
+ <Input className="box-border w-full" value={row.id} disabled />
</Field>
<Field label={t('field.name')} span={4}>
- <Input className={cls.fieldInput} value={row.name} disabled={saving} onChange={event => onChange(draft.key, { name: event.target.value })} />
+ <Input className="box-border w-full" value={row.name} disabled={saving} onChange={event => onChange(draft.key, { name: event.target.value })} />
</Field>
<Field label={t('field.host')} span={5}>
- <Input className={cls.fieldInput} value={row.host} disabled={saving} onChange={event => onChange(draft.key, { host: event.target.value })} />
+ <Input className="box-border w-full" value={row.host} disabled={saving} onChange={event => onChange(draft.key, { host: event.target.value })} />
</Field>
<Field label={t('field.port')} span={3}>
- <Input className={cls.fieldInput} type="number" value={row.port} disabled={saving} onChange={event => onChange(draft.key, { port: numberOf(event.target.value, DEFAULT_SSH_PORT) })} />
+ <Input className="box-border w-full" type="number" value={row.port} disabled={saving} onChange={event => onChange(draft.key, { port: numberOf(event.target.value, DEFAULT_SSH_PORT) })} />
</Field>
<Field label={t('field.user')} span={3}>
- <Input className={cls.fieldInput} value={row.user} disabled={saving} onChange={event => onChange(draft.key, { user: event.target.value })} />
+ <Input className="box-border w-full" value={row.user} disabled={saving} onChange={event => onChange(draft.key, { user: event.target.value })} />
</Field>
<Field label={t('field.remotePort')} span={3}>
- <Input className={cls.fieldInput} type="number" value={row.remotePort} disabled={saving} onChange={event => onChange(draft.key, { remotePort: numberOf(event.target.value, DEFAULT_REMOTE_PORT) })} />
+ <Input className="box-border w-full" type="number" value={row.remotePort} disabled={saving} onChange={event => onChange(draft.key, { remotePort: numberOf(event.target.value, DEFAULT_REMOTE_PORT) })} />
</Field>
<Field label={t('field.profileName')} span={3}>
- <Input className={cls.fieldInput} value={row.profileName ?? ''} placeholder="remote" disabled={saving || (row.startCommand ?? '') !== ''} onChange={event => onChange(draft.key, { profileName: event.target.value })} />
+ <Input className="box-border w-full" value={row.profileName ?? ''} placeholder="remote" disabled={saving || (row.startCommand ?? '') !== ''} onChange={event => onChange(draft.key, { profileName: event.target.value })} />
</Field>
<Field label={t('field.startCommand')} span={12}>
- <Input className={cls.fieldInput} value={row.startCommand ?? ''} disabled={saving} onChange={event => onChange(draft.key, { startCommand: event.target.value })} />
+ <Input className="box-border w-full" value={row.startCommand ?? ''} disabled={saving} onChange={event => onChange(draft.key, { startCommand: event.target.value })} />
</Field>
</div>
- <div className={cls.grid}>
- <SecretField field="password" span={6} label={t('field.password')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.password ?? ''} onValue={onSecret} />
- <SecretField field="passphrase" span={6} label={t('field.passphrase')} keyName={draft.key} secretSet={secretSet} t={t} value={dirty.passphrase ?? ''} onValue={onSecret} />
+ <div className="grid grid-cols-[repeat(12,minmax(0,1fr))] gap-[10px_12px] max-[760px]:grid-cols-[repeat(6,minmax(0,1fr))]">
+ <SecretField field="password" label={t('field.password')} keyName={draft.key} hasSecret={hasPassword} t={t} value={dirty.password ?? ''} onValue={onSecret} />
+ <SecretField field="passphrase" label={t('field.passphrase')} keyName={draft.key} hasSecret={hasPassphrase} t={t} value={dirty.passphrase ?? ''} onValue={onSecret} />
</div>
<AppearanceEditor row={row} t={t} onChange={onChange} draftKey={draft.key} />
- <div className={cls.editorActions}>
- {invalid ? <p className={cls.hint}>{t('saveHint')}</p> : null}
+ <div className="flex items-center justify-end gap-[8px]">
+ {invalid ? <p className={cn('m-0 text-[12px] leading-[18px] text-tertiary', 'mr-auto')}>{t('saveHint')}</p> : null}
<Button variant="ghost" size="sm" disabled={saving} onClick={() => onCancel(draft.key)}>
{t('add.cancel')}
</Button>
@@ -192,7 +163,6 @@ function EditPanel({ draft, t, secretSet, dirty, saving, onChange, onSecret, onS
)
}
-/** The shared trailing action cluster of one row (test/connect/open/disconnect + row-specific extras). */
function RowActions({ id, t, status, busy, bridgeOpen, bridgePending, opening, onTest, onConnect, onDisconnect, onOpen, extras }: {
id: string
t: (key: SshKey) => string
@@ -245,7 +215,6 @@ function RowActions({ id, t, status, busy, bridgeOpen, bridgePending, opening, o
)
}
-/** The detail block under a row: install surface, errors, tunnel link, live log. */
function RowDetails({ id, status, busy, logLines, bridgeError, installResult, t, onInstall }: {
id: string
status: MachineStatus | undefined
@@ -261,33 +230,31 @@ function RowDetails({ id, status, busy, logLines, bridgeError, installResult, t,
{status?.dshMissing === true
? <InstallPanel status={status} busy={busy} t={t} onInstall={() => onInstall(id)} />
: null}
- {status?.lastError !== undefined ? <p className={cls.statusError} role="alert">{status.lastError}</p> : null}
+ {status?.lastError !== undefined ? <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">{status.lastError}</p> : null}
{bridgeError !== undefined
? (
- <p className={cls.statusError} role="alert" data-testid={`bridge-error-${id}`}>
+ <p className="m-0 text-[12px] leading-[18px] text-error" role="alert" data-testid={`bridge-error-${id}`}>
{t('bridge.error')}
{bridgeError}
</p>
)
: null}
- {status?.tunnelBaseUrl !== undefined ? <p className={cls.link}>{status.tunnelBaseUrl}</p> : null}
+ {status?.tunnelBaseUrl !== undefined ? <p className="m-0 font-mono text-[12px] leading-[18px] text-tertiary [overflow-wrap:anywhere]">{status.tunnelBaseUrl}</p> : null}
<LogStream id={id} lines={logLines} fallback={status?.progress?.log} />
{installResult !== undefined
- ? <p className={cls.installNote} data-testid={`install-note-${id}`}>{installNoteOf(installResult, t)}</p>
+ ? <p className="m-0 text-[12px] leading-[18px] text-secondary" data-testid={`install-note-${id}`}>{installNoteOf(installResult, t)}</p>
: null}
</>
)
}
-/** The state dot: a primitive StateDot for live states, hollow CSS for idle. */
function StateDotOf({ status }: { status: MachineStatus | undefined }): ReactNode {
const state = dotStateOf(status)
if (state === 'idle')
- return <span className={cls.stateDot} data-state="idle" aria-hidden="true" />
+ return <span className="relative inline-block h-[8px] w-[8px] shrink-0 rounded-full bg-current text-[var(--dsw-alias-label-caption)] after:absolute after:inset-[25%] after:rounded-full after:bg-current after:content-['']" data-state="idle" aria-hidden="true" />
return <StateDot state={state} size={8} />
}
-/** The streaming log: the S2 event lines when present, else the progress log. */
function LogStream({ id, lines, fallback }: { id: string, lines: readonly string[], fallback: string | undefined }): ReactNode {
const output = lines.length > 0
? lines.join('\n')
@@ -295,13 +262,12 @@ function LogStream({ id, lines, fallback }: { id: string, lines: readonly string
if (output === '')
return null
return (
- <pre className={cls.logStream} data-testid={`machine-log-${id}`}>
+ <pre className="m-0 max-h-[160px] overflow-auto font-mono text-[11px] leading-[16px] whitespace-pre-wrap text-tertiary [overflow-wrap:anywhere]" data-testid={`machine-log-${id}`}>
{output}
</pre>
)
}
-/** The dsh-missing install surface: a one-click install (the log lives in the card stream). */
function InstallPanel({ status, busy, t, onInstall }: {
status: MachineStatus
busy: 'test' | 'connect' | 'disconnect' | 'install' | undefined
@@ -311,14 +277,14 @@ function InstallPanel({ status, busy, t, onInstall }: {
const installing = busy === 'install' || status.progress?.phase === 'installing'
if (installing) {
return (
- <div className={cls.installBox}>
- <p className={cls.installHint}>{t('progress.installing')}</p>
+ <div className="flex flex-col gap-[8px] rounded-[8px] border border-border-l2 bg-[var(--dsw-alias-surface-tinted)] px-[12px] py-[10px]">
+ <p className="m-0 text-[12px] leading-[18px] text-secondary">{t('progress.installing')}</p>
</div>
)
}
return (
- <div className={cls.installBox}>
- <p className={cls.installHint}>{t('install.hint')}</p>
+ <div className="flex flex-col gap-[8px] rounded-[8px] border border-border-l2 bg-[var(--dsw-alias-surface-tinted)] px-[12px] py-[10px]">
+ <p className="m-0 text-[12px] leading-[18px] text-secondary">{t('install.hint')}</p>
<Button variant="primary" size="sm" disabled={busy !== undefined} onClick={onInstall}>
{t('install.action')}
</Button>
@@ -326,7 +292,6 @@ function InstallPanel({ status, busy, t, onInstall }: {
)
}
-/** One operator-facing line for a finished install. */
function installNoteOf(result: InstallResult, t: (key: SshKey) => string): string {
if (result.credentialsError !== undefined) {
return t('install.done.error') + result.credentialsError
@@ -334,35 +299,26 @@ function installNoteOf(result: InstallResult, t: (key: SshKey) => string): strin
return result.credentialsCopied ? t('install.done.copied') : t('install.done.nokey')
}
-/** The grid spans the editor layout uses (12-column track). */
-export type FieldSpan = 3 | 4 | 5 | 6 | 8 | 12
-
-/** Span class per grid width (the 12-column editor track). */
-const SPAN_CLASS: Record<FieldSpan, string> = {
- 3: cls.span3,
- 4: cls.span4,
- 5: cls.span5,
- 6: cls.span6,
- 8: cls.span8,
- 12: cls.span12,
-}
+type FieldSpan = 3 | 4 | 5 | 6 | 8 | 12
-/** One labeled field row. */
function Field({ label, span = 6, children }: { label: string, span?: FieldSpan, children: ReactNode }): ReactNode {
return (
- <label className={`${cls.field} ${SPAN_CLASS[span]}`}>
- <span className={cls.fieldLabel}>{label}</span>
+ <label
+ className={cn('flex min-w-0 flex-col gap-[6px] max-[520px]:col-span-6!', {
+ 3: 'col-span-3',
+ 4: 'col-span-4 max-[760px]:col-span-3',
+ 5: 'col-span-5 max-[760px]:col-span-3',
+ 6: 'col-span-6 max-[760px]:col-span-3',
+ 8: 'col-span-8 max-[760px]:col-span-6',
+ 12: 'col-span-12 max-[760px]:col-span-6',
+ }[span])}
+ >
+ <span className="text-[12px] leading-[18px] font-medium text-secondary">{label}</span>
{children}
</label>
)
}
-/**
- * The appearance row of one machine editor: an identity-color swatch set
- * (plus a "default" reset) and the tint-the-border switch, which is only
- * meaningful while a color is chosen. Clearing writes the empty-string
- * (off) form — the save path drops it.
- */
function AppearanceEditor({ row, t, onChange, draftKey }: {
row: MachineRow
t: (key: SshKey) => string
@@ -371,14 +327,14 @@ function AppearanceEditor({ row, t, onChange, draftKey }: {
}): ReactNode {
const color = colorOf(row)
return (
- <div className={cls.appearance}>
- <span className={cls.fieldLabel}>{t('field.color')}</span>
- <div className={cls.swatches}>
+ <div className="flex flex-wrap items-center gap-[10px]">
+ <span className="text-[12px] leading-[18px] font-medium text-secondary">{t('field.color')}</span>
+ <div className="inline-flex flex-wrap items-center gap-[6px]">
{COLOR_CHOICES.map(choice => (
<button
key={choice}
type="button"
- className={cls.swatch}
+ className={cn('box-border h-[20px] w-[20px] cursor-pointer rounded-full border border-border-l2 bg-[color:var(--swatch-color)] p-0 hover:border-border-l4', color === choice && 'outline-2 outline-brand outline-offset-2')}
data-selected={color === choice}
style={{ '--swatch-color': choice } as CSSProperties}
aria-label={`${t('field.color')}: ${choice}`}
@@ -388,69 +344,53 @@ function AppearanceEditor({ row, t, onChange, draftKey }: {
))}
<button
type="button"
- className={`${cls.swatch} ${cls.swatchNone}`}
+ className={cn('box-border h-[20px] w-[20px] cursor-pointer rounded-full border border-border-l2 bg-[color:var(--swatch-color)] p-0 hover:border-border-l4', 'bg-[image:linear-gradient(to_top_right,transparent_calc(50%_-_1px),var(--dsw-alias-label-tertiary),transparent_calc(50%_+_1px))]', color === undefined && 'outline-2 outline-brand outline-offset-2')}
data-selected={color === undefined}
aria-label={t('color.none')}
aria-pressed={color === undefined}
title={t('color.none')}
onClick={() => onChange(draftKey, { color: '', tintBorder: false })}
/>
- <span className={cls.switchRow}>
- <button
- type="button"
- role="switch"
- aria-checked={row.tintBorder === true}
- className={cls.switch}
+ <span className="ml-[4px] inline-flex items-center gap-[8px]">
+ <Switch
+ checked={row.tintBorder === true}
disabled={color === undefined}
- onClick={() => onChange(draftKey, { tintBorder: row.tintBorder !== true })}
+ label={t('field.tintBorder')}
+ onChange={tintBorder => onChange(draftKey, { tintBorder })}
/>
- <span className={cls.fieldLabel}>{t('field.tintBorder')}</span>
+ <span className="text-[12px] leading-[18px] font-medium text-secondary">{t('field.tintBorder')}</span>
</span>
</div>
</div>
)
}
-/** One write-only secret input; the placeholder reports whether a value is stored. */
-export function SecretField({ field, label, keyName, secretSet, t, value, onValue, span = 6 }: {
+function SecretField({ field, label, keyName, hasSecret, t, value, onValue }: {
field: SecretFieldName
label: string
keyName: string
- secretSet: Record<string, boolean>
+ hasSecret: boolean
t: (key: SshKey) => string
value: string
onValue: (key: string, field: SecretFieldName, value: string) => void
- span?: FieldSpan
}): ReactNode {
- const placeholder = secretSet[`${keyName}.${field}`] ? t('secret.set') : t('secret.unset')
return (
- <label className={`${cls.field} ${SPAN_CLASS[span]}`}>
- <span className={cls.fieldLabel}>{label}</span>
+ <Field label={label}>
<Input
- className={cls.fieldInput}
+ className="box-border w-full"
type="password"
value={value}
- placeholder={placeholder}
+ placeholder={hasSecret ? t('secret.set') : t('secret.unset')}
onChange={event => onValue(keyName, field, event.target.value)}
/>
- </label>
+ </Field>
)
}
-/** The write-only secret presence flags of one draft row, keyed like the stored sidecar. */
-function secretFlagsOf(row: MachineRow): Record<string, boolean> {
- return {
- [`${row.id}.password`]: row.hasPassword,
- [`${row.id}.passphrase`]: row.hasPassphrase,
- }
-}
-
-/** The row's effective identity color ('' and undefined both mean none). */
function colorOf(row: MachineRow): string | undefined {
return row.color === undefined || row.color === '' ? undefined : row.color
}
-/** Short step labels of each pipeline phase (the long progress.* text stays in the status line). */
const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {
handshake: 'step.handshake',
installing: 'step.installing',
@@ -459,17 +399,16 @@ const STEP_KEY_OF: Record<ProgressPhase, SshKey> = {
syncing: 'step.syncing',
}
-/** The step rail: the phases one operation actually walked, latest current. */
function StepRail({ trail, t }: { trail: readonly ProgressPhase[], t: (key: SshKey) => string }): ReactNode {
if (trail.length === 0)
return null
const current = trail[trail.length - 1]
return (
- <ol className={cls.stepRail} data-testid="step-rail">
+ <ol className="m-0 ml-[8px] inline-flex list-none gap-[4px] p-0 align-middle" data-testid="step-rail">
{trail.map(phase => (
<li
key={phase}
- className={phase === current ? cls.stepCurrent : cls.stepDone}
+ className={phase === current ? 'rounded-full border border-current px-[6px] text-[11px] leading-[16px] text-[var(--dsw-alias-state-warning-primary,#d48806)]' : 'rounded-full border border-[color:var(--dsw-alias-line-secondary,currentColor)] px-[6px] text-[11px] leading-[16px] text-tertiary'}
>
{t(STEP_KEY_OF[phase])}
</li>
@@ -478,7 +417,6 @@ function StepRail({ trail, t }: { trail: readonly ProgressPhase[], t: (key: SshK
)
}
-/** The connection-state dot vocabulary (StateDot states; idle renders hollow). */
function dotStateOf(status: MachineStatus | undefined): DotState {
if (status?.state === 'connected')
return 'done'
@@ -489,7 +427,6 @@ function dotStateOf(status: MachineStatus | undefined): DotState {
return 'idle'
}
-/** The status-label key of each lifecycle state (the hyphenated state maps to camelCase keys). */
const STATUS_KEY_OF: Record<MachineLifecycleState, SshKey> = {
'disconnected': 'status.disconnected',
'testing': 'status.testing',
@@ -499,22 +436,10 @@ const STATUS_KEY_OF: Record<MachineLifecycleState, SshKey> = {
'given-up': 'status.givenUp',
}
-/** The status line: live progress text while an operation is in flight, else the state label. */
function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => string): string {
const progress = status?.progress
- if (progress?.phase === 'handshake')
- return t('progress.handshake')
- if (progress?.phase === 'starting')
- return t('progress.starting')
- if (progress?.phase === 'installing')
- return t('progress.installing')
- if (progress?.phase === 'probing') {
- return t('progress.probing')
- .replace('{attempt}', String(progress.attempt ?? '?'))
- .replace('{total}', String(progress.total ?? '?'))
- }
- if (progress?.phase === 'syncing') {
- return t('progress.syncing')
+ if (progress !== undefined) {
+ return t(`progress.${progress.phase}`)
.replace('{attempt}', String(progress.attempt ?? '?'))
.replace('{total}', String(progress.total ?? '?'))
}
@@ -529,32 +454,23 @@ function statusTextOf(status: MachineStatus | undefined, t: (key: SshKey) => str
return base
}
-/** Parse a number input; non-numbers fall back to the default. */
function numberOf(raw: string, fallback: number): number {
const parsed = Number(raw)
return raw !== '' && Number.isFinite(parsed) ? parsed : fallback
}
-/** Render one notice: host words verbatim, store literals through the locale table. */
function noticeTextOf(notice: MachinesNotice, t: (key: SshKey) => string): string {
if (notice.kind === 'text')
return notice.text
let text = t(notice.key)
for (const [name, value] of Object.entries(notice.params ?? {}))
- text = text.replace(`{${name}}`, value)
+ text = text.replace(`{${name}}`, String(value))
return text
}
-/**
- * The add-machine dialog: one focused form, saved immediately on submit
- * (the parent appends the row to the store). The id auto-derives from the
- * host until the operator touches the field. Remount per open (the parent
- * keys it by the open flag) so every open starts from a clean form.
- */
function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
t: (key: SshKey) => string
saving: boolean
- /** Ids the new machine must not collide with. */
takenIds: ReadonlySet<string>
onSubmit: (row: MachineRow) => void
onClose: () => void
@@ -609,12 +525,10 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
</>
)}
>
- {/* 新增表单同样按 12 栅格成组:主机 + 端口一行(8+4),
- 名称 / ID / 用户一行(4×3),远端端口 + 远端档案一行(6+6) */}
- <div className={cls.grid}>
+ <div className="grid grid-cols-[repeat(12,minmax(0,1fr))] gap-[10px_12px] max-[760px]:grid-cols-[repeat(6,minmax(0,1fr))]">
<Field label={t('field.host')} span={8}>
<Input
- className={cls.fieldInput}
+ className="box-border w-full"
value={host}
autoFocus
disabled={saving}
@@ -622,14 +536,14 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
/>
</Field>
<Field label={t('field.port')} span={4}>
- <Input className={cls.fieldInput} value={port} disabled={saving} onChange={event => setPort(event.target.value)} />
+ <Input className="box-border w-full" value={port} disabled={saving} onChange={event => setPort(event.target.value)} />
</Field>
<Field label={t('field.name')} span={4}>
- <Input className={cls.fieldInput} value={name} disabled={saving} onChange={event => setName(event.target.value)} />
+ <Input className="box-border w-full" value={name} disabled={saving} onChange={event => setName(event.target.value)} />
</Field>
<Field label={t('field.id')} span={4}>
<Input
- className={cls.fieldInput}
+ className="box-border w-full"
value={idTouched ? id : effectiveId}
placeholder={t('add.id_auto')}
disabled={saving}
@@ -640,53 +554,39 @@ function AddMachineDialog({ t, saving, takenIds, onSubmit, onClose }: {
/>
</Field>
<Field label={t('field.user')} span={4}>
- <Input className={cls.fieldInput} value={user} disabled={saving} onChange={event => setUser(event.target.value)} />
+ <Input className="box-border w-full" value={user} disabled={saving} onChange={event => setUser(event.target.value)} />
</Field>
<Field label={t('field.remotePort')} span={6}>
- <Input className={cls.fieldInput} value={remotePort} disabled={saving} onChange={event => setRemotePort(event.target.value)} />
+ <Input className="box-border w-full" value={remotePort} disabled={saving} onChange={event => setRemotePort(event.target.value)} />
</Field>
<Field label={t('field.profileName')} span={6}>
- <Input className={cls.fieldInput} value={profileName} placeholder="remote" disabled={saving} onChange={event => setProfileName(event.target.value)} />
+ <Input className="box-border w-full" value={profileName} placeholder="remote" disabled={saving} onChange={event => setProfileName(event.target.value)} />
</Field>
</div>
{errorKey === null
- ? <p className={cls.hint}>{t('add.id_auto')}</p>
- : <p className={cls.error} role="alert">{errorKey === null ? '' : t(errorKey)}</p>}
+ ? <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('add.id_auto')}</p>
+ : <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">{errorKey === null ? '' : t(errorKey)}</p>}
</Modal>
)
}
-/**
- * Render the SSH-machines settings page.
- *
- * Rows are display-first: identity + live status + actions. Editing a manual
- * machine expands an inline editor whose save applies to that row alone and
- * immediately (no page-level staging); add is a focused modal; remove is
- * confirmed then applied at once.
- * @returns the page element tree.
- */
-export function MachinesSection({ t, store, bridge }: MachinesSectionProps): ReactNode {
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot)
+export function MachinesSection({ t, bridge = desktopBridge }: MachinesSectionProps): ReactNode {
+ const state = useStore(store.machines)
const [drafts, setDrafts] = useState<Record<string, Draft>>({})
const [dirty, setDirty] = useState<DirtySecrets>({})
- /** The one row whose inline editor is open (null = all collapsed). */
const [editingId, setEditingId] = useState<string | null>(null)
const [savingId, setSavingId] = useState<string | null>(null)
const [addOpen, setAddOpen] = useState(false)
const [addSaving, setAddSaving] = useState(false)
- const [initialized, setInitialized] = useState(false)
const [availability, setAvailability] = useState<'desktop' | 'web' | 'unknown'>(() => bridge?.probe === undefined ? 'web' : 'unknown')
const [bridgeErrors, setBridgeErrors] = useState<Record<string, string>>({})
const [openingId, setOpeningId] = useState<string | null>(null)
const [removeTarget, setRemoveTarget] = useState<RemoveTarget | null>(null)
useEffect(() => {
- void store.load()
- }, [store])
+ void service.load()
+ }, [])
- // Probe the desktop bridge once: an answer means the popup affordance
- // exists; a timeout or rejection means pure web, where it never shows.
- // (No bridge at all settled synchronously in the initial state.)
useEffect(() => {
const probe = bridge?.probe
if (probe === undefined)
@@ -707,30 +607,6 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
}
}, [bridge])
- // While any machine has an operation in flight, poll the host every 1.5 s
- // so the live progress (handshake / starting / probing) and the event log
- // stay current.
- const anyInFlight = Object.keys(state.busy).length > 0
- || Object.values(state.statuses).some(status =>
- status.state === 'connecting' || status.state === 'reconnecting' || status.state === 'testing')
- useEffect(() => {
- if (!anyInFlight)
- return
- const timer = setInterval(() => void store.poll(), 1500)
- return () => clearInterval(timer)
- }, [anyInFlight, store])
-
- // Initialize the draft buffer once the first load lands; the buffer only
- // exists while a row editor is open (opened editors re-seed from the row).
- useEffect(() => {
- if (initialized || state.status !== 'ready')
- return
- // eslint-disable-next-line react/set-state-in-effect -- load-once hydration: the draft buffer cannot exist before the first machine.list lands
- setInitialized(true)
- // eslint-disable-next-line react/set-state-in-effect -- same hydrate-once guard as setInitialized above
- setDrafts(Object.fromEntries(state.machines.map(row => [row.id, { key: row.id, row: { ...row } }])))
- }, [initialized, state.status, state.machines])
-
const patchDraft = (key: string, patch: Partial<MachineRow>): void => {
setDrafts(previous => ({
...previous,
@@ -742,17 +618,12 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
setDirty(previous => ({ ...previous, [key]: { ...previous[key], [field]: value } }))
}
- /** Open a row's editor, re-seeding its buffer from the latest saved row. */
const openEditor = (row: MachineRow): void => {
setDrafts(previous => ({ ...previous, [row.id]: { key: row.id, row: { ...row } } }))
setEditingId(row.id)
}
- /** Discard a row's buffer and collapse its editor. */
const closeEditor = (key: string): void => {
- const saved = state.machines.find(row => row.id === key)
- if (saved !== undefined)
- setDrafts(previous => ({ ...previous, [key]: { key, row: { ...saved } } }))
setDirty((previous) => {
const next = { ...previous }
delete next[key]
@@ -761,17 +632,16 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
setEditingId(null)
}
- /** Save one row: persist the stored set with this row's buffer substituted. */
const saveRow = async (key: string): Promise<void> => {
const draft = drafts[key]
if (draft === undefined)
return
setSavingId(key)
const secrets = dirty[key] ?? {}
- const rows = store.getSnapshot().machines.map(row => row.id === draft.row.id ? draft.row : row)
- const ok = await store.persist(rows, { [key]: secrets })
+ const rows = store.machines.machines.map(row => row.id === draft.row.id ? draft.row : row)
+ const result = await service.persist({ machines: rows, secrets: { [key]: secrets } })
setSavingId(null)
- if (!ok)
+ if (!result.ok)
return
setDirty((previous) => {
const next = { ...previous }
@@ -781,16 +651,12 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
setEditingId(null)
}
- /**
- * Add = create-and-save now: persist the saved set plus the new row.
- */
const submitAdd = async (row: MachineRow): Promise<void> => {
setAddSaving(true)
- const ok = await store.persist([...store.getSnapshot().machines, row], {})
+ const result = await service.persist({ machines: [...store.machines.machines, row], secrets: {} })
setAddSaving(false)
- if (!ok)
+ if (!result.ok)
return
- setDrafts(previous => ({ ...previous, [row.id]: { key: row.id, row: { ...row } } }))
setAddOpen(false)
}
@@ -799,9 +665,8 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
return
const { key, id } = removeTarget
setRemoveTarget(null)
- // 删除立即生效:确认即调 machine.remove,成功后摘掉草稿与脏密钥
- void store.remove(id).then((ok) => {
- if (!ok)
+ void service.remove({ machineId: id }).then((result) => {
+ if (!result.ok)
return
setDrafts((previous) => {
const next = { ...previous }
@@ -818,13 +683,9 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
})
}
- /**
- * Ask the desktop shell for the remote window; failures surface per machine.
- * While the call is in flight the Open button shows an opening label.
- */
const openRemoteWindow = (id: string): void => {
const url = state.statuses[id]?.tunnelBaseUrl
- if (url === undefined || bridge === undefined || openingId !== null)
+ if (url === undefined || openingId !== null)
return
setOpeningId(id)
bridge.openWindow(id, url).then(
@@ -844,44 +705,40 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
}
const bridgeOpen = availability === 'desktop'
- // 桌面桥探测未落定前给「新窗口打开」留禁用占位:落定后桌面端原位点亮、
- // 纯 Web 端移除,避免按钮闪现造成布局跳动。
const bridgePending = availability === 'unknown'
- // 远端会话:本实例自己就是 SSH 目标,机器管理在发起端——整页只剩告示卡
- // (列表/添加/刷新全部让位),并点明回发起端用「同步到远端…」搬插件与 Skill。
if (state.role?.remote === true) {
return (
- <div className={cls.section} data-testid="remote-session">
- <h2 className={cls.title}>{t('title')}</h2>
- <div className={cls.remoteCard} data-testid="remote-session-banner">
- <span className={cls.remoteIcon} aria-hidden="true">
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="remote-session">
+ <h2 className="m-0 text-[18px] leading-[28px] font-semibold text-primary">{t('title')}</h2>
+ <div className="mt-[4px] flex flex-col items-center gap-[12px] rounded-[12px] border-[0.5px] border-border-l2 bg-layer-1 px-[24px] py-[40px] text-center" data-testid="remote-session-banner">
+ <span className="inline-flex h-[44px] w-[44px] items-center justify-center rounded-full bg-[var(--dsw-alias-surface-tinted)] text-success" aria-hidden="true">
<svg fill="none" height="22" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.6" viewBox="0 0 24 24" width="22">
<path d="M4 17l6-6-6-6" />
<path d="M12 19h8" />
</svg>
</span>
- <p className={cls.remoteTitle}>{t('session.remoteTitle')}</p>
- <p className={cls.remoteHint}>
+ <p className="m-0 text-[22px] leading-[32px] font-semibold text-primary">{t('session.remoteTitle')}</p>
+ <p className="m-0 max-w-[460px] text-[13px] leading-[21px] text-secondary">
{state.role.origin !== undefined && state.role.origin !== ''
? t('session.remoteHintNamed').replace('{name}', state.role.origin)
: t('session.remoteHint')}
</p>
- <p className={cls.remoteNote} data-testid="remote-session-sync-hint">{t('session.remoteSyncHint')}</p>
+ <p className="m-0 max-w-[460px] rounded-[8px] bg-[var(--dsw-alias-surface-tinted)] px-[12px] py-[8px] text-[12px] leading-[19px] text-tertiary" data-testid="remote-session-sync-hint">{t('session.remoteSyncHint')}</p>
</div>
</div>
)
}
return (
- <div className={cls.section}>
- <div className={cls.sectionHead}>
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary">
+ <div className="flex flex-wrap items-start justify-between gap-[12px]">
<div>
- <h2 className={cls.title}>{t('title')}</h2>
- <p className={cls.intro}>{t('intro')}</p>
+ <h2 className="m-0 text-[18px] leading-[28px] font-semibold text-primary">{t('title')}</h2>
+ <p className="m-0 text-[13px] leading-[20px] text-tertiary">{t('intro')}</p>
</div>
- <div className={cls.chrome}>
- <Button variant="outline" size="sm" disabled={state.status === 'loading'} onClick={() => void store.load()}>
+ <div className="flex shrink-0 flex-wrap items-center gap-[8px]">
+ <Button variant="outline" size="sm" disabled={state.status === 'loading'} onClick={() => void service.load()}>
{t('refresh')}
</Button>
<Button variant="primary" size="sm" disabled={state.status === 'loading'} onClick={() => setAddOpen(true)}>
@@ -889,29 +746,29 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
</Button>
</div>
</div>
- {state.notice !== null ? <p className={cls.notice} data-testid="notice">{noticeTextOf(state.notice, t)}</p> : null}
+ {state.notice !== null ? <p className="m-0 text-[12px] leading-[18px] text-secondary" data-testid="notice">{noticeTextOf(state.notice, t)}</p> : null}
{state.error !== null
? (
- <p className={cls.error} role="alert">
+ <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">
{t('error.banner')}
{errorTextOf(state.error, t)}
</p>
)
: null}
- {state.status === 'loading' ? <p className={cls.hint}>{t('loading')}</p> : null}
+ {state.status === 'loading' ? <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('loading')}</p> : null}
{state.status === 'error'
? (
- <div className={cls.emptyBlock}>
- <p className={cls.empty}>{t('loadFailed')}</p>
- <Button variant="outline" size="sm" onClick={() => void store.load()}>{t('refresh')}</Button>
+ <div className="flex flex-col items-start gap-[8px]">
+ <p className="m-0 rounded-[8px] border border-dashed border-border-l3 p-[12px] text-center text-[12px] leading-[18px] text-tertiary">{t('loadFailed')}</p>
+ <Button variant="outline" size="sm" onClick={() => void service.load()}>{t('refresh')}</Button>
</div>
)
: null}
{state.status === 'ready' && state.machines.length === 0 && state.discovered.length === 0
- ? <p className={cls.empty}>{t('empty')}</p>
+ ? <p className="m-0 rounded-[8px] border border-dashed border-border-l3 p-[12px] text-center text-[12px] leading-[18px] text-tertiary">{t('empty')}</p>
: null}
<>
- <ul className={cls.rows}>
+ <ul className="m-0 mt-[12px] flex list-none flex-col overflow-hidden rounded-[12px] border border-border-l2 bg-layer-3 p-0">
{state.machines.map((row) => {
const draft = drafts[row.id] ?? { key: row.id, row }
return (
@@ -934,16 +791,16 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
bridgeOpen={bridgeOpen}
bridgePending={bridgePending}
opening={openingId === row.id}
- onTest={id => void store.test(id)}
- onConnect={id => void store.connect(id)}
- onDisconnect={id => void store.disconnect(id)}
+ onTest={id => void service.test({ machineId: id })}
+ onConnect={id => void service.connect({ machineId: id })}
+ onDisconnect={id => void service.disconnect({ machineId: id })}
onOpen={openRemoteWindow}
extras={(
<>
<Button variant="outline" size="sm" disabled={editingId !== null && editingId !== row.id} onClick={() => editingId === row.id ? closeEditor(row.id) : openEditor(row)}>
{t('edit')}
</Button>
- <Button variant="ghost" size="sm" className={cls.dangerAction} disabled={state.busy[row.id] !== undefined} onClick={() => setRemoveTarget({ key: row.id, id: row.id, name: row.name === '' ? row.id : row.name })}>
+ <Button variant="ghost" size="sm" className="text-error" disabled={state.busy[row.id] !== undefined} onClick={() => setRemoveTarget({ key: row.id, id: row.id, name: row.name === '' ? row.id : row.name })}>
{t('remove')}
</Button>
</>
@@ -956,7 +813,8 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
<EditPanel
draft={draft}
t={t}
- secretSet={secretFlagsOf(row)}
+ hasPassword={row.hasPassword}
+ hasPassphrase={row.hasPassphrase}
dirty={dirty[row.id] ?? {}}
saving={savingId === row.id}
onChange={patchDraft}
@@ -974,7 +832,7 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
bridgeError={bridgeErrors[row.id]}
installResult={state.installResults[row.id]}
t={t}
- onInstall={id => void store.install(id)}
+ onInstall={id => void service.install({ machineId: id })}
/>
</RowShell>
)
@@ -983,11 +841,11 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
{state.discovered.length > 0
? (
<>
- <div className={cls.group}>
- <h3 className={cls.groupTitle}>{t('configHosts')}</h3>
- <p className={cls.groupHint}>{t('configHostsHint')}</p>
+ <div className="mt-[12px] flex flex-col gap-[2px]">
+ <h3 className="m-0 text-[12px] leading-[18px] font-medium text-secondary">{t('configHosts')}</h3>
+ <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('configHostsHint')}</p>
</div>
- <ul className={cls.rows}>
+ <ul className="m-0 mt-[12px] flex list-none flex-col overflow-hidden rounded-[12px] border border-border-l2 bg-layer-3 p-0">
{state.discovered.map(row => (
<RowShell
key={row.id}
@@ -1008,9 +866,9 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
bridgeOpen={bridgeOpen}
bridgePending={bridgePending}
opening={openingId === row.id}
- onTest={id => void store.test(id)}
- onConnect={id => void store.connect(id)}
- onDisconnect={id => void store.disconnect(id)}
+ onTest={id => void service.test({ machineId: id })}
+ onConnect={id => void service.connect({ machineId: id })}
+ onDisconnect={id => void service.disconnect({ machineId: id })}
onOpen={openRemoteWindow}
/>
)}
@@ -1023,7 +881,7 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
bridgeError={bridgeErrors[row.id]}
installResult={state.installResults[row.id]}
t={t}
- onInstall={id => void store.install(id)}
+ onInstall={id => void service.install({ machineId: id })}
/>
</RowShell>
))}
@@ -1055,7 +913,7 @@ export function MachinesSection({ t, store, bridge }: MachinesSectionProps): Rea
footer={(
<>
<Button variant="ghost" onClick={() => setRemoveTarget(null)}>{t('remove.confirm.cancel')}</Button>
- <Button variant="primary" className={cls.dangerAction} onClick={confirmRemove}>{t('remove.confirm.ok')}</Button>
+ <Button variant="primary" className="text-error" onClick={confirmRemove}>{t('remove.confirm.ok')}</Button>
</>
)}
/>
diff --git a/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx b/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx
index 85adae4b..1e69e806 100644
--- a/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/ssh-section.test.tsx
@@ -1,74 +1,46 @@
// @vitest-environment jsdom
-import type { FetchFn } from '../store/index'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { MachinesStore } from '../store/index'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { baseURL } from '../apis/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { SshSection } from './ssh-section'
-// dsh-tauri-ui/client 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器无法在
-// node 求值:通用控件用最小替身(本套用例只关心 Hero / Tabs 的取舍与定位),
-// listenParent 取真实源实现,好让 deep link 走一遍真实的消息过滤。
-vi.mock('dsh-tauri-ui/client', async () => {
- const mod = await import('../../../../dsh-tauri-ui/src/client/utils/cssr.ts')
- const React = await import('react')
- const h = React.createElement
- const passthrough = (props: { children?: unknown }) => h('div', null, props.children as never)
- return {
- cssr: mod.cssr,
- Button: ({ variant: _variant, size: _size, onPress, ...rest }: { variant?: unknown, size?: unknown, onPress?: () => void } & Record<string, unknown>) =>
- h('button', { type: 'button', ...rest, onClick: onPress ?? rest.onClick } as never, rest.children as never),
- Globe: () => null,
- Icon: () => null,
- Input: () => null,
- Modal: passthrough,
- Pill: passthrough,
- StateDot: () => null,
- SegmentedControl: (props: { options: Array<{ value: string, label: string }>, value: string, onChange: (next: string) => void, id?: string }) =>
- h('div', { role: 'tablist' }, props.options.map(option =>
- h('button', {
- 'key': option.value,
- 'type': 'button',
- 'role': 'tab',
- 'aria-selected': option.value === props.value,
- 'onClick': () => props.onChange(option.value),
- }, option.label))),
- }
-})
+vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
-vi.mock('dsh-tauri/client', async () => {
- const mod = await import('../../../../dsh-tauri/src/client/service/listen-parent.ts')
- return { listenParent: mod.listenParent }
-})
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
-/** A store whose /api-ssh answers the enable flow (off by default). */
-function bootStore(options: { enabled?: boolean } = {}) {
+function bootWire(options: { enabled?: boolean } = {}) {
let enabled = options.enabled ?? false
- const fetchFn = vi.fn<FetchFn>(async (_url, init) => {
- const request = JSON.parse(String(init.body)) as { method: string }
- if (request.method === 'settings.get')
- return { json: async () => ({ ok: true, value: { enabled } }) } as unknown as Response
- if (request.method === 'settings.set') {
+ answer((call) => {
+ if (call.url === `${baseURL}/settings` && call.http === 'GET')
+ return replies.ok({ enabled })
+ if (call.url === `${baseURL}/settings`) {
enabled = true
- return { json: async () => ({ ok: true, value: { enabled } }) } as unknown as Response
+ return replies.ok({ enabled })
}
- if (request.method === 'session.role')
- return { json: async () => ({ ok: true, value: { remote: false } }) } as unknown as Response
- return { json: async () => ({ ok: true, value: { enabled, items: [], discovered: [] } }) } as unknown as Response
+ if (call.url === `${baseURL}/session/role`)
+ return replies.ok({ remote: false })
+ return replies.ok({ enabled, items: [], discovered: [] })
})
- return { store: new MachinesStore(fetchFn), fetchFn }
}
-/** The bound dictionary lookup (key is the text, as elsewhere in this package). */
const t = (key: string) => `t:${key}`
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+})
+
afterEach(() => {
cleanup()
})
describe('sshSection', () => {
it('未启用时只渲染 Hero(图标 + 描述 + 开启按钮),不渲染 Tabs 内容', async () => {
- const { store } = bootStore()
- render(<SshSection t={t as never} store={store} />)
+ bootWire()
+ render(<SshSection t={t as never} />)
await waitFor(() => expect(screen.getByTestId('ssh-hero')).toBeTruthy())
expect(screen.getByText('t:hero.title')).toBeTruthy()
@@ -79,13 +51,13 @@ describe('sshSection', () => {
})
it('点击开启:settings.set 落定后原位切换到 Tabs(SSH 机器 / 同步到远端)', async () => {
- const { store, fetchFn } = bootStore()
- render(<SshSection t={t as never} store={store} />)
+ bootWire()
+ render(<SshSection t={t as never} />)
await waitFor(() => expect(screen.getByTestId('ssh-enable')).toBeTruthy())
fireEvent.click(screen.getByTestId('ssh-enable'))
await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
- expect(fetchFn.mock.calls.some(([, init]) => String(init?.body).includes('"settings.set"'))).toBe(true)
+ expect(sent.some(call => call.url === `${baseURL}/settings` && call.http === 'POST')).toBe(true)
const tabs = screen.getAllByRole('tab')
expect(tabs.map(tab => tab.textContent)).toEqual(['t:tabs.machines', 't:tabs.sync'])
expect(screen.queryByTestId('ssh-hero')).toBeNull()
@@ -93,8 +65,8 @@ describe('sshSection', () => {
})
it('已启用:Tabs 默认停在「SSH 机器」,切换后渲染同步面板且已访问面板保持挂载', async () => {
- const { store } = bootStore({ enabled: true })
- render(<SshSection t={t as never} store={store} />)
+ bootWire({ enabled: true })
+ render(<SshSection t={t as never} />)
await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
const machinesPanel = document.getElementById('dsh-tauri-ssh-tabs-machines-panel')
@@ -108,8 +80,8 @@ describe('sshSection', () => {
})
it('壳层 deep link:分区匹配时落到指定标签页,别的分区不动', async () => {
- const { store } = bootStore({ enabled: true })
- render(<SshSection t={t as never} store={store} />)
+ bootWire({ enabled: true })
+ render(<SshSection t={t as never} />)
await waitFor(() => expect(screen.getByTestId('ssh-tabs')).toBeTruthy())
window.dispatchEvent(new MessageEvent('message', {
@@ -128,9 +100,8 @@ describe('sshSection', () => {
})
it('读取开关失败(插件未加载):Hero 呈现本地化的不可用提示而非原生解析异常', async () => {
- const fetchFn = vi.fn<FetchFn>(async () => ({ ok: false, status: 405, json: async () => ({}) }) as unknown as Response)
- const store = new MachinesStore(fetchFn)
- render(<SshSection t={t as never} store={store} />)
+ answer(() => replies.http(405))
+ render(<SshSection t={t as never} />)
await waitFor(() => expect(screen.getByTestId('ssh-hero-error')).toBeTruthy())
expect(screen.getByTestId('ssh-hero-error').textContent).toBe('t:error.unavailable')
diff --git a/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx b/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx
index be72711f..78be822e 100644
--- a/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/ssh-section.tsx
@@ -1,99 +1,74 @@
-/**
- * The single `SSH` settings section: a feature switch in front of two tabs.
- * While the SSH feature is off (the default on a fresh install) the section
- * renders only the enable hero — no machine list, no sync surface, and no
- * connection work on the host. Switching it on reveals the `SSH machines` and
- * `Sync to remote` tabs; the desktop shell deep link picks the tab.
- * @module dsh-tauri-ssh/client/components/ssh-section
- */
-
import type { ReactNode } from 'react'
import type { SshKey } from '../locales/index'
-import type { MachinesStore } from '../store/index'
-import type { RemoteBridge } from '../types/index'
import { Button, Globe, Icon, SegmentedControl } from 'dsh-tauri-ui/client'
-import { listenParent } from 'dsh-tauri/client'
-import { useEffect, useState, useSyncExternalStore } from 'react'
-import { SETTINGS_OPEN_MESSAGE, SETTINGS_SECTION_ID, SSH_TAB_MACHINES, SSH_TAB_SYNC, SSH_TABS_ID } from '../constants'
-import { cls } from '../styles'
+import { cn, useListenParent, useStore } from 'dsh-tauri/client'
+import { useEffect, useState } from 'react'
+import { SETTINGS_OPEN_MESSAGE, SETTINGS_SECTION_ID, SSH_TAB_MACHINES, SSH_TAB_SYNC, SSH_TABS_ID } from '../constants/index'
+import * as service from '../service/machines'
+import { store } from '../store/index'
import { errorTextOf } from '../utils/error'
import { MachinesSection } from './machines-section'
import { SyncPanel } from './sync-panel'
-/** The two tabs of the merged SSH section. */
type SshTab = typeof SSH_TAB_MACHINES | typeof SSH_TAB_SYNC
-export interface SshSectionProps {
- store: MachinesStore
- /** Desktop bridge; absent (or unanswered probe) means pure web. */
- bridge?: RemoteBridge
+interface SshSectionProps {
t: (key: SshKey) => string
}
-/** The tabs of the section, in display order. */
const TAB_KEYS: Record<SshTab, SshKey> = {
[SSH_TAB_MACHINES]: 'tabs.machines',
[SSH_TAB_SYNC]: 'tabs.sync',
}
-/**
- * Render the merged SSH settings section.
- * @returns the enable hero while the feature is off, the tab surface once on.
- */
-export function SshSection({ t, store, bridge }: SshSectionProps): ReactNode {
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot)
+export function SshSection({ t }: SshSectionProps): ReactNode {
+ const state = useStore(store.machines)
const [tab, setTab] = useState<SshTab>(SSH_TAB_MACHINES)
const [visited, setVisited] = useState<ReadonlySet<SshTab>>(() => new Set<SshTab>([SSH_TAB_MACHINES]))
- // 已访问的标签页保持挂载(切回来不丢选择态),与扩展面板的同款做法一致;
- // 切换入口只有下面两个,visited 随选中一起推进,不必再挂一个同步 effect。
function openTab(next: SshTab): void {
setTab(next)
setVisited(previous => previous.has(next) ? previous : new Set<SshTab>([...previous, next]))
}
useEffect(() => {
- if (store.getSnapshot().enabled === null)
- void store.loadSettings()
- }, [store])
-
- // 壳层「管理机器…/同步到远端…」把分区与目标标签页一起发过来;本分区只认自己
- // 的 section,其余交回 dsh-tauri-ui 的通用 deep-link 处理。
- useEffect(() => {
- return listenParent((message) => {
- if (message.section !== SETTINGS_SECTION_ID)
- return
- if (message.tab === SSH_TAB_MACHINES || message.tab === SSH_TAB_SYNC)
- openTab(message.tab)
- }, SETTINGS_OPEN_MESSAGE)
+ if (store.machines.enabled === null)
+ void service.loadSettings()
}, [])
+ useListenParent(SETTINGS_OPEN_MESSAGE, (message) => {
+ if (message.section !== SETTINGS_SECTION_ID)
+ return
+ if (message.tab === SSH_TAB_MACHINES || message.tab === SSH_TAB_SYNC)
+ openTab(message.tab)
+ })
+
if (state.enabled === null) {
return (
- <div className={cls.section} data-testid="ssh-section">
- <p className={cls.hint}>{t('loading')}</p>
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
+ <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('loading')}</p>
</div>
)
}
if (state.enabled === false) {
return (
- <div className={cls.section} data-testid="ssh-section">
- <div className={cls.hero} data-testid="ssh-hero">
- <span className={cls.heroIcon} aria-hidden="true">
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
+ <div className="mt-[4px] flex flex-col items-center gap-[12px] rounded-[12px] border-[0.5px] border-border-l2 bg-layer-1 px-[24px] py-[40px] text-center" data-testid="ssh-hero">
+ <span className="inline-flex h-[44px] w-[44px] items-center justify-center rounded-full bg-[var(--dsw-alias-surface-tinted)] text-brand" aria-hidden="true">
<Icon as={Globe} size={22} />
</span>
- <h2 className={cls.heroTitle}>{t('hero.title')}</h2>
- <p className={cls.heroHint}>{t('hero.desc')}</p>
+ <h2 className="m-0 text-[22px] leading-[32px] font-semibold text-primary">{t('hero.title')}</h2>
+ <p className="m-0 max-w-[460px] text-[13px] leading-[21px] text-secondary">{t('hero.desc')}</p>
{state.error !== null
- ? <p className={cls.error} role="alert" data-testid="ssh-hero-error">{errorTextOf(state.error, t)}</p>
+ ? <p className="m-0 text-[12px] leading-[18px] text-error" role="alert" data-testid="ssh-hero-error">{errorTextOf(state.error, t)}</p>
: null}
<Button
variant="primary"
size="sm"
disabled={state.enabling}
data-testid="ssh-enable"
- onClick={() => void store.enable()}
+ onClick={() => void service.enable()}
>
{state.enabling ? t('hero.enabling') : t('hero.enable')}
</Button>
@@ -105,8 +80,8 @@ export function SshSection({ t, store, bridge }: SshSectionProps): ReactNode {
const tabs: SshTab[] = [SSH_TAB_MACHINES, SSH_TAB_SYNC]
return (
- <div className={cls.section} data-testid="ssh-section">
- <div className={cls.tabs} data-testid="ssh-tabs">
+ <div className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="ssh-section">
+ <div className="flex flex-wrap items-center gap-[8px]" data-testid="ssh-tabs">
<SegmentedControl
id={SSH_TABS_ID}
label={t('nav')}
@@ -124,14 +99,14 @@ export function SshSection({ t, store, bridge }: SshSectionProps): ReactNode {
<div
key={value}
id={`${SSH_TABS_ID}-${value}-panel`}
- className={cls.tabPanel}
+ className={cn('min-w-0 flex-col gap-[12px]', selected ? 'flex' : 'hidden')}
role="tabpanel"
aria-labelledby={`${SSH_TABS_ID}-${value}`}
hidden={!selected}
>
{value === SSH_TAB_MACHINES
- ? <MachinesSection t={t} store={store} bridge={bridge} />
- : <SyncPanel t={t} store={store} />}
+ ? <MachinesSection t={t} />
+ : <SyncPanel t={t} />}
</div>
)
})}
diff --git a/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx b/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx
index 64a4bf8c..58323f31 100644
--- a/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/sync-panel.test.tsx
@@ -1,20 +1,24 @@
+// @vitest-environment jsdom
import type { SshKey } from '../locales/index'
-import type { FetchFn, MachineRow } from '../store/index'
+import type { MachineRow } from '../types/index'
import { fireEvent, screen, waitFor } from '@testing-library/dom'
import { cleanup, render } from '@testing-library/react'
-// @vitest-environment jsdom
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { baseURL } from '../apis/index'
import { en } from '../locales/index'
-import { MachinesStore } from '../store/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
import { SyncPanel } from './sync-panel'
-// dsh-tauri-ui/client 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器
-// 无法在 node 求值;mock 到同一 cssr 实例的源文件(与 dsh-tauri-panel 同款做法),
-// 组件渲染只消费 cls 字符串,不需要真实样式;通用控件转发官方 primitives 真实实现。
-vi.mock('dsh-tauri-ui/client', async () => {
- const mod = await import('../../../../dsh-tauri-ui/src/client/utils/cssr.ts')
- const primitives = await import('@deepseek-ai/dsh-client-ui-primitives')
- return { cssr: mod.cssr, ...primitives }
+vi.mock('dsh-tauri-ui/client', async () => (await import('../test-utils/ui-mock')).uiMock)
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ store.sync.reset()
})
afterEach(() => {
@@ -24,18 +28,12 @@ afterEach(() => {
const t = ((key: string) => (en as Record<string, string>)[key] ?? key) as (key: SshKey) => string
-type FetchMock = ReturnType<typeof vi.fn<FetchFn>>
+const regexOf = (text: string): RegExp => new RegExp(text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
-/** A fetch mock dispatching by /api-ssh method name. */
-function routeFetch(routes: Record<string, unknown>, failures: string[] = []): FetchMock {
- return vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string }
- if (failures.includes(body.method)) {
- return { json: async () => ({ ok: false, error: { code: 'internal', message: `${body.method} broke` } }) } as unknown as Response
- }
- const value = routes[body.method] ?? {}
- return { json: async () => ({ ok: true, value }) } as unknown as Response
- })
+function routeWire(routes: Record<string, unknown>, failures: string[] = []): void {
+ answer(call => failures.includes(call.url)
+ ? replies.fail(`${call.url} broke`)
+ : replies.ok(routes[call.url] ?? {}))
}
const preview = {
@@ -60,37 +58,30 @@ const machineA: MachineRow = {
remotePort: 3080,
}
-/** A store preloaded with one connected machine and a landed sync preview. */
-function connectedStore(fetchFn: FetchMock): MachinesStore {
- const store = new MachinesStore(fetchFn)
- store.store.update((state) => {
- state.status = 'ready'
- state.machines = [machineA]
- state.statuses = { a: { state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' } }
- state.sync = { status: 'ready', error: null, preview, applying: false, results: null }
- })
- return store
+const connectedStatus = { state: 'connected' as const, tunnelBaseUrl: 'http://127.0.0.1:1' }
+
+function seedConnected(): void {
+ store.machines.commitList({ machines: [machineA], discovered: [], statuses: { a: connectedStatus } })
+ store.sync.commitPreview(preview)
}
describe('syncPanel', () => {
it('starts with every syncable item ticked and keeps independent tick state', async () => {
- const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/machines`]: { items: [] } })
+ seedConnected()
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-row-dsh-market')).toBeTruthy())
- // 默认=全选可同步项(不可同步的 local-thing 恒不勾)
expect(screen.getByTestId('sync-row-dsh-market').getAttribute('aria-checked')).toBe('true')
expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('true')
expect(screen.getByTestId('sync-row-beta').getAttribute('aria-checked')).toBe('true')
expect(screen.getByTestId('sync-row-local-thing').getAttribute('aria-checked')).toBe('false')
expect(screen.getByTestId('sync-selected').textContent).toContain('1 plugins and 2 skills selected')
- // 取消一项不动其它项(多选而非单选)
fireEvent.click(screen.getByTestId('sync-row-dsh-market'))
expect(screen.getByTestId('sync-row-dsh-market').getAttribute('aria-checked')).toBe('false')
expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('true')
expect(screen.getByTestId('sync-selected').textContent).toContain('0 plugins and 2 skills selected')
- // 清空 → 全选回来,计数复位
fireEvent.click(screen.getByText('Clear'))
expect(screen.getByTestId('sync-row-alpha').getAttribute('aria-checked')).toBe('false')
fireEvent.click(screen.getByText('Select all'))
@@ -98,22 +89,22 @@ describe('syncPanel', () => {
})
it('disables unsyncable plugins and shows their reason', async () => {
- const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/machines`]: { items: [] } })
+ seedConnected()
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-row-local-thing')).toBeTruthy())
expect(screen.getByTestId('sync-row-local-thing').hasAttribute('disabled')).toBe(true)
expect(screen.getByText(/local-path dependency/)).toBeTruthy()
})
it('sends the whole ticked selection to sync.apply', async () => {
- const fetchFn = routeFetch({ 'sync.apply': { items: [] } })
- const store = connectedStore(fetchFn)
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/sync/apply`]: { items: [] } })
+ seedConnected()
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-apply')).toBeTruthy())
- // 默认全选:一次点击就该带走全部可同步项,不可同步项被排除在外
fireEvent.click(screen.getByTestId('sync-apply'))
- await waitFor(() => expect(applyCalls(fetchFn)).toHaveLength(1))
- expect(applyCalls(fetchFn)[0]).toEqual({
+ await waitFor(() => expect(applyCalls()).toHaveLength(1))
+ expect(applyCalls()[0]).toEqual({
machineId: 'a',
plugins: [{ name: 'dsh-market', spec: 'github:omdsh/dsh-market' }],
skills: [{ name: 'alpha', root: 'dsh' }, { name: 'beta', root: 'agents' }],
@@ -121,31 +112,31 @@ describe('syncPanel', () => {
})
it('shows per-item live progress while an apply runs', async () => {
- const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))
- store.store.update((state) => {
- state.sync.applying = true
- state.statuses = { a: { state: 'connected', progress: { phase: 'syncing', attempt: 3, total: 5, item: 'dsh-tauri-pet' } } }
+ routeWire({ [`${baseURL}/machines`]: { items: [] } })
+ seedConnected()
+ store.sync.beginApply()
+ store.machines.commitList({
+ machines: [machineA],
+ discovered: [],
+ statuses: { a: { ...connectedStatus, progress: { phase: 'syncing', attempt: 3, total: 5, item: 'dsh-tauri-pet' } } },
})
- render(<SyncPanel store={store} t={t} />)
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-progress')).toBeTruthy())
expect(screen.getByTestId('sync-progress').textContent).toContain('3/5')
expect(screen.getByTestId('sync-progress').textContent).toContain('dsh-tauri-pet')
- // 3/5 起跑(已完成 2 项)→ 进度条 40%
- const fill = screen.getByTestId('sync-progress').querySelector('[class*="sync-bar-fill"]') as HTMLElement
+ const fill = screen.getByTestId('sync-progress').querySelector('[class~="bg-brand"]') as HTMLElement
expect(fill.style.width).toBe('40%')
expect(screen.getByTestId('sync-apply').textContent).toContain('Syncing')
})
it('renders partial failures per item with reasons and a retry that re-sends only them', async () => {
- const fetchFn = routeFetch({ 'sync.apply': { items: [] }, 'machine.list': { items: [] } })
- const store = connectedStore(fetchFn)
- store.store.update((state) => {
- state.sync.results = [
- { kind: 'plugin', name: 'dsh-market', ok: true },
- { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },
- ]
- })
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/sync/apply`]: { items: [] }, [`${baseURL}/machines`]: { items: [] } })
+ seedConnected()
+ store.sync.mergeResults([
+ { kind: 'plugin', name: 'dsh-market', ok: true },
+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },
+ ])
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())
expect(screen.getByTestId('sync-result-dsh-market').dataset.ok).toBe('true')
const failed = screen.getByTestId('sync-result-alpha')
@@ -155,8 +146,8 @@ describe('syncPanel', () => {
expect(screen.getByText(/1 succeeded, 1 failed/)).toBeTruthy()
fireEvent.click(screen.getByTestId('sync-retry'))
- await waitFor(() => expect(applyCalls(fetchFn)).toHaveLength(1))
- expect(applyCalls(fetchFn)[0]).toEqual({
+ await waitFor(() => expect(applyCalls()).toHaveLength(1))
+ expect(applyCalls()[0]).toEqual({
machineId: 'a',
plugins: [],
skills: [{ name: 'alpha', root: 'dsh' }],
@@ -164,22 +155,20 @@ describe('syncPanel', () => {
})
it('keeps the failure headline cause-first and shows the raw output on demand', async () => {
- const store = connectedStore(routeFetch({}))
- store.store.update((state) => {
- state.sync.results = [{
- kind: 'plugin',
- name: 'dsh-better-sidebar',
- ok: false,
- error: 'exit 1: make: *** [pty.target.mk:119] Error 127 | gyp ERR! stack Error: `make` failed with exit code: 2',
- log: 'Progress: resolved 584\nmake: *** [pty.target.mk:119] Error 127\n[ERR_PNPM_PREPARE_PACKAGE] failed',
- }]
- })
- render(<SyncPanel store={store} t={t} />)
+ routeWire({})
+ seedConnected()
+ store.sync.mergeResults([{
+ kind: 'plugin',
+ name: 'dsh-better-sidebar',
+ ok: false,
+ error: 'exit 1: make: *** [pty.target.mk:119] Error 127 | gyp ERR! stack Error: `make` failed with exit code: 2',
+ log: 'Progress: resolved 584\nmake: *** [pty.target.mk:119] Error 127\n[ERR_PNPM_PREPARE_PACKAGE] failed',
+ }])
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())
const row = screen.getByTestId('sync-result-dsh-better-sidebar')
expect(row.textContent).toContain('Error 127')
expect(row.textContent).not.toContain('Progress: resolved')
- // 完整输出默认收起,点开才显示(长日志不糊在行内)
const toggle = screen.getByTestId('sync-log-toggle-dsh-better-sidebar')
expect(toggle.getAttribute('aria-expanded')).toBe('false')
expect(screen.queryByTestId('sync-log')).toBeNull()
@@ -189,14 +178,13 @@ describe('syncPanel', () => {
})
it('renders a complete failure with every reason visible', async () => {
- const store = connectedStore(routeFetch({}))
- store.store.update((state) => {
- state.sync.results = [
- { kind: 'plugin', name: 'dsh-market', ok: false, error: 'exit 1: ERR_PNPM_NO_MATCH' },
- { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },
- ]
- })
- render(<SyncPanel store={store} t={t} />)
+ routeWire({})
+ seedConnected()
+ store.sync.mergeResults([
+ { kind: 'plugin', name: 'dsh-market', ok: false, error: 'exit 1: ERR_PNPM_NO_MATCH' },
+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: false, error: 'exit 1: read-only file system' },
+ ])
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-results')).toBeTruthy())
expect(screen.getByText(/0 succeeded, 2 failed/)).toBeTruthy()
expect(screen.getByTestId('sync-result-dsh-market').textContent).toContain('ERR_PNPM_NO_MATCH')
@@ -204,83 +192,67 @@ describe('syncPanel', () => {
})
it('surfaces a request-level failure without swallowing previous results', async () => {
- const fetchFn = routeFetch({ 'sync.apply': { items: [] } }, ['sync.apply'])
- const store = connectedStore(fetchFn)
- store.store.update((state) => {
- state.sync.results = [{ kind: 'plugin', name: 'dsh-market', ok: true }]
- })
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/sync/apply`]: { items: [] } }, [`${baseURL}/sync/apply`])
+ seedConnected()
+ store.sync.mergeResults([{ kind: 'plugin', name: 'dsh-market', ok: true }])
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-apply')).toBeTruthy())
fireEvent.click(screen.getByTestId('sync-apply'))
- await waitFor(() => expect(screen.getByText(/The sync request failed: sync.apply broke/)).toBeTruthy())
+ await waitFor(() => expect(screen.getByText(regexOf(`The sync request failed: ${baseURL}/sync/apply broke`))).toBeTruthy())
expect(screen.getByTestId('sync-result-dsh-market')).toBeTruthy()
})
it('disables apply with an empty tick set', async () => {
- const store = connectedStore(routeFetch({ 'machine.list': { items: [] } }))
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/machines`]: { items: [] } })
+ seedConnected()
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByText('Clear')).toBeTruthy())
fireEvent.click(screen.getByText('Clear'))
expect(screen.getByTestId('sync-apply').hasAttribute('disabled')).toBe(true)
})
it('loads the machine list itself and offers the connected machine as the target', async () => {
- // 本分区可以不经机器页直达:store 还没拉过列表时它必须自己拉一次,
- // 否则已连接的机器在这里看不见(回归:首版漏了这步,页面永远显示空态)。
- const fetchFn = routeFetch({
- 'machine.list': { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] },
- 'sync.preview': preview,
+ routeWire({
+ [`${baseURL}/machines`]: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] },
+ [`${baseURL}/sync/preview`]: preview,
})
- const store = new MachinesStore(fetchFn)
- render(<SyncPanel store={store} t={t} />)
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-target-a')).toBeTruthy())
- expect(apiMethods(fetchFn)).toContain('machine.list')
+ expect(apiMethods()).toContain(`${baseURL}/machines`)
expect(screen.getByTestId('sync-apply').textContent).toContain('Sync to alpha')
expect(screen.queryByTestId('sync-empty')).toBeNull()
})
it('points a remote-session instance back at the initiating machine', async () => {
- const store = new MachinesStore(routeFetch({ 'machine.list': { items: [] }, 'session.role': { remote: true, origin: 'ops' } }))
- render(<SyncPanel store={store} t={t} />)
+ routeWire({ [`${baseURL}/machines`]: { items: [] }, [`${baseURL}/session/role`]: { remote: true, origin: 'ops' } })
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-remote-note')).toBeTruthy())
expect(screen.getByTestId('sync-remote-note').textContent).toContain('Sync to remote')
expect(screen.queryByTestId('sync-apply')).toBeNull()
})
it('shows the not-connected note when no machine is connected', async () => {
- const store = new MachinesStore(routeFetch({}))
- store.store.update((state) => {
- state.status = 'ready'
- state.machines = [machineA]
- state.statuses = { a: { state: 'disconnected' } }
- state.sync = { status: 'ready', error: null, preview, applying: false, results: null }
- })
- render(<SyncPanel store={store} t={t} />)
+ routeWire({})
+ store.machines.commitList({ machines: [machineA], discovered: [], statuses: { a: { state: 'disconnected' } } })
+ store.sync.commitPreview(preview)
+ render(<SyncPanel t={t} />)
await waitFor(() => expect(screen.getByTestId('sync-empty')).toBeTruthy())
expect(screen.getByTestId('sync-empty').textContent).toContain('No connected machines')
expect(screen.queryByTestId('sync-apply')).toBeNull()
})
it('shows the preview load failure with the reason', async () => {
- const fetchFn = routeFetch({}, ['sync.preview'])
- const store = new MachinesStore(fetchFn)
- store.store.update((state) => {
- state.status = 'ready'
- })
- render(<SyncPanel store={store} t={t} />)
- await waitFor(() => expect(screen.getByText(/Failed to load the sync list: sync.preview broke/)).toBeTruthy())
+ routeWire({}, [`${baseURL}/sync/preview`])
+ store.machines.commitList({ machines: [], discovered: [], statuses: {} })
+ render(<SyncPanel t={t} />)
+ await waitFor(() => expect(screen.getByText(regexOf(`Failed to load the sync list: ${baseURL}/sync/preview broke`))).toBeTruthy())
})
})
-/** The /api-ssh methods the fake fetch received, in call order. */
-function apiMethods(fetchFn: ReturnType<typeof vi.fn>): string[] {
- return fetchFn.mock.calls.map(call => (JSON.parse(String(call[1]?.body)) as { method: string }).method)
+function apiMethods(): string[] {
+ return sent.map(call => call.url)
}
-/** The sync.apply request bodies the fake fetch received. */
-function applyCalls(fetchFn: ReturnType<typeof vi.fn>): Array<Record<string, unknown>> {
- return fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })
- .filter(call => call.method === 'sync.apply')
- .map(call => call.payload)
+function applyCalls(): Array<Record<string, unknown>> {
+ return sent.filter(call => call.url === `${baseURL}/sync/apply`).map(call => call.body)
}
diff --git a/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx b/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx
index b9cfe3e5..56be9375 100644
--- a/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx
+++ b/packages/dsh-tauri-ssh/src/client/components/sync-panel.tsx
@@ -1,141 +1,113 @@
'use no memo'
-/**
- * The sync-to-remote page: pick a connected target, tick the local plugins and
- * user-level skills to move (all syncable items start ticked — the entry point
- * is called "sync to remote", so the default answer is "everything"), then
- * watch each item settle. Live progress comes from the target's machine status
- * (`phase: 'syncing'`), which the host publishes item by item; outcomes merge
- * across runs so a retry keeps the earlier batch visible. All domain state
- * lives in the injected {@link MachinesStore}; only the selection and the
- * target are local.
- * @module dsh-tauri-ssh/client/components/sync-panel
- */
-
import type { ReactNode } from 'react'
import type { SshKey } from '../locales/index'
-import type { MachineRow, MachinesStore } from '../store/index'
import type { SyncItemResult, SyncPluginItem, SyncSkillItem } from '../types/index'
import { Button, Pill, StateDot } from 'dsh-tauri-ui/client'
-import { useEffect, useState, useSyncExternalStore } from 'react'
-import { pluginKeyOf, skillKeyOf, syncKeyOf, toggleSelection } from '../store/index'
-import { cls } from '../styles'
+import { cn, useStore } from 'dsh-tauri/client'
+import { useEffect, useState } from 'react'
+import * as machinesService from '../service/machines'
+import * as syncService from '../service/sync'
+import { store } from '../store/index'
+import { syncKeyOf, toggleSelection } from '../store/modules/sync.utils'
import { errorTextOf } from '../utils/error'
-/** The panel props: the framework `t` seat plus the injected store. */
-export interface SyncPanelProps {
- store: MachinesStore
+interface SyncPanelProps {
t: (key: SshKey) => string
}
-/** One selectable row of either group (plugins and skills share the layout). */
interface SelectableRow {
key: string
name: string
- /** The muted right-hand metadata: the dependency spec, or the skill root. */
meta: string
syncable: boolean
reason?: string
}
-/** Render the sync page over the store snapshot. */
-export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot)
- // 选择态:null = 还没动过手,按「全选可同步项」派生(入口叫「同步到远端」,
- // 默认答案就是「都同步」);一旦勾选/清空/重试就以显式集合为准。
+export function SyncPanel({ t }: SyncPanelProps): ReactNode {
+ const machinesState = useStore(store.machines)
+ const syncState = useStore(store.sync)
const [touched, setTouched] = useState<ReadonlySet<string> | null>(null)
const [targetId, setTargetId] = useState<string | null>(null)
useEffect(() => {
- if (state.sync.status === 'idle')
- void store.loadSyncPreview()
- }, [state.sync.status, store])
-
- // 目标候选来自 machine.list:本分区可以不经机器页直达,必须自己拉一次,
- // 否则已连接的机器在这里看不见(两页共用同一个 store 实例,各拉各的)。
- useEffect(() => {
- if (state.status === 'idle')
- void store.load()
- }, [state.status, store])
+ if (syncState.status === 'idle')
+ void syncService.loadSyncPreview()
+ }, [syncState.status])
- const preview = state.sync.preview
-
- // 同步期间轮询机器状态:逐项进度就长在这条通道上(phase: 'syncing')。
- const applying = state.sync.applying
useEffect(() => {
- if (!applying)
- return
- const timer = setInterval(() => void store.poll(), 1000)
- return () => clearInterval(timer)
- }, [applying, store])
+ if (machinesState.status === 'idle')
+ void machinesService.load()
+ }, [machinesState.status])
- const connected = connectedMachinesOf(state.machines, state.discovered, state.statuses)
+ const preview = syncState.preview
+ const applying = syncState.applying
+ const connected = [...machinesState.machines, ...machinesState.discovered].filter(machine => machinesState.statuses[machine.id]?.state === 'connected')
const target = connected.find(machine => machine.id === (targetId ?? connected[0]?.id))
const pluginRows: SelectableRow[] = (preview?.plugins ?? []).map(plugin => ({
- key: pluginKeyOf(plugin),
+ key: syncKeyOf({ kind: 'plugin', name: plugin.name }),
name: plugin.name,
meta: plugin.spec,
syncable: plugin.syncable,
...plugin.reason === undefined ? {} : { reason: plugin.reason },
}))
const skillRows: SelectableRow[] = (preview?.skills ?? []).map(skill => ({
- key: skillKeyOf(skill),
+ key: syncKeyOf({ kind: 'skill', name: skill.name, root: skill.root }),
name: skill.name,
meta: skill.root,
syncable: true,
}))
const selectableKeys = [...pluginRows, ...skillRows].filter(row => row.syncable).map(row => row.key)
const selected = touched ?? new Set(selectableKeys)
- const plugins = (preview?.plugins ?? []).filter(plugin => selected.has(pluginKeyOf(plugin)))
- const skills = (preview?.skills ?? []).filter(skill => selected.has(skillKeyOf(skill)))
+ const plugins = (preview?.plugins ?? []).filter(plugin => selected.has(syncKeyOf({ kind: 'plugin', name: plugin.name })))
+ const skills = (preview?.skills ?? []).filter(skill => selected.has(syncKeyOf({ kind: 'skill', name: skill.name, root: skill.root })))
const canApply = target !== undefined && !applying && (plugins.length > 0 || skills.length > 0)
- const progress = target === undefined ? undefined : state.statuses[target.id]?.progress
+ const progress = target === undefined ? undefined : machinesState.statuses[target.id]?.progress
const syncing = progress?.phase === 'syncing' ? progress : undefined
const apply = (): void => {
if (target === undefined)
return
- void store.applySync(target.id, plugins, skills)
+ void syncService.applySync({ machineId: target.id, plugins, skills })
}
const retryFailed = (): void => {
if (target === undefined || preview === null)
return
- const failed = failedRefsOf(state.sync.results ?? [], preview)
+ const failed = failedRefsOf(syncState.results ?? [], preview)
setTouched(new Set(failed.keys))
- void store.applySync(target.id, failed.plugins, failed.skills)
+ void syncService.applySync({ machineId: target.id, plugins: failed.plugins, skills: failed.skills })
}
return (
- <section className={cls.section} data-testid="sync-panel">
- <div className={cls.sectionHead}>
+ <section className="flex flex-col gap-[12px] max-w-[960px] text-primary" data-testid="sync-panel">
+ <div className="flex flex-wrap items-start justify-between gap-[12px]">
<div>
- <h2 className={cls.title}>{t('sync.title')}</h2>
- <p className={cls.intro}>{t('sync.desc')}</p>
+ <h2 className="m-0 text-[18px] leading-[28px] font-semibold text-primary">{t('sync.title')}</h2>
+ <p className="m-0 text-[13px] leading-[20px] text-tertiary">{t('sync.desc')}</p>
</div>
- <div className={cls.chrome}>
+ <div className="flex shrink-0 flex-wrap items-center gap-[8px]">
<Button
variant="outline"
size="sm"
- disabled={state.sync.status === 'loading' || applying}
+ disabled={syncState.status === 'loading' || applying}
onClick={() => {
- // 刷新回到派生默认(新出现的可同步项自动纳入),再看一遍计数。
setTouched(null)
- void store.loadSyncPreview()
+ void syncService.loadSyncPreview()
}}
>
{t('sync.refresh')}
</Button>
</div>
</div>
- {state.role?.remote === true
- ? <p className={cls.empty} data-testid="sync-remote-note">{t('sync.remoteSessionHint')}</p>
+ {machinesState.role?.remote === true
+ ? <p className="m-0 rounded-[8px] border border-dashed border-border-l3 p-[12px] text-center text-[12px] leading-[18px] text-tertiary" data-testid="sync-remote-note">{t('sync.remoteSessionHint')}</p>
: connected.length === 0
- ? <p className={cls.empty} data-testid="sync-empty">{t('sync.notConnectedHint')}</p>
+ ? <p className="m-0 rounded-[8px] border border-dashed border-border-l3 p-[12px] text-center text-[12px] leading-[18px] text-tertiary" data-testid="sync-empty">{t('sync.notConnectedHint')}</p>
: (
<>
- <div className={cls.syncTargets}>
- <span className={cls.fieldLabel}>{t('sync.target')}</span>
+ <div className="flex flex-wrap items-center gap-[6px]">
+ <span className="text-[12px] leading-[18px] font-medium text-secondary">{t('sync.target')}</span>
{connected.map(machine => (
<Pill
key={machine.id}
@@ -145,20 +117,20 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
data-testid={`sync-target-${machine.id}`}
onClick={() => setTargetId(machine.id)}
>
- <span className={cls.syncChip}>
+ <span className="inline-flex items-center gap-[6px]">
<StateDot state="done" size={6} />
{machine.name}
</span>
</Pill>
))}
</div>
- {preview === null || state.sync.status === 'loading'
- ? <p className={cls.hint}>{t('loading')}</p>
- : (state.sync.status === 'ready'
+ {preview === null || syncState.status === 'loading'
+ ? <p className="m-0 text-[12px] leading-[18px] text-tertiary">{t('loading')}</p>
+ : (syncState.status === 'ready'
? (
<>
- <div className={cls.syncToolbar}>
- <span className={cls.syncCount} data-testid="sync-selected">
+ <div className="flex flex-wrap items-center gap-[8px] pt-[2px]">
+ <span className="text-[12px] leading-[18px] text-secondary" data-testid="sync-selected">
{t('sync.selected')
.replace('{plugins}', String(plugins.length))
.replace('{skills}', String(skills.length))}
@@ -194,7 +166,7 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
</>
)
: null)}
- <div className={cls.syncActions}>
+ <div className="flex flex-wrap items-center gap-[10px] pt-[2px]">
<Button variant="primary" size="sm" disabled={!canApply} data-testid="sync-apply" onClick={apply}>
{applying
? t('sync.applying')
@@ -204,14 +176,14 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
</Button>
{syncing !== undefined
? (
- <div className={cls.syncProgress} data-testid="sync-progress">
- <span className={cls.syncBar} aria-hidden="true">
+ <div className="flex min-w-[220px] flex-1 items-center gap-[8px]" data-testid="sync-progress">
+ <span className="block h-[4px] flex-1 overflow-hidden rounded-[2px] bg-border-l2" aria-hidden="true">
<span
- className={cls.syncBarFill}
+ className="block h-full rounded-[2px] bg-brand [transition:width_200ms_ease]"
style={{ width: `${barPercentOf(syncing.attempt, syncing.total)}%` }}
/>
</span>
- <span className={cls.syncProgressText}>
+ <span className="shrink-0 text-[12px] leading-[18px] text-secondary">
{t('sync.progress')
.replace('{done}', String(syncing.attempt ?? 0))
.replace('{total}', String(syncing.total ?? 0))
@@ -223,30 +195,29 @@ export function SyncPanel({ store, t }: SyncPanelProps): ReactNode {
</div>
</>
)}
- {state.sync.status === 'error'
+ {syncState.status === 'error'
? (
- <p className={cls.error} role="alert">
+ <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">
{t('sync.loadFailed')}
- {errorTextOf(state.sync.error ?? '', t)}
+ {errorTextOf(syncState.error ?? '', t)}
</p>
)
: null}
- {state.sync.error !== null && state.sync.status !== 'error'
+ {syncState.error !== null && syncState.status !== 'error'
? (
- <p className={cls.error} role="alert">
+ <p className="m-0 text-[12px] leading-[18px] text-error" role="alert">
{t('sync.applyFailed')}
- {errorTextOf(state.sync.error, t)}
+ {errorTextOf(syncState.error, t)}
</p>
)
: null}
- {state.sync.results !== null
- ? <SyncResults results={state.sync.results} applying={applying} t={t} onRetry={retryFailed} />
+ {syncState.results !== null
+ ? <SyncResults results={syncState.results} applying={applying} t={t} onRetry={retryFailed} />
: null}
</section>
)
}
-/** One selection group: a counted header plus one checkbox row per item. */
function SyncGroup({ label, empty, rows, selected, t, onToggle }: {
label: string
empty: string
@@ -255,57 +226,58 @@ function SyncGroup({ label, empty, rows, selected, t, onToggle }: {
t: (key: SshKey) => string
onToggle: (key: string) => void
}): ReactNode {
- // 计数只算「可同步」的条目:不可同步的行恒不勾,算进去会读出「2/15 已选」的假象。
const syncable = rows.filter(row => row.syncable)
const checked = syncable.filter(row => selected.has(row.key)).length
return (
- <div className={cls.syncGroup}>
- <div className={cls.syncGroupHead}>
- <span className={cls.fieldLabel}>{label}</span>
+ <div className="flex flex-col gap-[6px]">
+ <div className="flex items-center gap-[6px]">
+ <span className="text-[12px] leading-[18px] font-medium text-secondary">{label}</span>
{rows.length === 0
? null
- : <span className={cls.syncCount}>{t('sync.groupCount').replace('{checked}', String(checked)).replace('{total}', String(syncable.length))}</span>}
+ : <span className="text-[12px] leading-[18px] text-secondary">{t('sync.groupCount').replace('{checked}', String(checked)).replace('{total}', String(syncable.length))}</span>}
</div>
{rows.length === 0
- ? <p className={cls.hint}>{empty}</p>
+ ? <p className="m-0 text-[12px] leading-[18px] text-tertiary">{empty}</p>
: (
- <ul className={cls.syncItems}>
- {rows.map(row => (
- <li key={row.key} className={cls.syncItem}>
- <button
- type="button"
- role="checkbox"
- aria-checked={row.syncable && selected.has(row.key)}
- className={cls.syncRow}
- data-testid={`sync-row-${row.name}`}
- disabled={!row.syncable || undefined}
- title={row.reason}
- onClick={() => onToggle(row.key)}
- >
- <span className={cls.syncBox} aria-hidden="true">
- {row.syncable && selected.has(row.key)
- ? (
- <svg fill="none" height="10" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.4" viewBox="0 0 12 12" width="10">
- <path d="M2 6.5 4.6 9 10 3.5" />
- </svg>
- )
- : null}
- </span>
- <span className={cls.syncText}>
- <span className={cls.syncName}>{row.name}</span>
- {row.syncable ? null : <span className={cls.syncReason}>{row.reason ?? t('sync.notSyncable')}</span>}
- </span>
- <span className={cls.syncMeta}>{row.meta}</span>
- </button>
- </li>
- ))}
+ <ul className="m-0 flex list-none flex-col gap-[2px] p-0">
+ {rows.map((row) => {
+ const ticked = row.syncable && selected.has(row.key)
+ return (
+ <li key={row.key} className="flex flex-wrap items-center gap-[8px]">
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={ticked}
+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-[8px] rounded-[6px] border-0 bg-transparent px-[8px] py-[5px] text-left text-[13px] leading-[20px] text-inherit [font-family:inherit] hover:not-disabled:bg-hover disabled:cursor-not-allowed disabled:opacity-60"
+ data-testid={`sync-row-${row.name}`}
+ disabled={!row.syncable || undefined}
+ title={row.reason}
+ onClick={() => onToggle(row.key)}
+ >
+ <span className={cn('inline-flex h-[14px] w-[14px] shrink-0 items-center justify-center rounded-[4px] border border-border-l4 text-primary-fg', ticked && 'border-brand bg-brand')} aria-hidden="true">
+ {ticked
+ ? (
+ <svg fill="none" height="10" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.4" viewBox="0 0 12 12" width="10">
+ <path d="M2 6.5 4.6 9 10 3.5" />
+ </svg>
+ )
+ : null}
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-[1px]">
+ <span className="truncate text-[13px] leading-[20px] text-primary">{row.name}</span>
+ {row.syncable ? null : <span className="truncate text-[11px] leading-[16px] text-[var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary))]">{row.reason ?? t('sync.notSyncable')}</span>}
+ </span>
+ <span className="ml-auto max-w-[40%] shrink-0 truncate pl-[8px] text-[11px] leading-[16px] text-tertiary">{row.meta}</span>
+ </button>
+ </li>
+ )
+ })}
</ul>
)}
</div>
)
}
-/** The merged outcome list: every item this page attempted, with the tally. */
function SyncResults({ results, applying, t, onRetry }: {
results: readonly SyncItemResult[]
applying: boolean
@@ -316,28 +288,28 @@ function SyncResults({ results, applying, t, onRetry }: {
const failed = results.length - okCount
const [openLogOf, setOpenLogOf] = useState<string | null>(null)
return (
- <div className={cls.syncResults} data-testid="sync-results">
- <p className={cls.syncSummary}>
+ <div className="mt-[4px] flex flex-col items-start gap-[6px] border-t border-t-border-l2 pt-[12px]" data-testid="sync-results">
+ <p className="m-0 text-[12px] leading-[18px] text-secondary">
{t('sync.summary').replace('{ok}', String(okCount)).replace('{failed}', String(failed))}
</p>
- <ul className={cls.syncItems}>
+ <ul className="m-0 flex list-none flex-col gap-[2px] p-0">
{results.map(item => (
<li
key={syncKeyOf(item)}
- className={cls.syncResult}
+ className="flex flex-wrap items-center gap-[8px]"
data-testid={`sync-result-${item.name}`}
data-ok={item.ok}
>
<StateDot state={item.ok ? 'done' : 'error'} size={8} />
- <span className={cls.syncResultName}>
+ <span className="text-[12px] leading-[18px] font-medium text-primary">
{item.name}
{item.root === undefined ? '' : ` (${item.root})`}
</span>
{item.ok
- ? <span className={cls.syncOk}>{t('sync.itemOk')}</span>
+ ? <span className="text-[12px] leading-[18px] text-success">{t('sync.itemOk')}</span>
: (
<>
- <span className={cls.statusError} role="alert">
+ <span className="m-0 text-[12px] leading-[18px] text-error" role="alert">
{t('sync.itemFailed')}
{item.error === undefined ? '' : `:${item.error}`}
</span>
@@ -346,7 +318,7 @@ function SyncResults({ results, applying, t, onRetry }: {
: (
<button
type="button"
- className={cls.syncLogToggle}
+ className="cursor-pointer border-0 bg-transparent p-0 text-[12px] leading-[18px] text-business"
aria-expanded={openLogOf === syncKeyOf(item)}
data-testid={`sync-log-toggle-${item.name}`}
onClick={() => setOpenLogOf(current => current === syncKeyOf(item) ? null : syncKeyOf(item))}
@@ -369,7 +341,7 @@ function SyncResults({ results, applying, t, onRetry }: {
{openLogOf === null
? null
: (
- <pre className={cls.logStream} data-testid="sync-log">
+ <pre className="m-0 max-h-[160px] overflow-auto font-mono text-[11px] leading-[16px] whitespace-pre-wrap text-tertiary [overflow-wrap:anywhere]" data-testid="sync-log">
{results.find(item => syncKeyOf(item) === openLogOf)?.log ?? ''}
</pre>
)}
@@ -377,31 +349,20 @@ function SyncResults({ results, applying, t, onRetry }: {
)
}
-/** The failed items of the last runs, resolved back to selectable refs. */
function failedRefsOf(
results: readonly SyncItemResult[],
- preview: { plugins: SyncPluginItem[], skills: SyncSkillItem[] },
+ preview: { plugins: readonly SyncPluginItem[], skills: readonly SyncSkillItem[] },
): { keys: Set<string>, plugins: SyncPluginItem[], skills: SyncSkillItem[] } {
const keys = new Set(results.filter(item => !item.ok).map(syncKeyOf))
return {
keys,
- plugins: preview.plugins.filter(plugin => keys.has(pluginKeyOf(plugin))),
- skills: preview.skills.filter(skill => keys.has(skillKeyOf(skill))),
+ plugins: preview.plugins.filter(plugin => keys.has(syncKeyOf({ kind: 'plugin', name: plugin.name }))),
+ skills: preview.skills.filter(skill => keys.has(syncKeyOf({ kind: 'skill', name: skill.name, root: skill.root }))),
}
}
-/** The determinate bar width; an unknown total reads as empty. */
function barPercentOf(attempt: number | undefined, total: number | undefined): number {
if (total === undefined || total <= 0)
return 0
return Math.min(100, Math.round((Math.max(0, (attempt ?? 0) - 1) / total) * 100))
}
-
-/** The connected machines, manual first then discovered, in list order. */
-function connectedMachinesOf(
- machines: readonly MachineRow[],
- discovered: readonly MachineRow[],
- statuses: Record<string, { state: string }>,
-): MachineRow[] {
- return [...machines, ...discovered].filter(machine => statuses[machine.id]?.state === 'connected')
-}
diff --git a/packages/dsh-tauri-ssh/src/client/constants/index.ts b/packages/dsh-tauri-ssh/src/client/constants/index.ts
index 309aa0e9..dfc524f5 100644
--- a/packages/dsh-tauri-ssh/src/client/constants/index.ts
+++ b/packages/dsh-tauri-ssh/src/client/constants/index.ts
@@ -1,44 +1,19 @@
-/**
- * Shared client constants of the SSH-machines settings page: the settings
- * slot protocol identifiers, the locale namespace, and the same-origin API
- * route the host half (`dsh-tauri-ssh`) mounts.
- * @module dsh-tauri-ssh/client/constants
- */
+import { SSH_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
-/** Dictionary namespace owned by this plugin. */
-export const SSH_LOCALE_NS = 'ssh'
+export { SSH_PLUGIN_NAME as PLUGIN_ID } from '../../shared/constants'
-/** The settings section slot this plugin registers into. */
export const SETTINGS_SECTION_SLOT = 'settings.section'
-
-/** Registration id of this plugin's single settings section (the host plugin's id). */
-export const SETTINGS_SECTION_ID = 'dsh-tauri-ssh'
-
-/** Order of this plugin's settings section among the other sections. */
+export const SETTINGS_SECTION_ID = PLUGIN_ID
export const SETTINGS_SECTION_ORDER = 50
-/** The machines tab of the SSH section (shared with the shell deep link). */
export const SSH_TAB_MACHINES = 'machines'
-
-/** The sync-to-remote tab of the SSH section (shared with the shell deep link). */
export const SSH_TAB_SYNC = 'sync'
-
-/** DOM id base of the tab strip; each panel is `${SSH_TABS_ID}-${tab}-panel`. */
export const SSH_TABS_ID = 'dsh-tauri-ssh-tabs'
-
-/** The shell → iframe settings deep link (the `tab` field picks the SSH tab). */
export const SETTINGS_OPEN_MESSAGE = 'dsh://settings:open'
-/** The /api-ssh route the host plugin mounts (same-origin POST envelope). */
-export { SSH_API_PREFIX as SSH_API_PATH } from '../../shared/constants'
-
-/**
- * C-BRIDGE (S5-owned): the desktop iframe invoke commands the panel talks to
- * through `invokeBridgedTauri`. A timeout or rejection on the ping means the
- * page runs outside the desktop shell (pure web) and the popup affordance
- * hides itself.
- */
export const REMOTE_BRIDGE_PING_COMMAND = 'remote_bridge_ping'
-
-/** Open (or focus) the `remote-<machineId>` window for a tunnel URL. */
export const REMOTE_OPEN_WINDOW_COMMAND = 'remote_open_window'
+
+export const LOCALE_EFFECT = `${PLUGIN_ID}: locale`
+export const SECTION_EFFECT = `${PLUGIN_ID}: settings section`
+export const POLL_EFFECT = `${PLUGIN_ID}: machine polling`
diff --git a/packages/dsh-tauri-ssh/src/client/index.test.ts b/packages/dsh-tauri-ssh/src/client/index.test.ts
index 2766ee6c..293990a5 100644
--- a/packages/dsh-tauri-ssh/src/client/index.test.ts
+++ b/packages/dsh-tauri-ssh/src/client/index.test.ts
@@ -1,70 +1,65 @@
-import type { UiContext } from './types/index'
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { SshSection } from './components/ssh-section.tsx'
-import { apply, inject } from './index'
-import { en, zh } from './locales/index'
-import { desktopBridge } from './service/bridge'
-import { MachinesStore } from './store/index'
+import type { ClientContext } from 'dsh-tauri/client'
+import { describe, expect, it, vi } from 'vitest'
-// The desktop invoke bridge resolves through the runtime module table, which
-// does not exist under vitest; the registrant tests only need its shape.
-// (vitest hoists vi.mock above the imports, so placement here is safe.)
-vi.mock('dsh-tauri/client', () => ({
- invoke: vi.fn(async () => undefined),
- defineRegister: (feature: (controller: unknown) => void) => feature,
-}))
+import { SshSection } from './components/ssh-section.tsx'
+import { LOCALE_EFFECT, PLUGIN_ID, POLL_EFFECT, SECTION_EFFECT } from './constants/index'
+import { apply, inject, name } from './index'
-// dsh-tauri-ui/client 的 dist bundle 以 ModuleLoader 工厂包裹,脱离宿主加载器
-// 无法在 node 求值;样式挂载只需要一个可观察的 mountStyle 桩,cssr 用源文件
-// 实例(与 dsh-tauri-panel 的 cssr 测试同款做法)。
-vi.mock('dsh-tauri-ui/client', async () => {
- const mod = await import('../../../dsh-tauri-ui/src/client/utils/cssr.ts')
- return { cssr: mod.cssr, mountStyle: vi.fn(() => () => {}) }
+vi.mock('dsh-tauri/client', async () => {
+ const seam = await import('./test-utils/client-mock')
+ return {
+ ...seam.clientMock,
+ defineLocale: () => ({ NS: 'dsh-tauri-ssh', text: (key: string) => `t:${key}`, registerLocale: () => () => {} }),
+ }
})
-function scriptedCtx(): {
- ctx: UiContext
- locale: { register: ReturnType<typeof vi.fn>, bind: ReturnType<typeof vi.fn> }
+vi.mock('dsh-tauri-ui/client', () => ({}))
+
+interface ScriptedCtx {
+ ctx: ClientContext
slots: { inject: ReturnType<typeof vi.fn>, register: ReturnType<typeof vi.fn> }
- effects: Array<() => void>
-} {
- const locale = {
- register: vi.fn(),
- bind: vi.fn(() => (key: string) => `t:${key}`),
- }
+ effects: { run: (this: unknown) => unknown, label: string }[]
+}
+
+function scriptedCtx(): ScriptedCtx {
const slots = {
- inject: vi.fn(),
+ inject: vi.fn((_slot: string, _callback: () => unknown) => () => {}),
register: vi.fn(() => 'registration'),
}
- const effects: Array<() => void> = []
+ const effects: { run: (this: unknown) => unknown, label: string }[] = []
const ctx = {
- effect: vi.fn((callback: () => void) => { effects.push(callback) }),
- get: vi.fn(() => undefined),
- locale,
+ effect: (run: (this: unknown) => unknown, label: string) => { effects.push({ run, label }) },
+ get: () => undefined,
+ locale: {},
slots,
- } as unknown as UiContext
- return { ctx, locale, slots, effects }
+ } as unknown as ClientContext
+ return { ctx, slots, effects }
}
-describe('ui-ssh client plugin', () => {
- it('declares its inject topology', () => {
+describe('dsh-tauri-ssh client plugin', () => {
+ it('declares its inject topology and its plugin name', () => {
expect(inject).toEqual(['slots', 'locale'])
+ expect(name).toBe(PLUGIN_ID)
})
- it('registers the ssh dictionaries on activation', () => {
- const { ctx, locale, effects } = scriptedCtx()
+ it('registers three declarative effects on activation and does no eager work', () => {
+ const { ctx, slots, effects } = scriptedCtx()
apply(ctx)
- expect(effects).toHaveLength(2)
- effects[0]?.()
- expect(locale.register).toHaveBeenCalledWith('ssh', { zh, en })
- expect(locale.bind).toHaveBeenCalledWith('ssh')
+ expect(effects.map(entry => entry.label)).toEqual([LOCALE_EFFECT, SECTION_EFFECT, POLL_EFFECT])
+ for (const entry of effects)
+ expect(entry.run).toBeTypeOf('function')
+ expect(slots.inject).not.toHaveBeenCalled()
+ expect(slots.register).not.toHaveBeenCalled()
})
- it('registers the single SSH settings section with a store-backed inject face', async () => {
- const { ctx, slots } = scriptedCtx()
+ it('registers the single SSH settings section through the slots service', () => {
+ const { ctx, slots, effects } = scriptedCtx()
apply(ctx)
+ const section = effects.find(entry => entry.label === SECTION_EFFECT)
+ const dispose = section?.run.call(ctx)
expect(slots.inject).toHaveBeenCalledTimes(1)
expect(slots.inject).toHaveBeenCalledWith('settings.section', expect.any(Function))
+
const contribution = slots.inject.mock.calls[0]?.[1] as () => unknown
contribution()
const options = slots.register.mock.calls[0]?.[0] as {
@@ -73,28 +68,16 @@ describe('ui-ssh client plugin', () => {
order: number
label: () => string
locale: string
- inject: () => Record<string, unknown>
+ inject?: unknown
}
expect(options.name).toBe('settings.section')
- expect(options.id).toBe('dsh-tauri-ssh')
+ expect(options.id).toBe(PLUGIN_ID)
expect(options.order).toBe(50)
expect(options.label()).toBe('t:nav')
- expect(options.locale).toBe('ssh')
- const injected = options.inject()
- expect(injected.store).toBeInstanceOf(MachinesStore)
- expect(injected.bridge).toBe(desktopBridge)
- // 机器管理与同步合并在同一个分区内(组件内部用 Tabs 分页)
+ expect(options.locale).toBe(PLUGIN_ID)
+ expect(options.inject).toBeUndefined()
expect(slots.register.mock.calls[0]?.[1]).toBe(SshSection)
- // Drive one store load so the window.fetch thunk the plugin installed
- // actually executes (stubbed: no network in tests).
- const fetchMock = vi.fn(async () => ({ json: async () => ({ ok: true, value: { enabled: true, items: [] } }) }) as unknown as Response)
- vi.stubGlobal('fetch', fetchMock)
- const store = injected.store as MachinesStore
- await store.load()
- expect(fetchMock).toHaveBeenCalledWith('/api-ssh', expect.objectContaining({ method: 'POST' }))
+ expect(dispose).toBeTypeOf('function')
+ ;(dispose as () => void)()
})
})
-
-afterEach(() => {
- vi.unstubAllGlobals()
-})
diff --git a/packages/dsh-tauri-ssh/src/client/index.ts b/packages/dsh-tauri-ssh/src/client/index.ts
index 31107b34..a54a3ac0 100644
--- a/packages/dsh-tauri-ssh/src/client/index.ts
+++ b/packages/dsh-tauri-ssh/src/client/index.ts
@@ -1,52 +1,17 @@
-/**
- * SSH-machines settings page, browser half. Registers the `ssh` dictionary
- * and the single `SSH` settings section that fronts the whole feature with an
- * enable switch (off by default) and, once on, hosts the machines and the
- * plugin/skill sync tabs. The page state lives in the injected MachinesStore
- * (feature flag, machine CRUD, the connection plane and the sync surface, all
- * through the host plugin's /api-ssh route). The css-render style tree mounts
- * once here via ctx.effect (unmounts with the plugin). Export discipline: thin
- * apply, everything else in feature modules.
- * @module dsh-tauri-ssh/client
- */
+import type { ClientContext } from 'dsh-tauri/client'
+import { LOCALE_EFFECT, PLUGIN_ID, POLL_EFFECT, SECTION_EFFECT } from './constants/index'
+import { locale } from './locales/index'
+import { pollFeature } from './register/poll'
+import { sectionFeature } from './register/section'
-import type { UiContext } from './types'
-import { mountStyle } from 'dsh-tauri-ui/client'
-import { SSH_PLUGIN_NAME } from '../shared/constants'
-import { SshSection } from './components/ssh-section'
-import {
- SETTINGS_SECTION_ID,
- SETTINGS_SECTION_ORDER,
- SETTINGS_SECTION_SLOT,
- SSH_LOCALE_NS,
-} from './constants'
-import { en, zh } from './locales'
-import { desktopBridge } from './service/bridge'
-import { MachinesStore } from './store'
-import { SSH_STYLE_ID, sshStyle } from './styles'
+export type { SshKey } from './locales/index'
+
+export const name = PLUGIN_ID
-/** Required services: the settings slot seam and the locale seat. */
export const inject = ['slots', 'locale']
-/**
- * Register the `ssh` dictionary and the SSH settings section, once the slot
- * declaration is on the ledger.
- * @param ctx - client root context.
- */
-export function apply(ctx: UiContext): void {
- ctx.effect(() => ctx.locale.register(SSH_LOCALE_NS, { zh, en }), 'dsh-tauri-ssh: dictionaries')
- ctx.effect(() => mountStyle(sshStyle, SSH_STYLE_ID, SSH_PLUGIN_NAME), 'dsh-tauri-ssh: styles')
- const t = ctx.locale.bind(SSH_LOCALE_NS)
- const store = new MachinesStore((url, init) => fetch(url, init))
- ctx.slots.inject(SETTINGS_SECTION_SLOT, () => ctx.slots.register({
- name: SETTINGS_SECTION_SLOT,
- id: SETTINGS_SECTION_ID,
- order: SETTINGS_SECTION_ORDER,
- label: () => t('nav'),
- locale: SSH_LOCALE_NS,
- inject: () => ({ store, bridge: desktopBridge }),
- }, SshSection))
+export function apply(ctx: ClientContext): void {
+ ctx.effect(locale.registerLocale, LOCALE_EFFECT)
+ ctx.effect(sectionFeature, SECTION_EFFECT)
+ ctx.effect(pollFeature, POLL_EFFECT)
}
-
-/** The dictionary key union, re-exported for the section props. */
-export type { SshKey } from './locales'
diff --git a/packages/dsh-tauri-ssh/src/client/locales/index.test.ts b/packages/dsh-tauri-ssh/src/client/locales/index.test.ts
index e33d44fc..80ad46cd 100644
--- a/packages/dsh-tauri-ssh/src/client/locales/index.test.ts
+++ b/packages/dsh-tauri-ssh/src/client/locales/index.test.ts
@@ -1,5 +1,9 @@
-import { describe, expect, it } from 'vitest'
-import { en, zh } from './index'
+import { describe, expect, it, vi } from 'vitest'
+
+import { PLUGIN_ID } from '../constants/index'
+import { en, locale, zh } from './index'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
describe('locales', () => {
it('en covers every zh key with no extras', () => {
@@ -14,4 +18,8 @@ describe('locales', () => {
expect(value, `en.${key}`).toBeTruthy()
}
})
+
+ it('registers the plugin namespace', () => {
+ expect(locale.NS).toBe(PLUGIN_ID)
+ })
})
diff --git a/packages/dsh-tauri-ssh/src/client/locales/index.ts b/packages/dsh-tauri-ssh/src/client/locales/index.ts
index 36930a6f..48960d35 100644
--- a/packages/dsh-tauri-ssh/src/client/locales/index.ts
+++ b/packages/dsh-tauri-ssh/src/client/locales/index.ts
@@ -1,6 +1,6 @@
-/** The SSH-machines settings page dictionary (zh is the key-set source of truth). */
+import { defineLocale } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../constants/index'
-/** Simplified Chinese dictionary. */
export const zh = {
'nav': '服务器',
'tabs.machines': 'SSH 机器',
@@ -9,7 +9,6 @@ export const zh = {
'hero.desc': '把本机作为发起端,用 SSH 连接其他机器上的 dsh 实例:直连使用本机 ~/.ssh 的配置与密钥,可管理多台机器并一键切换、同步插件与 Skill。默认关闭,开启后才建立连接。',
'hero.enable': '启用 SSH',
'hero.enabling': '正在启用…',
- 'hero.loadFailed': '无法读取 SSH 状态。',
'error.unavailable': 'SSH 服务不可用:插件未加载或本地实例未就绪。',
'title': 'SSH 远程机器',
'intro': '连接直接使用本机 ~/.ssh 的配置与密钥:支持 config 别名、IdentityFile 与默认密钥;密码和私钥口令可选,仅在密钥不可用时作为回退。',
@@ -63,7 +62,6 @@ export const zh = {
'status.nextRetry': '(下次重试:{hint})',
'retry.now': '即刻',
'retry.inSeconds': '{seconds}s 后',
- 'log.title': '日志',
'remove.confirm.title': '删除机器',
'remove.confirm.description': '将删除「{name}」的机器配置;已保存的密码/口令会一并删除。',
'remove.confirm.cancel': '取消',
@@ -120,13 +118,11 @@ export const zh = {
'install.done.copied': '安装完成,已复制本机 API Key,正在自动连接…',
'install.done.nokey': '安装完成。本机未找到 DEEPSEEK_API_KEY,请在远端 dsh Web 的 Models 页面配置后使用。',
'install.done.error': '安装完成,但凭据复制失败:',
-} satisfies Record<string, string>
+} as const
-/** The dictionary key union. */
export type SshKey = keyof typeof zh
-/** English dictionary, checked complete against the zh key set. */
-export const en = {
+export const en: Record<keyof typeof zh, string> = {
'nav': 'Service',
'tabs.machines': 'SSH machines',
'tabs.sync': 'Sync to remote',
@@ -134,7 +130,6 @@ export const en = {
'hero.desc': 'Drive other machines\' dsh instances from this one over SSH: connections use this machine\'s ~/.ssh directly, and you can keep several machines, switch between them, and sync plugins and skills. Off by default — nothing connects until you enable it.',
'hero.enable': 'Enable SSH',
'hero.enabling': 'Enabling…',
- 'hero.loadFailed': 'Could not read the SSH state.',
'error.unavailable': 'The SSH service is unavailable: the plugin is not loaded or the local instance is not ready.',
'title': 'SSH Remote Machines',
'intro': 'Connections use this machine\'s ~/.ssh directly: config aliases, IdentityFile, and the default keys are honored; password and passphrase are optional fallbacks.',
@@ -188,7 +183,6 @@ export const en = {
'status.nextRetry': ' (next retry: {hint})',
'retry.now': 'now',
'retry.inSeconds': 'in {seconds}s',
- 'log.title': 'Log',
'remove.confirm.title': 'Remove machine',
'remove.confirm.description': 'This removes the "{name}" machine profile; any stored password or passphrase goes with it.',
'remove.confirm.cancel': 'Cancel',
@@ -245,4 +239,6 @@ export const en = {
'install.done.copied': 'Installed. Your API key was copied to the remote; auto-connecting…',
'install.done.nokey': 'Installed. No DEEPSEEK_API_KEY found locally; configure one on the remote Models page to use it.',
'install.done.error': 'Installed, but copying credentials failed: ',
-} satisfies Record<SshKey, string>
+}
+
+export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/packages/dsh-tauri-ssh/src/client/register/poll.test.ts b/packages/dsh-tauri-ssh/src/client/register/poll.test.ts
new file mode 100644
index 00000000..f1525564
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/register/poll.test.ts
@@ -0,0 +1,88 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import type { MachineRow } from '../types/index'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { baseURL } from '../apis/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import { pollFeature } from './poll'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const MACHINES_INTERVAL_MS = 1500
+
+const machineA: MachineRow = {
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ hasPassword: true,
+ hasPassphrase: false,
+ remotePort: 3080,
+}
+
+const urls = (): string[] => sent.map(call => call.url)
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ store.sync.reset()
+ answer(call => call.url === `${baseURL}/machines`
+ ? replies.ok({ items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] })
+ : replies.ok({ items: [] }))
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+})
+
+describe('pollFeature', () => {
+ it('polls the host while an operation is in flight and stops when idle', async () => {
+ vi.useFakeTimers()
+ const stop = pollFeature.call({} as unknown as ClientContext)
+ store.machines.status = 'ready'
+ store.machines.machines = [machineA]
+ store.machines.statuses = { a: { state: 'connecting', progress: { phase: 'handshake' } } }
+
+ const before = sent.length
+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS + 100)
+ expect(sent.length).toBe(before + 2)
+ expect(urls()).toEqual([`${baseURL}/machines`, `${baseURL}/machines/events`])
+
+ store.machines.statuses = { a: { state: 'disconnected' } }
+ store.machines.busy = {}
+ const idle = sent.length
+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS * 2)
+ expect(sent.length).toBe(idle)
+
+ stop()
+ })
+
+ it('refreshes while an apply is running and stops when it finishes', async () => {
+ vi.useFakeTimers()
+ const stop = pollFeature.call({} as unknown as ClientContext)
+ store.sync.applying = true
+
+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS + 50)
+ expect(sent.length).toBe(2)
+
+ store.sync.applying = false
+ store.machines.statuses = {}
+ const idle = sent.length
+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS * 2)
+ expect(sent.length).toBe(idle)
+
+ stop()
+ })
+
+ it('disposes the interval when the feature unloads', async () => {
+ vi.useFakeTimers()
+ const stop = pollFeature.call({} as unknown as ClientContext)
+ store.machines.statuses = { a: { state: 'connecting' } }
+ stop()
+
+ await vi.advanceTimersByTimeAsync(MACHINES_INTERVAL_MS * 2)
+ expect(sent).toHaveLength(0)
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/register/poll.ts b/packages/dsh-tauri-ssh/src/client/register/poll.ts
new file mode 100644
index 00000000..1f01e298
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/register/poll.ts
@@ -0,0 +1,21 @@
+import type { MachineLifecycleState } from '../types/index'
+import { defineRegister } from 'dsh-tauri/client'
+import { poll } from '../service/machines'
+import { store } from '../store/index'
+
+const MACHINES_POLL_INTERVAL_MS = 1500
+const ACTIVE_STATES: readonly MachineLifecycleState[] = ['connecting', 'reconnecting', 'testing']
+
+function machinesInFlight(): boolean {
+ if (Object.keys(store.machines.busy).length > 0)
+ return true
+ return Object.values(store.machines.statuses).some(status => ACTIVE_STATES.includes(status.state))
+}
+
+export const pollFeature = defineRegister((controller) => {
+ controller.interval(() => {
+ if (controller.isDisposed() || !(machinesInFlight() || store.sync.applying))
+ return
+ void poll()
+ }, MACHINES_POLL_INTERVAL_MS)
+})
diff --git a/packages/dsh-tauri-ssh/src/client/register/section.ts b/packages/dsh-tauri-ssh/src/client/register/section.ts
new file mode 100644
index 00000000..1218152c
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/register/section.ts
@@ -0,0 +1,15 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import { defineRegister } from 'dsh-tauri/client'
+import { SshSection } from '../components/ssh-section'
+import { SETTINGS_SECTION_ID, SETTINGS_SECTION_ORDER, SETTINGS_SECTION_SLOT } from '../constants/index'
+import { locale } from '../locales/index'
+
+export const sectionFeature = defineRegister<ClientContext>((controller, ctx) => {
+ controller.add(ctx.slots.inject(SETTINGS_SECTION_SLOT as never, () => ctx.slots.register({
+ name: SETTINGS_SECTION_SLOT,
+ id: SETTINGS_SECTION_ID,
+ order: SETTINGS_SECTION_ORDER,
+ label: () => locale.text('nav'),
+ locale: locale.NS,
+ } as never, SshSection as never)))
+})
diff --git a/packages/dsh-tauri-ssh/src/client/service/bridge.ts b/packages/dsh-tauri-ssh/src/client/service/bridge.ts
index 5051fc31..4d5cb5bc 100644
--- a/packages/dsh-tauri-ssh/src/client/service/bridge.ts
+++ b/packages/dsh-tauri-ssh/src/client/service/bridge.ts
@@ -1,17 +1,7 @@
-/**
- * The desktop-bridge face (C-BRIDGE, S5 owns the shell commands): probing
- * whether this page sits inside the desktop's iframe invoke bridge, and
- * asking the shell to open (or focus) a machine's remote window. Both rides
- * go through `invoke` (the dsh-tauri/client bridge) — a timeout or rejection
- * on the ping means pure web, where the popup affordance simply never shows.
- * @module dsh-tauri-ssh/client/service/bridge
- */
-
import type { RemoteBridge } from '../types/index'
import { invoke } from 'dsh-tauri/client'
import { REMOTE_BRIDGE_PING_COMMAND, REMOTE_OPEN_WINDOW_COMMAND } from '../constants/index'
-/** The real desktop bridge: Tauri commands over the iframe postMessage relay. */
export const desktopBridge: RemoteBridge = {
probe: () => invoke(REMOTE_BRIDGE_PING_COMMAND),
openWindow: (machineId, url) => invoke(REMOTE_OPEN_WINDOW_COMMAND, { machineId, url }),
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.test.ts b/packages/dsh-tauri-ssh/src/client/service/machines.test.ts
new file mode 100644
index 00000000..5a9f8027
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/machines.test.ts
@@ -0,0 +1,422 @@
+import type { MachineRow } from '../types/index'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import * as api from '../apis/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import * as service from './machines'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const API = api.baseURL
+
+const machineA: MachineRow = {
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ hasPassword: true,
+ hasPassphrase: false,
+ remotePort: 3080,
+}
+const machineB: MachineRow = {
+ ...machineA,
+ id: 'b',
+ name: 'beta',
+ host: '10.0.0.2',
+ port: 2222,
+ user: 'deploy',
+ hasPassword: false,
+ hasPassphrase: true,
+ remotePort: 3000,
+ startCommand: 'dsh web --host 127.0.0.1 --port 3000',
+}
+
+const tick = () => new Promise(resolve => setTimeout(resolve, 0))
+const callsOf = (path: string, http: string) => sent.filter(call => call.url === `${API}${path}` && call.http === http)
+const bodiesOf = (path: string, http: string) => callsOf(path, http).map(call => call.body)
+const paramsOf = (path: string, http = 'GET') => callsOf(path, http).map(call => call.params)
+
+function wireList(items: readonly unknown[], discovered: readonly unknown[] = []): void {
+ answer((call) => {
+ if (call.url === `${API}/machines`)
+ return replies.ok({ items, discovered })
+ return replies.ok(call.url === `${API}/session/role` ? { remote: false } : {})
+ })
+}
+
+beforeEach(() => {
+ resetWire()
+ store.machines.reset()
+ store.sync.reset()
+})
+
+describe('load', () => {
+ it('loads the machines, their secret flags, and their live statuses', async () => {
+ wireList([
+ { ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' },
+ { ...machineB, state: 'disconnected', lastError: 'auth failed' },
+ ])
+ await service.load()
+ expect(store.machines.machines).toEqual([machineA, machineB])
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
+ expect(store.machines.statuses.b).toEqual({ state: 'disconnected', lastError: 'auth failed' })
+ expect(store.machines.status).toBe('ready')
+ expect(store.machines.error).toBeNull()
+ await vi.waitFor(() => expect(store.machines.role).toEqual({ remote: false }))
+ })
+
+ it('carries the retry instant, the auth method, and the dsh marker', async () => {
+ wireList([
+ { ...machineA, state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' },
+ { ...machineB, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true },
+ ])
+ await service.load()
+ expect(store.machines.statuses.a).toMatchObject({ state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' })
+ expect(store.machines.statuses.b).toMatchObject({ state: 'disconnected', dshMissing: true })
+ })
+
+ it('appends the phase trail and clears it when progress disappears', async () => {
+ wireList([{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }])
+ await service.load()
+ expect(store.machines.trails.a).toEqual(['handshake'])
+
+ wireList([{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }])
+ await service.poll()
+ expect(store.machines.trails.a).toEqual(['handshake', 'starting'])
+
+ wireList([{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }])
+ await service.poll()
+ expect(store.machines.trails.a).toEqual(['handshake', 'starting'])
+
+ wireList([{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' }])
+ await service.poll()
+ expect(store.machines.trails.a).toBeUndefined()
+ })
+
+ it('polls without flipping the loading banner', async () => {
+ wireList([machineA])
+ await service.load()
+ let release: ((reply: ReturnType<typeof replies.ok>) => void) | undefined
+ answer((call) => {
+ if (call.url === `${API}/machines`)
+ return new Promise((resolve) => { release = resolve })
+ return replies.ok({})
+ })
+ const pending = service.poll()
+ await tick()
+ expect(store.machines.status).toBe('ready')
+ release?.(replies.ok({ items: [machineA], discovered: [] }))
+ await pending
+ expect(store.machines.status).toBe('ready')
+ })
+
+ it('tolerates a list response without the items key', async () => {
+ answer(() => replies.ok({}))
+ await service.load()
+ expect(store.machines.status).toBe('ready')
+ expect(store.machines.machines).toEqual([])
+ })
+
+ it('loads the discovered aliases alongside the manual machines', async () => {
+ wireList([machineA], [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root' }])
+ await service.load()
+ expect(store.machines.machines.map(row => row.id)).toEqual(['a'])
+ expect(store.machines.discovered.map(row => row.id)).toEqual(['dev'])
+ })
+
+ it('reports a list failure on the status line', async () => {
+ answer(() => replies.fail('loopback only'))
+ await service.load()
+ expect(store.machines.status).toBe('error')
+ expect(store.machines.error).toBe('loopback only')
+ })
+
+ it('reports a poll failure without dropping the list', async () => {
+ wireList([machineA])
+ await service.load()
+ answer(() => replies.fail('nope'))
+ await service.poll()
+ expect(store.machines.status).toBe('ready')
+ expect(store.machines.error).toBe('nope')
+ expect(store.machines.machines.map(row => row.id)).toEqual(['a'])
+ })
+})
+
+describe('persist', () => {
+ it('saves the edited rows, the typed secrets, and removes the vanished machines', async () => {
+ let items: readonly unknown[] = [machineA, machineB]
+ answer(call => call.url === `${API}/machines` ? replies.ok({ items, discovered: [] }) : replies.ok({ remote: false }))
+ await service.load()
+ const renamed = { ...machineA, name: 'alpha-2' }
+ items = [renamed]
+ sent.length = 0
+ const result = await service.persist({ machines: [renamed], secrets: { a: { password: 'sekrit', passphrase: 'PHRASE' } } })
+ expect(result).toEqual({ ok: true })
+ expect(bodiesOf('/machines', 'POST')).toEqual([{
+ machineId: 'a',
+ row: { name: 'alpha-2', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },
+ secrets: { password: 'sekrit', passphrase: 'PHRASE' },
+ }])
+ expect(bodiesOf('/machines', 'DELETE')).toEqual([{ machineId: 'b' }])
+ expect(store.machines.error).toBeNull()
+ expect(store.machines.machines.map(row => row.id)).toEqual(['a'])
+ })
+
+ it('never persists a discovered alias', async () => {
+ wireList([machineA], [{ ...machineA, id: 'dev', name: 'dev', host: 'dev' }])
+ await service.load()
+ sent.length = 0
+ await service.persist({ machines: [machineA], secrets: {} })
+ expect(bodiesOf('/machines', 'POST')).toEqual([{ machineId: 'a', row: { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 } }])
+ expect(bodiesOf('/machines', 'DELETE')).toEqual([])
+ })
+
+ it('reports a save failure without throwing', async () => {
+ wireList([machineA])
+ await service.load()
+ answer(call => call.url === `${API}/machines` && call.http === 'POST' ? replies.fail('nope') : replies.ok({ items: [machineA], discovered: [] }))
+ await expect(service.persist({ machines: [machineA], secrets: {} })).resolves.toEqual({ ok: false, error: 'nope' })
+ expect(store.machines.error).toBe('nope')
+ })
+})
+
+describe('machine actions', () => {
+ beforeEach(async () => {
+ wireList([machineA])
+ await service.load()
+ sent.length = 0
+ })
+
+ it('publishes the probe banner and tracks the busy slot', async () => {
+ answer(() => replies.ok({ ok: true, banner: 'Linux alpha' }))
+ await expect(service.test({ machineId: 'a' })).resolves.toEqual({ ok: true })
+ expect(store.machines.notice).toEqual({ kind: 'text', text: 'Linux alpha' })
+ expect(store.machines.busy).toEqual({})
+ expect(bodiesOf('/machines/test', 'POST')).toEqual([{ machineId: 'a' }])
+ })
+
+ it('falls back to the locale keys when the probe says nothing', async () => {
+ answer(() => replies.ok({ ok: true }))
+ await service.test({ machineId: 'a' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.probe_ok' })
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected' })
+
+ answer(() => replies.ok({ ok: false }))
+ await service.test({ machineId: 'a' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.probe_failed' })
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected', lastError: 'failed' })
+ })
+
+ it('reports a failed probe message', async () => {
+ answer(() => replies.ok({ ok: false, message: 'auth failed' }))
+ await service.test({ machineId: 'a' })
+ expect(store.machines.notice).toEqual({ kind: 'text', text: 'auth failed' })
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected', lastError: 'auth failed' })
+ })
+
+ it('never downgrades a live connection after a probe', async () => {
+ answer(call => call.url === `${API}/machines/connect`
+ ? replies.ok({ tunnelBaseUrl: 'http://127.0.0.1:49152' })
+ : replies.ok({ ok: true }))
+ await service.connect({ machineId: 'a' })
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
+
+ await service.test({ machineId: 'a' })
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
+
+ answer(() => replies.ok({ ok: false, message: 'auth failed' }))
+ await service.test({ machineId: 'a' })
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152', lastError: 'auth failed' })
+ })
+
+ it('connects and disconnects with the tunnel URL in the notice', async () => {
+ answer(call => call.url === `${API}/machines/connect`
+ ? replies.ok({ tunnelBaseUrl: 'http://127.0.0.1:49152' })
+ : replies.ok({}))
+ await service.connect({ machineId: 'a' })
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.connected', params: { url: 'http://127.0.0.1:49152' } })
+
+ await service.disconnect({ machineId: 'a' })
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.disconnected' })
+ expect(bodiesOf('/machines/connect', 'POST')).toEqual([{ machineId: 'a' }])
+ expect(bodiesOf('/machines/disconnect', 'POST')).toEqual([{ machineId: 'a' }])
+ })
+
+ it('exposes the in-flight operation in the busy map', async () => {
+ let release: ((reply: ReturnType<typeof replies.ok>) => void) | undefined
+ answer(call => call.url === `${API}/machines/connect`
+ ? new Promise((resolve) => { release = resolve })
+ : replies.ok({}))
+ const pending = service.connect({ machineId: 'a' })
+ await tick()
+ expect(store.machines.busy.a).toBe('connect')
+ release?.(replies.ok({ tunnelBaseUrl: 'http://127.0.0.1:49152' }))
+ await pending
+ expect(store.machines.busy).toEqual({})
+ })
+
+ it('lands connection-plane failures on the error banner', async () => {
+ answer(() => replies.fail('refused'))
+ await expect(service.connect({ machineId: 'a' })).resolves.toEqual({ ok: false, error: 'refused' })
+ expect(store.machines.error).toBe('refused')
+
+ answer(() => replies.empty())
+ await service.connect({ machineId: 'a' })
+ expect(store.machines.error).toBe('SSH_API_EMPTY')
+
+ answer(() => replies.http(405))
+ await service.connect({ machineId: 'a' })
+ expect(store.machines.error).toBe('SSH_API_HTTP_405')
+ })
+
+ it('records an install result and reloads the list', async () => {
+ answer(call => call.url === `${API}/machines/install`
+ ? replies.ok({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })
+ : replies.ok({ items: [machineA], discovered: [] }))
+ await service.install({ machineId: 'a' })
+ expect(store.machines.installResults.a).toEqual({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })
+ expect(callsOf('/machines', 'GET').length).toBeGreaterThanOrEqual(1)
+ expect(store.machines.busy).toEqual({})
+ })
+
+ it('lands an install failure on the error banner', async () => {
+ answer(call => call.url === `${API}/machines/install` ? replies.fail('pnpm: not found') : replies.ok({ items: [machineA], discovered: [] }))
+ await expect(service.install({ machineId: 'a' })).resolves.toEqual({ ok: false, error: 'pnpm: not found' })
+ expect(store.machines.error).toBe('pnpm: not found')
+ expect(store.machines.busy).toEqual({})
+ })
+})
+
+describe('feature switch', () => {
+ it('reads the switch and skips loading while disabled', async () => {
+ answer(call => call.url === `${API}/settings` && call.http === 'GET' ? replies.ok({ enabled: false }) : replies.ok({}))
+ await service.loadSettings()
+ expect(store.machines.enabled).toBe(false)
+ expect(store.machines.error).toBeNull()
+
+ sent.length = 0
+ await service.load()
+ expect(store.machines.status).toBe('idle')
+ expect(callsOf('/machines', 'GET')).toEqual([])
+ })
+
+ it('enables through settings.set and then loads the machines', async () => {
+ answer((call) => {
+ if (call.url === `${API}/settings`)
+ return replies.ok({ enabled: call.http === 'POST' })
+ if (call.url === `${API}/machines`)
+ return replies.ok({ items: [machineA], discovered: [] })
+ return replies.ok({ remote: false })
+ })
+ await service.loadSettings()
+ await expect(service.enable()).resolves.toEqual({ ok: true })
+ expect(store.machines.enabled).toBe(true)
+ expect(store.machines.enabling).toBe(false)
+ expect(store.machines.machines.map(row => row.id)).toEqual(['a'])
+ })
+
+ it('reads an unavailable settings endpoint as disabled with the transport code', async () => {
+ answer(() => replies.http(405))
+ await service.loadSettings()
+ expect(store.machines.enabled).toBe(false)
+ expect(store.machines.error).toBe('SSH_API_HTTP_405')
+ })
+})
+
+describe('event polling', () => {
+ beforeEach(async () => {
+ wireList([machineA])
+ await service.load()
+ })
+
+ it('folds a terminal banner into the log and drops empty lines', async () => {
+ answer(call => call.url === `${API}/machines/events`
+ ? replies.ok({ items: [
+ { seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', stage: 'probe', line: '', terminal: 'failed', reason: 'port busy' },
+ { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: '' },
+ ] })
+ : replies.ok({ items: [machineA], discovered: [] }))
+ await service.poll()
+ expect(store.machines.logs.a).toEqual(['[failed] port busy'])
+ })
+
+ it('folds the new lines past the per-machine cursor', async () => {
+ answer(call => call.url === `${API}/machines/events`
+ ? replies.ok({ items: [
+ { seq: 1, ts: 't1', machineId: 'a', stage: 'probe', line: 'line 1' },
+ { seq: 2, ts: 't2', machineId: 'a', stage: 'probe', line: 'line 2' },
+ ] })
+ : replies.ok({ items: [machineA], discovered: [] }))
+ await service.poll()
+ expect(store.machines.logs.a).toEqual(['line 1', 'line 2'])
+ expect(paramsOf('/machines/events')).toEqual([{ machineId: 'a' }])
+
+ sent.length = 0
+ answer(call => call.url === `${API}/machines/events`
+ ? replies.ok({ items: [{ seq: 3, ts: 't3', machineId: 'a', stage: 'probe', line: 'line 3' }] })
+ : replies.ok({ items: [machineA], discovered: [] }))
+ await service.poll()
+ expect(store.machines.logs.a).toEqual(['line 1', 'line 2', 'line 3'])
+ expect(paramsOf('/machines/events')).toEqual([{ machineId: 'a', sinceSeq: 2 }])
+ })
+
+ it('keeps an independent cursor per machine', async () => {
+ wireList([{ ...machineA, state: 'connected' }, { ...machineB, state: 'connected' }])
+ await service.load()
+ sent.length = 0
+ answer(call => call.url === `${API}/machines/events`
+ ? replies.ok({ items: call.params.machineId === 'a'
+ ? [{ seq: 10, ts: 't', machineId: 'a', stage: 'probe', line: 'a line' }]
+ : [{ seq: 2, ts: 't', machineId: 'b', stage: 'probe', line: 'b line' }] })
+ : replies.ok({ items: [{ ...machineA, state: 'connected' }, { ...machineB, state: 'connected' }], discovered: [] }))
+ await service.poll()
+ expect(paramsOf('/machines/events')).toEqual([{ machineId: 'a' }, { machineId: 'b' }])
+
+ sent.length = 0
+ await service.poll()
+ expect(paramsOf('/machines/events')).toEqual([{ machineId: 'a', sinceSeq: 10 }, { machineId: 'b', sinceSeq: 2 }])
+ })
+
+ it('turns the channel off for good after a refusal', async () => {
+ answer(call => call.url === `${API}/machines/events`
+ ? replies.fail('unsupported')
+ : replies.ok({ items: [machineA], discovered: [] }))
+ await service.poll()
+ expect(store.machines.error).toBeNull()
+ sent.length = 0
+ await service.poll()
+ await service.poll()
+ expect(paramsOf('/machines/events')).toEqual([])
+ })
+})
+
+describe('notifications', () => {
+ it('notifies the subscribers and stops after unsubscribe', async () => {
+ const fire = vi.fn()
+ const stop = store.machines.$subscribe(fire)
+ wireList([machineA])
+ await service.load()
+ await tick()
+ expect(fire).toHaveBeenCalled()
+
+ stop()
+ const calls = fire.mock.calls.length
+ await service.load()
+ await tick()
+ expect(fire.mock.calls.length).toBe(calls)
+ })
+})
+
+describe('the request layer is the only seam', () => {
+ it('never reaches the wire outside the plugin API', async () => {
+ wireList([machineA])
+ await service.load()
+ await api.getSessionRole()
+ for (const call of sent)
+ expect(call.url.startsWith(API)).toBe(true)
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.ts b/packages/dsh-tauri-ssh/src/client/service/machines.ts
new file mode 100644
index 00000000..542bc1bd
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/machines.ts
@@ -0,0 +1,201 @@
+import type { MachineBusyOp } from '../store/modules/machines.types'
+import type { SecretValues, ServiceResult, SshMachineEvent } from '../types/index'
+import type { PersistMachinesInput } from './machines.types'
+import { uniq } from 'dsh-tauri/client'
+import * as api from '../apis/index'
+import {
+ enabledOf,
+ errorMessageOf,
+ installResultOf,
+ machineEventsOf,
+ machineListOf,
+ savePayloadOf,
+ sessionRoleOf,
+ SSH_API_EMPTY,
+ testResultOf,
+ tunnelUrlOf,
+} from '../apis/parsers'
+import { store } from '../store/index'
+
+const NO_SECRETS: SecretValues = {}
+
+export async function loadSettings(): Promise<void> {
+ try {
+ store.machines.setEnabled(enabledOf(await api.getSettings()) === true, null)
+ }
+ catch (error) {
+ store.machines.setEnabled(false, errorMessageOf(error))
+ }
+}
+
+export async function loadRole(): Promise<void> {
+ try {
+ store.machines.setRole(sessionRoleOf(await api.getSessionRole()))
+ }
+ catch {}
+}
+
+export async function load(): Promise<void> {
+ if (store.machines.enabled === false)
+ return
+ store.machines.beginLoad()
+ try {
+ if (store.machines.role === null)
+ await loadRole()
+ store.machines.commitList(machineListOf(await api.getMachines()))
+ }
+ catch (error) {
+ store.machines.failList(errorMessageOf(error))
+ }
+}
+
+export async function enable(): Promise<ServiceResult> {
+ store.machines.beginEnable()
+ try {
+ store.machines.setEnabled(enabledOf(await api.postSettings({ enabled: true })) !== false, null)
+ if (store.machines.enabled === true)
+ await load()
+ return { ok: true }
+ }
+ catch (error) {
+ const message = errorMessageOf(error)
+ store.machines.fail(message)
+ return { ok: false, error: message }
+ }
+ finally {
+ store.machines.endEnable()
+ }
+}
+
+export async function poll(): Promise<void> {
+ try {
+ store.machines.commitList(machineListOf(await api.getMachines()))
+ await pollEvents()
+ }
+ catch (error) {
+ store.machines.fail(errorMessageOf(error))
+ }
+}
+
+export async function persist(input: PersistMachinesInput): Promise<ServiceResult> {
+ try {
+ for (const machine of input.machines)
+ await api.postMachines(savePayloadOf(machine, input.secrets[machine.id] ?? NO_SECRETS))
+ const kept = input.machines.map(machine => machine.id)
+ for (const id of store.machines.machines.map(row => row.id)) {
+ if (!kept.includes(id))
+ await api.deleteMachines({ machineId: id })
+ }
+ store.machines.clearError()
+ await load()
+ return { ok: true }
+ }
+ catch (error) {
+ const message = errorMessageOf(error)
+ store.machines.fail(message)
+ return { ok: false, error: message }
+ }
+}
+
+export async function remove(input: { machineId: string }): Promise<ServiceResult> {
+ try {
+ await api.deleteMachines({ machineId: input.machineId })
+ store.machines.clearError()
+ await load()
+ return { ok: true }
+ }
+ catch (error) {
+ const message = errorMessageOf(error)
+ store.machines.fail(message)
+ return { ok: false, error: message }
+ }
+}
+
+export async function test(input: { machineId: string }): Promise<ServiceResult> {
+ return withBusy(input.machineId, 'test', async () => {
+ const value = testResultOf(await api.postMachinesTest({ machineId: input.machineId }))
+ if (value.ok)
+ store.machines.commitProbeOk(input.machineId, value.banner)
+ else
+ store.machines.commitProbeFailed(input.machineId, value.message)
+ })
+}
+
+export async function connect(input: { machineId: string }): Promise<ServiceResult> {
+ return withBusy(input.machineId, 'connect', async () => {
+ const tunnelBaseUrl = tunnelUrlOf(await api.postMachinesConnect({ machineId: input.machineId }))
+ if (tunnelBaseUrl === '')
+ throw new Error(SSH_API_EMPTY)
+ store.machines.commitConnected(input.machineId, tunnelBaseUrl)
+ })
+}
+
+export async function disconnect(input: { machineId: string }): Promise<ServiceResult> {
+ return withBusy(input.machineId, 'disconnect', async () => {
+ await api.postMachinesDisconnect({ machineId: input.machineId })
+ store.machines.commitDisconnected(input.machineId)
+ })
+}
+
+export async function install(input: { machineId: string }): Promise<ServiceResult> {
+ return withBusy(input.machineId, 'install', async () => {
+ store.machines.commitInstallResult(input.machineId, installResultOf(await api.postMachinesInstall({ machineId: input.machineId })))
+ await load()
+ })
+}
+
+async function withBusy(machineId: string, op: MachineBusyOp, action: () => Promise<void>): Promise<ServiceResult> {
+ store.machines.beginOp(machineId, op)
+ try {
+ await action()
+ return { ok: true }
+ }
+ catch (error) {
+ const message = errorMessageOf(error)
+ store.machines.fail(message)
+ return { ok: false, error: message }
+ }
+ finally {
+ store.machines.endOp(machineId)
+ }
+}
+
+async function pollEvents(): Promise<void> {
+ if (!store.machines.eventsSupported)
+ return
+ const known = uniq([...store.machines.machines, ...store.machines.discovered].map(row => row.id))
+ const lines: Record<string, string[]> = {}
+ const cursors: Record<string, number> = {}
+ try {
+ for (const machineId of known) {
+ const cursor = store.machines.eventCursors[machineId]
+ const events = machineEventsOf(await api.getMachinesEvents(cursor === undefined ? { machineId } : { machineId, sinceSeq: cursor }))
+ if (events.length === 0)
+ continue
+ cursors[machineId] = Math.max(...events.map(event => event.seq))
+ for (const event of events) {
+ const line = logLineOf(event)
+ if (line === '')
+ continue
+ lines[event.machineId] = [...(lines[event.machineId] ?? []), line]
+ }
+ }
+ }
+ catch {
+ store.machines.disableEvents()
+ return
+ }
+ store.machines.advanceEvents(cursors)
+ if (Object.keys(lines).length > 0)
+ store.machines.appendLogs(lines)
+}
+
+function logLineOf(event: SshMachineEvent): string {
+ if (event.line !== '')
+ return event.line
+ if (event.terminal === 'failed')
+ return event.reason === undefined || event.reason === '' ? '[failed]' : `[failed] ${event.reason}`
+ if (event.terminal === 'success')
+ return '[success]'
+ return ''
+}
diff --git a/packages/dsh-tauri-ssh/src/client/service/machines.types.ts b/packages/dsh-tauri-ssh/src/client/service/machines.types.ts
new file mode 100644
index 00000000..75412471
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/machines.types.ts
@@ -0,0 +1,6 @@
+import type { MachineRow, SecretValues } from '../types/index'
+
+export interface PersistMachinesInput {
+ machines: MachineRow[]
+ secrets: Record<string, SecretValues>
+}
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.test.ts b/packages/dsh-tauri-ssh/src/client/service/sync.test.ts
new file mode 100644
index 00000000..60992e4d
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/sync.test.ts
@@ -0,0 +1,102 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { baseURL } from '../apis/index'
+import { store } from '../store/index'
+import { answer, replies, resetWire, sent } from '../test-utils/client-mock'
+import * as service from './sync'
+
+vi.mock('dsh-tauri/client', async () => (await import('../test-utils/client-mock')).clientMock)
+
+const tick = () => new Promise(resolve => setTimeout(resolve, 0))
+
+const preview = {
+ plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }],
+ skills: [{ name: 's', root: 'dsh' }],
+}
+
+beforeEach(() => {
+ resetWire()
+ store.sync.reset()
+})
+
+describe('loadSyncPreview', () => {
+ it('publishes the previewed items', async () => {
+ answer(() => replies.ok(preview))
+ await service.loadSyncPreview()
+ expect(store.sync.status).toBe('ready')
+ expect(store.sync.preview).toEqual(preview)
+ expect(store.sync.error).toBeNull()
+ })
+
+ it('reports a preview failure on the panel status line', async () => {
+ answer(() => replies.fail('nope'))
+ await service.loadSyncPreview()
+ expect(store.sync.status).toBe('error')
+ expect(store.sync.error).toBe('nope')
+ })
+
+ it('reads a malformed preview as a failure', async () => {
+ answer(() => replies.ok({ plugins: 'nope' }))
+ await service.loadSyncPreview()
+ expect(store.sync.error).toBe('malformed sync.preview payload')
+ })
+})
+
+describe('applySync', () => {
+ it('sends the selected items and lands the per-item results', async () => {
+ answer(() => replies.ok({ items: [
+ { kind: 'plugin', name: 'p', ok: true },
+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },
+ ] }))
+ const result = await service.applySync({ machineId: 'a', plugins: [preview.plugins[0]!], skills: [preview.skills[0]!] })
+ expect(result).toEqual({ ok: true })
+ expect(sent).toEqual([{ url: `${baseURL}/sync/apply`, http: 'POST', body: {
+ machineId: 'a',
+ plugins: [{ name: 'p', spec: 'github:a/b' }],
+ skills: [{ name: 's', root: 'dsh' }],
+ }, params: {} }])
+ expect(store.sync.results).toEqual([
+ { kind: 'plugin', name: 'p', ok: true },
+ { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },
+ ])
+ expect(store.sync.applying).toBe(false)
+ expect(store.sync.error).toBeNull()
+ })
+
+ it('reports an apply failure without dropping the panel', async () => {
+ answer(() => replies.fail('ssh down'))
+ await expect(service.applySync({ machineId: 'a', plugins: [], skills: [] })).resolves.toEqual({ ok: false, error: 'ssh down' })
+ expect(store.sync.applying).toBe(false)
+ expect(store.sync.error).toBe('ssh down')
+ })
+
+ it('keeps the previous results while a retry is in flight', async () => {
+ answer(() => replies.ok({ items: [
+ { kind: 'plugin', name: 'p', ok: false, error: 'boom' },
+ { kind: 'skill', name: 's', root: 'dsh', ok: true },
+ ] }))
+ await service.applySync({ machineId: 'a', plugins: [preview.plugins[0]!], skills: [preview.skills[0]!] })
+
+ let release: ((reply: ReturnType<typeof replies.ok>) => void) | undefined
+ answer(() => new Promise((resolve) => {
+ release = resolve
+ }))
+ const pending = service.applySync({ machineId: 'a', plugins: [preview.plugins[0]!], skills: [] })
+ await tick()
+ expect(store.sync.applying).toBe(true)
+ expect(store.sync.results).toHaveLength(2)
+
+ release?.(replies.ok({ items: [{ kind: 'plugin', name: 'p', ok: true }] }))
+ await pending
+ expect(store.sync.results).toEqual([
+ { kind: 'plugin', name: 'p', ok: true },
+ { kind: 'skill', name: 's', root: 'dsh', ok: true },
+ ])
+ })
+
+ it('reads a malformed apply payload as a failure', async () => {
+ answer(() => replies.ok({}))
+ await expect(service.applySync({ machineId: 'a', plugins: [], skills: [] })).resolves.toEqual({ ok: false, error: 'malformed sync.apply payload' })
+ expect(store.sync.results).toBeNull()
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.ts b/packages/dsh-tauri-ssh/src/client/service/sync.ts
new file mode 100644
index 00000000..9f15ae2a
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/sync.ts
@@ -0,0 +1,41 @@
+import type { ServiceResult } from '../types/index'
+import type { SyncApplyInput } from './sync.types'
+import * as api from '../apis/index'
+import { errorMessageOf, syncApplyResultOf, syncPreviewOf } from '../apis/parsers'
+import { store } from '../store/index'
+
+export async function loadSyncPreview(): Promise<void> {
+ store.sync.beginLoad()
+ try {
+ const preview = syncPreviewOf(await api.getSyncPreview())
+ if (preview === null)
+ throw new Error('malformed sync.preview payload')
+ store.sync.commitPreview(preview)
+ }
+ catch (error) {
+ store.sync.failLoad(errorMessageOf(error))
+ }
+}
+
+export async function applySync(input: SyncApplyInput): Promise<ServiceResult> {
+ store.sync.beginApply()
+ try {
+ const result = syncApplyResultOf(await api.postSyncApply({
+ machineId: input.machineId,
+ plugins: input.plugins.map(item => ({ name: item.name, spec: item.spec })),
+ skills: input.skills.map(item => ({ name: item.name, root: item.root })),
+ }))
+ if (result === null)
+ throw new Error('malformed sync.apply payload')
+ store.sync.mergeResults(result.items)
+ return { ok: true }
+ }
+ catch (error) {
+ const message = errorMessageOf(error)
+ store.sync.fail(message)
+ return { ok: false, error: message }
+ }
+ finally {
+ store.sync.endApply()
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/client/service/sync.types.ts b/packages/dsh-tauri-ssh/src/client/service/sync.types.ts
new file mode 100644
index 00000000..0ea8eb1c
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/service/sync.types.ts
@@ -0,0 +1,7 @@
+import type { SyncPluginItem, SyncSkillItem } from '../types/index'
+
+export interface SyncApplyInput {
+ machineId: string
+ plugins: SyncPluginItem[]
+ skills: SyncSkillItem[]
+}
diff --git a/packages/dsh-tauri-ssh/src/client/store/index.test.ts b/packages/dsh-tauri-ssh/src/client/store/index.test.ts
deleted file mode 100644
index 5bbbf377..00000000
--- a/packages/dsh-tauri-ssh/src/client/store/index.test.ts
+++ /dev/null
@@ -1,708 +0,0 @@
-import type { FetchFn, MachineRow, SshApiResponse } from './index'
-import { describe, expect, it, vi } from 'vitest'
-import { machineEventsOf, machineRowOf, MachinesStore, mergeSyncResults, savePayloadOf, toggleSelection } from './index'
-
-type FetchMock = ReturnType<typeof vi.fn<FetchFn>>
-
-function fakeFetch(envelope: SshApiResponse): FetchMock {
- return vi.fn<FetchFn>(async () => ({ json: async () => envelope }) as unknown as Response)
-}
-
-function boot(envelope: SshApiResponse = { ok: true, value: { items: [] } }) {
- const fetchFn = fakeFetch(envelope)
- const store = new MachinesStore(fetchFn)
- return { store, fetchFn }
-}
-
-const machineA: MachineRow = {
- id: 'a',
- name: 'alpha',
- host: '10.0.0.1',
- port: 22,
- user: 'root',
- hasPassword: true,
- hasPassphrase: false,
- remotePort: 3080,
-}
-const machineB: MachineRow = {
- ...machineA,
- id: 'b',
- name: 'beta',
- host: '10.0.0.2',
- port: 2222,
- user: 'deploy',
- hasPassword: false,
- hasPassphrase: true,
- remotePort: 3000,
- startCommand: 'dsh web --host 127.0.0.1 --port 3000',
-}
-
-describe('machineRowOf', () => {
- it('parses a well-formed redacted row', () => {
- expect(machineRowOf(machineA)).toEqual(machineA)
- expect(machineRowOf(machineB)).toEqual(machineB)
- })
-
- it('rejects malformed rows', () => {
- expect(machineRowOf(undefined)).toBeUndefined()
- expect(machineRowOf('x')).toBeUndefined()
- expect(machineRowOf({ ...machineA, id: '' })).toBeUndefined()
- expect(machineRowOf({ ...machineA, id: 5 })).toBeUndefined()
- expect(machineRowOf({ ...machineA, name: 5 })).toBeUndefined()
- expect(machineRowOf({ ...machineA, host: '' })).toBeUndefined()
- expect(machineRowOf({ ...machineA, user: 5 })).toBeUndefined()
- })
-
- it('falls back to defaults for absent numeric fields and optional startCommand', () => {
- const row = machineRowOf({ ...machineA, port: undefined, remotePort: undefined, startCommand: '', hasPassword: undefined })
- expect(row).toMatchObject({ port: 22, remotePort: 3080, hasPassword: false })
- expect(row).not.toHaveProperty('startCommand')
- })
-
- it('accepts an empty user (resolved from ~/.ssh config or the OS user)', () => {
- const row = machineRowOf({ ...machineA, user: '' })
- expect(row).toMatchObject({ user: '' })
- })
-})
-
-describe('savePayloadOf', () => {
- it('builds the config row and carries only typed secrets', () => {
- expect(savePayloadOf(machineB, { passphrase: 'PHRASE', password: '' })).toEqual({
- machineId: 'b',
- row: {
- name: 'beta',
- host: '10.0.0.2',
- port: 2222,
- user: 'deploy',
- remotePort: 3000,
- startCommand: 'dsh web --host 127.0.0.1 --port 3000',
- },
- secrets: { passphrase: 'PHRASE' },
- })
- expect(savePayloadOf(machineA, {})).toEqual({
- machineId: 'a',
- row: { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },
- })
- expect(savePayloadOf({ ...machineA, startCommand: '' }, {})).not.toHaveProperty('row.startCommand')
- })
-})
-
-describe('machinesStore', () => {
- it('loads machines, secret flags, and live statuses from machine.list', async () => {
- const { store } = boot({
- ok: true,
- value: {
- items: [
- { ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' },
- { ...machineB, state: 'disconnected', lastError: 'auth failed' },
- { ...machineA, id: 'c', name: 'gamma', state: 'disconnected' },
- ],
- },
- })
- await store.load()
- const state = store.getSnapshot()
- expect(state.status).toBe('ready')
- expect(state.machines.map(row => row.id)).toEqual(['a', 'b', 'c'])
- expect(state.machines[0]).toMatchObject({ hasPassword: true, hasPassphrase: false })
- expect(state.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
- expect(state.statuses.b).toEqual({ state: 'disconnected', lastError: 'auth failed' })
- expect(state.statuses.c).toEqual({ state: 'disconnected' })
- })
-
- it('carries the live progress of in-flight operations', async () => {
- const { store } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }] },
- })
- await store.load()
- expect(store.getSnapshot().statuses.a)
- .toEqual({ state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } })
- })
-
- it('accumulates the observed phase trail and clears it when the operation settles', async () => {
- const { store, fetchFn } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] },
- })
- await store.load()
- expect(store.getSnapshot().trails.a).toEqual(['handshake'])
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } }),
- } as unknown as Response)
- await store.poll()
- expect(store.getSnapshot().trails.a).toEqual(['handshake', 'starting'])
- // 同阶段重复不重复入轨
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'starting' } }] } }),
- } as unknown as Response)
- await store.poll()
- expect(store.getSnapshot().trails.a).toEqual(['handshake', 'starting'])
- // 操作落定(progress 消失)清轨
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } }),
- } as unknown as Response)
- await store.poll()
- expect(store.getSnapshot().trails.a).toBeUndefined()
- })
-
- it('polls without flipping the loading banner', async () => {
- const { store, fetchFn } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'connecting', progress: { phase: 'handshake' } }] },
- })
- await store.load()
- fetchFn.mockClear()
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' }] } }),
- } as unknown as Response)
- await store.poll()
- const state = store.getSnapshot()
- expect(state.status).toBe('ready')
- expect(state.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' })
- })
-
- it('tolerates a list response without the items key', async () => {
- const { store } = boot({ ok: true, value: {} })
- await store.load()
- expect(store.getSnapshot()).toMatchObject({ status: 'ready', machines: [], discovered: [], statuses: {} })
- })
-
- it('loads the discovered config aliases alongside the manual machines', async () => {
- const { store } = boot({
- ok: true,
- value: {
- items: [{ ...machineA, state: 'disconnected' }],
- discovered: [
- { ...machineA, id: 'dev', name: 'dev', host: 'dev', user: 'root', hasPassword: false, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' },
- { ...machineA, id: 'ci', name: 'ci', host: 'ci', user: '', hasPassword: false, state: 'disconnected' },
- ],
- },
- })
- await store.load()
- const state = store.getSnapshot()
- expect(state.machines.map(row => row.id)).toEqual(['a'])
- expect(state.discovered.map(row => row.id)).toEqual(['dev', 'ci'])
- expect(state.discovered[0]).toMatchObject({ host: 'dev', user: 'root', hasPassword: false, hasPassphrase: false })
- expect(state.statuses.dev).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:9' })
- expect(state.statuses.ci).toEqual({ state: 'disconnected' })
- })
-
- it('reports a list failure as a page error', async () => {
- const { store } = boot({ ok: false, error: { code: 'forbidden', message: 'loopback only' } })
- await store.load()
- expect(store.getSnapshot()).toMatchObject({ status: 'error', error: 'loopback only' })
- })
-
- it('reports poll failures without flipping the ready status', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'forbidden', message: 'nope' } }) } as unknown as Response)
- await store.poll()
- expect(store.getSnapshot()).toMatchObject({ status: 'ready', error: 'nope' })
- })
-
- it('persists saves and removals through /api-ssh', async () => {
- const { store, fetchFn } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'disconnected' }, { ...machineB, state: 'disconnected' }] },
- })
- await store.load()
- fetchFn.mockClear()
- await store.persist(
- [{ ...machineA, name: 'alpha-2' }],
- { a: { password: 'sekrit', passphrase: 'PHRASE' } },
- )
- const calls = fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })
- .filter(call => call.method !== 'machine.list' && call.method !== 'session.role')
- expect(calls).toHaveLength(2)
- expect(calls[0]).toMatchObject({
- method: 'machine.save',
- payload: {
- machineId: 'a',
- row: { name: 'alpha-2', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 },
- secrets: { password: 'sekrit', passphrase: 'PHRASE' },
- },
- })
- expect(calls[1]).toEqual({ method: 'machine.remove', payload: { machineId: 'b' } })
- expect(store.getSnapshot().error).toBeNull()
- })
-
- it('persists only manual machines, never the discovered aliases', async () => {
- const { store, fetchFn } = boot({
- ok: true,
- value: {
- items: [{ ...machineA, state: 'disconnected' }],
- discovered: [{ ...machineA, id: 'dev', name: 'dev', host: 'dev', user: '', hasPassword: false, state: 'disconnected' }],
- },
- })
- await store.load()
- fetchFn.mockClear()
- await store.persist([machineA], {})
- const calls = fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })
- .filter(call => call.method !== 'machine.list' && call.method !== 'session.role')
- expect(calls).toHaveLength(1)
- expect(calls[0]).toMatchObject({ method: 'machine.save', payload: { machineId: 'a' } })
- })
-
- it('reports persist failures without throwing', async () => {
- const { store, fetchFn } = boot({ ok: true, value: { items: [{ ...machineA, state: 'disconnected' }] } })
- await store.load()
- fetchFn.mockClear()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'settings-rejected', message: 'nope' } }) } as unknown as Response)
- await store.persist([machineA], {})
- expect(store.getSnapshot().error).toBe('nope')
- })
-
- it('tests a machine and publishes the banner', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)
- await store.test('a')
- const state = store.getSnapshot()
- expect(state.notice).toEqual({ kind: 'text', text: 'Linux alpha' })
- expect(state.busy).toEqual({})
- const testCall = fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload?: Record<string, unknown> })
- .find(call => call.method === 'machine.test')
- expect(testCall).toEqual({ method: 'machine.test', payload: { machineId: 'a' } })
- })
-
- it('falls back to defaults when a probe omits banner or message', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true } }) } as unknown as Response)
- await store.test('a')
- expect(store.getSnapshot().notice).toEqual({ kind: 'key', key: 'notice.probe_ok' })
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: false } }) } as unknown as Response)
- await store.test('a')
- const state = store.getSnapshot()
- expect(state.notice).toEqual({ kind: 'key', key: 'notice.probe_failed' })
- expect(state.statuses.a).toEqual({ state: 'disconnected', lastError: 'failed' })
- })
-
- it('publishes failed probes with the failure message', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: false, message: 'auth failed' } }) } as unknown as Response)
- await store.test('a')
- const state = store.getSnapshot()
- expect(state.notice).toEqual({ kind: 'text', text: 'auth failed' })
- expect(state.statuses.a).toEqual({ state: 'disconnected', lastError: 'auth failed' })
- })
-
- it('never downgrades a live connection after a probe (regression)', async () => {
- // 探测是旁路健康检查,不触碰连接面:已连接的机器被点「测试」后必须
- // 保持 connected/tunnelBaseUrl,否则 UI 会把一条活连接显示成断开。
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)
- await store.connect('a')
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: true, banner: 'Linux alpha' } }) } as unknown as Response)
- await store.test('a')
- expect(store.getSnapshot().statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { ok: false, message: 'auth failed' } }) } as unknown as Response)
- await store.test('a')
- const state = store.getSnapshot()
- expect(state.statuses.a?.state).toBe('connected')
- expect(state.statuses.a?.lastError).toBe('auth failed')
- })
-
- it('connects, disconnects, and tracks busy state', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:49152' } }) } as unknown as Response)
- await store.connect('a')
- expect(store.getSnapshot().statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:49152' })
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: {} }) } as unknown as Response)
- await store.disconnect('a')
- expect(store.getSnapshot().statuses.a).toEqual({ state: 'disconnected' })
- expect(store.getSnapshot().notice).toEqual({ kind: 'key', key: 'notice.disconnected' })
- })
-
- it('marks a machine busy while a connection-plane op is in flight', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- let release: (() => void) | undefined
- const gate = new Promise<void>((resolve) => {
- release = resolve
- })
- fetchFn.mockReturnValueOnce(gate.then(() => ({ json: async () => ({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:1' } }) }) as unknown as Response))
- const pending = store.connect('a')
- expect(store.getSnapshot().busy.a).toBe('connect')
- release!()
- await pending
- expect(store.getSnapshot().busy).toEqual({})
- })
-
- it('reports connection-plane failures as a banner error', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'connect-failed', message: 'refused' } }) } as unknown as Response)
- await store.connect('a')
- expect(store.getSnapshot().error).toBe('refused')
- // 解析不了的信封(空响应体 / 非 JSON)归到稳定错误码,不外泄原生解析异常
- fetchFn.mockResolvedValueOnce({
- json: async () => {
- throw new Error('bad json')
- },
- } as unknown as Response)
- await store.test('a')
- expect(store.getSnapshot().error).toBe('SSH_API_EMPTY')
- fetchFn.mockResolvedValueOnce({ ok: false, status: 405, json: async () => ({}) } as unknown as Response)
- await store.test('a')
- expect(store.getSnapshot().error).toBe('SSH_API_HTTP_405')
- fetchFn.mockResolvedValueOnce({
-
- json: async () => {
- // eslint-disable-next-line no-throw-literal -- deliberately non-Error: covers messageOf(String(error))
- throw 'boom'
- },
- } as unknown as Response)
- await store.test('a')
- expect(store.getSnapshot().error).toBe('SSH_API_EMPTY')
- })
-
- it('reads the feature switch and enables the SSH service', async () => {
- const { store, fetchFn } = boot({ ok: true, value: { enabled: false } })
- await store.loadSettings()
- expect(store.getSnapshot().enabled).toBe(false)
-
- // 未启用:机器列表请求不发(分区只渲染开启 Hero)
- await store.load()
- expect(store.getSnapshot().status).toBe('idle')
-
- fetchFn.mockImplementation(async (_url: string, init: RequestInit) => {
- const request = JSON.parse(String(init.body)) as { method: string }
- const envelope = request.method === 'settings.set'
- ? { ok: true, value: { enabled: true } }
- : request.method === 'session.role'
- ? { ok: true, value: { remote: false } }
- : { ok: true, value: { enabled: true, items: [{ ...machineA, state: 'disconnected' }], discovered: [] } }
- return { json: async () => envelope } as unknown as Response
- })
- await store.enable()
- const state = store.getSnapshot()
- expect(state.enabled).toBe(true)
- expect(state.enabling).toBe(false)
- expect(state.machines.map(row => row.id)).toEqual(['a'])
- })
-
- it('treats an unavailable settings endpoint as switched off plus a transport code', async () => {
- const { store, fetchFn } = boot()
- fetchFn.mockResolvedValueOnce({ ok: false, status: 405, json: async () => ({}) } as unknown as Response)
- await store.loadSettings()
- expect(store.getSnapshot().enabled).toBe(false)
- expect(store.getSnapshot().error).toBe('SSH_API_HTTP_405')
- })
-
- it('carries the dshMissing marker on list rows', async () => {
- const { store } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'disconnected', lastError: 'dsh is not installed', dshMissing: true }] },
- })
- await store.load()
- const status = store.getSnapshot().statuses.a
- expect(status?.dshMissing).toBe(true)
- expect(status?.lastError).toBe('dsh is not installed')
- })
-
- it('installs dsh, records the outcome, and refreshes', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({
- json: async () => ({ ok: true, value: { dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true } }),
- } as unknown as Response)
- await store.install('a')
- const state = store.getSnapshot()
- expect(state.installResults.a).toEqual({ dshPath: '/home/root/.local/bin/dsh', credentialsCopied: true })
- // The follow-up load refreshed the list (auto-connect status).
- expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(2)
- expect(state.busy).toEqual({})
- })
-
- it('reports an install failure as a banner error', async () => {
- const { store, fetchFn } = boot()
- await store.load()
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: false, error: { code: 'machine-install-failed', message: 'pnpm: not found' } }) } as unknown as Response)
- await store.install('a')
- expect(store.getSnapshot().error).toBe('pnpm: not found')
- })
-
- it('exposes a uSES-compatible subscribe/getSnapshot seam', async () => {
- const { store } = boot()
- const listener = vi.fn()
- const unsubscribe = store.subscribe(listener)
- await store.load()
- expect(listener).toHaveBeenCalled()
- unsubscribe()
- const before = listener.mock.calls.length
- await store.load()
- expect(listener.mock.calls.length).toBe(before)
- expect(store.getSnapshot()).toBe(store.store.getSnapshot())
- })
-})
-
-describe('connection-state vocabulary', () => {
- it('reads the C-STATE states, the retry instant, and the auth method', async () => {
- const { store } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'reconnecting', nextRetryAt: 1_700_000_008_000, authMethod: 'key' }] },
- })
- await store.load()
- expect(store.getSnapshot().statuses.a).toMatchObject({
- state: 'reconnecting',
- nextRetryAt: 1_700_000_008_000,
- authMethod: 'key',
- })
- })
-
- it('reads unknown wire states as disconnected', async () => {
- const { store } = boot({
- ok: true,
- value: { items: [{ ...machineA, state: 'warping' }] },
- })
- await store.load()
- expect(store.getSnapshot().statuses.a?.state).toBe('disconnected')
- })
-})
-
-describe('machineEventsOf', () => {
- it('parses well-formed events and drops malformed ones', () => {
- expect(machineEventsOf({ events: [
- { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
- { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
- { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
- ] })).toEqual([
- { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'probing' },
- { seq: 3, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'install', line: 'pnpm install', terminal: 'success' },
- { seq: 4, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'auth', line: 'gave up', terminal: 'failed', reason: 'auth failed' },
- ])
- expect(machineEventsOf(undefined)).toEqual([])
- expect(machineEventsOf({ events: 'nope' })).toEqual([])
- expect(machineEventsOf({ events: [{ machineId: 'a', line: 'x' }, 'junk'] })).toEqual([])
- // A numeric ts or boolean terminal (the draft shapes) is malformed now.
- expect(machineEventsOf({ events: [{ seq: 1, ts: 1_700_000_000, machineId: 'a', line: 'x' }] })).toEqual([])
- expect(machineEventsOf({ events: [{ seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', line: 'x', terminal: true }] })[0]).not.toHaveProperty('terminal')
- })
-})
-
-describe('event polling', () => {
- it('synthesizes a marker line for terminal events with an empty line', async () => {
- const fetchFn = eventsFetch({
- a: [[
- { seq: 1, ts: '2025-09-01T00:00:00.000Z', machineId: 'a', stage: 'launch', line: '' },
- { seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'launch', line: '', terminal: 'failed', reason: 'port busy' },
- ]],
- })
- const store = new MachinesStore(fetchFn)
- await store.load()
- await store.poll()
- // 无 terminal 的空行丢弃;带 terminal 的收尾事件落成可见标记行
- expect(store.getSnapshot().logs.a).toEqual(['[failed] port busy'])
- })
- /**
- * A fetch mock that answers machine.list (one machine per id) and
- * per-machine machine.events payloads, keyed by the polled machineId.
- */
- function eventsFetch(pagesByMachine: Record<string, unknown[][]>, listItems: MachineRow[] = [machineA]): FetchMock {
- const batchByMachine = new Map<string, number>()
- return vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string, payload?: { machineId?: string } }
- if (body.method === 'machine.events') {
- const machineId = body.payload?.machineId ?? ''
- const pages = pagesByMachine[machineId] ?? []
- const batch = batchByMachine.get(machineId) ?? 0
- batchByMachine.set(machineId, batch + 1)
- const events = pages[Math.min(batch, pages.length - 1)] ?? []
- return { json: async () => ({ ok: true, value: { events } }) } as unknown as Response
- }
- return { json: async () => ({ ok: true, value: { items: listItems.map(row => ({ ...row, state: 'connecting' })) } }) } as unknown as Response
- })
- }
-
- /** The machine.events calls a fetch mock saw, as parsed payloads. */
- function eventCallsOf(fetchFn: FetchMock): Array<{ machineId?: string, sinceSeq?: number }> {
- return fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload?: { machineId?: string, sinceSeq?: number } })
- .filter(call => call.method === 'machine.events')
- .map(call => call.payload ?? {})
- }
-
- it('folds event lines into the per-machine log tail past the per-machine cursor', async () => {
- const fetchFn = eventsFetch({
- a: [
- [
- { seq: 1, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'line 1' },
- { seq: 2, ts: '2025-09-01T00:00:02.000Z', machineId: 'a', stage: 'probe', line: 'line 2' },
- ],
- [
- { seq: 3, ts: '2025-09-01T00:00:03.000Z', machineId: 'a', stage: 'ready', line: 'line 3', terminal: 'success' },
- ],
- ],
- })
- const store = new MachinesStore(fetchFn)
- await store.poll()
- expect(store.getSnapshot().logs.a).toEqual(['line 1', 'line 2'])
- await store.poll()
- expect(store.getSnapshot().logs.a).toEqual(['line 1', 'line 2', 'line 3'])
- // The cursor rode along per machine: the second poll of machine a asked
- // for events after its own seq 2 (the first poll omitted sinceSeq).
- const calls = eventCallsOf(fetchFn)
- expect(calls[0]).toEqual({ machineId: 'a' })
- expect(calls[1]).toEqual({ machineId: 'a', sinceSeq: 2 })
- })
-
- it('advances each machine cursor in its own seq space', async () => {
- const fetchFn = eventsFetch({
- a: [[{ seq: 10, ts: '2025-09-01T00:00:01.000Z', machineId: 'a', stage: 'probe', line: 'a line' }]],
- b: [[{ seq: 2, ts: '2025-09-01T00:00:01.000Z', machineId: 'b', stage: 'auth', line: 'b line' }]],
- }, [machineA, machineB])
- const store = new MachinesStore(fetchFn)
- await store.poll()
- expect(store.getSnapshot().logs.a).toEqual(['a line'])
- expect(store.getSnapshot().logs.b).toEqual(['b line'])
- // Both machines polled from the start on the first round; machine a's
- // high seq must not starve machine b's lower seq space.
- const firstRound = eventCallsOf(fetchFn)
- expect(firstRound).toContainEqual({ machineId: 'a' })
- expect(firstRound).toContainEqual({ machineId: 'b' })
- await store.poll()
- const secondRound = eventCallsOf(fetchFn).slice(firstRound.length)
- expect(secondRound).toContainEqual({ machineId: 'a', sinceSeq: 10 })
- expect(secondRound).toContainEqual({ machineId: 'b', sinceSeq: 2 })
- })
-
- it('turns the channel off after the host refuses it once', async () => {
- const fetchFn = vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string }
- if (body.method === 'machine.events') {
- return { json: async () => ({ ok: false, error: { code: 'unknown-method', message: 'unknown method "machine.events"' } }) } as unknown as Response
- }
- return { json: async () => ({ ok: true, value: { items: [{ ...machineA, state: 'connecting' }] } }) } as unknown as Response
- })
- const store = new MachinesStore(fetchFn)
- await store.poll()
- await store.poll()
- await store.poll()
- const eventsCalls = fetchFn.mock.calls
- .filter(call => (JSON.parse(String(call[1]?.body)) as { method: string }).method === 'machine.events')
- expect(eventsCalls).toHaveLength(1)
- // The refusal never fails the page.
- expect(store.getSnapshot().error).toBeNull()
- })
-})
-
-describe('toggleSelection', () => {
- it('toggles membership independently per key', () => {
- let selected = toggleSelection(new Set(), 'a')
- selected = toggleSelection(selected, 'b')
- expect([...selected].sort()).toEqual(['a', 'b'])
- selected = toggleSelection(selected, 'a')
- expect([...selected].sort()).toEqual(['b'])
- })
-})
-
-describe('sync state', () => {
- /** A fetch mock answering per method. */
- function syncFetch(routes: Record<string, unknown>): FetchMock {
- return vi.fn<FetchFn>(async (_url, init) => {
- const body = JSON.parse(String(init.body)) as { method: string }
- return { json: async () => ({ ok: true, value: routes[body.method] ?? {} }) } as unknown as Response
- })
- }
-
- it('loads the preview into the sync slice', async () => {
- const store = new MachinesStore(syncFetch({
- 'sync.preview': { plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }], skills: [{ name: 's', root: 'dsh' }] },
- }))
- await store.loadSyncPreview()
- expect(store.getSnapshot().sync).toMatchObject({
- status: 'ready',
- preview: {
- plugins: [{ name: 'p', spec: 'github:a/b', syncable: true }],
- skills: [{ name: 's', root: 'dsh' }],
- },
- })
- })
-
- it('settles a preview failure as the sync error state', async () => {
- const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'internal', message: 'nope' } }) }) as unknown as Response)
- const store = new MachinesStore(fetchFn)
- await store.loadSyncPreview()
- expect(store.getSnapshot().sync).toMatchObject({ status: 'error', error: 'nope' })
- })
-
- it('applies a selection and lands the per-item results', async () => {
- const fetchFn = syncFetch({
- 'sync.apply': { items: [
- { kind: 'plugin', name: 'p', ok: true },
- { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },
- ] },
- })
- const store = new MachinesStore(fetchFn)
- await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [{ name: 's', root: 'dsh' }])
- const sync = store.getSnapshot().sync
- expect(sync.applying).toBe(false)
- expect(sync.error).toBeNull()
- expect(sync.results).toEqual([
- { kind: 'plugin', name: 'p', ok: true },
- { kind: 'skill', name: 's', root: 'dsh', ok: false, error: 'exit 1' },
- ])
- const applyCall = fetchFn.mock.calls
- .map(call => JSON.parse(String(call[1]?.body)) as { method: string, payload: Record<string, unknown> })
- .find(call => call.method === 'sync.apply')
- expect(applyCall?.payload).toEqual({
- machineId: 'a',
- plugins: [{ name: 'p', spec: 'github:a/b' }],
- skills: [{ name: 's', root: 'dsh' }],
- })
- })
-
- it('settles an apply failure as the sync error without losing applying=false', async () => {
- const fetchFn = vi.fn<FetchFn>(async () => ({ json: async () => ({ ok: false, error: { code: 'machine-sync-failed', message: 'ssh down' } }) }) as unknown as Response)
- const store = new MachinesStore(fetchFn)
- await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [])
- expect(store.getSnapshot().sync).toMatchObject({ applying: false, error: 'ssh down' })
- })
-
- it('merges a retry batch over its own entries and appends new ones', async () => {
- const fetchFn = syncFetch({
- 'sync.apply': { items: [
- { kind: 'plugin', name: 'p', ok: false, error: 'exit 1' },
- { kind: 'skill', name: 's', root: 'dsh', ok: true },
- ] },
- })
- const store = new MachinesStore(fetchFn)
- await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [{ name: 's', root: 'dsh' }])
- // 重试 p:成功,且 s 的既有结论不被抹掉
- fetchFn.mockResolvedValueOnce({ json: async () => ({ ok: true, value: { items: [{ kind: 'plugin', name: 'p', ok: true }] } }) } as unknown as Response)
- await store.applySync('a', [{ name: 'p', spec: 'github:a/b', syncable: true }], [])
- expect(store.getSnapshot().sync.results).toEqual([
- { kind: 'plugin', name: 'p', ok: true },
- { kind: 'skill', name: 's', root: 'dsh', ok: true },
- ])
- })
-})
-
-describe('mergeSyncResults', () => {
- const ok = (name: string): { kind: 'plugin', name: string, ok: boolean } => ({ kind: 'plugin', name, ok: true })
-
- it('keeps the first-seen order and replaces in place', () => {
- const merged = mergeSyncResults([ok('a'), ok('b')], [{ kind: 'plugin', name: 'b', ok: false, error: 'boom' }])
- expect(merged).toEqual([ok('a'), { kind: 'plugin', name: 'b', ok: false, error: 'boom' }])
- })
-
- it('appends unseen items and separates skills by root', () => {
- const merged = mergeSyncResults(
- [{ kind: 'skill', name: 'alpha', root: 'dsh', ok: true }],
- [{ kind: 'skill', name: 'alpha', root: 'agents', ok: false }, ok('c')],
- )
- expect(merged.map(item => `${item.kind}:${item.root ?? ''}:${item.name}`)).toEqual([
- 'skill:dsh:alpha',
- 'skill:agents:alpha',
- 'plugin::c',
- ])
- })
-})
diff --git a/packages/dsh-tauri-ssh/src/client/store/index.ts b/packages/dsh-tauri-ssh/src/client/store/index.ts
index 00e5751d..2a469b9c 100644
--- a/packages/dsh-tauri-ssh/src/client/store/index.ts
+++ b/packages/dsh-tauri-ssh/src/client/store/index.ts
@@ -1,863 +1,4 @@
-/**
- * State owner of the SSH-machines settings page. Everything goes through the
- * host plugin's same-origin `/api-ssh` route: machine.list serves the config
- * rows (secrets replaced by presence flags), the live statuses, and the
- * connection plane; machine.save/machine.remove are the CRUD writes. The
- * upstream settings RPC is deliberately NOT used for this namespace — its
- * configuration-client allowlist is hard-coded upstream, and the plugin must
- * stay zero-upstream-change. Framework-agnostic: tests inject a fake fetch.
- * @module dsh-tauri-ssh/client/store
- */
+import { machines } from './modules/machines'
+import { sync } from './modules/sync'
-import type { SshKey } from '../locales/index'
-import type { MachineLifecycleState, SshMachineEvent, SyncApplyResult, SyncItemResult, SyncPreview } from '../types/index'
-import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
-import { messageOf } from '../../shared/error'
-import { SSH_API_PATH } from '../constants/index'
-import { isLifecycleState } from '../types/index'
-
-/**
- * A published notice: `text` carries host-provided words verbatim (banner /
- * failure message); `key` is a store-generated literal rendered through the
- * locale table (params folded by `{name}` replacement at render time).
- */
-export type MachinesNotice
- = | { kind: 'text', text: string }
- | { kind: 'key', key: SshKey, params?: Record<string, string> }
-
-/** One redacted machine row (secret fields live only in the form). */
-export interface MachineRow {
- id: string
- name: string
- host: string
- port: number
- user: string
- hasPassword: boolean
- hasPassphrase: boolean
- remotePort: number
- profileName?: string
- startCommand?: string
- /** Optional identity color (any CSS color) shown as the machine's pip. */
- color?: string
- /** Whether the identity color also tints the machine card's border. */
- tintBorder?: boolean
-}
-
-/** Secret values the operator typed into the form (write-only direction). */
-export interface SecretValues {
- password?: string
- passphrase?: string
-}
-
-/** The pipeline phases one connection-plane operation walks through. */
-export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing' | 'syncing'
-
-/** Live transport status of one machine, from the /api-ssh list. */
-export interface MachineStatus {
- /** The C-STATE vocabulary (S3-owned); unknown wire values read as disconnected. */
- state: MachineLifecycleState
- /** While reconnecting: epoch ms of the next scheduled retry (S3-owned field). */
- nextRetryAt?: number
- /** Which credential the live (or last successful) connection used; registered, not rendered. */
- authMethod?: 'agent' | 'key' | 'password'
- tunnelBaseUrl?: string
- lastError?: string
- /** Whether the last failure was "dsh not installed on the remote" (offers install). */
- dshMissing?: boolean
- /** Live progress of the in-flight operation (phase codes translated by the UI). */
- progress?: { phase: ProgressPhase, attempt?: number, total?: number, item?: string, log?: string }
-}
-
-/** Outcome of a machine.install call (the host's install result). */
-export interface InstallResult {
- dshPath: string
- credentialsCopied: boolean
- credentialsError?: string
-}
-
-/** One machine row as the /api-ssh machine.list method returns it. */
-export interface MachineListItem extends MachineRow, MachineStatus {}
-
-/** The /api-ssh envelope (host plugin protocol). */
-export type SshApiResponse
- = | { ok: true, value: unknown }
- | { ok: false, error: { code: string, message: string } }
-
-/** The sync panel's slice of the page state. */
-export interface SyncPanelState {
- status: 'idle' | 'loading' | 'ready' | 'error'
- error: string | null
- /** The selectable plugins and skills (null until a preview lands). */
- preview: SyncPreview | null
- /** Whether a sync.apply is in flight. */
- applying: boolean
- /**
- * Apply outcomes keyed by item (kind:root:name); a retry overwrites its own
- * entries instead of dropping the earlier batch, so the list stays a running
- * record of this page. Null before the first apply.
- */
- results: SyncItemResult[] | null
-}
-
-/** Page state published to the component through the snapshot seam. */
-export interface MachinesPageState {
- status: 'idle' | 'loading' | 'ready' | 'error'
- error: string | null
- /** Whether the SSH feature is switched on; null until settings.get answers. */
- enabled: boolean | null
- /** Whether a settings.set enable call is in flight. */
- enabling: boolean
- /** Redacted machine rows in settings order (the stored, editable set). */
- machines: MachineRow[]
- /** Read-only rows discovered from the host's ~/.ssh/config (aliases). */
- discovered: MachineRow[]
- /** Live status per machine id. */
- statuses: Record<string, MachineStatus>
- /** Streaming log lines per machine id (the S2 event channel; capped tail). */
- logs: Record<string, string[]>
- /** Observed progress-phase sequence per machine id (the step rail's truth). */
- trails: Record<string, ProgressPhase[]>
- /** One in-flight connection-plane op per machine id. */
- busy: Record<string, 'test' | 'connect' | 'disconnect' | 'install'>
- /** The latest connection-plane outcome, shown in the banner. */
- notice: MachinesNotice | null
- /** The latest install outcome per machine id (shown under the card). */
- installResults: Record<string, InstallResult>
- /** The sync-to-remote panel state. */
- sync: SyncPanelState
- /** This instance's session role (a remote target renders the read-only banner). */
- role: { remote: boolean, origin?: string } | null
-}
-
-/** The fetch seam (window.fetch in the browser, fakes in tests). */
-export type FetchFn = (url: string, init: RequestInit) => Promise<Response>
-
-/** uSES-compatible snapshot store (getSnapshot returns a fresh object per update). */
-export interface SnapshotStore<T> {
- getSnapshot: () => T
- subscribe: (listener: () => void) => () => void
-}
-
-/** Create a snapshot store around one mutable state object. */
-export function createSnapshotStore<T>(initial: T): SnapshotStore<T> & { update: (mutator: (state: T) => void) => void } {
- let state = initial
- const listeners = new Set<() => void>()
- return {
- getSnapshot: () => state,
- subscribe: (listener) => {
- listeners.add(listener)
- return () => listeners.delete(listener)
- },
- update: (mutator) => {
- const next = { ...state }
- mutator(next)
- state = next
- for (const listener of listeners) listener()
- },
- }
-}
-
-/** Read one wire state through the C-STATE vocabulary; unknowns read as disconnected. */
-function lifecycleStateOf(raw: unknown): MachineLifecycleState {
- return isLifecycleState(raw) ? raw : 'disconnected'
-}
-
-/** How many log lines one machine keeps (the streaming tail). */
-const LOG_TAIL_LINES = 300
-
-/** Parse one machine.events value; malformed entries are dropped, not fatal. */
-export function machineEventsOf(value: unknown): SshMachineEvent[] {
- if (typeof value !== 'object' || value === null)
- return []
- const events = (value as { events?: unknown }).events
- if (!Array.isArray(events))
- return []
- const out: SshMachineEvent[] = []
- for (const entry of events) {
- if (typeof entry !== 'object' || entry === null)
- continue
- const event = entry as Record<string, unknown>
- if (typeof event.seq !== 'number' || typeof event.machineId !== 'string' || typeof event.line !== 'string')
- continue
- if (event.ts !== undefined && typeof event.ts !== 'string')
- continue
- if (event.stage !== undefined && typeof event.stage !== 'string')
- continue
- out.push({
- seq: event.seq,
- ts: typeof event.ts === 'string' ? event.ts : '',
- machineId: event.machineId,
- stage: typeof event.stage === 'string' ? event.stage : '',
- line: event.line,
- ...(event.terminal === 'success' || event.terminal === 'failed') ? { terminal: event.terminal } : {},
- ...typeof event.reason === 'string' ? { reason: event.reason } : {},
- })
- }
- return out
-}
-
-/** Parse one sync.preview value; null when the shape is wrong. */
-export function syncPreviewOf(value: unknown): SyncPreview | null {
- if (typeof value !== 'object' || value === null)
- return null
- const raw = value as { plugins?: unknown, skills?: unknown }
- if (!Array.isArray(raw.plugins) || !Array.isArray(raw.skills))
- return null
- const plugins = raw.plugins.flatMap((entry): SyncPreview['plugins'] => {
- if (typeof entry !== 'object' || entry === null)
- return []
- const item = entry as Record<string, unknown>
- if (typeof item.name !== 'string' || typeof item.spec !== 'string')
- return []
- return [{
- name: item.name,
- spec: item.spec,
- syncable: item.syncable === true,
- ...typeof item.reason === 'string' ? { reason: item.reason } : {},
- }]
- })
- const skills = raw.skills.flatMap((entry): SyncPreview['skills'] => {
- if (typeof entry !== 'object' || entry === null)
- return []
- const item = entry as Record<string, unknown>
- if (typeof item.name !== 'string' || typeof item.root !== 'string')
- return []
- return [{ name: item.name, root: item.root }]
- })
- return { plugins, skills }
-}
-
-/** Parse one sync.apply value; null when the shape is wrong. */
-export function syncApplyResultOf(value: unknown): SyncApplyResult | null {
- if (typeof value !== 'object' || value === null)
- return null
- const items = (value as { items?: unknown }).items
- if (!Array.isArray(items))
- return null
- const out: SyncItemResult[] = []
- for (const entry of items) {
- if (typeof entry !== 'object' || entry === null)
- continue
- const item = entry as Record<string, unknown>
- if (typeof item.name !== 'string' || typeof item.ok !== 'boolean')
- continue
- if (item.kind !== 'plugin' && item.kind !== 'skill')
- continue
- out.push({
- kind: item.kind,
- name: item.name,
- ...typeof item.root === 'string' ? { root: item.root } : {},
- ok: item.ok,
- ...typeof item.error === 'string' ? { error: item.error } : {},
- ...typeof item.log === 'string' ? { log: item.log } : {},
- })
- }
- return { items: out }
-}
-
-/**
- * The multi-select toggle: independent Set membership per key. This is the
- * semantic the sync items needed (the old panel behaved like a radio group —
- * picking one item silently dropped the others).
- */
-export function toggleSelection(selected: ReadonlySet<string>, key: string): Set<string> {
- const next = new Set(selected)
- if (next.has(key))
- next.delete(key)
- else
- next.add(key)
- return next
-}
-
-/**
- * The selection key of one preview plugin — identical in shape to the outcome
- * key {@link syncKeyOf} derives, so a selection and its result never drift.
- */
-export function pluginKeyOf(plugin: { name: string }): string {
- return `plugin::${plugin.name}`
-}
-
-/** The selection key of one preview skill (same shape as the outcome key). */
-export function skillKeyOf(skill: { name: string, root: string }): string {
- return `skill:${skill.root}:${skill.name}`
-}
-
-/** The outcome key of one settled sync item. */
-export function syncKeyOf(item: SyncItemResult): string {
- return `${item.kind}:${item.root ?? ''}:${item.name}`
-}
-
-/**
- * Merge one apply batch into the running outcome list: an item that ran again
- * (a retry) replaces its own entry in place, a new item appends. Without this
- * a retry would wipe the earlier batch and hide which items had succeeded.
- */
-export function mergeSyncResults(previous: readonly SyncItemResult[], incoming: readonly SyncItemResult[]): SyncItemResult[] {
- const merged = [...previous]
- const at = new Map(merged.map((item, index) => [syncKeyOf(item), index]))
- for (const item of incoming) {
- const index = at.get(syncKeyOf(item))
- if (index === undefined) {
- at.set(syncKeyOf(item), merged.length)
- merged.push(item)
- }
- else {
- merged[index] = item
- }
- }
- return merged
-}
-
-/** Parse one /api-ssh envelope; a transport-level failure throws a stable code. */
-async function envelopeOf(response: Response): Promise<SshApiResponse> {
- // 非 2xx(路由未挂载 / 插件未启用时的 404、405)与空响应体都没有可解析的
- // JSON:直接抛稳定错误码,绝不把 `Unexpected end of JSON input` 这类原生
- // 解析异常泄漏到界面。
- if (response.ok === false)
- throw new Error(`SSH_API_HTTP_${response.status}`)
- try {
- return await response.json() as SshApiResponse
- }
- catch {
- throw new Error('SSH_API_EMPTY')
- }
-}
-
-/** Whether one failure text is a transport code rather than host-provided prose. */
-export function isTransportError(message: string): boolean {
- return message.startsWith('SSH_API_')
-}
-
-/** Build a redacted machine row from one machine.list item. */
-export function machineRowOf(value: unknown): MachineRow | undefined {
- if (typeof value !== 'object' || value === null)
- return undefined
- const row = value as Record<string, unknown>
- if (typeof row.id !== 'string' || row.id === '')
- return undefined
- if (typeof row.name !== 'string')
- return undefined
- if (typeof row.host !== 'string' || row.host === '')
- return undefined
- if (typeof row.user !== 'string')
- return undefined
- const port = typeof row.port === 'number' ? row.port : DEFAULT_SSH_PORT
- const remotePort = typeof row.remotePort === 'number' ? row.remotePort : DEFAULT_REMOTE_PORT
- const startCommand = typeof row.startCommand === 'string' && row.startCommand !== ''
- ? row.startCommand
- : undefined
- const rawProfileName = typeof row.profileName === 'string' ? row.profileName.trim() : ''
- const profileName = /^[\w-]+$/.test(rawProfileName) ? rawProfileName : undefined
- const color = typeof row.color === 'string' && row.color !== '' ? row.color : undefined
- return {
- id: row.id,
- name: row.name,
- host: row.host,
- port,
- user: row.user,
- hasPassword: row.hasPassword === true,
- hasPassphrase: row.hasPassphrase === true,
- remotePort,
- ...profileName === undefined ? {} : { profileName },
- ...startCommand === undefined ? {} : { startCommand },
- ...color === undefined ? {} : { color },
- ...row.tintBorder === true ? { tintBorder: true } : {},
- }
-}
-
-/** The machine.save config row shape (config fields only). */
-export interface MachineSaveRow {
- name: string
- host: string
- port: number
- user: string
- remotePort: number
- profileName?: string
- startCommand?: string
- color?: string
- tintBorder?: boolean
-}
-
-/** Map one form row onto the machine.save payload (id + row + write-only secrets). */
-export function savePayloadOf(machine: MachineRow, secrets: SecretValues): { machineId: string, row: MachineSaveRow, secrets?: SecretValues } {
- const row: MachineSaveRow = {
- name: machine.name,
- host: machine.host,
- port: machine.port,
- user: machine.user,
- remotePort: machine.remotePort,
- ...machine.profileName === undefined || machine.profileName === '' ? {} : { profileName: machine.profileName },
- ...machine.startCommand === undefined || machine.startCommand === '' ? {} : { startCommand: machine.startCommand },
- ...machine.color === undefined || machine.color === '' ? {} : { color: machine.color },
- ...machine.tintBorder === true ? { tintBorder: true } : {},
- }
- const typed: SecretValues = {}
- if (secrets.password !== undefined && secrets.password !== '')
- typed.password = secrets.password
- if (secrets.passphrase !== undefined && secrets.passphrase !== '')
- typed.passphrase = secrets.passphrase
- const payload: { machineId: string, row: MachineSaveRow, secrets?: SecretValues } = { machineId: machine.id, row }
- if (Object.keys(typed).length > 0)
- payload.secrets = typed
- return payload
-}
-
-/**
- * The page store: machine CRUD and the connection plane, all through
- * /api-ssh. Every mutation settles the published state; failures surface as
- * `state.error`/`state.notice` rather than throws.
- */
-export class MachinesStore {
- /** The published page state. */
- readonly store: SnapshotStore<MachinesPageState> & { update: (mutator: (state: MachinesPageState) => void) => void }
-
- /**
- * The consumed event cursor per machine id (the last `seq` seen for that
- * machine). `seq` is a per-machine space — a global high-water mark would
- * mix counters and starve machines with lower sequence numbers.
- */
- private readonly lastEventSeqByMachine = new Map<string, number>()
-
- /** Whether the host still gets asked for machine.events (off after first refusal). */
- private eventsSupported = true
-
- /**
- * @param fetchFn - the /api-ssh transport (window.fetch in the browser).
- */
- constructor(private readonly fetchFn: FetchFn) {
- this.store = createSnapshotStore<MachinesPageState>({
- status: 'idle',
- error: null,
- enabled: null,
- enabling: false,
- machines: [],
- discovered: [],
- statuses: {},
- logs: {},
- trails: {},
- busy: {},
- notice: null,
- installResults: {},
- sync: { status: 'idle', error: null, preview: null, applying: false, results: null },
- role: null,
- })
- }
-
- /** Snapshot subscribe seam for useSyncExternalStore. */
- subscribe = (listener: () => void): () => void => this.store.subscribe(listener)
-
- /** Snapshot read seam for useSyncExternalStore. */
- getSnapshot = (): MachinesPageState => this.store.getSnapshot()
-
- /** POST one connection-plane method and return its value; failures throw. */
- private async callApi<T>(method: string, payload: Record<string, unknown>): Promise<T> {
- const response = await this.fetchFn(SSH_API_PATH, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ method, payload }),
- })
- const envelope = await envelopeOf(response)
- if (!envelope.ok)
- throw new Error(envelope.error.message)
- return envelope.value as T
- }
-
- /** Apply one machine.list payload to the published state. */
- private applyList(list: { items?: MachineListItem[], discovered?: MachineListItem[] }): void {
- const machines = (list.items ?? []).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)
- const discovered = (list.discovered ?? []).map(machineRowOf).filter((row): row is MachineRow => row !== undefined)
- const statuses: Record<string, MachineStatus> = {}
- for (const item of [...(list.items ?? []), ...(list.discovered ?? [])]) {
- const status: MachineStatus = { state: lifecycleStateOf(item.state) }
- if (typeof item.nextRetryAt === 'number' && Number.isFinite(item.nextRetryAt))
- status.nextRetryAt = item.nextRetryAt
- if (item.authMethod === 'agent' || item.authMethod === 'key' || item.authMethod === 'password')
- status.authMethod = item.authMethod
- if (item.tunnelBaseUrl !== undefined)
- status.tunnelBaseUrl = item.tunnelBaseUrl
- if (item.lastError !== undefined)
- status.lastError = item.lastError
- if (item.dshMissing === true)
- status.dshMissing = true
- if (item.progress !== undefined)
- status.progress = item.progress
- statuses[item.id] = status
- }
- this.store.update((state) => {
- state.status = 'ready'
- state.error = null
- state.machines = machines
- state.discovered = discovered
- state.statuses = statuses
- // 阶段轨迹:操作期间把实际出现的 progress.phase 依次入轨(步骤条的
- // 真值——装没装过 install 阶段由轨迹说话);progress 消失即操作结束,
- // 清轨让步骤条收起。被删除的机器顺带清轨。
- for (const [id, status] of Object.entries(statuses)) {
- const phase = status.progress?.phase
- if (phase !== undefined) {
- const trail = state.trails[id] ?? []
- if (trail[trail.length - 1] !== phase)
- state.trails[id] = [...trail, phase]
- }
- else {
- delete state.trails[id]
- }
- }
- for (const id of Object.keys(state.trails)) {
- if (statuses[id] === undefined)
- delete state.trails[id]
- }
- })
- }
-
- /** Refresh machines, secret flags, and live statuses from machine.list. */
- async load(): Promise<void> {
- if (this.store.getSnapshot().enabled === false)
- return
- this.store.update((state) => {
- state.status = 'loading'
- state.error = null
- })
- try {
- if (this.store.getSnapshot().role === null)
- void this.loadRole()
- this.applyList(await this.callApi<{ items?: MachineListItem[], discovered?: MachineListItem[] }>('machine.list', {}))
- }
- catch (error) {
- this.store.update((state) => {
- state.status = 'error'
- state.error = messageOf(error)
- })
- }
- }
-
- /**
- * Read the feature switch (settings.get). A transport failure reads as
- * "off" plus an error notice: the section then shows the enable surface
- * instead of a raw parse error.
- */
- async loadSettings(): Promise<void> {
- try {
- const value = await this.callApi<{ enabled?: unknown }>('settings.get', {})
- this.store.update((state) => {
- state.enabled = value.enabled === true
- state.error = null
- })
- }
- catch (error) {
- this.store.update((state) => {
- state.enabled = false
- state.error = messageOf(error)
- })
- }
- }
-
- /** Switch the SSH feature on (settings.set), then load the machine table. */
- async enable(): Promise<void> {
- this.store.update((state) => {
- state.enabling = true
- state.error = null
- })
- try {
- const value = await this.callApi<{ enabled?: unknown }>('settings.set', { enabled: true })
- this.store.update((state) => {
- state.enabled = value.enabled !== false
- })
- if (this.store.getSnapshot().enabled === true)
- await this.load()
- }
- catch (error) {
- this.store.update((state) => {
- state.error = messageOf(error)
- })
- }
- finally {
- this.store.update((state) => {
- state.enabling = false
- })
- }
- }
-
- /** Load this instance's session role once (old hosts without the method keep null). */
- async loadRole(): Promise<void> {
- try {
- const role = await this.callApi<{ remote: boolean, origin?: string }>('session.role', {})
- this.store.update((state) => {
- state.role = role.remote === true ? { remote: true, ...role.origin === undefined || role.origin === '' ? {} : { origin: role.origin } } : { remote: false }
- })
- }
- catch {
- // Older hosts lack session.role; the banner simply stays hidden.
- }
- }
-
- /** Silent refresh: same payload as load(), but never flips the loading banner. */
- async poll(): Promise<void> {
- try {
- this.applyList(await this.callApi<{ items?: MachineListItem[], discovered?: MachineListItem[] }>('machine.list', {}))
- await this.pollEvents()
- }
- catch (error) {
- this.store.update((state) => {
- state.error = messageOf(error)
- })
- }
- }
-
- /**
- * Pull machine.events for every known machine and fold the lines into the
- * per-machine logs. The channel is per-machine: `seq` counts inside one
- * machine's buffer only, so the cursor lives per machine id and each poll
- * sends `{ machineId, sinceSeq }` per machine (the cursor is omitted on a
- * machine's first poll). A host without the S2 channel (or any refusal)
- * turns the channel off for good — the panel then lives on the status
- * progress fields alone, and the polling loop never fails the page for it.
- */
- private async pollEvents(): Promise<void> {
- if (!this.eventsSupported)
- return
- const snapshot = this.store.getSnapshot()
- const known = new Set([...snapshot.machines, ...snapshot.discovered].map(row => row.id))
- // Removed machines leave their cursors behind; drop them so the map
- // tracks the live machine set only.
- for (const id of this.lastEventSeqByMachine.keys()) {
- if (!known.has(id))
- this.lastEventSeqByMachine.delete(id)
- }
- const byMachine = new Map<string, string[]>()
- try {
- for (const machineId of known) {
- const cursor = this.lastEventSeqByMachine.get(machineId)
- const events = machineEventsOf(await this.callApi<unknown>('machine.events', {
- machineId,
- ...cursor === undefined ? {} : { sinceSeq: cursor },
- }))
- if (events.length === 0)
- continue
- this.lastEventSeqByMachine.set(machineId, Math.max(...events.map(event => event.seq)))
- for (const event of events) {
- // 空行的收尾事件(terminal/reason)合成一行标记,不再静默丢弃
- const line = event.line !== ''
- ? event.line
- : event.terminal === undefined
- ? ''
- : `[${event.terminal}]${event.reason === undefined ? '' : ` ${event.reason}`}`
- if (line === '')
- continue
- byMachine.set(event.machineId, [...(byMachine.get(event.machineId) ?? []), line])
- }
- }
- }
- catch {
- this.eventsSupported = false
- return
- }
- if (byMachine.size === 0)
- return
- this.store.update((state) => {
- for (const [machineId, lines] of byMachine) {
- state.logs[machineId] = [...(state.logs[machineId] ?? []), ...lines].slice(-LOG_TAIL_LINES)
- }
- })
- }
-
- /**
- * Persist the form: machine.save per row (write-only secrets; absent fields
- * keep the stored value) and machine.remove for ids that vanished.
- * @param machines - the form's machine rows (id is the dict key).
- * @param secrets - secret values the operator typed, keyed by machine id.
- * @returns whether every write landed (failures surface as `state.error`).
- */
- async persist(machines: MachineRow[], secrets: Record<string, SecretValues>): Promise<boolean> {
- const previous = this.store.getSnapshot().machines
- const previousIds = new Set(previous.map(row => row.id))
- try {
- for (const machine of machines) {
- await this.callApi<Record<string, never>>('machine.save', savePayloadOf(machine, secrets[machine.id] ?? {}))
- }
- for (const id of previousIds) {
- if (!machines.some(row => row.id === id)) {
- await this.callApi<Record<string, never>>('machine.remove', { machineId: id })
- }
- }
- this.store.update((state) => {
- state.error = null
- })
- await this.load()
- return true
- }
- catch (error) {
- this.store.update((state) => {
- state.error = messageOf(error)
- })
- return false
- }
- }
-
- /** Remove one machine immediately (config + secrets); returns success. */
- async remove(id: string): Promise<boolean> {
- try {
- await this.callApi<Record<string, never>>('machine.remove', { machineId: id })
- this.store.update((state) => {
- state.error = null
- })
- await this.load()
- return true
- }
- catch (error) {
- this.store.update((state) => {
- state.error = messageOf(error)
- })
- return false
- }
- }
-
- /** Mark one machine busy; failures settle the banner error. */
- private async withBusy(id: string, op: 'test' | 'connect' | 'disconnect' | 'install', action: () => Promise<void>): Promise<void> {
- this.store.update((state) => {
- state.busy[id] = op
- state.notice = null
- state.error = null
- })
- try {
- await action()
- }
- catch (error) {
- this.store.update((state) => {
- state.error = messageOf(error)
- })
- }
- finally {
- this.store.update((state) => {
- delete state.busy[id]
- })
- }
- }
-
- /** One-shot probe: runs `uname -srm` on the machine, never starts the instance. */
- async test(id: string): Promise<void> {
- await this.withBusy(id, 'test', async () => {
- const result = await this.callApi<{ ok: boolean, banner?: string, message?: string }>('machine.test', { machineId: id })
- if (result.ok) {
- this.store.update((state) => {
- state.notice = result.banner === undefined || result.banner === ''
- ? { kind: 'key', key: 'notice.probe_ok' }
- : { kind: 'text', text: result.banner }
- // 探测是旁路健康检查:只在还没有状态记录时落 disconnected,
- // 绝不把一条已建立/进行中的连接打回断开(连接面由轮询真值维护)。
- if (state.statuses[id] === undefined)
- state.statuses[id] = { state: 'disconnected' }
- })
- }
- else {
- this.store.update((state) => {
- state.notice = result.message === undefined || result.message === ''
- ? { kind: 'key', key: 'notice.probe_failed' }
- : { kind: 'text', text: result.message }
- const current = state.statuses[id]
- // 失败只追加 lastError;已有的连接态原样保留(真断开由轮询呈现)。
- state.statuses[id] = current === undefined || current.state === 'disconnected'
- ? { state: 'disconnected', lastError: result.message ?? 'failed' }
- : { ...current, lastError: result.message ?? 'failed' }
- })
- }
- })
- }
-
- /** Connect the machine: ensures the remote dsh instance and opens the tunnel. */
- async connect(id: string): Promise<void> {
- await this.withBusy(id, 'connect', async () => {
- const link = await this.callApi<{ tunnelBaseUrl: string }>('machine.connect', { machineId: id })
- this.store.update((state) => {
- state.statuses[id] = { state: 'connected', tunnelBaseUrl: link.tunnelBaseUrl }
- state.notice = { kind: 'key', key: 'notice.connected', params: { url: link.tunnelBaseUrl } }
- })
- })
- }
-
- /** Tear down one machine's link. */
- async disconnect(id: string): Promise<void> {
- await this.withBusy(id, 'disconnect', async () => {
- await this.callApi<Record<string, never>>('machine.disconnect', { machineId: id })
- this.store.update((state) => {
- state.statuses[id] = { state: 'disconnected' }
- state.notice = { kind: 'key', key: 'notice.disconnected' }
- })
- })
- }
-
- /**
- * One-click remote dsh install: streams through the host's machine.install,
- * which auto-connects on success. A follow-up load picks up the auto-connect
- * status (the polling loop keeps refreshing while it is in flight).
- */
- async install(id: string): Promise<void> {
- await this.withBusy(id, 'install', async () => {
- const result = await this.callApi<InstallResult>('machine.install', { machineId: id })
- this.store.update((state) => {
- state.installResults[id] = result
- })
- await this.load()
- })
- }
-
- /** Load the sync selection list (local plugins and skills) from sync.preview. */
- async loadSyncPreview(): Promise<void> {
- this.store.update((state) => {
- state.sync.status = 'loading'
- state.sync.error = null
- })
- try {
- const preview = syncPreviewOf(await this.callApi<unknown>('sync.preview', {}))
- if (preview === null)
- throw new Error('malformed sync.preview payload')
- this.store.update((state) => {
- state.sync.status = 'ready'
- state.sync.preview = preview
- })
- }
- catch (error) {
- this.store.update((state) => {
- state.sync.status = 'error'
- state.sync.error = messageOf(error)
- })
- }
- }
-
- /**
- * Sync one selection to a machine. The per-item outcomes land in
- * `state.sync.results` even on partial failure — a request-level failure
- * (session unreachable) surfaces as `state.sync.error`.
- * @param machineId - the connected target machine.
- * @param plugins - the selected plugin refs.
- * @param skills - the selected skill refs.
- */
- async applySync(machineId: string, plugins: SyncPreview['plugins'], skills: SyncPreview['skills']): Promise<void> {
- this.store.update((state) => {
- state.sync.applying = true
- state.sync.error = null
- })
- try {
- const result = syncApplyResultOf(await this.callApi<unknown>('sync.apply', {
- machineId,
- plugins: plugins.map(plugin => ({ name: plugin.name, spec: plugin.spec })),
- skills: skills.map(skill => ({ name: skill.name, root: skill.root })),
- }))
- if (result === null)
- throw new Error('malformed sync.apply payload')
- this.store.update((state) => {
- state.sync.results = mergeSyncResults(state.sync.results ?? [], result.items)
- })
- }
- catch (error) {
- this.store.update((state) => {
- state.sync.error = messageOf(error)
- })
- }
- finally {
- this.store.update((state) => {
- state.sync.applying = false
- })
- }
- }
-}
+export const store = { machines, sync }
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts b/packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts
new file mode 100644
index 00000000..6f1dc382
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/machines.test.ts
@@ -0,0 +1,166 @@
+import type { MachineListSnapshot } from '../../types/index'
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { store } from '../index'
+
+vi.mock('dsh-tauri/client', async () => (await import('../../test-utils/client-mock')).clientMock)
+
+const machineA = {
+ id: 'a',
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ hasPassword: true,
+ hasPassphrase: false,
+ remotePort: 3080,
+}
+const machineB = { ...machineA, id: 'b', name: 'beta' }
+
+function snapshot(rows: MachineListSnapshot['machines'], statuses: MachineListSnapshot['statuses'] = {}): MachineListSnapshot {
+ return {
+ machines: rows,
+ discovered: [],
+ statuses: Object.fromEntries(rows.map(row => [row.id, statuses[row.id] ?? { state: 'disconnected' as const }])),
+ }
+}
+
+beforeEach(() => {
+ store.machines.reset()
+})
+
+describe('commitList', () => {
+ it('publishes the rows, the statuses, and the phase trail', () => {
+ store.machines.commitList(snapshot([machineA, machineB], {
+ a: { state: 'connecting', progress: { phase: 'handshake' } },
+ }))
+ expect(store.machines.machines.map(row => row.id)).toEqual(['a', 'b'])
+ expect(store.machines.statuses.a).toEqual({ state: 'connecting', progress: { phase: 'handshake' } })
+ expect(store.machines.trails.a).toEqual(['handshake'])
+ expect(store.machines.status).toBe('ready')
+ })
+
+ it('drops the trail and the cursor of a machine that vanished', () => {
+ store.machines.commitList(snapshot([machineA, machineB], {
+ a: { state: 'connecting', progress: { phase: 'probing' } },
+ b: { state: 'connecting', progress: { phase: 'probing' } },
+ }))
+ store.machines.advanceEvents({ a: 4, b: 9 })
+ store.machines.commitList(snapshot([machineA]))
+ expect(store.machines.trails.b).toBeUndefined()
+ expect(store.machines.eventCursors).toEqual({ a: 4 })
+ })
+
+ it('keeps the same trail array while the phase does not move', () => {
+ store.machines.commitList(snapshot([machineA], { a: { state: 'connecting', progress: { phase: 'probing' } } }))
+ const first = store.machines.trails.a
+ store.machines.commitList(snapshot([machineA], { a: { state: 'connecting', progress: { phase: 'probing' } } }))
+ expect(store.machines.trails.a).toBe(first)
+ })
+})
+
+describe('appendLogs', () => {
+ it('appends to the previous lines and caps the tail', () => {
+ store.machines.appendLogs({ a: ['line 1'] })
+ store.machines.appendLogs({ a: ['line 2'] })
+ expect(store.machines.logs.a).toEqual(['line 1', 'line 2'])
+
+ store.machines.appendLogs({ a: Array.from({ length: 310 }, (_, index) => `line ${index + 3}`) })
+ expect(store.machines.logs.a).toHaveLength(300)
+ expect(store.machines.logs.a?.at(-1)).toBe('line 312')
+ expect(store.machines.logs.a?.[0]).toBe('line 13')
+ })
+})
+
+describe('probe outcomes', () => {
+ it('only fills in a status when the machine had none', () => {
+ store.machines.commitProbeOk('a', 'Linux alpha')
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected' })
+ expect(store.machines.notice).toEqual({ kind: 'text', text: 'Linux alpha' })
+
+ store.machines.commitConnected('a', 'http://127.0.0.1:1')
+ store.machines.commitProbeOk('a')
+ expect(store.machines.statuses.a).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.probe_ok' })
+ })
+
+ it('defaults the failure reason and keeps a live connection', () => {
+ store.machines.commitProbeFailed('a')
+ expect(store.machines.statuses.a).toEqual({ state: 'disconnected', lastError: 'failed' })
+ expect(store.machines.notice).toEqual({ kind: 'key', key: 'notice.probe_failed' })
+
+ store.machines.commitConnected('b', 'http://127.0.0.1:2')
+ store.machines.commitProbeFailed('b', 'auth failed')
+ expect(store.machines.statuses.b).toEqual({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:2', lastError: 'auth failed' })
+ expect(store.machines.notice).toEqual({ kind: 'text', text: 'auth failed' })
+ })
+})
+
+describe('the busy slot', () => {
+ it('tracks one in-flight operation per machine', () => {
+ store.machines.beginOp('a', 'connect')
+ expect(store.machines.busy).toEqual({ a: 'connect' })
+ store.machines.endOp('a')
+ expect(store.machines.busy).toEqual({})
+ })
+
+ it('clears the banner when an operation starts', () => {
+ store.machines.fail('nope')
+ store.machines.beginOp('a', 'test')
+ expect(store.machines.error).toBeNull()
+ })
+})
+
+describe('the feature switch', () => {
+ it('tracks the enable round trip', () => {
+ store.machines.setEnabled(false, null)
+ store.machines.beginEnable()
+ expect(store.machines.enabling).toBe(true)
+ store.machines.setEnabled(true, null)
+ store.machines.endEnable()
+ expect(store.machines.enabled).toBe(true)
+ expect(store.machines.enabling).toBe(false)
+ expect(store.machines.error).toBeNull()
+ })
+})
+
+describe('event cursors', () => {
+ it('only ever moves a cursor forward', () => {
+ store.machines.advanceEvents({ a: 5 })
+ store.machines.advanceEvents({ a: 3 })
+ expect(store.machines.eventCursors.a).toBe(5)
+ store.machines.advanceEvents({ a: 7 })
+ expect(store.machines.eventCursors.a).toBe(7)
+ })
+
+ it('turns the channel off for the session', () => {
+ store.machines.disableEvents()
+ expect(store.machines.eventsSupported).toBe(false)
+ })
+})
+
+describe('reset', () => {
+ it('restores the initial state', () => {
+ store.machines.commitList(snapshot([machineA]))
+ store.machines.disableEvents()
+ store.machines.fail('nope')
+ store.machines.reset()
+ expect(store.machines.$state).toEqual({
+ status: 'idle',
+ error: null,
+ enabled: null,
+ enabling: false,
+ machines: [],
+ discovered: [],
+ statuses: {},
+ logs: {},
+ trails: {},
+ busy: {},
+ notice: null,
+ installResults: {},
+ role: null,
+ eventCursors: {},
+ eventsSupported: true,
+ })
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.ts b/packages/dsh-tauri-ssh/src/client/store/modules/machines.ts
new file mode 100644
index 00000000..85a8e9ed
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/machines.ts
@@ -0,0 +1,130 @@
+import type { InstallResult, MachineListSnapshot, ProgressPhase } from '../../types/index'
+import type { MachineBusyOp, MachinesState } from './machines.types'
+import { defineStore } from 'dsh-tauri/client'
+
+const LOG_TAIL_LINES = 300
+
+function initialState(): MachinesState {
+ return {
+ status: 'idle',
+ error: null,
+ enabled: null,
+ enabling: false,
+ machines: [],
+ discovered: [],
+ statuses: {},
+ logs: {},
+ trails: {},
+ busy: {},
+ notice: null,
+ installResults: {},
+ role: null,
+ eventCursors: {},
+ eventsSupported: true,
+ }
+}
+
+export const machines = defineStore({
+ state: (): MachinesState => initialState(),
+ actions: {
+ reset(): void {
+ Object.assign(this, initialState())
+ },
+ beginLoad(): void {
+ this.status = 'loading'
+ this.error = null
+ },
+ commitList(list: MachineListSnapshot): void {
+ this.machines = list.machines
+ this.discovered = list.discovered
+ this.statuses = list.statuses
+ const trails: Record<string, ProgressPhase[]> = {}
+ for (const [id, status] of Object.entries(list.statuses)) {
+ if (status.progress === undefined)
+ continue
+ const trail = this.trails[id] ?? []
+ trails[id] = trail[trail.length - 1] === status.progress.phase
+ ? trail
+ : [...trail, status.progress.phase]
+ }
+ this.trails = trails
+ const known = new Set([...list.machines, ...list.discovered].map(row => row.id))
+ for (const id of Object.keys(this.eventCursors)) {
+ if (!known.has(id))
+ delete this.eventCursors[id]
+ }
+ this.status = 'ready'
+ this.error = null
+ },
+ failList(error: string): void {
+ this.status = 'error'
+ this.error = error
+ },
+ fail(error: string): void {
+ this.error = error
+ },
+ clearError(): void {
+ this.error = null
+ },
+ setEnabled(enabled: boolean, error: string | null): void {
+ this.enabled = enabled
+ this.error = error
+ },
+ beginEnable(): void {
+ this.enabling = true
+ this.error = null
+ },
+ endEnable(): void {
+ this.enabling = false
+ },
+ setRole(role: { remote: boolean, origin?: string }): void {
+ this.role = role
+ },
+ beginOp(id: string, op: MachineBusyOp): void {
+ this.busy[id] = op
+ this.notice = null
+ this.error = null
+ },
+ endOp(id: string): void {
+ delete this.busy[id]
+ },
+ commitProbeOk(id: string, banner?: string): void {
+ this.notice = banner === undefined || banner === '' ? { kind: 'key', key: 'notice.probe_ok' } : { kind: 'text', text: banner }
+ if (this.statuses[id] === undefined)
+ this.statuses[id] = { state: 'disconnected' }
+ },
+ commitProbeFailed(id: string, message?: string): void {
+ this.notice = message === undefined || message === '' ? { kind: 'key', key: 'notice.probe_failed' } : { kind: 'text', text: message }
+ const current = this.statuses[id]
+ const lastError = { lastError: message === undefined ? 'failed' : message }
+ this.statuses[id] = current === undefined || current.state === 'disconnected'
+ ? { state: 'disconnected', ...lastError }
+ : { ...current, ...lastError }
+ },
+ commitConnected(id: string, tunnelBaseUrl: string): void {
+ this.statuses[id] = { state: 'connected', tunnelBaseUrl }
+ this.notice = { kind: 'key', key: 'notice.connected', params: { url: tunnelBaseUrl } }
+ },
+ commitDisconnected(id: string): void {
+ this.statuses[id] = { state: 'disconnected' }
+ this.notice = { kind: 'key', key: 'notice.disconnected' }
+ },
+ commitInstallResult(id: string, result: InstallResult): void {
+ this.installResults[id] = result
+ },
+ appendLogs(lines: Record<string, string[]>): void {
+ for (const [id, incoming] of Object.entries(lines))
+ this.logs[id] = [...(this.logs[id] ?? []), ...incoming].slice(-LOG_TAIL_LINES)
+ },
+ advanceEvents(cursors: Record<string, number>): void {
+ for (const [id, seq] of Object.entries(cursors)) {
+ const current = this.eventCursors[id]
+ if (current === undefined || seq > current)
+ this.eventCursors[id] = seq
+ }
+ },
+ disableEvents(): void {
+ this.eventsSupported = false
+ },
+ },
+})
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts b/packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts
new file mode 100644
index 00000000..8a38d215
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/machines.types.ts
@@ -0,0 +1,33 @@
+import type { SshKey } from '../../locales/index'
+import type {
+ InstallResult,
+ MachineRow,
+ MachineStatus,
+ ProgressPhase,
+} from '../../types/index'
+
+export type MachinesStatus = 'idle' | 'loading' | 'ready' | 'error'
+
+export type MachineBusyOp = 'test' | 'connect' | 'disconnect' | 'install'
+
+export type MachinesNotice
+ = | { kind: 'text', text: string }
+ | { kind: 'key', key: SshKey, params?: Record<string, string | number> }
+
+export interface MachinesState {
+ status: MachinesStatus
+ error: string | null
+ enabled: boolean | null
+ enabling: boolean
+ machines: MachineRow[]
+ discovered: MachineRow[]
+ statuses: Record<string, MachineStatus>
+ logs: Record<string, string[]>
+ trails: Record<string, ProgressPhase[]>
+ busy: Record<string, MachineBusyOp>
+ notice: MachinesNotice | null
+ installResults: Record<string, InstallResult>
+ role: { remote: boolean, origin?: string } | null
+ eventCursors: Record<string, number>
+ eventsSupported: boolean
+}
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.ts b/packages/dsh-tauri-ssh/src/client/store/modules/sync.ts
new file mode 100644
index 00000000..9f7fb5e5
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/sync.ts
@@ -0,0 +1,43 @@
+import type { SyncItemResult, SyncPreview } from '../../types/index'
+import type { SyncState } from './sync.types'
+import { defineStore } from 'dsh-tauri/client'
+import { mergeSyncResults } from './sync.utils'
+
+function initialState(): SyncState {
+ return { status: 'idle', error: null, preview: null, applying: false, results: null }
+}
+
+export const sync = defineStore({
+ state: (): SyncState => initialState(),
+ actions: {
+ reset(): void {
+ Object.assign(this, initialState())
+ },
+ beginLoad(): void {
+ this.status = 'loading'
+ this.error = null
+ },
+ commitPreview(preview: SyncPreview): void {
+ this.preview = preview
+ this.status = 'ready'
+ this.error = null
+ },
+ failLoad(error: string): void {
+ this.status = 'error'
+ this.error = error
+ },
+ fail(error: string): void {
+ this.error = error
+ },
+ beginApply(): void {
+ this.applying = true
+ this.error = null
+ },
+ endApply(): void {
+ this.applying = false
+ },
+ mergeResults(items: SyncItemResult[]): void {
+ this.results = mergeSyncResults(this.results ?? [], items)
+ },
+ },
+})
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.types.ts b/packages/dsh-tauri-ssh/src/client/store/modules/sync.types.ts
new file mode 100644
index 00000000..c4197288
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/sync.types.ts
@@ -0,0 +1,11 @@
+import type { SyncItemResult, SyncPreview } from '../../types/index'
+
+export type SyncStatus = 'idle' | 'loading' | 'ready' | 'error'
+
+export interface SyncState {
+ status: SyncStatus
+ error: string | null
+ preview: SyncPreview | null
+ applying: boolean
+ results: SyncItemResult[] | null
+}
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.test.ts b/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.test.ts
new file mode 100644
index 00000000..bffa9548
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.test.ts
@@ -0,0 +1,53 @@
+import type { SyncItemResult } from '../../types/index'
+import { describe, expect, it } from 'vitest'
+import { mergeSyncResults, syncKeyOf, toggleSelection } from './sync.utils'
+
+describe('toggleSelection', () => {
+ it('toggles one key without touching the others', () => {
+ const first = new Set(['plugin::p'])
+ const second = toggleSelection(first, 'skill:dsh:s')
+ expect([...first]).toEqual(['plugin::p'])
+ expect([...second].sort()).toEqual(['plugin::p', 'skill:dsh:s'])
+ expect([...toggleSelection(second, 'plugin::p')]).toEqual(['skill:dsh:s'])
+ })
+})
+
+describe('key builders', () => {
+ it('keys plugins by name and skills by root and name', () => {
+ expect(syncKeyOf({ kind: 'plugin', name: 'p' })).toBe('plugin::p')
+ expect(syncKeyOf({ kind: 'skill', name: 'alpha', root: 'dsh' })).toBe('skill:dsh:alpha')
+ })
+})
+
+describe('mergeSyncResults', () => {
+ const ok = (name: string): SyncItemResult => ({ kind: 'plugin', name, ok: true })
+
+ it('keeps the first-seen order and replaces in place', () => {
+ const merged = mergeSyncResults([ok('a'), ok('b')], [{ kind: 'plugin', name: 'b', ok: false, error: 'boom' }])
+ expect(merged).toEqual([ok('a'), { kind: 'plugin', name: 'b', ok: false, error: 'boom' }])
+ })
+
+ it('keeps duplicate prior slots and replaces the last slot on repeated updates', () => {
+ const previous = [ok('a'), ok('a')]
+ const incoming: SyncItemResult[] = [ok('b'), { kind: 'plugin', name: 'a', ok: false }, { kind: 'plugin', name: 'b', ok: false }]
+ expect(mergeSyncResults(previous, incoming)).toEqual([
+ ok('a'),
+ { kind: 'plugin', name: 'a', ok: false },
+ { kind: 'plugin', name: 'b', ok: false },
+ ])
+ expect(previous).toEqual([ok('a'), ok('a')])
+ expect(mergeSyncResults([], [])).toEqual([])
+ })
+
+ it('appends unseen items and separates skills by root', () => {
+ const merged = mergeSyncResults(
+ [{ kind: 'skill', name: 'alpha', root: 'dsh', ok: true }],
+ [{ kind: 'skill', name: 'alpha', root: 'agents', ok: false }, ok('c')],
+ )
+ expect(merged).toEqual([
+ { kind: 'skill', name: 'alpha', root: 'dsh', ok: true },
+ { kind: 'skill', name: 'alpha', root: 'agents', ok: false },
+ ok('c'),
+ ])
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts b/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts
new file mode 100644
index 00000000..ee159ca8
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/store/modules/sync.utils.ts
@@ -0,0 +1,26 @@
+import type { SyncItemResult } from '../../types/index'
+
+export function syncKeyOf(item: { kind: string, name: string, root?: string }): string {
+ return `${item.kind}:${item.root ?? ''}:${item.name}`
+}
+
+export function toggleSelection(selected: ReadonlySet<string>, key: string): Set<string> {
+ const next = new Set(selected)
+ if (next.has(key))
+ next.delete(key)
+ else
+ next.add(key)
+ return next
+}
+
+export function mergeSyncResults(previous: readonly SyncItemResult[], incoming: readonly SyncItemResult[]): SyncItemResult[] {
+ const merged = [...previous]
+ const at = new Map(merged.map((item, index) => [syncKeyOf(item), index]))
+ for (const item of incoming) {
+ const key = syncKeyOf(item)
+ const index = at.get(key) ?? merged.length
+ at.set(key, index)
+ merged[index] = item
+ }
+ return merged
+}
diff --git a/packages/dsh-tauri-ssh/src/client/styles/index.cssr.ts b/packages/dsh-tauri-ssh/src/client/styles/index.cssr.ts
deleted file mode 100644
index da3d4deb..00000000
--- a/packages/dsh-tauri-ssh/src/client/styles/index.cssr.ts
+++ /dev/null
@@ -1,826 +0,0 @@
-import { cssr } from 'dsh-tauri-ui/client'
-
-const { c } = cssr
-
-/**
- * SSH-machines settings section styles (css-render tree, mounted once by the
- * client apply through ctx.effect). Ported 1:1 from the former CSS Modules
- * sheet: the official primitives (Button / Input / StateDot / Modal / Pill)
- * draw the controls; this tree keeps only layout and token alignment —
- * 14/22 body, 12/18 caption, hairline `border-l2` cards, and the few custom
- * visuals the primitives do not own (the hollow idle dot, the color
- * swatches, the tint switch). Every color resolves through a `--dsw-alias-*`
- * token, so light and dark themes both work without literals.
- *
- * Class names are flat with the plugin prefix (`dshp-ssh-*`); the TSX side
- * consumes them through the `cls` map in `./index.ts` — never hand-write the
- * prefixed strings in components.
- */
-export default c([
-
- c('.dshp-ssh-section', {
- display: 'flex',
- flexDirection: 'column',
- gap: '12px',
- /* 与 dsh-tauri-ui 的 panel-page 同宽(960px):760px 在宽窗口下会挤成一条窄栏 */
- maxWidth: '960px',
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- c('.dshp-ssh-title', {
- margin: 0,
- fontSize: '18px',
- lineHeight: '28px',
- fontWeight: 600,
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- c('.dshp-ssh-intro', {
- margin: 0,
- fontSize: '13px',
- lineHeight: '20px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- /* The section head: title/intro left, page actions right. */
- c('.dshp-ssh-section-head', {
- display: 'flex',
- alignItems: 'flex-start',
- justifyContent: 'space-between',
- gap: '12px',
- flexWrap: 'wrap',
- }),
-
- /* 合并后的 SSH 分区:标签条 + 面板。面板自身带页头,标签条只负责切换。 */
- c('.dshp-ssh-tabs', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flexWrap: 'wrap',
- }),
-
- c('.dshp-ssh-tab-panel', {
- display: 'flex',
- flexDirection: 'column',
- gap: '12px',
- minWidth: 0,
- }, [
- c('&[hidden]', {
- display: 'none',
- }),
- ]),
-
- /* 未启用时的 Hero:Icon / 描述 / 开启按钮,居中成一张卡。 */
- c('.dshp-ssh-hero', {
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '12px',
- marginTop: '4px',
- padding: '40px 24px',
- border: '0.5px solid var(--dsw-alias-border-l2)',
- borderRadius: '12px',
- background: 'var(--dsw-alias-bg-layer-1)',
- textAlign: 'center',
- }),
-
- c('.dshp-ssh-hero-icon', {
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- width: '44px',
- height: '44px',
- borderRadius: '50%',
- background: 'var(--dsw-alias-surface-tinted)',
- color: 'var(--dsw-alias-brand-primary)',
- }),
-
- c('.dshp-ssh-hero-title', {
- margin: 0,
- fontSize: '22px',
- lineHeight: '32px',
- fontWeight: 600,
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- c('.dshp-ssh-hero-hint', {
- margin: 0,
- maxWidth: '460px',
- fontSize: '13px',
- lineHeight: '21px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- /* The page chrome: refresh / add. */
- c('.dshp-ssh-chrome', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flexWrap: 'wrap',
- flexShrink: 0,
- }),
-
- /* The danger seat of an otherwise primitive button (token-aligned color). */
- c('.dshp-ssh-danger-action', {
- color: 'var(--dsw-alias-state-error-primary)',
- }),
-
- /* The step rail: compact phase chips of the in-flight operation. */
- c('.dshp-ssh-step-rail', {
- display: 'inline-flex',
- gap: '4px',
- margin: '0 0 0 8px',
- padding: 0,
- listStyle: 'none',
- verticalAlign: 'middle',
- }),
- c('.dshp-ssh-step-done', {
- fontSize: '11px',
- lineHeight: '16px',
- padding: '0 6px',
- borderRadius: '999px',
- color: 'var(--dsw-alias-label-tertiary)',
- border: '1px solid var(--dsw-alias-line-secondary, currentColor)',
- }),
- c('.dshp-ssh-step-current', {
- fontSize: '11px',
- lineHeight: '16px',
- padding: '0 6px',
- borderRadius: '999px',
- color: 'var(--dsw-alias-state-warning-primary, #d48806)',
- border: '1px solid currentColor',
- }),
-
- /* The machine list: one surface, hairline dividers between rows. */
- c('.dshp-ssh-rows', {
- listStyle: 'none',
- margin: '12px 0 0',
- padding: 0,
- display: 'flex',
- flexDirection: 'column',
- border: '1px solid var(--dsw-alias-border-l2)',
- borderRadius: '12px',
- background: 'var(--dsw-alias-bg-layer-3)',
- overflow: 'hidden',
- }),
-
- /* The read-only ~/.ssh/config group header. */
- c('.dshp-ssh-group', {
- display: 'flex',
- flexDirection: 'column',
- gap: '2px',
- marginTop: '12px',
- }),
-
- c('.dshp-ssh-group-title', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- fontWeight: 500,
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-group-hint', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- c('.dshp-ssh-row-card', {
- padding: '10px 14px',
- display: 'flex',
- flexDirection: 'column',
- gap: '8px',
- /* tintBorder 的机器:左侧 2px 标识色条(inline style 上色)。 */
- borderLeft: '2px solid transparent',
- }, [
- c('& + &', {
- borderTop: '1px solid var(--dsw-alias-border-l2)',
- }),
- ]),
-
- c('.dshp-ssh-row-head', {
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- }),
-
- c('.dshp-ssh-row-identity', {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '6px',
- minWidth: 0,
- }),
-
- c('.dshp-ssh-row-name', {
- fontSize: '14px',
- lineHeight: '22px',
- fontWeight: 500,
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- /* The host as a pill annotation on the name (the settings badge idiom). */
- c('.dshp-ssh-row-tag', {
- flex: 'none',
- padding: '2px 8px',
- border: 'none',
- borderRadius: '999px',
- background: 'var(--dsw-alias-bg-module-platform)',
- fontSize: '11px',
- lineHeight: '16px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- /* Connection state caption text (the dot itself is StateDot). */
- c('.dshp-ssh-status', {
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- /* The hollow idle dot: the one connection state StateDot has no glyph for. */
- c('.dshp-ssh-state-dot', {
- position: 'relative',
- display: 'inline-block',
- flex: 'none',
- width: '8px',
- height: '8px',
- borderRadius: '50%',
- background: 'currentColor',
- color: 'var(--dsw-alias-label-caption)',
- }, [
- c('&::after', {
- content: '\'\'',
- position: 'absolute',
- inset: '25%',
- borderRadius: '50%',
- background: 'currentColor',
- }),
- ]),
-
- /* Identity color pip next to the machine name. */
- c('.dshp-ssh-color-pip', {
- display: 'inline-block',
- flex: 'none',
- width: '10px',
- height: '10px',
- borderRadius: '50%',
- boxShadow: 'inset 0 0 0 1px rgb(0 0 0 / 12%)',
- }),
-
- /* The appearance row: swatches + the tint-border switch. */
- c('.dshp-ssh-appearance', {
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- flexWrap: 'wrap',
- }),
-
- c('.dshp-ssh-swatches', {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '6px',
- flexWrap: 'wrap',
- }),
-
- c('.dshp-ssh-swatch', {
- boxSizing: 'border-box',
- width: '20px',
- height: '20px',
- padding: 0,
- border: '1px solid var(--dsw-alias-border-l2)',
- borderRadius: '50%',
- background: 'var(--swatch-color)',
- cursor: 'pointer',
- }, [
- c('&:hover', {
- borderColor: 'var(--dsw-alias-border-l4)',
- }),
- c('&[data-selected=\'true\']', {
- outline: '2px solid var(--dsw-alias-brand-primary)',
- outlineOffset: '2px',
- }),
- ]),
-
- /* The "default" reset swatch: hollow with a diagonal strike. */
- c('.dshp-ssh-swatch-none', {
- background: 'linear-gradient(to top right, transparent calc(50% - 1px), var(--dsw-alias-label-tertiary), transparent calc(50% + 1px))',
- }),
-
- c('.dshp-ssh-switch-row', {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '8px',
- marginLeft: '4px',
- }),
-
- /* The hand-rolled toggle (the SubagentModelSelectionCard vocabulary). */
- c('.dshp-ssh-switch', {
- position: 'relative',
- width: '36px',
- height: '20px',
- padding: 0,
- border: 'none',
- borderRadius: '10px',
- background: 'var(--dsw-alias-border-l3)',
- cursor: 'pointer',
- transition: 'background 0.15s var(--ds-ease-in-out)',
- }, [
- c('&::after', {
- content: '\'\'',
- position: 'absolute',
- top: '2px',
- left: '2px',
- width: '16px',
- height: '16px',
- borderRadius: '50%',
- background: 'var(--dsw-alias-bg-layer-1)',
- boxShadow: '0 1px 2px rgb(0 0 0 / 20%)',
- transition: 'transform 0.15s var(--ds-ease-in-out)',
- }),
- c('&[aria-checked=\'true\']', {
- background: 'var(--dsw-alias-state-business-primary)',
- }, [
- c('&::after', {
- transform: 'translateX(16px)',
- }),
- ]),
- c('&:disabled', {
- opacity: 0.4,
- cursor: 'default',
- }),
- ]),
-
- c('.dshp-ssh-row-actions', {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '4px',
- marginLeft: 'auto',
- }),
-
- /* The inline editor: an indented分区 with a hairline top divider. */
- c('.dshp-ssh-editor', {
- margin: '2px 0 4px',
- paddingTop: '12px',
- borderTop: '1px solid var(--dsw-alias-border-l2)',
- display: 'flex',
- flexDirection: 'column',
- gap: '12px',
- }),
-
- /* The editor's action row: hint left, cancel/save right. */
- c('.dshp-ssh-editor-actions', {
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'flex-end',
- gap: '8px',
- }, [
- c('.dshp-ssh-hint', {
- marginRight: 'auto',
- }),
- ]),
-
- /*
- * The editor/add form track: 12 explicit columns so字段能按分组真正并排
- * (原来的 auto-fit + minmax(170px) 会按可用宽度重新折行,8 个字段排出
- * 锯齿状的对齐,也永远用不满宽窗口)。每个字段自带 span 类,窄窗口下由
- * 下面的 media 查询降级为两列 / 单列。
- */
- c('.dshp-ssh-grid', {
- display: 'grid',
- gridTemplateColumns: 'repeat(12, minmax(0, 1fr))',
- gap: '10px 12px',
- }),
-
- c('.dshp-ssh-span-3', { gridColumn: 'span 3' }),
- c('.dshp-ssh-span-4', { gridColumn: 'span 4' }),
- c('.dshp-ssh-span-5', { gridColumn: 'span 5' }),
- c('.dshp-ssh-span-6', { gridColumn: 'span 6' }),
- c('.dshp-ssh-span-8', { gridColumn: 'span 8' }),
- c('.dshp-ssh-span-12', { gridColumn: 'span 12' }),
-
- c('@media (max-width: 760px)', [
- c('.dshp-ssh-grid', { gridTemplateColumns: 'repeat(6, minmax(0, 1fr))' }),
- c('.dshp-ssh-span-3', { gridColumn: 'span 3' }),
- c('.dshp-ssh-span-4', { gridColumn: 'span 3' }),
- c('.dshp-ssh-span-5', { gridColumn: 'span 3' }),
- c('.dshp-ssh-span-6', { gridColumn: 'span 3' }),
- c('.dshp-ssh-span-8', { gridColumn: 'span 6' }),
- c('.dshp-ssh-span-12', { gridColumn: 'span 6' }),
- ]),
-
- c('@media (max-width: 520px)', [
- c('.dshp-ssh-field', { gridColumn: 'span 6' }),
- ]),
-
- c('.dshp-ssh-field', {
- display: 'flex',
- flexDirection: 'column',
- gap: '6px',
- /* grid 项默认 min-width:auto:长占位符/命令会把整列撑破,必须显式收紧 */
- minWidth: 0,
- }),
-
- c('.dshp-ssh-field-label', {
- fontSize: '12px',
- lineHeight: '18px',
- fontWeight: 500,
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- /*
- * The Input primitive draws the box; the field makes it fill the grid cell.
- * `border-box` is load-bearing: the primitive's `.wrap` is content-box, so a
- * bare `width: 100%` would add its padding/border on top of the track width
- * and bleed ~18px into the neighbouring column (adjacent inputs overlapped).
- */
- c('.dshp-ssh-field-input', {
- boxSizing: 'border-box',
- width: '100%',
- }),
-
- /* Per-machine status lines. */
- c('.dshp-ssh-status-error', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-state-error-primary)',
- }),
-
- c('.dshp-ssh-link', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- fontFamily: 'var(--ds-font-family-code)',
- color: 'var(--dsw-alias-label-tertiary)',
- overflowWrap: 'anywhere',
- }),
-
- /* The streaming log surface (machine.events lines, or the progress log). */
- c('.dshp-ssh-log-stream', {
- margin: 0,
- maxHeight: '160px',
- overflow: 'auto',
- whiteSpace: 'pre-wrap',
- overflowWrap: 'anywhere',
- fontFamily: 'var(--ds-font-family-code)',
- fontSize: '11px',
- lineHeight: '16px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- /* The one-click install surface (dsh missing on the remote). */
- c('.dshp-ssh-install-box', {
- display: 'flex',
- flexDirection: 'column',
- gap: '8px',
- padding: '10px 12px',
- border: '1px solid var(--dsw-alias-border-l2)',
- borderRadius: '8px',
- background: 'var(--dsw-alias-surface-tinted)',
- }),
-
- c('.dshp-ssh-install-hint', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-install-note', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- /* Page-level banners. */
- c('.dshp-ssh-notice', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-error', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-state-error-primary)',
- }),
-
- c('.dshp-ssh-hint', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- c('.dshp-ssh-empty', {
- margin: 0,
- padding: '12px',
- border: '1px dashed var(--dsw-alias-border-l3)',
- borderRadius: '8px',
- textAlign: 'center',
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- /* The load-failure block: empty state plus the retry affordance. */
- c('.dshp-ssh-empty-block', {
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'flex-start',
- gap: '8px',
- }),
-
- /*
- * 远端会话页(本实例自己就是 SSH 目标):整个分区只剩这张告示卡——机器
- * 列表、添加/刷新全部让位,标题刻意放大到页面级,一眼看清「这里没有可管
- * 理的东西,回发起端去配」。
- */
- c('.dshp-ssh-remote-card', {
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'center',
- gap: '12px',
- marginTop: '4px',
- padding: '40px 24px',
- border: '0.5px solid var(--dsw-alias-border-l2)',
- borderRadius: '12px',
- background: 'var(--dsw-alias-bg-layer-1)',
- textAlign: 'center',
- }),
-
- c('.dshp-ssh-remote-icon', {
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- width: '44px',
- height: '44px',
- borderRadius: '50%',
- background: 'var(--dsw-alias-surface-tinted)',
- color: 'var(--dsw-alias-state-success-primary)',
- }),
-
- c('.dshp-ssh-remote-title', {
- margin: 0,
- fontSize: '22px',
- lineHeight: '32px',
- fontWeight: 600,
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- c('.dshp-ssh-remote-hint', {
- margin: 0,
- maxWidth: '460px',
- fontSize: '13px',
- lineHeight: '21px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-remote-note', {
- margin: 0,
- maxWidth: '460px',
- padding: '8px 12px',
- borderRadius: '8px',
- background: 'var(--dsw-alias-surface-tinted)',
- fontSize: '12px',
- lineHeight: '19px',
- color: 'var(--dsw-alias-label-tertiary)',
- }),
-
- /* The sync page: target chips, selection rows, progress, outcomes. */
- c('.dshp-ssh-sync-targets', {
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- flexWrap: 'wrap',
- }),
-
- /* A target chip's inner line: connection dot + machine name. */
- c('.dshp-ssh-sync-chip', {
- display: 'inline-flex',
- alignItems: 'center',
- gap: '6px',
- }),
-
- c('.dshp-ssh-sync-toolbar', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flexWrap: 'wrap',
- paddingTop: '2px',
- }),
-
- c('.dshp-ssh-sync-count', {
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-sync-group', {
- display: 'flex',
- flexDirection: 'column',
- gap: '6px',
- }),
-
- c('.dshp-ssh-sync-group-head', {
- display: 'flex',
- alignItems: 'center',
- gap: '6px',
- }),
-
- c('.dshp-ssh-sync-items', {
- listStyle: 'none',
- margin: 0,
- padding: 0,
- display: 'flex',
- flexDirection: 'column',
- gap: '2px',
- }),
-
- c('.dshp-ssh-sync-item', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flexWrap: 'wrap',
- }),
-
- /*
- * One selectable row: the whole line is the hit target (checkbox + name +
- * metadata), so ticking does not require hitting a 12px box. Hover/focus
- * reuse the interactive tokens the primitives use.
- */
- c('.dshp-ssh-sync-row', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flex: 1,
- minWidth: 0,
- padding: '5px 8px',
- border: 0,
- borderRadius: '6px',
- background: 'transparent',
- color: 'inherit',
- font: 'inherit',
- textAlign: 'left',
- cursor: 'pointer',
- }),
-
- c('.dshp-ssh-sync-row:hover', {
- background: 'var(--dsw-alias-interactive-bg-hover)',
- }),
-
- c('.dshp-ssh-sync-row:disabled', {
- cursor: 'not-allowed',
- opacity: 0.6,
- }),
-
- c('.dshp-ssh-sync-box', {
- display: 'inline-flex',
- alignItems: 'center',
- justifyContent: 'center',
- flexShrink: 0,
- width: '14px',
- height: '14px',
- border: '1px solid var(--dsw-alias-border-l4)',
- borderRadius: '4px',
- color: 'var(--dsw-alias-label-primary-foreground)',
- }),
-
- c('.dshp-ssh-sync-row[aria-checked="true"] .dshp-ssh-sync-box', {
- borderColor: 'var(--dsw-alias-brand-primary)',
- background: 'var(--dsw-alias-brand-primary)',
- }),
-
- /* 名称与「为何不可同步」的两行文本列:原因收进行内,行宽才对得齐 */
- c('.dshp-ssh-sync-text', {
- display: 'flex',
- flexDirection: 'column',
- gap: '1px',
- flex: 1,
- minWidth: 0,
- }),
-
- c('.dshp-ssh-sync-name', {
- fontSize: '13px',
- lineHeight: '20px',
- color: 'var(--dsw-alias-label-primary)',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- }),
-
- c('.dshp-ssh-sync-meta', {
- flexShrink: 0,
- marginLeft: 'auto',
- paddingLeft: '8px',
- maxWidth: '40%',
- fontSize: '11px',
- lineHeight: '16px',
- color: 'var(--dsw-alias-label-tertiary)',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- }),
-
- c('.dshp-ssh-sync-reason', {
- fontSize: '11px',
- lineHeight: '16px',
- color: 'var(--dsw-alias-state-warning-primary, var(--dsw-alias-label-tertiary))',
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- }),
-
- c('.dshp-ssh-sync-actions', {
- display: 'flex',
- alignItems: 'center',
- gap: '10px',
- flexWrap: 'wrap',
- paddingTop: '2px',
- }),
-
- c('.dshp-ssh-sync-progress', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flex: 1,
- minWidth: '220px',
- }),
-
- c('.dshp-ssh-sync-bar', {
- display: 'block',
- flex: 1,
- height: '4px',
- borderRadius: '2px',
- background: 'var(--dsw-alias-border-l2)',
- overflow: 'hidden',
- }),
-
- c('.dshp-ssh-sync-bar-fill', {
- display: 'block',
- height: '100%',
- borderRadius: '2px',
- background: 'var(--dsw-alias-brand-primary)',
- transition: 'width 200ms ease',
- }),
-
- c('.dshp-ssh-sync-progress-text', {
- flexShrink: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-sync-results', {
- display: 'flex',
- flexDirection: 'column',
- alignItems: 'flex-start',
- gap: '6px',
- marginTop: '4px',
- paddingTop: '12px',
- borderTop: '1px solid var(--dsw-alias-border-l2)',
- }),
-
- c('.dshp-ssh-sync-summary', {
- margin: 0,
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-label-secondary)',
- }),
-
- c('.dshp-ssh-sync-result', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- flexWrap: 'wrap',
- }),
-
- c('.dshp-ssh-sync-result-name', {
- fontSize: '12px',
- lineHeight: '18px',
- fontWeight: 500,
- color: 'var(--dsw-alias-label-primary)',
- }),
-
- /* 「查看输出」开关:行内小按钮,展开后是卡片同款的滚动日志块 */
- c('.dshp-ssh-sync-log-toggle', {
- padding: '0',
- border: 0,
- background: 'transparent',
- color: 'var(--dsw-alias-state-business-primary)',
- fontSize: '12px',
- lineHeight: '18px',
- cursor: 'pointer',
- }),
-
- c('.dshp-ssh-sync-ok', {
- fontSize: '12px',
- lineHeight: '18px',
- color: 'var(--dsw-alias-state-success-primary)',
- }),
-])
diff --git a/packages/dsh-tauri-ssh/src/client/styles/index.ts b/packages/dsh-tauri-ssh/src/client/styles/index.ts
deleted file mode 100644
index 36733413..00000000
--- a/packages/dsh-tauri-ssh/src/client/styles/index.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-/**
- * Style barrel of the SSH-machines settings page: the css-render tree (in
- * `index.cssr.ts`), its mount id, and the `cls` map the components consume.
- * Class names keep the plugin prefix (`dshp-ssh-*`); components never
- * hand-write the prefixed strings.
- * @module dsh-tauri-ssh/client/styles
- */
-
-import sshStyle from './index.cssr'
-
-/** The mounted stylesheet id (style tag identity, plugin-prefixed). */
-export const SSH_STYLE_ID = 'dsh-tauri-ssh-styles'
-
-/** The css-render tree, mounted once by the client apply via ctx.effect. */
-export { sshStyle }
-
-/**
- * Logical class map (the former CSS-Modules keys) → prefixed class names.
- * Keys mirror the old `css.*` references one-to-one so the components read
- * unchanged in shape.
- */
-export const cls = {
- section: 'dshp-ssh-section',
- title: 'dshp-ssh-title',
- intro: 'dshp-ssh-intro',
- tabs: 'dshp-ssh-tabs',
- tabPanel: 'dshp-ssh-tab-panel',
- hero: 'dshp-ssh-hero',
- heroIcon: 'dshp-ssh-hero-icon',
- heroTitle: 'dshp-ssh-hero-title',
- heroHint: 'dshp-ssh-hero-hint',
- chrome: 'dshp-ssh-chrome',
- dangerAction: 'dshp-ssh-danger-action',
- sectionHead: 'dshp-ssh-section-head',
- editorActions: 'dshp-ssh-editor-actions',
- stepRail: 'dshp-ssh-step-rail',
- stepDone: 'dshp-ssh-step-done',
- stepCurrent: 'dshp-ssh-step-current',
- rows: 'dshp-ssh-rows',
- group: 'dshp-ssh-group',
- groupTitle: 'dshp-ssh-group-title',
- groupHint: 'dshp-ssh-group-hint',
- rowCard: 'dshp-ssh-row-card',
- rowHead: 'dshp-ssh-row-head',
- rowIdentity: 'dshp-ssh-row-identity',
- rowName: 'dshp-ssh-row-name',
- rowTag: 'dshp-ssh-row-tag',
- status: 'dshp-ssh-status',
- stateDot: 'dshp-ssh-state-dot',
- colorPip: 'dshp-ssh-color-pip',
- appearance: 'dshp-ssh-appearance',
- swatches: 'dshp-ssh-swatches',
- swatch: 'dshp-ssh-swatch',
- swatchNone: 'dshp-ssh-swatch-none',
- switchRow: 'dshp-ssh-switch-row',
- switch: 'dshp-ssh-switch',
- rowActions: 'dshp-ssh-row-actions',
- editor: 'dshp-ssh-editor',
- grid: 'dshp-ssh-grid',
- span3: 'dshp-ssh-span-3',
- span4: 'dshp-ssh-span-4',
- span5: 'dshp-ssh-span-5',
- span6: 'dshp-ssh-span-6',
- span8: 'dshp-ssh-span-8',
- span12: 'dshp-ssh-span-12',
- field: 'dshp-ssh-field',
- fieldLabel: 'dshp-ssh-field-label',
- fieldInput: 'dshp-ssh-field-input',
- statusError: 'dshp-ssh-status-error',
- link: 'dshp-ssh-link',
- logStream: 'dshp-ssh-log-stream',
- installBox: 'dshp-ssh-install-box',
- installHint: 'dshp-ssh-install-hint',
- installNote: 'dshp-ssh-install-note',
- notice: 'dshp-ssh-notice',
- error: 'dshp-ssh-error',
- hint: 'dshp-ssh-hint',
- empty: 'dshp-ssh-empty',
- emptyBlock: 'dshp-ssh-empty-block',
- remoteCard: 'dshp-ssh-remote-card',
- remoteIcon: 'dshp-ssh-remote-icon',
- remoteTitle: 'dshp-ssh-remote-title',
- remoteHint: 'dshp-ssh-remote-hint',
- remoteNote: 'dshp-ssh-remote-note',
- syncTargets: 'dshp-ssh-sync-targets',
- syncChip: 'dshp-ssh-sync-chip',
- syncToolbar: 'dshp-ssh-sync-toolbar',
- syncCount: 'dshp-ssh-sync-count',
- syncGroup: 'dshp-ssh-sync-group',
- syncGroupHead: 'dshp-ssh-sync-group-head',
- syncItems: 'dshp-ssh-sync-items',
- syncItem: 'dshp-ssh-sync-item',
- syncRow: 'dshp-ssh-sync-row',
- syncBox: 'dshp-ssh-sync-box',
- syncText: 'dshp-ssh-sync-text',
- syncName: 'dshp-ssh-sync-name',
- syncMeta: 'dshp-ssh-sync-meta',
- syncReason: 'dshp-ssh-sync-reason',
- syncActions: 'dshp-ssh-sync-actions',
- syncProgress: 'dshp-ssh-sync-progress',
- syncBar: 'dshp-ssh-sync-bar',
- syncBarFill: 'dshp-ssh-sync-bar-fill',
- syncProgressText: 'dshp-ssh-sync-progress-text',
- syncResults: 'dshp-ssh-sync-results',
- syncSummary: 'dshp-ssh-sync-summary',
- syncResult: 'dshp-ssh-sync-result',
- syncResultName: 'dshp-ssh-sync-result-name',
- syncOk: 'dshp-ssh-sync-ok',
- syncLogToggle: 'dshp-ssh-sync-log-toggle',
-} as const
diff --git a/packages/dsh-tauri-ssh/src/client/test-utils/client-mock.ts b/packages/dsh-tauri-ssh/src/client/test-utils/client-mock.ts
new file mode 100644
index 00000000..c6b5b1d9
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/test-utils/client-mock.ts
@@ -0,0 +1,76 @@
+import type { FetchOptions } from '../../../../dsh-tauri/src/client/request/index.ts'
+import { useListenParent } from '../../../../dsh-tauri/src/client/hooks/use-listen-parent.ts'
+import { defineLocale } from '../../../../dsh-tauri/src/client/locale/index.ts'
+import { uniq } from '../../../../dsh-tauri/src/client/modules/lodash-es.ts'
+import { cn } from '../../../../dsh-tauri/src/client/modules/tailwind-variants.ts'
+import { defineStore, useStore } from '../../../../dsh-tauri/src/client/modules/valtio-define.ts'
+import { defineRegister } from '../../../../dsh-tauri/src/client/register/index.ts'
+import { defaultErrorMessage, parseJsonResponse } from '../../../../dsh-tauri/src/client/request/index.utils.ts'
+import { invoke } from '../../../../dsh-tauri/src/client/service/invoke.ts'
+import { listenParent } from '../../../../dsh-tauri/src/client/service/listen-parent.ts'
+
+export interface WireCall {
+ url: string
+ http: string
+ body: Record<string, unknown>
+ params: Record<string, unknown>
+}
+
+export interface WireReply {
+ status: number
+ body?: unknown
+}
+
+export const replies = {
+ ok: (value: unknown): WireReply => ({ status: 200, body: value }),
+ fail: (message: string, status = 400): WireReply => ({ status, body: { error: message } }),
+ http: (status: number): WireReply => ({ status }),
+ empty: (): WireReply => ({ status: 200, body: '' }),
+}
+
+export const sent: WireCall[] = []
+
+export const wire: { reply: (call: WireCall) => WireReply | Promise<WireReply> } = {
+ reply: (_call: WireCall): WireReply => replies.ok({}),
+}
+
+export function answer(reply: (call: WireCall) => WireReply | Promise<WireReply>): void {
+ wire.reply = reply
+}
+
+export function resetWire(): void {
+ wire.reply = () => replies.ok({})
+ sent.length = 0
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null
+}
+
+function ofetch(path: string, options: FetchOptions = {}): Promise<unknown> {
+ const call: WireCall = {
+ url: `${options.baseURL ?? ''}${path}`,
+ http: String(options.method ?? 'get').toUpperCase(),
+ body: isRecord(options.body) ? options.body : {},
+ params: isRecord(options.params) ? options.params : {},
+ }
+ sent.push(call)
+ return Promise.resolve().then(() => wire.reply(call)).then((reply) => {
+ if (reply.status < 200 || reply.status >= 300)
+ throw new Error(defaultErrorMessage(reply.status, reply.body))
+ return typeof reply.body === 'string' ? parseJsonResponse(reply.body) : reply.body
+ })
+}
+
+export const clientMock = {
+ cn,
+ defineLocale,
+ defineRegister,
+ defineStore,
+ invoke,
+ listenParent,
+ ofetch,
+ uniq,
+ useListenParent,
+ useStore,
+}
diff --git a/packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts b/packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts
new file mode 100644
index 00000000..1349e1cb
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/client/test-utils/ui-mock.ts
@@ -0,0 +1,95 @@
+import type { ReactNode } from 'react'
+import { createElement } from 'react'
+
+type Props = Record<string, unknown> & { children?: ReactNode }
+
+function Button({ variant: _variant, size: _size, onPress, onClick, children, ...rest }: Props & { onPress?: () => void, onClick?: () => void }): ReactNode {
+ return createElement('button', { type: 'button', ...rest, onClick: onPress ?? onClick }, children as never)
+}
+
+function Pill({ active: _active, children, ...rest }: Props): ReactNode {
+ return createElement('button', { type: 'button', ...rest }, children as never)
+}
+
+function Input(props: Props): ReactNode {
+ return createElement('input', props)
+}
+
+function Modal({ open, onClose: _onClose, closeLabel: _closeLabel, title, description, footer, children }: Props): ReactNode {
+ if (open === false)
+ return null
+ return createElement(
+ 'div',
+ { 'role': 'dialog', 'aria-label': title },
+ createElement('p', null, title as never),
+ description === undefined ? null : createElement('p', null, description as never),
+ children as never,
+ footer as never,
+ )
+}
+
+function StateDot(): ReactNode {
+ return null
+}
+
+function Globe(): ReactNode {
+ return null
+}
+
+function Icon(): ReactNode {
+ return null
+}
+
+function SegmentedControl({ options, value, onChange }: Props & {
+ options: Array<{ value: string, label: string }>
+ value: string
+ onChange: (next: string) => void
+}): ReactNode {
+ return createElement(
+ 'div',
+ { role: 'tablist' },
+ options.map(option => createElement(
+ 'button',
+ {
+ 'key': option.value,
+ 'type': 'button',
+ 'role': 'tab',
+ 'aria-selected': option.value === value,
+ 'onClick': () => onChange(option.value),
+ },
+ option.label,
+ )),
+ )
+}
+
+function Switch({ checked, onChange, label, disabled, title, className }: {
+ checked: boolean
+ onChange: (next: boolean) => void
+ label: string
+ disabled?: boolean
+ title?: string | undefined
+ className?: string | undefined
+}): ReactNode {
+ return createElement('button', {
+ 'type': 'button',
+ 'role': 'switch',
+ 'aria-checked': checked,
+ 'aria-label': label,
+ disabled,
+ title,
+ className,
+ 'onClick': () => onChange(!checked),
+ })
+}
+
+export const uiMock = {
+ Button,
+ Globe,
+ Icon,
+ Input,
+ Modal,
+ Pill,
+ SegmentedControl,
+ StateDot,
+ Switch,
+}
diff --git a/packages/dsh-tauri-ssh/src/client/types/index.ts b/packages/dsh-tauri-ssh/src/client/types/index.ts
index a8570741..400684e0 100644
--- a/packages/dsh-tauri-ssh/src/client/types/index.ts
+++ b/packages/dsh-tauri-ssh/src/client/types/index.ts
@@ -1,52 +1,110 @@
-/**
- * Structural types of the DSH client services this plugin consumes. The
- * @deepseek-ai packages are private to the harness and never published; the
- * plugin declares local mirrors of the exact surfaces it touches (shapes
- * copied from the harness's own registrants) and never imports the private
- * packages at runtime — the loader calls `apply` with the real context and
- * duck-typing does the rest.
- * @module dsh-tauri-ssh/client/types
- */
-
-/** One settings-section registration option set. */
-export interface SlotRegisterOptions {
- name: string
+export type MachineLifecycleState
+ = | 'disconnected'
+ | 'testing'
+ | 'connecting'
+ | 'connected'
+ | 'reconnecting'
+ | 'given-up'
+
+export interface ServiceResult {
+ ok: boolean
+ error?: string
+}
+
+export function isLifecycleState(value: unknown): value is MachineLifecycleState {
+ return value === 'disconnected'
+ || value === 'testing'
+ || value === 'connecting'
+ || value === 'connected'
+ || value === 'reconnecting'
+ || value === 'given-up'
+}
+
+export interface MachineRow {
id: string
- order: number
- label: () => string
- locale?: string
- inject?: () => Record<string, unknown>
-}
-
-/** The slots ledger face (a subset of the runtime SlotsService). */
-export interface SlotsService {
- inject: (name: string, contribution: () => unknown) => void
- register: (options: SlotRegisterOptions, component: unknown) => unknown
-}
-
-/** The locale face (a subset of the locale service). */
-export interface LocaleService {
- register: (ns: string, dictionaries: { zh: Record<string, string>, en: Record<string, string> }) => void
- bind: (ns: string) => (key: string) => string
-}
-
-/** The client root context this plugin's apply receives. */
-export interface UiContext {
- effect: (execute: () => (() => void) | void, label?: string) => unknown
- get: <T = unknown>(name: string) => T
- on: (name: string, listener: (...args: unknown[]) => void) => () => boolean
- slots: SlotsService
- locale: LocaleService
-}
-
-export type {
- MachineLifecycleState,
- RemoteBridge,
- SshMachineEvent,
- SyncApplyResult,
- SyncItemResult,
- SyncPluginItem,
- SyncPreview,
- SyncSkillItem,
-} from './sync'
-export { isLifecycleState } from './sync'
+ name: string
+ host: string
+ port: number
+ user: string
+ hasPassword: boolean
+ hasPassphrase: boolean
+ remotePort: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+}
+
+export interface SecretValues {
+ password?: string
+ passphrase?: string
+}
+
+export type ProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing' | 'syncing'
+
+export interface MachineStatus {
+ state: MachineLifecycleState
+ nextRetryAt?: number
+ authMethod?: 'agent' | 'key' | 'password'
+ tunnelBaseUrl?: string
+ lastError?: string
+ dshMissing?: boolean
+ progress?: { phase: ProgressPhase, attempt?: number, total?: number, item?: string, log?: string }
+}
+
+export interface MachineListSnapshot {
+ machines: MachineRow[]
+ discovered: MachineRow[]
+ statuses: Record<string, MachineStatus>
+}
+
+export interface InstallResult {
+ dshPath: string
+ credentialsCopied: boolean
+ credentialsError?: string
+}
+
+export interface SshMachineEvent {
+ seq: number
+ ts: string
+ machineId: string
+ stage: string
+ line: string
+ terminal?: 'success' | 'failed'
+ reason?: string
+}
+
+export interface SyncPluginItem {
+ name: string
+ spec: string
+ syncable: boolean
+ reason?: string
+}
+
+export interface SyncSkillItem {
+ name: string
+ root: string
+}
+
+export interface SyncPreview {
+ plugins: SyncPluginItem[]
+ skills: SyncSkillItem[]
+}
+
+export interface SyncItemResult {
+ kind: 'plugin' | 'skill'
+ name: string
+ root?: string
+ ok: boolean
+ error?: string
+ log?: string
+}
+
+export interface SyncApplyResult {
+ items: SyncItemResult[]
+}
+
+export interface RemoteBridge {
+ probe: () => Promise<unknown>
+ openWindow: (machineId: string, url: string) => Promise<unknown>
+}
diff --git a/packages/dsh-tauri-ssh/src/client/types/sync.ts b/packages/dsh-tauri-ssh/src/client/types/sync.ts
deleted file mode 100644
index 3bd01682..00000000
--- a/packages/dsh-tauri-ssh/src/client/types/sync.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * Client-side mirrors of the S4-owned sync vocabulary, the S2-owned machine
- * event channel, and the S3-owned connection-state vocabulary this panel
- * consumes (the contracts are drafted by their owners; these shapes are the
- * panel's tolerant readers of them).
- * @module dsh-tauri-ssh/client/types/sync
- */
-
-/**
- * The connection-state vocabulary (C-STATE, S3-owned): the six lifecycle
- * states a machine row can report. A `reconnecting` row also carries the
- * optional `nextRetryAt` epoch-ms field (the retry-hint source).
- */
-export type MachineLifecycleState
- = | 'disconnected'
- | 'testing'
- | 'connecting'
- | 'connected'
- | 'reconnecting'
- | 'given-up'
-
-/** Whether a raw value is one of the lifecycle states. */
-export function isLifecycleState(value: unknown): value is MachineLifecycleState {
- return value === 'disconnected'
- || value === 'testing'
- || value === 'connecting'
- || value === 'connected'
- || value === 'reconnecting'
- || value === 'given-up'
-}
-
-/**
- * One machine event from the polled `machine.events` channel (C-EVENT,
- * S2-owned): a displayable log line tagged with its pipeline stage. `seq` is
- * a per-machine space (the poll cursor is kept per machine, never mixed).
- */
-export interface SshMachineEvent {
- /** Per-machine sequence number. */
- seq: number
- /** Wall-clock timestamp (ISO-8601), passed through as the host spelled it. */
- ts: string
- machineId: string
- /** Pipeline stage; passed through unclassified (auth/reconnect need no special case). */
- stage: string
- line: string
- /** Terminal verdict, present only on the settling event of an operation. */
- terminal?: 'success' | 'failed'
- reason?: string
-}
-
-/** One plugin sync candidate (the `sync.preview` plugins list member). */
-export interface SyncPluginItem {
- name: string
- spec: string
- syncable: boolean
- reason?: string
-}
-
-/** One skill sync candidate (the `sync.preview` skills list member). */
-export interface SyncSkillItem {
- name: string
- root: string
-}
-
-/** The `sync.preview` value. */
-export interface SyncPreview {
- plugins: SyncPluginItem[]
- skills: SyncSkillItem[]
-}
-
-/** Outcome of exactly one synced item (the `sync.apply` items member). */
-export interface SyncItemResult {
- kind: 'plugin' | 'skill'
- name: string
- root?: string
- ok: boolean
- /** Operator-facing failure: cause first, tail as context. */
- error?: string
- /** The remote command's own output (trimmed), shown on demand. */
- log?: string
-}
-
-/** The `sync.apply` value. */
-export interface SyncApplyResult {
- items: SyncItemResult[]
-}
-
-/** The desktop iframe bridge face (C-BRIDGE, S5-owned commands). */
-export interface RemoteBridge {
- /** Probe whether the desktop invoke bridge answers (timeout/rejection = pure web). */
- probe: () => Promise<unknown>
- /** Ask the desktop shell to open (or focus) the machine's remote window. */
- openWindow: (machineId: string, url: string) => Promise<unknown>
-}
diff --git a/packages/dsh-tauri-ssh/src/client/utils/error.ts b/packages/dsh-tauri-ssh/src/client/utils/error.ts
index 7a35a11e..3dd15595 100644
--- a/packages/dsh-tauri-ssh/src/client/utils/error.ts
+++ b/packages/dsh-tauri-ssh/src/client/utils/error.ts
@@ -1,13 +1,6 @@
import type { SshKey } from '../locales/index'
-import { isTransportError } from '../store/index'
+import { isTransportError } from '../apis/parsers'
-/**
- * One operator-facing failure line: a transport code (route missing, empty
- * body) reads as the localized "service unavailable" notice instead of a raw
- * `SSH_API_*` code; host-provided prose renders verbatim.
- * @param message - the stored failure text.
- * @param t - the bound dictionary lookup.
- */
export function errorTextOf(message: string, t: (key: SshKey) => string): string {
return isTransportError(message) ? t('error.unavailable') : message
}
diff --git a/packages/dsh-tauri-ssh/src/client/utils/retry.ts b/packages/dsh-tauri-ssh/src/client/utils/retry.ts
index 8d425aa9..7bde26e1 100644
--- a/packages/dsh-tauri-ssh/src/client/utils/retry.ts
+++ b/packages/dsh-tauri-ssh/src/client/utils/retry.ts
@@ -1,19 +1,3 @@
-/**
- * Pure time helpers for the machine-status line. The host reports the next
- * reconnect retry as an epoch-ms instant (`nextRetryAt`, S3-owned); the UI
- * renders it as a short relative hint, so the clock math lives here as a
- * pure function (testable without React or a store).
- * @module dsh-tauri-ssh/client/utils/retry
- */
-
-/**
- * Whole seconds until the scheduled retry, rounded up so a partial second
- * still reads as a full one (a "0s" hint would look like a bug while the
- * retry has not fired yet).
- * @param nextRetryAt - the epoch-ms instant the retry fires.
- * @param nowMs - the reference clock (injected; tests pin it).
- * @returns the remaining seconds; `0` means the retry is due now or overdue.
- */
export function retrySecondsOf(nextRetryAt: number, nowMs: number): number {
return Math.max(0, Math.ceil((nextRetryAt - nowMs) / 1000))
}
diff --git a/packages/dsh-tauri-ssh/src/host/apply.test.ts b/packages/dsh-tauri-ssh/src/host/apply.test.ts
index e2242498..c540faf9 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.test.ts
@@ -1,10 +1,12 @@
-import type { Config as SshRemoteConfig } from './storage/index'
+import type { Config as SshRemoteConfig } from './config/schema'
import type { SshHostContext } from './types/index'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { apply, inject, name, SshRemoteService } from './apply'
+import { apply, inject, name } from './apply'
+import { clearHostRuntime, knownHostsFilePath, machineProfiles } from './config/runtime'
+import { machine } from './service/machine'
import { MachineId } from './types/index'
function scriptedHttpServer() {
@@ -18,6 +20,19 @@ function scriptedHttpServer() {
}
}
+const REST_ENDPOINTS = [
+ '/api/desktop/dsh-tauri-ssh/settings',
+ '/api/desktop/dsh-tauri-ssh/session/role',
+ '/api/desktop/dsh-tauri-ssh/machines',
+ '/api/desktop/dsh-tauri-ssh/machines/test',
+ '/api/desktop/dsh-tauri-ssh/machines/connect',
+ '/api/desktop/dsh-tauri-ssh/machines/disconnect',
+ '/api/desktop/dsh-tauri-ssh/machines/install',
+ '/api/desktop/dsh-tauri-ssh/machines/events',
+ '/api/desktop/dsh-tauri-ssh/sync/preview',
+ '/api/desktop/dsh-tauri-ssh/sync/apply',
+]
+
/** Plugin config without the optional overrides; defaults are exercised separately. */
const baseConfig: SshRemoteConfig = {
connectTimeoutMs: 15000,
@@ -38,12 +53,15 @@ let sshDir: string
let statePath: string
beforeEach(() => {
+ clearHostRuntime()
sshDir = mkdtempSync(join(tmpdir(), 'ssh-index-'))
statePath = join(sshDir, 'machines.json')
})
afterEach(() => {
+ vi.restoreAllMocks()
rmSync(sshDir, { recursive: true, force: true })
+ clearHostRuntime()
})
/** One scripted context: cordis-shaped surface without real cordis types. */
@@ -71,13 +89,14 @@ function readState(): { version: number, enabled: boolean, machines: Record<stri
return JSON.parse(readFileSync(statePath, 'utf8')) as { version: number, enabled: boolean, machines: Record<string, Record<string, unknown>> }
}
-/** Construct the service on a scripted webServer double. */
-function construct(config: SshRemoteConfig = baseConfig): { ctx: SshHostContext, service: SshRemoteService, disposers: Array<() => void> } {
- const { ctx, disposers } = scriptedCtx(scriptedHttpServer())
- return { ctx, service: new SshRemoteService(ctx, { ...config, sshDir, statePath }), disposers }
+/** Assemble the plugin on a scripted webServer double. */
+function construct(config: SshRemoteConfig = baseConfig, webServer = scriptedHttpServer()): { ctx: SshHostContext, webServer: ReturnType<typeof scriptedHttpServer>, service: typeof machine, disposers: Array<() => void> } {
+ const { ctx, disposers } = scriptedCtx(webServer)
+ apply(ctx, { ...config, sshDir, statePath })
+ return { ctx, webServer, service: machine, disposers }
}
-function boot(overrides: {
+async function boot(overrides: {
state?: { enabled?: boolean, machines?: Record<string, unknown> }
webServer?: ReturnType<typeof scriptedHttpServer>
config?: Partial<SshRemoteConfig>
@@ -93,11 +112,12 @@ function boot(overrides: {
statePath,
...overrides.config,
}
- const service = new SshRemoteService(ctx, config)
- return { ctx, webServer, service }
+ apply(ctx, config)
+ await machine.start()
+ return { ctx, webServer, service: machine }
}
-function machine(id: string): Record<string, unknown> {
+function row(id: string): Record<string, unknown> {
return {
id,
name: `machine-${id}`,
@@ -112,7 +132,7 @@ function machine(id: string): Record<string, unknown> {
describe('ssh-remote plugin', () => {
it('declares its plugin metadata', () => {
expect(name).toBe('dsh-tauri-ssh')
- expect(inject).toEqual(['webServer'])
+ expect(inject).toEqual(['webServer', 'connection'])
expect(apply).toEqual(expect.any(Function))
})
@@ -120,7 +140,7 @@ describe('ssh-remote plugin', () => {
const descriptor = (await import('./apply')).default
expect(descriptor).toMatchObject({
name: 'dsh-tauri-ssh',
- inject: ['webServer'],
+ inject: ['webServer', 'connection'],
Config: expect.anything(),
})
expect(descriptor.apply).toEqual(expect.any(Function))
@@ -129,14 +149,14 @@ describe('ssh-remote plugin', () => {
expect(descriptor.apply).toBe(apply)
})
- it('mounts the /api-ssh route without any settings service', () => {
- const { webServer } = boot()
- expect(webServer.routes).toMatchObject([{ kind: 'prefix', path: '/api-ssh' }])
- expect(webServer.routes[0]?.handler).toEqual(expect.any(Function))
+ it('mounts the REST routes without any settings service', async () => {
+ const { webServer } = await boot()
+ expect(webServer.routes.map(route => `${route.kind} ${route.path}`)).toEqual(REST_ENDPOINTS.map(path => `exact ${path}`))
+ expect(webServer.routes.map(route => typeof route.handler)).toEqual(REST_ENDPOINTS.map(() => 'function'))
})
it('starts switched off and persists the enable switch', async () => {
- const { service } = boot()
+ const { service } = await boot()
expect(service.enabled()).toBe(false)
await service.setEnabled(true)
expect(service.enabled()).toBe(true)
@@ -146,41 +166,41 @@ describe('ssh-remote plugin', () => {
})
it('disconnects every machine when the feature is switched off', async () => {
- const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
- const dispose = vi.spyOn(service.manager, 'dispose').mockResolvedValue(undefined)
+ const { service } = await boot({ state: { enabled: true, machines: { a: row('a') } } })
+ const dispose = vi.spyOn(service, 'dispose').mockResolvedValue(undefined)
await service.setEnabled(true)
expect(dispose).not.toHaveBeenCalled()
await service.setEnabled(false)
expect(dispose).toHaveBeenCalledTimes(1)
})
- it('loads machine profiles from the state document', () => {
- const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
+ it('loads machine profiles from the state document', async () => {
+ const { service } = await boot({ state: { enabled: true, machines: { a: row('a') } } })
const views = service.profileViews()
expect(views.map(view => view.id)).toEqual(['a'])
expect(views[0]).toMatchObject({ name: 'machine-a', hasPassword: true })
expect(views[0]).not.toHaveProperty('password')
})
- it('reads a corrupt or absent document as the default state', () => {
+ it('reads a corrupt or absent document as the default state', async () => {
writeFileSync(statePath, '{ not json')
- const corrupt = boot()
+ const corrupt = await boot()
expect(corrupt.service.enabled()).toBe(false)
expect(corrupt.service.profileViews()).toEqual([])
rmSync(statePath, { force: true })
- const absent = boot()
+ const absent = await boot()
expect(absent.service.enabled()).toBe(false)
expect(absent.service.profileViews()).toEqual([])
})
- it('drops a stored row whose dict key disagrees with the profile id', () => {
- const { service } = boot({ state: { enabled: true, machines: { b: machine('a') } } })
+ it('drops a stored row whose dict key disagrees with the profile id', async () => {
+ const { service } = await boot({ state: { enabled: true, machines: { b: row('a') } } })
expect(service.profileViews()).toEqual([])
})
it('refreshes the manager when the stored machines change', async () => {
- const { service } = boot()
+ const { service } = await boot()
await service.save('a' as never, { name: 'alpha', host: '10.0.0.1', port: 22, user: 'root', remotePort: 3080 })
await service.save('b' as never, { name: 'beta', host: '10.0.0.2', port: 22, user: 'root', remotePort: 3080 })
expect(service.profileViews()).toHaveLength(2)
@@ -189,23 +209,23 @@ describe('ssh-remote plugin', () => {
})
it('exposes the manager connection plane', async () => {
- const { service } = boot()
+ const { service } = await boot()
expect(service.status('ghost' as never)).toEqual({ machineId: 'ghost' as never, state: 'disconnected' })
expect(service.profileViews()).toEqual([])
await service.disconnect('a' as never)
})
it('forwards installs to the manager', async () => {
- const { service } = boot()
- const install = vi.spyOn(service.manager, 'install')
+ const { service } = await boot()
+ const install = vi.spyOn(service, 'install')
.mockResolvedValue({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true })
- const result = await service.install(MachineId('a'))
+ const result = await service.install(MachineId('a'), undefined)
expect(install).toHaveBeenCalledWith(MachineId('a'), undefined)
expect(result).toEqual({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true })
})
it('saves a machine into the state document and refreshes the manager', async () => {
- const { service } = boot()
+ const { service } = await boot()
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -229,7 +249,7 @@ describe('ssh-remote plugin', () => {
})
it('keeps stored secrets on save unless rewritten', async () => {
- const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } } })
+ const { service } = await boot({ state: { enabled: true, machines: { a: row('a') } } })
await service.save('a' as never, {
name: 'alpha-2',
host: '10.0.0.1',
@@ -242,12 +262,12 @@ describe('ssh-remote plugin', () => {
})
it('clears optional appearance fields on save and keeps sibling machines intact', async () => {
- const { service } = boot({
+ const { service } = await boot({
state: {
enabled: true,
machines: {
- a: { ...machine('a'), color: '#ff0000', tintBorder: true, startCommand: 'custom dsh web' },
- b: machine('b'),
+ a: { ...row('a'), color: '#ff0000', tintBorder: true, startCommand: 'custom dsh web' },
+ b: row('b'),
},
},
})
@@ -269,8 +289,8 @@ describe('ssh-remote plugin', () => {
})
it('keeps stored secrets on save and stores the start command', async () => {
- const { service } = boot({
- state: { enabled: true, machines: { a: { ...machine('a'), passphrase: 'OLD-PHRASE' } } },
+ const { service } = await boot({
+ state: { enabled: true, machines: { a: { ...row('a'), passphrase: 'OLD-PHRASE' } } },
})
await service.save('a' as never, {
name: 'alpha',
@@ -290,7 +310,7 @@ describe('ssh-remote plugin', () => {
})
it('stores the remote profile name on save and clears it when the row omits it', async () => {
- const { service } = boot({ state: { enabled: true, machines: { a: { ...machine('a'), profileName: 'alpha' } } } })
+ const { service } = await boot({ state: { enabled: true, machines: { a: { ...row('a'), profileName: 'alpha' } } } })
await service.save('a' as never, {
name: 'alpha',
host: '10.0.0.1',
@@ -313,8 +333,8 @@ describe('ssh-remote plugin', () => {
})
it('keeps whichever stored secrets exist and rewrites only typed ones', async () => {
- const { service } = boot({
- state: { enabled: true, machines: { a: { ...machine('a'), password: undefined, passphrase: 'OLD-PHRASE' } } },
+ const { service } = await boot({
+ state: { enabled: true, machines: { a: { ...row('a'), password: undefined, passphrase: 'OLD-PHRASE' } } },
})
await service.save('a' as never, {
name: 'alpha',
@@ -341,7 +361,7 @@ describe('ssh-remote plugin', () => {
'Host *.example.com',
'Host !banned',
].join('\n'))
- const { service } = boot()
+ const { service } = await boot()
const views = await service.discoveredViews()
expect(views.map(view => view.id)).toEqual(['ci', 'dev'])
expect(views[1]).toMatchObject({
@@ -358,59 +378,57 @@ describe('ssh-remote plugin', () => {
})
it('lists no discovered machines without a config file', async () => {
- const { service } = boot()
+ const { service } = await boot()
expect(await service.discoveredViews()).toEqual([])
})
it('lets a manual machine shadow a config alias', async () => {
writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n')
- const { service } = boot({ state: { enabled: true, machines: { dev: { ...machine('dev'), host: '10.1.1.1' } } } })
+ const { service } = await boot({ state: { enabled: true, machines: { dev: { ...row('dev'), host: '10.1.1.1' } } } })
expect((await service.discoveredViews()).map(view => view.id)).toEqual([])
expect(service.profileViews().map(view => view.id)).toEqual(['dev'])
})
it('syncs discovered aliases into the manager profile map', async () => {
writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n Port 2222\n')
- const { service } = boot()
- await service.disconnect(MachineId('dev'))
- const views = service.manager.profileViews()
- expect(views.map(view => view.id)).toEqual(['dev'])
- expect(views[0]).toMatchObject({ host: 'dev', port: 2222, user: 'root' })
+ await boot()
+ await machine.syncProfiles()
+ const merged = machineProfiles.get(MachineId('dev'))
+ expect([...machineProfiles.keys()]).toEqual([MachineId('dev')])
+ expect(merged).toMatchObject({ host: 'dev', port: 2222, user: 'root' })
})
it('applies the configured remote port and start command template to discovered aliases', async () => {
writeFileSync(join(sshDir, 'config'), 'Host dev\n User root\n')
- const { service } = boot({ config: { remotePort: 3199, startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port {port}' } })
+ const { service } = await boot({ config: { remotePort: 3199, startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port {port}' } })
const views = await service.discoveredViews()
expect(views[0]).toMatchObject({ id: 'dev', remotePort: 3199, startCommand: '$HOME/.local/bin/dsh web --host 127.0.0.1 --port 3199' })
})
it('applies the configured default start command to manual machines without their own', async () => {
- const { service } = boot({ state: { enabled: true, machines: { a: machine('a') } }, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })
- await service.disconnect('a' as never)
- const views = service.manager.profileViews()
- expect(views[0]).toMatchObject({ id: 'a', startCommand: 'dsh web --port 3080' })
+ await boot({ state: { enabled: true, machines: { a: row('a') } }, config: { remotePort: 3080, startCommand: 'dsh web --port {port}' } })
+ await machine.syncProfiles()
+ expect(machineProfiles.get(MachineId('a'))).toMatchObject({ id: 'a', startCommand: 'dsh web --port 3080' })
})
it('keeps a manual start command over the configured default', async () => {
- const { service } = boot({
- state: { enabled: true, machines: { a: { ...machine('a'), startCommand: 'custom dsh web' } } },
+ await boot({
+ state: { enabled: true, machines: { a: { ...row('a'), startCommand: 'custom dsh web' } } },
config: { remotePort: 3080, startCommand: 'dsh web --port {port}' },
})
- await service.disconnect('a' as never)
- const views = service.manager.profileViews()
- expect(views[0]).toMatchObject({ id: 'a', startCommand: 'custom dsh web' })
+ await machine.syncProfiles()
+ expect(machineProfiles.get(MachineId('a'))).toMatchObject({ id: 'a', startCommand: 'custom dsh web' })
})
it('removes a machine from the state document', async () => {
- const { service } = boot({ state: { enabled: true, machines: { a: machine('a'), b: machine('b') } } })
+ const { service } = await boot({ state: { enabled: true, machines: { a: row('a'), b: row('b') } } })
await service.remove('a' as never)
expect(service.profileViews().map(view => view.id)).toEqual(['b'])
expect(readState().machines).not.toHaveProperty('a')
})
it('delegates test and connect to the manager', async () => {
- const { service } = boot()
+ const { service } = await boot()
await expect(service.test('ghost' as never)).rejects.toMatchObject({ code: 'machine-not-found' })
await expect(service.connect('ghost' as never)).rejects.toMatchObject({ code: 'machine-not-found' })
})
@@ -420,9 +438,10 @@ describe('ssh-remote plugin', () => {
const home = join(sshDir, 'dsh-home')
try {
process.env.DSH_HOME = home
- const service = constructWithDefaults()
- expect(service).toBeInstanceOf(SshRemoteService)
- await service.setEnabled(true)
+ apply(scriptedCtx(scriptedHttpServer()).ctx, { ...baseConfig, sshDir })
+ await machine.start()
+ expect(knownHostsFilePath()).toBe(join(home, 'ssh', 'known-hosts.json'))
+ await machine.setEnabled(true)
expect(JSON.parse(readFileSync(join(home, 'ssh', 'machines.json'), 'utf8'))).toMatchObject({ version: 1, enabled: true })
}
finally {
@@ -435,20 +454,15 @@ describe('ssh-remote plugin', () => {
it('disposes the manager when the context tears down', () => {
const { service, disposers } = construct()
- const dispose = vi.spyOn(service.manager, 'dispose').mockResolvedValue(undefined)
- expect(disposers).toHaveLength(1)
- disposers[0]?.()
+ const dispose = vi.spyOn(service, 'dispose').mockResolvedValue(undefined)
+ expect(disposers).toHaveLength(2)
+ for (const disposeAll of disposers) disposeAll()
expect(dispose).toHaveBeenCalledTimes(1)
})
- it('apply constructs the service', () => {
- const { ctx } = construct()
- expect(apply(ctx, baseConfig)).toBeInstanceOf(SshRemoteService)
+ it('assembles the plugin declaratively', () => {
+ const { ctx, webServer } = construct()
+ expect(webServer.routes.map(route => `${route.kind} ${route.path}`)).toEqual(REST_ENDPOINTS.map(path => `exact ${path}`))
+ expect(apply(ctx, { ...baseConfig, sshDir, statePath })).toBeUndefined()
})
})
-
-/** Construct on the config's path defaults (only `sshDir` is redirected). */
-function constructWithDefaults(): SshRemoteService {
- const { ctx } = scriptedCtx(scriptedHttpServer())
- return new SshRemoteService(ctx, { ...baseConfig, sshDir })
-}
diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.ts
index 6a9f19ed..0a1b8787 100644
--- a/packages/dsh-tauri-ssh/src/host/apply.ts
+++ b/packages/dsh-tauri-ssh/src/host/apply.ts
@@ -1,372 +1,51 @@
-/**
- * host/apply.ts — the DSH remote-machine host plugin assembly: owns the
- * plugin state document (`ssh/machines.json`: the enable switch and the manual
- * machine table), the SSH connection manager (TOFU host keys, remote `dsh web`
- * auto-start, loopback tunnels), and mounts the same-origin `/api-ssh` route on
- * `ctx.webServer` for the settings page. No upstream DSH source is touched:
- * every integration is a documented cordis extension point.
- * @module dsh-tauri-ssh/host/apply
- */
-
import type z from 'schemastery'
-import type { SshApiHost } from './routes/index'
-import type { SshHostBlock } from './service/ssh-config'
-import type { Config as SshRemoteConfig } from './storage/index'
-import type { MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshHostContext, SshInstallResult, SshLink, SshMachineEventsPage, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef } from './types/index'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { join } from 'pathe'
-import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants'
-import { createSshApiHandler } from './routes/index'
-import { carryWorkspaceAllowlist } from './service/allowlist'
-import { SshMachineEvents } from './service/events'
-import { KnownHostsStore } from './service/host-keys'
-import { profileView, SshManager } from './service/manager'
-import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config'
-import { SyncEngine } from './service/sync'
-import { profileAllowlistReader, profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local'
-import { Ssh2Transport } from './service/transport'
-import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MachineStateStore } from './storage/index'
-import { MachineId } from './types/index'
-
-/** The harness home every plugin-owned document lives under. */
-function harnessHome(): string {
- return process.env.DSH_HOME ?? join(homedir(), '.dsh')
-}
-
-/** Default location of the TOFU host-key document under the harness home. */
-function defaultKnownHostsPath(): string {
- return join(harnessHome(), 'ssh', 'known-hosts.json')
-}
-
-/** Default location of the machine state document under the harness home. */
-function defaultStatePath(): string {
- return join(harnessHome(), 'ssh', 'machines.json')
-}
-
-/**
- * The plugin service: manager-backed connection plane plus the `/api-ssh`
- * handler face. Two machine sources feed the manager: the plugin state
- * document (manual machines, with secrets) and the host's own `~/.ssh/config`
- * (discovered Host aliases, read-only, no secrets) — a manual machine with the
- * same id as an alias shadows it. The SSH feature is off until the operator
- * enables it from the settings page; while off the API serves the flag and
- * refuses to enumerate machines.
- */
-export class SshRemoteService implements SshApiHost {
- /** The connection manager (transport, TOFU store, and per-machine state). */
- readonly manager: SshManager
-
- /** The machine event channel drained by the `/api-ssh` `machine.events` method. */
- readonly machineEvents: SshMachineEvents
-
- /** The plugin state document (enable switch + manual machines). */
- readonly store: MachineStateStore
-
- /** The ssh directory the discovered aliases and credentials come from. */
- private readonly sshDir: string
-
- /** The home directory used for `~` expansion while reading the ssh config. */
- private readonly homeDir: string
-
- /** The validated plugin config (defaults applied by schemastery). */
- private readonly config: SshRemoteConfig
-
- /** The plugin/skill sync engine (local sources → one remote machine). */
- private readonly sync: SyncEngine
-
- /**
- * @param ctx - the plugin context (webServer available through inject).
- * @param config - the validated plugin config.
- */
- constructor(ctx: SshHostContext, config: SshRemoteConfig) {
- const knownHosts = new KnownHostsStore(config.knownHostsPath ?? defaultKnownHostsPath())
- this.homeDir = homedir()
- this.sshDir = config.sshDir ?? join(this.homeDir, '.ssh')
- this.config = config
- this.store = new MachineStateStore(config.statePath ?? defaultStatePath())
- this.machineEvents = new SshMachineEvents()
- this.manager = new SshManager({
- transport: new Ssh2Transport(
- config.connectTimeoutMs,
- // Credentials come from the host's own ~/.ssh (config + identity
- // files), exactly like a local `ssh` invocation; the auth chain is
- // ssh-agent → private keys → stored password, and the keepalive
- // watchdog timing is the plugin config's.
- new SshConfigResolver(this.sshDir, this.homeDir),
- {
- keepaliveIntervalMs: config.keepaliveIntervalMs,
- keepaliveCountMax: config.keepaliveCountMax,
- },
- ),
- knownHosts,
- config,
- events: this.machineEvents,
- // 本机档案的构建放行白名单:连接时带到远端(git 插件 prepare 门禁)
- localAllowlist: profileAllowlistReader(),
- // v8 ignore next -- deliberately empty status hook: the settings page polls /api-ssh
- emitStatus: () => {
- // The settings page polls status through /api-ssh; no live consumers.
- },
- })
- // The sync engine: local profile/skill sources, remote commands over a
- // dedicated session, the install-class deadline per remote command.
- this.sync = new SyncEngine({
- profileDependencies: profileDependenciesReader(),
- scanSkills: skillRootsScanner(),
- packSkills: tarPacker(),
- openSession: machineId => this.manager.openSession(machineId),
- ...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
- })
- this.manager.refreshProfiles(this.applyStartDefaults(this.manualProfiles()))
- this.store.subscribe(() => {
- void this.syncProfiles()
- })
- // Mount the same-origin connection-plane API.
- ctx.webServer.register({
- kind: 'prefix',
- path: SSH_API_PREFIX,
- handler: createSshApiHandler(this),
- })
- ctx.effect(() => () => {
- void this.manager.dispose()
- })
- }
-
- /** Whether the SSH feature is switched on. */
- enabled(): boolean {
- return this.store.enabled()
- }
-
- /** Flip the feature switch; switching off drops every live connection. */
- async setEnabled(enabled: boolean): Promise<void> {
- this.store.setEnabled(enabled)
- if (!enabled)
- await this.manager.dispose()
- }
+import type { Config as SshRemoteConfig } from './config/schema'
+import type { SshHostContext } from './types/index'
+import { SSH_PLUGIN_NAME } from '../shared/constants'
+import { clearHostRuntime, setCurrentHostInstance, setHostConfig, setMachineDeps, setSyncDeps } from './config/runtime'
+import { ConfigSchema } from './config/schema'
+import { routes } from './routes'
+import { machine } from './service/machine'
+import { transport } from './service/transport'
+import { packSkills, profileAllowlistReader, profileDependenciesReader, skillRootsScanner } from './utils/local'
- /** The manual profiles, read fresh from the state document. */
- private manualProfiles(): Map<MachineId, MachineProfile> {
- return this.store.machines()
- }
+const SSH_START_EFFECT = `${SSH_PLUGIN_NAME}: start`
- /** The configured default start command, `{port}` substituted, or none. */
- private defaultStartCommandFor(remotePort: number): string | undefined {
- const template = this.config.startCommand
- if (template === undefined || template === '')
- return undefined
- return template.replaceAll('{port}', String(remotePort))
- }
+const SSH_ROUTES_EFFECT = `${SSH_PLUGIN_NAME}: routes`
- /** Fill the configured default start command into profiles that lack one. */
- private applyStartDefaults(profiles: Map<MachineId, MachineProfile>): Map<MachineId, MachineProfile> {
- const next = new Map<MachineId, MachineProfile>()
- for (const [id, profile] of profiles) {
- const startCommand = profile.startCommand ?? this.defaultStartCommandFor(profile.remotePort)
- next.set(id, { ...profile, ...startCommand === undefined ? {} : { startCommand } })
- }
- return next
- }
-
- /** The discovered config-alias profiles, shadowed by manual ids. */
- private discoveredProfiles(
- blocks: SshHostBlock[],
- manual: Map<MachineId, MachineProfile>,
- ): Map<MachineId, MachineProfile> {
- const discovered = new Map<MachineId, MachineProfile>()
- const remotePort = this.config.remotePort ?? DEFAULT_REMOTE_PORT
- const startCommand = this.defaultStartCommandFor(remotePort)
- for (const alias of discoverableHosts(blocks)) {
- const id = MachineId(alias)
- if (manual.has(id))
- continue
- const settings = lookupSshConfig(blocks, alias)
- discovered.set(id, {
- id,
- name: alias,
- host: alias,
- port: settings.port ?? DEFAULT_SSH_PORT,
- user: settings.user ?? '',
- remotePort,
- ...startCommand === undefined ? {} : { startCommand },
- })
- }
- return discovered
- }
-
- /** Refresh the manager's profile map from both sources (settings + config). */
- private async syncProfiles(): Promise<void> {
- const manual = this.applyStartDefaults(this.manualProfiles())
- const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)
- const merged = new Map<MachineId, MachineProfile>(manual)
- for (const [id, profile] of this.discoveredProfiles(blocks, manual)) merged.set(id, profile)
- this.manager.refreshProfiles(merged)
- }
-
- /** Redacted views of the manual machines only (the stored, editable set). */
- profileViews(): MachineView[] {
- return [...this.manualProfiles().values()].map(profileView)
- }
-
- /** This instance's session role: a remote target (with its origin name) or a local host. */
- sessionRole(): { remote: boolean, origin?: string } {
- const origin = process.env.DSH_REMOTE_SESSION_ORIGIN
- return origin === undefined || origin === ''
- ? { remote: false }
- : { remote: true, origin }
- }
-
- /** Redacted views of the discovered `~/.ssh/config` aliases (read-only). */
- async discoveredViews(): Promise<MachineView[]> {
- const manual = this.manualProfiles()
- const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)
- return [...this.discoveredProfiles(blocks, manual).values()].map(profileView)
- }
-
- status(machineId: MachineId): SshMachineStatus {
- return this.manager.status(machineId)
- }
-
- async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {
- await this.syncProfiles()
- return this.manager.test(machineId, signal)
- }
-
- async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {
- await this.syncProfiles()
- return this.manager.connect(machineId, signal)
- }
-
- async disconnect(machineId: MachineId): Promise<void> {
- await this.syncProfiles()
- return this.manager.disconnect(machineId)
- }
-
- async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {
- await this.syncProfiles()
- return this.manager.install(machineId, signal)
- }
-
- events(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {
- return this.machineEvents.since(machineId, sinceSeq)
- }
-
- /**
- * Upsert one machine profile: merge the config row and any freshly typed
- * secrets into the stored profile (secrets omitted keep the stored value).
- * Optional fields absent from the row are *cleared* — the write restates the
- * whole profile, so a cleared field cannot be resurrected from a previous
- * layer (the former settings deep-merge did exactly that). The store
- * subscription refreshes the manager automatically.
- * @param machineId - the profile id (the settings dict key).
- * @param row - the config fields as the settings page edited them.
- * @param secrets - write-only secret values; absent fields keep stored ones.
- */
- async save(machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite): Promise<void> {
- const existing = this.store.machines().get(machineId)
- const next: MachineProfile = {
- id: machineId,
- name: row.name,
- host: row.host,
- port: row.port,
- user: row.user,
- remotePort: row.remotePort,
- }
- if (existing !== undefined) {
- if (existing.password !== undefined)
- next.password = existing.password
- if (existing.passphrase !== undefined)
- next.passphrase = existing.passphrase
- }
- if (row.startCommand !== undefined && row.startCommand !== '')
- next.startCommand = row.startCommand
- if (row.profileName !== undefined && row.profileName !== '')
- next.profileName = row.profileName
- if (row.color !== undefined && row.color !== '')
- next.color = row.color
- if (row.tintBorder === true)
- next.tintBorder = true
- if (secrets !== undefined) {
- if (secrets.password !== undefined && secrets.password !== '')
- next.password = secrets.password
- if (secrets.passphrase !== undefined && secrets.passphrase !== '')
- next.passphrase = secrets.passphrase
- }
- this.store.saveMachine(next)
- }
-
- /**
- * Delete one machine profile (idempotent for absent ids); the store
- * subscription refreshes the manager, which drops the machine's connection.
- * @param machineId - the profile id to drop.
- */
- async remove(machineId: MachineId): Promise<void> {
- this.store.removeMachine(machineId)
- }
-
- /** The local plugins and skills available to sync (the panel's selection list). */
- syncPreview(): SyncPreview {
- return this.sync.preview()
- }
-
- /**
- * Sync the selection to one machine over a dedicated authenticated session.
- * Command-level failures settle per item in the result; only a session the
- * engine cannot open at all escalates to an envelope error.
- * @param machineId - the target machine.
- * @param plugins - the plugin refs to install.
- * @param skills - the skill refs to copy.
- * @returns one outcome per requested item.
- */
- async syncApply(machineId: MachineId, plugins: SyncPluginRef[], skills: SyncSkillRef[]): Promise<SyncApplyResult> {
- await this.syncProfiles()
- try {
- // 逐条进度经机器状态发布:设置页只轮询 machine.status,同步是本服务里
- // 唯一「一条请求跑几分钟」的操作,不报进度就只能干等。
- const profileName = this.manager.profileName(machineId)
- return await this.sync.apply(machineId, plugins, skills, {
- // 装进这台机器真正在跑的档案:隧道只服务那一个 profile,装到别处
- // (历史上的硬编码 web)等于没同步。
- profileName,
- // 连接时已带过一次白名单;这里再兜一次——「刚在本机装了新插件就同步」
- // 的场景下,连接时刻的名单里还没有它的放行键。
- beforePlugins: (session) => {
- return carryWorkspaceAllowlist(session, profileName, this.manager.localAllowlist())
- .then(() => undefined)
- },
- onItem: (position, total, item) => this.manager.setProgress(machineId, { phase: 'syncing', attempt: position, total, item }),
- })
- }
- finally {
- this.manager.setProgress(machineId)
- }
- }
-}
+const SSH_RUNTIME_EFFECT = `${SSH_PLUGIN_NAME}: host runtime`
-/** Cordis plugin name. */
export const name = SSH_PLUGIN_NAME
-/** Required services: the webserver (route mount). */
-export const inject = ['webServer']
+export const inject = ['webServer', 'connection']
-/** Validated plugin config; schemastery applies defaults before construction. */
export const Config: z<SshRemoteConfig> = ConfigSchema
-/**
- * Cordis plugin entry: instantiate the service.
- * @param ctx - the plugin context.
- * @param config - the plugin config.
- * @returns the service instance.
- */
-export function apply(ctx: SshHostContext, config: SshRemoteConfig): SshRemoteService {
- return new SshRemoteService(ctx, config)
+export function apply(ctx: SshHostContext, config: SshRemoteConfig): void {
+ setCurrentHostInstance(ctx)
+ setHostConfig(config)
+ setMachineDeps({
+ transport,
+ emitStatus: () => {}, // keep: 进度出口注入点,故意留空——状态另经 status() 与事件环读取
+ localAllowlist: profileAllowlistReader(),
+ })
+ setSyncDeps({
+ profileDependencies: profileDependenciesReader(),
+ scanSkills: skillRootsScanner(),
+ packSkills,
+ ...config.installTimeoutMs === undefined ? {} : { commandTimeoutMs: config.installTimeoutMs },
+ })
+
+ ctx.effect(() => {
+ void machine.start().catch(() => undefined)
+ }, SSH_START_EFFECT)
+
+ ctx.effect(() => routes(ctx), SSH_ROUTES_EFFECT)
+
+ ctx.effect(() => () => {
+ void machine.dispose()
+ clearHostRuntime()
+ }, SSH_RUNTIME_EFFECT)
}
-/**
- * The cordis plugin descriptor. The loader imports the module and reads
- * `apply`/`Config`/`inject`/`name` from the **default export object** — a
- * bare function default carries neither the schema nor the inject list, so
- * config defaults would never apply and the webServer service would not be
- * injected.
- */
export default { apply, Config, inject, name }
diff --git a/packages/dsh-tauri-ssh/src/host/config/constants.ts b/packages/dsh-tauri-ssh/src/host/config/constants.ts
new file mode 100644
index 00000000..f959dc10
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/config/constants.ts
@@ -0,0 +1,5 @@
+export const EVENT_RING_CAPACITY = 500
+
+export const DEFAULT_REMOTE_PROFILE = 'remote'
+
+export const REMOTE_ROOT = '.dsh-desktop'
diff --git a/packages/dsh-tauri-ssh/src/host/config/runtime.ts b/packages/dsh-tauri-ssh/src/host/config/runtime.ts
new file mode 100644
index 00000000..3b65d46d
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/config/runtime.ts
@@ -0,0 +1,118 @@
+import type { MachineDeps, MachineState } from '../service/machine.types'
+import type { SyncDeps } from '../service/sync.types'
+import type { MachineId, MachineProfile, SshHostContext, SshMachineEvent } from '../types/index'
+import type { Config } from './schema'
+import { homedir } from 'node:os'
+import process from 'node:process'
+import { defineHostRuntime } from 'dsh-tauri'
+import { join } from 'pathe'
+import { EVENT_RING_CAPACITY } from './constants'
+
+export const { setCurrentHostInstance, getCurrentHostInstance } = defineHostRuntime<SshHostContext>()
+
+export const machineProfiles = new Map<MachineId, MachineProfile>()
+
+export const machineStates = new Map<MachineId, MachineState>()
+
+export const machineTable: { enabled: boolean, machines: Map<MachineId, MachineProfile> } = {
+ enabled: false,
+ machines: new Map(),
+}
+
+export const eventBuffers = new Map<MachineId, { seq: number, events: SshMachineEvent[] }>()
+
+let config: Config | undefined
+let homeDir = homedir()
+let sshDir = ''
+let statePath = ''
+let knownHostsPath = ''
+let eventCapacity = EVENT_RING_CAPACITY
+let deps: MachineDeps | undefined
+let syncDeps: SyncDeps | undefined
+
+export function harnessHome(): string {
+ return process.env.DSH_HOME ?? join(homedir(), '.dsh')
+}
+
+export function hostConfig(): Config {
+ if (config === undefined)
+ throw new TypeError('hostConfig: 插件配置尚未装配,apply.ts 需先调用 setHostConfig(config)')
+ return config
+}
+
+export function setHostConfig(next: Config): void {
+ config = next
+ homeDir = homedir()
+ sshDir = next.sshDir ?? join(homeDir, '.ssh')
+ statePath = next.statePath ?? join(harnessHome(), 'ssh', 'machines.json')
+ knownHostsPath = next.knownHostsPath ?? join(harnessHome(), 'ssh', 'known-hosts.json')
+}
+
+export function stateDocumentPath(): string {
+ return statePath === '' ? join(harnessHome(), 'ssh', 'machines.json') : statePath
+}
+
+export function setKnownHostsPath(path: string): void {
+ knownHostsPath = path
+}
+
+export function knownHostsFilePath(): string {
+ return knownHostsPath === '' ? join(harnessHome(), 'ssh', 'known-hosts.json') : knownHostsPath
+}
+
+export function sshDirPath(): string {
+ return sshDir === '' ? join(homedir(), '.ssh') : sshDir
+}
+
+export function homeDirPath(): string {
+ return homeDir
+}
+
+export function setEventCapacity(capacity: number): void {
+ eventCapacity = capacity
+}
+
+export function eventRingCapacity(): number {
+ return eventCapacity
+}
+
+export function setMachineDeps(next: MachineDeps): void {
+ deps = next
+}
+
+export function machineRuntimeDeps(): MachineDeps {
+ if (deps === undefined)
+ throw new TypeError('machineRuntimeDeps: 连接面依赖尚未装配,apply.ts 需先调用 setMachineDeps(deps)')
+ return deps
+}
+
+export function setSyncDeps(next: SyncDeps): void {
+ syncDeps = next
+}
+
+export function syncRuntimeDeps(): SyncDeps {
+ if (syncDeps === undefined)
+ throw new TypeError('syncRuntimeDeps: 同步面依赖尚未装配,apply.ts 需先调用 setSyncDeps(deps)')
+ return syncDeps
+}
+
+export function clearHostRuntime(): void {
+ // 使在途 attempt 失效:未完成的 performConnect/performInstall 恢复执行时会比对 generation,
+ // 若不等则不再对外拨号(否则它们的续跑会读到下一个 runtime 的 deps,把连接打到别人的 transport 上)。
+ for (const target of machineStates.values())
+ target.generation += 1
+ config = undefined
+ homeDir = homedir()
+ sshDir = ''
+ statePath = ''
+ knownHostsPath = ''
+ eventCapacity = EVENT_RING_CAPACITY
+ deps = undefined
+ syncDeps = undefined
+ machineProfiles.clear()
+ machineStates.clear()
+ machineTable.enabled = false
+ machineTable.machines.clear()
+ eventBuffers.clear()
+ setCurrentHostInstance(undefined)
+}
diff --git a/packages/dsh-tauri-ssh/src/host/config/schema.ts b/packages/dsh-tauri-ssh/src/host/config/schema.ts
new file mode 100644
index 00000000..14fa285b
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/config/schema.ts
@@ -0,0 +1,42 @@
+import z from 'schemastery'
+import { DEFAULT_REMOTE_PORT } from '../../shared/constants'
+
+export interface Config {
+ connectTimeoutMs: number
+ healthCheckTimeoutMs: number
+ healthPollIntervalMs: number
+ healthPollAttempts: number
+ knownHostsPath?: string
+ statePath?: string
+ sshDir?: string
+ remotePort?: number
+ startCommand?: string
+ installRepo?: string
+ installRef?: string
+ installTimeoutMs?: number
+ keepaliveIntervalMs: number
+ keepaliveCountMax: number
+ reconnectInitialDelayMs: number
+ reconnectMaxDelayMs: number
+ reconnectMaxAttempts: number
+}
+
+export const ConfigSchema: z<Config> = z.object({
+ connectTimeoutMs: z.number().default(15_000),
+ healthCheckTimeoutMs: z.number().default(3_000),
+ healthPollIntervalMs: z.number().default(1_000),
+ healthPollAttempts: z.number().default(30),
+ knownHostsPath: z.string(),
+ statePath: z.string(),
+ sshDir: z.string(),
+ remotePort: z.number().default(DEFAULT_REMOTE_PORT),
+ startCommand: z.string(),
+ installRepo: z.string(),
+ installRef: z.string(),
+ installTimeoutMs: z.number().default(1_800_000),
+ keepaliveIntervalMs: z.number().default(10_000),
+ keepaliveCountMax: z.number().default(3),
+ reconnectInitialDelayMs: z.number().default(1_000),
+ reconnectMaxDelayMs: z.number().default(20_000),
+ reconnectMaxAttempts: z.number().default(6),
+}) as z<Config>
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
index d7efe8f7..30a10db0 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.test.ts
@@ -1,12 +1,41 @@
-import type { MachineView, SshTestResult } from '../types/index'
-import type { SshApiHost, SshApiResponse } from './index'
-import { Buffer } from 'node:buffer'
-import { IncomingMessage, ServerResponse } from 'node:http'
-import { Socket } from 'node:net'
-import { describe, expect, it, vi } from 'vitest'
-import { SshMachineEvents } from '../service/events'
+import type { HostWebRoute, MachineView, SshMachineStatus, SshTestResult, SyncPreview } from '../types/index'
+import type { SshActionResponse, SshConnectResponse, SshInstallResponse, SshMachineEventsResponse, SshMachinesResponse, SshSessionRoleResponse, SshSettingsResponse, SshTestResponse, SyncApplyResponse, SyncPreviewResponse } from './index.types'
+import { createServer, request as httpRequest } from 'node:http'
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { events } from '../service/events'
+import { machine } from '../service/machine'
+import { session } from '../service/session'
+import { sync } from '../service/sync'
import { MachineId, SshError } from '../types/index'
-import { createSshApiHandler, isLoopbackPeer } from './index'
+import { routes } from './index'
+
+const BASE = '/api/desktop/dsh-tauri-ssh'
+
+const PATHS = [
+ `${BASE}/settings`,
+ `${BASE}/session/role`,
+ `${BASE}/machines`,
+ `${BASE}/machines/test`,
+ `${BASE}/machines/connect`,
+ `${BASE}/machines/disconnect`,
+ `${BASE}/machines/install`,
+ `${BASE}/machines/events`,
+ `${BASE}/sync/preview`,
+ `${BASE}/sync/apply`,
+]
+
+const ALLOW: Record<string, string> = {
+ [`${BASE}/settings`]: 'GET, HEAD, POST, OPTIONS',
+ [`${BASE}/session/role`]: 'GET, HEAD, OPTIONS',
+ [`${BASE}/machines`]: 'GET, HEAD, POST, DELETE, OPTIONS',
+ [`${BASE}/machines/test`]: 'POST, OPTIONS',
+ [`${BASE}/machines/connect`]: 'POST, OPTIONS',
+ [`${BASE}/machines/disconnect`]: 'POST, OPTIONS',
+ [`${BASE}/machines/install`]: 'POST, OPTIONS',
+ [`${BASE}/machines/events`]: 'GET, HEAD, OPTIONS',
+ [`${BASE}/sync/preview`]: 'GET, HEAD, OPTIONS',
+ [`${BASE}/sync/apply`]: 'POST, OPTIONS',
+}
const view: MachineView = {
id: MachineId('m1'),
@@ -19,13 +48,31 @@ const view: MachineView = {
remotePort: 3080,
}
-/** A seeded per-machine event log shared by the fake host. */
-const log = new SshMachineEvents()
+interface HostFakes {
+ sessionRole: () => { remote: boolean, origin?: string }
+ enabled: () => boolean
+ setEnabled: (enabled: boolean) => Promise<void>
+ profileViews: () => MachineView[]
+ discoveredViews: () => Promise<MachineView[]>
+ status: (machineId: MachineId) => SshMachineStatus
+ test: (machineId: MachineId, signal?: AbortSignal) => Promise<SshTestResult>
+ connect: (machineId: MachineId, signal?: AbortSignal) => Promise<{ machineId: MachineId, tunnelBaseUrl: string }>
+ disconnect: (machineId: MachineId) => Promise<void>
+ install: (machineId: MachineId, signal?: AbortSignal) => Promise<SshInstallResponse>
+ events: (machineId: MachineId, sinceSeq?: number) => { events: unknown[], nextSeq: number }
+ save: (machineId: MachineId, row: Record<string, unknown>, secrets?: Record<string, unknown>) => Promise<void>
+ remove: (machineId: MachineId) => Promise<void>
+ syncPreview: () => SyncPreview
+ syncApply: (machineId: MachineId, plugins: unknown[], skills: unknown[]) => Promise<SyncApplyResponse>
+}
+
+const log = events
+const readEvents = events.since
log.append(MachineId('m1'), 'probe', '探测远端平台 (uname -srm)')
log.append(MachineId('m1'), 'download', 'https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz')
log.append(MachineId('m1'), 'ready', '远端实例已就绪', { terminal: 'success' })
-function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {
+function fakeHost(overrides: Partial<HostFakes> = {}): HostFakes {
return {
sessionRole: () => ({ remote: false }),
enabled: () => true,
@@ -34,10 +81,10 @@ function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {
discoveredViews: async () => [],
status: () => ({ machineId: MachineId('m1'), state: 'disconnected' }),
test: async (): Promise<SshTestResult> => ({ ok: true, banner: 'Linux alpha' }),
- connect: async () => ({ tunnelBaseUrl: 'http://127.0.0.1:45678' }),
+ connect: async (machineId): Promise<{ machineId: MachineId, tunnelBaseUrl: string }> => ({ machineId, tunnelBaseUrl: 'http://127.0.0.1:45678' }),
disconnect: async () => {},
install: async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }),
- events: (machineId, sinceSeq) => log.since(machineId, sinceSeq),
+ events: (machineId, sinceSeq) => readEvents(machineId, sinceSeq),
save: async () => {},
remove: async () => {},
syncPreview: () => ({ plugins: [], skills: [] }),
@@ -46,163 +93,240 @@ function fakeHost(overrides: Partial<SshApiHost> = {}): SshApiHost {
}
}
-/** Drive one request through the handler and collect the response. */
-async function call(
- host: SshApiHost,
- body: string,
- options: { method?: string, address?: string, origin?: string } = {},
-): Promise<{ status: number, body: SshApiResponse, headers: Record<string, unknown> }> {
- const socket = new Socket()
- Object.defineProperty(socket, 'remoteAddress', { value: options.address ?? '127.0.0.1', configurable: true })
- const req = new IncomingMessage(socket)
- req.method = options.method ?? 'POST'
- if (options.origin !== undefined)
- req.headers.origin = options.origin
- const res = new ServerResponse(req)
- let status = 0
- let payload = ''
- let headers: Record<string, unknown> = {}
- res.writeHead = ((code: number, head?: Record<string, unknown>) => {
- status = code
- headers = head ?? {}
- return res
- }) as typeof res.writeHead
- res.end = ((chunk?: unknown) => {
- payload = String(chunk ?? '')
- return res
- }) as typeof res.end
- // Feed the body through the readable stream.
- req.push(Buffer.from(body))
- req.push(null)
- await createSshApiHandler(host)(req, res)
- // 204 preflight responses carry no body; parse only actual JSON payloads.
- return { status, body: (payload === '' ? {} : JSON.parse(payload)) as SshApiResponse, headers }
+const originalServices = {
+ events: { ...events },
+ machine: { ...machine },
+ session: { ...session },
+ sync: { ...sync },
}
-describe('isLoopbackPeer', () => {
- it('accepts loopback addresses and rejects everything else', () => {
- expect(isLoopbackPeer('127.0.0.1')).toBe(true)
- expect(isLoopbackPeer('::1')).toBe(true)
- expect(isLoopbackPeer('::ffff:127.0.0.1')).toBe(true)
- expect(isLoopbackPeer('192.168.1.5')).toBe(false)
- expect(isLoopbackPeer(undefined)).toBe(false)
- })
-})
-
-describe('/api-ssh handler', () => {
- it('answers the shell webview\'s CORS preflight and echoes its origin', async () => {
- const { status, headers } = await call(fakeHost(), '', { method: 'OPTIONS', origin: 'http://localhost:1420' })
- expect(status).toBe(204)
- expect(headers['access-control-allow-origin']).toBe('http://localhost:1420')
- expect(headers['access-control-allow-methods']).toBe('POST, OPTIONS')
- })
+function installHost(host: HostFakes): void {
+ Object.assign(session, { role: host.sessionRole })
+ Object.assign(machine, {
+ enabled: host.enabled,
+ setEnabled: host.setEnabled,
+ profileViews: host.profileViews,
+ discoveredViews: host.discoveredViews,
+ status: host.status,
+ test: host.test,
+ connect: host.connect,
+ disconnect: host.disconnect,
+ install: host.install,
+ save: host.save,
+ remove: host.remove,
+ })
+ Object.assign(events, { since: host.events })
+ Object.assign(sync, { preview: host.syncPreview, apply: host.syncApply })
+}
- it('allows every Tauri shell scheme origin on preflight', async () => {
- for (const origin of ['tauri://localhost', 'http://tauri.localhost']) {
- const { status, headers } = await call(fakeHost(), '', { method: 'OPTIONS', origin })
- expect(status).toBe(204)
- expect(headers['access-control-allow-origin']).toBe(origin)
+const registered: HostWebRoute[] = []
+let origin = ''
+let disposeRoutes: () => void
+let closeServer: () => Promise<void>
+
+function serveRoutes(): Promise<{ origin: string, close: () => Promise<void> }> {
+ const server = createServer((request, response) => {
+ const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname
+ const route = registered.find(entry => entry.path === path)
+ if (route === undefined) {
+ response.writeHead(404, { 'content-type': 'application/json' })
+ response.end('{"error":"no-route"}')
+ return
}
+ void route.handler(request, response)
+ })
+ return new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', () => {
+ const address = server.address()
+ resolve({
+ origin: `http://127.0.0.1:${typeof address === 'object' && address !== null ? address.port : 0}`,
+ close: () => new Promise<void>(done => server.close(() => done())),
+ })
+ })
})
+}
- it('refuses preflight from a non-shell origin', async () => {
- const { status, body, headers } = await call(fakeHost(), '', { method: 'OPTIONS', origin: 'http://evil.example' })
- expect(status).toBe(403)
- expect(body).toMatchObject({ ok: false, error: { code: 'forbidden' } })
- expect(headers['access-control-allow-origin']).toBeUndefined()
+const OVERSIZED_BODY_BYTES = 2 * 1024 * 1024
+
+function oversizedPost(origin: string, path: string): Promise<number> {
+ const target = new URL(path, origin)
+ return new Promise((resolve, reject) => {
+ const req = httpRequest({
+ hostname: target.hostname,
+ port: target.port,
+ path: target.pathname,
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-length': String(OVERSIZED_BODY_BYTES),
+ 'connection': 'close',
+ },
+ }, (response) => {
+ response.resume()
+ response.on('end', () => resolve(response.statusCode ?? 0))
+ })
+ req.on('error', reject)
+ req.end()
})
+}
- it('carries the CORS headers on cross-origin POST responses for shell origins only', async () => {
- const allowed = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }), { origin: 'tauri://localhost' })
- expect(allowed.status).toBe(200)
- expect(allowed.headers['access-control-allow-origin']).toBe('tauri://localhost')
- const rogue = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }), { origin: 'http://evil.example' })
- expect(rogue.status).toBe(200)
- expect(rogue.headers['access-control-allow-origin']).toBeUndefined()
+beforeAll(async () => {
+ disposeRoutes = routes({
+ webServer: {
+ register: (route: HostWebRoute) => {
+ registered.push(route)
+ return () => {
+ registered.splice(registered.indexOf(route), 1)
+ }
+ },
+ },
+ logger: { error: () => {} },
})
+ const listener = await serveRoutes()
+ origin = listener.origin
+ closeServer = listener.close
+})
- it('refuses non-loopback peers', async () => {
- const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }), { address: '10.0.0.9' })
- expect(status).toBe(403)
- expect(body).toMatchObject({ ok: false, error: { code: 'forbidden' } })
+afterEach(() => {
+ Object.assign(events, originalServices.events)
+ Object.assign(machine, originalServices.machine)
+ Object.assign(session, originalServices.session)
+ Object.assign(sync, originalServices.sync)
+})
+
+afterAll(async () => {
+ disposeRoutes()
+ await closeServer()
+})
+
+async function call<T = Record<string, unknown>>(
+ method: string,
+ path: string,
+ body?: unknown,
+): Promise<{ status: number, body: T, allow: string | undefined }> {
+ const response = await fetch(`${origin}${path}`, {
+ method,
+ headers: {
+ connection: 'close',
+ ...body === undefined ? {} : { 'content-type': 'application/json' },
+ },
+ ...body === undefined ? {} : { body: JSON.stringify(body) },
+ })
+ const text = await response.text()
+ return {
+ status: response.status,
+ body: (text === '' ? {} : JSON.parse(text)) as T,
+ allow: response.headers.get('allow') ?? undefined,
+ }
+}
+
+describe('ssh REST route table', () => {
+ it('declares one exact route per endpoint and disposes every registration', () => {
+ const declared: string[] = []
+ const disposed: string[] = []
+ const dispose = routes({
+ webServer: {
+ register: (route: HostWebRoute) => {
+ declared.push(`${route.kind} ${route.path}`)
+ return () => {
+ disposed.push(route.path)
+ }
+ },
+ },
+ logger: { error: () => {} },
+ })
+ expect(declared).toEqual(PATHS.map(path => `exact ${path}`))
+ dispose()
+ expect([...disposed].sort()).toEqual([...PATHS].sort())
})
- it('refuses non-POST methods', async () => {
- const { status, body } = await call(fakeHost(), '', { method: 'GET' })
- expect(status).toBe(405)
- expect(body).toMatchObject({ ok: false, error: { code: 'method-not-allowed' } })
+ it('answers the CORS preflight of every endpoint with its declared method set', async () => {
+ for (const path of PATHS) {
+ const reply = await call('OPTIONS', path)
+ expect(reply.status).toBe(204)
+ expect(reply.allow).toBe(ALLOW[path])
+ }
})
- it('rejects malformed JSON and missing methods', async () => {
- const bad = await call(fakeHost(), 'not json')
- expect(bad.status).toBe(400)
- expect(bad.body).toMatchObject({ ok: false, error: { code: 'bad-request' } })
- const missing = await call(fakeHost(), JSON.stringify({ payload: {} }))
- expect(missing.status).toBe(400)
- expect(missing.body).toMatchObject({ ok: false, error: { code: 'bad-request' } })
+ it('refuses undeclared methods with 405 and the same allow set', async () => {
+ const put = await call('PUT', `${BASE}/settings`)
+ expect(put.status).toBe(405)
+ expect(put.allow).toBe(ALLOW[`${BASE}/settings`])
+ const preview = await call('POST', `${BASE}/sync/preview`)
+ expect(preview.status).toBe(405)
+ expect(preview.allow).toBe(ALLOW[`${BASE}/sync/preview`])
+ const install = await call('GET', `${BASE}/machines/install`)
+ expect(install.status).toBe(405)
+ expect(install.allow).toBe(ALLOW[`${BASE}/machines/install`])
})
+})
+describe('ssh REST handlers', () => {
it('answers session.role from the host', async () => {
- const plain = await call(fakeHost(), JSON.stringify({ method: 'session.role' }))
- expect(plain.body).toEqual({ ok: true, value: { remote: false } })
- const remote = await call(fakeHost({ sessionRole: () => ({ remote: true, origin: 'ops' }) }), JSON.stringify({ method: 'session.role' }))
- expect(remote.body).toEqual({ ok: true, value: { remote: true, origin: 'ops' } })
+ installHost(fakeHost())
+ const plain = await call<SshSessionRoleResponse>('GET', `${BASE}/session/role`)
+ expect(plain.status).toBe(200)
+ expect(plain.body).toEqual({ role: 'local', remote: false })
+ installHost(fakeHost({ sessionRole: () => ({ remote: true, origin: 'ops' }) }))
+ const remote = await call<SshSessionRoleResponse>('GET', `${BASE}/session/role`)
+ expect(remote.body).toEqual({ role: 'remote', remote: true, origin: 'ops' })
})
it('reads and writes the SSH feature switch', async () => {
const setEnabled = vi.fn(async () => {})
- const off = fakeHost({ enabled: () => false, setEnabled })
- expect((await call(off, JSON.stringify({ method: 'settings.get' }))).body)
- .toEqual({ ok: true, value: { enabled: false } })
+ const host = fakeHost({ enabled: () => false, setEnabled })
+ installHost(host)
+ const read = await call<SshSettingsResponse>('GET', `${BASE}/settings`)
+ expect(read.status).toBe(200)
+ expect(read.body).toEqual({ enabled: false })
- const written = await call(off, JSON.stringify({ method: 'settings.set', payload: { enabled: true } }))
+ const written = await call<SshSettingsResponse>('POST', `${BASE}/settings`, { enabled: true })
expect(written.status).toBe(200)
- expect(written.body).toEqual({ ok: true, value: { enabled: true } })
+ expect(written.body).toEqual({ enabled: true })
expect(setEnabled).toHaveBeenCalledWith(true)
})
- it('refuses a settings.set without a boolean switch', async () => {
+ it('refuses a settings write without a boolean switch', async () => {
const setEnabled = vi.fn(async () => {})
- const host = fakeHost({ setEnabled })
- const { body } = await call(host, JSON.stringify({ method: 'settings.set', payload: {} }))
- expect(body).toMatchObject({ ok: false, error: { message: 'missing enabled' } })
+ installHost(fakeHost({ setEnabled }))
+ const reply = await call<SshSettingsResponse>('POST', `${BASE}/settings`, {})
+ expect(reply.status).toBe(400)
+ expect(reply.body).toEqual({ error: 'missing enabled' })
expect(setEnabled).not.toHaveBeenCalled()
})
- it('serves no machines while the feature is off (keeps the flag visible)', async () => {
- const host = fakeHost({
- enabled: () => false,
- profileViews: () => [view],
- discoveredViews: async () => [view],
+ it('rejects a malformed JSON body', async () => {
+ installHost(fakeHost())
+ const response = await fetch(`${origin}${BASE}/settings`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: 'not json',
})
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: { enabled: false, items: [], discovered: [] } })
+ expect(response.status).toBe(400)
+ })
+
+ it('serves no machines while the feature is off (keeps the flag visible)', async () => {
+ installHost(fakeHost({ enabled: () => false, profileViews: () => [view], discoveredViews: async () => [view] }))
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({ enabled: false, items: [], discovered: [] })
})
it('lists machines with live status', async () => {
- const host = fakeHost({
+ installHost(fakeHost({
status: () => ({ machineId: MachineId('m1'), state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1', lastError: 'boom' }),
- })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))
- expect(status).toBe(200)
- expect(body).toEqual({
- ok: true,
- value: {
- enabled: true,
- items: [{
- ...view,
- state: 'connected',
- tunnelBaseUrl: 'http://127.0.0.1:1',
- lastError: 'boom',
- }],
- discovered: [],
- },
+ }))
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({
+ enabled: true,
+ items: [{ ...view, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:1', lastError: 'boom' }],
+ discovered: [],
})
})
it('lists discovered config aliases with their live status', async () => {
- const host = fakeHost({
+ installHost(fakeHost({
discoveredViews: async () => [{
id: MachineId('dev'),
name: 'dev',
@@ -216,96 +340,97 @@ describe('/api-ssh handler', () => {
status: (id: MachineId) => id === MachineId('dev')
? { machineId: id, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:2' }
: { machineId: id, state: 'disconnected' },
- })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))
- expect(status).toBe(200)
- expect(body).toEqual({
- ok: true,
- value: {
- enabled: true,
- items: [{ ...view, state: 'disconnected' }],
- discovered: [{
- id: 'dev',
- name: 'dev',
- host: 'dev',
- port: 22,
- user: '',
- hasPassword: false,
- hasPassphrase: false,
- remotePort: 3080,
- state: 'connected',
- tunnelBaseUrl: 'http://127.0.0.1:2',
- }],
- },
+ }))
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({
+ enabled: true,
+ items: [{ ...view, state: 'disconnected' }],
+ discovered: [{
+ id: 'dev',
+ name: 'dev',
+ host: 'dev',
+ port: 22,
+ user: '',
+ hasPassword: false,
+ hasPassphrase: false,
+ remotePort: 3080,
+ state: 'connected',
+ tunnelBaseUrl: 'http://127.0.0.1:2',
+ }],
})
})
it('rides the live progress of an in-flight operation on list rows', async () => {
- const host = fakeHost({
+ installHost(fakeHost({
status: () => ({ machineId: MachineId('m1'), state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }),
- })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.list' }))
- expect(status).toBe(200)
- expect(body).toEqual({
- ok: true,
- value: {
- enabled: true,
- items: [{
- ...view,
- state: 'connecting',
- progress: { phase: 'probing', attempt: 2, total: 30 },
- }],
- discovered: [],
- },
+ }))
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({
+ enabled: true,
+ items: [{ ...view, state: 'connecting', progress: { phase: 'probing', attempt: 2, total: 30 } }],
+ discovered: [],
})
})
it('lists machines without link fields while disconnected', async () => {
- const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list' }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: { enabled: true, items: [{ ...view, state: 'disconnected' }], discovered: [] } })
+ installHost(fakeHost())
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({ enabled: true, items: [{ ...view, state: 'disconnected' }], discovered: [] })
+ })
+
+ it('carries the dshMissing marker on list rows', async () => {
+ installHost(fakeHost({ status: () => ({ machineId: MachineId('m1'), state: 'disconnected', dshMissing: true }) }))
+ const reply = await call<SshMachinesResponse>('GET', `${BASE}/machines`)
+ expect(reply.body.items?.[0]).toMatchObject({ dshMissing: true })
})
- it('rejects request bodies over the 64 KiB bound', async () => {
- const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.list', payload: { pad: 'x'.repeat(70 * 1024) } }))
- expect(status).toBe(400)
- expect(body).toMatchObject({ ok: false, error: { code: 'bad-request' } })
+ it('rejects a request body over the host bound without touching the service', async () => {
+ const save = vi.fn(async () => {})
+ installHost(fakeHost({ save }))
+ const listener = await serveRoutes()
+ try {
+ expect(await oversizedPost(listener.origin, `${BASE}/machines`)).toBe(413)
+ }
+ finally {
+ await listener.close()
+ }
+ expect(save).not.toHaveBeenCalled()
})
it('tests a machine', async () => {
- const host = fakeHost()
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: { ok: true, banner: 'Linux alpha' } })
+ installHost(fakeHost())
+ const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({ ok: true, banner: 'Linux alpha' })
})
it('connects a machine and returns the tunnel URL', async () => {
- const host = fakeHost()
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.connect', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:45678' } })
+ installHost(fakeHost())
+ const reply = await call<SshConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({ tunnelBaseUrl: 'http://127.0.0.1:45678' })
})
it('saves a machine with write-only secrets', async () => {
const save = vi.fn(async () => {})
- const host = fakeHost({ save })
- const { status, body } = await call(host, JSON.stringify({
- method: 'machine.save',
- payload: {
- machineId: 'm1',
- row: {
- name: 'alpha',
- host: '10.0.0.1',
- port: 22,
- user: 'root',
- remotePort: 3000,
- startCommand: 'dsh web --port 3000',
- },
- secrets: { password: 'PW', passphrase: 'PHRASE' },
+ installHost(fakeHost({ save }))
+ const reply = await call<SshActionResponse>('POST', `${BASE}/machines`, {
+ machineId: 'm1',
+ row: {
+ name: 'alpha',
+ host: '10.0.0.1',
+ port: 22,
+ user: 'root',
+ remotePort: 3000,
+ startCommand: 'dsh web --port 3000',
},
- }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: {} })
+ secrets: { password: 'PW', passphrase: 'PHRASE' },
+ })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({})
expect(save).toHaveBeenCalledWith(
MachineId('m1'),
{
@@ -320,70 +445,57 @@ describe('/api-ssh handler', () => {
)
})
- it('rejects malformed machine.save payloads', async () => {
+ it('rejects malformed machine writes', async () => {
const save = vi.fn(async () => {})
- const host = fakeHost({ save })
- const missingRow = await call(host, JSON.stringify({ method: 'machine.save', payload: { machineId: 'm1' } }))
- expect(missingRow.body).toEqual({ ok: false, error: { code: 'internal', message: 'missing row' } })
- const badName = await call(host, JSON.stringify({
- method: 'machine.save',
- payload: { machineId: 'm1', row: { name: '', host: 'x', user: 'u' } },
- }))
- expect(badName.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: name' } })
- const badUserType = await call(host, JSON.stringify({
- method: 'machine.save',
- payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 7 } },
- }))
- expect(badUserType.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: user' } })
- const badHost = await call(host, JSON.stringify({
- method: 'machine.save',
- payload: { machineId: 'm1', row: { name: 'a', host: '', user: 'u' } },
- }))
- expect(badHost.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid row: host' } })
- const badSecrets = await call(host, JSON.stringify({
- method: 'machine.save',
- payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u' }, secrets: 'nope' },
- }))
- expect(badSecrets.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid secrets' } })
+ installHost(fakeHost({ save }))
+ const missingRow = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1' })
+ expect(missingRow.status).toBe(400)
+ expect(missingRow.body).toEqual({ error: 'missing row' })
+ const badName = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: '', host: 'x', user: 'u' } })
+ expect(badName.body).toEqual({ error: 'invalid row: name' })
+ const badHost = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: '', user: 'u' } })
+ expect(badHost.body).toEqual({ error: 'invalid row: host' })
+ const badUser = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 7 } })
+ expect(badUser.body).toEqual({ error: 'invalid row: user' })
+ const badSecrets = await call<SshActionResponse>('POST', `${BASE}/machines`, { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u' }, secrets: 'nope' })
+ expect(badSecrets.body).toEqual({ error: 'invalid secrets' })
+ const noMachine = await call<SshActionResponse>('POST', `${BASE}/machines`, { row: { name: 'a', host: 'x', user: 'u' } })
+ expect(noMachine.body).toEqual({ error: 'missing machineId' })
expect(save).not.toHaveBeenCalled()
})
- it('applies row defaults for absent numeric fields', async () => {
+ it('applies row defaults for absent numeric fields and drops empty optionals', async () => {
const save = vi.fn(async () => {})
- await call(fakeHost({ save }), JSON.stringify({
- method: 'machine.save',
- payload: { machineId: 'm1', row: { name: 'a', host: 'x', user: 'u', startCommand: '' } },
- }))
+ installHost(fakeHost({ save }))
+ await call('POST', `${BASE}/machines`, {
+ machineId: 'm1',
+ row: { name: 'a', host: 'x', user: 'u', startCommand: '', profileName: ' keep-me ', color: '', tintBorder: false },
+ })
expect(save).toHaveBeenCalledWith(
MachineId('m1'),
- { name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },
+ { name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080, profileName: 'keep-me' },
undefined,
)
})
it('drops absent secret fields', async () => {
const save = vi.fn(async () => {})
- await call(fakeHost({ save }), JSON.stringify({
- method: 'machine.save',
- payload: {
- machineId: 'm1',
- row: { name: 'a', host: 'x', user: 'u' },
- secrets: { passphrase: 'PHRASE' },
- },
- }))
+ installHost(fakeHost({ save }))
+ await call('POST', `${BASE}/machines`, {
+ machineId: 'm1',
+ row: { name: 'a', host: 'x', user: 'u' },
+ secrets: { passphrase: 'PHRASE' },
+ })
expect(save).toHaveBeenCalledWith(
MachineId('m1'),
{ name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },
{ passphrase: 'PHRASE' },
)
- await call(fakeHost({ save }), JSON.stringify({
- method: 'machine.save',
- payload: {
- machineId: 'm1',
- row: { name: 'a', host: 'x', user: 'u' },
- secrets: { password: 'P' },
- },
- }))
+ await call('POST', `${BASE}/machines`, {
+ machineId: 'm1',
+ row: { name: 'a', host: 'x', user: 'u' },
+ secrets: { password: 'P' },
+ })
expect(save).toHaveBeenLastCalledWith(
MachineId('m1'),
{ name: 'a', host: 'x', port: 22, user: 'u', remotePort: 3080 },
@@ -393,82 +505,92 @@ describe('/api-ssh handler', () => {
it('removes a machine', async () => {
const remove = vi.fn(async () => {})
- const host = fakeHost({ remove })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.remove', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: {} })
+ installHost(fakeHost({ remove }))
+ const reply = await call<SshActionResponse>('DELETE', `${BASE}/machines`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({})
expect(remove).toHaveBeenCalledWith(MachineId('m1'))
})
+ it('requires a machineId on removal', async () => {
+ const remove = vi.fn(async () => {})
+ installHost(fakeHost({ remove }))
+ const reply = await call<SshActionResponse>('DELETE', `${BASE}/machines`, {})
+ expect(reply.status).toBe(400)
+ expect(reply.body).toEqual({ error: 'missing machineId' })
+ expect(remove).not.toHaveBeenCalled()
+ })
+
it('disconnects a machine', async () => {
- const host = fakeHost()
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.disconnect', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: {} })
+ const disconnect = vi.fn(async () => {})
+ installHost(fakeHost({ disconnect }))
+ const reply = await call<SshActionResponse>('POST', `${BASE}/machines/disconnect`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({})
+ expect(disconnect).toHaveBeenCalledWith(MachineId('m1'))
})
it('installs dsh on a machine and returns the outcome', async () => {
const install = vi.fn(async () => ({ installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true }))
- const host = fakeHost({ install })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.install', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({
- ok: true,
- value: { installed: ['node'], dshRef: 'dsh-0.1.2-rc.1-1', dshVersion: '0.1.2-rc.1', dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js', credentialsCopied: true },
+ installHost(fakeHost({ install }))
+ const reply = await call<SshInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({
+ installed: ['node'],
+ dshRef: 'dsh-0.1.2-rc.1-1',
+ dshVersion: '0.1.2-rc.1',
+ dshPath: '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js',
+ credentialsCopied: true,
})
expect(install).toHaveBeenCalledWith(MachineId('m1'), expect.any(AbortSignal))
})
- it('surfaces install failures on the envelope', async () => {
- const host = fakeHost({
- install: async () => { throw new SshError('machine-install-failed', MachineId('m1'), 'pnpm: not found') },
- })
- const { body } = await call(host, JSON.stringify({ method: 'machine.install', payload: { machineId: 'm1' } }))
- expect(body).toEqual({ ok: false, error: { code: 'machine-install-failed', message: 'pnpm: not found' } })
- })
-
- it('carries the dshMissing marker on list rows', async () => {
- const host = fakeHost({
- status: () => ({ machineId: MachineId('m1'), state: 'disconnected', dshMissing: true }),
- })
- const { body } = await call(host, JSON.stringify({ method: 'machine.list' }))
- expect(body).toMatchObject({ ok: true })
- const value = (body as { ok: true, value: { items: Array<Record<string, unknown>> } }).value
- expect(value.items[0]).toMatchObject({ dshMissing: true })
- })
+ it('surfaces machine failures as 400 messages', async () => {
+ installHost(fakeHost({
+ install: async () => {
+ throw new SshError('machine-install-failed', MachineId('m1'), 'pnpm: not found')
+ },
+ }))
+ const install = await call<SshInstallResponse>('POST', `${BASE}/machines/install`, { machineId: 'm1' })
+ expect(install.status).toBe(400)
+ expect(install.body).toEqual({ error: 'pnpm: not found' })
- it('maps business failures onto the envelope', async () => {
- const host = fakeHost({
- test: async () => { throw new SshError('machine-connect-failed', MachineId('m1'), 'auth failed') },
- })
- const { status, body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: false, error: { code: 'machine-connect-failed', message: 'auth failed' } })
- })
+ installHost(fakeHost({
+ test: async () => {
+ throw new SshError('machine-connect-failed', MachineId('m1'), 'auth failed')
+ },
+ }))
+ const test = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ expect(test.status).toBe(400)
+ expect(test.body).toEqual({ error: 'auth failed' })
- it('maps plain failures onto internal', async () => {
- const host = fakeHost({
- connect: async () => { throw new Error('tunnel broken') },
- })
- const { body } = await call(host, JSON.stringify({ method: 'machine.connect', payload: { machineId: 'm1' } }))
- expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'tunnel broken' } })
+ installHost(fakeHost({
+ connect: async () => {
+ throw new Error('tunnel broken')
+ },
+ }))
+ const connect = await call<SshConnectResponse>('POST', `${BASE}/machines/connect`, { machineId: 'm1' })
+ expect(connect.status).toBe(400)
+ expect(connect.body).toEqual({ error: 'tunnel broken' })
})
- it('maps non-Error failures onto internal', async () => {
- const host = fakeHost({
-
+ it('maps non-Error failures onto their string form', async () => {
+ installHost(fakeHost({
test: async () => {
- // eslint-disable-next-line no-throw-literal -- deliberately non-Error: covers failureOf's String(error) arm
+ // eslint-disable-next-line no-throw-literal
throw 'boom'
},
- })
- const { body } = await call(host, JSON.stringify({ method: 'machine.test', payload: { machineId: 'm1' } }))
- expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'boom' } })
+ }))
+ const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, { machineId: 'm1' })
+ expect(reply.status).toBe(400)
+ expect(reply.body).toEqual({ error: 'boom' })
})
it('requires a machineId on actions', async () => {
- const { body } = await call(fakeHost(), JSON.stringify({ method: 'machine.test', payload: {} }))
- expect(body).toEqual({ ok: false, error: { code: 'internal', message: 'missing machineId' } })
+ installHost(fakeHost())
+ const reply = await call<SshTestResponse>('POST', `${BASE}/machines/test`, {})
+ expect(reply.status).toBe(400)
+ expect(reply.body).toEqual({ error: 'missing machineId' })
})
it('serves the sync preview', async () => {
@@ -476,10 +598,10 @@ describe('/api-ssh handler', () => {
plugins: [{ name: 'dsh-market', spec: 'github:a/b', syncable: true }],
skills: [{ name: 'alpha', root: 'dsh' as const }],
}
- const host = fakeHost({ syncPreview: () => preview })
- const { status, body } = await call(host, JSON.stringify({ method: 'sync.preview' }))
- expect(status).toBe(200)
- expect(body).toEqual({ ok: true, value: preview })
+ installHost(fakeHost({ syncPreview: () => preview }))
+ const reply = await call<SyncPreviewResponse>('GET', `${BASE}/sync/preview`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual(preview)
})
it('applies a sync selection and returns per-item results', async () => {
@@ -489,96 +611,82 @@ describe('/api-ssh handler', () => {
{ kind: 'skill' as const, name: 'alpha', root: 'dsh' as const, ok: false, error: 'exit 1: read-only' },
],
}))
- const host = fakeHost({ syncApply })
- const { status, body } = await call(host, JSON.stringify({
- method: 'sync.apply',
- payload: {
- machineId: 'm1',
- plugins: [{ name: 'dsh-market', spec: 'github:a/b' }],
- skills: [{ name: 'alpha', root: 'dsh' }],
- },
- }))
- expect(status).toBe(200)
- expect(body).toMatchObject({ ok: true })
+ installHost(fakeHost({ syncApply }))
+ const reply = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, {
+ machineId: 'm1',
+ plugins: [{ name: 'dsh-market', spec: 'github:a/b' }],
+ skills: [{ name: 'alpha', root: 'dsh' }],
+ })
+ expect(reply.status).toBe(200)
expect(syncApply).toHaveBeenCalledWith(
MachineId('m1'),
[{ name: 'dsh-market', spec: 'github:a/b' }],
[{ name: 'alpha', root: 'dsh' }],
)
- const value = (body as { ok: true, value: { items: Array<Record<string, unknown>> } }).value
- expect(value.items).toHaveLength(2)
- expect(value.items[1]).toMatchObject({ ok: false, error: 'exit 1: read-only' })
+ expect(reply.body.items).toHaveLength(2)
+ expect(reply.body.items?.[1]).toMatchObject({ ok: false, error: 'exit 1: read-only' })
})
it('defaults an absent sync selection to empty lists', async () => {
const syncApply = vi.fn(async () => ({ items: [] }))
- const host = fakeHost({ syncApply })
- const { body } = await call(host, JSON.stringify({ method: 'sync.apply', payload: { machineId: 'm1' } }))
- expect(body).toMatchObject({ ok: true })
+ installHost(fakeHost({ syncApply }))
+ const reply = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, { machineId: 'm1' })
+ expect(reply.status).toBe(200)
expect(syncApply).toHaveBeenCalledWith(MachineId('m1'), [], [])
})
it('rejects malformed sync selections', async () => {
- const badPlugin = await call(fakeHost(), JSON.stringify({
- method: 'sync.apply',
- payload: { machineId: 'm1', plugins: [{ name: 'x' }] },
- }))
- expect(badPlugin.body).toMatchObject({ ok: false, error: { message: 'invalid plugin ref' } })
+ installHost(fakeHost())
+ const badPlugin = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, { machineId: 'm1', plugins: [{ name: 'x' }] })
+ expect(badPlugin.status).toBe(400)
+ expect(badPlugin.body).toEqual({ error: 'invalid plugin ref' })
- const badRoot = await call(fakeHost(), JSON.stringify({
- method: 'sync.apply',
- payload: { machineId: 'm1', skills: [{ name: 'x', root: 'elsewhere' }] },
- }))
- expect(badRoot.body).toMatchObject({ ok: false, error: { message: 'invalid skill ref: root' } })
+ const badRoot = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, { machineId: 'm1', skills: [{ name: 'x', root: 'elsewhere' }] })
+ expect(badRoot.body).toEqual({ error: 'invalid skill ref: root' })
- const notArray = await call(fakeHost(), JSON.stringify({
- method: 'sync.apply',
- payload: { machineId: 'm1', plugins: 'nope' },
- }))
- expect(notArray.body).toMatchObject({ ok: false, error: { message: 'invalid plugins' } })
- })
+ const notArray = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, { machineId: 'm1', plugins: 'nope' })
+ expect(notArray.body).toEqual({ error: 'invalid plugins' })
- it('rejects unknown methods', async () => {
- const { status, body } = await call(fakeHost(), JSON.stringify({ method: 'machine.warp' }))
- expect(status).toBe(404)
- expect(body).toMatchObject({ ok: false, error: { code: 'unknown-method' } })
+ const badSkills = await call<SyncApplyResponse>('POST', `${BASE}/sync/apply`, { machineId: 'm1', skills: 'nope' })
+ expect(badSkills.body).toEqual({ error: 'invalid skills' })
})
+
it('drains machine events from the beginning', async () => {
- const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1' } }))
- expect(response.status).toBe(200)
- expect(response.body).toEqual({
- ok: true,
- value: {
- events: [
- expect.objectContaining({ seq: 1, stage: 'probe' }),
- expect.objectContaining({ seq: 2, stage: 'download' }),
- expect.objectContaining({ seq: 3, stage: 'ready', terminal: 'success' }),
- ],
- nextSeq: 4,
- },
+ installHost(fakeHost())
+ const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1`)
+ expect(reply.status).toBe(200)
+ expect(reply.body).toEqual({
+ items: [
+ expect.objectContaining({ seq: 1, stage: 'probe' }),
+ expect.objectContaining({ seq: 2, stage: 'download' }),
+ expect.objectContaining({ seq: 3, stage: 'ready', terminal: 'success' }),
+ ],
+ nextSeq: 4,
})
})
it('drains machine events incrementally by sinceSeq', async () => {
- const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1', sinceSeq: 2 } }))
- expect(response.body).toMatchObject({
- ok: true,
- value: {
- events: [expect.objectContaining({ seq: 3 })],
- nextSeq: 4,
- },
- })
+ installHost(fakeHost())
+ const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=2`)
+ expect(reply.body).toMatchObject({ items: [expect.objectContaining({ seq: 3 })], nextSeq: 4 })
})
it('reports unknown event machines as an empty page anchored at seq 1', async () => {
- const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'ghost' } }))
- expect(response.body).toEqual({ ok: true, value: { events: [], nextSeq: 1 } })
+ installHost(fakeHost())
+ const reply = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=ghost`)
+ expect(reply.body).toEqual({ items: [], nextSeq: 1 })
})
it('rejects malformed event cursors', async () => {
- const response = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: { machineId: 'm1', sinceSeq: -1 } }))
- expect(response.body).toEqual({ ok: false, error: { code: 'internal', message: 'invalid sinceSeq' } })
- const missing = await call(fakeHost(), JSON.stringify({ method: 'machine.events', payload: {} }))
- expect(missing.body).toEqual({ ok: false, error: { code: 'internal', message: 'missing machineId' } })
+ installHost(fakeHost())
+ const negative = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=-1`)
+ expect(negative.status).toBe(400)
+ expect(negative.body).toEqual({ error: 'invalid sinceSeq' })
+
+ const fractional = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events?machineId=m1&sinceSeq=1.5`)
+ expect(fractional.body).toEqual({ error: 'invalid sinceSeq' })
+
+ const missing = await call<SshMachineEventsResponse>('GET', `${BASE}/machines/events`)
+ expect(missing.body).toEqual({ error: 'missing machineId' })
})
})
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.ts b/packages/dsh-tauri-ssh/src/host/routes/index.ts
index eca60618..f03dbeca 100644
--- a/packages/dsh-tauri-ssh/src/host/routes/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.ts
@@ -1,406 +1,30 @@
-/**
- * The plugin's own HTTP API, mounted by the plugin on `ctx.webServer` under
- * `/api-ssh` (same-origin with the web UI; no upstream gateway changes).
- * Loopback-only by construction: non-loopback peers are refused before any
- * dispatch. The protocol is a minimal JSON envelope:
- *
- * POST /api-ssh { "method": "machine.list", "payload": {} }
- * → 200 { "ok": true, "value": ... } | { "ok": false, "error": { "code", "message" } }
- *
- * The plugin state lives in the plugin-owned state document; this API serves
- * the feature switch (`settings.get`/`settings.set`), the connection plane
- * (list/test/connect/disconnect/install), the per-machine bootstrap event
- * drain (`machine.events`: ring-buffered, seq-cursored polling — no
- * SSE/WebSocket), and the CRUD writes (save/remove), which is exactly what the
- * settings page cannot do through the settings domain.
- * @module dsh-tauri-ssh/host/routes
- */
-
-import type { IncomingMessage, ServerResponse } from 'node:http'
-import type { MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshMachineEventsPage, SshMachineStatus, SshTestResult, SyncApplyResult, SyncPluginRef, SyncPreview, SyncSkillRef, SyncSkillRoot } from '../types/index'
-import { Buffer } from 'node:buffer'
-import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
-import { MachineId, SshError } from '../types/index'
-
-/** One request envelope. */
-export interface SshApiRequest {
- method: string
- payload?: unknown
-}
-
-/** One response envelope. */
-export type SshApiResponse
- = | { ok: true, value: unknown }
- | { ok: false, error: { code: string, message: string } }
-
-/**
- * The connection-plane method set (CRUD lives here too: the settings domain
- * only serves an upstream allowlist, so the page writes through this route),
- * the plugin state switch, plus the S4-owned `sync.*` surface.
- */
-export type SshApiMethod
- = | 'machine.list'
- | 'machine.test'
- | 'machine.connect'
- | 'machine.disconnect'
- | 'machine.install'
- | 'machine.events'
- | 'machine.save'
- | 'machine.remove'
- | 'session.role'
- | 'settings.get'
- | 'settings.set'
- | 'sync.preview'
- | 'sync.apply'
-
-/** A machine list row: the redacted profile plus its live status. */
-export interface SshMachineListItem extends MachineView {
- state: SshMachineStatus['state']
- tunnelBaseUrl?: string
- lastError?: string
- dshMissing?: boolean
- /** Epoch ms of the next scheduled reconnect retry (while reconnecting). */
- nextRetryAt?: number
- /** Which credential the live (or last successful) connection used. */
- authMethod?: SshMachineStatus['authMethod']
- /** Live progress of the in-flight operation. */
- progress?: SshMachineStatus['progress']
-}
-
-/** The manager face this API needs (the plugin's service). */
-export interface SshApiHost {
- /** Whether this host instance is itself a remote target of an SSH session. */
- sessionRole: () => { remote: boolean, origin?: string }
- /** Whether the SSH feature is switched on. */
- enabled: () => boolean
- /** Flip the feature switch. */
- setEnabled: (enabled: boolean) => Promise<void>
- profileViews: () => MachineView[]
- /** The read-only `~/.ssh/config` alias machines (awaits the config read). */
- discoveredViews: () => Promise<MachineView[]>
- status: (machineId: MachineId) => SshMachineStatus
- test: (machineId: MachineId, signal?: AbortSignal) => Promise<SshTestResult>
- connect: (machineId: MachineId, signal?: AbortSignal) => Promise<{ tunnelBaseUrl: string }>
- disconnect: (machineId: MachineId) => Promise<void>
- /** One-shot remote dsh install; a successful install auto-connects. */
- install: (machineId: MachineId, signal?: AbortSignal) => Promise<SshInstallResult>
- /** Drain one machine's bootstrap log/progress events after a seq cursor. */
- events: (machineId: MachineId, sinceSeq?: number) => SshMachineEventsPage
- save: (machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite) => Promise<void>
- remove: (machineId: MachineId) => Promise<void>
- /** The local plugins and skills available to sync (the selection list). */
- syncPreview: () => SyncPreview
- /** Sync the selection to one machine; every item settles in the result. */
- syncApply: (machineId: MachineId, plugins: SyncPluginRef[], skills: SyncSkillRef[]) => Promise<SyncApplyResult>
-}
-
-/** Whether a socket peer is loopback (the only allowed caller of this API). */
-export function isLoopbackPeer(address: string | undefined): boolean {
- return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
-}
-
-/** Map one business failure onto the envelope. */
-function failureOf(error: unknown): { code: string, message: string } {
- if (error instanceof SshError) {
- return { code: error.code, message: error.message }
- }
- return { code: 'internal', message: error instanceof Error ? error.message : String(error) }
-}
-
-/** Read and parse the request body (bounded). */
-async function readBody(req: IncomingMessage): Promise<unknown> {
- const chunks: Buffer[] = []
- let size = 0
- for await (const chunk of req) {
- const buffer = chunk as Buffer
- size += buffer.length
- if (size > 64 * 1024)
- throw new Error('request body too large')
- chunks.push(buffer)
- }
- return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown
-}
-
-/**
- * The origins the desktop shell's webview may cross-origin read this API from:
- * the Tauri 2 shell schemes (macOS/Linux `tauri://localhost`, Windows
- * `http://tauri.localhost`) and the dev-shell Vite origin. The embedded web UI
- * itself is same-origin and needs none of this; without these headers the
- * shell's switcher poll (`fetch` from the webview) is CORS-blocked with a bare
- * "Load failed". Any other origin stays blocked, so a rogue local page cannot
- * read (or preflight into) the API.
- */
-const SHELL_ORIGINS = new Set([
- 'tauri://localhost',
- 'http://tauri.localhost',
- 'http://localhost:1420',
-])
-
-/** CORS headers for one request's Origin, or none when the origin is not a shell origin. */
-function shellCorsHeaders(origin: string | undefined): Record<string, string> {
- if (origin === undefined || !SHELL_ORIGINS.has(origin))
- return {}
- return {
- 'access-control-allow-origin': origin,
- 'access-control-allow-methods': 'POST, OPTIONS',
- 'access-control-allow-headers': 'content-type',
- 'access-control-max-age': '86400',
- 'vary': 'Origin',
- }
-}
-
-/**
- * Build the `/api-ssh` request handler over one service.
- * @param host - the manager-backed service face.
- * @returns the node:http handler (owns the full response lifecycle).
- */
-export function createSshApiHandler(host: SshApiHost): (req: IncomingMessage, res: ServerResponse) => Promise<void> {
- return async (req, res) => {
- const cors = shellCorsHeaders(req.headers.origin)
- const respond = (status: number, body: SshApiResponse): void => {
- res.writeHead(status, { 'content-type': 'application/json', ...cors })
- res.end(JSON.stringify(body))
- }
- if (!isLoopbackPeer(req.socket.remoteAddress)) {
- respond(403, { ok: false, error: { code: 'forbidden', message: 'this API is loopback-only' } })
- return
- }
- // CORS preflight from the shell webview: answer without touching the body.
- if (req.method === 'OPTIONS') {
- if (cors['access-control-allow-origin'] === undefined) {
- respond(403, { ok: false, error: { code: 'forbidden', message: 'origin not allowed' } })
- return
- }
- res.writeHead(204, cors)
- res.end()
- return
- }
- if (req.method !== 'POST') {
- respond(405, { ok: false, error: { code: 'method-not-allowed', message: 'POST only' } })
- return
- }
- let request: SshApiRequest
- try {
- request = await readBody(req) as SshApiRequest
- }
- catch {
- respond(400, { ok: false, error: { code: 'bad-request', message: 'malformed JSON body' } })
- return
- }
- if (typeof request.method !== 'string' || request.method === '') {
- respond(400, { ok: false, error: { code: 'bad-request', message: 'missing method' } })
- return
- }
- const payload = (request.payload ?? {}) as Record<string, unknown>
- try {
- switch (request.method as SshApiMethod) {
- case 'session.role': {
- respond(200, { ok: true, value: host.sessionRole() })
- return
- }
- case 'settings.get': {
- respond(200, { ok: true, value: { enabled: host.enabled() } })
- return
- }
- case 'settings.set': {
- const enabled = enabledOf(payload)
- await host.setEnabled(enabled)
- respond(200, { ok: true, value: { enabled } })
- return
- }
- case 'machine.list': {
- // 未启用:不枚举任何机器(不读 ~/.ssh/config,也不碰连接面),只回报开关,
- // 壳层据此不渲染「本地」控件。
- if (!host.enabled()) {
- respond(200, { ok: true, value: { enabled: false, items: [], discovered: [] } })
- return
- }
- const items: SshMachineListItem[] = host.profileViews().map(view => listItemOf(host, view))
- const discovered: SshMachineListItem[] = (await host.discoveredViews()).map(view => listItemOf(host, view))
- respond(200, { ok: true, value: { enabled: true, items, discovered } })
- return
- }
- case 'machine.test': {
- const value = await host.test(machineIdOf(payload), new AbortController().signal)
- respond(200, { ok: true, value })
- return
- }
- case 'machine.connect': {
- const link = await host.connect(machineIdOf(payload), new AbortController().signal)
- respond(200, { ok: true, value: { tunnelBaseUrl: link.tunnelBaseUrl } })
- return
- }
- case 'machine.disconnect': {
- await host.disconnect(machineIdOf(payload))
- respond(200, { ok: true, value: {} })
- return
- }
- case 'machine.install': {
- const value = await host.install(machineIdOf(payload), new AbortController().signal)
- respond(200, { ok: true, value })
- return
- }
- case 'machine.events': {
- const machineId = machineIdOf(payload)
- const sinceSeq = sinceSeqOf(payload)
- respond(200, { ok: true, value: host.events(machineId, sinceSeq) })
- return
- }
- case 'machine.save': {
- const machineId = machineIdOf(payload)
- const row = saveRowOf(payload)
- const secrets = secretsOf(payload)
- await host.save(machineId, row, secrets)
- respond(200, { ok: true, value: {} })
- return
- }
- case 'machine.remove': {
- const machineId = machineIdOf(payload)
- await host.remove(machineId)
- respond(200, { ok: true, value: {} })
- return
- }
- case 'sync.preview': {
- respond(200, { ok: true, value: host.syncPreview() })
- return
- }
- case 'sync.apply': {
- const machineId = machineIdOf(payload)
- const value = await host.syncApply(machineId, pluginRefsOf(payload), skillRefsOf(payload))
- respond(200, { ok: true, value })
- return
- }
- default:
- respond(404, { ok: false, error: { code: 'unknown-method', message: `unknown method "${request.method}"` } })
- }
- }
- catch (error) {
- respond(200, { ok: false, error: failureOf(error) })
- }
- }
-}
-
-/** Read the machineId payload field; missing payloads fail loud. */
-function machineIdOf(payload: Record<string, unknown>): MachineId {
- if (typeof payload.machineId !== 'string' || payload.machineId === '') {
- throw new Error('missing machineId')
- }
- return MachineId(payload.machineId)
-}
-
-/** Read the settings.set payload; a non-boolean switch fails loud. */
-function enabledOf(payload: Record<string, unknown>): boolean {
- if (typeof payload.enabled !== 'boolean')
- throw new Error('missing enabled')
- return payload.enabled
-}
-
-/** Read the optional event poll cursor; absent or non-numeric means "from the start". */
-function sinceSeqOf(payload: Record<string, unknown>): number | undefined {
- if (payload.sinceSeq === undefined)
- return undefined
- if (typeof payload.sinceSeq !== 'number' || !Number.isInteger(payload.sinceSeq) || payload.sinceSeq < 0) {
- throw new Error('invalid sinceSeq')
- }
- return payload.sinceSeq
-}
-
-/** One list row: the redacted view plus its live status. */
-function listItemOf(host: SshApiHost, view: MachineView): SshMachineListItem {
- const status = host.status(view.id)
- return {
- ...view,
- state: status.state,
- ...status.tunnelBaseUrl === undefined ? {} : { tunnelBaseUrl: status.tunnelBaseUrl },
- ...status.lastError === undefined ? {} : { lastError: status.lastError },
- ...status.dshMissing === true ? { dshMissing: true } : {},
- ...status.progress === undefined ? {} : { progress: status.progress },
- ...status.nextRetryAt === undefined ? {} : { nextRetryAt: status.nextRetryAt },
- ...status.authMethod === undefined ? {} : { authMethod: status.authMethod },
- }
-}
-
-/** Validate one machine.save config row; defaults mirror the schema. */
-function saveRowOf(payload: Record<string, unknown>): MachineSaveRow {
- const row = payload.row
- if (typeof row !== 'object' || row === null)
- throw new Error('missing row')
- const value = row as Record<string, unknown>
- if (typeof value.name !== 'string' || value.name === '')
- throw new Error('invalid row: name')
- if (typeof value.host !== 'string' || value.host === '')
- throw new Error('invalid row: host')
- if (typeof value.user !== 'string')
- throw new Error('invalid row: user')
- const port = typeof value.port === 'number' ? value.port : DEFAULT_SSH_PORT
- const remotePort = typeof value.remotePort === 'number' ? value.remotePort : DEFAULT_REMOTE_PORT
- const startCommand = typeof value.startCommand === 'string' && value.startCommand !== ''
- ? value.startCommand
- : undefined
- const rawProfileName = typeof value.profileName === 'string' ? value.profileName.trim() : ''
- const profileName = /^[\w-]+$/.test(rawProfileName) ? rawProfileName : undefined
- const color = typeof value.color === 'string' && value.color !== '' ? value.color : undefined
- return {
- name: value.name,
- host: value.host,
- port,
- user: value.user,
- remotePort,
- ...profileName === undefined ? {} : { profileName },
- ...startCommand === undefined ? {} : { startCommand },
- ...color === undefined ? {} : { color },
- ...value.tintBorder === true ? { tintBorder: true } : {},
- }
-}
-
-/** Validate the write-only secret block; absent or empty fields are dropped. */
-function secretsOf(payload: Record<string, unknown>): MachineSecretWrite | undefined {
- const secrets = payload.secrets
- if (secrets === undefined)
- return undefined
- if (typeof secrets !== 'object' || secrets === null)
- throw new Error('invalid secrets')
- const value = secrets as Record<string, unknown>
- const out: MachineSecretWrite = {}
- if (typeof value.password === 'string' && value.password !== '')
- out.password = value.password
- if (typeof value.passphrase === 'string' && value.passphrase !== '')
- out.passphrase = value.passphrase
- return out
-}
-
-/** Validate the sync.apply plugin refs; the panel sends its display names along. */
-function pluginRefsOf(payload: Record<string, unknown>): SyncPluginRef[] {
- const list = payload.plugins
- if (list === undefined)
- return []
- if (!Array.isArray(list))
- throw new Error('invalid plugins')
- return list.map((entry) => {
- if (typeof entry !== 'object' || entry === null)
- throw new Error('invalid plugin ref')
- const ref = entry as Record<string, unknown>
- if (typeof ref.name !== 'string' || typeof ref.spec !== 'string' || ref.spec === '')
- throw new Error('invalid plugin ref')
- return { name: ref.name, spec: ref.spec }
- })
-}
-
-/** Validate the sync.apply skill refs; the root picks the local source tree. */
-function skillRefsOf(payload: Record<string, unknown>): SyncSkillRef[] {
- const list = payload.skills
- if (list === undefined)
- return []
- if (!Array.isArray(list))
- throw new Error('invalid skills')
- return list.map((entry) => {
- if (typeof entry !== 'object' || entry === null)
- throw new Error('invalid skill ref')
- const ref = entry as Record<string, unknown>
- if (typeof ref.name !== 'string' || ref.name === '')
- throw new Error('invalid skill ref')
- if (ref.root !== 'dsh' && ref.root !== 'agents')
- throw new Error('invalid skill ref: root')
- return { name: ref.name, root: ref.root as SyncSkillRoot }
- })
-}
+import { defineRoutes } from 'dsh-tauri'
+import machinesConnect from './machines/connect/post'
+import machinesDelete from './machines/delete'
+import machinesDisconnect from './machines/disconnect/post'
+import machinesEvents from './machines/events/get'
+import machinesGet from './machines/get'
+import machinesInstall from './machines/install/post'
+import machinesPost from './machines/post'
+import machinesTest from './machines/test/post'
+import sessionRole from './session/role/get'
+import settingsGet from './settings/get'
+import settingsPost from './settings/post'
+import syncApply from './sync/apply/post'
+import syncPreview from './sync/preview/get'
+
+export const routes = defineRoutes((disposer) => {
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/settings' }, settingsGet)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/settings' }, settingsPost)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/session/role' }, sessionRole)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines' }, machinesGet)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines' }, machinesPost)
+ disposer.delete({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines' }, machinesDelete)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines/test' }, machinesTest)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines/connect' }, machinesConnect)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines/disconnect' }, machinesDisconnect)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines/install' }, machinesInstall)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/machines/events' }, machinesEvents)
+ disposer.get({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/sync/preview' }, syncPreview)
+ disposer.post({ kind: 'exact', path: '/api/desktop/dsh-tauri-ssh/sync/apply' }, syncApply)
+})
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.types.ts b/packages/dsh-tauri-ssh/src/host/routes/index.types.ts
new file mode 100644
index 00000000..26049109
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.types.ts
@@ -0,0 +1,168 @@
+import type { SshAuthMethod, SshConnectionState, SshProgress } from '../types/index'
+
+export interface SshMachineListItem {
+ id?: string
+ name?: string
+ host?: string
+ port?: number
+ user?: string
+ hasPassword?: boolean
+ hasPassphrase?: boolean
+ remotePort?: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+ state?: SshConnectionState
+ tunnelBaseUrl?: string
+ lastError?: string
+ dshMissing?: boolean
+ progress?: SshProgress
+ nextRetryAt?: number
+ authMethod?: SshAuthMethod
+}
+
+export interface SshSettingsBody {
+ enabled?: boolean
+}
+
+export interface SshSettingsResponse {
+ enabled?: boolean
+ error?: string
+}
+
+export interface SshSessionRoleResponse {
+ role?: string
+ remote?: boolean
+ origin?: string
+ error?: string
+}
+
+export interface SshMachinesResponse {
+ enabled?: boolean
+ items?: SshMachineListItem[]
+ discovered?: SshMachineListItem[]
+ error?: string
+}
+
+export interface SshMachineRowBody {
+ name?: string
+ host?: string
+ port?: number
+ user?: string
+ remotePort?: number
+ profileName?: string
+ startCommand?: string
+ color?: string
+ tintBorder?: boolean
+}
+
+export interface SshMachineSecretsBody {
+ password?: string
+ passphrase?: string
+}
+
+export interface SshMachineSaveBody {
+ machineId?: string
+ row?: SshMachineRowBody
+ secrets?: SshMachineSecretsBody
+}
+
+export interface SshMachineIdBody {
+ machineId?: string
+}
+
+export interface SshMachineEventsQuery {
+ machineId?: string
+ sinceSeq?: number
+}
+
+export interface SshMachineEventItem {
+ seq?: number
+ ts?: string
+ machineId?: string
+ stage?: string
+ line?: string
+ terminal?: string
+ reason?: string
+}
+
+export interface SshMachineEventsResponse {
+ items?: SshMachineEventItem[]
+ nextSeq?: number
+ error?: string
+}
+
+export interface SshTestResponse {
+ ok?: boolean
+ banner?: string
+ message?: string
+ error?: string
+}
+
+export interface SshConnectResponse {
+ tunnelBaseUrl?: string
+ error?: string
+}
+
+export interface SshInstallResponse {
+ installed?: string[]
+ dshRef?: string
+ dshVersion?: string
+ dshPath?: string
+ credentialsCopied?: boolean
+ credentialsError?: string
+ error?: string
+}
+
+export interface SshActionResponse {
+ error?: string
+}
+
+export interface SyncPreviewPluginItem {
+ name?: string
+ spec?: string
+ syncable?: boolean
+ reason?: string
+}
+
+export interface SyncPreviewSkillItem {
+ name?: string
+ root?: string
+}
+
+export interface SyncPreviewResponse {
+ plugins?: SyncPreviewPluginItem[]
+ skills?: SyncPreviewSkillItem[]
+ error?: string
+}
+
+export interface SyncPluginRefBody {
+ name?: string
+ spec?: string
+}
+
+export interface SyncSkillRefBody {
+ name?: string
+ root?: string
+}
+
+export interface SyncApplyBody {
+ machineId?: string
+ plugins?: SyncPluginRefBody[]
+ skills?: SyncSkillRefBody[]
+}
+
+export interface SyncApplyItemResult {
+ kind?: string
+ name?: string
+ root?: string
+ ok?: boolean
+ error?: string
+ log?: string
+}
+
+export interface SyncApplyResponse {
+ items?: SyncApplyItemResult[]
+ error?: string
+}
diff --git a/packages/dsh-tauri-ssh/src/host/routes/index.utils.ts b/packages/dsh-tauri-ssh/src/host/routes/index.utils.ts
new file mode 100644
index 00000000..04f7792f
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/index.utils.ts
@@ -0,0 +1,133 @@
+import type { MachineSaveRow, MachineSecretWrite, MachineView, SshMachineStatus, SyncPluginRef, SyncSkillRef, SyncSkillRoot } from '../types/index'
+import type { SshMachineListItem } from './index.types'
+import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
+import { MachineId } from '../types/index'
+
+export async function guarded<T>(event: { res: { status?: number } }, run: () => Promise<T>): Promise<T | { error: string }> {
+ try {
+ return await run()
+ }
+ catch (error) {
+ const status = typeof error === 'object' && error !== null ? (error as { statusCode?: unknown }).statusCode : undefined
+ if (typeof status === 'number')
+ throw error
+ event.res.status = 400
+ return { error: error instanceof Error ? error.message : String(error) }
+ }
+}
+
+export function listItemOf(view: MachineView, status: SshMachineStatus): SshMachineListItem {
+ return {
+ ...view,
+ state: status.state,
+ ...status.tunnelBaseUrl === undefined ? {} : { tunnelBaseUrl: status.tunnelBaseUrl },
+ ...status.lastError === undefined ? {} : { lastError: status.lastError },
+ ...status.dshMissing === true ? { dshMissing: true } : {},
+ ...status.progress === undefined ? {} : { progress: status.progress },
+ ...status.nextRetryAt === undefined ? {} : { nextRetryAt: status.nextRetryAt },
+ ...status.authMethod === undefined ? {} : { authMethod: status.authMethod },
+ }
+}
+
+export function machineIdOf(value: { machineId?: unknown }): MachineId {
+ if (typeof value.machineId !== 'string' || value.machineId === '')
+ throw new Error('missing machineId')
+ return MachineId(value.machineId)
+}
+
+export function enabledOf(value: { enabled?: unknown }): boolean {
+ if (typeof value.enabled !== 'boolean')
+ throw new Error('missing enabled')
+ return value.enabled
+}
+
+export function sinceSeqOf(value: { sinceSeq?: unknown }): number | undefined {
+ const raw = value.sinceSeq
+ if (raw === undefined || raw === '')
+ return undefined
+ const seq = typeof raw === 'number' ? raw : typeof raw === 'string' && /^\d+$/.test(raw) ? Number(raw) : Number.NaN
+ if (!Number.isInteger(seq) || seq < 0)
+ throw new Error('invalid sinceSeq')
+ return seq
+}
+
+export function saveRowOf(value: { row?: unknown }): MachineSaveRow {
+ const row = value.row
+ if (typeof row !== 'object' || row === null)
+ throw new Error('missing row')
+ const fields = row as Record<string, unknown>
+ if (typeof fields.name !== 'string' || fields.name === '')
+ throw new Error('invalid row: name')
+ if (typeof fields.host !== 'string' || fields.host === '')
+ throw new Error('invalid row: host')
+ if (typeof fields.user !== 'string')
+ throw new Error('invalid row: user')
+ const port = typeof fields.port === 'number' ? fields.port : DEFAULT_SSH_PORT
+ const remotePort = typeof fields.remotePort === 'number' ? fields.remotePort : DEFAULT_REMOTE_PORT
+ const startCommand = typeof fields.startCommand === 'string' && fields.startCommand !== ''
+ ? fields.startCommand
+ : undefined
+ const rawProfileName = typeof fields.profileName === 'string' ? fields.profileName.trim() : ''
+ const profileName = /^[\w-]+$/.test(rawProfileName) ? rawProfileName : undefined
+ const color = typeof fields.color === 'string' && fields.color !== '' ? fields.color : undefined
+ return {
+ name: fields.name,
+ host: fields.host,
+ port,
+ user: fields.user,
+ remotePort,
+ ...profileName === undefined ? {} : { profileName },
+ ...startCommand === undefined ? {} : { startCommand },
+ ...color === undefined ? {} : { color },
+ ...fields.tintBorder === true ? { tintBorder: true } : {},
+ }
+}
+
+export function secretsOf(value: { secrets?: unknown }): MachineSecretWrite | undefined {
+ const secrets = value.secrets
+ if (secrets === undefined)
+ return undefined
+ if (typeof secrets !== 'object' || secrets === null)
+ throw new Error('invalid secrets')
+ const fields = secrets as Record<string, unknown>
+ const out: MachineSecretWrite = {}
+ if (typeof fields.password === 'string' && fields.password !== '')
+ out.password = fields.password
+ if (typeof fields.passphrase === 'string' && fields.passphrase !== '')
+ out.passphrase = fields.passphrase
+ return out
+}
+
+export function pluginRefsOf(value: { plugins?: unknown }): SyncPluginRef[] {
+ const list = value.plugins
+ if (list === undefined)
+ return []
+ if (!Array.isArray(list))
+ throw new Error('invalid plugins')
+ return list.map((entry) => {
+ if (typeof entry !== 'object' || entry === null)
+ throw new Error('invalid plugin ref')
+ const ref = entry as Record<string, unknown>
+ if (typeof ref.name !== 'string' || typeof ref.spec !== 'string' || ref.spec === '')
+ throw new Error('invalid plugin ref')
+ return { name: ref.name, spec: ref.spec }
+ })
+}
+
+export function skillRefsOf(value: { skills?: unknown }): SyncSkillRef[] {
+ const list = value.skills
+ if (list === undefined)
+ return []
+ if (!Array.isArray(list))
+ throw new Error('invalid skills')
+ return list.map((entry) => {
+ if (typeof entry !== 'object' || entry === null)
+ throw new Error('invalid skill ref')
+ const ref = entry as Record<string, unknown>
+ if (typeof ref.name !== 'string' || ref.name === '')
+ throw new Error('invalid skill ref')
+ if (ref.root !== 'dsh' && ref.root !== 'agents')
+ throw new Error('invalid skill ref: root')
+ return { name: ref.name, root: ref.root as SyncSkillRoot }
+ })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/connect/post.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/connect/post.ts
new file mode 100644
index 00000000..3aa2af0c
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/connect/post.ts
@@ -0,0 +1,12 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshConnectResponse, SshMachineIdBody } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../../service/machine'
+import { guarded, machineIdOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshConnectResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+ const link = await machine.connect(machineIdOf(body), new AbortController().signal)
+ return { tunnelBaseUrl: link.tunnelBaseUrl }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/delete.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/delete.ts
new file mode 100644
index 00000000..87ab816f
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/delete.ts
@@ -0,0 +1,12 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshActionResponse, SshMachineIdBody } from '../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../service/machine'
+import { guarded, machineIdOf } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+ await machine.remove(machineIdOf(body))
+ return {}
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/disconnect/post.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/disconnect/post.ts
new file mode 100644
index 00000000..13deddb5
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/disconnect/post.ts
@@ -0,0 +1,12 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshActionResponse, SshMachineIdBody } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../../service/machine'
+import { guarded, machineIdOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+ await machine.disconnect(machineIdOf(body))
+ return {}
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/events/get.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/events/get.ts
new file mode 100644
index 00000000..ca9c162a
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/events/get.ts
@@ -0,0 +1,12 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshMachineEventsQuery, SshMachineEventsResponse } from '../../index.types'
+import { defineEventHandler, getQuery } from 'dsh-tauri'
+import { events } from '../../../service/events'
+import { guarded, machineIdOf, sinceSeqOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshMachineEventsResponse>>(async event =>
+ guarded(event, async () => {
+ const query = getQuery<SshMachineEventsQuery>(event)
+ const page = events.since(machineIdOf(query), sinceSeqOf(query))
+ return { items: page.events, nextSeq: page.nextSeq }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/get.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/get.ts
new file mode 100644
index 00000000..f31bf55b
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/get.ts
@@ -0,0 +1,14 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshMachinesResponse } from '../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { machine } from '../../service/machine'
+import { guarded, listItemOf } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshMachinesResponse>>(async event =>
+ guarded(event, async () => {
+ if (!machine.enabled())
+ return { enabled: false, items: [], discovered: [] }
+ const items = machine.profileViews().map(view => listItemOf(view, machine.status(view.id)))
+ const discovered = (await machine.discoveredViews()).map(view => listItemOf(view, machine.status(view.id)))
+ return { enabled: true, items, discovered }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/install/post.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/install/post.ts
new file mode 100644
index 00000000..1f7a8302
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/install/post.ts
@@ -0,0 +1,11 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshInstallResponse, SshMachineIdBody } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../../service/machine'
+import { guarded, machineIdOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshInstallResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+ return await machine.install(machineIdOf(body), new AbortController().signal)
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/post.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/post.ts
new file mode 100644
index 00000000..3138197c
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/post.ts
@@ -0,0 +1,12 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshActionResponse, SshMachineSaveBody } from '../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../service/machine'
+import { guarded, machineIdOf, saveRowOf, secretsOf } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshActionResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineSaveBody>(event)) ?? {}
+ await machine.save(machineIdOf(body), saveRowOf(body), secretsOf(body))
+ return {}
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/machines/test/post.ts b/packages/dsh-tauri-ssh/src/host/routes/machines/test/post.ts
new file mode 100644
index 00000000..18f1b190
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/machines/test/post.ts
@@ -0,0 +1,11 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshMachineIdBody, SshTestResponse } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../../service/machine'
+import { guarded, machineIdOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshTestResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshMachineIdBody>(event)) ?? {}
+ return await machine.test(machineIdOf(body), new AbortController().signal)
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/session/role/get.ts b/packages/dsh-tauri-ssh/src/host/routes/session/role/get.ts
new file mode 100644
index 00000000..6dd0b673
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/session/role/get.ts
@@ -0,0 +1,11 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshSessionRoleResponse } from '../../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { session } from '../../../service/session'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshSessionRoleResponse>>(async event =>
+ guarded(event, async () => {
+ const role = session.role()
+ return { ...role, role: role.remote ? 'remote' : 'local' }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/settings/get.ts b/packages/dsh-tauri-ssh/src/host/routes/settings/get.ts
new file mode 100644
index 00000000..5c89c4b5
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/settings/get.ts
@@ -0,0 +1,8 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshSettingsResponse } from '../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { machine } from '../../service/machine'
+import { guarded } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshSettingsResponse>>(async event =>
+ guarded(event, async () => ({ enabled: machine.enabled() })))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/settings/post.ts b/packages/dsh-tauri-ssh/src/host/routes/settings/post.ts
new file mode 100644
index 00000000..6617d433
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/settings/post.ts
@@ -0,0 +1,13 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SshSettingsBody, SshSettingsResponse } from '../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { machine } from '../../service/machine'
+import { enabledOf, guarded } from '../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SshSettingsResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SshSettingsBody>(event)) ?? {}
+ const enabled = enabledOf(body)
+ await machine.setEnabled(enabled)
+ return { enabled }
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/sync/apply/post.ts b/packages/dsh-tauri-ssh/src/host/routes/sync/apply/post.ts
new file mode 100644
index 00000000..02ce1fef
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/sync/apply/post.ts
@@ -0,0 +1,11 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SyncApplyBody, SyncApplyResponse } from '../../index.types'
+import { defineEventHandler, readBody } from 'dsh-tauri'
+import { sync } from '../../../service/sync'
+import { guarded, machineIdOf, pluginRefsOf, skillRefsOf } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SyncApplyResponse>>(async event =>
+ guarded(event, async () => {
+ const body = (await readBody<SyncApplyBody>(event)) ?? {}
+ return await sync.apply(machineIdOf(body), pluginRefsOf(body), skillRefsOf(body))
+ }))
diff --git a/packages/dsh-tauri-ssh/src/host/routes/sync/preview/get.ts b/packages/dsh-tauri-ssh/src/host/routes/sync/preview/get.ts
new file mode 100644
index 00000000..3ed7da51
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/routes/sync/preview/get.ts
@@ -0,0 +1,8 @@
+import type { EventHandlerRequest } from 'dsh-tauri'
+import type { SyncPreviewResponse } from '../../index.types'
+import { defineEventHandler } from 'dsh-tauri'
+import { sync } from '../../../service/sync'
+import { guarded } from '../../index.utils'
+
+export default defineEventHandler<EventHandlerRequest, Promise<SyncPreviewResponse>>(async event =>
+ guarded(event, async () => sync.preview()))
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts
index 5e535ed9..8d234918 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.arm64-dryrun.test.ts
@@ -1,17 +1,7 @@
/* eslint-disable no-console -- the run's console output IS the recorded evidence */
-/**
- * arm64 substitute evidence (spec S2 acceptance 6): no arm64 machine exists,
- * so the dry run resolves the REAL linux/arm64 install plan against the live
- * npm registry and proves every download URL answers — without writing any
- * bytes to disk. Gated behind `DSH_SSH_ARM64_DRYRUN=1`:
- *
- * DSH_SSH_ARM64_DRYRUN=1 pnpm --filter dsh-tauri-ssh exec vitest run \
- * src/host/service/bootstrap.arm64-dryrun.test.ts
- * @module dsh-tauri-ssh/host/service/bootstrap.arm64-dryrun
- */
import { describe, expect, it } from 'vitest'
-import { buildInstallScript, planRemoteInstall } from './bootstrap'
+import { buildInstallScript, planRemoteInstall } from './bootstrap.utils'
const RUN = process.env.DSH_SSH_ARM64_DRYRUN === '1'
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
index bc799450..ac1fed21 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.e2e.test.ts
@@ -1,32 +1,24 @@
-/**
- * Real-machine E2E (linux x64): a fresh remote bootstrap through the REAL
- * transport, planner (live GitHub metadata), install script, launch, and
- * boot-HTML readiness, then a reconnect that skips the install. Gated behind
- * `DSH_SSH_E2E_HOST` so the ordinary test run never needs a remote:
- *
- * DSH_SSH_E2E_HOST=dev pnpm --filter dsh-tauri-ssh exec vitest run \
- * src/host/service/bootstrap.e2e.test.ts
- *
- * Shares the machine with parallel nodes: default layout (`~/.dsh-desktop`)
- * and the default port, leftover processes cleaned before and after, and the
- * installed tree deliberately left in place (the shared "already
- * initialized" state other nodes may reuse).
- * @module dsh-tauri-ssh/host/service/bootstrap.e2e
- */
-
/* eslint-disable no-console -- the run's console output IS the recorded evidence */
-import type { MachineProfile, SshLink } from '../types/index'
-import type { SshTransport } from './transport'
+import type { MachineProfile, SshLink, SshSession } from '../types/index'
+import type { SshTransportOptions } from './transport.types'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { clearHostRuntime, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
import { MachineId } from '../types/index'
-import { SshMachineEvents } from './events'
-import { KnownHostsStore } from './host-keys'
-import { SshManager } from './manager'
-import { SshConfigResolver } from './ssh-config'
-import { Ssh2Transport } from './transport'
+import { EMPTY_ALLOWLIST } from '../utils/allowlist'
+import { resolveSshAuth } from '../utils/ssh-config'
+import { events } from './events'
+import { machine } from './machine'
+import { transport } from './transport'
+
+const HOME_DIR = process.env.HOME ?? ''
+const SSH_DIR = join(HOME_DIR, '.ssh')
+
+function credentialsOf(target: MachineProfile) {
+ return resolveSshAuth(target, SSH_DIR, HOME_DIR)
+}
/** The shared dev machine alias from `~/.ssh/config` (key auth). */
const HOST = process.env.DSH_SSH_E2E_HOST
@@ -97,30 +89,32 @@ EOF
describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', () => {
const roots: string[] = []
- let manager!: SshManager
- let events!: SshMachineEvents
- let transport!: SshTransport
+ const options: SshTransportOptions = {
+ readyTimeoutMs: E2E_CONFIG.connectTimeoutMs,
+ resolveProfile: credentialsOf,
+ keepaliveIntervalMs: E2E_CONFIG.keepaliveIntervalMs,
+ keepaliveCountMax: E2E_CONFIG.keepaliveCountMax,
+ }
+
+ async function openRaw(): Promise<SshSession> {
+ return await transport.connect(profile, () => true, options)
+ }
beforeAll(() => {
const known = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-'))
roots.push(known)
- events = new SshMachineEvents()
- transport = new Ssh2Transport(E2E_CONFIG.connectTimeoutMs, new SshConfigResolver(join(process.env.HOME ?? '', '.ssh'), process.env.HOME ?? ''))
- manager = new SshManager({
- transport,
- knownHosts: new KnownHostsStore(join(known, 'known-hosts.json')),
- config: E2E_CONFIG,
- events,
- emitStatus: () => {},
- })
- manager.refreshProfiles(new Map([[profile.id, profile]]))
+ clearHostRuntime()
+ setHostConfig({ ...E2E_CONFIG, sshDir: SSH_DIR })
+ setKnownHostsPath(join(known, 'known-hosts.json'))
+ setMachineDeps({ transport, emitStatus: () => {}, localAllowlist: () => EMPTY_ALLOWLIST })
+ machine.refreshProfiles(new Map([[profile.id, profile]]))
})
afterAll(async () => {
- await manager.disconnect(profile.id).catch(() => undefined)
- await manager.dispose().catch(() => undefined)
+ await machine.disconnect(profile.id).catch(() => undefined)
+ await machine.dispose().catch(() => undefined)
// Leave the installed tree for sibling nodes; stop only our processes.
- const session = await transport.connect(profile, () => true).catch(() => undefined)
+ const session = await openRaw().catch(() => undefined)
if (session !== undefined) {
const leftovers = await session.exec(`${CLEANUP_COMMAND}\nrm -f "$HOME/.dsh-e2e-port.yml"`).catch(() => undefined)
const remaining = (leftovers?.stdout ?? '(probe failed)').trim()
@@ -136,7 +130,7 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
it('bootstraps a fresh machine end to end (probe → download → verify → install → launch → ready)', async () => {
// Fresh start: stop leftover shared-layout processes, wipe the tree, and
// stage the port overlay the launch's --patch consumes.
- const cleaner = await transport.connect(profile, () => true)
+ const cleaner = await openRaw()
const wiped = await cleaner.exec(`${CLEANUP_COMMAND}\nrm -rf "$HOME/.dsh-desktop"\n${PORT_PATCH_COMMAND}\n[ -f "$HOME/.dsh-e2e-port.yml" ] && [ ! -e "$HOME/.dsh-desktop" ] && echo wiped`)
await cleaner.close()
expect(wiped.stdout).toContain('wiped')
@@ -144,7 +138,7 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
const startedAt = Date.now()
let link: SshLink
try {
- link = await manager.connect(profile.id)
+ link = await machine.connect(profile.id)
}
catch (error) {
// Surface everything the event channel captured before failing.
@@ -169,11 +163,11 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
// readiness is judged by the legacy fallback — the designed behavior;
// instances that serve the SPA manifest take the boot-HTML path instead.
console.log(`[e2e] readiness judged by: ${ready?.line}`)
- expect(manager.status(profile.id).state).toBe('connected')
+ expect(machine.status(profile.id).state).toBe('connected')
}, 30 * 60_000)
it('installs the shared default layout with working binaries', async () => {
- const session = await transport.connect(profile, () => true)
+ const session = await openRaw()
const probe = await session.exec(
`"$HOME/.dsh-desktop/runtime/bin/node" --version && ls "$HOME/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js" >/dev/null && echo entry-ok && ls "$HOME/.dsh-desktop/dependencies/pnpm/bin/pnpm.cjs" >/dev/null && echo pnpm-ok`,
)
@@ -186,9 +180,9 @@ describe.skipIf(HOST === undefined)('bootstrap E2E (real linux x64 remote)', ()
})
it('reconnects without reinstalling and returns to ready', async () => {
- await manager.disconnect(profile.id)
+ await machine.disconnect(profile.id)
const page0 = events.since(profile.id)
- const link = await manager.connect(profile.id)
+ const link = await machine.connect(profile.id)
expect(link.tunnelBaseUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/)
const page1 = events.since(profile.id)
const fresh = page1.events.filter(event => event.seq > (page0.events.at(-1)?.seq ?? 0))
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
index 641ead46..98eaf6c1 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.test.ts
@@ -1,6 +1,5 @@
-import type { MachineProfile } from '../types/index'
-import type { RemoteInstallPlan } from './bootstrap'
-import type { SshExecOptions, SshExecResult, SshSession } from './transport'
+import type { MachineProfile, SshExecOptions, SshExecResult, SshSession } from '../types/index'
+import type { RemoteInstallPlan } from './bootstrap.types'
import { Buffer } from 'node:buffer'
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
@@ -8,8 +7,10 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, st
import { tmpdir } from 'node:os'
import { promisify } from 'node:util'
import { join } from 'pathe'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { REMOTE_ROOT } from '../config/constants'
import { MachineId } from '../types/index'
+import { FALLBACK_DSH_TAG, RECOMMENDED_DSH_VERSION } from '../utils/version'
import {
buildInstallScript,
bundleProbeCommand,
@@ -27,13 +28,11 @@ import {
planRemoteInstall,
readEnvCredentials,
REMOTE_PROBE_NO_DOWNLOADER,
- REMOTE_ROOT,
rootProbeCommand,
skippedVerificationSummary,
splitBundleProbeStdout,
startCommandFor,
-} from './bootstrap'
-import { FALLBACK_DSH_TAG, RECOMMENDED_DSH_VERSION } from './version'
+} from './bootstrap.utils'
const profile: MachineProfile = {
id: MachineId('m1'),
@@ -88,6 +87,20 @@ function healthyFetchers(overrides: Partial<{
}
}
+function githubJson(body: unknown): { ok: boolean, status: number, json: () => Promise<unknown> } {
+ return { ok: true, status: 200, json: async () => body }
+}
+
+function stubGithub(): void {
+ vi.stubGlobal('fetch', (url: string) => {
+ if (url.includes('/releases?per_page='))
+ return Promise.resolve(githubJson(RELEASES.map(release => ({ tag_name: release.tag, prerelease: release.prerelease }))))
+ if (url.includes('/releases/tags/'))
+ return Promise.resolve(githubJson({ assets: LINUX_ASSETS.map(asset => ({ name: asset.name, browser_download_url: asset.url, digest: asset.digest })) }))
+ return Promise.reject(new Error(`unexpected fetch ${url}`))
+ })
+}
+
class FakeSession implements SshSession {
commands: string[] = []
@@ -117,6 +130,17 @@ function tempDir(): string {
return dir
}
+function runCommand(command: string, sandbox: string): Promise<{ code: number, stdout: string, stderr: string }> {
+ const scriptPath = join(sandbox, 'command.sh')
+ writeFileSync(scriptPath, command)
+ const run = promisify(execFile)
+ return run('sh', [scriptPath], { env: { ...process.env, HOME: sandbox } }).then(
+ ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),
+ (error: { code?: number, stdout?: string, stderr?: string }) =>
+ ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),
+ )
+}
+
afterEach(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
@@ -200,6 +224,8 @@ describe('planRemoteInstall', () => {
const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
expect(plan.os).toBe('linux')
expect(plan.arch).toBe('x64')
+ expect(plan.node.filename).toBe('node-v22.22.0-linux-x64.tar.gz')
+ expect(plan.node.version).toBe('v22.22.0')
expect(plan.dsh.kind).toBe('pkg-zip')
if (plan.dsh.kind !== 'pkg-zip')
throw new Error('expected pkg-zip')
@@ -225,6 +251,8 @@ describe('planRemoteInstall', () => {
}
expect(plan.dshEntry).toBe('lib/bin.js')
expect(plan.node.urls[0]).toBe('https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-arm64.tar.gz')
+ expect(plan.node.filename).toBe('node-v22.22.0-linux-arm64.tar.gz')
+ expect(plan.node.version).toBe('v22.22.0')
})
it('derives deterministic URLs and notes skipped verification when metadata fails', async () => {
@@ -540,18 +568,6 @@ describe('install script execution (real POSIX sh)', () => {
})
describe('remote pnpm shim (real POSIX sh)', () => {
- /** Run a generated command under the real `sh` inside a sandboxed HOME. */
- async function runCommand(command: string, sandbox: string): Promise<{ code: number, stdout: string, stderr: string }> {
- const scriptPath = join(sandbox, 'command.sh')
- writeFileSync(scriptPath, command)
- const run = promisify(execFile)
- return run('sh', [scriptPath], { env: { ...process.env, HOME: sandbox } }).then(
- ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),
- (error: { code?: number, stdout?: string, stderr?: string }) =>
- ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),
- )
- }
-
it('writes a shim that runs the layout pnpm under the layout node', async () => {
const sandbox = mkdtempSync(join(tmpdir(), 'pnpm-shim-'))
try {
@@ -790,18 +806,6 @@ describe('credentials', () => {
})
describe('credentials copy execution (real POSIX sh)', () => {
- /** Run one generated command under the real `sh` inside a sandboxed HOME. */
- function runCommand(command: string, sandbox: string): Promise<{ code: number, stdout: string, stderr: string }> {
- const scriptPath = join(sandbox, 'cmd.sh')
- writeFileSync(scriptPath, command)
- const run = promisify(execFile)
- return run('sh', [scriptPath], { env: { ...process.env, HOME: sandbox } }).then(
- ({ stdout, stderr }) => ({ code: 0, stdout, stderr }),
- (error: { code?: number, stdout?: string, stderr?: string }) =>
- ({ code: error.code ?? -1, stdout: error.stdout ?? '', stderr: error.stderr ?? '' }),
- )
- }
-
it('merges into an existing remote .env, keeping unrelated variables and replacing managed keys', async () => {
const sandbox = tempDir()
mkdirSync(join(sandbox, '.dsh'), { recursive: true })
@@ -859,17 +863,28 @@ const BOOT_HTML = [
].join('')
const BOOTSTRAP = {
- config: {},
+ connectTimeoutMs: 15_000,
healthCheckTimeoutMs: 1000,
healthPollIntervalMs: 5,
healthPollAttempts: 3,
-}
-
-function plannerOf(plan: RemoteInstallPlan) {
- return async (): Promise<RemoteInstallPlan> => plan
+ installRef: DSH_TAG,
+ installTimeoutMs: 60_000,
+ keepaliveIntervalMs: 10_000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1,
+ reconnectMaxDelayMs: 2,
+ reconnectMaxAttempts: 2,
}
describe('ensureRemoteInstance', () => {
+ beforeEach(() => {
+ stubGithub()
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ })
+
it('is satisfied immediately when the boot manifest answers with a real bundle', async () => {
const session = new FakeSession((command) => {
if (command.includes('-w'))
@@ -899,7 +914,6 @@ describe('ensureRemoteInstance', () => {
})
it('bootstraps a fresh machine end to end: probe → install → launch → ready', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
let started = false
const session = new FakeSession((command) => {
if (command === 'uname -srm')
@@ -924,7 +938,7 @@ describe('ensureRemoteInstance', () => {
await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {
onProgress: progress => phases.push(progress),
onEvent: (stage, line, options) => events.push({ stage, line, ...options ?? {} }),
- }, plannerOf(plan))).resolves.toBe('10.0.0.1:3080')
+ })).resolves.toBe('10.0.0.1:3080')
const kinds = events.map(event => event.stage)
expect(kinds).toEqual(['probe', 'probe', 'probe', 'launch', 'ready'])
expect(events[0]?.line).toContain('探测远端平台')
@@ -936,7 +950,6 @@ describe('ensureRemoteInstance', () => {
})
it('skips the install when the three components are already present', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
let started = false
const session = new FakeSession((command) => {
if (command === 'uname -srm')
@@ -956,13 +969,12 @@ describe('ensureRemoteInstance', () => {
const events: string[] = []
await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {
onEvent: (stage, line) => events.push(`${stage}: ${line}`),
- }, plannerOf(plan))).resolves.toBe('10.0.0.1:3080')
+ })).resolves.toBe('10.0.0.1:3080')
expect(events.some(entry => entry.includes('三件套已就绪,跳过安装'))).toBe(true)
expect(session.commands.some(command => command.includes('trap cleanup EXIT'))).toBe(false)
})
it('records the terminal failure and reason when the install script fails', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
const session = new FakeSession((command) => {
if (command === 'uname -srm')
return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }
@@ -978,7 +990,7 @@ describe('ensureRemoteInstance', () => {
if (stage === 'failed')
failures.push({ line, ...options ?? {} })
},
- }, plannerOf(plan))).rejects.toThrow(/install failed on remote/)
+ })).rejects.toThrow(/install failed on remote/)
expect(failures[0]?.terminal).toBe('failed')
expect(failures[0]?.reason).toContain('checksum mismatch')
})
@@ -1000,7 +1012,6 @@ describe('ensureRemoteInstance', () => {
})
it('fails loud with fallback details when the instance never becomes ready', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
const session = new FakeSession((command) => {
if (command === 'uname -srm')
return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }
@@ -1021,12 +1032,11 @@ describe('ensureRemoteInstance', () => {
if (options?.terminal === 'failed')
failures.push({ terminal: options.terminal, ...options.reason === undefined ? {} : { reason: options.reason } })
},
- }, plannerOf(plan))).rejects.toThrow(/did not become ready.*fallback probe: root no answer.*err2 \| err3 \| err4 \| err5 \| err6/)
+ })).rejects.toThrow(/did not become ready.*fallback probe: root no answer.*err2 \| err3 \| err4 \| err5 \| err6/)
expect(failures[0]?.terminal).toBe('failed')
})
it('says the remote has no downloader instead of a misleading not-ready', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
const session = new FakeSession((command) => {
if (command === 'uname -srm')
return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }
@@ -1052,12 +1062,11 @@ describe('ensureRemoteInstance', () => {
if (options?.terminal === 'failed')
failures.push(options.reason ?? '')
},
- }, plannerOf(plan))).rejects.toThrow(/no downloader/)
+ })).rejects.toThrow(/no downloader/)
expect(failures[0]).toContain('REMOTE_PROBE_NO_DOWNLOADER')
})
it('surfaces REMOTE_NOT_INSTALLED when the launch finds an incomplete runtime', async () => {
- const plan = await planRemoteInstall('Linux 6.8.0-45-generic x86_64', {}, healthyFetchers())
const session = new FakeSession((command) => {
if (command === 'uname -srm')
return { code: 0, stdout: 'Linux 6.8.0-45-generic x86_64\n', stderr: '' }
@@ -1067,7 +1076,7 @@ describe('ensureRemoteInstance', () => {
return { code: 1, stdout: 'REMOTE_NOT_INSTALLED: 远端三件套未安装完整', stderr: '' }
return { code: 7, stdout: '', stderr: '' }
})
- await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {}, plannerOf(plan)))
+ await expect(ensureRemoteInstance(session, profile, BOOTSTRAP, {}))
.rejects
.toThrow(/REMOTE_NOT_INSTALLED/)
})
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
index 8df90b29..8963f58b 100644
--- a/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.ts
@@ -1,1018 +1,24 @@
-/**
- * Remote-instance assurance, v2: binary distribution. Connect-time flow =
- * probe the remote platform (`uname -srm`), download/verify/install the
- * three-part runtime (Node + DSH + pnpm) under the remote-exclusive
- * `~/.dsh-desktop` layout when components are missing, launch the instance,
- * and judge readiness by parsing the served boot HTML's `__DSH_BOOT__`
- * client manifest (the legacy any-response port probe stays as fallback).
- * Ported from the retired Rust engine's `service/remote/bootstrap.rs`
- * (official → mirror download fallback, SHA verification, single-top-level
- * flattening, detached launch) with the stage-tagged event stream this spec
- * adds. Commands remain pure functions of the profile/plan so the manager
- * drives them through any transport.
- * @module dsh-tauri-ssh/host/service/bootstrap
- */
-
-import type { Config } from '../storage/index'
-import type { MachineProfile, SshMachineStage, SshMachineTerminal, SshProgress } from '../types/index'
-import type { RemoteArch, RemoteAssetMatrix, RemoteOs } from './assets'
-import type { SshSession } from './transport'
-import { Buffer } from 'node:buffer'
-import { readFileSync } from 'node:fs'
-import { DEFAULT_REMOTE_PROFILE } from '../storage/index'
-import { assetMatrixFor, dshNpmTarballUrls, dshZipDownloadUrls, nodeDownloadUrls, nodeFilenameFor, nodeShasumUrls, parsePlatform, PNPM_SHA256, PNPM_VERSION, pnpmDownloadUrls } from './assets'
-import { clientUrlsFromBootHtml, looksLikePluginBundle } from './boot-html'
-import { shQuote } from './transport'
-import { listGithubAssets, listGithubReleases, npmDistMetadata, parseGitHubRepo, pickReleaseTag, pkgRepoOf } from './version'
-
-/** Log file of the auto-started remote instance, under the remote home. */
-export const REMOTE_WEB_LOG = '.dsh/dsh-remote-web.log'
-
-/** The remote-exclusive install root, relative to the remote home. */
-export const REMOTE_ROOT = '.dsh-desktop'
-
-/** The packaged-zip DSH entry, relative to the dsh install directory. */
-const DSH_ZIP_ENTRY = 'node_modules/@deepseek-ai/dsh/lib/bin.js'
-
-/** The npm-tarball DSH entry, relative to the dsh install directory. */
-const DSH_NPM_ENTRY = 'lib/bin.js'
-
-/** The pnpm entry, relative to the pnpm install directory. */
-const PNPM_ENTRY = 'bin/pnpm.cjs'
-
-/** Marker prefix the install script tags its stage lines with. */
-export const BOOTSTRAP_LOG_PREFIX = '::dsh '
-
-/** One parsed stage line of the install script's output stream. */
-export interface BootstrapLogLine {
- stage: SshMachineStage
- line: string
-}
-
-/**
- * The install script's stage vocabulary as a runtime set. Keyed by every
- * {@link SshMachineStage} member so the compiler flags drift (S3 adds the
- * connection-lifecycle stages here too).
- */
-const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
- probe: true,
- download: true,
- verify: true,
- install: true,
- launch: true,
- ready: true,
- failed: true,
- auth: true,
- reconnect: true,
-}
-
-/** Whether a parsed marker word is one of the known stage tags. */
-function isBootstrapStage(value: string): value is SshMachineStage {
- return (BOOTSTRAP_STAGES as Record<string, true | undefined>)[value] === true
-}
-
-/**
- * Parse one output line of the install script into its stage tag; lines
- * without a known marker are unexpected tool output and report stage
- * `install` with the raw line kept.
- * @param chunk - one raw output line.
- */
-export function parseBootstrapLine(chunk: string): BootstrapLogLine {
- const match = /^::dsh (\w+) (.*)$/u.exec(chunk)
- const stage = match?.[1]
- if (match === null || stage === undefined || !isBootstrapStage(stage))
- return { stage: 'install', line: chunk }
- return { stage, line: match[2] ?? '' }
-}
-
-/**
- * Line-buffered dispatcher for a bootstrap script's streamed output: SSH
- * data arrives in arbitrary chunk boundaries, so a half-received line is
- * held back until its newline (or the final flush) completes it.
- * @param onLine - one complete output line.
- */
-export function createBootstrapLineDispatcher(onLine: (line: string) => void): { push: (chunk: string) => void, flush: () => void } {
- let pending = ''
- return {
- push(chunk: string): void {
- pending = `${pending}${chunk}`
- const lines = pending.split('\n')
- pending = lines.pop() ?? ''
- for (const line of lines) {
- if (line !== '')
- onLine(line)
- }
- },
- flush(): void {
- const line = pending
- pending = ''
- if (line !== '')
- onLine(line)
- },
- }
-}
-
-/**
- * The skipped-verification summary terminal events carry: plan-level notes
- * ("no trusted digest") plus the install script's live skip warnings,
- * deduplicated. Empty when every artifact was actually verified — the
- * fail-open skips stay impossible to miss on the settling event.
- * @param notes - the install plan's resolution notes.
- * @param skipLines - streamed verify lines that recorded a skipped check.
- */
-export function skippedVerificationSummary(notes: string[], skipLines: string[]): string {
- const items = [...new Set([...notes, ...skipLines].filter(item => item.includes('跳过')))]
- return items.length === 0 ? '' : `;跳过校验项: ${items.join(';')}`
-}
-
-/** The npm-registry DSH kind's resolved asset. */
-interface DshNpmPlan {
- kind: 'npm-tgz'
- urls: string[]
- /**
- * Trusted digest in the install script's `sha512:<hex>` form (normalized
- * from the packument's SRI `sha512-<base64>`), when available.
- */
- integrity?: string
- packageName: string
- version: string
-}
-
-/**
- * Normalize an npm packument integrity into the `shaNNN:<hex>` form the
- * install script's `verify` understands. npm carries SRI (`sha512-<base64>`),
- * which the script would otherwise compare against a hex digest — a
- * guaranteed mismatch. Already-colonformed or unshaped values pass through
- * unchanged (colon forms verify; unshaped ones mismatch loudly) — except
- * unparseable ones, which report undefined so the plan notes the skip.
- * @param integrity - the packument's `dist.integrity`, when present.
- * @returns the `shaNNN:<hex>` digest, or undefined when unusable.
- */
-export function normalizeNpmIntegrity(integrity: string | undefined): string | undefined {
- if (integrity === undefined)
- return undefined
- const sri = /^sha(256|512)-([A-Za-z0-9+/]+={0,2})$/u.exec(integrity)
- if (sri !== null)
- return `sha${sri[1]}:${Buffer.from(sri[2] ?? '', 'base64').toString('hex')}`
- return integrity.startsWith('sha256:') || integrity.startsWith('sha512:') ? integrity : undefined
-}
-
-/** The packaged-zip DSH kind's resolved asset. */
-interface DshZipPlan {
- kind: 'pkg-zip'
- urls: string[]
- /** Trusted `sha256:<hex>` digest from the GitHub release, when available. */
- digest?: string
- zipName: string
- tag: string
-}
-
-/** The fully resolved install plan for one remote. */
-export interface RemoteInstallPlan {
- os: RemoteOs
- arch: RemoteArch
- matrix: RemoteAssetMatrix
- /** The GitHub `owner/name` the DSH asset downloads from. */
- repo: string
- /** The DSH entry path relative to `$HOME/.dsh-desktop/dependencies/dsh`. */
- dshEntry: string
- /** The resolved DSH semver (empty when the tag carries none). */
- dshVersion: string
- node: { urls: string[], shasumUrls: string[], filename: string, version: string }
- dsh: DshNpmPlan | DshZipPlan
- pnpm: { urls: string[], sha256: string, version: string }
- /** Resolution notes (fallbacks, skipped verification) worth surfacing. */
- notes: string[]
-}
-
-/**
- * Plan one remote's install: platform → asset matrix → pinned release tag →
- * per-asset URLs and trusted digests. Pure orchestration over the injectable
- * network functions, so tests cover every path without touching the network.
- * @param unameOut - the remote `uname -srm` output.
- * @param config - plugin config (source repository and version pin).
- * @param fetchers - network overrides for tests.
- * @param fetchers.listReleases - the packaged release list (newest first).
- * @param fetchers.listAssets - one tag's release assets.
- * @param fetchers.npmDist - the npm packument dist metadata.
- * @throws {UnsupportedRemotePlatformError} when the platform is outside the matrix.
- */
-export async function planRemoteInstall(
- unameOut: string,
- config: Pick<Config, 'installRepo' | 'installRef'>,
- fetchers: {
- listReleases?: (repo: string) => Promise<{ tag: string, prerelease: boolean }[]>
- listAssets?: (repo: string, tag: string) => Promise<Array<{ name: string, url: string, digest?: string }>>
- npmDist?: (packageName: string, version: string) => Promise<{ url: string, mirrorUrl: string, integrity?: string }>
- } = {},
-): Promise<RemoteInstallPlan> {
- const { os, arch } = parsePlatform(unameOut)
- const matrix = assetMatrixFor(os, arch)
- const repo = pkgRepoOf(config.installRepo)
- const notes: string[] = []
- // An unparseable configured repository falls back inside pkgRepoOf; note
- // it so a config typo is visible instead of silently installing official.
- const configuredRepo = config.installRepo?.trim()
- if (configuredRepo !== undefined && configuredRepo !== '' && parseGitHubRepo(configuredRepo) === undefined)
- notes.push(`installRepo "${configuredRepo}" 无法解析为 GitHub 仓库,回退官方发行仓 ${repo}`)
- const listReleases = fetchers.listReleases ?? listGithubReleases
- const listAssets = fetchers.listAssets ?? listGithubAssets
- const npmDist = fetchers.npmDist ?? npmDistMetadata
- let metas
- try {
- metas = await listReleases(repo)
- }
- catch (error) {
- notes.push(`release 列表获取失败(${describeError(error)})`)
- }
- const resolved = pickReleaseTag(metas, { ref: config.installRef })
- notes.push(...resolved.notes.map(note => `版本选择: ${note}`))
- const nodeFilename = nodeFilenameFor(os, arch)
- if (nodeFilename === undefined)
- throw new Error(`node asset missing for ${os}/${arch}`)
- const node = {
- urls: nodeDownloadUrls(os, arch),
- shasumUrls: nodeShasumUrls(),
- filename: nodeFilename,
- version: nodeFilename.split('-')[1] ?? '',
- }
- const pnpm = { urls: pnpmDownloadUrls(), sha256: PNPM_SHA256, version: PNPM_VERSION }
- if (matrix.dshKind === 'pkg-zip') {
- const zipName = matrix.dshZipName ?? ''
- let urls: string[] | undefined
- let digest: string | undefined
- try {
- const assets = await listAssets(repo, resolved.tag)
- const asset = assets.find(candidate => candidate.name === zipName)
- if (asset !== undefined) {
- urls = [asset.url, ...dshZipDownloadUrls(repo, resolved.tag, zipName).slice(1)]
- digest = asset.digest
- }
- }
- catch (error) {
- notes.push(`release 资产元数据获取失败(${describeError(error)})`)
- }
- if (digest === undefined)
- notes.push(`未取得 ${zipName} 的可信摘要,将跳过 SHA-256 校验`)
- return {
- os,
- arch,
- matrix,
- repo,
- dshEntry: DSH_ZIP_ENTRY,
- dshVersion: resolved.version,
- node,
- dsh: { kind: 'pkg-zip', urls: urls ?? dshZipDownloadUrls(repo, resolved.tag, zipName), ...digest === undefined ? {} : { digest }, zipName, tag: resolved.tag },
- pnpm,
- notes,
- }
- }
- const packageName = matrix.dshNpmPackage ?? '@deepseek-ai/dsh'
- if (resolved.version === '')
- throw new Error(`cannot resolve a DSH npm version from tag "${resolved.tag}"`)
- let urls: string[] | undefined
- let integrity: string | undefined
- try {
- const dist = await npmDist(packageName, resolved.version)
- // A packument served by the mirror already carries the mirror tarball
- // URL — dedupe so the fallback list never repeats the same URL.
- urls = [...new Set([dist.url, dist.mirrorUrl])]
- integrity = normalizeNpmIntegrity(dist.integrity)
- }
- catch (error) {
- notes.push(`npm 元数据获取失败(${describeError(error)}),回退确定性 URL`)
- }
- if (integrity === undefined)
- notes.push(`未取得 ${packageName}@${resolved.version} 的可校验完整性摘要,将跳过校验`)
- return {
- os,
- arch,
- matrix,
- repo,
- dshEntry: DSH_NPM_ENTRY,
- dshVersion: resolved.version,
- node,
- dsh: { kind: 'npm-tgz', urls: urls ?? dshNpmTarballUrls(packageName, resolved.version), ...integrity === undefined ? {} : { integrity }, packageName, version: resolved.version },
- pnpm,
- notes,
- }
-}
-
-/** The shell-quoted URL list for a fetch call. */
-function quoteUrls(urls: string[]): string {
- return urls.map(shQuote).join(' ')
-}
-
-/**
- * Build the remote install script (POSIX sh) for one plan. Behavior: idempotent
- * (installed components are skipped), official → mirror download fallback with
- * both sources' errors reported on double failure, SHA-256/512 verification
- * with mismatch abort and partial cleanup (`trap`), single-top-level
- * flattening, and the `npm-tgz` kind's `pnpm install` (registry official →
- * mirror fallback). Progress reports through `::dsh <stage> <line>` markers.
- * @param plan - the resolved install plan.
- * @returns the full script text.
- */
-export function buildInstallScript(plan: RemoteInstallPlan): string {
- const dshSection = plan.dsh.kind === 'pkg-zip'
- ? [
- `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then`,
- ` log install "dsh 已就绪"`,
- `else`,
- ` log download "dsh ${plan.dsh.tag}"`,
- ` fetch "$TMP/dsh-pkg.zip" ${quoteUrls(plan.dsh.urls)}`,
- ` verify "$TMP/dsh-pkg.zip" "${plan.dsh.digest ?? ''}" "${plan.dsh.zipName}"`,
- ` extract_zip "$TMP/dsh-pkg.zip" "$ROOT/dependencies/dsh.new"`,
- ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,
- ` log install "dsh 安装完成 (${plan.dsh.tag})"`,
- `fi`,
- ].join('\n')
- : [
- // The npm kind assembles node_modules on the remote: pnpm resolves
- // the platform-correct natives, official registry first, mirror
- // fallback. pnpm must run inside the extracted package (SSH exec
- // starts in $HOME, where pnpm would abort with NO_PKG_MANIFEST).
- `install_dsh_deps() {`,
- ` for _reg in ${quoteUrls(['https://registry.npmjs.org', 'https://registry.npmmirror.com'])}; do`,
- ` if ( cd "$ROOT/dependencies/dsh" && "$ROOT/runtime/bin/node" "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" install --prod --silent --registry="$_reg" >"$TMP/pnpm.log" 2>&1 ); then`,
- ` log install "dsh 依赖安装完成 (registry $_reg)"`,
- ` return 0`,
- ` fi`,
- ` done`,
- ` log failed "pnpm install 失败: $(tail -n 5 "$TMP/pnpm.log" 2>/dev/null | tr '\n' ' ')"`,
- ` return 1`,
- `}`,
- `if [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then`,
- ` log install "dsh 已就绪"`,
- `else`,
- ` log download "dsh ${plan.dsh.packageName}@${plan.dsh.version} (npm)"`,
- ` fetch "$TMP/dsh.tgz" ${quoteUrls(plan.dsh.urls)}`,
- ` verify "$TMP/dsh.tgz" "${plan.dsh.integrity ?? ''}" "${plan.dsh.packageName}-${plan.dsh.version}.tgz"`,
- ` rm -rf "$ROOT/dependencies/dsh.new"`,
- ` mkdir -p "$ROOT/dependencies/dsh.new"`,
- ` tar -xzf "$TMP/dsh.tgz" -C "$ROOT/dependencies/dsh.new" --strip-components=1`,
- ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,
- ` install_dsh_deps || exit 13`,
- ` log install "dsh 安装完成 (${plan.dsh.packageName}@${plan.dsh.version})"`,
- `fi`,
- ].join('\n')
- return [
- 'set -eu',
- 'ROOT="$HOME/.dsh-desktop"',
- 'TMP="$ROOT/tmp"',
- 'mkdir -p "$ROOT/dependencies" "$TMP"',
- // Half-finished products never outlive the run: the trap clears the
- // staging area and any *.new partial directory on every exit path.
- 'cleanup() { rm -rf "$TMP" "$ROOT/runtime.new" "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/dsh.new"; }',
- 'trap cleanup EXIT',
- `log() { printf '${BOOTSTRAP_LOG_PREFIX}%s %s\\n' "$1" "$2"; }`,
- 'fetch() {',
- ' _dst="$1"; shift',
- ' _errs=""',
- ' for _url in "$@"; do',
- ' if command -v curl >/dev/null 2>&1; then',
- ' log download "$_url"',
- ' if curl -fsSL --retry 3 --connect-timeout 15 -o "$_dst" "$_url" 2>"$TMP/fetch.err"; then return 0; fi',
- ' _errs="$_errs | $_url: $(head -n 1 "$TMP/fetch.err" 2>/dev/null || echo download failed)"',
- ' elif command -v wget >/dev/null 2>&1; then',
- ' log download "$_url"',
- ' if wget -q --tries=3 -O "$_dst" "$_url" 2>/dev/null; then return 0; fi',
- ' _errs="$_errs | $_url: wget download failed"',
- ' else',
- ' log failed "REMOTE_INSTALL_NO_DOWNLOADER: 远端缺少 curl 或 wget,请先安装其一"',
- ' exit 9',
- ' fi',
- ' done',
- ' log failed "所有下载源均失败:$_errs"',
- ' exit 10',
- '}',
- 'verify() {',
- ' _file="$1"; _want="$2"; _name="$3"',
- ' case "$_want" in',
- ' sha256:*) _algo=256; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha256://\')" ;;',
- ' sha512:*) _algo=512; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha512://\')" ;;',
- ' "") log verify "警告: 未取得可信摘要,跳过校验 $_name"; return 0 ;;',
- ' *) _algo=256; _hex="$_want" ;;',
- ' esac',
- ' _got=""',
- ` if [ "\$_algo" = 256 ]; then`,
- ' if command -v sha256sum >/dev/null 2>&1; then _got="$(sha256sum "$_file" | cut -d\' \' -f1)"',
- ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 256 "$_file" | cut -d\' \' -f1)"',
- ' fi',
- ' else',
- ' if command -v sha512sum >/dev/null 2>&1; then _got="$(sha512sum "$_file" | cut -d\' \' -f1)"',
- ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 512 "$_file" | cut -d\' \' -f1)"',
- ' fi',
- ' fi',
- ' if [ -z "$_got" ]; then',
- ' log verify "警告: 远端缺少摘要工具,跳过校验 $_name"',
- ' return 0',
- ' fi',
- ' if [ "$_got" != "$_hex" ]; then',
- ' log failed "checksum mismatch: $_name (want sha$_algo:$_hex, got $_got)"',
- ' exit 11',
- ' fi',
- ` log verify "$_name 校验通过 (sha$_algo)"`,
- '}',
- 'extract_zip() {',
- ' _zip="$1"; _dir="$2"',
- ' mkdir -p "$_dir"',
- ' if command -v unzip >/dev/null 2>&1; then unzip -q -o "$_zip" -d "$_dir"',
- ' elif command -v python3 >/dev/null 2>&1; then python3 -m zipfile -e "$_zip" "$_dir"',
- ' else',
- ' log failed "REMOTE_INSTALL_NO_UNZIP: 远端缺少 unzip 或 python3,无法解压发行包"',
- ' exit 12',
- ' fi',
- '}',
- 'flatten_move() {',
- ' _src="$1"; _dst="$2"',
- ' _count=0; _top=""',
- ' for _e in "$_src"/*; do',
- ' if [ -e "$_e" ]; then _count=$((_count + 1)); _top="$_e"; fi',
- ' done',
- ' rm -rf "$_dst"',
- ' if [ "$_count" -eq 1 ] && [ -d "$_top" ]; then',
- ' mkdir -p "$_dst"',
- ' for _e in "$_top"/* "$_top"/.[!.]* "$_top"/..?*; do',
- ' if [ -e "$_e" ]; then mv -f "$_e" "$_dst/"; fi',
- ' done',
- ' rmdir "$_top" 2>/dev/null || true',
- ' rmdir "$_src" 2>/dev/null || true',
- ' else',
- ' mv -f "$_src" "$_dst"',
- ' fi',
- '}',
- 'if [ -x "$ROOT/runtime/bin/node" ]; then',
- ' log install "node 已就绪: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo installed)"',
- 'else',
- ` log download "node ${plan.node.version}"`,
- ` fetch "$TMP/node.tar.gz" ${quoteUrls(plan.node.urls)}`,
- ` fetch "$TMP/SHASUMS256.txt" ${quoteUrls(plan.node.shasumUrls)}`,
- ` _want="$(grep " ${plan.node.filename}\$" "$TMP/SHASUMS256.txt" | head -n 1 | tr -d '\\r' | sed 's/^ *//' | cut -d' ' -f1)"`,
- ` verify "$TMP/node.tar.gz" "\$_want" "${plan.node.filename}"`,
- ' rm -rf "$ROOT/runtime.new"',
- ' mkdir -p "$ROOT/runtime.new"',
- ' tar -xzf "$TMP/node.tar.gz" -C "$ROOT/runtime.new" --strip-components=1',
- ' flatten_move "$ROOT/runtime.new" "$ROOT/runtime"',
- ` log install "node 安装完成: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo ok)"`,
- 'fi',
- `if [ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ]; then`,
- ' log install "pnpm 已就绪"',
- 'else',
- ` log download "pnpm ${plan.pnpm.version}"`,
- ` fetch "$TMP/pnpm.tgz" ${quoteUrls(plan.pnpm.urls)}`,
- ` verify "$TMP/pnpm.tgz" "sha256:${plan.pnpm.sha256}" "pnpm-${plan.pnpm.version}.tgz"`,
- ' rm -rf "$ROOT/dependencies/pnpm.new"',
- ' mkdir -p "$ROOT/dependencies/pnpm.new"',
- ' tar -xzf "$TMP/pnpm.tgz" -C "$ROOT/dependencies/pnpm.new" --strip-components=1',
- ' flatten_move "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/pnpm"',
- ` log install "pnpm 安装完成: ${plan.pnpm.version}"`,
- 'fi',
- dshSection,
- 'log install "远端初始化完成"',
- ].join('\n')
-}
-
-/**
- * The remote missing-components probe: prints one line per missing member of
- * the three-part runtime (nothing when fully installed).
- */
-export function checkMissingCommand(): string {
- return [
- `ROOT="$HOME/${REMOTE_ROOT}"`,
- `[ -x "$ROOT/runtime/bin/node" ] || echo node`,
- `[ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ] || echo pnpm`,
- `if [ ! -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ] && [ ! -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then echo dsh; fi`,
- 'true',
- ].join('\n')
-}
-
-/** Parse the check script's stdout into the missing component set. */
-export function missingComponentsOf(stdout: string): string[] {
- return stdout.split('\n').map(line => line.trim()).filter(line => line !== '' && ['node', 'dsh', 'pnpm'].includes(line))
-}
-
-/**
- * The default remote-instance start command's entry resolution: the layout's
- * Node binary and DSH entry, always (the installer's `~/.local/bin` link no
- * longer exists in the binary layout).
- */
-export function layoutDshEntry(plan?: RemoteInstallPlan): string {
- return `$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan?.dshEntry ?? DSH_ZIP_ENTRY}`
-}
-
-/** The layout's Node binary, double-quoted so `$HOME` still expands under `sh -lc`. */
-export function layoutNodeBinary(): string {
- return `"$HOME/${REMOTE_ROOT}/runtime/bin/node"`
-}
-
-/**
- * The layout's shared bin directory (unquoted; `$HOME` expands in the remote
- * shell). It is already on the remote instance's PATH — the start command
- * exports it — so anything placed here is visible to the instance's own
- * tooling as well.
- */
-export function layoutBinDir(): string {
- return `$HOME/${REMOTE_ROOT}/runtime/bin`
-}
-
-/**
- * Make the layout's bundled pnpm reachable as a bare `pnpm` on PATH.
- *
- * `dsh plugin add` shells out to `pnpm`, but a stock remote install only
- * ships the binary at `dependencies/pnpm/bin/pnpm.cjs` (the installer uses it
- * by absolute path) — nothing named `pnpm` exists, so every plugin install
- * died with `exit 127: dsh: pnpm not found on PATH`. The shim is written
- * once (an existing one is left alone), runs the layout's own Node and pnpm,
- * and needs no network: the version is the one the installer already pinned
- * ({@link PNPM_VERSION}).
- */
-export function ensurePnpmCommand(): string {
- const shim = `#!/bin/sh\nexec "$HOME/${REMOTE_ROOT}/runtime/bin/node" "$HOME/${REMOTE_ROOT}/dependencies/pnpm/${PNPM_ENTRY}" "$@"\n`
- return `B="${layoutBinDir()}"; [ -x "$B/pnpm" ] || { mkdir -p "$B" && printf %s ${shQuote(shim)} > "$B/pnpm" && chmod +x "$B/pnpm"; }`
-}
-
-/**
- * The installed dsh-entry probe for command-driving callers (the sync
- * engine): prints the first entry the binary layout actually holds — zip
- * layout first, npm layout second, the same precedence as
- * {@link checkMissingCommand} — or nothing when neither is installed.
- * Unlike the instance launch the plan is unknown here, so the probe resolves
- * it remotely; the printed path is absolute (`$HOME` already expanded).
- */
-export function dshEntryProbeCommand(): string {
- return [
- `ROOT="$HOME/${REMOTE_ROOT}"`,
- `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}"`,
- `elif [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}"`,
- 'fi',
- 'true',
- ].join('\n')
-}
-
-/**
- * The remote-instance launch: the profile override when present, else the
- * layout's Node + DSH entry with the port pinned twice (`DSH_WEB_PORT` and
- * the flag). Detached through a double subshell so the exec channel settles
- * immediately; the pid lands in `~/.dsh/.dsh-remote.pid`; output redirects
- * to the log with stdin from /dev/null; no `nohup` (macOS kills the child).
- * @param profile - the machine profile (port + start command override).
- * @param plan - the resolved install plan (chooses the DSH entry).
- * @returns the shell command line that starts (or restarts) the instance.
- */
-/**
- * The launch-token lookup command: `dsh web` prints its authenticated URL
- * (`…/?token=…`) to stdout, which the start command appends to the remote
- * web log. The last match wins (a restarted instance appends a fresh line);
- * prints nothing when the log has no token (callers fall back to the bare
- * tunnel URL). Token charset is the URL-safe base the launch token uses.
- */
-export function remoteWebTokenCommand(): string {
- return `grep -oE 'token=[A-Za-z0-9._~-]+' "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null | tail -n 1 | cut -d= -f2`
-}
-
-/** Shell- and path-safe profile names only (`^[A-Za-z0-9_-]+$`); anything else falls back to the default. */
-export function safeProfileName(raw: string | undefined): string {
- return raw !== undefined && /^[\w-]+$/.test(raw) ? raw : DEFAULT_REMOTE_PROFILE
-}
-
-export function startCommandFor(profile: MachineProfile, plan?: RemoteInstallPlan): string {
- if (profile.startCommand !== undefined)
- return `mkdir -p "$HOME/.dsh" && ( ${profile.startCommand} >>"$HOME/${REMOTE_WEB_LOG}" 2>&1 < /dev/null & ) &`
- const node = `$HOME/${REMOTE_ROOT}/runtime/bin/node`
- const dshBin = layoutDshEntry(plan)
- const profileName = safeProfileName(profile.profileName)
- return [
- `ROOT="$HOME/${REMOTE_ROOT}"`,
- `NODE=${node}`,
- `DSH_BIN=${dshBin}`,
- `LOG_DIR="$HOME/.dsh"`,
- `LOG="$LOG_DIR/dsh-remote-web.log"`,
- `if [ ! -x "$NODE" ] || [ ! -f "$DSH_BIN" ]; then echo "REMOTE_NOT_INSTALLED: 远端三件套未安装完整"; exit 1; fi`,
- `mkdir -p "$LOG_DIR"`,
- `export PATH="$ROOT/runtime/bin:$PATH"`,
- `export DSH_TELEMETRY_DISABLED=1 NO_COLOR=1 DSH_WEB_PORT=${profile.remotePort}`,
- `export DSH_REMOTE_SESSION_ORIGIN=${shQuote(profile.name)}`,
- `( sh -c 'echo $$ > "$1/.dsh-remote.pid"; exec "$2" "$3" --profile "$5" --host 127.0.0.1 --port "$4" --no-open' dsh-remote "$LOG_DIR" "$NODE" "$DSH_BIN" ${profile.remotePort} ${profileName} </dev/null >>"$LOG" 2>&1 & )`,
- `echo "远端实例已拉起(档案: ${profileName}, 日志: $LOG)"`,
- ].join('\n')
-}
-
-/** Credentials read from a local dsh `.env` document. */
-export interface EnvCredentials {
- apiKey?: string
- baseUrl?: string
-}
-
-/**
- * Read `DEEPSEEK_API_KEY`/`DEEPSEEK_BASE_URL` from a dsh `.env` document.
- * @param path - the `.env` file path (the harness home's `.env`).
- * @returns the credentials present in the document.
- */
-export function readEnvCredentials(path: string): EnvCredentials {
- let text: string
- try {
- text = readFileSync(path, 'utf8')
- }
- catch {
- return {}
- }
- const out: EnvCredentials = {}
- const apiKey = envValueOf(text, 'DEEPSEEK_API_KEY')
- /* v8 ignore next -- attribution artifact: both arms are exercised by the credentials tests */
- if (apiKey !== undefined)
- out.apiKey = apiKey
- const baseUrl = envValueOf(text, 'DEEPSEEK_BASE_URL')
- if (baseUrl !== undefined)
- out.baseUrl = baseUrl
- return out
-}
-
-/**
- * Write credentials into the remote `~/.dsh/.env`: print `copied` when the
- * write happened, `existing` when the remote already carries a key (kept
- * untouched). The write merges instead of replacing — only the keys being
- * written are filtered out of an existing document, so remote-set variables
- * (including a remote `DEEPSEEK_BASE_URL` when the local env carries none)
- * survive — and it lands through a temp file + `mv`, so a failed write can
- * never truncate the existing document.
- * @param credentials - the credentials to write (apiKey required).
- * @returns the shell command line.
- */
-export function credentialsCopyCommand(credentials: EnvCredentials & { apiKey: string }): string {
- // Only the keys this write owns are filtered from the existing document.
- const managed = ['DEEPSEEK_API_KEY', ...(credentials.baseUrl === undefined ? [] : ['DEEPSEEK_BASE_URL'])]
- const writes = [`printf 'DEEPSEEK_API_KEY=%s\\n' ${shQuote(credentials.apiKey)}`]
- if (credentials.baseUrl !== undefined)
- writes.push(`printf 'DEEPSEEK_BASE_URL=%s\\n' ${shQuote(credentials.baseUrl)}`)
- const filter = managed.map(key => `^${key}=`).join('|')
- return [
- `mkdir -p "$HOME/.dsh"`,
- `if grep -q '^DEEPSEEK_API_KEY=' "$HOME/.dsh/.env" 2>/dev/null; then echo existing; else umask 077 && { grep -v -E '${filter}' "$HOME/.dsh/.env" 2>/dev/null || true; ${writes.join('; ')}; } > "$HOME/.dsh/.env.new" && mv -f "$HOME/.dsh/.env.new" "$HOME/.dsh/.env" && echo copied; fi`,
- ].join(' && ')
-}
-
-/** One `KEY=value` line of a `.env` document, optional surrounding quotes stripped. */
-function envValueOf(text: string, key: string): string | undefined {
- for (const line of text.split('\n')) {
- if (!line.startsWith(`${key}=`))
- continue
- const value = line.slice(key.length + 1).trim().replace(/^"(.*)"$/u, '$1')
- return value === '' ? undefined : value
- }
- return undefined
-}
-
-/** The first non-empty line of a command's stdout, trimmed (a probe prints one path). */
-export function firstLineOf(stdout: string): string {
- for (const line of stdout.split('\n')) {
- const trimmed = line.trim()
- if (trimmed !== '')
- return trimmed
- }
- return ''
-}
-
-/** Marker the readiness probes report when the remote has neither curl nor wget. */
-export const REMOTE_PROBE_NO_DOWNLOADER = 'REMOTE_PROBE_NO_DOWNLOADER'
-
-/**
- * Wrap one probe's fetch arms with the downloader selection the install
- * script's `fetch()` uses: curl when present, wget next, and a loud
- * `REMOTE_PROBE_NO_DOWNLOADER` marker (exit 1) when neither exists — a
- * wget-only remote must not install fine and then fail readiness forever.
- * `command -v` runs inside a command substitution so the probes never
- * contain a `/dev/null` redirect (the legacy verdict probe is told apart
- * by exactly that token).
- * @param curlArm - the curl invocation.
- * @param wgetArm - the wget invocation.
- */
-function withDownloaderFallback(curlArm: string, wgetArm: string): string {
- return [
- `if [ -n "$(command -v curl)" ]; then ${curlArm}`,
- `elif [ -n "$(command -v wget)" ]; then ${wgetArm}`,
- `else echo "${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态" >&2; exit 1; fi`,
- ].join('; ')
-}
-
-/**
- * The root-page probe: fetch the instance's boot HTML. Any HTTP response
- * (including 401/404) exits 0 — the body decides; a connection-level
- * failure exits nonzero. The wget arm normalizes GNU wget's exit codes to
- * curl's any-response-answers semantics: 6 is an authentication challenge
- * (the auth fence's 401), 8 a server error status — both are answers
- * (verified live: GNU Wget 1.21.2 gives 6 on 401, 8 on 404, 4 on refused).
- * busybox wget collapses every failure to 1 and lands on the not-ready
- * side of that split.
- * @param remotePort - the instance's loopback port.
- * @param timeoutMs - per-probe downloader deadline.
- */
-export function rootProbeCommand(remotePort: number, timeoutMs: number): string {
- const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
- return withDownloaderFallback(
- `curl -s -m ${seconds} http://127.0.0.1:${remotePort}/`,
- `wget -q -T ${seconds} -O - http://127.0.0.1:${remotePort}/; case $? in 0|6|8) ;; *) exit 1 ;; esac`,
- )
-}
-
-/**
- * The client-bundle probe: fetch one boot-manifest URL, printing the body
- * followed by the numeric status code on its last line. wget cannot append
- * a status line, so its arm synthesizes one: a completed fetch (exit 0) IS
- * a 2xx answer; anything else — connection failure or a server error
- * status (exit 8) — reports status 0, which never passes readiness.
- * @param url - the absolute loopback URL to fetch.
- * @param timeoutMs - per-probe downloader deadline.
- */
-export function bundleProbeCommand(url: string, timeoutMs: number): string {
- const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
- return withDownloaderFallback(
- `curl -s -m ${seconds} -w '\\n%{http_code}' ${shQuote(url)}`,
- `wget -q -T ${seconds} -O - ${shQuote(url)} && printf '\\n200\\n' || printf '\\n0\\n'`,
- )
-}
-
-/**
- * Split a bundle probe's stdout into body and numeric status. Malformed
- * output (no trailing status line) reports status 0.
- * @param stdout - the raw probe stdout.
- */
-export function splitBundleProbeStdout(stdout: string): { body: string, status: number } {
- const trimmed = stdout.replace(/\n$/u, '')
- const index = trimmed.lastIndexOf('\n')
- if (index < 0) {
- // A single-line answer is the bare status (an empty body).
- const status = Number.parseInt(trimmed, 10)
- return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: '', status }
- }
- const status = Number.parseInt(trimmed.slice(index + 1).trim(), 10)
- return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: trimmed.slice(0, index), status }
-}
-
-/** The tail command that recovers the remote instance's log for the error message. */
-export function logTailCommand(): string {
- return `tail -n 20 "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null || true`
-}
-
-/** One operator-facing fragment for a failed remote command. */
-export function describeExecFailure(code: number | null, stderr: string): string {
- const tail = stderr.trim().split('\n').slice(-3).join(' | ')
- return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`
-}
-
-/** One operator-facing fragment for an unknown-shape failure. */
-export function describeError(error: unknown): string {
- return error instanceof Error ? error.message : String(error)
-}
-
-/** Hooks the assurance flow reports through (both optional). */
-export interface BootstrapHooks {
- /** Coarse UI progress (the settings page's live status line). */
- onProgress?: (progress: SshProgress) => void
- /** Machine event channel appends (stage-tagged, the spec's C-EVENT). */
- onEvent?: (stage: SshMachineStage, line: string, options?: { terminal?: SshMachineTerminal, reason?: string }) => void
-}
-
-/** Timing + source configuration of the assurance flow. */
-export interface BootstrapConfig {
- config: Pick<Config, 'installRepo' | 'installRef' | 'installTimeoutMs'>
- healthCheckTimeoutMs: number
- healthPollIntervalMs: number
- healthPollAttempts: number
-}
-
-/**
- * Ensure the remote instance is ready: judge readiness from the served boot
- * HTML (client-bundle manifest), and when it is not, bootstrap the machine —
- * probe the platform, install missing runtime components from pinned binary
- * assets, launch the instance, and poll until the manifest answers. The
- * legacy any-response verdict stays as the fallback for instances whose HTML
- * carries no manifest.
- * @param session - the authenticated SSH session.
- * @param profile - the machine profile (port + start command override).
- * @param bootstrap - timing + source configuration.
- * @param hooks - progress and event reporting.
- * @param planner - the install-plan resolver (injectable for tests).
- * @returns a short description of the ready instance (host:port, plus how
- * readiness was judged).
- * @throws {Error} with an operator-facing message when the machine cannot be
- * bootstrapped (unsupported platform, install failure, never ready).
- */
-export async function ensureRemoteInstance(
- session: SshSession,
- profile: MachineProfile,
- bootstrap: BootstrapConfig,
- hooks: BootstrapHooks = {},
- planner: (unameOut: string, config: Pick<Config, 'installRepo' | 'installRef'>) => Promise<RemoteInstallPlan> = (unameOut, config) => planRemoteInstall(unameOut, config),
-): Promise<string> {
- const { onEvent, onProgress } = hooks
- const target = `${profile.host}:${profile.remotePort}`
- const readyFromHtml = await judgeReadiness(session, profile, bootstrap)
- if (readyFromHtml !== undefined) {
- emitReady(onEvent, target, readyFromHtml)
- return target
- }
- // The instance is not answering: bootstrap (probe → install → launch).
- onEvent?.('probe', '探测远端平台 (uname -srm)')
- const uname = await session.exec('uname -srm')
- if (uname.code !== 0) {
- return failBootstrap(onEvent, `无法探测远端平台: ${describeExecFailure(uname.code, uname.stderr)}`)
- }
- let plan: RemoteInstallPlan
- try {
- plan = await planner(uname.stdout, bootstrap.config)
- }
- catch (error) {
- return failBootstrap(onEvent, describeError(error))
- }
- onEvent?.('probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)
- for (const note of plan.notes)
- onEvent?.('probe', note)
- const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
- let skips: string[] = []
- if (missing.length > 0) {
- onEvent?.('probe', `缺失组件: ${missing.join(', ')}`)
- skips = await runInstallScript(session, plan, bootstrap.config.installTimeoutMs, hooks)
- }
- else {
- onEvent?.('probe', '三件套已就绪,跳过安装')
- }
- // The bootstrap's settling event carries the skipped-verification summary
- // (plan notes + the script's live verify warnings), if any.
- const skipSummary = skippedVerificationSummary(plan.notes, skips)
- onProgress?.({ phase: 'starting' })
- onEvent?.('launch', `拉起远端实例 (端口 ${profile.remotePort})`)
- const started = await session.exec(startCommandFor(profile, plan))
- if (started.code !== 0) {
- const message = started.stdout.includes('REMOTE_NOT_INSTALLED')
- ? `remote runtime incomplete on "${profile.host}" (REMOTE_NOT_INSTALLED)`
- : `remote instance start failed on "${profile.host}": ${describeExecFailure(started.code, started.stderr)}`
- return failBootstrap(onEvent, message)
- }
- for (let attempt = 0; attempt < bootstrap.healthPollAttempts; attempt++) {
- onProgress?.({ phase: 'probing', attempt: attempt + 1, total: bootstrap.healthPollAttempts })
- await sleep(bootstrap.healthPollIntervalMs)
- const verdict = await judgeReadiness(session, profile, bootstrap)
- if (verdict !== undefined) {
- emitReady(onEvent, target, verdict, skipSummary)
- return target
- }
- }
- const tail = await logTail(session)
- return failBootstrap(
- onEvent,
- `remote dsh web did not become ready on "${target}" within ${bootstrap.healthPollAttempts} polls; `
- + `fallback probe: root ${await legacyRootVerdict(session, profile, bootstrap)}; `
- + `remote log tail: ${tail}`,
- )
-}
-
-/**
- * One readiness judgement: boot-HTML manifest (primary) or any-response
- * (legacy fallback). Returns `boot …` / `legacy …`, or undefined while not
- * ready.
- */
-async function judgeReadiness(session: SshSession, profile: MachineProfile, bootstrap: BootstrapConfig): Promise<string | undefined> {
- const root = await session.exec(rootProbeCommand(profile.remotePort, bootstrap.healthCheckTimeoutMs))
- if (root.code !== 0)
- return undefined
- const urls = clientUrlsFromBootHtml(profile.remotePort, root.stdout)
- if (urls === undefined) {
- // No usable manifest: keep the legacy verdict — an answered port still
- // proves a webserver listens (the v1 behavior, demoted to fallback).
- return await legacyRootVerdict(session, profile, bootstrap)
- }
- const first = urls[0]
- if (first === undefined)
- return undefined
- const probe = await session.exec(bundleProbeCommand(first, bootstrap.healthCheckTimeoutMs))
- const { body, status } = splitBundleProbeStdout(probe.stdout)
- if (probe.code === 0 && status >= 200 && status < 300 && looksLikePluginBundle(true, body))
- return `boot manifest (${urls.length} bundles)`
- return undefined
-}
-
-/**
- * The legacy any-response probe command: the status code on stdout, exit
- * nonzero only when nothing answered. curl prints the real code; the wget
- * arm normalizes GNU wget's exit codes — 0 is a 2xx answer, 6/8 are server
- * answers (auth challenge / error status, code unknown → `4xx/5xx`), and
- * the rest are connection-level failures. The no-downloader marker rides
- * stdout so the failure message says why instead of a misleading "no
- * answer".
- * @param remotePort - the instance's loopback port.
- * @param timeoutMs - per-probe downloader deadline.
- */
-export function legacyProbeCommand(remotePort: number, timeoutMs: number): string {
- const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
- return [
- `if [ -n "$(command -v curl)" ]; then curl -s -o /dev/null -m ${seconds} -w '%{http_code}' http://127.0.0.1:${remotePort}/`,
- `elif [ -n "$(command -v wget)" ]; then wget -q -T ${seconds} -O /dev/null http://127.0.0.1:${remotePort}/; case $? in 0) echo 200 ;; 6|8) echo 4xx/5xx ;; *) exit 1 ;; esac`,
- `else echo ${REMOTE_PROBE_NO_DOWNLOADER}; fi`,
- ].join('; ')
-}
-
-/** The legacy any-response verdict, with the observed status code attached. */
-async function legacyRootVerdict(session: SshSession, profile: MachineProfile, bootstrap: BootstrapConfig): Promise<string> {
- const probe = await session.exec(legacyProbeCommand(profile.remotePort, bootstrap.healthCheckTimeoutMs))
- if (probe.stdout.includes(REMOTE_PROBE_NO_DOWNLOADER))
- return `no downloader (${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态)`
- return probe.code === 0 ? `root answered ${probe.stdout.trim() || '?'}` : 'no answer'
-}
-
-/**
- * Run the generated install script, streaming its stage-tagged output
- * line-buffered (SSH chunks may split mid-line). Returns the verify-stage
- * lines that recorded a skipped check, for the settling event's summary.
- * The single install executor for both the connect-time bootstrap and the
- * manager's install operation — the caller injects its event adapter
- * through {@link BootstrapHooks.onEvent}, so the two flows can never drift.
- * @param session - the authenticated session.
- * @param plan - the resolved install plan.
- * @param installTimeoutMs - the install exec deadline, when configured.
- * @param hooks - progress and event reporting.
- * @param failureLine - the settling failure event's display line.
- * @returns the verify-stage lines that recorded a skipped check.
- * @throws {Error} with the output tail when the script exits nonzero.
- */
-export async function runInstallScript(
- session: SshSession,
- plan: RemoteInstallPlan,
- installTimeoutMs: number | undefined,
- hooks: BootstrapHooks,
- failureLine = 'bootstrap 失败',
-): Promise<string[]> {
- const { onEvent, onProgress } = hooks
- let log = ''
- const skips: string[] = []
- const dispatch = createBootstrapLineDispatcher((line) => {
- const parsed = parseBootstrapLine(line)
- if (parsed.stage === 'verify' && parsed.line.includes('跳过'))
- skips.push(parsed.line)
- onEvent?.(parsed.stage, parsed.line)
- })
- const result = await session.exec(buildInstallScript(plan), {
- ...installTimeoutMs === undefined ? {} : { timeoutMs: installTimeoutMs },
- onData: (chunk) => {
- log = `${log}${chunk}`.slice(-2000)
- dispatch.push(chunk)
- onProgress?.({ phase: 'installing', log })
- },
- })
- dispatch.flush()
- if (result.code !== 0) {
- // Prefer the streamed log (the transport taps stdout live); transports
- // without the tap still surface the markers through the collected
- // stdout, and a totally silent failure keeps its exit stderr.
- const streamed = log.trim()
- const collected = streamed !== '' ? streamed : result.stdout.trim()
- const stream = collected !== '' ? collected : result.stderr.trim()
- const tail = stream === '' ? '(no output captured)' : stream.split('\n').slice(-5).join(' | ')
- failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`, failureLine)
- }
- return skips
-}
-
-/**
- * The settling ready event: primary boot-manifest verdict, legacy-fallback
- * note, and the skipped-verification summary when checks were skipped.
- */
-function emitReady(
- onEvent: BootstrapHooks['onEvent'],
- target: string,
- verdict: string,
- skipSummary = '',
-): void {
- const base = verdict.startsWith('boot')
- ? `远端实例已就绪 (${target})`
- : `远端实例已就绪(旧探测兜底: ${verdict})`
- onEvent?.('ready', `${base}${skipSummary}`, { terminal: 'success' })
-}
-
-/**
- * Record the terminal failure and build the thrown error.
- * @param onEvent - the event hook receiving the settling event.
- * @param reason - the operator-facing failure reason.
- * @param line - the settling event's display line (the install operation
- * passes its own wording; the default matches the connect-time bootstrap).
- */
-function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string, line = 'bootstrap 失败'): never {
- onEvent?.('failed', line, { terminal: 'failed', reason })
- throw new Error(reason)
-}
-
-/** The remote instance log's tail, or a note when nothing was captured. */
-async function logTail(session: SshSession): Promise<string> {
- try {
- const result = await session.exec(logTailCommand())
- const tail = result.stdout.trim()
- return tail === '' ? '(log is empty)' : tail.split('\n').slice(-5).join(' | ')
- }
- catch {
- return '(log unreadable)'
- }
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise(resolve => setTimeout(resolve, ms))
-}
+import type { MachineProfile, SshSession } from '../types/index'
+import type { BootstrapHooks, RemoteInstallPlan } from './bootstrap.types'
+import { defineService } from 'dsh-tauri'
+import { hostConfig } from '../config/runtime'
+import { ensureRemoteInstance, runInstallScript } from './bootstrap.utils'
+
+export const bootstrap = defineService({
+ async provision(
+ session: SshSession,
+ profile: MachineProfile,
+ hooks: BootstrapHooks = {},
+ ): Promise<string> {
+ return await ensureRemoteInstance(session, profile, hostConfig(), hooks)
+ },
+
+ async install(
+ session: SshSession,
+ plan: RemoteInstallPlan,
+ hooks: BootstrapHooks = {},
+ failureLine = 'bootstrap 失败',
+ ): Promise<string[]> {
+ return await runInstallScript(session, plan, hostConfig().installTimeoutMs!, hooks, failureLine)
+ },
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts
new file mode 100644
index 00000000..58cde486
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.types.ts
@@ -0,0 +1,46 @@
+import type { SshMachineStage, SshMachineTerminal, SshProgress } from '../types/index'
+import type { RemoteArch, RemoteAssetMatrix, RemoteOs } from '../utils/assets'
+
+export interface BootstrapLogLine {
+ stage: SshMachineStage
+ line: string
+}
+
+export interface DshNpmPlan {
+ kind: 'npm-tgz'
+ urls: string[]
+ integrity?: string
+ packageName: string
+ version: string
+}
+
+export interface DshZipPlan {
+ kind: 'pkg-zip'
+ urls: string[]
+ digest?: string
+ zipName: string
+ tag: string
+}
+
+export interface RemoteInstallPlan {
+ os: RemoteOs
+ arch: RemoteArch
+ matrix: RemoteAssetMatrix
+ repo: string
+ dshEntry: string
+ dshVersion: string
+ node: { urls: string[], shasumUrls: string[], filename: string, version: string }
+ dsh: DshNpmPlan | DshZipPlan
+ pnpm: { urls: string[], sha256: string, version: string }
+ notes: string[]
+}
+
+export interface EnvCredentials {
+ apiKey?: string
+ baseUrl?: string
+}
+
+export interface BootstrapHooks {
+ onProgress?: (progress: SshProgress) => void
+ onEvent?: (stage: SshMachineStage, line: string, options?: { terminal?: SshMachineTerminal, reason?: string }) => void
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts b/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts
new file mode 100644
index 00000000..2902e135
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/bootstrap.utils.ts
@@ -0,0 +1,665 @@
+import type { Config } from '../config/schema'
+import type { MachineProfile, SshMachineStage, SshSession } from '../types/index'
+import type { BootstrapHooks, BootstrapLogLine, EnvCredentials, RemoteInstallPlan } from './bootstrap.types'
+import { Buffer } from 'node:buffer'
+import { readFileSync } from 'node:fs'
+import { messageOf } from '../../shared/error'
+import { DEFAULT_REMOTE_PROFILE, REMOTE_ROOT } from '../config/constants'
+import { assetMatrixFor, dshNpmTarballUrls, dshZipDownloadUrls, NODE_VERSION, nodeDownloadUrls, nodeShasumUrls, parsePlatform, PNPM_SHA256, PNPM_VERSION, pnpmDownloadUrls } from '../utils/assets'
+import { clientUrlsFromBootHtml, looksLikePluginBundle } from '../utils/boot-html'
+import { shQuote } from '../utils/shell'
+import { listGithubAssets, listGithubReleases, npmDistMetadata, parseGitHubRepo, pickReleaseTag, pkgRepoOf } from '../utils/version'
+
+export const REMOTE_WEB_LOG = '.dsh/dsh-remote-web.log'
+
+export const BOOTSTRAP_LOG_PREFIX = '::dsh '
+
+const DSH_ZIP_ENTRY = 'node_modules/@deepseek-ai/dsh/lib/bin.js'
+
+const DSH_NPM_ENTRY = 'lib/bin.js'
+
+const PNPM_ENTRY = 'bin/pnpm.cjs'
+
+const BOOTSTRAP_STAGES: Record<SshMachineStage, true> = {
+ probe: true,
+ download: true,
+ verify: true,
+ install: true,
+ launch: true,
+ ready: true,
+ failed: true,
+ auth: true,
+ reconnect: true,
+}
+
+function isBootstrapStage(value: string): value is SshMachineStage {
+ return (BOOTSTRAP_STAGES as Record<string, true | undefined>)[value] === true
+}
+
+export function parseBootstrapLine(chunk: string): BootstrapLogLine {
+ const match = /^::dsh (\w+) (.*)$/u.exec(chunk)
+ const stage = match?.[1]
+ if (match === null || stage === undefined || !isBootstrapStage(stage))
+ return { stage: 'install', line: chunk }
+ return { stage, line: match[2] ?? '' }
+}
+
+export function createBootstrapLineDispatcher(onLine: (line: string) => void): { push: (chunk: string) => void, flush: () => void } {
+ let pending = ''
+ return {
+ push(chunk: string): void {
+ pending = `${pending}${chunk}`
+ const lines = pending.split('\n')
+ pending = lines.pop() ?? ''
+ for (const line of lines) {
+ if (line !== '')
+ onLine(line)
+ }
+ },
+ flush(): void {
+ const line = pending
+ pending = ''
+ if (line !== '')
+ onLine(line)
+ },
+ }
+}
+
+export function skippedVerificationSummary(notes: string[], skipLines: string[]): string {
+ const items = [...new Set([...notes, ...skipLines].filter(item => item.includes('跳过')))]
+ return items.length === 0 ? '' : `;跳过校验项: ${items.join(';')}`
+}
+
+export function normalizeNpmIntegrity(integrity: string | undefined): string | undefined {
+ if (integrity === undefined)
+ return undefined
+ const sri = /^sha(256|512)-([A-Za-z0-9+/]+={0,2})$/u.exec(integrity)
+ if (sri !== null)
+ return `sha${sri[1]}:${Buffer.from(sri[2] ?? '', 'base64').toString('hex')}`
+ return integrity.startsWith('sha256:') || integrity.startsWith('sha512:') ? integrity : undefined
+}
+
+export async function planRemoteInstall(
+ unameOut: string,
+ config: Pick<Config, 'installRepo' | 'installRef'>,
+ fetchers: {
+ listReleases?: (repo: string) => Promise<{ tag: string, prerelease: boolean }[]>
+ listAssets?: (repo: string, tag: string) => Promise<Array<{ name: string, url: string, digest?: string }>>
+ npmDist?: (packageName: string, version: string) => Promise<{ url: string, mirrorUrl: string, integrity?: string }>
+ } = {},
+): Promise<RemoteInstallPlan> {
+ const { os, arch } = parsePlatform(unameOut)
+ const matrix = assetMatrixFor(os, arch)
+ const repo = pkgRepoOf(config.installRepo)
+ const notes: string[] = []
+ const configuredRepo = config.installRepo?.trim()
+ if (configuredRepo !== undefined && configuredRepo !== '' && parseGitHubRepo(configuredRepo) === undefined)
+ notes.push(`installRepo "${configuredRepo}" 无法解析为 GitHub 仓库,回退官方发行仓 ${repo}`)
+ const listReleases = fetchers.listReleases ?? listGithubReleases
+ const listAssets = fetchers.listAssets ?? listGithubAssets
+ const npmDist = fetchers.npmDist ?? npmDistMetadata
+ let metas
+ try {
+ metas = await listReleases(repo)
+ }
+ catch (error) {
+ notes.push(`release 列表获取失败(${messageOf(error)})`)
+ }
+ const resolved = pickReleaseTag(metas, { ref: config.installRef })
+ notes.push(...resolved.notes.map(note => `版本选择: ${note}`))
+ const node = {
+ urls: nodeDownloadUrls(os, arch),
+ shasumUrls: nodeShasumUrls(),
+ filename: matrix.nodeFilename,
+ version: NODE_VERSION,
+ }
+ const pnpm = { urls: pnpmDownloadUrls(), sha256: PNPM_SHA256, version: PNPM_VERSION }
+ if (matrix.dshKind === 'pkg-zip') {
+ const zipName = matrix.dshZipName ?? ''
+ let urls: string[] | undefined
+ let digest: string | undefined
+ try {
+ const assets = await listAssets(repo, resolved.tag)
+ const asset = assets.find(candidate => candidate.name === zipName)
+ if (asset !== undefined) {
+ urls = [asset.url, ...dshZipDownloadUrls(repo, resolved.tag, zipName).slice(1)]
+ digest = asset.digest
+ }
+ }
+ catch (error) {
+ notes.push(`release 资产元数据获取失败(${messageOf(error)})`)
+ }
+ if (digest === undefined)
+ notes.push(`未取得 ${zipName} 的可信摘要,将跳过 SHA-256 校验`)
+ return {
+ os,
+ arch,
+ matrix,
+ repo,
+ dshEntry: DSH_ZIP_ENTRY,
+ dshVersion: resolved.version,
+ node,
+ dsh: { kind: 'pkg-zip', urls: urls ?? dshZipDownloadUrls(repo, resolved.tag, zipName), ...digest === undefined ? {} : { digest }, zipName, tag: resolved.tag },
+ pnpm,
+ notes,
+ }
+ }
+ const packageName = matrix.dshNpmPackage ?? '@deepseek-ai/dsh'
+ if (resolved.version === '')
+ throw new Error(`cannot resolve a DSH npm version from tag "${resolved.tag}"`)
+ let urls: string[] | undefined
+ let integrity: string | undefined
+ try {
+ const dist = await npmDist(packageName, resolved.version)
+ urls = [...new Set([dist.url, dist.mirrorUrl])]
+ integrity = normalizeNpmIntegrity(dist.integrity)
+ }
+ catch (error) {
+ notes.push(`npm 元数据获取失败(${messageOf(error)}),回退确定性 URL`)
+ }
+ if (integrity === undefined)
+ notes.push(`未取得 ${packageName}@${resolved.version} 的可校验完整性摘要,将跳过校验`)
+ return {
+ os,
+ arch,
+ matrix,
+ repo,
+ dshEntry: DSH_NPM_ENTRY,
+ dshVersion: resolved.version,
+ node,
+ dsh: { kind: 'npm-tgz', urls: urls ?? dshNpmTarballUrls(packageName, resolved.version), ...integrity === undefined ? {} : { integrity }, packageName, version: resolved.version },
+ pnpm,
+ notes,
+ }
+}
+
+function quoteUrls(urls: string[]): string {
+ return urls.map(shQuote).join(' ')
+}
+
+export function buildInstallScript(plan: RemoteInstallPlan): string {
+ const dshSection = plan.dsh.kind === 'pkg-zip'
+ ? [
+ `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then`,
+ ` log install "dsh 已就绪"`,
+ `else`,
+ ` log download "dsh ${plan.dsh.tag}"`,
+ ` fetch "$TMP/dsh-pkg.zip" ${quoteUrls(plan.dsh.urls)}`,
+ ` verify "$TMP/dsh-pkg.zip" "${plan.dsh.digest ?? ''}" "${plan.dsh.zipName}"`,
+ ` extract_zip "$TMP/dsh-pkg.zip" "$ROOT/dependencies/dsh.new"`,
+ ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,
+ ` log install "dsh 安装完成 (${plan.dsh.tag})"`,
+ `fi`,
+ ].join('\n')
+ : [
+ `install_dsh_deps() {`,
+ ` for _reg in ${quoteUrls(['https://registry.npmjs.org', 'https://registry.npmmirror.com'])}; do`,
+ ` if ( cd "$ROOT/dependencies/dsh" && "$ROOT/runtime/bin/node" "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" install --prod --silent --registry="$_reg" >"$TMP/pnpm.log" 2>&1 ); then`,
+ ` log install "dsh 依赖安装完成 (registry $_reg)"`,
+ ` return 0`,
+ ` fi`,
+ ` done`,
+ ` log failed "pnpm install 失败: $(tail -n 5 "$TMP/pnpm.log" 2>/dev/null | tr '\n' ' ')"`,
+ ` return 1`,
+ `}`,
+ `if [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then`,
+ ` log install "dsh 已就绪"`,
+ `else`,
+ ` log download "dsh ${plan.dsh.packageName}@${plan.dsh.version} (npm)"`,
+ ` fetch "$TMP/dsh.tgz" ${quoteUrls(plan.dsh.urls)}`,
+ ` verify "$TMP/dsh.tgz" "${plan.dsh.integrity ?? ''}" "${plan.dsh.packageName}-${plan.dsh.version}.tgz"`,
+ ` rm -rf "$ROOT/dependencies/dsh.new"`,
+ ` mkdir -p "$ROOT/dependencies/dsh.new"`,
+ ` tar -xzf "$TMP/dsh.tgz" -C "$ROOT/dependencies/dsh.new" --strip-components=1`,
+ ` flatten_move "$ROOT/dependencies/dsh.new" "$ROOT/dependencies/dsh"`,
+ ` install_dsh_deps || exit 13`,
+ ` log install "dsh 安装完成 (${plan.dsh.packageName}@${plan.dsh.version})"`,
+ `fi`,
+ ].join('\n')
+ return [
+ 'set -eu',
+ 'ROOT="$HOME/.dsh-desktop"',
+ 'TMP="$ROOT/tmp"',
+ 'mkdir -p "$ROOT/dependencies" "$TMP"',
+ 'cleanup() { rm -rf "$TMP" "$ROOT/runtime.new" "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/dsh.new"; }',
+ 'trap cleanup EXIT',
+ `log() { printf '${BOOTSTRAP_LOG_PREFIX}%s %s\\n' "$1" "$2"; }`,
+ 'fetch() {',
+ ' _dst="$1"; shift',
+ ' _errs=""',
+ ' for _url in "$@"; do',
+ ' if command -v curl >/dev/null 2>&1; then',
+ ' log download "$_url"',
+ ' if curl -fsSL --retry 3 --connect-timeout 15 -o "$_dst" "$_url" 2>"$TMP/fetch.err"; then return 0; fi',
+ ' _errs="$_errs | $_url: $(head -n 1 "$TMP/fetch.err" 2>/dev/null || echo download failed)"',
+ ' elif command -v wget >/dev/null 2>&1; then',
+ ' log download "$_url"',
+ ' if wget -q --tries=3 -O "$_dst" "$_url" 2>/dev/null; then return 0; fi',
+ ' _errs="$_errs | $_url: wget download failed"',
+ ' else',
+ ' log failed "REMOTE_INSTALL_NO_DOWNLOADER: 远端缺少 curl 或 wget,请先安装其一"',
+ ' exit 9',
+ ' fi',
+ ' done',
+ ' log failed "所有下载源均失败:$_errs"',
+ ' exit 10',
+ '}',
+ 'verify() {',
+ ' _file="$1"; _want="$2"; _name="$3"',
+ ' case "$_want" in',
+ ' sha256:*) _algo=256; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha256://\')" ;;',
+ ' sha512:*) _algo=512; _hex="$(printf \'%s\' "$_want" | sed \'s/^sha512://\')" ;;',
+ ' "") log verify "警告: 未取得可信摘要,跳过校验 $_name"; return 0 ;;',
+ ' *) _algo=256; _hex="$_want" ;;',
+ ' esac',
+ ' _got=""',
+ ` if [ "\$_algo" = 256 ]; then`,
+ ' if command -v sha256sum >/dev/null 2>&1; then _got="$(sha256sum "$_file" | cut -d\' \' -f1)"',
+ ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 256 "$_file" | cut -d\' \' -f1)"',
+ ' fi',
+ ' else',
+ ' if command -v sha512sum >/dev/null 2>&1; then _got="$(sha512sum "$_file" | cut -d\' \' -f1)"',
+ ' elif command -v shasum >/dev/null 2>&1; then _got="$(shasum -a 512 "$_file" | cut -d\' \' -f1)"',
+ ' fi',
+ ' fi',
+ ' if [ -z "$_got" ]; then',
+ ' log verify "警告: 远端缺少摘要工具,跳过校验 $_name"',
+ ' return 0',
+ ' fi',
+ ' if [ "$_got" != "$_hex" ]; then',
+ ' log failed "checksum mismatch: $_name (want sha$_algo:$_hex, got $_got)"',
+ ' exit 11',
+ ' fi',
+ ` log verify "$_name 校验通过 (sha$_algo)"`,
+ '}',
+ 'extract_zip() {',
+ ' _zip="$1"; _dir="$2"',
+ ' mkdir -p "$_dir"',
+ ' if command -v unzip >/dev/null 2>&1; then unzip -q -o "$_zip" -d "$_dir"',
+ ' elif command -v python3 >/dev/null 2>&1; then python3 -m zipfile -e "$_zip" "$_dir"',
+ ' else',
+ ' log failed "REMOTE_INSTALL_NO_UNZIP: 远端缺少 unzip 或 python3,无法解压发行包"',
+ ' exit 12',
+ ' fi',
+ '}',
+ 'flatten_move() {',
+ ' _src="$1"; _dst="$2"',
+ ' _count=0; _top=""',
+ ' for _e in "$_src"/*; do',
+ ' if [ -e "$_e" ]; then _count=$((_count + 1)); _top="$_e"; fi',
+ ' done',
+ ' rm -rf "$_dst"',
+ ' if [ "$_count" -eq 1 ] && [ -d "$_top" ]; then',
+ ' mkdir -p "$_dst"',
+ ' for _e in "$_top"/* "$_top"/.[!.]* "$_top"/..?*; do',
+ ' if [ -e "$_e" ]; then mv -f "$_e" "$_dst/"; fi',
+ ' done',
+ ' rmdir "$_top" 2>/dev/null || true',
+ ' rmdir "$_src" 2>/dev/null || true',
+ ' else',
+ ' mv -f "$_src" "$_dst"',
+ ' fi',
+ '}',
+ 'if [ -x "$ROOT/runtime/bin/node" ]; then',
+ ' log install "node 已就绪: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo installed)"',
+ 'else',
+ ` log download "node ${plan.node.version}"`,
+ ` fetch "$TMP/node.tar.gz" ${quoteUrls(plan.node.urls)}`,
+ ` fetch "$TMP/SHASUMS256.txt" ${quoteUrls(plan.node.shasumUrls)}`,
+ ` _want="$(grep " ${plan.node.filename}\$" "$TMP/SHASUMS256.txt" | head -n 1 | tr -d '\\r' | sed 's/^ *//' | cut -d' ' -f1)"`,
+ ` verify "$TMP/node.tar.gz" "\$_want" "${plan.node.filename}"`,
+ ' rm -rf "$ROOT/runtime.new"',
+ ' mkdir -p "$ROOT/runtime.new"',
+ ' tar -xzf "$TMP/node.tar.gz" -C "$ROOT/runtime.new" --strip-components=1',
+ ' flatten_move "$ROOT/runtime.new" "$ROOT/runtime"',
+ ` log install "node 安装完成: $("$ROOT/runtime/bin/node" --version 2>/dev/null || echo ok)"`,
+ 'fi',
+ `if [ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ]; then`,
+ ' log install "pnpm 已就绪"',
+ 'else',
+ ` log download "pnpm ${plan.pnpm.version}"`,
+ ` fetch "$TMP/pnpm.tgz" ${quoteUrls(plan.pnpm.urls)}`,
+ ` verify "$TMP/pnpm.tgz" "sha256:${plan.pnpm.sha256}" "pnpm-${plan.pnpm.version}.tgz"`,
+ ' rm -rf "$ROOT/dependencies/pnpm.new"',
+ ' mkdir -p "$ROOT/dependencies/pnpm.new"',
+ ' tar -xzf "$TMP/pnpm.tgz" -C "$ROOT/dependencies/pnpm.new" --strip-components=1',
+ ' flatten_move "$ROOT/dependencies/pnpm.new" "$ROOT/dependencies/pnpm"',
+ ` log install "pnpm 安装完成: ${plan.pnpm.version}"`,
+ 'fi',
+ dshSection,
+ 'log install "远端初始化完成"',
+ ].join('\n')
+}
+
+export function checkMissingCommand(): string {
+ return [
+ `ROOT="$HOME/${REMOTE_ROOT}"`,
+ `[ -x "$ROOT/runtime/bin/node" ] || echo node`,
+ `[ -f "$ROOT/dependencies/pnpm/${PNPM_ENTRY}" ] || echo pnpm`,
+ `if [ ! -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ] && [ ! -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then echo dsh; fi`,
+ 'true',
+ ].join('\n')
+}
+
+export function missingComponentsOf(stdout: string): string[] {
+ return stdout.split('\n').map(line => line.trim()).filter(line => line !== '' && ['node', 'dsh', 'pnpm'].includes(line))
+}
+
+export function layoutDshEntry(plan?: RemoteInstallPlan): string {
+ return `$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan?.dshEntry ?? DSH_ZIP_ENTRY}`
+}
+
+export function layoutNodeBinary(): string {
+ return `"$HOME/${REMOTE_ROOT}/runtime/bin/node"`
+}
+
+export function layoutBinDir(): string {
+ return `$HOME/${REMOTE_ROOT}/runtime/bin`
+}
+
+export function ensurePnpmCommand(): string {
+ const shim = `#!/bin/sh\nexec "$HOME/${REMOTE_ROOT}/runtime/bin/node" "$HOME/${REMOTE_ROOT}/dependencies/pnpm/${PNPM_ENTRY}" "$@"\n`
+ return `B="${layoutBinDir()}"; [ -x "$B/pnpm" ] || { mkdir -p "$B" && printf %s ${shQuote(shim)} > "$B/pnpm" && chmod +x "$B/pnpm"; }`
+}
+
+export function dshEntryProbeCommand(): string {
+ return [
+ `ROOT="$HOME/${REMOTE_ROOT}"`,
+ `if [ -f "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_ZIP_ENTRY}"`,
+ `elif [ -f "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}" ]; then printf '%s\\n' "$ROOT/dependencies/dsh/${DSH_NPM_ENTRY}"`,
+ 'fi',
+ 'true',
+ ].join('\n')
+}
+
+export function remoteWebTokenCommand(): string {
+ return `grep -oE 'token=[A-Za-z0-9._~-]+' "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null | tail -n 1 | cut -d= -f2`
+}
+
+export function safeProfileName(raw: string | undefined): string {
+ return raw !== undefined && /^[\w-]+$/.test(raw) ? raw : DEFAULT_REMOTE_PROFILE
+}
+
+export function startCommandFor(profile: MachineProfile, plan?: RemoteInstallPlan): string {
+ if (profile.startCommand !== undefined)
+ return `mkdir -p "$HOME/.dsh" && ( ${profile.startCommand} >>"$HOME/${REMOTE_WEB_LOG}" 2>&1 < /dev/null & ) &`
+ const node = `$HOME/${REMOTE_ROOT}/runtime/bin/node`
+ const dshBin = layoutDshEntry(plan)
+ const profileName = safeProfileName(profile.profileName)
+ return [
+ `ROOT="$HOME/${REMOTE_ROOT}"`,
+ `NODE=${node}`,
+ `DSH_BIN=${dshBin}`,
+ `LOG_DIR="$HOME/.dsh"`,
+ `LOG="$LOG_DIR/dsh-remote-web.log"`,
+ `if [ ! -x "$NODE" ] || [ ! -f "$DSH_BIN" ]; then echo "REMOTE_NOT_INSTALLED: 远端三件套未安装完整"; exit 1; fi`,
+ `mkdir -p "$LOG_DIR"`,
+ `export PATH="$ROOT/runtime/bin:$PATH"`,
+ `export DSH_TELEMETRY_DISABLED=1 NO_COLOR=1 DSH_WEB_PORT=${profile.remotePort}`,
+ `export DSH_REMOTE_SESSION_ORIGIN=${shQuote(profile.name)}`,
+ `( sh -c 'echo $$ > "$1/.dsh-remote.pid"; exec "$2" "$3" --profile "$5" --host 127.0.0.1 --port "$4" --no-open' dsh-remote "$LOG_DIR" "$NODE" "$DSH_BIN" ${profile.remotePort} ${profileName} </dev/null >>"$LOG" 2>&1 & )`,
+ `echo "远端实例已拉起(档案: ${profileName}, 日志: $LOG)"`,
+ ].join('\n')
+}
+
+export function readEnvCredentials(path: string): EnvCredentials {
+ let text: string
+ try {
+ text = readFileSync(path, 'utf8')
+ }
+ catch {
+ return {}
+ }
+ const out: EnvCredentials = {}
+ const apiKey = envValueOf(text, 'DEEPSEEK_API_KEY')
+ /* v8 ignore next -- attribution artifact: both arms are exercised by the credentials tests */
+ if (apiKey !== undefined)
+ out.apiKey = apiKey
+ const baseUrl = envValueOf(text, 'DEEPSEEK_BASE_URL')
+ if (baseUrl !== undefined)
+ out.baseUrl = baseUrl
+ return out
+}
+
+export function credentialsCopyCommand(credentials: EnvCredentials & { apiKey: string }): string {
+ const managed = ['DEEPSEEK_API_KEY', ...(credentials.baseUrl === undefined ? [] : ['DEEPSEEK_BASE_URL'])]
+ const writes = [`printf 'DEEPSEEK_API_KEY=%s\\n' ${shQuote(credentials.apiKey)}`]
+ if (credentials.baseUrl !== undefined)
+ writes.push(`printf 'DEEPSEEK_BASE_URL=%s\\n' ${shQuote(credentials.baseUrl)}`)
+ const filter = managed.map(key => `^${key}=`).join('|')
+ return [
+ `mkdir -p "$HOME/.dsh"`,
+ `if grep -q '^DEEPSEEK_API_KEY=' "$HOME/.dsh/.env" 2>/dev/null; then echo existing; else umask 077 && { grep -v -E '${filter}' "$HOME/.dsh/.env" 2>/dev/null || true; ${writes.join('; ')}; } > "$HOME/.dsh/.env.new" && mv -f "$HOME/.dsh/.env.new" "$HOME/.dsh/.env" && echo copied; fi`,
+ ].join(' && ')
+}
+
+function envValueOf(text: string, key: string): string | undefined {
+ for (const line of text.split('\n')) {
+ if (!line.startsWith(`${key}=`))
+ continue
+ const value = line.slice(key.length + 1).trim().replace(/^"(.*)"$/u, '$1')
+ return value === '' ? undefined : value
+ }
+ return undefined
+}
+
+export function firstLineOf(stdout: string): string {
+ for (const line of stdout.split('\n')) {
+ const trimmed = line.trim()
+ if (trimmed !== '')
+ return trimmed
+ }
+ return ''
+}
+
+export const REMOTE_PROBE_NO_DOWNLOADER = 'REMOTE_PROBE_NO_DOWNLOADER'
+
+function withDownloaderFallback(curlArm: string, wgetArm: string): string {
+ return [
+ `if [ -n "$(command -v curl)" ]; then ${curlArm}`,
+ `elif [ -n "$(command -v wget)" ]; then ${wgetArm}`,
+ `else echo "${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态" >&2; exit 1; fi`,
+ ].join('; ')
+}
+
+export function rootProbeCommand(remotePort: number, timeoutMs: number): string {
+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
+ return withDownloaderFallback(
+ `curl -s -m ${seconds} http://127.0.0.1:${remotePort}/`,
+ `wget -q -T ${seconds} -O - http://127.0.0.1:${remotePort}/; case $? in 0|6|8) ;; *) exit 1 ;; esac`,
+ )
+}
+
+export function bundleProbeCommand(url: string, timeoutMs: number): string {
+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
+ return withDownloaderFallback(
+ `curl -s -m ${seconds} -w '\\n%{http_code}' ${shQuote(url)}`,
+ `wget -q -T ${seconds} -O - ${shQuote(url)} && printf '\\n200\\n' || printf '\\n0\\n'`,
+ )
+}
+
+export function splitBundleProbeStdout(stdout: string): { body: string, status: number } {
+ const trimmed = stdout.replace(/\n$/u, '')
+ const index = trimmed.lastIndexOf('\n')
+ if (index < 0) {
+ const status = Number.parseInt(trimmed, 10)
+ return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: '', status }
+ }
+ const status = Number.parseInt(trimmed.slice(index + 1).trim(), 10)
+ return Number.isNaN(status) ? { body: trimmed, status: 0 } : { body: trimmed.slice(0, index), status }
+}
+
+export function logTailCommand(): string {
+ return `tail -n 20 "$HOME/${REMOTE_WEB_LOG}" 2>/dev/null || true`
+}
+
+export function describeExecFailure(code: number | null, stderr: string): string {
+ const tail = stderr.trim().split('\n').slice(-3).join(' | ')
+ return `exit ${code ?? '?'}${tail === '' ? '' : `: ${tail}`}`
+}
+
+export async function ensureRemoteInstance(
+ session: SshSession,
+ profile: MachineProfile,
+ config: Config,
+ hooks: BootstrapHooks = {},
+): Promise<string> {
+ const { onEvent, onProgress } = hooks
+ const target = `${profile.host}:${profile.remotePort}`
+ const readyFromHtml = await judgeReadiness(session, profile, config)
+ if (readyFromHtml !== undefined) {
+ emitReady(onEvent, target, readyFromHtml)
+ return target
+ }
+ onEvent?.('probe', '探测远端平台 (uname -srm)')
+ const uname = await session.exec('uname -srm')
+ if (uname.code !== 0) {
+ return failBootstrap(onEvent, `无法探测远端平台: ${describeExecFailure(uname.code, uname.stderr)}`)
+ }
+ let plan: RemoteInstallPlan
+ try {
+ plan = await planRemoteInstall(uname.stdout, config)
+ }
+ catch (error) {
+ return failBootstrap(onEvent, messageOf(error))
+ }
+ onEvent?.('probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)
+ for (const note of plan.notes)
+ onEvent?.('probe', note)
+ const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
+ let skips: string[] = []
+ if (missing.length > 0) {
+ onEvent?.('probe', `缺失组件: ${missing.join(', ')}`)
+ skips = await runInstallScript(session, plan, config.installTimeoutMs!, hooks)
+ }
+ else {
+ onEvent?.('probe', '三件套已就绪,跳过安装')
+ }
+ const skipSummary = skippedVerificationSummary(plan.notes, skips)
+ onProgress?.({ phase: 'starting' })
+ onEvent?.('launch', `拉起远端实例 (端口 ${profile.remotePort})`)
+ const started = await session.exec(startCommandFor(profile, plan))
+ if (started.code !== 0) {
+ const message = started.stdout.includes('REMOTE_NOT_INSTALLED')
+ ? `remote runtime incomplete on "${profile.host}" (REMOTE_NOT_INSTALLED)`
+ : `remote instance start failed on "${profile.host}": ${describeExecFailure(started.code, started.stderr)}`
+ return failBootstrap(onEvent, message)
+ }
+ for (let attempt = 0; attempt < config.healthPollAttempts; attempt++) {
+ onProgress?.({ phase: 'probing', attempt: attempt + 1, total: config.healthPollAttempts })
+ await sleep(config.healthPollIntervalMs)
+ const verdict = await judgeReadiness(session, profile, config)
+ if (verdict !== undefined) {
+ emitReady(onEvent, target, verdict, skipSummary)
+ return target
+ }
+ }
+ const tail = await logTail(session)
+ return failBootstrap(
+ onEvent,
+ `remote dsh web did not become ready on "${target}" within ${config.healthPollAttempts} polls; `
+ + `fallback probe: root ${await legacyRootVerdict(session, profile, config)}; `
+ + `remote log tail: ${tail}`,
+ )
+}
+
+async function judgeReadiness(session: SshSession, profile: MachineProfile, config: Config): Promise<string | undefined> {
+ const root = await session.exec(rootProbeCommand(profile.remotePort, config.healthCheckTimeoutMs))
+ if (root.code !== 0)
+ return undefined
+ const urls = clientUrlsFromBootHtml(profile.remotePort, root.stdout)
+ if (urls === undefined) {
+ return await legacyRootVerdict(session, profile, config)
+ }
+ const first = urls[0]
+ if (first === undefined)
+ return undefined
+ const probe = await session.exec(bundleProbeCommand(first, config.healthCheckTimeoutMs))
+ const { body, status } = splitBundleProbeStdout(probe.stdout)
+ if (probe.code === 0 && status >= 200 && status < 300 && looksLikePluginBundle(true, body))
+ return `boot manifest (${urls.length} bundles)`
+ return undefined
+}
+
+export function legacyProbeCommand(remotePort: number, timeoutMs: number): string {
+ const seconds = Math.max(1, Math.ceil(timeoutMs / 1000))
+ return [
+ `if [ -n "$(command -v curl)" ]; then curl -s -o /dev/null -m ${seconds} -w '%{http_code}' http://127.0.0.1:${remotePort}/`,
+ `elif [ -n "$(command -v wget)" ]; then wget -q -T ${seconds} -O /dev/null http://127.0.0.1:${remotePort}/; case $? in 0) echo 200 ;; 6|8) echo 4xx/5xx ;; *) exit 1 ;; esac`,
+ `else echo ${REMOTE_PROBE_NO_DOWNLOADER}; fi`,
+ ].join('; ')
+}
+
+async function legacyRootVerdict(session: SshSession, profile: MachineProfile, config: Config): Promise<string> {
+ const probe = await session.exec(legacyProbeCommand(profile.remotePort, config.healthCheckTimeoutMs))
+ if (probe.stdout.includes(REMOTE_PROBE_NO_DOWNLOADER))
+ return `no downloader (${REMOTE_PROBE_NO_DOWNLOADER}: 远端缺少 curl 与 wget,无法探测就绪状态)`
+ return probe.code === 0 ? `root answered ${probe.stdout.trim() || '?'}` : 'no answer'
+}
+
+export async function runInstallScript(
+ session: SshSession,
+ plan: RemoteInstallPlan,
+ installTimeoutMs: number,
+ hooks: BootstrapHooks,
+ failureLine = 'bootstrap 失败',
+): Promise<string[]> {
+ const { onEvent, onProgress } = hooks
+ let log = ''
+ const skips: string[] = []
+ const dispatch = createBootstrapLineDispatcher((line) => {
+ const parsed = parseBootstrapLine(line)
+ if (parsed.stage === 'verify' && parsed.line.includes('跳过'))
+ skips.push(parsed.line)
+ onEvent?.(parsed.stage, parsed.line)
+ })
+ const result = await session.exec(buildInstallScript(plan), {
+ timeoutMs: installTimeoutMs,
+ onData: (chunk) => {
+ log = `${log}${chunk}`.slice(-2000)
+ dispatch.push(chunk)
+ onProgress?.({ phase: 'installing', log })
+ },
+ })
+ dispatch.flush()
+ if (result.code !== 0) {
+ const streamed = log.trim()
+ const collected = streamed !== '' ? streamed : result.stdout.trim()
+ const stream = collected !== '' ? collected : result.stderr.trim()
+ const tail = stream === '' ? '(no output captured)' : stream.split('\n').slice(-5).join(' | ')
+ failBootstrap(onEvent, `install failed on remote (exit ${result.code ?? '?'}): ${tail}`, failureLine)
+ }
+ return skips
+}
+
+function emitReady(
+ onEvent: BootstrapHooks['onEvent'],
+ target: string,
+ verdict: string,
+ skipSummary = '',
+): void {
+ const base = verdict.startsWith('boot')
+ ? `远端实例已就绪 (${target})`
+ : `远端实例已就绪(旧探测兜底: ${verdict})`
+ onEvent?.('ready', `${base}${skipSummary}`, { terminal: 'success' })
+}
+
+function failBootstrap(onEvent: BootstrapHooks['onEvent'], reason: string, line = 'bootstrap 失败'): never {
+ onEvent?.('failed', line, { terminal: 'failed', reason })
+ throw new Error(reason)
+}
+
+async function logTail(session: SshSession): Promise<string> {
+ try {
+ const result = await session.exec(logTailCommand())
+ const tail = result.stdout.trim()
+ return tail === '' ? '(log is empty)' : tail.split('\n').slice(-5).join(' | ')
+ }
+ catch {
+ return '(log unreadable)'
+ }
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise(resolve => setTimeout(resolve, ms))
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/events.test.ts b/packages/dsh-tauri-ssh/src/host/service/events.test.ts
index c8a35296..c7ff17c6 100644
--- a/packages/dsh-tauri-ssh/src/host/service/events.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/events.test.ts
@@ -1,13 +1,20 @@
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it } from 'vitest'
+import { EVENT_RING_CAPACITY } from '../config/constants'
+import { clearHostRuntime, setEventCapacity } from '../config/runtime'
import { MachineId } from '../types/index'
-import { EVENT_RING_CAPACITY, SshMachineEvents } from './events'
+import { events } from './events'
const m1 = MachineId('m1')
const m2 = MachineId('m2')
+beforeEach(() => {
+ clearHostRuntime()
+ setEventCapacity(EVENT_RING_CAPACITY)
+})
+
describe('sshMachineEvents', () => {
it('assigns per-machine monotonic seqs starting at 1', () => {
- const log = new SshMachineEvents()
+ const log = events
log.append(m1, 'probe', 'one')
log.append(m1, 'download', 'two')
log.append(m2, 'probe', 'other machine')
@@ -18,7 +25,7 @@ describe('sshMachineEvents', () => {
})
it('stamps ts and machineId on every event and carries terminal/reason only when present', () => {
- const log = new SshMachineEvents()
+ const log = events
const first = log.append(m1, 'probe', 'probing')
expect(first.machineId).toBe(m1)
expect(first.ts).toBeTruthy()
@@ -32,7 +39,7 @@ describe('sshMachineEvents', () => {
})
it('drains incrementally by sinceSeq', () => {
- const log = new SshMachineEvents()
+ const log = events
for (let i = 0; i < 5; i++)
log.append(m1, 'install', `line ${i}`)
const first = log.since(m1)
@@ -45,12 +52,13 @@ describe('sshMachineEvents', () => {
})
it('anchors unknown machines at an empty page', () => {
- const log = new SshMachineEvents()
+ const log = events
expect(log.since(MachineId('nope'))).toEqual({ events: [], nextSeq: 1 })
})
it('keeps only the newest events per machine (ring buffer)', () => {
- const log = new SshMachineEvents(3)
+ setEventCapacity(3)
+ const log = events
for (let i = 0; i < 6; i++)
log.append(m1, 'download', `url ${i}`)
const page = log.since(m1)
@@ -61,14 +69,14 @@ describe('sshMachineEvents', () => {
})
it('uses the documented default capacity', () => {
- const log = new SshMachineEvents()
+ const log = events
for (let i = 0; i < EVENT_RING_CAPACITY + 25; i++)
log.append(m1, 'install', `line ${i}`)
expect(log.since(m1).events).toHaveLength(EVENT_RING_CAPACITY)
})
it('forgets a removed machine independently of its neighbors', () => {
- const log = new SshMachineEvents()
+ const log = events
log.append(m1, 'probe', 'one')
log.append(m2, 'probe', 'two')
log.forget(m1)
diff --git a/packages/dsh-tauri-ssh/src/host/service/events.ts b/packages/dsh-tauri-ssh/src/host/service/events.ts
index c4856f07..c00c082a 100644
--- a/packages/dsh-tauri-ssh/src/host/service/events.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/events.ts
@@ -1,45 +1,10 @@
-/**
- * The machine-level log/progress event channel (`/api-ssh` method
- * `machine.events`): a per-machine ring buffer of bootstrap stages, drained
- * by polling (no SSE/WebSocket — the settings page polls `sinceSeq`
- * incrementally). Owned by this plugin's bootstrap plane; the connection
- * lifecycle stages (S3) extend the same stage union on this channel.
- * @module dsh-tauri-ssh/host/service/events
- */
-
import type { MachineId, SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from '../types/index'
+import { defineService } from 'dsh-tauri'
+import { eventBuffers, eventRingCapacity } from '../config/runtime'
-export type { SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal }
-
-/** Events kept per machine before the oldest are dropped. */
-export const EVENT_RING_CAPACITY = 500
-
-/**
- * The per-machine ring buffer. Appends are serialized through a monotonic
- * per-machine counter; reads never mutate. One instance is shared by the
- * manager and the `/api-ssh` route.
- */
-export class SshMachineEvents {
- private readonly buffers = new Map<MachineId, { seq: number, events: SshMachineEvent[] }>()
-
- /**
- * @param capacity - events kept per machine (defaults to
- * {@link EVENT_RING_CAPACITY}).
- */
- constructor(private readonly capacity: number = EVENT_RING_CAPACITY) {}
-
- /**
- * Append one event.
- * @param machineId - the machine the event is about.
- * @param stage - the pipeline stage.
- * @param line - the displayable log line.
- * @param options - the terminal verdict and failure reason, when present.
- * @param options.terminal - the terminal verdict, when the event settles an operation.
- * @param options.reason - the failure reason, on `terminal: 'failed'`.
- * @returns the stored event (with its assigned `seq`).
- */
+export const events = defineService({
append(machineId: MachineId, stage: SshMachineStage, line: string, options: { terminal?: SshMachineTerminal, reason?: string } = {}): SshMachineEvent {
- const buffer = this.ensure(machineId)
+ const buffer = ensureBuffer(machineId)
buffer.seq += 1
const event: SshMachineEvent = {
seq: buffer.seq,
@@ -51,21 +16,14 @@ export class SshMachineEvents {
...options.reason === undefined ? {} : { reason: options.reason },
}
buffer.events.push(event)
- if (buffer.events.length > this.capacity)
- buffer.events.splice(0, buffer.events.length - this.capacity)
+ const capacity = eventRingCapacity()
+ if (buffer.events.length > capacity)
+ buffer.events.splice(0, buffer.events.length - capacity)
return event
- }
+ },
- /**
- * Drain one machine's events after `sinceSeq` (inclusive lower bound is
- * `sinceSeq + 1`; omit it to read from the beginning).
- * @param machineId - the machine to read.
- * @param sinceSeq - the last seq the caller already saw.
- * @returns the drained slice and the next poll cursor; unknown machines
- * report an empty page anchored at `nextSeq: 1` (the first event's seq).
- */
since(machineId: MachineId, sinceSeq?: number): SshMachineEventsPage {
- const buffer = this.buffers.get(machineId)
+ const buffer = eventBuffers.get(machineId)
if (buffer === undefined)
return { events: [], nextSeq: 1 }
const after = sinceSeq === undefined ? 0 : Math.max(0, sinceSeq)
@@ -73,19 +31,18 @@ export class SshMachineEvents {
events: buffer.events.filter(event => event.seq > after),
nextSeq: buffer.seq + 1,
}
- }
+ },
- /** Forget one machine's buffer (profile removed). */
forget(machineId: MachineId): void {
- this.buffers.delete(machineId)
- }
-
- private ensure(machineId: MachineId): { seq: number, events: SshMachineEvent[] } {
- let buffer = this.buffers.get(machineId)
- if (buffer === undefined) {
- buffer = { seq: 0, events: [] }
- this.buffers.set(machineId, buffer)
- }
- return buffer
+ eventBuffers.delete(machineId)
+ },
+})
+
+function ensureBuffer(machineId: MachineId): { seq: number, events: SshMachineEvent[] } {
+ let buffer = eventBuffers.get(machineId)
+ if (buffer === undefined) {
+ buffer = { seq: 0, events: [] }
+ eventBuffers.set(machineId, buffer)
}
+ return buffer
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/host-keys.ts b/packages/dsh-tauri-ssh/src/host/service/host-keys.ts
deleted file mode 100644
index 53517f9d..00000000
--- a/packages/dsh-tauri-ssh/src/host/service/host-keys.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * Trust-on-first-use host-key store for SSH connections. One JSON document
- * under the harness home records the accepted host-key fingerprint per
- * machine profile; a connection whose fingerprint matches is accepted, an
- * unknown one is accepted-and-persisted (TOFU), and a mismatch is rejected so
- * a swapped host cannot impersonate a known machine without an operator
- * resetting the record. Self-contained: the atomic write is a same-directory
- * temp + rename (no harness dependencies).
- * @module dsh-tauri-ssh/host/service/host-keys
- */
-
-import type { Buffer } from 'node:buffer'
-import type { MachineId } from '../types/index'
-import { createHash, randomBytes } from 'node:crypto'
-import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
-import { dirname } from 'pathe'
-
-/** One persisted host-key record. */
-export interface HostKeyRecord {
- /** Machine profile id the record belongs to. */
- machineId: string
- /** Fingerprint the profile's first successful connection saw. */
- fingerprint: string
-}
-
-/** Verdict of one host-key check. */
-export type HostKeyVerdict = 'accepted' | 'unknown' | 'mismatch'
-
-/** Fingerprint a raw SSH host key into the ssh-keygen-style `SHA256:<base64>` form. */
-export function fingerprintHostKey(key: Buffer): string {
- return `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/u, '')}`
-}
-
-/** Atomically replace `filename` with `content` (owner-only permissions, same-dir rename). */
-async function writeFileAtomic(filename: string, content: string): Promise<void> {
- await mkdir(dirname(filename), { recursive: true, mode: 0o700 })
- const temp = `${filename}.${randomBytes(6).toString('hex')}.tmp`
- try {
- await writeFile(temp, content, { mode: 0o600, flag: 'wx' })
- await rename(temp, filename)
- }
- catch (error) {
- await rm(temp, { force: true }).catch(() => undefined)
- throw error
- }
-}
-
-/**
- * File-backed TOFU store. Reads are cached in memory and refreshed on each
- * load; writes are atomic.
- */
-export class KnownHostsStore {
- private records: HostKeyRecord[] = []
-
- /**
- * @param file - absolute path of the known-hosts JSON document.
- */
- constructor(private readonly file: string) {}
-
- /**
- * Load the document (idempotent, cached). A missing or malformed document
- * starts empty — the store must never block a first connection on its own
- * durability.
- */
- async load(): Promise<void> {
- let raw: string
- try {
- raw = await readFile(this.file, 'utf8')
- }
- catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
- this.records = []
- return
- }
- throw error
- }
- try {
- const parsed: unknown = JSON.parse(raw)
- this.records = Array.isArray(parsed) ? parsed as HostKeyRecord[] : []
- }
- catch {
- // A corrupt document resets trust rather than failing every connection.
- this.records = []
- }
- }
-
- /**
- * Check one machine's fingerprint against the store.
- * @param machineId - the machine profile being connected.
- * @param fingerprint - the presented host-key fingerprint.
- * @returns `accepted` on a match, `unknown` on a first sight, `mismatch` on a conflict.
- */
- async verify(machineId: MachineId, fingerprint: string): Promise<HostKeyVerdict> {
- await this.load()
- const record = this.records.find(entry => entry.machineId === machineId)
- if (record === undefined)
- return 'unknown'
- return record.fingerprint === fingerprint ? 'accepted' : 'mismatch'
- }
-
- /**
- * Persist a first-sight fingerprint (the TOFU commit). A concurrent
- * mismatch never overwrites: the caller verifies first.
- * @param machineId - the machine profile being connected.
- * @param fingerprint - the fingerprint to remember.
- */
- async accept(machineId: MachineId, fingerprint: string): Promise<void> {
- await this.load()
- const others = this.records.filter(entry => entry.machineId !== machineId)
- this.records = [...others, { machineId, fingerprint }]
- await writeFileAtomic(this.file, JSON.stringify(this.records, null, 2))
- }
-
- /**
- * Forget one machine's record (the operator-side reset when a host key
- * legitimately changed). Idempotent.
- * @param machineId - the machine whose record to drop.
- */
- async forget(machineId: MachineId): Promise<void> {
- const next = this.records.filter(entry => entry.machineId !== machineId)
- if (next.length === this.records.length)
- return
- this.records = next
- await writeFileAtomic(this.file, JSON.stringify(this.records, null, 2))
- }
-}
diff --git a/packages/dsh-tauri-ssh/src/host/service/host-keys.test.ts b/packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts
similarity index 86%
rename from packages/dsh-tauri-ssh/src/host/service/host-keys.test.ts
rename to packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts
index e76fc073..37f82098 100644
--- a/packages/dsh-tauri-ssh/src/host/service/host-keys.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/known-hosts.test.ts
@@ -4,8 +4,16 @@ import * as fsPromises from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'pathe'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { clearHostRuntime, setKnownHostsPath } from '../config/runtime'
import { MachineId } from '../types/index'
-import { fingerprintHostKey, KnownHostsStore } from './host-keys'
+import { knownHosts } from './known-hosts'
+import { fingerprintHostKey } from './known-hosts.utils'
+
+function open(file: string): typeof knownHosts {
+ clearHostRuntime()
+ setKnownHostsPath(file)
+ return knownHosts
+}
// Wrap the real fs/promises so one test can force an atomic-rename failure;
// every other call passes through to the actual implementation.
@@ -38,17 +46,17 @@ describe('fingerprintHostKey', () => {
describe('knownHostsStore', () => {
it('starts empty on a missing document', async () => {
- const store = new KnownHostsStore(tempFile('missing.json'))
+ const store = open(tempFile('missing.json'))
expect(await store.verify(MachineId('m1'), 'SHA256:abc')).toBe('unknown')
})
it('accepts and persists a first sight, then verifies it', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
const fingerprint = 'SHA256:first'
expect(await store.verify(MachineId('m1'), fingerprint)).toBe('unknown')
await store.accept(MachineId('m1'), fingerprint)
- const reloaded = new KnownHostsStore(file)
+ const reloaded = open(file)
expect(await reloaded.verify(MachineId('m1'), fingerprint)).toBe('accepted')
expect(await reloaded.verify(MachineId('m1'), 'SHA256:other')).toBe('mismatch')
expect(await reloaded.verify(MachineId('m2'), fingerprint)).toBe('unknown')
@@ -56,65 +64,65 @@ describe('knownHostsStore', () => {
it('keeps records of other machines on accept', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
await store.accept(MachineId('m1'), 'SHA256:a')
await store.accept(MachineId('m2'), 'SHA256:b')
- const reloaded = new KnownHostsStore(file)
+ const reloaded = open(file)
expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')
expect(await reloaded.verify(MachineId('m2'), 'SHA256:b')).toBe('accepted')
})
it('forgets one machine idempotently', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
await store.accept(MachineId('m1'), 'SHA256:a')
await store.accept(MachineId('m2'), 'SHA256:b')
await store.forget(MachineId('m1'))
await store.forget(MachineId('m1'))
- const reloaded = new KnownHostsStore(file)
+ const reloaded = open(file)
expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')
expect(await reloaded.verify(MachineId('m2'), 'SHA256:b')).toBe('accepted')
})
it('treats a corrupt document as empty and rewrites it on accept', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
await store.accept(MachineId('m1'), 'SHA256:a')
const raw = JSON.parse(readFileSync(file, 'utf8')) as unknown[]
raw.push({ machineId: 'broken' })
writeFileSync(file, JSON.stringify(raw))
await store.accept(MachineId('m2'), 'SHA256:b')
- const reloaded = new KnownHostsStore(file)
+ const reloaded = open(file)
expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')
})
it('treats a non-array document as empty', async () => {
const file = tempFile('hosts.json')
writeFileSync(file, JSON.stringify({ not: 'an array' }))
- const store = new KnownHostsStore(file)
+ const store = open(file)
expect(await store.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')
})
it('rejects invalid JSON as empty', async () => {
const file = tempFile('hosts.json')
writeFileSync(file, 'not json {')
- const store = new KnownHostsStore(file)
+ const store = open(file)
expect(await store.verify(MachineId('m1'), 'SHA256:a')).toBe('unknown')
await store.accept(MachineId('m1'), 'SHA256:a')
- const reloaded = new KnownHostsStore(file)
+ const reloaded = open(file)
expect(await reloaded.verify(MachineId('m1'), 'SHA256:a')).toBe('accepted')
})
it('rethrows non-ENOENT read failures', async () => {
const path = tempFile('hosts.json')
mkdirSync(path)
- const store = new KnownHostsStore(path)
+ const store = open(path)
await expect(store.verify(MachineId('m1'), 'SHA256:a')).rejects.toThrow()
})
it('cleans up the temp document and rethrows when the atomic rename fails', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
vi.mocked(fsPromises.rename).mockRejectedValueOnce(new Error('rename failed'))
await expect(store.accept(MachineId('m1'), 'SHA256:a')).rejects.toThrow('rename failed')
expect(readdirSync(dirname(file)).filter(entry => entry.endsWith('.tmp'))).toEqual([])
@@ -122,7 +130,7 @@ describe('knownHostsStore', () => {
it('swallows a failing temp cleanup and rethrows the original failure', async () => {
const file = tempFile('hosts.json')
- const store = new KnownHostsStore(file)
+ const store = open(file)
vi.mocked(fsPromises.rename).mockRejectedValueOnce(new Error('rename failed'))
vi.mocked(fsPromises.rm).mockRejectedValueOnce(new Error('rm failed'))
await expect(store.accept(MachineId('m1'), 'SHA256:a')).rejects.toThrow('rename failed')
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.ts b/packages/dsh-tauri-ssh/src/host/service/known-hosts.ts
new file mode 100644
index 00000000..d128cc93
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/known-hosts.ts
@@ -0,0 +1,29 @@
+import type { MachineId } from '../types/index'
+import type { HostKeyVerdict } from './known-hosts.types'
+import { defineService } from 'dsh-tauri'
+import { knownHostsFilePath } from '../config/runtime'
+import { readHostKeyRecords, writeHostKeyRecords } from './known-hosts.utils'
+
+export const knownHosts = defineService({
+ async verify(machineId: MachineId, fingerprint: string): Promise<HostKeyVerdict> {
+ const records = await readHostKeyRecords(knownHostsFilePath())
+ const record = records.find(entry => entry.machineId === machineId)
+ if (record === undefined)
+ return 'unknown'
+ return record.fingerprint === fingerprint ? 'accepted' : 'mismatch'
+ },
+
+ async accept(machineId: MachineId, fingerprint: string): Promise<void> {
+ const records = await readHostKeyRecords(knownHostsFilePath())
+ const others = records.filter(entry => entry.machineId !== machineId)
+ await writeHostKeyRecords(knownHostsFilePath(), [...others, { machineId, fingerprint }])
+ },
+
+ async forget(machineId: MachineId): Promise<void> {
+ const records = await readHostKeyRecords(knownHostsFilePath())
+ const next = records.filter(entry => entry.machineId !== machineId)
+ if (next.length === records.length)
+ return
+ await writeHostKeyRecords(knownHostsFilePath(), next)
+ },
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.types.ts b/packages/dsh-tauri-ssh/src/host/service/known-hosts.types.ts
new file mode 100644
index 00000000..26762e5a
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/known-hosts.types.ts
@@ -0,0 +1,6 @@
+export interface HostKeyRecord {
+ machineId: string
+ fingerprint: string
+}
+
+export type HostKeyVerdict = 'accepted' | 'unknown' | 'mismatch'
diff --git a/packages/dsh-tauri-ssh/src/host/service/known-hosts.utils.ts b/packages/dsh-tauri-ssh/src/host/service/known-hosts.utils.ts
new file mode 100644
index 00000000..119c0936
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/known-hosts.utils.ts
@@ -0,0 +1,41 @@
+import type { Buffer } from 'node:buffer'
+import type { HostKeyRecord } from './known-hosts.types'
+import { createHash, randomBytes } from 'node:crypto'
+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
+import { dirname } from 'pathe'
+
+export function fingerprintHostKey(key: Buffer): string {
+ return `SHA256:${createHash('sha256').update(key).digest('base64').replace(/=+$/u, '')}`
+}
+
+export async function readHostKeyRecords(file: string): Promise<HostKeyRecord[]> {
+ let raw: string
+ try {
+ raw = await readFile(file, 'utf8')
+ }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
+ return []
+ throw error
+ }
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ return Array.isArray(parsed) ? parsed as HostKeyRecord[] : []
+ }
+ catch {
+ return []
+ }
+}
+
+export async function writeHostKeyRecords(file: string, records: HostKeyRecord[]): Promise<void> {
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 })
+ const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`
+ try {
+ await writeFile(temp, JSON.stringify(records, null, 2), { mode: 0o600, flag: 'wx' })
+ await rename(temp, file)
+ }
+ catch (error) {
+ await rm(temp, { force: true }).catch(() => undefined)
+ throw error
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
similarity index 85%
rename from packages/dsh-tauri-ssh/src/host/service/manager.test.ts
rename to packages/dsh-tauri-ssh/src/host/service/machine.test.ts
index 14b7cc56..4a2251df 100644
--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
@@ -1,15 +1,17 @@
-import type { MachineProfile, SshMachineEvent } from '../types/index'
-import type { RemoteInstallPlan } from './bootstrap'
-import type { SshExecOptions, SshExecResult, SshSession, SshTransport, SshTunnelHandle } from './transport'
+import type { AddressInfo } from 'node:net'
+import type { MachineProfile, SshExecOptions, SshExecResult, SshMachineEvent, SshSession, SshTunnelHandle } from '../types/index'
+import type { SshTransport, SshTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
-import { mkdtempSync, rmSync } from 'node:fs'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { clearHostRuntime, machineStates, machineTable, setHostConfig, setKnownHostsPath, setMachineDeps } from '../config/runtime'
import { MachineId, SshError } from '../types/index'
-import { SshMachineEvents } from './events'
-import { KnownHostsStore } from './host-keys'
-import { SshManager } from './manager'
+import { EMPTY_ALLOWLIST } from '../utils/allowlist'
+import { events } from './events'
+import { machine } from './machine'
const profile: MachineProfile = {
id: MachineId('m1'),
@@ -33,6 +35,7 @@ const config = {
healthCheckTimeoutMs: 1000,
healthPollIntervalMs: 5,
healthPollAttempts: 3,
+ installRef: 'dsh-0.1.2-rc.1-33729514615',
installTimeoutMs: 60000,
keepaliveIntervalMs: 10000,
keepaliveCountMax: 3,
@@ -41,39 +44,26 @@ const config = {
reconnectMaxAttempts: 2,
}
+function githubJson(body: unknown): { ok: boolean, status: number, json: () => Promise<unknown> } {
+ return { ok: true, status: 200, json: async () => body }
+}
+
+function stubGithub(): void {
+ vi.stubGlobal('fetch', (url: string) => {
+ if (url.includes('/releases?per_page='))
+ return Promise.resolve(githubJson([{ tag_name: config.installRef, draft: false, prerelease: true }]))
+ if (url.includes('/releases/tags/'))
+ return Promise.resolve(githubJson({ assets: [{ name: 'deepseek-harness-pkg-linux.zip', browser_download_url: 'https://example.test/deepseek-harness-pkg-linux.zip', digest: 'sha256:0000' }] }))
+ return Promise.reject(new Error(`unexpected fetch ${url}`))
+ })
+}
+
/** A boot page whose manifest the bundle probe confirms. */
const BOOT_HTML = '<html><body><script>globalThis["__DSH_BOOT__"] = {"entries":[{"url":"/plugins/@deepseek-ai/dsh-client-ui-layout/client.js"}]};</script></body></html>'
-/** The layout entry the v2 install resolves (see {@link fakePlan}): the remote shell expands $HOME (root user in the fake). */
+/** The layout entry the pinned dsh release resolves: the remote shell expands $HOME (root user in the fake). */
const ENTRY = '/root/.dsh-desktop/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js'
-/** A literal linux/x64 plan (no network): the recommended pin with digest. */
-function fakePlan(): RemoteInstallPlan {
- return {
- os: 'linux',
- arch: 'x64',
- matrix: { os: 'linux', arch: 'x64', dshKind: 'pkg-zip', nodeFilename: 'node-v22.22.0-linux-x64.tar.gz', dshZipName: 'deepseek-harness-pkg-linux.zip' },
- repo: 'dsh-tauri-desk/deepseek-harness-pkg',
- dshEntry: 'node_modules/@deepseek-ai/dsh/lib/bin.js',
- dshVersion: '0.1.2-rc.1',
- node: {
- urls: ['https://nodejs.org/dist/v22.22.0/node-v22.22.0-linux-x64.tar.gz'],
- shasumUrls: ['https://nodejs.org/dist/v22.22.0/SHASUMS256.txt'],
- filename: 'node-v22.22.0-linux-x64.tar.gz',
- version: 'v22.22.0',
- },
- dsh: {
- kind: 'pkg-zip',
- urls: ['https://github.com/dsh-tauri-desk/deepseek-harness-pkg/releases/download/dsh-0.1.2-rc.1-33729514615/deepseek-harness-pkg-linux.zip'],
- digest: 'sha256:6b7ecfeb',
- zipName: 'deepseek-harness-pkg-linux.zip',
- tag: 'dsh-0.1.2-rc.1-33729514615',
- },
- pnpm: { urls: ['https://registry.npmjs.org/pnpm/-/pnpm-11.7.0.tgz'], sha256: 'deaf'.repeat(16), version: '11.7.0' },
- notes: [],
- }
-}
-
class FakeSession implements SshSession {
commands: string[] = []
options: SshExecOptions[] = []
@@ -102,6 +92,10 @@ class FakeSession implements SshSession {
unameResult = 'Linux 6.8.0-45-generic x86_64\n'
/** The check-script answer: one missing component per line (default: none). */
missingResult = ''
+ /** When set, the plugin-sync apply command answers a non-zero code with this stderr. */
+ pluginSyncError: Error | undefined
+ /** The local port the fake tunnel reports. */
+ tunnelPort = 49152
/** Whether the launch answered REMOTE_NOT_INSTALLED instead of starting. */
startNotInstalled = false
/** The web-log token grep answer (default: no token → bare tunnel URL). */
@@ -126,6 +120,13 @@ class FakeSession implements SshSession {
return { code: 1, stdout: '::dsh install far', stderr: this.installError.message }
return { code: 0, stdout: '::dsh install 远端初始化完成', stderr: '' }
}
+ if (command.includes('.dsh-desktop/plugins')) {
+ if (this.pluginSyncError !== undefined)
+ return { code: 1, stdout: '', stderr: this.pluginSyncError.message }
+ return command.includes('PLUGINS_SYNCED')
+ ? { code: 0, stdout: 'PLUGINS_SYNCED\n', stderr: '' }
+ : { code: 0, stdout: '', stderr: '' }
+ }
if (command.includes('test -f ')) {
// The real command prints the $HOME-expanded absolute entry path.
return { code: 0, stdout: `${ENTRY}\n`, stderr: '' }
@@ -186,7 +187,7 @@ class FakeSession implements SshSession {
if (this.tunnelGate !== undefined)
await this.tunnelGate
this.tunnel = {
- localPort: 49152,
+ localPort: this.tunnelPort,
close: async () => {
this.tunnelCloseCalls += 1
this.tunnel = undefined
@@ -226,6 +227,8 @@ class FakeTransport implements SshTransport {
async connect(
profile: MachineProfile,
hostKeyVerifier: (label: string, key: Buffer) => boolean | Promise<boolean>,
+ _options: SshTransportOptions,
+ _signal?: AbortSignal,
): Promise<SshSession> {
this.connectCalls += 1
this.profiles.push(profile)
@@ -243,23 +246,57 @@ class FakeTransport implements SshTransport {
const roots: string[] = []
-function tempKnownHosts(): KnownHostsStore {
+const harnessHomeBefore = process.env.DSH_HOME
+
+function tempRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-ssh-manager-'))
roots.push(root)
- return new KnownHostsStore(join(root, 'known-hosts.json'))
+ return root
}
-afterEach(() => {
+function harnessHomeWith(credentials: { apiKey?: string, baseUrl?: string }): string {
+ const root = tempRoot()
+ const lines = [
+ ...credentials.apiKey === undefined ? [] : [`DEEPSEEK_API_KEY=${credentials.apiKey}`],
+ ...credentials.baseUrl === undefined ? [] : [`DEEPSEEK_BASE_URL=${credentials.baseUrl}`],
+ ]
+ writeFileSync(join(root, '.env'), lines.length === 0 ? '' : `${lines.join('\n')}\n`)
+ return root
+}
+
+function quiet(): boolean {
+ return [...machineStates.values()].every(state => state.connecting === undefined && state.installing === undefined && state.reconnect === undefined)
+}
+
+async function settleRuntime(): Promise<void> {
+ let seen = -1
+ let calm = 0
+ for (let attempt = 0; attempt < 200 && calm < 4; attempt += 1) {
+ const terminals = terminalsOf(events).length
+ calm = quiet() && terminals === seen ? calm + 1 : 0
+ seen = terminals
+ await new Promise(resolve => setTimeout(resolve, 5))
+ }
+}
+
+beforeEach(() => {
+ stubGithub()
+})
+
+afterEach(async () => {
+ await machine.dispose()
+ await settleRuntime()
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
+ if (harnessHomeBefore === undefined)
+ delete process.env.DSH_HOME
+ else
+ process.env.DSH_HOME = harnessHomeBefore
+ vi.unstubAllGlobals()
+ clearHostRuntime()
})
-/**
- * The bootstrap flow's own commands, without the connect-time prelude (the
- * idempotent pnpm-shim write). Flow assertions stay about the bootstrap, and
- * a new prelude step never renumbers them.
- */
-/** The connect-time prelude markers (pnpm shim, build-allowlist carry). */
-const PRELUDE_MARKERS = ['chmod +x "$B/pnpm"', 'pnpm-workspace.yaml']
+/** The connect-time prelude markers (plugin sync, pnpm shim, build-allowlist carry). */
+const PRELUDE_MARKERS = ['.dsh-desktop/plugins', 'chmod +x "$B/pnpm"', 'pnpm-workspace.yaml']
function bootstrapFlowCommands(session: FakeSession): string[] {
return session.commands.filter(command => !PRELUDE_MARKERS.some(marker => command.includes(marker)))
@@ -276,7 +313,7 @@ async function until(predicate: () => boolean, label: string): Promise<void> {
}
/** Wait until one machine settles into its terminal state after a failure. */
-async function untilSettled(manager: SshManager, machineId: MachineId = MachineId('m1')): Promise<void> {
+async function untilSettled(manager: typeof machine, machineId: MachineId = MachineId('m1')): Promise<void> {
await until(() => {
const state = manager.status(machineId).state
return state === 'given-up' || state === 'connected' || state === 'disconnected'
@@ -286,41 +323,34 @@ async function untilSettled(manager: SshManager, machineId: MachineId = MachineI
function boot(overrides: Partial<{
sessionFactory: () => FakeSession
rejectKeys: boolean
- readEnvCredentials: () => { apiKey?: string, baseUrl?: string }
+ envCredentials: () => { apiKey?: string, baseUrl?: string }
config: typeof config
- planInstall: () => Promise<RemoteInstallPlan>
- mintCookie: (authenticatedUrl: string) => Promise<string | undefined>
- syncPlugins: (session: import('./transport').SshSession, profileName: string, remotePort: number, hooks: { onEvent?: (stage: import('../types/index').SshMachineStage, line: string) => void }) => Promise<boolean>
- localAllowlist: () => import('./allowlist').WorkspaceAllowlist
+ localAllowlist: () => import('../utils/allowlist').WorkspaceAllowlist
}> = {}) {
const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))
transport.rejectKeys = overrides.rejectKeys ?? false
const emits: Array<{ id: MachineId, state: string, progress?: { phase: string } }> = []
- const events = new SshMachineEvents()
- const plan = fakePlan()
- const manager = new SshManager({
+ clearHostRuntime()
+ if (overrides.envCredentials !== undefined)
+ process.env.DSH_HOME = harnessHomeWith(overrides.envCredentials())
+ setHostConfig({ ...(overrides.config ?? config), sshDir: tempRoot() })
+ setKnownHostsPath(join(tempRoot(), 'known-hosts.json'))
+ setMachineDeps({
transport,
- knownHosts: tempKnownHosts(),
- config: overrides.config ?? config,
- events,
- planInstall: overrides.planInstall ?? (() => Promise.resolve(plan)),
- // 默认离线 mint:不走真实 HTTP;个别用例经 overrides 覆盖
- mintCookie: overrides.mintCookie ?? (() => Promise.resolve(undefined)),
- // 默认离线插件同步:不打本地 tar;个别用例经 overrides 覆盖
- syncPlugins: overrides.syncPlugins ?? (() => Promise.resolve(false)),
- ...overrides.localAllowlist === undefined ? {} : { localAllowlist: overrides.localAllowlist },
- ...overrides.readEnvCredentials === undefined ? {} : { readEnvCredentials: overrides.readEnvCredentials },
+ localAllowlist: overrides.localAllowlist ?? (() => EMPTY_ALLOWLIST),
emitStatus: (id, status) => {
emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })
},
})
- manager.refreshProfiles(new Map([[profile.id, profile], [secondProfile.id, secondProfile]]))
- return { manager, transport, emits, events }
+ machineTable.machines.set(profile.id, profile)
+ machineTable.machines.set(secondProfile.id, secondProfile)
+ machine.refreshProfiles(new Map(machineTable.machines))
+ return { manager: machine, transport, emits, events }
}
/** The terminal (settling) events one machine's channel recorded. */
-function terminalsOf(events: SshMachineEvents): SshMachineEvent[] {
- return events.since(MachineId('m1')).events.filter(event => event.terminal !== undefined)
+function terminalsOf(log: typeof events): SshMachineEvent[] {
+ return log.since(MachineId('m1')).events.filter(event => event.terminal !== undefined)
}
describe('sshManager', () => {
@@ -458,13 +488,13 @@ describe('sshManager', () => {
releaseStart = resolve
})
const session = new FakeSession(index => index !== 0)
- session.execGate = command => command.includes('dsh-remote.pid') ? startGate : undefined
+ session.execGate = command => command.includes('--no-open') ? startGate : undefined
const { manager, emits } = boot({ sessionFactory: () => session })
const pending = manager.connect(MachineId('m1'))
// Wait until the start command is in flight, then supersede the attempt.
await new Promise<void>((resolve) => {
const timer = setInterval(() => {
- if (session.commands.some(command => command.includes('dsh-remote.pid'))) {
+ if (session.commands.some(command => command.includes('--no-open'))) {
clearInterval(timer)
resolve()
}
@@ -785,14 +815,15 @@ describe('sshManager', () => {
it('exposes the startCommand override in profile views', () => {
const { manager } = boot()
const overridden: MachineProfile = { ...profile, startCommand: 'dsh web --port 4000' }
- manager.refreshProfiles(new Map([[MachineId('m1'), overridden]]))
+ machineTable.machines.set(MachineId('m1'), overridden)
+ manager.refreshProfiles(new Map(machineTable.machines))
expect(manager.profileViews()[0]?.startCommand).toBe('dsh web --port 4000')
})
it('rejects a mismatched host key (TOFU conflict)', async () => {
const { manager, transport } = boot()
await manager.connect(MachineId('m1'))
- transport.connect = async function (this: FakeTransport, p: MachineProfile, verifier: (label: string, key: Buffer) => boolean | Promise<boolean>): Promise<SshSession> {
+ transport.connect = async function (this: FakeTransport, p: MachineProfile, verifier: (label: string, key: Buffer) => boolean | Promise<boolean>, _options: SshTransportOptions, _signal?: AbortSignal): Promise<SshSession> {
const accepted = await verifier(String(p.id), Buffer.from('other-key'))
if (!accepted)
throw new Error('Host key verification failed')
@@ -867,7 +898,7 @@ describe('sshManager install', () => {
}
const { manager, transport } = boot({
sessionFactory: factory,
- readEnvCredentials: () => ({ apiKey: 'sk-test', baseUrl: 'https://api.example.com' }),
+ envCredentials: () => ({ apiKey: 'sk-test', baseUrl: 'https://api.example.com' }),
})
const result = await manager.install(MachineId('m1'))
expect(result).toEqual({
@@ -910,7 +941,7 @@ describe('sshManager install', () => {
it('dedupes concurrent installs onto one attempt', async () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
- const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, transport } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const [a, b] = await Promise.all([manager.install(MachineId('m1')), manager.install(MachineId('m1'))])
expect(a).toEqual(b)
// One install exec (the auto-connect reuses the same session instance,
@@ -923,7 +954,7 @@ describe('sshManager install', () => {
it('skips the credentials copy when the local env has no key', async () => {
const session = new FakeSession(() => false)
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({}) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({}) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
expect(session.commands.some(command => command.includes('DEEPSEEK_API_KEY'))).toBe(false)
@@ -932,17 +963,21 @@ describe('sshManager install', () => {
it('keeps an existing remote key untouched', async () => {
const session = new FakeSession(() => false)
session.credentialsAnswer = 'existing'
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
})
it('reports a credentials write failure without failing the install', async () => {
const session = new FakeSession(() => false)
- session.exec = (command, _options) => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')
- ? Promise.resolve({ code: 1, stdout: '', stderr: 'disk full' })
- : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ session.exec = (command, _options) => {
+ if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\''))
+ return Promise.resolve({ code: 1, stdout: '', stderr: 'disk full' })
+ if (command === 'uname -srm')
+ return Promise.resolve({ code: 0, stdout: session.unameResult, stderr: '' })
+ return Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
+ }
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
expect(result.credentialsError).toContain('disk full')
@@ -956,7 +991,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
- const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({}) })
+ const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({}) })
const pending = manager.install(MachineId('m1'))
await until(() => session.commands.some(command => command.includes('trap cleanup EXIT')), 'install exec')
const installIndex = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))
@@ -987,7 +1022,7 @@ describe('sshManager install', () => {
session.exec = (command, options) => command.includes('trap cleanup EXIT')
? Promise.resolve({ code: 1, stdout: '', stderr: 'pnpm: not found' })
: original(command, options)
- const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
// Capture the rejection: toMatchObject silently ignores message regexes,
// so the message is asserted on the caught error directly.
const failure = await manager.install(MachineId('m1')).then(
@@ -1023,7 +1058,7 @@ describe('sshManager install', () => {
}
return original(command, options)
}
- const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
error => error as SshError,
@@ -1042,7 +1077,7 @@ describe('sshManager install', () => {
// A tap-less transport: markers only in the collected stdout.
? Promise.resolve({ code: 10, stdout: '::dsh failed 所有下载源均失败: node.tar.gz', stderr: '' })
: original(command, undefined)
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
error => error as SshError,
@@ -1069,12 +1104,10 @@ describe('sshManager install', () => {
expect(terminals[0]?.reason).toContain('cannot probe remote platform')
})
- it('settles the install stream when the planner rejects the platform', async () => {
+ it('settles the install stream when the platform probe reports an unsupported target', async () => {
const session = new FakeSession(() => false)
- const { manager, events } = boot({
- sessionFactory: () => session,
- planInstall: () => Promise.reject(new Error('REMOTE_PLATFORM_UNSUPPORTED: mingw/x64 outside the asset matrix')),
- })
+ session.unameResult = 'MINGW64_NT-10.0-22631 3.4.10.x86_64 x86_64\n'
+ const { manager, events } = boot({ sessionFactory: () => session })
await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })
const terminals = terminalsOf(events)
expect(terminals).toHaveLength(1)
@@ -1088,7 +1121,7 @@ describe('sshManager install', () => {
session.exec = (command, options) => command.includes('trap cleanup EXIT')
? Promise.reject(new Error('install exec timed out after 60000ms'))
: original(command, options)
- const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const failure = await manager.install(MachineId('m1')).then(
() => { throw new Error('expected a rejection') },
error => error as SshError,
@@ -1112,27 +1145,22 @@ describe('sshManager install', () => {
expect(status.lastError).toBe('connect failed after 3 attempt(s): auth failed')
})
- it('runs without an install timeout when the config omits it', async () => {
+ it('runs the install script with the configured timeout', async () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
- const { manager } = boot({
- sessionFactory: () => session,
- config: { ...config, installTimeoutMs: undefined as unknown as number },
- readEnvCredentials: () => ({ apiKey: 'sk-test' }),
- })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
await manager.install(MachineId('m1'))
const installIndex = session.commands.findIndex(command => command.includes('trap cleanup EXIT'))
- expect(session.options[installIndex]!.timeoutMs).toBeUndefined()
+ expect(session.options[installIndex]!.timeoutMs).toBe(60000)
expect(typeof session.options[installIndex]!.onData).toBe('function')
})
- it('falls back to the local harness .env when no credentials reader is injected', async () => {
+ it('completes the install when the harness .env holds no credentials', async () => {
const session = new FakeSession(() => false)
- const { manager } = boot({ sessionFactory: () => session })
- // No readEnvCredentials injection: the manager reads the host's own
- // $DSH_HOME/.env — whatever it holds, the install still completes.
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({}) })
const result = await manager.install(MachineId('m1'))
expect(result.dshPath).toBe(ENTRY)
+ expect(result.credentialsCopied).toBe(false)
expect(result.credentialsError).toBeUndefined()
})
@@ -1168,12 +1196,16 @@ describe('sshManager install', () => {
it('reports a non-Error credentials failure without failing the install', async () => {
const session = new FakeSession(() => false)
- session.exec = (command, _options) => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')
- // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection
- // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeExecFailure's message tail
- ? Promise.reject('disk full')
- : Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ session.exec = (command, _options) => {
+ if (command.includes('grep -q \'^DEEPSEEK_API_KEY=\''))
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors -- hostile rejection
+ // eslint-disable-next-line prefer-promise-reject-errors -- deliberately non-Error: covers describeExecFailure's message tail
+ return Promise.reject('disk full')
+ if (command === 'uname -srm')
+ return Promise.resolve({ code: 0, stdout: session.unameResult, stderr: '' })
+ return Promise.resolve({ code: 0, stdout: command.includes('test -f ') ? `${ENTRY}\n` : 'installed', stderr: '' })
+ }
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(false)
expect(result.credentialsError).toBe('disk full')
@@ -1187,7 +1219,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))
session.missingResult = 'node\n'
session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
- const { manager, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const pending = manager.install(MachineId('m1'))
await new Promise<void>((resolve) => {
const timer = setInterval(() => {
@@ -1209,12 +1241,15 @@ describe('sshManager install', () => {
expect(manager.status(MachineId('m1')).progress).toBeUndefined()
// The script's own settling event fired inside the shared executor
// before the supersede was noticed; the catch must not add a second.
- expect(terminalsOf(events)).toHaveLength(1)
+ const terminals = terminalsOf(events)
+ expect(terminals).toHaveLength(1)
})
it('fails loud when the install finished but the entry is not present', async () => {
const session = new FakeSession(() => false)
session.exec = (command, _options) => {
+ if (command === 'uname -srm')
+ return Promise.resolve({ code: 0, stdout: session.unameResult, stderr: '' })
if (command.includes('echo node'))
return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })
if (command.includes('trap cleanup EXIT'))
@@ -1249,7 +1284,7 @@ describe('sshManager install', () => {
}
const { manager, transport } = boot({
sessionFactory: factory,
- readEnvCredentials: () => ({ apiKey: 'sk-test' }),
+ envCredentials: () => ({ apiKey: 'sk-test' }),
})
await expect(manager.connect(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-bootstrap-failed' })
expect(manager.status(MachineId('m1')).dshMissing).toBe(true)
@@ -1269,7 +1304,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
- const { manager, transport, events } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, transport, events } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const pending = manager.install(MachineId('m1'))
const installIndex = await new Promise<number>((resolve) => {
const timer = setInterval(() => {
@@ -1294,6 +1329,27 @@ describe('sshManager install', () => {
expect(terminalsOf(events)).toHaveLength(0)
})
+ it('does not dial into the next runtime when a teardown lands mid-install', async () => {
+ let releaseInstall: (() => void) | undefined
+ const installGate = new Promise<void>((resolve) => {
+ releaseInstall = resolve
+ })
+ const session = new FakeSession(() => false)
+ session.missingResult = 'node\n'
+ session.execGate = command => command.includes('trap cleanup EXIT') ? installGate : undefined
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
+ const pending = manager.install(MachineId('m1'))
+ await until(() => session.commands.some(command => command.includes('trap cleanup EXIT')), 'install script')
+ // 下一个 runtime 已装配:在途 attempt 的续跑必须失效,否则它会读到新 runtime 的
+ // transport,把连接计到别人的账上(host 单例 + deps 延迟解析下的串场)。
+ const next = boot({ sessionFactory: () => new FakeSession(() => true) })
+ releaseInstall!()
+ await pending.catch(() => undefined)
+ // 无修复时这里是 1:在途 attempt 的续跑借用下一个 runtime 的 transport 拨号。
+ expect(next.transport.connectCalls).toBe(0)
+ await expect(pending).rejects.toMatchObject({ code: 'machine-install-failed' })
+ })
+
it('returns the install result without connecting once a disconnect superseded the finish', async () => {
let releaseCopy: (() => void) | undefined
const copyGate = new Promise<void>((resolve) => {
@@ -1301,7 +1357,7 @@ describe('sshManager install', () => {
})
const session = new FakeSession(() => false)
session.execGate = command => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'') ? copyGate : undefined
- const { manager, transport } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, transport } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const pending = manager.install(MachineId('m1'))
await until(() => session.commands.some(command => command.includes('grep -q \'^DEEPSEEK_API_KEY=\'')), 'credentials copy')
await manager.disconnect(MachineId('m1'))
@@ -1316,7 +1372,7 @@ describe('sshManager install', () => {
it('swallows a session close failure at the end of a successful install', async () => {
const session = new FakeSession(() => false)
session.closeError = new Error('close refused')
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(true)
expect(result.credentialsError).toBeUndefined()
@@ -1326,7 +1382,7 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false, undefined, undefined, new Error('pnpm: not found'))
session.missingResult = 'node\n'
session.closeError = new Error('close refused')
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })
expect(session.closeCalls).toBe(1)
})
@@ -1340,7 +1396,7 @@ describe('sshManager install', () => {
? new FakeSession(() => false)
: new FakeSession(() => true, new Error('auth failed'))
}
- const { manager, transport } = boot({ sessionFactory: factory, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager, transport } = boot({ sessionFactory: factory, envCredentials: () => ({ apiKey: 'sk-test' }) })
const result = await manager.install(MachineId('m1'))
expect(result.credentialsCopied).toBe(true)
// The auto-connect fails auth and its reconnect retries also fail: the
@@ -1355,6 +1411,8 @@ describe('sshManager install', () => {
const session = new FakeSession(() => false)
session.missingResult = 'node\n'
session.exec = (command, _options) => {
+ if (command === 'uname -srm')
+ return Promise.resolve({ code: 0, stdout: session.unameResult, stderr: '' })
if (command.includes('echo node'))
return Promise.resolve({ code: 0, stdout: 'node\n', stderr: '' })
if (command.includes('trap cleanup EXIT'))
@@ -1363,7 +1421,7 @@ describe('sshManager install', () => {
return Promise.reject('pnpm blew up')
return Promise.resolve({ code: 0, stdout: '', stderr: '' })
}
- const { manager } = boot({ sessionFactory: () => session, readEnvCredentials: () => ({ apiKey: 'sk-test' }) })
+ const { manager } = boot({ sessionFactory: () => session, envCredentials: () => ({ apiKey: 'sk-test' }) })
await expect(manager.install(MachineId('m1'))).rejects.toMatchObject({ code: 'machine-install-failed' })
expect(manager.status(MachineId('m1')).lastError).toBe('pnpm blew up')
})
@@ -1502,21 +1560,22 @@ describe('sshManager reconnect', () => {
})
it('syncs bundled plugins before ensuring the instance (failure degrades, never blocks)', async () => {
- const calls: string[] = []
- const { manager } = boot({
- syncPlugins: () => {
- calls.push('sync')
- return Promise.resolve(true)
- },
- })
+ const session = new FakeSession(() => true)
+ const { manager, events } = boot({ sessionFactory: () => session })
const link = await manager.connect(MachineId('m1'))
expect(link.tunnelBaseUrl).toContain('http://127.0.0.1:')
- expect(calls).toEqual(['sync'])
+ expect(session.commands.some(command => command.startsWith('cat "$HOME/.dsh-desktop/plugins'))).toBe(true)
+ expect(session.commands.some(command => command.includes('PLUGINS_SYNCED'))).toBe(true)
+ expect(events.since(MachineId('m1')).events.map(event => event.line).some(line => line.includes('捆绑插件已同步'))).toBe(true)
})
it('a plugin-sync failure degrades to the stock remote UI without failing the connect', async () => {
const { manager, events } = boot({
- syncPlugins: () => Promise.reject(new Error('upload broke')),
+ sessionFactory: () => {
+ const session = new FakeSession(() => true)
+ session.pluginSyncError = new Error('upload broke')
+ return session
+ },
})
const link = await manager.connect(MachineId('m1'))
expect(link.tunnelBaseUrl).toContain('http://127.0.0.1:')
@@ -1525,23 +1584,36 @@ describe('sshManager reconnect', () => {
})
it('stamps the tunnel with the minted session cookie once the launch token resolves', async () => {
- let mintedUrl = ''
- const { manager, transport } = boot({
- sessionFactory: () => {
- const session = new FakeSession(() => true)
- session.webTokenResult = 'tok-abc-123\n'
- return session
- },
- mintCookie: (url) => {
- mintedUrl = url
- return Promise.resolve('dsh-auth-x=v1.signed')
- },
+ const requests: string[] = []
+ const server = createServer((request, response) => {
+ requests.push(request.url ?? '')
+ response.setHeader('set-cookie', ['dsh-auth-x=v1.signed; Path=/; HttpOnly'])
+ response.end('ok')
})
- const link = await manager.connect(MachineId('m1'))
- // mint 走隧道自身的带 token URL;注入槽随后携带 Cookie(iframe 免登录)
- expect(mintedUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
- expect(transport.sessions[0]?.tunnelInjection?.cookie).toBe('dsh-auth-x=v1.signed')
- expect(link.tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
+ await new Promise<void>((resolve) => {
+ server.listen(0, '127.0.0.1', resolve)
+ })
+ try {
+ const port = (server.address() as AddressInfo).port
+ const { manager, transport } = boot({
+ sessionFactory: () => {
+ const session = new FakeSession(() => true)
+ session.webTokenResult = 'tok-abc-123\n'
+ session.tunnelPort = port
+ return session
+ },
+ })
+ const link = await manager.connect(MachineId('m1'))
+ // mint 走隧道自身的带 token URL;注入槽随后携带 Cookie(iframe 免登录)
+ expect(requests).toEqual(['/?token=tok-abc-123'])
+ expect(transport.sessions[0]?.tunnelInjection?.cookie).toBe('dsh-auth-x=v1.signed')
+ expect(link.tunnelBaseUrl).toBe(`http://127.0.0.1:${port}/?token=tok-abc-123`)
+ }
+ finally {
+ await new Promise<void>((resolve) => {
+ server.close(() => resolve())
+ })
+ }
})
it('exits given-up on a fresh connect', async () => {
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.ts b/packages/dsh-tauri-ssh/src/host/service/machine.ts
new file mode 100644
index 00000000..aca4cb34
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.ts
@@ -0,0 +1,777 @@
+import type { Buffer } from 'node:buffer'
+import type { MachineProfile, MachineSaveRow, MachineSecretWrite, MachineView, SshInstallResult, SshLink, SshMachineStatus, SshProgress, SshSession, SshTestResult, TunnelHeaderInjection } from '../types/index'
+import type { WorkspaceAllowlist } from '../utils/allowlist'
+import type { SshHostBlock } from '../utils/ssh-config'
+import type { BootstrapHooks } from './bootstrap.types'
+import type { MachineState, ReconnectState } from './machine.types'
+import { defineService } from 'dsh-tauri'
+import { join } from 'pathe'
+import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
+import { messageOf } from '../../shared/error'
+import { REMOTE_ROOT } from '../config/constants'
+import { harnessHome, homeDirPath, hostConfig, machineProfiles, machineRuntimeDeps, machineStates, machineTable, sshDirPath } from '../config/runtime'
+import { MachineId, SshError } from '../types/index'
+import { carryWorkspaceAllowlist } from '../utils/allowlist'
+import { syncBundledPlugins } from '../utils/plugins-sync'
+import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, resolveSshAuth } from '../utils/ssh-config'
+import { bootstrap } from './bootstrap'
+import { checkMissingCommand, credentialsCopyCommand, describeExecFailure, ensurePnpmCommand, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, remoteWebTokenCommand, safeProfileName, skippedVerificationSummary } from './bootstrap.utils'
+import { events } from './events'
+import { knownHosts } from './known-hosts'
+import { fingerprintHostKey } from './known-hosts.utils'
+import { state } from './state'
+import { mintTunnelCookie } from './transport.utils'
+
+export const machine = defineService({
+ enabled(): boolean {
+ return machineTable.enabled
+ },
+
+ async setEnabled(enabled: boolean): Promise<void> {
+ await state.setEnabled(enabled)
+ if (!enabled)
+ await machine.dispose()
+ },
+
+ async start(): Promise<void> {
+ await state.load()
+ await machine.syncProfiles()
+ },
+
+ async syncProfiles(): Promise<void> {
+ const manual = applyStartDefaults(manualProfiles())
+ const blocks = await loadSshConfigBlocks(sshDirPath(), homeDirPath())
+ const merged = new Map<MachineId, MachineProfile>(manual)
+ for (const [id, profile] of discoveredProfiles(blocks, manual))
+ merged.set(id, profile)
+ machine.refreshProfiles(merged)
+ },
+
+ refreshProfiles(next: ReadonlyMap<MachineId, MachineProfile>): void {
+ machineProfiles.clear()
+ for (const [id, profile] of next)
+ machineProfiles.set(id, profile)
+ for (const id of machineStates.keys()) {
+ if (!machineProfiles.has(id)) {
+ events.forget(id)
+ void machine.disconnect(id)
+ }
+ }
+ },
+
+ profileViews(): MachineView[] {
+ return [...manualProfiles().values()].map(profileView)
+ },
+
+ async discoveredViews(): Promise<MachineView[]> {
+ const manual = manualProfiles()
+ const blocks = await loadSshConfigBlocks(sshDirPath(), homeDirPath())
+ return [...discoveredProfiles(blocks, manual).values()].map(profileView)
+ },
+
+ statuses(): SshMachineStatus[] {
+ return [...machineProfiles.keys()].map(id => machine.status(id))
+ },
+
+ localAllowlist(): WorkspaceAllowlist {
+ return machineRuntimeDeps().localAllowlist()
+ },
+
+ profileName(machineId: MachineId): string {
+ return safeProfileName(machineProfiles.get(machineId)?.profileName)
+ },
+
+ setProgress(machineId: MachineId, progress?: SshProgress): void {
+ const target = ensureState(machineId)
+ if (progress === undefined)
+ delete target.progress
+ else
+ target.progress = progress
+ emit(machineId)
+ },
+
+ status(machineId: MachineId): SshMachineStatus {
+ const target = machineStates.get(machineId)
+ const lastError = target?.lastError
+ const progress = target?.progress
+ const nextRetryAt = target?.reconnect?.nextRetryAt
+ const authMethod = target?.authMethod
+ return {
+ machineId,
+ state: target?.phase ?? 'disconnected',
+ ...target?.link !== undefined ? { tunnelBaseUrl: target.link.tunnelBaseUrl } : {},
+ ...lastError === undefined ? {} : { lastError },
+ ...target?.dshMissing === true ? { dshMissing: true } : {},
+ ...progress === undefined ? {} : { progress },
+ ...nextRetryAt === undefined ? {} : { nextRetryAt },
+ ...authMethod === undefined ? {} : { authMethod },
+ }
+ },
+
+ link(machineId: MachineId): SshLink | undefined {
+ return machineStates.get(machineId)?.link
+ },
+
+ async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {
+ const profile = requireProfile(machineId)
+ const target = ensureState(machineId)
+ const previousPhase = target.phase
+ target.phase = 'testing'
+ target.progress = { phase: 'handshake' }
+ emit(machineId)
+ const restore = (): void => {
+ const current = machineStates.get(machineId)
+ if (current === target && current.phase === 'testing') {
+ current.phase = previousPhase === 'testing' ? 'disconnected' : previousPhase
+ delete current.progress
+ }
+ emit(machineId)
+ }
+ let session: SshSession
+ try {
+ session = await openTransportSession(profile, signal)
+ }
+ catch (error) {
+ restore()
+ return { ok: false, message: redacted(machineId, describeSshFailure(error)) }
+ }
+ try {
+ const result = await session.exec('uname -srm')
+ if (result.code !== 0)
+ return { ok: false, message: describeExecFailure(result.code, result.stderr) }
+ return { ok: true, banner: result.stdout.trim() }
+ }
+ catch (error) {
+ return { ok: false, message: redacted(machineId, describeSshFailure(error)) }
+ }
+ finally {
+ restore()
+ await session.close()
+ }
+ },
+
+ async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {
+ const profile = requireProfile(machineId)
+ const target = ensureState(machineId)
+ if (target.link !== undefined)
+ return target.link
+ refuseWhileReconnecting(machineId, target)
+ if (target.connecting === undefined) {
+ target.phase = 'connecting'
+ delete target.lastError
+ delete target.dshMissing
+ target.progress = { phase: 'handshake' }
+ emit(machineId)
+ const generation = target.generation
+ const attempt = performConnect(machineId, profile, signal)
+ target.connecting = attempt.finally(() => {
+ delete machineStates.get(machineId)?.connecting
+ })
+ void attempt.catch((error) => {
+ const current = machineStates.get(machineId)
+ if (current === undefined || current.generation !== generation)
+ return
+ if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
+ giveUp(machineId, current)
+ return
+ }
+ beginReconnect(machineId)
+ })
+ }
+ return target.connecting
+ },
+
+ async openSession(machineId: MachineId, signal?: AbortSignal): Promise<SshSession> {
+ const profile = requireProfile(machineId)
+ refuseWhileReconnecting(machineId, ensureState(machineId))
+ return await openTransportSession(profile, signal)
+ },
+
+ async disconnect(machineId: MachineId): Promise<void> {
+ const target = machineStates.get(machineId)
+ if (target === undefined)
+ return
+ target.generation += 1
+ stopReconnect(target)
+ delete target.lastError
+ delete target.dshMissing
+ delete target.progress
+ const tunnel = target.tunnel
+ const session = target.session
+ delete target.tunnel
+ delete target.session
+ delete target.link
+ target.phase = 'disconnected'
+ if (tunnel !== undefined)
+ await tunnel.close().catch(() => undefined)
+ if (session !== undefined)
+ await session.close().catch(() => undefined)
+ emit(machineId)
+ },
+
+ async dispose(): Promise<void> {
+ await Promise.all([...machineStates.keys()].map(id => machine.disconnect(id)))
+ },
+
+ async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {
+ const profile = requireProfile(machineId)
+ const target = ensureState(machineId)
+ refuseWhileReconnecting(machineId, target)
+ if (target.installing === undefined) {
+ target.progress = { phase: 'installing' }
+ emit(machineId)
+ const attempt = performInstall(machineId, profile, signal)
+ target.installing = attempt.finally(() => {
+ delete machineStates.get(machineId)?.installing
+ })
+ }
+ return target.installing
+ },
+
+ async save(machineId: MachineId, row: MachineSaveRow, secrets?: MachineSecretWrite): Promise<void> {
+ await state.save(buildProfile(machineId, row, secrets, machineTable.machines.get(machineId)))
+ await machine.syncProfiles()
+ },
+
+ async remove(machineId: MachineId): Promise<void> {
+ await state.remove(machineId)
+ await machine.syncProfiles()
+ },
+})
+
+// --- internal ---
+
+function manualProfiles(): Map<MachineId, MachineProfile> {
+ return new Map(machineTable.machines)
+}
+
+function buildProfile(machineId: MachineId, row: MachineSaveRow, secrets: MachineSecretWrite | undefined, existing: MachineProfile | undefined): MachineProfile {
+ const next: MachineProfile = {
+ id: machineId,
+ name: row.name,
+ host: row.host,
+ port: row.port,
+ user: row.user,
+ remotePort: row.remotePort,
+ }
+ if (existing !== undefined) {
+ if (existing.password !== undefined)
+ next.password = existing.password
+ if (existing.passphrase !== undefined)
+ next.passphrase = existing.passphrase
+ }
+ if (row.startCommand !== undefined && row.startCommand !== '')
+ next.startCommand = row.startCommand
+ if (row.profileName !== undefined && row.profileName !== '')
+ next.profileName = row.profileName
+ if (row.color !== undefined && row.color !== '')
+ next.color = row.color
+ if (row.tintBorder === true)
+ next.tintBorder = true
+ if (secrets !== undefined) {
+ if (secrets.password !== undefined && secrets.password !== '')
+ next.password = secrets.password
+ if (secrets.passphrase !== undefined && secrets.passphrase !== '')
+ next.passphrase = secrets.passphrase
+ }
+ return next
+}
+
+function defaultStartCommandFor(remotePort: number): string | undefined {
+ const template = hostConfig().startCommand
+ if (template === undefined || template === '')
+ return undefined
+ return template.replaceAll('{port}', String(remotePort))
+}
+
+function applyStartDefaults(profiles: Map<MachineId, MachineProfile>): Map<MachineId, MachineProfile> {
+ const next = new Map<MachineId, MachineProfile>()
+ for (const [id, profile] of profiles) {
+ const startCommand = profile.startCommand ?? defaultStartCommandFor(profile.remotePort)
+ next.set(id, { ...profile, ...startCommand === undefined ? {} : { startCommand } })
+ }
+ return next
+}
+
+function discoveredProfiles(blocks: SshHostBlock[], manual: Map<MachineId, MachineProfile>): Map<MachineId, MachineProfile> {
+ const discovered = new Map<MachineId, MachineProfile>()
+ const remotePort = hostConfig().remotePort ?? DEFAULT_REMOTE_PORT
+ const startCommand = defaultStartCommandFor(remotePort)
+ for (const alias of discoverableHosts(blocks)) {
+ const id = MachineId(alias)
+ if (manual.has(id))
+ continue
+ const settings = lookupSshConfig(blocks, alias)
+ discovered.set(id, {
+ id,
+ name: alias,
+ host: alias,
+ port: settings.port ?? DEFAULT_SSH_PORT,
+ user: settings.user ?? '',
+ remotePort,
+ ...startCommand === undefined ? {} : { startCommand },
+ })
+ }
+ return discovered
+}
+
+function requireProfile(machineId: MachineId): MachineProfile {
+ const profile = machineProfiles.get(machineId)
+ if (profile === undefined)
+ throw new SshError('machine-not-found', machineId, `no SSH machine profile "${machineId}"`)
+ return profile
+}
+
+function ensureState(machineId: MachineId): MachineState {
+ let target = machineStates.get(machineId)
+ if (target === undefined) {
+ target = { generation: 0, phase: 'disconnected' }
+ machineStates.set(machineId, target)
+ }
+ return target
+}
+
+async function openTransportSession(profile: MachineProfile, signal?: AbortSignal): Promise<SshSession> {
+ const deps = machineRuntimeDeps()
+ const config = hostConfig()
+ return await deps.transport.connect(
+ profile,
+ (label, key) => checkHostKey(MachineId(label), key),
+ {
+ readyTimeoutMs: config.connectTimeoutMs,
+ resolveProfile: profile => resolveSshAuth(profile, sshDirPath(), homeDirPath()),
+ keepaliveIntervalMs: config.keepaliveIntervalMs,
+ keepaliveCountMax: config.keepaliveCountMax,
+ },
+ signal,
+ )
+}
+
+async function readRemoteWebToken(session: SshSession): Promise<string | undefined> {
+ try {
+ const result = await session.exec(remoteWebTokenCommand())
+ const token = result.stdout.trim()
+ return token === '' ? undefined : token
+ }
+ catch {
+ return undefined
+ }
+}
+
+async function checkHostKey(machineId: MachineId, hostKey: Buffer): Promise<boolean> {
+ const fingerprint = fingerprintHostKey(hostKey)
+ const verdict = await knownHosts.verify(machineId, fingerprint)
+ if (verdict === 'accepted')
+ return true
+ if (verdict === 'unknown') {
+ await knownHosts.accept(machineId, fingerprint)
+ return true
+ }
+ return false
+}
+
+class AttemptCancelled extends Error {}
+
+async function performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {
+ const target = ensureState(machineId)
+ const generation = target.generation
+ let bootstrapSettled = false
+ const onEvent = settlingEventSink(machineId, () => {
+ bootstrapSettled = true
+ })
+ const session = await openSessionOrFail(machineId, profile, signal)
+ try {
+ await syncBundledPlugins(session, safeProfileName(profile.profileName), profile.remotePort, {
+ onEvent: (stage, line) => {
+ if (generation === target.generation)
+ events.append(machineId, stage, line)
+ },
+ })
+ }
+ catch (error) {
+ events.append(machineId, 'install', `捆绑插件同步失败(降级原生 UI): ${messageOf(error)}`)
+ }
+ try {
+ await session.exec(ensurePnpmCommand())
+ events.append(machineId, 'install', '远端 pnpm 垫片就绪(dsh plugin 依赖它)')
+ }
+ catch (error) {
+ events.append(machineId, 'install', `远端 pnpm 垫片写入失败: ${messageOf(error)}`)
+ }
+ try {
+ const added = await carryWorkspaceAllowlist(session, safeProfileName(profile.profileName), machine.localAllowlist())
+ if (added.length > 0)
+ events.append(machineId, 'install', `远端构建放行白名单已补齐 ${added.length} 项(git 插件 prepare 门禁)`)
+ }
+ catch (error) {
+ events.append(machineId, 'install', `构建放行白名单同步失败: ${messageOf(error)}`)
+ }
+ try {
+ await bootstrap.provision(
+ session,
+ profile,
+ {
+ onProgress: (progress) => {
+ if (generation === target.generation) {
+ target.progress = progress
+ emit(machineId)
+ }
+ },
+ onEvent,
+ },
+ )
+ const injection: TunnelHeaderInjection = { cookie: undefined }
+ const tunnel = await session.openTunnel(profile.remotePort, target.preferredTunnelPort, injection)
+ if (generation !== target.generation) {
+ await tunnel.close().catch(() => undefined)
+ throw new AttemptCancelled()
+ }
+ const webToken = await readRemoteWebToken(session)
+ if (webToken !== undefined)
+ injection.cookie = await mintTunnelCookie(`http://127.0.0.1:${tunnel.localPort}/?token=${webToken}`)
+ const link: SshLink = {
+ machineId,
+ tunnelBaseUrl: `http://127.0.0.1:${tunnel.localPort}${webToken === undefined ? '' : `/?token=${webToken}`}`,
+ }
+ const reconnected = target.reconnect !== undefined ? target.reconnect.reasons.length : undefined
+ target.session = session
+ target.tunnel = tunnel
+ target.link = link
+ target.preferredTunnelPort = tunnel.localPort
+ if (session.authMethod === undefined)
+ delete target.authMethod
+ else
+ target.authMethod = session.authMethod
+ delete target.progress
+ stopReconnect(target)
+ target.phase = 'connected'
+ session.onClosed(() => {
+ const current = machineStates.get(machineId)
+ if (current?.session !== session)
+ return
+ const dropped = current.tunnel
+ delete current.session
+ delete current.tunnel
+ delete current.link
+ delete current.progress
+ void dropped?.close().catch(() => undefined)
+ current.lastError = 'SSH connection closed'
+ beginReconnect(machineId)
+ })
+ emit(machineId)
+ events.append(
+ machineId,
+ 'auth',
+ redacted(machineId, `connected to ${profile.host}${session.authMethod === undefined ? '' : ` (auth: ${session.authMethod})`}`),
+ { terminal: 'success' },
+ )
+ if (reconnected !== undefined) {
+ events.append(
+ machineId,
+ 'reconnect',
+ redacted(machineId, `reconnected to ${profile.host} after ${reconnected} failed attempt(s)`),
+ { terminal: 'success' },
+ )
+ }
+ return link
+ }
+ catch (error) {
+ await session.close().catch(() => undefined)
+ if (error instanceof AttemptCancelled)
+ throw new SshError('machine-connect-failed', machineId, 'connection cancelled by disconnect')
+ const message = redacted(machineId, messageOf(error))
+ if (generation === target.generation && !bootstrapSettled)
+ onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: message })
+ if (generation === target.generation) {
+ delete target.progress
+ noteConnectFailure(machineId, message)
+ target.phase = 'disconnected'
+ emit(machineId)
+ }
+ throw new SshError('machine-bootstrap-failed', machineId, message)
+ }
+}
+
+function noteConnectFailure(machineId: MachineId, message: string): void {
+ const target = machineStates.get(machineId)
+ if (target === undefined)
+ return
+ const redactedMessage = redacted(machineId, message)
+ target.lastError = redactedMessage
+ if (message.includes('REMOTE_NOT_INSTALLED'))
+ target.dshMissing = true
+ events.append(machineId, 'auth', redactedMessage)
+}
+
+function beginReconnect(machineId: MachineId): void {
+ const target = ensureState(machineId)
+ if (target.reconnect !== undefined)
+ return
+ target.reconnect = {
+ generation: target.generation,
+ attempt: 0,
+ reasons: [target.lastError ?? 'connection failed'],
+ }
+ scheduleReconnect(machineId)
+}
+
+function scheduleReconnect(machineId: MachineId): void {
+ const target = machineStates.get(machineId)
+ const rec = target?.reconnect
+ if (target === undefined || rec === undefined)
+ return
+ const config = hostConfig()
+ rec.attempt += 1
+ if (rec.attempt > config.reconnectMaxAttempts) {
+ giveUp(machineId, target)
+ return
+ }
+ const delay = Math.min(config.reconnectInitialDelayMs * 2 ** (rec.attempt - 1), config.reconnectMaxDelayMs)
+ rec.nextRetryAt = Date.now() + delay
+ target.phase = 'reconnecting'
+ delete target.progress
+ emit(machineId)
+ events.append(
+ machineId,
+ 'reconnect',
+ redacted(machineId, `retrying in ${Math.round(delay / 100) / 10} s (attempt ${rec.attempt} of ${config.reconnectMaxAttempts})`),
+ )
+ rec.timer = setTimeout(() => {
+ void attemptReconnect(machineId, rec)
+ }, delay)
+ rec.timer.unref?.()
+}
+
+async function attemptReconnect(machineId: MachineId, expected: ReconnectState): Promise<void> {
+ const target = machineStates.get(machineId)
+ const rec = target?.reconnect
+ if (target === undefined || rec !== expected || rec.generation !== target.generation)
+ return
+ const profile = machineProfiles.get(machineId)
+ if (profile === undefined)
+ return
+ delete rec.nextRetryAt
+ target.progress = { phase: 'handshake' }
+ emit(machineId)
+ try {
+ await performConnect(machineId, profile)
+ }
+ catch (error) {
+ if (error instanceof AttemptCancelled)
+ return
+ const current = machineStates.get(machineId)
+ const loop = current?.reconnect
+ if (current === undefined || loop === undefined || loop.generation !== current.generation)
+ return
+ if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
+ giveUp(machineId, current)
+ return
+ }
+ loop.reasons.push(current.lastError ?? describeSshFailure(error))
+ scheduleReconnect(machineId)
+ }
+}
+
+function giveUp(machineId: MachineId, target: MachineState): void {
+ const rec = target.reconnect
+ stopReconnect(target)
+ delete target.progress
+ target.phase = 'given-up'
+ const last = rec?.reasons[rec.reasons.length - 1] ?? target.lastError ?? 'connection failed'
+ target.lastError = rec === undefined
+ ? redacted(machineId, last)
+ : redacted(machineId, `connect failed after ${rec.reasons.length} attempt(s): ${last}`)
+ emit(machineId)
+ events.append(machineId, 'reconnect', target.lastError, { terminal: 'failed', reason: target.lastError })
+}
+
+function stopReconnect(target: MachineState): void {
+ if (target.reconnect?.timer !== undefined)
+ clearTimeout(target.reconnect.timer)
+ delete target.reconnect
+}
+
+function refuseWhileReconnecting(machineId: MachineId, target: MachineState): void {
+ const rec = target.reconnect
+ if (rec === undefined)
+ return
+ throw new SshError(
+ 'machine-reconnecting',
+ machineId,
+ `machine is reconnecting (attempt ${rec.attempt} of ${hostConfig().reconnectMaxAttempts}); `
+ + 'wait for the automatic retry or disconnect first',
+ )
+}
+
+function redacted(machineId: MachineId, text: string): string {
+ const profile = machineProfiles.get(machineId)
+ let out = text
+ for (const secret of [profile?.password, profile?.passphrase]) {
+ if (secret !== undefined && secret !== '')
+ out = out.replaceAll(secret, '***')
+ }
+ return out
+}
+
+async function performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {
+ const config = hostConfig()
+ const target = ensureState(machineId)
+ const generation = target.generation
+ let settled = false
+ const onEvent = settlingEventSink(machineId, () => {
+ settled = true
+ })
+ const session = await openSessionOrFail(machineId, profile, signal, () => beginReconnect(machineId))
+ try {
+ onEvent('probe', '探测远端平台 (uname -srm)')
+ const uname = await session.exec('uname -srm')
+ if (uname.code !== 0)
+ throw new Error(`cannot probe remote platform: ${describeExecFailure(uname.code, uname.stderr)}`)
+ const plan = await planRemoteInstall(uname.stdout, config)
+ onEvent('probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)
+ for (const note of plan.notes)
+ onEvent('probe', note)
+ const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
+ const skips: string[] = []
+ if (missing.length > 0) {
+ onEvent('probe', `缺失组件: ${missing.join(', ')}`)
+ skips.push(...await bootstrap.install(session, plan, {
+ onEvent,
+ onProgress: (progress) => {
+ if (generation !== target.generation)
+ return
+ target.progress = progress
+ emit(machineId)
+ },
+ }, 'install 失败'))
+ if (generation !== target.generation)
+ throw new AttemptCancelled()
+ }
+ else {
+ onEvent('probe', '三件套已就绪,跳过安装')
+ }
+ const dshExpr = `"$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan.dshEntry}"`
+ const entryCheck = await session.exec(`test -f ${dshExpr} && printf '%s\\n' ${dshExpr}`)
+ const dshPath = firstLineOf(entryCheck.stdout)
+ if (entryCheck.code !== 0 || dshPath === '') {
+ throw new SshError(
+ 'machine-dsh-missing',
+ machineId,
+ `dsh install finished on "${profile.host}" but the entry ${dshExpr} is not present`,
+ )
+ }
+ let credentialsCopied = false
+ let credentialsError: string | undefined
+ try {
+ credentialsCopied = await copyCredentials(session)
+ }
+ catch (error) {
+ credentialsError = error instanceof Error ? error.message : String(error)
+ }
+ const dshRef = plan.dsh.kind === 'pkg-zip' ? plan.dsh.tag : `npm:${plan.dsh.version}`
+ onEvent('install', `dsh 安装成功 (${dshRef})${skippedVerificationSummary(plan.notes, skips)}`, { terminal: 'success' })
+ await session.close().catch(() => undefined)
+ if (generation === target.generation) {
+ delete target.progress
+ delete target.dshMissing
+ delete target.lastError
+ target.phase = 'disconnected'
+ emit(machineId)
+ void machine.connect(machineId).catch(() => undefined)
+ }
+ return {
+ installed: missing,
+ dshRef,
+ dshVersion: plan.dshVersion,
+ dshPath,
+ credentialsCopied,
+ ...credentialsError === undefined ? {} : { credentialsError },
+ }
+ }
+ catch (error) {
+ await session.close().catch(() => undefined)
+ if (error instanceof AttemptCancelled)
+ throw new SshError('machine-install-failed', machineId, 'install cancelled by disconnect')
+ const message = redacted(machineId, messageOf(error))
+ if (generation === target.generation && !settled)
+ onEvent('failed', 'install 失败', { terminal: 'failed', reason: message })
+ if (generation === target.generation) {
+ delete target.progress
+ target.lastError = message
+ target.phase = 'disconnected'
+ emit(machineId)
+ }
+ if (error instanceof SshError)
+ throw error
+ throw new SshError('machine-install-failed', machineId, message)
+ }
+}
+
+async function copyCredentials(session: SshSession): Promise<boolean> {
+ const credentials = readEnvCredentials(join(harnessHome(), '.env'))
+ const apiKey = credentials.apiKey
+ if (apiKey === undefined)
+ return false
+ const result = await session.exec(credentialsCopyCommand({
+ apiKey,
+ ...credentials.baseUrl === undefined ? {} : { baseUrl: credentials.baseUrl },
+ }))
+ if (result.code !== 0)
+ throw new Error(`writing remote credentials failed: ${describeExecFailure(result.code, result.stderr)}`)
+ return result.stdout.includes('copied')
+}
+
+function emit(machineId: MachineId): void {
+ machineRuntimeDeps().emitStatus(machineId, machine.status(machineId))
+}
+
+function profileView(profile: MachineProfile): MachineView {
+ return {
+ id: profile.id,
+ name: profile.name,
+ host: profile.host,
+ port: profile.port,
+ user: profile.user,
+ hasPassword: profile.password !== undefined,
+ hasPassphrase: profile.passphrase !== undefined,
+ remotePort: profile.remotePort,
+ ...profile.profileName === undefined ? {} : { profileName: profile.profileName },
+ ...profile.startCommand === undefined ? {} : { startCommand: profile.startCommand },
+ ...profile.color === undefined ? {} : { color: profile.color },
+ ...profile.tintBorder === true ? { tintBorder: true } : {},
+ }
+}
+
+async function openSessionOrFail(
+ machineId: MachineId,
+ profile: MachineProfile,
+ signal?: AbortSignal,
+ onFail?: () => void,
+): Promise<SshSession> {
+ const target = ensureState(machineId)
+ const generation = target.generation
+ try {
+ return await openTransportSession(profile, signal)
+ }
+ catch (error) {
+ const message = redacted(machineId, describeSshFailure(error))
+ if (generation === target.generation) {
+ delete target.progress
+ noteConnectFailure(machineId, message)
+ onFail?.()
+ }
+ throw new SshError('machine-connect-failed', machineId, message)
+ }
+}
+
+function settlingEventSink(machineId: MachineId, onSettle: () => void): NonNullable<BootstrapHooks['onEvent']> {
+ return (stage, line, options) => {
+ if (options?.terminal !== undefined)
+ onSettle()
+ events.append(machineId, stage, line, options)
+ }
+}
+
+function describeSshFailure(error: unknown): string {
+ return messageOf(error) || 'SSH connection failed'
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.types.ts b/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
new file mode 100644
index 00000000..fbd402e8
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
@@ -0,0 +1,42 @@
+import type {
+ MachineId,
+ SshAuthMethod,
+ SshInstallResult,
+ SshLink,
+ SshMachineStatus,
+ SshProgress,
+ SshSession,
+ SshTunnelHandle,
+} from '../types/index'
+import type { WorkspaceAllowlist } from '../utils/allowlist'
+import type { SshTransport } from './transport.types'
+
+export interface MachineState {
+ generation: number
+ phase: 'disconnected' | 'testing' | 'connecting' | 'connected' | 'reconnecting' | 'given-up'
+ connecting?: Promise<SshLink>
+ installing?: Promise<SshInstallResult>
+ session?: SshSession
+ tunnel?: SshTunnelHandle
+ link?: SshLink
+ lastError?: string
+ dshMissing?: boolean
+ progress?: SshProgress
+ reconnect?: ReconnectState
+ preferredTunnelPort?: number
+ authMethod?: SshAuthMethod
+}
+
+export interface ReconnectState {
+ generation: number
+ attempt: number
+ nextRetryAt?: number
+ timer?: NodeJS.Timeout
+ reasons: string[]
+}
+
+export interface MachineDeps {
+ transport: SshTransport
+ emitStatus: (machineId: MachineId, status: SshMachineStatus) => void
+ localAllowlist: () => WorkspaceAllowlist
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.ts
deleted file mode 100644
index c3847983..00000000
--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts
+++ /dev/null
@@ -1,988 +0,0 @@
-import type { Buffer } from 'node:buffer'
-import type { Config } from '../storage/index'
-/**
- * Per-machine connection manager: profile map, the connection state machine
- * (disconnected/testing/connecting/connected/reconnecting/given-up), TOFU
- * host-key gating, remote-instance assurance, the tunnel lifecycle, and the
- * watchdog-driven reconnect loop (exponential backoff, tunnel rebuild).
- * Transport-agnostic — tests inject a fake transport and never touch the
- * network.
- * @module dsh-tauri-ssh/host/service/manager
- */
-
-import type { MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStage, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'
-import type { WorkspaceAllowlist } from './allowlist'
-import type { BootstrapHooks } from './bootstrap'
-import type { SshMachineEvents } from './events'
-import type { KnownHostsStore } from './host-keys'
-import type { SshSession, SshTransport, SshTunnelHandle, TunnelHeaderInjection } from './transport'
-import { homedir } from 'node:os'
-import process from 'node:process'
-import { join } from 'pathe'
-import { MachineId, SshError } from '../types/index'
-import { carryWorkspaceAllowlist, EMPTY_ALLOWLIST } from './allowlist'
-import { checkMissingCommand, credentialsCopyCommand, describeError, describeExecFailure, ensurePnpmCommand, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, remoteWebTokenCommand, runInstallScript, safeProfileName, skippedVerificationSummary } from './bootstrap'
-import { fingerprintHostKey } from './host-keys'
-import { syncBundledPlugins } from './plugins-sync'
-import { mintTunnelCookie } from './transport'
-
-/** One machine's live connection state. */
-interface MachineState {
- /** Monotonic attempt counter; a disconnect invalidates in-flight connects. */
- generation: number
- /** Published connection phase; the status source of truth. */
- phase: 'disconnected' | 'testing' | 'connecting' | 'connected' | 'reconnecting' | 'given-up'
- /** In-flight connect promise; concurrent connects share it. */
- connecting?: Promise<SshLink>
- /** In-flight install promise; concurrent installs share it. */
- installing?: Promise<SshInstallResult>
- /** The authenticated SSH session, while connected. */
- session?: SshSession
- /** The local tunnel listener, while connected. */
- tunnel?: SshTunnelHandle
- /** The published link, while connected. */
- link?: SshLink
- /** Operator-facing description of the last failed transition. */
- lastError?: string
- /** Whether the last failure was "dsh not installed on the remote". */
- dshMissing?: boolean
- /** Live progress of the in-flight operation. */
- progress?: SshProgress
- /** The active reconnect loop, while one owns the machine. */
- reconnect?: ReconnectState
- /** Local port to prefer when (re)binding the tunnel, keeping the URL stable. */
- preferredTunnelPort?: number
- /** Which credential the live (or last successful) connection used. */
- authMethod?: SshSession['authMethod']
-}
-
-/** The background reconnect loop's bookkeeping. */
-interface ReconnectState {
- /** Generation this loop belongs to; a disconnect invalidates it. */
- generation: number
- /** Number of the retry that runs next, 1-based; exceeds the budget → give up. */
- attempt: number
- /** Epoch ms when the scheduled retry fires; absent while a retry is in flight. */
- nextRetryAt?: number
- /** The pending retry timer; a disconnect clears it. */
- timer?: NodeJS.Timeout
- /** Redacted reason of every failed attempt so far, first attempt included. */
- reasons: string[]
-}
-
-/** Manager dependencies (all transport seams injectable for tests). */
-export interface SshManagerDeps {
- transport: SshTransport
- knownHosts: KnownHostsStore
- config: Config
- /** The machine event channel (C-EVENT): bootstrap log/progress events. */
- events: SshMachineEvents
- /** The install-plan resolver (overridable so tests never touch the network). */
- planInstall?: (unameOut: string, config: Pick<Config, 'installRepo' | 'installRef'>) => Promise<import('./bootstrap').RemoteInstallPlan>
- /** Publish one machine's status change (the service emits the seam event). */
- emitStatus: (machineId: MachineId, status: SshMachineStatus) => void
- /** Local dsh `.env` credentials to copy after an install (defaults to the host's own). */
- readEnvCredentials?: () => ReturnType<typeof readEnvCredentials>
- /**
- * Mint the tunnel's session cookie: one local GET of the authenticated URL
- * (no redirect follow), resolving the `name=value` pair from `set-cookie`.
- * Defaults to the node:http implementation; tests stub it to stay offline.
- */
- mintCookie?: (authenticatedUrl: string) => Promise<string | undefined>
- /**
- * The local profile's build allowlist to carry to the remote (defaults to
- * none; the plugin wires the real reader). See {@link carryWorkspaceAllowlist}.
- */
- localAllowlist?: () => WorkspaceAllowlist
- /**
- * Sync the desktop-bundled plugins to the remote (defaults to the real
- * tarball pipeline; tests stub it to stay offline). Returns whether the
- * remote was modified (a running instance gets restarted by the sync).
- */
- syncPlugins?: (session: SshSession, profileName: string, remotePort: number, hooks: { onEvent?: (stage: SshMachineStage, line: string) => void }) => Promise<boolean>
-}
-
-/** The sentinel rethrown when an in-flight attempt loses to a disconnect. */
-class AttemptCancelled extends Error {}
-
-/**
- * The per-machine state machine. All public methods are safe to call
- * concurrently: connects dedupe on the in-flight promise, disconnects settle
- * a live link idempotently, and session-closed callbacks race-check their
- * ownership before tearing down. Every transition publishes through
- * `emitStatus` exactly when it happens; a superseded attempt never publishes.
- */
-export class SshManager {
- private readonly profiles = new Map<MachineId, MachineProfile>()
- private readonly states = new Map<MachineId, MachineState>()
-
- /**
- * @param deps - transport, TOFU store, timing config, and the status publisher.
- */
- constructor(private readonly deps: SshManagerDeps) {}
-
- /**
- * Replace the profile map (settings changed). Machines whose profile
- * vanished are disconnected; live connections keep their established link
- * until the operator reconnects (a profile edit applies on next connect).
- * @param profiles - the new profile map keyed by machine id.
- */
- refreshProfiles(profiles: ReadonlyMap<MachineId, MachineProfile>): void {
- this.profiles.clear()
- for (const [id, profile] of profiles) this.profiles.set(id, profile)
- for (const id of this.states.keys()) {
- if (!this.profiles.has(id)) {
- this.deps.events.forget(id)
- void this.disconnect(id)
- }
- }
- }
-
- /** Redacted views of every profile, in settings order. */
- profileViews(): MachineView[] {
- return [...this.profiles.values()].map(profileView)
- }
-
- /** Transport status of every known machine, in settings order. */
- statuses(): SshMachineStatus[] {
- return [...this.profiles.keys()].map(id => this.status(id))
- }
-
- /** The local profile's build allowlist (empty when no reader is wired). */
- localAllowlist(): WorkspaceAllowlist {
- return (this.deps.localAllowlist ?? (() => EMPTY_ALLOWLIST))()
- }
-
- /**
- * The remote dsh profile this machine serves (its configured name, falling
- * back to the default). Callers that install plugins on the remote must
- * target it: the tunnel only ever serves this one profile.
- * @param machineId - the machine to look up.
- * @returns the shell-safe profile name.
- */
- profileName(machineId: MachineId): string {
- return safeProfileName(this.profiles.get(machineId)?.profileName)
- }
-
- /**
- * Publish (or clear, with no value) the live progress of an operation the
- * manager does not own a lifecycle for — the sync engine's item-by-item
- * pass. The status line is the only channel the settings page polls, so an
- * externally driven operation reports itself here to stay visible.
- * @param machineId - the machine the operation runs against.
- * @param progress - the progress to publish; omit to clear.
- */
- setProgress(machineId: MachineId, progress?: SshProgress): void {
- const state = this.ensureState(machineId)
- if (progress === undefined)
- delete state.progress
- else
- state.progress = progress
- this.emit(machineId)
- }
-
- /** Transport status of one machine; unknown ids report `disconnected`. */
- status(machineId: MachineId): SshMachineStatus {
- const state = this.states.get(machineId)
- const lastError = state?.lastError
- const progress = state?.progress
- const nextRetryAt = state?.reconnect?.nextRetryAt
- const authMethod = state?.authMethod
- return {
- machineId,
- state: state?.phase ?? 'disconnected',
- ...state?.link !== undefined ? { tunnelBaseUrl: state.link.tunnelBaseUrl } : {},
- ...lastError === undefined ? {} : { lastError },
- ...state?.dshMissing === true ? { dshMissing: true } : {},
- ...progress === undefined ? {} : { progress },
- ...nextRetryAt === undefined ? {} : { nextRetryAt },
- ...authMethod === undefined ? {} : { authMethod },
- }
- }
-
- /** The current tunnel link of one machine, when connected. */
- link(machineId: MachineId): SshLink | undefined {
- return this.states.get(machineId)?.link
- }
-
- /**
- * One-shot probe: authenticate, run `uname -srm`, close. Never starts the
- * remote instance and never leaves a connection behind. Publishes the
- * transient `testing` state for the probe's duration, then restores the
- * phase it found (unless something else transitioned the machine in the
- * meantime — reconnects and disconnects own their transitions).
- * @param machineId - the machine to probe.
- * @param signal - aborts the probe.
- * @returns the probe outcome.
- * @throws {SshError} `machine-not-found` for an unknown id.
- */
- async test(machineId: MachineId, signal?: AbortSignal): Promise<SshTestResult> {
- const profile = this.requireProfile(machineId)
- const state = this.ensureState(machineId)
- const previousPhase = state.phase
- state.phase = 'testing'
- state.progress = { phase: 'handshake' }
- this.emit(machineId)
- const restore = (): void => {
- const current = this.states.get(machineId)
- // Only test() ever sets `testing`, so a different phase means another
- // transition (drop, reconnect, disconnect) took ownership meanwhile.
- if (current === state && current.phase === 'testing') {
- current.phase = previousPhase === 'testing' ? 'disconnected' : previousPhase
- delete current.progress
- }
- this.emit(machineId)
- }
- let session: SshSession
- try {
- session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
- }
- catch (error) {
- restore()
- return { ok: false, message: this.redacted(machineId, describeSshFailure(error)) }
- }
- try {
- const result = await session.exec('uname -srm')
- if (result.code !== 0) {
- return { ok: false, message: describeExecFailure(result.code, result.stderr) }
- }
- return { ok: true, banner: result.stdout.trim() }
- }
- catch (error) {
- return { ok: false, message: this.redacted(machineId, describeSshFailure(error)) }
- }
- finally {
- restore()
- await session.close()
- }
- }
-
- /**
- * Establish (or reuse) the machine link: SSH connection, remote-instance
- * assurance, and the local tunnel. Idempotent. A failed attempt hands the
- * machine to the background reconnect loop (the caller sees the failure;
- * the loop keeps retrying with exponential backoff and either reconnects
- * or lands in the `given-up` terminal state).
- * @param machineId - the machine to connect.
- * @param signal - aborts the connection attempt.
- * @returns the live link.
- * @throws {SshError} on any failure, or `machine-reconnecting` while the
- * reconnect loop owns the machine.
- */
- async connect(machineId: MachineId, signal?: AbortSignal): Promise<SshLink> {
- const profile = this.requireProfile(machineId)
- const state = this.ensureState(machineId)
- if (state.link !== undefined)
- return state.link
- this.refuseWhileReconnecting(machineId, state)
- if (state.connecting === undefined) {
- state.phase = 'connecting'
- delete state.lastError
- delete state.dshMissing
- state.progress = { phase: 'handshake' }
- this.emit(machineId)
- const generation = state.generation
- const attempt = this.performConnect(machineId, profile, signal)
- state.connecting = attempt.finally(() => {
- // The slot is only ever replaced while undefined, so the settling
- // attempt always owns it at this point.
- delete this.states.get(machineId)?.connecting
- })
- // The caller sees the first failure; the reconnect loop keeps trying
- // in the background (unless the failure is persistent dsh-missing or
- // a disconnect superseded the attempt).
- void attempt.catch((error) => {
- const current = this.states.get(machineId)
- if (current === undefined || current.generation !== generation)
- return
- if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
- this.giveUp(machineId, current)
- return
- }
- this.beginReconnect(machineId)
- })
- }
- return state.connecting
- }
-
- /**
- * Open one dedicated authenticated session to the machine — handshake and
- * TOFU gate only, no remote-instance bootstrap and no tunnel. Callers that
- * drive plain remote commands (the sync engine) get an independent
- * lifecycle: closing the returned session never touches a live link.
- * @param machineId - the machine to reach.
- * @param signal - aborts the handshake.
- * @returns the authenticated session; the caller owns closing it.
- * @throws {SshError} `machine-not-found` for an unknown id, or
- * `machine-reconnecting` while the reconnect loop owns the machine.
- */
- async openSession(machineId: MachineId, signal?: AbortSignal): Promise<SshSession> {
- const profile = this.requireProfile(machineId)
- // 与 connect/install 一致:重连窗口拥有机器时拒绝新会话(S3 的在途操
- // 作一致性语义——sync 引擎经此开专用会话,裸 /api-ssh 调用方同样拿到
- // 可区分的 machine-reconnecting 而非并行建连)。
- this.refuseWhileReconnecting(machineId, this.ensureState(machineId))
- return await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
- }
-
- /**
- * Tear down one machine's link, invalidating any in-flight connect and any
- * running reconnect loop. Idempotent for an absent link; unknown ids
- * resolve without writing anything.
- * @param machineId - the machine to disconnect.
- */
- async disconnect(machineId: MachineId): Promise<void> {
- const state = this.states.get(machineId)
- if (state === undefined)
- return
- state.generation += 1
- this.stopReconnect(state)
- delete state.lastError
- delete state.dshMissing
- delete state.progress
- const tunnel = state.tunnel
- const session = state.session
- delete state.tunnel
- delete state.session
- delete state.link
- state.phase = 'disconnected'
- if (tunnel !== undefined)
- await tunnel.close().catch(() => undefined)
- if (session !== undefined)
- await session.close().catch(() => undefined)
- this.emit(machineId)
- }
-
- /**
- * Disconnect every machine (composition teardown).
- */
- async dispose(): Promise<void> {
- await Promise.all([...this.states.keys()].map(id => this.disconnect(id)))
- }
-
- /** @throws {SshError} `machine-not-found` for an unknown id. */
- private requireProfile(machineId: MachineId): MachineProfile {
- const profile = this.profiles.get(machineId)
- if (profile === undefined) {
- throw new SshError('machine-not-found', machineId, `no SSH machine profile "${machineId}"`)
- }
- return profile
- }
-
- private ensureState(machineId: MachineId): MachineState {
- let state = this.states.get(machineId)
- if (state === undefined) {
- state = { generation: 0, phase: 'disconnected' }
- this.states.set(machineId, state)
- }
- return state
- }
-
- /**
- * Best-effort launch-token read from the remote web log. No exec timeout:
- * a timeout in this session implementation closes the whole connection,
- * and a slow grep must never kill a healthy link — any failure simply
- * degrades to the bare tunnel URL.
- */
- private async readRemoteWebToken(session: SshSession): Promise<string | undefined> {
- try {
- const result = await session.exec(remoteWebTokenCommand())
- const token = result.stdout.trim()
- return token === '' ? undefined : token
- }
- catch {
- return undefined
- }
- }
-
- /** TOFU gate: accept a known fingerprint, remember a first sight, reject a mismatch. */
- private async checkHostKey(machineId: MachineId, hostKey: Buffer): Promise<boolean> {
- const fingerprint = fingerprintHostKey(hostKey)
- const verdict = await this.deps.knownHosts.verify(machineId, fingerprint)
- if (verdict === 'accepted')
- return true
- if (verdict === 'unknown') {
- await this.deps.knownHosts.accept(machineId, fingerprint)
- return true
- }
- return false
- }
-
- /**
- * One full connection attempt. Publishes exactly one terminal transition
- * (connected or disconnected) unless a disconnect superseded the attempt —
- * a superseded attempt closes its session and throws without publishing.
- * The bootstrap event stream likewise settles on every failure (its own
- * settling events, or the catch for transport exceptions that bypass
- * them), except a superseded attempt: cancellation by an explicit
- * disconnect is the documented no-terminal case. Failures record the
- * (redacted, auth-stage) reason — the caller decides whether the reconnect
- * loop takes over.
- */
- private async performConnect(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshLink> {
- const state = this.ensureState(machineId)
- const generation = state.generation
- // The settling guard: remembers whether this attempt's bootstrap already
- // settled the event stream (failBootstrap/emitReady fire their own
- // terminal events), so the catch below settles only the gaps — transport
- // exceptions such as exec timeouts or a dropped session, which bypass
- // the bootstrap's own failure reporting.
- let bootstrapSettled = false
- const onEvent: NonNullable<BootstrapHooks['onEvent']> = (stage, line, options) => {
- if (options?.terminal !== undefined)
- bootstrapSettled = true
- this.deps.events.append(machineId, stage, line, options)
- }
- let session: SshSession
- try {
- session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
- }
- catch (error) {
- // The locally captured, redacted message: a superseded attempt must
- // not read state.lastError back — that slot may already belong to a
- // newer try.
- const message = this.redacted(machineId, describeSshFailure(error))
- if (generation === state.generation) {
- delete state.progress
- this.noteConnectFailure(machineId, message)
- }
- throw new SshError('machine-connect-failed', machineId, message)
- }
- // 桌面捆绑插件随远端实例走(远端窗口与本体唯一区别=后端):树变化时
- // 上传并重启实例,随后的 ensure 按新 profile 拉起。best-effort:同步
- // 失败降级为原生远端 UI,连接本身不受影响。
- try {
- await (this.deps.syncPlugins ?? syncBundledPlugins)(session, safeProfileName(profile.profileName), profile.remotePort, {
- onEvent: (stage, line) => {
- if (generation === state.generation)
- this.deps.events.append(machineId, stage, line)
- },
- })
- }
- catch (error) {
- this.deps.events.append(machineId, 'install', `捆绑插件同步失败(降级原生 UI): ${describeError(error)}`)
- }
- // 远端自带的 pnpm 只在 dependencies/pnpm 下,PATH 上没有裸 `pnpm`——而
- // `dsh plugin add`(同步面板装第三方插件、远端自己装插件)都找它。补一个
- // 指向布局自带 pnpm 的垫片(幂等、不需联网),失败只记一行日志。
- try {
- await session.exec(ensurePnpmCommand())
- this.deps.events.append(machineId, 'install', '远端 pnpm 垫片就绪(dsh plugin 依赖它)')
- }
- catch (error) {
- this.deps.events.append(machineId, 'install', `远端 pnpm 垫片写入失败: ${describeError(error)}`)
- }
- // 本机已放行的构建白名单(桌面端插件安装器写进 profile 的 pnpm-workspace.yaml)
- // 带到远端:git 托管的插件在远端同样要过 pnpm 的 prepare 门禁,而远端 profile
- // 是从模板起的、一个放行项都没有。
- try {
- const added = await carryWorkspaceAllowlist(session, safeProfileName(profile.profileName), (this.deps.localAllowlist ?? (() => EMPTY_ALLOWLIST))())
- if (added.length > 0)
- this.deps.events.append(machineId, 'install', `远端构建放行白名单已补齐 ${added.length} 项(git 插件 prepare 门禁)`)
- }
- catch (error) {
- this.deps.events.append(machineId, 'install', `构建放行白名单同步失败: ${describeError(error)}`)
- }
- try {
- await ensureRemoteInstance(
- session,
- profile,
- {
- config: this.deps.config,
- healthCheckTimeoutMs: this.deps.config.healthCheckTimeoutMs,
- healthPollIntervalMs: this.deps.config.healthPollIntervalMs,
- healthPollAttempts: this.deps.config.healthPollAttempts,
- },
- {
- onProgress: (progress) => {
- if (generation === state.generation) {
- state.progress = progress
- this.emit(machineId)
- }
- },
- onEvent,
- },
- this.deps.planInstall,
- )
- // Prefer the previously published tunnel port so a reconnect keeps
- // the machine's URL stable for consumers (falls back to ephemeral).
- // Cookie 注入槽先挂上:隧道一旦发布即可服务;mint 落定后每条连接
- // 自动带 Cookie( mint 前的纯裸管阶段只发生在发布前,外部不可见)。
- const injection: TunnelHeaderInjection = { cookie: undefined }
- const tunnel = await session.openTunnel(profile.remotePort, state.preferredTunnelPort, injection)
- // A disconnect that landed anywhere above (bootstrap, tunnel opening)
- // must not publish a link; tear the tunnel down and abort the attempt.
- if (generation !== state.generation) {
- await tunnel.close().catch(() => undefined)
- throw new AttemptCancelled()
- }
- // dsh web 的 launch token:隧道 URL 带上 ?token= 后,首次加载即 mint
- // 该 authority 的鉴权 cookie(303 → /),壳层 iframe 与新窗口免登录;
- // 读不到(实例非本插件拉起/日志无记录)退化为裸 URL(401 页自行呈现)。
- const webToken = await this.readRemoteWebToken(session)
- // 会话 cookie 是 SameSite=Strict:iframe 第三方上下文存不下也发不出
- // (壳层内嵌 401 的根因)——隧道自注 Cookie 才是不挑嵌入上下文的解法;
- // URL 同时保留 ?token=(顶层导航的新窗口/浏览器自举用)。
- if (webToken !== undefined) {
- const mint = this.deps.mintCookie ?? mintTunnelCookie
- injection.cookie = await mint(`http://127.0.0.1:${tunnel.localPort}/?token=${webToken}`)
- }
- const link: SshLink = {
- machineId,
- tunnelBaseUrl: `http://127.0.0.1:${tunnel.localPort}${webToken === undefined ? '' : `/?token=${webToken}`}`,
- }
- const reconnected = state.reconnect !== undefined ? state.reconnect.reasons.length : undefined
- state.session = session
- state.tunnel = tunnel
- state.link = link
- state.preferredTunnelPort = tunnel.localPort
- state.authMethod = session.authMethod
- delete state.progress
- this.stopReconnect(state)
- state.phase = 'connected'
- session.onClosed(() => {
- const current = this.states.get(machineId)
- if (current?.session !== session)
- return
- // The established connection dropped (server went away, network,
- // keepalive watchdog): hand the machine to the reconnect loop.
- const tunnel = current.tunnel
- delete current.session
- delete current.tunnel
- delete current.link
- delete current.progress
- void tunnel?.close().catch(() => undefined)
- current.lastError = 'SSH connection closed'
- this.beginReconnect(machineId)
- })
- this.emit(machineId)
- this.deps.events.append(
- machineId,
- 'auth',
- this.redacted(machineId, `connected to ${profile.host}${session.authMethod === undefined ? '' : ` (auth: ${session.authMethod})`}`),
- { terminal: 'success' },
- )
- if (reconnected !== undefined) {
- this.deps.events.append(
- machineId,
- 'reconnect',
- this.redacted(machineId, `reconnected to ${profile.host} after ${reconnected} failed attempt(s)`),
- { terminal: 'success' },
- )
- }
- return link
- }
- catch (error) {
- await session.close().catch(() => undefined)
- if (error instanceof AttemptCancelled) {
- throw new SshError('machine-connect-failed', machineId, 'connection cancelled by disconnect')
- }
- // The locally captured message: a superseded attempt must not read
- // state.lastError back — that slot may already belong to a newer try.
- const message = error instanceof Error ? error.message : String(error)
- if (generation === state.generation && !bootstrapSettled) {
- onEvent('failed', 'bootstrap 失败', { terminal: 'failed', reason: this.redacted(machineId, message) })
- }
- if (generation === state.generation) {
- delete state.progress
- this.noteConnectFailure(machineId, message)
- state.phase = 'disconnected'
- this.emit(machineId)
- }
- throw new SshError('machine-bootstrap-failed', machineId, this.redacted(machineId, message))
- }
- }
-
- /**
- * Record one failed connection attempt: redacted `lastError`, the
- * dsh-missing marker, and an `auth`-stage event line on the machine event
- * channel. Never publishes the phase — the caller owns that transition.
- */
- private noteConnectFailure(machineId: MachineId, message: string): void {
- const state = this.states.get(machineId)
- if (state === undefined)
- return
- const redactedMessage = this.redacted(machineId, message)
- state.lastError = redactedMessage
- // The start script's own "not installed" verdict keeps the UI's install
- // hint alive (the auto-bootstrap could not complete).
- if (message.includes('REMOTE_NOT_INSTALLED'))
- state.dshMissing = true
- this.deps.events.append(machineId, 'auth', redactedMessage)
- }
-
- /**
- * Hand one machine to the reconnect loop after its first failed attempt
- * (user connect, install connect, or a dropped established connection).
- * Idempotent — a machine already owned by a loop stays on its schedule.
- */
- private beginReconnect(machineId: MachineId): void {
- const state = this.ensureState(machineId)
- if (state.reconnect !== undefined)
- return
- state.reconnect = {
- generation: state.generation,
- attempt: 0,
- reasons: [state.lastError ?? 'connection failed'],
- }
- this.scheduleReconnect(machineId)
- }
-
- /**
- * Schedule the loop's next retry (or give up when the budget is spent):
- * exponential backoff from the configured initial delay, capped at the
- * configured ceiling. Publishes the `reconnecting` phase with the retry
- * hint each time the schedule changes.
- */
- private scheduleReconnect(machineId: MachineId): void {
- const state = this.states.get(machineId)
- const rec = state?.reconnect
- if (state === undefined || rec === undefined)
- return
- rec.attempt += 1
- if (rec.attempt > this.deps.config.reconnectMaxAttempts) {
- this.giveUp(machineId, state)
- return
- }
- const base = this.deps.config.reconnectInitialDelayMs
- const ceiling = this.deps.config.reconnectMaxDelayMs
- const delay = Math.min(base * 2 ** (rec.attempt - 1), ceiling)
- rec.nextRetryAt = Date.now() + delay
- state.phase = 'reconnecting'
- delete state.progress
- this.emit(machineId)
- this.deps.events.append(
- machineId,
- 'reconnect',
- this.redacted(machineId, `retrying in ${Math.round(delay / 100) / 10} s (attempt ${rec.attempt} of ${this.deps.config.reconnectMaxAttempts})`),
- )
- rec.timer = setTimeout(() => {
- void this.attemptReconnect(machineId)
- }, delay)
- // A pending retry must never hold the host process open on its own.
- rec.timer.unref?.()
- }
-
- /**
- * One background reconnect attempt: re-reads the live profile (an edit
- * during the outage — e.g. a fixed password — applies on the next retry)
- * and stops silently when a disconnect superseded the loop.
- */
- private async attemptReconnect(machineId: MachineId): Promise<void> {
- const state = this.states.get(machineId)
- const rec = state?.reconnect
- if (state === undefined || rec === undefined || rec.generation !== state.generation)
- return
- const profile = this.profiles.get(machineId)
- if (profile === undefined)
- return
- delete rec.nextRetryAt
- state.progress = { phase: 'handshake' }
- this.emit(machineId)
- try {
- await this.performConnect(machineId, profile)
- // performConnect published `connected`, cleared the loop, and emitted
- // the success events.
- }
- catch (error) {
- if (error instanceof AttemptCancelled)
- return
- const current = this.states.get(machineId)
- const loop = current?.reconnect
- if (current === undefined || loop === undefined || loop.generation !== current.generation)
- return
- if ((error instanceof SshError && error.code === 'machine-dsh-missing') || current.dshMissing === true) {
- // A missing dsh runtime is persistent — retrying cannot fix it, and
- // the given-up state frees the machine for the install flow.
- this.giveUp(machineId, current)
- return
- }
- loop.reasons.push(current.lastError ?? describeSshFailure(error))
- this.scheduleReconnect(machineId)
- }
- }
-
- /**
- * Land one machine in the `given-up` terminal state: summarized failure
- * reason, loop cleared, terminal event emitted. A fresh `connect` exits it.
- */
- private giveUp(machineId: MachineId, state: MachineState): void {
- const rec = state.reconnect
- this.stopReconnect(state)
- delete state.progress
- state.phase = 'given-up'
- const last = rec?.reasons[rec.reasons.length - 1] ?? state.lastError ?? 'connection failed'
- state.lastError = rec === undefined
- ? this.redacted(machineId, last)
- : this.redacted(machineId, `connect failed after ${rec.reasons.length} attempt(s): ${last}`)
- this.emit(machineId)
- this.deps.events.append(machineId, 'reconnect', state.lastError, { terminal: 'failed', reason: state.lastError })
- }
-
- /** Clear one machine's reconnect loop (timer and bookkeeping). */
- private stopReconnect(state: MachineState): void {
- if (state.reconnect?.timer !== undefined)
- clearTimeout(state.reconnect.timer)
- delete state.reconnect
- }
-
- /** @throws {SshError} `machine-reconnecting` while the reconnect loop owns the machine. */
- private refuseWhileReconnecting(machineId: MachineId, state: MachineState): void {
- const rec = state.reconnect
- if (rec === undefined)
- return
- throw new SshError(
- 'machine-reconnecting',
- machineId,
- `machine is reconnecting (attempt ${rec.attempt} of ${this.deps.config.reconnectMaxAttempts}); `
- + 'wait for the automatic retry or disconnect first',
- )
- }
-
- /** Scrub the profile's secret values out of any operator-facing text. */
- private redacted(machineId: MachineId, text: string): string {
- const profile = this.profiles.get(machineId)
- let out = text
- for (const secret of [profile?.password, profile?.passphrase]) {
- if (secret !== undefined && secret !== '')
- out = out.replaceAll(secret, '***')
- }
- return out
- }
-
- /**
- * One-shot remote dsh install (binary distribution): authenticate, probe
- * the platform, download/verify/install the missing runtime components
- * from the pinned release, copy the local API credentials into the remote
- * `~/.dsh/.env`, then hand off to {@link connect} automatically.
- * Idempotent while in flight. Refused while the reconnect loop owns the
- * machine.
- * @param machineId - the machine to install on.
- * @param signal - aborts the attempt.
- * @returns the install outcome.
- * @throws {SshError} on any failure (connect, install, or probe), or
- * `machine-reconnecting` while reconnecting.
- */
- async install(machineId: MachineId, signal?: AbortSignal): Promise<SshInstallResult> {
- const profile = this.requireProfile(machineId)
- const state = this.ensureState(machineId)
- this.refuseWhileReconnecting(machineId, state)
- if (state.installing === undefined) {
- state.progress = { phase: 'installing' }
- this.emit(machineId)
- const attempt = this.performInstall(machineId, profile, signal)
- state.installing = attempt.finally(() => {
- // The slot is only ever replaced while undefined, so the settling
- // attempt always owns it at this point.
- delete this.states.get(machineId)?.installing
- })
- }
- return state.installing
- }
-
- /**
- * One full install attempt. Publishes the terminal transition unless a
- * disconnect superseded the attempt; a successful install hands off to
- * {@link connect} (fire-and-forget — its outcome lands in the status).
- * The event stream settles on every failure — the install script's own
- * terminal event, or the catch for exception failures (probe, planner,
- * transport rejects, missing entry) that bypass it. A superseded attempt
- * (cancellation by an explicit disconnect) is the documented no-terminal
- * case. A failed install connection hands the machine to the reconnect
- * loop, like a failed connect.
- */
- private async performInstall(machineId: MachineId, profile: MachineProfile, signal?: AbortSignal): Promise<SshInstallResult> {
- const state = this.ensureState(machineId)
- const generation = state.generation
- const events = this.deps.events
- // The settling guard mirrors the connect path: the install script's own
- // failure path (and the success line below) settle the stream exactly
- // once; the catch below covers the exception failures that bypass them.
- let settled = false
- const onEvent: NonNullable<BootstrapHooks['onEvent']> = (stage, line, options) => {
- if (options?.terminal !== undefined)
- settled = true
- events.append(machineId, stage, line, options)
- }
- let session: SshSession
- try {
- session = await this.deps.transport.connect(profile, (label, key) => this.checkHostKey(MachineId(label), key), signal)
- }
- catch (error) {
- // The locally captured, redacted message: a superseded attempt must
- // not read state.lastError back — that slot may already belong to a
- // newer try.
- const message = this.redacted(machineId, describeSshFailure(error))
- if (generation === state.generation) {
- delete state.progress
- this.noteConnectFailure(machineId, message)
- this.beginReconnect(machineId)
- }
- throw new SshError('machine-connect-failed', machineId, message)
- }
- try {
- const installTimeoutMs = this.deps.config.installTimeoutMs
- onEvent('probe', '探测远端平台 (uname -srm)')
- const uname = await session.exec('uname -srm')
- if (uname.code !== 0) {
- throw new Error(`cannot probe remote platform: ${describeExecFailure(uname.code, uname.stderr)}`)
- }
- const plan = await (this.deps.planInstall ?? planRemoteInstall)(uname.stdout, this.deps.config)
- onEvent('probe', `远端平台 ${plan.os}/${plan.arch},安装源 ${plan.repo}${plan.dsh.kind === 'pkg-zip' ? ` tag ${plan.dsh.tag}` : ` npm ${plan.dsh.version}`}`)
- for (const note of plan.notes)
- onEvent('probe', note)
- const missing = missingComponentsOf((await session.exec(checkMissingCommand())).stdout)
- const skips: string[] = []
- if (missing.length > 0) {
- onEvent('probe', `缺失组件: ${missing.join(', ')}`)
- // The single install executor (shared with the connect-time
- // bootstrap): line-buffered stage streaming, the collected-stdout
- // fallback for tap-less transports, and its own settling failure.
- skips.push(...await runInstallScript(session, plan, installTimeoutMs, {
- onEvent,
- onProgress: (progress) => {
- if (generation !== state.generation)
- return
- state.progress = progress
- this.emit(machineId)
- },
- }, 'install 失败'))
- if (generation !== state.generation)
- throw new AttemptCancelled()
- }
- else {
- onEvent('probe', '三件套已就绪,跳过安装')
- }
- // The entry check doubles as $HOME expansion: the shell prints the
- // absolute path the type contract promises (never a literal `$HOME`).
- const dshExpr = `"$HOME/${REMOTE_ROOT}/dependencies/dsh/${plan.dshEntry}"`
- const entryCheck = await session.exec(`test -f ${dshExpr} && printf '%s\\n' ${dshExpr}`)
- const dshPath = firstLineOf(entryCheck.stdout)
- if (entryCheck.code !== 0 || dshPath === '') {
- throw new SshError(
- 'machine-dsh-missing',
- machineId,
- `dsh install finished on "${profile.host}" but the entry ${dshExpr} is not present`,
- )
- }
- let credentialsCopied = false
- let credentialsError: string | undefined
- try {
- credentialsCopied = await this.copyCredentials(session)
- }
- catch (error) {
- credentialsError = error instanceof Error ? error.message : String(error)
- }
- const dshRef = plan.dsh.kind === 'pkg-zip' ? plan.dsh.tag : `npm:${plan.dsh.version}`
- // The install operation settles here regardless of the connect handoff
- // that follows: S4 can tell "installed, connect pending" from a failed
- // install purely from the channel's terminal event. Skipped
- // verifications (fail-open checks) ride the settling line.
- onEvent('install', `dsh 安装成功 (${dshRef})${skippedVerificationSummary(plan.notes, skips)}`, { terminal: 'success' })
- await session.close().catch(() => undefined)
- if (generation === state.generation) {
- delete state.progress
- delete state.dshMissing
- delete state.lastError
- state.phase = 'disconnected'
- this.emit(machineId)
- // The operator's intent behind "install" is "connect": hand off and
- // let the connect plane report its own progress/outcome.
- void this.connect(machineId).catch(() => undefined)
- }
- return {
- installed: missing,
- dshRef,
- dshVersion: plan.dshVersion,
- dshPath,
- credentialsCopied,
- ...credentialsError === undefined ? {} : { credentialsError },
- }
- }
- catch (error) {
- await session.close().catch(() => undefined)
- if (error instanceof AttemptCancelled) {
- throw new SshError('machine-install-failed', machineId, 'install cancelled by disconnect')
- }
- // The locally captured message: a superseded attempt must not read
- // state.lastError back — that slot may already belong to a newer try.
- // 与其它失败路径对称地过脱敏(纵深防御:安装错误源今天不含 secret,
- // 但不留给未来调用方)。
- const message = this.redacted(machineId, error instanceof Error ? error.message : String(error))
- // Exception failures (platform probe, planner rejects such as
- // REMOTE_PLATFORM_UNSUPPORTED, transport exec rejects including the
- // install timeout, the missing entry) never reach the script's own
- // settling path: settle the channel here so S4 can tell a failed
- // install from a still-running one purely from the stream.
- if (generation === state.generation && !settled) {
- onEvent('failed', 'install 失败', { terminal: 'failed', reason: message })
- }
- if (generation === state.generation) {
- delete state.progress
- state.lastError = message
- state.phase = 'disconnected'
- this.emit(machineId)
- }
- if (error instanceof SshError)
- throw error
- throw new SshError('machine-install-failed', machineId, message)
- }
- }
-
- /**
- * Copy the local API credentials into the remote `~/.dsh/.env`, unless the
- * remote already carries a key (kept untouched). A failure to read the
- * local `.env` is not an error — it just reports `false`.
- * @param session - the authenticated session (install connection).
- * @returns whether the credentials were copied.
- */
- private async copyCredentials(session: SshSession): Promise<boolean> {
- const credentials = (this.deps.readEnvCredentials ?? defaultEnvCredentials)()
- const apiKey = credentials.apiKey
- if (apiKey === undefined)
- return false
- const result = await session.exec(credentialsCopyCommand({
- apiKey,
- ...credentials.baseUrl === undefined ? {} : { baseUrl: credentials.baseUrl },
- }))
- if (result.code !== 0) {
- throw new Error(`writing remote credentials failed: ${describeExecFailure(result.code, result.stderr)}`)
- }
- return result.stdout.includes('copied')
- }
-
- private emit(machineId: MachineId): void {
- this.deps.emitStatus(machineId, this.status(machineId))
- }
-}
-
-/** Redacted wire view of one profile. */
-export function profileView(profile: MachineProfile): MachineView {
- return {
- id: profile.id,
- name: profile.name,
- host: profile.host,
- port: profile.port,
- user: profile.user,
- hasPassword: profile.password !== undefined,
- hasPassphrase: profile.passphrase !== undefined,
- remotePort: profile.remotePort,
- ...profile.profileName === undefined ? {} : { profileName: profile.profileName },
- ...profile.startCommand === undefined ? {} : { startCommand: profile.startCommand },
- ...profile.color === undefined ? {} : { color: profile.color },
- ...profile.tintBorder === true ? { tintBorder: true } : {},
- }
-}
-
-/** One operator-facing fragment for an SSH transport failure. */
-export function describeSshFailure(error: unknown): string {
- const message = error instanceof Error ? error.message : String(error)
- if (message === '')
- return 'SSH connection failed'
- return message
-}
-
-/** The default local `.env` read: the harness home (`$DSH_HOME`, else `~/.dsh`). */
-function defaultEnvCredentials(): ReturnType<typeof readEnvCredentials> {
- return readEnvCredentials(join(process.env.DSH_HOME ?? join(homedir(), '.dsh'), '.env'))
-}
diff --git a/packages/dsh-tauri-ssh/src/host/service/session.ts b/packages/dsh-tauri-ssh/src/host/service/session.ts
new file mode 100644
index 00000000..c7779df6
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/session.ts
@@ -0,0 +1,11 @@
+import process from 'node:process'
+import { defineService } from 'dsh-tauri'
+
+export const session = defineService({
+ role(): { remote: boolean, origin?: string } {
+ const origin = process.env.DSH_REMOTE_SESSION_ORIGIN
+ return origin === undefined || origin === ''
+ ? { remote: false }
+ : { remote: true, origin }
+ },
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts b/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts
deleted file mode 100644
index 466dcdec..00000000
--- a/packages/dsh-tauri-ssh/src/host/service/ssh-config.ts
+++ /dev/null
@@ -1,390 +0,0 @@
-import type { MachineProfile } from '../types/index'
-/**
- * The host's own `~/.ssh` as the credential source: `ssh_config` parsing
- * (Host blocks, HostName/User/Port/IdentityFile, Include expansion), the
- * OpenSSH matching semantics (first matching pattern decides; first obtained
- * value per parameter; IdentityFile accumulates), and the resolver that turns
- * one machine profile into a concrete connection plan (connect host/port/user
- * plus the ordered identity files to try). Keys are read fresh on every
- * connect — a key added to `~/.ssh` is picked up without touching DSH.
- *
- * `ProxyJump` resolves to the ordered hop list (alias form `[user@]host[:port]`,
- * comma-separated for multi-hop; `none` disables); the transport walks it.
- * Deliberate subset: `Match` blocks, `ProxyCommand`, and agent forwarding are
- * out of scope; a host with no config match falls back to the profile fields
- * and the default identity files, exactly like a bare `ssh host` would.
- * @module dsh-tauri-ssh/host/service/ssh-config
- */
-
-import { readdirSync } from 'node:fs'
-import { readFile } from 'node:fs/promises'
-import process from 'node:process'
-import { join, sep } from 'pathe'
-
-/** Default identity file basenames, tried in order when no config `IdentityFile` exists. */
-export const DEFAULT_IDENTITY_FILES = ['id_ed25519', 'id_ecdsa', 'id_rsa']
-
-/** The config file name inside the ssh directory. */
-export const SSH_CONFIG_FILE = 'config'
-
-/** Recursion cap for `Include` chains; OpenSSH effectively has none, this one is for safety. */
-export const INCLUDE_DEPTH_LIMIT = 8
-
-/** One `Host` block: the patterns it applies to and the settings it carries. */
-export interface SshHostBlock {
- /** The `Host` pattern list of this block (may contain `!`, `*`, `?`). */
- patterns: string[]
- /** Settings keyed by lower-cased keyword; every keyword may appear multiple times. */
- values: Record<string, string[]>
-}
-
-/** The resolved per-host settings for one connection. */
-export interface SshHostSettings {
- /** `HostName` override; absent means "connect to the requested host directly". */
- hostName?: string
- /** `User` override. */
- user?: string
- /** `Port` override (parsed). */
- port?: number
- /** Every `IdentityFile` from the matching blocks, in order. */
- identityFiles: string[]
- /**
- * The `ProxyJump` hops (first obtained value wins, comma-split, `none`
- * filtered out); each entry is the raw `[user@]alias[:port]` token.
- */
- proxyJump: string[]
-}
-
-/** The concrete connection plan one machine profile resolves to. */
-export interface ResolvedSshAuth {
- /** The host to actually connect to. */
- host: string
- /** The TCP port to actually connect to. */
- port: number
- /** The login user name. */
- username: string
- /** The stored password fallback, when the profile carries one. */
- password?: string
- /** The identity files to try, in order, as raw file contents. */
- keys: Array<{ privateKey: string, passphrase?: string }>
- /** The resolved ProxyJump hop tokens (`[user@]alias[:port]`), in order; empty when direct. */
- proxyJump: string[]
-}
-
-/** Token expansion for `~`, `%d`, `%h`, `%r` in config paths (the OpenSSH subset). */
-export function expandTokenPath(path: string, homeDir: string, host: string, user: string): string {
- let out = expandPathTokens(path, homeDir, host, user)
- if (!out.startsWith('/')) {
- // ssh_config resolves bare relative IdentityFile paths under the home dir.
- out = join(homeDir, out)
- }
- return out
-}
-
-/** Expand `~`, `~/"`, `%d`, `%h`, `%r` without anchoring a bare relative path. */
-function expandPathTokens(path: string, homeDir: string, host: string, user: string): string {
- let out = path
- if (out === '~') {
- out = homeDir
- }
- else if (out.startsWith('~/')) {
- out = join(homeDir, out.slice(2))
- }
- return out.replaceAll('%d', homeDir).replaceAll('%h', host).replaceAll('%r', user)
-}
-
-/**
- * Whether one `Host` pattern matches a host name. `*` matches any run of
- * characters, `?` exactly one; the pattern may be comma-separated, each
- * alternative tried in order — the first one that matches decides, and a
- * leading `!` (negation) turns that decision into "no match". Case-insensitive,
- * like OpenSSH host names.
- */
-export function hostPatternMatches(pattern: string, host: string): boolean {
- const lowered = host.toLowerCase()
- for (const alternative of pattern.split(',')) {
- const negated = alternative.startsWith('!')
- const body = negated ? alternative.slice(1) : alternative
- if (globMatches(body.toLowerCase(), lowered))
- return !negated
- }
- return false
-}
-
-/** Match one glob (only `*` and `?`) against a string. */
-export function globMatches(glob: string, value: string): boolean {
- // A greedy two-pointer matcher: walk both strings, backtrack on `*`.
- let globIndex = 0
- let valueIndex = 0
- let starGlob = -1
- let starValue = -1
- while (valueIndex < value.length) {
- const g = glob[globIndex]
- if (g === '*') {
- starGlob = globIndex
- starValue = valueIndex
- globIndex += 1
- }
- else if (g === '?' || g === value[valueIndex]) {
- globIndex += 1
- valueIndex += 1
- }
- else if (starGlob !== -1) {
- globIndex = starGlob + 1
- starValue += 1
- valueIndex = starValue
- }
- else {
- return false
- }
- }
- while (glob[globIndex] === '*') globIndex += 1
- return globIndex === glob.length
-}
-
-/**
- * Parse one ssh_config document into `Host` blocks. Keywords are
- * case-insensitive; `#` starts a comment; `key value` and `key=value` both
- * parse. Only `Host` opens a block; a top-level `Include` (before any `Host`)
- * becomes a synthetic pattern-less block the loader expands in place. Other
- * lines outside any block are dropped (OpenSSH applies them to every host,
- * but the common `Host *` form parses the same way).
- */
-export function parseSshConfig(text: string): SshHostBlock[] {
- const blocks: SshHostBlock[] = []
- let current: SshHostBlock | undefined
- for (const rawLine of text.split('\n')) {
- const line = rawLine.replace(/#.*$/u, '').trim()
- if (line === '')
- continue
- const equals = line.indexOf('=')
- // The line is non-blank, so the split always yields a first token.
- const key = (equals === -1 ? line.split(/\s+/u)[0]! : line.slice(0, equals)).trim().toLowerCase()
- if (key === '')
- continue
- const value = equals === -1
- ? line.slice(key.length).trim()
- : line.slice(equals + 1).trim()
- if (value === '')
- continue
- if (key === 'host') {
- current = {
- patterns: value.split(/\s+/u).filter(part => part !== ''),
- values: {},
- }
- blocks.push(current)
- continue
- }
- if (current === undefined) {
- if (key === 'include') {
- current = { patterns: [], values: {} }
- blocks.push(current)
- }
- else {
- continue
- }
- }
- const values = current.values[key] ?? (current.values[key] = [])
- values.push(value)
- }
- return blocks
-}
-
-/**
- * Resolve one host name against parsed blocks, with the OpenSSH rules: a
- * block applies when its first matching pattern decides (a matching negation
- * excludes the block), the first obtained value per parameter wins, and
- * `IdentityFile` accumulates across all matching blocks.
- */
-export function lookupSshConfig(blocks: SshHostBlock[], host: string): SshHostSettings {
- const settings: SshHostSettings = { identityFiles: [], proxyJump: [] }
- for (const block of blocks) {
- const applies = block.patterns.some(pattern => hostPatternMatches(pattern, host))
- if (!applies)
- continue
- const hostname = block.values.hostname?.[0]
- if (settings.hostName === undefined && hostname !== undefined) {
- settings.hostName = hostname
- }
- const user = block.values.user?.[0]
- if (settings.user === undefined && user !== undefined) {
- settings.user = user
- }
- const port = block.values.port?.[0]
- if (settings.port === undefined && port !== undefined) {
- settings.port = Number(port)
- }
- if (block.values.identityfile !== undefined) {
- settings.identityFiles.push(...block.values.identityfile)
- }
- if (settings.proxyJump.length === 0 && block.values.proxyjump !== undefined) {
- settings.proxyJump = block.values.proxyjump[0]!
- .split(',')
- .map(token => token.trim())
- .filter(token => token !== '' && token.toLowerCase() !== 'none')
- }
- }
- return settings
-}
-
-/**
- * The literal `Host` aliases worth surfacing as machines: every pattern token
- * that names one concrete host — no `*`/`?` wildcards, no `!` negation, no
- * comma alternation. Multi-pattern entries contribute each literal token;
- * the result is deduplicated and sorted.
- */
-export function discoverableHosts(blocks: SshHostBlock[]): string[] {
- const hosts = new Set<string>()
- for (const block of blocks) {
- for (const pattern of block.patterns) {
- if (pattern === '' || /[?*,!]/u.test(pattern))
- continue
- hosts.add(pattern)
- }
- }
- return [...hosts].sort()
-}
-
-/**
- * Expand one `Include` path into the file paths it names (sorted, missing
- * targets dropped). OpenSSH anchors relative paths under the ssh directory
- * (the user config home) and globs the basename.
- */
-export function expandIncludePath(path: string, sshDir: string, homeDir: string, host: string, user: string): string[] {
- let expanded = expandPathTokens(path, homeDir, host, user)
- if (!expanded.startsWith('/'))
- expanded = join(sshDir, expanded)
- // The path is absolute by now, so a separator always exists.
- const slash = expanded.lastIndexOf(sep)
- const dir = expanded.slice(0, slash)
- const basename = expanded.slice(slash + 1)
- if (!/[?*]/u.test(basename))
- return [expanded]
- // Basename globs only (the common `Include ~/.ssh/config.d/*` shape);
- // readdirSyncSafe never throws, an unreadable directory reads as empty.
- return readdirSyncSafe(dir)
- .filter(name => globMatches(basename, name))
- .sort()
- .map(name => join(dir, name))
-}
-
-/** One synchronous directory listing; failures read as an empty list. */
-function readdirSyncSafe(dir: string): string[] {
- try {
- return readdirSync(dir)
- }
- catch {
- return []
- }
-}
-
-/**
- * Load every `Host` block reachable from the ssh config, following `Include`
- * chains (depth-capped, cycle-safe, missing targets silently skipped).
- * @param sshDir - the ssh directory (defaults to `~/.ssh`).
- * @param homeDir - the home directory for `~` expansion.
- * @returns the concatenated blocks, outermost first.
- */
-export async function loadSshConfigBlocks(sshDir: string, homeDir: string): Promise<SshHostBlock[]> {
- const blocks: SshHostBlock[] = []
- const visited = new Set<string>()
- await collectConfigBlocks(sshDir, homeDir, join(sshDir, SSH_CONFIG_FILE), 0, visited, blocks)
- return blocks
-}
-
-/** One recursive leg of {@link loadSshConfigBlocks}. */
-async function collectConfigBlocks(
- sshDir: string,
- homeDir: string,
- file: string,
- depth: number,
- visited: Set<string>,
- out: SshHostBlock[],
-): Promise<void> {
- if (depth > INCLUDE_DEPTH_LIMIT || visited.has(file))
- return
- visited.add(file)
- let text: string
- try {
- text = await readFile(file, 'utf8')
- }
- catch {
- return
- }
- for (const block of parseSshConfig(text)) {
- const includes = block.values.include
- if (includes === undefined) {
- out.push(block)
- continue
- }
- // OpenSSH splices include content in place: a Host block that carries an
- // Include keeps its own settings (the Include keyword is not itself a
- // setting), and the included files' blocks follow it. A synthetic
- // pattern-less block (top-level Include) contributes only its includes.
- if (block.patterns.length > 0) {
- const { include: _dropped, ...values } = block.values
- out.push({ patterns: block.patterns, values })
- }
- for (const path of includes) {
- for (const target of expandIncludePath(path, sshDir, homeDir, '', '')) {
- await collectConfigBlocks(sshDir, homeDir, target, depth + 1, visited, out)
- }
- }
- }
-}
-
-/**
- * The credential resolver: reads the host's `~/.ssh` and turns one machine
- * profile into the concrete connection plan. Pure file access — no network,
- * no ssh2 — so tests drive it with a scratch ssh directory.
- */
-export class SshConfigResolver {
- /**
- * @param sshDir - the ssh directory holding `config` and the identity files.
- * @param homeDir - the home directory used for `~` expansion.
- * @param defaultUser - the OS user name used when neither the profile nor
- * the config names a user (what a bare `ssh` would log in as).
- */
- constructor(
- private readonly sshDir: string,
- private readonly homeDir: string,
- private readonly defaultUser: string = process.env.USER ?? '',
- ) {}
-
- /**
- * Resolve one machine profile into the connection plan.
- * @param profile - the machine profile to connect.
- * @returns the host/port/user to connect and the ordered credentials.
- */
- async resolve(profile: MachineProfile): Promise<ResolvedSshAuth> {
- const blocks = await loadSshConfigBlocks(this.sshDir, this.homeDir)
- const settings = lookupSshConfig(blocks, profile.host)
- const username = profile.user !== '' ? profile.user : settings.user ?? this.defaultUser
- const host = settings.hostName ?? profile.host
- const port = settings.port ?? profile.port
- const passphrase = profile.passphrase === undefined || profile.passphrase === '' ? undefined : profile.passphrase
- const password = profile.password === undefined || profile.password === '' ? undefined : profile.password
- const identityPaths = settings.identityFiles.length > 0
- ? settings.identityFiles
- : DEFAULT_IDENTITY_FILES.map(name => join(this.sshDir, name))
- const keys: ResolvedSshAuth['keys'] = []
- for (const path of identityPaths) {
- const expanded = expandTokenPath(path, this.homeDir, host, username)
- try {
- const privateKey = await readFile(expanded, 'utf8')
- keys.push({ privateKey, ...passphrase === undefined ? {} : { passphrase } })
- }
- catch {
- // Missing or unreadable identity files are skipped, like ssh does.
- }
- }
- return {
- host,
- port,
- username,
- keys,
- proxyJump: settings.proxyJump,
- ...password === undefined ? {} : { password },
- }
- }
-}
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.ts b/packages/dsh-tauri-ssh/src/host/service/state.ts
new file mode 100644
index 00000000..feaf5c9b
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/state.ts
@@ -0,0 +1,46 @@
+import type { MachineId, MachineProfile } from '../types/index'
+import type { SshState } from './state.types'
+import { defineService } from 'dsh-tauri'
+import { machineTable } from '../config/runtime'
+import { storage } from '../storage/index'
+import { parseStateDocument } from './state.utils'
+
+const DOCUMENT_KEY = 'state'
+const STATE_VERSION = 1
+
+export const state = defineService({
+ async load(): Promise<SshState> {
+ const parsed = parseStateDocument(await storage.getItem(DOCUMENT_KEY))
+ machineTable.enabled = parsed.enabled
+ machineTable.machines = new Map(Object.entries(parsed.machines).map(([key, profile]) => [key as MachineId, profile]))
+ return parsed
+ },
+
+ async save(profile: MachineProfile): Promise<void> {
+ machineTable.machines.set(profile.id, profile)
+ await persist()
+ },
+
+ async remove(machineId: MachineId): Promise<void> {
+ if (!machineTable.machines.delete(machineId))
+ return
+ await persist()
+ },
+
+ async setEnabled(enabled: boolean): Promise<void> {
+ if (machineTable.enabled === enabled)
+ return
+ machineTable.enabled = enabled
+ await persist()
+ },
+})
+
+// --- internal ---
+
+async function persist(): Promise<void> {
+ await storage.setItem(DOCUMENT_KEY, {
+ version: STATE_VERSION,
+ enabled: machineTable.enabled,
+ machines: Object.fromEntries(machineTable.machines),
+ })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.types.ts b/packages/dsh-tauri-ssh/src/host/service/state.types.ts
new file mode 100644
index 00000000..9a36a248
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/state.types.ts
@@ -0,0 +1,6 @@
+import type { MachineProfile } from '../types/index'
+
+export interface SshState {
+ enabled: boolean
+ machines: Record<string, MachineProfile>
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/state.utils.ts b/packages/dsh-tauri-ssh/src/host/service/state.utils.ts
new file mode 100644
index 00000000..ef82565e
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/state.utils.ts
@@ -0,0 +1,47 @@
+import type { MachineProfile } from '../types/index'
+import type { SshState } from './state.types'
+import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
+import { MachineId as brandMachineId } from '../types/index'
+
+export function machineProfileOf(raw: unknown): MachineProfile | undefined {
+ if (typeof raw !== 'object' || raw === null)
+ return undefined
+ const value = raw as Record<string, unknown>
+ if (typeof value.id !== 'string' || value.id === '')
+ return undefined
+ if (typeof value.name !== 'string')
+ return undefined
+ if (typeof value.host !== 'string' || value.host === '')
+ return undefined
+ if (typeof value.user !== 'string')
+ return undefined
+ return {
+ id: brandMachineId(value.id),
+ name: value.name,
+ host: value.host,
+ port: typeof value.port === 'number' ? value.port : DEFAULT_SSH_PORT,
+ user: value.user,
+ remotePort: typeof value.remotePort === 'number' ? value.remotePort : DEFAULT_REMOTE_PORT,
+ ...typeof value.password === 'string' && value.password !== '' ? { password: value.password } : {},
+ ...typeof value.passphrase === 'string' && value.passphrase !== '' ? { passphrase: value.passphrase } : {},
+ ...typeof value.profileName === 'string' && value.profileName !== '' ? { profileName: value.profileName } : {},
+ ...typeof value.startCommand === 'string' && value.startCommand !== '' ? { startCommand: value.startCommand } : {},
+ ...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},
+ ...value.tintBorder === true ? { tintBorder: true } : {},
+ }
+}
+
+export function parseStateDocument(raw: unknown): SshState {
+ if (typeof raw !== 'object' || raw === null)
+ return { enabled: false, machines: {} }
+ const record = raw as { enabled?: unknown, machines?: unknown }
+ const machines: Record<string, MachineProfile> = {}
+ if (typeof record.machines === 'object' && record.machines !== null) {
+ for (const [key, raw] of Object.entries(record.machines as Record<string, unknown>)) {
+ const profile = machineProfileOf(raw)
+ if (profile !== undefined && profile.id === key)
+ machines[key] = profile
+ }
+ }
+ return { enabled: record.enabled === true, machines }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
index 25cd373d..93a1e0f5 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts
@@ -1,12 +1,19 @@
-import type { SshExecResult, SshSession } from './transport'
+import type { Config } from '../config/schema'
+import type { SshExecResult, SshSession } from '../types/index'
+import type { SyncSkillScan } from './sync.types'
import { Buffer } from 'node:buffer'
-import { describe, expect, it, vi } from 'vitest'
-import { DEFAULT_REMOTE_PROFILE } from '../storage/index'
+import { tmpdir } from 'node:os'
+import { join } from 'pathe'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { DEFAULT_REMOTE_PROFILE } from '../config/constants'
+import { clearHostRuntime, machineTable, setHostConfig, setMachineDeps, setSyncDeps } from '../config/runtime'
import { MachineId } from '../types/index'
-import { layoutNodeBinary } from './bootstrap'
-import { buildPreview, classifySpec, installSpecOf, pluginAddCommand, skillExtractCommand, SyncEngine } from './sync'
+import { EMPTY_ALLOWLIST } from '../utils/allowlist'
+import { layoutNodeBinary } from './bootstrap.utils'
+import { machine } from './machine'
+import { sync } from './sync'
+import { buildPreview, classifySpec, installSpecOf, pluginAddCommand, skillExtractCommand } from './sync.utils'
-/** A scripted SSH session: commands dispatched by order or by matcher. */
function fakeSession(respond: (command: string, options?: { stdinData?: Buffer }) => SshExecResult): SshSession & { execSpy: ReturnType<typeof vi.fn>, closed: () => boolean } {
let open = true
const execSpy = vi.fn(async (command: string, options?: { stdinData?: Buffer }) => respond(command, options))
@@ -105,8 +112,57 @@ describe('command builders', () => {
})
})
+const SSH_DIR = join(tmpdir(), 'dsh-ssh-sync-test', '.ssh')
+
+const HOST_CONFIG: Config = {
+ connectTimeoutMs: 1_000,
+ healthCheckTimeoutMs: 1_000,
+ healthPollIntervalMs: 10,
+ healthPollAttempts: 1,
+ keepaliveIntervalMs: 10_000,
+ keepaliveCountMax: 3,
+ reconnectInitialDelayMs: 1,
+ reconnectMaxDelayMs: 1,
+ reconnectMaxAttempts: 1,
+ sshDir: SSH_DIR,
+ statePath: join(tmpdir(), 'dsh-ssh-sync-test', 'machines.json'),
+ knownHostsPath: join(tmpdir(), 'dsh-ssh-sync-test', 'known-hosts.json'),
+}
+
describe('syncEngine.apply', () => {
- const machine = MachineId('m1')
+ const machineId = MachineId('m1')
+
+ interface Wiring {
+ connect: () => Promise<SshSession>
+ profileDependencies?: () => Record<string, string>
+ scanSkills?: () => SyncSkillScan[]
+ packSkills?: (dir: string, names: readonly string[]) => Promise<Buffer>
+ profileName?: string
+ }
+
+ function seed(wiring: Wiring): void {
+ clearHostRuntime()
+ setHostConfig(HOST_CONFIG)
+ setMachineDeps({ transport: { connect: wiring.connect }, emitStatus: () => {}, localAllowlist: () => EMPTY_ALLOWLIST })
+ setSyncDeps({
+ profileDependencies: wiring.profileDependencies ?? (() => ({})),
+ scanSkills: wiring.scanSkills ?? (() => []),
+ packSkills: wiring.packSkills ?? (async () => Buffer.alloc(0)),
+ })
+ machineTable.machines.set(machineId, {
+ id: machineId,
+ name: 'm1',
+ host: 'e2e-host',
+ port: 22,
+ user: 'root',
+ remotePort: 3080,
+ ...wiring.profileName === undefined ? {} : { profileName: wiring.profileName },
+ })
+ }
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
it('returns per-item successes when everything lands', async () => {
const session = fakeSession((command) => {
@@ -116,14 +172,12 @@ describe('syncEngine.apply', () => {
return ok()
})
const packSkills = vi.fn(async () => Buffer.from('TARDATA'))
- const openSession = vi.fn(async () => session)
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
+ seed({
+ connect: async () => session,
scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
packSkills,
- openSession,
})
- const result = await sync.apply(machine, [{ name: 'p1', spec: 'github:a/b' }], [{ name: 'alpha', root: 'dsh' }])
+ const result = await sync.apply(machineId, [{ name: 'p1', spec: 'github:a/b' }], [{ name: 'alpha', root: 'dsh' }])
expect(result.items).toEqual([
{ kind: 'plugin', name: 'p1', ok: true },
{ kind: 'skill', name: 'alpha', root: 'dsh', ok: true },
@@ -142,14 +196,9 @@ describe('syncEngine.apply', () => {
return ok('/home/u/.dsh-desktop/dependencies/dsh/lib/bin.js\n')
return command.includes('bad-pkg') ? fail('ERR_PNPM_NO_MATCH') : ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
+ seed({ connect: async () => session })
const result = await sync.apply(
- machine,
+ machineId,
[
{ name: 'good', spec: 'github:a/good' },
{ name: 'bad', spec: 'npm:bad-pkg' },
@@ -163,13 +212,8 @@ describe('syncEngine.apply', () => {
it('fails every plugin item when the remote has no dsh entry', async () => {
const session = fakeSession(() => ok('\n'))
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [])
+ seed({ connect: async () => session })
+ const result = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
expect(result.items).toHaveLength(1)
expect(result.items[0]).toMatchObject({ ok: false, error: expect.stringContaining('no dsh entry') })
})
@@ -179,13 +223,12 @@ describe('syncEngine.apply', () => {
const packSkills = vi.fn(async () => {
throw new Error('tar failed: disk full')
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
+ seed({
+ connect: async () => session,
scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
packSkills,
- openSession: async () => session,
})
- const result = await sync.apply(machine, [], [
+ const result = await sync.apply(machineId, [], [
{ name: 'ghost', root: 'dsh' },
{ name: 'alpha', root: 'dsh' },
])
@@ -201,13 +244,12 @@ describe('syncEngine.apply', () => {
return fail('cannot write: read-only file system')
return ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
+ seed({
+ connect: async () => session,
scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha', 'beta'] }],
packSkills: async () => Buffer.from('TAR'),
- openSession: async () => session,
})
- const result = await sync.apply(machine, [], [
+ const result = await sync.apply(machineId, [], [
{ name: 'alpha', root: 'dsh' },
{ name: 'beta', root: 'dsh' },
])
@@ -220,19 +262,18 @@ describe('syncEngine.apply', () => {
it('dedupes repeated selections and skips the session for an empty selection', async () => {
const session = fakeSession(() => ok('/dsh\n'))
- const openSession = vi.fn(async () => session)
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
+ const connect = vi.fn(async () => session)
+ seed({
+ connect,
scanSkills: () => [{ root: 'dsh', dir: '/root/skills', names: ['alpha'] }],
packSkills: async () => Buffer.alloc(0),
- openSession,
})
- const empty = await sync.apply(machine, [], [])
+ const empty = await sync.apply(machineId, [], [])
expect(empty.items).toEqual([])
- expect(openSession).not.toHaveBeenCalled()
+ expect(connect).not.toHaveBeenCalled()
const deduped = await sync.apply(
- machine,
+ machineId,
[{ name: 'p', spec: 'github:a/b' }, { name: 'p again', spec: 'github:a/b' }],
[{ name: 'alpha', root: 'dsh' }, { name: 'alpha', root: 'dsh' }],
)
@@ -258,13 +299,8 @@ describe('syncEngine.apply', () => {
'dsh: git-hosted plugins build on install via their prepare script, which pnpm blocks until allowed — add the exact key pnpm printed above',
].join('\n')
const session = fakeSession(command => command.includes('printf') ? ok('/dsh\n') : { code: 1, stdout, stderr })
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- const result = await sync.apply(machine, [{ name: 'dsh-better-sidebar', spec: 'github:a/b' }], [], { profileName: 'remote' })
+ seed({ connect: async () => session, profileName: 'remote' })
+ const result = await sync.apply(machineId, [{ name: 'dsh-better-sidebar', spec: 'github:a/b' }], [])
const item = result.items[0]!
expect(item.ok).toBe(false)
// 头一条是真正的原因(缺 make/g++ 的编译失败),且不掺末尾那句会误导人的通用指引
@@ -282,23 +318,14 @@ describe('syncEngine.apply', () => {
it('caps the carried output and skips it on success', async () => {
const huge = Array.from({ length: 200 }, (_, index) => `line ${index}`).join('\n')
const session = fakeSession(command => command.includes('printf') ? ok('/dsh\n') : { code: 1, stdout: huge, stderr: '' })
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- const failed = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })
+ seed({ connect: async () => session, profileName: 'remote' })
+ const failed = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
expect(failed.items[0]?.log?.split('\n').length).toBe(60)
expect(failed.items[0]?.log).toContain('line 199')
const healthy = fakeSession(() => ok('/dsh\n'))
- const fine = await new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => healthy,
- }).apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })
+ seed({ connect: async () => healthy, profileName: 'remote' })
+ const fine = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
expect(fine.items[0]?.log).toBeUndefined()
})
@@ -309,24 +336,39 @@ describe('syncEngine.apply', () => {
if (command.includes('printf'))
return ok('/dsh\n')
if (command.includes('pnpm-workspace.yaml') && command.startsWith('cat '))
- return ok('packages:\n - .\n')
+ return ok('packages:\n - .\nallowBuilds:\n existing: true\n keep-blocked: false\n')
if (command.includes('plugin --profile')) {
installs += 1
return installs === 1 ? fail(guidance) : ok()
}
return ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })
+ seed({ connect: async () => session, profileName: 'remote' })
+ const result = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
expect(result.items).toEqual([{ kind: 'plugin', name: 'p', ok: true }])
expect(installs).toBe(2)
const write = session.execSpy.mock.calls.map(([command]) => command).find(command => command.includes('> "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml"'))
expect(write).toContain('p@https://example.com/p.tar.gz/abc')
+ expect(write).toContain('existing: true')
+ expect(write).toContain('keep-blocked: false')
+ })
+
+ it('does not rewrite the workspace or retry when the requested build key is already allowed', async () => {
+ const session = fakeSession((command) => {
+ if (command.includes('printf'))
+ return ok('/dsh\n')
+ if (command.includes('pnpm-workspace.yaml') && command.startsWith('cat '))
+ return ok('allowBuilds:\n p: true\n')
+ return command.includes('plugin --profile') ? fail('allowBuilds:\n p: true\n') : ok()
+ })
+ seed({ connect: async () => session, profileName: 'remote' })
+ const result = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
+ expect(result.items[0]).toMatchObject({ ok: false })
+ const commands = session.execSpy.mock.calls.map(([command]) => command)
+ expect(commands.filter(command => command.includes('plugin --profile'))).toHaveLength(1)
+ expect(commands.filter(command => command.includes('pnpm-workspace.yaml'))).toEqual([
+ 'cat "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml" 2>/dev/null || true',
+ ])
})
it('reports the original failure when pnpm names no build key', async () => {
@@ -335,13 +377,8 @@ describe('syncEngine.apply', () => {
return ok('/dsh\n')
return command.includes('plugin --profile') ? fail('ERR_PNPM_NO_MATCH') : ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })
+ seed({ connect: async () => session, profileName: 'remote' })
+ const result = await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
expect(result.items[0]).toMatchObject({ ok: false })
expect(result.items[0]?.error).toContain('ERR_PNPM_NO_MATCH')
expect(session.execSpy.mock.calls.filter(([command]) => command.includes('pnpm-workspace.yaml'))).toHaveLength(0)
@@ -353,13 +390,8 @@ describe('syncEngine.apply', () => {
return ok('/dsh\n')
return ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- await sync.apply(machine, [{ name: 'dshmarket', spec: '^1.31.1' }], [])
+ seed({ connect: async () => session })
+ await sync.apply(machineId, [{ name: 'dshmarket', spec: '^1.31.1' }], [])
const add = session.execSpy.mock.calls.map(([command]) => command).find(command => command.includes('plugin --profile'))
expect(add).toContain('add \'dshmarket@^1.31.1\'')
})
@@ -370,13 +402,8 @@ describe('syncEngine.apply', () => {
return ok('/dsh\n')
return ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
- scanSkills: () => [],
- packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
- })
- await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'work' })
+ seed({ connect: async () => session, profileName: 'work' })
+ await sync.apply(machineId, [{ name: 'p', spec: 'github:a/b' }], [])
const add = session.execSpy.mock.calls.map(([command]) => command).find(command => command.includes('plugin --profile'))
expect(add).toContain('--profile \'work\' add')
})
@@ -387,21 +414,23 @@ describe('syncEngine.apply', () => {
return ok('/dsh\n')
return ok()
})
- const sync = new SyncEngine({
- profileDependencies: () => ({}),
+ seed({
+ connect: async () => session,
scanSkills: () => [
{ root: 'dsh', dir: '/root/dsh-skills', names: ['alpha', 'beta'] },
{ root: 'agents', dir: '/root/agent-skills', names: ['gamma'] },
],
packSkills: async () => Buffer.alloc(0),
- openSession: async () => session,
})
const seen: string[] = []
+ vi.spyOn(machine, 'setProgress').mockImplementation((_machineId, progress) => {
+ if (progress !== undefined)
+ seen.push(`${progress.attempt}/${progress.total}:${progress.item}`)
+ })
await sync.apply(
- machine,
+ machineId,
[{ name: 'p1', spec: 'github:a/b' }, { name: 'p1 dup', spec: 'github:a/b' }, { name: 'p2', spec: '^1.0.0' }],
[{ name: 'alpha', root: 'dsh' }, { name: 'beta', root: 'dsh' }, { name: 'ghost', root: 'dsh' }, { name: 'gamma', root: 'agents' }],
- { onItem: (position, total, name) => seen.push(`${position}/${total}:${name}`) },
)
// 去重后 2 插件 + 4 skill;ghost 在本地校验出局(不公告但照样结算),
// 每个 root 的 skill 共用一份 tar,故只公告批首那条。
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.ts
index 9db5ff5e..d0572283 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts
@@ -1,423 +1,178 @@
-/**
- * Plugin & skill sync (local → one remote machine): the S4-owned `sync.*`
- * surface behind `/api-ssh`. `preview` reads the local dsh profile's plugin
- * dependencies and the user-level skill roots; `apply` installs the selected
- * plugins on the remote (`<dsh> plugin --profile web add <spec>`, one exec
- * per plugin so every item earns its own outcome) and streams the selected
- * skills as a tarball over the command's stdin (`tar -xf -`). The apply
- * result is deliberately per-item — a partial failure must never hide
- * behind a batched error string (the defect this panel was rebuilt to fix).
- * Command builders are pure functions; the engine's fs/ssh seams are
- * injectable so tests never touch the network.
- * @module dsh-tauri-ssh/host/service/sync
- */
-
import type { Buffer } from 'node:buffer'
-import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index'
-import type { SshSession } from './transport'
-import { DEFAULT_REMOTE_PROFILE } from '../storage/index'
-import { allowlistReadCommand, allowlistWriteCommand, mergeWorkspaceAllowlist, parseBuildAllowKeys } from './allowlist'
-import { dshEntryProbeCommand, firstLineOf, layoutBinDir, layoutNodeBinary } from './bootstrap'
-import { shQuote } from './transport'
-
-export { DEFAULT_REMOTE_PROFILE as REMOTE_PLUGIN_PROFILE } from '../storage/index'
-
-/** How many output lines an item failure carries (the operator-facing tail). */
-const FAILURE_TAIL_LINES = 5
-
-/** How many cause lines the headline carries: the earliest ones are the root cause. */
-const FAILURE_CAUSE_LINES = 2
-
-/** The lines a cause is picked from: every real error signature pnpm/node-gyp emit. */
-const FAILURE_CAUSE = /ERR_PNPM_|gyp ERR!|error:|Error:|Error \d|not ok|not found|No such file|Permission denied|exit code|Command failed|ELIFECYCLE/u
-
-/** The full output an item carries for on-demand display (lines, then bytes). */
-const FAILURE_LOG_LINES = 60
-const FAILURE_LOG_BYTES = 8000
-
-/**
- * The desktop's own bundled plugins (`dsh-tauri*`). They ride the connect-time
- * bundle sync automatically, so the manual sync list must not offer them:
- * their `link:` specs are local paths that could never resolve remotely, and
- * listing them as "not syncable" reads as a defect rather than a fact.
- */
-const BUNDLED_PLUGIN_NAME = /^dsh-tauri(?:-|$)/u
-
-/** Classify one dependency spec: can a remote `dsh plugin add` resolve it? */
-export function classifySpec(spec: string): { syncable: boolean, reason?: string } {
- const value = spec.trim()
- if (value === '')
- return { syncable: false, reason: 'empty dependency spec' }
- if (/^(?:github:|git\+|git@)/u.test(value))
- return { syncable: true }
- if (/^(?:file:|link:|workspace:)/u.test(value))
- return { syncable: false, reason: 'local-path dependency; it cannot be resolved on the remote' }
- if (/^https?:\/\//u.test(value))
- return { syncable: false, reason: 'URL dependencies are not supported' }
- // Anything else is an npm version spec (^1.0.0, 0.16.0, latest, …).
- return { syncable: true }
-}
-
-/**
- * Build the preview from the local sources: profile dependencies minus the
- * `@deepseek-ai/` core packages (the remote release ships those) and minus
- * {@link BUNDLED_PLUGIN_NAME} (they sync with the bundle automatically), plus
- * the scanned skill roots. Both halves sorted by name for a stable panel order.
- * @param dependencies - the profile package.json dependency map.
- * @param skillRoots - per root, the SKILL.md directory names found locally.
- * @returns the preview payload.
- */
-export function buildPreview(dependencies: Record<string, string>, skillRoots: ReadonlyArray<{ root: SyncSkillRoot, names: readonly string[] }>): SyncPreview {
- const plugins: SyncPluginItem[] = Object.entries(dependencies)
- .filter(([name]) => !name.startsWith('@deepseek-ai/') && !BUNDLED_PLUGIN_NAME.test(name))
- .map(([name, spec]) => {
- const verdict = classifySpec(spec)
- return {
- name,
- spec,
- syncable: verdict.syncable,
- ...verdict.reason === undefined ? {} : { reason: verdict.reason },
- }
- })
- .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
- const skills: SyncSkillItem[] = []
- for (const entry of skillRoots) {
- for (const name of [...entry.names].sort()) {
- skills.push({ name, root: entry.root })
- }
- }
- return { plugins, skills }
-}
-
-/**
- * The `dsh plugin add` argument for one profile dependency: a git spec is a
- * complete locator on its own, while a version spec (`^1.0.0`, `latest`) only
- * means something together with the package name — passing the bare range
- * makes pnpm reject the install.
- */
-export function installSpecOf(name: string, spec: string): string {
- const value = spec.trim()
- return /^(?:github:|git\+|git@)/u.test(value) ? value : `${name}@${value}`
-}
-
-/**
- * The remote plugin-install command for one dependency (dsh add is
- * pnpm-backed). The dsh entry is a Node script in the binary layout, so it
- * always runs under the layout's Node binary (never a bare `dsh` from the
- * login PATH).
- * @param dshEntry - the absolute entry path the layout probe resolved.
- * @param target - the install argument, see {@link installSpecOf}.
- * @param profileName - the remote profile to install into.
- * @returns the shell command line.
- */
-export function pluginAddCommand(dshEntry: string, target: string, profileName: string = DEFAULT_REMOTE_PROFILE): string {
- // `dsh plugin add` spawns a bare `pnpm`: the layout bin dir carries the
- // shim the connect pipeline writes (see `ensurePnpmCommand`), so prepend it
- // to PATH for this command only.
- return `PATH="${layoutBinDir()}:$PATH" ${layoutNodeBinary()} ${shQuote(dshEntry)} plugin --profile ${shQuote(profileName)} add ${shQuote(target)}`
-}
-
-/** The remote skill-extract command; the tarball arrives on its stdin. */
-export function skillExtractCommand(): string {
- return `mkdir -p "$HOME/.dsh/skills" && tar -xf - -C "$HOME/.dsh/skills"`
-}
-
-/**
- * The lines of one command's output, trimmed, blanks dropped.
- * @param stdout - captured stdout.
- * @param stderr - captured stderr.
- * @returns stdout lines first, then stderr lines.
- */
-function outputLines(stdout: string, stderr: string): string[] {
- return `${stdout}\n${stderr}`.split('\n').map(line => line.trim()).filter(line => line !== '')
-}
-
-/**
- * One operator-facing failure for a finished remote command.
- *
- * The headline names the *cause* first: a multi-minute install buries the real
- * error (`gyp ERR! stack Error: make failed…`, `ERR_PNPM_PREPARE_PACKAGE`) well
- * above the last few lines, and the sweeping guidance pnpm/dsh print last is
- * generic — reading only the tail tells the operator the wrong story. The tail
- * still rides along as context, and the full output travels in the item's
- * `log` for on-demand display.
- * @param code - the command's exit code.
- * @param stdout - captured stdout.
- * @param stderr - captured stderr.
- * @returns the operator-facing message.
- */
-function describeFailure(code: number | null, stdout: string, stderr: string): string {
- const lines = outputLines(stdout, stderr)
- // 有原因行就只报原因(最早的几条=根因),不再掺末尾的通用指引——那句往往
- // 与真实原因无关(真机案例:构建门禁已放行,末尾仍在讲门禁,真因是缺 g++)。
- const causes = lines.filter(line => FAILURE_CAUSE.test(line)).slice(0, FAILURE_CAUSE_LINES)
- const picked = causes.length > 0 ? causes : lines.slice(-FAILURE_TAIL_LINES)
- const parts = picked.map(line => (line.length > 300 ? `${line.slice(0, 300)}…` : line))
- return `exit ${code ?? '?'}${parts.length === 0 ? '' : `: ${parts.join(' | ')}`}`
-}
-
-/** The trimmed full output an item keeps for on-demand display (newest kept). */
-function failureLogOf(stdout: string, stderr: string): string | undefined {
- const lines = outputLines(stdout, stderr)
- if (lines.length === 0)
- return undefined
- const kept = lines.slice(-FAILURE_LOG_LINES).join('\n')
- return kept.length > FAILURE_LOG_BYTES ? `${kept.slice(kept.length - FAILURE_LOG_BYTES)}` : kept
-}
-
-/** Engine seams — the fs/ssh touchpoints, injectable for tests. */
-export interface SyncEngineDeps {
- /** The local profile's package.json dependency map. */
- profileDependencies: () => Record<string, string>
- /** The local skill roots as scanned, with their directories. */
- scanSkills: () => Array<{ root: SyncSkillRoot, dir: string, names: string[] }>
- /** Pack skill directories into a tar stream (local `tar -cf -`). */
- packSkills: (dir: string, names: readonly string[]) => Promise<Buffer>
- /** Open one dedicated authenticated session; the engine closes it. */
- openSession: (machineId: MachineId) => Promise<SshSession>
- /** Per-remote-command deadline (plugin adds are install-class operations). */
- commandTimeoutMs?: number
-}
-
-/** One apply run's options. */
-export interface SyncApplyOptions {
- /**
- * Live progress of the run: the item about to start (1-based position), the
- * deduped item count, and the item's display name. Called before every
- * remote command, so the UI can show progress instead of a silent
- * multi-minute wait.
- */
- onItem?: (position: number, total: number, name: string) => void
- /**
- * The remote dsh profile the plugins install into. The tunnel serves this
- * machine's configured profile (default {@link DEFAULT_REMOTE_PROFILE}), so
- * installing anywhere else would leave the synced plugins inert.
- */
- profileName?: string
- /**
- * Runs once on the freshly opened session before the first plugin install
- * (the caller's chance to prepare the remote profile — e.g. carry the local
- * build allowlist). Best-effort by contract: it must not fail the sync, and
- * is skipped entirely for skill-only runs.
- */
- beforePlugins?: (session: SshSession) => Promise<void>
-}
-
-/**
- * The sync engine: preview from local sources, apply over one SSH session.
- * Apply never throws for command-level failures — every requested item
- * settles into the returned list, so the panel can render each outcome.
- */
-export class SyncEngine {
- constructor(private readonly deps: SyncEngineDeps) {}
-
- /** The selectable local plugins and skills. */
+import type { MachineId, SshSession, SyncApplyResult, SyncItemResult, SyncPluginRef, SyncPreview, SyncSkillRef, SyncSkillRoot } from '../types/index'
+import type { SyncDeps } from './sync.types'
+import { defineService } from 'dsh-tauri'
+import { syncRuntimeDeps } from '../config/runtime'
+import { carryWorkspaceAllowlist, parseBuildAllowKeys } from '../utils/allowlist'
+import { dshEntryProbeCommand, firstLineOf } from './bootstrap.utils'
+import { machine } from './machine'
+import { buildPreview, dedupeBy, describeFailure, failureLogOf, installSpecOf, pluginAddCommand, skillExtractCommand } from './sync.utils'
+
+export const sync = defineService({
preview(): SyncPreview {
- return buildPreview(this.deps.profileDependencies(), this.deps.scanSkills())
- }
+ const deps = syncRuntimeDeps()
+ return buildPreview(deps.profileDependencies(), deps.scanSkills())
+ },
- /**
- * Sync the selected plugins and skills to one machine, item by item.
- * @param machineId - the target machine.
- * @param plugins - the plugin refs to install (name is display identity).
- * @param skills - the skill refs to copy (root picks the local source).
- * @param options - live progress and the install target profile.
- * @returns one outcome per requested item, in request order.
- */
- async apply(
- machineId: MachineId,
- plugins: readonly SyncPluginRef[],
- skills: readonly SyncSkillRef[],
- options: SyncApplyOptions = {},
- ): Promise<SyncApplyResult> {
+ async apply(machineId: MachineId, plugins: readonly SyncPluginRef[], skills: readonly SyncSkillRef[]): Promise<SyncApplyResult> {
+ const deps = syncRuntimeDeps()
const items: SyncItemResult[] = []
const uniquePlugins = dedupeBy(plugins, ref => ref.spec)
const uniqueSkills = dedupeBy(skills, ref => `${ref.root}:${ref.name}`)
if (uniquePlugins.length === 0 && uniqueSkills.length === 0)
return { items }
- // 进度只按「已结算的条目数」推进:公告的 position 恒为 settled + 1,UI 的
- // 「第 n/N 项」因此在任何失败路径下都不跳号(本地校验出局的条目也结算)。
+ await machine.syncProfiles()
+ const profileName = machine.profileName(machineId)
const progress: SyncProgress = { settled: 0, total: uniquePlugins.length + uniqueSkills.length }
- const session = await this.deps.openSession(machineId)
+ const session = await machine.openSession(machineId)
try {
if (uniquePlugins.length > 0)
- await options.beforePlugins?.(session).catch(() => undefined)
- await this.applyPlugins(session, uniquePlugins, items, progress, options)
- await this.applySkills(session, uniqueSkills, items, progress, options)
+ await carryWorkspaceAllowlist(session, profileName, machine.localAllowlist()).then(() => undefined).catch(() => undefined)
+ await applyPlugins(session, deps, uniquePlugins, items, progress, machineId, profileName)
+ await applySkills(session, deps, uniqueSkills, items, progress, machineId)
}
finally {
await session.close().catch(() => undefined)
+ machine.setProgress(machineId)
}
return { items }
- }
+ },
+})
- /** Install each plugin spec in its own exec so outcomes stay per-item. */
- private async applyPlugins(
- session: SshSession,
- plugins: readonly SyncPluginRef[],
- items: SyncItemResult[],
- progress: SyncProgress,
- options: SyncApplyOptions,
- ): Promise<void> {
- if (plugins.length === 0)
- return
- const dshEntry = firstLineOf((await session.exec(dshEntryProbeCommand())).stdout)
- for (const plugin of plugins) {
- announceItem(progress, options, plugin.name)
- if (dshEntry === '') {
- items.push({
- kind: 'plugin',
- name: plugin.name,
- ok: false,
- error: 'no dsh entry under the remote ~/.dsh-desktop install layout; run the machine install first',
- })
- continue
- }
- const deadline = this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs }
- const command = pluginAddCommand(dshEntry, installSpecOf(plugin.name, plugin.spec), options.profileName)
- let result = await session.exec(command, deadline)
- if (result.code !== 0) {
- // pnpm 的 prepare 门禁会打印它要求的 allowBuilds 键(git depPath 钉的是
- // 解析出来的 commit,本机旧键对不上远端今天解析到的 commit):补写一次
- // 白名单再原样重试一次,与桌面端本地安装器的做法一致。
- const granted = await this.grantBuildKeys(session, options.profileName, `${result.stdout}\n${result.stderr}`)
- if (granted.length > 0)
- result = await session.exec(command, deadline)
- }
- if (result.code === 0) {
- items.push({ kind: 'plugin', name: plugin.name, ok: true })
- }
- else {
- const log = failureLogOf(result.stdout, result.stderr)
- items.push({
- kind: 'plugin',
- name: plugin.name,
- ok: false,
- error: describeFailure(result.code, result.stdout, result.stderr),
- ...log === undefined ? {} : { log },
- })
- }
- progress.settled += 1
- }
- }
+// --- internal ---
- /**
- * Grant the build keys a failed install asked for, into the remote profile's
- * `pnpm-workspace.yaml`. Best-effort: a remote file that cannot be parsed, or
- * output naming no key, simply yields no grant (the item then reports the
- * original failure — never a masked one).
- * @returns the keys actually added.
- */
- private async grantBuildKeys(session: SshSession, profileName: string | undefined, output: string): Promise<string[]> {
- const keys = parseBuildAllowKeys(output)
- if (keys.length === 0)
- return []
- const remote = await session.exec(allowlistReadCommand(profileName ?? DEFAULT_REMOTE_PROFILE))
- const { yaml, added } = mergeWorkspaceAllowlist(
- remote.stdout,
- { allowBuilds: Object.fromEntries(keys.map(key => [key, true])), onlyBuiltDependencies: [] },
- )
- if (added.length > 0)
- await session.exec(allowlistWriteCommand(profileName ?? DEFAULT_REMOTE_PROFILE, yaml))
- return added
- }
+interface SyncProgress {
+ settled: number
+ total: number
+}
- /** Copy skills per root: local validation per item, one tar stream per root. */
- private async applySkills(
- session: SshSession,
- skills: readonly SyncSkillRef[],
- items: SyncItemResult[],
- progress: SyncProgress,
- options: SyncApplyOptions,
- ): Promise<void> {
- if (skills.length === 0)
- return
- const roots = new Map(this.deps.scanSkills().map(entry => [entry.root as SyncSkillRoot, entry]))
- for (const [root, entry] of roots) {
- const requested = skills.filter(skill => skill.root === root)
- if (requested.length === 0)
- continue
- const known = new Set(entry.names)
- const transferable: SyncSkillRef[] = []
- for (const skill of requested) {
- if (known.has(skill.name)) {
- transferable.push(skill)
- }
- else {
- items.push({
- kind: 'skill',
- name: skill.name,
- root,
- ok: false,
- error: `not found under the local "${root}" skill root (it may have been removed)`,
- })
- progress.settled += 1
- }
- }
- if (transferable.length === 0)
- continue
- // 一个 root 的全部 skill 走同一份 tar:公告取批首那条,位置即批次起点。
- announceItem(progress, options, transferable[0]!.name)
- let tar: Buffer
- try {
- tar = await this.deps.packSkills(entry.dir, transferable.map(skill => skill.name))
- }
- catch (error) {
- // The local pack failed: every transferable item carries the reason.
- const message = error instanceof Error ? error.message : String(error)
- for (const skill of transferable) {
- items.push({ kind: 'skill', name: skill.name, root, ok: false, error: message })
- }
- progress.settled += transferable.length
- continue
- }
- const result = await session.exec(skillExtractCommand(), {
- stdinData: tar,
- ...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },
+function announceItem(machineId: MachineId, progress: SyncProgress, name: string): void {
+ machine.setProgress(machineId, { phase: 'syncing', attempt: progress.settled + 1, total: progress.total, item: name })
+}
+
+async function applyPlugins(
+ session: SshSession,
+ deps: SyncDeps,
+ plugins: readonly SyncPluginRef[],
+ items: SyncItemResult[],
+ progress: SyncProgress,
+ machineId: MachineId,
+ profileName: string,
+): Promise<void> {
+ if (plugins.length === 0)
+ return
+ const dshEntry = firstLineOf((await session.exec(dshEntryProbeCommand())).stdout)
+ for (const plugin of plugins) {
+ announceItem(machineId, progress, plugin.name)
+ if (dshEntry === '') {
+ items.push({
+ kind: 'plugin',
+ name: plugin.name,
+ ok: false,
+ error: 'no dsh entry under the remote ~/.dsh-desktop install layout; run the machine install first',
+ })
+ continue
+ }
+ const deadline = deps.commandTimeoutMs === undefined ? {} : { timeoutMs: deps.commandTimeoutMs }
+ const command = pluginAddCommand(dshEntry, installSpecOf(plugin.name, plugin.spec), profileName)
+ let result = await session.exec(command, deadline)
+ if (result.code !== 0) {
+ const granted = await grantBuildKeys(session, profileName, `${result.stdout}\n${result.stderr}`)
+ if (granted.length > 0)
+ result = await session.exec(command, deadline)
+ }
+ if (result.code === 0) {
+ items.push({ kind: 'plugin', name: plugin.name, ok: true })
+ }
+ else {
+ const log = failureLogOf(result.stdout, result.stderr)
+ items.push({
+ kind: 'plugin',
+ name: plugin.name,
+ ok: false,
+ error: describeFailure(result.code, result.stdout, result.stderr),
+ ...log === undefined ? {} : { log },
})
- const log = result.code === 0 ? undefined : failureLogOf(result.stdout, result.stderr)
- for (const skill of transferable) {
- items.push(
- result.code === 0
- ? { kind: 'skill', name: skill.name, root, ok: true }
- : {
- kind: 'skill',
- name: skill.name,
- root,
- ok: false,
- error: describeFailure(result.code, result.stdout, result.stderr),
- ...log === undefined ? {} : { log },
- },
- )
- }
- progress.settled += transferable.length
}
+ progress.settled += 1
}
}
-/** The live progress bookkeeping of one apply run (see `SyncProgressHook`). */
-interface SyncProgress {
- /** Items already settled (success or failure); the next item is `settled + 1`. */
- settled: number
- /** Deduped item count of the run. */
- total: number
-}
-
-/** Announce the item about to run; no-op when the caller passed no hook. */
-function announceItem(progress: SyncProgress, options: SyncApplyOptions, name: string): void {
- options.onItem?.(progress.settled + 1, progress.total, name)
+async function grantBuildKeys(session: SshSession, profileName: string, output: string): Promise<string[]> {
+ const keys = parseBuildAllowKeys(output)
+ if (keys.length === 0)
+ return []
+ return carryWorkspaceAllowlist(session, profileName, {
+ allowBuilds: Object.fromEntries(keys.map(key => [key, true])),
+ onlyBuiltDependencies: [],
+ })
}
-/** Keep the first occurrence of each keyed item, preserving request order. */
-function dedupeBy<T>(items: readonly T[], keyOf: (item: T) => string): T[] {
- const seen = new Set<string>()
- const out: T[] = []
- for (const item of items) {
- const key = keyOf(item)
- if (seen.has(key))
+async function applySkills(
+ session: SshSession,
+ deps: SyncDeps,
+ skills: readonly SyncSkillRef[],
+ items: SyncItemResult[],
+ progress: SyncProgress,
+ machineId: MachineId,
+): Promise<void> {
+ if (skills.length === 0)
+ return
+ const roots = new Map(deps.scanSkills().map(entry => [entry.root as SyncSkillRoot, entry]))
+ for (const [root, entry] of roots) {
+ const requested = skills.filter(skill => skill.root === root)
+ if (requested.length === 0)
continue
- seen.add(key)
- out.push(item)
+ const known = new Set(entry.names)
+ const transferable: SyncSkillRef[] = []
+ for (const skill of requested) {
+ if (known.has(skill.name)) {
+ transferable.push(skill)
+ }
+ else {
+ items.push({
+ kind: 'skill',
+ name: skill.name,
+ root,
+ ok: false,
+ error: `not found under the local "${root}" skill root (it may have been removed)`,
+ })
+ progress.settled += 1
+ }
+ }
+ if (transferable.length === 0)
+ continue
+ announceItem(machineId, progress, transferable[0]!.name)
+ let tar: Buffer
+ try {
+ tar = await deps.packSkills(entry.dir, transferable.map(skill => skill.name))
+ }
+ catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ for (const skill of transferable)
+ items.push({ kind: 'skill', name: skill.name, root, ok: false, error: message })
+ progress.settled += transferable.length
+ continue
+ }
+ const result = await session.exec(skillExtractCommand(), {
+ stdinData: tar,
+ ...deps.commandTimeoutMs === undefined ? {} : { timeoutMs: deps.commandTimeoutMs },
+ })
+ const log = result.code === 0 ? undefined : failureLogOf(result.stdout, result.stderr)
+ for (const skill of transferable) {
+ items.push(
+ result.code === 0
+ ? { kind: 'skill', name: skill.name, root, ok: true }
+ : {
+ kind: 'skill',
+ name: skill.name,
+ root,
+ ok: false,
+ error: describeFailure(result.code, result.stdout, result.stderr),
+ ...log === undefined ? {} : { log },
+ },
+ )
+ }
+ progress.settled += transferable.length
}
- return out
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.types.ts b/packages/dsh-tauri-ssh/src/host/service/sync.types.ts
new file mode 100644
index 00000000..d77f3755
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.types.ts
@@ -0,0 +1,15 @@
+import type { Buffer } from 'node:buffer'
+import type { SyncSkillRoot } from '../types/index'
+
+export interface SyncSkillScan {
+ root: SyncSkillRoot
+ dir: string
+ names: string[]
+}
+
+export interface SyncDeps {
+ profileDependencies: () => Record<string, string>
+ scanSkills: () => SyncSkillScan[]
+ packSkills: (dir: string, names: readonly string[]) => Promise<Buffer>
+ commandTimeoutMs?: number
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.utils.ts b/packages/dsh-tauri-ssh/src/host/service/sync.utils.ts
new file mode 100644
index 00000000..df9f6b71
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/sync.utils.ts
@@ -0,0 +1,91 @@
+import type { SyncPluginItem, SyncPreview, SyncSkillItem, SyncSkillRoot } from '../types/index'
+import { DEFAULT_REMOTE_PROFILE } from '../config/constants'
+import { shQuote } from '../utils/shell'
+import { layoutBinDir, layoutNodeBinary } from './bootstrap.utils'
+
+const FAILURE_TAIL_LINES = 5
+const FAILURE_CAUSE_LINES = 2
+const FAILURE_CAUSE = /ERR_PNPM_|gyp ERR!|error:|Error:|Error \d|not ok|not found|No such file|Permission denied|exit code|Command failed|ELIFECYCLE/u
+const FAILURE_LOG_LINES = 60
+const FAILURE_LOG_BYTES = 8000
+const BUNDLED_PLUGIN_NAME = /^dsh-tauri(?:-|$)/u
+
+export function classifySpec(spec: string): { syncable: boolean, reason?: string } {
+ const value = spec.trim()
+ if (value === '')
+ return { syncable: false, reason: 'empty dependency spec' }
+ if (/^(?:github:|git\+|git@)/u.test(value))
+ return { syncable: true }
+ if (/^(?:file:|link:|workspace:)/u.test(value))
+ return { syncable: false, reason: 'local-path dependency; it cannot be resolved on the remote' }
+ if (/^https?:\/\//u.test(value))
+ return { syncable: false, reason: 'URL dependencies are not supported' }
+ return { syncable: true }
+}
+
+export function buildPreview(dependencies: Record<string, string>, skillRoots: ReadonlyArray<{ root: SyncSkillRoot, names: readonly string[] }>): SyncPreview {
+ const plugins: SyncPluginItem[] = Object.entries(dependencies)
+ .filter(([name]) => !name.startsWith('@deepseek-ai/') && !BUNDLED_PLUGIN_NAME.test(name))
+ .map(([name, spec]) => {
+ const verdict = classifySpec(spec)
+ return {
+ name,
+ spec,
+ syncable: verdict.syncable,
+ ...verdict.reason === undefined ? {} : { reason: verdict.reason },
+ }
+ })
+ .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0))
+ const skills: SyncSkillItem[] = []
+ for (const entry of skillRoots) {
+ for (const name of [...entry.names].sort())
+ skills.push({ name, root: entry.root })
+ }
+ return { plugins, skills }
+}
+
+export function installSpecOf(name: string, spec: string): string {
+ const value = spec.trim()
+ return /^(?:github:|git\+|git@)/u.test(value) ? value : `${name}@${value}`
+}
+
+export function pluginAddCommand(dshEntry: string, target: string, profileName: string = DEFAULT_REMOTE_PROFILE): string {
+ return `PATH="${layoutBinDir()}:$PATH" ${layoutNodeBinary()} ${shQuote(dshEntry)} plugin --profile ${shQuote(profileName)} add ${shQuote(target)}`
+}
+
+export function skillExtractCommand(): string {
+ return `mkdir -p "$HOME/.dsh/skills" && tar -xf - -C "$HOME/.dsh/skills"`
+}
+
+export function describeFailure(code: number | null, stdout: string, stderr: string): string {
+ const lines = outputLines(stdout, stderr)
+ const causes = lines.filter(line => FAILURE_CAUSE.test(line)).slice(0, FAILURE_CAUSE_LINES)
+ const picked = causes.length > 0 ? causes : lines.slice(-FAILURE_TAIL_LINES)
+ const parts = picked.map(line => (line.length > 300 ? `${line.slice(0, 300)}…` : line))
+ return `exit ${code ?? '?'}${parts.length === 0 ? '' : `: ${parts.join(' | ')}`}`
+}
+
+export function failureLogOf(stdout: string, stderr: string): string | undefined {
+ const lines = outputLines(stdout, stderr)
+ if (lines.length === 0)
+ return undefined
+ const kept = lines.slice(-FAILURE_LOG_LINES).join('\n')
+ return kept.length > FAILURE_LOG_BYTES ? kept.slice(-FAILURE_LOG_BYTES) : kept
+}
+
+export function dedupeBy<T>(items: readonly T[], keyOf: (item: T) => string): T[] {
+ const seen = new Set<string>()
+ const out: T[] = []
+ for (const item of items) {
+ const key = keyOf(item)
+ if (seen.has(key))
+ continue
+ seen.add(key)
+ out.push(item)
+ }
+ return out
+}
+
+function outputLines(stdout: string, stderr: string): string[] {
+ return `${stdout}\n${stderr}`.split('\n').map(line => line.trim()).filter(line => line !== '')
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
index cd1baa04..6f37b769 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.test.ts
@@ -1,12 +1,26 @@
import type { AddressInfo } from 'node:net'
-import type { MachineProfile } from '../types/index'
+import type { MachineProfile, SshSession } from '../types/index'
+import type { SshCredentialsResolver, SshHostKeyVerifier, SshTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
import { EventEmitter } from 'node:events'
import { Server, connect as tcpConnect } from 'node:net'
import { PassThrough } from 'node:stream'
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { MachineId } from '../types/index'
-import { classifyConnectFailure, describeConnectFailure, injectCookieHead, loginShell, shQuote, Ssh2Transport } from './transport'
+import { loginShell, shQuote } from '../utils/shell'
+import { transport } from './transport'
+import { classifyConnectFailure, describeConnectFailure, injectCookieHead } from './transport.utils'
+
+const READY_TIMEOUT_MS = 15_000
+
+function newTransport(resolver: SshCredentialsResolver, options: Partial<SshTransportOptions> = {}) {
+ const settings: SshTransportOptions = { readyTimeoutMs: READY_TIMEOUT_MS, resolveProfile: resolver, ...options }
+ return {
+ async connect(profile: MachineProfile, hostKeyVerifier: SshHostKeyVerifier, signal?: AbortSignal): Promise<SshSession> {
+ return await transport.connect(profile, hostKeyVerifier, settings, signal)
+ },
+ }
+}
const profile: MachineProfile = {
id: MachineId('m1'),
@@ -25,28 +39,19 @@ function withoutPassword(profile: MachineProfile): MachineProfile {
}
/** A credential resolver double: password rides the profile, keys come from the plan. */
-class StubResolver {
- constructor(private readonly plan: {
- host?: string
- port?: number
- username?: string
- keys?: Array<{ privateKey: string, passphrase?: string }>
- } = {}) {}
-
- async resolve(input: MachineProfile): Promise<{
- host: string
- port: number
- username: string
- password?: string
- keys: Array<{ privateKey: string, passphrase?: string }>
- proxyJump: string[]
- }> {
+function stubResolver(plan: {
+ host?: string
+ port?: number
+ username?: string
+ keys?: Array<{ privateKey: string, passphrase?: string }>
+} = {}): SshCredentialsResolver {
+ return async (input: MachineProfile) => {
const password = input.password === undefined || input.password === '' ? undefined : input.password
return {
- host: this.plan.host ?? input.host,
- port: this.plan.port ?? input.port,
- username: this.plan.username ?? input.user,
- keys: this.plan.keys ?? [],
+ host: plan.host ?? input.host,
+ port: plan.port ?? input.port,
+ username: plan.username ?? input.user,
+ keys: plan.keys ?? [],
proxyJump: [],
...password === undefined ? {} : { password },
}
@@ -55,8 +60,7 @@ class StubResolver {
type HostVerifier = (key: Buffer, verify: (valid: boolean) => void) => void
-/** Transport options with the agent step disabled — deterministic chains. */
-const noAgent = { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3, agentSocket: '' }
+const keepalive = { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3 }
class FakeClient extends EventEmitter {
connectConfig: Record<string, unknown> | undefined
@@ -259,8 +263,19 @@ describe('shQuote / loginShell', () => {
})
describe('ssh2Transport', () => {
+ const agentSocketBefore = process.env.SSH_AUTH_SOCK
+ beforeEach(() => {
+ delete process.env.SSH_AUTH_SOCK
+ })
+ afterEach(() => {
+ if (agentSocketBefore === undefined)
+ delete process.env.SSH_AUTH_SOCK
+ else
+ process.env.SSH_AUTH_SOCK = agentSocketBefore
+ })
+
it('connects with password auth and resolves on ready', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
expect(session).toBeDefined()
const client = lastClient()
@@ -276,10 +291,11 @@ describe('ssh2Transport', () => {
})
it('tries the ssh-agent first, then keys, then the stored password, then gives up', async () => {
- const resolver = new StubResolver({
+ process.env.SSH_AUTH_SOCK = '/tmp/agent.sock'
+ const resolver = stubResolver({
keys: [{ privateKey: 'KEY-A' }],
})
- const transport = new Ssh2Transport(15000, resolver, { ...noAgent, agentSocket: '/tmp/agent.sock' })
+ const transport = newTransport(resolver, keepalive)
const session = await transport.connect(profile, () => true)
const client = lastClient()
const handler = authHandlerOf(client)
@@ -293,10 +309,10 @@ describe('ssh2Transport', () => {
})
it('tries the resolved keys first, then the stored password, then gives up', async () => {
- const resolver = new StubResolver({
+ const resolver = stubResolver({
keys: [{ privateKey: 'KEY-A' }, { privateKey: 'KEY-B', passphrase: 'PASS' }],
})
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
const session = await transport.connect(profile, () => true)
const client = lastClient()
const handler = authHandlerOf(client)
@@ -308,8 +324,8 @@ describe('ssh2Transport', () => {
})
it('tries only keys when no password is stored', async () => {
- const resolver = new StubResolver({ keys: [{ privateKey: 'KEY', passphrase: 'PASS' }] })
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const resolver = stubResolver({ keys: [{ privateKey: 'KEY', passphrase: 'PASS' }] })
+ const transport = newTransport(resolver, keepalive)
const session = await transport.connect(withoutPassword(profile), () => true)
const client = lastClient()
const handler = authHandlerOf(client)
@@ -319,46 +335,38 @@ describe('ssh2Transport', () => {
})
it('gives up immediately when nothing resolves', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(withoutPassword(profile), () => true)
expect(lastClient().acceptedAuth).toBe(false)
await session.close()
})
- it('reads SSH_AUTH_SOCK when no agent socket is injected', async () => {
- const previous = process.env.SSH_AUTH_SOCK
- try {
- process.env.SSH_AUTH_SOCK = '/tmp/from-env.sock'
- const transport = new Ssh2Transport(15000, new StubResolver(), { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3 })
- const session = await transport.connect(profile, () => true)
- expect(lastClient().acceptedAuth).toEqual({ type: 'agent', username: 'root', agent: '/tmp/from-env.sock' })
- await session.close()
- }
- finally {
- if (previous === undefined)
- delete process.env.SSH_AUTH_SOCK
- else
- process.env.SSH_AUTH_SOCK = previous
- }
+ it('reads the agent socket from SSH_AUTH_SOCK', async () => {
+ process.env.SSH_AUTH_SOCK = '/tmp/from-env.sock'
+ const transport = newTransport(stubResolver(), { keepaliveIntervalMs: 10_000, keepaliveCountMax: 3 })
+ const session = await transport.connect(profile, () => true)
+ expect(lastClient().acceptedAuth).toEqual({ type: 'agent', username: 'root', agent: '/tmp/from-env.sock' })
+ await session.close()
})
it('configures the keepalive watchdog from the injected options', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver(), { keepaliveIntervalMs: 25_000, keepaliveCountMax: 7, agentSocket: '' })
+ const transport = newTransport(stubResolver(), { keepaliveIntervalMs: 25_000, keepaliveCountMax: 7 })
const session = await transport.connect(profile, () => true)
expect(lastClient().connectConfig).toMatchObject({ keepaliveInterval: 25_000, keepaliveCountMax: 7 })
await session.close()
})
it('defaults the keepalive watchdog to 10 s and 3 missed beats', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver(), { agentSocket: '' })
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
expect(lastClient().connectConfig).toMatchObject({ keepaliveInterval: 10_000, keepaliveCountMax: 3 })
await session.close()
})
it('reports the winning auth method on the session', async () => {
- const resolver = new StubResolver({ keys: [{ privateKey: 'KEY-A' }] })
- const transport = new Ssh2Transport(15000, resolver, { ...noAgent, agentSocket: '/tmp/agent.sock' })
+ process.env.SSH_AUTH_SOCK = '/tmp/agent.sock'
+ const resolver = stubResolver({ keys: [{ privateKey: 'KEY-A' }] })
+ const transport = newTransport(resolver, keepalive)
const session = await transport.connect(profile, () => true)
// The fake server accepted the agent offer, so the session reports it.
expect(lastClient().acceptedAuth).toMatchObject({ type: 'agent' })
@@ -367,39 +375,37 @@ describe('ssh2Transport', () => {
})
it('connects to the resolver-resolved host, port, and user', async () => {
- const resolver = new StubResolver({ host: '10.0.0.9', port: 2222, username: 'deploy' })
- const transport = new Ssh2Transport(15000, resolver)
+ const resolver = stubResolver({ host: '10.0.0.9', port: 2222, username: 'deploy' })
+ const transport = newTransport(resolver)
const session = await transport.connect(profile, () => true)
expect(lastClient().connectConfig).toMatchObject({ host: '10.0.0.9', port: 2222, username: 'deploy' })
await session.close()
})
it('rejects when the resolver fails', async () => {
- const failing = {
- async resolve() {
- throw new Error('config read failed')
- },
+ const failing: SshCredentialsResolver = async () => {
+ throw new Error('config read failed')
}
- const transport = new Ssh2Transport(15000, failing as never)
+ const transport = newTransport(failing)
await expect(transport.connect(profile, () => true)).rejects.toThrow('config read failed')
})
it('rejects on transport errors', async () => {
const { Client } = await import('ssh2')
vi.mocked(Client).mockImplementationOnce(errorClientOnce('ECONNREFUSED'))
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
await expect(transport.connect(profile, () => true)).rejects.toThrow('ECONNREFUSED')
})
it('rejects when already aborted', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const controller = new AbortController()
controller.abort()
await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow()
})
it('aborts an in-flight handshake', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const controller = new AbortController()
const pending = transport.connect(profile, () => true, controller.signal)
controller.abort()
@@ -407,35 +413,35 @@ describe('ssh2Transport', () => {
})
it('propagates a string abort reason', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const controller = new AbortController()
controller.abort('caller gave up')
await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow('caller gave up')
})
it('propagates an arbitrary abort reason', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const controller = new AbortController()
controller.abort({ code: 'custom' })
await expect(transport.connect(profile, () => true, controller.signal)).rejects.toThrow('This operation was aborted')
})
it('accepts a synchronous verifier verdict', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => false)
expect(lastClient().hostKeyAccepted).toBe(false)
await session.close()
})
it('accepts an asynchronous verifier verdict through the callback', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, async () => true)
expect(lastClient().hostKeyAccepted).toBe(true)
await session.close()
})
it('rejects when an asynchronous verifier fails', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, async () => {
throw new Error('verifier blew up')
})
@@ -444,7 +450,7 @@ describe('ssh2Transport', () => {
})
it('collects exec output and exit code', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const result = await session.exec('uname -srm')
expect(result.code).toBe(0)
@@ -454,7 +460,7 @@ describe('ssh2Transport', () => {
})
it('rejects exec when the channel cannot open', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
lastClient().execError = new Error('channel open failure')
await expect(session.exec('x')).rejects.toThrow('channel open failure')
@@ -462,7 +468,7 @@ describe('ssh2Transport', () => {
})
it('rejects exec with a deadline even when the channel cannot open', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
lastClient().execError = new Error('channel open failure')
await expect(session.exec('x', { timeoutMs: 1000 })).rejects.toThrow('channel open failure')
@@ -470,7 +476,7 @@ describe('ssh2Transport', () => {
})
it('clears the deadline when a command finishes normally', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const result = await session.exec('x', { timeoutMs: 1000 })
expect(result.code).toBe(0)
@@ -478,7 +484,7 @@ describe('ssh2Transport', () => {
})
it('rejects exec when the stream itself errors', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
lastClient().streamError = new Error('stream reset')
await expect(session.exec('x')).rejects.toThrow('stream reset')
@@ -486,7 +492,7 @@ describe('ssh2Transport', () => {
})
it('rejects exec on a stream error with a deadline pending', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
lastClient().streamError = new Error('stream reset')
await expect(session.exec('x', { timeoutMs: 1000 })).rejects.toThrow('stream reset')
@@ -494,7 +500,7 @@ describe('ssh2Transport', () => {
})
it('streams stdout through the onData tap', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const chunks: string[] = []
const result = await session.exec('x', { onData: chunk => chunks.push(chunk) })
@@ -504,7 +510,7 @@ describe('ssh2Transport', () => {
})
it('times out a hung command and closes the connection', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
lastClient().execHang = true
await expect(session.exec('slow', { timeoutMs: 10 })).rejects.toThrow(/timed out after 10 ms/)
@@ -512,7 +518,7 @@ describe('ssh2Transport', () => {
})
it('forwards the remote port to a loopback listener', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
expect(tunnel.localPort).toBeGreaterThan(0)
@@ -521,7 +527,7 @@ describe('ssh2Transport', () => {
})
it('pipes real socket traffic through the tunnel', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
@@ -535,7 +541,7 @@ describe('ssh2Transport', () => {
})
it('destroys open sockets when the tunnel closes', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
@@ -547,7 +553,7 @@ describe('ssh2Transport', () => {
})
it('destroys the client socket when the tunnel channel fails', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
lastClient().forwardError = new Error('tunnel closed')
@@ -565,7 +571,7 @@ describe('ssh2Transport', () => {
// 回归:插件寄宿在 dsh 进程内,隧道 socket/channel 未处理的 'error'
// 事件会把整个 dsh 拉崩(实报 ECONNRESET 杀进程)。channel 报错必须
// 只销毁对应连接;若仍有未处理错误,vitest worker 会直接崩溃。
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
@@ -584,14 +590,14 @@ describe('ssh2Transport', () => {
queueMicrotask(() => server.emit('error', new Error('EADDRINUSE')))
return server
})
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
await expect(session.openTunnel(3080)).rejects.toThrow('EADDRINUSE')
await session.close()
})
it('fires the closed callback once when the connection drops', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const callback = vi.fn()
session.onClosed(callback)
@@ -603,7 +609,7 @@ describe('ssh2Transport', () => {
})
it('fires the closed callback immediately for an already-closed session', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
lastClient().emit('close')
const callback = vi.fn()
@@ -617,7 +623,7 @@ describe('ssh2Transport', () => {
await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', () => resolve()))
const freePort = (holder.address() as AddressInfo).port
await new Promise<void>(resolve => holder.close(() => resolve()))
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080, freePort)
expect(tunnel.localPort).toBe(freePort)
@@ -630,7 +636,7 @@ describe('ssh2Transport', () => {
const holder = new Server()
await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', () => resolve()))
const takenPort = (holder.address() as AddressInfo).port
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080, takenPort)
expect(tunnel.localPort).not.toBe(takenPort)
@@ -682,14 +688,14 @@ describe('describeConnectFailure', () => {
it('wraps transport failures with the classified message', async () => {
const { Client } = await import('ssh2')
vi.mocked(Client).mockImplementationOnce(errorClientOnce('connect ECONNREFUSED 127.0.0.1:1'))
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
await expect(transport.connect(profile, () => true)).rejects.toThrow(/host unreachable: .*ECONNREFUSED/)
})
it('keeps the auth-failure message distinguishable when the chain exhausts', async () => {
const { Client } = await import('ssh2')
vi.mocked(Client).mockImplementationOnce(errorClientOnce('All configured authentication methods failed'))
- const transport = new Ssh2Transport(15000, new StubResolver(), noAgent)
+ const transport = newTransport(stubResolver(), keepalive)
// With a stored password in the chain the message points at the password.
await expect(transport.connect(profile, () => true)).rejects.toThrow(/stored password was rejected/)
vi.mocked(Client).mockImplementationOnce(errorClientOnce('All configured authentication methods failed'))
@@ -699,22 +705,14 @@ describe('describeConnectFailure', () => {
})
/** A resolver that answers per config alias: ops jumps through dev. */
-class JumpResolver {
- constructor(private readonly plans: Record<string, {
- host: string
- port: number
- username?: string
- proxyJump?: string[]
- }>) {}
-
- async resolve(input: MachineProfile): Promise<{
- host: string
- port: number
- username: string
- keys: Array<{ privateKey: string, passphrase?: string }>
- proxyJump: string[]
- }> {
- const plan = this.plans[input.host]
+function jumpResolver(plans: Record<string, {
+ host: string
+ port: number
+ username?: string
+ proxyJump?: string[]
+}>): SshCredentialsResolver {
+ return async (input: MachineProfile) => {
+ const plan = plans[input.host]
if (plan === undefined)
throw new Error(`unknown host ${input.host}`)
return {
@@ -738,12 +736,12 @@ describe('ssh2Transport ProxyJump', () => {
}
it('walks the jump chain: hop connects directly, target rides the forwarded stream', async () => {
- const resolver = new JumpResolver({
+ const resolver = jumpResolver({
ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },
dev: { host: '10.1.0.2', port: 22 },
})
const labels: string[] = []
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
const before = fakeClientInstances.length
const session = await transport.connect(opsProfile, (label) => {
labels.push(label)
@@ -765,12 +763,12 @@ describe('ssh2Transport ProxyJump', () => {
})
it('supports user@ and :port overrides and comma-separated multi-hop chains', async () => {
- const resolver = new JumpResolver({
+ const resolver = jumpResolver({
ops: { host: '192.168.42.192', port: 2222, proxyJump: ['root@dev:22', 'admin@bastion'] },
dev: { host: '10.1.0.2', port: 22 },
bastion: { host: '10.1.0.3', port: 2222 },
})
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
const before = fakeClientInstances.length
await transport.connect(opsProfile, () => true)
const [first, second, target] = fakeClientInstances.slice(before)
@@ -782,29 +780,29 @@ describe('ssh2Transport ProxyJump', () => {
})
it('rejects a proxy jump cycle before dialing', async () => {
- const resolver = new JumpResolver({
+ const resolver = jumpResolver({
ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev', 'dev'] },
dev: { host: '10.1.0.2', port: 22 },
})
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
await expect(transport.connect(opsProfile, () => true)).rejects.toThrow(/proxy jump cycle/iu)
})
it('rejects a nested ProxyJump on the jump alias', async () => {
- const resolver = new JumpResolver({
+ const resolver = jumpResolver({
ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },
dev: { host: '10.1.0.2', port: 22, proxyJump: ['third'] },
})
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
await expect(transport.connect(opsProfile, () => true)).rejects.toThrow(/nested ProxyJump/iu)
})
it('closes the jump session when the target handshake fails', async () => {
- const resolver = new JumpResolver({
+ const resolver = jumpResolver({
ops: { host: '192.168.42.192', port: 2222, proxyJump: ['dev'] },
dev: { host: '10.1.0.2', port: 22 },
})
- const transport = new Ssh2Transport(15000, resolver, noAgent)
+ const transport = newTransport(resolver, keepalive)
const before = fakeClientInstances.length
// 第一跳就绪,目标握手失败
const { Client } = await import('ssh2')
@@ -840,7 +838,7 @@ describe('injectCookieHead', () => {
describe('tunnel cookie injection', () => {
it('stamps the request head with the minted cookie through the pipe', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const injection = { cookie: 'dsh-auth-x=v1.signed' as string | undefined }
const tunnel = await session.openTunnel(3080, undefined, injection)
@@ -861,7 +859,7 @@ describe('tunnel cookie injection', () => {
})
it('without a minted cookie the tunnel stays a plain pipe', async () => {
- const transport = new Ssh2Transport(15000, new StubResolver())
+ const transport = newTransport(stubResolver())
const session = await transport.connect(profile, () => true)
const tunnel = await session.openTunnel(3080)
const socket = tcpConnect(tunnel.localPort, '127.0.0.1')
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.ts b/packages/dsh-tauri-ssh/src/host/service/transport.ts
index 33943771..77151da4 100644
--- a/packages/dsh-tauri-ssh/src/host/service/transport.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.ts
@@ -1,144 +1,56 @@
-/**
- * SSH transport seam and its ssh2 implementation. The manager depends on the
- * narrow interfaces here — connect, exec, tunnel, close — so tests inject a
- * fake transport and never touch the network.
- * @module dsh-tauri-ssh/host/service/transport
- */
-
-import type { AddressInfo, Server } from 'node:net'
+import type { AddressInfo, Server, Socket } from 'node:net'
import type { Duplex } from 'node:stream'
import type { ConnectConfig } from 'ssh2'
-import type { MachineProfile, SshAuthMethod } from '../types/index'
-import type { ResolvedSshAuth } from './ssh-config'
+import type { MachineProfile, SshAuthMethod, SshExecOptions, SshExecResult, SshSession, SshTunnelHandle, TunnelHeaderInjection } from '../types/index'
+import type { ResolvedSshAuth } from '../utils/ssh-config'
+import type { SshHostKeyVerifier, SshTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
-import { get as httpGet } from 'node:http'
import { createServer } from 'node:net'
import process from 'node:process'
+import { defineService } from 'dsh-tauri'
import { Client } from 'ssh2'
import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
import { MachineId } from '../types/index'
+import { loginShell } from '../utils/shell'
+import { classifyConnectFailure, describeConnectFailure, injectCookieHead } from './transport.utils'
-/** The credential-resolution face the transport needs (SshConfigResolver implements it). */
-export interface SshCredentialsResolver {
- resolve: (profile: MachineProfile) => Promise<ResolvedSshAuth>
-}
-
-/** One completed remote command. */
-export interface SshExecResult {
- /** Exit code; null when the remote side reported none. */
- code: number | null
- stdout: string
- stderr: string
-}
-
-/** Optional exec behavior: a deadline, a streaming stdout tap, and stdin bytes. */
-export interface SshExecOptions {
- /** Abort the command after this many milliseconds (closes the connection). */
- timeoutMs?: number
- /** Receive stdout chunks as they arrive (long-running commands, logs). */
- onData?: (chunk: string) => void
- /**
- * Bytes written to the command's stdin, then EOF. Used to stream payloads
- * (a skill tarball) without landing them on the remote command line, whose
- * single-argument length the kernel caps far below a real payload.
- */
- stdinData?: Buffer
-}
-
-/**
- * Cookie-injection slot of one tunnel. The remote `dsh web` session cookie is
- * `SameSite=Strict`: an iframe embedding the tunnel URL is a cross-site
- * context and neither stores nor sends it (the shell's remote view showed
- * the bare 401 page even with the launch token in the URL). With a cookie
- * minted at connect time (one local `GET …/?token=…` round-trip, no redirect
- * follow), the tunnel stamps every request head itself — any embedding
- * context (iframe, webview, browser tab) is authenticated transparently.
- * `cookie === undefined` keeps the plain TCP pipe.
- */
-export interface TunnelHeaderInjection {
- /** The raw `Cookie` header value (`name=value`); read per accepted connection. */
- cookie: string | undefined
-}
-
-/** A local loopback listener forwarding into the SSH tunnel. */
-export interface SshTunnelHandle {
- /** The bound loopback port (0 = ephemeral, read from the server). */
- localPort: number
- /** Close the listener; in-flight forwarded connections are aborted. */
- close: () => Promise<void>
-}
-
-/** One authenticated SSH session. */
-export interface SshSession {
- /**
- * Which credential this session authenticated with (`agent`, `key`, or
- * `password`); absent when the transport cannot tell.
- */
- readonly authMethod?: SshAuthMethod | undefined
- /**
- * Run one command through the remote login shell.
- * @param command - the full command line.
- * @param options - optional deadline and streaming stdout tap.
- * @returns the collected result.
- */
- exec: (command: string, options?: SshExecOptions) => Promise<SshExecResult>
- /**
- * Forward a remote loopback port to a new local loopback listener
- * (`ssh -L` semantics).
- * @param remotePort - the remote 127.0.0.1 port to reach.
- * @param preferredLocalPort - keep the tunnel's published URL stable across
- * reconnects by re-binding this port when possible (falls back to an
- * ephemeral port when it is taken).
- * @param injection - mutable cookie-injection slot; when `cookie` is set,
- * every request head through the tunnel gets it stamped (see
- * {@link TunnelHeaderInjection}).
- * @returns the local listener handle.
- */
- openTunnel: (remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection) => Promise<SshTunnelHandle>
- /**
- * Register the session-closed callback (connection dropped, server went
- * away, or {@link close} ran).
- * @param callback - fired exactly once.
- */
- onClosed: (callback: () => void) => void
- /** Close the session; idempotent. */
- close: () => Promise<void>
-}
-
-/**
- * TOFU host-key gate, keyed by hop label: the target machine id for the final
- * hop, the `ProxyJump` alias for each jump host (jump keys are remembered
- * under their own alias, so a host used as both jump and machine shares one
- * TOFU record). May be async (the ssh2 callback form waits for the verdict).
- */
-export type SshHostKeyVerifier = (label: string, hostKey: Buffer) => boolean | Promise<boolean>
+const TUNNEL_HEAD_CAP = 64 * 1024
+const DEFAULT_KEEPALIVE_INTERVAL_MS = 10_000
+const DEFAULT_KEEPALIVE_COUNT_MAX = 3
-/** Transport factory: authenticate one machine and return its session. */
-export interface SshTransport {
- /**
- * @param profile - the machine profile to connect.
- * @param hostKeyVerifier - TOFU host-key gate, per hop label.
- * @param signal - aborts the handshake.
- * @returns the authenticated session.
- */
- connect: (
+export const transport = defineService({
+ async connect(
profile: MachineProfile,
hostKeyVerifier: SshHostKeyVerifier,
+ options: SshTransportOptions,
signal?: AbortSignal,
- ) => Promise<SshSession>
-}
+ ): Promise<SshSession> {
+ const hops: Ssh2Session[] = []
+ try {
+ const credentials = await options.resolveProfile(profile)
+ const session = await connectTarget(credentials, String(profile.id), hostKeyVerifier, options, signal, hops, new Set())
+ session.onClosed(() => {
+ for (const hop of hops)
+ void hop.close().catch(() => undefined)
+ })
+ return session
+ }
+ catch (error) {
+ for (const hop of hops)
+ void hop.close().catch(() => undefined)
+ throw error
+ }
+ },
+})
+
+// --- internal ---
-/** One parsed ProxyJump hop: the `[user@]alias[:port]` token, split. */
interface ProxyJumpHop {
- /** The config alias (drives the jump's own Host-block lookup). */
alias: string
- /** Optional `user@` override. */
user?: string
- /** Optional `:port` override. */
port?: number
}
-/** Parse one ProxyJump token (`[user@]alias[:port]`). */
function parseProxyJumpHop(token: string): ProxyJumpHop {
let rest = token
let user: string | undefined
@@ -156,310 +68,136 @@ function parseProxyJumpHop(token: string): ProxyJumpHop {
return { alias: rest, ...user === undefined ? {} : { user }, ...port === undefined ? {} : { port } }
}
-/** Wrap one string for safe inclusion in a remote shell command line. */
-export function shQuote(value: string): string {
- return `'${value.replace(/'/gu, `'\\''`)}'`
-}
-
-/** Build the `sh -lc <command>` wrapper used for every remote command. */
-export function loginShell(command: string): string {
- return `sh -lc ${shQuote(command)}`
-}
-
-/** The three operator-distinguishable connection failure classes. */
-export type SshConnectFailureKind
- = | 'key-rejected'
- | 'password-rejected'
- | 'unreachable'
- | 'other'
-
-/** Network-level error codes that mean "the host cannot be reached at all". */
-const UNREACHABLE_CODES = new Set([
- 'ENOTFOUND',
- 'EAI_AGAIN',
- 'ECONNREFUSED',
- 'ETIMEDOUT',
- 'EHOSTUNREACH',
- 'ENETUNREACH',
- 'ECONNRESET',
-])
-
-/** Whether one raw transport error reads as "host unreachable". */
-function isUnreachable(error: Error): boolean {
- const code = (error as NodeJS.ErrnoException).code
- if (code !== undefined && UNREACHABLE_CODES.has(code))
- return true
- return /timed?\s?out|connection refused|econnrefused|no route to host|name or service not known|getaddrinfo/iu.test(error.message)
-}
-
-/**
- * Classify one connection failure into the three operator-distinguishable
- * classes (key/agent rejected → check keys or store a password; password
- * rejected → update the stored password; unreachable → network/host name).
- * @param error - the raw transport failure.
- * @param passwordOffered - whether the stored password was part of the chain.
- * @returns the failure class.
- */
-export function classifyConnectFailure(error: unknown, passwordOffered: boolean): SshConnectFailureKind {
- const message = error instanceof Error ? error.message : String(error)
- const normalized = error instanceof Error ? error : new Error(message)
- if (isUnreachable(normalized))
- return 'unreachable'
- if (/all configured authentication methods failed|authentication failed|no supported authentication/iu.test(message)) {
- return passwordOffered ? 'password-rejected' : 'key-rejected'
+async function connectTarget(
+ credentials: ResolvedSshAuth,
+ label: string,
+ hostKeyVerifier: SshHostKeyVerifier,
+ options: SshTransportOptions,
+ signal: AbortSignal | undefined,
+ hops: Ssh2Session[],
+ visited: ReadonlySet<string>,
+): Promise<Ssh2Session> {
+ const proxyJump = credentials.proxyJump ?? []
+ if (proxyJump.length === 0)
+ return connectWithAuth(credentials, label, hostKeyVerifier, options, signal, undefined)
+
+ const chain: Array<{ alias: string, auth: ResolvedSshAuth }> = []
+ const seen = new Set(visited)
+ for (const token of proxyJump) {
+ const hop = parseProxyJumpHop(token)
+ const key = hop.alias.toLowerCase()
+ if (seen.has(key))
+ throw new Error(`proxy jump cycle through "${hop.alias}"`)
+ seen.add(key)
+ const jumpProfile: MachineProfile = {
+ id: MachineId(hop.alias),
+ name: hop.alias,
+ host: hop.alias,
+ user: hop.user ?? '',
+ port: hop.port ?? DEFAULT_SSH_PORT,
+ remotePort: DEFAULT_REMOTE_PORT,
+ }
+ const jumpAuth = await options.resolveProfile(jumpProfile)
+ if ((jumpAuth.proxyJump ?? []).length > 0)
+ throw new Error(`nested ProxyJump on "${hop.alias}" is not supported`)
+ chain.push({ alias: hop.alias, auth: jumpAuth })
}
- return 'other'
-}
-/** One operator-facing message for a classified connection failure. */
-export function describeConnectFailure(kind: SshConnectFailureKind, error: unknown): string {
- const message = error instanceof Error ? error.message : String(error)
- switch (kind) {
- case 'key-rejected':
- return 'authentication failed: no key or ssh-agent was accepted — check your keys or store a password for this machine'
- case 'password-rejected':
- return 'authentication failed: the stored password was rejected — update the stored password'
- case 'unreachable':
- return `host unreachable: ${message === '' ? 'SSH connection failed' : message}`
- default:
- return message === '' ? 'SSH connection failed' : message
+ let sock: Duplex | undefined
+ for (const [index, hop] of chain.entries()) {
+ const session = await connectWithAuth(hop.auth, hop.alias, hostKeyVerifier, options, signal, sock)
+ hops.push(session)
+ const next = index + 1 < chain.length ? chain[index + 1]!.auth : credentials
+ sock = await session.forwardOutStream(next.host, next.port)
}
+ return connectWithAuth(credentials, label, hostKeyVerifier, options, signal, sock)
}
-/** Transport timing/watchdog options; the manager passes the plugin config through. */
-export interface Ssh2TransportOptions {
- /** ssh2 keepalive heartbeat interval in milliseconds (default 10 s). */
- keepaliveIntervalMs?: number
- /** Unanswered-heartbeat threshold that declares the connection dead (default 3). */
- keepaliveCountMax?: number
- /**
- * ssh-agent socket path. `undefined` reads `SSH_AUTH_SOCK` per connect
- * (an empty/unset variable disables the agent step); an explicit empty
- * string disables it too.
- */
- agentSocket?: string
-}
-
-/**
- * ssh2-backed transport. One `Client` per session; exec and tunnel run over
- * the shared connection. Credentials come from the injected
- * {@link SshCredentialsResolver}: the host's own `~/.ssh` (config aliases,
- * IdentityFiles, default keys) with the profile's stored password/passphrase
- * as fallbacks — the connection behaves like a local `ssh` invocation. The
- * auth chain order is fixed: ssh-agent → private keys → stored password;
- * without an agent or a stored password the chain degrades to exactly the
- * previous behavior.
- */
-export class Ssh2Transport implements SshTransport {
- private readonly options: Required<Pick<Ssh2TransportOptions, 'keepaliveIntervalMs' | 'keepaliveCountMax'>> & Pick<Ssh2TransportOptions, 'agentSocket'>
-
- /**
- * @param readyTimeoutMs - handshake deadline for {@link Client.connect}.
- * @param resolver - the `~/.ssh` credential resolver (host, port, user, keys).
- * @param options - keepalive watchdog timing and the agent socket override;
- * omitted fields fall back to the 10 s / 3-beat defaults.
- */
- constructor(
- private readonly readyTimeoutMs: number,
- private readonly resolver: SshCredentialsResolver,
- options?: Ssh2TransportOptions,
- ) {
- this.options = {
- keepaliveIntervalMs: options?.keepaliveIntervalMs ?? 10_000,
- keepaliveCountMax: options?.keepaliveCountMax ?? 3,
- ...options?.agentSocket === undefined ? {} : { agentSocket: options.agentSocket },
- }
- }
-
- async connect(
- profile: MachineProfile,
- hostKeyVerifier: SshHostKeyVerifier,
- signal?: AbortSignal,
- ): Promise<SshSession> {
- const hops: Ssh2Session[] = []
- try {
- const session = await this.connectTarget(profile, String(profile.id), hostKeyVerifier, signal, hops, new Set())
- // 跳板会话与目标会话同生命周期:目标关闭时逐个收掉跳板(反序无必要,
- // 逐跳 close 会连带掐断穿过它的 direct-tcpip 通道)。
- session.onClosed(() => {
- for (const hop of hops)
- void hop.close().catch(() => undefined)
- })
- return session
- }
- catch (error) {
- for (const hop of hops)
- void hop.close().catch(() => undefined)
- throw error
+function connectWithAuth(
+ auth: ResolvedSshAuth,
+ label: string,
+ hostKeyVerifier: SshHostKeyVerifier,
+ options: SshTransportOptions,
+ signal: AbortSignal | undefined,
+ sock: Duplex | undefined,
+): Promise<Ssh2Session> {
+ return new Promise<Ssh2Session>((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(abortError(signal))
+ return
}
- }
-
- /**
- * Connect one target, walking its resolved ProxyJump chain first. The whole
- * chain resolves locally up front (config files only), then hops connect in
- * order: hop i opens a direct-tcpip channel (`ssh -W` semantics) to the
- * next hop's resolved host:port — the last hop points at the real target —
- * and the next handshake rides that stream as its socket. A jump alias
- * whose own config also sets ProxyJump is rejected (nested chains), as is
- * any cycle. Stored secrets do not cross hops: jump auth uses the agent and
- * the alias's identity files, exactly like `ssh -J`.
- */
- private async connectTarget(
- profile: MachineProfile,
- label: string,
- hostKeyVerifier: SshHostKeyVerifier,
- signal: AbortSignal | undefined,
- hops: Ssh2Session[],
- visited: ReadonlySet<string>,
- ): Promise<Ssh2Session> {
- const auth = await this.resolver.resolve(profile)
- // 缺省视直连(兼容不填 proxyJump 的 resolver 实现)
- const proxyJump = auth.proxyJump ?? []
- if (proxyJump.length === 0)
- return this.connectWithAuth(auth, label, hostKeyVerifier, signal, undefined)
-
- const chain: Array<{ alias: string, auth: ResolvedSshAuth }> = []
- const seen = new Set(visited)
- for (const token of proxyJump) {
- const hop = parseProxyJumpHop(token)
- const key = hop.alias.toLowerCase()
- if (seen.has(key))
- throw new Error(`proxy jump cycle through "${hop.alias}"`)
- seen.add(key)
- const jumpProfile: MachineProfile = {
- id: MachineId(hop.alias),
- name: hop.alias,
- host: hop.alias,
- user: hop.user ?? '',
- port: hop.port ?? DEFAULT_SSH_PORT,
- remotePort: DEFAULT_REMOTE_PORT,
- }
- const jumpAuth = await this.resolver.resolve(jumpProfile)
- if ((jumpAuth.proxyJump ?? []).length > 0)
- throw new Error(`nested ProxyJump on "${hop.alias}" is not supported`)
- chain.push({ alias: hop.alias, auth: jumpAuth })
+ const client = new Client()
+ const onAbort = (): void => {
+ client.end()
+ reject(abortError(signal as AbortSignal))
}
-
- let sock: Duplex | undefined
- for (const [index, hop] of chain.entries()) {
- const session = await this.connectWithAuth(hop.auth, hop.alias, hostKeyVerifier, signal, sock)
- hops.push(session)
- const next = index + 1 < chain.length ? chain[index + 1]!.auth : auth
- sock = await session.forwardOutStream(next.host, next.port)
+ if (signal !== undefined)
+ signal.addEventListener('abort', onAbort, { once: true })
+ const settle = (fn: () => void): void => {
+ signal?.removeEventListener('abort', onAbort)
+ fn()
}
- return this.connectWithAuth(auth, label, hostKeyVerifier, signal, sock)
- }
-
- /** One ssh2 handshake: direct, or over a jump-forwarded stream when `sock` rides a hop. */
- private connectWithAuth(
- auth: ResolvedSshAuth,
- label: string,
- hostKeyVerifier: SshHostKeyVerifier,
- signal: AbortSignal | undefined,
- sock: Duplex | undefined,
- ): Promise<Ssh2Session> {
- return new Promise<Ssh2Session>((resolve, reject) => {
- if (signal?.aborted) {
- reject(abortError(signal))
- return
- }
- const client = new Client()
- const onAbort = (): void => {
- client.end()
- reject(abortError(signal as AbortSignal))
- }
- if (signal !== undefined)
- signal.addEventListener('abort', onAbort, { once: true })
- const settle = (fn: () => void): void => {
- signal?.removeEventListener('abort', onAbort)
- fn()
+ let winningMethod: SshAuthMethod | undefined
+ let passwordOffered = false
+ client.on('ready', () => {
+ settle(() => resolve(new Ssh2Session(client, winningMethod)))
+ })
+ client.on('error', (error) => {
+ settle(() => reject(describedConnectFailure(error, passwordOffered)))
+ })
+ void Promise.resolve().then(() => {
+ const agent = process.env.SSH_AUTH_SOCK || undefined
+ let agentOffered = false
+ let keyIndex = 0
+ const authHandler: NonNullable<ConnectConfig['authHandler']> = (_methodsLeft, _partialSuccess, callback) => {
+ if (agent !== undefined && !agentOffered) {
+ agentOffered = true
+ winningMethod = 'agent'
+ callback({ type: 'agent', username: auth.username, agent })
+ }
+ else if (keyIndex < auth.keys.length) {
+ const key = auth.keys[keyIndex]!
+ keyIndex += 1
+ winningMethod = 'key'
+ callback({
+ type: 'publickey',
+ username: auth.username,
+ key: key.privateKey,
+ ...key.passphrase === undefined ? {} : { passphrase: key.passphrase },
+ })
+ }
+ else if (auth.password !== undefined && !passwordOffered) {
+ passwordOffered = true
+ winningMethod = 'password'
+ callback({ type: 'password', username: auth.username, password: auth.password })
+ }
+ else {
+ callback(false as never)
+ }
}
- // The auth chain's shared bookkeeping: which method won (reported on
- // the session once ready) and whether the stored password participated
- // (drives the failure classification when everything is rejected).
- let winningMethod: SshAuthMethod | undefined
- let passwordOffered = false
- client.on('ready', () => {
- settle(() => resolve(new Ssh2Session(client, winningMethod)))
- })
- client.on('error', (error) => {
- settle(() => reject(describedConnectFailure(error, passwordOffered)))
- })
- void Promise.resolve().then(() => {
- const agentSocket = this.options.agentSocket === undefined
- ? process.env.SSH_AUTH_SOCK
- : this.options.agentSocket
- const agent = agentSocket === undefined || agentSocket === '' ? undefined : agentSocket
- // Try the ssh-agent first, then every resolved identity in order,
- // then the stored password — the same preference order as OpenSSH
- // (agent, publickey, password). ssh2 parses each key itself and
- // skips invalid ones, so a bad or passphrase-locked key never aborts
- // the attempt. Each credential is offered at most once; the handler
- // then gives up.
- let agentOffered = false
- let keyIndex = 0
- const authHandler: NonNullable<ConnectConfig['authHandler']> = (_methodsLeft, _partialSuccess, callback) => {
- if (agent !== undefined && !agentOffered) {
- agentOffered = true
- winningMethod = 'agent'
- callback({ type: 'agent', username: auth.username, agent })
- }
- else if (keyIndex < auth.keys.length) {
- const key = auth.keys[keyIndex]!
- keyIndex += 1
- winningMethod = 'key'
- callback({
- type: 'publickey',
- username: auth.username,
- key: key.privateKey,
- ...key.passphrase === undefined ? {} : { passphrase: key.passphrase },
- })
- }
- else if (auth.password !== undefined && !passwordOffered) {
- passwordOffered = true
- winningMethod = 'password'
- callback({ type: 'password', username: auth.username, password: auth.password })
+ client.connect({
+ ...sock === undefined ? {} : { sock: sock as NonNullable<ConnectConfig['sock']> },
+ host: auth.host,
+ port: auth.port,
+ username: auth.username,
+ readyTimeout: options.readyTimeoutMs,
+ keepaliveInterval: options.keepaliveIntervalMs ?? DEFAULT_KEEPALIVE_INTERVAL_MS,
+ keepaliveCountMax: options.keepaliveCountMax ?? DEFAULT_KEEPALIVE_COUNT_MAX,
+ authHandler,
+ hostVerifier: (key: Buffer, verify: (valid: boolean) => void): void => {
+ const verdict = hostKeyVerifier(label, key)
+ if (verdict instanceof Promise) {
+ void verdict.then(verify, () => verify(false))
}
else {
- // `false` signals "no more methods" at runtime; the published
- // NextAuthHandler type omits it.
- callback(false as never)
+ verify(verdict)
}
- }
- client.connect({
- ...sock === undefined ? {} : { sock: sock as NonNullable<ConnectConfig['sock']> },
- host: auth.host,
- port: auth.port,
- username: auth.username,
- readyTimeout: this.readyTimeoutMs,
- // Keepalive watchdog: with these settings ssh2 declares the
- // connection dead after `countMax` unanswered heartbeats and
- // surfaces it as a close — the manager's reconnect trigger.
- keepaliveInterval: this.options.keepaliveIntervalMs,
- keepaliveCountMax: this.options.keepaliveCountMax,
- authHandler,
- // ssh2 accepts a synchronous boolean return OR the verify-callback
- // form; always driving the callback keeps async verifiers uniform.
- hostVerifier: (key: Buffer, verify: (valid: boolean) => void): void => {
- const verdict = hostKeyVerifier(label, key)
- if (verdict instanceof Promise) {
- void verdict.then(verify, () => verify(false))
- }
- else {
- verify(verdict)
- }
- },
- })
- }, reject)
- })
- }
+ },
+ })
+ }, reject)
+ })
}
-/**
- * Wrap one raw ssh2 handshake failure with its classified, operator-facing
- * message (the three-way auth/unreachable distinction rides the message; the
- * raw error's own text never carries secrets).
- */
function describedConnectFailure(error: Error, passwordOffered: boolean): Error {
const kind = classifyConnectFailure(error, passwordOffered)
const message = describeConnectFailure(kind, error)
@@ -468,7 +206,6 @@ function describedConnectFailure(error: Error, passwordOffered: boolean): Error
return new Error(message)
}
-/** The ssh2 session face over one authenticated `Client`. */
class Ssh2Session implements SshSession {
private readonly closed = new Set<() => void>()
private closedFired = false
@@ -486,11 +223,6 @@ class Ssh2Session implements SshSession {
})
}
- /**
- * Open one direct-tcpip channel (`ssh -W` semantics) through this session.
- * Internal to the ProxyJump chain: the next hop's handshake rides the
- * returned stream as its socket; closing this session kills the stream.
- */
forwardOutStream(host: string, port: number): Promise<Duplex> {
return new Promise((resolve, reject) => {
this.client.forwardOut('127.0.0.1', 0, host, port, (error, stream) => {
@@ -513,8 +245,6 @@ class Ssh2Session implements SshSession {
if (settled)
return
settled = true
- // Closing the connection kills the remote channel (and its process)
- // and settles any in-flight close events.
this.client.end()
reject(new Error(`remote command timed out after ${options.timeoutMs} ms`))
}, options.timeoutMs)
@@ -531,8 +261,6 @@ class Ssh2Session implements SshSession {
}
let stdout = ''
let stderr = ''
- // Stdin payloads go out first (half-close semantics: EOF lets the
- // remote `tar -xf -` finish while stdout keeps flowing back).
if (options?.stdinData !== undefined && options.stdinData.length > 0) {
stream.write(options.stdinData)
stream.end()
@@ -542,9 +270,6 @@ class Ssh2Session implements SshSession {
stdout += text
options?.onData?.(text)
})
- // ssh2 exposes stderr as a Readable *property* (`stream.stderr`); it
- // never emits a `'stderr'` event, so a listener for one silently drops
- // every remote error message and failures degrade to a bare exit code.
stream.stderr.on('data', (chunk: Buffer) => {
stderr += chunk.toString('utf8')
})
@@ -573,20 +298,12 @@ class Ssh2Session implements SshSession {
return this.listenTunnel(remotePort, preferredLocalPort, true, injection)
}
- /**
- * Bind the loopback forwarder, preferring `preferredLocalPort` so a
- * reconnect can re-publish the same tunnel URL; a taken port falls back
- * to an ephemeral one (only the first, deliberate preference retries).
- */
private listenTunnel(remotePort: number, preferredLocalPort: number | undefined, allowFallback: boolean, injection?: TunnelHeaderInjection): Promise<SshTunnelHandle> {
return new Promise<SshTunnelHandle>((resolve, reject) => {
- const sockets = new Set<import('node:net').Socket>()
+ const sockets = new Set<Socket>()
const server: Server = createServer((socket) => {
sockets.add(socket)
socket.on('close', () => sockets.delete(socket))
- // 对端中止(浏览器取消加载、curl 超时)会给 socket 发 ECONNRESET:
- // 本进程就是整个 dsh(插件寄宿其中),未处理的 'error' 事件会把
- // 整个宿主进程拉崩——socket 与 channel 双侧都必须吞错销毁。
socket.on('error', () => {
sockets.delete(socket)
socket.destroy()
@@ -607,9 +324,6 @@ class Ssh2Session implements SshSession {
})
server.on('error', (error: NodeJS.ErrnoException) => {
if (allowFallback && error.code === 'EADDRINUSE' && preferredLocalPort !== undefined) {
- // The preferred port was reclaimed while we were away; an
- // ephemeral port keeps the reconnect alive (the URL change rides
- // the status publication).
void this.listenTunnel(remotePort, undefined, false, injection).then(resolve, reject)
return
}
@@ -621,7 +335,6 @@ class Ssh2Session implements SshSession {
localPort: port,
close: () => new Promise<void>((closeResolve) => {
server.close(() => closeResolve())
- // A half-open forwarded socket must not park the close forever.
for (const socket of sockets) socket.destroy()
}),
})
@@ -643,35 +356,7 @@ class Ssh2Session implements SshSession {
}
}
-/** Request-head cap for the cookie injector; a head never completing within it pipes raw (fail-open). */
-const TUNNEL_HEAD_CAP = 64 * 1024
-
-/**
- * Stamp one request head with the minted cookie: any existing `Cookie` line
- * is replaced (the browser has none worth keeping in an iframe context) and
- * `Connection` collapses to `close` — one request per connection means the
- * injector only ever parses the FIRST head. Upgrade (websocket) handshakes
- * keep their `Connection: Upgrade` untouched; after the head the stream
- * pipes raw in both directions.
- */
-export function injectCookieHead(head: string, cookie: string): string {
- const lines = head.split('\r\n')
- const isUpgrade = lines.some(line => /^connection:\s*upgrade/iu.test(line))
- const kept = lines.filter(line =>
- !/^cookie:/iu.test(line) && (isUpgrade || !/^connection:/iu.test(line)))
- // The request line stays first; the injected headers follow it.
- kept.splice(1, 0, `Cookie: ${cookie}`)
- if (!isUpgrade)
- kept.splice(2, 0, 'Connection: close')
- return kept.join('\r\n')
-}
-
-/** Pipe one tunneled connection, stamping the first request head with the cookie. */
-function pipeChannelWithCookie(
- socket: import('node:net').Socket,
- channel: Duplex,
- cookie: string,
-): void {
+function pipeChannelWithCookie(socket: Socket, channel: Duplex, cookie: string): void {
const buffered: Buffer[] = []
let bufferedLength = 0
let injected = false
@@ -706,32 +391,6 @@ function pipeChannelWithCookie(
channel.pipe(socket)
}
-/**
- * Mint the tunnel's session cookie: GET the authenticated URL once WITHOUT
- * following the 303 and read the `name=value` pair back from `set-cookie`.
- * Resolves `undefined` on any failure (no token endpoint, timeout, transport
- * error) — the tunnel then stays a plain pipe and the `?token=` URL remains
- * the top-level fallback. The 3 s cap keeps a black-hole remote from
- * stalling the connect; the request itself needs no cookie (the query token
- * is the credential).
- */
-export function mintTunnelCookie(authenticatedUrl: string): Promise<string | undefined> {
- return new Promise((resolve) => {
- const request = httpGet(authenticatedUrl, (response) => {
- response.resume()
- const raw = response.headers['set-cookie']?.[0]
- const pair = raw === undefined ? undefined : raw.split(';')[0]?.trim()
- resolve(pair === undefined || pair === '' ? undefined : pair)
- })
- request.on('error', () => resolve(undefined))
- request.setTimeout(3_000, () => {
- request.destroy()
- resolve(undefined)
- })
- })
-}
-
-/** Mirror fetch's abort rejection: the signal's reason when present, else a DOMException-style AbortError. */
function abortError(signal: AbortSignal): Error {
const reason: unknown = signal.reason
if (reason instanceof Error)
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.types.ts b/packages/dsh-tauri-ssh/src/host/service/transport.types.ts
new file mode 100644
index 00000000..3db973f9
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.types.ts
@@ -0,0 +1,29 @@
+import type { Buffer } from 'node:buffer'
+import type { MachineProfile, SshSession } from '../types/index'
+import type { ResolvedSshAuth } from '../utils/ssh-config'
+
+export type SshCredentialsResolver = (profile: MachineProfile) => Promise<ResolvedSshAuth>
+
+export interface SshTransportOptions {
+ readyTimeoutMs: number
+ resolveProfile: SshCredentialsResolver
+ keepaliveIntervalMs?: number
+ keepaliveCountMax?: number
+}
+
+export type SshHostKeyVerifier = (label: string, hostKey: Buffer) => boolean | Promise<boolean>
+
+export interface SshTransport {
+ connect: (
+ profile: MachineProfile,
+ hostKeyVerifier: SshHostKeyVerifier,
+ options: SshTransportOptions,
+ signal?: AbortSignal,
+ ) => Promise<SshSession>
+}
+
+export type SshConnectFailureKind
+ = | 'key-rejected'
+ | 'password-rejected'
+ | 'unreachable'
+ | 'other'
diff --git a/packages/dsh-tauri-ssh/src/host/service/transport.utils.ts b/packages/dsh-tauri-ssh/src/host/service/transport.utils.ts
new file mode 100644
index 00000000..bcb46cc6
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/service/transport.utils.ts
@@ -0,0 +1,70 @@
+import type { SshConnectFailureKind } from './transport.types'
+import { get as httpGet } from 'node:http'
+
+const UNREACHABLE_CODES = new Set([
+ 'ENOTFOUND',
+ 'EAI_AGAIN',
+ 'ECONNREFUSED',
+ 'ETIMEDOUT',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'ECONNRESET',
+])
+
+function isUnreachable(error: Error): boolean {
+ const code = (error as NodeJS.ErrnoException).code
+ if (code !== undefined && UNREACHABLE_CODES.has(code))
+ return true
+ return /timed?\s?out|connection refused|econnrefused|no route to host|name or service not known|getaddrinfo/iu.test(error.message)
+}
+
+export function classifyConnectFailure(error: unknown, passwordOffered: boolean): SshConnectFailureKind {
+ const message = error instanceof Error ? error.message : String(error)
+ const normalized = error instanceof Error ? error : new Error(message)
+ if (isUnreachable(normalized))
+ return 'unreachable'
+ if (/all configured authentication methods failed|authentication failed|no supported authentication/iu.test(message))
+ return passwordOffered ? 'password-rejected' : 'key-rejected'
+ return 'other'
+}
+
+export function describeConnectFailure(kind: SshConnectFailureKind, error: unknown): string {
+ const message = error instanceof Error ? error.message : String(error)
+ switch (kind) {
+ case 'key-rejected':
+ return 'authentication failed: no key or ssh-agent was accepted — check your keys or store a password for this machine'
+ case 'password-rejected':
+ return 'authentication failed: the stored password was rejected — update the stored password'
+ case 'unreachable':
+ return `host unreachable: ${message === '' ? 'SSH connection failed' : message}`
+ default:
+ return message === '' ? 'SSH connection failed' : message
+ }
+}
+
+export function injectCookieHead(head: string, cookie: string): string {
+ const lines = head.split('\r\n')
+ const isUpgrade = lines.some(line => /^connection:\s*upgrade/iu.test(line))
+ const kept = lines.filter(line =>
+ !/^cookie:/iu.test(line) && (isUpgrade || !/^connection:/iu.test(line)))
+ kept.splice(1, 0, `Cookie: ${cookie}`)
+ if (!isUpgrade)
+ kept.splice(2, 0, 'Connection: close')
+ return kept.join('\r\n')
+}
+
+export function mintTunnelCookie(authenticatedUrl: string): Promise<string | undefined> {
+ return new Promise((resolve) => {
+ const request = httpGet(authenticatedUrl, (response) => {
+ response.resume()
+ const raw = response.headers['set-cookie']?.[0]
+ const pair = raw === undefined ? undefined : raw.split(';')[0]?.trim()
+ resolve(pair === undefined || pair === '' ? undefined : pair)
+ })
+ request.on('error', () => resolve(undefined))
+ request.setTimeout(3_000, () => {
+ request.destroy()
+ resolve(undefined)
+ })
+ })
+}
diff --git a/packages/dsh-tauri-ssh/src/host/storage/driver.ts b/packages/dsh-tauri-ssh/src/host/storage/driver.ts
new file mode 100644
index 00000000..440dffe2
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/storage/driver.ts
@@ -0,0 +1,55 @@
+import type { Driver } from 'unstorage'
+import { randomBytes } from 'node:crypto'
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname } from 'pathe'
+import { stateDocumentPath } from '../config/runtime'
+
+const DOCUMENT_KEY = 'state'
+
+export function sshDocumentDriver(): Driver {
+ return {
+ name: 'dsh-tauri-ssh-document',
+ hasItem(key: string): boolean {
+ return key === DOCUMENT_KEY && readDocument() !== undefined
+ },
+ getItem(key: string): string | null {
+ if (key !== DOCUMENT_KEY)
+ return null
+ return readDocument() ?? null
+ },
+ setItem(key: string, value: string): void {
+ if (key === DOCUMENT_KEY)
+ writeDocument(value)
+ },
+ removeItem(key: string): void {
+ if (key === DOCUMENT_KEY)
+ rmSync(stateDocumentPath(), { force: true })
+ },
+ getKeys(): string[] {
+ return [DOCUMENT_KEY]
+ },
+ }
+}
+
+function readDocument(): string | undefined {
+ try {
+ return readFileSync(stateDocumentPath(), 'utf8')
+ }
+ catch {
+ return undefined
+ }
+}
+
+function writeDocument(text: string): void {
+ const file = stateDocumentPath()
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`
+ try {
+ writeFileSync(temp, `${JSON.stringify(JSON.parse(text) as unknown, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
+ renameSync(temp, file)
+ }
+ catch (error) {
+ rmSync(temp, { force: true })
+ throw error
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/storage/index.ts b/packages/dsh-tauri-ssh/src/host/storage/index.ts
index e3a5d7e1..d3cf2365 100644
--- a/packages/dsh-tauri-ssh/src/host/storage/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/storage/index.ts
@@ -1,251 +1,4 @@
-/**
- * Plugin config and the plugin-owned machine state document. 0.1.7 removed
- * `ctx.settings.register` (namespaces are now plugin Config entries), so the
- * machine table and the enable flag live in one JSON document under the
- * harness home — the same shape of self-owned persistence the TOFU host-key
- * store already uses, and therefore kernel-version agnostic.
- * @module dsh-tauri-ssh/host/storage
- */
+import { createStorage } from 'unstorage'
+import { sshDocumentDriver } from './driver'
-import type { MachineId, MachineProfile } from '../types/index'
-import { randomBytes } from 'node:crypto'
-import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
-import { dirname } from 'pathe'
-import z from 'schemastery'
-import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
-import { MachineId as brandMachineId } from '../types/index'
-
-export { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT } from '../../shared/constants'
-
-/** Default remote dsh profile name (`dsh --profile <name> web`). */
-export const DEFAULT_REMOTE_PROFILE = 'remote'
-
-/** Schema version of the state document. */
-export const STATE_VERSION = 1
-
-/** The persisted plugin state: the feature switch plus the manual machine dict. */
-export interface SshState {
- enabled: boolean
- machines: Record<string, MachineProfile>
-}
-
-/**
- * Validated plugin config. Timeouts are deployment-varying choices, never
- * hardcoded tunables.
- */
-export interface Config {
- /** SSH handshake/authentication deadline in milliseconds. */
- connectTimeoutMs: number
- /** Per-probe deadline of the remote-instance health check in milliseconds. */
- healthCheckTimeoutMs: number
- /** Pause between health-check probes while waiting for the instance. */
- healthPollIntervalMs: number
- /** How many probes run before the bootstrap attempt is declared failed. */
- healthPollAttempts: number
- /** Override for the TOFU known-hosts file (defaults under the harness home). */
- knownHostsPath?: string
- /** Override for the machine state document (defaults under the harness home). */
- statePath?: string
- /** Override for the `~/.ssh` directory the credentials resolve against. */
- sshDir?: string
- /** Default remote `dsh web` port for machines that do not override it. */
- remotePort?: number
- /**
- * Default remote-instance start command for machines without their own
- * override; `{port}` is replaced with the machine's remote port. Covers
- * the discovered `~/.ssh/config` aliases, which cannot carry per-machine
- * overrides.
- */
- startCommand?: string
- /**
- * The DSH install-source repository anchor. Defaults to the official DSH
- * repository (org verified: `deepseek-ai`); the binary install resolves its
- * download repository from it — the official anchor maps onto the official
- * packaging repository (`dsh-tauri-desk/deepseek-harness-pkg`), and any
- * other configured `owner/name` or GitHub URL is used directly as the
- * release repository, so forks/mirrors of the packaging repo keep working.
- */
- installRepo?: string
- /**
- * DSH version pin for the binary install: a semver (`0.1.5-rc.3`) or a full
- * release tag (`dsh-0.1.5-rc.3-35833820356`). Defaults to the recommended
- * version; unresolvable pins fall back to the latest stable release.
- */
- installRef?: string
- /** Deadline for one remote binary install (download + verify + extract + pnpm assembly). */
- installTimeoutMs?: number
- /** ssh2 keepalive interval in milliseconds — the connection watchdog's heartbeat. */
- keepaliveIntervalMs: number
- /** How many unanswered keepalives declare the connection dead (the watchdog threshold). */
- keepaliveCountMax: number
- /** Delay before the first reconnect retry, in milliseconds. */
- reconnectInitialDelayMs: number
- /** Ceiling of the exponential reconnect backoff, in milliseconds. */
- reconnectMaxDelayMs: number
- /**
- * Give-up threshold: how many reconnect retries run (after the initial
- * attempt) before the machine lands in the `given-up` terminal state.
- */
- reconnectMaxAttempts: number
-}
-
-/** Plugin config schema; schemastery fills defaults before construction. */
-export const ConfigSchema: z<Config> = z.object({
- connectTimeoutMs: z.number().default(15_000),
- healthCheckTimeoutMs: z.number().default(3_000),
- healthPollIntervalMs: z.number().default(1_000),
- healthPollAttempts: z.number().default(30),
- knownHostsPath: z.string(),
- statePath: z.string(),
- sshDir: z.string(),
- remotePort: z.number().default(DEFAULT_REMOTE_PORT),
- startCommand: z.string(),
- installRepo: z.string(),
- installRef: z.string(),
- installTimeoutMs: z.number().default(1_800_000),
- keepaliveIntervalMs: z.number().default(10_000),
- keepaliveCountMax: z.number().default(3),
- reconnectInitialDelayMs: z.number().default(1_000),
- reconnectMaxDelayMs: z.number().default(20_000),
- reconnectMaxAttempts: z.number().default(6),
-}) as z<Config>
-
-/** Project one stored record; malformed rows are dropped, never fatal. */
-export function machineProfileOf(raw: unknown): MachineProfile | undefined {
- if (typeof raw !== 'object' || raw === null)
- return undefined
- const value = raw as Record<string, unknown>
- if (typeof value.id !== 'string' || value.id === '')
- return undefined
- if (typeof value.name !== 'string')
- return undefined
- if (typeof value.host !== 'string' || value.host === '')
- return undefined
- if (typeof value.user !== 'string')
- return undefined
- return {
- id: brandMachineId(value.id),
- name: value.name,
- host: value.host,
- port: typeof value.port === 'number' ? value.port : DEFAULT_SSH_PORT,
- user: value.user,
- remotePort: typeof value.remotePort === 'number' ? value.remotePort : DEFAULT_REMOTE_PORT,
- ...typeof value.password === 'string' && value.password !== '' ? { password: value.password } : {},
- ...typeof value.passphrase === 'string' && value.passphrase !== '' ? { passphrase: value.passphrase } : {},
- ...typeof value.profileName === 'string' && value.profileName !== '' ? { profileName: value.profileName } : {},
- ...typeof value.startCommand === 'string' && value.startCommand !== '' ? { startCommand: value.startCommand } : {},
- ...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},
- ...value.tintBorder === true ? { tintBorder: true } : {},
- }
-}
-
-/** Project a stored dict into a profile map; a mismatched row is dropped. */
-export function machinesOf(value: unknown): Map<MachineId, MachineProfile> {
- const profiles = new Map<MachineId, MachineProfile>()
- if (typeof value !== 'object' || value === null)
- return profiles
- for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
- const profile = machineProfileOf(raw)
- if (profile === undefined || profile.id !== key)
- continue
- profiles.set(brandMachineId(key), profile)
- }
- return profiles
-}
-
-/** Parse one state document; an absent or corrupt file reads as the default state. */
-function readState(file: string): SshState {
- let parsed: unknown
- try {
- parsed = JSON.parse(readFileSync(file, 'utf8')) as unknown
- }
- catch {
- return { enabled: false, machines: {} }
- }
- if (typeof parsed !== 'object' || parsed === null)
- return { enabled: false, machines: {} }
- const record = parsed as { enabled?: unknown, machines?: unknown }
- const machines: Record<string, MachineProfile> = {}
- for (const [key, profile] of machinesOf(record.machines))
- machines[key] = profile
- return { enabled: record.enabled === true, machines }
-}
-
-/** Atomically replace `file` with `content` (same-directory rename, owner-only). */
-function writeStateFile(file: string, content: string): void {
- mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
- const temp = `${file}.${randomBytes(6).toString('hex')}.tmp`
- try {
- writeFileSync(temp, content, { mode: 0o600, flag: 'wx' })
- renameSync(temp, file)
- }
- catch (error) {
- rmSync(temp, { force: true })
- throw error
- }
-}
-
-/**
- * File-backed machine state. The document is read once at construction (the
- * manager needs the profile map synchronously) and every write is atomic and
- * announces itself to the service, which refreshes the manager.
- */
-export class MachineStateStore {
- private state: SshState
-
- private readonly listeners = new Set<() => void>()
-
- /** @param file - absolute path of the state document. */
- constructor(private readonly file: string) {
- this.state = readState(file)
- }
-
- /** Whether the SSH feature is switched on. */
- enabled(): boolean {
- return this.state.enabled
- }
-
- /** The stored manual machines keyed by id. */
- machines(): Map<MachineId, MachineProfile> {
- const profiles = new Map<MachineId, MachineProfile>()
- for (const [key, profile] of Object.entries(this.state.machines)) {
- const id = brandMachineId(key)
- profiles.set(id, { ...profile, id })
- }
- return profiles
- }
-
- /** Subscribe to in-process changes; returns the unsubscribe. */
- subscribe(listener: () => void): () => void {
- this.listeners.add(listener)
- return () => this.listeners.delete(listener)
- }
-
- /** Flip the feature switch (idempotent). */
- setEnabled(enabled: boolean): void {
- if (this.state.enabled === enabled)
- return
- this.commit({ ...this.state, enabled })
- }
-
- /** Upsert one machine profile. */
- saveMachine(profile: MachineProfile): void {
- this.commit({ ...this.state, machines: { ...this.state.machines, [profile.id]: profile } })
- }
-
- /** Delete one machine profile (idempotent for absent ids). */
- removeMachine(machineId: MachineId): void {
- if (this.state.machines[machineId] === undefined)
- return
- const machines = { ...this.state.machines }
- delete machines[machineId]
- this.commit({ ...this.state, machines })
- }
-
- /** Persist the next state, adopt it, then notify subscribers. */
- private commit(next: SshState): void {
- writeStateFile(this.file, `${JSON.stringify({ version: STATE_VERSION, ...next }, null, 2)}\n`)
- this.state = next
- for (const listener of this.listeners) listener()
- }
-}
+export const storage = createStorage({ driver: sshDocumentDriver() })
diff --git a/packages/dsh-tauri-ssh/src/host/types/index.ts b/packages/dsh-tauri-ssh/src/host/types/index.ts
index 7426b90a..24cee8c8 100644
--- a/packages/dsh-tauri-ssh/src/host/types/index.ts
+++ b/packages/dsh-tauri-ssh/src/host/types/index.ts
@@ -1,77 +1,35 @@
-/**
- * Public type vocabulary of the SSH remote-machine plugin: the `MachineId`
- * brand, the stored machine profile, its redacted view, connection status,
- * the tunnel link, the typed failure vocabulary, and the structural host
- * services the plugin consumes (the DSH packages providing them are private
- * to the harness, so the plugin declares just the surface it touches).
- * @module dsh-tauri-ssh/host/types
- */
-
+import type { Buffer } from 'node:buffer'
import type { IncomingMessage, ServerResponse } from 'node:http'
-/** Identifies one SSH machine profile. A generated uuid, never the host name: hosts are not unique. */
export type MachineId = string & { readonly __machineId: unique symbol }
-/**
- * Brand a string as a {@link MachineId}.
- * @param id - the raw machine id string.
- * @returns the same string, branded (a compile-time cast — no runtime cost).
- */
// eslint-disable-next-line ts/no-redeclare -- 品牌类型惯用法:值与类型同名
export function MachineId(id: string): MachineId {
return id as MachineId
}
-/**
- * One stored SSH machine profile: the state document's machine value shape.
- * Credentials are deliberately sparse: authentication runs on the host's own
- * `~/.ssh` (config aliases, `IdentityFile`s, default keys), so only the
- * optional fallback secrets live here — they never ride a redacted wire
- * surface, only the plugin's in-process value.
- */
export interface MachineProfile {
- /** Stable profile id (generated uuid). */
id: MachineId
- /** Display name (duplicates allowed). */
name: string
- /** SSH server host name, IP literal, or a `~/.ssh/config` `Host` alias. */
host: string
- /** SSH server TCP port; a config `Port` override wins when present. */
port: number
- /** Login user name; empty means "resolve from config or the OS user". */
user: string
- /** Password credential; secret. Optional fallback when no key works. */
password?: string
- /** Passphrase unlocking the `~/.ssh` identity files; secret. Optional. */
passphrase?: string
- /** TCP port the remote `dsh web` instance listens on (loopback). */
remotePort: number
- /**
- * Remote dsh profile name (`dsh --profile <name> web`); defaults to
- * `remote`. Ignored when the machine carries its own `startCommand`.
- */
profileName?: string
- /** Command that starts the remote instance; defaults to `dsh web --host 127.0.0.1 --port <remotePort>`. */
startCommand?: string
- /** Optional identity color (any CSS color) shown as the machine's pip in the UI. */
color?: string
- /** Whether the identity color also tints the machine card's border in the UI. */
tintBorder?: boolean
}
-/**
- * Redacted view of one machine profile: secrets replaced by presence flags.
- * This is the only profile shape that may cross a wire surface.
- */
export interface MachineView {
id: MachineId
name: string
host: string
port: number
user: string
- /** Whether the profile currently holds a password (the value itself never rides). */
hasPassword: boolean
- /** Whether the profile currently holds a key passphrase (the value itself never rides). */
hasPassphrase: boolean
remotePort: number
profileName?: string
@@ -80,7 +38,6 @@ export interface MachineView {
tintBorder?: boolean
}
-/** One machine row as the settings page writes it: config fields only, no secrets. */
export interface MachineSaveRow {
name: string
host: string
@@ -93,28 +50,11 @@ export interface MachineSaveRow {
tintBorder?: boolean
}
-/** Secret values the settings page writes (write-only direction; absent = keep stored). */
export interface MachineSecretWrite {
password?: string
passphrase?: string
}
-/**
- * Live connection state of one machine — the C-STATE vocabulary consumed by
- * the status dot (S4) and the switcher (S5).
- *
- * - `disconnected` — not connected (never tried, or a deliberate disconnect);
- * - `testing` — a one-shot `machine.test` probe is in flight;
- * - `connecting` — a user-initiated connect is in flight;
- * - `connected` — the tunnel link is live;
- * - `reconnecting` — an established connection dropped and the automatic
- * retry loop owns the machine (a scheduled retry is announced through
- * {@link SshMachineStatus.nextRetryAt});
- * - `given-up` — terminal failure state: either the first connect never
- * succeeded or the reconnect budget ran out. `lastError` carries the
- * reason; the same word is used for both sources on purpose (switchers
- * need not distinguish them). A fresh `connect` attempt exits it.
- */
export type SshConnectionState
= | 'disconnected'
| 'testing'
@@ -123,60 +63,38 @@ export type SshConnectionState
| 'reconnecting'
| 'given-up'
-/** Which credential the transport last authenticated with. */
export type SshAuthMethod = 'agent' | 'key' | 'password'
-/** One progress phase of a connection-plane operation, shown live in the UI. */
export type SshProgressPhase = 'handshake' | 'starting' | 'probing' | 'installing' | 'syncing'
-/** Structured progress of an in-flight connection-plane operation. */
export interface SshProgress {
phase: SshProgressPhase
- /** Progress position (health-probe attempt, or the sync item's 1-based index). */
attempt?: number
- /** Progress total (health-probe attempt budget, or the sync item count). */
total?: number
- /** Display label of the work in flight (the sync item's name). */
item?: string
- /** Recent streaming output of the operation (the install log), newest last. */
log?: string
}
-/** Transport-level status of one machine. */
export interface SshMachineStatus {
machineId: MachineId
state: SshConnectionState
- /** Local loopback URL of the SSH tunnel to the remote instance; present while connected. */
tunnelBaseUrl?: string
- /** Operator-facing failure description of the last failed transition; absent while healthy. */
lastError?: string
- /** Whether the last failure was "dsh not installed on the remote" (offers install). */
dshMissing?: boolean
- /** Live progress of the in-flight operation; absent while idle. */
progress?: SshProgress
- /** Epoch milliseconds of the next scheduled reconnect retry; present while `reconnecting` waits. */
nextRetryAt?: number
- /** Which credential the live (or last successful) connection authenticated with. */
authMethod?: SshAuthMethod
}
-/** A live machine link: the id and the tunnel base URL. */
export interface SshLink {
machineId: MachineId
- /** `http://127.0.0.1:<localPort>` — loopback only, never exposed to remote clients. */
tunnelBaseUrl: string
}
-/** Outcome of a one-shot connection test. */
export type SshTestResult
= | { ok: true, banner: string }
| { ok: false, message: string }
-/**
- * One stage of the machine event channel: S2's bootstrap pipeline stages
- * plus S3's connection-lifecycle stages (`auth`/`reconnect`, declared by
- * {@link SSH_CONNECTION_EVENT_STAGES} on the same channel).
- */
export type SshMachineStage
= | 'probe'
| 'download'
@@ -188,55 +106,32 @@ export type SshMachineStage
| 'auth'
| 'reconnect'
-/** Terminal verdict of a machine event, when it settles an operation. */
export type SshMachineTerminal = 'success' | 'failed'
-/**
- * One machine-scoped event of the `/api-ssh` `machine.events` channel: a
- * displayable log line tagged with its pipeline stage. `seq` is per-machine
- * and monotonically increasing; consumers poll with the last seen seq.
- */
export interface SshMachineEvent {
- /** Per-machine sequence number, starting at 1. */
seq: number
- /** Wall-clock timestamp of the event (ISO-8601). */
ts: string
- /** The machine the event is about. */
machineId: MachineId
- /** The pipeline stage the line belongs to. */
stage: SshMachineStage
- /** The displayable log line. */
line: string
- /** Terminal verdict, present only on the settling event of an operation. */
terminal?: SshMachineTerminal
- /** Failure reason, present on `terminal: 'failed'` events. */
reason?: string
}
-/** The `machine.events` response: the drained slice plus the poll cursor. */
export interface SshMachineEventsPage {
events: SshMachineEvent[]
- /** The next event's seq; poll again with `sinceSeq = nextSeq - 1`. */
nextSeq: number
}
-/** Outcome of a one-shot remote dsh install. */
export interface SshInstallResult {
- /** Components freshly installed this run (a subset of node/dsh/pnpm). */
installed: string[]
- /** The pinned DSH release actually installed (`<tag>` or `npm:<version>`). */
dshRef: string
- /** The resolved DSH semver. */
dshVersion: string
- /** Absolute path of the installed `dsh` entry as the remote sees it. */
dshPath: string
- /** Whether the local DEEPSEEK_API_KEY was copied to the remote `~/.dsh/.env`. */
credentialsCopied: boolean
- /** Operator-facing description when the credentials copy itself failed. */
credentialsError?: string
}
-/** Closed failure vocabulary of the ssh primitives. */
export type SshErrorCode
= | 'machine-not-found'
| 'machine-connect-failed'
@@ -247,118 +142,95 @@ export type SshErrorCode
| 'machine-reconnecting'
| 'machine-sync-failed'
-/**
- * Connection-lifecycle stages this plugin feeds into the machine-level event
- * channel (C-EVENT). The channel itself — `/api-ssh` `machine.events` — is
- * owned by S2; this constant declares S3's augmentation of
- * {@link SshMachineStage}, and the `satisfies` clause keeps it checked
- * against the merged union (adding a stage here requires it on the union).
- */
-export const SSH_CONNECTION_EVENT_STAGES = ['auth', 'reconnect'] as const satisfies readonly SshMachineStage[]
-
-/** One connection-lifecycle stage of the machine event channel (S3's slice). */
-export type SshConnectionEventStage = typeof SSH_CONNECTION_EVENT_STAGES[number]
-
-/** Label of one local user-level skill root the sync scans. */
export type SyncSkillRoot = 'dsh' | 'agents'
-/** One plugin sync candidate: a dependency of the local dsh profile. */
export interface SyncPluginItem {
- /** Package name as the profile's package.json spells it. */
name: string
- /** The dependency spec to install on the remote (e.g. `github:org/repo`, `^1.2.0`). */
spec: string
- /** Whether the spec can be installed on a remote at all. */
syncable: boolean
- /** Operator-facing reason a non-syncable spec is excluded. */
reason?: string
}
-/** One skill sync candidate: a SKILL.md directory under a user-level root. */
export interface SyncSkillItem {
name: string
- /** The local root the skill was found under. */
root: SyncSkillRoot
}
-/** The `sync.preview` value: what the panel offers for selection. */
export interface SyncPreview {
plugins: SyncPluginItem[]
skills: SyncSkillItem[]
}
-/** One plugin the panel asked to sync, as `sync.apply` receives it. */
export interface SyncPluginRef {
name: string
spec: string
}
-/** One skill the panel asked to sync, as `sync.apply` receives it. */
export interface SyncSkillRef {
name: string
root: SyncSkillRoot
}
-/** Outcome of exactly one synced item — the per-item failure surface. */
export interface SyncItemResult {
kind: 'plugin' | 'skill'
- /** Display identity, matching the ref the panel sent. */
name: string
- /** Skill root; plugins carry none. */
root?: SyncSkillRoot
ok: boolean
- /**
- * Operator-facing failure description; absent on success. It leads with the
- * cause line(s) and keeps the tail as context — a long install log buries
- * the real error well above the end.
- */
error?: string
- /**
- * The command's own output (trimmed, newest kept) for on-demand display;
- * absent on success and when the command printed nothing.
- */
log?: string
}
-/** The `sync.apply` value: every requested item, success and failure alike. */
export interface SyncApplyResult {
items: SyncItemResult[]
}
-/** Typed failure thrown by ssh primitives so consumers map business codes without string matching. */
export class SshError extends Error {
- /**
- * @param code - closed business code of the failure.
- * @param machineId - the machine the failure is about.
- * @param message - operator-facing description.
- */
constructor(readonly code: SshErrorCode, readonly machineId: MachineId, message: string) {
super(message)
this.name = 'SshError'
}
}
-/** The webserver route shape this plugin registers (a subset of the harness's WebRoute). */
+export interface SshExecResult {
+ code: number | null
+ stdout: string
+ stderr: string
+}
+
+export interface SshExecOptions {
+ timeoutMs?: number
+ onData?: (chunk: string) => void
+ stdinData?: Buffer
+}
+
+export interface TunnelHeaderInjection {
+ cookie: string | undefined
+}
+
+export interface SshTunnelHandle {
+ localPort: number
+ close: () => Promise<void>
+}
+
+export interface SshSession {
+ readonly authMethod?: SshAuthMethod | undefined
+ exec: (command: string, options?: SshExecOptions) => Promise<SshExecResult>
+ openTunnel: (remotePort: number, preferredLocalPort?: number, injection?: TunnelHeaderInjection) => Promise<SshTunnelHandle>
+ onClosed: (callback: () => void) => void
+ close: () => Promise<void>
+}
+
export interface HostWebRoute {
kind: 'exact' | 'prefix'
- /** Absolute pathname, no trailing slash. */
path: string
- /** Owns the full response lifecycle (may hold the response open, e.g. SSE). */
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
}
-/** The webserver service surface this plugin needs. */
export interface HostWebServer {
register: (route: HostWebRoute) => () => void
}
-/**
- * The host context this plugin's apply receives: the webserver (route mount)
- * plus the teardown-effect seat. Structural — the harness's real context
- * duck-types onto it.
- */
export interface SshHostContext {
webServer: HostWebServer
- /** Register a teardown effect (narrow cordis surface). */
- effect: (execute: () => () => void, label?: string) => unknown
+ effect: (execute: () => (() => void) | void, label?: string) => unknown
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/allowlist.test.ts b/packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts
similarity index 99%
rename from packages/dsh-tauri-ssh/src/host/service/allowlist.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts
index d0c0a267..b3e74ae3 100644
--- a/packages/dsh-tauri-ssh/src/host/service/allowlist.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/allowlist.test.ts
@@ -1,4 +1,4 @@
-import type { SshExecResult, SshSession } from './transport'
+import type { SshExecResult, SshSession } from '../types/index'
import { Buffer } from 'node:buffer'
import { describe, expect, it, vi } from 'vitest'
import { parse } from 'yaml'
diff --git a/packages/dsh-tauri-ssh/src/host/service/allowlist.ts b/packages/dsh-tauri-ssh/src/host/utils/allowlist.ts
similarity index 53%
rename from packages/dsh-tauri-ssh/src/host/service/allowlist.ts
rename to packages/dsh-tauri-ssh/src/host/utils/allowlist.ts
index 47f6da6c..6cb7dd07 100644
--- a/packages/dsh-tauri-ssh/src/host/service/allowlist.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/allowlist.ts
@@ -1,51 +1,20 @@
-/**
- * Profile build-allowlist carry-over (local → remote).
- *
- * pnpm refuses to run a git-hosted plugin's `prepare` build unless the profile
- * allows it (`allowBuilds` map, pnpm 11; `onlyBuiltDependencies` list, pnpm 10;
- * both in the profile's `pnpm-workspace.yaml`). The desktop's own installer
- * writes those keys back locally after a gated install, but a remote profile
- * starts from the bare template — so every git-hosted plugin the sync panel
- * pushed died on pnpm's prepare gate. This module reads the two sections from
- * the local profile and merges the missing keys into the remote profile's file.
- *
- * Cross-platform: keys describing the *local* filesystem (drive letters,
- * backslash paths, `file:`/`link:`/`workspace:` resolutions) can never match on
- * a POSIX remote, so they are dropped instead of copied. The merge is a YAML
- * round-trip (never string concatenation): git depPath keys carry `@`, `:`,
- * `/` and `#`, which only a real serializer quotes correctly.
- * @module dsh-tauri-ssh/host/service/allowlist
- */
-
-import type { SshSession } from './transport'
+import type { SshSession } from '../types/index'
import { parse, stringify } from 'yaml'
-import { shQuote } from './transport'
+import { shQuote } from './shell'
-/** The two build-allowlist sections of one profile's `pnpm-workspace.yaml`. */
export interface WorkspaceAllowlist {
- /** pnpm 11's map form: depPath (or package name) → allowed. */
allowBuilds: Record<string, boolean>
- /** pnpm 10's list form: package names allowed to run build scripts. */
onlyBuiltDependencies: string[]
}
-/** The empty allowlist (a profile that installed nothing gated). */
export const EMPTY_ALLOWLIST: WorkspaceAllowlist = { allowBuilds: {}, onlyBuiltDependencies: [] }
-/** The template dsh writes for a fresh profile (mirrors the desktop's fallback). */
export const WORKSPACE_TEMPLATE = 'packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n'
-/** The remote profile directory, relative to `$HOME` (the layout's own convention). */
export function remoteProfileDir(profileName: string): string {
return `.dsh/profiles/${profileName}`
}
-/**
- * Whether one allowlist key can ever match on a POSIX remote: a key that names
- * a local-only resolution (`C:\…`, `file:…`, `link:…`, `workspace:…`) or spells
- * a Windows path is dropped — pnpm could never satisfy it there, and copying it
- * would only suggest the remote has a permission it does not.
- */
export function isPortableAllowKey(key: string): boolean {
const value = key.trim()
if (value === '')
@@ -54,25 +23,16 @@ export function isPortableAllowKey(key: string): boolean {
return false
if (/^[a-z]:[\\/]/iu.test(value))
return false
- // The resolution decides: a bare name is the resolution, and a `name@spec`
- // key keeps only its spec. Scoped names (`@scope/pkg`) start with `@`; the
- // slice below then yields `scope/pkg`, which still matches neither marker.
const resolution = value.includes('@') ? value.slice(value.indexOf('@') + 1) : value
if (/^(?:file|link|workspace):/iu.test(resolution))
return false
return true
}
-/** Read one boolean-ish YAML value; anything but an explicit false reads as allowed. */
function allowedValue(value: unknown): boolean {
return value !== false
}
-/**
- * Parse the two allowlist sections out of one workspace document. Unparsable
- * text, a non-mapping document, or missing sections all read as empty: the
- * caller carries what it can without ever blocking the connection.
- */
export function parseAllowlist(text: string): WorkspaceAllowlist {
let doc: unknown
try {
@@ -102,20 +62,6 @@ export function parseAllowlist(text: string): WorkspaceAllowlist {
return { allowBuilds, onlyBuiltDependencies: onlyBuilt }
}
-/**
- * Merge the local allowlist into one remote workspace document.
- *
- * Only *missing* keys are carried: an explicit `false` the operator wrote on
- * the remote stays a denial. The document is round-tripped through the YAML
- * library, so every other key (packages, nodeLinker, user settings) survives
- * and the emitted quoting is always valid.
- * @param remoteYaml - the remote profile's current document (empty when absent).
- * @param incoming - the local profile's allowlist sections.
- * @returns the document to write and the keys that were actually added
- * (empty `added` means the remote already allows everything: do not write).
- * @throws {Error} when the remote document is not valid YAML — rewriting it
- * would destroy whatever the operator has there.
- */
export function mergeWorkspaceAllowlist(remoteYaml: string, incoming: WorkspaceAllowlist): { yaml: string, added: string[] } {
const text = remoteYaml.trim() === '' ? WORKSPACE_TEMPLATE : remoteYaml
let doc: unknown
@@ -159,19 +105,6 @@ export function mergeWorkspaceAllowlist(remoteYaml: string, incoming: WorkspaceA
return { yaml: stringify(record), added }
}
-/**
- * Parse the build keys pnpm names in a failed install's output, mirroring the
- * desktop's own installer (its `parse_allowlist_keys`): the guidance prints an
- * `allowBuilds:` example whose following indented `<key>: true` line is the
- * exact depPath to allow, and older pnpm prints an `onlyBuiltDependencies:`
- * list ("Ignored build scripts: name@version"). Both forms are read here.
- *
- * Needed because a git depPath pins the *resolved commit*: the key recorded on
- * this machine for an older commit never matches the commit a remote resolves
- * today, so the failure output is the only correct source for that key.
- * @param output - the failed command's stdout and stderr, concatenated.
- * @returns the keys to grant, deduped and in output order.
- */
export function parseBuildAllowKeys(output: string): string[] {
const keys: string[] = []
const push = (key: string): void => {
@@ -183,7 +116,6 @@ export function parseBuildAllowKeys(output: string): string[] {
for (const [index, line] of lines.entries()) {
const trimmed = line.trim()
if (trimmed === 'allowBuilds:') {
- // 条目必须缩进且形如 `<key>: true`:先切掉缩进,再按「冒号 + true」判定
const entry = lines[index + 1] ?? ''
const match = isIndented(entry) ? /^(.*):[ \t]*true$/u.exec(entry.trim()) : null
if (match?.[1] !== undefined)
@@ -198,7 +130,7 @@ export function parseBuildAllowKeys(output: string): string[] {
continue
}
if (body !== '' && !indented)
- break // 顶层键:列表已结束
+ break
}
}
const ignored = line.includes('Ignored build scripts:') ? line.split('Ignored build scripts:')[1] ?? '' : ''
@@ -210,35 +142,19 @@ export function parseBuildAllowKeys(output: string): string[] {
return keys
}
-/** Whether one output line is indented (a block entry rather than a top-level key). */
function isIndented(line: string): boolean {
return line.startsWith(' ') || line.startsWith('\t')
}
-/** Read the remote profile's workspace document (empty when it does not exist yet). */
export function allowlistReadCommand(profileName: string): string {
return `cat "$HOME/${remoteProfileDir(profileName)}/pnpm-workspace.yaml" 2>/dev/null || true`
}
-/**
- * Write the merged document back. The payload is one shell-quoted argument
- * (never a heredoc or a base64 pipe): `shQuote` keeps every `@`, `:`, `#` and
- * newline intact, and the text is emitted with LF endings on every platform.
- */
export function allowlistWriteCommand(profileName: string, yamlText: string): string {
const dir = `$HOME/${remoteProfileDir(profileName)}`
return `mkdir -p "${dir}" && printf %s ${shQuote(yamlText)} > "${dir}/pnpm-workspace.yaml"`
}
-/**
- * Carry the local allowlist into the remote profile over one live session.
- * Idempotent and quiet when there is nothing to add; a remote document that
- * cannot be parsed leaves the file untouched.
- * @param session - the authenticated session to run the file commands on.
- * @param profileName - the remote profile whose workspace file is the target.
- * @param local - the local profile's allowlist sections.
- * @returns the keys that were added (empty when the remote was already complete).
- */
export async function carryWorkspaceAllowlist(
session: SshSession,
profileName: string,
diff --git a/packages/dsh-tauri-ssh/src/host/service/assets.test.ts b/packages/dsh-tauri-ssh/src/host/utils/assets.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/assets.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/assets.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/assets.ts b/packages/dsh-tauri-ssh/src/host/utils/assets.ts
similarity index 52%
rename from packages/dsh-tauri-ssh/src/host/service/assets.ts
rename to packages/dsh-tauri-ssh/src/host/utils/assets.ts
index 2bd2c93e..6e198602 100644
--- a/packages/dsh-tauri-ssh/src/host/service/assets.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/assets.ts
@@ -1,44 +1,19 @@
-/**
- * The remote install asset matrix: `uname` output → platform identifiers, the
- * per-platform choice of the three install assets (Node runtime, DSH
- * distribution, pnpm), and their official → mirror download URL pairs. Pure
- * functions over injectable constants so the matrix is fully unit-testable
- * without touching the network.
- *
- * DSH ships two distribution kinds: the packaged zip (a `pnpm deploy` tree
- * with platform-pinned native modules — only linux x64 and macOS x64 assets
- * exist) and the npm tarball of `@deepseek-ai/dsh` (assembled on the remote
- * by `pnpm install`, which resolves the correct platform natives — the only
- * honest asset for linux arm64, where no packaged zip exists).
- * @module dsh-tauri-ssh/host/service/assets
- */
-
-/** Remote platform identifiers the install matrix understands. */
export type RemoteOs = 'linux' | 'macos'
-/** Remote CPU architectures the install matrix understands. */
export type RemoteArch = 'x64' | 'arm64'
-/** How the DSH distribution is fetched and laid out for one platform. */
export type DshAssetKind = 'pkg-zip' | 'npm-tgz'
-/** One supported matrix cell. */
export interface RemoteAssetMatrix {
os: RemoteOs
arch: RemoteArch
- /** The DSH distribution kind this platform installs. */
dshKind: DshAssetKind
- /** Node.js distribution tarball file name (under `<base>/<version>/`). */
nodeFilename: string
- /** The packaged DSH zip asset name, when `dshKind` is `pkg-zip`. */
dshZipName?: string
- /** The npm package the `npm-tgz` kind installs. */
dshNpmPackage?: string
}
-/** Typed failure for a remote platform outside the install matrix. */
export class UnsupportedRemotePlatformError extends Error {
- /** The raw `uname -srm` parts as detected (first column, last column). */
readonly detected: { system: string, machine: string }
constructor(system: string, machine: string) {
@@ -51,14 +26,6 @@ export class UnsupportedRemotePlatformError extends Error {
}
}
-/**
- * Parse `uname -srm` output into the platform identifiers. Output looks like
- * `Linux 6.8.0-45-generic x86_64` / `Darwin host.local 24.0 arm64`: the
- * system name is the first column, the machine architecture the last.
- * @param unameOut - the raw `uname -srm` stdout.
- * @returns the supported (os, arch) pair.
- * @throws {UnsupportedRemotePlatformError} for anything outside the matrix.
- */
export function parsePlatform(unameOut: string): { os: RemoteOs, arch: RemoteArch } {
const parts = unameOut.trim().split(/\s+/u)
const system = parts[0] ?? ''
@@ -67,22 +34,11 @@ export function parsePlatform(unameOut: string): { os: RemoteOs, arch: RemoteArc
const arch: RemoteArch | undefined = machine === 'x86_64' || machine === 'amd64'
? 'x64'
: machine === 'aarch64' || machine === 'arm64' ? 'arm64' : undefined
- // macOS arm64 remotes are deliberately out of scope (spec S2): the matrix
- // stops at the three combinations the distribution actually covers.
if (os === undefined || arch === undefined || (os === 'macos' && arch === 'arm64'))
throw new UnsupportedRemotePlatformError(system, machine)
return { os, arch }
}
-/**
- * The asset matrix cell for one supported platform.
- * @param os - the remote operating system.
- * @param arch - the remote CPU architecture.
- * @returns the matrix entry (asset names; URLs are built by the dedicated
- * builders).
- * @throws {UnsupportedRemotePlatformError} for combinations outside the
- * matrix (Windows, macOS arm64, other architectures).
- */
export function assetMatrixFor(os: RemoteOs, arch: RemoteArch): RemoteAssetMatrix {
const nodeFilename = nodeFilenameFor(os, arch)
if (nodeFilename === undefined)
@@ -91,8 +47,6 @@ export function assetMatrixFor(os: RemoteOs, arch: RemoteArch): RemoteAssetMatri
return { os, arch, dshKind: 'pkg-zip', nodeFilename, dshZipName: 'deepseek-harness-pkg-linux.zip' }
}
if (os === 'linux' && arch === 'arm64') {
- // No packaged arm64 zip exists (the zips carry x64-pinned natives);
- // the npm tarball lets the remote resolve arm64 natives itself.
return { os, arch, dshKind: 'npm-tgz', nodeFilename, dshNpmPackage: '@deepseek-ai/dsh' }
}
if (os === 'macos' && arch === 'x64') {
@@ -101,31 +55,22 @@ export function assetMatrixFor(os: RemoteOs, arch: RemoteArch): RemoteAssetMatri
throw new UnsupportedRemotePlatformError(os, arch)
}
-/** Bundled Node.js runtime line (satisfies DSH's `^22.19.0 || >=24` engine). */
export const NODE_VERSION = 'v22.22.0'
-/** Node.js official distribution base. */
export const NODE_BASE_URL = 'https://nodejs.org/dist/'
-/** Node.js mirror base (npmmirror; domestic fallback). */
export const NODE_MIRROR_BASE_URL = 'https://npmmirror.com/mirrors/node/'
-/** pnpm version, aligned with the packaged distribution's `packageManager`. */
export const PNPM_VERSION = '11.7.0'
-/** pnpm npm tarball SHA-256; must be updated together with the version. */
export const PNPM_SHA256 = 'deafa7ec98a1218b6a047289b92fbe2395c1e22d3495bb711653013218ee15ee'
-/** pnpm official npm registry tarball base. */
export const PNPM_BASE_URL = 'https://registry.npmjs.org/pnpm/-/'
-/** pnpm mirror (npmmirror registry) tarball base. */
export const PNPM_MIRROR_BASE_URL = 'https://registry.npmmirror.com/pnpm/-/'
-/** npm registry bases for the `npm-tgz` DSH kind (official → mirror). */
export const NPM_REGISTRY_BASES = ['https://registry.npmjs.org', 'https://registry.npmmirror.com'] as const
-/** The Node.js tarball file name for one platform, when supported. */
export function nodeFilenameFor(os: RemoteOs, arch: RemoteArch): string | undefined {
if (os === 'linux' && arch === 'x64')
return `node-${NODE_VERSION}-linux-x64.tar.gz`
@@ -135,11 +80,6 @@ export function nodeFilenameFor(os: RemoteOs, arch: RemoteArch): string | undefi
return `node-${NODE_VERSION}-darwin-x64.tar.gz`
return undefined
}
-/**
- * The Node.js tarball download URLs (official → mirror), in fallback order.
- * @param os - the remote operating system.
- * @param arch - the remote CPU architecture.
- */
export function nodeDownloadUrls(os: RemoteOs, arch: RemoteArch): string[] {
const filename = nodeFilenameFor(os, arch)
if (filename === undefined)
@@ -150,7 +90,6 @@ export function nodeDownloadUrls(os: RemoteOs, arch: RemoteArch): string[] {
]
}
-/** The Node.js `SHASUMS256.txt` URLs (official → mirror). */
export function nodeShasumUrls(): string[] {
return [
`${NODE_BASE_URL}${NODE_VERSION}/SHASUMS256.txt`,
@@ -158,7 +97,6 @@ export function nodeShasumUrls(): string[] {
]
}
-/** The pnpm tarball download URLs (official registry → mirror). */
export function pnpmDownloadUrls(): string[] {
return [
`${PNPM_BASE_URL}pnpm-${PNPM_VERSION}.tgz`,
@@ -166,24 +104,11 @@ export function pnpmDownloadUrls(): string[] {
]
}
-/**
- * The packaged DSH zip download URLs (GitHub official → ghfast.top mirror)
- * for one release tag.
- * @param repo - the GitHub `owner/name` hosting the packaged releases.
- * @param tag - the release tag.
- * @param assetName - the platform zip asset name.
- */
export function dshZipDownloadUrls(repo: string, tag: string, assetName: string): string[] {
const official = `https://github.com/${repo}/releases/download/${tag}/${assetName}`
return [official, `https://ghfast.top/${official}`]
}
-/**
- * The `@deepseek-ai/dsh` npm tarball URLs (official registry → mirror) for
- * one version. The packument's `dist.tarball` URL shape is deterministic.
- * @param packageName - the scoped npm package name.
- * @param version - the resolved package version.
- */
export function dshNpmTarballUrls(packageName: string, version: string): string[] {
return NPM_REGISTRY_BASES.map(base => `${base}/${packageName}/-/${packageName.split('/')[1]}-${version}.tgz`)
}
diff --git a/packages/dsh-tauri-ssh/src/host/service/boot-html.test.ts b/packages/dsh-tauri-ssh/src/host/utils/boot-html.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/boot-html.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/boot-html.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/boot-html.ts b/packages/dsh-tauri-ssh/src/host/utils/boot-html.ts
similarity index 50%
rename from packages/dsh-tauri-ssh/src/host/service/boot-html.ts
rename to packages/dsh-tauri-ssh/src/host/utils/boot-html.ts
index 33b9fbbb..5267d6e8 100644
--- a/packages/dsh-tauri-ssh/src/host/service/boot-html.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/boot-html.ts
@@ -1,27 +1,5 @@
-/**
- * Boot-HTML readiness parsing, ported from the retired Rust engine's
- * `client_urls_from_boot_html` (`service/workflow/utils.rs`): the remote
- * instance's readiness verdict comes from the `__DSH_BOOT__` client manifest
- * embedded in its served HTML — a real manifest proves the actual dsh web
- * server is up with its plugin bundles mounted, where a bare "some HTTP
- * server answered" probe (the legacy fallback) cannot.
- * @module dsh-tauri-ssh/host/service/boot-html
- */
-
-/** The boot-manifest assignment marker inside the served HTML. */
const BOOT_MARKER = /globalThis\[(['"])__DSH_BOOT__\1\]\s*=\s*/u
-/**
- * Extract the client-bundle URLs from one served boot HTML document. Both
- * collection axes of the blueprint are honored: the `entries[].url` graph of
- * the `__DSH_BOOT__` manifest and the `<script src>` attributes (the preload
- * script does not always repeat in entries), deduped and sorted.
- * @param port - the remote instance's loopback port.
- * @param html - the HTML the root probe received.
- * @returns the absolute loopback URLs, or undefined when the document is not
- * a dsh boot page (marker missing, malformed manifest JSON, no entries
- * array, or no same-origin client-bundle paths at all).
- */
export function clientUrlsFromBootHtml(port: number, html: string): string[] | undefined {
const marker = BOOT_MARKER.exec(html)
if (marker === null)
@@ -68,13 +46,6 @@ export function clientUrlsFromBootHtml(port: number, html: string): string[] | u
return unique.map(path => `http://127.0.0.1:${port}${path}`)
}
-/**
- * Whether a probe response body is a plugin bundle (not the SPA fallback):
- * unknown `/plugins/...` paths get rewritten to `index.html` with HTTP 200,
- * so an HTML-looking body must not count as a served bundle.
- * @param okStatus - whether the HTTP exchange itself succeeded (2xx).
- * @param body - the response body.
- */
export function looksLikePluginBundle(okStatus: boolean, body: string): boolean {
if (!okStatus)
return false
@@ -85,11 +56,6 @@ export function looksLikePluginBundle(okStatus: boolean, body: string): boolean
return !lower.startsWith('<!doctype') && !lower.startsWith('<html')
}
-/**
- * Restore the limited named entities boot HTML attributes/JSON carry (the
- * combo route's `&rev=` arrives as `&amp;rev=`).
- * @param value - the raw attribute value.
- */
export function decodeHtmlAttribute(value: string): string {
return value
.replaceAll('&amp;', '&')
@@ -99,10 +65,6 @@ export function decodeHtmlAttribute(value: string): string {
.replaceAll('&gt;', '>')
}
-/**
- * Drop the leading `./` segments a relative bundle path carries.
- * @param path - the raw path.
- */
function trimRelativePrefix(path: string): string {
let rest = path
while (rest.startsWith('./'))
@@ -110,25 +72,10 @@ function trimRelativePrefix(path: string): string {
return rest
}
-/**
- * The canonical same-origin `/plugins/...` form. From 0.1.7 the kernel boot
- * page injects `<base href="./">`, so the same bundle addresses appear in the
- * HTML as **relative** paths (`plugins/...`, `./plugins/...`); accepting only
- * the absolute form makes the parse fall through to the hardcoded probe. Both
- * forms converge here, so dedupe and sort run on one set of addresses.
- * @param path - an accepted client-bundle path.
- */
function normalizeClientBundlePath(path: string): string {
return `/${trimRelativePrefix(path).replace(/^\/+/u, '')}`
}
-/**
- * Whether a path is a same-origin client-bundle path: under `/plugins/`,
- * naming `client.js` (the combo route's `/plugins/??<pkg>/client.js&rev=…`
- * included), never protocol-relative or foreign. Both the absolute form and
- * the relative form a 0.1.7+ boot page serves are accepted.
- * @param path - the candidate path.
- */
export function isClientBundlePath(path: string): boolean {
const normalized = trimRelativePrefix(path)
if (normalized.startsWith('//'))
diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/garbage.txt b/packages/dsh-tauri-ssh/src/host/utils/fixtures/garbage.txt
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/fixtures/garbage.txt
rename to packages/dsh-tauri-ssh/src/host/utils/fixtures/garbage.txt
diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519 b/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519
rename to packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519
diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519.pub b/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519.pub
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519.pub
rename to packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519.pub
diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519_enc b/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519_enc
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/fixtures/id_ed25519_enc
rename to packages/dsh-tauri-ssh/src/host/utils/fixtures/id_ed25519_enc
diff --git a/packages/dsh-tauri-ssh/src/host/service/fixtures/id_rsa.pub b/packages/dsh-tauri-ssh/src/host/utils/fixtures/id_rsa.pub
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/fixtures/id_rsa.pub
rename to packages/dsh-tauri-ssh/src/host/utils/fixtures/id_rsa.pub
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.test.ts b/packages/dsh-tauri-ssh/src/host/utils/local.test.ts
similarity index 99%
rename from packages/dsh-tauri-ssh/src/host/service/sync-local.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/local.test.ts
index 93a04e32..412ee16d 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync-local.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/local.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
import { afterEach, describe, expect, it } from 'vitest'
-import { profileAllowlistReader, profileDependenciesReader } from './sync-local'
+import { profileAllowlistReader, profileDependenciesReader } from './local'
const roots: string[] = []
diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts b/packages/dsh-tauri-ssh/src/host/utils/local.ts
similarity index 51%
rename from packages/dsh-tauri-ssh/src/host/service/sync-local.ts
rename to packages/dsh-tauri-ssh/src/host/utils/local.ts
index 782ce7af..a184efca 100644
--- a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/local.ts
@@ -1,11 +1,3 @@
-/**
- * Local-source readers for the sync engine: the profile's package.json
- * dependencies and the user-level skill roots, plus the local `tar` packer.
- * These are the fs/process touchpoints the engine's seams abstract, kept
- * apart from the pure engine so tests import neither.
- * @module dsh-tauri-ssh/host/service/sync-local
- */
-
import type { Buffer } from 'node:buffer'
import type { SyncSkillRoot } from '../types/index'
import type { WorkspaceAllowlist } from './allowlist'
@@ -19,10 +11,8 @@ import { EMPTY_ALLOWLIST, parseAllowlist } from './allowlist'
const execFileAsync = promisify(execFile)
-/** The tar stream size budget (a skill folder can carry fixtures and assets). */
const MAX_TAR_BYTES = 64 * 1024 * 1024
-/** Profile that boots this process: `--profile <name>` on the CLI invocation. */
export function argvProfile(argv: readonly string[] = process.argv): string | undefined {
const flag = argv.indexOf('--profile')
const value = flag === -1 ? undefined : argv[flag + 1]
@@ -31,18 +21,10 @@ export function argvProfile(argv: readonly string[] = process.argv): string | un
return undefined
}
-/** The harness home: `$DSH_HOME`, else `~/.dsh`. */
function dshHomeOf(override?: string): string {
return override ?? process.env.DSH_HOME ?? join(homedir(), '.dsh')
}
-/**
- * Read the local profile's plugin dependencies (`profiles/<name>/package.json`
- * → `dependencies`). A missing or malformed manifest yields an empty map: "no
- * plugins installed here" is a state to show, not a failure to raise.
- * @param dshHome - harness-home override (tests).
- * @returns the dependency-name → spec map.
- */
export function profileDependenciesReader(dshHome?: string): () => Record<string, string> {
return () => {
const profile = argvProfile() ?? 'web'
@@ -62,15 +44,6 @@ export function profileDependenciesReader(dshHome?: string): () => Record<string
}
}
-/**
- * Read the local profile's build allowlist (`pnpm-workspace.yaml` →
- * `allowBuilds` + `onlyBuiltDependencies`). A missing or unparsable file reads
- * as empty: nothing to carry is a state, not a failure. Paths go through
- * `pathe`, so a Windows host resolves the same document as a POSIX one.
- * @param dshHome - harness-home override (tests).
- * @param profile - profile-name override (tests); defaults to the `--profile` the process runs under.
- * @returns the allowlist sections to carry to a remote profile.
- */
export function profileAllowlistReader(dshHome?: string, profile?: string): () => WorkspaceAllowlist {
return () => {
const workspacePath = join(dshHomeOf(dshHome), 'profiles', profile ?? argvProfile() ?? 'web', 'pnpm-workspace.yaml')
@@ -83,13 +56,6 @@ export function profileAllowlistReader(dshHome?: string, profile?: string): () =
}
}
-/**
- * Scan the user-level skill roots (`<dsh-home>/skills`, `~/.agents/skills`)
- * for SKILL.md-carrying directories. Absent roots simply contribute nothing.
- * @param dshHome - harness-home override (tests).
- * @param homeDir - user-home override (tests).
- * @returns per root: the label, its directory, and its sorted skill names.
- */
export function skillRootsScanner(dshHome?: string, homeDir?: string): () => Array<{ root: SyncSkillRoot, dir: string, names: string[] }> {
return () => {
const roots: Array<{ root: SyncSkillRoot, dir: string }> = [
@@ -104,7 +70,6 @@ export function skillRootsScanner(dshHome?: string, homeDir?: string): () => Arr
}
}
-/** The SKILL.md directories under one root, sorted; absent roots stay empty. */
function skillNamesOf(dir: string): string[] {
if (!existsSync(dir))
return []
@@ -117,28 +82,19 @@ function skillNamesOf(dir: string): string[] {
names.push(entry.name)
}
catch {
- // A broken symlink or unreadable entry is not a skill; skip it.
}
}
return names.sort()
}
-/**
- * The local `tar` packer: one streamed archive (`tar -cf -`) of the selected
- * skill directories under their root, exactly as the remote extract expects.
- * @returns the tar bytes.
- */
-export function tarPacker(): (dir: string, names: readonly string[]) => Promise<Buffer> {
- return async (dir, names) => {
- // `--` 分隔符:防止以 `-` 开头的 skill 目录名被 tar 当作选项。
- const { stdout, stderr } = await execFileAsync('tar', ['-cf', '-', '-C', dir, '--', ...names], {
- maxBuffer: MAX_TAR_BYTES,
- windowsHide: true,
- encoding: 'buffer',
- })
- if (stdout.length === 0) {
- throw new Error(`packing skills produced no archive${stderr.length === 0 ? '' : `: ${stderr.toString('utf8').trim()}`}`)
- }
- return stdout
+export async function packSkills(dir: string, names: readonly string[]): Promise<Buffer> {
+ const { stdout, stderr } = await execFileAsync('tar', ['-cf', '-', '-C', dir, '--', ...names], {
+ maxBuffer: MAX_TAR_BYTES,
+ windowsHide: true,
+ encoding: 'buffer',
+ })
+ if (stdout.length === 0) {
+ throw new Error(`packing skills produced no archive${stderr.length === 0 ? '' : `: ${stderr.toString('utf8').trim()}`}`)
}
+ return stdout
}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/packing.test.ts b/packages/dsh-tauri-ssh/src/host/utils/packing.test.ts
new file mode 100644
index 00000000..c8a7084b
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/utils/packing.test.ts
@@ -0,0 +1,60 @@
+import { Buffer } from 'node:buffer'
+import { existsSync } from 'node:fs'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { packSkills } from './local'
+import { buildPluginsBundle } from './plugins-sync'
+
+const { execFileAsync } = vi.hoisted(() => ({ execFileAsync: vi.fn() }))
+
+vi.mock('node:child_process', async () => {
+ const { promisify } = await import('node:util')
+ return { execFile: Object.assign(vi.fn(), { [promisify.custom]: execFileAsync }) }
+})
+
+afterEach(() => vi.resetAllMocks())
+
+describe('packSkills', () => {
+ it('packs the selected names directly with bounded binary output', async () => {
+ const archive = Buffer.from('tar output')
+ execFileAsync.mockResolvedValue({ stdout: archive, stderr: Buffer.alloc(0) })
+ expect(await packSkills('/skills', ['alpha', '-beta'])).toBe(archive)
+ expect(execFileAsync).toHaveBeenCalledWith('tar', ['-cf', '-', '-C', '/skills', '--', 'alpha', '-beta'], {
+ maxBuffer: 64 * 1024 * 1024,
+ windowsHide: true,
+ encoding: 'buffer',
+ })
+ })
+
+ it('rejects an empty archive with the stderr diagnostic', async () => {
+ execFileAsync.mockResolvedValue({ stdout: Buffer.alloc(0), stderr: Buffer.from(' nothing packed\n') })
+ await expect(packSkills('/skills', ['alpha'])).rejects.toThrow('packing skills produced no archive: nothing packed')
+ })
+})
+
+describe('buildPluginsBundle process lifecycle', () => {
+ it('closes tar stdin before awaiting output and cleans the staging directory', async () => {
+ const archive = Buffer.from('plugin tar output')
+ let finish!: (output: { stdout: Buffer, stderr: Buffer }) => void
+ const pending = new Promise<{ stdout: Buffer, stderr: Buffer }>((resolve) => {
+ finish = resolve
+ })
+ const end = vi.fn(() => finish({ stdout: archive, stderr: Buffer.alloc(0) }))
+ execFileAsync.mockReturnValue(Object.assign(pending, { child: { stdin: { end } } }))
+ const result = await buildPluginsBundle({ root: '/plugins', pluginNames: ['plugin-a'] })
+ expect(end).toHaveBeenCalledOnce()
+ expect(result.tar).toBe(archive)
+ expect(result.hash).toMatch(/^[0-9a-f]{64}$/)
+ expect(execFileAsync).toHaveBeenCalledWith('tar', ['-czf', '-', '-C', '/plugins', '.', '-C', expect.any(String), '_wire.js'], {
+ maxBuffer: 64 * 1024 * 1024,
+ encoding: 'buffer',
+ })
+ expect(existsSync(execFileAsync.mock.calls[0]![1][6])).toBe(false)
+ })
+
+ it('propagates tar failures and still cleans the staging directory without stdin', async () => {
+ const error = new Error('tar failed')
+ execFileAsync.mockReturnValue(Object.assign(Promise.reject(error), { child: { stdin: null } }))
+ await expect(buildPluginsBundle({ root: '/plugins', pluginNames: [] })).rejects.toBe(error)
+ expect(existsSync(execFileAsync.mock.calls[0]![1][6])).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-ssh/src/host/service/plugins-sync.test.ts b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/plugins-sync.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/plugins-sync.ts b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
similarity index 60%
rename from packages/dsh-tauri-ssh/src/host/service/plugins-sync.ts
rename to packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
index 57345830..aaf099e2 100644
--- a/packages/dsh-tauri-ssh/src/host/service/plugins-sync.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
@@ -1,47 +1,19 @@
-/**
- * Sync the desktop-bundled internal plugins (`dsh-tauri-*`) to the remote
- * instance. The desktop shell carries these plugins in every local window;
- * a remote machine without them renders the stock upstream UI (its own
- * "open-in-app" banner, no desktop sidebar surface) — the remote window must
- * differ from the local one ONLY in the backend it talks to.
- *
- * Mechanism (verified against `@deepseek-ai/dsh-app-boot` profile loading):
- * - the deployed tree `src-tauri/resources/node_modules` (build:plugins
- * `pnpm deploy` output) is a flat node_modules: 12 plugin packages plus
- * their hoisted third-party deps — uploaded verbatim as ONE tarball;
- * - a profile composes `dsh.profile.bundles` entries, and each plugin
- * package declares `dsh.bundle.patch` (its own `cordis.patch.yml`), so
- * adding the plugin names to the remote profile's bundles + `link:`
- * dependencies + node_modules symlinks mounts them exactly like the
- * desktop's internal install does locally;
- * - a content hash marker skips re-uploads; when the tree changed and an
- * instance is already running, its recorded pid is killed so the normal
- * ensure-launch flow restarts it onto the new profile.
- *
- * Failure policy: best-effort. A sync failure (no local tree, upload error)
- * downgrades to the stock remote UI — the connect itself must not fail.
- * @module dsh-tauri-ssh/host/service/plugins-sync
- */
-
import type { Buffer } from 'node:buffer'
-import type { SshMachineStage } from '../types/index'
-import type { SshSession } from './transport'
+import type { SshMachineStage, SshSession } from '../types/index'
import { execFile } from 'node:child_process'
import { createHash } from 'node:crypto'
import { existsSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { promisify } from 'node:util'
+
+import { REMOTE_ROOT } from '../config/constants'
-import { REMOTE_ROOT } from './bootstrap'
-/** Remote directory the plugin tree is synced into (flat node_modules inside). */
const REMOTE_PLUGINS_DIR = `${REMOTE_ROOT}/plugins`
-/** Remote marker recording the last synced tree hash. */
const SYNC_MARKER = `${REMOTE_PLUGINS_DIR}/.sync-sha256`
-/** Remote pidfile written by the instance start command (bootstrap.ts). */
const REMOTE_PIDFILE = '.dsh/dsh-remote.pid'
-/** The wiring helper uploaded alongside the tree (keeps shell quoting trivial). */
export const WIRE_SCRIPT = `const fs = require('fs')
const path = require('path')
const [profilePkg, base, ...names] = process.argv.slice(2)
@@ -76,26 +48,12 @@ fs.writeFileSync(profilePkg, JSON.stringify(doc, null, 2) + '\\n')
console.log('wired ' + names.length + ' bundled plugins')
`
-/** One local bundled-plugin tree: its root dir and the plugin package names. */
export interface BundledPluginsTree {
- /** The flat node_modules root (plugin dirs + hoisted deps as siblings). */
root: string
- /** Package names carrying a `dsh` manifest field (the mountable plugins). */
pluginNames: string[]
}
-/**
- * Locate the deployed bundled-plugin tree from this plugin's own installed
- * location. Release layout: the profile `link:` lands us inside
- * `resources/node_modules/<name>` — the parent IS the tree. Dev layout: the
- * profile links to `packages/<name>` sources, so fall back to the repo's
- * `src-tauri/resources/node_modules` (build:plugins output). A candidate
- * qualifies only when it holds both a known plugin and a known third-party
- * dep (the source `packages/` dir fails that check).
- */
export function findBundledPluginsTree(): BundledPluginsTree | undefined {
- // 自定位包根:运行时住在 dist/index.js(dist 上一层即包根),测试住在
- // src/host/service/(需上溯更多层)——统一「向上找自己的 package.json」
let ownPkgDir = dirname(realpathSync(fileURLToPath(import.meta.url)))
for (let depth = 0; depth < 6; depth += 1) {
try {
@@ -134,29 +92,16 @@ export function findBundledPluginsTree(): BundledPluginsTree | undefined {
return undefined
}
-/**
- * Build the sync tarball (tree content + the wiring helper as `_wire.js`)
- * and its content hash. The hash rides the marker file on the remote, so a
- * rebuilt tree (dev iteration) re-syncs on the next connect while an
- * unchanged tree costs one cheap `cat`.
- */
export async function buildPluginsBundle(tree: BundledPluginsTree): Promise<{ tar: Buffer, hash: string }> {
const staging = mkdtempSync(join(tmpdir(), 'dsh-plugins-wire-'))
try {
writeFileSync(join(staging, '_wire.js'), WIRE_SCRIPT)
- const tar = await new Promise<Buffer>((resolvePromise, rejectPromise) => {
- const child = execFile('tar', ['-czf', '-', '-C', tree.root, '.', '-C', staging, '_wire.js'], {
- maxBuffer: 64 * 1024 * 1024,
- encoding: 'buffer',
- }, (error, stdout) => {
- if (error !== null) {
- rejectPromise(error)
- return
- }
- resolvePromise(stdout)
- })
- child.stdin?.end()
+ const pending = promisify(execFile)('tar', ['-czf', '-', '-C', tree.root, '.', '-C', staging, '_wire.js'], {
+ maxBuffer: 64 * 1024 * 1024,
+ encoding: 'buffer',
})
+ pending.child.stdin?.end()
+ const { stdout: tar } = await pending
return { tar, hash: createHash('sha256').update(tar).digest('hex') }
}
finally {
@@ -164,18 +109,10 @@ export async function buildPluginsBundle(tree: BundledPluginsTree): Promise<{ ta
}
}
-/** The remote marker-read command (empty stdout = never synced / unknown). */
export function pluginSyncMarkerCommand(): string {
return `cat "$HOME/${SYNC_MARKER}" 2>/dev/null || true`
}
-/**
- * The one-shot remote sync script: extract the tarball from stdin, atomic
- * swap, record the hash marker, wire the profile (deps link entries +
- * bundles entries + node_modules symlinks via the uploaded `_wire.js`), and
- * restart a running instance so the ensure-launch flow relaunches it onto
- * the new profile.
- */
export function pluginSyncApplyCommand(tree: BundledPluginsTree, hash: string, profileName: string, remotePort: number): string {
const names = tree.pluginNames.join(' ')
const profile = `.dsh/profiles/${profileName}`
@@ -191,8 +128,6 @@ export function pluginSyncApplyCommand(tree: BundledPluginsTree, hash: string, p
`echo "${hash}" > "$HOME/${SYNC_MARKER}"`,
`[ -f "$HOME/${profile}/package.json" ] || "$HOME/${REMOTE_ROOT}/runtime/bin/node" "$HOME/${REMOTE_ROOT}/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js" --profile ${profileName} --from-default-profile web --help >/dev/null 2>&1`,
`"$HOME/${REMOTE_ROOT}/runtime/bin/node" "$BASE/node_modules/_wire.js" "$HOME/${profile}/package.json" "$BASE/node_modules" ${names}`,
- // 实例在跑则重启:pidfile 之外还按安装路径精确清场(pidfile 可能因上次崩溃
- // 指向已死进程),并等远端实例端口释放后再交还 ensure 拉起,避免新实例 EADDRINUSE
`[ -f "$HOME/${REMOTE_PIDFILE}" ] && kill "$(cat "$HOME/${REMOTE_PIDFILE}")" 2>/dev/null || true`,
`pkill -f "$HOME/${REMOTE_ROOT}/dependencies/dsh/node_modules/@deepseek-ai/dsh/lib/bin.js web" 2>/dev/null || true`,
`i=0; while [ $i -lt 50 ] && (exec 3<>/dev/tcp/127.0.0.1/${remotePort}) 2>/dev/null; do i=$((i+1)); sleep 0.2; done`,
@@ -200,10 +135,6 @@ export function pluginSyncApplyCommand(tree: BundledPluginsTree, hash: string, p
].join('\n')
}
-/**
- * Sync the bundled plugins when the tree changed (hash marker mismatch).
- * @returns whether the remote was modified (instance restart triggered).
- */
export async function syncBundledPlugins(
session: SshSession,
profileName: string,
diff --git a/packages/dsh-tauri-ssh/src/host/utils/shell.ts b/packages/dsh-tauri-ssh/src/host/utils/shell.ts
new file mode 100644
index 00000000..34380db0
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/utils/shell.ts
@@ -0,0 +1,7 @@
+export function shQuote(value: string): string {
+ return `'${value.replace(/'/gu, `'\\''`)}'`
+}
+
+export function loginShell(command: string): string {
+ return `sh -lc ${shQuote(command)}`
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts b/packages/dsh-tauri-ssh/src/host/utils/ssh-config.test.ts
similarity index 91%
rename from packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/ssh-config.test.ts
index 012983ca..4b2b30ef 100644
--- a/packages/dsh-tauri-ssh/src/host/service/ssh-config.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/ssh-config.test.ts
@@ -20,7 +20,7 @@ import {
loadSshConfigBlocks,
lookupSshConfig,
parseSshConfig,
- SshConfigResolver,
+ resolveSshAuth,
} from './ssh-config'
const FIXTURES = join(import.meta.dirname, 'fixtures')
@@ -289,8 +289,7 @@ describe('loadSshConfigBlocks', () => {
describe('sshConfigResolver', () => {
it('uses the profile fields and default identity files when no config exists', async () => {
await installFixtures()
- const resolver = new SshConfigResolver(sshDir, home, 'fallback-user')
- const auth = await resolver.resolve(profile())
+ const auth = await resolveSshAuth(profile(), sshDir, home, 'fallback-user')
expect(auth).toMatchObject({ host: '10.0.0.1', port: 22, username: 'root' })
// Defaults are id_ed25519/id_ecdsa/id_rsa; the missing ones are skipped.
expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8') }])
@@ -306,8 +305,7 @@ describe('sshConfigResolver', () => {
' Port 2222',
' IdentityFile %d/.ssh/id_ed25519',
].join('\n'))
- const resolver = new SshConfigResolver(sshDir, home, 'fallback')
- const auth = await resolver.resolve(profile({ host: 'webserver', user: '' }))
+ const auth = await resolveSshAuth(profile({ host: 'webserver', user: '' }), sshDir, home, 'fallback')
expect(auth).toMatchObject({ host: '10.0.0.9', port: 2222, username: 'deploy' })
expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8') }])
})
@@ -321,8 +319,7 @@ describe('sshConfigResolver', () => {
' IdentityFile .ssh/garbage.txt',
' IdentityFile %h-keys/id',
].join('\n'))
- const resolver = new SshConfigResolver(sshDir, home, 'os-user')
- const auth = await resolver.resolve(profile({ host: 'box', user: '' }))
+ const auth = await resolveSshAuth(profile({ host: 'box', user: '' }), sshDir, home, 'os-user')
expect(auth.keys).toEqual([
{ privateKey: await readFile(join(sshDir, 'id_ed25519.pub'), 'utf8') },
{ privateKey: await readFile(join(sshDir, 'id_ed25519_enc'), 'utf8') },
@@ -332,33 +329,30 @@ describe('sshConfigResolver', () => {
it('prefers the profile user over the config user over the default user', async () => {
await writeFile(join(sshDir, 'config'), 'Host box\n User config-user\n')
- const resolver = new SshConfigResolver(sshDir, home, 'os-user')
- expect((await resolver.resolve(profile({ host: 'box', user: 'profile-user' }))).username).toBe('profile-user')
- expect((await resolver.resolve(profile({ host: 'box', user: '' }))).username).toBe('config-user')
- expect((await resolver.resolve(profile({ host: 'no-match', user: '' }))).username).toBe('os-user')
+ expect((await resolveSshAuth(profile({ host: 'box', user: 'profile-user' }), sshDir, home, 'os-user')).username).toBe('profile-user')
+ expect((await resolveSshAuth(profile({ host: 'box', user: '' }), sshDir, home, 'os-user')).username).toBe('config-user')
+ expect((await resolveSshAuth(profile({ host: 'no-match', user: '' }), sshDir, home, 'os-user')).username).toBe('os-user')
})
it('attaches the stored password and passphrase, and skips unreadable keys', async () => {
await installFixtures()
await writeFile(join(sshDir, 'config'), 'Host box\n IdentityFile %h-keys/id\n IdentityFile .ssh/id_ed25519\n')
- const resolver = new SshConfigResolver(sshDir, home, 'os-user')
- const auth = await resolver.resolve(profile({
+ const auth = await resolveSshAuth(profile({
host: 'box',
user: '',
password: 'pw',
passphrase: 'phrase',
- }))
+ }), sshDir, home, 'os-user')
expect(auth.password).toBe('pw')
expect(auth.keys).toEqual([{ privateKey: await readFile(join(sshDir, 'id_ed25519'), 'utf8'), passphrase: 'phrase' }])
})
it('re-reads keys on every resolve (fresh ~/.ssh)', async () => {
await installFixtures()
- const resolver = new SshConfigResolver(sshDir, home)
- const first = await resolver.resolve(profile())
+ const first = await resolveSshAuth(profile(), sshDir, home)
const rotated = '-----BEGIN OPENSSH PRIVATE KEY-----\nrotated\n'
await writeFile(join(sshDir, 'id_ed25519'), rotated)
- const second = await resolver.resolve(profile())
+ const second = await resolveSshAuth(profile(), sshDir, home)
expect(first.keys[0]?.privateKey).not.toBe(rotated)
expect(second.keys[0]?.privateKey).toBe(rotated)
})
@@ -367,8 +361,7 @@ describe('sshConfigResolver', () => {
const previous = process.env.USER
try {
delete process.env.USER
- const resolver = new SshConfigResolver(sshDir, home)
- const auth = await resolver.resolve(profile({ user: '' }))
+ const auth = await resolveSshAuth(profile({ user: '' }), sshDir, home)
expect(auth.username).toBe('')
}
finally {
diff --git a/packages/dsh-tauri-ssh/src/host/utils/ssh-config.ts b/packages/dsh-tauri-ssh/src/host/utils/ssh-config.ts
new file mode 100644
index 00000000..ff703f98
--- /dev/null
+++ b/packages/dsh-tauri-ssh/src/host/utils/ssh-config.ts
@@ -0,0 +1,270 @@
+import type { MachineProfile } from '../types/index'
+
+import { readdirSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import process from 'node:process'
+import { isAbsolute, join, sep } from 'pathe'
+
+export const DEFAULT_IDENTITY_FILES = ['id_ed25519', 'id_ecdsa', 'id_rsa']
+
+export const SSH_CONFIG_FILE = 'config'
+
+export const INCLUDE_DEPTH_LIMIT = 8
+
+export interface SshHostBlock {
+ patterns: string[]
+ values: Record<string, string[]>
+}
+
+export interface SshHostSettings {
+ hostName?: string
+ user?: string
+ port?: number
+ identityFiles: string[]
+ proxyJump: string[]
+}
+
+export interface ResolvedSshAuth {
+ host: string
+ port: number
+ username: string
+ password?: string
+ keys: Array<{ privateKey: string, passphrase?: string }>
+ proxyJump: string[]
+}
+
+export function expandTokenPath(path: string, homeDir: string, host: string, user: string): string {
+ const out = expandPathTokens(path, homeDir, host, user)
+ return isAbsolute(out) ? out : join(homeDir, out)
+}
+
+function expandPathTokens(path: string, homeDir: string, host: string, user: string): string {
+ let out = path
+ if (out === '~') {
+ out = homeDir
+ }
+ else if (out.startsWith('~/')) {
+ out = join(homeDir, out.slice(2))
+ }
+ return out.replaceAll('%d', homeDir).replaceAll('%h', host).replaceAll('%r', user)
+}
+
+export function hostPatternMatches(pattern: string, host: string): boolean {
+ const lowered = host.toLowerCase()
+ for (const alternative of pattern.split(',')) {
+ const negated = alternative.startsWith('!')
+ const body = negated ? alternative.slice(1) : alternative
+ if (globMatches(body.toLowerCase(), lowered))
+ return !negated
+ }
+ return false
+}
+
+export function globMatches(glob: string, value: string): boolean {
+ let globIndex = 0
+ let valueIndex = 0
+ let starGlob = -1
+ let starValue = -1
+ while (valueIndex < value.length) {
+ const g = glob[globIndex]
+ if (g === '*') {
+ starGlob = globIndex
+ starValue = valueIndex
+ globIndex += 1
+ }
+ else if (g === '?' || g === value[valueIndex]) {
+ globIndex += 1
+ valueIndex += 1
+ }
+ else if (starGlob !== -1) {
+ globIndex = starGlob + 1
+ starValue += 1
+ valueIndex = starValue
+ }
+ else {
+ return false
+ }
+ }
+ while (glob[globIndex] === '*') globIndex += 1
+ return globIndex === glob.length
+}
+
+export function parseSshConfig(text: string): SshHostBlock[] {
+ const blocks: SshHostBlock[] = []
+ let current: SshHostBlock | undefined
+ for (const rawLine of text.split('\n')) {
+ const line = rawLine.replace(/#.*$/u, '').trim()
+ if (line === '')
+ continue
+ const equals = line.indexOf('=')
+ const key = (equals === -1 ? line.split(/\s+/u)[0]! : line.slice(0, equals)).trim().toLowerCase()
+ if (key === '')
+ continue
+ const value = equals === -1
+ ? line.slice(key.length).trim()
+ : line.slice(equals + 1).trim()
+ if (value === '')
+ continue
+ if (key === 'host') {
+ current = {
+ patterns: value.split(/\s+/u).filter(part => part !== ''),
+ values: {},
+ }
+ blocks.push(current)
+ continue
+ }
+ if (current === undefined) {
+ if (key === 'include') {
+ current = { patterns: [], values: {} }
+ blocks.push(current)
+ }
+ else {
+ continue
+ }
+ }
+ const values = current.values[key] ?? (current.values[key] = [])
+ values.push(value)
+ }
+ return blocks
+}
+
+export function lookupSshConfig(blocks: SshHostBlock[], host: string): SshHostSettings {
+ const settings: SshHostSettings = { identityFiles: [], proxyJump: [] }
+ for (const block of blocks) {
+ const applies = block.patterns.some(pattern => hostPatternMatches(pattern, host))
+ if (!applies)
+ continue
+ const hostname = block.values.hostname?.[0]
+ if (settings.hostName === undefined && hostname !== undefined) {
+ settings.hostName = hostname
+ }
+ const user = block.values.user?.[0]
+ if (settings.user === undefined && user !== undefined) {
+ settings.user = user
+ }
+ const port = block.values.port?.[0]
+ if (settings.port === undefined && port !== undefined) {
+ settings.port = Number(port)
+ }
+ if (block.values.identityfile !== undefined) {
+ settings.identityFiles.push(...block.values.identityfile)
+ }
+ if (settings.proxyJump.length === 0 && block.values.proxyjump !== undefined) {
+ settings.proxyJump = block.values.proxyjump[0]!
+ .split(',')
+ .map(token => token.trim())
+ .filter(token => token !== '' && token.toLowerCase() !== 'none')
+ }
+ }
+ return settings
+}
+
+export function discoverableHosts(blocks: SshHostBlock[]): string[] {
+ const hosts = new Set<string>()
+ for (const block of blocks) {
+ for (const pattern of block.patterns) {
+ if (pattern === '' || /[?*,!]/u.test(pattern))
+ continue
+ hosts.add(pattern)
+ }
+ }
+ return [...hosts].sort()
+}
+
+export function expandIncludePath(path: string, sshDir: string, homeDir: string, host: string, user: string): string[] {
+ const tokens = expandPathTokens(path, homeDir, host, user)
+ const expanded = isAbsolute(tokens) ? tokens : join(sshDir, tokens)
+ const slash = expanded.lastIndexOf(sep)
+ const dir = expanded.slice(0, slash)
+ const basename = expanded.slice(slash + 1)
+ if (!/[?*]/u.test(basename))
+ return [expanded]
+ return readdirSyncSafe(dir)
+ .filter(name => globMatches(basename, name))
+ .sort()
+ .map(name => join(dir, name))
+}
+
+function readdirSyncSafe(dir: string): string[] {
+ try {
+ return readdirSync(dir)
+ }
+ catch {
+ return []
+ }
+}
+
+export async function loadSshConfigBlocks(sshDir: string, homeDir: string): Promise<SshHostBlock[]> {
+ const blocks: SshHostBlock[] = []
+ const visited = new Set<string>()
+ await collectConfigBlocks(sshDir, homeDir, join(sshDir, SSH_CONFIG_FILE), 0, visited, blocks)
+ return blocks
+}
+
+async function collectConfigBlocks(
+ sshDir: string,
+ homeDir: string,
+ file: string,
+ depth: number,
+ visited: Set<string>,
+ out: SshHostBlock[],
+): Promise<void> {
+ if (depth > INCLUDE_DEPTH_LIMIT || visited.has(file))
+ return
+ visited.add(file)
+ let text: string
+ try {
+ text = await readFile(file, 'utf8')
+ }
+ catch {
+ return
+ }
+ for (const block of parseSshConfig(text)) {
+ const includes = block.values.include
+ if (includes === undefined) {
+ out.push(block)
+ continue
+ }
+ if (block.patterns.length > 0) {
+ const { include: _dropped, ...values } = block.values
+ out.push({ patterns: block.patterns, values })
+ }
+ for (const path of includes) {
+ for (const target of expandIncludePath(path, sshDir, homeDir, '', '')) {
+ await collectConfigBlocks(sshDir, homeDir, target, depth + 1, visited, out)
+ }
+ }
+ }
+}
+
+export async function resolveSshAuth(
+ profile: MachineProfile,
+ sshDir: string,
+ homeDir: string,
+ defaultUser: string = process.env.USER ?? '',
+): Promise<ResolvedSshAuth> {
+ const blocks = await loadSshConfigBlocks(sshDir, homeDir)
+ const settings = lookupSshConfig(blocks, profile.host)
+ const username = profile.user !== '' ? profile.user : settings.user ?? defaultUser
+ const host = settings.hostName ?? profile.host
+ const port = settings.port ?? profile.port
+ const passphrase = profile.passphrase === undefined || profile.passphrase === '' ? undefined : profile.passphrase
+ const password = profile.password === undefined || profile.password === '' ? undefined : profile.password
+ const identityPaths = settings.identityFiles.length > 0
+ ? settings.identityFiles
+ : DEFAULT_IDENTITY_FILES.map(name => join(sshDir, name))
+ const keys: ResolvedSshAuth['keys'] = []
+ for (const path of identityPaths) {
+ const privateKey = await readFile(expandTokenPath(path, homeDir, host, username), 'utf8').catch(() => undefined)
+ if (privateKey !== undefined)
+ keys.push({ privateKey, ...passphrase === undefined ? {} : { passphrase } })
+ }
+ return {
+ host,
+ port,
+ username,
+ keys,
+ proxyJump: settings.proxyJump,
+ ...password === undefined ? {} : { password },
+ }
+}
diff --git a/packages/dsh-tauri-ssh/src/host/service/version.test.ts b/packages/dsh-tauri-ssh/src/host/utils/version.test.ts
similarity index 100%
rename from packages/dsh-tauri-ssh/src/host/service/version.test.ts
rename to packages/dsh-tauri-ssh/src/host/utils/version.test.ts
diff --git a/packages/dsh-tauri-ssh/src/host/service/version.ts b/packages/dsh-tauri-ssh/src/host/utils/version.ts
similarity index 58%
rename from packages/dsh-tauri-ssh/src/host/service/version.ts
rename to packages/dsh-tauri-ssh/src/host/utils/version.ts
index 168f5d41..160c260d 100644
--- a/packages/dsh-tauri-ssh/src/host/service/version.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/version.ts
@@ -1,71 +1,25 @@
-/**
- * DSH version selection and download-metadata pinning, ported from the
- * retired Rust engine's semantics (`service/download/github.rs` +
- * `src-tauri/resources/manifest.jsonc`'s `engines.dsh.recommend`): never
- * "latest 直下" — resolve the
- * recommended version onto a concrete release tag, pin that tag's asset URL
- * and trusted digest, and on resolution failure fall back to a known stable
- * tag while reporting why. Also owns the install-source repository mapping
- * (`installRepo` config → the GitHub repository hosting the packaged
- * releases).
- * @module dsh-tauri-ssh/host/service/version
- */
-
-/** One packaged release as the GitHub API lists it. */
export interface DshPkgReleaseMeta {
tag: string
- /** GitHub's Pre-release label for the tag. */
prerelease: boolean
}
-/** How a release tag was chosen. */
export type DshTagSource = 'pin' | 'recommended' | 'latest-stable' | 'fallback'
-/** The outcome of release-tag resolution. */
export interface ResolvedDshTag {
tag: string
- /** The parsed semver (empty when the tag carries none). */
version: string
source: DshTagSource
- /** Human-readable notes for every departure from the primary choice. */
notes: string[]
}
-/**
- * The recommended DSH version pinned for remote installs. Kept in lockstep
- * with the desktop mainline's `src-tauri/resources/manifest.jsonc`
- * (`engines.dsh.recommend`, both name the version this desktop generation is
- * verified against); installs pin this version instead of following whatever
- * "latest" happens to be.
- */
export const RECOMMENDED_DSH_VERSION = '0.2.0-rc.2'
-/**
- * The last known-good packaged release tag, used when version resolution
- * fails (offline, rate-limited, or the recommended version vanished). A
- * concrete tag — never an unknown version. It names a release of the
- * packaging repository, so it advances only once that repository has
- * actually published the corresponding build; `0.2.0-rc.2` is packaged as
- * `dsh-0.2.0-rc.2-36556493178`, so the fallback no longer trails the
- * recommendation.
- */
export const FALLBACK_DSH_TAG = 'dsh-0.2.0-rc.2-36556493178'
-/** The official DSH project repository (org verified on GitHub). */
export const OFFICIAL_INSTALL_REPO = 'https://github.com/deepseek-ai/deepseek-harness.git'
-/** The GitHub repository hosting the packaged DSH binary releases. */
export const OFFICIAL_PKG_REPO = 'dsh-tauri-desk/deepseek-harness-pkg'
-/**
- * Map the `installRepo` config onto the GitHub `owner/name` repository whose
- * releases the binary install downloads from. The official anchor (and the
- * legacy wrong-org spelling it replaces) maps onto the official packaging
- * repository; any other configured repository is used as-is, so forks and
- * mirrors of the packaging repo work.
- * @param installRepo - the configured install repository (URL or `owner/name`).
- * @returns the `owner/name` release repository.
- */
export function pkgRepoOf(installRepo?: string): string {
const configured = installRepo === undefined || installRepo.trim() === '' ? undefined : installRepo.trim()
if (configured === undefined)
@@ -78,34 +32,20 @@ export function pkgRepoOf(installRepo?: string): string {
return parsed
}
-/** The `owner/name` of a GitHub repository URL (`.git` suffix tolerated). */
export function parseGitHubRepo(value: string): string | undefined {
const match = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/u.exec(value)
if (match === null) {
- // A bare `owner/name` is accepted for local mirrors expressed concisely.
const bare = /^([\w.-]+)\/([\w.-]+)$/u.exec(value)
return bare === null ? undefined : `${bare[1]}/${bare[2]}`
}
return `${match[1] ?? ''}/${match[2] ?? ''}`
}
-/**
- * Parse the DSH semver out of a packaged release tag: `dsh-0.1.2-rc.1-<build>`
- * (the trailing build id is dropped) and `dsh-src-0.1.2-alpha.1-<build>`
- * yield the version with its prerelease segment intact. A bare dsh-prefixed
- * tag still loses its last dash segment — the build-id convention applied
- * unconditionally, matching the retired Rust parser — so bare
- * `dsh-0.1.2-rc.1` yields `0.1.2` (the `rc.1` segment is dropped); only a
- * bare `src-<version>` tag passes through as-is.
- * @param tag - the release tag.
- * @returns the version string, or undefined when the tag carries none.
- */
export function parseVersionFromTag(tag: string): string | undefined {
const hasDshPrefix = tag.startsWith('dsh-')
const stripped = hasDshPrefix ? tag.slice('dsh-'.length) : tag
if (stripped.startsWith('src-')) {
const rest = stripped.slice('src-'.length)
- // `dsh-src-<version>-<build>`: drop the build id; bare `src-<version>`: as-is.
const version = hasDshPrefix ? rest.split('-').slice(0, -1).join('-') : rest
return version === '' ? undefined : version
}
@@ -115,15 +55,8 @@ export function parseVersionFromTag(tag: string): string | undefined {
return version === '' ? undefined : version
}
-/** Pre-release markers that make a tag a preview (rc does not — rc ships). */
const PREVIEW_MARKERS = ['preview', 'beta', 'alpha', 'canary', 'next'] as const
-/**
- * Whether a tag is a preview release (its version's pre-release segment
- * carries a non-rc preview marker). Preview releases never win the
- * "latest stable" fallback.
- * @param tag - the release tag.
- */
export function isPreviewTag(tag: string): boolean {
const version = parseVersionFromTag(tag)
if (version === undefined)
@@ -134,19 +67,6 @@ export function isPreviewTag(tag: string): boolean {
return pre.split('.').some(id => PREVIEW_MARKERS.some(marker => id.startsWith(marker)))
}
-/**
- * Resolve the install tag from the release list (pure — the network fetch is
- * injected). Resolution order: the configured pin (`ref`, a tag or version),
- * the {@link RECOMMENDED_DSH_VERSION} match, the newest stable release, and
- * finally the {@link FALLBACK_DSH_TAG} constant when no list was available.
- * Every departure from the primary choice carries a human-readable note.
- * @param metas - the packaged release list (newest first), or undefined when
- * the listing itself failed.
- * @param options - the pin (`ref`) and the recommended version override.
- * @param options.ref - the configured pin: a full release tag or a semver.
- * @param options.recommended - the recommended version (defaults to the constant).
- * @returns the resolved tag, its version, the resolution source, and notes.
- */
export function pickReleaseTag(
metas: DshPkgReleaseMeta[] | undefined,
options: { ref?: string | undefined, recommended?: string | undefined } = {},
@@ -171,10 +91,6 @@ export function pickReleaseTag(
notes.push('release 列表不可用(网络/限流),回退已知稳定 tag')
return { tag: FALLBACK_DSH_TAG, version: parseVersionFromTag(FALLBACK_DSH_TAG) ?? '', source: 'fallback', notes }
}
- // Dedupe by version keeping the first-listed tag: GitHub lists releases
- // newest-first (created_at descending, verified against the pkg repo), so
- // the first tag of a version is its newest republish — e.g. `dsh-…` wins
- // over an older `dsh-src-…` that parses to the same version.
const byVersion = new Map<string, DshPkgReleaseMeta>()
for (const meta of metas) {
const version = parseVersionFromTag(meta.tag)
@@ -195,15 +111,12 @@ export function pickReleaseTag(
return { tag: fallback.tag, version: parseVersionFromTag(fallback.tag) ?? '', source: 'latest-stable', notes }
}
-/** One packaged release asset as GitHub reports it. */
export interface GithubAsset {
name: string
url: string
- /** Trusted digest (`sha256:<hex>`), when GitHub computed one. */
digest?: string
}
-/** Fetch JSON with a deadline; a non-2xx fails with the status. */
async function fetchJson(url: string, headers: Record<string, string>, timeoutMs: number): Promise<unknown> {
const response = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
if (!response.ok)
@@ -211,7 +124,6 @@ async function fetchJson(url: string, headers: Record<string, string>, timeoutMs
return await response.json() as unknown
}
-/** List the packaged releases (newest first) from the GitHub API. */
export async function listGithubReleases(repo: string, timeoutMs = 15_000): Promise<DshPkgReleaseMeta[]> {
const json = await fetchJson(
`https://api.github.com/repos/${repo}/releases?per_page=100`,
@@ -227,7 +139,6 @@ export async function listGithubReleases(repo: string, timeoutMs = 15_000): Prom
.map(entry => ({ tag: entry.tag_name, prerelease: entry.prerelease }))
}
-/** Fetch one tag's release assets from the GitHub API. */
export async function listGithubAssets(repo: string, tag: string, timeoutMs = 15_000): Promise<GithubAsset[]> {
const json = await fetchJson(
`https://api.github.com/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`,
@@ -247,15 +158,6 @@ export async function listGithubAssets(repo: string, tag: string, timeoutMs = 15
}))
}
-/**
- * Resolve the `npm-tgz` DSH asset metadata for one version from the npm
- * registry (official → npmmirror fallback): the deterministic tarball URL
- * pair and the packument's trusted integrity digest.
- * @param packageName - the scoped package name (`@deepseek-ai/dsh`).
- * @param version - the resolved version.
- * @param timeoutMs - per-request deadline.
- * @returns the tarball URL (official), its mirror, and the `sha512` integrity.
- */
export async function npmDistMetadata(
packageName: string,
version: string,
diff --git a/packages/dsh-tauri-ssh/src/index.ts b/packages/dsh-tauri-ssh/src/index.ts
index e5d19665..840ddcda 100644
--- a/packages/dsh-tauri-ssh/src/index.ts
+++ b/packages/dsh-tauri-ssh/src/index.ts
@@ -1,22 +1,2 @@
-/**
- * The DSH remote-machine host plugin. Owns the plugin state document (the
- * enable switch + the manual machine table), the SSH connection manager (TOFU
- * host keys, remote `dsh web` auto-start, loopback tunnels), and mounts the
- * same-origin `/api-ssh` route on `ctx.webServer` for the settings page. No
- * upstream DSH source is touched: every integration is a documented cordis
- * extension point.
- *
- * 三层目录(host / shared):
- * - index.ts(本文件) public barrel(只保留导出面);
- * - shared/constants 跨 half 协议常量(插件名 / API 前缀);
- * - host/ Node half:routes(/api-ssh 路由)/ storage
- * (状态文档读写与插件配置)/
- * service(manager 状态机、bootstrap 远端保障、
- * ssh-config 凭据解析、transport ssh2 传输、
- * host-keys TOFU 存储)/ types / apply。
- * @module dsh-tauri-ssh
- */
-
-export { apply, Config, default, inject, name, SshRemoteService } from './host/apply'
+export { apply, Config, default, inject, name } from './host/apply'
export type { SshMachineEvent, SshMachineEventsPage, SshMachineStage, SshMachineTerminal } from './host/types/index'
-export { SSH_API_PREFIX } from './shared/constants'
diff --git a/packages/dsh-tauri-ssh/src/shared/constants.test.ts b/packages/dsh-tauri-ssh/src/shared/constants.test.ts
index a5123934..27f1a736 100644
--- a/packages/dsh-tauri-ssh/src/shared/constants.test.ts
+++ b/packages/dsh-tauri-ssh/src/shared/constants.test.ts
@@ -1,30 +1,24 @@
import { describe, expect, it } from 'vitest'
-import { SSH_API_PATH } from '../client/constants/index'
-import { machineRowOf } from '../client/store/index'
-import { REMOTE_PLUGIN_PROFILE } from '../host/service/sync'
-import { DEFAULT_REMOTE_PORT as hostRemotePort, DEFAULT_SSH_PORT as hostSshPort, machineProfileOf } from '../host/storage/index'
-import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, SSH_API_PREFIX } from './constants'
+import { DEFAULT_REMOTE_PROFILE } from '../host/config/constants'
+import { machineProfileOf } from '../host/service/state.utils'
+import { DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, DEFAULT_REMOTE_PORT as hostRemotePort, DEFAULT_SSH_PORT as hostSshPort } from './constants'
describe('shared SSH defaults', () => {
- it('preserves numeric defaults and legacy host exports', () => {
+ it('preserves numeric defaults and host exports', () => {
expect(DEFAULT_SSH_PORT).toBe(22)
expect(DEFAULT_REMOTE_PORT).toBe(3080)
expect(hostSshPort).toBe(22)
expect(hostRemotePort).toBe(3080)
- expect(REMOTE_PLUGIN_PROFILE).toBe('remote')
- expect(SSH_API_PREFIX).toBe('/api-ssh')
- expect(SSH_API_PATH).toBe('/api-ssh')
+ expect(DEFAULT_REMOTE_PROFILE).toBe('remote')
})
- it.each([{}, { port: 'bad', remotePort: null }])('keeps client and stored wire fallback values for %j', (ports) => {
+ it.each([{}, { port: 'bad', remotePort: null }])('keeps stored wire fallback values for %j', (ports) => {
const wire = { id: 'a', name: 'alpha', host: 'localhost', user: 'ops', ...ports }
- expect(machineRowOf(wire)).toMatchObject({ port: 22, remotePort: 3080 })
expect(machineProfileOf(wire)).toMatchObject({ port: 22, remotePort: 3080 })
})
it('preserves explicitly supplied numeric ports', () => {
const wire = { id: 'a', name: 'alpha', host: 'localhost', user: 'ops', port: 2222, remotePort: 4000 }
- expect(machineRowOf(wire)).toMatchObject({ port: 2222, remotePort: 4000 })
expect(machineProfileOf(wire)).toMatchObject({ port: 2222, remotePort: 4000 })
})
})
diff --git a/packages/dsh-tauri-ssh/src/shared/constants.ts b/packages/dsh-tauri-ssh/src/shared/constants.ts
index 8a2cc610..9717c45c 100644
--- a/packages/dsh-tauri-ssh/src/shared/constants.ts
+++ b/packages/dsh-tauri-ssh/src/shared/constants.ts
@@ -1,19 +1,5 @@
-/**
- * Cross-half protocol constants of the SSH remote-machine plugin
- * (`dsh-tauri-ssh` host half + `dsh-tauri-ssh/client` browser half). Both
- * halves and the docs reference these identifiers; centralizing them prevents
- * drift.
- * @module dsh-tauri-ssh/shared/constants
- */
-
-/** Cordis plugin name / loader id of the host half. */
export const SSH_PLUGIN_NAME = 'dsh-tauri-ssh'
-/**
- * The same-origin connection-plane route the host half mounts on
- * `ctx.webServer` (and the client half POSTs to). Loopback-only by contract.
- */
-export const SSH_API_PREFIX = '/api-ssh'
-
export const DEFAULT_SSH_PORT = 22
+
export const DEFAULT_REMOTE_PORT = 3080
diff --git a/packages/dsh-tauri-ssh/vitest.config.ts b/packages/dsh-tauri-ssh/vitest.config.ts
deleted file mode 100644
index 4d51076a..00000000
--- a/packages/dsh-tauri-ssh/vitest.config.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { fileURLToPath } from 'node:url'
-import { defineConfig } from 'vitest/config'
-
-/**
- * 包内套件入口:根 vitest.config.ts 已改为 project 清单(unit/plugin/desktop
- * 三 lane),从包目录裸跑 `vitest run` 会在错误的 CWD 下解析那份清单。本包用例
- * 显式声明自身配置即可独立运行(`pnpm --filter dsh-tauri-ssh test`),也避免
- * 依赖根 lane 的装配前提。
- *
- * 组件用例渲染官方 UI primitives,其包带真实 `.module.css` 边车文件、且在 pnpm 下
- * 嵌套了另一份 react@18——而本包面向 workspace 的 react 开发。部署时的 ModuleLoader
- * 里两者共用同一个平台 react,这里用测试期设置复原该环境:primitives 包内联让 Vite
- * 处理它的 CSS import,所有 react specifier 钉到 workspace 那份,使 jsdom 只挂一个
- * 渲染器而不是两个。(组件用例自带 `@vitest-environment jsdom` 文档块。)
- */
-const reactRoot = fileURLToPath(new URL('../../node_modules/react', import.meta.url))
-
-export default defineConfig({
- resolve: {
- alias: [
- { find: /^react$/, replacement: reactRoot },
- { find: /^react\/jsx-runtime$/, replacement: `${reactRoot}/jsx-runtime.js` },
- { find: /^react\/jsx-dev-runtime$/, replacement: `${reactRoot}/jsx-dev-runtime.js` },
- ],
- },
- test: {
- environment: 'node',
- css: true,
- server: {
- deps: {
- inline: [/@deepseek-ai\/dsh-client-ui-primitives/],
- },
- },
- },
-})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3fc60334..8f97253c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -952,9 +952,6 @@ importers:
specifier: catalog:testing
version: 2.9.0
devDependencies:
- '@deepseek-ai/dsh-client-ui-primitives':
- specifier: catalog:dsh
- version: 0.2.0-rc.2(@deepseek-ai/[email protected])
'@testing-library/dom':
specifier: catalog:testing
version: 10.4.2
@@ -2433,12 +2430,6 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
- '@kwsites/[email protected]':
- resolution: {integrity: sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==}
-
- '@kwsites/[email protected]':
- resolution: {integrity: sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==}
-
'@napi-rs/[email protected]':
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
engines: {node: ^22.20 || ^24.12 || >=25}
@@ -3123,12 +3114,6 @@ packages:
cpu: [x64]
os: [win32]
- '@simple-git/[email protected]':
- resolution: {integrity: sha512-ngJMaHlsWDTfjyq9F3VIQ8b7NXbBLq5j9i5bJ6XLYtD6qlDXT7fdKY2KscWWUF8t18xx052Y/PUO1K1TRc9yKA==}
-
- '@simple-git/[email protected]':
- resolution: {integrity: sha512-Q9lBcfQ+VQCpQqGJFHe5yooOS5hGdLFFbJ5R+R5aDsnkPCahtn1hSkMcORX65J2Z5lxSkD0lQorMsncuBQxYUw==}
-
'@sinclair/[email protected]':
resolution: {integrity: sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==}
@@ -6080,9 +6065,6 @@ packages:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-cGQjLjK8bxJw4QuYT7gxHw3/IouVESbhahSsHrX97MzCL1gu2u7oy38W6L2ZIGECEfIBG4BabsWDPjBxJENv9Q==}
-
resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}
@@ -8225,14 +8207,6 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
- '@kwsites/[email protected]':
- dependencies:
- debug: 4.4.3
- transitivePeerDependencies:
- - supports-color
-
- '@kwsites/[email protected]': {}
-
'@napi-rs/[email protected]':
optional: true
@@ -8697,12 +8671,6 @@ snapshots:
'@rollup/[email protected]':
optional: true
- '@simple-git/[email protected]': {}
-
- '@simple-git/[email protected]':
- dependencies:
- '@simple-git/args-pathspec': 1.0.3
-
'@sinclair/[email protected]': {}
'@sindresorhus/[email protected]': {}
@@ -12126,16 +12094,6 @@ snapshots:
- dependencies:
- '@kwsites/file-exists': 1.1.1
- '@kwsites/promise-deferred': 1.1.1
- '@simple-git/args-pathspec': 1.0.3
- '@simple-git/argv-parser': 1.1.1
- debug: 4.4.3
- transitivePeerDependencies:
- - supports-color
-
diff --git a/scripts/e2e-ssh-data-plane.mjs b/scripts/e2e-ssh-data-plane.mjs
index 36bc3574..540293a1 100644
--- a/scripts/e2e-ssh-data-plane.mjs
+++ b/scripts/e2e-ssh-data-plane.mjs
@@ -1,15 +1,20 @@
#!/usr/bin/env node
/**
- * S5 整体验收·数据面全旅程驱动脚本(无头,经 /api-ssh HTTP 信封直驱引擎)。
+ * S5 整体验收·数据面全旅程驱动脚本(无头,直驱 /api/desktop/dsh-tauri-ssh REST 面)。
*
* 旅程(对应 S5 Spec 验收标准 2 的可自动化子集):
- * machine.save(dev 真机,含 color/tintBorder/startCommand)
- * → machine.connect(S2 bootstrap:远端已装 dsh 则直接拉起实例 + 建隧道)
- * → machine.list 轮询至 connected + tunnelBaseUrl
+ * POST /machines(dev 真机,含 color/tintBorder/startCommand)
+ * → POST /machines/connect(S2 bootstrap:远端已装 dsh 则直接拉起实例 + 建隧道)
+ * → GET /machines 轮询至 connected + tunnelBaseUrl
* → 经隧道 GET /(远端实例可达性证据:200 或远端 dsh 的鉴权提示 401)
- * → machine.events 探日志(连接生命周期阶段)
- * → machine.disconnect → list 回 disconnected
- * → machine.remove → list 行消失
+ * → GET /machines/events 探日志(连接生命周期阶段)
+ * → POST /machines/disconnect → GET /machines 回 disconnected
+ * → DELETE /machines → GET /machines 行消失
+ *
+ * 鉴权:路由层沿用宿主 connection 的浏览器会话闸门(Host/Origin fence + 签名 Cookie),
+ * 没有信封 token 通道。`--token` 只用于在根路径换取会话 Cookie(`GET /?token=…`
+ * → 303 + set-cookie),随后所有请求带着该 Cookie 走;也可以直接给 `--cookie`
+ * (例如从浏览器 DevTools 复制)。
*
* 用法(先起一个挂了 dsh-tauri-ssh 的本地 dsh 实例,见
* docs/testing/s5-ssh-e2e-evidence.md 的复现步骤):
@@ -31,7 +36,7 @@ function argOf(name, fallback) {
return index >= 0 ? args[index + 1] : fallback
}
-const base = argOf('base', 'http://127.0.0.1:3185')
+const base = argOf('base', 'http://127.0.0.1:3185').replace(/\/+$/u, '')
const token = argOf('token', '')
const host = argOf('host', 'dev')
const user = argOf('user', 'root')
@@ -40,6 +45,8 @@ const remotePort = Number(argOf('remote-port', '3082'))
const startCommand = argOf('start-command', '')
const outPath = argOf('out', '')
const machineId = randomUUID()
+const api = `${base}/api/desktop/dsh-tauri-ssh`
+let cookie = argOf('cookie', '')
const lines = []
function log(line) {
@@ -47,17 +54,45 @@ function log(line) {
lines.push(line)
}
-async function call(method, payload) {
- const url = `${base}/api-ssh?token=${encodeURIComponent(token)}`
+async function signIn() {
+ const response = await fetch(`${base}/?token=${encodeURIComponent(token)}`, { redirect: 'manual' })
+ const setCookie = response.headers.getSetCookie?.()[0] ?? response.headers.get('set-cookie') ?? ''
+ if (response.status !== 303 || setCookie === '')
+ throw new Error(`launch-token exchange failed: HTTP ${response.status}(--token 是否与 dsh web 打印的一致?也可直接给 --cookie)`)
+ return setCookie.split(';')[0]
+}
+
+async function request(method, path, body, query) {
+ const url = new URL(`${api}${path}`)
+ for (const [key, value] of Object.entries(query ?? {}))
+ url.searchParams.set(key, String(value))
const response = await fetch(url, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ method, payload }),
+ method,
+ headers: {
+ ...cookie === '' ? {} : { cookie },
+ ...body === undefined ? {} : { 'content-type': 'application/json' },
+ },
+ ...body === undefined ? {} : { body: JSON.stringify(body) },
+ redirect: 'manual',
})
- const envelope = await response.json()
- if (!envelope.ok)
- throw new Error(`${method} failed: ${envelope.error?.code}: ${envelope.error?.message}`)
- return envelope.value
+ const text = await response.text()
+ const payload = jsonOf(text)
+ if (!response.ok || payload?.error !== undefined)
+ throw new Error(`${method} ${path} failed: HTTP ${response.status}${payload?.error === undefined ? `: ${text.slice(0, 200)}` : `: ${payload.error}`}`)
+ return payload
+}
+
+function jsonOf(text) {
+ try {
+ return JSON.parse(text)
+ }
+ catch {
+ return undefined
+ }
+}
+
+function listMachines() {
+ return request('GET', '/machines')
}
function sleep(ms) {
@@ -67,8 +102,8 @@ function sleep(ms) {
async function waitForState(machineId, predicate, timeoutMs, label) {
const deadline = Date.now() + timeoutMs
for (;;) {
- const value = await call('machine.list', {})
- const row = value.items.find(item => item.id === machineId)
+ const value = await listMachines()
+ const row = (value.items ?? []).find(item => item.id === machineId)
if (row !== undefined && predicate(row))
return row
if (Date.now() > deadline)
@@ -78,13 +113,20 @@ async function waitForState(machineId, predicate, timeoutMs, label) {
}
async function main() {
+ if (cookie === '')
+ cookie = await signIn()
+
+ const settings = await request('GET', '/settings')
+ if (settings.enabled !== true)
+ throw new Error('dsh-tauri-ssh 未启用:先 POST /api/desktop/dsh-tauri-ssh/settings {"enabled":true}')
+
log(`# S5 SSH 数据面全旅程 — ${new Date().toISOString()}`)
log(`base=${base} host=${host} user=${user} sshPort=${sshPort} remotePort=${remotePort}`)
log(`machineId=${machineId}`)
- // 1) machine.save:新建机器(color/tintBorder 供切换器色点与边框着色消费;
+ // 1) POST /machines:新建机器(color/tintBorder 供切换器色点与边框着色消费;
// startCommand 留空 = 走引擎默认 bootstrap 启动命令)
- await call('machine.save', {
+ await request('POST', '/machines', {
machineId,
row: {
name: 's5-e2e-dev',
@@ -97,16 +139,16 @@ async function main() {
tintBorder: true,
},
})
- let list = await call('machine.list', {})
- let row = list.items.find(item => item.id === machineId)
+ let list = await listMachines()
+ let row = (list.items ?? []).find(item => item.id === machineId)
if (row === undefined)
- throw new Error('saved machine missing from machine.list')
- log(`\n[1] machine.save ok → name=${row.name} state=${row.state} color=${row.color} tintBorder=${row.tintBorder} (discovered aliases: ${list.discovered.length})`)
+ throw new Error('saved machine missing from GET /machines')
+ log(`\n[1] machine.save ok → name=${row.name} state=${row.state} color=${row.color} tintBorder=${row.tintBorder} (discovered aliases: ${(list.discovered ?? []).length})`)
- // 2) machine.connect:S2 bootstrap + 隧道(阻塞到 tunnelBaseUrl 就绪)
+ // 2) POST /machines/connect:S2 bootstrap + 隧道(阻塞到 tunnelBaseUrl 就绪)
log('\n[2] machine.connect …(bootstrap/健康探测可能需要数十秒)')
const startedAt = Date.now()
- const link = await call('machine.connect', { machineId })
+ const link = await request('POST', '/machines/connect', { machineId })
log(` connect ok in ${((Date.now() - startedAt) / 1000).toFixed(1)}s tunnelBaseUrl=${link.tunnelBaseUrl}`)
row = await waitForState(machineId, item => item.state === 'connected', 30_000, 'connected')
@@ -123,22 +165,23 @@ async function main() {
throw new Error(`tunnel GET / unexpected: ${tunnelResponse.status} ${tunnelBody.slice(0, 120)}`)
log(`[4] tunnel GET / → HTTP ${tunnelResponse.status}(${tunnelResponse.status === 200 ? '直出页面' : '远端实例鉴权提示,隧道传输已通'})body head: ${tunnelBody.slice(0, 60).replace(/\n/g, ' ')}`)
- // 4) machine.events:连接生命周期日志证据
- const events = await call('machine.events', { machineId, sinceSeq: 0 })
- const stages = (events.events ?? []).map(event => `${event.seq}:${event.stage ?? event.kind ?? '?'}`).join(' ')
- log(`[5] machine.events → ${(events.events ?? []).length} 条 (${stages.slice(0, 400)})`)
+ // 4) GET /machines/events:连接生命周期日志证据
+ const page = await request('GET', '/machines/events', undefined, { machineId, sinceSeq: 0 })
+ const items = page.items ?? []
+ const stages = items.map(event => `${event.seq}:${event.stage ?? '?'}`).join(' ')
+ log(`[5] machine.events → ${items.length} 条 (${stages.slice(0, 400)})`)
- // 5) machine.disconnect → 回 disconnected
- await call('machine.disconnect', { machineId })
+ // 5) POST /machines/disconnect → 回 disconnected
+ await request('POST', '/machines/disconnect', { machineId })
row = await waitForState(machineId, item => item.state === 'disconnected', 30_000, 'disconnected')
log(`[6] machine.disconnect ok → state=${row.state}`)
- // 6) machine.remove → 行消失
- await call('machine.remove', { machineId })
- list = await call('machine.list', {})
- if (list.items.some(item => item.id === machineId))
- throw new Error('removed machine still present in machine.list')
- log(`[7] machine.remove ok → items=${list.items.length}(目标机器已从列表消失,discovered 别名不受影响:${list.discovered.length})`)
+ // 6) DELETE /machines → 行消失
+ await request('DELETE', '/machines', { machineId })
+ list = await listMachines()
+ if ((list.items ?? []).some(item => item.id === machineId))
+ throw new Error('removed machine still present in GET /machines')
+ log(`[7] machine.remove ok → items=${(list.items ?? []).length}(目标机器已从列表消失,discovered 别名不受影响:${(list.discovered ?? []).length})`)
log('\nALL STEPS PASSED ✅')
}
diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rs
index 2004c63f..8e565155 100644
--- a/src-tauri/src/bridge/remote.rs
+++ b/src-tauri/src/bridge/remote.rs
@@ -1,24 +1,113 @@
-//! bridge/remote.rs — SSH 远端机器的桌面集成命令(S5 桥契约 C-BRIDGE)。
-//!
-//! 引擎(机器存储/连接/隧道)全部住在 `dsh-tauri-ssh` 插件里,桌面壳不持有
-//! 任何机器状态;这里只暴露 iframe 内插件做不了的两件事:
-//!
-//! - `remote_open_window { machineId, url }`:打开(已开则聚焦)label 为
-//! `remote-<machineId>` 的专用 WebviewWindow。窗口加载的是壳层应用本体
-//! (与主窗口同一套导航栏/切换器),前端按自身 label 解析出 machineId
-//! 并在启动时切到该机器——远端界面嵌在壳内呈现,而不是裸加载隧道页。
-//! `url`(隧道 URL)仍做回环校验(纵深防御:桥白名单之外的输入不可信,
-//! 且未连接机器的调用在第一道就被挡掉)。
-//! - `remote_bridge_ping`:无参探测。iframe 内的插件(S4 面板)用它判定
-//! 自己运行在桌面壳内;纯 web 环境下该调用超时/被拒,弹窗按钮自隐藏。
-//!
-//! 两个命令都被 `src/hooks/use-iframe-invoke.ts` 的白名单登记,且弹窗窗口
-//! label(`remote-*`)已列入 `capabilities/default.json` 的窗口 glob,其
-//! remote URL 面与主窗口一致(仅 loopback)。错误遵循仓库约定:
-//! `Result<_, String>`,Err 以大写协议前缀开头(如 `REMOTE_URL_INVALID:`)。
+use std::time::Duration;
+use serde_json::Value;
use tauri::{AppHandle, Manager};
+fn remote_method(method: &str) -> Result<(reqwest::Method, &str), String> {
+ if !matches!(
+ method,
+ "GET /api/desktop/dsh-tauri-ssh/machines"
+ | "POST /api/desktop/dsh-tauri-ssh/machines"
+ | "DELETE /api/desktop/dsh-tauri-ssh/machines"
+ | "POST /api/desktop/dsh-tauri-ssh/machines/connect"
+ | "POST /api/desktop/dsh-tauri-ssh/machines/disconnect"
+ | "GET /api/desktop/dsh-tauri-ssh/machines/events"
+ | "POST /api/desktop/dsh-tauri-ssh/machines/install"
+ | "POST /api/desktop/dsh-tauri-ssh/machines/test"
+ | "GET /api/desktop/dsh-tauri-ssh/session/role"
+ | "GET /api/desktop/dsh-tauri-ssh/settings"
+ | "POST /api/desktop/dsh-tauri-ssh/settings"
+ | "POST /api/desktop/dsh-tauri-ssh/sync/apply"
+ | "GET /api/desktop/dsh-tauri-ssh/sync/preview"
+ ) {
+ return Err(format!("REMOTE_METHOD_INVALID: {method}"));
+ }
+ let (verb, path) = method
+ .split_once(' ')
+ .ok_or_else(|| format!("REMOTE_METHOD_INVALID: {method}"))?;
+ let verb = verb
+ .parse()
+ .map_err(|_| format!("REMOTE_METHOD_INVALID: {method}"))?;
+ Ok((verb, path))
+}
+
+async fn remote_request(
+ port: u16,
+ method: reqwest::Method,
+ path: &str,
+ payload: Option<Value>,
+) -> Result<Value, String> {
+ let is_get = method == reqwest::Method::GET;
+ let client = reqwest::Client::builder()
+ .no_proxy()
+ .redirect(reqwest::redirect::Policy::none())
+ .timeout(Duration::from_secs(if is_get { 10 } else { 600 }))
+ .build()
+ .map_err(|error| format!("REMOTE_REQUEST_FAILED: {error}"))?;
+ let mut request = client.request(
+ method,
+ format!("{}{path}", crate::config::get_dsh_service_url(port)),
+ );
+ if let Some(payload) = payload.filter(|value| !value.is_null()) {
+ if is_get {
+ let params = payload.as_object().ok_or_else(|| {
+ "REMOTE_PAYLOAD_INVALID: GET payload must be a query object".to_string()
+ })?;
+ let mut query = Vec::new();
+ for (key, value) in params {
+ let value = match value {
+ Value::Null => continue,
+ Value::String(value) => value.clone(),
+ Value::Bool(_) | Value::Number(_) => value.to_string(),
+ _ => {
+ return Err(format!(
+ "REMOTE_PAYLOAD_INVALID: query parameter {key} must be primitive"
+ ));
+ }
+ };
+ query.push((key, value));
+ }
+ request = request.query(&query);
+ } else {
+ request = request.json(&payload);
+ }
+ }
+ let response = request
+ .send()
+ .await
+ .map_err(|error| format!("REMOTE_REQUEST_FAILED: {error}"))?;
+ let status = response.status();
+ if matches!(status.as_u16(), 404 | 405) {
+ return Err(format!("REMOTE_API_MISSING: {}", status.as_u16()));
+ }
+ let body = response
+ .bytes()
+ .await
+ .map_err(|error| format!("REMOTE_REQUEST_FAILED: {error}"))?;
+ let value: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
+ if !status.is_success() {
+ let message = value
+ .get("error")
+ .and_then(Value::as_str)
+ .or_else(|| value.get("message").and_then(Value::as_str))
+ .map(str::to_string)
+ .unwrap_or_else(|| format!("HTTP {}", status.as_u16()));
+ return Err(format!("REMOTE_REQUEST_FAILED: {message}"));
+ }
+ Ok(value)
+}
+
+#[tauri::command]
+pub async fn remote(
+ app_handle: AppHandle,
+ method: String,
+ payload: Option<Value>,
+) -> Result<Value, String> {
+ let (method, path) = remote_method(&method)?;
+ let port = crate::config::get_store_dat_setting(&app_handle).port;
+ remote_request(port, method, path, payload).await
+}
+
/// 弹窗窗口 label 前缀(与 capability 的 `remote-*` glob 对应)。
const REMOTE_WINDOW_LABEL_PREFIX: &str = "remote-";
@@ -26,7 +115,13 @@ const REMOTE_WINDOW_LABEL_PREFIX: &str = "remote-";
/// 其余字符一律折叠为 `-`,避免任意 machineId 注入非法 label。
fn sanitize_label_part(raw: &str) -> String {
raw.chars()
- .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | ':') { c } else { '-' })
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | ':') {
+ c
+ } else {
+ '-'
+ }
+ })
.collect()
}
@@ -82,7 +177,7 @@ fn open_window_args(machine_id: &str, url: &str) -> Result<(String, Option<tauri
/// 打开(已开则聚焦)`remote-<machineId>` 弹窗窗口,加载壳层应用。
///
/// 壳不自存机器状态:前端按窗口 label 自解析目标机器并切换(机器状态经
-/// `/api-ssh` 轮询获取);`url` 只做回环校验。重复调用聚焦已有窗口(不
+/// `/api/desktop/dsh-tauri-ssh/machines` 轮询获取);`url` 只做回环校验。重复调用聚焦已有窗口(不
/// 重复建窗);失败返回带前缀的可读错误,由调用方(S4 面板按钮)呈现。
#[tauri::command]
pub fn remote_open_window(
@@ -107,7 +202,281 @@ pub fn remote_open_window(
#[cfg(test)]
mod tests {
- use super::{sanitize_label_part, validate_loopback_http_url};
+ use super::{remote_method, remote_request, sanitize_label_part, validate_loopback_http_url};
+ use serde_json::{json, Value};
+ use std::time::Duration;
+ use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+
+ async fn response_server(
+ status: &str,
+ headers: &str,
+ body: &str,
+ ) -> (u16, tokio::task::JoinHandle<(String, Vec<u8>)>) {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let response = format!(
+ "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n{headers}\r\n{body}",
+ body.len()
+ );
+ let server = tokio::spawn(async move {
+ tokio::time::timeout(Duration::from_secs(3), async move {
+ let (socket, _) = listener.accept().await.unwrap();
+ let mut socket = BufReader::new(socket);
+ let mut headers = String::new();
+ let mut length = 0;
+ loop {
+ let mut line = String::new();
+ assert_ne!(socket.read_line(&mut line).await.unwrap(), 0);
+ if line == "\r\n" {
+ break;
+ }
+ if let Some(value) = line.to_ascii_lowercase().strip_prefix("content-length:") {
+ length = value.trim().parse().unwrap();
+ }
+ headers.push_str(&line);
+ }
+ let mut body = vec![0; length];
+ socket.read_exact(&mut body).await.unwrap();
+ socket
+ .get_mut()
+ .write_all(response.as_bytes())
+ .await
+ .unwrap();
+ (headers, body)
+ })
+ .await
+ .expect("isolated loopback server must finish within three seconds")
+ });
+ (port, server)
+ }
+
+ #[test]
+ fn remote_whitelist_accepts_all_thirteen_generated_endpoints() {
+ for method in [
+ "GET /api/desktop/dsh-tauri-ssh/machines",
+ "POST /api/desktop/dsh-tauri-ssh/machines",
+ "DELETE /api/desktop/dsh-tauri-ssh/machines",
+ "POST /api/desktop/dsh-tauri-ssh/machines/connect",
+ "POST /api/desktop/dsh-tauri-ssh/machines/disconnect",
+ "GET /api/desktop/dsh-tauri-ssh/machines/events",
+ "POST /api/desktop/dsh-tauri-ssh/machines/install",
+ "POST /api/desktop/dsh-tauri-ssh/machines/test",
+ "GET /api/desktop/dsh-tauri-ssh/session/role",
+ "GET /api/desktop/dsh-tauri-ssh/settings",
+ "POST /api/desktop/dsh-tauri-ssh/settings",
+ "POST /api/desktop/dsh-tauri-ssh/sync/apply",
+ "GET /api/desktop/dsh-tauri-ssh/sync/preview",
+ ] {
+ let (verb, path) = remote_method(method).expect("generated endpoint must be allowed");
+ assert_eq!(format!("{verb} {path}"), method);
+ }
+ }
+
+ #[test]
+ fn remote_whitelist_rejects_unknown_verbs_paths_and_urls() {
+ for method in [
+ "",
+ "GET",
+ "get /api/desktop/dsh-tauri-ssh/machines",
+ "PUT /api/desktop/dsh-tauri-ssh/machines",
+ "GET /api/desktop/dsh-tauri-ssh/machines/connect",
+ "POST /api/desktop/dsh-tauri-ssh/machines/events",
+ "GET /api/desktop/dsh-tauri-ssh/machines?machineId=m1",
+ "GET /api/desktop/dsh-tauri-ssh/machines/../settings",
+ "GET /api/desktop/dsh-tauri-ssh/machines/",
+ "GET /api/desktop/dsh-tauri-ssh/machines",
+ "GET /api/desktop/dsh-tauri-ssh/machines\n",
+ "GET http://127.0.0.1:3080/api/desktop/dsh-tauri-ssh/machines",
+ "GET https://example.com/api/desktop/dsh-tauri-ssh/machines",
+ "GET //example.com/api/desktop/dsh-tauri-ssh/machines",
+ "GET /api/other",
+ ] {
+ assert_eq!(
+ remote_method(method).unwrap_err(),
+ format!("REMOTE_METHOD_INVALID: {method}")
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_get_forwards_encoded_primitive_query_without_body() {
+ let (port, server) = response_server("200 OK", "", r#"{"events":[]}"#).await;
+ let (verb, path) = remote_method("GET /api/desktop/dsh-tauri-ssh/machines/events").unwrap();
+ let result = remote_request(
+ port,
+ verb,
+ path,
+ Some(json!({"machineId": "m /&?中", "sinceSeq": 42, "flag": false, "absent": null})),
+ )
+ .await;
+ let (headers, body) = server.await.unwrap();
+ assert_eq!(result.unwrap(), json!({"events": []}));
+ let target = headers
+ .lines()
+ .next()
+ .unwrap()
+ .split_whitespace()
+ .nth(1)
+ .unwrap();
+ let url = tauri::Url::parse(&format!("http://127.0.0.1{target}")).unwrap();
+ assert_eq!(url.path(), "/api/desktop/dsh-tauri-ssh/machines/events");
+ let query: std::collections::BTreeMap<_, _> = url.query_pairs().into_owned().collect();
+ assert_eq!(
+ query,
+ std::collections::BTreeMap::from([
+ ("machineId".to_string(), "m /&?中".to_string()),
+ ("sinceSeq".to_string(), "42".to_string()),
+ ("flag".to_string(), "false".to_string()),
+ ])
+ );
+ assert!(body.is_empty());
+ }
+
+ #[tokio::test]
+ async fn remote_mutations_forward_json_body_and_preserve_http_verb() {
+ for method in [
+ "POST /api/desktop/dsh-tauri-ssh/machines/connect",
+ "DELETE /api/desktop/dsh-tauri-ssh/machines",
+ ] {
+ let (port, server) = response_server("200 OK", "", r#"{"ok":true}"#).await;
+ let (verb, path) = remote_method(method).unwrap();
+ let result = remote_request(port, verb, path, Some(json!({"machineId": "m1"}))).await;
+ let (headers, body) = server.await.unwrap();
+ assert_eq!(result.unwrap(), json!({"ok": true}));
+ assert_eq!(
+ headers.lines().next().unwrap(),
+ format!("{method} HTTP/1.1")
+ );
+ assert!(headers
+ .to_ascii_lowercase()
+ .contains("content-type: application/json\r\n"));
+ assert_eq!(
+ serde_json::from_slice::<Value>(&body).unwrap(),
+ json!({"machineId": "m1"})
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_absent_or_null_payload_sends_no_query_or_body() {
+ for method in [
+ "GET /api/desktop/dsh-tauri-ssh/machines",
+ "POST /api/desktop/dsh-tauri-ssh/machines/install",
+ ] {
+ for payload in [None, Some(Value::Null)] {
+ let (port, server) = response_server("200 OK", "", "null").await;
+ let (verb, path) = remote_method(method).unwrap();
+ let result = remote_request(port, verb, path, payload).await;
+ let (headers, body) = server.await.unwrap();
+ assert_eq!(result.unwrap(), Value::Null);
+ assert_eq!(
+ headers.lines().next().unwrap(),
+ format!("{method} HTTP/1.1")
+ );
+ assert!(body.is_empty());
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_success_tolerates_empty_or_non_json_body() {
+ for (status, body) in [
+ ("204 No Content", ""),
+ ("200 OK", ""),
+ ("201 Created", "not JSON"),
+ ] {
+ let (port, server) = response_server(status, "", body).await;
+ let (verb, path) = remote_method("POST /api/desktop/dsh-tauri-ssh/settings").unwrap();
+ let result = remote_request(port, verb, path, None).await;
+ server.await.unwrap();
+ assert_eq!(result.unwrap(), Value::Null);
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_missing_api_is_distinct_from_other_http_failures() {
+ for (status, expected) in [("404 Not Found", "404"), ("405 Method Not Allowed", "405")] {
+ let (port, server) = response_server(status, "", r#"{"error":"disabled"}"#).await;
+ let (verb, path) = remote_method("GET /api/desktop/dsh-tauri-ssh/settings").unwrap();
+ let result = remote_request(port, verb, path, None).await;
+ server.await.unwrap();
+ assert_eq!(
+ result.unwrap_err(),
+ format!("REMOTE_API_MISSING: {expected}")
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_http_failures_keep_server_error_message_or_status() {
+ for (body, expected) in [
+ (
+ r#"{"error":"SSH refused","message":"ignored"}"#,
+ "SSH refused",
+ ),
+ (r#"{"message":"bootstrap failed"}"#, "bootstrap failed"),
+ ("not JSON", "HTTP 500"),
+ ("", "HTTP 500"),
+ ] {
+ let (port, server) = response_server("500 Internal Server Error", "", body).await;
+ let (verb, path) =
+ remote_method("POST /api/desktop/dsh-tauri-ssh/machines/test").unwrap();
+ let result = remote_request(port, verb, path, None).await;
+ server.await.unwrap();
+ assert_eq!(
+ result.unwrap_err(),
+ format!("REMOTE_REQUEST_FAILED: {expected}")
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn remote_unreachable_service_is_not_reported_as_missing_api() {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ let (verb, path) = remote_method("GET /api/desktop/dsh-tauri-ssh/machines").unwrap();
+ let error = remote_request(port, verb, path, None).await.unwrap_err();
+ assert!(
+ error.starts_with("REMOTE_REQUEST_FAILED:"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[tokio::test]
+ async fn remote_redirects_are_rejected_without_contacting_target() {
+ let target = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ target.set_nonblocking(true).unwrap();
+ for location in [
+ format!("http://{}/outside", target.local_addr().unwrap()),
+ "https://example.invalid/outside".to_string(),
+ ] {
+ let (port, server) =
+ response_server("302 Found", &format!("Location: {location}\r\n"), "").await;
+ let (verb, path) = remote_method("GET /api/desktop/dsh-tauri-ssh/machines").unwrap();
+ let result = remote_request(port, verb, path, None).await;
+ server.await.unwrap();
+ assert_eq!(result.unwrap_err(), "REMOTE_REQUEST_FAILED: HTTP 302");
+ }
+ assert_eq!(
+ target.accept().unwrap_err().kind(),
+ std::io::ErrorKind::WouldBlock
+ );
+ }
+
+ #[tokio::test]
+ async fn remote_invalid_get_payload_is_rejected_before_connecting() {
+ let (verb, path) = remote_method("GET /api/desktop/dsh-tauri-ssh/machines/events").unwrap();
+ for payload in [json!([]), json!({"machineId": {"nested": true}})] {
+ let error = remote_request(0, verb.clone(), path, Some(payload))
+ .await
+ .unwrap_err();
+ assert!(
+ error.starts_with("REMOTE_PAYLOAD_INVALID:"),
+ "unexpected error: {error}"
+ );
+ }
+ }
#[test]
fn label_part_keeps_tauri_charset_and_folds_the_rest() {
@@ -120,10 +489,7 @@ mod tests {
#[test]
fn loopback_http_urls_pass_validation() {
- for raw in [
- "http://127.0.0.1:3080",
- "http://127.0.0.1:49152/",
- ] {
+ for raw in ["http://127.0.0.1:3080", "http://127.0.0.1:49152/"] {
let url = validate_loopback_http_url(raw)
.unwrap_or_else(|err| panic!("{raw} should pass: {err}"));
assert_eq!(url.scheme(), "http");
@@ -133,14 +499,14 @@ mod tests {
#[test]
fn non_loopback_or_non_http_urls_are_rejected() {
for raw in [
- "https://127.0.0.1:3080", // https 不允许(隧道是明文回环)
- "http://192.168.1.5:3080", // 非回环
- "http://example.com", // 公网域名
- "http://localhost:3080", // 命不中 capability remote.urls,命令侧一并拒绝
- "http://[::1]:3080", // 同上:与 127.0.0.1 精确对齐
- "file:///etc/passwd", // 非 http scheme
- "not a url", // 解析失败
- "", // 空
+ "https://127.0.0.1:3080", // https 不允许(隧道是明文回环)
+ "http://192.168.1.5:3080", // 非回环
+ "http://example.com", // 公网域名
+ "http://localhost:3080", // 命不中 capability remote.urls,命令侧一并拒绝
+ "http://[::1]:3080", // 同上:与 127.0.0.1 精确对齐
+ "file:///etc/passwd", // 非 http scheme
+ "not a url", // 解析失败
+ "", // 空
] {
let err = validate_loopback_http_url(raw)
.err()
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 32b37c86..9c462602 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1117,6 +1117,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::get_pet_asset,
crate::bridge::list_preset_pets,
crate::desktop::pet_mouse::start_pet_mouse_stream,
+ crate::bridge::remote::remote,
crate::bridge::remote_bridge_ping,
crate::bridge::remote_open_window,
]
diff --git a/src-tauri/src/service/plugin/internal/manifest.rs b/src-tauri/src/service/plugin/internal/manifest.rs
index ee1bfe40..901efe8f 100644
--- a/src-tauri/src/service/plugin/internal/manifest.rs
+++ b/src-tauri/src/service/plugin/internal/manifest.rs
@@ -266,14 +266,15 @@ pub(super) fn dep_matches_spec(actual: &str, expected: &str) -> bool {
.strip_prefix("link:")
.or_else(|| spec.strip_prefix("file:"))
.unwrap_or(spec);
- // 统一用 dunce 归一化 Windows 扩展长度路径前缀(`\\?\`):
- // 期望值已经由 bundled_dep_spec 归一化掉前缀;若历史命中的实值仍带
- // `//?/` / `\\?\` 前缀,先归一再比对,保证幂等(避免旧值一次次触发
- // 不必要的重装)。先把手写正斜杠的 verbatim 形式(`//?/`)换算成反斜杠
- // (dunce 依赖 `\\?\` 识别 verbatim),再交给 dunce::simplified,最后
- // 统一回正斜杠,与 bundled_dep_spec 的产出可比。
- let backslash = stripped.replace('/', "\\");
- dunce::simplified(Path::new(&backslash))
+ let normalized = stripped.replace(['/', '\\'], std::path::MAIN_SEPARATOR_STR);
+ let path = Path::new(&normalized);
+ let resolved = if path.is_absolute() {
+ dunce::canonicalize(path).ok()
+ } else {
+ None
+ };
+ resolved
+ .unwrap_or_else(|| dunce::simplified(path).to_path_buf())
.to_string_lossy()
.replace('\\', "/")
.trim_end_matches('/')
@@ -523,11 +524,40 @@ mod tests {
));
}
+ #[test]
+ fn dep_spec_does_not_reinstall_healthy_workspace_path_alias() {
+ let root = std::env::temp_dir().join(format!(
+ "dsh-dep-path-alias-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(root.join("src-tauri")).unwrap();
+ std::fs::create_dir_all(root.join("packages/dsh-tauri")).unwrap();
+ let actual =
+ crate::service::plugin::preset::bundled_dep_spec(&root.join("packages/dsh-tauri"));
+ let expected = crate::service::plugin::preset::bundled_dep_spec(
+ &root.join("src-tauri/../packages/dsh-tauri"),
+ );
+ let matches = dep_matches_spec(&actual, &expected);
+ std::fs::remove_dir_all(&root).unwrap();
+ assert!(
+ matches,
+ "healthy plugin must not reinstall: actual={actual}, expected={expected}"
+ );
+ }
+
#[test]
fn dep_spec_rejects_wrong_path_or_source() {
let expected = "link:C:/Apps/dsh/resources/internal-plugins/dsh-tauri";
// 仍指向 npm 版本(用户手动从 npm 安装,非捆绑 link: 源)
assert!(!dep_matches_spec("[email protected]", expected));
+ assert!(!dep_matches_spec("^0.2.0", expected));
+ let cwd_spec =
+ crate::service::plugin::preset::bundled_dep_spec(&std::env::current_dir().unwrap());
+ assert!(!dep_matches_spec(".", &cwd_spec));
// 指向其它位置(旧版本安装目录等)
assert!(!dep_matches_spec("link:D:/elsewhere/dsh-tauri", expected));
// 同名不同宿主盘符
diff --git a/src/apis/http.test.ts b/src/apis/http.test.ts
new file mode 100644
index 00000000..85e9a7c4
--- /dev/null
+++ b/src/apis/http.test.ts
@@ -0,0 +1,29 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { getMachines, getMachinesEvents, postMachinesConnect } from './remote'
+
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
+vi.mock('@tauri-apps/api/core', () => ({ invoke }))
+
+beforeEach(() => invoke.mockReset())
+afterEach(() => vi.restoreAllMocks())
+
+describe('generated remote API transport', () => {
+ it('列表和事件参数通过 remote invoke 转发,不在前端拼服务地址', async () => {
+ invoke.mockResolvedValueOnce({ enabled: true, items: [] }).mockResolvedValueOnce({ items: [] })
+ await expect(getMachines()).resolves.toEqual({ enabled: true, items: [] })
+ await expect(getMachinesEvents({ machineId: 'm1', sinceSeq: 3 })).resolves.toEqual({ items: [] })
+ expect(invoke.mock.calls).toEqual([
+ ['remote', { method: 'GET /api/desktop/dsh-tauri-ssh/machines', payload: null }],
+ ['remote', { method: 'GET /api/desktop/dsh-tauri-ssh/machines/events', payload: { machineId: 'm1', sinceSeq: 3 } }],
+ ])
+ })
+
+ it('连接载荷原样传递并保留 Rust 拒绝码', async () => {
+ invoke.mockRejectedValueOnce('REMOTE_API_MISSING: 405')
+ await expect(postMachinesConnect({ machineId: 'm1' })).rejects.toBe('REMOTE_API_MISSING: 405')
+ expect(invoke).toHaveBeenCalledWith('remote', {
+ method: 'POST /api/desktop/dsh-tauri-ssh/machines/connect',
+ payload: { machineId: 'm1' },
+ })
+ })
+})
diff --git a/src/apis/http.ts b/src/apis/http.ts
new file mode 100644
index 00000000..da5c10cc
--- /dev/null
+++ b/src/apis/http.ts
@@ -0,0 +1,15 @@
+import { invoke } from '@tauri-apps/api/core'
+
+export interface FetchOptions {
+ baseURL?: string
+ method?: string
+ params?: object
+ body?: unknown
+}
+
+export function ofetch<T>(path: string, options: FetchOptions = {}): Promise<T> {
+ return invoke<T>('remote', {
+ method: `${(options.method ?? 'get').toUpperCase()} ${options.baseURL ?? ''}${path}`,
+ payload: options.params ?? options.body ?? null,
+ })
+}
diff --git a/src/apis/remote.ts b/src/apis/remote.ts
new file mode 100644
index 00000000..3c4e238f
--- /dev/null
+++ b/src/apis/remote.ts
@@ -0,0 +1,76 @@
+/*
+ * @title dsh-tauri-ssh
+ * @swagger 2.0
+ * @version 0.0.0
+ */
+
+import type { FetchOptions } from "./http";
+import { ofetch } from "./http";
+import type * as Types from "./remote.types";
+
+export const baseURL = "/api/desktop/dsh-tauri-ssh";
+
+/** @method post */
+export function postMachinesConnect(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshConnectResponse>("/machines/connect", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getMachines(options?: FetchOptions) {
+ return ofetch<Types.SshMachinesResponse>("/machines", { baseURL, method: "get", ...options });
+}
+
+/** @method post */
+export function postMachines(body: Types.SshMachineSaveBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines", { baseURL, method: "post", body, ...options });
+}
+
+/** @method delete */
+export function deleteMachines(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines", { baseURL, method: "delete", body, ...options });
+}
+
+/** @method post */
+export function postMachinesDisconnect(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshActionResponse>("/machines/disconnect", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getMachinesEvents(params?: Types.GetMachinesEventsQuery, options?: FetchOptions) {
+ return ofetch<Types.SshMachineEventsResponse>("/machines/events", { baseURL, method: "get", params, ...options });
+}
+
+/** @method post */
+export function postMachinesInstall(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshInstallResponse>("/machines/install", { baseURL, method: "post", body, ...options });
+}
+
+/** @method post */
+export function postMachinesTest(body: Types.SshMachineIdBody, options?: FetchOptions) {
+ return ofetch<Types.SshTestResponse>("/machines/test", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getSessionRole(options?: FetchOptions) {
+ return ofetch<Types.SshSessionRoleResponse>("/session/role", { baseURL, method: "get", ...options });
+}
+
+/** @method get */
+export function getSettings(options?: FetchOptions) {
+ return ofetch<Types.SshSettingsResponse>("/settings", { baseURL, method: "get", ...options });
+}
+
+/** @method post */
+export function postSettings(body: Types.SshSettingsBody, options?: FetchOptions) {
+ return ofetch<Types.SshSettingsResponse>("/settings", { baseURL, method: "post", body, ...options });
+}
+
+/** @method post */
+export function postSyncApply(body: Types.SyncApplyBody, options?: FetchOptions) {
+ return ofetch<Types.SyncApplyResponse>("/sync/apply", { baseURL, method: "post", body, ...options });
+}
+
+/** @method get */
+export function getSyncPreview(options?: FetchOptions) {
+ return ofetch<Types.SyncPreviewResponse>("/sync/preview", { baseURL, method: "get", ...options });
+}
diff --git a/src/apis/remote.types.ts b/src/apis/remote.types.ts
new file mode 100644
index 00000000..ff14c9a8
--- /dev/null
+++ b/src/apis/remote.types.ts
@@ -0,0 +1,154 @@
+export type SshConnectResponse = {
+ tunnelBaseUrl?: string;
+ error?: string;
+};
+export type SshActionResponse = {
+ error?: string;
+};
+export type SshMachineEventsResponse = {
+ items?: SshMachineEventItem[];
+ nextSeq?: number;
+ error?: string;
+};
+export type SshMachineEventItem = {
+ seq?: number;
+ ts?: string;
+ machineId?: string;
+ stage?: string;
+ line?: string;
+ terminal?: string;
+ reason?: string;
+};
+export type SshMachinesResponse = {
+ enabled?: boolean;
+ items?: SshMachineListItem[];
+ discovered?: SshMachineListItem[];
+ error?: string;
+};
+export type SshMachineListItem = {
+ id?: string;
+ name?: string;
+ host?: string;
+ port?: number;
+ user?: string;
+ hasPassword?: boolean;
+ hasPassphrase?: boolean;
+ remotePort?: number;
+ profileName?: string;
+ startCommand?: string;
+ color?: string;
+ tintBorder?: boolean;
+ state?: SshConnectionState;
+ tunnelBaseUrl?: string;
+ lastError?: string;
+ dshMissing?: boolean;
+ progress?: SshProgress;
+ nextRetryAt?: number;
+ authMethod?: SshAuthMethod;
+};
+export type SshConnectionState = "disconnected" | "testing" | "connecting" | "connected" | "reconnecting" | "given-up";
+export type SshProgress = {
+ phase: SshProgressPhase;
+ attempt?: number;
+ total?: number;
+ item?: string;
+ log?: string;
+};
+export type SshProgressPhase = "handshake" | "starting" | "probing" | "installing" | "syncing";
+export type SshAuthMethod = "agent" | "key" | "password";
+export type SshInstallResponse = {
+ installed?: string[];
+ dshRef?: string;
+ dshVersion?: string;
+ dshPath?: string;
+ credentialsCopied?: boolean;
+ credentialsError?: string;
+ error?: string;
+};
+export type SshMachineRowBody = {
+ name?: string;
+ host?: string;
+ port?: number;
+ user?: string;
+ remotePort?: number;
+ profileName?: string;
+ startCommand?: string;
+ color?: string;
+ tintBorder?: boolean;
+};
+export type SshMachineSecretsBody = {
+ password?: string;
+ passphrase?: string;
+};
+export type SshTestResponse = {
+ ok?: boolean;
+ banner?: string;
+ message?: string;
+ error?: string;
+};
+export type SshSessionRoleResponse = {
+ role?: string;
+ remote?: boolean;
+ origin?: string;
+ error?: string;
+};
+export type SshSettingsResponse = {
+ enabled?: boolean;
+ error?: string;
+};
+export type SyncPluginRefBody = {
+ name?: string;
+ spec?: string;
+};
+export type SyncSkillRefBody = {
+ name?: string;
+ root?: string;
+};
+export type SyncApplyResponse = {
+ items?: SyncApplyItemResult[];
+ error?: string;
+};
+export type SyncApplyItemResult = {
+ kind?: string;
+ name?: string;
+ root?: string;
+ ok?: boolean;
+ error?: string;
+ log?: string;
+};
+export type SyncPreviewResponse = {
+ plugins?: SyncPreviewPluginItem[];
+ skills?: SyncPreviewSkillItem[];
+ error?: string;
+};
+export type SyncPreviewPluginItem = {
+ name?: string;
+ spec?: string;
+ syncable?: boolean;
+ reason?: string;
+};
+export type SyncPreviewSkillItem = {
+ name?: string;
+ root?: string;
+};
+
+export interface SshMachineIdBody {
+ machineId?: string;
+}
+export interface SshMachineSaveBody {
+ machineId?: string;
+ row?: SshMachineRowBody;
+ secrets?: SshMachineSecretsBody;
+}
+export interface SshSettingsBody {
+ enabled?: boolean;
+}
+export interface SyncApplyBody {
+ machineId?: string;
+ plugins?: SyncPluginRefBody[];
+ skills?: SyncSkillRefBody[];
+}
+export interface GetMachinesEventsQuery {
+ machineId?: string;
+ sinceSeq?: number;
+}
diff --git a/src/config/query-keys.ts b/src/config/query-keys.ts
index c9967af3..f382374d 100644
--- a/src/config/query-keys.ts
+++ b/src/config/query-keys.ts
@@ -19,4 +19,6 @@ export const queryKeys = {
profiles: ['profiles'] as const,
/** 当前档案的备份快照列表 */
backups: ['backups'] as const,
+ remoteMachines: ['remote_machines'] as const,
+ remoteEvents: ['remote_events'] as const,
} as const
diff --git a/src/hooks/use-remote-machines.ts b/src/hooks/use-remote-machines.ts
deleted file mode 100644
index c5a135df..00000000
--- a/src/hooks/use-remote-machines.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useEventListener, useMount } from '@reause/core'
-import { getCurrentWindow } from '@tauri-apps/api/window'
-import { useRef } from 'react'
-import { store } from '@/store'
-
-/** 远端弹窗 label 前缀(与 rust remote_open_window 的窗口命名一致)。 */
-const REMOTE_WINDOW_LABEL_PREFIX = 'remote-'
-
-/**
- * 远端机器数据面的组件侧装配:启动轮询(store 内幂等)并挂「窗口聚焦 /
- * 页面可见」触发的即时刷新。卸载时只摘监听——轮询属于壳层生命周期,由
- * store 持有(StrictMode 双挂载下 boot 只执行一次)。
- *
- * 远端弹窗(label remote-<machineId>,加载壳层本体)启动即切到目标机器:
- * 本窗口的 store 独立于主窗口,切换只影响本窗口视图。
- */
-export function useRemoteMachines(): void {
- useMount(() => {
- store.remote.boot()
- // 非 tauri 运行时(单测 jsdom)getCurrentWindow 直接抛——按主窗口语义跳过
- let label = ''
- try {
- label = getCurrentWindow().label
- }
- catch {
- label = ''
- }
- if (label.startsWith(REMOTE_WINDOW_LABEL_PREFIX)) {
- const machineId = label.slice(REMOTE_WINDOW_LABEL_PREFIX.length)
- if (machineId !== '')
- void store.remote.openInitialMachine(machineId)
- }
- })
-
- function refreshNow() {
- if (!document.hidden)
- void store.remote.refresh()
- }
-
- useEventListener('focus', refreshNow)
- useEventListener(useRef(document), 'visibilitychange', refreshNow)
-}
diff --git a/src/store/modules/remote/logic.test.ts b/src/hooks/use-remote.logic.test.ts
similarity index 85%
rename from src/store/modules/remote/logic.test.ts
rename to src/hooks/use-remote.logic.test.ts
index ff19bd2c..5bc19ffc 100644
--- a/src/store/modules/remote/logic.test.ts
+++ b/src/hooks/use-remote.logic.test.ts
@@ -1,6 +1,6 @@
-import type { SshMachineRow } from './types'
+import type { SshMachineRow } from './use-remote'
import { describe, expect, it } from 'vitest'
-import { borderTintOf, dotClassOf, dotStyleOf, reconcileSwitcher } from './logic'
+import { dotClassOf, reconcileSwitcher } from './use-remote'
function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
return {
@@ -15,7 +15,6 @@ describe('dotClassOf(S3 词汇表色点语义)', () => {
it('机器标识色优先:任何状态都不覆盖内联色', () => {
for (const state of ['disconnected', 'connected', 'reconnecting', 'given-up'] as const) {
expect(dotClassOf({ color: '#ff00ff', state })).toBe('')
- expect(dotStyleOf({ color: '#ff00ff' })).toEqual({ backgroundColor: '#ff00ff' })
}
})
@@ -26,16 +25,6 @@ describe('dotClassOf(S3 词汇表色点语义)', () => {
expect(dotClassOf({ state: 'testing' })).toBe('bg-warning')
expect(dotClassOf({ state: 'given-up' })).toBe('bg-danger')
expect(dotClassOf({ state: 'disconnected' })).toBe('bg-line-strong')
- expect(dotStyleOf({})).toBeUndefined()
- })
-})
-
-describe('borderTintOf(内容区着色)', () => {
- it('活动机器勾选 tintBorder 且有标识色才描边', () => {
- expect(borderTintOf(machineOf({ color: '#123456', tintBorder: true }))).toBe('#123456')
- expect(borderTintOf(machineOf({ color: '#123456' }))).toBeNull()
- expect(borderTintOf(machineOf({ tintBorder: true }))).toBeNull()
- expect(borderTintOf(undefined)).toBeNull()
})
})
diff --git a/src/hooks/use-remote.machines.test.ts b/src/hooks/use-remote.machines.test.ts
new file mode 100644
index 00000000..eb15c2b8
--- /dev/null
+++ b/src/hooks/use-remote.machines.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest'
+import { eventEntriesOf, machineRowsOf } from './use-remote'
+
+describe('machineRowsOf', () => {
+ it('合并 items 与 discovered、按名排序并丢掉坏行', () => {
+ const { enabled, machines } = machineRowsOf({
+ enabled: true,
+ items: [
+ { id: 'b', name: 'beta', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', color: '#123456', tintBorder: true },
+ { id: 'a', name: 'alpha', state: 'disconnected', lastError: 'boom', authMethod: 'key', nextRetryAt: 1725000000000 },
+ { id: '', name: 'bad', state: 'connected' },
+ { id: 'x' },
+ { id: 'c', name: 'gamma', state: 'nonsense' },
+ null,
+ ],
+ discovered: [{ id: 'alias', name: 'alias-host', state: 'disconnected' }],
+ })
+
+ expect(enabled).toBe(true)
+ expect(machines.map(row => row.id)).toEqual(['alias', 'a', 'b'])
+ expect(machines[2]).toMatchObject({ color: '#123456', tintBorder: true, tunnelBaseUrl: 'http://127.0.0.1:4002' })
+ expect(machines[1]).toMatchObject({ authMethod: 'key', nextRetryAt: 1725000000000, lastError: 'boom' })
+ })
+
+ it('未启用或载荷缺失都退化为空列表', () => {
+ expect(machineRowsOf({ enabled: false, items: [], discovered: [] })).toEqual({ enabled: false, machines: [] })
+ expect(machineRowsOf(undefined)).toEqual({ enabled: false, machines: [] })
+ expect(machineRowsOf({ enabled: true })).toEqual({ enabled: true, machines: [] })
+ })
+
+ it('progress 只保留合法阶段,丢弃壳层未消费的字段', () => {
+ const { machines } = machineRowsOf({
+ enabled: true,
+ items: [
+ { id: 'm1', name: 'm1', state: 'connecting', progress: { phase: 'bogus' } },
+ { id: 'm2', name: 'm2', state: 'connecting', remotePort: 3080, startCommand: 'dsh', hasPassword: true, hasPassphrase: true, progress: { phase: 'installing', attempt: 2, total: 3, log: 'download' } },
+ ],
+ })
+
+ expect(machines[0].progress).toBeUndefined()
+ expect(machines[1]).toEqual({ id: 'm2', name: 'm2', state: 'connecting', progress: { phase: 'installing' } })
+ })
+})
+
+describe('eventEntriesOf', () => {
+ it('seq/line 齐备才收', () => {
+ expect(eventEntriesOf({
+ items: [{ seq: 1, line: 'a' }, { seq: 'x', line: 'b' }, { line: 'c' }, null, { seq: 2, line: 'd' }],
+ })).toEqual([{ seq: 1, line: 'a' }, { seq: 2, line: 'd' }])
+ expect(eventEntriesOf(undefined)).toEqual([])
+ })
+})
diff --git a/src/hooks/use-remote.test.ts b/src/hooks/use-remote.test.ts
new file mode 100644
index 00000000..1bba0fc3
--- /dev/null
+++ b/src/hooks/use-remote.test.ts
@@ -0,0 +1,399 @@
+// @vitest-environment jsdom
+import type { PropsWithChildren } from 'react'
+import type { SshMachineRow } from './use-remote'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import { createElement, StrictMode } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { queryKeys } from '@/config/query-keys'
+import { useRemote } from './use-remote'
+
+const { invoke, windowInfo } = vi.hoisted(() => ({ invoke: vi.fn(), windowInfo: { label: 'main' } }))
+vi.mock('@tauri-apps/api/core', () => ({ invoke }))
+vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => windowInfo }))
+
+let client: QueryClient
+let rows: SshMachineRow[]
+let enabled: boolean
+let listError: unknown
+let eventItems: { seq: number, line: string }[]
+let connect: (id: string) => Promise<{ tunnelBaseUrl: string }>
+const disconnect = vi.fn(async (_id: string) => ({}))
+
+function machineOf(partial: Partial<SshMachineRow> = {}): SshMachineRow {
+ return { id: 'm1', name: 'alpha', state: 'disconnected', ...partial }
+}
+
+function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client }, children)
+}
+
+function StrictWrapper({ children }: PropsWithChildren) {
+ return createElement(StrictMode, null, createElement(Wrapper, null, children))
+}
+
+function mount() {
+ return renderHook(useRemote, { wrapper: Wrapper })
+}
+
+async function ready() {
+ const hook = mount()
+ await waitFor(() => expect(hook.result.current.enabled).toBe(true))
+ return hook
+}
+
+beforeEach(() => {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })
+ rows = [machineOf()]
+ enabled = true
+ listError = undefined
+ eventItems = []
+ windowInfo.label = 'main'
+ Object.assign(window, { __TAURI_INTERNALS__: {} })
+ disconnect.mockClear()
+ connect = vi.fn(async (id: string) => {
+ rows = rows.map(row => row.id === id ? { ...row, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' } : row)
+ return { tunnelBaseUrl: 'http://127.0.0.1:4001' }
+ })
+ invoke.mockReset().mockImplementation(async (command: string, args: { method: string, payload: { machineId: string, sinceSeq?: number } }) => {
+ expect(command).toBe('remote')
+ switch (args.method) {
+ case 'GET /api/desktop/dsh-tauri-ssh/machines':
+ if (listError !== undefined)
+ throw listError
+ return { enabled, items: rows, discovered: [] }
+ case 'GET /api/desktop/dsh-tauri-ssh/machines/events':
+ return { items: eventItems.filter(item => item.seq >= (args.payload.sinceSeq ?? 0)) }
+ case 'POST /api/desktop/dsh-tauri-ssh/machines/connect':
+ return connect(args.payload.machineId)
+ case 'POST /api/desktop/dsh-tauri-ssh/machines/disconnect':
+ return disconnect(args.payload.machineId)
+ default:
+ throw new Error(`Unexpected method: ${args.method}`)
+ }
+ })
+})
+
+afterEach(() => {
+ cleanup()
+ client.clear()
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+describe('useRemote 查询、降级与启动寻址', () => {
+ it('刷新失败保留列表并降级,恢复后可用', async () => {
+ const { result } = await ready()
+ expect(result.current.machines.map(row => row.name)).toEqual(['alpha'])
+ listError = 'REMOTE_REQUEST_FAILED: connection refused'
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.available).toBe(false))
+ expect(result.current.machines.map(row => row.name)).toEqual(['alpha'])
+ listError = undefined
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.available).toBe(true))
+ })
+
+ it.each([404, 405])('http %i 缺失 API 清空远端视图而非降级,启用后恢复', async (status) => {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ listError = `REMOTE_API_MISSING: ${status}`
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.available).toBe(true)
+ await waitFor(() => expect(result.current.enabled).toBe(false))
+ await waitFor(() => expect(result.current.machines).toEqual([]))
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.activeTunnelUrl).toBe('')
+ listError = undefined
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.enabled).toBe(true))
+ expect(result.current.machines.map(row => row.name)).toEqual(['alpha'])
+ })
+
+ it('enabled=false 清空列表和活动目标', async () => {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ enabled = false
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.machines).toEqual([]))
+ expect(result.current.activeId).toBeNull()
+ await waitFor(() => expect(result.current.enabled).toBe(false))
+ })
+
+ it('strictMode 下 React Query 单飞并按两秒轮询,卸载停止请求', async () => {
+ vi.useFakeTimers()
+ const { unmount } = renderHook(useRemote, { wrapper: StrictWrapper })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(6000)
+ })
+ const lists = invoke.mock.calls.filter(call => call[1].method === 'GET /api/desktop/dsh-tauri-ssh/machines')
+ expect(lists).toHaveLength(4)
+ unmount()
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4000)
+ })
+ expect(invoke.mock.calls.filter(call => call[1].method.endsWith('/machines'))).toHaveLength(4)
+ })
+
+ it('重新可见时由 React Query 刷新并恢复可用状态', async () => {
+ listError = 'REMOTE_REQUEST_FAILED: connection refused'
+ const { result } = mount()
+ await waitFor(() => expect(result.current.available).toBe(false))
+ await waitFor(() => expect(client.getQueryState(queryKeys.remoteMachines)?.fetchStatus).toBe('idle'))
+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
+ act(() => document.dispatchEvent(new Event('visibilitychange', { bubbles: true })))
+ listError = undefined
+ visibility.mockReturnValue('visible')
+ act(() => document.dispatchEvent(new Event('visibilitychange', { bubbles: true })))
+ await waitFor(() => expect(result.current.available).toBe(true))
+ expect(result.current.machines.map(row => row.name)).toEqual(['alpha'])
+ expect(invoke.mock.calls.filter(call => call[1].method.endsWith('/machines'))).toHaveLength(2)
+ })
+
+ it('remote-窗口已连接目标直接切换', async () => {
+ windowInfo.label = 'remote-m1'
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+ expect(connect).not.toHaveBeenCalled()
+ })
+
+ it('remote-窗口首轮不可达,后续成功查询补切换', async () => {
+ windowInfo.label = 'remote-m1'
+ listError = 'REMOTE_REQUEST_FAILED: startup'
+ const { result } = mount()
+ await waitFor(() => expect(result.current.available).toBe(false))
+ listError = undefined
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+ })
+
+ it('remote-窗口未连接目标走标准连接流程', async () => {
+ windowInfo.label = 'remote-m1'
+ const { result } = await ready()
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ expect(connect).toHaveBeenCalledWith('m1')
+ })
+
+ it('未知窗口目标不切换,手动选本地撤销迟到启动目标', async () => {
+ windowInfo.label = 'remote-ghost'
+ const { result } = await ready()
+ expect(result.current.activeId).toBeNull()
+ expect(connect).not.toHaveBeenCalled()
+ act(() => result.current.backToLocal())
+ rows = [machineOf({ id: 'ghost', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.activeTunnelUrl).toBe('')
+ })
+})
+
+describe('useRemote 切换和连接进度', () => {
+ it('已连接目标立即切换,不调用 connect', async () => {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ expect(result.current.activeId).toBe('m1')
+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+ expect(result.current.pendingId).toBeNull()
+ expect(connect).not.toHaveBeenCalled()
+ })
+
+ it('未连接目标通过 mutation 连接和失效查询,就绪后切换', async () => {
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ expect(result.current.pendingId).toBe('m1')
+ expect(result.current.activeTunnelUrl).toBe('')
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ expect(connect).toHaveBeenCalledWith('m1')
+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+ expect(result.current.pendingId).toBeNull()
+ })
+
+ it('连接失败撤销挂起,刷新引擎 given-up 状态和原始原因', async () => {
+ connect = vi.fn(async () => {
+ rows = [machineOf({ state: 'given-up', lastError: 'refused' })]
+ throw new Error('dial tcp timeout')
+ })
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ await waitFor(() => expect(result.current.connectFailed).toEqual({ id: 'm1', error: 'dial tcp timeout' }))
+ await waitFor(() => expect(result.current.machines[0].state).toBe('given-up'))
+ expect(result.current.machines[0].lastError).toBe('refused')
+ expect(result.current.pendingId).toBeNull()
+ expect(result.current.activeId).toBeNull()
+ })
+
+ it('reconnecting 目标只挂起,轮询就绪后切换且 URL 粘性保留', async () => {
+ rows = [machineOf({ state: 'reconnecting' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ expect(result.current.pendingId).toBe('m1')
+ expect(connect).not.toHaveBeenCalled()
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ rows = [machineOf({ state: 'reconnecting' })]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.activeId).toBe('m1')
+ expect(result.current.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+ })
+
+ it('活动机器被断开时查询自动回本地', async () => {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ rows = [machineOf()]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.activeId).toBeNull())
+ expect(result.current.activeTunnelUrl).toBe('')
+ })
+
+ it('手动回本地撤销挂起,目标随后就绪不抢切', async () => {
+ rows = [machineOf({ state: 'connecting' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ expect(result.current.pendingId).toBe('m1')
+ act(() => result.current.backToLocal())
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.pendingId).toBeNull()
+ })
+
+ it('降级态忽略远端切换', async () => {
+ listError = 'REMOTE_REQUEST_FAILED: refused'
+ const { result } = mount()
+ await waitFor(() => expect(result.current.available).toBe(false))
+ act(() => result.current.switchTo('m1'))
+ expect(result.current.pendingId).toBeNull()
+ expect(connect).not.toHaveBeenCalled()
+ })
+
+ it('断开活动机器先回本地,再下发 mutation 并刷新', async () => {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ disconnect.mockImplementationOnce(async () => {
+ rows = [machineOf()]
+ return {}
+ })
+ act(() => result.current.disconnect('m1'))
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.activeTunnelUrl).toBe('')
+ await waitFor(() => expect(disconnect).toHaveBeenCalledWith('m1'))
+ await waitFor(() => expect(result.current.machines[0].state).toBe('disconnected'))
+ })
+
+ it('增量事件和实际阶段累积,连接成功后清空跟踪', async () => {
+ let release!: (value: { tunnelBaseUrl: string }) => void
+ connect = vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((resolve) => {
+ release = resolve
+ }))
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ await waitFor(() => expect(connect).toHaveBeenCalledWith('m1'))
+ rows = [machineOf({ state: 'connecting', progress: { phase: 'installing' } })]
+ eventItems = [{ seq: 0, line: 'ssh ok' }, { seq: 1, line: 'download' }]
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.connectTrail).toEqual(['installing']))
+ await act(async () => {
+ await client.refetchQueries({ queryKey: queryKeys.remoteEvents })
+ })
+ await waitFor(() => expect(result.current.connectLog).toEqual(['ssh ok', 'download']))
+ eventItems.push({ seq: 2, line: 'started' })
+ await act(async () => {
+ await client.refetchQueries({ queryKey: queryKeys.remoteEvents })
+ })
+ await waitFor(() => expect(result.current.connectLog).toEqual(['ssh ok', 'download', 'started']))
+ expect(invoke).toHaveBeenCalledWith('remote', { method: 'GET /api/desktop/dsh-tauri-ssh/machines/events', payload: { machineId: 'm1', sinceSeq: 2 } })
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ await act(async () => {
+ release({ tunnelBaseUrl: 'http://127.0.0.1:4001' })
+ })
+ await waitFor(() => expect(result.current.activeId).toBe('m1'))
+ expect(result.current.connectTrail).toEqual([])
+ expect(result.current.connectLog).toEqual([])
+ })
+
+ it('关闭进行中弹窗不取消 mutation,失败重新显示并保留错误日志', async () => {
+ let reject!: (reason: Error) => void
+ connect = vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((_resolve, fail) => {
+ reject = fail
+ }))
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ await waitFor(() => expect(connect).toHaveBeenCalled())
+ act(() => result.current.dismissConnect())
+ expect(result.current.pendingId).toBe('m1')
+ expect(result.current.connectDismissed).toBe(true)
+ eventItems = [{ seq: 0, line: 'handshake failed' }]
+ await act(async () => {
+ reject(new Error('timeout'))
+ })
+ await waitFor(() => expect(result.current.connectFailed).toEqual({ id: 'm1', error: 'timeout' }))
+ expect(result.current.connectDismissed).toBe(false)
+ await waitFor(() => expect(result.current.connectLog).toEqual(['handshake failed']))
+ act(() => result.current.dismissConnect())
+ expect(result.current.connectFailed).toBeNull()
+ expect(result.current.connectLog).toEqual([])
+ })
+
+ it.each(['success', 'failure'])('取消连接后迟到 %s 静默且不抢切换', async (outcome) => {
+ let resolve!: (value: { tunnelBaseUrl: string }) => void
+ let reject!: (reason: Error) => void
+ connect = vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((ok, fail) => {
+ resolve = ok
+ reject = fail
+ }))
+ const { result } = await ready()
+ act(() => result.current.switchTo('m1'))
+ await waitFor(() => expect(connect).toHaveBeenCalled())
+ act(() => result.current.disconnect('m1'))
+ expect(result.current.pendingId).toBeNull()
+ await waitFor(() => expect(disconnect).toHaveBeenCalledWith('m1'))
+ await act(async () => {
+ if (outcome === 'success') {
+ rows = [machineOf({ state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ resolve({ tunnelBaseUrl: 'http://127.0.0.1:4001' })
+ }
+ else {
+ reject(new Error('cancelled by disconnect'))
+ }
+ })
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.connectFailed).toBeNull()
+ })
+})
diff --git a/src/hooks/use-remote.ts b/src/hooks/use-remote.ts
new file mode 100644
index 00000000..02c5326d
--- /dev/null
+++ b/src/hooks/use-remote.ts
@@ -0,0 +1,284 @@
+import type { SshConnectionState, SshMachineListItem, SshProgress, SshProgressPhase } from '@/apis/remote.types'
+import { useEventListener, useUnmount, useWatch } from '@reause/core'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { getCurrentWindow } from '@tauri-apps/api/window'
+import { useRef, useState } from 'react'
+import { getMachines, getMachinesEvents, postMachinesConnect, postMachinesDisconnect } from '@/apis/remote'
+import { queryKeys } from '@/config/query-keys'
+
+export type SshMachineRow = { id: string, name: string, state: SshConnectionState } & Pick<SshMachineListItem, 'color' | 'tintBorder' | 'host' | 'port' | 'user' | 'tunnelBaseUrl' | 'lastError' | 'nextRetryAt' | 'authMethod'> & { progress?: Pick<SshProgress, 'phase'> }
+
+interface SwitcherTargets {
+ activeId: string | null
+ pendingId: string | null
+ activeTunnelUrl: string
+}
+
+function initialMachineId(): string | null {
+ if (!('__TAURI_INTERNALS__' in window))
+ return null
+ const label = getCurrentWindow().label
+ return label.startsWith('remote-') ? label.slice('remote-'.length) || null : null
+}
+
+export function useRemote() {
+ const queryClient = useQueryClient()
+ const [targets, setTargets] = useState<SwitcherTargets>({ activeId: null, pendingId: null, activeTunnelUrl: '' })
+ const [bootId, setBootId] = useState(initialMachineId)
+ const [connectTrail, setConnectTrail] = useState<SshProgressPhase[]>([])
+ const [connectDismissed, setConnectDismissed] = useState(false)
+ const [attempt, setAttempt] = useState(0)
+ const epochRef = useRef(0)
+ const machinesQuery = useQuery({
+ queryKey: queryKeys.remoteMachines,
+ queryFn: async () => {
+ try {
+ return machineRowsOf(await getMachines())
+ }
+ catch (error) {
+ if (String(error).startsWith('REMOTE_API_MISSING:'))
+ return { enabled: false, machines: [] as SshMachineRow[] }
+ throw error
+ }
+ },
+ refetchInterval: 2000,
+ })
+ const machines = machinesQuery.data?.enabled ? machinesQuery.data.machines : []
+ const available = !machinesQuery.isError
+ const enabled = machinesQuery.data?.enabled === true
+
+ function refresh() {
+ return machinesQuery.refetch({ cancelRefetch: false })
+ }
+
+ function invalidate() {
+ return queryClient.invalidateQueries({ queryKey: queryKeys.remoteMachines })
+ }
+
+ const connect = useMutation({
+ mutationFn: ({ id }: { id: string, epoch: number }) => postMachinesConnect({ machineId: id }),
+ onSuccess: async (_link, variables) => {
+ if (variables.epoch === epochRef.current)
+ await invalidate()
+ },
+ onError: (_error, variables) => {
+ if (variables.epoch !== epochRef.current)
+ return
+ setTargets(previous => ({ ...previous, pendingId: null }))
+ setConnectDismissed(false)
+ void invalidate()
+ },
+ })
+ const disconnect = useMutation({
+ mutationFn: (machineId: string) => postMachinesDisconnect({ machineId }),
+ onSettled: invalidate,
+ })
+ const connectFailed = connect.isError && connect.variables.epoch === epochRef.current
+ ? { id: connect.variables.id, error: connect.error instanceof Error ? connect.error.message : String(connect.error) }
+ : null
+ const trackedId = targets.pendingId ?? connectFailed?.id ?? null
+ const events = useQuery({
+ queryKey: [...queryKeys.remoteEvents, trackedId, attempt],
+ enabled: trackedId !== null && !connectDismissed,
+ queryFn: async () => {
+ const key = [...queryKeys.remoteEvents, trackedId, attempt]
+ const previous = queryClient.getQueryData<{ seq: number, line: string }[]>(key) ?? []
+ const sinceSeq = previous.reduce((next, item) => Math.max(next, item.seq + 1), 0)
+ const items = eventEntriesOf(await getMachinesEvents({ machineId: trackedId!, sinceSeq }))
+ return [...previous, ...items.filter(item => item.seq >= sinceSeq)]
+ },
+ refetchInterval: 2000,
+ gcTime: 0,
+ })
+
+ useWatch([machinesQuery.data], () => {
+ if (machinesQuery.data === undefined)
+ return
+ if (!enabled) {
+ epochRef.current += 1
+ setTargets({ activeId: null, pendingId: null, activeTunnelUrl: '' })
+ connect.reset()
+ setConnectTrail([])
+ return
+ }
+ setTargets(previous => reconcileSwitcher(previous, machines))
+ }, { immediate: true })
+
+ const phase = machines.find(machine => machine.id === trackedId)?.progress?.phase
+ useWatch([phase, trackedId], () => {
+ if (phase !== undefined)
+ setConnectTrail(previous => previous.at(-1) === phase ? previous : [...previous, phase])
+ if (trackedId === null)
+ setConnectTrail([])
+ })
+
+ useWatch([bootId, machinesQuery.data, available], () => {
+ if (bootId !== null && available && enabled && machines.some(machine => machine.id === bootId))
+ switchTo(bootId)
+ }, { immediate: true })
+
+ useEventListener('focus', () => {
+ if (!document.hidden)
+ void refresh()
+ })
+ useWatch([available], () => {
+ if (!available)
+ console.warn('[remote] ssh api unreachable:', String(machinesQuery.error))
+ })
+ useUnmount(() => {
+ epochRef.current += 1
+ })
+
+ function switchTo(machineId: string) {
+ setBootId(null)
+ if (!available)
+ return
+ const machine = machines.find(item => item.id === machineId)
+ if (machine === undefined)
+ return
+ epochRef.current += 1
+ setAttempt(previous => previous + 1)
+ connect.reset()
+ setConnectTrail([])
+ setConnectDismissed(false)
+ if (machine.state === 'connected' && machine.tunnelBaseUrl !== undefined) {
+ setTargets({ activeId: machineId, pendingId: null, activeTunnelUrl: machine.tunnelBaseUrl })
+ return
+ }
+ setTargets(previous => ({ ...previous, pendingId: machineId }))
+ if (machine.state === 'disconnected' || machine.state === 'given-up')
+ connect.mutate({ id: machineId, epoch: epochRef.current })
+ }
+
+ function dismissConnect() {
+ if (targets.pendingId === null)
+ connect.reset()
+ setConnectTrail([])
+ setConnectDismissed(true)
+ setAttempt(previous => previous + 1)
+ }
+
+ function backToLocal() {
+ epochRef.current += 1
+ setBootId(null)
+ setTargets({ activeId: null, pendingId: null, activeTunnelUrl: '' })
+ connect.reset()
+ dismissConnect()
+ }
+
+ function disconnectMachine(machineId: string) {
+ if (targets.activeId === machineId || targets.pendingId === machineId)
+ backToLocal()
+ disconnect.mutate(machineId)
+ }
+
+ return {
+ machines,
+ enabled,
+ available,
+ ...targets,
+ connectTrail,
+ connectLog: connectDismissed ? [] : (events.data ?? []).map(item => item.line),
+ connectFailed,
+ connectDismissed,
+ switchTo,
+ backToLocal,
+ disconnect: disconnectMachine,
+ dismissConnect,
+ refresh,
+ }
+}
+
+export type Remote = ReturnType<typeof useRemote>
+
+export function dotClassOf(machine: Pick<SshMachineRow, 'color' | 'state'>): string {
+ if (machine.color !== undefined)
+ return ''
+ switch (machine.state) {
+ case 'connected':
+ return 'bg-success'
+ case 'reconnecting':
+ case 'connecting':
+ case 'testing':
+ return 'bg-warning'
+ case 'given-up':
+ return 'bg-danger'
+ default:
+ return 'bg-line-strong'
+ }
+}
+
+export function reconcileSwitcher(prev: SwitcherTargets, machines: readonly SshMachineRow[]): SwitcherTargets {
+ let { activeId, pendingId, activeTunnelUrl } = prev
+ const active = machines.find(machine => machine.id === activeId)
+ if (active === undefined || active.state === 'disconnected' || active.state === 'given-up') {
+ activeId = null
+ activeTunnelUrl = ''
+ }
+ else if (active.state === 'connected' && active.tunnelBaseUrl !== undefined) {
+ activeTunnelUrl = active.tunnelBaseUrl
+ }
+ const pending = machines.find(machine => machine.id === pendingId)
+ if (pending === undefined || pending.state === 'given-up') {
+ pendingId = null
+ }
+ else if (pending.state === 'connected' && pending.tunnelBaseUrl !== undefined) {
+ activeId = pending.id
+ activeTunnelUrl = pending.tunnelBaseUrl
+ pendingId = null
+ }
+ return { activeId, pendingId, activeTunnelUrl }
+}
+
+export function machineRowsOf(value?: { enabled?: boolean, items?: readonly unknown[], discovered?: readonly unknown[] }): { enabled: boolean, machines: SshMachineRow[] } {
+ const machines = [...(value?.items ?? []), ...(value?.discovered ?? [])]
+ .map(machineRowOf)
+ .filter((row): row is SshMachineRow => row !== undefined)
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+ return { enabled: value?.enabled === true, machines }
+}
+
+export function eventEntriesOf(value?: { items?: readonly unknown[] }): { seq: number, line: string }[] {
+ return (value?.items ?? []).flatMap((raw) => {
+ if (typeof raw !== 'object' || raw === null)
+ return []
+ const item = raw as Record<string, unknown>
+ if (typeof item.seq !== 'number' || typeof item.line !== 'string')
+ return []
+ return [{ seq: item.seq, line: item.line }]
+ })
+}
+
+function machineRowOf(raw: unknown): SshMachineRow | undefined {
+ if (typeof raw !== 'object' || raw === null)
+ return undefined
+ const value = raw as Record<string, unknown>
+ if (typeof value.id !== 'string' || value.id === '' || typeof value.name !== 'string' || value.name === '')
+ return undefined
+ if (!['disconnected', 'testing', 'connecting', 'connected', 'reconnecting', 'given-up'].includes(String(value.state)))
+ return undefined
+ return {
+ id: value.id,
+ name: value.name,
+ ...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},
+ ...value.tintBorder === true ? { tintBorder: true } : {},
+ ...typeof value.host === 'string' && value.host !== '' ? { host: value.host } : {},
+ ...typeof value.port === 'number' ? { port: value.port } : {},
+ ...typeof value.user === 'string' && value.user !== '' ? { user: value.user } : {},
+ state: value.state as SshConnectionState,
+ ...typeof value.tunnelBaseUrl === 'string' ? { tunnelBaseUrl: value.tunnelBaseUrl } : {},
+ ...typeof value.lastError === 'string' ? { lastError: value.lastError } : {},
+ ...typeof value.nextRetryAt === 'number' ? { nextRetryAt: value.nextRetryAt } : {},
+ ...value.authMethod === 'agent' || value.authMethod === 'key' || value.authMethod === 'password' ? { authMethod: value.authMethod } : {},
+ ...progressOf(value.progress),
+ }
+}
+
+function progressOf(raw: unknown): { progress?: Pick<SshProgress, 'phase'> } {
+ if (typeof raw !== 'object' || raw === null)
+ return {}
+ const value = raw as Record<string, unknown>
+ if (!['handshake', 'installing', 'starting', 'probing', 'syncing'].includes(String(value.phase)))
+ return {}
+ return { progress: { phase: value.phase as SshProgressPhase } }
+}
diff --git a/src/layout/components/connect-dialog.test.tsx b/src/layout/components/connect-dialog.test.tsx
index 941b415b..3563dc7b 100644
--- a/src/layout/components/connect-dialog.test.tsx
+++ b/src/layout/components/connect-dialog.test.tsx
@@ -1,83 +1,107 @@
// @vitest-environment jsdom
+import type { Remote } from '@/hooks/use-remote'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { bindSshApiForTests, disposeRemoteForTests, remote } from '@/store/modules/remote'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { ConnectDialog } from './connect-dialog'
-// i18n 直通(key 即文案)
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string, params?: Record<string, unknown>) => params?.name !== undefined ? `${key}:${String(params.name)}` : key }),
}))
-beforeEach(() => {
- disposeRemoteForTests()
-})
+function remoteOf(overrides: Partial<Remote> = {}): Remote {
+ return {
+ machines: [],
+ enabled: true,
+ available: true,
+ activeId: null,
+ pendingId: null,
+ activeTunnelUrl: '',
+ connectTrail: [],
+ connectLog: [],
+ connectFailed: null,
+ connectDismissed: false,
+ switchTo: vi.fn(),
+ backToLocal: vi.fn(),
+ disconnect: vi.fn(),
+ dismissConnect: vi.fn(),
+ refresh: vi.fn<Remote['refresh']>(),
+ ...overrides,
+ }
+}
afterEach(() => {
cleanup()
- disposeRemoteForTests()
+ vi.restoreAllMocks()
})
describe('connectDialog 连接进度弹窗', () => {
it('pending 时打开:标题含机器名、步骤条只显示走过的阶段、日志尾呈现', async () => {
- remote.machines = [{ id: 'm1', name: 'alpha', state: 'connecting', progress: { phase: 'installing' } }]
- remote.pendingId = 'm1'
- remote.connectTrail = ['handshake', 'installing']
- remote.connectLog = ['[handshake] ssh ok', '[installing] download 42%']
- render(<ConnectDialog />)
+ const remote = remoteOf({
+ machines: [{ id: 'm1', name: 'alpha', state: 'connecting', progress: { phase: 'installing' } }],
+ pendingId: 'm1',
+ connectTrail: ['handshake', 'installing'],
+ connectLog: ['[handshake] ssh ok', '[installing] download 42%'],
+ })
+ render(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
expect(screen.getByText('remote.connect.title:alpha')).toBeTruthy()
const steps = screen.getByTestId('connect-steps')
expect(steps.textContent).toContain('remote.step.handshake')
expect(steps.textContent).toContain('remote.step.installing')
- // 未走过的阶段不出现
expect(steps.textContent).not.toContain('remote.step.starting')
expect(screen.getByText('[installing] download 42%')).toBeTruthy()
expect(screen.getByText('remote.connect.working')).toBeTruthy()
})
it('无 pending 且无失败定格:不渲染弹窗', () => {
- render(<ConnectDialog />)
+ render(<ConnectDialog remote={remoteOf()} />)
expect(screen.queryByRole('dialog')).toBeNull()
})
it('失败定格:直接原因 + 重试按钮(重试重新发起连接)', async () => {
- const connectSpy = vi.fn(() => new Promise<{ tunnelBaseUrl: string }>(() => {}))
- bindSshApiForTests({
- listMachines: vi.fn(async () => ({ enabled: true, machines: [{ id: 'm1', name: 'alpha', state: 'given-up' as const, lastError: 'boom' }] })),
- connect: connectSpy,
- disconnect: vi.fn(async () => undefined),
+ const connectSpy = vi.fn()
+ let remote = remoteOf({
+ machines: [{ id: 'm1', name: 'alpha', state: 'given-up', lastError: 'boom' }],
+ connectFailed: { id: 'm1', error: 'dial tcp timeout' },
+ connectLog: ['[handshake] fail'],
+ switchTo: connectSpy,
})
- remote.machines = [{ id: 'm1', name: 'alpha', state: 'given-up', lastError: 'boom' }]
- remote.connectFailed = { id: 'm1', error: 'dial tcp timeout' }
- remote.connectLog = ['[handshake] fail']
- render(<ConnectDialog />)
+ const { rerender } = render(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
expect(screen.getByText('remote.connect.failed_title')).toBeTruthy()
expect(screen.getByText('dial tcp timeout')).toBeTruthy()
fireEvent.click(screen.getByText('remote.connect.retry'))
- // 重试:失败定格清除并重新挂起连接
+ await waitFor(() => expect(connectSpy).toHaveBeenCalledWith('m1'))
+ expect(remote.dismissConnect).toHaveBeenCalledOnce()
+ remote = {
+ ...remote,
+ machines: [{ id: 'm1', name: 'alpha', state: 'connecting' }],
+ connectFailed: null,
+ pendingId: 'm1',
+ connectLog: [],
+ }
+ rerender(<ConnectDialog remote={remote} />)
await waitFor(() => expect(remote.connectFailed).toBeNull())
expect(remote.pendingId).toBe('m1')
- await waitFor(() => expect(connectSpy).toHaveBeenCalledWith('m1'))
+ expect(screen.queryByText('dial tcp timeout')).toBeNull()
+ expect(screen.getByText('remote.connect.working')).toBeTruthy()
})
it('取消连接(进行中):中止引擎尝试并关闭弹窗,无失败定格', async () => {
- const disconnectSpy = vi.fn(async () => undefined)
- bindSshApiForTests({
- listMachines: vi.fn(async () => ({ enabled: true, machines: [] })),
- connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:1' })),
- disconnect: disconnectSpy,
+ const cancelSpy = vi.fn()
+ let remote = remoteOf({
+ machines: [{ id: 'm1', name: 'alpha', state: 'connecting' }],
+ pendingId: 'm1',
+ connectTrail: ['handshake'],
+ connectLog: ['[handshake] ssh ok'],
+ disconnect: cancelSpy,
})
- remote.machines = [{ id: 'm1', name: 'alpha', state: 'connecting' }]
- remote.pendingId = 'm1'
- remote.connectTrail = ['handshake']
- remote.connectLog = ['[handshake] ssh ok']
- render(<ConnectDialog />)
+ const { rerender } = render(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
fireEvent.click(screen.getByTestId('connect-cancel'))
- // 取消:断开下发、挂起与跟踪清空、弹窗关闭,且无失败定格
- await waitFor(() => expect(disconnectSpy).toHaveBeenCalledWith('m1'))
+ await waitFor(() => expect(cancelSpy).toHaveBeenCalledWith('m1'))
+ remote = { ...remote, pendingId: null, connectTrail: [], connectLog: [] }
+ rerender(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(remote.pendingId).toBeNull()
expect(remote.connectFailed).toBeNull()
@@ -85,15 +109,20 @@ describe('connectDialog 连接进度弹窗', () => {
})
it('关闭(进行中):弹窗关闭、跟踪态清理,pending 语义不撤销', async () => {
- remote.machines = [{ id: 'm1', name: 'alpha', state: 'connecting' }]
- remote.pendingId = 'm1'
- remote.connectLog = ['[handshake] ssh ok']
- render(<ConnectDialog />)
+ let remote = remoteOf({
+ machines: [{ id: 'm1', name: 'alpha', state: 'connecting' }],
+ pendingId: 'm1',
+ connectLog: ['[handshake] ssh ok'],
+ })
+ const { rerender } = render(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.getByRole('dialog')).toBeTruthy())
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+ await waitFor(() => expect(remote.dismissConnect).toHaveBeenCalledOnce())
+ expect(remote.disconnect).not.toHaveBeenCalled()
+ remote = { ...remote, connectDismissed: true, connectTrail: [], connectLog: [] }
+ rerender(<ConnectDialog remote={remote} />)
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(remote.connectLog).toEqual([])
- // 关闭只是隐藏:连接挂起仍在(后台继续,就绪后自动切换)
expect(remote.pendingId).toBe('m1')
})
})
diff --git a/src/layout/components/connect-dialog.tsx b/src/layout/components/connect-dialog.tsx
index aef04142..84baae76 100644
--- a/src/layout/components/connect-dialog.tsx
+++ b/src/layout/components/connect-dialog.tsx
@@ -1,22 +1,13 @@
+import type { Remote } from '@/hooks/use-remote'
import { Button, Description, Modal, Spinner } from '@heroui/react'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { cn } from 'tailwind-variants'
-import { useStore } from 'valtio-define'
import { Logs } from '@/components/logs'
-import { store } from '@/store'
-/**
- * 连接进度弹窗:点击未连接机器后实时呈现管线进度。
- *
- * 内容:阶段步骤条(只显示真实走过的阶段,当前阶段高亮)+ machine.events
- * 实时日志尾。成功即自动关闭(pendingId 清空);失败定格:直接原因 +
- * 已走阶段 + 日志全部保留,提供「重试 / 关闭」。进行中可关闭弹窗,
- * 连接在后台继续(不影响引擎侧)。
- */
-export function ConnectDialog() {
+export function ConnectDialog({ remote }: { remote: Remote }) {
const { t } = useTranslation()
- const { machines, pendingId, connectFailed, connectTrail, connectLog, connectDismissed } = useStore(store.remote)
+ const { machines, pendingId, connectFailed, connectTrail, connectLog, connectDismissed } = remote
const targetId = pendingId ?? connectFailed?.id ?? null
const machine = targetId === null ? undefined : machines.find(item => item.id === targetId)
@@ -29,8 +20,8 @@ export function ConnectDialog() {
function handleRetry() {
if (connectFailed === null)
return
- store.remote.dismissConnect()
- store.remote.switchTo(connectFailed.id)
+ remote.dismissConnect()
+ remote.switchTo(connectFailed.id)
}
return (
@@ -38,7 +29,7 @@ export function ConnectDialog() {
isOpen={isOpen}
onOpenChange={(open: boolean) => {
if (!open)
- store.remote.dismissConnect()
+ remote.dismissConnect()
}}
>
<Modal.Backdrop>
@@ -82,7 +73,7 @@ export function ConnectDialog() {
</Modal.Body>
<Modal.Footer>
<If cond={failed}>
- <Button className="rounded-md" variant="tertiary" onPress={() => store.remote.dismissConnect()}>
+ <Button className="rounded-md" variant="tertiary" onPress={() => remote.dismissConnect()}>
{t('buttons.close')}
</Button>
<Button className="rounded-md" variant="primary" onPress={handleRetry}>
@@ -90,14 +81,14 @@ export function ConnectDialog() {
</Button>
</If>
<If cond={!failed}>
- <Button className="rounded-md" variant="tertiary" onPress={() => store.remote.dismissConnect()}>
+ <Button className="rounded-md" variant="tertiary" onPress={() => remote.dismissConnect()}>
{t('buttons.close')}
</Button>
<Button
className="rounded-md"
variant="secondary"
data-testid="connect-cancel"
- onPress={() => pendingId !== null && store.remote.cancelConnect(pendingId)}
+ onPress={() => pendingId !== null && remote.disconnect(pendingId)}
>
{t('remote.connect.cancel')}
</Button>
diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsx
index d234891c..465c8c51 100644
--- a/src/layout/components/iframe.tsx
+++ b/src/layout/components/iframe.tsx
@@ -68,7 +68,7 @@ export interface IframeProps {
iframeRef: RefObject<HTMLIFrameElement | null>
/**
* 远端模式:非空时 iframe 指向该隧道 URL(远端机器的本地回环隧道,见
- * `store.remote`),不再等本地实例健康;为空维持本地实例语义。
+ * `useRemote`),不再等本地实例健康;为空维持本地实例语义。
*/
srcOverride?: string | null
/** 远端机器勾选「边框着色」时的标识色:给内容区描 inset ring(一眼可辨远端态)。 */
@@ -202,7 +202,7 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr
const harness = useStore(store.harness)
const setting = useStore(store.setting)
// 远端模式:非空时 iframe 指向该隧道 URL(远端机器的本地回环隧道,见
- // `store.remote`),不再等本地实例健康;为空维持本地实例语义。
+ // `useRemote`),不再等本地实例健康;为空维持本地实例语义。
// 远端加载进度:「已落定 URL」派生——换 URL 自动回到加载态,iframe onLoad
// 记录落定收起(无 effect、无额外渲染轮次)。
const remoteMode = srcOverride !== null && srcOverride !== ''
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index a071ac14..572d63a8 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -29,7 +29,6 @@ import { ConfigDialog } from '@/ui/dialog/config'
import { DesktopUpdateDialog } from '@/ui/dialog/update'
import { writeClipboardText } from '@/utils/clipboard'
import { toast } from '@/utils/toast'
-import { ConnectDialog } from './connect-dialog'
import { RemoteSwitcher } from './remote-switcher'
/**
@@ -210,7 +209,9 @@ function ShortcutLabel({ label, hint }: { label: string, hint?: string }) {
)
}
-export interface NavbarProps { /** iframe 回报的 dsh 侧边栏折叠状态(导航桥逻辑在 `iframe.tsx`) */
+export interface NavbarProps {
+ onRemoteChange: (url: string, tint: string | null) => void
+ /** iframe 回报的 dsh 侧边栏折叠状态(导航桥逻辑在 `iframe.tsx`) */
sidebarCollapsed?: boolean
/** 切换 iframe 内 dsh 侧边栏(向 iframe 发 `dsh://sidebar:toggle`);传入时启用左侧导航控制 */
onToggleSidebar?: () => void
@@ -226,7 +227,7 @@ export interface NavbarProps { /** iframe 回报的 dsh 侧边栏折叠状态(
onOpenShortcuts?: () => void
}
-export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onOpenMachineManager, onOpenSyncToRemote }: NavbarProps) {
+export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onOpenMachineManager, onOpenSyncToRemote }: NavbarProps) {
const { t } = useTranslation()
const isFullscreen = useMacOSFullscreen()
const isMaximized = useMaximized()
@@ -460,9 +461,6 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o
/>
</Button>
</If>
- <If cond={onToggleSidebar != null}>
- <ConnectDialog />
- </If>
<If cond={!IS_MACOS}>
<div className="ml-1">
{/* 文件:新建窗口 / 新聊天 / 打开文件夹 / 关闭 / 退出。
@@ -693,9 +691,7 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o
{/* 「本地」/ 远端机器切换器:SSH 功能启用后才出现(未启用时组件自身不渲染),
位置固定在「更新可用」右侧,与左侧的文件/运行/帮助菜单分列两端。 */}
- <If cond={onToggleSidebar != null}>
- <RemoteSwitcher onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} />
- </If>
+ <RemoteSwitcher onChange={onRemoteChange} visible={onToggleSidebar != null} onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} />
<If cond={!IS_MACOS}>
<Button
diff --git a/src/layout/components/remote-switcher.test.tsx b/src/layout/components/remote-switcher.test.tsx
index c13a4e07..2ae06e56 100644
--- a/src/layout/components/remote-switcher.test.tsx
+++ b/src/layout/components/remote-switcher.test.tsx
@@ -1,11 +1,12 @@
// @vitest-environment jsdom
-import type { SshMachineRow } from '@/store/modules/remote'
-import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import type { ComponentProps } from 'react'
+import type { SshMachineRow } from '@/hooks/use-remote'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { bindSshApiForTests, disposeRemoteForTests, remote } from '@/store/modules/remote'
+import { queryKeys } from '@/config/query-keys'
import { RemoteSwitcher } from './remote-switcher'
-// jsdom 未实现 CSS.escape(react-aria 可选集合的焦点定位依赖);按 CSS 规范转义特殊字符
if (typeof globalThis.CSS === 'undefined') {
Object.assign(globalThis, {
CSS: {
@@ -14,151 +15,181 @@ if (typeof globalThis.CSS === 'undefined') {
})
}
-// i18n 直通(key 即文案);toast 捕获调用参数
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({ t: (key: string, params?: Record<string, unknown>) => params?.name !== undefined ? `${key}:${String(params.name)}` : key }),
}))
const toastSpy = vi.fn()
const manageSpy = vi.fn()
-const invokeSpy = vi.fn(async (..._args: unknown[]) => undefined)
+const changeSpy = vi.fn<(url: string, tint: string | null) => void>()
+const { windowInfo } = vi.hoisted(() => ({ windowInfo: { label: 'main' } }))
+const invokeSpy = vi.fn<(command: string, args?: { method?: string, payload?: unknown, machineId?: string, url?: string }) => Promise<unknown>>()
vi.mock('@/utils/toast', () => ({
toast: (...args: unknown[]) => { toastSpy(...args) },
}))
vi.mock('@tauri-apps/api/core', () => ({
- invoke: (...args: unknown[]) => invokeSpy(...args),
+ invoke: (...args: Parameters<typeof invokeSpy>) => invokeSpy(...args),
}))
+vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => windowInfo }))
function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
}
-/** 本轮引擎返回的机器列表(boot 的首次 refresh 会异步覆写 store,须同源)。 */
-let engineMachines: SshMachineRow[] = []
-/** 本轮引擎回报的 SSH 开关(false = 插件未启用,壳层不渲染控件)。 */
-let engineEnabled = true
-/** 是否模拟本地实例不可达(/api-ssh 抛错 → 降级态)。 */
-let engineUnreachable = false
-
-let disconnectSpy = vi.fn(async () => undefined)
-
-function bindEngine() {
- disconnectSpy = vi.fn(async () => undefined)
- bindSshApiForTests({
- listMachines: vi.fn(async () => {
- if (engineUnreachable)
- throw new TypeError('fetch failed')
- return { enabled: engineEnabled, machines: engineMachines }
- }),
- connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
- disconnect: disconnectSpy,
- })
+let queryClient: QueryClient
+let engineMachines: SshMachineRow[]
+let engineEnabled: boolean
+let engineUnreachable: boolean
+let eventItems: { seq: number, line: string }[]
+
+function switcherElement(props: Partial<ComponentProps<typeof RemoteSwitcher>> = {}) {
+ return (
+ <QueryClientProvider client={queryClient}>
+ <RemoteSwitcher onChange={changeSpy} onManage={manageSpy} {...props} />
+ </QueryClientProvider>
+ )
+}
+
+function renderSwitcher(props: Partial<ComponentProps<typeof RemoteSwitcher>> = {}) {
+ return render(switcherElement(props))
}
-/** 打开下拉并等待菜单出现在 portal 中。 */
async function openMenu() {
- fireEvent.click(screen.getByRole('button', { name: 'remote.switcher' }))
- await waitFor(() => {
- expect(screen.getByRole('menu')).toBeTruthy()
+ fireEvent.click(await screen.findByRole('button', { name: 'remote.switcher' }))
+ return screen.findByRole('menu')
+}
+
+async function selectMachine(name: string) {
+ const menu = await openMenu()
+ fireEvent.click(within(menu).getByText(name))
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
+}
+
+async function refreshMachines() {
+ await act(async () => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.remoteMachines })
})
- return screen.getByRole('menu')
}
-/** 设定机器列表(store 与 mock 引擎同源,避免 boot 首刷覆写)。 */
-function seedMachines(machines: SshMachineRow[]) {
- engineMachines = machines
- engineEnabled = true
- remote.enabled = true
- remote.machines = machines
+function requests(method: string) {
+ return invokeSpy.mock.calls.filter(([command, args]) => command === 'remote' && args?.method === method)
}
beforeEach(() => {
- disposeRemoteForTests()
+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })
toastSpy.mockClear()
manageSpy.mockClear()
- invokeSpy.mockClear()
+ changeSpy.mockClear()
+ invokeSpy.mockReset()
+ windowInfo.label = 'main'
engineMachines = []
engineEnabled = true
engineUnreachable = false
- bindEngine()
+ eventItems = []
+ invokeSpy.mockImplementation(async (command, args) => {
+ if (command === 'remote_open_window')
+ return undefined
+ if (command !== 'remote')
+ throw new Error(`Unexpected native command: ${command}`)
+ switch (args?.method) {
+ case 'GET /api/desktop/dsh-tauri-ssh/machines':
+ if (engineUnreachable)
+ throw new TypeError('fetch failed')
+ return { enabled: engineEnabled, items: engineMachines, discovered: [] }
+ case 'GET /api/desktop/dsh-tauri-ssh/machines/events': {
+ const { sinceSeq } = args.payload as { sinceSeq: number }
+ return { items: eventItems.filter(item => item.seq >= sinceSeq) }
+ }
+ case 'POST /api/desktop/dsh-tauri-ssh/machines/connect': {
+ const { machineId } = args.payload as { machineId: string }
+ engineMachines = engineMachines.map(machine => machine.id === machineId ? { ...machine, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' } : machine)
+ return { tunnelBaseUrl: 'http://127.0.0.1:4001' }
+ }
+ case 'POST /api/desktop/dsh-tauri-ssh/machines/disconnect': {
+ const { machineId } = args.payload as { machineId: string }
+ engineMachines = engineMachines.map(machine => machine.id === machineId ? { ...machine, state: 'disconnected', tunnelBaseUrl: undefined } : machine)
+ return {}
+ }
+ default:
+ throw new Error(`Unexpected remote request: ${args?.method}`)
+ }
+ })
})
afterEach(() => {
cleanup()
- disposeRemoteForTests()
+ queryClient.clear()
+ vi.useRealTimers()
vi.restoreAllMocks()
})
describe('remoteSwitcher 渲染', () => {
it('空态:本地项 + 空态引导 + 管理入口(打开壳层管理面板)', async () => {
- render(<RemoteSwitcher onManage={manageSpy} />)
- await openMenu()
- const menu = screen.getByRole('menu')
+ renderSwitcher()
+ const menu = await openMenu()
expect(within(menu).getByText('remote.local')).toBeTruthy()
expect(within(menu).getByText('remote.empty')).toBeTruthy()
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
fireEvent.click(within(menu).getByText('remote.manage'))
- await waitFor(() => {
- expect(manageSpy).toHaveBeenCalled()
- })
+ await waitFor(() => expect(manageSpy).toHaveBeenCalledOnce())
})
it('操作区:管理机器与同步到远端同级且各自回调;缺回调时双双置灰', async () => {
const syncSpy = vi.fn()
- const { unmount } = render(<RemoteSwitcher onManage={manageSpy} onSync={syncSpy} />)
+ const { unmount } = renderSwitcher({ onSync: syncSpy })
const menu = await openMenu()
- fireEvent.click(within(menu).getByText('remote.sync'))
- await waitFor(() => {
- expect(syncSpy).toHaveBeenCalled()
- })
expect(within(menu).getByText('remote.manage')).toBeTruthy()
+ fireEvent.click(within(menu).getByText('remote.sync'))
+ await waitFor(() => expect(syncSpy).toHaveBeenCalledOnce())
+ expect(manageSpy).not.toHaveBeenCalled()
+ fireEvent.click(within(await openMenu()).getByText('remote.manage'))
+ await waitFor(() => expect(manageSpy).toHaveBeenCalledOnce())
+ expect(syncSpy).toHaveBeenCalledOnce()
unmount()
- render(<RemoteSwitcher />)
+ renderSwitcher({ onManage: undefined })
const bare = await openMenu()
expect(within(bare).getByText('remote.manage').closest('[role="menuitem"]')?.getAttribute('aria-disabled')).toBe('true')
expect(within(bare).getByText('remote.sync').closest('[role="menuitem"]')?.getAttribute('aria-disabled')).toBe('true')
})
it('机器项:状态点语义(标识色优先内联 / 已连接绿 / 重连琥珀 / 放弃红)与状态文案', async () => {
- seedMachines([
+ engineMachines = [
machineOf({ id: 'colored', name: 'colored', color: '#ff00ff', state: 'reconnecting' }),
machineOf({ id: 'green', name: 'green', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }),
machineOf({ id: 'amber', name: 'amber', state: 'connecting' }),
machineOf({ id: 'red', name: 'red', state: 'given-up', lastError: 'connect failed after 3 attempt(s): refused' }),
- ])
- render(<RemoteSwitcher onManage={manageSpy} />)
- await openMenu()
+ ]
+ renderSwitcher()
+ const menu = await openMenu()
- const colored = screen.getByText('colored').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
+ const colored = within(menu).getByText('colored').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
expect(colored?.getAttribute('style')).toContain('rgb(255, 0, 255)')
- const green = screen.getByText('green').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
+ const green = within(menu).getByText('green').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
expect(green?.className).toContain('bg-success')
- expect(screen.getByText('remote.state.connected')).toBeTruthy()
+ expect(green?.getAttribute('style')).toBeNull()
+ expect(within(menu).getByText('remote.state.connected')).toBeTruthy()
- const amber = screen.getByText('amber').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
+ const amber = within(menu).getByText('amber').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
expect(amber?.className).toContain('bg-warning')
- const red = screen.getByText('red').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
+ const red = within(menu).getByText('red').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
expect(red?.className).toContain('bg-danger')
- // 放弃态的原因入口(title 提示)
- expect(screen.getByText('red').closest('[title]')?.getAttribute('title')).toContain('refused')
+ expect(within(menu).getByText('red').closest('[title]')?.getAttribute('title')).toContain('refused')
})
it('触发按钮显示活动机器名与标识色点;无活动时显示本地', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', color: '#123456', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
- remote.activeId = 'm1'
- remote.activeTunnelUrl = 'http://127.0.0.1:4001'
- const { unmount } = render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', color: '#123456', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ renderSwitcher()
+ await selectMachine('alpha')
const trigger = screen.getByRole('button', { name: 'remote.switcher' })
expect(trigger.textContent).toContain('alpha')
- // jsdom 将内联色归一为 rgb()(#123456 → rgb(18, 52, 86))
expect(trigger.querySelector('span[class*="rounded-full"]')?.getAttribute('style')).toContain('rgb(18, 52, 86)')
- unmount()
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', null)
- remote.activeId = null
- remote.activeTunnelUrl = ''
- render(<RemoteSwitcher onManage={manageSpy} />)
+ fireEvent.click(within(await openMenu()).getByText('remote.local'))
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('', null))
expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
})
})
@@ -166,105 +197,187 @@ describe('remoteSwitcher 渲染', () => {
describe('remoteSwitcher 交互与降级', () => {
it('未启用(或插件未加载)时壳层不渲染「本地」控件;启用后随下一轮轮询出现', async () => {
engineEnabled = false
- remote.enabled = false
- render(<RemoteSwitcher onManage={manageSpy} />)
- // boot 首刷回报未启用:整枚控件缺席(不是禁用的死按钮)
- await vi.waitFor(() => {
- expect(remote.available).toBe(true)
+ renderSwitcher()
+ await waitFor(() => {
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'GET /api/desktop/dsh-tauri-ssh/machines', payload: null })
+ expect(queryClient.getQueryState(queryKeys.remoteMachines)?.status).toBe('success')
+ expect(queryClient.getQueryState(queryKeys.remoteMachines)?.fetchStatus).toBe('idle')
})
expect(screen.queryByRole('button', { name: 'remote.switcher' })).toBeNull()
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
- // 用户在设置页启用后:聚焦触发的即时刷新让控件出现
engineEnabled = true
- window.dispatchEvent(new Event('focus'))
- await vi.waitFor(() => {
- expect(screen.getByRole('button', { name: 'remote.switcher' })).toBeTruthy()
- })
+ fireEvent(window, new Event('focus'))
+ expect(await screen.findByRole('button', { name: 'remote.switcher' })).toBeTruthy()
})
it('点击已连接机器项:切换视图(activeId/隧道 URL)', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', color: '#123456', tintBorder: true, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ renderSwitcher()
+ await selectMachine('alpha')
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', '#123456'))
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('alpha')
+ expect(screen.queryByRole('dialog')).toBeNull()
const menu = await openMenu()
- fireEvent.click(within(menu).getByText('alpha'))
- await waitFor(() => {
- expect(remote.activeId).toBe('m1')
- expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001')
- })
+ expect(within(menu).getByText('alpha').closest('[role="menuitem"]')?.textContent).toContain('remote.state.connected')
+ expect(within(menu).getByText('remote.disconnect_active')).toBeTruthy()
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/connect')).toHaveLength(0)
})
it('点击本地项:回本地并撤销挂起切换', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connecting' })])
- remote.activeId = 'm1'
- remote.activeTunnelUrl = 'http://127.0.0.1:4001'
- remote.pendingId = 'm1'
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [
+ machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }),
+ machineOf({ id: 'm2', name: 'beta', state: 'connecting', progress: { phase: 'installing' } }),
+ ]
+ renderSwitcher()
+ await selectMachine('alpha')
+ await selectMachine('beta')
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText('remote.connect.title:beta')).toBeTruthy()
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', null)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'buttons.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ fireEvent.click(within(await openMenu()).getByText('remote.local'))
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('', null))
+
+ engineMachines = engineMachines.map(machine => machine.id === 'm2' ? { ...machine, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002' } : machine)
+ await refreshMachines()
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/disconnect')).toHaveLength(0)
const menu = await openMenu()
- fireEvent.click(within(menu).getByText('remote.local'))
- await waitFor(() => {
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
- expect(remote.pendingId).toBeNull()
- })
+ expect(within(menu).getByText('beta').closest('[role="menuitem"]')?.getAttribute('aria-disabled')).not.toBe('true')
+ expect(within(menu).queryByText('remote.disconnect_active')).toBeNull()
})
it('本地实例不可达:降级提示 + 远端项禁用(不弹错误风暴),恢复后自动复原', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ renderSwitcher()
+ await screen.findByRole('button', { name: 'remote.switcher' })
engineUnreachable = true
- render(<RemoteSwitcher onManage={manageSpy} />)
- // boot 首刷即不可达 → 降级
- await vi.waitFor(() => {
- expect(remote.available).toBe(false)
- })
+ await refreshMachines()
const menu = await openMenu()
expect(within(menu).getByText('remote.degraded')).toBeTruthy()
const item = within(menu).getByText('alpha').closest('[role="menuitem"]')
expect(item?.getAttribute('aria-disabled')).toBe('true')
+ fireEvent.click(within(menu).getByText('alpha'))
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/connect')).toHaveLength(0)
- // 轮询恢复(引擎重新可达):窗口聚焦触发的即时刷新让切换器立即复原
engineUnreachable = false
- window.dispatchEvent(new Event('focus'))
- await vi.waitFor(() => {
- expect(remote.available).toBe(true)
- })
- await vi.waitFor(() => {
+ fireEvent(window, new Event('focus'))
+ await waitFor(() => {
expect(screen.queryByText('remote.degraded')).toBeNull()
+ expect(within(menu).getByText('alpha').closest('[role="menuitem"]')?.getAttribute('aria-disabled')).not.toBe('true')
})
+ expect(toastSpy).not.toHaveBeenCalled()
+ })
+
+ it('重连保留活动 URL,标识色与描边开关更新立即回报,禁用插件清空视图', async () => {
+ engineMachines = [machineOf({ name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001', color: '#123456', tintBorder: true })]
+ renderSwitcher()
+ await selectMachine('alpha')
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', '#123456')
+ engineMachines = [machineOf({ name: 'alpha', state: 'reconnecting', color: '#654321', tintBorder: true })]
+ await refreshMachines()
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', '#654321'))
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('alpha')
+ engineMachines = [machineOf({ name: 'alpha', state: 'reconnecting', color: '#654321' })]
+ await refreshMachines()
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', null))
+ engineMachines = [machineOf({ name: 'alpha', state: 'reconnecting', tintBorder: true })]
+ await refreshMachines()
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', null)
+
+ engineEnabled = false
+ await refreshMachines()
+ await waitFor(() => expect(changeSpy).toHaveBeenLastCalledWith('', null))
+ expect(screen.queryByRole('button', { name: 'remote.switcher' })).toBeNull()
+ })
+
+ it('内部连接弹窗呈现阶段与事件日志,取消向引擎断开且不切换视图', async () => {
+ engineMachines = [machineOf({ name: 'alpha', state: 'connecting', progress: { phase: 'installing' } })]
+ eventItems = [{ seq: 0, line: '[installing] download 42%' }]
+ renderSwitcher()
+ await selectMachine('alpha')
+ const dialog = await screen.findByRole('dialog')
+ expect(within(dialog).getByText('remote.connect.title:alpha')).toBeTruthy()
+ expect(within(dialog).getByText('remote.step.installing')).toBeTruthy()
+ expect(await within(dialog).findByText('[installing] download 42%')).toBeTruthy()
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'remote.connect.cancel' }))
+ await waitFor(() => {
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/desktop/dsh-tauri-ssh/machines/disconnect', payload: { machineId: 'm1' } })
+ expect(screen.queryByRole('dialog')).toBeNull()
+ })
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ expect(screen.queryByText('remote.connect.failed_title')).toBeNull()
+ })
+
+ it('隐藏时仍启动远端窗口目标并轮询,显示后保留同一视图,卸载停止请求', async () => {
+ vi.useFakeTimers()
+ windowInfo.label = 'remote-m1'
+ engineMachines = [machineOf({ name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001', color: '#123456', tintBorder: true })]
+ const { rerender, unmount } = renderSwitcher({ visible: false })
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(100)
+ })
+ expect(screen.queryByRole('button', { name: 'remote.switcher' })).toBeNull()
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4001', '#123456')
+ expect(requests('GET /api/desktop/dsh-tauri-ssh/machines')).toHaveLength(1)
+
+ engineMachines = [machineOf({ name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', color: '#654321', tintBorder: true })]
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2000)
+ })
+ expect(requests('GET /api/desktop/dsh-tauri-ssh/machines')).toHaveLength(2)
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4002', '#654321')
+ rerender(switcherElement())
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('alpha')
+ expect(changeSpy).toHaveBeenLastCalledWith('http://127.0.0.1:4002', '#654321')
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/connect')).toHaveLength(0)
+ unmount()
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(4000)
+ })
+ expect(requests('GET /api/desktop/dsh-tauri-ssh/machines')).toHaveLength(2)
})
})
describe('remoteSwitcher 增强(4.4)', () => {
it('活动机器:状态点强制绿色 + 底部「断开当前连接」一键断开并回本地', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
- remote.activeId = 'm1'
- remote.activeTunnelUrl = 'http://127.0.0.1:4001'
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', color: '#ff00ff', tintBorder: true, state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ renderSwitcher()
+ await selectMachine('alpha')
const menu = await openMenu()
-
const dot = within(menu).getByText('alpha').closest('[role="menuitem"]')?.querySelector('[class*="rounded-full"]')
expect(dot?.className).toContain('bg-success')
+ expect(dot?.getAttribute('style')).toBeNull()
fireEvent.click(within(menu).getByText('remote.disconnect_active'))
await waitFor(() => {
- expect(disconnectSpy).toHaveBeenCalledWith('m1')
+ expect(invokeSpy).toHaveBeenCalledWith('remote', { method: 'POST /api/desktop/dsh-tauri-ssh/machines/disconnect', payload: { machineId: 'm1' } })
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
})
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
})
it('无活动机器时不出现断开项', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
+ renderSwitcher()
const menu = await openMenu()
expect(within(menu).queryByText('remote.disconnect_active')).toBeNull()
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
})
it('重连机器显示重试倒计时;已知凭据类型缀在状态后', async () => {
- seedMachines([
+ engineMachines = [
machineOf({ id: 'm1', name: 'alpha', state: 'reconnecting', nextRetryAt: Date.now() + 42_000 }),
machineOf({ id: 'm2', name: 'beta', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', authMethod: 'key' }),
- ])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ ]
+ renderSwitcher()
const menu = await openMenu()
const alpha = within(menu).getByText('alpha').closest('[role="menuitem"]')
expect(alpha?.textContent).toContain('remote.retry_in')
@@ -275,39 +388,42 @@ describe('remoteSwitcher 增强(4.4)', () => {
describe('remoteSwitcher 行内双动作(当前窗口 vs 新窗口)', () => {
it('新窗口按钮常驻所有机器行:点击只发 remote_open_window,不触发切换', async () => {
- seedMachines([
+ engineMachines = [
machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }),
machineOf({ id: 'm2', name: 'beta', state: 'disconnected' }),
- ])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ ]
+ renderSwitcher()
const menu = await openMenu()
- // 已连接与未连接行都有按钮(未连接开窗后由新窗口内壳层发起连接)
const buttons = within(menu).getAllByRole('button', { name: 'remote.open_new_window' })
- expect(buttons.length).toBe(2)
+ expect(buttons).toHaveLength(2)
fireEvent.click(buttons[0]!)
- await waitFor(() => {
- expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm1', url: 'http://127.0.0.1:4001' })
- })
- // 行本体语义未被连带触发:视图仍是本地
- expect(remote.activeId).toBeNull()
- expect(remote.pendingId).toBeNull()
+ await waitFor(() => expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm1', url: 'http://127.0.0.1:4001' }))
+ expect(within(menu).queryByText('remote.disconnect_active')).toBeNull()
+ fireEvent.keyDown(menu, { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/connect')).toHaveLength(0)
})
it('未连接机器的新窗口按钮:url 置空(窗口内启动连接流程)', async () => {
- seedMachines([machineOf({ id: 'm2', name: 'beta', state: 'disconnected' })])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm2', name: 'beta', state: 'disconnected' })]
+ renderSwitcher()
const menu = await openMenu()
- const button = within(menu).getByRole('button', { name: 'remote.open_new_window' })
- fireEvent.click(button)
- await waitFor(() => {
- expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm2', url: '' })
- })
- expect(remote.activeId).toBeNull()
+ fireEvent.click(within(menu).getByRole('button', { name: 'remote.open_new_window' }))
+ await waitFor(() => expect(invokeSpy).toHaveBeenCalledWith('remote_open_window', { machineId: 'm2', url: '' }))
+ fireEvent.keyDown(menu, { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull())
+ expect(changeSpy).toHaveBeenLastCalledWith('', null)
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
+ expect(screen.queryByRole('dialog')).toBeNull()
+ expect(requests('POST /api/desktop/dsh-tauri-ssh/machines/connect')).toHaveLength(0)
})
it('机器行显示 user@host:port 副标题', async () => {
- seedMachines([machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root', state: 'disconnected' })])
- render(<RemoteSwitcher onManage={manageSpy} />)
+ engineMachines = [machineOf({ id: 'm1', name: 'alpha', host: '10.1.1.1', port: 22, user: 'root', state: 'disconnected' })]
+ renderSwitcher()
const menu = await openMenu()
expect(within(menu).getByText('[email protected]:22')).toBeTruthy()
})
diff --git a/src/layout/components/remote-switcher.tsx b/src/layout/components/remote-switcher.tsx
index 66540fdd..58f5e0d6 100644
--- a/src/layout/components/remote-switcher.tsx
+++ b/src/layout/components/remote-switcher.tsx
@@ -1,15 +1,13 @@
-import type { SshMachineRow } from '@/store/modules/remote'
import { ArrowUpRightFromSquare, ArrowUpToLine, Gear, House, Power, Server } from '@gravity-ui/icons'
import { Button, Description, Dropdown, Label } from '@heroui/react'
+import { useWatch } from '@reause/core'
import { invoke } from '@tauri-apps/api/core'
import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { cn } from 'tailwind-variants'
-import { useStore } from 'valtio-define'
-import { useRemoteMachines } from '@/hooks/use-remote-machines'
-import { store } from '@/store'
-import { dotClassOf, dotStyleOf } from '@/store/modules/remote'
+import { dotClassOf, useRemote } from '@/hooks/use-remote'
import { toast } from '@/utils/toast'
+import { ConnectDialog } from './connect-dialog'
/** 机器行的状态描述:pending 立即「连接中」;重连带倒计时;已知凭据类型缀后。 */
function stateTextOf(
@@ -29,207 +27,186 @@ function stateTextOf(
return text
}
-/** 行内副标题:`user@host:port`(信息不全时退化为已有字段)。 */
-function subtitleOf(machine: SshMachineRow): string | undefined {
- if (machine.host === undefined)
- return undefined
- const target = `${machine.user !== undefined ? `${machine.user}@` : ''}${machine.host}${machine.port !== undefined ? `:${machine.port}` : ''}`
- return target
-}
-
-/**
- * 新窗口打开远端(复用壳层 remote_open_window 命令;聚焦已有窗口)。
- * 未连接机器也可开窗(url 置空):新窗口内壳层启动即发起标准连接流程。
- */
-function openInNewWindow(machine: SshMachineRow, onError: (err: unknown) => void): void {
- invoke('remote_open_window', { machineId: machine.id, url: machine.tunnelBaseUrl ?? '' })
- .catch(onError)
-}
-
-/**
- * 导航栏远端机器切换器:本地实例 ↔ 各远端机器。
- *
- * 数据面全部来自本地实例 `/api-ssh`(`useRemoteMachines` 启动秒级轮询 +
- * 聚焦刷新);点击机器行=当前窗口切换(未连接则发起连接,进度弹窗实时
- * 呈现),行尾图标=新窗口打开(已连接机器可用)。操作区两项同级:底部
- * 「管理机器…」与「同步到远端…」,各自直达 SSH 设置浮层的对应标签页。
- *
- * SSH 未启用(插件开关关闭,或本地实例没有该 API)时不渲染任何控件——「本地」
- * 这一项本身就是 SSH 功能的一部分;轮询照常进行,启用后下一轮即出现。
- *
- * 色点语义(S3 词汇表):机器标识色优先 → 已连接绿 → 重连/进行中琥珀 →
- * 放弃红 → 其余中性灰;未连接行整体降不透明度。本地实例不可达时进入降级
- * 态:远端项禁用 + 顶部提示,恢复后自动复原(轮询静默重试,不弹错误)。
- */
-export function RemoteSwitcher({ onManage, onSync }: { onManage?: () => void, onSync?: () => void }) {
+export function RemoteSwitcher({ onChange, visible = true, onManage, onSync }: {
+ onChange: (url: string, tint: string | null) => void
+ visible?: boolean
+ onManage?: () => void
+ onSync?: () => void
+}) {
const { t } = useTranslation()
- useRemoteMachines()
- const { machines, activeId, available, enabled, pendingId } = useStore(store.remote)
+ const remote = useRemote()
+ const { machines, activeId, activeTunnelUrl, available, enabled, pendingId } = remote
const activeMachine = machines.find(machine => machine.id === activeId)
const activeColor = activeMachine?.color
+ const tint = activeTunnelUrl !== '' && activeMachine?.tintBorder ? activeColor ?? null : null
+ useWatch([activeTunnelUrl, tint], () => onChange(activeTunnelUrl, tint), { immediate: true })
function handleOpenWindowError(err: unknown) {
toast(t('remote.open_window_failed'), {})
console.warn('[remote] open window failed:', err)
}
- if (!enabled)
+ if (!visible || !enabled)
return null
return (
- <Dropdown>
- <Button
- className="rounded-lg h-7 text-[12.5px] px-1.5 ml-1 gap-1.5"
- size="sm"
- variant="ghost"
- aria-label={t('remote.switcher')}
- >
- <Server className={cn(!available && 'text-warning')} />
- <span className="max-w-28 truncate">{activeMachine ? activeMachine.name : t('remote.local')}</span>
- <If cond={activeColor !== undefined}>
- <span
- aria-hidden="true"
- className="size-1.5 rounded-full"
- style={activeColor !== undefined ? { backgroundColor: activeColor } : undefined}
- />
- </If>
- </Button>
- <Dropdown.Popover className="rounded-lg w-72!">
- <Dropdown.Menu>
- <If cond={!available}>
- <Dropdown.Item className="rounded-md" id="remote-degraded" isDisabled textValue={t('remote.degraded')}>
- <Description className="text-warning">{t('remote.degraded')}</Description>
- </Dropdown.Item>
+ <>
+ <ConnectDialog remote={remote} />
+ <Dropdown>
+ <Button
+ className="rounded-lg h-7 text-[12.5px] px-1.5 ml-1 gap-1.5"
+ size="sm"
+ variant="ghost"
+ aria-label={t('remote.switcher')}
+ >
+ <Server className={cn(!available && 'text-warning')} />
+ <span className="max-w-28 truncate">{activeMachine ? activeMachine.name : t('remote.local')}</span>
+ <If cond={activeColor !== undefined}>
+ <span
+ aria-hidden="true"
+ className="size-1.5 rounded-full"
+ style={activeColor !== undefined ? { backgroundColor: activeColor } : undefined}
+ />
</If>
- <Dropdown.Section aria-label={t('remote.section_local')}>
- <Dropdown.Item
- className="rounded-md"
- id="remote-local"
- textValue={t('remote.local')}
- onAction={() => { store.remote.backToLocal() }}
- >
- <span className="flex w-full items-center gap-2">
- <span
- aria-hidden="true"
- className={cn('size-1.5 rounded-full', activeMachine === undefined ? 'bg-success' : 'bg-line-strong')}
- />
- <House className="size-3.5 text-muted" />
- <Label>{t('remote.local')}</Label>
- <If cond={activeId === null}>
- <Description className="ml-auto">{t('remote.current')}</Description>
- </If>
- </span>
- </Dropdown.Item>
- </Dropdown.Section>
- <Dropdown.Section aria-label={t('remote.section_machines')}>
- <If cond={machines.length === 0}>
- <Dropdown.Item className="rounded-md" id="remote-empty" isDisabled textValue={t('remote.empty')}>
- <Description>{t('remote.empty')}</Description>
+ </Button>
+ <Dropdown.Popover className="rounded-lg w-72!">
+ <Dropdown.Menu>
+ <If cond={!available}>
+ <Dropdown.Item className="rounded-md" id="remote-degraded" isDisabled textValue={t('remote.degraded')}>
+ <Description className="text-warning">{t('remote.degraded')}</Description>
</Dropdown.Item>
</If>
- {machines.map((machine) => {
- const pending = pendingId === machine.id
- const connected = machine.state === 'connected' && machine.tunnelBaseUrl !== undefined
- return (
- <Dropdown.Item
- key={machine.id}
- className="rounded-md"
- id={`remote-${machine.id}`}
- textValue={machine.name}
- isDisabled={!available || pendingId !== null}
- onAction={() => { store.remote.switchTo(machine.id) }}
- >
+ <Dropdown.Section aria-label={t('remote.section_local')}>
+ <Dropdown.Item
+ className="rounded-md"
+ id="remote-local"
+ textValue={t('remote.local')}
+ onAction={() => { remote.backToLocal() }}
+ >
+ <span className="flex w-full items-center gap-2">
<span
- title={machine.lastError}
- className={cn(
- 'flex w-full items-center gap-2',
- connected ? '' : 'opacity-60',
- )}
+ aria-hidden="true"
+ className={cn('size-1.5 rounded-full', activeMachine === undefined ? 'bg-success' : 'bg-line-strong')}
+ />
+ <House className="size-3.5 text-muted" />
+ <Label>{t('remote.local')}</Label>
+ <If cond={activeId === null}>
+ <Description className="ml-auto">{t('remote.current')}</Description>
+ </If>
+ </span>
+ </Dropdown.Item>
+ </Dropdown.Section>
+ <Dropdown.Section aria-label={t('remote.section_machines')}>
+ <If cond={machines.length === 0}>
+ <Dropdown.Item className="rounded-md" id="remote-empty" isDisabled textValue={t('remote.empty')}>
+ <Description>{t('remote.empty')}</Description>
+ </Dropdown.Item>
+ </If>
+ {machines.map((machine) => {
+ const pending = pendingId === machine.id
+ const connected = machine.state === 'connected' && machine.tunnelBaseUrl !== undefined
+ const subtitle = machine.host === undefined ? undefined : `${machine.user !== undefined ? `${machine.user}@` : ''}${machine.host}${machine.port !== undefined ? `:${machine.port}` : ''}`
+ return (
+ <Dropdown.Item
+ key={machine.id}
+ className="rounded-md"
+ id={`remote-${machine.id}`}
+ textValue={machine.name}
+ isDisabled={!available || pendingId !== null}
+ onAction={() => { remote.switchTo(machine.id) }}
>
<span
- aria-hidden="true"
- className={cn('size-1.5 shrink-0 rounded-full', machine.id === activeId ? 'bg-success' : dotClassOf(machine))}
- style={machine.id === activeId ? undefined : dotStyleOf(machine)}
- />
- <span className="flex min-w-0 flex-col">
- <Label className="truncate">{machine.name}</Label>
- <If cond={subtitleOf(machine) !== undefined}>
- <Description className="truncate text-[11px] leading-4">{subtitleOf(machine)}</Description>
- </If>
- </span>
- <Description className={cn('ml-auto shrink-0', pending && 'text-warning')}>
- {stateTextOf(machine, pending, t)}
- </Description>
- {/* 行尾双动作:行本体=当前窗口切换;图标=新窗口打开(常驻——
+ title={machine.lastError}
+ className={cn(
+ 'flex w-full items-center gap-2',
+ connected ? '' : 'opacity-60',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn('size-1.5 shrink-0 rounded-full', machine.id === activeId ? 'bg-success' : dotClassOf(machine))}
+ style={machine.id !== activeId && machine.color !== undefined ? { backgroundColor: machine.color } : undefined}
+ />
+ <span className="flex min-w-0 flex-col">
+ <Label className="truncate">{machine.name}</Label>
+ <If cond={subtitle !== undefined}>
+ <Description className="truncate text-[11px] leading-4">{subtitle}</Description>
+ </If>
+ </span>
+ <Description className={cn('ml-auto shrink-0', pending && 'text-warning')}>
+ {stateTextOf(machine, pending, t)}
+ </Description>
+ {/* 行尾双动作:行本体=当前窗口切换;图标=新窗口打开(常驻——
未连接机器开窗后由新窗口内壳层发起连接)。RAC 菜单项的
press 由原生事件冒泡驱动(其 PressEvent 无
stopPropagation),故图标用原生 span + 事件阻断:
点击只发 remote_open_window,本窗口不跟着切换 */}
- <span
- role="button"
- tabIndex={-1}
- aria-label={t('remote.open_new_window')}
- className="inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted hover:bg-panel2 hover:text-ink"
- onPointerDown={e => e.stopPropagation()}
- onPointerUp={e => e.stopPropagation()}
- onClick={(e) => {
- e.stopPropagation()
- openInNewWindow(machine, handleOpenWindowError)
- }}
- >
- <ArrowUpRightFromSquare className="size-3.5" />
+ <span
+ role="button"
+ tabIndex={-1}
+ aria-label={t('remote.open_new_window')}
+ className="inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted hover:bg-panel2 hover:text-ink"
+ onPointerDown={e => e.stopPropagation()}
+ onPointerUp={e => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation()
+ invoke('remote_open_window', { machineId: machine.id, url: machine.tunnelBaseUrl ?? '' }).catch(handleOpenWindowError)
+ }}
+ >
+ <ArrowUpRightFromSquare className="size-3.5" />
+ </span>
</span>
+ </Dropdown.Item>
+ )
+ })}
+ </Dropdown.Section>
+ <Dropdown.Section aria-label={t('remote.section_actions')}>
+ {/* 活动远端连接的一键断开(视图先回本地,再向引擎发断开) */}
+ <If cond={activeId !== null}>
+ <Dropdown.Item
+ className="rounded-md"
+ id="remote-disconnect-active"
+ textValue={t('remote.disconnect_active')}
+ onAction={() => {
+ if (activeId !== null)
+ void remote.disconnect(activeId)
+ }}
+ >
+ <span className="flex w-full items-center gap-2 text-warning">
+ <Power className="size-3.5" />
+ <Label className="text-warning">{t('remote.disconnect_active')}</Label>
</span>
</Dropdown.Item>
- )
- })}
- </Dropdown.Section>
- <Dropdown.Section aria-label={t('remote.section_actions')}>
- {/* 活动远端连接的一键断开(视图先回本地,再向引擎发断开) */}
- <If cond={activeId !== null}>
+ </If>
<Dropdown.Item
className="rounded-md"
- id="remote-disconnect-active"
- textValue={t('remote.disconnect_active')}
- onAction={() => {
- if (activeId !== null)
- void store.remote.disconnect(activeId)
- }}
+ id="remote-manage"
+ isDisabled={onManage == null}
+ textValue={t('remote.manage')}
+ onAction={onManage}
>
- <span className="flex w-full items-center gap-2 text-warning">
- <Power className="size-3.5" />
- <Label className="text-warning">{t('remote.disconnect_active')}</Label>
+ <span className="flex w-full items-center gap-2">
+ <Gear className="size-3.5 text-muted" />
+ <Label>{t('remote.manage')}</Label>
</span>
</Dropdown.Item>
- </If>
- <Dropdown.Item
- className="rounded-md"
- id="remote-manage"
- isDisabled={onManage == null}
- textValue={t('remote.manage')}
- onAction={onManage}
- >
- <span className="flex w-full items-center gap-2">
- <Gear className="size-3.5 text-muted" />
- <Label>{t('remote.manage')}</Label>
- </span>
- </Dropdown.Item>
- <Dropdown.Item
- className="rounded-md"
- id="remote-sync"
- isDisabled={onSync == null}
- textValue={t('remote.sync')}
- onAction={onSync}
- >
- <span className="flex w-full items-center gap-2">
- <ArrowUpToLine className="size-3.5 text-muted" />
- <Label>{t('remote.sync')}</Label>
- </span>
- </Dropdown.Item>
- </Dropdown.Section>
- </Dropdown.Menu>
- </Dropdown.Popover>
- </Dropdown>
+ <Dropdown.Item
+ className="rounded-md"
+ id="remote-sync"
+ isDisabled={onSync == null}
+ textValue={t('remote.sync')}
+ onAction={onSync}
+ >
+ <span className="flex w-full items-center gap-2">
+ <ArrowUpToLine className="size-3.5 text-muted" />
+ <Label>{t('remote.sync')}</Label>
+ </span>
+ </Dropdown.Item>
+ </Dropdown.Section>
+ </Dropdown.Menu>
+ </Dropdown.Popover>
+ </Dropdown>
+ </>
)
}
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index 17294449..5de2fb31 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -7,7 +7,6 @@ import { useDshStyle } from '@/hooks/use-dsh-style'
import { useIframeMessage } from '@/hooks/use-iframe-message'
import { useIframePost } from '@/hooks/use-iframe-post'
import { store } from '@/store'
-import { borderTintOf } from '@/store/modules/remote'
import { Recovery } from '@/ui/plugin/recovery'
import { Iframe } from './iframe'
import { Navbar } from './navbar'
@@ -41,11 +40,12 @@ export function Webview() {
const { status, serviceHealthy } = useStore(store.harness)
const { recovery } = useStore(store.recovery)
- const { machines, activeId, activeTunnelUrl } = useStore(store.remote)
- // 远端模式:活动机器的隧道 URL 就绪才切换(不指向空端口);重连窗口内
- // store 粘性保留上一次 URL,等待引擎按端口稳定策略恢复
+ const [{ url: activeTunnelUrl, tint: borderTint }, setRemoteView] = useState({ url: '', tint: null as string | null })
const remoteMode = activeTunnelUrl !== ''
- const borderTint = remoteMode ? borderTintOf(machines.find(machine => machine.id === activeId)) : null
+
+ function handleRemoteChange(url: string, tint: string | null) {
+ setRemoteView({ url, tint })
+ }
// 2. Iframe 消息通信监听
useIframeMessage<NavBridgeMessage>(iframeRef, (data) => {
@@ -98,7 +98,7 @@ export function Webview() {
// 5. 统一布局输出
return (
<main className="relative flex flex-col min-h-0 flex-1" style={dshStyle.frame || {}}>
- <Navbar sidebarCollapsed={sidebarCollapsed} {...bridge} />
+ <Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />
<div className="flex min-h-0 flex-1">
{renderContent()}
</div>
diff --git a/src/store/index.ts b/src/store/index.ts
index 6246f524..65a3caee 100644
--- a/src/store/index.ts
+++ b/src/store/index.ts
@@ -4,7 +4,6 @@ import { harnessUpdater } from './modules/harness-updater'
import { plugins } from './modules/plugins'
import { preinstall } from './modules/preinstall'
import { recovery } from './modules/recovery'
-import { remote } from './modules/remote'
import { setting } from './modules/setting'
/**
@@ -26,5 +25,4 @@ export const store = {
recovery,
setting,
desktopUpdater,
- remote,
}
diff --git a/src/store/modules/remote/api.test.ts b/src/store/modules/remote/api.test.ts
deleted file mode 100644
index 6f2d4034..00000000
--- a/src/store/modules/remote/api.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import type { SshFetchFn } from './api'
-import type { SshMachineListValue } from './types'
-import { describe, expect, it, vi } from 'vitest'
-import { createSshApiClient } from './api'
-
-/** 组一个返回固定信封的 fetch mock。 */
-function fakeFetch(envelope: unknown, status = 200): SshFetchFn {
- return vi.fn(async () => ({ ok: status < 400, status, json: async () => envelope }) as unknown as Response)
-}
-
-const listValue: SshMachineListValue = {
- items: [
- { id: 'b', name: 'beta', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002', color: '#123456', tintBorder: true },
- { id: 'a', name: 'alpha', state: 'disconnected', lastError: 'boom', authMethod: 'key', nextRetryAt: 1725000000000 },
- ],
- discovered: [
- { id: 'alias', name: 'alias-host', state: 'disconnected' },
- ],
-}
-
-describe('createSshApiClient', () => {
- it('listMachines 合并手动机器与别名机器并按名排序,丢掉缺字段的坏行', async () => {
- const fetchFn = fakeFetch({
- ok: true,
- value: {
- enabled: true,
- items: [...listValue.items, { id: '', name: 'bad', state: 'connected' }, { id: 'x' }],
- discovered: listValue.discovered,
- },
- })
- const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
- const { enabled, machines } = await client.listMachines()
- expect(enabled).toBe(true)
- // 按 name 排序:alias-host < alpha < beta
- expect(machines.map(row => row.id)).toEqual(['alias', 'a', 'b'])
- expect(machines[2]).toMatchObject({ color: '#123456', tintBorder: true, tunnelBaseUrl: 'http://127.0.0.1:4002' })
- // 增量投影:authMethod 与 nextRetryAt 随行透出(切换器倒计时/凭据后缀用)
- expect(machines[1]).toMatchObject({ authMethod: 'key', nextRetryAt: 1725000000000 })
- // 请求形状:POST /api-ssh + machine.list 信封
- expect(fetchFn).toHaveBeenCalledWith(
- 'http://127.0.0.1:3081/api-ssh',
- expect.objectContaining({ method: 'POST', body: JSON.stringify({ method: 'machine.list', payload: {} }) }),
- )
- })
-
- it('未启用时返回空列表与 enabled=false(壳层据此隐藏切换器)', async () => {
- const fetchFn = fakeFetch({ ok: true, value: { enabled: false, items: [], discovered: [] } })
- const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
- await expect(client.listMachines()).resolves.toEqual({ enabled: false, machines: [] })
- })
-
- it('connect 透传 machineId 并返回隧道 URL', async () => {
- const fetchFn = fakeFetch({ ok: true, value: { tunnelBaseUrl: 'http://127.0.0.1:4004' } })
- const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
- await expect(client.connect('m1')).resolves.toEqual({ tunnelBaseUrl: 'http://127.0.0.1:4004' })
- expect(fetchFn).toHaveBeenCalledWith(
- 'http://127.0.0.1:3081/api-ssh',
- expect.objectContaining({ body: JSON.stringify({ method: 'machine.connect', payload: { machineId: 'm1' } }) }),
- )
- })
-
- it('ok:false 信封抛引擎错误消息(供切换器降级/失败呈现)', async () => {
- const client = createSshApiClient(
- fakeFetch({ ok: false, error: { code: 'machine-reconnecting', message: 'machine is reconnecting' } }),
- () => 'http://127.0.0.1:3081',
- )
- await expect(client.connect('m1')).rejects.toThrow('machine is reconnecting')
- })
-
- it('hTTP 非 200、空响应体与网络失败都抛错(本地实例不可达 / 无 SSH API)', async () => {
- const httpError = createSshApiClient(fakeFetch({ ok: true, value: {} }, 503), () => 'http://127.0.0.1:3081')
- await expect(httpError.listMachines()).rejects.toThrow('SSH_API_HTTP_503')
-
- // 405 是「插件未挂载」的实况(内核 fallback 只答状态码、正文为空):
- // 必须是稳定的 HTTP 错误码,而不是原生 JSON 解析异常。
- const routeMissing = createSshApiClient(
- vi.fn(async () => ({ ok: false, status: 405, json: async () => { throw new SyntaxError('Unexpected end of JSON input') } }) as unknown as Response),
- () => 'http://127.0.0.1:3081',
- )
- await expect(routeMissing.listMachines()).rejects.toThrow('SSH_API_HTTP_405')
-
- // 200 但没有可解析正文:同样归到稳定错误码
- const emptyBody = createSshApiClient(
- vi.fn(async () => ({ ok: true, status: 200, json: async () => { throw new SyntaxError('Unexpected end of JSON input') } }) as unknown as Response),
- () => 'http://127.0.0.1:3081',
- )
- await expect(emptyBody.listMachines()).rejects.toThrow('SSH_API_HTTP_200')
-
- const networkError = createSshApiClient(
- vi.fn(async () => { throw new TypeError('fetch failed') }) as unknown as SshFetchFn,
- () => 'http://127.0.0.1:3081',
- )
- await expect(networkError.listMachines()).rejects.toThrow('fetch failed')
- })
-})
diff --git a/src/store/modules/remote/api.ts b/src/store/modules/remote/api.ts
deleted file mode 100644
index 74b531a3..00000000
--- a/src/store/modules/remote/api.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * `/api-ssh` 客户端:壳层与 SSH 引擎(本地实例上的 dsh-tauri-ssh 插件)的
- * 全部数据往来。协议是 S1 契约的最小 JSON 信封(同源 POST、loopback-only):
- *
- * POST /api-ssh { "method": "machine.list", "payload": {} }
- * → 200 { "ok": true, "value": ... } | { "ok": false, "error": {...} }
- *
- * 壳层消费:`machine.list`(轮询)、`machine.connect`/`machine.disconnect`
- * (切换与断开)、`machine.save`/`machine.remove`/`machine.test`(管理面板)、
- * `machine.events`(连接进度弹窗的实时日志)。fetch 与基础 URL 均可注入,
- * 便于单测与复用。
- * @module store/remote/api
- */
-
-import type { SshConnectionState, SshEventEntry, SshMachineListValue, SshMachineProfile, SshMachineRow, SshProgress, SshSecrets } from './types'
-
-/** 一次请求信封。 */
-interface SshApiRequest {
- method: string
- payload?: Record<string, unknown>
-}
-
-/** 一次应答信封。 */
-type SshApiResponse
- = | { ok: true, value: unknown }
- | { ok: false, error: { code: string, message: string } }
-
-/** fetch 函数形状(与全局 fetch 兼容,可注入 mock)。 */
-export type SshFetchFn = (input: string, init?: RequestInit) => Promise<Response>
-
-/**
- * 本地实例答了,但没有 SSH API:插件未加载 / 未启用(404、405 或非 JSON 响应)。
- * 与网络失败区分——前者是「SSH 不可用」,后者才是「本地实例不可达」。
- */
-export class SshApiHttpError extends Error {
- readonly status: number
-
- constructor(status: number) {
- super(`SSH_API_HTTP_${status}`)
- this.status = status
- }
-}
-
-/** `machine.list` 的应答值:SSH 开关 + 机器行。 */
-export interface SshMachineList {
- /** SSH 功能是否已启用;未启用时机器行为空,壳层不渲染切换器。 */
- enabled: boolean
- machines: SshMachineRow[]
-}
-
-/** 本客户端面向壳层暴露的引擎动作。 */
-export interface SshApiClient {
- /** `machine.list`:SSH 开关 + 手动机器与 ~/.ssh/config 别名机器(已按名排序合并)。 */
- listMachines: () => Promise<SshMachineList>
- /** `machine.connect`:阻塞到隧道就绪,返回隧道 URL。 */
- connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>
- /** `machine.disconnect`:主动断开(远端实例保持运行)。 */
- disconnect: (machineId: string) => Promise<void>
- /** `machine.save`:保存(新增/覆盖)手动机器;secrets 仅显式传入时更新。 */
- save: (machine: SshMachineProfile, secrets?: SshSecrets) => Promise<void>
- /** `machine.remove`:删除手动机器。 */
- remove: (machineId: string) => Promise<void>
- /** `machine.test`:快速 SSH 握手探测(不建隧道)。 */
- test: (machineId: string) => Promise<{ ok: boolean, banner?: string }>
- /** `machine.events`:增量事件日志(seq 游标)。 */
- events: (machineId: string, sinceSeq?: number) => Promise<{ items: SshEventEntry[] }>
-}
-
-/** 非法机器行兜底:缺 id/name/state 的行直接丢弃,不让坏数据进切换器。 */
-function machineRowOf(raw: unknown): SshMachineRow | undefined {
- if (typeof raw !== 'object' || raw === null)
- return undefined
- const value = raw as Record<string, unknown>
- if (typeof value.id !== 'string' || value.id === '')
- return undefined
- if (typeof value.name !== 'string' || value.name === '')
- return undefined
- const STATES: SshConnectionState[] = ['disconnected', 'testing', 'connecting', 'connected', 'reconnecting', 'given-up']
- if (!STATES.includes(value.state as SshConnectionState))
- return undefined
- return {
- id: value.id,
- name: value.name,
- ...typeof value.color === 'string' && value.color !== '' ? { color: value.color } : {},
- ...value.tintBorder === true ? { tintBorder: true } : {},
- ...typeof value.host === 'string' && value.host !== '' ? { host: value.host } : {},
- ...typeof value.port === 'number' ? { port: value.port } : {},
- ...typeof value.user === 'string' && value.user !== '' ? { user: value.user } : {},
- ...typeof value.remotePort === 'number' ? { remotePort: value.remotePort } : {},
- ...typeof value.startCommand === 'string' && value.startCommand !== '' ? { startCommand: value.startCommand } : {},
- ...value.hasPassword === true ? { hasPassword: true } : {},
- ...value.hasPassphrase === true ? { hasPassphrase: true } : {},
- state: value.state as SshConnectionState,
- ...typeof value.tunnelBaseUrl === 'string' ? { tunnelBaseUrl: value.tunnelBaseUrl } : {},
- ...typeof value.lastError === 'string' ? { lastError: value.lastError } : {},
- ...typeof value.nextRetryAt === 'number' ? { nextRetryAt: value.nextRetryAt } : {},
- ...value.authMethod === 'agent' || value.authMethod === 'key' || value.authMethod === 'password'
- ? { authMethod: value.authMethod }
- : {},
- ...progressOf(value.progress),
- }
-}
-
-/** progress 投影:phase 合法才保留,附带可选 attempt/total/log。 */
-function progressOf(raw: unknown): { progress?: SshProgress } {
- if (typeof raw !== 'object' || raw === null)
- return {}
- const value = raw as Record<string, unknown>
- const PHASES: SshProgress['phase'][] = ['handshake', 'installing', 'starting', 'probing']
- if (!PHASES.includes(value.phase as SshProgress['phase']))
- return {}
- return {
- progress: {
- phase: value.phase as SshProgress['phase'],
- ...typeof value.attempt === 'number' ? { attempt: value.attempt } : {},
- ...typeof value.total === 'number' ? { total: value.total } : {},
- ...typeof value.log === 'string' ? { log: value.log } : {},
- },
- }
-}
-
-/**
- * 组一个 `/api-ssh` 客户端。
- *
- * @param fetchFn - fetch 实现(默认全局 fetch;测试注入 mock)。
- * @param getBaseUrl - 本地实例基址(默认读 harness store 的 serviceUrl)。
- */
-export function createSshApiClient(
- fetchFn: SshFetchFn,
- getBaseUrl: () => string,
-): SshApiClient {
- async function call<T>(method: string, payload?: Record<string, unknown>): Promise<T> {
- const response = await fetchFn(`${getBaseUrl()}/api-ssh`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ method, payload: payload ?? {} } satisfies SshApiRequest),
- })
- // 非 2xx 与空/非 JSON 响应都不是信封:抛稳定的 HTTP 错误码,避免把
- // `Unexpected end of JSON input` 这类原生解析异常泄漏到界面/降级提示。
- if (!response.ok)
- throw new SshApiHttpError(response.status)
- let envelope: SshApiResponse
- try {
- envelope = await response.json() as SshApiResponse
- }
- catch {
- throw new SshApiHttpError(response.status)
- }
- if (!envelope.ok)
- throw new Error(envelope.error?.message || envelope.error?.code || 'SSH_API_ERROR')
- return envelope.value as T
- }
-
- return {
- async listMachines() {
- const value = await call<SshMachineListValue>('machine.list')
- const items = (value?.items ?? []).map(machineRowOf).filter((row): row is SshMachineRow => row !== undefined)
- const discovered = (value?.discovered ?? []).map(machineRowOf).filter((row): row is SshMachineRow => row !== undefined)
- // 确定性排序(localeCompare 的 ICU 整序在不同环境不稳定)
- const machines = [...items, ...discovered].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
- return { enabled: value?.enabled === true, machines }
- },
- connect: machineId => call<{ tunnelBaseUrl: string }>('machine.connect', { machineId }),
- disconnect: async (machineId) => {
- await call<unknown>('machine.disconnect', { machineId })
- },
- /** 保存(新增/覆盖)一台手动机器;secrets 仅在显式传入时更新。 */
- save: async (machine: SshMachineProfile, secrets?: SshSecrets) => {
- await call<unknown>('machine.save', { machine, secrets })
- },
- remove: async (machineId) => {
- await call<unknown>('machine.remove', { machineId })
- },
- /** 快速 SSH 握手探测(不建隧道);失败时引擎错误消息即原因。 */
- test: machineId => call<{ ok: boolean, banner?: string }>('machine.test', { machineId }),
- /** 增量取事件日志(seq 游标;空数组 = 无新事件)。 */
- events: (machineId, sinceSeq = 0) => call<{ items: SshEventEntry[] }>('machine.events', { machineId, sinceSeq }),
- }
-}
diff --git a/src/store/modules/remote/index.ts b/src/store/modules/remote/index.ts
deleted file mode 100644
index 18dce75c..00000000
--- a/src/store/modules/remote/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export { borderTintOf, dotClassOf, dotStyleOf, reconcileSwitcher } from './logic'
-export { bindSshApiForTests, disposeRemoteForTests, remote, sshApi } from './store'
-export type { SshMachineProfile, SshMachineRow, SshSecrets } from './types'
diff --git a/src/store/modules/remote/logic.ts b/src/store/modules/remote/logic.ts
deleted file mode 100644
index 7b2c7e63..00000000
--- a/src/store/modules/remote/logic.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * 切换器与内容区着色的纯逻辑(无副作用,供 store/组件复用与单测):
- *
- * - 色点语义(S3 词汇表消费):机器标识色优先 → 已连接绿 → 重连中/进行中
- * 琥珀 → 放弃/失败红 → 其余中性灰;
- * - 边框着色:活动机器勾选 tintBorder 且有标识色时返回颜色,否则不描边;
- * - 切换 reconcile:把一份最新机器列表折叠进 { activeId, pendingId,
- * activeTunnelUrl } 三元组——断开/放弃自动回本地、重连窗口粘性保留隧道
- * URL(端口稳定策略见引擎 preferredTunnelPort)、待切换机器就绪即切换。
- * @module store/remote/logic
- */
-
-import type { SshMachineRow } from './types'
-
-/** 切换器的三个视图状态键(reconcile 的输入与输出同形)。 */
-export interface SwitcherTargets {
- activeId: string | null
- pendingId: string | null
- activeTunnelUrl: string
-}
-
-/**
- * 色点 class:标识色走内联样式(见 dotStyleOf),这里只给无标识色时的
- * 语义色。进行中(connecting/testing/reconnecting)统一琥珀。
- */
-export function dotClassOf(machine: Pick<SshMachineRow, 'color' | 'state'>): string {
- if (machine.color !== undefined)
- return ''
- switch (machine.state) {
- case 'connected':
- return 'bg-success'
- case 'reconnecting':
- case 'connecting':
- case 'testing':
- return 'bg-warning'
- case 'given-up':
- return 'bg-danger'
- default:
- return 'bg-line-strong'
- }
-}
-
-/** 色点内联颜色:有标识色时用它(任何状态),否则交给语义 class。 */
-export function dotStyleOf(machine: Pick<SshMachineRow, 'color'>): Record<string, string> | undefined {
- return machine.color !== undefined ? { backgroundColor: machine.color } : undefined
-}
-
-/** 边框着色:活动机器 + tintBorder + 标识色齐备才描边。 */
-export function borderTintOf(machine: SshMachineRow | undefined): string | null {
- if (machine === undefined)
- return null
- if (!machine.tintBorder || machine.color === undefined)
- return null
- return machine.color
-}
-
-/**
- * 用最新机器列表推进切换语义(幂等纯函数)。
- *
- * 规则(S5 契约):
- * - 活动机器行消失 / 被断开(disconnected)/ 放弃(given-up)→ 回本地;
- * - 活动机器重连中(reconnecting 等)→ 保持指向,隧道 URL 粘性保留
- * (不闪空端口,恢复后按引擎的端口稳定策略续用原 URL);
- * - 活动机器已连接 → 采用最新 tunnelBaseUrl(重连换端口时换 iframe 键重载);
- * - 待切换机器就绪 → 升为活动;消失/放弃 → 撤销待切换(留在本地,失败态
- * 由切换器列表呈现)。
- */
-export function reconcileSwitcher(
- prev: SwitcherTargets,
- machines: readonly SshMachineRow[],
-): SwitcherTargets {
- let { activeId, pendingId, activeTunnelUrl } = prev
- const activeMachine = machines.find(machine => machine.id === activeId)
- if (activeMachine === undefined) {
- // 行消失(被删除或引擎重启清空):回本地
- activeId = null
- activeTunnelUrl = ''
- }
- else if (activeMachine.state === 'disconnected' || activeMachine.state === 'given-up') {
- // 断开/放弃:回本地(切换器列表里保留失败态与原因)
- activeId = null
- activeTunnelUrl = ''
- }
- else if (activeMachine.state === 'connected' && activeMachine.tunnelBaseUrl !== undefined) {
- // 就绪:采纳最新隧道 URL(重连后端口变化时 iframe 换键重载)
- activeTunnelUrl = activeMachine.tunnelBaseUrl
- }
- // reconnecting/testing/connecting:保持活动与粘性 URL,等待自动恢复
-
- const pendingMachine = machines.find(machine => machine.id === pendingId)
- if (pendingMachine === undefined || pendingMachine.state === 'given-up') {
- pendingId = null
- }
- else if (pendingMachine.state === 'connected' && pendingMachine.tunnelBaseUrl !== undefined) {
- activeId = pendingMachine.id
- activeTunnelUrl = pendingMachine.tunnelBaseUrl
- pendingId = null
- }
-
- return { activeId, pendingId, activeTunnelUrl }
-}
diff --git a/src/store/modules/remote/store.test.ts b/src/store/modules/remote/store.test.ts
deleted file mode 100644
index 44e8952c..00000000
--- a/src/store/modules/remote/store.test.ts
+++ /dev/null
@@ -1,403 +0,0 @@
-import type { SshMachineList } from './api'
-import type { SshMachineRow } from './types'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { SshApiHttpError } from './api'
-import { bindSshApiForTests, disposeRemoteForTests, remote } from './store'
-
-function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
- return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
-}
-
-/** SSH 已启用的 machine.list 应答。 */
-function listOf(machines: SshMachineRow[]): SshMachineList {
- return { enabled: true, machines }
-}
-
-/** 组一个按调用序返回快照序列的 listMachines mock(末张快照驻留)。 */
-function bindListSequence(list: SshMachineRow[][]) {
- let call = 0
- return vi.fn(async () => {
- const snapshot = list[Math.min(call, list.length - 1)] ?? []
- call += 1
- return listOf(snapshot)
- })
-}
-
-/** 注入可编程 mock 引擎:listMachines 按调用序返回快照序列。 */
-function bindEngine(options: {
- list: SshMachineRow[][]
- connect?: () => Promise<{ tunnelBaseUrl: string }>
-}) {
- let call = 0
- const listMachines = vi.fn(async () => {
- const snapshot = options.list[Math.min(call, options.list.length - 1)] ?? []
- call += 1
- return listOf(snapshot)
- })
- const connect = options.connect ?? (vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })))
- bindSshApiForTests({ listMachines, connect, disconnect: vi.fn(async () => undefined) })
- return { listMachines, connect }
-}
-
-beforeEach(() => {
- disposeRemoteForTests()
-})
-
-afterEach(() => {
- disposeRemoteForTests()
-})
-
-describe('remote store 轮询与降级', () => {
- it('refresh 成功更新机器列表;网络失败进入降级态并保留既有列表,恢复后复原', async () => {
- bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
- await remote.refresh()
- expect(remote.machines.map(m => m.name)).toEqual(['alpha'])
- expect(remote.enabled).toBe(true)
- expect(remote.available).toBe(true)
-
- // 本地实例不可达:fetch 抛错 → 降级但不清空列表(静默,不弹错误)
- bindSshApiForTests({
- listMachines: vi.fn(async () => { throw new TypeError('fetch failed') }),
- connect: vi.fn(async () => { throw new Error('unreachable') }),
- disconnect: vi.fn(async () => undefined),
- })
- await remote.refresh()
- expect(remote.available).toBe(false)
- expect(remote.machines.map(m => m.name)).toEqual(['alpha'])
-
- // 恢复
- bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
- await remote.refresh()
- expect(remote.available).toBe(true)
- })
-
- it('本地实例可达但没有 SSH API(404/405):不算不可达,按未启用处理并清空远端视图', async () => {
- bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
- await remote.refresh()
- remote.activeId = 'm1'
- remote.activeTunnelUrl = 'http://127.0.0.1:4001'
-
- // 插件未加载 / 未启用:内核 fallback 只回 405、正文为空(0.1.7 的实况)
- bindSshApiForTests({
- listMachines: vi.fn(async () => { throw new SshApiHttpError(405) }),
- connect: vi.fn(async () => { throw new Error('unreachable') }),
- disconnect: vi.fn(async () => undefined),
- })
- await remote.refresh()
- expect(remote.available).toBe(true)
- expect(remote.enabled).toBe(false)
- expect(remote.machines).toEqual([])
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
-
- // 用户在设置页启用插件后:下一轮轮询即恢复
- bindEngine({ list: [[machineOf({ id: 'm1', name: 'alpha' })]] })
- await remote.refresh()
- expect(remote.enabled).toBe(true)
- expect(remote.machines.map(m => m.name)).toEqual(['alpha'])
- })
-
- it('未启用(enabled=false)时清空列表且不推进切换', async () => {
- remote.machines = [machineOf({ id: 'm1', name: 'alpha' })]
- remote.activeId = 'm1'
- bindSshApiForTests({
- listMachines: vi.fn(async () => ({ enabled: false, machines: [] })),
- connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
- disconnect: vi.fn(async () => undefined),
- })
- await remote.refresh()
- expect(remote.enabled).toBe(false)
- expect(remote.machines).toEqual([])
- expect(remote.activeId).toBeNull()
- })
-
- it('boot 幂等:只挂一个轮询定时器(fake timers 下按周期节奏发请求)', async () => {
- vi.useFakeTimers()
- try {
- const engine = bindEngine({ list: [[machineOf({ id: 'm1' })]] })
- remote.boot()
- remote.boot()
- const afterBoot = engine.listMachines.mock.calls.length
- await vi.advanceTimersByTimeAsync(6000)
- // 6 秒 = 3 个周期;boot 即时 1 次 + 每周期 1 次(无重复 boot 的翻倍)
- expect(engine.listMachines.mock.calls.length).toBeLessThanOrEqual(afterBoot + 3)
- expect(engine.listMachines.mock.calls.length).toBeGreaterThanOrEqual(afterBoot + 2)
- }
- finally {
- vi.useRealTimers()
- }
- })
-})
-
-describe('remote store 远端弹窗启动寻址', () => {
- it('openInitialMachine:登记挂起并拉一轮,已连接机器直接切换', async () => {
- const engine = bindEngine({ list: [[machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]] })
- expect(remote.machines).toHaveLength(0)
- remote.openInitialMachine('m1')
- expect(remote.pendingBootMachineId).toBe('m1')
- await vi.waitFor(() => expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001'))
- expect(engine.listMachines).toHaveBeenCalled()
- expect(remote.activeId).toBe('m1')
- expect(remote.pendingBootMachineId).toBeNull()
- })
-
- it('openInitialMachine:实例未就绪时不落空——后续成功轮询补切换', async () => {
- // 首轮不可达(新窗口启动时实例健康检查常未就绪),恢复后轮询推进
- bindEngine({ list: [] })
- const engine = bindEngine({ list: [] })
- engine.listMachines.mockRejectedValueOnce(new TypeError('fetch failed'))
- engine.listMachines.mockImplementation(async () =>
- listOf([machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]))
- remote.openInitialMachine('m1')
- await vi.waitFor(() => expect(remote.available).toBe(false))
- expect(remote.activeId).toBeNull()
- await remote.refresh()
- await vi.waitFor(() => expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001'))
- expect(remote.activeId).toBe('m1')
- })
-
- it('openInitialMachine:未连接机器走标准连接流程(进度弹窗照常)', async () => {
- // 状态机式 mock:connect 前 disconnected、后 connected(轮询发现就绪)
- let connected = false
- const engine = bindEngine({
- list: [[]],
- connect: vi.fn(async () => {
- connected = true
- return { tunnelBaseUrl: 'http://127.0.0.1:4001' }
- }),
- })
- engine.listMachines.mockImplementation(async () =>
- listOf([machineOf(connected
- ? { id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' }
- : { id: 'm1', state: 'disconnected' })]))
- remote.openInitialMachine('m1')
- await vi.waitFor(() => expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001'))
- expect(engine.connect).toHaveBeenCalledWith('m1')
- expect(remote.activeId).toBe('m1')
- })
-
- it('openInitialMachine:未知机器静默不切换(label 与列表不符的兜底)', async () => {
- bindEngine({ list: [[]] })
- remote.openInitialMachine('ghost')
- await remote.refresh()
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
- // 挂起目标仍在(机器可能在后续轮询中出现),手动回本地即撤销
- expect(remote.pendingBootMachineId).toBe('ghost')
- remote.backToLocal()
- expect(remote.pendingBootMachineId).toBeNull()
- })
-})
-
-describe('remote store 切换语义', () => {
- it('switchTo 已连接机器:立即切换到隧道 URL', async () => {
- bindEngine({ list: [[machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]] })
- await remote.refresh()
- remote.switchTo('m1')
- expect(remote.activeId).toBe('m1')
- expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001')
- expect(remote.pendingId).toBeNull()
- })
-
- it('switchTo 未连接机器:发起连接,就绪后自动切换(不指向空端口)', async () => {
- // 状态机式 mock:connect 调用前 disconnected,之后 connected 并给出隧道 URL
- let connected = false
- const engine = bindEngine({
- list: [[]],
- connect: vi.fn(async () => {
- connected = true
- return { tunnelBaseUrl: 'http://127.0.0.1:4002' }
- }),
- })
- engine.listMachines.mockImplementation(async () =>
- listOf([machineOf(connected
- ? { id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002' }
- : { id: 'm1', state: 'disconnected' })]))
-
- await remote.refresh()
- remote.switchTo('m1')
- expect(engine.connect).toHaveBeenCalledWith('m1')
- // connectAndSwitch 内部 refresh 驱动 reconcile,就绪后升为活动
- await vi.waitFor(() => {
- expect(remote.activeId).toBe('m1')
- expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4002')
- expect(remote.pendingId).toBeNull()
- })
- })
-
- it('连接失败:撤销待切换留在本地,失败态经 refresh 呈现', async () => {
- bindEngine({
- list: [
- [machineOf({ id: 'm1', state: 'disconnected' })],
- [machineOf({ id: 'm1', state: 'given-up', lastError: 'connect failed after 3 attempt(s): refused' })],
- ],
- connect: vi.fn(async () => { throw new Error('machine is reconnecting') }),
- })
- await remote.refresh()
- remote.switchTo('m1')
- // connect 拒绝后 pending 清空;收尾 refresh 拉到 given-up 状态
- await vi.waitFor(() => {
- expect(remote.pendingId).toBeNull()
- expect(remote.machines[0]?.state).toBe('given-up')
- expect(remote.machines[0]?.lastError).toContain('refused')
- })
- expect(remote.activeId).toBeNull()
- })
-
- it('reconnecting 中点击:不重复 connect,挂起等待自动恢复', async () => {
- const engine = bindEngine({
- list: [
- [machineOf({ id: 'm1', state: 'reconnecting', nextRetryAt: Date.now() + 4000 })],
- [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],
- ],
- })
- await remote.refresh()
- remote.switchTo('m1')
- expect(remote.pendingId).toBe('m1')
- expect(engine.connect).not.toHaveBeenCalled()
- await remote.refresh()
- expect(remote.activeId).toBe('m1')
- expect(remote.activeTunnelUrl).toBe('http://127.0.0.1:4001')
- })
-
- it('活动机器被断开(面板 disconnect):轮询自动回本地', async () => {
- bindEngine({
- list: [
- [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],
- [machineOf({ id: 'm1', state: 'disconnected' })],
- ],
- })
- await remote.refresh()
- remote.switchTo('m1')
- expect(remote.activeId).toBe('m1')
- await remote.refresh()
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
- })
-
- it('backToLocal:回本地并撤销挂起中的切换(不抢切)', async () => {
- bindEngine({
- list: [
- [machineOf({ id: 'm1', state: 'connecting' })],
- [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],
- ],
- })
- await remote.refresh()
- remote.switchTo('m1')
- expect(remote.pendingId).toBe('m1')
- remote.backToLocal()
- expect(remote.activeId).toBeNull()
- expect(remote.pendingId).toBeNull()
- // 用户已选本地:即便机器随后就绪也不自动切换
- await remote.refresh()
- expect(remote.activeId).toBeNull()
- })
-
- it('降级态下 switchTo 直接忽略(远端项在切换器中已禁用)', async () => {
- bindSshApiForTests({
- listMachines: vi.fn(async () => { throw new TypeError('fetch failed') }),
- connect: vi.fn(async () => { throw new Error('unreachable') }),
- disconnect: vi.fn(async () => undefined),
- })
- await remote.refresh()
- expect(remote.available).toBe(false)
- remote.switchTo('m1')
- expect(remote.pendingId).toBeNull()
- })
-
- it('disconnect:活动机器先回本地视图再向引擎发断开,随后 refresh 落定', async () => {
- const disconnectSpy = vi.fn(async () => undefined)
- bindSshApiForTests({
- listMachines: vi.fn(async () => listOf([machineOf({ id: 'm1', state: 'disconnected' })])),
- connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
- disconnect: disconnectSpy,
- })
- remote.machines = [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })]
- remote.enabled = true
- remote.activeId = 'm1'
- remote.activeTunnelUrl = 'http://127.0.0.1:4001'
- await remote.disconnect('m1')
- expect(disconnectSpy).toHaveBeenCalledWith('m1')
- // 视图立即回本地(不等 refresh),refresh 后引擎落定 disconnected
- expect(remote.activeId).toBeNull()
- expect(remote.activeTunnelUrl).toBe('')
- expect(remote.machines[0]?.state).toBe('disconnected')
- })
-
- it('连接进行中:累积走过的 progress 阶段 + 增量追加事件日志;成功自动复位', async () => {
- let release: () => void = () => {}
- bindSshApiForTests({
- listMachines: bindListSequence([
- [machineOf({ id: 'm1', state: 'disconnected' })],
- [machineOf({ id: 'm1', state: 'connecting', progress: { phase: 'installing' } })],
- [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],
- ]),
- connect: vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((resolve) => {
- release = () => resolve({ tunnelBaseUrl: 'http://127.0.0.1:4001' })
- })),
- disconnect: vi.fn(async () => undefined),
- events: vi.fn(async (_id: string, sinceSeq = 0) => ({
- items: sinceSeq === 0
- ? [{ seq: 0, line: '[handshake] ssh ok' }, { seq: 1, line: '[installing] download' }]
- : [],
- })),
- })
- await remote.refresh()
- remote.switchTo('m1')
- // 连接阻塞中:轮询 refresh 把 progress 阶段与事件增量累积进跟踪态
- await remote.refresh()
- expect(remote.connectTrail).toEqual(['installing'])
- expect(remote.connectLog).toEqual(['[handshake] ssh ok', '[installing] download'])
- // 就绪:切换完成,跟踪态自动复位(弹窗随 pendingId 清空关闭)
- release()
- await vi.waitFor(() => expect(remote.activeId).toBe('m1'))
- expect(remote.connectTrail).toEqual([])
- expect(remote.connectLog).toEqual([])
- expect(remote.connectFailed).toBeNull()
- })
-
- it('连接失败:定格目标与直接原因供进度弹窗呈现,dismissConnect 关闭清理', async () => {
- bindSshApiForTests({
- listMachines: vi.fn(async () => listOf([machineOf({ id: 'm1', state: 'given-up', lastError: 'timeout' })])),
- connect: vi.fn(async () => { throw new Error('dial tcp timeout') }),
- disconnect: vi.fn(async () => undefined),
- events: vi.fn(async () => ({ items: [{ seq: 0, line: '[handshake] fail' }] })),
- })
- await remote.refresh()
- remote.switchTo('m1')
- await vi.waitFor(() => expect(remote.connectFailed).toEqual({ id: 'm1', error: 'dial tcp timeout' }))
- // 失败期间的事件日志保留在弹窗里(用户可见问题所在)
- await vi.waitFor(() => expect(remote.connectLog).toEqual(['[handshake] fail']))
- remote.dismissConnect()
- expect(remote.connectFailed).toBeNull()
- expect(remote.connectLog).toEqual([])
- })
-
- describe('cancelConnect(取消连接)', () => {
- it('取消进行中的连接:在飞 connect 以取消错误落定时静默,不定格失败', async () => {
- let releaseConnect: (err: Error) => void = () => {}
- const engine = bindEngine({
- list: [[machineOf({ id: 'm1', state: 'disconnected' })]],
- connect: vi.fn(() => new Promise<{ tunnelBaseUrl: string }>((_resolve, reject) => {
- releaseConnect = reject
- })),
- })
- const disconnectSpy = vi.fn(async () => undefined)
- bindSshApiForTests({ listMachines: engine.listMachines, connect: engine.connect, disconnect: disconnectSpy })
-
- await remote.refresh()
- remote.switchTo('m1')
- expect(engine.connect).toHaveBeenCalledWith('m1')
- expect(remote.pendingId).toBe('m1')
-
- remote.cancelConnect('m1')
- expect(remote.pendingId).toBeNull()
- await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledWith('m1'))
-
- // 引擎侧在飞 connect 以 "cancelled by disconnect" 拒绝:静默收场(不定格失败)
- releaseConnect(new Error('connect failed: connection cancelled by disconnect'))
- await vi.waitFor(() => expect(disconnectSpy).toHaveBeenCalledTimes(1))
- expect(remote.connectFailed).toBeNull()
- })
- })
-})
diff --git a/src/store/modules/remote/store.ts b/src/store/modules/remote/store.ts
deleted file mode 100644
index af61807b..00000000
--- a/src/store/modules/remote/store.ts
+++ /dev/null
@@ -1,351 +0,0 @@
-/**
- * 远端机器模块(壳层):机器列表轮询、iframe 切换目标(activeId/粘性隧道
- * URL)与降级态。数据面完全来自本地实例 `/api-ssh`(dsh-tauri-ssh 插件,
- * S1 契约)——壳不自存任何机器,连接/隧道/bootstrap 全部由插件引擎推进。
- *
- * 节奏(KISS,无推送通道):秒级轮询 + 窗口聚焦触发刷新(监听在组件侧
- * hook 装配);本地实例不可达时进入降级态(保留列表、静默重试,不弹错误
- * 风暴),恢复后自动复原。插件侧 SSH 开关未启用(或本地实例没有该 API)时
- * 清空远端视图并隐藏壳层切换器,而不是谎报「本地实例不可达」。切换语义
- * (断开回本地、重连粘性、就绪即切)由纯函数 `reconcileSwitcher` 承担
- * (见 logic.ts)。
- * @module store/remote/store
- */
-
-import type { SshApiClient } from './api'
-import type { SshMachineRow, SshProgressPhase } from './types'
-import { defineStore } from 'valtio-define'
-import { harness } from '../harness'
-import { createSshApiClient, SshApiHttpError } from './api'
-import { reconcileSwitcher } from './logic'
-
-/** 轮询间隔(毫秒):秒级即可让切换器跟上连接/重连状态流转。 */
-const POLL_INTERVAL_MS = 2000
-
-/** machine.events 增量游标(模块级,不属于 UI 状态)。 */
-let eventSeq = 0
-
-/** 连接尝试代次:取消/新尝试作废旧 connectAndSwitch 的落定(成功与失败都静默)。 */
-let connectEpoch = 0
-
-/** 引擎/网络错误的可读摘要(与 ssh-ui 的 messageOf 同语义)。 */
-function messageOf(error: unknown): string {
- return error instanceof Error ? error.message : String(error)
-}
-
-/** 模块级轮询句柄(与 harness store 的定时器管理模式一致)。 */
-let pollTimer: ReturnType<typeof setInterval> | undefined
-
-/** 数据面客户端:默认走全局 fetch 与 harness 的 serviceUrl(测试可替换)。 */
-let api = createSshApiClient(
- (input, init) => fetch(input, init),
- () => harness.$state.serviceUrl,
-)
-
-/** 当前数据面客户端(管理面板复用同一实例;测试经 bindSshApiForTests 替换)。 */
-export function sshApi(): SshApiClient {
- return api
-}
-
-/** 测试注入口:替换数据面客户端并复位切换状态(仅测试使用)。 */
-export function bindSshApiForTests(client: Partial<SshApiClient> & Pick<SshApiClient, 'listMachines' | 'connect' | 'disconnect'>): void {
- api = {
- save: async () => {},
- remove: async () => {},
- test: async () => ({ ok: true }),
- events: async () => ({ items: [] }),
- ...client,
- }
-}
-
-export const remote = defineStore({
- state: () => ({
- /** 全部机器(手动机器 + ~/.ssh/config 别名,按名排序)。 */
- machines: [] as SshMachineRow[],
- /** SSH 功能是否已启用(插件侧开关);未启用时壳层不渲染切换器。 */
- enabled: false,
- /** iframe 当前指向的远端机器(null = 本地实例)。 */
- activeId: null as string | null,
- /** 点击未连接机器后待切换的目标(连接就绪后升为 activeId)。 */
- pendingId: null as string | null,
- /** 远端弹窗启动寻址的挂起目标(refresh 成功且机器出现即切换;手动操作撤销) */
- pendingBootMachineId: null as string | null,
- /** 活动机器最近已知的隧道 URL(重连窗口粘性保留,避免指向空端口)。 */
- activeTunnelUrl: '',
- /** `/api-ssh` 是否可达;不可达时切换器降级(禁用远端项 + 提示)。 */
- available: true,
- /** 连接进度弹窗:本次连接实际走过的管线阶段(落定后保留供失败复盘)。 */
- connectTrail: [] as SshProgressPhase[],
- /** 连接进度弹窗:machine.events 实时日志尾(增量轮询追加)。 */
- connectLog: [] as string[],
- /** 连接失败定格:目标机器 + 直接原因(弹窗呈现与重试入口)。 */
- connectFailed: null as { id: string, error: string } | null,
- /** 进行中手动关了弹窗:隐藏到落定;失败时重新弹出(原因必须可见)。 */
- connectDismissed: false,
- /** 单飞标志:上一轮未完成时跳过本轮,避免请求堆积。 */
- refreshing: false,
- booted: false,
- }),
- actions: {
- /** 首次挂载切换器时启动轮询(StrictMode 重复挂载下只执行一次)。 */
- boot() {
- if (this.booted)
- return
- this.booted = true
- void this.refresh()
- pollTimer = setInterval(() => {
- // 窗口隐藏时跳过本轮(平台 WebView 报告可见性才生效;恢复可见由
- // 组件侧 visibilitychange 触发的即时刷新兜底)
- if (typeof document !== 'undefined' && document.hidden)
- return
- void this.refresh()
- }, POLL_INTERVAL_MS)
- },
-
- /** 拉取机器列表并推进切换语义;不可达时进入降级态(静默,保留列表)。 */
- async refresh() {
- if (this.refreshing)
- return
- this.refreshing = true
- try {
- const { enabled, machines } = await api.listMachines()
- this.available = true
- this.enabled = enabled
- // 未启用:机器列表与远端视图一并清空(连接已由主机侧断开),壳层隐藏
- // 切换器;挂起中的启动寻址保留,启用后随下一轮成功轮询兑现。
- if (!enabled) {
- this.machines = []
- this.activeId = null
- this.activeTunnelUrl = ''
- this.pendingId = null
- return
- }
- const next = reconcileSwitcher(
- { activeId: this.activeId, pendingId: this.pendingId, activeTunnelUrl: this.activeTunnelUrl },
- machines,
- )
- this.machines = machines
- this.activeId = next.activeId
- this.pendingId = next.pendingId
- this.activeTunnelUrl = next.activeTunnelUrl
- // 启动寻址(远端弹窗 remote-<id>):实例就绪前 refresh 会连续失败,
- // 一次性「拉一轮再切」抢跑必然落空——挂起目标随每次成功轮询推进,
- // 机器一出现即切(已连接直切/未连接发起连接),用户手动操作则撤销
- if (this.pendingBootMachineId !== null
- && this.machines.some(machine => machine.id === this.pendingBootMachineId)) {
- const target = this.pendingBootMachineId
- this.pendingBootMachineId = null
- // 必须等本轮 refresh 收尾再切:switchTo 的连接路径
- // (connectAndSwitch)内部会再 refresh,嵌套调用会被
- // refreshing 重入守卫吞掉导致永不切换
- setTimeout(() => this.switchTo(target), 0)
- }
- await this.trackConnectProgress()
- }
- catch (err) {
- // 本地实例可达但没有 SSH API(插件未加载 / 未启用):SSH 不可用,
- // 不是「本地实例不可达」——静默隐藏切换器,不弹误导性的降级提示。
- if (err instanceof SshApiHttpError) {
- this.available = true
- this.enabled = false
- this.machines = []
- this.activeId = null
- this.activeTunnelUrl = ''
- this.pendingId = null
- }
- else {
- // 本地实例不可达(启动中/已停止):降级但保留既有列表,静默重试。
- // 只在「可达 → 不可达」这一次打日志,之后每 2 秒的失败轮次不再打:实例停着
- // (插件操作会停服)时会连续失败几百轮,每轮带一份堆栈就是把日志淹掉,而这行
- // 信息的增量是零——`available` 已经表达了降级态。
- if (this.available)
- console.warn('[remote] /api-ssh unreachable:', messageOf(err))
- this.available = false
- }
- }
- finally {
- this.refreshing = false
- }
- },
-
- /** 连接进行中:累积实际走过的 progress 阶段 + 增量拉取事件日志。 */
- async trackConnectProgress() {
- const id = this.pendingId ?? this.connectFailed?.id
- if (id === undefined || id === null)
- return
- const machine = this.machines.find(item => item.id === id)
- const phase = machine?.progress?.phase
- if (phase !== undefined && this.connectTrail[this.connectTrail.length - 1] !== phase)
- this.connectTrail = [...this.connectTrail, phase]
- try {
- const { items } = await api.events(id, eventSeq)
- for (const item of items) {
- eventSeq = Math.max(eventSeq, item.seq + 1)
- this.connectLog = [...this.connectLog, item.line]
- }
- }
- catch {
- // 事件通道失败不阻断连接进度(列表轮询仍在推进)
- }
- },
-
- /** 关闭连接进度弹窗:清日志/阶段/失败定格(不影响进行中的连接)。 */
- dismissConnect() {
- this.connectTrail = []
- this.connectLog = []
- this.connectFailed = null
- // 仍在连接中:仅隐藏到落定(失败会重新弹出),成功/失败后自然复位
- if (this.pendingId !== null)
- this.connectDismissed = true
- },
-
- /**
- * 取消进行中的连接:抬代次(在飞的 connectAndSwitch 落定静默)+ 中止
- * 引擎侧尝试(manager 的 disconnect 会取消在飞 connect)。弹窗随
- * pendingId 清空关闭;无失败定格。
- */
- cancelConnect(machineId: string) {
- if (this.pendingId !== machineId)
- return
- connectEpoch += 1
- this.pendingId = null
- this.dismissConnect()
- this.connectDismissed = false
- void api.disconnect(machineId)
- .catch(err => console.warn('[remote] cancel disconnect failed:', err))
- .finally(() => void this.refresh())
- },
-
- /**
- * 切换视图:已连接直接切换;进行中(连接/重连)挂起等待;否则发起
- * 连接(阻塞到隧道就绪,见 S1 契约——不会指向空端口)。
- */
- switchTo(machineId: string) {
- this.pendingBootMachineId = null
- if (!this.available)
- return
- const machine = this.machines.find(item => item.id === machineId)
- if (machine === undefined)
- return
- if (machine.state === 'connected' && machine.tunnelBaseUrl !== undefined) {
- this.activeId = machineId
- this.activeTunnelUrl = machine.tunnelBaseUrl
- this.pendingId = null
- return
- }
- if (machine.state === 'connecting' || machine.state === 'testing' || machine.state === 'reconnecting') {
- // 引擎已在推进(用户连接或自动重连):挂起等待,轮询 reconcile 接管
- if (this.pendingId !== machineId)
- this.beginTracking(machineId)
- return
- }
- // disconnected / given-up:重新连接(given-up 可经再次 connect 退出)
- this.beginTracking(machineId)
- void this.connectAndSwitch(machineId)
- },
-
- /** 开始跟踪一台机器的连接:复位日志/阶段/游标并挂起。 */
- beginTracking(machineId: string) {
- connectEpoch += 1
- this.pendingId = machineId
- this.connectFailed = null
- this.connectDismissed = false
- this.connectTrail = []
- this.connectLog = []
- eventSeq = 0
- },
-
- /** 连接一台机器并在就绪后切换;失败定格原因(进度弹窗呈现重试入口)。 */
- async connectAndSwitch(machineId: string) {
- const epoch = connectEpoch
- try {
- const link = await api.connect(machineId)
- // 已被取消或被新尝试取代:静默(不动 activeId/失败定格)
- if (epoch !== connectEpoch)
- return
- await this.refresh()
- const machine = this.machines.find(item => item.id === machineId)
- if (machine !== undefined && machine.state === 'connected') {
- this.activeId = machineId
- this.activeTunnelUrl = machine.tunnelBaseUrl ?? link.tunnelBaseUrl
- this.pendingId = null
- // 成功:弹窗随 pendingId 清空自动关闭,日志/阶段一并复位
- this.dismissConnect()
- this.connectDismissed = false
- }
- }
- catch (err) {
- // 用户取消(或新尝试取代):引擎报 "cancelled by disconnect",不定格失败
- if (epoch !== connectEpoch)
- return
- console.warn('[remote] connect failed:', err)
- this.pendingId = null
- this.connectFailed = { id: machineId, error: messageOf(err) }
- // 失败必须可见:进行中手动关过弹窗也重新弹出
- this.connectDismissed = false
- // 拉取引擎落定的失败态(given-up + lastError)供切换器呈现
- void this.refresh()
- }
- },
-
- /**
- * 远端弹窗启动寻址:窗口 label 为 remote-<machineId> 时由壳层调用——
- * 登记挂起目标并立即触发一轮拉取;机器在任一成功轮询中出现即切
- * (已连接直切;未连接发起连接,进度弹窗照常)。挂在 refresh 成功分支
- * 而非一次性 await:新窗口启动时实例健康检查往往尚未就绪,抢跑的
- * refresh 只会失败落空。幂等:重复调用以最后一次为准。
- */
- openInitialMachine(machineId: string) {
- this.pendingBootMachineId = machineId
- void this.refresh()
- },
-
- /** 退回本地实例视图(不断开远端连接;同时撤销挂起中的切换)。 */
- backToLocal() {
- this.pendingBootMachineId = null
- this.activeId = null
- this.activeTunnelUrl = ''
- this.pendingId = null
- },
-
- /** 断开一台机器:活动机器先退回本地视图,再向引擎发断开。 */
- async disconnect(machineId: string) {
- if (this.activeId === machineId)
- this.backToLocal()
- if (this.pendingId === machineId)
- this.pendingId = null
- try {
- await api.disconnect(machineId)
- }
- catch (err) {
- console.warn('[remote] disconnect failed:', err)
- }
- finally {
- void this.refresh()
- }
- },
- },
-})
-
-/** 停止轮询并复位(测试收尾用;壳层生命周期内不调用)。 */
-export function disposeRemoteForTests(): void {
- if (pollTimer !== undefined) {
- clearInterval(pollTimer)
- pollTimer = undefined
- }
- remote.booted = false
- remote.machines = []
- remote.enabled = false
- remote.activeId = null
- remote.pendingId = null
- remote.pendingBootMachineId = null
- remote.activeTunnelUrl = ''
- remote.available = true
- remote.refreshing = false
- remote.connectTrail = []
- remote.connectLog = []
- remote.connectFailed = null
- remote.connectDismissed = false
- eventSeq = 0
- connectEpoch = 0
-}
diff --git a/src/store/modules/remote/types.ts b/src/store/modules/remote/types.ts
deleted file mode 100644
index 28f39c46..00000000
--- a/src/store/modules/remote/types.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * SSH 远端机器的类型面:壳层消费 `/api-ssh`(本地实例上的 dsh-tauri-ssh
- * 插件路由)所需的最小机器行词汇。字段与插件 host 侧
- * `SshMachineListItem`(C-STATE / S1 契约)逐字对齐:六态连接状态 +
- * `nextRetryAt`/`authMethod` 增量、隧道 URL、最近错误与机器标识色。
- * @module store/remote/types
- */
-
-/** S3 状态词汇表(六态):切换器状态点与切换语义的共用词汇。 */
-export type SshConnectionState
- = | 'disconnected'
- | 'testing'
- | 'connecting'
- | 'connected'
- | 'reconnecting'
- | 'given-up'
-
-/** 切换器渲染所需的机器行(`machine.list` 行的壳层投影)。 */
-export interface SshMachineRow {
- id: string
- name: string
- /** 标识色(手动机器可选);色点优先取它。 */
- color?: string
- /** 是否用标识色给内容区描边。 */
- tintBorder?: boolean
- /** 连接目标(管理面板表单回填与切换器副标题)。 */
- host?: string
- port?: number
- user?: string
- /** 远端 dsh web 端口。 */
- remotePort?: number
- /** 自定义启动命令(远端 home pin 端口时用)。 */
- startCommand?: string
- /** 是否已存密码/密钥口令(值本身永不过线;表单「留空=保留」提示用)。 */
- hasPassword?: boolean
- hasPassphrase?: boolean
- state: SshConnectionState
- /** 隧道就绪时的本地回环 URL(`http://127.0.0.1:<port>`)。 */
- tunnelBaseUrl?: string
- /** 最近一次失败的原因(given-up 时呈现入口)。 */
- lastError?: string
- /** 下次重连重试时间(epoch ms,reconnecting 时出现)。 */
- nextRetryAt?: number
- /** 当前(或最近一次成功)连接使用的凭据类型。 */
- authMethod?: 'agent' | 'key' | 'password'
- /** 进行中操作的实时阶段(连接/安装管线),落定即消失。 */
- progress?: SshProgress
-}
-
-/** 连接管线阶段(宿主 progress.phase 词汇;installing 含 bootstrap 安装段)。 */
-export type SshProgressPhase = 'handshake' | 'installing' | 'starting' | 'probing'
-
-/** 进行中操作的实时进度(来自 machine.list 行的 progress 字段)。 */
-export interface SshProgress {
- phase: SshProgressPhase
- attempt?: number
- total?: number
- log?: string
-}
-
-/** machine.save 的机器档案(与宿主 MachineProfile 契约对齐;敏感值走 secrets 另传)。 */
-export interface SshMachineProfile {
- id: string
- name: string
- host: string
- port?: number
- user?: string
- remotePort?: number
- color?: string
- tintBorder?: boolean
- startCommand?: string
-}
-
-/** machine.save 的敏感字段:仅在保存时传输,任何状态不落库。 */
-export interface SshSecrets {
- password?: string
- passphrase?: string
-}
-
-/** machine.events 返回的单条事件(seq 单调递增,增量轮询游标)。 */
-export interface SshEventEntry {
- seq: number
- line: string
-}
-
-/**
- * `machine.list` 的应答信封(items = 手动机器,discovered = ~/.ssh/config 别名)。
- * `enabled` 为 SSH 功能开关:关闭时两侧机器行为空,壳层据此不渲染切换器。
- */
-export interface SshMachineListValue {
- enabled?: boolean
- items: SshMachineRow[]
- discovered: SshMachineRow[]
-}
diff --git a/test/e2e/plugins/dsh-tauri-ssh.e2e.ts b/test/e2e/plugins/dsh-tauri-ssh.e2e.ts
index 5f56c810..c4fd2bfb 100644
--- a/test/e2e/plugins/dsh-tauri-ssh.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-ssh.e2e.ts
@@ -1,10 +1,14 @@
/**
* dsh-tauri-ssh 远程机插件 E2E:真实 ssh2 传输层与真实 SSH 协议往返。
*
- * 四条契约各占一个 describe,共用同一套 `bootHarness` 脚手架——真实的
- * `Ssh2Transport`、宿主自身 `~/.ssh` 的别名与身份文件解析、带时间戳的
- * status/event 证据日志。断言对象是外部世界(HTTP 字节、服务端记录的认证方法
- * 序列、被杀的 sshd 会话进程),不采信插件自报:
+ * 四条契约各占一个 describe,共用同一套 `bootHarness` 脚手架——装配真实的
+ * 运行时单例(`transport` 服务 + `config/runtime.ts` 的 use* 装配面),宿主
+ * 自身 `~/.ssh` 的别名与身份文件解析,带时间戳的 status/event 证据日志。
+ * 事件证据走公开读面 `events.since(machineId, fromSeq)` 轮询:重构后事件类
+ * 已不存在,轮询读回的每一行按 `event <stage>[/<terminal>]: <line>` 打平,
+ * `at` 取事件自报的 `ts`,因此重连退避的间隔算术与轮询延迟无关。断言对象是
+ * 外部世界(HTTP 字节、服务端记录的认证方法序列、被杀的 sshd 会话进程),
+ * 不采信插件自报:
* - reconnect:真实 linux x64 机器上杀掉服务端会话 → 自动重连 → 同一隧道 URL 继续服务;
* - give-up:持续不可达的本机端口上的指数退避节奏与 given-up 终态;
* - password-chain:回环 ssh2 协议服务器上的 agent→key→password 认证链与三类失败分类;
@@ -18,37 +22,22 @@
*/
import type { Connection, Server as SshServer } from 'ssh2'
-import type { MachineProfile, SshMachineStage, SshMachineTerminal } from '../../../packages/dsh-tauri-ssh/src/host/types/index'
+import type { MachineProfile, SshHostContext, SshSession } from '../../../packages/dsh-tauri-ssh/src/host/types/index'
import { execSync } from 'node:child_process'
import { generateKeyPairSync } from 'node:crypto'
-import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createServer, connect as tcpConnect } from 'node:net'
import { homedir, tmpdir } from 'node:os'
+import process from 'node:process'
import { join } from 'pathe'
import { Server } from 'ssh2'
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import { SshMachineEvents } from '../../../packages/dsh-tauri-ssh/src/host/service/events'
-import { KnownHostsStore } from '../../../packages/dsh-tauri-ssh/src/host/service/host-keys'
-import { SshManager } from '../../../packages/dsh-tauri-ssh/src/host/service/manager'
-import { SshConfigResolver } from '../../../packages/dsh-tauri-ssh/src/host/service/ssh-config'
-import { Ssh2Transport } from '../../../packages/dsh-tauri-ssh/src/host/service/transport'
+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
+import { clearHostRuntime, machineProfiles, setCurrentHostInstance, setHostConfig, setMachineDeps } from '../../../packages/dsh-tauri-ssh/src/host/config/runtime'
+import { events } from '../../../packages/dsh-tauri-ssh/src/host/service/events'
+import { machine } from '../../../packages/dsh-tauri-ssh/src/host/service/machine'
+import { transport } from '../../../packages/dsh-tauri-ssh/src/host/service/transport'
import { MachineId } from '../../../packages/dsh-tauri-ssh/src/host/types/index'
-
-/**
- * The machine event channel with evidence logging: every appended line is
- * echoed into the harness log (`event <stage>[/<terminal>]: <line>`) before
- * it lands in the ring buffer, so the specs can grep the emitted stream.
- */
-class LoggingMachineEvents extends SshMachineEvents {
- constructor(private readonly log: (text: string) => void) {
- super()
- }
-
- override append(machineId: MachineId, stage: SshMachineStage, line: string, options: { terminal?: SshMachineTerminal, reason?: string } = {}) {
- this.log(`event ${stage}${options.terminal === undefined ? '' : `/${options.terminal}`}: ${line}`)
- return super.append(machineId, stage, line, options)
- }
-}
+import { EMPTY_ALLOWLIST } from '../../../packages/dsh-tauri-ssh/src/host/utils/allowlist'
/** One timestamped evidence line. */
interface EvidenceLine {
@@ -56,10 +45,11 @@ interface EvidenceLine {
text: string
}
-/** The E2E harness: manager plus captured evidence. */
+/** The E2E harness: the assembled runtime service plus captured evidence. */
interface Harness {
- manager: SshManager
+ manager: typeof machine
evidence: EvidenceLine[]
+ drain: () => void
log: (text: string) => void
dispose: () => Promise<void>
}
@@ -76,9 +66,29 @@ function freshRsaPem(): string {
}
/**
- * Boot one real-transport manager with scratch TOFU storage and the given
- * connect/reconnect timing, logging every status and event emission with a
- * timestamp.
+ * The minimal host context the runtime needs: the E2E suite drives the
+ * services directly, so nothing is ever registered on the web server and no
+ * effect is ever mounted.
+ */
+function hostContextStub(): SshHostContext {
+ return {
+ webServer: { register: () => () => {} },
+ effect: () => undefined,
+ }
+}
+
+/** Every `it` leaves no runtime behind (assembly is process-global state). */
+afterEach(() => {
+ clearHostRuntime()
+})
+
+/**
+ * Boot one real-transport runtime with scratch TOFU/state storage and the
+ * given connect/reconnect timing, logging every status and event emission
+ * with a timestamp.
+ *
+ * Assembly order is the production one (`apply.ts` is the only other caller):
+ * clear the runtime → bind the host instance → `setHostConfig` → `setMachineDeps`.
*/
function bootHarness(options: {
connectTimeoutMs?: number
@@ -93,37 +103,62 @@ function bootHarness(options: {
} = {}): Harness {
const evidence: EvidenceLine[] = []
const t0 = now()
+ const root = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-'))
+ const seenSeq = new Map<MachineId, number>()
+
+ /**
+ * Read the public event surface forward from the last seen seq. `at` is the
+ * event's own timestamp, so the retry spacing is exact regardless of how
+ * often this poller happens to run.
+ */
+ const drain = (): void => {
+ for (const machineId of machineProfiles.keys()) {
+ const after = seenSeq.get(machineId) ?? 0
+ const page = events.since(machineId, after)
+ // Advance only past events actually handed over: `nextSeq` is the
+ // buffer's own next seq and would skip events appended after the poll.
+ const last = page.events.at(-1)?.seq
+ if (last !== undefined)
+ seenSeq.set(machineId, last)
+ for (const event of page.events) {
+ const at = Date.parse(event.ts)
+ evidence.push({
+ at: Number.isNaN(at) ? now() : at,
+ text: `event ${event.stage}${event.terminal === undefined ? '' : `/${event.terminal}`}: ${event.line}`,
+ })
+ }
+ }
+ }
+
const log = (text: string): void => {
+ drain()
const line = { at: now(), text }
evidence.push(line)
// eslint-disable-next-line no-console -- the E2E evidence log is the point
console.log(`[+${(line.at - t0).toString().padStart(6)}ms] ${text}`)
}
- const root = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-'))
- const manager = new SshManager({
- transport: new Ssh2Transport(
- options.connectTimeoutMs ?? 15_000,
- // The host's real ~/.ssh: config aliases and identity files, exactly
- // what the plugin in the desktop app would resolve against.
- new SshConfigResolver(options.sshDir ?? join(homedir(), '.ssh'), homedir()),
- {
- keepaliveIntervalMs: options.keepaliveIntervalMs ?? 3_000,
- keepaliveCountMax: options.keepaliveCountMax ?? 3,
- },
- ),
- knownHosts: new KnownHostsStore(join(root, 'known-hosts.json')),
- config: {
- connectTimeoutMs: options.connectTimeoutMs ?? 15_000,
- healthCheckTimeoutMs: 3_000,
- healthPollIntervalMs: options.healthPollIntervalMs ?? 500,
- healthPollAttempts: options.healthPollAttempts ?? 30,
- keepaliveIntervalMs: options.keepaliveIntervalMs ?? 3_000,
- keepaliveCountMax: options.keepaliveCountMax ?? 3,
- reconnectInitialDelayMs: options.reconnectInitialDelayMs ?? 1_000,
- reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 5_000,
- reconnectMaxAttempts: options.reconnectMaxAttempts ?? 6,
- },
- events: new LoggingMachineEvents(log),
+
+ clearHostRuntime()
+ setCurrentHostInstance(hostContextStub())
+ setHostConfig({
+ connectTimeoutMs: options.connectTimeoutMs ?? 15_000,
+ healthCheckTimeoutMs: 3_000,
+ healthPollIntervalMs: options.healthPollIntervalMs ?? 500,
+ healthPollAttempts: options.healthPollAttempts ?? 30,
+ keepaliveIntervalMs: options.keepaliveIntervalMs ?? 3_000,
+ keepaliveCountMax: options.keepaliveCountMax ?? 3,
+ reconnectInitialDelayMs: options.reconnectInitialDelayMs ?? 1_000,
+ reconnectMaxDelayMs: options.reconnectMaxDelayMs ?? 5_000,
+ reconnectMaxAttempts: options.reconnectMaxAttempts ?? 6,
+ // The host's real ~/.ssh: config aliases and identity files, exactly
+ // what the plugin in the desktop app would resolve against.
+ sshDir: options.sshDir ?? join(homedir(), '.ssh'),
+ // Scratch TOFU + machine table: the suite must never touch ~/.dsh.
+ knownHostsPath: join(root, 'known-hosts.json'),
+ statePath: join(root, 'machines.json'),
+ })
+ setMachineDeps({
+ transport,
emitStatus: (statusId, status) => {
const hints = [
status.state,
@@ -134,13 +169,21 @@ function bootHarness(options: {
]
log(`status ${String(statusId)}: ${hints.join(' ')}`)
},
+ localAllowlist: () => ({ ...EMPTY_ALLOWLIST }),
})
+ const poller = setInterval(drain, 50)
+
return {
- manager,
+ manager: machine,
evidence,
+ drain,
log,
dispose: async () => {
- await manager.dispose()
+ clearInterval(poller)
+ drain()
+ await machine.dispose()
+ clearHostRuntime()
+ rmSync(root, { recursive: true, force: true })
},
}
}
@@ -360,6 +403,7 @@ describe('e2e give-up (local unreachable port)', () => {
// The retry schedule from the event log: one auth failure per attempt,
// one reconnect line per scheduled retry, gaps growing 300→600→1200→1200.
+ harness.drain()
const retryLines = harness.evidence.filter(line => line.text.includes('event reconnect: retrying'))
const gaps: number[] = []
let previous: number | undefined
@@ -414,15 +458,37 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
const attempts: AuthAttempt[] = []
let server: SshServer
let serverPort = 0
+ let scratchHome: string
let scratchSshDir: string
+ const envBefore: { USERPROFILE: string | undefined, HOME: string | undefined } = {
+ USERPROFILE: process.env.USERPROFILE,
+ HOME: process.env.HOME,
+ }
+ /**
+ * A scratch identity file is fed to the host as `~/.ssh/id_rsa` of a scratch
+ * HOME, not as an absolute path: `resolveSshAuth` treats every identity path
+ * that does not literally start with `/` as home-relative
+ * (`host/utils/ssh-config.ts:37-41`), so a Windows drive path such as
+ * `C:/…/.ssh/id_rsa` is joined onto the home dir twice and resolves to no
+ * key at all. Going through the home-relative branch keeps the production
+ * path (config discovery → identity files → transport auth order) real on
+ * every platform; the absolute-path defect is the package's own problem
+ * (`utils/ssh-config.test.ts` is red on Windows for exactly that reason).
+ */
beforeAll(async () => {
// A fresh host key pair for the server and one for the client's (rejected)
// identity file.
const hostKey = freshRsaPem()
const clientKey = freshRsaPem()
- scratchSshDir = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-sshdir-'))
+ scratchHome = mkdtempSync(join(tmpdir(), 'dsh-ssh-e2e-home-'))
+ scratchSshDir = join(scratchHome, '.ssh')
+ mkdirSync(scratchSshDir, { recursive: true })
writeFileSync(join(scratchSshDir, 'id_rsa'), clientKey)
+ // `homeDir()` is read when the runtime is assembled, so it must already
+ // point at the scratch home before the first `bootHarness` in each `it`.
+ process.env.USERPROFILE = scratchHome
+ process.env.HOME = scratchHome
server = new Server({ hostKeys: [hostKey] }, (client: Connection) => {
client.on('authentication', (ctx) => {
@@ -455,7 +521,13 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
afterAll(() => {
server.close()
- rmSync(scratchSshDir, { recursive: true, force: true })
+ rmSync(scratchHome, { recursive: true, force: true })
+ if (envBefore.USERPROFILE === undefined)
+ delete process.env.USERPROFILE
+ else process.env.USERPROFILE = envBefore.USERPROFILE
+ if (envBefore.HOME === undefined)
+ delete process.env.HOME
+ else process.env.HOME = envBefore.HOME
})
function profileWith(password?: string): MachineProfile {
@@ -472,7 +544,7 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
it('authenticates with the stored password after agent and keys are refused', async () => {
attempts.length = 0
- const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ const harness = bootHarness({ sshDir: '.ssh', connectTimeoutMs: 5_000 })
try {
const profile = profileWith(PASSWORD)
harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
@@ -496,7 +568,7 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
it('classifies a wrong stored password as password-rejected', async () => {
attempts.length = 0
- const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ const harness = bootHarness({ sshDir: '.ssh', connectTimeoutMs: 5_000 })
try {
const profile = profileWith('wrong-password')
harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
@@ -511,7 +583,7 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
it('classifies exhausted keys without a password as key-rejected', async () => {
attempts.length = 0
- const harness = bootHarness({ sshDir: scratchSshDir, connectTimeoutMs: 5_000 })
+ const harness = bootHarness({ sshDir: '.ssh', connectTimeoutMs: 5_000 })
try {
const profile = profileWith()
harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
@@ -531,6 +603,9 @@ describe('e2e password chain (loopback ssh2 protocol server)', () => {
* what a NAT/firewall drop looks like); ssh2's keepalive misses its
* heartbeat budget and must declare the session closed, surfacing through
* the session's onClosed callback (the manager's reconnect trigger).
+ *
+ * The session comes from `machine.openSession`, i.e. the keepalive budget is
+ * the assembled Config's, not a hand-built transport's.
*/
describe('e2e keepalive watchdog (silent connection freeze)', () => {
const PASSWORD = 'e2e-watchdog'
@@ -617,11 +692,6 @@ describe('e2e keepalive watchdog (silent connection freeze)', () => {
it('declares a hung session closed after the heartbeat budget', async () => {
const proxy = await startStallingProxy()
- const transport = new Ssh2Transport(
- 5_000,
- new SshConfigResolver(scratchSshDir, homedir()),
- { keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS, keepaliveCountMax: KEEPALIVE_COUNT_MAX },
- )
const profile: MachineProfile = {
id: MachineId('watchdog'),
name: 'watchdog',
@@ -631,12 +701,21 @@ describe('e2e keepalive watchdog (silent connection freeze)', () => {
password: PASSWORD,
remotePort: 3080,
}
+ const harness = bootHarness({
+ connectTimeoutMs: 5_000,
+ keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS,
+ keepaliveCountMax: KEEPALIVE_COUNT_MAX,
+ sshDir: scratchSshDir,
+ })
+ let session: SshSession | undefined
try {
- const session = await transport.connect(profile, () => true)
- expect(session.authMethod).toBe('password')
+ harness.manager.refreshProfiles(new Map([[profile.id, profile]]))
+ const opened = await harness.manager.openSession(profile.id)
+ session = opened
+ expect(opened.authMethod).toBe('password')
const closedAt = new Promise<number>((resolve) => {
- session.onClosed(() => resolve(Date.now()))
+ opened.onClosed(() => resolve(Date.now()))
})
const frozeAt = Date.now()
proxy.freeze()
@@ -655,7 +734,9 @@ describe('e2e keepalive watchdog (silent connection freeze)', () => {
expect(elapsed).toBeLessThan(20_000)
}
finally {
+ await session?.close().catch(() => undefined)
proxy.close()
+ await harness.dispose()
}
}, 60_000)
})
diff --git a/test/remote-poll-logging.test.ts b/test/remote-poll-logging.test.ts
index 207bb210..6591c638 100644
--- a/test/remote-poll-logging.test.ts
+++ b/test/remote-poll-logging.test.ts
@@ -1,74 +1,78 @@
-import type { SshApiClient } from '../src/store/modules/remote/api'
+// @vitest-environment jsdom
+import type { PropsWithChildren } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import { createElement } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { queryKeys } from '../src/config/query-keys'
+import { useRemote } from '../src/hooks/use-remote'
-// 本地实例不可达时的降级轮询:`refresh` 每 2 秒跑一轮,实例停着(插件操作会停服)时会
-// 连续失败几百轮。这里锁定「一轮降级只留一条日志」——每轮都带堆栈打一遍会把日志淹掉,
-// 而这行信息的增量是零。恢复之后再次不可达要能重新打一次,否则第二次故障看不见。
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
+vi.mock('@tauri-apps/api/core', () => ({ invoke }))
-const { bindSshApiForTests, remote } = await import('../src/store/modules/remote/store')
-
-const unreachable = (): Promise<never> => Promise.reject(new TypeError('Failed to fetch'))
+let client: QueryClient
+let failure: string | undefined
+let warn: ReturnType<typeof vi.spyOn>
-/** 只替换数据面:`bindSshApiForTests` 还要求 connect/disconnect(这些用例走不到)。 */
-function onlyListMachines(listMachines: SshApiClient['listMachines']) {
- return {
- listMachines,
- connect: async () => ({ tunnelBaseUrl: '' }),
- disconnect: async () => {},
- }
+function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client }, children)
}
-let warn: ReturnType<typeof vi.spyOn>
-
beforeEach(() => {
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })
+ failure = 'REMOTE_REQUEST_FAILED: connection refused'
+ invoke.mockReset().mockImplementation(async () => {
+ if (failure !== undefined)
+ throw failure
+ return { enabled: false, items: [] }
+ })
warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
- remote.available = true
- remote.refreshing = false
})
afterEach(() => {
+ cleanup()
+ client.clear()
vi.restoreAllMocks()
})
describe('remote poll logging', () => {
it('logs an unreachable instance once per outage, not once per poll', async () => {
- bindSshApiForTests(onlyListMachines(unreachable))
-
- await remote.refresh()
- await remote.refresh()
- await remote.refresh()
-
+ const { result } = renderHook(useRemote, { wrapper: Wrapper })
+ await waitFor(() => expect(result.current.available).toBe(false))
+ await act(async () => {
+ await result.current.refresh()
+ await result.current.refresh()
+ })
expect(warn).toHaveBeenCalledTimes(1)
- expect(remote.available).toBe(false)
+ expect(warn).toHaveBeenCalledWith('[remote] ssh api unreachable:', 'REMOTE_REQUEST_FAILED: connection refused')
})
it('logs again when a fresh outage follows a recovery', async () => {
- bindSshApiForTests(onlyListMachines(unreachable))
- await remote.refresh()
- await remote.refresh()
-
- bindSshApiForTests(onlyListMachines(async () => ({ enabled: false, machines: [] })))
- await remote.refresh()
- expect(remote.available).toBe(true)
+ const { result } = renderHook(useRemote, { wrapper: Wrapper })
+ await waitFor(() => expect(result.current.available).toBe(false))
+ await act(async () => {
+ await result.current.refresh()
+ })
+ failure = undefined
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.available).toBe(true))
expect(warn).toHaveBeenCalledTimes(1)
-
- bindSshApiForTests(onlyListMachines(unreachable))
- await remote.refresh()
-
+ failure = 'REMOTE_REQUEST_FAILED: connection refused'
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(result.current.available).toBe(false))
expect(warn).toHaveBeenCalledTimes(2)
})
it('does not log when the instance is reachable but has no SSH API', async () => {
- const { SshApiHttpError } = await import('../src/store/modules/remote/api')
- bindSshApiForTests(onlyListMachines(async () => {
- throw new SshApiHttpError(404)
- }))
-
- await remote.refresh()
-
- // 可达但没有 API 是「SSH 未启用」,不是不可达:不该产生降级日志
+ failure = 'REMOTE_API_MISSING: 404'
+ const { result } = renderHook(useRemote, { wrapper: Wrapper })
+ await waitFor(() => expect(client.getQueryState(queryKeys.remoteMachines)?.status).toBe('success'))
+ expect(result.current.available).toBe(true)
+ expect(result.current.enabled).toBe(false)
expect(warn).not.toHaveBeenCalled()
- expect(remote.available).toBe(true)
- expect(remote.enabled).toBe(false)
})
})
diff --git a/test/shell-csp.test.ts b/test/shell-csp.test.ts
index 73fb08c9..9e79cb51 100644
--- a/test/shell-csp.test.ts
+++ b/test/shell-csp.test.ts
@@ -2,11 +2,12 @@ import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
/**
- * 壳层自己(不是 iframe 里的网页)要跨源 POST 本地实例的 `/api-ssh`——远端机器
- * 切换器的秒级轮询走这条路。`connect-src` 漏掉本地实例来源时,fetch 被文档 CSP
- * 直接拒掉,控制台只刷「Refused to connect because it violates the document's
- * Content Security Policy」,切换器静默降级,功能整个不可用。端口因占用冲突会
- * 自动递增(见后端 runtime info),所以只能按 host 通配。
+ * 壳层与本地实例同属回环:远端机器在 `remote-*` 弹窗里以 `http://127.0.0.1:<port>`
+ * 作为文档来源,壳层也要放行本地实例来源。ssh 数据面已改走
+ * `@tauri-apps/plugin-http`(请求在内核侧发出,不受文档 CSP 约束),但 CSP 漏掉
+ * 本地实例来源仍会让 iframe/窗口加载被拒,控制台只刷「Refused to connect because
+ * it violates the document's Content Security Policy」。端口因占用冲突会自动递增
+ * (见后端 runtime info),所以只能按 host 通配。
*/
const config = JSON.parse(
readFileSync(new URL('../src-tauri/tauri.conf.json', import.meta.url), 'utf8'),
diff --git a/test/tooling-config.test.ts b/test/tooling-config.test.ts
index 0b334fdc..e14be15b 100644
--- a/test/tooling-config.test.ts
+++ b/test/tooling-config.test.ts
@@ -40,13 +40,11 @@ describe('tooling configuration contracts', () => {
it('each project retains its distinct setup, scheduling and timeout envelope', () => {
expect(unitConfig.test).toEqual({
name: 'unit',
- include: ['packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}', 'test/**/*.test.ts', 'src/**/*.test.ts'],
+ include: ['packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}', 'test/**/*.test.ts', 'src/**/*.test.{ts,tsx}'],
exclude: [
'**/node_modules/**',
'test/archive/**',
'archive/**',
- 'packages/dsh-tauri-ssh/src/client/components/**',
- 'packages/dsh-tauri-ssh/src/client/index.test.ts',
],
setupFiles: ['./test/setup/tauri-runtime.ts'],
maxWorkers: 4,
@@ -98,8 +96,10 @@ describe('tooling configuration contracts', () => {
['archive/contract.test.ts', []],
['source/contract.test.ts', []],
['packages/dsh-tauri/node_modules/copy/index.test.ts', []],
- ['packages/dsh-tauri-ssh/src/client/components/panel.test.tsx', []],
- ['packages/dsh-tauri-ssh/src/client/index.test.ts', []],
+ ['packages/dsh-tauri-ssh/src/client/components/panel.test.tsx', ['unit']],
+ ['packages/dsh-tauri-ssh/src/client/index.test.ts', ['unit']],
+ ['src/layout/components/remote-switcher.test.tsx', ['unit']],
+ ['src/layout/components/connect-dialog.test.tsx', ['unit']],
] as const
for (const [relative, projects] of cases) {
expect(runtime.projects.filter(project => project.matchesTestGlob(path.join(root, relative))).map(project => project.name), relative).toEqual(projects)
@@ -108,11 +108,18 @@ describe('tooling configuration contracts', () => {
expect(specs.filter(spec => spec.moduleId.endsWith('/test/tooling-config.test.ts')).map(spec => spec.project.name)).toEqual(['unit'])
expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/desktop/boot.e2e.ts')).map(spec => spec.project.name)).toEqual(['desktop'])
expect(specs.filter(spec => spec.moduleId.endsWith('/test/e2e/plugins/dsh-tauri.e2e.ts')).map(spec => spec.project.name)).toEqual(['plugin'])
+ for (const file of [
+ 'packages/dsh-tauri-ssh/src/client/components/machines-section.test.tsx',
+ 'packages/dsh-tauri-ssh/src/client/index.test.ts',
+ 'src/layout/components/remote-switcher.test.tsx',
+ 'src/layout/components/connect-dialog.test.tsx',
+ ]) {
+ expect(specs.filter(spec => spec.moduleId.replaceAll('\\', '/').endsWith(`/${file}`)).map(spec => spec.project.name), file).toEqual(['unit'])
+ }
for (const spec of specs) {
const relative = path.relative(root, spec.moduleId).replaceAll('\\', '/')
expect(relative).not.toMatch(/(^|\/)node_modules\//)
expect(relative).not.toMatch(/^(?:archive|source|test\/archive)\//)
- expect(relative).not.toMatch(/^packages\/dsh-tauri-ssh\/src\/client\/(?:components\/|index\.test\.ts$)/)
}
})
diff --git a/vitest.unit.config.ts b/vitest.unit.config.ts
index ada08935..8c90e198 100644
--- a/vitest.unit.config.ts
+++ b/vitest.unit.config.ts
@@ -10,18 +10,12 @@ export default defineProject({
include: [
'packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}',
'test/**/*.test.ts',
- 'src/**/*.test.ts',
+ 'src/**/*.test.{ts,tsx}',
],
exclude: [
'**/node_modules/**',
'test/archive/**',
'archive/**',
- // 渲染官方 UI primitives 的 ssh 组件套件需要包内 vitest.config 的
- // CSS 内联与 react 单副本别名(pnpm 下 primitives 嵌套 react@18),
- // 本 project 无此处理会挂载失败;这些套件由
- // `pnpm --filter dsh-tauri-ssh test` 全量执行。
- 'packages/dsh-tauri-ssh/src/client/components/**',
- 'packages/dsh-tauri-ssh/src/client/index.test.ts',
],
// 壳层模块在导入期就访问 Tauri API,node 下需要最小运行时垫片,见该文件说明。
setupFiles: ['./test/setup/tauri-runtime.ts'],