Skip to content

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

feat(mobile): 插件自绘移动侧栏抽屉与最小化布局补丁 (#912)

Mao Mrf1339ac77e92
diff --git a/packages/dsh-tauri-mobile-ui/package.json b/packages/dsh-tauri-mobile-ui/package.json
index b5b8a19f..7742190a 100644
--- a/packages/dsh-tauri-mobile-ui/package.json
+++ b/packages/dsh-tauri-mobile-ui/package.json
@@ -28,6 +28,10 @@
"@deepseek-ai/dsh-client-ui-renderer",
"@deepseek-ai/dsh-client-ui-theme",
"@deepseek-ai/dsh-client-locale",
+ "@deepseek-ai/dsh-client-ui-layout",
+ "@deepseek-ai/dsh-api-session-controller",
+ "@deepseek-ai/dsh-client-ui-session",
+ "@deepseek-ai/dsh-client-ui-workspace",
"dsh-tauri",
"dsh-tauri-ui"
],
diff --git a/packages/dsh-tauri-mobile-ui/src/client/index.test.ts b/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
index cf606958..75738f59 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/index.test.ts
@@ -1,20 +1,42 @@
+// @vitest-environment jsdom
import { afterEach, expect, it, vi } from 'vitest'
import { apply, inject, name } from './index'
+import { locale } from './locales'
+import { installBridgeConfig, registerBridgeConfig } from './register/bridge'
import { registerMobilePreferences } from './register/preferences'
+import { registerMobileSidebar } from './register/sidebar'
import { registerStyles } from './register/styles'
+vi.mock('./locales', () => ({
+ locale: { registerLocale: vi.fn() },
+}))
+vi.mock('./register/bridge', () => ({
+ installBridgeConfig: vi.fn(() => {
+ window.__DSH_BRIDGE_CONFIG__ = { disablePageTweaks: true }
+ }),
+ registerBridgeConfig: vi.fn(),
+}))
vi.mock('./register/preferences', () => ({ registerMobilePreferences: vi.fn() }))
+vi.mock('./register/sidebar', () => ({ registerMobileSidebar: vi.fn() }))
vi.mock('./register/styles', () => ({ registerStyles: vi.fn() }))
-afterEach(() => vi.restoreAllMocks())
+afterEach(() => {
+ delete window.__DSH_BRIDGE_CONFIG__
+ vi.restoreAllMocks()
+})
-it('assembles mobile-only effects under its own plugin identity', () => {
+it('assembles mobile-only effects and yields bridge page tweaks early', () => {
const effect = vi.fn()
apply({ effect } as unknown as Parameters<typeof apply>[0])
expect(name).toBe('dsh-tauri-mobile-ui')
- expect(inject).toEqual(['slots', 'locale'])
+ expect(inject).toEqual(['slots', 'layout', 'locale', 'sessions'])
+ expect(installBridgeConfig).toHaveBeenCalledTimes(1)
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
expect(effect.mock.calls).toEqual([
+ [registerBridgeConfig, 'dsh-tauri-mobile-ui: bridge'],
+ [locale.registerLocale, 'dsh-tauri-mobile-ui: locale'],
[registerStyles, 'dsh-tauri-mobile-ui: styles'],
[registerMobilePreferences, 'dsh-tauri-mobile-ui: preferences'],
+ [registerMobileSidebar, 'dsh-tauri-mobile-ui: sidebar'],
])
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/index.ts b/packages/dsh-tauri-mobile-ui/src/client/index.ts
index 9f5a582c..87b8e547 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/index.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/index.ts
@@ -1,12 +1,20 @@
+import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type { ClientContext } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../shared/constants'
+import { locale } from './locales'
+import { installBridgeConfig, registerBridgeConfig } from './register/bridge'
import { registerMobilePreferences } from './register/preferences'
+import { registerMobileSidebar } from './register/sidebar'
import { registerStyles } from './register/styles'
export const name = PLUGIN_ID
-export const inject = ['slots', 'locale']
+export const inject = ['slots', 'layout', 'locale', 'sessions']
export function apply(ctx: ClientContext): void {
+ installBridgeConfig()
+ ctx.effect(registerBridgeConfig, `${PLUGIN_ID}: bridge`)
+ ctx.effect(locale.registerLocale, `${PLUGIN_ID}: locale`)
ctx.effect(registerStyles, `${PLUGIN_ID}: styles`)
ctx.effect(registerMobilePreferences, `${PLUGIN_ID}: preferences`)
+ ctx.effect(registerMobileSidebar, `${PLUGIN_ID}: sidebar`)
}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts b/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts
new file mode 100644
index 00000000..0a024432
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/locales/index.ts
@@ -0,0 +1,28 @@
+import { defineLocale } from 'dsh-tauri/client'
+import { PLUGIN_ID } from '../../shared/constants'
+
+const zh = {
+ 'toggle.open': '打开侧边栏',
+ 'toggle.close': '收起侧边栏',
+ 'shade.close': '关闭侧边栏',
+ 'navbar.label': '会话导航',
+ 'session.new': '新会话',
+ 'session.failed': '无法新建会话,请重试',
+} as const
+
+const en: Record<keyof typeof zh, string> = {
+ 'toggle.open': 'Open sidebar',
+ 'toggle.close': 'Close sidebar',
+ 'shade.close': 'Close sidebar',
+ 'navbar.label': 'Conversation navigation',
+ 'session.new': 'New Session',
+ 'session.failed': 'Unable to start a session. Please try again.',
+}
+
+declare module '@deepseek-ai/dsh-client-ui-slots' {
+ interface LocaleNamespaceMap {
+ 'dsh-tauri-mobile-ui': keyof typeof zh
+ }
+}
+
+export const locale = defineLocale(PLUGIN_ID, { zh, en })
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/bridge.test.ts b/packages/dsh-tauri-mobile-ui/src/client/register/bridge.test.ts
new file mode 100644
index 00000000..bc636402
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/bridge.test.ts
@@ -0,0 +1,133 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('dsh-tauri/client', () => ({
+ defineRegister: (setup: (controller: { add: (dispose: () => void) => void }) => void) => () => {
+ const cleanups: Array<() => void> = []
+ setup({ add: dispose => cleanups.push(dispose) })
+ return () => cleanups.splice(0).reverse().forEach(dispose => dispose())
+ },
+}))
+
+const initialConfig = Object.getOwnPropertyDescriptor(window, '__DSH_BRIDGE_CONFIG__')
+const disposers: Array<() => void> = []
+
+beforeEach(() => {
+ vi.resetModules()
+ delete window.__DSH_BRIDGE_CONFIG__
+})
+
+afterEach(() => {
+ disposers.splice(0).reverse().forEach(dispose => dispose())
+ if (initialConfig)
+ Object.defineProperty(window, '__DSH_BRIDGE_CONFIG__', initialConfig)
+ else
+ delete window.__DSH_BRIDGE_CONFIG__
+ vi.restoreAllMocks()
+})
+
+describe('bridge configuration ownership', () => {
+ it('installs the opt-out during module evaluation when configuration is absent', async () => {
+ await import('./bridge')
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ })
+
+ it('installs the opt-out when the initial configuration is explicitly undefined', async () => {
+ window.__DSH_BRIDGE_CONFIG__ = undefined
+ const bridge = await import('./bridge')
+ disposers.push(bridge.registerBridgeConfig())
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ })
+
+ it('keeps the installed object stable across repeated installs and registration', async () => {
+ const bridge = await import('./bridge')
+ const installed = window.__DSH_BRIDGE_CONFIG__
+ expect(installed).toEqual({ disablePageTweaks: true })
+ bridge.installBridgeConfig()
+ bridge.installBridgeConfig()
+ disposers.push(bridge.registerBridgeConfig())
+ expect(window.__DSH_BRIDGE_CONFIG__).toBe(installed)
+ })
+
+ it('reinstalls the opt-out during registration if the early configuration was removed', async () => {
+ const bridge = await import('./bridge')
+ delete window.__DSH_BRIDGE_CONFIG__
+ disposers.push(bridge.registerBridgeConfig())
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ })
+
+ it('restores the exact preexisting object captured before controller setup', async () => {
+ const previous = Object.freeze({ disablePageTweaks: false })
+ window.__DSH_BRIDGE_CONFIG__ = previous
+ const bridge = await import('./bridge')
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ expect(window.__DSH_BRIDGE_CONFIG__).not.toBe(previous)
+ bridge.installBridgeConfig()
+ const dispose = bridge.registerBridgeConfig()
+ disposers.push(dispose)
+ dispose()
+ expect(window.__DSH_BRIDGE_CONFIG__).toBe(previous)
+ })
+
+ it('removes its owned configuration on disposal when no prior object existed', async () => {
+ const bridge = await import('./bridge')
+ const dispose = bridge.registerBridgeConfig()
+ disposers.push(dispose)
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ dispose()
+ expect(Object.hasOwn(window, '__DSH_BRIDGE_CONFIG__')).toBe(false)
+ })
+
+ it('preserves another owner that replaces the configuration after registration', async () => {
+ window.__DSH_BRIDGE_CONFIG__ = { disablePageTweaks: false }
+ const bridge = await import('./bridge')
+ const dispose = bridge.registerBridgeConfig()
+ disposers.push(dispose)
+ const later = { disablePageTweaks: true }
+ window.__DSH_BRIDGE_CONFIG__ = later
+ dispose()
+ expect(window.__DSH_BRIDGE_CONFIG__).toBe(later)
+ })
+
+ it('reinstalls the opt-out after disposal without resetting the module', async () => {
+ const bridge = await import('./bridge')
+ const firstDispose = bridge.registerBridgeConfig()
+ disposers.push(firstDispose)
+ firstDispose()
+ expect(Object.hasOwn(window, '__DSH_BRIDGE_CONFIG__')).toBe(false)
+ const secondDispose = bridge.registerBridgeConfig()
+ disposers.push(secondDispose)
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ secondDispose()
+ expect(Object.hasOwn(window, '__DSH_BRIDGE_CONFIG__')).toBe(false)
+ })
+
+ it('captures the current owner when reapplied after disposal', async () => {
+ const bridge = await import('./bridge')
+ const firstDispose = bridge.registerBridgeConfig()
+ disposers.push(firstDispose)
+ firstDispose()
+ const previous = { disablePageTweaks: false }
+ window.__DSH_BRIDGE_CONFIG__ = previous
+ const secondDispose = bridge.registerBridgeConfig()
+ disposers.push(secondDispose)
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ secondDispose()
+ expect(window.__DSH_BRIDGE_CONFIG__).toBe(previous)
+ })
+
+ it('supports module reload after disposal without leaking configuration', async () => {
+ const first = await import('./bridge')
+ const firstDispose = first.registerBridgeConfig()
+ disposers.push(firstDispose)
+ firstDispose()
+ expect(Object.hasOwn(window, '__DSH_BRIDGE_CONFIG__')).toBe(false)
+ vi.resetModules()
+ const second = await import('./bridge')
+ const secondDispose = second.registerBridgeConfig()
+ disposers.push(secondDispose)
+ expect(window.__DSH_BRIDGE_CONFIG__).toEqual({ disablePageTweaks: true })
+ secondDispose()
+ expect(Object.hasOwn(window, '__DSH_BRIDGE_CONFIG__')).toBe(false)
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/bridge.ts b/packages/dsh-tauri-mobile-ui/src/client/register/bridge.ts
new file mode 100644
index 00000000..591078bf
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/bridge.ts
@@ -0,0 +1,57 @@
+import type { ClientContext } from 'dsh-tauri/client'
+import { defineRegister } from 'dsh-tauri/client'
+
+const CONFIG_KEY = '__DSH_BRIDGE_CONFIG__'
+interface BridgeConfig {
+ disablePageTweaks?: boolean
+}
+
+let previousConfig: BridgeConfig | undefined
+let configCaptured = false
+let installedConfig: BridgeConfig | undefined
+
+declare global {
+ interface Window {
+ __DSH_BRIDGE_CONFIG__?: BridgeConfig
+ }
+}
+
+export function installBridgeConfig(): void {
+ if (typeof window === 'undefined')
+ return
+
+ if (!configCaptured) {
+ previousConfig = window[CONFIG_KEY]
+ configCaptured = true
+ }
+
+ if (installedConfig !== undefined && window[CONFIG_KEY] === installedConfig)
+ return
+
+ installedConfig = { disablePageTweaks: true }
+ window[CONFIG_KEY] = installedConfig
+}
+
+function restoreBridgeConfig(): void {
+ if (typeof window === 'undefined' || !configCaptured)
+ return
+
+ if (window[CONFIG_KEY] === installedConfig) {
+ if (previousConfig === undefined)
+ delete window[CONFIG_KEY]
+ else
+ window[CONFIG_KEY] = previousConfig
+ }
+
+ previousConfig = undefined
+ installedConfig = undefined
+ configCaptured = false
+}
+
+export const registerBridgeConfig = defineRegister<ClientContext>((controller) => {
+ installBridgeConfig()
+ controller.add(restoreBridgeConfig)
+})
+
+// keep:effect dsh-bridge probes once before Cordis effects; install the opt-out during module evaluation.
+installBridgeConfig()
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx
new file mode 100644
index 00000000..e2f577fb
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.test.tsx
@@ -0,0 +1,752 @@
+// @vitest-environment jsdom
+import type { ComponentType } from 'react'
+import type { LifecycleController } from '../../../../dsh-tauri/src/client/controller'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createLifecycleController } from '../../../../dsh-tauri/src/client/controller'
+import { defineAdapter } from '../../../../dsh-tauri/src/client/register/index.adapter'
+
+import { registerMobileSidebar } from './sidebar'
+
+interface TestContext {
+ layout: {
+ toggleSidebar: () => void
+ selectPanel: (panel: string | null) => void
+ }
+ slots: {
+ inject: (slot: string, activate: () => () => void) => () => void
+ register: (options: unknown, component: ComponentType) => () => void
+ }
+}
+
+const mocks = vi.hoisted(() => ({
+ mobile: true,
+ component: undefined as ComponentType | undefined,
+ parentHandler: undefined as ((message: { type?: string }) => void) | undefined,
+ invokeParent: vi.fn(),
+ listenParent: vi.fn(),
+ sessions: undefined as unknown,
+ sessionListeners: new Set<() => void>(),
+ startSession: vi.fn(),
+}))
+
+vi.mock('dsh-tauri/client', () => ({
+ defineLocale: (namespace: string, dictionaries: Record<string, unknown>) => ({
+ NS: namespace,
+ text: (key: string) => key,
+ useLocale: () => 'en',
+ registerLocale: vi.fn(),
+ ...dictionaries,
+ }),
+ MOBILE_MEDIA_QUERIES: ['(hover: none)', '(any-pointer: coarse)', '(any-hover: none)'],
+ detectMobileDevice: () => mocks.mobile,
+ invokeParent: mocks.invokeParent,
+ listenParent: mocks.listenParent,
+ defineRegister: (setup: (controller: LifecycleController, ctx: unknown, adapter: unknown) => void) => function (this: unknown) {
+ const controller = createLifecycleController()
+ setup(controller, this, {
+ sessions: {
+ list: {
+ getSnapshot: () => mocks.sessions,
+ subscribe: (listener: () => void) => {
+ mocks.sessionListeners.add(listener)
+ return () => mocks.sessionListeners.delete(listener)
+ },
+ },
+ },
+ startSession: mocks.startSession,
+ })
+ return () => controller.dispose()
+ },
+}))
+
+vi.mock('../locales', () => ({
+ locale: {
+ NS: 'dsh-tauri-mobile-ui',
+ text: (key: string) => ({
+ 'toggle.open': 'Open sidebar',
+ 'toggle.close': 'Close sidebar',
+ 'shade.close': 'Close sidebar',
+ 'navbar.label': 'Conversation navigation',
+ 'session.new': 'New Session',
+ 'session.failed': 'Unable to start a session. Please try again.',
+ }[key] ?? key),
+ useLocale: () => 'en',
+ registerLocale: vi.fn(),
+ },
+}))
+
+vi.mock('dsh-tauri-ui/client', async () => ({
+ ...await import('../../../../dsh-tauri-ui/src/client/components/icons'),
+ ...await import('../../../../dsh-tauri-ui/src/client/components/icon'),
+}))
+
+const disposers: Array<() => void> = []
+
+function setupFrame(): { sidebar: HTMLElement, center: HTMLElement, main: HTMLElement, overlay: HTMLElement } {
+ document.body.innerHTML = '<div class="pI_x6G_frame" data-rightbar-collapsed><div class="pI_x6G_sidebarCol"></div><div class="pI_x6G_centerCol"><div data-slot="main"><div data-conversation-scroll></div></div></div><div data-shell-overlay></div></div>'
+ const frame = document.querySelector<HTMLElement>('[data-shell-overlay]')?.parentElement
+ if (frame === null || frame === undefined)
+ throw new Error('Missing layout frame')
+ return {
+ sidebar: frame.querySelector<HTMLElement>('[class$="_sidebarCol"]')!,
+ center: frame.querySelector<HTMLElement>('[class$="_centerCol"]')!,
+ main: frame.querySelector<HTMLElement>('[data-slot="main"]')!,
+ overlay: frame.querySelector<HTMLElement>('[data-shell-overlay]')!,
+ }
+}
+
+function renderOverlay(overlay: HTMLElement): void {
+ const Component = mocks.component
+ if (Component === undefined)
+ throw new Error('Sidebar overlay was not registered')
+ render(<Component />, { container: overlay })
+}
+
+function touch(target: Element, type: string, x: number, y: number, time: number, count = 1, cancelable = true): Event {
+ const event = new Event(type, { bubbles: true, cancelable })
+ const point = { identifier: 1, clientX: x, clientY: y }
+ Object.defineProperties(event, {
+ touches: { value: type === 'touchend' || type === 'touchcancel' ? [] : Array.from({ length: count }, (_, index) => ({ ...point, identifier: index + 1 })) },
+ changedTouches: { value: [point] },
+ timeStamp: { value: time },
+ })
+ fireEvent(target, event)
+ return event
+}
+
+function pointer(target: Element, type: string, x: number, y: number, time: number, pointerType = 'mouse', buttons = type === 'pointerup' ? 0 : 1): Event {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ pointerId: { value: 7 },
+ pointerType: { value: pointerType },
+ isPrimary: { value: true },
+ button: { value: 0 },
+ buttons: { value: buttons },
+ clientX: { value: x },
+ clientY: { value: y },
+ timeStamp: { value: time },
+ })
+ fireEvent(target, event)
+ return event
+}
+
+function register(layout: Partial<TestContext['layout']> = {}): { dispose: () => void, ctx: TestContext } {
+ const ctx: TestContext = {
+ layout: {
+ toggleSidebar: vi.fn(),
+ selectPanel: vi.fn(),
+ ...layout,
+ },
+ slots: {
+ inject: (_slot, activate) => activate(),
+ register: (_options, component) => {
+ mocks.component = component
+ return vi.fn()
+ },
+ },
+ }
+ const dispose = registerMobileSidebar.call(ctx)
+ disposers.push(dispose)
+ return { dispose, ctx }
+}
+
+beforeEach(() => {
+ const inertValues = new WeakMap<HTMLElement, boolean>()
+ Object.defineProperty(HTMLElement.prototype, 'inert', {
+ configurable: true,
+ get(this: HTMLElement) {
+ return inertValues.get(this) ?? false
+ },
+ set(this: HTMLElement, value: boolean) {
+ inertValues.set(this, value)
+ },
+ })
+ cleanup()
+ document.documentElement.removeAttribute('data-dsh-mobile-sidebar')
+ document.documentElement.removeAttribute('data-dsh-mobile-sidebar-open')
+ document.documentElement.removeAttribute('data-dsh-mobile-sidebar-dragging')
+ document.body.innerHTML = ''
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: 390, writable: true })
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn((query: string) => ({
+ matches: true,
+ media: query,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ })),
+ })
+ mocks.mobile = true
+ mocks.component = undefined
+ mocks.parentHandler = undefined
+ mocks.invokeParent.mockReset()
+ mocks.listenParent.mockReset()
+ mocks.sessions = { ids: [], byId: {} }
+ mocks.sessionListeners.clear()
+ mocks.startSession.mockReset().mockResolvedValue({ status: 'started' })
+ mocks.listenParent.mockImplementation((handler: (message: { type?: string }) => void) => {
+ mocks.parentHandler = handler
+ return vi.fn()
+ })
+})
+
+afterEach(() => {
+ disposers.splice(0).reverse().forEach(dispose => dispose())
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('registerMobileSidebar', () => {
+ it('uses the same sidebar glyph as the desktop navbar and an outlined circle-plus without button wrappers', () => {
+ const { overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const toggle = screen.getByRole('button', { name: 'Open sidebar' })
+ const plus = screen.getByRole('button', { name: 'New Session' })
+ const sidebarPath = 'M6 3.5h6A1.5 1.5 0 0 1 13.5 5v6a1.5 1.5 0 0 1-1.5 1.5H6zm-1.5 0H4A1.5 1.5 0 0 0 2.5 5v6A1.5 1.5 0 0 0 4 12.5h.5zM1 5a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3v6a3 3 0 0 1-3 3H4a3 3 0 0 1-3-3z'
+ const circlePlusPath = 'M13.5 8a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0M8.75 5.5a.75.75 0 0 0-1.5 0v1.75H5.5a.75.75 0 1 0 0 1.5h1.75v1.75a.75.75 0 0 0 1.5 0V8.75h1.75a.75.75 0 0 0 0-1.5H8.75z'
+ expect(toggle.querySelector('path')?.getAttribute('d')).toBe(sidebarPath)
+ expect(plus.querySelector('path')?.getAttribute('d')).toBe(circlePlusPath)
+ expect(toggle.closest('button')).toBeNull()
+ expect(plus.closest('button')).toBeNull()
+ fireEvent.click(toggle)
+ expect(toggle.querySelector('path')?.getAttribute('d')).toBe(sidebarPath)
+ })
+
+ it('keeps navigation in the moving center while only drawer/main content becomes inert', () => {
+ const { sidebar, center, main, overlay } = setupFrame()
+ sidebar.setAttribute('aria-hidden', 'false')
+ main.setAttribute('aria-hidden', 'false')
+ const { dispose, ctx } = register()
+ renderOverlay(overlay)
+ const toggle = screen.getByRole('button', { name: 'Open sidebar' })
+
+ expect(toggle.tagName.toLowerCase()).toBe('svg')
+ expect(toggle.closest('button')).toBeNull()
+ expect(center.firstElementChild).toBe(toggle.closest('[data-dsh-mobile-navbar-host]'))
+ expect(toggle.closest('[data-shell-overlay]')).toBeNull()
+ expect(sidebar.getAttribute('aria-hidden')).toBe('true')
+ expect(sidebar.inert).toBe(true)
+ expect(main.inert).toBe(false)
+ toggle.focus()
+ fireEvent.click(toggle)
+
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ expect(sidebar.getAttribute('aria-hidden')).toBe('false')
+ expect(sidebar.inert).toBe(false)
+ expect(main.getAttribute('aria-hidden')).toBe('true')
+ expect(main.inert).toBe(true)
+ expect(center.inert).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('319px')
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-shadow')).toBe('')
+ expect(mocks.invokeParent).toHaveBeenCalledWith({ type: 'dsh://sidebar:collapsed', collapsed: false })
+
+ fireEvent.click(overlay.querySelector('[data-dsh-mobile-sidebar-shade]')!)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(document.activeElement).toBe(toggle)
+ expect(mocks.invokeParent).toHaveBeenLastCalledWith({ type: 'dsh://sidebar:collapsed', collapsed: true })
+
+ dispose()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false)
+ expect(document.querySelector('[data-dsh-mobile-navbar-host]')).toBeNull()
+ expect(sidebar.getAttribute('aria-hidden')).toBe('false')
+ expect(sidebar.inert).toBe(false)
+ expect(main.getAttribute('aria-hidden')).toBe('false')
+ expect(main.inert).toBe(false)
+ expect(ctx.layout.toggleSidebar).not.toHaveBeenCalled()
+ expect(mocks.sessionListeners.size).toBe(0)
+ })
+
+ it('closes with a touch swipe on the real shell-overlay shade', () => {
+ const { overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ const shade = overlay.querySelector<HTMLElement>('[data-dsh-mobile-sidebar-shade]')!
+
+ touch(shade, 'touchstart', 365, 220, 100)
+ const move = touch(shade, 'touchmove', 175, 222, 200)
+ expect(move.defaultPrevented).toBe(true)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('129px')
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ touch(shade, 'touchend', 145, 222, 240)
+
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ expect(mocks.invokeParent).toHaveBeenLastCalledWith({ type: 'dsh://sidebar:collapsed', collapsed: true })
+ })
+
+ it('opens by swiping main content instead of requiring a screen-edge start', () => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const content = main.querySelector<HTMLElement>('[data-conversation-scroll]')!
+
+ touch(content, 'touchstart', 140, 300, 100)
+ const move = touch(content, 'touchmove', 300, 302, 300)
+ expect(move.defaultPrevented).toBe(true)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('160px')
+ touch(content, 'touchend', 320, 302, 400)
+
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('319px')
+ })
+
+ it.each(['shade', 'center', 'frame'])('suppresses a swipe compatibility click retargeted to the %s without swallowing unrelated controls', (surface) => {
+ const { main, center, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const content = main.querySelector<HTMLElement>('[data-conversation-scroll]')!
+ const shade = overlay.querySelector<HTMLElement>('[data-dsh-mobile-sidebar-shade]')!
+ const frame = overlay.parentElement!
+ const target = surface === 'shade' ? shade : surface === 'center' ? center : frame
+ const onRetarget = vi.fn()
+ target.addEventListener('click', onRetarget)
+ touch(content, 'touchstart', 140, 300, 100)
+ touch(content, 'touchmove', 300, 302, 300)
+ touch(content, 'touchend', 330, 302, 400)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ fireEvent.click(target)
+ expect(onRetarget).not.toHaveBeenCalled()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ fireEvent.click(shade)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ touch(content, 'touchstart', 140, 300, 500)
+ touch(content, 'touchmove', 300, 302, 700)
+ touch(content, 'touchend', 330, 302, 800)
+ fireEvent.click(document.querySelector('[data-dsh-mobile-sidebar-toggle]')!)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ })
+
+ it('keeps vertical scrolls, editable targets, and other overlays outside the drawer gesture', () => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const input = document.createElement('textarea')
+ main.append(input)
+ const otherOverlay = document.createElement('div')
+ overlay.append(otherOverlay)
+ for (const target of [input, otherOverlay]) {
+ touch(target, 'touchstart', 10, 300, 100)
+ expect(touch(target, 'touchmove', 250, 302, 300).defaultPrevented).toBe(false)
+ touch(target, 'touchend', 250, 302, 400)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ }
+ touch(main, 'touchstart', 10, 300, 100)
+ expect(touch(main, 'touchmove', 15, 380, 300).defaultPrevented).toBe(false)
+ touch(main, 'touchend', 15, 380, 400)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ })
+
+ it('supports mouse/pen pointers on mobile without double-processing touch pointer streams', () => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ pointer(main, 'pointerdown', 100, 200, 100, 'touch')
+ expect(pointer(main, 'pointermove', 300, 200, 200, 'touch').defaultPrevented).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ pointer(main, 'pointerdown', 100, 200, 100)
+ expect(pointer(main, 'pointermove', 300, 200, 200).defaultPrevented).toBe(true)
+ touch(main, 'touchstart', 10, 200, 200)
+ touch(main, 'touchmove', 20, 200, 220)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('200px')
+ pointer(main, 'pointerup', 320, 200, 240)
+ const shade = overlay.querySelector<HTMLElement>('[data-dsh-mobile-sidebar-shade]')!
+ pointer(shade, 'pointerdown', 360, 200, 300, 'pen')
+ expect(pointer(shade, 'pointermove', 140, 200, 400, 'pen').defaultPrevented).toBe(true)
+ pointer(shade, 'pointerup', 120, 200, 450, 'pen')
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ })
+
+ it.each(['release', 'lost', 'buttons', 'dispose'])('captures only a claimed mouse drag and releases it on %s', (reason) => {
+ const { main, overlay } = setupFrame()
+ const frame = overlay.parentElement!
+ const capture = vi.fn()
+ const release = vi.fn()
+ let captured = false
+ Object.defineProperties(frame, {
+ setPointerCapture: { value: (id: number) => {
+ captured = true
+ capture(id)
+ } },
+ hasPointerCapture: { value: () => captured },
+ releasePointerCapture: { value: (id: number) => {
+ captured = false
+ release(id)
+ } },
+ })
+ const { dispose } = register()
+ renderOverlay(overlay)
+ pointer(main, 'pointerdown', 100, 200, 100)
+ expect(capture).not.toHaveBeenCalled()
+ expect(pointer(main, 'pointermove', 105, 200, 130).defaultPrevented).toBe(false)
+ expect(capture).not.toHaveBeenCalled()
+ pointer(main, 'pointermove', 200, 200, 300)
+ expect(capture).toHaveBeenCalledWith(7)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ if (reason === 'release') {
+ pointer(frame, 'pointerup', 200, 200, 500)
+ }
+ else if (reason === 'lost') {
+ captured = false
+ pointer(frame, 'lostpointercapture', 200, 200, 500)
+ }
+ else if (reason === 'buttons') {
+ expect(pointer(frame, 'pointermove', 300, 200, 500, 'mouse', 0).defaultPrevented).toBe(false)
+ }
+ else {
+ act(() => dispose())
+ }
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ if (reason === 'dispose') {
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('')
+ }
+ else {
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ }
+ const released = release.mock.calls.length
+ if (reason === 'lost') {
+ expect(released).toBe(0)
+ }
+ else {
+ expect(released).toBe(1)
+ expect(release).toHaveBeenCalledWith(7)
+ }
+ if (reason !== 'dispose') {
+ pointer(main, 'pointerdown', 100, 200, 600)
+ pointer(main, 'pointermove', 300, 200, 900)
+ pointer(frame, 'pointerup', 300, 200, 1200)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ }
+ })
+
+ it.each(['content', 'main', 'frame'])('cancels a claimed touch gesture when its %s is detached at the same viewport width', async (part) => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const content = main.querySelector<HTMLElement>('[data-conversation-scroll]')!
+ touch(content, 'touchstart', 100, 200, 100)
+ touch(content, 'touchmove', 260, 200, 300)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ const original = part === 'content' ? content : part === 'main' ? main : overlay.parentElement!
+ await act(async () => {
+ const replacement = original.cloneNode(true) as HTMLElement
+ if (part === 'frame')
+ replacement.querySelector('[data-dsh-mobile-navbar-host]')?.remove()
+ original.replaceWith(replacement)
+ })
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ const replacement = document.querySelector('[data-conversation-scroll]')!
+ touch(replacement, 'touchstart', 100, 200, 400)
+ touch(replacement, 'touchmove', 300, 200, 700)
+ touch(replacement, 'touchend', 300, 200, 1000)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ })
+
+ it('never toggles core preferences to refresh mobile ownership across the desktop breakpoint', async () => {
+ setupFrame()
+ let desktopWidth = 350
+ let narrowExpanded = false
+ const toggleSidebar = vi.fn(() => {
+ if (window.innerWidth < 1024)
+ narrowExpanded = !narrowExpanded
+ else
+ desktopWidth = desktopWidth === 0 ? 280 : 0
+ })
+ const { dispose } = register({ toggleSidebar })
+ window.innerWidth = 1200
+ fireEvent(window, new Event('resize'))
+ await act(async () => {
+ dispose()
+ })
+ expect(toggleSidebar).not.toHaveBeenCalled()
+ expect(desktopWidth).toBe(350)
+ expect(narrowExpanded).toBe(false)
+ })
+
+ it.each(['cancel', 'multitouch', 'noncancelable', 'resize'])('cancels an in-progress swipe on %s', (reason) => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ touch(main, 'touchstart', 100, 200, 100)
+ touch(main, 'touchmove', 260, 200, 200)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(true)
+ if (reason === 'cancel')
+ touch(main, 'touchcancel', 300, 200, 300)
+ else if (reason === 'multitouch')
+ touch(main, 'touchmove', 300, 200, 300, 2)
+ else if (reason === 'noncancelable')
+ touch(main, 'touchmove', 300, 200, 300, 1, false)
+ else
+ fireEvent(window, new Event('resize'))
+ touch(main, 'touchend', 360, 200, 400)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(document.documentElement.style.getPropertyValue('--dsh-mobile-sidebar-offset')).toBe('0px')
+ })
+
+ it('preserves horizontal scrollers, selected text, and navbar controls', () => {
+ const { main, overlay } = setupFrame()
+ register()
+ renderOverlay(overlay)
+ const code = document.createElement('pre')
+ code.style.overflowX = 'auto'
+ Object.defineProperties(code, { scrollWidth: { value: 500 }, clientWidth: { value: 100 } })
+ main.append(code)
+ const toggle = screen.getByRole('button', { name: 'Open sidebar' })
+ for (const target of [code, toggle]) {
+ touch(target, 'touchstart', 100, 200, 100)
+ expect(touch(target, 'touchmove', 300, 200, 200).defaultPrevented).toBe(false)
+ touch(target, 'touchend', 320, 200, 300)
+ }
+ const selection = window.getSelection()!
+ vi.spyOn(selection, 'isCollapsed', 'get').mockReturnValue(false)
+ touch(main, 'touchstart', 100, 200, 100)
+ expect(touch(main, 'touchmove', 300, 200, 200).defaultPrevented).toBe(false)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ })
+
+ it.each([140, 220])('suppresses the swipe-origin click after ending at x=%i and still allows unrelated controls', (endX) => {
+ const { sidebar, overlay } = setupFrame()
+ const row = document.createElement('button')
+ row.textContent = 'Existing session'
+ sidebar.append(row)
+ const onRow = vi.fn()
+ row.addEventListener('click', onRow)
+ register()
+ renderOverlay(overlay)
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ touch(row, 'touchstart', 220, 200, 100)
+ touch(row, 'touchmove', 140, 200, 300)
+ touch(row, 'touchmove', endX, 200, 400)
+ touch(row, 'touchend', endX, 200, 600)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ fireEvent.click(row)
+ expect(onRow).not.toHaveBeenCalled()
+ fireEvent.click(document.querySelector('[data-dsh-mobile-sidebar-toggle]')!)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ fireEvent.click(row)
+ expect(onRow).toHaveBeenCalledTimes(1)
+ })
+
+ it('reconciles delayed/replaced frames and restores all owned DOM state on unload', async () => {
+ const root = document.documentElement
+ root.style.setProperty('--dsh-mobile-sidebar-width', '7px')
+ vi.spyOn(root.style, 'getPropertyPriority').mockImplementation(name => name === '--dsh-mobile-sidebar-width' ? 'important' : '')
+ const setProperty = vi.spyOn(root.style, 'setProperty')
+ const { ctx, dispose } = register()
+ expect(ctx.layout.toggleSidebar).not.toHaveBeenCalled()
+ const { center, main, sidebar, overlay } = setupFrame()
+ renderOverlay(overlay)
+ await waitFor(() => expect(center.querySelector('[data-dsh-mobile-topbar]')).not.toBeNull())
+ expect(ctx.layout.toggleSidebar).not.toHaveBeenCalled()
+ const toggle = screen.getByRole('button', { name: 'Open sidebar' })
+ toggle.focus()
+ fireEvent.click(toggle)
+ const replacementMain = document.createElement('div')
+ replacementMain.setAttribute('data-slot', 'main')
+ main.replaceWith(replacementMain)
+ await waitFor(() => expect(replacementMain.inert).toBe(true))
+ expect(main.inert).toBe(false)
+ const replacementSidebar = document.createElement('div')
+ replacementSidebar.className = 'new_sidebarCol'
+ sidebar.replaceWith(replacementSidebar)
+ await waitFor(() => expect(document.activeElement).toBe(replacementSidebar))
+ fireEvent.keyDown(document, { key: 'Escape' })
+ expect(document.activeElement).toBe(toggle)
+ act(() => dispose())
+ expect(replacementMain.inert).toBe(false)
+ expect(replacementSidebar.getAttribute('tabindex')).toBeNull()
+ expect(root.style.getPropertyValue('--dsh-mobile-sidebar-width')).toBe('7px')
+ expect(setProperty).toHaveBeenCalledWith('--dsh-mobile-sidebar-width', '7px', 'important')
+ root.style.removeProperty('--dsh-mobile-sidebar-width')
+ })
+
+ it('hands the layout back at the desktop breakpoint without leftover navigation or gesture', () => {
+ const { main, overlay } = setupFrame()
+ const { dispose } = register()
+ renderOverlay(overlay)
+ touch(main, 'touchstart', 100, 200, 100)
+ touch(main, 'touchmove', 260, 200, 200)
+ window.innerWidth = 1200
+ fireEvent(window, new Event('resize'))
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-dragging')).toBe(false)
+ expect(document.querySelector('[data-dsh-mobile-navbar-host]')).toBeNull()
+ expect(main.inert).toBe(false)
+ dispose()
+ })
+
+ it('follows active titles, renames, and blank sessions without reading DOM titles', () => {
+ const { overlay } = setupFrame()
+ mocks.sessions = { current: 'selected', byId: { selected: { title: 'First title', blank: false } } }
+ register()
+ renderOverlay(overlay)
+ const title = document.querySelector('[data-dsh-mobile-navbar-title]')!
+ expect(title.textContent).toBe('First title')
+ act(() => {
+ mocks.sessions = { current: 'selected', byId: { selected: { title: 'Renamed title', blank: false } } }
+ mocks.sessionListeners.forEach(listener => listener())
+ })
+ expect(title.textContent).toBe('Renamed title')
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ act(() => {
+ mocks.sessions = { current: 'new', byId: { new: { title: 'Stale title', blank: true } } }
+ mocks.sessionListeners.forEach(listener => listener())
+ })
+ expect(title.textContent).toBe('New Session')
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ })
+
+ it('creates sessions through the adapter from a naked keyboard-accessible plus icon', async () => {
+ const { overlay } = setupFrame()
+ const { ctx } = register()
+ renderOverlay(overlay)
+ const plus = screen.getByRole('button', { name: 'New Session' })
+ const toggle = screen.getByRole('button', { name: 'Open sidebar' })
+ expect(plus.tagName.toLowerCase()).toBe('svg')
+ expect(plus.closest('button')).toBeNull()
+ fireEvent.keyDown(toggle, { key: ' ' })
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+ let finish: (result: { status: 'started' }) => void = () => {}
+ mocks.startSession.mockImplementationOnce(() => new Promise((resolve) => {
+ finish = resolve
+ }))
+ fireEvent.keyDown(plus, { key: 'Enter' })
+ fireEvent.keyDown(plus, { key: 'Enter', repeat: true })
+ fireEvent.click(plus)
+ expect(mocks.startSession).toHaveBeenCalledTimes(1)
+ expect(plus.getAttribute('aria-disabled')).toBe('true')
+ await act(async () => {
+ finish({ status: 'started' })
+ })
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(plus.getAttribute('aria-disabled')).toBe('false')
+ fireEvent.keyDown(plus, { key: ' ' })
+ await waitFor(() => expect(mocks.startSession).toHaveBeenCalledTimes(2))
+ })
+
+ it.each(['unavailable', 'rejected'])('keeps failure %s visible and allows retry', async (status) => {
+ const { overlay } = setupFrame()
+ const { ctx } = register()
+ renderOverlay(overlay)
+ if (status === 'unavailable')
+ mocks.startSession.mockResolvedValueOnce({ status, reason: 'Unavailable test capability' })
+ else
+ mocks.startSession.mockRejectedValueOnce(new Error('Test navigation failed'))
+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
+ expect(await screen.findByRole('status')).toHaveProperty('textContent', 'Unable to start a session. Please try again.')
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
+ await waitFor(() => expect(screen.queryByRole('status')).toBeNull())
+ expect(mocks.startSession).toHaveBeenCalledTimes(2)
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ })
+
+ it('does not abort pending native navigation when the official startSession returns void', async () => {
+ const { overlay } = setupFrame()
+ const { ctx } = register()
+ renderOverlay(overlay)
+ const navigation = new AbortController()
+ vi.mocked(ctx.layout.selectPanel).mockImplementation(() => navigation.abort())
+ let finishConnect: (id: string) => void = () => {}
+ const connect = new Promise<string>((resolve) => {
+ finishConnect = resolve
+ })
+ const selectSession = vi.fn()
+ const start = vi.fn(() => {
+ void connect.then((id) => {
+ if (!navigation.signal.aborted) {
+ selectSession(id)
+ ctx.layout.selectPanel(null)
+ }
+ })
+ })
+ const adapter = defineAdapter({ uiWorkspace: { startSession: start } })
+ mocks.startSession.mockImplementation(() => adapter.startSession())
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
+ })
+ expect(start).toHaveBeenCalledTimes(1)
+ expect(navigation.signal.aborted).toBe(false)
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ expect(selectSession).not.toHaveBeenCalled()
+ await act(async () => {
+ finishConnect('created')
+ })
+ expect(selectSession).toHaveBeenCalledWith('created')
+ expect(ctx.layout.selectPanel).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not touch layout or DOM when new-session navigation settles after unload', async () => {
+ const { overlay } = setupFrame()
+ const { ctx, dispose } = register()
+ renderOverlay(overlay)
+ let finish: (result: { status: 'started' }) => void = () => {}
+ mocks.startSession.mockImplementationOnce(() => new Promise((resolve) => {
+ finish = resolve
+ }))
+ fireEvent.click(screen.getByRole('button', { name: 'New Session' }))
+ act(() => dispose())
+ await act(async () => {
+ finish({ status: 'started' })
+ })
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ expect(document.querySelector('[data-dsh-mobile-navbar-host]')).toBeNull()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false)
+ })
+
+ it('yields to an open rightbar and resumes closed without changing core layout state', async () => {
+ const { main, overlay } = setupFrame()
+ const frame = overlay.parentElement!
+ const { ctx } = register()
+ renderOverlay(overlay)
+ fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' }))
+ expect(main.inert).toBe(true)
+
+ act(() => frame.removeAttribute('data-rightbar-collapsed'))
+ await waitFor(() => expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false))
+ expect(main.inert).toBe(false)
+ expect(document.querySelector('[data-dsh-mobile-navbar-host]')).toBeNull()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+
+ act(() => frame.setAttribute('data-rightbar-collapsed', ''))
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeInstanceOf(SVGElement))
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(true)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(false)
+ expect(ctx.layout.toggleSidebar).not.toHaveBeenCalled()
+ expect(ctx.layout.selectPanel).not.toHaveBeenCalled()
+ })
+
+ it('does not take ownership when the native rightbar is already visible', () => {
+ const { overlay } = setupFrame()
+ overlay.parentElement!.removeAttribute('data-rightbar-collapsed')
+ register()
+ renderOverlay(overlay)
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false)
+ expect(document.querySelector('[data-dsh-mobile-navbar-host]')).toBeNull()
+ expect(screen.queryByRole('navigation')).toBeNull()
+ })
+
+ it('maps the host toggle command to the drawer and remains inactive on desktop', () => {
+ setupFrame()
+ const { dispose } = register()
+ const Component = mocks.component
+ if (Component === undefined)
+ throw new Error('Sidebar overlay was not registered')
+ render(<Component />)
+
+ mocks.parentHandler?.({ type: 'dsh://sidebar:toggle' })
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar-open')).toBe(true)
+
+ dispose()
+ mocks.mobile = false
+ const desktop = register()
+ expect(document.documentElement.hasAttribute('data-dsh-mobile-sidebar')).toBe(false)
+ desktop.dispose()
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx
new file mode 100644
index 00000000..16c2799c
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/sidebar.tsx
@@ -0,0 +1,600 @@
+import type { ClientContext, ParentMessage } from 'dsh-tauri/client'
+import type { KeyboardEvent } from 'react'
+import type { SidebarGesture, SidebarGesturePoint } from '../service/sidebar-gesture'
+import { CirclePlus, Icon, LayoutSideContentLeft } from 'dsh-tauri-ui/client'
+import {
+ defineRegister,
+ detectMobileDevice,
+ invokeParent,
+ listenParent,
+ MOBILE_MEDIA_QUERIES,
+} from 'dsh-tauri/client'
+import { useSyncExternalStore } from 'react'
+import { createPortal } from 'react-dom'
+import { PLUGIN_ID } from '../../shared/constants'
+import { locale } from '../locales'
+import { createSidebarGesture, finishSidebarGesture, moveSidebarGesture, SIDEBAR_CLICK_SUPPRESSION_MS } from '../service/sidebar-gesture'
+import { getMobileSessionId, getMobileSessionTitle } from '../service/sidebar-session'
+
+const SHELL_OVERLAY_SLOT = 'shell.overlay'
+const SIDEBAR_TOGGLE_COMMAND = 'dsh://sidebar:toggle'
+const SIDEBAR_COLLAPSED_EVENT = 'dsh://sidebar:collapsed'
+const SIDEBAR_BREAKPOINT = 1024
+const SIDEBAR_PROPERTIES = [
+ '--dsh-mobile-sidebar-width',
+ '--dsh-mobile-sidebar-offset',
+] as const
+const LAYOUT_SELECTOR = '[data-shell-overlay], [class$="_frame"], [class$="_sidebarCol"], [class$="_centerCol"], [data-slot="main"]'
+
+interface SidebarSnapshot {
+ mobile: boolean
+ open: boolean
+ dragging: boolean
+ offset: number
+ width: number
+ starting: boolean
+ startFailed: boolean
+}
+
+interface ActiveGesture {
+ state: SidebarGesture
+ target: Element
+ frame: HTMLElement
+ source: 'touch' | 'pointer'
+}
+
+interface InlineProperty {
+ value: string
+ priority: string
+}
+
+function getSidebarWidth(): number {
+ return Math.min(320, Math.max(1, Math.floor(window.innerWidth * 0.82)))
+}
+
+function getFrame(): HTMLElement | null {
+ return document.querySelector<HTMLElement>('[data-shell-overlay]')?.parentElement ?? null
+}
+
+function canOwnMobileSidebar(): boolean {
+ const frame = getFrame()
+ return detectMobileDevice() && window.innerWidth < SIDEBAR_BREAKPOINT
+ && (frame === null || frame.hasAttribute('data-rightbar-collapsed'))
+}
+
+function canStartGesture(target: EventTarget | null, frame: HTMLElement): target is Element {
+ if (!(target instanceof Element) || !frame.contains(target))
+ return false
+ if (target.closest('input,textarea,select,[contenteditable]') !== null)
+ return false
+ if (target.closest('[data-dsh-mobile-sidebar-toggle], [data-dsh-mobile-new-session]') !== null)
+ return false
+ if (target.closest('[data-shell-overlay]') !== null && target.closest('[data-dsh-mobile-sidebar-shade]') === null)
+ return false
+ if (window.getSelection()?.isCollapsed === false)
+ return false
+ let current: Element | null = target
+ while (current !== null && current !== frame) {
+ const style = getComputedStyle(current)
+ if ((style.overflowX === 'auto' || style.overflowX === 'scroll') && current.scrollWidth > current.clientWidth + 1)
+ return false
+ current = current.parentElement
+ }
+ return true
+}
+
+function eventTime(event: Event): number {
+ return event.timeStamp || performance.now()
+}
+
+function touchPoint(touch: Touch, event: TouchEvent): SidebarGesturePoint {
+ return { id: touch.identifier, x: touch.clientX, y: touch.clientY, time: eventTime(event) }
+}
+
+function pointerPoint(event: PointerEvent): SidebarGesturePoint {
+ return { id: event.pointerId, x: event.clientX, y: event.clientY, time: eventTime(event) }
+}
+
+function activateIcon(event: KeyboardEvent<SVGSVGElement>, activate: () => void): void {
+ if (event.key !== 'Enter' && event.key !== ' ')
+ return
+ event.preventDefault()
+ if (!event.repeat)
+ activate()
+}
+
+function safeReportCollapsed(collapsed: boolean): void {
+ try {
+ invokeParent({ type: SIDEBAR_COLLAPSED_EVENT, collapsed })
+ }
+ catch { }
+}
+
+export const registerMobileSidebar = defineRegister<ClientContext>((controller, ctx, adapter) => {
+ if (typeof document === 'undefined' || typeof window === 'undefined')
+ return
+
+ const root = document.documentElement
+ const previousProperties = new Map<string, InlineProperty>(SIDEBAR_PROPERTIES.map(name => [name, {
+ value: root.style.getPropertyValue(name),
+ priority: root.style.getPropertyPriority(name),
+ }]))
+ const navbarHost = document.createElement('div')
+ navbarHost.setAttribute('data-dsh-mobile-navbar-host', '')
+ const listeners = new Set<() => void>()
+ const notify = (): void => listeners.forEach(listener => listener())
+ const subscribe = (listener: () => void): (() => void) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ }
+ let snapshot: SidebarSnapshot = {
+ mobile: canOwnMobileSidebar(),
+ open: false,
+ dragging: false,
+ offset: 0,
+ width: getSidebarWidth(),
+ starting: false,
+ startFailed: false,
+ }
+ const getSnapshot = (): SidebarSnapshot => snapshot
+ const getNavbarHost = (): HTMLElement | null => navbarHost.isConnected ? navbarHost : null
+ const sessionSource = adapter.sessions.list
+ const getSessionSnapshot = (): unknown => sessionSource?.getSnapshot()
+ let selectedSession = getMobileSessionId(getSessionSnapshot())
+ let gesture: ActiveGesture | null = null
+ let suppressClickUntil = 0
+ let suppressedClickTarget: Element | null = null
+ let suppressedClickFrame: HTMLElement | null = null
+ const accessibility = new Map<HTMLElement, { ariaHidden: string | null, inert: boolean }>()
+ let focusRestoreTarget: HTMLElement | SVGElement | null = null
+ let focusedDrawer: { element: HTMLElement, tabIndex: string | null } | null = null
+ let focusDrawerOnOpen = false
+
+ const clearGesture = (): void => {
+ const current = gesture
+ gesture = null
+ if (current?.source === 'pointer' && current.state.axis === 'x'
+ && typeof current.frame.hasPointerCapture === 'function'
+ && current.frame.hasPointerCapture(current.state.id)) {
+ current.frame.releasePointerCapture(current.state.id)
+ }
+ }
+ const restoreFocusedDrawer = (): void => {
+ if (focusedDrawer === null)
+ return
+ if (focusedDrawer.tabIndex === null)
+ focusedDrawer.element.removeAttribute('tabindex')
+ else
+ focusedDrawer.element.setAttribute('tabindex', focusedDrawer.tabIndex)
+ focusedDrawer = null
+ }
+ const restoreFocusTarget = (): void => {
+ const target = focusRestoreTarget
+ focusRestoreTarget = null
+ focusDrawerOnOpen = false
+ restoreFocusedDrawer()
+ if (target?.isConnected)
+ target.focus({ preventScroll: true })
+ }
+ const syncAccessibility = (): void => {
+ const frame = getFrame()
+ const sidebar = frame?.querySelector<HTMLElement>('[class$="_sidebarCol"]')
+ const main = frame?.querySelector<HTMLElement>('[class$="_centerCol"] > [data-slot="main"]')
+ const targets = new Map<HTMLElement, boolean>()
+ if (snapshot.mobile && sidebar)
+ targets.set(sidebar, !snapshot.open)
+ if (snapshot.mobile && main)
+ targets.set(main, snapshot.open)
+ for (const [element, state] of accessibility) {
+ if (targets.get(element) === true)
+ continue
+ if (state.ariaHidden === null)
+ element.removeAttribute('aria-hidden')
+ else
+ element.setAttribute('aria-hidden', state.ariaHidden)
+ element.inert = state.inert
+ accessibility.delete(element)
+ }
+ for (const [element, inert] of targets) {
+ if (!inert)
+ continue
+ if (!accessibility.has(element)) {
+ accessibility.set(element, {
+ ariaHidden: element.getAttribute('aria-hidden'),
+ inert: element.inert,
+ })
+ }
+ element.inert = true
+ element.setAttribute('aria-hidden', 'true')
+ }
+ if (snapshot.mobile && snapshot.open && focusedDrawer !== null && !focusedDrawer.element.isConnected)
+ focusDrawerOnOpen = true
+ if (snapshot.mobile && snapshot.open && focusDrawerOnOpen) {
+ const drawer = sidebar?.querySelector<HTMLElement>('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])') ?? sidebar
+ if (drawer) {
+ if (focusedDrawer?.element !== drawer) {
+ restoreFocusedDrawer()
+ focusedDrawer = { element: drawer, tabIndex: drawer.getAttribute('tabindex') }
+ if (!drawer.matches('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'))
+ drawer.tabIndex = -1
+ }
+ drawer.focus({ preventScroll: true })
+ focusDrawerOnOpen = false
+ }
+ }
+ }
+ const reconcileFrame = (): void => {
+ const previousHost = getNavbarHost()
+ const frame = getFrame()
+ if (gesture !== null && (frame !== gesture.frame || !gesture.target.isConnected || !frame?.contains(gesture.target)))
+ resetGesture()
+ const center = snapshot.mobile ? frame?.querySelector<HTMLElement>('[class$="_centerCol"]') : null
+ if (center) {
+ if (center.firstElementChild !== navbarHost)
+ center.prepend(navbarHost)
+ }
+ else {
+ navbarHost.remove()
+ }
+ syncAccessibility()
+ if (previousHost !== getNavbarHost())
+ notify()
+ }
+ const restoreProperties = (): void => {
+ previousProperties.forEach((property, name) => {
+ if (property.value !== '')
+ root.style.setProperty(name, property.value, property.priority)
+ else
+ root.style.removeProperty(name)
+ })
+ }
+ const syncDom = (): void => {
+ root.toggleAttribute('data-dsh-mobile-sidebar', snapshot.mobile)
+ root.toggleAttribute('data-dsh-mobile-sidebar-open', snapshot.mobile && snapshot.open)
+ root.toggleAttribute('data-dsh-mobile-sidebar-dragging', snapshot.mobile && snapshot.dragging)
+ if (snapshot.mobile) {
+ root.style.setProperty(SIDEBAR_PROPERTIES[0], `${snapshot.width}px`)
+ root.style.setProperty(SIDEBAR_PROPERTIES[1], `${snapshot.offset}px`)
+ }
+ else {
+ restoreProperties()
+ }
+ reconcileFrame()
+ }
+ const publish = (next: SidebarSnapshot): void => {
+ if (
+ next.mobile === snapshot.mobile && next.open === snapshot.open
+ && next.dragging === snapshot.dragging && next.offset === snapshot.offset
+ && next.width === snapshot.width && next.starting === snapshot.starting
+ && next.startFailed === snapshot.startFailed
+ ) {
+ return
+ }
+ snapshot = next
+ syncDom()
+ notify()
+ }
+ const setOpen = (open: boolean, report = true): void => {
+ if (!snapshot.mobile || controller.isDisposed())
+ return
+ const wasOpen = snapshot.open
+ const changed = open !== wasOpen || snapshot.dragging
+ clearGesture()
+ if (open && !wasOpen) {
+ focusDrawerOnOpen = true
+ const active = document.activeElement
+ focusRestoreTarget = (active instanceof HTMLElement || active instanceof SVGElement)
+ && active !== document.body && !active.closest('[data-dsh-mobile-sidebar-shade]')
+ ? active
+ : null
+ }
+ publish({ ...snapshot, open, dragging: false, offset: open ? snapshot.width : 0 })
+ if (!open && wasOpen)
+ restoreFocusTarget()
+ if (changed && report)
+ safeReportCollapsed(!open)
+ }
+ // keep:function `reconcileFrame` 属于 publish → syncDom → reconcileFrame 环,声明式函数才能在环内前向引用。
+ function resetGesture(): void {
+ clearGesture()
+ publish({ ...snapshot, dragging: false, offset: snapshot.open ? snapshot.width : 0 })
+ }
+ const syncMobile = (): void => {
+ const mobile = canOwnMobileSidebar()
+ const width = getSidebarWidth()
+ const wasMobile = snapshot.mobile
+ if (!mobile) {
+ clearGesture()
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ publish({ ...snapshot, mobile: false, open: false, dragging: false, offset: 0, width, startFailed: false })
+ if (wasMobile) {
+ restoreFocusTarget()
+ controller.timeout(() => safeReportCollapsed(getFrame()?.hasAttribute('data-sidebar-collapsed') === true), 0)
+ }
+ return
+ }
+ if (width !== snapshot.width)
+ clearGesture()
+ publish({
+ ...snapshot,
+ mobile: true,
+ width,
+ dragging: gesture !== null && snapshot.dragging,
+ offset: gesture !== null && snapshot.dragging ? Math.min(width, snapshot.offset) : snapshot.open ? width : 0,
+ })
+ if (!wasMobile)
+ safeReportCollapsed(!snapshot.open)
+ }
+ const toggle = (): void => setOpen(!snapshot.open)
+ const startSession = async (): Promise<void> => {
+ if (!snapshot.mobile || snapshot.starting || controller.isDisposed())
+ return
+ publish({ ...snapshot, starting: true, startFailed: false })
+ try {
+ const outcome = await adapter.startSession()
+ if (controller.isDisposed())
+ return
+ if (outcome.status === 'unavailable') {
+ publish({ ...snapshot, starting: false, startFailed: true })
+ return
+ }
+ // Native startSession may return void before navigation finishes; its owner reveals the session.
+ if (snapshot.mobile)
+ setOpen(false)
+ publish({ ...snapshot, starting: false })
+ }
+ catch {
+ if (!controller.isDisposed())
+ publish({ ...snapshot, starting: false, startFailed: true })
+ }
+ }
+
+ syncDom()
+ if (snapshot.mobile)
+ safeReportCollapsed(!snapshot.open)
+ if (sessionSource) {
+ controller.add(sessionSource.subscribe(() => {
+ const selected = getMobileSessionId(getSessionSnapshot())
+ if (selected !== selectedSession && snapshot.open)
+ setOpen(false)
+ selectedSession = selected
+ notify()
+ }))
+ }
+ controller.add(listenParent<ParentMessage>(() => toggle(), SIDEBAR_TOGGLE_COMMAND))
+ controller.listen('keydown', (event) => {
+ if (event.key === 'Escape' && !event.defaultPrevented && snapshot.mobile && snapshot.open)
+ setOpen(false)
+ })
+ controller.listen('click', (event) => {
+ const target = event.target
+ if (performance.now() >= suppressClickUntil || suppressedClickTarget === null || !(target instanceof Element))
+ return
+ const frame = suppressedClickFrame
+ const retargeted = frame?.contains(target) && (target.closest('[data-dsh-mobile-sidebar-shade]') !== null
+ || target === frame || target === frame.querySelector('[class$="_centerCol"]'))
+ if (!suppressedClickTarget.contains(target) && !retargeted)
+ return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ suppressClickUntil = 0
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ }, { capture: true })
+
+ const beginGesture = (point: SidebarGesturePoint, target: EventTarget | null, source: ActiveGesture['source']): void => {
+ const frame = getFrame()
+ if (!snapshot.mobile || gesture !== null || frame === null || !canStartGesture(target, frame))
+ return
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ gesture = { state: createSidebarGesture(point, snapshot.open, snapshot.width), target, frame, source }
+ }
+ const moveGesture = (point: SidebarGesturePoint, event: TouchEvent | PointerEvent, source: ActiveGesture['source']): void => {
+ if (gesture === null || gesture.source !== source || gesture.state.id !== point.id)
+ return
+ const result = moveSidebarGesture(gesture.state, point, snapshot.width, event.cancelable)
+ if (result.gesture === null) {
+ resetGesture()
+ return
+ }
+ const claimed = gesture.state.axis === null && result.gesture.axis === 'x'
+ gesture.state = result.gesture
+ if (result.offset === undefined)
+ return
+ if (claimed && source === 'pointer' && typeof gesture.frame.setPointerCapture === 'function')
+ gesture.frame.setPointerCapture(point.id)
+ event.preventDefault()
+ publish({ ...snapshot, dragging: true, offset: result.offset })
+ }
+ const endGesture = (point: SidebarGesturePoint | undefined, cancelled: boolean, source: ActiveGesture['source']): void => {
+ if (gesture === null || gesture.source !== source || (point !== undefined && gesture.state.id !== point.id))
+ return
+ const current = gesture
+ const result = cancelled ? null : finishSidebarGesture(current.state, point, snapshot.width)
+ clearGesture()
+ if (result === null) {
+ resetGesture()
+ return
+ }
+ setOpen(result.open)
+ suppressedClickTarget = result.suppressClick ? current.target : null
+ suppressedClickFrame = result.suppressClick ? current.frame : null
+ suppressClickUntil = result.suppressClick ? performance.now() + SIDEBAR_CLICK_SUPPRESSION_MS : 0
+ }
+ controller.listen('touchstart', (event) => {
+ if (event.touches.length !== 1) {
+ if (gesture?.source === 'touch')
+ resetGesture()
+ return
+ }
+ if (!event.defaultPrevented)
+ beginGesture(touchPoint(event.touches[0], event), event.target, 'touch')
+ }, { passive: true })
+ controller.listen('touchmove', (event) => {
+ if (gesture?.source !== 'touch')
+ return
+ if (event.touches.length !== 1) {
+ resetGesture()
+ return
+ }
+ const touch = [...event.touches].find(point => point.identifier === gesture?.state.id)
+ if (touch)
+ moveGesture(touchPoint(touch, event), event, 'touch')
+ }, { passive: false })
+ const endTouch = (event: TouchEvent, cancelled: boolean): void => {
+ const touch = [...event.changedTouches].find(point => point.identifier === gesture?.state.id)
+ if (touch || cancelled)
+ endGesture(touch ? touchPoint(touch, event) : undefined, cancelled, 'touch')
+ }
+ controller.listen('touchend', event => endTouch(event, false))
+ controller.listen('touchcancel', event => endTouch(event, true))
+ controller.listen('pointerdown', (event) => {
+ if (event.pointerType !== 'touch' && event.button === 0 && event.isPrimary !== false && !event.defaultPrevented)
+ beginGesture(pointerPoint(event), event.target, 'pointer')
+ })
+ controller.listen('pointermove', (event) => {
+ if (event.pointerType === 'touch')
+ return
+ if (gesture?.source === 'pointer' && event.buttons === 0) {
+ resetGesture()
+ return
+ }
+ moveGesture(pointerPoint(event), event, 'pointer')
+ }, { passive: false })
+ controller.listen('pointerup', (event) => {
+ if (event.pointerType !== 'touch')
+ endGesture(pointerPoint(event), false, 'pointer')
+ })
+ controller.listen('pointercancel', (event) => {
+ if (event.pointerType !== 'touch')
+ endGesture(pointerPoint(event), true, 'pointer')
+ })
+ controller.listen('lostpointercapture', (event) => {
+ if (gesture?.source === 'pointer' && gesture.state.id === event.pointerId)
+ resetGesture()
+ })
+ controller.listenWindow('blur', () => resetGesture())
+
+ const resize = (): void => {
+ resetGesture()
+ syncMobile()
+ reconcileFrame()
+ }
+ controller.listenWindow('resize', resize)
+ if (typeof window.matchMedia === 'function') {
+ MOBILE_MEDIA_QUERIES.forEach((query) => {
+ const media = window.matchMedia(query)
+ if (typeof media.addEventListener === 'function') {
+ media.addEventListener('change', resize)
+ controller.add(() => media.removeEventListener('change', resize))
+ }
+ else if (typeof media.addListener === 'function') {
+ media.addListener(resize)
+ controller.add(() => media.removeListener(resize))
+ }
+ })
+ }
+ controller.observe(root, (records) => {
+ const layoutChanged = records.some((record) => {
+ if (record.type === 'attributes')
+ return record.target instanceof Element && record.target.matches(`${LAYOUT_SELECTOR}, [data-sidebar-collapsed], [data-dsh-mobile-sidebar]`)
+ if (record.target instanceof Element && record.target.matches('[class$="_frame"], [class$="_centerCol"]'))
+ return true
+ if (focusedDrawer !== null && !focusedDrawer.element.isConnected)
+ return true
+ if (gesture !== null && (!gesture.target.isConnected || !gesture.frame.isConnected))
+ return true
+ return [...record.addedNodes, ...record.removedNodes].some(node => node instanceof Element
+ && (node.matches(LAYOUT_SELECTOR) || node.querySelector(LAYOUT_SELECTOR) !== null))
+ })
+ if (layoutChanged) {
+ syncMobile()
+ reconcileFrame()
+ }
+ }, {
+ attributes: true,
+ attributeFilter: ['class', 'data-shell-overlay', 'data-sidebar-collapsed', 'data-rightbar-collapsed', 'data-dsh-mobile-sidebar'],
+ childList: true,
+ subtree: true,
+ })
+ controller.add(() => {
+ listeners.clear()
+ clearGesture()
+ suppressedClickTarget = null
+ suppressedClickFrame = null
+ suppressClickUntil = 0
+ snapshot = { ...snapshot, mobile: false, open: false, dragging: false, offset: 0 }
+ syncDom()
+ restoreFocusTarget()
+ safeReportCollapsed(getFrame()?.hasAttribute('data-sidebar-collapsed') === true)
+ })
+
+ controller.add(ctx.slots.inject(SHELL_OVERLAY_SLOT, () => ctx.slots.register(
+ {
+ name: SHELL_OVERLAY_SLOT,
+ id: `${PLUGIN_ID}-mobile-sidebar-overlay`,
+ order: 20,
+ locale: locale.NS,
+ registrant: PLUGIN_ID,
+ },
+ () => {
+ locale.useLocale()
+ const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)
+ const host = useSyncExternalStore(subscribe, getNavbarHost, () => null)
+ const sessions = useSyncExternalStore(subscribe, getSessionSnapshot, getSessionSnapshot)
+ if (!current.mobile)
+ return null
+ const title = getMobileSessionTitle(sessions) ?? locale.text('session.new')
+ return (
+ <>
+ {host && createPortal(
+ <nav data-dsh-mobile-topbar aria-label={locale.text('navbar.label')}>
+ <Icon
+ as={LayoutSideContentLeft}
+ size={12}
+ data-dsh-mobile-sidebar-toggle
+ role="button"
+ tabIndex={0}
+ focusable="true"
+ aria-label={locale.text(current.open ? 'toggle.close' : 'toggle.open')}
+ aria-expanded={current.open}
+ onClick={toggle}
+ onKeyDown={event => activateIcon(event, toggle)}
+ />
+ <span data-dsh-mobile-navbar-title title={title}>{title}</span>
+ <Icon
+ as={CirclePlus}
+ size={24}
+ data-dsh-mobile-new-session
+ role="button"
+ tabIndex={0}
+ focusable="true"
+ aria-label={locale.text('session.new')}
+ aria-disabled={current.starting}
+ aria-busy={current.starting}
+ onClick={() => { void startSession() }}
+ onKeyDown={event => activateIcon(event, () => { void startSession() })}
+ />
+ {current.startFailed && <span data-dsh-mobile-navbar-status role="status">{locale.text('session.failed')}</span>}
+ </nav>,
+ host,
+ )}
+ <div data-dsh-mobile-sidebar-overlay data-dsh-mobile-sidebar-dragging={current.dragging || undefined}>
+ <button
+ type="button"
+ data-dsh-mobile-sidebar-shade
+ aria-label={locale.text('shade.close')}
+ aria-hidden={!current.open}
+ tabIndex={current.open ? 0 : -1}
+ onClick={() => setOpen(false)}
+ />
+ </div>
+ </>
+ )
+ },
+ )))
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts b/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
index 84ed0eef..fef9d5a9 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/styles.test.ts
@@ -36,7 +36,6 @@ it('owns mobile styles and composer activation until unload, and can reload clea
'[class$="_turnErrorCode"]',
'[data-slot="conversation.header"] [class$="_header"]',
'[data-slot="main"] header[class*="_pageHead"]',
- 'header[class*="_pageHead"] [class*="_toolbar"]',
'[data-slot="conversation.view"] [class$="_scroll"]',
'[class*="_userStack"]',
'[data-slot="main"] [data-conversation-scroll]',
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts
new file mode 100644
index 00000000..5308db3a
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+import { createSidebarGesture, finishSidebarGesture, moveSidebarGesture } from './sidebar-gesture'
+
+const point = (x: number, y: number, time: number) => ({ id: 1, x, y, time })
+
+describe('sidebar gesture state machine', () => {
+ it('locks horizontally only after enough movement and clamps the reveal width', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ expect(moveSidebarGesture(gesture, point(105, 202, 120), 319, true)).toEqual({ gesture })
+ const move = moveSidebarGesture(gesture, point(280, 202, 300), 319, true)
+ expect(move.offset).toBe(180)
+ expect(move.gesture?.axis).toBe('x')
+ expect(moveSidebarGesture(move.gesture!, point(500, 202, 400), 319, true).offset).toBe(319)
+ })
+
+ it.each([
+ { open: false, end: point(90, 200, 200) },
+ { open: true, end: point(110, 200, 200) },
+ { open: false, end: point(105, 250, 200) },
+ ])('abandons wrong directions and vertical scrolling from %j', ({ open, end }) => {
+ expect(moveSidebarGesture(createSidebarGesture(point(100, 200, 100), open, 319), end, 319, true)).toEqual({ gesture: null })
+ })
+
+ it('abandons noncancelable horizontal moves instead of committing release travel', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ expect(moveSidebarGesture(gesture, point(300, 200, 200), 319, false)).toEqual({ gesture: null })
+ expect(finishSidebarGesture(gesture, point(500, 200, 300), 319)).toBeNull()
+ })
+
+ it('settles slow swipes by the revealed midpoint', () => {
+ const closed = createSidebarGesture(point(100, 200, 100), false, 319)
+ const short = moveSidebarGesture(closed, point(180, 200, 400), 319, true).gesture!
+ const long = moveSidebarGesture(closed, point(280, 200, 400), 319, true).gesture!
+ expect(finishSidebarGesture(short, point(180, 200, 700), 319)).toEqual({ open: false, suppressClick: true })
+ expect(finishSidebarGesture(long, point(280, 200, 700), 319)).toEqual({ open: true, suppressClick: true })
+ })
+
+ it('uses release velocity for short flings but never for tiny accidental motion', () => {
+ const gesture = createSidebarGesture(point(100, 200, 100), false, 319)
+ const fling = moveSidebarGesture(gesture, point(140, 200, 140), 319, true).gesture!
+ const tiny = moveSidebarGesture(gesture, point(108, 200, 105), 319, true).gesture!
+ expect(finishSidebarGesture(fling, point(150, 200, 150), 319)).toEqual({ open: true, suppressClick: true })
+ expect(finishSidebarGesture(tiny, point(108, 200, 110), 319)).toEqual({ open: false, suppressClick: true })
+ })
+
+ it('suppresses out-and-back claimed drags but leaves genuine taps alone', () => {
+ const tap = createSidebarGesture(point(220, 200, 100), true, 319)
+ expect(finishSidebarGesture(tap, point(220, 200, 200), 319)).toBeNull()
+ const claimed = moveSidebarGesture(tap, point(140, 200, 300), 319, true).gesture!
+ const returned = moveSidebarGesture(claimed, point(220, 200, 600), 319, true).gesture!
+ expect(finishSidebarGesture(returned, point(220, 200, 900), 319)).toEqual({ open: true, suppressClick: true })
+ })
+
+ it('expires older samples for a direction change near release', () => {
+ let gesture = createSidebarGesture(point(350, 200, 100), true, 319)
+ for (const sample of [point(100, 200, 200), point(150, 200, 400), point(200, 200, 500)])
+ gesture = moveSidebarGesture(gesture, sample, 319, true).gesture!
+ expect(gesture.samples[0].time).toBe(200)
+ gesture = moveSidebarGesture(gesture, point(250, 200, 550), 319, true).gesture!
+ expect(gesture.samples[0].time).toBe(400)
+ expect(finishSidebarGesture(gesture, point(270, 200, 580), 319)?.open).toBe(true)
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts
new file mode 100644
index 00000000..ec6913bf
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-gesture.ts
@@ -0,0 +1,84 @@
+const AXIS_LOCK_DISTANCE = 8
+const SWIPE_DISTANCE = 18
+const SWIPE_VELOCITY = 0.5
+
+export const SIDEBAR_CLICK_SUPPRESSION_MS = 400
+
+export interface SidebarGesturePoint {
+ id: number
+ x: number
+ y: number
+ time: number
+}
+
+export interface SidebarGesture {
+ id: number
+ startX: number
+ startY: number
+ base: number
+ open: boolean
+ axis: 'x' | null
+ samples: readonly SidebarGesturePoint[]
+}
+
+export interface SidebarGestureMove {
+ gesture: SidebarGesture | null
+ offset?: number
+}
+
+export function createSidebarGesture(point: SidebarGesturePoint, open: boolean, width: number): SidebarGesture {
+ return {
+ id: point.id,
+ startX: point.x,
+ startY: point.y,
+ base: open ? width : 0,
+ open,
+ axis: null,
+ samples: [point],
+ }
+}
+
+export function moveSidebarGesture(
+ gesture: SidebarGesture,
+ point: SidebarGesturePoint,
+ width: number,
+ cancelable: boolean,
+): SidebarGestureMove {
+ const dx = point.x - gesture.startX
+ const dy = point.y - gesture.startY
+ if (gesture.axis === null) {
+ if (Math.max(Math.abs(dx), Math.abs(dy)) < AXIS_LOCK_DISTANCE)
+ return { gesture }
+ if (Math.abs(dy) >= Math.abs(dx) * 0.8 || (gesture.open ? dx > 0 : dx < 0))
+ return { gesture: null }
+ }
+ if (!cancelable)
+ return { gesture: null }
+ const samples = [...gesture.samples, point]
+ while (samples.length > 2 && samples[1].time < point.time - 120)
+ samples.shift()
+ return {
+ gesture: { ...gesture, axis: 'x', samples },
+ offset: Math.min(width, Math.max(0, gesture.base + dx)),
+ }
+}
+
+export function finishSidebarGesture(
+ gesture: SidebarGesture,
+ point: SidebarGesturePoint | undefined,
+ width: number,
+): { open: boolean, suppressClick: boolean } | null {
+ if (gesture.axis !== 'x')
+ return null
+ const samples = point === undefined ? gesture.samples : [...gesture.samples, point]
+ const first = samples[0]
+ const last = samples[samples.length - 1]
+ const travel = last.x - gesture.startX
+ const velocity = (last.x - first.x) / Math.max(1, last.time - first.time)
+ const fling = Math.abs(velocity) >= SWIPE_VELOCITY && Math.abs(travel) >= SWIPE_DISTANCE
+ const position = Math.min(width, Math.max(0, gesture.base + travel))
+ return {
+ open: fling ? velocity > 0 : position >= width * 0.5,
+ suppressClick: true,
+ }
+}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.test.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.test.ts
new file mode 100644
index 00000000..30ef6a92
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { getMobileSessionId, getMobileSessionTitle } from './sidebar-session'
+
+describe('mobile navbar session projection', () => {
+ it('prefers a valid current row over a main-view retained row', () => {
+ const snapshot = {
+ current: 'selected',
+ byId: {
+ retained: { title: 'Retained title', retainedBy: { mainView: 1 } },
+ selected: { title: ' Selected title ' },
+ },
+ }
+ expect(getMobileSessionId(snapshot)).toBe('selected')
+ expect(getMobileSessionTitle(snapshot)).toBe('Selected title')
+ })
+
+ it.each([undefined, null, 7, '', 'missing', 'invalid'])('falls back to the main-view retained row when current is %j', (current) => {
+ const snapshot = {
+ current,
+ ids: ['first', 'selected'],
+ byId: {
+ first: { title: 'Not selected', retainedBy: { gateway: 1 } },
+ invalid: null,
+ selected: { title: 'Retained title', retainedBy: { mainView: 2 } },
+ },
+ }
+ expect(getMobileSessionId(snapshot)).toBe('selected')
+ expect(getMobileSessionTitle(snapshot)).toBe('Retained title')
+ })
+
+ it('leaves the localized New Session label to the caller for a blank selected session', () => {
+ const snapshot = {
+ current: 'selected',
+ byId: {
+ selected: { blank: true, title: 'Stored title', displayTitle: 'Fallback title' },
+ retained: { title: 'Wrong session', retainedBy: { mainView: 1 } },
+ },
+ }
+ expect(getMobileSessionId(snapshot)).toBe('selected')
+ expect(getMobileSessionTitle(snapshot)).toBeUndefined()
+ })
+
+ it.each([
+ { title: ' Durable title ', displayTitle: 'Fallback', expected: 'Durable title' },
+ { title: ' ', displayTitle: ' Project name ', expected: 'Project name' },
+ { title: undefined, displayTitle: 'Session id', expected: 'Session id' },
+ { title: 17, displayTitle: ' Fallback ', expected: 'Fallback' },
+ { title: '', displayTitle: '\t\n', expected: undefined },
+ { title: null, displayTitle: 17, expected: undefined },
+ ])('projects a trimmed nonempty title from %j', ({ title, displayTitle, expected }) => {
+ expect(getMobileSessionTitle({ current: 'selected', byId: { selected: { title, displayTitle } } })).toBe(expected)
+ })
+
+ it.each([undefined, null, false, 7, 'snapshot', [], {}, { byId: null }, { byId: [] }, { byId: 'rows' }])('returns absence for an incomplete snapshot %j', (snapshot) => {
+ expect(getMobileSessionId(snapshot)).toBeUndefined()
+ expect(getMobileSessionTitle(snapshot)).toBeUndefined()
+ })
+
+ it.each([null, [], 'row', 17, { retainedBy: null }, { retainedBy: [] }, { retainedBy: { mainView: 0 } }, { retainedBy: { mainView: -1 } }, { retainedBy: { mainView: '1' } }])('ignores a malformed or unselected fallback row %j', (summary) => {
+ const snapshot = { ids: ['first'], byId: { first: summary } }
+ expect(getMobileSessionId(snapshot)).toBeUndefined()
+ expect(getMobileSessionTitle(snapshot)).toBeUndefined()
+ })
+
+ it('does not infer selection from the first catalog id', () => {
+ const snapshot = { ids: ['first'], byId: { first: { title: 'First title', displayTitle: 'First display title', blank: false } } }
+ expect(getMobileSessionId(snapshot)).toBeUndefined()
+ expect(getMobileSessionTitle(snapshot)).toBeUndefined()
+ })
+
+ it('does not treat inherited catalog properties as a valid current row', () => {
+ expect(getMobileSessionId({ current: 'toString', byId: {} })).toBeUndefined()
+ expect(getMobileSessionTitle({ current: 'toString', byId: {} })).toBeUndefined()
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.ts b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.ts
new file mode 100644
index 00000000..c06a52a7
--- /dev/null
+++ b/packages/dsh-tauri-mobile-ui/src/client/service/sidebar-session.ts
@@ -0,0 +1,36 @@
+import type { SessionSummary } from 'dsh-tauri/client'
+
+type MobileSessionSummary = Partial<Pick<SessionSummary, 'title' | 'displayTitle' | 'blank' | 'retainedBy'>>
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+export function getMobileSessionId(snapshot: unknown): string | undefined {
+ if (!isRecord(snapshot) || !isRecord(snapshot.byId))
+ return undefined
+ const { current, byId } = snapshot
+ if (typeof current === 'string' && current.trim() !== '' && Object.hasOwn(byId, current) && isRecord(byId[current]))
+ return current
+ return Object.keys(byId).find((id) => {
+ const summary = byId[id]
+ if (id.trim() === '' || !isRecord(summary) || !isRecord(summary.retainedBy))
+ return false
+ const count = summary.retainedBy.mainView
+ return typeof count === 'number' && count > 0
+ })
+}
+
+export function getMobileSessionTitle(snapshot: unknown): string | undefined {
+ const id = getMobileSessionId(snapshot)
+ if (id === undefined || !isRecord(snapshot) || !isRecord(snapshot.byId))
+ return undefined
+ const summary = snapshot.byId[id] as MobileSessionSummary
+ if (summary.blank === true)
+ return undefined
+ const title = typeof summary.title === 'string' ? summary.title.trim() : ''
+ if (title !== '')
+ return title
+ const displayTitle = typeof summary.displayTitle === 'string' ? summary.displayTitle.trim() : ''
+ return displayTitle || undefined
+}
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
index a56d394c..244508af 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
@@ -10,28 +10,89 @@ vi.mock('dsh-tauri-ui/client', () => ({ cssr }))
describe('mobile conversation layout', () => {
const root = postcss.parse(mobileStyle.render())
- it('keeps current mobile layout overrides scoped to mobile devices', () => {
+ it('keeps the existing mobile layout overrides scoped to touch devices', () => {
const media = root.nodes.find(node => node.type === 'atrule' && node.name === 'media' && node.params === '(hover: none) and (any-pointer: coarse) and (any-hover: none)')
expect(media?.type).toBe('atrule')
if (media?.type !== 'atrule')
throw new Error('Missing mobile media query')
expect(media.params).toBe('(hover: none) and (any-pointer: coarse) and (any-hover: none)')
- const rules: Record<string, unknown> = {}
- media.walkRules((rule) => {
- rules[rule.selector] = rule.nodes.map(node => node.type === 'decl' ? [node.prop, node.value, node.important] : [])
+ const css = media.toString()
+ for (const selector of [
+ '[data-dsh-mobile-preferences]',
+ '[data-slot="conversation.composer.bar"] [class$="_dock"]',
+ '[class$="_composerStack"] > [data-slot="conversation.input.dock"]',
+ '[class$="_turnErrorCode"]',
+ '[data-slot="conversation.header"] [class$="_header"]',
+ '[data-slot="main"] header[class*="_pageHead"]',
+ '[data-slot="conversation.view"] [class$="_scroll"]',
+ '[class*="_userStack"]',
+ '[data-slot="main"] [data-conversation-scroll]',
+
+ ]) {
+ expect(css).toContain(selector)
+ }
+ })
+
+ it('positions the drawer without relying on the upstream collapsed marker', () => {
+ const css = root.toString()
+ for (const selector of [
+ 'html[data-dsh-mobile-sidebar] [data-slot="root"] > [class$="_frame"]',
+ 'html[data-dsh-mobile-sidebar] [class$="_sidebarCol"]',
+ 'html[data-dsh-mobile-sidebar] body [data-slot="sidebar"]',
+ 'html[data-dsh-mobile-sidebar] [class$="_centerCol"]',
+ 'html[data-dsh-mobile-sidebar-open] [data-dsh-mobile-sidebar-shade]',
+ '[data-dsh-mobile-topbar]',
+ ]) {
+ expect(css).toContain(selector)
+ }
+ expect(css).toContain('grid-template-columns: minmax(0, 1fr) !important')
+ expect(css).not.toContain('[data-sidebar-collapsed]')
+ })
+
+ it('keeps the sidebar stationary behind a raised rounded main panel without a gray shade', () => {
+ const declarations = (selector: string): Record<string, string> => {
+ const values: Record<string, string> = {}
+ root.walkRules(selector, (rule) => {
+ rule.walkDecls((decl) => {
+ values[decl.prop] = `${decl.value}${decl.important ? ' !important' : ''}`
+ })
+ })
+ return values
+ }
+ expect(declarations('html[data-dsh-mobile-sidebar] [class$="_sidebarCol"]')).toMatchObject({
+ 'z-index': '0',
+ 'transform': 'none',
+ })
+ expect(declarations('html[data-dsh-mobile-sidebar] [class$="_centerCol"]')).toMatchObject({
+ 'position': 'absolute',
+ 'inset': '0',
+ 'z-index': '1',
+ 'transform': 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ '--dsh-mobile-sidebar-radius': 'clamp(0px, calc(var(--dsh-mobile-sidebar-offset) / 10), 24px)',
+ 'border-radius': 'var(--dsh-mobile-sidebar-radius) 0 0 var(--dsh-mobile-sidebar-radius)',
+ 'corner-shape': 'round',
+ 'background-color': 'Canvas',
+ 'background-image': 'linear-gradient(var(--dsw-alias-bg-base, Canvas), var(--dsw-alias-bg-base, Canvas))',
+ 'box-shadow': 'none',
+ })
+ expect(declarations('html[data-dsh-mobile-sidebar] body [data-slot="sidebar"]')).toMatchObject({
+ // 终端模式外观会在折叠标记下隐藏侧栏,抽屉接管时用更高特异度还原可见性。
+ visibility: 'visible',
+ })
+ expect(declarations('html[data-dsh-mobile-sidebar-open] [class$="_centerCol"], html[data-dsh-mobile-sidebar-dragging] [class$="_centerCol"]')).toMatchObject({
+ 'box-shadow': 'var(--dsw-shadow-lv3)',
+ })
+ expect(declarations('[data-dsh-mobile-sidebar-shade]').background).toBe('transparent')
+ expect(declarations('html[data-dsh-mobile-sidebar] [data-side="sidebar"]').display).toBe('none !important')
+ expect(declarations('[data-dsh-mobile-topbar]')).toMatchObject({
+ position: 'sticky',
+ top: '0',
})
- expect(rules).toEqual({
- '[data-dsh-mobile-preferences]': [['display', 'flex', undefined], ['flex', '1', undefined], ['min-width', '0', undefined], ['align-items', 'center', undefined], ['gap', '8px', undefined], ['padding', '8px 0', undefined]],
- '[data-dsh-mobile-preferences] button': [['margin-left', 'auto', undefined], ['flex-shrink', '0', undefined]],
- '[data-slot="conversation.composer.bar"] [class$="_dock"]': [['display', 'none', true]],
- '[class$="_composerStack"] > [data-slot="conversation.input.dock"]': [['display', 'none', true]],
- '[class$="_turnErrorCode"]': [['display', 'none', true]],
- '[data-slot="conversation.header"] [class$="_header"]': [['display', 'none', true]],
- '[data-slot="main"] header[class*="_pageHead"]': [['padding-left', '0', true], ['padding-top', '24px', true]],
- 'header[class*="_pageHead"] [class*="_toolbar"]': [['display', 'none', true]],
- '[data-slot="conversation.view"] [class$="_scroll"]': [['padding', '16px', true]],
- '[class*="_userStack"]': [['max-width', '100%', true]],
- '[data-slot="main"] [data-conversation-scroll]': [['padding-bottom', '0', true]],
+ expect(declarations('[data-dsh-mobile-sidebar-toggle]')).toMatchObject({
+ 'width': '24px',
+ 'height': '24px',
+ 'background': 'transparent',
+ 'box-shadow': 'none',
})
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
index b041b669..1488c6a8 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
@@ -32,9 +32,6 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
paddingLeft: '0 !important',
paddingTop: '24px !important',
}),
- c('header[class*="_pageHead"] [class*="_toolbar"]', {
- display: 'none !important',
- }),
c('[data-slot="conversation.view"] [class$="_scroll"]', {
padding: '16px !important',
}),
@@ -44,4 +41,177 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
c('[data-slot="main"] [data-conversation-scroll]', {
paddingBottom: '0 !important',
}),
+ c('html[data-dsh-mobile-sidebar] [data-slot="root"] > [class$="_frame"]', {
+ gridTemplateColumns: 'minmax(0, 1fr) !important',
+ background: 'var(--dsw-specific-sidebar-fill) !important',
+ transition: 'none !important',
+ overscrollBehaviorX: 'none',
+ }),
+ c('[class$="_bottomRow"]', {
+ background: 'var(--dsw-specific-sidebar-fill) !important',
+ }),
+ c('html[data-dsh-mobile-sidebar] [class$="_sidebarCol"]', {
+ position: 'absolute',
+ inset: '0 auto 0 0',
+ zIndex: '0',
+ width: 'var(--dsh-mobile-sidebar-width)',
+ maxWidth: '82vw',
+ border: '0 !important',
+ visibility: 'visible',
+ transform: 'none',
+ transition: 'none',
+ }),
+ // keep: 终端模式外观(dsh-tauri appearance)会在 `body [data-sidebar-collapsed] [data-slot="sidebar"]`
+ // 上隐藏侧栏;抽屉接管时侧栏就是抽屉内容,这里用更高特异度还原可见性(不用 !important,
+ // 免得和外观插件比谁的后缀更靠后)。
+ c('html[data-dsh-mobile-sidebar] body [data-slot="sidebar"]', {
+ visibility: 'visible',
+ }),
+ c('html[data-dsh-mobile-sidebar] [class$="_centerCol"]', {
+ 'position': 'absolute',
+ 'inset': '0',
+ 'zIndex': '1',
+ '--dsh-mobile-sidebar-radius': 'clamp(0px, calc(var(--dsh-mobile-sidebar-offset) / 10), 24px)',
+ 'colorScheme': 'light',
+ 'backgroundColor': 'Canvas',
+ 'backgroundImage': 'linear-gradient(var(--dsw-alias-bg-base, Canvas), var(--dsw-alias-bg-base, Canvas))',
+ 'overflow': 'hidden',
+ 'transform': 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ 'borderRadius': 'var(--dsh-mobile-sidebar-radius) 0 0 var(--dsh-mobile-sidebar-radius)',
+ 'cornerShape': 'round',
+ 'boxShadow': 'none',
+ 'transition': 'transform 240ms cubic-bezier(.2, .8, .2, 1), border-radius 240ms ease, box-shadow 240ms ease',
+ 'willChange': 'transform',
+ }),
+ c('html[data-dsh-mobile-sidebar-open] [class$="_centerCol"], html[data-dsh-mobile-sidebar-dragging] [class$="_centerCol"]', {
+ boxShadow: 'var(--dsw-shadow-lv3)',
+ }),
+ c('html[data-dsh-mobile-sidebar] body[data-ds-dark-theme] [class$="_centerCol"]', {
+ colorScheme: 'dark',
+ }),
+ c('html[data-dsh-mobile-sidebar-dragging] [class$="_centerCol"]', {
+ transition: 'none',
+ }),
+ c('html[data-dsh-mobile-sidebar] [class$="_rightbarCol"]', {
+ display: 'none !important',
+ }),
+ c('html[data-dsh-mobile-sidebar] [data-side="sidebar"]', {
+ display: 'none !important',
+ }),
+ c('html[data-dsh-mobile-sidebar] [class$="_centerCol"] > [data-slot="main"]', {
+ flex: '1',
+ minHeight: '0',
+ height: 'auto',
+ }),
+ c('html[data-dsh-mobile-sidebar] [data-dsh-mobile-navbar-host]', {
+ flexShrink: '0',
+ minWidth: '0',
+ }),
+ c('html[data-dsh-mobile-sidebar] [data-shell-overlay]', {
+ zIndex: '20',
+ pointerEvents: 'none',
+ }),
+ c('[data-dsh-mobile-sidebar-overlay]', {
+ position: 'absolute',
+ inset: '0',
+ zIndex: '40',
+ pointerEvents: 'none',
+ }),
+ c('[data-dsh-mobile-topbar]', {
+ position: 'sticky',
+ top: '0',
+ zIndex: '3',
+ display: 'grid',
+ gridTemplateColumns: '24px minmax(0, 1fr) 24px',
+ alignItems: 'center',
+ gap: '16px',
+ height: 'calc(52px + env(safe-area-inset-top))',
+ padding: 'calc(14px + env(safe-area-inset-top)) 16px 14px',
+ boxSizing: 'border-box',
+ backgroundColor: 'Canvas',
+ backgroundImage: 'linear-gradient(var(--dsw-alias-bg-base, Canvas), var(--dsw-alias-bg-base, Canvas))',
+ }),
+ c('[data-dsh-mobile-sidebar-toggle]', {
+ display: 'block',
+ width: '24px',
+ height: '24px',
+ padding: '0',
+ border: '0',
+ color: 'var(--dsw-alias-label-primary)',
+ background: 'transparent',
+ boxShadow: 'none',
+ cursor: 'pointer',
+ pointerEvents: 'auto',
+ touchAction: 'manipulation',
+ }),
+ c('[data-dsh-mobile-new-session]', {
+ display: 'block',
+ width: '24px',
+ height: '24px',
+ padding: '0',
+ border: '0',
+ color: 'var(--dsw-alias-label-primary)',
+ background: 'transparent',
+ boxShadow: 'none',
+ cursor: 'pointer',
+ pointerEvents: 'auto',
+ touchAction: 'manipulation',
+ }),
+ c('[data-dsh-mobile-sidebar-toggle]:focus-visible, [data-dsh-mobile-new-session]:focus-visible', {
+ outline: 'var(--dsw-focus-ring-width, 2px) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary))',
+ outlineOffset: '4px',
+ }),
+ c('[data-dsh-mobile-navbar-title]', {
+ minWidth: '0',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ textAlign: 'center',
+ color: 'var(--dsw-alias-label-primary)',
+ fontSize: '16px',
+ fontWeight: '500',
+ lineHeight: '24px',
+ }),
+ c('[data-dsh-mobile-navbar-status]', {
+ position: 'absolute',
+ top: '100%',
+ left: '16px',
+ right: '16px',
+ textAlign: 'center',
+ color: 'var(--dsw-alias-label-caption)',
+ backgroundColor: 'Canvas',
+ backgroundImage: 'linear-gradient(var(--dsw-alias-bg-base, Canvas), var(--dsw-alias-bg-base, Canvas))',
+ fontSize: '12px',
+ lineHeight: '20px',
+ }),
+ c('[data-dsh-mobile-sidebar-shade]', {
+ position: 'absolute',
+ inset: 'calc(52px + env(safe-area-inset-top)) 0 0',
+ zIndex: '2',
+ display: 'block',
+ width: '100%',
+ padding: '0',
+ border: '0',
+ background: 'transparent',
+ opacity: '0',
+ visibility: 'hidden',
+ pointerEvents: 'none',
+ transform: 'translate3d(var(--dsh-mobile-sidebar-offset), 0, 0)',
+ transition: 'transform 240ms cubic-bezier(.2, .8, .2, 1), opacity 180ms ease, visibility 0s linear 240ms',
+ touchAction: 'pan-y pinch-zoom',
+ }),
+ c('html[data-dsh-mobile-sidebar-open] [data-dsh-mobile-sidebar-shade], html[data-dsh-mobile-sidebar-dragging] [data-dsh-mobile-sidebar-shade]', {
+ opacity: '1',
+ visibility: 'visible',
+ pointerEvents: 'auto',
+ transitionDelay: '0s',
+ }),
+ c('html[data-dsh-mobile-sidebar-dragging] [data-dsh-mobile-sidebar-shade]', {
+ transition: 'none',
+ }),
+ c('@media (prefers-reduced-motion: reduce)', [
+ c('html[data-dsh-mobile-sidebar] [class$="_centerCol"], html[data-dsh-mobile-sidebar] [data-dsh-mobile-sidebar-shade]', {
+ transition: 'none !important',
+ }),
+ ]),
])
diff --git a/packages/dsh-tauri-ui/src/client/components/icons.tsx b/packages/dsh-tauri-ui/src/client/components/icons.tsx
index 4d935eb5..d6f3c658 100644
--- a/packages/dsh-tauri-ui/src/client/components/icons.tsx
+++ b/packages/dsh-tauri-ui/src/client/components/icons.tsx
@@ -15,6 +15,7 @@ export { default as CircleCheck } from '@gravity-ui/icons/CircleCheck'
export { default as CircleDashed } from '@gravity-ui/icons/CircleDashed'
export { default as CirclePause } from '@gravity-ui/icons/CirclePause'
export { default as CirclePlay } from '@gravity-ui/icons/CirclePlay'
+export { default as CirclePlus } from '@gravity-ui/icons/CirclePlus'
export { default as CircleStop } from '@gravity-ui/icons/CircleStop'
export { default as CircleTree } from '@gravity-ui/icons/CircleTree'
export { default as CircleXmark } from '@gravity-ui/icons/CircleXmark'
@@ -32,6 +33,7 @@ export { default as Gear } from '@gravity-ui/icons/Gear'
export { default as Ghost } from '@gravity-ui/icons/Ghost'
export { default as Globe } from '@gravity-ui/icons/Globe'
export { default as GraduationCap } from '@gravity-ui/icons/GraduationCap'
+export { default as LayoutSideContentLeft } from '@gravity-ui/icons/LayoutSideContentLeft'
export { default as LayoutSplitSideContentRight } from '@gravity-ui/icons/LayoutSplitSideContentRight'
export { default as LogoGithub } from '@gravity-ui/icons/LogoGithub'
export { default as Magnifier } from '@gravity-ui/icons/Magnifier'
diff --git a/packages/dsh-tauri/src/client/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.ts
index 17b68bac..245e180f 100644
--- a/packages/dsh-tauri/src/client/apply.test.ts
+++ b/packages/dsh-tauri/src/client/apply.test.ts
@@ -66,7 +66,8 @@ function stubEnv(): Harness {
vi.stubGlobal('document', {
body: {},
head,
- documentElement: { style: { colorScheme: 'light' } },
+ // 移动抽屉归属标记挂在 documentElement 上,桌面假实现里始终未设置。
+ documentElement: { style: { colorScheme: 'light' }, hasAttribute: () => false },
createElement: () => ({ setAttribute: () => {}, textContent: '', parentElement: head }),
querySelector: () => null,
querySelectorAll: () => [],
diff --git a/packages/dsh-tauri/src/client/controller/index.test.ts b/packages/dsh-tauri/src/client/controller/index.test.ts
index 65b39a5b..7b0023f8 100644
--- a/packages/dsh-tauri/src/client/controller/index.test.ts
+++ b/packages/dsh-tauri/src/client/controller/index.test.ts
@@ -1,7 +1,10 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createLifecycleController } from './index'
-afterEach(() => vi.restoreAllMocks())
+afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
describe('createLifecycleController', () => {
it('cancels only the selected registration and disposes the rest once in order', () => {
@@ -23,6 +26,27 @@ describe('createLifecycleController', () => {
expect(calls).toEqual(['middle', 'duplicate'])
})
+ it('removes window listeners on explicit and controller disposal', () => {
+ const controller = createLifecycleController()
+ const windowListeners = new Map<string, EventListener>()
+ vi.stubGlobal('window', {
+ addEventListener: vi.fn((type: string, listener: EventListener) => windowListeners.set(type, listener)),
+ removeEventListener: vi.fn((type: string, _listener: EventListener) => windowListeners.delete(type)),
+ })
+ const handler = vi.fn()
+ const remove = controller.listenWindow('resize', handler)
+
+ expect(windowListeners.has('resize')).toBe(true)
+ remove()
+ expect(windowListeners.has('resize')).toBe(false)
+ expect(window.removeEventListener).toHaveBeenCalledTimes(1)
+
+ controller.listenWindow('resize', handler)
+ controller.dispose()
+ expect(windowListeners.has('resize')).toBe(false)
+ expect(window.removeEventListener).toHaveBeenCalledTimes(2)
+ })
+
it('continues cleanup after a disposer throws', () => {
const controller = createLifecycleController()
const error = new Error('cleanup failed')
diff --git a/packages/dsh-tauri/src/client/controller/index.ts b/packages/dsh-tauri/src/client/controller/index.ts
index da5bfa9e..31839998 100644
--- a/packages/dsh-tauri/src/client/controller/index.ts
+++ b/packages/dsh-tauri/src/client/controller/index.ts
@@ -27,6 +27,14 @@ export interface LifecycleController {
fn: (event: DocumentEventMap[K]) => void,
options?: AddEventListenerOptions,
) => () => void
+ /**
+ * 受控 window 事件监听:dispose 时自动移除;返回移除句柄。
+ */
+ listenWindow: <K extends keyof WindowEventMap>(
+ type: K,
+ fn: (event: WindowEventMap[K]) => void,
+ options?: AddEventListenerOptions,
+ ) => () => void
/**
* 受控 MutationObserver:dispose 时自动 disconnect;返回 observer 本体。
* 观察配置是第三个参数且可省略,默认见 DEFAULT_MUTATION_OPTIONS。
@@ -120,6 +128,21 @@ export function createLifecycleController(): LifecycleController {
}
},
+ listenWindow(type, fn, options) {
+ if (isDisposed || typeof window === 'undefined')
+ return noop
+
+ const handler = fn as EventListener
+ window.addEventListener(type, handler, options)
+
+ const remove = () => window.removeEventListener(type, handler, options)
+ const unhook = controller.add(remove)
+ return () => {
+ remove()
+ unhook()
+ }
+ },
+
observe(target, onMutate, options) {
const observer = new MutationObserver(onMutate)
diff --git a/packages/dsh-tauri/src/client/register/sidebar.test.ts b/packages/dsh-tauri/src/client/register/sidebar.test.ts
index b4aeb0d1..0970dfd1 100644
--- a/packages/dsh-tauri/src/client/register/sidebar.test.ts
+++ b/packages/dsh-tauri/src/client/register/sidebar.test.ts
@@ -15,6 +15,7 @@ const CMD_TOGGLE = 'dsh://sidebar:toggle'
const EVENT_SIDEBAR_COLLAPSED = 'dsh://sidebar:collapsed'
const ERROR_TYPE = 'dsh://plugin-error'
const SIDEBAR_COLLAPSED_ATTRIBUTE = 'data-sidebar-collapsed'
+const MOBILE_SIDEBAR_ATTRIBUTE = 'data-dsh-mobile-sidebar'
/** 假 MutationObserver:记录回调,供测试手动触发 DOM 变化。 */
class FakeMutationObserver {
@@ -64,11 +65,16 @@ function stubHost(): Host {
}
/** 假 document:`[data-shell-overlay]` 的父节点即 AppFrame。 */
-function stubDocument(collapsed: boolean): { setCollapsed: (value: boolean) => void } {
+function stubDocument(collapsed: boolean): { setCollapsed: (value: boolean) => void, setMobileOwned: (value: boolean) => void } {
let state = collapsed
+ let mobileOwned = false
const frame = { hasAttribute: (name: string) => name === SIDEBAR_COLLAPSED_ATTRIBUTE && state }
+ const documentElement = {
+ hasAttribute: (name: string) => name === MOBILE_SIDEBAR_ATTRIBUTE && mobileOwned,
+ }
vi.stubGlobal('document', {
body: {},
+ documentElement,
querySelector: () => ({ parentElement: frame }),
addEventListener: () => {},
removeEventListener: () => {},
@@ -77,6 +83,9 @@ function stubDocument(collapsed: boolean): { setCollapsed: (value: boolean) => v
setCollapsed(value: boolean) {
state = value
},
+ setMobileOwned(value: boolean) {
+ mobileOwned = value
+ },
}
}
@@ -165,4 +174,26 @@ describe('sidebarFeature', () => {
host.dispatch({ type: CMD_TOGGLE })
expect(collapsedReports(host)).toEqual([false, true])
})
+
+ it('defers bridge ownership to the mobile drawer and resumes after handoff', () => {
+ const host = stubHost()
+ const frame = stubDocument(false)
+ vi.stubGlobal('MutationObserver', FakeMutationObserver)
+ const { ctx, toggleSidebar } = fakeCtx()
+
+ const dispose = sidebarFeature.call(ctx)
+ frame.setMobileOwned(true)
+ host.dispatch({ type: CMD_TOGGLE })
+ FakeMutationObserver.latest?.callback([], FakeMutationObserver.latest as unknown as MutationObserver)
+ expect(toggleSidebar).not.toHaveBeenCalled()
+ expect(collapsedReports(host)).toEqual([false])
+
+ frame.setMobileOwned(false)
+ FakeMutationObserver.latest?.callback([], FakeMutationObserver.latest as unknown as MutationObserver)
+ expect(collapsedReports(host)).toEqual([false, false])
+ host.dispatch({ type: CMD_TOGGLE })
+ expect(toggleSidebar).toHaveBeenCalledTimes(1)
+
+ dispose()
+ })
})
diff --git a/packages/dsh-tauri/src/client/register/sidebar.ts b/packages/dsh-tauri/src/client/register/sidebar.ts
index ea7511b6..e6d640ce 100644
--- a/packages/dsh-tauri/src/client/register/sidebar.ts
+++ b/packages/dsh-tauri/src/client/register/sidebar.ts
@@ -24,6 +24,11 @@ const EVENT_SIDEBAR_COLLAPSED = 'dsh://sidebar:collapsed'
/** dsh 应用布局根(AppFrame):`data-shell-overlay` 的父节点,带侧边栏折叠属性。 */
const SIDEBAR_FRAME_SELECTOR = '[data-shell-overlay]'
const SIDEBAR_COLLAPSED_ATTRIBUTE = 'data-sidebar-collapsed'
+const MOBILE_SIDEBAR_ATTRIBUTE = 'data-dsh-mobile-sidebar'
+
+function isMobileSidebarOwned(): boolean {
+ return document.documentElement.hasAttribute(MOBILE_SIDEBAR_ATTRIBUTE)
+}
/** 应用晚挂载时补报一次折叠状态的轮询参数(拿到 AppFrame 即停,有界)。 */
const SIDEBAR_TRACK_MAX_TRIES = 30
@@ -39,6 +44,8 @@ function findFrame(): HTMLElement | null {
/** 折叠状态回报(幂等:宿主只把它写进自己的状态)。 */
function reportCollapsed(): void {
+ if (isMobileSidebarOwned())
+ return
invokeParent({
type: EVENT_SIDEBAR_COLLAPSED,
collapsed: findFrame()?.hasAttribute(SIDEBAR_COLLAPSED_ATTRIBUTE) === true,
@@ -48,7 +55,7 @@ function reportCollapsed(): void {
export const sidebarFeature = defineRegister<ClientContext>((controller, ctx) => {
// 宿主命令 → dsh 布局服务;布局服务抛错只上报,不影响后续命令。
controller.add(listenParent<ParentMessage>((data) => {
- if (data.type !== CMD_TOGGLE)
+ if (data.type !== CMD_TOGGLE || isMobileSidebarOwned())
return
try {
ctx.layout.toggleSidebar()
@@ -59,9 +66,9 @@ export const sidebarFeature = defineRegister<ClientContext>((controller, ctx) =>
}, [CMD_TOGGLE]))
// 属性翻转即回报(AppFrame 出现后的每次变化都会命中)。
- controller.observe(document.body, reportCollapsed, {
+ controller.observe(document.documentElement, reportCollapsed, {
attributes: true,
- attributeFilter: [SIDEBAR_COLLAPSED_ATTRIBUTE],
+ attributeFilter: [SIDEBAR_COLLAPSED_ATTRIBUTE, MOBILE_SIDEBAR_ATTRIBUTE],
subtree: true,
})
diff --git a/src-tauri/src/service/patch/mobile_sidebar.rs b/src-tauri/src/service/patch/mobile_sidebar.rs
new file mode 100644
index 00000000..6f1ad416
--- /dev/null
+++ b/src-tauri/src/service/patch/mobile_sidebar.rs
@@ -0,0 +1,158 @@
+use std::path::Path;
+
+use crate::utils::{patch_core_file, patch_dsh, PatchOutcome};
+
+const CLIENT: &str = "node_modules/@deepseek-ai/dsh-client-ui-layout/lib/client.js";
+const PATCH_MARKER: &str = "dsh-tauri: mobile sidebar slot props";
+const ORIGINAL: &str = r#"const sidebar = (0, react.useMemo)(() => renderSlot("sidebar", {
+ collapsed: sidebarCollapsed,
+ width: cols.sidebar
+ }), [
+ renderSlot,
+ sidebarCollapsed,
+ cols.sidebar
+ ]);"#;
+/// 首版补丁把 `isDshMobileSidebar()` 放在模块级、靠 `viewport` 依赖重算;已经打过首版补丁的运行时
+/// 必须整体升级,否则会永远命中 AnchorMissing 而停留在旧行为上。
+const LEGACY_HELPER: &str = r#"function isDshMobileSidebar() {
+ return typeof document !== "undefined" && document.documentElement.hasAttribute("data-dsh-mobile-ui") && typeof window !== "undefined" && typeof window.matchMedia === "function" && window.innerWidth < 1024 && ["(hover: none)", "(any-pointer: coarse)", "(any-hover: none)"].every(query => window.matchMedia(query).matches);
+}
+"#;
+const LEGACY_TARGET: &str = r#"/* dsh-tauri: mobile sidebar slot props */
+ const sidebar = (0, react.useMemo)(() => renderSlot("sidebar", {
+ collapsed: isDshMobileSidebar() ? false : sidebarCollapsed,
+ width: isDshMobileSidebar() ? Math.min(320, Math.floor(window.innerWidth * .82)) : cols.sidebar
+ }), [
+ renderSlot,
+ sidebarCollapsed,
+ cols.sidebar,
+ viewport
+ ]);"#;
+/// 只有插件的 `<html data-dsh-mobile-sidebar>` 所有权标记 + 窄屏触摸媒体查询同时成立才放宽侧栏;
+/// 订阅标记/尺寸变化自行重算,**不写布局状态**(写状态会改掉桌面端的侧栏宽度偏好)。
+const PATCHED_TARGET: &str = r#"/* dsh-tauri: mobile sidebar slot props */
+ const mobileSidebarWidth = (0, react.useSyncExternalStore)(subscribeDshMobileSidebar, getDshMobileSidebarWidth, () => 0);
+ const sidebar = (0, react.useMemo)(() => renderSlot("sidebar", {
+ collapsed: mobileSidebarWidth > 0 ? false : sidebarCollapsed,
+ width: mobileSidebarWidth > 0 ? mobileSidebarWidth : cols.sidebar
+ }), [
+ renderSlot,
+ sidebarCollapsed,
+ cols.sidebar,
+ mobileSidebarWidth
+ ]);
+ function getDshMobileSidebarWidth() {
+ return typeof document !== "undefined" && typeof window !== "undefined" && typeof window.matchMedia === "function" && document.documentElement.hasAttribute("data-dsh-mobile-sidebar") && window.innerWidth < 1024 && ["(hover: none)", "(any-pointer: coarse)", "(any-hover: none)"].every(query => window.matchMedia(query).matches) ? Math.min(320, Math.floor(window.innerWidth * .82)) : 0;
+ }
+ function subscribeDshMobileSidebar(onChange) {
+ if (typeof document === "undefined" || typeof window === "undefined") return () => {};
+ const observer = new MutationObserver(onChange);
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-dsh-mobile-sidebar"] });
+ window.addEventListener("resize", onChange);
+ return () => {
+ observer.disconnect();
+ window.removeEventListener("resize", onChange);
+ };
+ }"#;
+
+fn patch_source(source: &str) -> PatchOutcome {
+ if source.contains(PATCHED_TARGET) {
+ return PatchOutcome::AlreadyPatched;
+ }
+ let legacy = format!("{LEGACY_HELPER}{LEGACY_TARGET}");
+ if source.matches(&legacy).count() == 1 {
+ return PatchOutcome::Patched(source.replacen(&legacy, PATCHED_TARGET, 1));
+ }
+ if source.contains(PATCH_MARKER)
+ || source.contains("isDshMobileSidebar")
+ || source.contains("subscribeDshMobileSidebar")
+ {
+ return PatchOutcome::AnchorMissing;
+ }
+ if source.matches(ORIGINAL).count() != 1 {
+ return PatchOutcome::AnchorMissing;
+ }
+ PatchOutcome::Patched(source.replacen(ORIGINAL, PATCHED_TARGET, 1))
+}
+
+pub fn apply_at(core_dir: &Path) -> Result<(), String> {
+ patch_core_file(core_dir, CLIENT, patch_source)
+}
+
+pub fn apply(app_handle: &tauri::AppHandle) -> Result<(), String> {
+ patch_dsh(app_handle, CLIENT, patch_source)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn fixture() -> String {
+ ORIGINAL.to_owned()
+ }
+
+ #[test]
+ fn widens_mobile_sidebar_without_mutating_layout_preferences() {
+ let PatchOutcome::Patched(patched) = patch_source(&fixture()) else {
+ panic!("expected patched source");
+ };
+ assert!(patched.contains(PATCH_MARKER));
+ assert!(patched.contains(
+ "(0, react.useSyncExternalStore)(subscribeDshMobileSidebar, getDshMobileSidebarWidth, () => 0)"
+ ));
+ assert!(patched.contains("collapsed: mobileSidebarWidth > 0 ? false : sidebarCollapsed"));
+ assert!(patched.contains("width: mobileSidebarWidth > 0 ? mobileSidebarWidth : cols.sidebar"));
+ assert!(patched.contains(r#"attributeFilter: ["data-dsh-mobile-sidebar"]"#));
+ assert!(patched.contains("window.innerWidth < 1024"));
+ assert!(patched.contains("window.matchMedia(query).matches"));
+ assert!(patched.contains("Math.min(320, Math.floor(window.innerWidth * .82))"));
+ assert!(!patched.contains("toggleSidebar"));
+ assert!(!patched.contains("isDshMobileSidebar"));
+ assert_eq!(patch_source(&patched), PatchOutcome::AlreadyPatched);
+ }
+
+ #[test]
+ fn upgrades_the_legacy_viewport_dependent_patch() {
+ let legacy = format!("{LEGACY_HELPER}{LEGACY_TARGET}");
+ let PatchOutcome::Patched(patched) = patch_source(&legacy) else {
+ panic!("expected the legacy patch to be upgraded");
+ };
+ assert!(!patched.contains("isDshMobileSidebar"));
+ assert!(patched.contains("(0, react.useSyncExternalStore)"));
+ assert!(patched.contains("mobileSidebarWidth > 0 ? false : sidebarCollapsed"));
+ assert_eq!(patch_source(&patched), PatchOutcome::AlreadyPatched);
+ }
+
+ #[test]
+ fn skips_missing_or_ambiguous_sidebar_anchors() {
+ assert_eq!(patch_source(""), PatchOutcome::AnchorMissing);
+ assert_eq!(
+ patch_source(&format!("{}{}", ORIGINAL, ORIGINAL)),
+ PatchOutcome::AnchorMissing
+ );
+ assert_eq!(
+ patch_source(&fixture().replace("width: cols.sidebar", "width: cols.main")),
+ PatchOutcome::AnchorMissing
+ );
+ assert_eq!(patch_source(LEGACY_HELPER), PatchOutcome::AnchorMissing);
+ assert_eq!(patch_source(LEGACY_TARGET), PatchOutcome::AnchorMissing);
+ assert_eq!(
+ patch_source(&format!("{PATCH_MARKER}\n{ORIGINAL}")),
+ PatchOutcome::AnchorMissing
+ );
+ assert_eq!(
+ patch_source(&format!("{LEGACY_HELPER}{ORIGINAL}")),
+ PatchOutcome::AnchorMissing
+ );
+ assert_eq!(
+ patch_source(&PATCHED_TARGET.replace("const sidebar", "const sidebarX")),
+ PatchOutcome::AnchorMissing
+ );
+ }
+
+ #[test]
+ fn ignores_unrelated_mobile_marker_text() {
+ let source = format!("// data-dsh-mobile-ui\n{ORIGINAL}");
+ assert!(matches!(patch_source(&source), PatchOutcome::Patched(_)));
+ }
+}
diff --git a/src-tauri/src/service/patch/mod.rs b/src-tauri/src/service/patch/mod.rs
index b65627da..5b39c3a0 100644
--- a/src-tauri/src/service/patch/mod.rs
+++ b/src-tauri/src/service/patch/mod.rs
@@ -12,6 +12,7 @@
pub(crate) mod composer;
pub(crate) mod llm_session;
pub(crate) mod mobile_composer;
+pub(crate) mod mobile_sidebar;
pub(crate) mod model_selection;
pub(crate) mod pi_ai_thinking;
pub(crate) mod plugin_visibility;
@@ -32,10 +33,11 @@ use std::path::Path;
/// 让编排层能看见哪一条出了问题。
pub(crate) fn apply_all_at(core_dir: &Path) -> Result<(), String> {
#[allow(clippy::type_complexity)]
- let patches: [(&str, fn(&Path) -> Result<(), String>); 10] = [
+ let patches: [(&str, fn(&Path) -> Result<(), String>); 11] = [
("renderer", renderer::apply_at),
("composer", composer::apply_at),
("mobile_composer", mobile_composer::apply_at),
+ ("mobile_sidebar", mobile_sidebar::apply_at),
("session", session::apply_at),
("llm_session", llm_session::apply_at),
("pi_ai_thinking", pi_ai_thinking::apply_at),
diff --git a/src-tauri/src/service/workflow/launch.rs b/src-tauri/src/service/workflow/launch.rs
index e3b5ebba..559dd4a3 100644
--- a/src-tauri/src/service/workflow/launch.rs
+++ b/src-tauri/src/service/workflow/launch.rs
@@ -421,6 +421,9 @@ pub async fn launch(app_handle: tauri::AppHandle) -> Result<(), String> {
if let Err(e) = crate::service::patch::mobile_composer::apply(&app_handle) {
log::warn!("mobile composer patch failed: {e}");
}
+ if let Err(e) = crate::service::patch::mobile_sidebar::apply(&app_handle) {
+ log::warn!("mobile sidebar patch failed: {e}");
+ }
// Expose an id-based SessionStore.remove facade so plugins can perform a
// real in-memory teardown instead of leaving deleted sessions ungrouped.
if let Err(e) = crate::service::patch::session::apply(&app_handle) {