Skip to content

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

feat(desktop): 会话右键在新窗口打开 (#1068)

Hairy820892be4fad
diff --git a/packages/dsh-tauri-rightclick/src/client/locales/index.ts b/packages/dsh-tauri-rightclick/src/client/locales/index.ts
index 33ac1461..16162472 100644
--- a/packages/dsh-tauri-rightclick/src/client/locales/index.ts
+++ b/packages/dsh-tauri-rightclick/src/client/locales/index.ts
@@ -2,6 +2,7 @@ import { defineLocale } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../constants'
const zh = {
+ openInNewWindow: '在新窗口打开',
renameSession: '重命名会话',
archiveSession: '归档会话',
openInExplorer: '在资源管理器中打开',
@@ -74,6 +75,7 @@ const zh = {
} as const satisfies Record<string, string>
const en: Record<keyof typeof zh, string> = {
+ openInNewWindow: 'Open in new window',
renameSession: 'Rename session',
archiveSession: 'Archive session',
openInExplorer: 'Open in File Explorer',
diff --git a/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.test.ts b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.test.ts
new file mode 100644
index 00000000..3d30c7b3
--- /dev/null
+++ b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.test.ts
@@ -0,0 +1,40 @@
+// @vitest-environment jsdom
+import type { SessionSummaryLike } from '../types'
+import type { MenuComposer } from './context-menu.types'
+import { afterEach, expect, it, vi } from 'vitest'
+import { buildSessionMenu } from './context-menu.menu'
+
+const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
+vi.mock('dsh-tauri/client', async importOriginal => ({
+ ...await importOriginal<typeof import('dsh-tauri/client')>(),
+ invoke,
+}))
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ invoke.mockReset()
+})
+
+it('only offers a desktop window in the shell and targets the clicked session without selecting it', async () => {
+ const actions = new Map<string, () => unknown>()
+ const open = vi.fn()
+ const composer = {
+ add: (label: string, action: () => unknown) => actions.set(label, action),
+ split: vi.fn(),
+ sessions: { open },
+ workspaces: {},
+ } as unknown as MenuComposer
+ const session = { id: 'clicked', title: 'Clicked session' } as SessionSummaryLike
+ const row = document.createElement('div')
+ buildSessionMenu(composer, row, session, null, [])
+ expect(actions.has('Open in new window')).toBe(false)
+ vi.stubGlobal('dshDesktop', {})
+ actions.clear()
+ buildSessionMenu(composer, row, session, null, [])
+ expect([...actions.keys()].slice(-2)).toEqual(['Open in new window', 'Refresh'])
+ await actions.get('Open in new window')?.()
+ expect(invoke).toHaveBeenCalledWith('create_app_window', { sessionId: 'clicked', iframeUrl: window.location.origin })
+ expect(open).not.toHaveBeenCalled()
+ invoke.mockRejectedValue(new Error('WINDOW_CREATE_FAILED'))
+ await expect(actions.get('Open in new window')?.()).rejects.toThrow('WINDOW_CREATE_FAILED')
+})
diff --git a/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
index cfd0a2d5..def33f69 100644
--- a/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
+++ b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
@@ -6,6 +6,7 @@ import type {
WorkspaceViewLike,
} from '../types'
import type { MenuComposer } from './context-menu.types'
+import { invoke } from 'dsh-tauri/client'
import { confirmDialog } from '../components/confirm-dialog'
import { locale } from '../locales'
import {
@@ -135,6 +136,12 @@ export function buildSessionMenu(
}
composer.split()
+ if (current && 'dshDesktop' in globalThis) {
+ composer.add(locale.text('openInNewWindow'), () => invoke<void>('create_app_window', {
+ sessionId: current.id,
+ iframeUrl: window.location.origin,
+ }))
+ }
composer.add(locale.text('refresh'), reload, shortcutLabel('R'))
}
diff --git a/packages/dsh-tauri/src/client/register/navigation.test.ts b/packages/dsh-tauri/src/client/register/navigation.test.ts
index 54e4fe0e..f073f17f 100644
--- a/packages/dsh-tauri/src/client/register/navigation.test.ts
+++ b/packages/dsh-tauri/src/client/register/navigation.test.ts
@@ -14,15 +14,16 @@ const CMD_NEW_SESSION = 'dsh://session:new'
const CMD_ADD_WORKSPACE = 'dsh://workspace:add'
/** 父窗口桥假实现:只保留 dispatch(宿主 → iframe 命令)。 */
-function stubHost(): { dispatch: (data: unknown) => void } {
+function stubHost(): { post: ReturnType<typeof vi.fn>, dispatch: (data: unknown) => void } {
const listeners = new Set<(event: MessageEvent) => void>()
- const parent = { postMessage: () => {} }
+ const parent = { postMessage: vi.fn() }
vi.stubGlobal('window', {
parent,
addEventListener: (_type: string, handler: (event: MessageEvent) => void) => listeners.add(handler),
removeEventListener: (_type: string, handler: (event: MessageEvent) => void) => listeners.delete(handler),
})
return {
+ post: parent.postMessage,
dispatch: (data) => {
for (const handler of [...listeners])
handler({ source: parent, data } as unknown as MessageEvent)
@@ -40,6 +41,50 @@ afterEach(() => {
})
describe('navigationFeature', () => {
+ it('waits for the existing target, opens it once and acknowledges without creating a session', async () => {
+ const host = stubHost()
+ let ids: string[] = []
+ let complete!: () => void
+ const openSession = vi.fn(() => new Promise<void>((resolve) => {
+ complete = resolve
+ }))
+ const startSession = vi.fn()
+ const dispose = navigationFeature.call(ctxWithServices({
+ sessions: { list: { getSnapshot: () => ({ ids }), subscribe: vi.fn() } },
+ uiWorkspace: { openSession, startSession },
+ }))
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ expect(openSession).not.toHaveBeenCalled()
+ ids = ['target', 'current']
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ expect(host.post).not.toHaveBeenCalled()
+ complete()
+ await vi.waitFor(() => expect(host.post).toHaveBeenCalledExactlyOnceWith({ type: 'dsh://session:opened', sessionId: 'target' }, '*'))
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ expect(host.post.mock.calls).toEqual([
+ [{ type: 'dsh://session:opened', sessionId: 'target' }, '*'],
+ [{ type: 'dsh://session:opened', sessionId: 'target' }, '*'],
+ ])
+ expect(openSession.mock.calls).toEqual([['target']])
+ expect(startSession).not.toHaveBeenCalled()
+ dispose()
+ })
+
+ it('reports a failed open and allows retrying the same session', async () => {
+ const host = stubHost()
+ const openSession = vi.fn().mockRejectedValueOnce(new Error('load failed')).mockResolvedValue(undefined)
+ const dispose = navigationFeature.call(ctxWithServices({
+ sessions: { list: { getSnapshot: () => ({ ids: ['target'] }), subscribe: vi.fn() } },
+ uiWorkspace: { openSession },
+ }))
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ await vi.waitFor(() => expect(host.post).toHaveBeenCalledWith({ type: 'dsh://session:opened', sessionId: 'target', error: 'Error: load failed' }, '*'))
+ host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+ await vi.waitFor(() => expect(openSession).toHaveBeenCalledTimes(2))
+ dispose()
+ })
+
it('dsh://session:new 走官方 startSession,其它 type 不触发', async () => {
const startSession = vi.fn()
const host = stubHost()
diff --git a/packages/dsh-tauri/src/client/register/navigation.ts b/packages/dsh-tauri/src/client/register/navigation.ts
index 8be1885d..6253cc68 100644
--- a/packages/dsh-tauri/src/client/register/navigation.ts
+++ b/packages/dsh-tauri/src/client/register/navigation.ts
@@ -11,6 +11,7 @@
* 逐字一致(只有本文件消费,按常量归属规则留在消费方)。
*/
import type { ClientContext, ParentMessage } from '../types'
+import { invokeParent } from '../service/invoke-parent'
import { listenParent } from '../service/listen-parent'
import { reportPluginError } from '../utils/error'
import { defineRegister } from './index'
@@ -22,7 +23,36 @@ const CMD_NEW_SESSION = 'dsh://session:new'
const CMD_ADD_WORKSPACE = 'dsh://workspace:add'
export const navigationFeature = defineRegister<ClientContext>((controller, _ctx, adapter) => {
+ let openingSession: string | undefined
+ let openedSession: string | undefined
controller.add(listenParent<ParentMessage>((data) => {
+ if (data.type === 'dsh://session:open' && typeof data.sessionId === 'string') {
+ const sessionId = data.sessionId
+ if (openedSession === sessionId) {
+ invokeParent({ type: 'dsh://session:opened', sessionId })
+ return
+ }
+ const list = adapter.sessionList()
+ if (openingSession === sessionId || !list?.ids.includes(sessionId) || !adapter.has('navigation.openSession'))
+ return
+ openingSession = sessionId
+ void (async () => {
+ try {
+ const outcome = adapter.openSession(sessionId)
+ if (outcome.status !== 'opened')
+ throw new Error(outcome.reason)
+ await outcome.value
+ openingSession = undefined
+ openedSession = sessionId
+ invokeParent({ type: 'dsh://session:opened', sessionId })
+ }
+ catch (error) {
+ openingSession = undefined
+ invokeParent({ type: 'dsh://session:opened', sessionId, error: String(error) })
+ }
+ })()
+ return
+ }
if (data.type === CMD_NEW_SESSION) {
// 目录选择器不可用 / 建工作区被拒等失败上报宿主插件面板,不影响后续命令。
void adapter.startSession().catch((error: unknown) => reportPluginError(error))
@@ -30,5 +60,5 @@ export const navigationFeature = defineRegister<ClientContext>((controller, _ctx
}
if (data.type === CMD_ADD_WORKSPACE)
void adapter.addWorkspace({ openSession: true }).catch((error: unknown) => reportPluginError(error))
- }, [CMD_NEW_SESSION, CMD_ADD_WORKSPACE]))
+ }, [CMD_NEW_SESSION, CMD_ADD_WORKSPACE, 'dsh://session:open']))
})
diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rs
index 7fbaee29..7a40e65d 100644
--- a/src-tauri/src/bridge/remote.rs
+++ b/src-tauri/src/bridge/remote.rs
@@ -199,7 +199,7 @@ pub fn remote_open_window(
// 桥脚本按窗口注入、(Windows)WebView2 共用数据目录等,远端窗口与本体
// 唯一区别是连接的后端。label 即机器寻址:前端 remote-<id> 自切换。
let title = format!("DSH Remote · {machine_id}");
- crate::desktop::builder::build_shell_window(&app_handle, label, &title)
+ crate::desktop::builder::build_shell_window(&app_handle, label, &title, "index.html".into())
.map(|_| ())
.map_err(|err| format!("REMOTE_WINDOW_FAILED: {err}"))
}
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index ad8d8ede..1c699ea0 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1162,12 +1162,13 @@ pub fn build_shell_window(
app: &tauri::AppHandle<Wry>,
label: String,
title: &str,
+ path: std::path::PathBuf,
) -> tauri::Result<tauri::WebviewWindow<Wry>> {
let app_handle = app.clone();
let webview_builder = with_shell_chrome(
app,
- WebviewWindowBuilder::new(app, label, WebviewUrl::App("index.html".into())).title(title),
+ WebviewWindowBuilder::new(app, label, WebviewUrl::App(path)).title(title),
)?;
// 非 Windows 平台没有 WebView2 的 FrameCreated/ContentLoading 流程,兼容桥、
@@ -1211,12 +1212,16 @@ pub fn build_shell_window(
}
/// 「文件 → 新建窗口」:`window-<N>` 序号 label,chrome 全部取 `build_shell_window`。
-pub fn build_extra_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::WebviewWindow<Wry>> {
+pub fn build_extra_window(
+ app: &tauri::AppHandle<Wry>,
+ path: std::path::PathBuf,
+) -> tauri::Result<tauri::WebviewWindow<Wry>> {
let sequence = EXTRA_WINDOW_SEQ.fetch_add(1, Ordering::SeqCst) + 1;
build_shell_window(
app,
format!("window-{sequence}"),
crate::desktop::product_name(app),
+ path,
)
}
diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rs
index f0c7b7b8..cbb2c227 100644
--- a/src-tauri/src/desktop/window.rs
+++ b/src-tauri/src/desktop/window.rs
@@ -120,12 +120,74 @@ pub fn on_page_load(
/// 异步命令(不占用主线程)是唯一安全的调用侧:`WebviewWindowBuilder::build()`
/// 需要主线程事件循环回包,主线程调用会死锁(与 `pet::ensure_pet_window` 同约束)。
#[tauri::command]
-pub async fn create_app_window(app_handle: AppHandle<Wry>) -> Result<(), String> {
- crate::desktop::builder::build_extra_window(&app_handle)
+pub async fn create_app_window(
+ app_handle: AppHandle<Wry>,
+ session_id: Option<String>,
+ iframe_url: Option<String>,
+) -> Result<(), String> {
+ let path = session_window_path(session_id.as_deref(), iframe_url.as_deref())?;
+ crate::desktop::builder::build_extra_window(&app_handle, path)
.map(|_| ())
.map_err(|error| format!("WINDOW_CREATE_FAILED: {error}"))
}
+fn session_window_path(
+ session_id: Option<&str>,
+ iframe_url: Option<&str>,
+) -> Result<std::path::PathBuf, String> {
+ let Some(session_id) = session_id else {
+ return Ok("index.html".into());
+ };
+ if session_id.trim().is_empty() || session_id.len() > 512 {
+ return Err("WINDOW_CREATE_FAILED: invalid sessionId".into());
+ }
+ let url = Url::parse(iframe_url.unwrap_or_default())
+ .map_err(|error| format!("WINDOW_CREATE_FAILED: invalid iframeUrl: {error}"))?;
+ if url.scheme() != "http"
+ || !matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]"))
+ || !url.username().is_empty()
+ || url.password().is_some()
+ || url.path() != "/"
+ || url.query().is_some()
+ || url.fragment().is_some()
+ {
+ return Err("WINDOW_CREATE_FAILED: iframeUrl must be a loopback HTTP origin".into());
+ }
+ let mut target = url.clone();
+ target
+ .query_pairs_mut()
+ .append_pair("sessionId", session_id)
+ .append_pair("iframeUrl", url.as_str());
+ Ok(format!("index.html#{}", target.query().unwrap_or_default()).into())
+}
+
+#[cfg(test)]
+mod session_window_tests {
+ use super::session_window_path;
+
+ #[test]
+ fn session_target_is_encoded_and_rejects_untrusted_urls() {
+ assert_eq!(
+ session_window_path(None, None).unwrap().to_str(),
+ Some("index.html")
+ );
+ assert_eq!(
+ session_window_path(Some("session &/?#"), Some("http://127.0.0.1:3080")).unwrap().to_str(),
+ Some("index.html#sessionId=session+%26%2F%3F%23&iframeUrl=http%3A%2F%2F127.0.0.1%3A3080%2F")
+ );
+ for url in [
+ "https://example.com",
+ "file:///x",
+ "http://localhost/api",
+ "http://u@localhost",
+ "http://localhost/?token=x",
+ ] {
+ assert!(session_window_path(Some("s1"), Some(url)).is_err());
+ }
+ assert!(session_window_path(Some(" "), Some("http://localhost:3080")).is_err());
+ }
+}
+
/// 壳层导航栏「文件 → 退出」:与托盘「退出」同语义,走 `exit(0)` 完整退出
/// (触发 `RunEvent::ExitRequested` 的主窗口几何保存与 `RunEvent::Exit` 的进程回收)。
#[tauri::command]
diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.ts
index 79481536..51d175e4 100644
--- a/src/hooks/use-invoke-iframe.ts
+++ b/src/hooks/use-invoke-iframe.ts
@@ -61,6 +61,7 @@ const ALLOWED_INVOKE_CMDS = new Set([
'list_preset_pets',
'remote_bridge_ping',
'remote_open_window',
+ 'create_app_window',
// 右键菜单「粘贴」的原生读取:WKWebView 的 navigator.clipboard.readText() 拿不到授权,
// 帧内据此命令读取系统剪贴板纯文本(命令侧无参、只读,见 bridge/clipboard.rs)。
'read_clipboard_text',
@@ -76,7 +77,7 @@ export function useInvokeIframe(iframeRef: RefObject<HTMLIFrameElement | null>):
return
}
const cmd = data.cmd
- const args = data.args
+ const args = cmd === 'create_app_window' ? { ...data.args, iframeUrl: origin } : data.args
const nonce = data.nonce ?? ''
function reply(payload: { ok: boolean, value?: unknown, error?: string }) {
diff --git a/src/hooks/use-remote.test.ts b/src/hooks/use-remote.test.ts
index f4e188f5..1f1276ee 100644
--- a/src/hooks/use-remote.test.ts
+++ b/src/hooks/use-remote.test.ts
@@ -49,6 +49,7 @@ beforeEach(() => {
listError = undefined
eventItems = []
windowInfo.label = 'main'
+ window.location.hash = ''
Object.assign(window, { __TAURI_INTERNALS__: {} })
disconnect.mockClear()
connect = vi.fn(async (id: string) => {
@@ -82,6 +83,22 @@ afterEach(() => {
})
describe('useRemote 查询、降级与启动寻址', () => {
+ it('session windows retain the target remote machine and can switch back to local', async () => {
+ windowInfo.label = 'window-2'
+ window.location.hash = new URLSearchParams({ sessionId: 'target', iframeUrl: 'http://127.0.0.1:4001/' }).toString()
+ 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()
+ act(() => result.current.backToLocal())
+ await act(async () => {
+ await result.current.refresh()
+ })
+ expect(result.current.activeId).toBeNull()
+ expect(result.current.activeTunnelUrl).toBe('')
+ })
+
it('刷新失败保留列表并降级,恢复后可用', async () => {
const { result } = await ready()
expect(result.current.machines.map(row => row.name)).toEqual(['alpha'])
diff --git a/src/hooks/use-remote.ts b/src/hooks/use-remote.ts
index d21ce4c8..fa211aca 100644
--- a/src/hooks/use-remote.ts
+++ b/src/hooks/use-remote.ts
@@ -23,7 +23,11 @@ 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
+ if (label.startsWith('remote-'))
+ return label.slice('remote-'.length) || null
+ const parameters = new URLSearchParams(window.location.hash.slice(1))
+ const url = parameters.has('sessionId') ? parameters.get('iframeUrl') : null
+ return url && URL.canParse(url) ? new URL(url).origin : null
}
export function useRemote() {
@@ -119,8 +123,9 @@ export function useRemote() {
})
useWatch([bootId, machinesQuery.data, available], () => {
- if (bootId !== null && available && enabled && machines.some(machine => machine.id === bootId))
- switchTo(bootId)
+ const target = machines.find(machine => machine.id === bootId || (machine.tunnelBaseUrl !== undefined && URL.canParse(machine.tunnelBaseUrl) && new URL(machine.tunnelBaseUrl).origin === bootId))?.id
+ if (target !== undefined && available && enabled)
+ switchTo(target)
}, { immediate: true })
useEventListener('focus', () => {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index a9a1689a..fbf05d53 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -1,4 +1,5 @@
{
+ "session.open_failed": "Could not load the selected session. Retry or check that it still exists",
"app.wordmark": "HARNESS",
"app.retry": "Retry",
"app.open_editor": "Open DeepSeek Harness",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 675eb771..93e2ff02 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "session.open_failed": "无法加载指定会话,请重试或检查会话是否仍然存在",
"app.wordmark": "HARNESS",
"app.retry": "重试",
"app.open_editor": "打开 DeepSeek Harness",
diff --git a/src/layout/components/webview.test.tsx b/src/layout/components/webview.test.tsx
new file mode 100644
index 00000000..39b1bfaa
--- /dev/null
+++ b/src/layout/components/webview.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+import type { IframeProps } from './iframe'
+import type { NavbarProps } from './navbar'
+import { act, cleanup, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { Webview } from './webview'
+
+const mocks = vi.hoisted(() => ({
+ navbar: vi.fn<(props: NavbarProps) => void>(),
+ shortcuts: { rows: [] },
+ setShortcuts: vi.fn(),
+}))
+
+vi.mock('@tauri-apps/api/window', () => ({ getCurrentWindow: () => ({ label: 'window-2' }) }))
+vi.mock('@tauri-apps/plugin-os', () => ({ type: () => 'windows' }))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
+vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))
+vi.mock('@/store', () => ({ store: { harness: { status: 'ready', serviceHealthy: true }, recovery: {} } }))
+vi.mock('@/hooks/use-appearance', () => ({ useAppearance: () => '' }))
+vi.mock('@/hooks/use-dsh-style', () => ({ useDshStyle: () => [{}] }))
+vi.mock('@/hooks/use-dsh-shortcuts', () => ({
+ DSH_VIEW_COMMANDS: [],
+ shortcutHint: vi.fn(),
+ useDshShortcuts: () => [mocks.shortcuts, mocks.setShortcuts],
+}))
+vi.mock('@/hooks/use-listen', () => ({ useListen: vi.fn() }))
+vi.mock('@/ui/plugin/recovery', () => ({ Recovery: () => null }))
+vi.mock('./setup', () => ({ Setup: () => null }))
+vi.mock('./setup-preinstall', () => ({ PreinstallSetup: () => null }))
+vi.mock('./navbar', () => ({
+ Navbar: (props: NavbarProps) => {
+ mocks.navbar(props)
+ return null
+ },
+}))
+vi.mock('./iframe', () => ({
+ Iframe: ({ iframeRef, srcOverride }: IframeProps) => (
+ <iframe key={srcOverride} ref={iframeRef} src={srcOverride ?? 'http://127.0.0.1:3081'} title="session" />
+ ),
+}))
+vi.mock('./loadable', () => ({ Loadable: () => <div data-testid="session-pending" /> }))
+
+function navbar() {
+ return mocks.navbar.mock.lastCall![0]
+}
+
+function acknowledge(frame: HTMLIFrameElement, sessionId: string) {
+ act(() => {
+ window.dispatchEvent(new MessageEvent('message', {
+ source: frame.contentWindow,
+ origin: 'http://127.0.0.1:4001',
+ data: { type: 'dsh://session:opened', sessionId },
+ }))
+ })
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ window.location.hash = new URLSearchParams({ sessionId: 'target', iframeUrl: 'http://127.0.0.1:4001/' }).toString()
+ mocks.navbar.mockClear()
+ mocks.setShortcuts.mockClear()
+})
+
+afterEach(() => {
+ cleanup()
+ window.location.hash = ''
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+})
+
+it('remote session windows retain the acknowledged frame until explicitly switching back to local', async () => {
+ render(<Webview />)
+ const frame = screen.getByTitle<HTMLIFrameElement>('session')
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage')
+ expect(frame.getAttribute('src')).toBe('http://127.0.0.1:4001')
+ expect(screen.queryByTestId('session-pending')).not.toBeNull()
+
+ act(() => navbar().onRemoteChange('', null))
+ expect(frame.getAttribute('src')).toBe('http://127.0.0.1:4001')
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(500)
+ })
+ expect(post).toHaveBeenCalledExactlyOnceWith({ source: 'dsh-desktop', type: 'dsh://session:open', sessionId: 'target' }, 'http://127.0.0.1:4001')
+
+ acknowledge(frame, 'other')
+ expect(screen.queryByTestId('session-pending')).not.toBeNull()
+ acknowledge(frame, 'target')
+ expect(screen.queryByTestId('session-pending')).toBeNull()
+ expect(frame.getAttribute('src')).toBe('http://127.0.0.1:4001')
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31000)
+ })
+ expect(post).toHaveBeenCalledTimes(1)
+
+ act(() => navbar().onRemoteChange('http://127.0.0.1:4001', null))
+ expect(screen.getByTitle('session')).toBe(frame)
+ act(() => navbar().onRemoteChange('', null))
+ expect(screen.getByTitle('session').getAttribute('src')).toBe('http://127.0.0.1:3081')
+})
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index 0b7c0cee..ead921af 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -1,9 +1,10 @@
import type { DshShortcutRow, DshViewCommand } from '@/hooks/use-dsh-shortcuts'
-import { useWatch } from '@reause/core'
+import { useIntervalFn, useTimeoutFn, useWatch } from '@reause/core'
import { invoke } from '@tauri-apps/api/core'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { type } from '@tauri-apps/plugin-os'
import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
import { useAppearance } from '@/hooks/use-appearance'
@@ -15,6 +16,7 @@ import { useListen } from '@/hooks/use-listen'
import { store } from '@/store'
import { Recovery } from '@/ui/plugin/recovery'
import { Iframe } from './iframe'
+import { Loadable } from './loadable'
import { REMOTE_SECTION, REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES } from './nav-bridge'
import { Navbar } from './navbar'
import { Setup } from './setup'
@@ -24,9 +26,20 @@ interface NavBridgeMessage {
type?: string
collapsed?: boolean
rows?: unknown
+ sessionId?: unknown
+ error?: unknown
}
export function Webview() {
+ const { t } = useTranslation()
+ const [sessionTarget] = useState(() => {
+ const parameters = new URLSearchParams(window.location.hash.slice(1))
+ const id = parameters.get('sessionId')
+ const url = parameters.get('iframeUrl')
+ return id ? { id, url: url && URL.canParse(url) ? new URL(url).origin : '' } : null
+ })
+ const [sessionPending, setSessionPending] = useState(sessionTarget !== null)
+ const [sessionError, setSessionError] = useState('')
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
const iframeRef = useRef<HTMLIFrameElement>(null)
const pendingSettingsTabRef = useRef<string | null>(null)
@@ -39,7 +52,9 @@ export function Webview() {
const { status, serviceHealthy } = useStore(store.harness)
const { recovery } = useStore(store.recovery)
const [remoteView, setRemoteView] = useState({ url: '', tint: null as string | null })
- const { url: activeTunnelUrl, tint: borderTint } = remoteView
+ const [sessionSource, setSessionSource] = useState(sessionTarget?.url ?? '')
+ const activeTunnelUrl = remoteView.url || sessionSource
+ const borderTint = remoteView.tint
const remoteMode = activeTunnelUrl !== ''
const live = status === 'ready' && (remoteMode || serviceHealthy)
@@ -65,6 +80,8 @@ export function Webview() {
useListen('macos-menu-rebuilt', syncViewMenu, { target: getCurrentWindow().label })
function handleRemoteChange(url: string, tint: string | null) {
+ if (url)
+ setSessionSource('')
setRemoteView({ url, tint })
}
@@ -77,13 +94,38 @@ export function Webview() {
function openLocalSettingsTab(tab: string) {
if (remoteMode) {
pendingSettingsTabRef.current = tab
+ setSessionSource('')
handleRemoteChange('', null)
return
}
openSettingsTab(tab)
}
+ const sessionPoll = useIntervalFn(() => {
+ if (sessionPending && !sessionError && live && sessionTarget)
+ post({ type: 'dsh://session:open', sessionId: sessionTarget.id })
+ }, 500, { immediate: false })
+ const sessionTimeout = useTimeoutFn(() => {
+ if (sessionPending)
+ setSessionError(t('session.open_failed'))
+ }, 30000, { immediate: false })
+ useWatch(live, (ready) => {
+ if (ready && sessionPending) {
+ sessionPoll.resume()
+ sessionTimeout.start()
+ }
+ }, { immediate: true })
+
useIframeMessage<NavBridgeMessage>(iframeRef, (data) => {
+ if (data.type === 'dsh://session:opened' && sessionTarget && data.sessionId === sessionTarget.id) {
+ sessionPoll.pause()
+ sessionTimeout.stop()
+ if (typeof data.error === 'string')
+ setSessionError(`${t('session.open_failed')}: ${data.error}`)
+ else
+ setSessionPending(false)
+ return
+ }
if (data.type === 'dsh://sidebar:collapsed') {
setSidebarCollapsed(Boolean(data.collapsed))
}
@@ -139,8 +181,22 @@ export function Webview() {
{/* 挂在 Iframe 外:启动页/预装引导/恢复页先于 Iframe 渲染,否则拿不到透明与调色板 token */}
<style>{appearanceCss}</style>
<Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />
- <div className="flex min-h-0 flex-1">
+ <div className="relative flex min-h-0 flex-1">
{renderContent()}
+ <If cond={sessionPending}>
+ <div className="absolute inset-0">
+ <Loadable
+ errorMsg={sessionError || undefined}
+ onRetry={sessionError
+ ? () => {
+ setSessionError('')
+ sessionPoll.resume()
+ sessionTimeout.start()
+ }
+ : undefined}
+ />
+ </div>
+ </If>
</div>
</main>
)