DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(desktop): 右侧栏新增「在新窗口全屏打开」 (#1168)
Hairy490a1441ed16
diff --git a/packages/dsh-tauri/src/client/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.tsindex 6d4529e8..15d5ee06 100644--- a/packages/dsh-tauri/src/client/apply.test.ts+++ b/packages/dsh-tauri/src/client/apply.test.ts@@ -11,6 +11,7 @@ const EXPECTED_LABELS = ['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: sidebar full window (open-in-new-window button + full-screen setup)','dsh-tauri: account sign-in (auto-open the authorize url)','dsh-tauri: shortcuts (catalog report + edit commands)',]@@ -283,7 +284,7 @@ describe('apply', () => {expect(env.styles).toHaveLength(1)expect(env.sent.filter(message => message.type === 'dsh://plugin-error')).toEqual([])expect(env.windowListeners()).toBe(3)- expect(env.documentListeners()).toBe(2)+ expect(env.documentListeners()).toBe(3)for (const dispose of disposers.splice(0))await dispose()diff --git a/packages/dsh-tauri/src/client/apply.ts b/packages/dsh-tauri/src/client/apply.tsindex 368f5707..1bb65494 100644--- a/packages/dsh-tauri/src/client/apply.ts+++ b/packages/dsh-tauri/src/client/apply.ts@@ -4,6 +4,7 @@ import { registerAppearance } from './register/appearance'import { navigationFeature } from './register/navigation'import { shortcutsFeature } from './register/shortcuts'import { sidebarFeature } from './register/sidebar'+import { sidebarFullwindowFeature } from './register/sidebar-fullwindow'import { sidebarTweaksFeature } from './register/sidebar-tweaks'import { registerStyle } from './register/style'import { zoomShortcutFeature } from './register/zoom-shortcut'@@ -12,6 +13,7 @@ const SIDEBAR_TOGGLE_EFFECT = 'dsh-tauri: sidebar (toggle command + collapsed reconst 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 SIDEBAR_FULLWINDOW_EFFECT = 'dsh-tauri: sidebar full window (open-in-new-window button + full-screen setup)'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'@@ -29,6 +31,7 @@ export function apply(ctx: ClientContext): void {})ctx.effect(zoomShortcutFeature, ZOOM_SHORTCUT_EFFECT)ctx.effect(sidebarTweaksFeature, SIDEBAR_TWEAKS_EFFECT)+ ctx.effect(sidebarFullwindowFeature, SIDEBAR_FULLWINDOW_EFFECT)ctx.effect(accountSignInFeature, ACCOUNT_SIGN_IN_EFFECT)ctx.effect(shortcutsFeature, SHORTCUTS_EFFECT)}diff --git a/packages/dsh-tauri/src/client/register/navigation.test.ts b/packages/dsh-tauri/src/client/register/navigation.test.tsindex 278b0924..87c1c4d0 100644--- a/packages/dsh-tauri/src/client/register/navigation.test.ts+++ b/packages/dsh-tauri/src/client/register/navigation.test.ts@@ -206,4 +206,134 @@ describe('navigationFeature', () => {expect(clicked[1]).toContain('添加工作区')dispose()})++ it('会话已消费过(刷新出的新文档)仍重新就位全屏形态,但不重复打开会话', async () => {+ const host = stubHost()+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target', presentation: 'full-sidebar' }+ const storage = host.window.sessionStorage as { setItem: (key: string, value: string) => void }+ storage.setItem('__DSH_NAVIGATION_CONSUMED__', 'target')+ const clicked: string[] = []+ const marked: string[] = []+ vi.stubGlobal('document', {+ documentElement: { hasAttribute: () => false, setAttribute: (name: string, value: string) => marked.push(`${name}=${value}`) },+ querySelector: (selector: string) => selector === '[data-sidebar-right-expand]' ? { click: () => clicked.push('expand') } : null,+ })+ let ids: string[] = []+ const openSession = vi.fn(() => ({ status: 'opened', value: Promise.resolve() }))++ const dispose = navigationFeature.call(ctxWithServices({+ sessions: stubSessions(() => ids),+ uiWorkspace: { openSession },+ }))++ ids = ['target']+ await vi.advanceTimersByTimeAsync(500)+ expect(openSession).not.toHaveBeenCalled()+ expect(marked).toContain('data-dsh-tauri-full-sidebar=presenting')+ expect(clicked).toEqual(['expand'])+ dispose()+ })++ it('带 presentation=full-sidebar 的跳转在打开会话后展开右列并切入全屏', async () => {+ const host = stubHost()+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target', presentation: 'full-sidebar' }+ const clicked: string[] = []+ const marked: string[] = []+ let mode: { getAttribute: (name: string) => string | null, click: () => void } | undefined+ const expand = { click: () => clicked.push('expand') }+ vi.stubGlobal('document', {+ documentElement: { hasAttribute: () => false, setAttribute: (name: string, value: string) => marked.push(`${name}=${value}`) },+ querySelector: (selector: string) => {+ if (selector === '[data-sidebar-right-mode]')+ return mode ?? null+ return selector === '[data-sidebar-right-expand]' ? expand : null+ },+ })+ let ids: string[] = []+ const openSession = vi.fn(() => ({ status: 'opened', value: Promise.resolve() }))++ const dispose = navigationFeature.call(ctxWithServices({+ sessions: stubSessions(() => ids),+ uiWorkspace: { openSession },+ }))++ ids = ['target']+ await vi.advanceTimersByTimeAsync(500)+ expect(openSession).toHaveBeenCalledExactlyOnceWith('target')+ expect(marked).toContain('data-dsh-tauri-full-sidebar=presenting')++ await vi.advanceTimersByTimeAsync(250)+ expect(clicked).toEqual(['expand'])++ let fullscreen = 'fullscreen'+ mode = {+ getAttribute: () => fullscreen,+ click: () => {+ clicked.push('mode')+ fullscreen = 'push'+ },+ }+ await vi.advanceTimersByTimeAsync(500)+ expect(clicked).toEqual(['expand', 'mode'])+ expect(marked.at(-1)).toBe('data-dsh-tauri-full-sidebar=ready')++ await vi.advanceTimersByTimeAsync(31_000)+ expect(clicked).toEqual(['expand', 'mode'])+ dispose()+ })++ it('会话被归档后关掉全屏窗口,而不是让它退回会话列表', () => {+ const host = stubHost()+ host.window[NAVIGATION_GLOBAL] = { sessionId: 'target', presentation: 'full-sidebar' }+ vi.stubGlobal('document', {+ documentElement: { hasAttribute: () => false, setAttribute: () => {} },+ })+ const sources: FakeEventSource[] = []+ vi.stubGlobal('EventSource', class extends FakeEventSource {+ constructor(url: string) {+ super(url)+ sources.push(this)+ }+ })+ const dispose = navigationFeature.call(ctxWithServices({+ sessions: stubSessions(() => ['target']),+ }))++ const closes = () => host.post.mock.calls.filter(call => (call[0] as { type?: string }).type === 'dsh://window:close')+ expect(sources).toHaveLength(1)+ expect(sources[0]?.url).toBe('/api/tauri/desktop/archive/events')+ expect(closes()).toHaveLength(0)++ sources[0]?.emit(JSON.stringify({ archivedSessionIds: ['other'] }))+ expect(closes()).toHaveLength(0)++ sources[0]?.emit(JSON.stringify({ archivedSessionIds: ['other', 'target'] }))+ expect(closes()).toHaveLength(1)+ expect(sources[0]?.closed).toBe(true)++ sources[0]?.emit(JSON.stringify({ archivedSessionIds: ['target'] }))+ expect(closes()).toHaveLength(1)+ dispose()+ })})++/** 最小 `EventSource` 替身:只实现窗口侧用到的接口,测试里手动投递宿主帧。 */+class FakeEventSource {+ closed = false+ private readonly listeners: Array<(event: { data: string }) => void> = []++ constructor(readonly url: string) {}++ addEventListener(_type: string, listener: (event: { data: string }) => void): void {+ this.listeners.push(listener)+ }++ close(): void {+ this.closed = true+ }++ emit(data: string): void {+ for (const listener of this.listeners)+ listener({ data })+ }+}diff --git a/packages/dsh-tauri/src/client/register/navigation.ts b/packages/dsh-tauri/src/client/register/navigation.tsindex 2f952eed..8e6b0a5c 100644--- a/packages/dsh-tauri/src/client/register/navigation.ts+++ b/packages/dsh-tauri/src/client/register/navigation.ts@@ -3,6 +3,7 @@ import type { ClientAdapter, RegisterController } from './index'import { listenParent } from '../service/listen-parent'import { reportPluginError } from '../utils/error'import { defineRegister } from './index'+import { closeWhenArchived, isolateSidebarLayout, PRESENTATION_FULL_SIDEBAR, presentFullSidebar } from './sidebar-fullwindow'/** 宿主 → iframe:新建会话命令。 */const CMD_NEW_SESSION = 'dsh://session:new'@@ -21,6 +22,7 @@ const NAVIGATION_TIMEOUT_MS = 30_000interface InjectedNavigation {sessionId?: unknown+ presentation?: unknown}function injectedSessionConsumed(sessionId: string): boolean {@@ -41,16 +43,23 @@ function markInjectedSessionConsumed(sessionId: string): void {}}-function takeInjectedSession(): string | undefined {+/**+ * 取走壳层注入的跳转载荷(每次文档只取一次)。+ * @returns 会话 id、窗口形态与「会话已打开过」;格式不对的字段各自丢弃。+ */+function takeInjectedNavigation(): { sessionId?: string, presentation?: string, consumed: boolean } {const host = window as unknown as Record<string, unknown>const payload = host[NAVIGATION_GLOBAL] as InjectedNavigation | undefinedif (payload === undefined)- return undefined+ return { consumed: false }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+ if (typeof payload !== 'object' || payload === null)+ return { consumed: false }+ const presentation = payload.presentation === PRESENTATION_FULL_SIDEBAR ? PRESENTATION_FULL_SIDEBAR : undefined+ const sessionId = payload.sessionId+ if (typeof sessionId !== 'string' || sessionId.trim() === '')+ return { presentation, consumed: false }+ return { sessionId, presentation, consumed: injectedSessionConsumed(sessionId) }}function consumeInjectedSession(controller: RegisterController, adapter: ClientAdapter, sessionId: string): void {@@ -103,7 +112,17 @@ export const navigationFeature = defineRegister<ClientContext>((controller, _ctxvoid adapter.addWorkspace({ openSession: true }).catch((error: unknown) => reportPluginError(error))}, [CMD_NEW_SESSION, CMD_ADD_WORKSPACE]))- const sessionId = takeInjectedSession()- if (sessionId !== undefined)+ const { sessionId, presentation, consumed } = takeInjectedNavigation()+ console.warn('[dsh-tauri] navigation: injected', { sessionId, presentation, consumed })+ if (presentation === PRESENTATION_FULL_SIDEBAR) {+ // 先把本窗口的右栏布局从共享存储里隔离出来,否则两个窗口会互相覆盖形态。+ if (sessionId !== undefined) {+ isolateSidebarLayout(sessionId)+ closeWhenArchived(controller, sessionId)+ }+ // 形态先就位:它自带看门狗,会话没打开(例如主窗口中途关闭)也会自己揭开,不会留白屏。+ presentFullSidebar(controller)+ }+ if (sessionId !== undefined && !consumed)consumeInjectedSession(controller, adapter, sessionId)})diff --git a/packages/dsh-tauri/src/client/register/sidebar-fullwindow.test.ts b/packages/dsh-tauri/src/client/register/sidebar-fullwindow.test.tsnew file mode 100644index 00000000..df63241f--- /dev/null+++ b/packages/dsh-tauri/src/client/register/sidebar-fullwindow.test.ts@@ -0,0 +1,202 @@+import type { ClientContext } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { invoke } from '../service/invoke'+import { sidebarFullwindowFeature } from './sidebar-fullwindow'++vi.mock('../service/invoke', () => ({ invoke: vi.fn(() => Promise.resolve()) }))++interface FakeNode {+ attributes: Map<string, string>+ className: string+ clicks: number+ innerHTML: string+ parentElement: FakeContainer | null+ style: { display: string, removeProperty: (name: string) => void, setProperty: (name: string, value: string) => void }+ title: string+ setAttribute: (name: string, value: string) => void+ getAttribute: (name: string) => string | null+ addEventListener: (type: string, handler: () => void) => void+ click: () => void+ closest: () => unknown+}++interface FakeContainer {+ children: FakeNode[]+ insertBefore: (node: FakeNode, before: FakeNode) => FakeNode+}++function createNode(): FakeNode {+ const listeners = new Map<string, () => void>()+ const node: FakeNode = {+ attributes: new Map(),+ className: '',+ clicks: 0,+ innerHTML: '',+ parentElement: null,+ style: {+ display: '',+ setProperty: (name, value) => {+ if (name === 'display')+ node.style.display = value+ },+ removeProperty: (name) => {+ if (name === 'display')+ node.style.display = ''+ },+ },+ title: '',+ setAttribute(name, value) { node.attributes.set(name, value) },+ getAttribute: name => node.attributes.get(name) ?? null,+ addEventListener(type, handler) { listeners.set(type, handler) },+ click() {+ node.clicks += 1+ listeners.get('click')?.()+ },+ closest: () => ({ getAttribute: (name: string) => name === 'data-sidebar-right-session' ? 'session-1' : null }),+ }+ return node+}++function stubDom(options: { fullSidebar?: boolean, tabs?: number } = {}) {+ const container: FakeContainer = {+ children: [],+ insertBefore(node, before) {+ const at = container.children.indexOf(node)+ if (at >= 0)+ container.children.splice(at, 1)+ container.children.splice(container.children.indexOf(before), 0, node)+ node.parentElement = container+ return node+ },+ }+ const toggle = createNode()+ toggle.setAttribute('data-sidebar-right-toggle', '')+ const mode = createNode()+ mode.className = 'P3OORG_iconButton'+ mode.setAttribute('aria-label', '全屏')+ mode.setAttribute('data-sidebar-right-mode', 'fullscreen')+ mode.parentElement = container+ container.children.push(mode)+ const expand = createNode()+ expand.setAttribute('data-sidebar-right-expand', '')+ const closes = Array.from({ length: options.tabs ?? 2 }, () => {+ const tab = createNode()+ tab.setAttribute('data-dockkit-tab', 'tab')+ const close = createNode()+ close.setAttribute('data-dockkit-tab-close', 'tab')+ tab.parentElement = container+ tab.closest = () => tab+ return { close, tab }+ })+ const tabs = closes.map(entry => entry.tab)+ const contextHandlers = new Map<string, (event: unknown) => void>()++ vi.stubGlobal('document', {+ body: { style: { setProperty: vi.fn(), removeProperty: vi.fn() } },+ documentElement: {+ setAttribute: vi.fn(),+ hasAttribute: () => options.fullSidebar ?? false,+ },+ createElement: () => createNode(),+ addEventListener: (type: string, handler: (event: unknown) => void) => contextHandlers.set(type, handler),+ removeEventListener: (type: string) => contextHandlers.delete(type),+ querySelector: (selector: string) => {+ if (selector === '[data-sidebar-right-mode]')+ return mode+ if (selector === '[data-sidebar-right-expand]')+ return expand+ if (selector === '[data-sidebar-right-toggle]')+ return toggle+ if (selector === '[data-dsh-tauri-open-window]')+ return container.children.find(node => node.attributes.has('data-dsh-tauri-open-window')) ?? null+ return null+ },+ querySelectorAll: (selector: string) => {+ if (selector === '[data-dockkit-tab]')+ return tabs+ return selector === '[data-dockkit-tab-close]' ? closes.map(entry => entry.close) : []+ },+ })+ vi.stubGlobal('HTMLElement', class {})+ vi.stubGlobal('Element', class {})+ vi.stubGlobal('MutationObserver', class {+ observe() {}+ disconnect() {}+ })+ return { closes, container, contextHandlers, mode, tabs, toggle }+}++function runFeature(): () => void {+ return sidebarFullwindowFeature.call({ get: () => undefined } as unknown as ClientContext)+}++beforeEach(() => {+ vi.mocked(invoke).mockClear()+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('sidebarFullwindowFeature', () => {+ it('在全屏按钮左侧注入官方同款按钮,并按官方按钮语言取文案', () => {+ const { container, mode } = stubDom()+ const dispose = runFeature()++ const [button] = container.children+ expect(container.children).toHaveLength(2)+ expect(container.children[1]).toBe(mode)+ expect(button.attributes.has('data-dsh-tauri-open-window')).toBe(true)+ expect(button.className).toBe(mode.className)+ expect(button.getAttribute('aria-label')).toBe('在新窗口全屏打开')+ expect(button.innerHTML).toContain('<svg')+ dispose()+ })++ it('点击后按当前会话的 id 走宿主建窗,并带上全屏形态标记,同时收起本窗口右栏', async () => {+ const { container, toggle } = stubDom()+ const dispose = runFeature()++ container.children[0].click()++ expect(invoke).toHaveBeenCalledExactlyOnceWith('create_app_window', {+ sessionId: 'session-1',+ presentation: 'full-sidebar',+ })+ expect(toggle.clicks).toBe(1)+ dispose()+ })++ it('已经是全屏形态的按钮不重复注入', () => {+ const { container } = stubDom()+ runFeature()+ runFeature()++ expect(container.children).toHaveLength(2)+ })++ it('全屏形态窗口只剩一个 tab 时收掉关闭按钮并吞掉右键菜单', () => {+ const { closes, contextHandlers, tabs } = stubDom({ fullSidebar: true, tabs: 1 })+ const dispose = runFeature()++ expect(closes[0].close.style.display).toBe('none')+ const preventDefault = vi.fn()+ const stopPropagation = vi.fn()+ contextHandlers.get('contextmenu')?.({ preventDefault, stopPropagation, target: tabs[0] })+ expect(preventDefault).toHaveBeenCalledOnce()+ expect(stopPropagation).toHaveBeenCalledOnce()+ dispose()+ })++ it('多 tab 时不介入右键菜单', () => {+ const { closes, contextHandlers, tabs } = stubDom({ fullSidebar: true, tabs: 2 })+ const dispose = runFeature()++ expect(closes[0].close.style.display).toBe('')+ const preventDefault = vi.fn()+ contextHandlers.get('contextmenu')?.({ preventDefault, stopPropagation: vi.fn(), target: tabs[0] })+ expect(preventDefault).not.toHaveBeenCalled()+ dispose()+ })+})diff --git a/packages/dsh-tauri/src/client/register/sidebar-fullwindow.ts b/packages/dsh-tauri/src/client/register/sidebar-fullwindow.tsnew file mode 100644index 00000000..d0f36e25--- /dev/null+++ b/packages/dsh-tauri/src/client/register/sidebar-fullwindow.ts@@ -0,0 +1,363 @@+import type { RegisterController } from './index'+/**+ * register/sidebar-fullwindow.ts — 右栏「在新窗口全屏打开」:+ *+ * 官方没有对外暴露全屏命令,右栏 chrome 也没有插槽,只能落在界面上现成的那几枚控件上:+ * 在全屏按钮左侧注入一枚官方同款按钮,点击走宿主的 `create_app_window` 并带上+ * `presentation=full-sidebar`;带该标记的窗口启动后把右列展开、切进全屏,chrome 上只留+ * 内容(窗口形态由壳层的 `full-sidebar-navbar` 承载)。+ *+ * 用 DOM 注入而不是 React 组件:chrome 由官方包渲染且不接受外部插槽,`data-sidebar-right-*`+ * 稳定属性比生成的 CSS module 类名可靠。+ */+import { ARCHIVE_STREAM_PATH } from '../../shared/constants'+import { invoke } from '../service/invoke'+import { invokeParent } from '../service/invoke-parent'+import { reportPluginError } from '../utils/error'+import { defineRegister } from './index'++/** 注入按钮的标记属性(幂等判断用)。 */+const OPEN_WINDOW_ATTRIBUTE = 'data-dsh-tauri-open-window'++/** 全屏切换按钮:它的存在说明右栏已挂载,值是 `fullscreen` 表示还没全屏。 */+const FULLSCREEN_SELECTOR = '[data-sidebar-right-mode]'++/** 折叠态轨上的展开按钮。 */+const EXPAND_SELECTOR = '[data-sidebar-right-expand]'++/** 展开态 chrome 上的收起按钮。 */+const TOGGLE_SELECTOR = '[data-sidebar-right-toggle]'++/** 右栏根节点:携带本栏所属会话 id。 */+const SESSION_SELECTOR = '[data-sidebar-right-session]'++/** dockkit 的 tab 与其关闭按钮(关闭按钮带稳定属性,见官方 tab 渲染)。 */+const TAB_SELECTOR = '[data-dockkit-tab]'+const TAB_CLOSE_SELECTOR = '[data-dockkit-tab-close]'++/** 全屏形态窗口的根标记:隐藏 chrome 按钮,也是壳层判定窗口形态的依据。 */+export const FULL_SIDEBAR_ATTRIBUTE = 'data-dsh-tauri-full-sidebar'++/** 建窗载荷里的窗口形态(与 `src-tauri/src/desktop/window.rs` 逐字一致)。 */+export const PRESENTATION_FULL_SIDEBAR = 'full-sidebar'++/** 官方右栏布局的落盘前缀(`<前缀><sessionId>`)。 */+const LAYOUT_STORAGE_PREFIX = 'dsh.sidebar-right.v1.'++/** 布局已隔离的标记:每个文档只装一次。 */+const LAYOUT_ISOLATED_ATTRIBUTE = 'data-dsh-tauri-layout-isolated'++/**+ * 把右栏布局搬进本窗口的 sessionStorage。+ *+ * 官方按 Session 把布局存在共享的 localStorage 里,同一会话开两个窗口就会互相覆盖:+ * 主窗口收起右栏会把全屏窗口刷回普通布局,全屏窗口切全屏又会让主窗口刷新后变全屏。+ * 隔离后每个窗口各存各的,互不干扰。+ * @param sessionId - 本窗口要就位成全屏的那条会话。+ */+export function isolateSidebarLayout(sessionId: string): void {+ if (document.documentElement.hasAttribute(LAYOUT_ISOLATED_ATTRIBUTE))+ return+ let shared: Storage+ let own: Storage+ try {+ shared = window.localStorage+ own = window.sessionStorage+ }+ catch {+ return+ }+ document.documentElement.setAttribute(LAYOUT_ISOLATED_ATTRIBUTE, sessionId)+ const key = `${LAYOUT_STORAGE_PREFIX}${sessionId}`+ try {+ const saved = own.getItem(key) ?? shared.getItem(key)+ if (saved !== null) {+ const parsed = JSON.parse(saved) as { bySession?: Record<string, { layout?: { expanded?: boolean, mode?: string } }> }+ const layout = parsed.bySession?.[sessionId]?.layout+ if (layout !== undefined) {+ layout.expanded = true+ layout.mode = 'fullscreen'+ own.setItem(key, JSON.stringify(parsed))+ }+ }+ }+ catch (error) {+ reportPluginError(error)+ }+ const proto = Object.getPrototypeOf(own) as Storage | null+ if (proto === null || typeof proto.getItem !== 'function')+ return+ const { getItem, setItem, removeItem } = proto+ const routed = (target: string) => target.startsWith(LAYOUT_STORAGE_PREFIX)+ proto.getItem = function (target: string): string | null {+ return routed(target) ? getItem.call(own, target) : getItem.call(this, target)+ }+ proto.setItem = function (target: string, value: string): void {+ if (routed(target))+ setItem.call(own, target, value)+ else+ setItem.call(this, target, value)+ }+ proto.removeItem = function (target: string): void {+ if (routed(target))+ removeItem.call(own, target)+ else+ removeItem.call(this, target)+ }+}++/** 就位中:整页先藏起来,避免先看到普通布局再跳成全屏。 */+const FULL_SIDEBAR_PRESENTING = 'presenting'++const FULL_SIDEBAR_READY = 'ready'++const PRESENT_POLL_MS = 250+const PRESENT_MAX_TICKS = 32++/** 就位完成通知:壳层据此揭开内容区的遮罩。 */+const FULL_SIDEBAR_READY_MESSAGE = 'dsh://full-sidebar:ready'++/** 官方 tooltip 气泡的观感(同官方样式表,行内写死以免依赖模块化类名)。 */+const TOOLTIP_STYLE = 'position:fixed;z-index:100;padding:3px 7px;border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-tooltip-bg);color:var(--dsw-static-neutral-bluish-00);font-size:13px;line-height:20px;white-space:nowrap;pointer-events:none;display:none'++const TOOLTIP_DELAY_MS = 300+const TOOLTIP_GAP = 6++/** 官方字形风格:16×16 描边图标。 */+const ICON = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M9.5 2.5H13C13.2761 2.5 13.5 2.72386 13.5 3V6.5" stroke="currentColor"/><path d="M13.1 2.9L8.5 7.5" stroke="currentColor"/><path d="M12 9.5V13C12 13.2761 11.7761 13.5 11.5 13.5H3C2.72386 13.5 2.5 13.2761 2.5 13V3C2.5 2.72386 2.72386 2.5 3 2.5H6.5" stroke="currentColor"/></svg>'++/** 按钮文案跟随官方按钮的语言:官方全屏按钮只有中英两种。 */+function buttonLabel(mode: Element): string {+ return /[\u4E00-\u9FA5]/.test(mode.getAttribute('aria-label') ?? '')+ ? '在新窗口全屏打开'+ : 'Open full screen in new window'+}++function openWindow(button: HTMLElement): void {+ const sessionId = button.closest(SESSION_SELECTOR)?.getAttribute('data-sidebar-right-session')+ document.querySelector<HTMLElement>(TOGGLE_SELECTOR)?.click()+ void invoke('create_app_window', {+ sessionId: sessionId ?? undefined,+ presentation: PRESENTATION_FULL_SIDEBAR,+ }).catch((error: unknown) => reportPluginError(error))+}++function isFullSidebarDocument(): boolean {+ return document.documentElement.hasAttribute(FULL_SIDEBAR_ATTRIBUTE)+}++interface Tooltip {+ attach: (anchor: HTMLElement, text: string) => void+ hide: () => void+ dispose: () => void+}++/**+ * 官方 chrome 按钮的悬停提示:自带的气泡样式,而不是原生 `title`。+ * 状态留在特性闭包里,插件卸载时一起收走。+ * @returns 提示气泡的挂载、隐藏与销毁。+ */+function createTooltip(): Tooltip {+ let bubble: HTMLDivElement | null = null+ let timer: ReturnType<typeof setTimeout> | undefined+ const hide = () => {+ clearTimeout(timer)+ if (bubble !== null)+ bubble.style.display = 'none'+ }+ const show = (anchor: HTMLElement, text: string) => {+ bubble ??= document.createElement('div')+ bubble.setAttribute('role', 'tooltip')+ bubble.style.cssText = TOOLTIP_STYLE+ bubble.textContent = text+ document.body.append(bubble)+ const rect = anchor.getBoundingClientRect()+ bubble.style.display = 'block'+ const width = bubble.getBoundingClientRect().width+ bubble.style.top = `${rect.bottom + TOOLTIP_GAP}px`+ bubble.style.left = `${Math.min(Math.max(rect.left + rect.width / 2 - width / 2, 4), window.innerWidth - width - 4)}px`+ }+ return {+ attach(anchor, text) {+ anchor.addEventListener('pointerenter', () => {+ clearTimeout(timer)+ timer = setTimeout(show, TOOLTIP_DELAY_MS, anchor, text)+ })+ anchor.addEventListener('pointerleave', hide)+ },+ hide,+ dispose() {+ hide()+ bubble?.remove()+ bubble = null+ },+ }+}++/** 用行内样式藏控件:插件样式表可能被宿主模块系统回收,行内样式不会。 */+function conceal(element: Element | null | undefined): void {+ if (element instanceof HTMLElement)+ element.style.setProperty('display', 'none', 'important')+}++/**+ * 全屏形态窗口的右栏只剩一个 tab:关掉它就是关掉整个面板,+ * 所以收掉关闭按钮,也不让它弹出右键菜单。+ */+function guardLastTab(): void {+ const single = isFullSidebarDocument() && document.querySelectorAll(TAB_SELECTOR).length <= 1+ document.querySelectorAll<HTMLElement>(TAB_CLOSE_SELECTOR).forEach((close) => {+ if (single)+ close.style.setProperty('display', 'none', 'important')+ else+ close.style.removeProperty('display')+ })+}++/** 把按钮插到全屏按钮左侧;右栏重渲染丢掉按钮时由观察者再次调用。 */+function place(tooltip: Tooltip): void {+ const mode = document.querySelector<HTMLElement>(FULLSCREEN_SELECTOR)+ const parent = mode?.parentElement+ if (mode == null || parent == null)+ return+ let button = document.querySelector<HTMLButtonElement>(`[${OPEN_WINDOW_ATTRIBUTE}]`)+ if (button === null) {+ const created = document.createElement('button')+ created.type = 'button'+ created.setAttribute(OPEN_WINDOW_ATTRIBUTE, '')+ const label = buttonLabel(mode)+ created.setAttribute('aria-label', label)+ // 直接沿用官方按钮的类名:尺寸与 hover 完全跟着官方样式表走。+ created.className = mode.className+ created.innerHTML = ICON+ created.addEventListener('click', () => {+ tooltip.hide()+ openWindow(created)+ })+ tooltip.attach(created, label)+ parent.insertBefore(created, mode)+ button = created+ }+ else if (mode.previousElementSibling !== button) {+ parent.insertBefore(button, mode)+ }+ if (isFullSidebarDocument()) {+ conceal(button)+ conceal(mode)+ conceal(document.querySelector(TOGGLE_SELECTOR))+ }+}++/**+ * 把本窗口就位成全屏右栏:标记形态 → 展开右列 → 切进全屏。+ *+ * 右列可能还没渲染(会话刚打开)或还没折叠可展开,所以逐帧推进而不是一次点完;+ * 轮询自带看门狗,会话始终没打开也会自己揭开,不留白屏。+ * @param controller - 生命周期控制器;窗口关闭或插件重载时停掉轮询。+ */+/**+ * 本窗口的会话被归档即关窗:官方会收回那条会话的右栏,窗口会掉回会话列表,+ * 与其留一个空壳不如随会话消失。+ * @param controller - 生命周期控制器(订阅随插件卸载关闭)。+ * @param sessionId - 本窗口承载的会话 id。+ */+export function closeWhenArchived(controller: RegisterController, sessionId: string): void {+ if (typeof EventSource === 'undefined') {+ console.warn('[dsh-tauri] archive-watch: no EventSource')+ return+ }+ const source = new EventSource(ARCHIVE_STREAM_PATH)+ console.warn('[dsh-tauri] archive-watch: subscribe', { sessionId, url: ARCHIVE_STREAM_PATH })+ let closing = false+ controller.add(() => source.close())+ source.addEventListener('open', () => console.warn('[dsh-tauri] archive-watch: open'))+ source.addEventListener('error', () => console.warn('[dsh-tauri] archive-watch: error', { readyState: source.readyState }))+ source.addEventListener('message', (event) => {+ if (closing)+ return+ const archived = archivedSessionIds(event.data)+ if (archived?.includes(sessionId) !== true)+ return+ closing = true+ source.close()+ console.warn('[dsh-tauri] archive-watch: closing archived window', { sessionId })+ invokeParent({ type: 'dsh://window:close' })+ })+}++/** 解析宿主帧 `{"archivedSessionIds":[…]}`;格式不对当作没收到。 */+function archivedSessionIds(data: unknown): string[] | undefined {+ if (typeof data !== 'string')+ return undefined+ try {+ const payload = JSON.parse(data) as { archivedSessionIds?: unknown }+ return Array.isArray(payload.archivedSessionIds) ? payload.archivedSessionIds.map(String) : undefined+ }+ catch {+ return undefined+ }+}++export function presentFullSidebar(controller: RegisterController): void {+ document.documentElement.setAttribute(FULL_SIDEBAR_ATTRIBUTE, FULL_SIDEBAR_PRESENTING)+ document.body?.style.setProperty('visibility', 'hidden', 'important')+ let ticks = 0+ let expandClicked = false+ const cancel = controller.interval(() => {+ ticks += 1+ const settle = () => {+ cancel()+ document.documentElement.setAttribute(FULL_SIDEBAR_ATTRIBUTE, FULL_SIDEBAR_READY)+ document.body?.style.removeProperty('visibility')+ console.warn('[dsh-tauri] present: ready', { ticks })+ invokeParent({ type: FULL_SIDEBAR_READY_MESSAGE })+ }+ if (ticks > PRESENT_MAX_TICKS) {+ settle()+ return+ }+ const mode = document.querySelector<HTMLElement>(FULLSCREEN_SELECTOR)+ if (mode == null) {+ const expand = document.querySelector<HTMLElement>(EXPAND_SELECTOR)+ if (!expandClicked && expand !== null) {+ expandClicked = true+ expand.click()+ }+ return+ }+ if (mode.getAttribute('data-sidebar-right-mode') === 'fullscreen') {+ mode.click()+ return+ }+ settle()+ }, PRESENT_POLL_MS)+}++/** tab 全关会把整个右栏收掉:全屏形态窗口里只留一个 tab 时掐掉右键菜单。 */+function blockLastTabMenu(event: MouseEvent): void {+ if (!isFullSidebarDocument() || document.querySelectorAll(TAB_SELECTOR).length > 1)+ return+ const target = event.target as Element | null+ if (typeof target?.closest !== 'function' || target.closest(TAB_SELECTOR) === null)+ return+ event.preventDefault()+ event.stopPropagation()+}++export const sidebarFullwindowFeature = defineRegister((controller) => {+ const tooltip = createTooltip()+ controller.add(() => tooltip.dispose())+ const inject = () => {+ try {+ place(tooltip)+ guardLastTab()+ }+ catch (error) {+ reportPluginError(error)+ }+ }+ document.addEventListener('contextmenu', blockLastTabMenu, true)+ controller.add(() => document.removeEventListener('contextmenu', blockLastTabMenu, true))+ controller.observe(document.body, inject)+ inject()+})diff --git a/packages/dsh-tauri/src/client/register/sidebar-layout-isolation.test.ts b/packages/dsh-tauri/src/client/register/sidebar-layout-isolation.test.tsnew file mode 100644index 00000000..5d788538--- /dev/null+++ b/packages/dsh-tauri/src/client/register/sidebar-layout-isolation.test.ts@@ -0,0 +1,103 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { isolateSidebarLayout } from './sidebar-fullwindow'++const KEY = 'dsh.sidebar-right.v1.session-1'+const ISOLATED = 'data-dsh-tauri-layout-isolated'++class FakeStorage {+ map = new Map<string, string>()+ get length(): number {+ return this.map.size+ }++ getItem(key: string): string | null {+ return this.map.get(key) ?? null+ }++ setItem(key: string, value: string): void {+ this.map.set(key, String(value))+ }++ removeItem(key: string): void {+ this.map.delete(key)+ }++ clear(): void {+ this.map.clear()+ }++ key(index: number): string | null {+ return [...this.map.keys()][index] ?? null+ }+}++const attributes = new Map<string, string>()+const shared = new FakeStorage()+const own = new FakeStorage()++const native = {+ getItem: FakeStorage.prototype.getItem,+ setItem: FakeStorage.prototype.setItem,+ removeItem: FakeStorage.prototype.removeItem,+}++function stubGlobals(): void {+ vi.stubGlobal('window', { localStorage: shared, sessionStorage: own })+ vi.stubGlobal('localStorage', shared)+ vi.stubGlobal('sessionStorage', own)+ vi.stubGlobal('document', {+ documentElement: {+ getAttribute: (name: string) => attributes.get(name) ?? null,+ setAttribute: (name: string, value: string) => attributes.set(name, value),+ hasAttribute: (name: string) => attributes.has(name),+ },+ })+}++function sharedValue(key: string): string | null {+ return shared.map.get(key) ?? null+}++describe('isolateSidebarLayout', () => {+ beforeEach(() => {+ attributes.clear()+ shared.map.clear()+ own.map.clear()+ stubGlobals()+ })++ afterEach(() => {+ FakeStorage.prototype.getItem = native.getItem+ FakeStorage.prototype.setItem = native.setItem+ FakeStorage.prototype.removeItem = native.removeItem+ vi.unstubAllGlobals()+ })++ it('把本窗口要用的右栏布局搬进 sessionStorage 并强制成全屏形态', () => {+ shared.setItem(KEY, JSON.stringify({ bySession: { 'session-1': { layout: { expanded: false, mode: 'push' }, minted: 3 } } }))++ isolateSidebarLayout('session-1')++ expect(JSON.parse(own.getItem(KEY) ?? '')).toEqual({+ bySession: { 'session-1': { layout: { expanded: true, mode: 'fullscreen' }, minted: 3 } },+ })+ })++ it('隔离后的写入不再落到主窗口共享的 localStorage', () => {+ isolateSidebarLayout('session-1')++ localStorage.setItem(KEY, 'own-layout')++ expect(sharedValue(KEY)).toBeNull()+ expect(own.getItem(KEY)).toBe('own-layout')+ expect(localStorage.getItem(KEY)).toBe('own-layout')+ })++ it('同一文档只装一次,别的会话不会被顺带隔离', () => {+ isolateSidebarLayout('session-1')+ isolateSidebarLayout('session-2')++ expect(attributes.get(ISOLATED)).toBe('session-1')+ expect(own.getItem('dsh.sidebar-right.v1.session-2')).toBeNull()+ })+})diff --git a/packages/dsh-tauri/src/host/apply.test.ts b/packages/dsh-tauri/src/host/apply.test.tsindex c5befee9..15a5513b 100644--- a/packages/dsh-tauri/src/host/apply.test.ts+++ b/packages/dsh-tauri/src/host/apply.test.ts@@ -18,6 +18,7 @@ function activate() {})const ctx = {connection: { authorizeIndex: () => false },+ webServer: { register: () => () => {} },effect: (callback: () => unknown) => { callback() },on,} as unknown as HostContextdiff --git a/packages/dsh-tauri/src/host/apply.ts b/packages/dsh-tauri/src/host/apply.tsindex 29d04d8f..73201252 100644--- a/packages/dsh-tauri/src/host/apply.ts+++ b/packages/dsh-tauri/src/host/apply.ts@@ -1,10 +1,12 @@import type { ConnectionHost, HostContext } from './types'import process from 'node:process'import { PLUGIN_ID } from '../shared/constants'+import { server } from './server'import { gate } from './service/gate'const GATE_EFFECT = `${PLUGIN_ID}: gate`const ACCOUNT_EFFECT = `${PLUGIN_ID}: account desktop marker`+const ROUTES_EFFECT = `${PLUGIN_ID}: routes`/*** 官方账号 UI 只认 `'dshDesktop' in globalThis`(`dsh-client-ui-settings-account` 的@@ -26,6 +28,7 @@ const ACCOUNT_MARKER_SCRIPT = 'if (new URLSearchParams(location.search).has(\'dsexport function apply(ctx: HostContext): void {ctx.effect(() => gate.attach(ctx as unknown as ConnectionHost), GATE_EFFECT)+ ctx.effect(() => server(ctx), ROUTES_EFFECT)if (process.env.DSH_TAURI_EMBEDDED === '1') {ctx.effect(() => ctx.on('webserver/index-inject', (table) => {table.push({ kind: 'script', placement: 'head', text: ACCOUNT_MARKER_SCRIPT })diff --git a/packages/dsh-tauri/src/host/server/index.test.ts b/packages/dsh-tauri/src/host/server/index.test.tsnew file mode 100644index 00000000..9b1fa5b7--- /dev/null+++ b/packages/dsh-tauri/src/host/server/index.test.ts@@ -0,0 +1,124 @@+import type { Context } from '@deepseek-ai/cordis'+import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'+import type { IncomingMessage, ServerResponse } from 'node:http'+import type { AddressInfo } from 'node:net'+import { createServer } from 'node:http'+import { afterEach, describe, expect, it } from 'vitest'+import { server } from '.'+import { ARCHIVE_STREAM_PATH } from '../../shared/constants'++interface Harness {+ registered: Map<string, WebRoute>+ /** 改归档集合后模拟官方的存储域变更广播。 */+ archive: (ids: string[]) => void+ /** 当前挂上的 `domain/changed` 监听数量(连接关闭后必须归零)。 */+ listenerCount: () => number+}++function createHarness(): Harness {+ const registered = new Map<string, WebRoute>()+ let archived: string[] = []+ const listeners = new Set<() => void>()+ const ctx = {+ webServer: {+ register(route: WebRoute): () => void {+ const key = `${route.kind}\0${route.path}`+ registered.set(key, route)+ return () => {+ registered.delete(key)+ }+ },+ },+ logger: { error: () => {}, info: () => {} },+ get workspaceRegistry() {+ return { archivedSessionIds: archived }+ },+ on: (event: string, listener: () => void) => {+ expect(event).toBe('domain/changed')+ listeners.add(listener)+ return () => listeners.delete(listener)+ },+ } as unknown as Context+ server(ctx)+ return {+ registered,+ archive(ids) {+ archived = ids+ for (const listener of listeners)+ listener()+ },+ listenerCount: () => listeners.size,+ }+}++const servers: ReturnType<typeof createServer>[] = []++async function listen(registered: Map<string, WebRoute>): Promise<string> {+ const instance = createServer((request: IncomingMessage, response: ServerResponse) => {+ const pathname = new URL(request.url ?? '/', 'http://127.0.0.1').pathname+ const route = registered.get(`exact\0${pathname}`)+ if (!route) {+ response.writeHead(404)+ response.end()+ return+ }+ Promise.resolve(route.handler(request, response)).catch(() => {+ if (!response.headersSent) {+ response.writeHead(500)+ response.end()+ }+ })+ })+ servers.push(instance)+ await new Promise<void>(resolve => instance.listen(0, '127.0.0.1', resolve))+ return `http://127.0.0.1:${(instance.address() as AddressInfo).port}`+}++/** 读帧直到 `match` 命中:SSE 是流式的,不能等整份响应体结束。 */+async function readUntil(reader: ReadableStreamDefaultReader<Uint8Array>, match: (text: string) => boolean): Promise<string> {+ const decoder = new TextDecoder()+ let text = ''+ for (;;) {+ const { value, done } = await reader.read()+ if (done)+ throw new Error(`stream ended before match: ${text}`)+ text += decoder.decode(value, { stream: true })+ if (match(text))+ return text+ }+}++afterEach(async () => {+ await Promise.all(servers.splice(0).map(instance => new Promise<void>(resolve => instance.close(() => resolve()))))+})++describe('归档推送流', () => {+ it('按归档集合声明 GET 路由', () => {+ const harness = createHarness()+ expect([...harness.registered.keys()]).toEqual([`exact\0${ARCHIVE_STREAM_PATH}`])+ })++ it('接入即给当前快照,随后只在集合变化时推新帧', async () => {+ const harness = createHarness()+ harness.archive(['old'])+ const base = await listen(harness.registered)++ const response = await fetch(`${base}${ARCHIVE_STREAM_PATH}`)+ expect(response.headers.get('content-type')).toContain('text/event-stream')+ const reader = response.body!.getReader()++ let text = await readUntil(reader, chunk => chunk.includes('{"archivedSessionIds":["old"]}'))+ expect(text).toContain(': keepalive')++ harness.archive(['old', 'target'])+ text = await readUntil(reader, chunk => chunk.includes('{"archivedSessionIds":["old","target"]}'))++ harness.archive(['old', 'target'])+ expect(text).not.toContain('["old","target","target"]')++ await reader.cancel()+ for (let attempt = 0; attempt < 50 && harness.listenerCount() !== 0; attempt += 1)+ await new Promise(resolve => setTimeout(resolve, 20))+ expect(harness.listenerCount()).toBe(0)+ })+})diff --git a/packages/dsh-tauri/src/host/server/index.ts b/packages/dsh-tauri/src/host/server/index.tsnew file mode 100644index 00000000..32834a85--- /dev/null+++ b/packages/dsh-tauri/src/host/server/index.ts@@ -0,0 +1,9 @@+import { defineWebServer } from 'dsh-h3'+import { ARCHIVE_STREAM_PATH } from '../../shared/constants'+import { guard } from '../service/request'+import archiveEvents from './routes/archive/events/get'++export const server = defineWebServer((app) => {+ app.use(guard)+ app.get(ARCHIVE_STREAM_PATH, archiveEvents)+})diff --git a/packages/dsh-tauri/src/host/server/routes/archive/events/get.ts b/packages/dsh-tauri/src/host/server/routes/archive/events/get.tsnew file mode 100644index 00000000..31a2c9b8--- /dev/null+++ b/packages/dsh-tauri/src/host/server/routes/archive/events/get.ts@@ -0,0 +1,33 @@+import type { HostContext } from '../../../../types'+import { getServerContext } from 'dsh-h3/utils'+import { defineEventHandler, EventStream } from 'h3'+import { watchArchive } from '../../../../service/archive'++const SSE_KEEPALIVE_COMMENT = 'keepalive'+const SSE_KEEPALIVE_MS = 25_000++/**+ * GET `ARCHIVE_STREAM_PATH` — 归档集合 SSE 流。+ *+ * 数据帧 `data: {"archivedSessionIds":[…]}\n\n`,接入即发当前快照;心跳注释帧+ * `: keepalive\n\n` 防止空闲断连。窗口侧的 `EventSource` 只认数据帧。+ */+export default defineEventHandler((event) => {+ const stream = new EventStream(event)+ // 接入即刷一帧注释:Node 的 writeHead 不会单独把响应头写出去,先让客户端确认连接就绪。+ void stream.pushComment(SSE_KEEPALIVE_COMMENT)++ const ctx = getServerContext<HostContext>(event)+ const detach = watchArchive(ctx, (archived) => {+ void stream.push({ data: JSON.stringify({ archivedSessionIds: archived }) })+ })+ const keepalive = setInterval(() => {+ void stream.pushComment(SSE_KEEPALIVE_COMMENT)+ }, SSE_KEEPALIVE_MS)++ stream.onClosed(() => {+ clearInterval(keepalive)+ detach()+ })+ return stream+})diff --git a/packages/dsh-tauri/src/host/service/archive.ts b/packages/dsh-tauri/src/host/service/archive.tsnew file mode 100644index 00000000..0650e7f1--- /dev/null+++ b/packages/dsh-tauri/src/host/service/archive.ts@@ -0,0 +1,41 @@+import type { HostContext } from '../types'++/**+ * 存储域变更广播:官方把归档集合的变化以 `domain/changed` 发出(会话右栏、归档面板+ * 都靠它刷新),本仓库的宿主类型面没有引入该事件声明,在此收窄一次。+ */+interface DomainChangeSource {+ on: (name: 'domain/changed', listener: () => void) => () => void+}++/**+ * 宿主侧兜底轮询:`domain/changed` 在插件热重载后可能不再送达既有连接,靠这条+ * 兜底保证已打开的窗口仍能收到归档变化(集合未变不会重复推送)。+ */+const ARCHIVE_POLL_MS = 1_000++/**+ * 订阅归档集合:接入即先行推送当前快照(晚连上的窗口也要立刻知道现状),此后集合+ * 变化时再推(事件 + 轮询双通道,去重后只推一次)。+ * @param ctx - 宿主上下文(读注册表的权威归档集合)。+ * @param sink - 每次集合变化收到一份完整归档 id 列表。+ * @returns 取消订阅。+ */+export function watchArchive(ctx: HostContext, sink: (archived: readonly string[]) => void): () => void {+ let delivered = ''+ const push = (): void => {+ const archived = ctx.workspaceRegistry.archivedSessionIds.map(String)+ const next = archived.join('\n')+ if (next === delivered)+ return+ delivered = next+ sink(archived)+ }+ push()+ const poll = setInterval(push, ARCHIVE_POLL_MS)+ const detach = (ctx as unknown as DomainChangeSource).on('domain/changed', push)+ return () => {+ clearInterval(poll)+ detach()+ }+}diff --git a/packages/dsh-tauri/src/index.ts b/packages/dsh-tauri/src/index.tsindex c46b32ad..874902cc 100644--- a/packages/dsh-tauri/src/index.ts+++ b/packages/dsh-tauri/src/index.ts@@ -2,8 +2,8 @@ import { PLUGIN_ID } from './shared/constants'export const name = PLUGIN_ID-/** 宿主服务依赖:`connection`(注入载体标记时覆写它的两道桌面鉴权闸门)。 */-export const inject = ['connection']+/** 宿主服务依赖:`connection`(注入载体标记时覆写它的两道桌面鉴权闸门)、`webServer`/`workspaceRegistry`(归档推送流)。 */+export const inject = ['connection', 'webServer', 'workspaceRegistry']export { apply } from './host/apply'export * from './host/config/constants'diff --git a/packages/dsh-tauri/src/shared/constants.ts b/packages/dsh-tauri/src/shared/constants.tsindex 3d8d6cb1..cbab0433 100644--- a/packages/dsh-tauri/src/shared/constants.ts+++ b/packages/dsh-tauri/src/shared/constants.ts@@ -1 +1,7 @@export const PLUGIN_ID = 'dsh-tauri'++/**+ * 宿主归档集合推送流:宿主侧监听存储域变更后即时下发,窗口侧据此判断自己看的会话+ * 是否已被归档(归档集合没有专属宿主事件,见 `host/service/archive.ts`)。+ */+export const ARCHIVE_STREAM_PATH = '/api/tauri/desktop/archive/events'diff --git a/src-tauri/src/desktop/window.rs b/src-tauri/src/desktop/window.rsindex 43b48eb3..7070cf95 100644--- a/src-tauri/src/desktop/window.rs+++ b/src-tauri/src/desktop/window.rs@@ -121,12 +121,18 @@ pub fn on_page_load(/// 跳转信息全局名(与 `packages/dsh-tauri/src/client/register/navigation.ts` 逐字一致)。const NAVIGATION_GLOBAL: &str = "__DSH_NAVIGATION__";+/// 「全屏右栏」窗口形态:壳层换用 `full-sidebar-navbar`,页面把右栏展开并切进全屏。+/// 载荷值同样与插件 `sidebar-fullwindow.ts` 逐字一致。+const PRESENTATION_FULL_SIDEBAR: &str = "full-sidebar";+/// 壳层导航栏「文件 → 新建窗口」:以同一 `index.html` 再开一个独立 webview 窗口。////// 传入 `session_id` 时把跳转目标注入新窗口的全部 frame,由 dsh-tauri 插件在启动后接收并/// 打开该会话。注入而不是拼 `index.html#...`:hash 只有壳层可读,内嵌 dsh 的插件拿不到,/// 只能退回壳层轮询转发,并把新窗口误当成 remote 视图。///+/// `presentation` 与 `session_id` 同行:壳层读它决定导航栏形态,插件读它把右栏展开成全屏。+////// 异步命令(不占用主线程)是唯一安全的调用侧:`WebviewWindowBuilder::build()`/// 需要主线程事件循环回包,主线程调用会死锁(与 `pet::ensure_pet_window` 同约束)。#[tauri::command]@@ -134,10 +140,23 @@ pub async fn create_app_window(app_handle: AppHandle<Wry>,window: WebviewWindow<Wry>,session_id: Option<String>,+ presentation: Option<String>,) -> Result<(), String> {+ if let Some(value) = presentation.as_deref() {+ if value != PRESENTATION_FULL_SIDEBAR {+ return Err("WINDOW_CREATE_FAILED: unsupported presentation".into());+ }+ if session_id.is_none() {+ return Err("WINDOW_CREATE_FAILED: presentation requires sessionId".into());+ }+ }+ log::info!(+ "[window] create_app_window from {}: session={session_id:?} presentation={presentation:?}",+ window.label()+ );let navigation = session_id.as_deref()- .map(session_navigation_script)+ .map(|session_id| session_navigation_script(session_id, presentation.as_deref())).transpose()?;let _transition = crate::service::workflow::acquire_core_transition().await?;let profile = crate::service::workflow::instances::window_profile(&app_handle, window.label());@@ -151,23 +170,42 @@ pub async fn create_app_window(.map_err(|error| format!("WINDOW_CREATE_FAILED: {error}"))}-/// 校验会话 id 并生成跳转脚本;JSON 序列化负责转义,避免把用户输入拼成可执行代码。-fn session_navigation_script(session_id: &str) -> Result<String, String> {+/// 校验会话 id 与窗口形态并生成跳转脚本;JSON 序列化负责转义,避免把用户输入拼成可执行代码。+fn session_navigation_script(+ session_id: &str,+ presentation: Option<&str>,+) -> Result<String, String> {if session_id.trim().is_empty() || session_id.len() > 512 {return Err("WINDOW_CREATE_FAILED: invalid sessionId".into());}- let payload = serde_json::json!({ "sessionId": session_id });+ let payload = match presentation {+ None => serde_json::json!({ "sessionId": session_id }),+ Some(PRESENTATION_FULL_SIDEBAR) => serde_json::json!({+ "sessionId": session_id,+ "presentation": PRESENTATION_FULL_SIDEBAR,+ }),+ Some(_) => return Err("WINDOW_CREATE_FAILED: unsupported presentation".into()),+ };Ok(format!("globalThis.{NAVIGATION_GLOBAL} = {payload};"))}#[cfg(test)]mod session_navigation_tests {- use super::session_navigation_script;+ use super::{session_navigation_script, NAVIGATION_GLOBAL, PRESENTATION_FULL_SIDEBAR};++ fn payload_of(script: &str) -> serde_json::Value {+ let assignment = format!("globalThis.{NAVIGATION_GLOBAL} = ");+ let payload = script+ .strip_prefix(assignment.as_str())+ .and_then(|rest| rest.strip_suffix(';'))+ .expect("script is one global assignment");+ serde_json::from_str(payload).expect("payload is json")+ }#[test]fn session_navigation_script_assigns_the_session_target_to_the_shared_global() {assert_eq!(- session_navigation_script("session &/?#").unwrap(),+ session_navigation_script("session &/?#", None).unwrap(),r#"globalThis.__DSH_NAVIGATION__ = {"sessionId":"session &/?#"};"#);}@@ -175,20 +213,37 @@ mod session_navigation_tests {#[test]fn session_navigation_script_escapes_values_through_json_serialization() {assert_eq!(- session_navigation_script("a\"b\\c\nd").unwrap(),+ session_navigation_script("a\"b\\c\nd", None).unwrap(),r#"globalThis.__DSH_NAVIGATION__ = {"sessionId":"a\"b\\c\nd"};"#);}+ #[test]+ fn session_navigation_script_carries_the_full_sidebar_presentation() {+ let payload = payload_of(+ &session_navigation_script("session-1", Some(PRESENTATION_FULL_SIDEBAR)).unwrap(),+ );+ assert_eq!(payload["sessionId"], "session-1");+ assert_eq!(payload["presentation"], PRESENTATION_FULL_SIDEBAR);+ }++ #[test]+ fn session_navigation_script_rejects_unknown_presentations() {+ assert_eq!(+ session_navigation_script("session-1", Some("detached")),+ Err("WINDOW_CREATE_FAILED: unsupported presentation".into())+ );+ }+#[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),+ session_navigation_script(id, None),Err("WINDOW_CREATE_FAILED: invalid sessionId".into()));}- assert!(session_navigation_script(&"s".repeat(512)).is_ok());+ assert!(session_navigation_script(&"s".repeat(512), None).is_ok());}}diff --git a/src/layout/components/full-sidebar-navbar.test.tsx b/src/layout/components/full-sidebar-navbar.test.tsxnew file mode 100644index 00000000..cae5e85a--- /dev/null+++ b/src/layout/components/full-sidebar-navbar.test.tsx@@ -0,0 +1,90 @@+// @vitest-environment jsdom+import type { ReactNode } from 'react'+import { mockIPC, mockWindows } from '@tauri-apps/api/mocks'+import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { FullSidebarNavbar } from './full-sidebar-navbar'+import { isFullSidebarWindow } from './window-presentation'++const { native } = vi.hoisted(() => ({ native: vi.fn<(command: string, args?: Record<string, unknown>) => unknown>() }))++vi.mock('@/store', () => ({ store: { desktopUpdater: { updateInfo: null }, setting: { zoom: vi.fn() } } }))+vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))+vi.mock('@tanstack/react-query', () => ({+ useQuery: () => ({ data: [] }),+ useQueryClient: () => ({ ensureQueryData: () => Promise.resolve('dsh-tauri') }),+}))+vi.mock('@overlastic/react', () => ({ useOverlay: () => vi.fn() }))+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))+vi.mock('i18next', () => ({ default: { t: (key: string) => key } }))+vi.mock('@/hooks/use-dsh-style', () => ({ useDshStyle: () => [{}] }))+vi.mock('@/ui/dialog/about', () => ({ DesktopAboutDialog: () => null }))+vi.mock('@/ui/dialog/config', () => ({ ConfigDialog: () => null }))+vi.mock('@/ui/dialog/task-manager', () => ({ TaskManagerDialog: () => null }))+vi.mock('@/ui/dialog/update', () => ({ DesktopUpdateDialog: () => null }))+vi.mock('@/utils/toast', () => ({ toast: vi.fn<(title: string, options?: { description?: ReactNode }) => void>() }))+vi.mock('./remote-switcher', () => ({ RemoteSwitcher: () => null }))+vi.mock('./remote-share', () => ({ RemoteShare: () => null }))++beforeEach(() => {+ native.mockReset().mockImplementation((command) => {+ switch (command) {+ case 'plugin:event|listen':+ return 1+ case 'plugin:window|is_maximized':+ return false+ default:+ return undefined+ }+ })+ mockIPC((command, args) => native(command, args as Record<string, unknown> | undefined))+ mockWindows('window-2')+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ delete (globalThis as Record<string, unknown>).__DSH_NAVIGATION__+})++describe('fullSidebarNavbar', () => {+ it('只留不可交互的布局标记与窗口控制,没有侧栏开关、菜单与远程切换', () => {+ render(<FullSidebarNavbar />)++ expect(screen.getByTestId('dsh-full-sidebar-navbar-root')).toBeTruthy()+ expect(screen.getByTestId('dsh-full-sidebar-navbar-mark').getAttribute('aria-hidden')).toBe('true')+ expect(screen.queryByTestId('dsh-navbar-sidebar-toggle')).toBeNull()+ expect(screen.queryByTestId('dsh-navbar-menu-file')).toBeNull()+ expect(screen.queryByTestId('dsh-navbar-menu-view')).toBeNull()+ expect(screen.queryByTestId('dsh-navbar-menu-help')).toBeNull()+ expect(screen.queryByTestId('dsh-navbar-dev-chip')).toBeNull()+ expect(screen.getByLabelText('nav.minimize')).toBeTruthy()+ })++ it('只有带 presentation=full-sidebar 的注入载荷才算全屏右栏窗口', () => {+ expect(isFullSidebarWindow()).toBe(false)++ ;(globalThis as Record<string, unknown>).__DSH_NAVIGATION__ = { sessionId: 'session-1' }+ expect(isFullSidebarWindow()).toBe(false)++ ;(globalThis as Record<string, unknown>).__DSH_NAVIGATION__ = { sessionId: 'session-1', presentation: 'full-sidebar' }+ expect(isFullSidebarWindow()).toBe(true)+ })++ it('最大化状态按原生窗口回报切换字形', async () => {+ native.mockImplementation((command) => {+ switch (command) {+ case 'plugin:event|listen':+ return 1+ case 'plugin:window|is_maximized':+ return true+ default:+ return undefined+ }+ })+ render(<FullSidebarNavbar />)++ await waitFor(() => expect(screen.getByLabelText('nav.restore')).toBeTruthy())+ })+})diff --git a/src/layout/components/full-sidebar-navbar.tsx b/src/layout/components/full-sidebar-navbar.tsxnew file mode 100644index 00000000..21c909e8--- /dev/null+++ b/src/layout/components/full-sidebar-navbar.tsx@@ -0,0 +1,57 @@+/**+ * 全屏右栏窗口的壳层导航栏。+ *+ * 「右侧栏 → 在新窗口全屏打开」建出的窗口用它(`presentation=full-sidebar`):没有+ * sidebar-toggle、文件/视图/运行/帮助菜单,也没有远程与本地/远端切换——纯全屏阅读形态下+ * 这些都是噪音。左侧那枚 `LayoutHeader` 只是形态标记,不可聚焦、不可点击。+ * 窗口控制保留:非 macOS 的壳层窗口没有原生标题栏,去掉就关不掉。+ */+import { LayoutHeader } from '@gravity-ui/icons'+import { If } from 'react-if-lite'+import { cn } from 'tailwind-variants'+import { useDshStyle } from '@/hooks/use-dsh-style'+import { WindowControls } from './navbar'+import { IS_MACOS, onDragRegionPointerDown, useMacOSFullscreen } from './window-chrome'++export function FullSidebarNavbar() {+ const isFullscreen = useMacOSFullscreen()+ const [dshStyle] = useDshStyle()++ return (+ <div+ className={cn(+ 'relative flex h-11 w-full flex-none select-none items-center gap-0.5 bg-panel',+ {+ 'hidden': IS_MACOS && isFullscreen,+ 'pl-24 pr-1.5': IS_MACOS && !isFullscreen,+ 'px-1.5': !IS_MACOS || isFullscreen,+ },+ )}+ style={{ background: dshStyle.sidebar?.background }}+ data-testid="dsh-full-sidebar-navbar-root"+ >+ <span+ className="pointer-events-none flex size-7 flex-none items-center justify-center text-foreground/40"+ aria-hidden="true"+ data-testid="dsh-full-sidebar-navbar-mark"+ >+ <LayoutHeader />+ </span>++ {/* 拖拽区:与常规导航栏同语义(仅此元素带 data-tauri-drag-region,双击最大化交给 Tauri)。 */}+ <div+ className="min-w-0 flex-1 self-stretch touch-none"+ data-testid="dsh-full-sidebar-navbar-drag-region"+ data-tauri-drag-region+ onPointerDown={onDragRegionPointerDown}+ />++ {/* 纯装饰:镜像 dsh 遮罩底色,让导航栏与页面两段观感连续(同常规导航栏)。 */}+ <div className="absolute" style={dshStyle.marked || {}} />++ <If cond={!IS_MACOS}>+ <WindowControls />+ </If>+ </div>+ )+}diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsxindex f03983a1..b6d607a2 100644--- a/src/layout/components/navbar.tsx+++ b/src/layout/components/navbar.tsx@@ -16,7 +16,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query'import { getIdentifier } from '@tauri-apps/api/app'import { invoke } from '@tauri-apps/api/core'import { getCurrentWindow } from '@tauri-apps/api/window'-import { Fragment, useEffect, useState } from 'react'+import { Fragment, useState } from 'react'import { useTranslation } from 'react-i18next'import { Else, If, Then } from 'react-if-lite'import { cn } from 'tailwind-variants'@@ -34,6 +34,7 @@ import { writeClipboardText } from '@/utils/clipboard'import { toast } from '@/utils/toast'import { RemoteShare } from './remote-share'import { RemoteSwitcher } from './remote-switcher'+import { IS_MACOS, onDragRegionPointerDown, useMacOSFullscreen, useMaximized } from './window-chrome'/*** 壳层窗口顶部导航栏(44px,常驻):@@ -115,107 +116,77 @@ const CONFIG_TABS = [{ id: 'dataDir', labelKey: 'config.dataDir' },] as const-/** WKWebView 的 macOS UA 稳定包含 Macintosh,用于切换平台原生窗口 chrome。 */-function detectMacOS() {- return navigator.userAgent.includes('Macintosh')-}--const IS_MACOS = detectMacOS()--/** macOS 原生全屏时收起整条壳层导航栏。 */-function useMacOSFullscreen() {- const [isFullscreen, setIsFullscreen] = useState(false)-- useEffect(() => {- if (!IS_MACOS)- return-- const appWindow = getCurrentWindow()- let mounted = true- let unlisten: (() => void) | undefined-- async function syncFullscreen() {- try {- const fullscreen = await appWindow.isFullscreen()- if (mounted)- setIsFullscreen(fullscreen)- }- catch (error) {- console.error('[Navbar] failed to sync fullscreen state:', error)- }- }-- async function setupListener() {- try {- await syncFullscreen()- const stopListening = await appWindow.onResized(() => {- void syncFullscreen()- })- if (mounted)- unlisten = stopListening- else- stopListening()- }- catch (error) {- console.error('[Navbar] failed to listen for fullscreen state:', error)- }- }-- void setupListener()- return () => {- mounted = false- unlisten?.()- }- }, [])-- return isFullscreen+function handleWindowAction(action: 'minimize' | 'maximize' | 'close') {+ const appWindow = getCurrentWindow()+ switch (action) {+ case 'minimize':+ void appWindow.minimize()+ break+ case 'maximize':+ void appWindow.toggleMaximize()+ break+ case 'close':+ // 主窗口按设置驻留托盘(hide),附加窗口关闭即销毁:隐藏会留下没有恢复入口、+ // 却仍在监听通知的窗口(点击通知时它们会一起冒出来)。+ if (appWindow.label === 'main')+ void appWindow.hide()+ else+ void appWindow.close()+ break+ }}-/** 最大化状态:Windows/Linux 自绘的最大化按钮据此在「最大化 / 还原」字形间切换(issue #673)。 */-function useMaximized() {- const [isMaximized, setIsMaximized] = useState(false)-- // keep:effect 显式注册/注销原生窗口 onResized 订阅(@reause/core 不覆盖窗口事件)- useEffect(() => {- const appWindow = getCurrentWindow()- let mounted = true- let unlisten: (() => void) | undefined-- async function syncMaximized() {- try {- const maximized = await appWindow.isMaximized()- if (mounted)- setIsMaximized(maximized)- }- catch (error) {- console.error('[Navbar] failed to sync maximized state:', error)- }- }-- async function setupListener() {- try {- await syncMaximized()- const stopListening = await appWindow.onResized(() => {- void syncMaximized()- })- if (mounted)- unlisten = stopListening- else- stopListening()- }- catch (error) {- console.error('[Navbar] failed to listen for maximized state:', error)- }- }-- void setupListener()- return () => {- mounted = false- unlisten?.()- }- }, [])+/**+ * Windows/Linux 自绘窗口控制(最小化 / 最大化切换 / 关闭)。+ *+ * 关闭语义由 Rust 按 label 决定(见 src-tauri/src/desktop/builder.rs 的 CloseRequested):+ * 主窗口按设置驻留托盘或退出,附加窗口直接销毁,这里只在文案上区分两者。+ */+export function WindowControls() {+ const { t } = useTranslation()+ const isMaximized = useMaximized()+ const isMainWindow = getCurrentWindow().label === 'main'- return isMaximized+ return (+ <>+ <Button+ className="size-7"+ isIconOnly+ size="sm"+ variant="ghost"+ aria-label={t('nav.minimize')}+ onPress={() => { handleWindowAction('minimize') }}+ >+ <Minus />+ </Button>++ <Button+ className="size-7"+ isIconOnly+ size="sm"+ variant="ghost"+ aria-label={t(isMaximized ? 'nav.restore' : 'nav.maximize')}+ onPress={() => { handleWindowAction('maximize') }}+ >+ <If+ cond={isMaximized}+ then={<Copy style={{ width: 14, height: 14 }} />}+ else={<Square style={{ width: 14, height: 14 }} />}+ />+ </Button>++ <Button+ className="size-7 transition-colors enabled:hover:bg-danger/16 enabled:hover:text-danger"+ isIconOnly+ size="sm"+ variant="ghost"+ aria-label={t(isMainWindow ? 'nav.background' : 'nav.close')}+ onPress={() => { handleWindowAction('close') }}+ >+ <Xmark />+ </Button>+ </>+ )}/** 菜单项:左侧文案 + 右侧按键提示;没有生效绑定时只渲染文案(布局不变)。 */@@ -255,7 +226,6 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebconst { t } = useTranslation()const queryClient = useQueryClient()const isFullscreen = useMacOSFullscreen()- const isMaximized = useMaximized()const { data: appIdentifier } = useQuery(APP_IDENTIFIER_QUERY)// 只读取「dsh-tauri 插件是否已安装」;查询键与「插件」面板共用(同一份缓存),// 挂载时自动拉取,服务重启 / 插件操作后的失效由 store 与该缓存同步共同保证。@@ -279,35 +249,6 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebconst tauriEnabled = plugins.some(plugin => plugin.id === TAURI_PLUGIN_ID)const isNightly = appIdentifier === 'dsh-tauri-nightly'const showUpdateAvailable = appIdentifier != null && !isNightly && updateInfo != null- const isMainWindow = getCurrentWindow().label === 'main'- function handleWindowAction(action: 'minimize' | 'maximize' | 'close') {- const appWindow = getCurrentWindow()- switch (action) {- case 'minimize':- void appWindow.minimize()- break- case 'maximize':- void appWindow.toggleMaximize()- break- case 'close':- if (isMainWindow)- void appWindow.hide()- else- void appWindow.close()- break- }- }-- function onDragRegionPointerDown(event: React.PointerEvent<HTMLDivElement>) {- // data-tauri-drag-region 原生只监听鼠标事件(mousedown/mouseup),- // 触摸屏/笔输入不会触发原生拖拽(见 tauri#13762)。- // 这里对非鼠标输入手动调用 startDragging 进入系统边拖边跟随。- if (event.pointerType === 'mouse')- return- // 阻止浏览器生成兼容鼠标事件,避免与 data-tauri-drag-region 的原生拖拽重复触发。- event.preventDefault()- void getCurrentWindow().startDragging()- }function onHelpAction(key: HelpAction) {if (key === 'toggle-devtools')@@ -859,42 +800,7 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb<RemoteSwitcher onChange={onRemoteChange} visible={onToggleSidebar != null} onManage={onOpenMachineManager} onSync={onOpenSyncToRemote} /><If cond={!IS_MACOS}>- <Button- className="size-7"- isIconOnly- size="sm"- variant="ghost"- aria-label={t('nav.minimize')}- onPress={() => { handleWindowAction('minimize') }}- >- <Minus />- </Button>-- <Button- className="size-7"- isIconOnly- size="sm"- variant="ghost"- aria-label={t(isMaximized ? 'nav.restore' : 'nav.maximize')}- onPress={() => { handleWindowAction('maximize') }}- >- <If- cond={isMaximized}- then={<Copy style={{ width: 14, height: 14 }} />}- else={<Square style={{ width: 14, height: 14 }} />}- />- </Button>-- <Button- className="size-7 transition-colors enabled:hover:bg-danger/16 enabled:hover:text-danger"- isIconOnly- size="sm"- variant="ghost"- aria-label={t(isMainWindow ? 'nav.background' : 'nav.close')}- onPress={() => { handleWindowAction('close') }}- >- <Xmark />- </Button>+ <WindowControls /></If></div>)diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsxindex 7fe99a2a..cf025f6a 100644--- a/src/layout/components/webview.tsx+++ b/src/layout/components/webview.tsx@@ -3,7 +3,7 @@ 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 { useEffect, useRef, useState } from 'react'import { If } from 'react-if-lite'import { useStore } from 'valtio-define'import { useAppearance } from '@/hooks/use-appearance'@@ -14,11 +14,13 @@ import { useIframePost } from '@/hooks/use-iframe-post'import { useListen } from '@/hooks/use-listen'import { store } from '@/store'import { Recovery } from '@/ui/plugin/recovery'+import { FullSidebarNavbar } from './full-sidebar-navbar'import { Iframe } from './iframe'import { REMOTE_SECTION, REMOTE_TAB_ACCESS, REMOTE_TAB_MACHINES } from './nav-bridge'import { Navbar } from './navbar'import { Setup } from './setup'import { PreinstallSetup } from './setup-preinstall'+import { isFullSidebarWindow } from './window-presentation'interface NavBridgeMessage {type?: string@@ -26,7 +28,10 @@ interface NavBridgeMessage {rows?: unknown}+const FULL_SIDEBAR_REVEAL_MS = 15_000+export function Webview() {+ const [fullSidebarRevealed, setFullSidebarRevealed] = useState(false)const [sidebarCollapsed, setSidebarCollapsed] = useState(false)const iframeRef = useRef<HTMLIFrameElement>(null)const pendingSettingsTabRef = useRef<string | null>(null)@@ -107,6 +112,12 @@ export function Webview() {else if (data.type === 'dsh://shortcuts') {setDshShortcuts({ rows: parseShortcutRows(data.rows) })}+ else if (data.type === 'dsh://full-sidebar:ready') {+ setFullSidebarRevealed(true)+ }+ else if (data.type === 'dsh://window:close') {+ void getCurrentWindow().close()+ }else if (data.type === 'dsh://plugin-boot:ready') {const pending = pendingSettingsTabRef.currentif (pending !== null) {@@ -139,6 +150,17 @@ export function Webview() {}}+ // 窗口形态在进程内不会变:建窗时注入一次载荷,这里读一次就够。+ const fullSidebar = isFullSidebarWindow()++ // 全屏形态窗口先盖住内容区:插件在帧内就位前不露半成品 chrome,兜底超时后强制揭开。+ useEffect(() => {+ if (!fullSidebar || fullSidebarRevealed)+ return+ const timer = window.setTimeout(setFullSidebarRevealed, FULL_SIDEBAR_REVEAL_MS, true)+ return () => window.clearTimeout(timer)+ }, [fullSidebar, fullSidebarRevealed])+const bridge = live? {onToggleSidebar: () => post({ type: 'dsh://sidebar:toggle' }),@@ -155,9 +177,16 @@ export function Webview() {<main className="relative flex flex-col min-h-0 flex-1" style={dshStyle.frame || {}}>{/* 挂在 Iframe 外:启动页/预装引导/恢复页先于 Iframe 渲染,否则拿不到透明与调色板 token */}<style>{appearanceCss}</style>- <Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />+ <If+ cond={fullSidebar}+ then={<FullSidebarNavbar />}+ else={<Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />}+ /><div className="relative flex min-h-0 flex-1">{renderContent()}+ <If cond={fullSidebar && !fullSidebarRevealed && status === 'ready'}>+ <div className="absolute inset-0 z-10" data-testid="dsh-full-sidebar-cover" style={{ background: dshStyle.sidebar?.background }} />+ </If></div></main>)diff --git a/src/layout/components/window-chrome.ts b/src/layout/components/window-chrome.tsnew file mode 100644index 00000000..c5b0f395--- /dev/null+++ b/src/layout/components/window-chrome.ts@@ -0,0 +1,108 @@+import type { PointerEvent } from 'react'+import { getCurrentWindow } from '@tauri-apps/api/window'+import { useEffect, useState } from 'react'++/** WKWebView 的 macOS UA 稳定包含 Macintosh,用于切换平台原生窗口 chrome。 */+export const IS_MACOS = navigator.userAgent.includes('Macintosh')++/** macOS 原生全屏时收起整条壳层导航栏。 */+export function useMacOSFullscreen() {+ const [isFullscreen, setIsFullscreen] = useState(false)++ useEffect(() => {+ if (!IS_MACOS)+ return++ const appWindow = getCurrentWindow()+ let mounted = true+ let unlisten: (() => void) | undefined++ async function syncFullscreen() {+ try {+ const fullscreen = await appWindow.isFullscreen()+ if (mounted)+ setIsFullscreen(fullscreen)+ }+ catch (error) {+ console.error('[Navbar] failed to sync fullscreen state:', error)+ }+ }++ async function setupListener() {+ try {+ await syncFullscreen()+ const stopListening = await appWindow.onResized(() => {+ void syncFullscreen()+ })+ if (mounted)+ unlisten = stopListening+ else+ stopListening()+ }+ catch (error) {+ console.error('[Navbar] failed to listen for fullscreen state:', error)+ }+ }++ void setupListener()+ return () => {+ mounted = false+ unlisten?.()+ }+ }, [])++ return isFullscreen+}++export function useMaximized() {+ const [isMaximized, setIsMaximized] = useState(false)++ useEffect(() => {+ const appWindow = getCurrentWindow()+ let mounted = true+ let unlisten: (() => void) | undefined++ async function syncMaximized() {+ try {+ const maximized = await appWindow.isMaximized()+ if (mounted)+ setIsMaximized(maximized)+ }+ catch (error) {+ console.error('[Navbar] failed to sync maximized state:', error)+ }+ }++ async function setupListener() {+ try {+ await syncMaximized()+ const stopListening = await appWindow.onResized(() => {+ void syncMaximized()+ })+ if (mounted)+ unlisten = stopListening+ else+ stopListening()+ }+ catch (error) {+ console.error('[Navbar] failed to listen for maximized state:', error)+ }+ }++ void setupListener()+ return () => {+ mounted = false+ unlisten?.()+ }+ }, [])++ return isMaximized+}++/** 拖拽区指针处理:`data-tauri-drag-region` 原生只认鼠标,触摸/笔输入要手动进入系统拖拽。 */+export function onDragRegionPointerDown(event: PointerEvent<HTMLDivElement>) {+ if (event.pointerType === 'mouse')+ return+ event.preventDefault()+ void getCurrentWindow().startDragging()+}diff --git a/src/layout/components/window-presentation.ts b/src/layout/components/window-presentation.tsnew file mode 100644index 00000000..25656c64--- /dev/null+++ b/src/layout/components/window-presentation.ts@@ -0,0 +1,18 @@+/** 壳层建窗时注入的全局名(与 `src-tauri/src/desktop/window.rs` 逐字一致)。 */+const NAVIGATION_GLOBAL = '__DSH_NAVIGATION__'++/** 全屏右栏窗口的载荷标记(与插件 `sidebar-fullwindow.ts` 逐字一致)。 */+const PRESENTATION_FULL_SIDEBAR = 'full-sidebar'++/**+ * 本窗口是否由「在新窗口全屏打开」建出。+ *+ * 注入脚本对全部 frame 生效:壳层与内嵌 dsh 各读自己 realm 的同一份载荷,+ * 所以这里读壳层全局,不需要插件经 iframe 转发。+ */+export function isFullSidebarWindow(): boolean {+ const payload = (globalThis as Record<string, unknown>)[NAVIGATION_GLOBAL]+ if (typeof payload !== 'object' || payload === null)+ return false+ return (payload as { presentation?: unknown }).presentation === PRESENTATION_FULL_SIDEBAR+}diff --git a/test/navbar-maximize-icon.test.ts b/test/navbar-maximize-icon.test.tsindex 0446d060..39c19841 100644--- a/test/navbar-maximize-icon.test.ts+++ b/test/navbar-maximize-icon.test.ts@@ -9,6 +9,7 @@ import { describe, expect, it } from 'vitest'import { readLocale, readSource } from './setup/read-source'const navbarSource = readSource('src/layout/components/navbar.tsx')+const chromeSource = readSource('src/layout/components/window-chrome.ts')const zhCN = readLocale('zh-CN')const enUS = readLocale('en-US')@@ -18,8 +19,8 @@ describe('maximize button follows the window state', () => {// 断言「订阅来源」而非孤立 token:初读 + resize 重读缺一不可,// 只留其中一个都会让拖拽区双击 / Win+↑ 等原生路径漏同步。expect(navbarSource).toMatch(/const isMaximized = useMaximized\(\)/)- expect(navbarSource).toMatch(/await appWindow\.isMaximized\(\)/)- expect(navbarSource).toMatch(/await appWindow\.onResized\(/)+ expect(chromeSource).toMatch(/await appWindow\.isMaximized\(\)/)+ expect(chromeSource).toMatch(/await appWindow\.onResized\(/)})it('swaps the glyph between Copy (restore) and Square (maximize)', () => {