Skip to content

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

feat(remote): desktop shell integration — switcher, tunnel webview tint, popup bridge commands

Menghuan19183e9eb1c07e8d
diff --git a/package.json b/package.json
index 455c5742..9f348b87 100644
--- a/package.json
+++ b/package.json
@@ -85,6 +85,8 @@
"@tailwindcss/postcss": "catalog:build",
"@tailwindcss/vite": "catalog:build",
"@tauri-apps/cli": "catalog:tauri",
+ "@testing-library/dom": "catalog:testing",
+ "@testing-library/react": "catalog:testing",
"@types/node": "catalog:types",
"@types/react": "catalog:types",
"@types/react-dom": "catalog:types",
@@ -100,6 +102,7 @@
"dotenv": "catalog:utils",
"eslint": "catalog:lint",
"eslint-plugin-react-refresh": "catalog:lint",
+ "jsdom": "catalog:testing",
"knip": "catalog:lint",
"pathe": "catalog:utils",
"playwright": "catalog:testing",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5f66f231..a574c33e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -483,6 +483,12 @@ importers:
'@tauri-apps/cli':
specifier: catalog:tauri
version: 2.11.4
+ '@testing-library/dom':
+ specifier: catalog:testing
+ version: 10.4.1
+ '@testing-library/react':
+ specifier: catalog:testing
'@types/node':
specifier: catalog:types
version: 22.20.1
@@ -528,6 +534,9 @@ importers:
eslint-plugin-react-refresh:
specifier: catalog:lint
+ jsdom:
+ specifier: catalog:testing
+ version: 26.1.0
knip:
specifier: catalog:lint
version: 6.32.2
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
index 155b92a2..64ba54ca 100644
--- a/src-tauri/capabilities/default.json
+++ b/src-tauri/capabilities/default.json
@@ -1,10 +1,17 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
- "description": "Capability for the main window and embedded Harness GUI. The remote Harness origin is restricted to loopback, while the shell validates every cross-origin postMessage before servicing bridge requests. The service port is NOT fixed: it defaults to 3080/3081 but is user-configurable and advances to the next free port when the default is occupied (service/workflow::find_available_port).",
- "windows": ["main", "pet", "window-*"],
+ "description": "Capability for the main window and embedded Harness GUI. The remote Harness origin is restricted to loopback, while the shell validates every cross-origin postMessage before servicing bridge requests. The service port is NOT fixed: it defaults to 3080/3081 but is user-configurable and advances to the next free port when the default is occupied (service/workflow::find_available_port). The `remote-*` glob covers the SSH remote-machine popup windows (remote_open_window, loopback tunnel URLs only); `window-*` covers the File\u2192New Window shell windows.",
+ "windows": [
+ "main",
+ "pet",
+ "remote-*",
+ "window-*"
+ ],
"remote": {
- "urls": ["http://127.0.0.1:*"]
+ "urls": [
+ "http://127.0.0.1:*"
+ ]
},
"permissions": [
"core:default",
diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rs
index 75fb49a9..1a242336 100644
--- a/src-tauri/src/bridge/mod.rs
+++ b/src-tauri/src/bridge/mod.rs
@@ -14,6 +14,7 @@ pub mod pet;
pub mod plugin;
pub mod preset_pet;
pub mod profile;
+pub mod remote;
pub mod system_os;
pub mod updater;
@@ -26,5 +27,6 @@ pub use pet::*;
pub use plugin::*;
pub use preset_pet::*;
pub use profile::*;
+pub use remote::*;
pub use system_os::*;
pub use updater::*;
diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rs
new file mode 100644
index 00000000..d6152b65
--- /dev/null
+++ b/src-tauri/src/bridge/remote.rs
@@ -0,0 +1,146 @@
+//! bridge/remote.rs — SSH 远端机器的桌面集成命令(S5 桥契约 C-BRIDGE)。
+//!
+//! 引擎(机器存储/连接/隧道)全部住在 `dsh-tauri-ssh` 插件里,桌面壳不持有
+//! 任何机器状态;这里只暴露 iframe 内插件做不了的两件事:
+//!
+//! - `remote_open_window { machineId, url }`:打开(已开则聚焦)label 为
+//! `remote-<machineId>` 的专用 WebviewWindow,加载调用方传入的隧道 URL。
+//! URL 由插件经 `/api-ssh` 的连接状态给出(`http://127.0.0.1:<port>`),
+//! 命令侧再做一次回环校验(纵深防御:桥白名单之外的输入不可信)。
+//! - `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 tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};
+
+/// 弹窗窗口 label 前缀(与 capability 的 `remote-*` glob 对应)。
+const REMOTE_WINDOW_LABEL_PREFIX: &str = "remote-";
+
+/// 窗口 label 里仅允许的字符(Tauri label 字符集:字母数字与 `- _ / :`),
+/// 其余字符一律折叠为 `-`,避免任意 machineId 注入非法 label。
+fn sanitize_label_part(raw: &str) -> String {
+ raw.chars()
+ .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/' | ':') { c } else { '-' })
+ .collect()
+}
+
+/// 校验隧道 URL:仅接受回环 host 的明文 http(隧道由引擎建在
+/// `127.0.0.1:<port>`,见插件 `SshLink`;非回环/非 http 一律拒绝)。
+fn validate_loopback_http_url(raw: &str) -> Result<tauri::Url, String> {
+ let url: tauri::Url = raw
+ .parse()
+ .map_err(|err| format!("REMOTE_URL_INVALID: {err}"))?;
+ if url.scheme() != "http" {
+ return Err(format!(
+ "REMOTE_URL_INVALID: scheme must be http, got {:?}",
+ url.scheme()
+ ));
+ }
+ // url::Url 的 host_str 对 IPv6 保留方括号("[::1]"),比较前先剥掉。
+ let host = url.host_str().unwrap_or("");
+ let bare_host = host.trim_start_matches('[').trim_end_matches(']');
+ let is_loopback = matches!(bare_host, "127.0.0.1" | "::1" | "localhost");
+ if !is_loopback {
+ return Err(format!(
+ "REMOTE_URL_INVALID: only loopback hosts are allowed, got {:?}",
+ url.host_str()
+ ));
+ }
+ Ok(url)
+}
+
+/// 桥探测命令:iframe 内插件据此判定处于桌面壳(无参、恒成功)。
+#[tauri::command]
+pub fn remote_bridge_ping() -> String {
+ "ok".to_string()
+}
+
+/// 打开(已开则聚焦)`remote-<machineId>` 弹窗窗口,加载隧道 URL。
+///
+/// 壳不自存机器状态:URL 由插件随调用传入,此处只做回环校验。重复调用
+/// 聚焦已有窗口(不重复建窗);失败返回带前缀的可读错误,由调用方(S4
+/// 面板按钮)呈现。
+#[tauri::command]
+pub fn remote_open_window(
+ app_handle: AppHandle,
+ machine_id: String,
+ url: String,
+) -> Result<(), String> {
+ if machine_id.trim().is_empty() {
+ return Err("REMOTE_URL_INVALID: machineId must not be empty".to_string());
+ }
+ let parsed_url = validate_loopback_http_url(&url)?;
+ let label = format!(
+ "{}{}",
+ REMOTE_WINDOW_LABEL_PREFIX,
+ sanitize_label_part(&machine_id)
+ );
+ // 已有窗口:聚焦即可(再次「打开」同一机器的语义)。
+ if let Some(existing) = app_handle.get_webview_window(&label) {
+ let _ = existing.set_focus();
+ return Ok(());
+ }
+ WebviewWindowBuilder::new(
+ &app_handle,
+ &label,
+ WebviewUrl::External(parsed_url),
+ )
+ .title(format!("DSH Remote · {machine_id}"))
+ .inner_size(1280.0, 840.0)
+ .min_inner_size(720.0, 480.0)
+ .build()
+ .map(|_| ())
+ .map_err(|err| format!("REMOTE_WINDOW_FAILED: {err}"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{sanitize_label_part, validate_loopback_http_url};
+
+ #[test]
+ fn label_part_keeps_tauri_charset_and_folds_the_rest() {
+ assert_eq!(sanitize_label_part("abc-123"), "abc-123");
+ assert_eq!(sanitize_label_part("a_b/c:d"), "a_b/c:d");
+ // 空格、点、@ 等非法字符折叠为 '-',防止注入越权 label
+ assert_eq!(sanitize_label_part("a b.c@d"), "a-b-c-d");
+ assert_eq!(sanitize_label_part("机器"), "--");
+ }
+
+ #[test]
+ fn loopback_http_urls_pass_validation() {
+ for raw in [
+ "http://127.0.0.1:3080",
+ "http://127.0.0.1:49152/",
+ "http://localhost:3080",
+ "http://[::1]:3080",
+ ] {
+ let url = validate_loopback_http_url(raw)
+ .unwrap_or_else(|err| panic!("{raw} should pass: {err}"));
+ assert_eq!(url.scheme(), "http");
+ }
+ }
+
+ #[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", // 公网域名
+ "file:///etc/passwd", // 非 http scheme
+ "not a url", // 解析失败
+ "", // 空
+ ] {
+ let err = validate_loopback_http_url(raw)
+ .err()
+ .unwrap_or_else(|| panic!("{raw:?} should be rejected"));
+ assert!(
+ err.starts_with("REMOTE_URL_INVALID:"),
+ "error should carry the protocol prefix: {err}"
+ );
+ }
+ }
+}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index caa19c1a..ef2684f2 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -813,6 +813,18 @@ mod security_tests {
);
}
+ #[test]
+ fn remote_popup_windows_are_scoped_by_glob_and_stay_loopback() {
+ let capability = include_str!("../../capabilities/default.json");
+ // 弹窗窗口 label 为 remote-<machineId>(machineId 是 uuid),只能以
+ // glob 覆盖;不接受裸 "remote-" 或 "*" 之类的过度放宽。
+ assert!(capability.contains("\"remote-*\""));
+ assert!(!capability.contains("\"*\""));
+ // remote URL 面仍然只有 loopback 通配(弹窗与主窗口同一约束)。
+ let wildcard_loopback = ["http://127.0.0.1:", "*"].concat();
+ assert!(capability.contains(wildcard_loopback.as_str()));
+ }
+
#[test]
fn webview_security_features_are_not_disabled() {
let source = include_str!("builder.rs");
@@ -965,6 +977,8 @@ 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_bridge_ping,
+ crate::bridge::remote_open_window,
]
}
diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.ts
index a21b5632..6cfbb5e5 100644
--- a/src/hooks/use-invoke-iframe.ts
+++ b/src/hooks/use-invoke-iframe.ts
@@ -30,7 +30,11 @@ interface InvokeBridgeRequest {
/**
* 允许 iframe 桥调用的 Tauri command 白名单(与 dsh-tauri-pet 的
* client/apis/index.ts 一一对应)。凡新增可经桥调用的 command 必须在此登记,
- * 防止 iframe 内其他插件借道桥执行任意 Tauri command(越权)。
+ * 防止 iframe 内其他插件借道桥执行任意 Tauri command(越权)。另一类是
+ * SSH 远端机器桥契约(C-BRIDGE):`remote_bridge_ping` 无参探测(S4 面板
+ * 据此判定桌面环境,纯 web 超时隐藏弹窗按钮)、`remote_open_window`
+ * 打开/聚焦 `remote-<machineId>` 弹窗窗口(URL 由插件传入,命令侧仅接受
+ * 回环 http——见 src-tauri/src/bridge/remote.rs)。
*/
const ALLOWED_INVOKE_CMDS = new Set([
'get_pet_status',
@@ -42,6 +46,8 @@ const ALLOWED_INVOKE_CMDS = new Set([
'import_pet',
'get_pet_asset',
'list_preset_pets',
+ 'remote_bridge_ping',
+ 'remote_open_window',
])
export function useInvokeIframe(iframeRef: RefObject<HTMLIFrameElement | null>): void {
diff --git a/src/hooks/use-remote-machines.ts b/src/hooks/use-remote-machines.ts
new file mode 100644
index 00000000..95bd1408
--- /dev/null
+++ b/src/hooks/use-remote-machines.ts
@@ -0,0 +1,25 @@
+import { useEffect } from 'react'
+import { store } from '@/store'
+
+/**
+ * 远端机器数据面的组件侧装配:启动轮询(store 内幂等)并挂「窗口聚焦 /
+ * 页面可见」触发的即时刷新。卸载时只摘监听——轮询属于壳层生命周期,由
+ * store 持有(StrictMode 双挂载下 boot 只执行一次)。
+ */
+export function useRemoteMachines(): void {
+ useEffect(() => {
+ store.remote.boot()
+
+ function refreshNow() {
+ if (!document.hidden)
+ void store.remote.refresh()
+ }
+
+ window.addEventListener('focus', refreshNow)
+ document.addEventListener('visibilitychange', refreshNow)
+ return () => {
+ window.removeEventListener('focus', refreshNow)
+ document.removeEventListener('visibilitychange', refreshNow)
+ }
+ }, [])
+}
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index bff1c5bb..716f3b51 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -350,5 +350,17 @@
"recovery.reason.runtime.detail": "The plugin reported a runtime error. Removing it and continuing may resolve the issue.",
"recovery.reason.unknown.title": "A plugin failed during startup",
"recovery.reason.unknown.detail": "Harness reported an error while loading a plugin, but the exact cause could not be determined automatically.",
- "backup.size_unit": "MB"
+ "backup.size_unit": "MB",
+ "remote.switcher": "Remote machines",
+ "remote.local": "Local",
+ "remote.manage": "Manage machines",
+ "remote.manage_hint": "Add or manage machines in the web app: open Settings → SSH Remote Machines.",
+ "remote.empty": "No machines yet — add one from the web Settings → SSH Remote Machines panel.",
+ "remote.degraded": "Local instance unreachable — retrying",
+ "remote.state.disconnected": "Disconnected",
+ "remote.state.testing": "Testing",
+ "remote.state.connecting": "Connecting",
+ "remote.state.connected": "Connected",
+ "remote.state.reconnecting": "Reconnecting",
+ "remote.state.given-up": "Failed"
}
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 2a46b295..a2a717d3 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -350,5 +350,17 @@
"recovery.reason.runtime.detail": "该插件运行期上报了错误。卸载它并继续可能解决问题。",
"recovery.reason.unknown.title": "插件启动失败",
"recovery.reason.unknown.detail": "Harness 在加载插件时发生错误,但暂时无法自动判断更具体的原因。",
- "backup.size_unit": "MB"
+ "backup.size_unit": "MB",
+ "remote.switcher": "远端机器",
+ "remote.local": "本地",
+ "remote.manage": "管理机器",
+ "remote.manage_hint": "在网页端「设置 → SSH 远端机器」面板中添加或管理机器。",
+ "remote.empty": "还没有机器——在网页端「设置 → SSH 远端机器」面板添加。",
+ "remote.degraded": "本地实例不可达,正在重试",
+ "remote.state.disconnected": "未连接",
+ "remote.state.testing": "测试中",
+ "remote.state.connecting": "连接中",
+ "remote.state.connected": "已连接",
+ "remote.state.reconnecting": "重连中",
+ "remote.state.given-up": "已放弃"
}
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index 80900cf3..fb180751 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -26,6 +26,9 @@ 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 { RemoteManager } from './remote-manager'
+import { RemoteSwitcher } from './remote-switcher'
/**
* 壳层窗口顶部导航栏(44px,常驻):
@@ -154,6 +157,7 @@ export interface NavbarProps {
}
export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder }: NavbarProps) {
+ const [managerOpen, setManagerOpen] = useState(false)
const { t } = useTranslation()
const isFullscreen = useMacOSFullscreen()
// 只读取「dsh-tauri 插件是否已安装」;查询键与「插件」面板共用(同一份缓存),
@@ -365,6 +369,11 @@ export function Navbar({ sidebarCollapsed = false, onToggleSidebar, onNewChat, o
/>
</Button>
</If>
+ <If cond={onToggleSidebar != null}>
+ <RemoteSwitcher onManage={() => setManagerOpen(true)} />
+ <ConnectDialog />
+ <RemoteManager isOpen={managerOpen} onClose={() => setManagerOpen(false)} />
+ </If>
<If cond={!IS_MACOS}>
<div className="ml-1">
{/* 文件:新建窗口 / 新聊天 / 打开文件夹 / 关闭 / 退出。
diff --git a/src/layout/components/remote-switcher.test.tsx b/src/layout/components/remote-switcher.test.tsx
new file mode 100644
index 00000000..d84913c3
--- /dev/null
+++ b/src/layout/components/remote-switcher.test.tsx
@@ -0,0 +1,184 @@
+// @vitest-environment jsdom
+import type { SshMachineRow } from '@/store/modules/remote'
+import { 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 { RemoteSwitcher } from './remote-switcher'
+
+// jsdom 未实现 CSS.escape(react-aria 可选集合的焦点定位依赖);按 CSS 规范转义特殊字符
+if (typeof globalThis.CSS === 'undefined') {
+ Object.assign(globalThis, {
+ CSS: {
+ escape: (value: string) => value.replace(/[^\w-]/g, c => `\\${c}`),
+ },
+ })
+}
+
+// i18n 直通(key 即文案);toast 捕获调用参数
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+const toastSpy = vi.fn()
+vi.mock('@/utils/toast', () => ({
+ toast: (...args: unknown[]) => { toastSpy(...args) },
+}))
+
+function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
+ return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
+}
+
+/** 本轮引擎返回的机器列表(boot 的首次 refresh 会异步覆写 store,须同源)。 */
+let engineMachines: SshMachineRow[] = []
+/** 是否模拟本地实例不可达(/api-ssh 抛错 → 降级态)。 */
+let engineUnreachable = false
+
+function bindEngine() {
+ bindSshApiForTests({
+ listMachines: vi.fn(async () => {
+ if (engineUnreachable)
+ throw new Error('SSH_API_HTTP_503')
+ return engineMachines
+ }),
+ connect: vi.fn(async () => ({ tunnelBaseUrl: 'http://127.0.0.1:4001' })),
+ disconnect: vi.fn(async () => undefined),
+ })
+}
+
+/** 打开下拉并等待菜单出现在 portal 中。 */
+async function openMenu() {
+ fireEvent.click(screen.getByRole('button', { name: 'remote.switcher' }))
+ await waitFor(() => {
+ expect(screen.getByRole('menu')).toBeTruthy()
+ })
+ return screen.getByRole('menu')
+}
+
+/** 设定机器列表(store 与 mock 引擎同源,避免 boot 首刷覆写)。 */
+function seedMachines(machines: SshMachineRow[]) {
+ engineMachines = machines
+ remote.machines = machines
+}
+
+beforeEach(() => {
+ disposeRemoteForTests()
+ toastSpy.mockClear()
+ engineMachines = []
+ engineUnreachable = false
+ bindEngine()
+})
+
+afterEach(() => {
+ cleanup()
+ disposeRemoteForTests()
+ vi.restoreAllMocks()
+})
+
+describe('remoteSwitcher 渲染', () => {
+ it('空态:本地项 + 空态引导 + 管理入口(toast 引导到内嵌设置页)', async () => {
+ render(<RemoteSwitcher />)
+ await openMenu()
+ const menu = screen.getByRole('menu')
+ expect(within(menu).getByText('remote.local')).toBeTruthy()
+ expect(within(menu).getByText('remote.empty')).toBeTruthy()
+
+ fireEvent.click(within(menu).getByText('remote.manage'))
+ await waitFor(() => {
+ expect(toastSpy).toHaveBeenCalledWith('remote.manage_hint', {})
+ })
+ })
+
+ it('机器项:状态点语义(标识色优先内联 / 已连接绿 / 重连琥珀 / 放弃红)与状态文案', async () => {
+ seedMachines([
+ 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 />)
+ await openMenu()
+
+ const colored = screen.getByText('colored').closest('[class*="flex"]')?.querySelector('span')
+ expect(colored?.getAttribute('style')).toContain('rgb(255, 0, 255)')
+
+ const green = screen.getByText('green').closest('[class*="flex"]')?.querySelector('span')
+ expect(green?.className).toContain('bg-success')
+ expect(screen.getByText('remote.state.connected')).toBeTruthy()
+
+ const amber = screen.getByText('amber').closest('[class*="flex"]')?.querySelector('span')
+ expect(amber?.className).toContain('bg-warning')
+
+ const red = screen.getByText('red').closest('[class*="flex"]')?.querySelector('span')
+ expect(red?.className).toContain('bg-danger')
+ // 放弃态的原因入口(title 提示)
+ expect(screen.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 />)
+ 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()
+
+ remote.activeId = null
+ remote.activeTunnelUrl = ''
+ render(<RemoteSwitcher />)
+ expect(screen.getByRole('button', { name: 'remote.switcher' }).textContent).toContain('remote.local')
+ })
+})
+
+describe('remoteSwitcher 交互与降级', () => {
+ it('点击已连接机器项:切换视图(activeId/隧道 URL)', async () => {
+ seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
+ render(<RemoteSwitcher />)
+ 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')
+ })
+ })
+
+ 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 />)
+ 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()
+ })
+ })
+
+ it('本地实例不可达:降级提示 + 远端项禁用(不弹错误风暴),恢复后自动复原', async () => {
+ seedMachines([machineOf({ id: 'm1', name: 'alpha', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })])
+ engineUnreachable = true
+ render(<RemoteSwitcher />)
+ // boot 首刷即不可达 → 降级
+ await vi.waitFor(() => {
+ expect(remote.available).toBe(false)
+ })
+ 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')
+
+ // 轮询恢复(引擎重新可达):窗口聚焦触发的即时刷新让切换器立即复原
+ engineUnreachable = false
+ window.dispatchEvent(new Event('focus'))
+ await vi.waitFor(() => {
+ expect(remote.available).toBe(true)
+ })
+ await vi.waitFor(() => {
+ expect(screen.queryByText('remote.degraded')).toBeNull()
+ })
+ })
+})
diff --git a/src/layout/components/remote-switcher.tsx b/src/layout/components/remote-switcher.tsx
new file mode 100644
index 00000000..0a2ddfa8
--- /dev/null
+++ b/src/layout/components/remote-switcher.tsx
@@ -0,0 +1,120 @@
+import { Globe } from '@gravity-ui/icons'
+import { Button, Description, Dropdown, Label } 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 { useRemoteMachines } from '@/hooks/use-remote-machines'
+import { store } from '@/store'
+import { dotClassOf, dotStyleOf } from '@/store/modules/remote'
+import { toast } from '@/utils/toast'
+
+/**
+ * 导航栏远端机器切换器:本地实例 ↔ 各远端机器。
+ *
+ * 数据面全部来自本地实例 `/api-ssh`(`useRemoteMachines` 启动秒级轮询 +
+ * 聚焦刷新);点击已连接机器直接切换视图,点击未连接机器发起连接、就绪后
+ * 自动切换;点击「本地」回到本地实例(不断开远端)。机器的增删改与断开
+ * 入口在内嵌 web 设置页的 SSH 面板(本组件只提供引导)。
+ *
+ * 色点语义(S3 词汇表):机器标识色优先 → 已连接绿 → 重连/进行中琥珀 →
+ * 放弃红 → 其余中性灰;未连接行整体降不透明度。本地实例不可达时进入降级
+ * 态:远端项禁用 + 顶部提示,恢复后自动复原(轮询静默重试,不弹错误)。
+ */
+export function RemoteSwitcher() {
+ const { t } = useTranslation()
+ useRemoteMachines()
+ const { machines, activeId, available } = useStore(store.remote)
+
+ const activeMachine = machines.find(machine => machine.id === activeId)
+ const activeColor = activeMachine?.color
+
+ function handleManage() {
+ // 机器管理唯一入口 = 内嵌 web 设置页的 SSH 面板(web 应用无 URL 路由,
+ // 壳层无法深链,给出路径引导)
+ toast(t('remote.manage_hint'), {})
+ }
+
+ return (
+ <Dropdown>
+ <Button
+ className="rounded-lg h-6 text-xs px-1.5 ml-1 gap-1.5"
+ size="sm"
+ variant="ghost"
+ aria-label={t('remote.switcher')}
+ >
+ <Globe className={cn('size-3.5', !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-md w-64!">
+ <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>
+ <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')}
+ />
+ <Label>{t('remote.local')}</Label>
+ </span>
+ </Dropdown.Item>
+ <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 => (
+ <Dropdown.Item
+ key={machine.id}
+ className="rounded-md"
+ id={`remote-${machine.id}`}
+ textValue={machine.name}
+ isDisabled={!available}
+ onAction={() => { store.remote.switchTo(machine.id) }}
+ >
+ <span
+ title={machine.lastError}
+ className={cn(
+ 'flex w-full items-center gap-2',
+ machine.state === 'connected' ? '' : 'opacity-60',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn('size-1.5 shrink-0 rounded-full', dotClassOf(machine))}
+ style={dotStyleOf(machine)}
+ />
+ <Label className="min-w-0 truncate">{machine.name}</Label>
+ <Description className="ml-auto shrink-0">{t(`remote.state.${machine.state}`)}</Description>
+ </span>
+ </Dropdown.Item>
+ ))}
+ <Dropdown.Item
+ className="rounded-md"
+ id="remote-manage"
+ textValue={t('remote.manage')}
+ onAction={handleManage}
+ >
+ <Label>{t('remote.manage')}</Label>
+ </Dropdown.Item>
+ </Dropdown.Menu>
+ </Dropdown.Popover>
+ </Dropdown>
+ )
+}
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index fe00284b..f77206cb 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -4,6 +4,7 @@ import { useStore } from 'valtio-define'
import { useDshStyle } from '@/hooks/use-dsh-style'
import { useIframeMessage } from '@/hooks/use-iframe-message'
import { useIframePost } from '@/hooks/use-iframe-post'
+import { borderTintOf } from '@/store/modules/remote'
import { store } from '@/store'
import { Recovery } from '@/ui/plugin/recovery'
import { Iframe } from './iframe'
@@ -36,6 +37,11 @@ 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 remoteMode = activeTunnelUrl !== ''
+ const borderTint = remoteMode ? borderTintOf(machines.find(machine => machine.id === activeId)) : null
// 2. Iframe 消息通信监听
useIframeMessage<NavBridgeMessage>(iframeRef, (data) => {
@@ -56,7 +62,13 @@ export function Webview() {
case 'preinstall':
return <PreinstallSetup />
case 'ready':
- return <Iframe iframeRef={iframeRef} />
+ return (
+ <Iframe
+ iframeRef={iframeRef}
+ srcOverride={remoteMode ? activeTunnelUrl : null}
+ borderTint={borderTint}
+ />
+ )
default:
return <Setup />
}
diff --git a/src/store/index.ts b/src/store/index.ts
index 792a6476..c74b719f 100644
--- a/src/store/index.ts
+++ b/src/store/index.ts
@@ -3,6 +3,7 @@ import { harness } from './modules/harness'
import { harnessUpdater } from './modules/harness-updater'
import { preinstall } from './modules/preinstall'
import { recovery } from './modules/recovery'
+import { remote } from './modules/remote'
import { setting } from './modules/setting'
/**
@@ -23,4 +24,5 @@ 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
new file mode 100644
index 00000000..edde6883
--- /dev/null
+++ b/src/store/modules/remote/api.test.ts
@@ -0,0 +1,70 @@
+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' },
+ ],
+ discovered: [
+ { id: 'alias', name: 'alias-host', state: 'disconnected' },
+ ],
+}
+
+describe('createSshApiClient', () => {
+ it('listMachines 合并手动机器与别名机器并按名排序,丢掉缺字段的坏行', async () => {
+ const fetchFn = fakeFetch({
+ ok: true,
+ value: {
+ items: [...listValue.items, { id: '', name: 'bad', state: 'connected' }, { id: 'x' }],
+ discovered: listValue.discovered,
+ },
+ })
+ const client = createSshApiClient(fetchFn, () => 'http://127.0.0.1:3081')
+ const rows = await client.listMachines()
+ // 按 name 排序:alias-host < alpha < beta
+ expect(rows.map(row => row.id)).toEqual(['alias', 'a', 'b'])
+ expect(rows[2]).toMatchObject({ color: '#123456', tintBorder: true, tunnelBaseUrl: 'http://127.0.0.1:4002' })
+ // 请求形状: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('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 与网络失败都抛错(本地实例不可达)', 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')
+
+ 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
new file mode 100644
index 00000000..779723ff
--- /dev/null
+++ b/src/store/modules/remote/api.ts
@@ -0,0 +1,101 @@
+/**
+ * `/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`(面板之外的断开入口,预留给后续壳层动作)。
+ * fetch 与基础 URL 均可注入,便于单测与复用。
+ * @module store/remote/api
+ */
+
+import type { SshConnectionState, SshMachineListValue, SshMachineRow } 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>
+
+/** 本客户端面向壳层暴露的引擎动作。 */
+export interface SshApiClient {
+ /** `machine.list`:手动机器 + ~/.ssh/config 别名机器(已按名排序合并)。 */
+ listMachines: () => Promise<SshMachineRow[]>
+ /** `machine.connect`:阻塞到隧道就绪,返回隧道 URL。 */
+ connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>
+ /** `machine.disconnect`:主动断开(远端实例保持运行)。 */
+ disconnect: (machineId: string) => Promise<void>
+}
+
+/** 非法机器行兜底:缺 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 } : {},
+ 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 } : {},
+ }
+}
+
+/**
+ * 组一个 `/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),
+ })
+ if (!response.ok)
+ throw new Error(`SSH_API_HTTP_${response.status}`)
+ const envelope = await response.json() as SshApiResponse
+ 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 整序在不同环境不稳定)
+ return [...items, ...discovered].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
+ },
+ connect: machineId => call<{ tunnelBaseUrl: string }>('machine.connect', { machineId }),
+ disconnect: async (machineId) => {
+ await call<unknown>('machine.disconnect', { machineId })
+ },
+ }
+}
diff --git a/src/store/modules/remote/index.ts b/src/store/modules/remote/index.ts
new file mode 100644
index 00000000..eb4df098
--- /dev/null
+++ b/src/store/modules/remote/index.ts
@@ -0,0 +1,6 @@
+export { createSshApiClient } from './api'
+export type { SshApiClient, SshFetchFn } from './api'
+export { borderTintOf, dotClassOf, dotStyleOf, reconcileSwitcher } from './logic'
+export type { SwitcherTargets } from './logic'
+export { bindSshApiForTests, disposeRemoteForTests, remote } from './store'
+export type { SshConnectionState, SshMachineListValue, SshMachineRow } from './types'
diff --git a/src/store/modules/remote/logic.test.ts b/src/store/modules/remote/logic.test.ts
new file mode 100644
index 00000000..ff19bd2c
--- /dev/null
+++ b/src/store/modules/remote/logic.test.ts
@@ -0,0 +1,111 @@
+import type { SshMachineRow } from './types'
+import { describe, expect, it } from 'vitest'
+import { borderTintOf, dotClassOf, dotStyleOf, reconcileSwitcher } from './logic'
+
+function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
+ return {
+ id: 'm1',
+ name: 'machine',
+ state: 'disconnected',
+ ...partial,
+ }
+}
+
+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' })
+ }
+ })
+
+ it('无标识色时按状态给语义色:已连接绿、重连/进行中琥珀、放弃红、其余中性', () => {
+ expect(dotClassOf({ state: 'connected' })).toBe('bg-success')
+ expect(dotClassOf({ state: 'reconnecting' })).toBe('bg-warning')
+ expect(dotClassOf({ state: 'connecting' })).toBe('bg-warning')
+ 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()
+ })
+})
+
+describe('reconcileSwitcher(切换语义)', () => {
+ const idle = { activeId: null, pendingId: null, activeTunnelUrl: '' }
+
+ it('活动机器断开或放弃 → 自动回本地', () => {
+ for (const state of ['disconnected', 'given-up'] as const) {
+ const next = reconcileSwitcher(
+ { activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [machineOf({ id: 'm1', state })],
+ )
+ expect(next).toEqual(idle)
+ }
+ })
+
+ it('活动机器行消失(被删除)→ 回本地', () => {
+ const next = reconcileSwitcher(
+ { activeId: 'gone', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [],
+ )
+ expect(next).toEqual(idle)
+ })
+
+ it('重连窗口保持指向:粘性保留隧道 URL,不指向空端口', () => {
+ const next = reconcileSwitcher(
+ { activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [machineOf({ id: 'm1', state: 'reconnecting', nextRetryAt: 1 })],
+ )
+ expect(next).toEqual({ activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' })
+ })
+
+ it('重连恢复后采用最新隧道 URL(端口稳定策略下通常不变,变化则换 URL)', () => {
+ const same = reconcileSwitcher(
+ { activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4001' })],
+ )
+ expect(same.activeTunnelUrl).toBe('http://127.0.0.1:4001')
+
+ const moved = reconcileSwitcher(
+ { activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4009' })],
+ )
+ expect(moved.activeTunnelUrl).toBe('http://127.0.0.1:4009')
+ })
+
+ it('待切换机器就绪 → 升为活动;放弃或消失 → 撤销待切换留在本地', () => {
+ const promoted = reconcileSwitcher(
+ { activeId: null, pendingId: 'm1', activeTunnelUrl: '' },
+ [machineOf({ id: 'm1', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4002' })],
+ )
+ expect(promoted).toEqual({ activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4002' })
+
+ for (const machines of [
+ [machineOf({ id: 'm1', state: 'given-up', lastError: 'connect failed' })],
+ [],
+ ]) {
+ const next = reconcileSwitcher({ activeId: null, pendingId: 'm1', activeTunnelUrl: '' }, machines)
+ expect(next).toEqual(idle)
+ }
+ })
+
+ it('活动机器待重连时另一台机器就绪不抢切换(同一时刻一台活动机器)', () => {
+ const next = reconcileSwitcher(
+ { activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' },
+ [
+ machineOf({ id: 'm1', state: 'reconnecting' }),
+ machineOf({ id: 'm2', state: 'connected', tunnelBaseUrl: 'http://127.0.0.1:4003' }),
+ ],
+ )
+ expect(next).toEqual({ activeId: 'm1', pendingId: null, activeTunnelUrl: 'http://127.0.0.1:4001' })
+ })
+})
diff --git a/src/store/modules/remote/logic.ts b/src/store/modules/remote/logic.ts
new file mode 100644
index 00000000..7b2c7e63
--- /dev/null
+++ b/src/store/modules/remote/logic.ts
@@ -0,0 +1,101 @@
+/**
+ * 切换器与内容区着色的纯逻辑(无副作用,供 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
new file mode 100644
index 00000000..e37a24e4
--- /dev/null
+++ b/src/store/modules/remote/store.test.ts
@@ -0,0 +1,189 @@
+import type { SshMachineRow } from './types'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { bindSshApiForTests, disposeRemoteForTests, remote } from './store'
+
+function machineOf(partial: Partial<SshMachineRow>): SshMachineRow {
+ return { id: 'm1', name: 'machine', state: 'disconnected', ...partial }
+}
+
+/** 注入可编程 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 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.available).toBe(true)
+
+ // 本地实例不可达:fetch 抛错 → 降级但不清空列表(静默,不弹错误)
+ bindSshApiForTests({
+ listMachines: vi.fn(async () => { throw new Error('SSH_API_HTTP_503') }),
+ 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('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('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 () =>
+ [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 Error('SSH_API_HTTP_503') }),
+ 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()
+ })
+})
diff --git a/src/store/modules/remote/store.ts b/src/store/modules/remote/store.ts
new file mode 100644
index 00000000..eb762308
--- /dev/null
+++ b/src/store/modules/remote/store.ts
@@ -0,0 +1,163 @@
+/**
+ * 远端机器模块(壳层):机器列表轮询、iframe 切换目标(activeId/粘性隧道
+ * URL)与降级态。数据面完全来自本地实例 `/api-ssh`(dsh-tauri-ssh 插件,
+ * S1 契约)——壳不自存任何机器,连接/隧道/bootstrap 全部由插件引擎推进。
+ *
+ * 节奏(KISS,无推送通道):秒级轮询 + 窗口聚焦触发刷新(监听在组件侧
+ * hook 装配);本地实例不可达时进入降级态(保留列表、静默重试,不弹错误
+ * 风暴),恢复后自动复原。切换语义(断开回本地、重连粘性、就绪即切)由
+ * 纯函数 `reconcileSwitcher` 承担(见 logic.ts)。
+ * @module store/remote/store
+ */
+
+import type { SshMachineRow } from './types'
+import { defineStore } from 'valtio-define'
+import { harness } from '../harness'
+import { createSshApiClient } from './api'
+import { reconcileSwitcher } from './logic'
+
+/** 轮询间隔(毫秒):秒级即可让切换器跟上连接/重连状态流转。 */
+const POLL_INTERVAL_MS = 2000
+
+/** 模块级轮询句柄(与 harness store 的定时器管理模式一致)。 */
+let pollTimer: ReturnType<typeof setInterval> | undefined
+
+/** 数据面客户端:默认走全局 fetch 与 harness 的 serviceUrl(测试可替换)。 */
+let api = createSshApiClient(
+ (input, init) => fetch(input, init),
+ () => harness.$state.serviceUrl,
+)
+
+/** 测试注入口:替换数据面客户端并复位切换状态(仅测试使用)。 */
+export function bindSshApiForTests(client: {
+ listMachines: () => Promise<SshMachineRow[]>
+ connect: (machineId: string) => Promise<{ tunnelBaseUrl: string }>
+ disconnect: (machineId: string) => Promise<void>
+}): void {
+ api = client
+}
+
+export const remote = defineStore({
+ state: () => ({
+ /** 全部机器(手动机器 + ~/.ssh/config 别名,按名排序)。 */
+ machines: [] as SshMachineRow[],
+ /** iframe 当前指向的远端机器(null = 本地实例)。 */
+ activeId: null as string | null,
+ /** 点击未连接机器后待切换的目标(连接就绪后升为 activeId)。 */
+ pendingId: null as string | null,
+ /** 活动机器最近已知的隧道 URL(重连窗口粘性保留,避免指向空端口)。 */
+ activeTunnelUrl: '',
+ /** `/api-ssh` 是否可达;不可达时切换器降级(禁用远端项 + 提示)。 */
+ available: true,
+ /** 单飞标志:上一轮未完成时跳过本轮,避免请求堆积。 */
+ refreshing: false,
+ booted: false,
+ }),
+ actions: {
+ /** 首次挂载切换器时启动轮询(StrictMode 重复挂载下只执行一次)。 */
+ boot() {
+ if (this.booted)
+ return
+ this.booted = true
+ void this.refresh()
+ pollTimer = setInterval(() => {
+ void this.refresh()
+ }, POLL_INTERVAL_MS)
+ },
+
+ /** 拉取机器列表并推进切换语义;不可达时进入降级态(静默,保留列表)。 */
+ async refresh() {
+ if (this.refreshing)
+ return
+ this.refreshing = true
+ try {
+ const machines = await api.listMachines()
+ 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
+ this.available = true
+ }
+ catch (err) {
+ // 本地实例不可达(启动中/已停止):降级但保留既有列表,静默重试
+ console.warn('[remote] /api-ssh unreachable:', err)
+ this.available = false
+ }
+ finally {
+ this.refreshing = false
+ }
+ },
+
+ /**
+ * 切换视图:已连接直接切换;进行中(连接/重连)挂起等待;否则发起
+ * 连接(阻塞到隧道就绪,见 S1 契约——不会指向空端口)。
+ */
+ switchTo(machineId: string) {
+ 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 接管
+ this.pendingId = machineId
+ return
+ }
+ // disconnected / given-up:重新连接(given-up 可经再次 connect 退出)
+ this.pendingId = machineId
+ void this.connectAndSwitch(machineId)
+ },
+
+ /** 连接一台机器并在就绪后切换;失败留在本地(失败态由列表呈现)。 */
+ async connectAndSwitch(machineId: string) {
+ try {
+ const link = await api.connect(machineId)
+ 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
+ }
+ }
+ catch (err) {
+ console.warn('[remote] connect failed:', err)
+ this.pendingId = null
+ // 拉取引擎落定的失败态(given-up + lastError)供切换器呈现
+ void this.refresh()
+ }
+ },
+
+ /** 退回本地实例视图(不断开远端连接;同时撤销挂起中的切换)。 */
+ backToLocal() {
+ this.activeId = null
+ this.activeTunnelUrl = ''
+ this.pendingId = null
+ },
+ },
+})
+
+/** 停止轮询并复位(测试收尾用;壳层生命周期内不调用)。 */
+export function disposeRemoteForTests(): void {
+ if (pollTimer !== undefined) {
+ clearInterval(pollTimer)
+ pollTimer = undefined
+ }
+ remote.booted = false
+ remote.machines = []
+ remote.activeId = null
+ remote.pendingId = null
+ remote.activeTunnelUrl = ''
+ remote.available = true
+ remote.refreshing = false
+}
diff --git a/src/store/modules/remote/types.ts b/src/store/modules/remote/types.ts
new file mode 100644
index 00000000..19a5a6f2
--- /dev/null
+++ b/src/store/modules/remote/types.ts
@@ -0,0 +1,39 @@
+/**
+ * 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
+ state: SshConnectionState
+ /** 隧道就绪时的本地回环 URL(`http://127.0.0.1:<port>`)。 */
+ tunnelBaseUrl?: string
+ /** 最近一次失败的原因(given-up 时呈现入口)。 */
+ lastError?: string
+ /** 下次重连重试时间(epoch ms,reconnecting 时出现)。 */
+ nextRetryAt?: number
+}
+
+/** `machine.list` 的应答信封(items = 手动机器,discovered = ~/.ssh/config 别名)。 */
+export interface SshMachineListValue {
+ items: SshMachineRow[]
+ discovered: SshMachineRow[]
+}