Skip to content

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

feat(dsh-tauri-pet): 设置菜单里加入启用/关闭宠物条目

hairyf930134e1b866
diff --git a/docs/specs/plugin.test.md b/docs/specs/plugin.test.md
index 29dfa8f4..6685bd5b 100644
--- a/docs/specs/plugin.test.md
+++ b/docs/specs/plugin.test.md
@@ -154,7 +154,7 @@ node node_modules/vitest/vitest.mjs run --project plugin test/e2e/plugins/dsh-ta
| --- | --- | --- |
| **插件包** (`packages/*`) | `data-dsh-*`<br>
-<br>*(例: `[data-dsh-tauri-pet-icon]`)* | 插件渲染的挂载点。某些属性属于**行为钩子**(如 DOM 变更过滤),**严禁为测试擅改**。 |
+<br>*(例: `[data-dsh-tauri-pet-menu-item]`)* | 插件渲染的挂载点。某些属性属于**行为钩子**(如 DOM 变更过滤),**严禁为测试擅改**。 |
| **壳层** (`src/**`) | `data-testid="dsh-<域>-<名称>"` | 全小写连字符,集中登记于 `test/e2e/support/selectors.ts`。 |
| **dsh 上游结构** | `data-slot` / `role` / 前缀类 (`dsh`/`dshp`) | 上游 DOM 结构,属于 C 浏览器层断言范畴。用例中需注释来源。 |
| **帧内阻塞弹层** | 结构与类名后缀组合 | 详见 §5,严禁依赖文本内容。 |
diff --git a/packages/dsh-tauri-pet/src/client/constants/index.ts b/packages/dsh-tauri-pet/src/client/constants/index.ts
index f3b7802b..be8981cd 100644
--- a/packages/dsh-tauri-pet/src/client/constants/index.ts
+++ b/packages/dsh-tauri-pet/src/client/constants/index.ts
@@ -9,8 +9,8 @@ export const PET_STYLES_ID = 'dsh-tauri-pet-styles'
export const PET_LOCALE_EFFECT = `${PLUGIN_ID}: locale`
export const PET_STYLES_EFFECT = `${PLUGIN_ID}: styles`
export const PET_SECTION_EFFECT = `${PLUGIN_ID}: settings section`
-export const PET_ICON_PATCH_EFFECT = `${PLUGIN_ID}: sidebar icon patch`
export const PET_PREFILL_EFFECT = `${PLUGIN_ID}: conversation prefill`
+export const PET_MENU_EFFECT = `${PLUGIN_ID}: settings menu items`
/** conversation.input.left 槽位里的一次性草稿注入。 */
export const CONVERSATION_INPUT_LEFT_SLOT = 'conversation.input.left'
@@ -28,15 +28,22 @@ export const CMD_LIST_PETS = 'list_pets'
export const CMD_IMPORT_PET = 'import_pet'
export const CMD_LIST_PRESET_PETS = 'list_preset_pets'
-/** 侧栏入口补丁的稳定选择器与守卫属性(禁止依赖文案或动态类名)。 */
-export const SIDEBAR_SELECTOR = '[data-slot="sidebar"]'
-export const SETTINGS_TRIGGER_SELECTOR = '.dshp-settings-trigger'
-/** 折叠态(Rail 圆形按钮)标记:官方 trigger 组件在窄侧栏下附加,保持定宽不拉伸。 */
-export const SETTINGS_TRIGGER_RAIL_CLASS = 'dshp-settings-trigger--rail'
-export const PET_ICON_ATTRIBUTE = 'data-dsh-tauri-pet-icon'
-export const PET_SETTINGS_ROW_CLASS = 'dshp-pet__settings-row'
-export const PET_ICON_RETRY_MS = 500
-export const PET_ICON_RETRY_MAX = 30
+/**
+ * 设置菜单补丁的选择器与守卫属性。
+ *
+ * 官方账号菜单(桌面载体)与壳层自有菜单(浏览器直开)都是官方 primitives 的 portal `Menu`,
+ * 条目为 `button[role=menuitem]` 且由 `itemWrap` 包裹;「设置」条目是唯一锚点,其它菜单
+ * (工作区、模型选择等)不含该文案。克隆官方条目以继承样式,因此不依赖动态类名哈希。
+ *
+ * 桌宠的开关只存在于这个菜单里:侧栏爪按钮已删除(设置入口两种形态都是菜单)。
+ */
+export const SETTINGS_MENU_LABELS: readonly string[] = ['设置', 'Settings']
+export const MENU_ITEM_SELECTOR = 'button[role="menuitem"]'
+export const MENU_ITEM_WRAP_SELECTOR = '[class*="itemWrap"]'
+export const MENU_ITEM_LABEL_SELECTOR = '[class*="itemLabel"]'
+export const MENU_ITEM_ICON_SELECTOR = '[class*="itemIcon"]'
+export const PET_MENU_ITEM_ATTRIBUTE = 'data-dsh-tauri-pet-menu-item'
+export const PET_MENU_PATCH_ATTRIBUTE = 'data-dsh-tauri-pet-menu-patched'
/** 桌宠窗口大小(百分比)。 */
export const PET_DEFAULT_SIZE = 100
diff --git a/packages/dsh-tauri-pet/src/client/index.ts b/packages/dsh-tauri-pet/src/client/index.ts
index e402f5e7..e7a8f470 100644
--- a/packages/dsh-tauri-pet/src/client/index.ts
+++ b/packages/dsh-tauri-pet/src/client/index.ts
@@ -1,8 +1,8 @@
import type { ClientContext } from 'dsh-tauri/client'
import { PLUGIN_ID } from '../shared/constants'
import {
- PET_ICON_PATCH_EFFECT,
PET_LOCALE_EFFECT,
+ PET_MENU_EFFECT,
PET_PREFILL_EFFECT,
PET_SECTION_EFFECT,
PET_STYLES_EFFECT,
@@ -10,7 +10,7 @@ import {
import { locale } from './locales'
import { petSectionFeature } from './register/pet-section'
import { prefillFeature } from './register/prefill'
-import { sidebarIconFeature } from './register/sidebar-icon'
+import { settingsMenuFeature } from './register/settings-menu'
import { stylesFeature } from './register/styles'
/** 插件显示名(诊断元数据)。 */
@@ -19,13 +19,13 @@ export const name = PLUGIN_ID
/** 需要的客户端服务:slots(槽位注册)、locale(双语文案)、sessions/workspaces(新建会话)。 */
export const inject = ['slots', 'locale', 'sessions', 'workspaces']
-/** 插件体:安装文案与样式,注册设置分区、侧栏入口补丁与草稿注入。 */
+/** 插件体:安装文案与样式,注册设置分区、设置菜单项与草稿注入。 */
export function apply(ctx: ClientContext): void {
if (typeof window === 'undefined' || typeof document === 'undefined' || window.parent === window)
return
ctx.effect(locale.registerLocale, PET_LOCALE_EFFECT)
ctx.effect(stylesFeature, PET_STYLES_EFFECT)
ctx.effect(petSectionFeature, PET_SECTION_EFFECT)
- ctx.effect(sidebarIconFeature, PET_ICON_PATCH_EFFECT)
+ ctx.effect(settingsMenuFeature, PET_MENU_EFFECT)
ctx.effect(prefillFeature, PET_PREFILL_EFFECT)
}
diff --git a/packages/dsh-tauri-pet/src/client/register/settings-menu.ts b/packages/dsh-tauri-pet/src/client/register/settings-menu.ts
new file mode 100644
index 00000000..8189239e
--- /dev/null
+++ b/packages/dsh-tauri-pet/src/client/register/settings-menu.ts
@@ -0,0 +1,69 @@
+import { defineRegister } from 'dsh-tauri/client'
+import {
+ MENU_ITEM_SELECTOR,
+ MENU_ITEM_WRAP_SELECTOR,
+ PET_MENU_ITEM_ATTRIBUTE,
+ PET_MENU_PATCH_ATTRIBUTE,
+} from '../constants'
+import { locale } from '../locales'
+import { loadPetStatus, togglePet } from '../service/pet'
+import { store } from '../store'
+import { decoratePetMenuItem, isSettingsMenuItem } from './settings-menu.utils'
+
+/**
+ * 设置菜单里的桌宠开关。
+ *
+ * 桌面载体下「设置」入口由官方账号菜单占据(`settings.launcher`),浏览器直开时由壳层
+ * 自有菜单占据——两者都是官方 primitives 的 portal `Menu`,因此统一按「含『设置』条目」
+ * 识别菜单,克隆该条目改成当前可用的桌宠动作(启用 / 关闭),点击后切换并收起菜单。
+ * 官方菜单条目是 React 管理的节点,克隆项不在其 fiber 里,交互只能走本模块的原生监听。
+ */
+export const settingsMenuFeature = defineRegister((controller) => {
+ if (typeof document === 'undefined')
+ return
+
+ void loadPetStatus()
+
+ function patchMenu(settingsItem: HTMLButtonElement): void {
+ const menu = settingsItem.closest<HTMLElement>('[role="menu"]')
+ if (menu === null || menu.hasAttribute(PET_MENU_PATCH_ATTRIBUTE))
+ return
+ menu.setAttribute(PET_MENU_PATCH_ATTRIBUTE, '1')
+ // 只认官方 primitives 条目:其它插件自绘的 role=menuitem 没有 itemWrap 结构。
+ if (settingsItem.closest(MENU_ITEM_WRAP_SELECTOR) === null)
+ return
+ const item = decoratePetMenuItem(settingsItem, enabled() ? locale.text('closePet') : locale.text('enablePet'))
+ if (item === null)
+ return
+ settingsItem.after(item)
+ }
+
+ function scan(): void {
+ for (const item of document.querySelectorAll<HTMLButtonElement>(MENU_ITEM_SELECTOR)) {
+ if (isSettingsMenuItem(item))
+ patchMenu(item)
+ }
+ }
+
+ controller.observe(document.body, scan, { childList: true, subtree: true })
+ controller.listen('click', (event) => {
+ const origin = event.target
+ if (!(origin instanceof Element))
+ return
+ if (origin.closest(`[${PET_MENU_ITEM_ATTRIBUTE}]`) === null)
+ return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ void togglePet({ enabled: !enabled() })
+ // 克隆条目不会触发官方 onSelect(菜单不自关),派发一次外部 pointerdown 收起菜单。
+ const PointerEventCtor = typeof PointerEvent === 'function' ? PointerEvent : MouseEvent
+ document.dispatchEvent(new PointerEventCtor('pointerdown', { bubbles: true, cancelable: true }))
+ }, { capture: true })
+})
+
+// --- internal ---
+
+/** 当前是否启用(菜单条目文案与点击切换共用的唯一真值)。 */
+function enabled(): boolean {
+ return store.pet.$state.status?.enabled ?? false
+}
diff --git a/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.test.ts b/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.test.ts
new file mode 100644
index 00000000..1b3ade20
--- /dev/null
+++ b/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.test.ts
@@ -0,0 +1,75 @@
+/**
+ * settings-menu.utils.test.ts — 设置菜单桌宠条目的补丁契约。
+ *
+ * 仓库未装 jsdom:这里用最小假节点锁住三条真实契约——只认「设置」文案锚点、克隆项换文案
+ * 与爪印图标并打守卫属性、缺 primitives 文案节点时中止(不插半成品条目)。
+ */
+import { describe, expect, it } from 'vitest'
+import { decoratePetMenuItem, isSettingsMenuItem } from './settings-menu.utils'
+
+interface FakeNode {
+ textContent?: string
+ label: FakeLabel | null
+ icon: FakeIcon | null
+ attributes: Record<string, string>
+}
+
+interface FakeLabel {
+ textContent: string
+}
+
+interface FakeIcon {
+ innerHTML: string
+}
+
+function fakeItem(text: string, structure = true): HTMLButtonElement {
+ const label: FakeLabel | null = structure ? { textContent: text } : null
+ const icon: FakeIcon | null = structure ? { innerHTML: '<svg data-official="1"></svg>' } : null
+ const node = {
+ textContent: text,
+ label,
+ icon,
+ attributes: {} as Record<string, string>,
+ cloneNode(): unknown {
+ return fakeItem(text, structure)
+ },
+ querySelector(selector: string): unknown {
+ if (selector.includes('itemLabel'))
+ return node.label
+ if (selector.includes('itemIcon'))
+ return node.icon
+ return null
+ },
+ setAttribute(name: string, value: string): void {
+ node.attributes[name] = value
+ },
+ }
+ return node as unknown as HTMLButtonElement
+}
+
+describe('isSettingsMenuItem', () => {
+ it('matches only the settings labels', () => {
+ expect(isSettingsMenuItem(fakeItem('设置'))).toBe(true)
+ expect(isSettingsMenuItem(fakeItem('Settings'))).toBe(true)
+ expect(isSettingsMenuItem(fakeItem('删除工作区'))).toBe(false)
+ expect(isSettingsMenuItem(fakeItem('设置宠物'))).toBe(false)
+ })
+})
+
+describe('decoratePetMenuItem', () => {
+ it('rewrites the label and icon and marks the clone', () => {
+ const source = fakeItem('设置')
+
+ const item = decoratePetMenuItem(source, '启用宠物')
+ const clone = item as unknown as FakeNode
+
+ expect(clone).not.toBe(source)
+ expect(clone.label?.textContent).toBe('启用宠物')
+ expect(clone.icon?.innerHTML).toContain('<path')
+ expect(clone.attributes['data-dsh-tauri-pet-menu-item']).toBe('1')
+ })
+
+ it('refuses to decorate a non-primitives item', () => {
+ expect(decoratePetMenuItem(fakeItem('设置', false), '启用宠物')).toBeNull()
+ })
+})
diff --git a/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.ts b/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.ts
new file mode 100644
index 00000000..68bb345e
--- /dev/null
+++ b/packages/dsh-tauri-pet/src/client/register/settings-menu.utils.ts
@@ -0,0 +1,47 @@
+import {
+ MENU_ITEM_ICON_SELECTOR,
+ MENU_ITEM_LABEL_SELECTOR,
+ PET_MENU_ITEM_ATTRIBUTE,
+ SETTINGS_MENU_LABELS,
+} from '../constants'
+
+/** 爪印字形(@gravity-ui/icons 无对应图标,随 currentColor 变色)。 */
+const PET_PAW_PATHS = [
+ 'M12 13.5c-2.7 0-5.5 2-5.5 4.3 0 1.4 1 2.2 2.3 2.2 1 0 1.9-.6 3.2-.6s2.2.6 3.2.6c1.3 0 2.3-.8 2.3-2.2 0-2.3-2.8-4.3-5.5-4.3z',
+ 'M7.3 8.1c-1 .1-1.8 1.2-1.7 2.5.1 1.2 1 2.1 2 2 .9-.1 1.7-1.2 1.6-2.4-.1-1.2-1-2.2-1.9-2.1z',
+ 'M12 4.5c-1.1 0-2 1.1-2 2.5s.9 2.5 2 2.5 2-1.1 2-2.5-.9-2.5-2-2.5z',
+ 'M16.7 8.1c-.9-.1-1.8.9-1.9 2.1-.1 1.2.7 2.3 1.6 2.4 1 .1 1.9-.8 2-2 .1-1.3-.7-2.4-1.7-2.5z',
+ 'M4.8 12.3c-.8.3-1.2 1.4-.9 2.4.3 1 1.2 1.6 2 1.3.8-.3 1.1-1.4.8-2.4-.3-1-1.1-1.6-1.9-1.3z',
+ 'M19.2 12.3c-.8-.3-1.6.3-1.9 1.3-.3 1 0 2.1.8 2.4.8.3 1.7-.3 2-1.3.3-1-.1-2.1-.9-2.4z',
+]
+
+/** 克隆条目换图标用的标记串(不引入 react-dom/server)。 */
+const PET_PAW_SVG = `<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">${PET_PAW_PATHS.map(path => `<path d="${path}"/>`).join('')}</svg>`
+
+/**
+ * 该条目是否是设置菜单的锚点(文案为「设置」)。
+ *
+ * 官方账号菜单与壳层自有菜单都以它作为唯一稳定锚点:两者条目结构相同(primitives 的
+ * `button[role=menuitem]`),其它菜单(工作区、模型选择)不含该文案。
+ */
+export function isSettingsMenuItem(item: HTMLElement): boolean {
+ const text = item.textContent?.trim() ?? ''
+ return SETTINGS_MENU_LABELS.includes(text)
+}
+
+/**
+ * 克隆官方条目改成桌宠动作项:样式随克隆继承(绝不手写动态类名哈希),只换文案与图标。
+ * 文案节点缺失(非 primitives 结构)时返回 null,调用方中止插入,不追加半成品条目。
+ */
+export function decoratePetMenuItem(source: HTMLButtonElement, label: string): HTMLButtonElement | null {
+ const item = source.cloneNode(true) as HTMLButtonElement
+ const labelNode = item.querySelector<HTMLElement>(MENU_ITEM_LABEL_SELECTOR)
+ if (labelNode === null)
+ return null
+ labelNode.textContent = label
+ const icon = item.querySelector<HTMLElement>(MENU_ITEM_ICON_SELECTOR)
+ if (icon !== null)
+ icon.innerHTML = PET_PAW_SVG
+ item.setAttribute(PET_MENU_ITEM_ATTRIBUTE, '1')
+ return item
+}
diff --git a/packages/dsh-tauri-pet/src/client/register/sidebar-icon.ts b/packages/dsh-tauri-pet/src/client/register/sidebar-icon.ts
deleted file mode 100644
index 1465483d..00000000
--- a/packages/dsh-tauri-pet/src/client/register/sidebar-icon.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import type { RegisterController } from 'dsh-tauri/client'
-import { Icon, IconButton, StateDot } from 'dsh-tauri-ui/client'
-import { defineRegister } from 'dsh-tauri/client'
-import { createElement } from 'react'
-import { createRoot } from 'react-dom/client'
-import {
- PET_ICON_ATTRIBUTE,
- PET_ICON_RETRY_MAX,
- PET_ICON_RETRY_MS,
- SETTINGS_TRIGGER_SELECTOR,
- SIDEBAR_SELECTOR,
-} from '../constants'
-import { locale } from '../locales'
-import { loadPetStatus, togglePet } from '../service/pet'
-import { store } from '../store'
-import {
- applySettingsRow,
- isRailTrigger,
- PetPawIcon,
- revertSettingsRow,
-} from './sidebar-icon.utils'
-
-/**
- * 侧栏桌宠入口补丁:入口由 dsh-tauri-ui 的 IconButton 渲染,插在 `.dshp-settings-trigger`
- * 右侧;两态(绿点 = 已启用),点击切换启用状态,设置页走 settings.section。
- */
-export const sidebarIconFeature = defineRegister((controller) => {
- registerSidebarPetIcon(controller)
-})
-
-/** 当前是否启用(绿点两态的唯一真值来自共享 store)。 */
-function iconActive(): boolean {
- return store.pet.$state.status?.enabled ?? false
-}
-
-/** 纯持久开关:关掉即落盘 `enabled=false`,重启后不会自己再起来(失败由服务层记录)。 */
-async function toggleEnabled(): Promise<void> {
- await togglePet({ enabled: !iconActive() })
-}
-
-function registerSidebarPetIcon(controller: RegisterController): void {
- if (typeof document === 'undefined')
- return
-
- const label = locale.text('name')
- // 按钮渲染在脱离文档的 React 根里再搬进侧栏:根外收不到合成事件(交互走原生监听),
- // 卸载前必须搬回容器(React 只从自己的容器里摘节点)。
- const entryHost = document.createElement('div')
- const entryRoot = createRoot(entryHost)
- let button: HTMLButtonElement | undefined
- let rowHost: HTMLElement | undefined
- let patchedTrigger: HTMLElement | undefined
- let patchedRail: boolean | undefined
-
- const onClick = (): void => {
- void toggleEnabled()
- }
-
- function render(): void {
- const active = iconActive()
- entryRoot.render(createElement(
- IconButton,
- {
- 'variant': 'round',
- 'className': 'dshp-pet__icon-entry',
- 'icon': createElement(Icon, { as: PetPawIcon }),
- 'aria-label': label,
- 'aria-pressed': active,
- },
- active
- ? createElement(
- 'span',
- { className: 'dshp-pet__icon-dot' },
- createElement(StateDot, { state: 'done', size: 6 }),
- )
- : null,
- ))
- }
-
- /** 按钮由 React 异步渲染进宿主,落到宿主后才挂守卫属性、提示气泡与点击监听。 */
- function capture(): void {
- if (button !== undefined)
- return
- const node = entryHost.firstElementChild
- if (!(node instanceof HTMLButtonElement))
- return
- button = node
- button.setAttribute(PET_ICON_ATTRIBUTE, '1')
- button.setAttribute('data-tip', label)
- button.addEventListener('click', onClick)
- scan()
- }
-
- /** 行布局只在宿主/触发器/折叠态真的变化时才重写(观察器回调高频)。 */
- function applyRowStyles(host: HTMLElement, trigger: HTMLElement): void {
- const rail = isRailTrigger(trigger)
- if (host === rowHost && trigger === patchedTrigger && rail === patchedRail)
- return
- applySettingsRow(host, trigger, rail)
- rowHost = host
- patchedTrigger = trigger
- patchedRail = rail
- }
-
- /** 看护入口按钮:触发器就绪且按钮不在其右侧时(首次挂载 / React 重渲染丢弃)重新插入。 */
- function ensurePlaced(): void {
- const trigger = document.querySelector<HTMLElement>(SETTINGS_TRIGGER_SELECTOR)
- if (!trigger?.parentElement)
- return
- applyRowStyles(trigger.parentElement, trigger)
- if (button === undefined || (button.isConnected && button.previousElementSibling === trigger))
- return
- trigger.after(button)
- }
-
- function scan(): void {
- // 侧栏未就绪时静默跳过(由重试计时器兜底),就绪后交由观察器看护。
- if (!document.querySelector(SIDEBAR_SELECTOR))
- return
- ensurePlaced()
- }
-
- // 按钮异步落到宿主,宿主一变就去认领;两态随 store 变化,首屏再拉一次权威状态。
- controller.observe(entryHost, capture, { childList: true })
- render()
- controller.add(store.pet.$subscribe(render))
- void loadPetStatus()
-
- controller.observe(document.body, scan, { childList: true, subtree: true })
-
- // 观察器覆盖不到「应用晚挂载、长时间无 DOM 变更」的空窗,补一条短暂轮询(侧栏出现即停)。
- let tries = 0
- const stopPolling = controller.interval(() => {
- scan()
- if (document.querySelector(SIDEBAR_SELECTOR) || ++tries > PET_ICON_RETRY_MAX)
- stopPolling()
- }, PET_ICON_RETRY_MS)
- scan()
-
- // 收尾:注册顺序保证它在观察器断开之后执行(否则移除按钮会触发 scan 重新插入)。
- controller.add(() => {
- if (button !== undefined) {
- button.removeEventListener('click', onClick)
- entryHost.append(button)
- button = undefined
- }
- entryRoot.unmount()
- revertSettingsRow(rowHost, patchedTrigger)
- rowHost = undefined
- patchedTrigger = undefined
- patchedRail = undefined
- })
-}
diff --git a/packages/dsh-tauri-pet/src/client/register/sidebar-icon.utils.ts b/packages/dsh-tauri-pet/src/client/register/sidebar-icon.utils.ts
deleted file mode 100644
index cb227e44..00000000
--- a/packages/dsh-tauri-pet/src/client/register/sidebar-icon.utils.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import type { ReactElement, SVGProps } from 'react'
-import { createElement } from 'react'
-import {
- PET_SETTINGS_ROW_CLASS,
- SETTINGS_TRIGGER_RAIL_CLASS,
-} from '../constants'
-
-/** 爪印字形(@gravity-ui/icons 无对应图标,随 currentColor 变色)。 */
-const PET_PAW_PATHS = [
- 'M12 13.5c-2.7 0-5.5 2-5.5 4.3 0 1.4 1 2.2 2.3 2.2 1 0 1.9-.6 3.2-.6s2.2.6 3.2.6c1.3 0 2.3-.8 2.3-2.2 0-2.3-2.8-4.3-5.5-4.3z',
- 'M7.3 8.1c-1 .1-1.8 1.2-1.7 2.5.1 1.2 1 2.1 2 2 .9-.1 1.7-1.2 1.6-2.4-.1-1.2-1-2.2-1.9-2.1z',
- 'M12 4.5c-1.1 0-2 1.1-2 2.5s.9 2.5 2 2.5 2-1.1 2-2.5-.9-2.5-2-2.5z',
- 'M16.7 8.1c-.9-.1-1.8.9-1.9 2.1-.1 1.2.7 2.3 1.6 2.4 1 .1 1.9-.8 2-2 .1-1.3-.7-2.4-1.7-2.5z',
- 'M4.8 12.3c-.8.3-1.2 1.4-.9 2.4.3 1 1.2 1.6 2 1.3.8-.3 1.1-1.4.8-2.4-.3-1-1.1-1.6-1.9-1.3z',
- 'M19.2 12.3c-.8-.3-1.6.3-1.9 1.3-.3 1 0 2.1.8 2.4.8.3 1.7-.3 2-1.3.3-1-.1-2.1-.9-2.4z',
-]
-
-export function PetPawIcon(props: SVGProps<SVGSVGElement>): ReactElement {
- return createElement(
- 'svg',
- { 'viewBox': '0 0 24 24', 'fill': 'currentColor', 'aria-hidden': 'true', ...props },
- PET_PAW_PATHS.map(path => createElement('path', { key: path, d: path })),
- )
-}
-
-/** 触发器是否处于折叠态(Rail 圆形按钮):折叠态保持定宽,不做拉伸修正。 */
-export function isRailTrigger(trigger: HTMLElement): boolean {
- return trigger.classList.contains(SETTINGS_TRIGGER_RAIL_CLASS)
-}
-
-/**
- * 把触发器宿主立成 flex 行(复刻新版 dsh 客户端 SettingsRoot 的 triggerRow)。
- *
- * 除行类 + CSS 规则外再写一份内联样式兜底:CSS 可能被加载顺序/特异性盖过(表现为图标
- * 仍被挤到下一行),而 React 对未声明 style 的节点不会清除外部内联样式。
- */
-export function applySettingsRow(host: HTMLElement, trigger: HTMLElement, rail: boolean): void {
- host.classList.add(PET_SETTINGS_ROW_CLASS)
- host.style.display = 'flex'
- host.style.alignItems = 'center'
- host.style.gap = '8px'
- host.style.width = '100%'
- if (rail) {
- trigger.style.removeProperty('flex')
- trigger.style.removeProperty('width')
- trigger.style.removeProperty('min-width')
- return
- }
- trigger.style.flex = '1 1 auto'
- trigger.style.width = 'auto'
- trigger.style.minWidth = '0'
-}
-
-/** 撤销设置行的类与内联样式(卸载时;未打过补丁的节点原样返回)。 */
-export function revertSettingsRow(host: HTMLElement | undefined, trigger: HTMLElement | undefined): void {
- if (host) {
- host.classList.remove(PET_SETTINGS_ROW_CLASS)
- host.style.removeProperty('display')
- host.style.removeProperty('align-items')
- host.style.removeProperty('gap')
- host.style.removeProperty('width')
- }
- if (!trigger)
- return
- trigger.style.removeProperty('flex')
- trigger.style.removeProperty('width')
- trigger.style.removeProperty('min-width')
-}
diff --git a/packages/dsh-tauri-pet/src/client/styles/index.cssr.ts b/packages/dsh-tauri-pet/src/client/styles/index.cssr.ts
index c9797723..972b34ab 100644
--- a/packages/dsh-tauri-pet/src/client/styles/index.cssr.ts
+++ b/packages/dsh-tauri-pet/src/client/styles/index.cssr.ts
@@ -137,44 +137,4 @@ export default c([
alignItems: 'center',
gap: '6px',
}),
-
- // 旧版客户端触发器是通栏块级元素,补丁给宿主加 flex 行,入口按钮才不会被挤到下一行。
- c('.dshp-pet__settings-row', {
- display: 'flex',
- alignItems: 'center',
- gap: '8px',
- width: '100%',
- }),
- c('.dshp-pet__settings-row > .dshp-settings-trigger:not(.dshp-settings-trigger--rail)', {
- flex: '1 1 auto',
- width: 'auto',
- minWidth: '0',
- }),
- c('.dshp-pet__icon-entry', { flex: 'none', marginRight: '2px' }),
- c('[data-sidebar-collapsed] .dshp-pet__icon-entry', { display: 'none' }),
- c('.dshp-pet__icon-dot', {
- display: 'flex',
- position: 'absolute',
- top: '3px',
- right: '3px',
- }),
- c('.dshp-pet__icon-entry::after', {
- content: 'attr(data-tip)',
- position: 'absolute',
- bottom: 'calc(100% + 6px)',
- left: '50%',
- transform: 'translateX(-50%)',
- background: 'var(--dsw-alias-label-primary)',
- color: 'var(--dsw-alias-bg-layer-3)',
- padding: '4px 8px',
- borderRadius: '6px',
- fontSize: '12px',
- lineHeight: '16px',
- whiteSpace: 'nowrap',
- pointerEvents: 'none',
- opacity: '0',
- transition: 'opacity 0.15s ease',
- zIndex: '10',
- }),
- c('.dshp-pet__icon-entry:hover::after, .dshp-pet__icon-entry:focus-visible::after', { opacity: '1' }),
])
diff --git a/test/e2e/desktop/pet.e2e.ts b/test/e2e/desktop/pet.e2e.ts
index 64331002..f1b14569 100644
--- a/test/e2e/desktop/pet.e2e.ts
+++ b/test/e2e/desktop/pet.e2e.ts
@@ -22,8 +22,14 @@ const MAIN_WEBVIEW = 'main'
/** 桌宠独立窗口 label(`src-tauri/src/desktop/pet.rs:29`)。 */
const PET_WEBVIEW = 'pet'
-/** 插件侧栏入口的稳定锚点(`packages/dsh-tauri-pet/src/client/constants/index.ts:38`)。 */
-const PET_ICON = '[data-dsh-tauri-pet-icon]'
+/** 插件就绪锚点:插件样式元素(`mountStyle` 交给 css-render 落成 `style[cssr-id=…]`)。 */
+const PET_STYLES = 'style[cssr-id="dsh-tauri-pet-styles"]'
+
+/** 设置入口触发器(`packages/dsh-tauri-ui/src/client/ui/trigger.tsx`)。 */
+const SETTINGS_TRIGGER = '.dshp-settings-trigger'
+
+/** 设置菜单里的桌宠条目(`packages/dsh-tauri-pet/src/client/constants/index.ts`)。 */
+const PET_MENU_ITEM = '[data-dsh-tauri-pet-menu-item="1"]'
/** 桌宠尺寸合法区间(`src-tauri/src/desktop/pet.rs:48-49` 的 50.0 / 200.0)。 */
const PET_SIZE_MIN = 50
@@ -57,9 +63,9 @@ function elementExists(selector: string): boolean {
return document.querySelector(selector) !== null
}
-/** 元素的 `aria-pressed` 属性 */
-function elementAriaPressed(selector: string): string | null {
- return document.querySelector(selector)?.getAttribute('aria-pressed') ?? null
+/** 匹配元素的数量(`browser.$$` 的 `length` 在 WDIO 9 里是 Promise,脚本函数更直接) */
+function elementCount(selector: string): number {
+ return document.querySelectorAll(selector).length
}
/** 在页面(壳层或帧内)安装报错收集器:三类页面级错误收进 `window.__dshE2eErrors` */
@@ -116,8 +122,8 @@ describe.skipIf(process.platform !== 'win32')('桌面端桌宠独立窗口', ()
await withIframe(async () => {
await browser.execute(collectPageErrors)
await browser.waitUntil(
- () => browser.execute(elementExists, PET_ICON),
- { timeout: 60_000, timeoutMsg: '内嵌 dsh 界面未渲染出桌宠入口(插件 client 未生效)' },
+ () => browser.execute(elementExists, PET_STYLES),
+ { timeout: 60_000, timeoutMsg: '内嵌 dsh 界面未渲染出桌宠插件产物(插件 client 未生效)' },
)
})
@@ -203,34 +209,53 @@ describe.skipIf(process.platform !== 'win32')('桌面端桌宠独立窗口', ()
}
}
- /** 帧内读入口两态 */
- async function iconAriaPressed(): Promise<string | null> {
- return withIframe(() => app.browser.execute(elementAriaPressed, PET_ICON))
- }
-
- /** 帧内点击侧栏桌宠入口(用户路径),返回点击前的 `aria-pressed` */
- async function clickSidebarIcon(): Promise<string | null> {
+ /**
+ * 帧内打开设置入口,并等菜单里出现唯一的桌宠条目。
+ *
+ * 桌宠条目由插件在「设置」菜单展开时才克隆出来,只有菜单处于展开态才存在;
+ * `.dshp-settings-trigger` / `data-dsh-tauri-pet-menu-item` 都是插件自有的稳定选择器。
+ */
+ async function openPetMenu(): Promise<void> {
const browser = app.browser
await dismissDshModals(browser)
- return withIframe(async () => {
- const icon = await browser.$(PET_ICON)
- expect(await icon.isExisting(), '侧栏桌宠入口必须存在').toBe(true)
+ await withIframe(async () => {
+ const trigger = await browser.$(SETTINGS_TRIGGER)
+ await browser.waitUntil(
+ async () => await trigger.isExisting(),
+ { timeout: 30_000, timeoutMsg: '设置入口未渲染(dsh-tauri-ui 未生效)' },
+ )
+
+ if (await trigger.getAttribute('aria-expanded') !== 'true')
+ await trigger.click()
- const before = await browser.execute(elementAriaPressed, PET_ICON)
- await icon.click()
- return before
+ await browser.waitUntil(
+ async () => await browser.execute(elementCount, PET_MENU_ITEM) === 1,
+ { timeout: 30_000, timeoutMsg: '设置菜单展开后必须出现唯一的桌宠条目' },
+ )
})
}
- /** 点击侧栏入口并验证句柄及同步状态 */
- async function clickIconToggling(expectBefore: string, expected: string[], message: string): Promise<void> {
- const beforeState = await clickSidebarIcon()
- expect(
- beforeState,
- `点击前入口 aria-pressed 必须为 ${expectBefore}(不一致即入口 store 与后端失同步)`,
- ).toBe(expectBefore)
+ /** 帧内点击设置菜单里的桌宠条目(用户路径的唯一开关入口),随后菜单自行收起。 */
+ async function togglePet(): Promise<void> {
+ const browser = app.browser
+ await openPetMenu()
+
+ await withIframe(async () => {
+ await (await browser.$(PET_MENU_ITEM)).click()
+ })
+
+ await dismissDshModals(browser)
+ }
+
+ /** 从设置菜单切换桌宠,先断后端状态真的翻转,再等窗口句柄收敛(全部断言 Tauri 原生产物)。 */
+ async function togglePetExpecting(expected: string[], message: string): Promise<void> {
+ const before = (await status()).enabled
+ expect(before, '切换前必须能读到后端 enabled 状态(否则后端已失联)').toBeTypeOf('boolean')
+
+ await togglePet()
+ expect((await status()).enabled, `点击桌宠条目后后端 enabled 必须从 ${before} 翻转`).toBe(!before)
await waitHandles(expected, message)
}
@@ -241,13 +266,13 @@ describe.skipIf(process.platform !== 'win32')('桌面端桌宠独立窗口', ()
it('TC-PET-L3-02-001 启用后出现独立的桌宠窗口', async () => {
await waitHandles([MAIN_WEBVIEW], '复位后窗口句柄必须恰为主窗口')
- await clickIconToggling('false', [MAIN_WEBVIEW, PET_WEBVIEW], '点击侧栏入口后必须出现独立的 pet 窗口句柄')
+ await togglePetExpecting([MAIN_WEBVIEW, PET_WEBVIEW], '点击设置菜单里的桌宠条目后必须出现独立的 pet 窗口句柄')
const state = await status()
expect(state.enabled, '创建窗口后状态必须为 enabled:true').toBe(true)
expect(state.visible, 'enabled 为真时 visible 必须同为真').toBe(true)
- await clickIconToggling('true', [MAIN_WEBVIEW], '再次点击入口后 pet 窗口必须销毁')
+ await togglePetExpecting([MAIN_WEBVIEW], '再次点击桌宠条目后 pet 窗口必须销毁')
expect((await status()).enabled, '关闭后状态必须回到 enabled:false').toBe(false)
await expectNoPageErrors('TC-PET-L3-02-001 建窗/销毁全流程')
@@ -262,15 +287,15 @@ describe.skipIf(process.platform !== 'win32')('桌面端桌宠独立窗口', ()
expect(await app.browser.getWindowHandles(), '未启用时窗口句柄必须恰为 [main]').toEqual([MAIN_WEBVIEW])
})
- it('TC-PET-L3-02-003 侧栏入口按钮切换后窗口随之创建与销毁', async () => {
+ it('TC-PET-L3-02-003 设置菜单桌宠条目切换后窗口随之创建与销毁', async () => {
await setEnabled(false)
await waitHandles([MAIN_WEBVIEW], '复位后窗口句柄必须恰为主窗口')
- expect(await iconAriaPressed(), '复位后入口两态必须停在关闭态').toBe('false')
+ expect((await status()).enabled, '复位后后端必须停在关闭态').toBe(false)
- await clickIconToggling('false', [MAIN_WEBVIEW, PET_WEBVIEW], '首次点击后必须出现 pet 窗口')
+ await togglePetExpecting([MAIN_WEBVIEW, PET_WEBVIEW], '首次点击后必须出现 pet 窗口')
expect((await status()).enabled, '首次点击后状态必须为 enabled:true').toBe(true)
- await clickIconToggling('true', [MAIN_WEBVIEW], '二次点击后 pet 窗口必须销毁')
+ await togglePetExpecting([MAIN_WEBVIEW], '二次点击后 pet 窗口必须销毁')
expect((await status()).enabled, '二次点击后状态必须回到 enabled:false').toBe(false)
await expectNoPageErrors('TC-PET-L3-02-003 点击切换往返')
diff --git a/test/e2e/plugins/dsh-tauri-pet.e2e.ts b/test/e2e/plugins/dsh-tauri-pet.e2e.ts
index 820e59e9..f7d9d5b6 100644
--- a/test/e2e/plugins/dsh-tauri-pet.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-pet.e2e.ts
@@ -6,26 +6,35 @@
* 「路由已注册且 handler 跑起来了」的正向证据。
*
* 上半部分只走 HTTP:断言对象是路由注册与 SSE 字节;下半部分是浏览器层用例,
- * 覆盖 Bundle Slot 挂载与侧栏 DOM 补丁。
+ * 覆盖 Bundle Slot 挂载与设置菜单 DOM 补丁。
*/
-import type { Browser } from 'playwright'
+import type { Browser, Locator } from 'playwright'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterAll, beforeAll, describe, expect, inject, it } from 'vitest'
-import { PET_ICON_RETRY_MAX, PET_ICON_RETRY_MS } from '../../../packages/dsh-tauri-pet/src/client/constants/index.ts'
import {
expectNoSyntheticFallbacks,
launchDshBrowser,
newDshPage,
openSettings,
- PET_ICON,
+ openSettingsMenu,
+ PET_MENU_ITEM,
+ PET_MENU_PATCHED,
+ PET_STYLES,
selectSettingsSection,
SETTINGS_NAV_ITEM,
SETTINGS_TRIGGER,
- SIDEBAR,
} from '../support/browser'
+/** 桌宠条目里承载文案的节点(与插件 `MENU_ITEM_LABEL_SELECTOR` 对齐)。 */
+const MENU_ITEM_LABEL = '[class*="itemLabel"]'
+
+/** 读桌宠条目的文案:用 `textContent`(插件自己写的就是它,不触发布局)。 */
+function readMenuLabel(item: Locator): Promise<string> {
+ return item.locator(MENU_ITEM_LABEL).first().evaluate(element => element.textContent?.trim() ?? '')
+}
+
/** 与 `packages/dsh-tauri-pet/src/shared/constants.ts` 的 SESSION_STREAM_PATH 对齐。 */
const SESSION_STREAM_PATH = '/api/desktop/dsh-tauri-pet/session/stream'
@@ -61,16 +70,6 @@ const KEEPALIVE_MS = 15_000
/** 第 2 帧心跳的可接受上界:一个周期 + 2s 抖动余量,不因读慢了就放宽。 */
const KEEPALIVE_WINDOW_MAX_MS = 17_000
-/**
- * 侧栏入口兜底轮询的最长存活窗口,取自插件真实常量:
- * `packages/dsh-tauri-pet/src/client/register/sidebar-icon.ts:110-114` 每 `PET_ICON_RETRY_MS`
- * 走一轮,`tries > PET_ICON_RETRY_MAX` 即停止,因此最长 31 轮。
- */
-const RETRY_WINDOW_MS = PET_ICON_RETRY_MS * (PET_ICON_RETRY_MAX + 1)
-
-/** 观察时长:必须长于轮询窗口,否则「预算耗尽之后」的断言无从谈起。 */
-const RETRY_SETTLE_MS = 18_000
-
/** 一次读取的结果:累计文本、自建连起的耗时、已消费的响应块数。 */
interface SseRead {
text: string
@@ -239,12 +238,12 @@ describe('L2 客户端', () => {
const slots = await top.frame.evaluate(() => ({
hasTrigger: document.querySelector('.dshp-settings-trigger') !== null,
- petIcons: document.querySelectorAll('[data-dsh-tauri-pet-icon]').length,
+ petStyles: document.querySelectorAll('style[cssr-id="dsh-tauri-pet-styles"]').length,
petSections: document.querySelectorAll('[id="dsh-tauri-pet-settings"]').length,
}))
expect(slots.hasTrigger, '顶层页面必须真的渲染出设置触发器(否则这条断言是空转)').toBe(true)
- expect(slots.petIcons, '顶层页面不得被插入桌宠入口(window.parent === window 早退)').toBe(0)
+ expect(slots.petStyles, '顶层页面不得挂载桌宠样式与菜单补丁(window.parent === window 早退)').toBe(0)
expect(slots.petSections, '顶层页面不得注册桌宠设置分区').toBe(0)
expectNoSyntheticFallbacks(top)
expect(top.errors, '早退路径不得产出应用级错误').toEqual([])
@@ -255,7 +254,7 @@ describe('L2 客户端', () => {
})
it('验证 iframe 内桌宠设置分区正常渲染且无崩溃', async () => {
- const app = await newDshPage(browser, { ready: PET_ICON })
+ const app = await newDshPage(browser, { ready: PET_STYLES })
try {
await openSettings(app.page, app.frame, app.syntheticFallbacks)
@@ -301,81 +300,100 @@ describe('L2 客户端', () => {
}
})
- it('验证侧栏桌宠入口按钮被插入到设置触发器右侧且状态可读', async () => {
- const app = await newDshPage(browser, { ready: PET_ICON })
+ it('验证设置菜单里克隆出唯一的桌宠条目且状态可读', async () => {
+ const app = await newDshPage(browser, { ready: PET_STYLES })
try {
- const icon = app.frame.locator(PET_ICON).first()
- await icon.waitFor({ state: 'attached', timeout: 20_000 })
-
- expect(await app.frame.locator(PET_ICON).count(), '守卫属性必须防止重复插入').toBe(1)
- expect(await icon.getAttribute('aria-pressed'), 'aria-pressed 必须显式表达两态').toMatch(/^(true|false)$/)
-
- const geometry = await app.frame.evaluate(() => {
- const button = document.querySelector('[data-dsh-tauri-pet-icon]')
- const trigger = document.querySelector('.dshp-settings-trigger')
- const sidebar = document.querySelector('[data-slot="sidebar"]')
- if (!button || !trigger || !sidebar)
- return null
- const buttonRect = button.getBoundingClientRect()
- const triggerRect = trigger.getBoundingClientRect()
- const host = button.parentElement as HTMLElement
- return {
- isNextSibling: button.previousElementSibling === trigger,
- toTheRight: buttonRect.left >= triggerRect.right - 2,
- verticalOverlap: Math.min(buttonRect.bottom, triggerRect.bottom) - Math.max(buttonRect.top, triggerRect.top),
- iconCenterInsideTrigger: buttonRect.top + buttonRect.height / 2 >= triggerRect.top
- && buttonRect.top + buttonRect.height / 2 <= triggerRect.bottom,
- hostClass: host.className,
- hostDisplay: getComputedStyle(host).display,
- hostGap: getComputedStyle(host).gap,
- hostFlexWrap: getComputedStyle(host).flexWrap,
- triggerHostIsParent: trigger.parentElement === host,
- insideSidebar: sidebar.contains(button) && sidebar.contains(trigger),
- }
- })
-
- expect(geometry, '侧栏、触发器与桌宠入口必须同时存在').not.toBeNull()
- expect(geometry!.isNextSibling, '桌宠入口必须是设置触发器的紧邻后继兄弟').toBe(true)
- expect(geometry!.triggerHostIsParent, '触发器必须与桌宠入口同处一个宿主行').toBe(true)
- expect(geometry!.toTheRight, '桌宠入口不得落在设置触发器左侧').toBe(true)
- expect(geometry!.verticalOverlap, '桌宠入口必须与触发器同处一行(垂直区间重叠)').toBeGreaterThan(10)
- expect(geometry!.iconCenterInsideTrigger, '桌宠入口必须与触发器垂直居中对齐').toBe(true)
- expect(geometry!.hostClass, '触发器宿主必须被立成桌宠设置行').toContain('dshp-pet__settings-row')
- expect(geometry!.hostDisplay, '触发器宿主必须被立成 flex 行').toBe('flex')
- expect(geometry!.hostGap, 'flex 行必须带插件声明的间距').toBe('8px')
- expect(geometry!.hostFlexWrap, 'flex 行不得换行').toBe('nowrap')
- expect(geometry!.insideSidebar, '两者都必须在侧栏内').toBe(true)
- expect(app.errors, '侧栏补丁不得抛出应用级错误').toEqual([])
- expect(await app.frame.locator(SIDEBAR).count(), '侧栏根必须存在').toBeGreaterThan(0)
+ await openSettingsMenu(app.page, app.frame, app.syntheticFallbacks)
+
+ await expect.poll(
+ async () => await app.frame.locator(PET_MENU_ITEM).count(),
+ { timeout: 20_000, message: '设置菜单展开后必须出现桌宠条目(菜单补丁未生效)' },
+ ).toBe(1)
+
+ const item = app.frame.locator(PET_MENU_ITEM).first()
+ expect(await item.evaluate(element => element.tagName), '克隆体必须沿用菜单项的原生元素').toBe('BUTTON')
+ expect(await item.getAttribute('role'), '克隆体必须仍是规范菜单项').toBe('menuitem')
+ expect(
+ await item.evaluate(element => element.closest('[role="menu"]')?.getAttribute('data-dsh-tauri-pet-menu-patched') ?? null),
+ '桌宠条目所在的菜单必须带补丁标记(幂等守卫)',
+ ).toBe('1')
+ expect(
+ await app.frame.locator(PET_MENU_PATCHED).count(),
+ '本层只有壳层设置菜单一个「设置」菜单,被打补丁的菜单必须恰为一个',
+ ).toBe(1)
+
+ // 文案随状态变化,属不稳定文案:按 testing.md 用正则限定两种合法取值并校验状态语义。
+ // 本层(浏览器态 iframe,无 Tauri 宿主)`invoke` 必然失败,插件 `enabled()` 读到的
+ // `status` 恒为 null,因此合法取值只有「未开启」一侧;出现另一侧说明状态来源被伪造。
+ const label = await readMenuLabel(item)
+ expect(label, '桌宠条目文案必须是「未开启」一侧(状态不可读时 enabled() === false)').toMatch(/^(启用宠物|Enable pet)$/)
+ expect(
+ await item.locator('[class*="itemIcon"] svg').count(),
+ '克隆体必须换成插件自己的爪子图标,而不是继承「设置」的齿轮',
+ ).toBe(1)
+
+ await item.click()
+
+ // 克隆体不在 React fiber 里,官方 onSelect 不会触发;插件自己补发 pointerdown 收起菜单,
+ // 这是「点击真的进了插件处理器」的正向证据。
+ await expect.poll(
+ async () => await app.frame.locator(SETTINGS_TRIGGER).first().getAttribute('aria-expanded'),
+ { timeout: 15_000, message: '点击桌宠条目后设置菜单必须收起(点击未进插件处理器)' },
+ ).toBe('false')
+
+ await openSettingsMenu(app.page, app.frame, app.syntheticFallbacks)
+ await expect.poll(
+ async () => await app.frame.locator(PET_MENU_ITEM).count(),
+ { timeout: 15_000, message: '重开菜单后桌宠条目必须重新出现且仍为 1 个' },
+ ).toBe(1)
+ expect(
+ await readMenuLabel(app.frame.locator(PET_MENU_ITEM).first()),
+ '宿主未应答时不得乐观翻转本地状态:重开后文案仍必须是「未开启」一侧',
+ ).toMatch(/^(启用宠物|Enable pet)$/)
+
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '菜单补丁不得抛出应用级错误').toEqual([])
}
finally {
await app.close()
}
})
- it('验证侧栏长时间未就绪时停止轮询且不抛错', async () => {
- const app = await newDshPage(browser, { ready: SETTINGS_TRIGGER })
+ it('验证设置菜单重开与重复扫描后桌宠条目恒为一个', async () => {
+ const app = await newDshPage(browser, { ready: PET_STYLES })
+ const itemCount = async () => await app.frame.locator(PET_MENU_ITEM).count()
try {
- expect(
- RETRY_WINDOW_MS,
- `观察窗口 ${RETRY_SETTLE_MS}ms 必须覆盖插件真实轮询预算 ${RETRY_WINDOW_MS}ms(PET_ICON_RETRY_MS×PET_ICON_RETRY_MAX,常量变大时本用例必须失败)`,
- ).toBeLessThan(RETRY_SETTLE_MS)
-
- await new Promise(resolve => setTimeout(resolve, RETRY_SETTLE_MS))
-
- const state = await app.frame.evaluate(() => {
- const button = document.querySelector('[data-dsh-tauri-pet-icon]')
- return {
- iconCount: document.querySelectorAll('[data-dsh-tauri-pet-icon]').length,
- stillConnected: button?.isConnected ?? false,
- previousIsTrigger: button?.previousElementSibling === document.querySelector('.dshp-settings-trigger'),
- }
- })
-
- expect(state.iconCount, '补丁恰好插入一个入口,观察器重入不得叠加或移除').toBe(1)
- expect(state.stillConnected, '兜底轮询窗口结束后入口必须留在 DOM 上').toBe(true)
- expect(state.previousIsTrigger, '看护循环结束后位置必须仍然正确').toBe(true)
- expect(app.errors, '轮询耗尽预算后必须静默停止,不得抛出应用级错误').toEqual([])
+ await openSettingsMenu(app.page, app.frame, app.syntheticFallbacks)
+ await expect.poll(itemCount, { timeout: 20_000, message: '设置菜单展开后必须出现桌宠条目' }).toBe(1)
+
+ // 每一轮都真实收起再重开:菜单节点被重建、MutationObserver 也再跑一次扫描,
+ // 两处都不得叠加计数(幂等守卫靠菜单上的补丁标记)。
+ for (let round = 1; round <= 3; round += 1) {
+ await app.frame.locator(PET_MENU_ITEM).first().click()
+ await expect.poll(
+ async () => await app.frame.locator(SETTINGS_TRIGGER).first().getAttribute('aria-expanded'),
+ { timeout: 15_000, message: `第 ${round} 轮点击后菜单必须收起,否则重开路径未被验证` },
+ ).toBe('false')
+
+ await openSettingsMenu(app.page, app.frame, app.syntheticFallbacks)
+ await expect.poll(itemCount, { timeout: 15_000, message: `第 ${round} 次重开菜单后桌宠条目必须仍为 1 个` }).toBe(1)
+
+ // 真实制造 childList 变更(观察器配置为 childList + subtree),逼出一次重新扫描。
+ await app.frame.evaluate(() => {
+ const probe = document.createElement('div')
+ document.body.appendChild(probe)
+ probe.remove()
+ })
+
+ await expect.poll(itemCount, { timeout: 15_000, message: `第 ${round} 次重新扫描后桌宠条目不得被重复插入` }).toBe(1)
+ expect(
+ await app.frame.locator(PET_MENU_PATCHED).count(),
+ `第 ${round} 次重新扫描后被打补丁的菜单仍必须恰为一个`,
+ ).toBe(1)
+ }
+
+ expectNoSyntheticFallbacks(app)
+ expect(app.errors, '重复扫描不得抛出应用级错误').toEqual([])
}
finally {
await app.close()
diff --git a/test/e2e/plugins/dsh-tauri-ui.e2e.ts b/test/e2e/plugins/dsh-tauri-ui.e2e.ts
index 9c2dfe4e..7f13de4d 100644
--- a/test/e2e/plugins/dsh-tauri-ui.e2e.ts
+++ b/test/e2e/plugins/dsh-tauri-ui.e2e.ts
@@ -20,7 +20,7 @@ import {
launchDshBrowser,
newDshPage,
openSettings,
- PET_ICON,
+ PET_STYLES,
SETTINGS_SIDEBAR,
SETTINGS_TRIGGER,
} from '../support/browser'
@@ -126,7 +126,7 @@ describe('L2 客户端', () => {
})
it('验证设置侧栏与触发器被注入 dsh 界面', async () => {
- const app = await newDshPage(browser, { ready: PET_ICON })
+ const app = await newDshPage(browser, { ready: PET_STYLES })
try {
const triggerHost = await app.frame.evaluate(() => {
const trigger = document.querySelector('.dshp-settings-trigger')
diff --git a/test/e2e/support/browser.ts b/test/e2e/support/browser.ts
index 6cb486f2..2b4bba19 100644
--- a/test/e2e/support/browser.ts
+++ b/test/e2e/support/browser.ts
@@ -32,7 +32,6 @@ export const IGNORED_APP_ERRORS: readonly string[] = [
]
/** 插件自身注入的元素用 `data-dsh-*`(`plugin.client.md` §4)。 */
-export const PET_ICON = '[data-dsh-tauri-pet-icon]'
export const SCHEDULER_ICON = '[data-dsh-scheduler-icon]'
export const WORKTREE_ICON = '[data-dsh-worktree-icon]'
export const WORKTREE_MODE_ANCHOR = '[data-dsh-tauri-worktree-mode-anchor]'
@@ -41,6 +40,19 @@ export const SESSION_ARCHIVE_ITEM = '[data-dsh-tauri-session-archive-item]'
export const SESSION_ARCHIVE_MENU_PATCHED = '[data-dsh-tauri-session-archive-menu-patched="1"]'
export const RUNNING_CHANGES = '[data-running-changes]'
+/**
+ * `dsh-tauri-pet` 的就绪锚点:插件的样式元素。
+ *
+ * `stylesFeature` 把 `PET_STYLES_ID`(`packages/dsh-tauri-pet/src/client/constants/index.ts`)
+ * 交给 `dsh-tauri-ui` 的 `mountStyle`,由 css-render 落成 `<style cssr-id="...">`——`cssr-id`
+ * 是属性而非 id,`#dsh-tauri-pet-styles` 不存在。插件客户端一跑起来就挂上它。
+ */
+export const PET_STYLES = 'style[cssr-id="dsh-tauri-pet-styles"]'
+
+/** 设置菜单里的桌宠条目与「该菜单已被补丁」标记(同上常量文件)。 */
+export const PET_MENU_ITEM = '[data-dsh-tauri-pet-menu-item="1"]'
+export const PET_MENU_PATCHED = '[data-dsh-tauri-pet-menu-patched="1"]'
+
/** dsh 内部结构(上游产物):可用稳定结构性锚点。 */
export const SIDEBAR = '[data-slot="sidebar"]'
export const SIDEBAR_PANELLIST = '[data-slot="sidebar.panellist"]'
@@ -221,7 +233,7 @@ interface FrameSnapshot {
loaderKeys: string[]
loaderMode: string
loaderPending: number
- petIcon: boolean
+ petStyles: boolean
settingsTrigger: boolean
settingsSidebar: boolean
}
@@ -274,7 +286,7 @@ async function captureFrameSnapshot(frame: Frame): Promise<FrameSnapshot | strin
loaderKeys: loader === undefined ? [] : Object.keys(loader),
loaderMode: String(loader?.mode ?? 'n/a'),
loaderPending: Array.isArray(loader?.pendingQueue) ? loader.pendingQueue.length : -1,
- petIcon: doc.querySelector('[data-dsh-tauri-pet-icon]') !== null,
+ petStyles: doc.querySelector('style[cssr-id="dsh-tauri-pet-styles"]') !== null,
settingsTrigger: doc.querySelector('.dshp-settings-trigger') !== null,
settingsSidebar: doc.querySelector('[data-slot-sidebar="dsh-tauri-ui"]') !== null,
}
@@ -318,7 +330,7 @@ export async function describePageState(page: Page, frame: Frame): Promise<strin
lines.push(`[data-slot] count=${snapshot.slotCount} values=${snapshot.slots.join(',') || '(none)'}`)
lines.push(`__DSH_BOOT__.modules=${snapshot.bootModules} ids=${snapshot.bootIds.join(',') || '(none)'}`)
lines.push(`__ModuleLoader__ keys=${snapshot.loaderKeys.join(',') || '(none)'} mode=${snapshot.loaderMode} pendingQueue=${snapshot.loaderPending}`)
- lines.push(`pluginAnchors petIcon=${snapshot.petIcon} settingsTrigger=${snapshot.settingsTrigger} settingsSidebar=${snapshot.settingsSidebar}`)
+ lines.push(`pluginAnchors petStyles=${snapshot.petStyles} settingsTrigger=${snapshot.settingsTrigger} settingsSidebar=${snapshot.settingsSidebar}`)
pushList('pluginComboScripts', snapshot.pluginScripts, '(none: 启动 HTML 里没有任何 /plugins/ 脚本)')
pushList('injectedDataDshAttrs', snapshot.dshAttrs, '(none: 没有任何插件注入的元素)')
}
@@ -347,10 +359,10 @@ async function failWithDiagnostics(page: Page, frame: Frame, reason: string, cau
* 在当前 browser 上新建一个内嵌 dsh 页面并等待界面可用。
*
* 默认就绪锚点取核心 dsh 的结构性槽位 `SIDEBAR`(`[data-slot="sidebar"]`),不取任何插件
- * 注入的元素:`SETTINGS_TRIGGER` 由 `dsh-tauri-ui` 渲染、`PET_ICON` 由 `dsh-tauri-pet`
- * 插入,在 Ubuntu CI 上都可能迟迟不出现,而它们缺席并不表示 dsh 未就绪——`SIDEBAR` 是
+ * 注入的元素:`SETTINGS_TRIGGER` 由 `dsh-tauri-ui` 渲染、`PET_STYLES` 由 `dsh-tauri-pet`
+ * 挂载,在 Ubuntu CI 上都可能迟迟不出现,而它们缺席并不表示 dsh 未就绪——`SIDEBAR` 是
* 上游产物,也是各插件自己判定「侧栏就绪」时读取的同一个锚点。需要断言插件产物的用例
- * 必须显式传 `{ ready: PET_ICON }` / `{ ready: SETTINGS_TRIGGER }` 等,不依赖默认值。
+ * 必须显式传 `{ ready: PET_STYLES }` / `{ ready: SETTINGS_TRIGGER }` 等,不依赖默认值。
*/
export async function newDshPage(
browser: Browser,
@@ -573,8 +585,13 @@ export async function waitForCredentialModal(
throw new Error('等待带凭据输入的 API Key 引导弹层超时')
}
-/** 打开设置侧栏,返回触发器的 locator。 */
-export async function openSettings(
+/**
+ * 点开设置入口并把菜单**停在展开态**,返回触发器的 locator。
+ *
+ * 桌宠开关是设置菜单里克隆出来的条目,只有菜单展开时才存在,因此断言它的用例必须在
+ * 这一步停下;`openSettings` 会继续点「设置」条目把菜单收掉。
+ */
+export async function openSettingsMenu(
page: Page,
frame: Frame,
fallbacks?: SyntheticFallback[],
@@ -594,7 +611,7 @@ export async function openSettings(
trigger,
'aria-expanded',
'true',
- 'openSettings',
+ 'openSettingsMenu',
`${SETTINGS_TRIGGER} aria-expanded 未被指针点击改写`,
fallbacks,
)
@@ -602,9 +619,20 @@ export async function openSettings(
await expect.poll(
() => trigger.getAttribute('aria-expanded'),
- { timeout: 15_000, message: '点击设置触发器后 aria-expanded 必须变为 true' },
+ { timeout: 15_000, message: '点击设置入口后 aria-expanded 必须变为 true(设置菜单未展开)' },
).toBe('true')
+ return trigger
+}
+
+/** 打开设置侧栏,返回触发器的 locator。 */
+export async function openSettings(
+ page: Page,
+ frame: Frame,
+ fallbacks?: SyntheticFallback[],
+): Promise<Locator> {
+ const trigger = await openSettingsMenu(page, frame, fallbacks)
+
// 浏览器态(无桌面账号菜单)下触发器点开的是壳层自有设置菜单,还要再选中「设置」条目;
// 桌面载体下官方账号菜单占据该座位,点开即是设置面板,不会有菜单条目。
if (await frame.locator(SETTINGS_SECTION_SLOT).count() === 0) {
diff --git a/test/e2e/support/dsh.ts b/test/e2e/support/dsh.ts
index 1e6b644a..af46c04a 100644
--- a/test/e2e/support/dsh.ts
+++ b/test/e2e/support/dsh.ts
@@ -312,7 +312,7 @@ const FIXTURE_SKILL_NAME = 'e2e-fixture-skill'
* npm 安装,漏了补丁就会让 `dsh-tauri-ui` 按设计降级:只打一条 console.warn
* `<SlotOutlet> unavailable (renderer patch missing)`(**不是 error**,所以诊断里的
* appErrors 为空),随后所有 `dsh-tauri-*` 的座位注入静默 no-op,症状只剩
- * `.dshp-settings-trigger` / `[data-dsh-tauri-pet-icon]` 就绪锚点超时。
+ * `.dshp-settings-trigger` / `style[cssr-id="dsh-tauri-pet-styles"]` 就绪锚点超时。
*
* Windows 本地曾因此「假绿」:那里解析到的是桌面端已就地打过补丁的共享装配核心。
*/