Skip to content

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

fix(desktop): 新窗口改用注入跳转信息打开会话 (#1115)

Hairy508c7d9f9616
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
index 3d30c7b3..a7b2399c 100644
--- 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
@@ -33,7 +33,7 @@ it('only offers a desktop window in the shell and targets the clicked session wi
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(invoke).toHaveBeenCalledWith('create_app_window', { sessionId: 'clicked' })
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 def33f69..28379869 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
@@ -139,7 +139,6 @@ export function buildSessionMenu(
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/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.ts
index 3f3ffd4f..6d4529e8 100644
--- a/packages/dsh-tauri/src/client/apply.test.ts
+++ b/packages/dsh-tauri/src/client/apply.test.ts
@@ -1,20 +1,14 @@
-/**
- * apply.test.ts — 装配入口的回归测试(broke-once 防线)。
- *
- * `5b3b9534` 重建时 `client/apply.ts` 连同四个注册器被整体删除,宿主侧发送方
- * (`src/layout/components/webview.tsx`、`iframe.tsx`)原地保留,结果「壳的收起侧边栏」
- * 等控件全部空转。这里锁住每条 effect 都被登记,且登记过程确实挂上了父窗口桥监听。
- */
import type { ClientContext, ParentMessage } from './types'
+import { Context } from '@deepseek-ai/cordis'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { apply } from './apply'
+import { apply, inject } from './index'
// effect 标签是 `ctx.effect` 的卸载日志标识:与 `client/apply.ts` 逐字一致。
const EXPECTED_LABELS = [
'dsh-tauri: appearance',
'dsh-tauri: style (sidebar background)',
'dsh-tauri: sidebar (toggle command + collapsed report)',
- 'dsh-tauri: navigation (new session, add workspace)',
+ 'dsh-tauri: navigation (session target, new session, add workspace)',
'dsh-tauri: zoom shortcuts (ctrl/cmd +/-/0)',
'dsh-tauri: sidebar tweaks (hide collapse toggle, center brand)',
'dsh-tauri: account sign-in (auto-open the authorize url)',
@@ -52,8 +46,15 @@ function stubEnv(): Harness {
const documentListeners = new Map<(event: KeyboardEvent) => void, string>()
const sent: ParentMessage[] = []
const parent = { postMessage: (message: ParentMessage) => sent.push(message) }
+ const storage = new Map<string, string>()
vi.stubGlobal('window', {
parent,
+ sessionStorage: {
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ storage.set(key, value)
+ },
+ },
addEventListener: (type: string, handler: (event: MessageEvent) => void) => windowListeners.set(handler, type),
removeEventListener: (_type: string, handler: (event: MessageEvent) => void) => windowListeners.delete(handler),
})
@@ -109,7 +110,7 @@ function stubEnv(): Harness {
}
}
-const disposers: (() => void)[] = []
+const disposers: (() => void | Promise<void>)[] = []
/** 最小客户端 ctx:effect 按 cordis 的 `callback.call(fiber)` 语义绑定 this。 */
function fakeCtx(labels: string[]): ClientContext {
@@ -121,6 +122,9 @@ function fakeCtx(labels: string[]): ClientContext {
disposers.push(dispose)
return dispose
},
+ inject(_names: string[], callback: (scoped: ClientContext) => void) {
+ callback(ctx as unknown as ClientContext)
+ },
layout: { toggleSidebar: () => {} },
// 可选服务读取(`ctx.get`)与属性同源:老核心没有 `shortcuts`,属性面也不存在。
get(name: string): unknown {
@@ -130,18 +134,90 @@ function fakeCtx(labels: string[]): ClientContext {
return ctx as unknown as ClientContext
}
+interface NavigationWindow {
+ __DSH_NAVIGATION__?: { sessionId?: unknown }
+}
+
+function injectSessionTarget(sessionId: string): void {
+ (window as unknown as NavigationWindow).__DSH_NAVIGATION__ = { sessionId }
+}
+
+function injectedSessionTarget(): unknown {
+ return (window as unknown as NavigationWindow).__DSH_NAVIGATION__
+}
+
beforeEach(() => {
vi.useFakeTimers()
})
-afterEach(() => {
+afterEach(async () => {
for (const dispose of disposers.splice(0))
- dispose()
+ await dispose()
+ vi.restoreAllMocks()
vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('apply', () => {
+ it('会话服务后到时仍能消费注入的目标会话,不创建新会话', async () => {
+ const env = stubEnv()
+ injectSessionTarget('target')
+ const ctx = new Context()
+ disposers.push(ctx.fiber.dispose)
+ const toggleSidebar = vi.fn()
+ ctx.provide('layout', { toggleSidebar })
+ ctx.provide('theme', {})
+ const bridge = await ctx.plugin({ inject, apply })
+ env.paint()
+ expect(env.sent).toContainEqual({ type: 'dsh://style', sidebar: null, marked: null, frame: null, colorScheme: 'light' })
+ env.dispatch({ type: 'dsh://sidebar:toggle' })
+ expect(toggleSidebar).toHaveBeenCalledTimes(1)
+ const openSession = vi.fn()
+ const create = vi.fn()
+ const startSession = vi.fn()
+
+ ctx.provide('sessions', {
+ list: { getSnapshot: () => ({ ids: ['target'] }), subscribe: vi.fn() },
+ create,
+ })
+ await bridge.await()
+ expect(injectedSessionTarget()).toBeUndefined()
+ ctx.provide('uiWorkspace', { openSession, startSession })
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(openSession.mock.calls).toEqual([['target']])
+ expect(create).not.toHaveBeenCalled()
+ expect(startSession).not.toHaveBeenCalled()
+ })
+
+ it('会话服务撤销再重建时不重复消费注入的目标会话', async () => {
+ const env = stubEnv()
+ injectSessionTarget('target')
+ const ctx = new Context()
+ disposers.push(ctx.fiber.dispose)
+ ctx.provide('layout', { toggleSidebar: vi.fn() })
+ ctx.provide('theme', {})
+ const sessions = { list: { getSnapshot: () => ({ ids: ['target'] }), subscribe: vi.fn() } }
+ const removeSessions = ctx.provide('sessions', sessions)
+ const openSession = vi.fn()
+ ctx.provide('uiWorkspace', { openSession })
+ const bridge = await ctx.plugin({ inject, apply })
+ expect(openSession).toHaveBeenCalledTimes(1)
+
+ await removeSessions()
+ ctx.provide('sessions', { ...sessions })
+ await bridge.await()
+ await vi.advanceTimersByTimeAsync(500)
+ expect(openSession).toHaveBeenCalledTimes(1)
+
+ await bridge.dispose()
+ expect(env.windowListeners()).toBe(0)
+ expect(env.documentListeners()).toBe(0)
+ expect(env.styles).toEqual([])
+ expect(env.pendingFrames()).toBe(0)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
it('独立浏览器跳过桌面 effect,不拦截原生缩放快捷键', () => {
const env = stubEnv()
Object.defineProperty(window, 'parent', { value: window })
@@ -210,7 +286,7 @@ describe('apply', () => {
expect(env.documentListeners()).toBe(2)
for (const dispose of disposers.splice(0))
- dispose()
+ await dispose()
await vi.waitFor(() => {
expect(env.windowListeners()).toBe(0)
expect(env.documentListeners()).toBe(0)
diff --git a/packages/dsh-tauri/src/client/apply.ts b/packages/dsh-tauri/src/client/apply.ts
index 30d7fe1a..368f5707 100644
--- a/packages/dsh-tauri/src/client/apply.ts
+++ b/packages/dsh-tauri/src/client/apply.ts
@@ -1,15 +1,3 @@
-/**
- * client/apply.ts — dsh-tauri 客户端插件体(browser half):纯消息桥 + 侧边栏视觉微调。
- *
- * 本插件是壳层宿主 → iframe 四条协议的唯一接收方,宿主侧的发送方分别是:
- * - `src/layout/components/webview.tsx`:`dsh://sidebar:toggle`、`dsh://session:new`、
- * `dsh://workspace:add`;
- * - `src/layout/components/iframe.tsx`:`dsh://zoom-shortcut`(iframe 内捕获后回报),
- * 以及插件错误上报 `dsh://plugin-error` 的落库端。
- *
- * 这些原先由桌面端注入的 `NAV_SHIM_JS` / `ZOOM_SHORTCUT_BRIDGE_JS` 承担,现在统一
- * 收敛到插件客户端;插件缺席时宿主控件只会空转,没有任何降级路径。
- */
import type { ClientContext } from './types'
import { accountSignInFeature } from './register/account'
import { registerAppearance } from './register/appearance'
@@ -20,25 +8,25 @@ import { sidebarTweaksFeature } from './register/sidebar-tweaks'
import { registerStyle } from './register/style'
import { zoomShortcutFeature } from './register/zoom-shortcut'
-/** effect 标签(只有本文件消费,按常量归属规则留在消费方)。 */
const SIDEBAR_TOGGLE_EFFECT = 'dsh-tauri: sidebar (toggle command + collapsed report)'
-const NAVIGATION_EFFECT = 'dsh-tauri: navigation (new session, add workspace)'
+const NAVIGATION_EFFECT = 'dsh-tauri: navigation (session target, new session, add workspace)'
const ZOOM_SHORTCUT_EFFECT = 'dsh-tauri: zoom shortcuts (ctrl/cmd +/-/0)'
const SIDEBAR_TWEAKS_EFFECT = 'dsh-tauri: sidebar tweaks (hide collapse toggle, center brand)'
const STYLE_EFFECT = 'dsh-tauri: style (sidebar background)'
const ACCOUNT_SIGN_IN_EFFECT = 'dsh-tauri: account sign-in (auto-open the authorize url)'
const APPEARANCE_EFFECT = 'dsh-tauri: appearance'
const SHORTCUTS_EFFECT = 'dsh-tauri: shortcuts (catalog report + edit commands)'
-/** 插件体:注册侧边栏桥、导航命令、缩放快捷键、账号登录接管与侧边栏 UI 微调。 */
+
export function apply(ctx: ClientContext): void {
- // issue #573:独立浏览器没有桌面宿主,保留原生侧栏控件与缩放快捷键。
if (typeof window === 'undefined' || typeof document === 'undefined' || window.parent === window)
return
ctx.effect(registerAppearance, APPEARANCE_EFFECT)
ctx.effect(registerStyle, STYLE_EFFECT)
ctx.effect(sidebarFeature, SIDEBAR_TOGGLE_EFFECT)
- ctx.effect(navigationFeature, NAVIGATION_EFFECT)
+ ctx.inject(['sessions'], (scoped) => {
+ scoped.effect(navigationFeature, NAVIGATION_EFFECT)
+ })
ctx.effect(zoomShortcutFeature, ZOOM_SHORTCUT_EFFECT)
ctx.effect(sidebarTweaksFeature, SIDEBAR_TWEAKS_EFFECT)
ctx.effect(accountSignInFeature, ACCOUNT_SIGN_IN_EFFECT)
diff --git a/packages/dsh-tauri/src/client/register/navigation.test.ts b/packages/dsh-tauri/src/client/register/navigation.test.ts
index 45eb32cf..278b0924 100644
--- a/packages/dsh-tauri/src/client/register/navigation.test.ts
+++ b/packages/dsh-tauri/src/client/register/navigation.test.ts
@@ -1,29 +1,36 @@
-/**
- * register/navigation.test.ts — 宿主「文件」菜单两条命令的回归测试。
- *
- * 锁住的契约(`src/layout/components/webview.tsx` 是发送方):
- * `dsh://session:new` → 官方新建会话入口;`dsh://workspace:add` → 选目录 + 建工作区 +
- * 开新会话。官方能力缺席时退级为点官方按钮(DOM 路径),两边都不可用才告警。
- */
import type { ClientContext } from '../types'
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { navigationFeature } from './navigation'
-// 协议字面量按宿主侧 `src/layout/components/webview.tsx` 逐字写死。
const CMD_NEW_SESSION = 'dsh://session:new'
const CMD_ADD_WORKSPACE = 'dsh://workspace:add'
+const NAVIGATION_GLOBAL = '__DSH_NAVIGATION__'
-/** 父窗口桥假实现:只保留 dispatch(宿主 → iframe 命令)。 */
-function stubHost(): { post: ReturnType<typeof vi.fn>, dispatch: (data: unknown) => void } {
+interface Host {
+ post: ReturnType<typeof vi.fn>
+ window: Record<string, unknown>
+ dispatch: (data: unknown) => void
+}
+
+function stubHost(): Host {
const listeners = new Set<(event: MessageEvent) => void>()
const parent = { postMessage: vi.fn() }
- vi.stubGlobal('window', {
+ const storage = new Map<string, string>()
+ const host: Record<string, unknown> = {
parent,
+ sessionStorage: {
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ storage.set(key, value)
+ },
+ },
addEventListener: (_type: string, handler: (event: MessageEvent) => void) => listeners.add(handler),
removeEventListener: (_type: string, handler: (event: MessageEvent) => void) => listeners.delete(handler),
- })
+ }
+ vi.stubGlobal('window', host)
return {
post: parent.postMessage,
+ window: host,
dispatch: (data) => {
for (const handler of [...listeners])
handler({ source: parent, data } as unknown as MessageEvent)
@@ -31,66 +38,135 @@ function stubHost(): { post: ReturnType<typeof vi.fn>, dispatch: (data: unknown)
}
}
-/** ctx 只暴露适配层要探测的服务名(`readService` 优先走 ctx.get)。 */
function ctxWithServices(services: Record<string, unknown>): ClientContext {
return { get: (name: string) => services[name] } as unknown as ClientContext
}
+function stubSessions(ids: () => string[], subscribe = vi.fn()) {
+ return { list: { getSnapshot: () => ({ ids: ids() }), subscribe } }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+})
+
afterEach(() => {
+ vi.useRealTimers()
vi.unstubAllGlobals()
})
describe('navigationFeature', () => {
- it('waits for the existing target, opens it once and acknowledges without creating a session', async () => {
+ it('会话列表就绪后消费一次性注入的跳转目标,并清除注入载荷', async () => {
const host = stubHost()
+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target' }
let ids: string[] = []
- let complete!: () => void
- const openSession = vi.fn(() => new Promise<void>((resolve) => {
- complete = resolve
+ const openSession = vi.fn()
+
+ const dispose = navigationFeature.call(ctxWithServices({
+ sessions: stubSessions(() => ids),
+ uiWorkspace: { openSession },
}))
- const startSession = vi.fn()
+
+ expect(host.window[NAVIGATION_GLOBAL]).toBeUndefined()
+ expect(openSession).not.toHaveBeenCalled()
+
+ ids = ['other', 'target']
+ await vi.advanceTimersByTimeAsync(500)
+ expect(openSession).toHaveBeenCalledExactlyOnceWith('target')
+
+ await vi.advanceTimersByTimeAsync(31_000)
+ expect(openSession).toHaveBeenCalledOnce()
+ expect(host.post).not.toHaveBeenCalled()
+ dispose()
+ expect(vi.getTimerCount()).toBe(0)
+ })
+
+ it('同一窗口的帧内重载不再重复打开已消费的跳转目标', async () => {
+ const host = stubHost()
+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target' }
+ const openSession = vi.fn()
+ const services = {
+ sessions: stubSessions(() => ['target']),
+ uiWorkspace: { openSession },
+ }
+
+ const dispose = navigationFeature.call(ctxWithServices(services))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(openSession).toHaveBeenCalledOnce()
+ dispose()
+
+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target' }
+ const reloaded = navigationFeature.call(ctxWithServices(services))
+ await vi.advanceTimersByTimeAsync(31_000)
+ expect(openSession).toHaveBeenCalledOnce()
+ expect(host.post).not.toHaveBeenCalled()
+ reloaded()
+ })
+
+ it('没有注入载荷时不打开任何会话', async () => {
+ const host = stubHost()
+ const openSession = vi.fn()
+
const dispose = navigationFeature.call(ctxWithServices({
- sessions: { list: { getSnapshot: () => ({ ids }), subscribe: vi.fn() } },
- uiWorkspace: { openSession, startSession },
+ sessions: stubSessions(() => ['target']),
+ uiWorkspace: { openSession },
}))
- host.dispatch({ type: 'dsh://session:open', sessionId: 'target' })
+
+ await vi.advanceTimersByTimeAsync(31_000)
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 () => {
+ it('目标会话始终缺席时上报插件错误而不是静默半工作', async () => {
+ const host = stubHost()
+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'missing' }
+ const openSession = vi.fn()
+
+ const dispose = navigationFeature.call(ctxWithServices({
+ sessions: stubSessions(() => ['target']),
+ uiWorkspace: { openSession },
+ }))
+ await vi.advanceTimersByTimeAsync(30_000)
+
+ expect(openSession).not.toHaveBeenCalled()
+ expect(host.post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'dsh://plugin-error',
+ error: expect.stringContaining('missing'),
+ action: 'runtime',
+ }),
+ '*',
+ )
+ dispose()
+ })
+
+ it('打开会话失败时上报插件错误', async () => {
const host = stubHost()
- const openSession = vi.fn().mockRejectedValueOnce(new Error('load failed')).mockResolvedValue(undefined)
+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target' }
+ const openSession = vi.fn(() => Promise.reject(new Error('load failed')))
+
const dispose = navigationFeature.call(ctxWithServices({
- sessions: { list: { getSnapshot: () => ({ ids: ['target'] }), subscribe: vi.fn() } },
+ sessions: stubSessions(() => ['target']),
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))
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(host.post).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'dsh://plugin-error',
+ error: 'Error: load failed',
+ }),
+ '*',
+ )
dispose()
})
it('dsh://session:new 走官方 startSession,其它 type 不触发', async () => {
- const startSession = vi.fn()
const host = stubHost()
- const ctx = ctxWithServices({ uiWorkspace: { startSession } })
+ const startSession = vi.fn()
+ const dispose = navigationFeature.call(ctxWithServices({ uiWorkspace: { startSession } }))
- const dispose = navigationFeature.call(ctx)
host.dispatch({ type: 'dsh://other' })
host.dispatch({ type: CMD_NEW_SESSION })
@@ -103,9 +179,8 @@ describe('navigationFeature', () => {
const pickDirectory = vi.fn(async () => 'C:/ws')
const create = vi.fn(async () => ({ workspaceId: 'ws-1' }))
const host = stubHost()
- const ctx = ctxWithServices({ workspaces: { create }, uiWorkspace: { startSession, pickDirectory } })
+ const dispose = navigationFeature.call(ctxWithServices({ workspaces: { create }, uiWorkspace: { startSession, pickDirectory } }))
- const dispose = navigationFeature.call(ctx)
host.dispatch({ type: CMD_ADD_WORKSPACE })
await vi.waitFor(() => expect(create).toHaveBeenCalledWith({ path: 'C:/ws' }))
@@ -121,9 +196,8 @@ describe('navigationFeature', () => {
}),
})
const host = stubHost()
- const ctx = ctxWithServices({})
+ const dispose = navigationFeature.call(ctxWithServices({}))
- const dispose = navigationFeature.call(ctx)
host.dispatch({ type: CMD_NEW_SESSION })
host.dispatch({ type: CMD_ADD_WORKSPACE })
diff --git a/packages/dsh-tauri/src/client/register/navigation.ts b/packages/dsh-tauri/src/client/register/navigation.ts
index 6253cc68..2f952eed 100644
--- a/packages/dsh-tauri/src/client/register/navigation.ts
+++ b/packages/dsh-tauri/src/client/register/navigation.ts
@@ -1,17 +1,5 @@
-/**
- * register/navigation.ts — 宿主「文件」菜单的两条命令(宿主 → iframe):
- *
- * - `dsh://session:new`(新聊天):官方「新建会话」同款入口;
- * - `dsh://workspace:add`(打开文件夹):官方「添加工作区」流程
- * (选目录 → 建工作区 → 在新工作区开会话)。
- *
- * 两条命令都只**调用**官方能力,不复制官方 UI:跨核心版本的服务形态漂移全部收在
- * 适配层(`register/index.adapter.ts`),能力缺席时由适配层退级到点官方按钮,
- * 两边都不可用才告警 —— 绝不静默半工作。协议字面量与 `src/layout/components/webview.tsx`
- * 逐字一致(只有本文件消费,按常量归属规则留在消费方)。
- */
import type { ClientContext, ParentMessage } from '../types'
-import { invokeParent } from '../service/invoke-parent'
+import type { ClientAdapter, RegisterController } from './index'
import { listenParent } from '../service/listen-parent'
import { reportPluginError } from '../utils/error'
import { defineRegister } from './index'
@@ -22,37 +10,90 @@ const CMD_NEW_SESSION = 'dsh://session:new'
/** 宿主 → iframe:打开文件夹命令。 */
const CMD_ADD_WORKSPACE = 'dsh://workspace:add'
+/** 壳层建窗时注入的跳转信息全局名(与 `src-tauri/src/desktop/window.rs` 逐字一致)。 */
+const NAVIGATION_GLOBAL = '__DSH_NAVIGATION__'
+
+/** 同一 webview 已消费过的跳转目标:脚本在 iframe 重载时会再次注入,不能重复切回旧会话。 */
+const NAVIGATION_CONSUMED_KEY = '__DSH_NAVIGATION_CONSUMED__'
+
+const NAVIGATION_POLL_MS = 500
+const NAVIGATION_TIMEOUT_MS = 30_000
+
+interface InjectedNavigation {
+ sessionId?: unknown
+}
+
+function injectedSessionConsumed(sessionId: string): boolean {
+ try {
+ return window.sessionStorage.getItem(NAVIGATION_CONSUMED_KEY) === sessionId
+ }
+ catch {
+ return false
+ }
+}
+
+function markInjectedSessionConsumed(sessionId: string): void {
+ try {
+ window.sessionStorage.setItem(NAVIGATION_CONSUMED_KEY, sessionId)
+ }
+ catch {
+ // 存储不可用时退化为「每个文档内只消费一次」,不阻断本次打开。
+ }
+}
+
+function takeInjectedSession(): string | undefined {
+ const host = window as unknown as Record<string, unknown>
+ const payload = host[NAVIGATION_GLOBAL] as InjectedNavigation | undefined
+ if (payload === undefined)
+ return undefined
+ delete host[NAVIGATION_GLOBAL]
+ const sessionId = typeof payload === 'object' && payload !== null ? payload.sessionId : undefined
+ if (typeof sessionId !== 'string' || sessionId.trim() === '' || injectedSessionConsumed(sessionId))
+ return undefined
+ return sessionId
+}
+
+function consumeInjectedSession(controller: RegisterController, adapter: ClientAdapter, sessionId: string): void {
+ let settled = false
+ let cancelPoll = () => {}
+ let cancelTimeout = () => {}
+
+ function settle(error?: unknown): void {
+ if (settled)
+ return
+ settled = true
+ cancelPoll()
+ cancelTimeout()
+ if (error !== undefined)
+ reportPluginError(error)
+ }
+
+ function open(): void {
+ if (settled)
+ return
+ const list = adapter.sessionList()
+ if (list === undefined || !list.ids.includes(sessionId) || !adapter.has('navigation.openSession'))
+ return
+ settle()
+ void (async () => {
+ const outcome = adapter.openSession(sessionId)
+ if (outcome.status !== 'opened')
+ throw new Error(outcome.reason)
+ await outcome.value
+ markInjectedSessionConsumed(sessionId)
+ })().catch((error: unknown) => reportPluginError(error))
+ }
+
+ cancelPoll = controller.interval(open, NAVIGATION_POLL_MS)
+ cancelTimeout = controller.timeout(
+ () => settle(`dsh-tauri: session ${sessionId} was not opened (missing from the list or no openSession capability)`),
+ NAVIGATION_TIMEOUT_MS,
+ )
+ open()
+}
+
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))
@@ -60,5 +101,9 @@ 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, 'dsh://session:open']))
+ }, [CMD_NEW_SESSION, CMD_ADD_WORKSPACE]))
+
+ const sessionId = takeInjectedSession()
+ if (sessionId !== undefined)
+ consumeInjectedSession(controller, adapter, sessionId)
})
diff --git a/src-tauri/src/bridge/profile.rs b/src-tauri/src/bridge/profile.rs
index 714c07b1..db55f051 100644
--- a/src-tauri/src/bridge/profile.rs
+++ b/src-tauri/src/bridge/profile.rs
@@ -166,7 +166,7 @@ mod tests {
(
include_str!("../desktop/window.rs"),
"pub async fn create_app_window(",
- "fn session_window_path(",
+ "pub fn quit_app(",
),
(
include_str!("remote.rs"),
diff --git a/src-tauri/src/bridge/remote.rs b/src-tauri/src/bridge/remote.rs
index ad3a3b0d..d45fd77c 100644
--- a/src-tauri/src/bridge/remote.rs
+++ b/src-tauri/src/bridge/remote.rs
@@ -225,12 +225,18 @@ pub async fn remote_open_window(
.query_pairs_mut()
.append_pair("remoteMachineId", &machine_id);
let path = format!("index.html#{}", route.query().unwrap_or_default());
- crate::desktop::builder::build_shell_window(&app_handle, label.clone(), &title, path.into())
- .map(|_| ())
- .inspect_err(|_| {
- crate::service::workflow::instances::release_window(&label);
- })
- .map_err(|err| format!("REMOTE_WINDOW_FAILED: {err}"))
+ crate::desktop::builder::build_shell_window(
+ &app_handle,
+ label.clone(),
+ &title,
+ path.into(),
+ None,
+ )
+ .map(|_| ())
+ .inspect_err(|_| {
+ crate::service::workflow::instances::release_window(&label);
+ })
+ .map_err(|err| format!("REMOTE_WINDOW_FAILED: {err}"))
}
#[cfg(test)]
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 3c77a855..bc727fcb 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -1185,6 +1185,7 @@ pub fn build_shell_window(
label: String,
title: &str,
path: std::path::PathBuf,
+ navigation_script: Option<&str>,
) -> tauri::Result<tauri::WebviewWindow<Wry>> {
let app_handle = app.clone();
@@ -1192,6 +1193,10 @@ pub fn build_shell_window(
app,
WebviewWindowBuilder::new(app, label, WebviewUrl::App(path)).title(title),
)?;
+ let webview_builder = match navigation_script {
+ Some(script) => webview_builder.initialization_script_for_all_frames(script),
+ None => webview_builder,
+ };
// 非 Windows 平台没有 WebView2 的 FrameCreated/ContentLoading 流程,兼容桥、
// 通知桥、剪贴板图片桥、帧内日志桥与 boot 探测桥必须按窗口重新注入(与主窗口一致)。
@@ -1238,11 +1243,18 @@ pub fn build_extra_window(
app: &tauri::AppHandle<Wry>,
path: std::path::PathBuf,
profile: &str,
+ navigation_script: Option<&str>,
) -> tauri::Result<tauri::WebviewWindow<Wry>> {
let sequence = EXTRA_WINDOW_SEQ.fetch_add(1, Ordering::SeqCst) + 1;
let label = format!("window-{sequence}");
crate::service::workflow::instances::bind_window(&label, profile);
- let result = build_shell_window(app, label.clone(), crate::desktop::product_name(app), path);
+ let result = build_shell_window(
+ app,
+ label.clone(),
+ crate::desktop::product_name(app),
+ path,
+ navigation_script,
+ );
if result.is_err() {
crate::service::workflow::instances::release_window(&label);
}
diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rs
index 3f1804da..43b48eb3 100644
--- a/src-tauri/src/desktop/window.rs
+++ b/src-tauri/src/desktop/window.rs
@@ -118,8 +118,15 @@ pub fn on_page_load(
}
}
+/// 跳转信息全局名(与 `packages/dsh-tauri/src/client/register/navigation.ts` 逐字一致)。
+const NAVIGATION_GLOBAL: &str = "__DSH_NAVIGATION__";
+
/// 壳层导航栏「文件 → 新建窗口」:以同一 `index.html` 再开一个独立 webview 窗口。
///
+/// 传入 `session_id` 时把跳转目标注入新窗口的全部 frame,由 dsh-tauri 插件在启动后接收并
+/// 打开该会话。注入而不是拼 `index.html#...`:hash 只有壳层可读,内嵌 dsh 的插件拿不到,
+/// 只能退回壳层轮询转发,并把新窗口误当成 remote 视图。
+///
/// 异步命令(不占用主线程)是唯一安全的调用侧:`WebviewWindowBuilder::build()`
/// 需要主线程事件循环回包,主线程调用会死锁(与 `pet::ensure_pet_window` 同约束)。
#[tauri::command]
@@ -127,78 +134,61 @@ pub async fn create_app_window(
app_handle: AppHandle<Wry>,
window: WebviewWindow<Wry>,
session_id: Option<String>,
- iframe_url: Option<String>,
) -> Result<(), String> {
+ let navigation = session_id
+ .as_deref()
+ .map(session_navigation_script)
+ .transpose()?;
let _transition = crate::service::workflow::acquire_core_transition().await?;
let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());
- let path = crate::service::workflow::instances::scope_sync(profile.clone(), || {
- let origin =
- config::get_dsh_service_url(crate::service::workflow::instances::port(&app_handle));
- session_window_path(
- session_id.as_deref(),
- session_id.as_ref().map(|_| origin.as_str()),
- )
- })?;
- let _ = iframe_url;
- crate::desktop::builder::build_extra_window(&app_handle, path, &profile)
- .map(|_| ())
- .map_err(|error| format!("WINDOW_CREATE_FAILED: {error}"))
+ crate::desktop::builder::build_extra_window(
+ &app_handle,
+ "index.html".into(),
+ &profile,
+ navigation.as_deref(),
+ )
+ .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());
- };
+/// 校验会话 id 并生成跳转脚本;JSON 序列化负责转义,避免把用户输入拼成可执行代码。
+fn session_navigation_script(session_id: &str) -> Result<String, String> {
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())
+ let payload = serde_json::json!({ "sessionId": session_id });
+ Ok(format!("globalThis.{NAVIGATION_GLOBAL} = {payload};"))
}
#[cfg(test)]
-mod session_window_tests {
- use super::session_window_path;
+mod session_navigation_tests {
+ use super::session_navigation_script;
#[test]
- fn session_target_is_encoded_and_rejects_untrusted_urls() {
+ fn session_navigation_script_assigns_the_session_target_to_the_shared_global() {
assert_eq!(
- session_window_path(None, None).unwrap().to_str(),
- Some("index.html")
+ session_navigation_script("session &/?#").unwrap(),
+ r#"globalThis.__DSH_NAVIGATION__ = {"sessionId":"session &/?#"};"#
);
+ }
+
+ #[test]
+ fn session_navigation_script_escapes_values_through_json_serialization() {
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")
+ session_navigation_script("a\"b\\c\nd").unwrap(),
+ r#"globalThis.__DSH_NAVIGATION__ = {"sessionId":"a\"b\\c\nd"};"#
);
- 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());
+ }
+
+ #[test]
+ fn session_navigation_script_rejects_empty_blank_or_oversized_identifiers() {
+ for id in ["", " ", " \t\n", &"s".repeat(513)] {
+ assert_eq!(
+ session_navigation_script(id),
+ Err("WINDOW_CREATE_FAILED: invalid sessionId".into())
+ );
}
- assert!(session_window_path(Some(" "), Some("http://localhost:3080")).is_err());
+ assert!(session_navigation_script(&"s".repeat(512)).is_ok());
}
}
diff --git a/src/hooks/use-invoke-iframe.ts b/src/hooks/use-invoke-iframe.ts
index 51d175e4..0570b927 100644
--- a/src/hooks/use-invoke-iframe.ts
+++ b/src/hooks/use-invoke-iframe.ts
@@ -77,7 +77,7 @@ export function useInvokeIframe(iframeRef: RefObject<HTMLIFrameElement | null>):
return
}
const cmd = data.cmd
- const args = cmd === 'create_app_window' ? { ...data.args, iframeUrl: origin } : data.args
+ const args = 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 fe67c0e6..ca995be1 100644
--- a/src/hooks/use-remote.test.ts
+++ b/src/hooks/use-remote.test.ts
@@ -83,20 +83,14 @@ afterEach(() => {
})
describe('useRemote 查询、降级与启动寻址', () => {
- it('session windows retain the target remote machine and can switch back to local', async () => {
+ it('会话窗口不再把 hash 里的 iframeUrl 当作远端机器来源', 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('')
+ expect(connect).not.toHaveBeenCalled()
})
it('刷新失败保留列表并降级,恢复后可用', async () => {
diff --git a/src/hooks/use-remote.ts b/src/hooks/use-remote.ts
index 21ee52ef..dfbf7124 100644
--- a/src/hooks/use-remote.ts
+++ b/src/hooks/use-remote.ts
@@ -29,8 +29,7 @@ function initialMachineId(): string | null {
const label = getCurrentWindow().label
if (label.startsWith('remote-'))
return label.slice('remote-'.length) || null
- const url = parameters.has('sessionId') ? parameters.get('iframeUrl') : null
- return url && URL.canParse(url) ? new URL(url).origin : null
+ return null
}
export function useRemote() {
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index c6c6a508..fd015248 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -1,5 +1,4 @@
{
- "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 1e0abf9f..9b22ce72 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -1,5 +1,4 @@
{
- "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
index aaf368a9..4f3096d0 100644
--- a/src/layout/components/webview.test.tsx
+++ b/src/layout/components/webview.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import type { IframeProps } from './iframe'
import type { NavbarProps } from './navbar'
-import { act, cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, render } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { Webview } from './webview'
@@ -15,7 +15,6 @@ const mocks = vi.hoisted(() => ({
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: mocks.harness, recovery: mocks.recovery } }))
vi.mock('@/hooks/use-appearance', () => ({ useAppearance: () => '' }))
@@ -40,7 +39,6 @@ vi.mock('./iframe', () => ({
<iframe key={srcOverride} ref={iframeRef} src={srcOverride ?? 'http://127.0.0.1:3081'} title="session" />
),
}))
-vi.mock('./loadable', () => ({ Loadable: () => <div data-testid="session-pending" /> }))
it('logs the selected shell branch and deduplicates unrelated rerenders without exposing remote URLs', () => {
window.location.hash = ''
@@ -79,19 +77,9 @@ 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()
+ window.location.hash = ''
Object.assign(mocks.harness, { status: 'ready', serviceHealthy: true })
mocks.recovery.recovery.required = false
vi.spyOn(console, 'warn').mockImplementation(() => {})
@@ -105,33 +93,3 @@ afterEach(() => {
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 56c7f4ab..7fe99a2a 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -1,10 +1,9 @@
import type { DshShortcutRow, DshViewCommand } from '@/hooks/use-dsh-shortcuts'
-import { useIntervalFn, useTimeoutFn, useWatch } from '@reause/core'
+import { 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'
@@ -16,7 +15,6 @@ 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'
@@ -26,20 +24,9 @@ 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)
@@ -52,13 +39,12 @@ export function Webview() {
const { status, serviceHealthy, serviceRunning, iframeKey, iframeLoaded, iframeAlive, iframeError, startupPhase, busyAction } = useStore(store.harness)
const { recovery } = useStore(store.recovery)
const [remoteView, setRemoteView] = useState({ url: '', tint: null as string | null })
- const [sessionSource, setSessionSource] = useState(sessionTarget?.url ?? '')
- const activeTunnelUrl = remoteView.url || sessionSource
+ const activeTunnelUrl = remoteView.url
const borderTint = remoteView.tint
const remoteMode = activeTunnelUrl !== ''
const live = status === 'ready' && (remoteMode || serviceHealthy)
const branch = status === 'ready' ? 'iframe' : status === 'preinstall' ? 'preinstall' : status === 'error' && recovery.required ? 'recovery' : 'setup'
- useWatch([branch, status, remoteMode, serviceHealthy, serviceRunning, iframeKey, iframeLoaded, iframeAlive, iframeError, startupPhase, busyAction, sessionPending, Boolean(sessionError)], () => {
+ useWatch([branch, status, remoteMode, serviceHealthy, serviceRunning, iframeKey, iframeLoaded, iframeAlive, iframeError, startupPhase, busyAction], () => {
console.warn('[Webview] shell view', {
branch,
status,
@@ -71,8 +57,6 @@ export function Webview() {
iframeError,
startupPhase,
busyAction,
- sessionPending,
- sessionError: Boolean(sessionError),
})
}, { immediate: true })
@@ -98,8 +82,6 @@ export function Webview() {
useListen('macos-menu-rebuilt', syncViewMenu, { target: getCurrentWindow().label })
function handleRemoteChange(url: string, tint: string | null) {
- if (url)
- setSessionSource('')
setRemoteView({ url, tint })
}
@@ -112,38 +94,13 @@ 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))
}
@@ -201,20 +158,6 @@ export function Webview() {
<Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />
<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>
)