DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(settings): 修复 patch 设置页快捷键无法打开 (#867)
Mao Mr78d76cb6d9f9
diff --git a/packages/dsh-tauri-ui/src/client/register/settings.register.test.ts b/packages/dsh-tauri-ui/src/client/register/settings.register.test.tsindex 951b51c1..05f1d7e2 100644--- a/packages/dsh-tauri-ui/src/client/register/settings.register.test.ts+++ b/packages/dsh-tauri-ui/src/client/register/settings.register.test.ts@@ -18,12 +18,9 @@ vi.mock('../store', () => ({ store: { settings: mocks.settings } }))vi.mock('../ui/settings-sidebar', () => ({ SettingsSidebar: () => null }))vi.mock('../ui/settings-trigger', () => ({ SettingsTrigger: () => null }))vi.mock('@deepseek-ai/dsh-client-ui-renderer', () => ({ SlotOutlet: () => null }))-vi.mock('dsh-tauri/client', () => ({- defineRegister: (setup: (controller: unknown, ctx: unknown) => void) =>- function registerEffect(this: unknown) {- setup({ add: (): void => {} }, this)- return (): void => {}- },+vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/register'),+ ...await import('../../../../dsh-tauri/src/client/modules/reause'),}))interface MatchMediaHost {@@ -32,6 +29,7 @@ interface MatchMediaHost {const host = globalThis as unknown as MatchMediaHostconst originalWindow = host.window+const disposers: Array<() => void> = []/** 手机端才有三条设备查询全部成立;触屏为主但另接鼠标的设备缺 `(any-hover: none)`。 */const MOBILE_DEVICE = {@@ -53,9 +51,14 @@ function stubDevice(answers: Record<string, boolean>): void {}afterEach(() => {+ for (const dispose of disposers.splice(0))+ dispose()host.window = originalWindowmocks.settings.launcherAvailable = falsemocks.settings.launcherShortcut = undefined+ vi.clearAllMocks()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()})/** 用最小 slots 面记录注入点:inject 只登记,register 由激活回调按需触发。 */@@ -65,8 +68,17 @@ function activate(shortcuts?: unknown) {const ctx = {slots: {inject(key: string, callback: () => unknown) {- injected.push({ key, activate: callback })- return (): void => {}+ let dispose: (() => void) | undefined+ injected.push({+ key,+ activate() {+ const result = callback()+ if (typeof result === 'function')+ dispose = result as () => void+ return result+ },+ })+ return () => dispose?.()},register(options: { name: string }) {registered.push(options.name)@@ -76,10 +88,10 @@ function activate(shortcuts?: unknown) {effect(callback: () => () => void) {return callback()},- get: () => shortcuts,+ get: (name: string) => name === 'slots' ? ctx.slots : shortcuts,}- ;(registerSettings as unknown as (this: unknown) => void).call(ctx)+ disposers.push(registerSettings.call(ctx))return { injected, registered }}diff --git a/packages/dsh-tauri-ui/src/client/register/settings.shortcut.test.tsx b/packages/dsh-tauri-ui/src/client/register/settings.shortcut.test.tsxnew file mode 100644index 00000000..b5c25fbf--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/register/settings.shortcut.test.tsx@@ -0,0 +1,338 @@+// @vitest-environment jsdom+import type { ActionsDecl, PropsStore, StoreHandle, StoreInstance } from '@deepseek-ai/dsh-client-store'+import type { ComponentType } from 'react'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { useSyncExternalStore } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { store } from '../store'+import { registerSettings } from './settings'++const modal = vi.hoisted(() => ({ available: true, useModalLayer: vi.fn(), mount: vi.fn() }))++vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => {+ const { useLayoutEffect } = await import('react')+ function useModalLayer(dialog: { current: HTMLElement | null }, open: boolean, onClose: () => void): void {+ modal.useModalLayer(dialog, open, onClose)+ useLayoutEffect(() => {+ modal.mount(dialog.current, open)+ }, [dialog, open])+ }+ return {+ get useModalLayer() {+ return modal.available ? useModalLayer : undefined+ },+ }+})++vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/register'),+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define'),+ ...await import('../../../../dsh-tauri/src/client/modules/reause'),+ ...await import('../../../../dsh-tauri/src/client/modules/lodash-es'),+ ...await import('../../../../dsh-tauri/src/client/modules/tailwind-variants'),+}))+vi.mock('@deepseek-ai/dsh-client-ui-renderer', () => ({+ SlotOutlet: ({ opts }: { opts: { only: string } }) => <div data-testid="settings-section">{opts.only}</div>,+}))+vi.mock('../locales', () => ({ locale: { useLocale: () => {}, text: (key: string) => key } }))+vi.mock('../ui/settings-trigger', () => ({ SettingsTrigger: () => null }))+vi.mock('../components/icon', () => ({ Icon: () => null }))+vi.mock('../components/official', async () => {+ const { createElement } = await import('react')+ return { Input: (props: import('react').ComponentProps<'input'>) => createElement('input', props) }+})++interface ShellState {+ open: boolean+ activeId: string | undefined+}++interface ShellActions extends ActionsDecl<ShellState> {+ open: (draft: ShellState) => void+ close: (draft: ShellState) => void+ select: (draft: ShellState, id: string) => void+ openSection: (draft: ShellState, id: string) => void+}++type ShellHandle = StoreHandle<ShellState, ShellActions>+type ShellInstance = StoreInstance<ShellState, ShellActions>++interface Registration {+ options: { name: string, id?: string, priority?: number, registrant?: string, store?: ShellHandle }+ component: ComponentType<PropsStore<ShellHandle>>+}++const disposers: Array<() => void> = []++beforeEach(() => {+ modal.available = true+ vi.clearAllMocks()+ store.settings.close()+ store.settings.setLauncherAvailable(false)+ store.settings.setLauncherShortcut(undefined)+ store.sections.setRows([+ { id: 'general', label: 'General', order: 0 },+ { id: 'models', label: 'Models', order: 1 },+ ])+})++afterEach(() => {+ cleanup()+ for (const dispose of disposers.splice(0))+ dispose()+ store.settings.close()+ store.settings.setLauncherAvailable(false)+ store.settings.setLauncherShortcut(undefined)+ store.sections.setRows([])+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++function createOfficialShell() {+ let snapshot: ShellState = { open: false, activeId: undefined }+ const listeners = new Set<() => void>()+ function update(next: ShellState): void {+ snapshot = next+ listeners.forEach(listener => listener())+ }+ const instance: ShellInstance = {+ getSnapshot: () => snapshot,+ subscribe(listener) {+ listeners.add(listener)+ return () => listeners.delete(listener)+ },+ clearPersisted() {},+ actions: {+ open: () => update({ ...snapshot, open: true }),+ close: () => update({ open: false, activeId: undefined }),+ select: id => update({ ...snapshot, activeId: id }),+ openSection: id => update({ open: true, activeId: id }),+ },+ }+ const handle: ShellHandle = {+ spec: {+ init: () => ({ open: false, activeId: undefined }),+ actions: {+ open(draft) { draft.open = true },+ close(draft) {+ draft.open = false+ draft.activeId = undefined+ },+ select(draft, id) { draft.activeId = id },+ openSection(draft, id) {+ draft.open = true+ draft.activeId = id+ },+ },+ },+ create: vi.fn(() => instance),+ }+ return { handle, instance, listeners, openCommand: () => instance.actions.open() }+}++function activate(owner?: unknown) {+ const registrations: Registration[] = []+ const ledgerListeners = new Set<() => void>()+ const renderListeners = new Set<() => void>()+ const instances = new Map<ShellHandle, ShellInstance>()+ let entries = owner ? [{ store: owner, registrant: '@deepseek-ai/dsh-client-ui-settings-general' }] : []+ let revision = 0+ function notifyRender(): void {+ revision+++ renderListeners.forEach(listener => listener())+ }+ const registerCommand = vi.fn(() => {+ throw new Error('Duplicate shortcut command: settings.open')+ })+ const slots = {+ inject(_key: string, callback: () => () => void) {+ return callback()+ },+ register(options: Registration['options'], component: Registration['component']) {+ const entry = { options, component }+ registrations.push(entry)+ notifyRender()+ return () => {+ registrations.splice(registrations.indexOf(entry), 1)+ notifyRender()+ }+ },+ entries: () => entries,+ subscribe(_key: string, listener: () => void) {+ ledgerListeners.add(listener)+ return () => ledgerListeners.delete(listener)+ },+ }+ const ctx = {+ slots,+ get(name: string) {+ if (name === 'slots')+ return slots+ if (name === 'shortcuts')+ return { register: registerCommand, catalog: { getSnapshot: () => [{ id: 'settings.open', keys: ['Ctrl+,'] }] } }+ },+ effect: (callback: () => () => void) => callback(),+ }+ const dispose = registerSettings.call(ctx)+ disposers.push(dispose)++ function BoundEntry({ entry }: { entry: Registration }) {+ const { component: Component, options } = entry+ if (!options.store)+ return <Component {...{} as PropsStore<ShellHandle>} />+ let instance = instances.get(options.store)+ if (!instance) {+ instance = options.store.create()+ instances.set(options.store, instance)+ }+ const source = instance+ function useStore<T>(selector: (state: ShellState) => T): T {+ return selector(useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot))+ }+ return <Component useStore={useStore} actions={source.actions} />+ }++ function Overlays() {+ useSyncExternalStore(+ (listener) => {+ renderListeners.add(listener)+ return () => renderListeners.delete(listener)+ },+ () => revision,+ () => revision,+ )+ return registrations.filter(entry => entry.options.name === 'shell.overlay').map(entry => (+ <BoundEntry key={entry.options.id} entry={entry} />+ ))+ }++ function setOwner(next?: unknown): void {+ entries = next ? [{ store: next, registrant: '@deepseek-ai/dsh-client-ui-settings-general' }] : []+ ledgerListeners.forEach(listener => listener())+ }++ return { Overlays, registrations, ledgerListeners, setOwner, dispose, registerCommand }+}++describe('patched settings shortcut store route', () => {+ it('opens the replacement from the existing command and resets the hidden shell for reopening', () => {+ const owner = createOfficialShell()+ const host = activate(owner.handle)+ render(<host.Overlays />)+ expect(screen.queryByRole('dialog')).toBeNull()++ act(owner.openCommand)++ expect(screen.getByRole('dialog').dataset.slotSidebar).toBe('dsh-tauri-ui')+ expect(owner.instance.getSnapshot().open).toBe(false)+ expect(host.registerCommand).not.toHaveBeenCalled()+ expect(host.registrations.filter(entry => entry.options.store === owner.handle)).toHaveLength(1)+ expect(owner.handle.create).toHaveBeenCalledTimes(1)++ act(() => store.settings.close())+ expect(screen.queryByRole('dialog')).toBeNull()+ act(owner.openCommand)+ expect(screen.getByRole('dialog').dataset.slotSidebar).toBe('dsh-tauri-ui')+ expect(owner.instance.getSnapshot().open).toBe(false)+ })++ it('preserves an official section request and existing menu/deep-link state', () => {+ const owner = createOfficialShell()+ const host = activate(owner.handle)+ render(<host.Overlays />)+ act(() => owner.instance.actions.openSection('models'))++ expect(screen.getByTestId('settings-section').textContent).toBe('models')+ expect(owner.instance.getSnapshot()).toEqual({ open: false, activeId: undefined })+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'Models' } })+ expect(store.settings.query).toBe('Models')++ act(() => store.settings.close())+ act(() => store.settings.openAt('general'))+ expect(screen.getByTestId('settings-section').textContent).toBe('general')+ expect(store.settings.query).toBe('')+ })++ it('tracks late owners, avoids duplicate seats, and disconnects replaced owners and unloads', () => {+ const first = createOfficialShell()+ const second = createOfficialShell()+ const host = activate()+ const view = render(<host.Overlays />)++ act(() => host.setOwner(first.handle))+ act(first.openCommand)+ expect(screen.getByRole('dialog').dataset.slotSidebar).toBe('dsh-tauri-ui')+ act(() => store.settings.close())++ act(() => host.setOwner(first.handle))+ expect(first.handle.create).toHaveBeenCalledTimes(1)+ act(() => host.setOwner(second.handle))+ act(first.openCommand)+ expect(screen.queryByRole('dialog')).toBeNull()+ act(second.openCommand)+ expect(screen.getByRole('dialog').dataset.slotSidebar).toBe('dsh-tauri-ui')++ act(() => host.setOwner())+ act(() => store.settings.close())+ act(second.openCommand)+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(host.registrations.some(entry => entry.options.store)).toBe(false)++ view.unmount()+ host.dispose()+ host.dispose()+ expect(host.ledgerListeners.size).toBe(0)+ expect(first.listeners.size).toBe(0)+ expect(second.listeners.size).toBe(0)+ expect(host.registrations).toEqual([])+ expect(store.settings.launcherShortcut).toBeUndefined()+ expect(host.registerCommand).not.toHaveBeenCalled()+ })++ it('ignores incompatible owner stores without creating a relay seat', () => {+ const host = activate()+ render(<host.Overlays />)+ const owner = createOfficialShell()+ for (const candidate of [null, {}, () => owner.handle, { create: owner.handle.create, spec: { actions: {} } }]) {+ act(() => host.setOwner(candidate))+ expect(host.registrations.some(entry => entry.options.store)).toBe(false)+ }+ expect(owner.handle.create).not.toHaveBeenCalled()+ act(() => store.settings.openAt('models'))+ expect(screen.getByTestId('settings-section').textContent).toBe('models')+ })++ it('gives the official modal layer the mounted settings dialog and close callback', () => {+ const host = activate()+ render(<host.Overlays />)+ act(() => store.settings.openAt())+ const dialog = screen.getByRole('dialog')++ expect(dialog.getAttribute('aria-modal')).toBe('true')+ expect(dialog.dataset.shortcutModal).toBe('settings')+ expect(modal.mount).toHaveBeenLastCalledWith(dialog, true)+ const [ref, open, close] = modal.useModalLayer.mock.lastCall!+ expect(ref.current).toBe(dialog)+ expect(open).toBe(true)+ act(close)+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('does not race the official modal layer with an independent Escape handler', () => {+ const host = activate()+ render(<host.Overlays />)+ act(() => store.settings.openAt())+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape', code: 'Escape' })+ expect(store.settings.open).toBe(true)+ })++ it('keeps Escape closing functional when the core has no modal layer hook', () => {+ modal.available = false+ const host = activate()+ render(<host.Overlays />)+ act(() => store.settings.openAt())+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape', code: 'Escape' })+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(modal.useModalLayer).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-ui/src/client/register/settings.ts b/packages/dsh-tauri-ui/src/client/register/settings.tsindex 919e3410..27579c30 100644--- a/packages/dsh-tauri-ui/src/client/register/settings.ts+++ b/packages/dsh-tauri-ui/src/client/register/settings.ts@@ -1,6 +1,7 @@-import type { ClientContext } from 'dsh-tauri/client'+import type { PropsStore, StoreHandle } from '@deepseek-ai/dsh-client-store'+import type { ClientContext, SlotRegistry } from 'dsh-tauri/client'import { SlotOutlet } from '@deepseek-ai/dsh-client-ui-renderer'-import { defineRegister } from 'dsh-tauri/client'+import { defineRegister, useWatchImmediate } from 'dsh-tauri/client'import {SETTINGS_LAUNCHER_SLOT,SETTINGS_REGISTRANT,@@ -14,9 +15,15 @@ import { SettingsSidebar } from '../ui/settings-sidebar'import { SettingsTrigger } from '../ui/settings-trigger'import { detectMobileDevice } from './settings.utils'-const SETTINGS_SHORTCUT_EFFECT = 'dsh-tauri-ui: settings launcher shortcut (Ctrl+, hint)'+const SETTINGS_SHORTCUT_EFFECT = 'dsh-tauri-ui: settings launcher shortcut'+const SETTINGS_OPEN_RELAY_ID = 'dsh-tauri-ui-settings-open-relay'-export const registerSettings = defineRegister<ClientContext>((controller, ctx) => {+type SettingsShell = StoreHandle<{ open: boolean, activeId?: string }, {+ open: (draft: { open: boolean }) => void+ close: (draft: { open: boolean }) => void+}>++export const registerSettings = defineRegister<ClientContext>((controller, ctx, adapter) => {if (typeof SlotOutlet !== 'function') {console.warn('[dsh-tauri-ui] <SlotOutlet> unavailable (renderer patch missing) — settings sidebar disabled, official dialog stays.',@@ -28,11 +35,17 @@ export const registerSettings = defineRegister<ClientContext>((controller, ctx)returncontroller.add(- ctx.slots.inject(SETTINGS_SHELL_OVERLAY_SLOT, () =>- ctx.slots.register(+ ctx.slots.inject(SETTINGS_SHELL_OVERLAY_SLOT, () => {+ const disposeSidebar = ctx.slots.register({ name: SETTINGS_SHELL_OVERLAY_SLOT, id: SETTINGS_SIDEBAR_ID, registrant: SETTINGS_REGISTRANT, inject: () => ({}) } as never,SettingsSidebar as never,- )),+ )+ const disposeRelay = registerSettingsOpenRelay(adapter.service<SlotRegistry>('slots'))+ return () => {+ disposeRelay()+ disposeSidebar()+ }+ }),)controller.add(ctx.slots.inject(SETTINGS_SIDEBAR_SLOT as never, () =>@@ -47,16 +60,56 @@ export const registerSettings = defineRegister<ClientContext>((controller, ctx)return () => store.settings.setLauncherAvailable(false)}),)- controller.add(ctx.effect(() => publishLauncherShortcut(ctx), SETTINGS_SHORTCUT_EFFECT))+ controller.add(ctx.effect(() => publishLauncherShortcut(adapter.service<ShortcutsLike>('shortcuts')), SETTINGS_SHORTCUT_EFFECT))})-/**- * 官方启动器座位的「Ctrl+,」提示:座位拿的是 ownerProps,读不到服务,- * 这里把 `settings.open` 的生效按键投影进自己的 store(用户改键后重发)。- * 核心没有快捷键服务(老核心)时不写值,座位不显示提示。- */-function publishLauncherShortcut(ctx: ClientContext): () => void {- const catalog = (ctx.get('shortcuts') as ShortcutsLike | undefined)?.catalog+function registerSettingsOpenRelay(slots?: SlotRegistry): () => void {+ if (typeof slots?.entries !== 'function' || typeof slots.subscribe !== 'function')+ return () => {}++ let handle: SettingsShell | undefined+ let disposeSeat: (() => void) | undefined+ function refresh(): void {+ const next = slots!.entries(SETTINGS_SIDEBAR_SLOT as never).find(entry =>+ entry.registrant !== SETTINGS_REGISTRANT+ && typeof entry.store === 'object' && entry.store !== null+ && typeof entry.store.create === 'function'+ && typeof entry.store.spec?.actions?.open === 'function'+ && typeof entry.store.spec?.actions?.close === 'function',+ )?.store as SettingsShell | undefined+ if (next === handle)+ return+ disposeSeat?.()+ handle = next+ disposeSeat = next+ ? slots!.register(+ { name: SETTINGS_SHELL_OVERLAY_SLOT, id: SETTINGS_OPEN_RELAY_ID, registrant: SETTINGS_REGISTRANT, store: next } as never,+ SettingsOpenRelay as never,+ )+ : undefined+ }+ refresh()+ const off = slots.subscribe(SETTINGS_SIDEBAR_SLOT as never, refresh)+ return () => {+ off()+ disposeSeat?.()+ }+}++function SettingsOpenRelay({ useStore, actions }: PropsStore<SettingsShell>): null {+ const state = useStore(state => state)+ // 被遮蔽的官方座位仍持有 settings.open;消费后复位,让下一次打开请求继续生效。+ useWatchImmediate([state.open, state.activeId], () => {+ if (state.open !== true)+ return+ store.settings.openAt(typeof state.activeId === 'string' ? state.activeId : undefined)+ actions.close()+ })+ return null+}++function publishLauncherShortcut(shortcuts?: ShortcutsLike): () => void {+ const catalog = shortcuts?.catalogconst snapshot = catalog?.getSnapshotif (typeof snapshot !== 'function')return () => {}@@ -72,7 +125,6 @@ function publishLauncherShortcut(ctx: ClientContext): () => void {}}-/** 目录里 `settings.open` 的生效按键;缺行或键位为空即视为没有提示。 */function shortcutOf(rows: unknown): { keys: readonly string[], aria?: string } | undefined {if (!Array.isArray(rows))return undefined@@ -90,11 +142,9 @@ function shortcutOf(rows: unknown): { keys: readonly string[], aria?: string } |return undefined}-interface CatalogLike {- getSnapshot?: () => unknown- subscribe?: (listener: () => void) => () => void-}-interface ShortcutsLike {- catalog?: CatalogLike+ catalog?: {+ getSnapshot?: () => unknown+ subscribe?: (listener: () => void) => () => void+ }}diff --git a/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx b/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsxindex c8ecb68c..75e69ab7 100644--- a/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx+++ b/packages/dsh-tauri-ui/src/client/ui/settings-sidebar.tsx@@ -1,7 +1,8 @@import type { SessionListState } from 'dsh-tauri/client'-import type { CSSProperties, ReactElement, PointerEvent as ReactPointerEvent } from 'react'+import type { CSSProperties, ReactElement, PointerEvent as ReactPointerEvent, RefObject } from 'react'import type { IconComponent } from '../components/icon'import type { SelectorHook } from '../types/selector'+import { useModalLayer } from '@deepseek-ai/dsh-client-ui-primitives'import { SlotOutlet } from '@deepseek-ai/dsh-client-ui-renderer'import { clamp, cn, isEmpty, useEventListener, useStore } from 'dsh-tauri/client'import { useEffect, useRef, useState } from 'react'@@ -41,6 +42,7 @@ export function SettingsSidebar(_props: SettingsSidebarProps): ReactElement | nuconst { rows } = useStore(store.sections)locale.useLocale()const searchRef = useRef<HTMLInputElement>(null)+ const dialogRef = useRef<HTMLDivElement>(null)// 官方 `Input` 的 props 类型没声明 ref(实现里 `...rest` 会落到 <input>),官方类型补全后可直接写 ref。const searchInputRefProps = { ref: searchRef }const [dragging, setDragging] = useState(false)@@ -77,7 +79,7 @@ export function SettingsSidebar(_props: SettingsSidebarProps): ReactElement | nu})useEventListener(documentRef, 'keydown', (event: KeyboardEvent) => {- if (ui.open && event.key === 'Escape')+ if (typeof useModalLayer !== 'function' && ui.open && event.key === 'Escape')store.settings.close()})@@ -107,74 +109,85 @@ export function SettingsSidebar(_props: SettingsSidebarProps): ReactElement | nu: visible[0]?.idreturn (- <div- className="fixed inset-0 z-[1000] flex bg-[var(--dsw-specific-sidebar-fill)] text-primary [--dsh-chat-content-width:748px] [--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width)_+_32px)] [--dsh-composer-side-clearance:16px]"- data-slot-sidebar="dsh-tauri-ui"- role="dialog"- aria-label={locale.text('settings')}- >+ <><div- className="flex-none box-border flex flex-col gap-[14px] w-[var(--dsh-settings-rail-width)] px-[12px] py-[6px] bg-[var(--dsw-specific-sidebar-fill)] overflow-hidden"- style={{ '--dsh-settings-rail-width': `${railWidth}px` } as CSSProperties}- >- <button- type="button"- className="flex items-center gap-[8px] self-start w-full px-[10px] py-[6px] border-none rounded-[10px] bg-transparent cursor-pointer [font-family:inherit] text-[14px] leading-[22px] text-primary hover:bg-hover"- onClick={() => store.settings.close()}- >- <Icon as={ArrowLeft} />- {locale.text('back')}- </button>- <Input- {...searchInputRefProps}- value={ui.query}- placeholder={locale.text('search')}- aria-label={locale.text('search')}- onChange={event => store.settings.setQuery(event.target.value)}- />- <nav className="flex flex-col gap-[4px] flex-1 overflow-y-auto min-h-0" aria-label={locale.text('settings')}>- {visible.map(row => (- <button- key={row.id}- type="button"- className={cn(- 'box-border h-[40px] px-[12px] py-[9px] border-none rounded-[12px] bg-transparent text-left cursor-pointer [font-family:inherit] text-[14px] leading-[22px] font-normal text-primary flex items-center gap-[8px]',- row.id === activeId && 'bg-[var(--dsw-specific-sidebar-nav-item-active)] font-medium',- )}- aria-current={row.id === activeId ? 'true' : undefined}- onClick={() => store.settings.select(row.id)}- >- <Icon as={Icons[row.id] ?? Gear} size={16} className="flex-none" />- <span className="flex-1 min-w-0 truncate">{row.label}</span>- </button>- ))}- {isEmpty(visible) && <div className="px-[10px] py-[12px] text-[13px] leading-[20px] text-[var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary))]">{locale.text('noResults')}</div>}- </nav>- </div>- <div- role="separator"- aria-orientation="vertical"+ ref={dialogRef}+ className="fixed inset-0 z-[1000] flex bg-[var(--dsw-specific-sidebar-fill)] text-primary [--dsh-chat-content-width:748px] [--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width)_+_32px)] [--dsh-composer-side-clearance:16px]"+ data-slot-sidebar="dsh-tauri-ui"+ data-shortcut-modal="settings"+ role="dialog"+ aria-modal="true"aria-label={locale.text('settings')}- className={cn(- 'flex-none self-stretch w-[8px] -ml-1 z-[2] cursor-col-resize touch-none bg-transparent rounded-[4px]',- dragging && 'bg-border-l2',- )}- onPointerDown={onHandlePointerDown}- />- <div- data-slot="settings.content"- className="flex-1 min-w-0 h-full box-border overflow-y-auto flex bg-[var(--dsw-alias-bg-base)] rounded-tl-[16px] [corner-shape:round]">- <div className="w-[min(calc(var(--dsh-composer-card-max-width)_+_2_*_var(--dsh-composer-side-clearance)),100%)] mx-auto box-border px-[36px] py-[28px]">- {activeId !== undefined && (- <SlotOutlet- slotKey={SETTINGS_SECTION_SLOT}- ownerProps={{ close: () => store.settings.close() }}- opts={{ only: activeId }}- />+ <div+ className="flex-none box-border flex flex-col gap-[14px] w-[var(--dsh-settings-rail-width)] px-[12px] py-[6px] bg-[var(--dsw-specific-sidebar-fill)] overflow-hidden"+ style={{ '--dsh-settings-rail-width': `${railWidth}px` } as CSSProperties}+ >+ <button+ type="button"+ className="flex items-center gap-[8px] self-start w-full px-[10px] py-[6px] border-none rounded-[10px] bg-transparent cursor-pointer [font-family:inherit] text-[14px] leading-[22px] text-primary hover:bg-hover"+ onClick={() => store.settings.close()}+ >+ <Icon as={ArrowLeft} />+ {locale.text('back')}+ </button>+ <Input+ {...searchInputRefProps}+ value={ui.query}+ placeholder={locale.text('search')}+ aria-label={locale.text('search')}+ onChange={event => store.settings.setQuery(event.target.value)}+ />+ <nav className="flex flex-col gap-[4px] flex-1 overflow-y-auto min-h-0" aria-label={locale.text('settings')}>+ {visible.map(row => (+ <button+ key={row.id}+ type="button"+ className={cn(+ 'box-border h-[40px] px-[12px] py-[9px] border-none rounded-[12px] bg-transparent text-left cursor-pointer [font-family:inherit] text-[14px] leading-[22px] font-normal text-primary flex items-center gap-[8px]',+ row.id === activeId && 'bg-[var(--dsw-specific-sidebar-nav-item-active)] font-medium',+ )}+ aria-current={row.id === activeId ? 'true' : undefined}+ onClick={() => store.settings.select(row.id)}+ >+ <Icon as={Icons[row.id] ?? Gear} size={16} className="flex-none" />+ <span className="flex-1 min-w-0 truncate">{row.label}</span>+ </button>+ ))}+ {isEmpty(visible) && <div className="px-[10px] py-[12px] text-[13px] leading-[20px] text-[var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary))]">{locale.text('noResults')}</div>}+ </nav>+ </div>+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label={locale.text('settings')}+ className={cn(+ 'flex-none self-stretch w-[8px] -ml-1 z-[2] cursor-col-resize touch-none bg-transparent rounded-[4px]',+ dragging && 'bg-border-l2',)}+ onPointerDown={onHandlePointerDown}+ />+ <div+ data-slot="settings.content"+ className="flex-1 min-w-0 h-full box-border overflow-y-auto flex bg-[var(--dsw-alias-bg-base)] rounded-tl-[16px] [corner-shape:round]"+ >+ <div className="w-[min(calc(var(--dsh-composer-card-max-width)_+_2_*_var(--dsh-composer-side-clearance)),100%)] mx-auto box-border px-[36px] py-[28px]">+ {activeId !== undefined && (+ <SlotOutlet+ slotKey={SETTINGS_SECTION_SLOT}+ ownerProps={{ close: () => store.settings.close() }}+ opts={{ only: activeId }}+ />+ )}+ </div></div></div>- </div>+ {typeof useModalLayer === 'function' && <SettingsModalLayer dialog={dialogRef} />}+ </>)}++function SettingsModalLayer({ dialog }: { dialog: RefObject<HTMLElement | null> }): null {+ useModalLayer(dialog, true, () => store.settings.close())+ return null+}diff --git a/test/e2e/plugins/browser-modals.e2e.ts b/test/e2e/plugins/browser-modals.e2e.tsnew file mode 100644index 00000000..d890a16b--- /dev/null+++ b/test/e2e/plugins/browser-modals.e2e.ts@@ -0,0 +1,78 @@+import type { Browser, BrowserContext, Page } from 'playwright'+import type { SyntheticFallback } from '../support/browser'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import { dismissAppModals, launchDshBrowser, selectSettingsSection } from '../support/browser'++const SETTINGS = `<section role="dialog" aria-modal="true" data-shortcut-modal="settings" data-slot-sidebar="dsh-tauri-ui">+ <button onclick="this.closest('section').remove()">关闭设置</button>+ <input aria-label="搜索设置" value="kept-query">+ <nav aria-label="设置分区">+ <button aria-current="false" onclick="this.setAttribute('aria-current', 'true')">模型</button>+ </nav>+</section>`+const ONBOARDING = `<section role="dialog" aria-modal="true">+ <div class="fixture_editorActions">+ <button onclick="this.closest('section').remove()">稍后配置</button>+ </div>+</section>`++let browser: Browser+let context: BrowserContext+let page: Page++beforeAll(async () => {+ browser = await launchDshBrowser()+})++beforeEach(async () => {+ context = await browser.newContext()+ page = await context.newPage()+})++afterEach(async () => {+ await context.close()+})++afterAll(async () => {+ await browser.close()+})++describe('浏览器编排:阻塞引导弹窗', () => {+ it('关闭阻塞弹窗时保留已打开的设置页', async () => {+ await page.setContent(SETTINGS)+ const fallbacks: SyntheticFallback[] = []++ await dismissAppModals(page, page.mainFrame(), fallbacks)++ expect(await page.locator('[data-slot-sidebar="dsh-tauri-ui"]').count(), '设置页不是需要自动关闭的引导弹窗').toBe(1)+ expect(await page.getByRole('textbox', { name: '搜索设置' }).inputValue(), '弹窗闸不得重建或清空已打开的设置页').toBe('kept-query')+ expect(fallbacks, '弹窗闸不得合成点击设置页').toEqual([])+ })++ it('iframe 内设置页与引导弹窗共存时只关闭引导并允许选择分区', async () => {+ await page.setContent('<iframe style="width:100%;height:600px"></iframe>')+ const frame = page.frames().find(candidate => candidate.parentFrame() === page.mainFrame())+ if (!frame)+ throw new Error('夹具的应用 iframe 未挂载')+ await frame.setContent(SETTINGS + ONBOARDING)+ const fallbacks: SyntheticFallback[] = []++ await dismissAppModals(page, frame, fallbacks)++ expect(await frame.locator('[data-slot-sidebar="dsh-tauri-ui"]').count(), '关闭引导时必须保留设置侧栏').toBe(1)+ expect(await frame.locator('[role="dialog"]:not([data-slot-sidebar])').count(), '真正的阻塞引导必须被关闭').toBe(0)+ const section = await selectSettingsSection(page, frame, '模型', fallbacks)+ expect(await section.getAttribute('aria-current'), '经过可重入弹窗闸后仍必须能用真实指针选择模型分区').toBe('true')+ expect(fallbacks, '关闭引导与选择分区都不得依赖合成点击').toEqual([])+ })++ it('没有设置页时仍逐个关闭阻塞引导弹窗', async () => {+ await page.setContent(ONBOARDING + ONBOARDING)+ const fallbacks: SyntheticFallback[] = []++ await dismissAppModals(page, page.mainFrame(), fallbacks)++ expect(await page.getByRole('dialog').count(), '所有阻塞引导必须被关闭,不得因设置页保护而漏关').toBe(0)+ expect(fallbacks, '引导关闭必须走真实指针事件').toEqual([])+ })+})diff --git a/test/e2e/support/browser.ts b/test/e2e/support/browser.tsindex 009f211f..9d604ed1 100644--- a/test/e2e/support/browser.ts+++ b/test/e2e/support/browser.ts@@ -62,7 +62,7 @@ export const CONVERSATION_SESSION = '[data-slot="conversation.session"]'export const SIDEBAR_ROW = 'button[class*="panelRow"]'/** 阻塞式引导弹层选择器 */-export const APP_MODAL = '[role="dialog"][aria-modal="true"]'+export const APP_MODAL = '[role="dialog"][aria-modal="true"]:not([data-shortcut-modal="settings"])'export const APP_MODAL_CANCEL = 'div[class*="_editorActions"] > button'// ==========================================