Skip to content

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

fix(bridge): 避免无关 DOM 更新触发全页样式读取 (#1057)

Mao Mrbceb7b60c4ab
diff --git a/packages/dsh-tauri/src/client/apply.test.ts b/packages/dsh-tauri/src/client/apply.test.ts
index 245e180f..9046e6a1 100644
--- a/packages/dsh-tauri/src/client/apply.test.ts
+++ b/packages/dsh-tauri/src/client/apply.test.ts
@@ -48,13 +48,13 @@ interface Harness {
/** 装上 DOM 假实现(node 环境无 jsdom)。 */
function stubEnv(): Harness {
- const windowListeners = new Set<(event: MessageEvent) => void>()
- const documentListeners = new Set<(event: KeyboardEvent) => void>()
+ const windowListeners = new Map<(event: MessageEvent) => void, string>()
+ const documentListeners = new Map<(event: KeyboardEvent) => void, string>()
const sent: ParentMessage[] = []
const parent = { postMessage: (message: ParentMessage) => sent.push(message) }
vi.stubGlobal('window', {
parent,
- addEventListener: (_type: string, handler: (event: MessageEvent) => void) => windowListeners.add(handler),
+ addEventListener: (type: string, handler: (event: MessageEvent) => void) => windowListeners.set(handler, type),
removeEventListener: (_type: string, handler: (event: MessageEvent) => void) => windowListeners.delete(handler),
})
const styles: HTMLStyleElement[] = []
@@ -71,7 +71,7 @@ function stubEnv(): Harness {
createElement: () => ({ setAttribute: () => {}, textContent: '', parentElement: head }),
querySelector: () => null,
querySelectorAll: () => [],
- addEventListener: (_type: string, handler: (event: KeyboardEvent) => void) => documentListeners.add(handler),
+ addEventListener: (type: string, handler: (event: KeyboardEvent) => void) => documentListeners.set(handler, type),
removeEventListener: (_type: string, handler: (event: KeyboardEvent) => void) => documentListeners.delete(handler),
})
vi.stubGlobal('MutationObserver', FakeMutationObserver)
@@ -93,12 +93,16 @@ function stubEnv(): Harness {
},
pendingFrames: () => frames.size,
dispatch(data) {
- for (const handler of windowListeners)
- handler({ source: window.parent, data } as MessageEvent)
+ for (const [handler, type] of windowListeners) {
+ if (type === 'message')
+ handler({ source: window.parent, data } as MessageEvent)
+ }
},
keydown(event) {
- for (const handler of documentListeners)
- handler(event)
+ for (const [handler, type] of documentListeners) {
+ if (type === 'keydown')
+ handler(event)
+ }
},
windowListeners: () => windowListeners.size,
documentListeners: () => documentListeners.size,
@@ -201,9 +205,8 @@ describe('apply', () => {
expect(env.labels).toEqual(EXPECTED_LABELS)
expect(env.styles).toHaveLength(1)
expect(env.sent.filter(message => message.type === 'dsh://plugin-error')).toEqual([])
- // 侧边栏桥 + 导航命令各挂一个父窗口消息监听;缩放快捷键挂一个 document 捕获监听。
- expect(env.windowListeners()).toBe(2)
- expect(env.documentListeners()).toBe(1)
+ expect(env.windowListeners()).toBe(3)
+ expect(env.documentListeners()).toBe(2)
for (const dispose of disposers.splice(0))
dispose()
diff --git a/packages/dsh-tauri/src/client/register/style.test.ts b/packages/dsh-tauri/src/client/register/style.test.ts
index 439f0f42..0509e4ad 100644
--- a/packages/dsh-tauri/src/client/register/style.test.ts
+++ b/packages/dsh-tauri/src/client/register/style.test.ts
@@ -7,6 +7,8 @@ const disposers: Array<() => void> = []
afterEach(() => {
disposers.splice(0).forEach(dispose => dispose())
document.body.replaceChildren()
+ document.body.removeAttribute('class')
+ document.head.querySelectorAll('style, link').forEach(element => element.remove())
document.documentElement.removeAttribute('style')
vi.restoreAllMocks()
vi.unstubAllGlobals()
@@ -42,20 +44,24 @@ describe('desktop style reporting', () => {
expect(post.mock.calls[0][0]).toMatchObject({ type: 'dsh://style', sidebar: { background: 'rgb(20, 30, 40)' }, marked: null, frame: null })
})
- it('coalesces streamed chat mutations before reading styles and suppresses unchanged messages', async () => {
+ it('ignores streamed chat mutations before querying or reading styles', async () => {
const { frames, paint, post, reads } = setup()
paint()
post.mockClear()
reads.mockClear()
+ const chat = document.querySelector('main')!
+ const queries = vi.spyOn(document, 'querySelectorAll')
+ const query = vi.spyOn(document, 'querySelector')
for (let i = 0; i < 20; i++) {
- document.querySelector('main')!.textContent = `Stream chunk ${i}`
+ chat.innerHTML = `<div class="chunk-${i}">Stream chunk ${i}</div>`
+ chat.firstElementChild!.setAttribute('style', 'color:red')
await Promise.resolve()
}
- expect(reads).not.toHaveBeenCalled()
- expect(post).not.toHaveBeenCalled()
- expect(frames.size).toBe(1)
+ expect(frames.size).toBe(0)
paint()
- expect(reads).toHaveBeenCalledOnce()
+ expect(reads).not.toHaveBeenCalled()
+ expect(queries).not.toHaveBeenCalled()
+ expect(query).not.toHaveBeenCalled()
expect(post).not.toHaveBeenCalled()
})
@@ -70,6 +76,159 @@ describe('desktop style reporting', () => {
expect(post.mock.calls[0][0].sidebar).toEqual({ background: 'rgb(50, 60, 70)' })
})
+ it('coalesces relevant mutations and suppresses unchanged messages', async () => {
+ const { paint, frames, reads, post } = setup()
+ paint()
+ reads.mockClear()
+ post.mockClear()
+ for (let i = 0; i < 20; i++) {
+ document.body.className = `theme-${i}`
+ await Promise.resolve()
+ }
+ expect(frames.size).toBe(1)
+ expect(reads).not.toHaveBeenCalled()
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ expect(post).not.toHaveBeenCalled()
+ })
+
+ it.each(['insert', 'remove', 'replace', 'ancestor', 'class', 'slot'] as const)('refreshes sidebar inputs after %s mutations', async (change) => {
+ const { paint, post } = setup()
+ const sidebar = document.querySelector<HTMLElement>('[data-slot="sidebar"]')!
+ const wrapper = document.createElement('section')
+ sidebar.replaceWith(wrapper)
+ wrapper.append(sidebar)
+ await Promise.resolve()
+ paint()
+ post.mockClear()
+ if (change === 'insert') {
+ sidebar.remove()
+ await Promise.resolve()
+ paint()
+ post.mockClear()
+ wrapper.append(sidebar)
+ }
+ else if (change === 'remove') {
+ wrapper.remove()
+ }
+ else if (change === 'replace') {
+ sidebar.innerHTML = '<div style="background:rgb(50, 60, 70)"></div>'
+ }
+ else if (change === 'ancestor') {
+ wrapper.style.background = 'rgb(50, 60, 70)'
+ }
+ else if (change === 'class') {
+ wrapper.className = 'dark'
+ }
+ else {
+ sidebar.removeAttribute('data-slot')
+ }
+ const reads = vi.spyOn(window, 'getComputedStyle').mockClear()
+ await Promise.resolve()
+ paint()
+ if (change === 'remove' || change === 'slot')
+ expect(post.mock.calls[0][0].sidebar).toBeNull()
+ else
+ expect(reads).toHaveBeenCalled()
+ if (change === 'insert')
+ expect(post.mock.calls[0][0].sidebar).toEqual({ background: 'rgb(20, 30, 40)' })
+ if (change === 'replace')
+ expect(post.mock.calls[0][0].sidebar).toEqual({ background: 'rgb(50, 60, 70)' })
+ })
+
+ it('detects frame class entry and exit without relying on current selector matches', async () => {
+ const { paint, post } = setup()
+ paint()
+ const frame = document.createElement('div')
+ frame.style.background = 'rgb(50, 60, 70)'
+ document.querySelector('main')!.append(frame)
+ await Promise.resolve()
+ paint()
+ post.mockClear()
+ frame.className = 'layout_frame'
+ await Promise.resolve()
+ paint()
+ expect(post.mock.calls[0][0].frame).toEqual({ background: 'rgb(50, 60, 70)' })
+ post.mockClear()
+ frame.className = ''
+ await Promise.resolve()
+ paint()
+ expect(post.mock.calls[0][0].frame).toBeNull()
+ })
+
+ it('reports nested overlay insertion, parent changes and removal', async () => {
+ const computedStyle = window.getComputedStyle.bind(window)
+ const { paint, post, reads } = setup()
+ reads.mockImplementation(element => computedStyle(element))
+ paint()
+ post.mockClear()
+ const portal = document.createElement('div')
+ portal.style.position = 'fixed'
+ portal.innerHTML = '<div class="_mask_modal" style="background:rgba(0, 0, 0, 0.5)"></div>'
+ document.body.append(portal)
+ await Promise.resolve()
+ paint()
+ expect(post.mock.calls[0][0].marked.background).toContain('rgba(0, 0, 0, 0.5)')
+ reads.mockClear()
+ portal.style.position = 'absolute'
+ await Promise.resolve()
+ paint()
+ expect(reads).toHaveBeenCalled()
+ post.mockClear()
+ portal.remove()
+ await Promise.resolve()
+ paint()
+ expect(post.mock.calls[0][0].marked).toBeNull()
+ })
+
+ it('refreshes styles for stylesheet changes and window resizing', async () => {
+ const { paint, frames, reads } = setup()
+ paint()
+ reads.mockClear()
+ const stylesheet = document.createElement('style')
+ stylesheet.textContent = 'body { color:red }'
+ document.head.append(stylesheet)
+ await Promise.resolve()
+ expect(frames.size).toBe(1)
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ reads.mockClear()
+ stylesheet.firstChild!.nodeValue = 'body { color:blue }'
+ await Promise.resolve()
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ reads.mockClear()
+ window.dispatchEvent(new Event('resize'))
+ expect(frames.size).toBe(1)
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ stylesheet.remove()
+ })
+
+ it('refreshes tokenized stylesheet links on href changes and load completion', async () => {
+ const { paint, frames, reads, dispose } = setup()
+ paint()
+ const link = document.createElement('link')
+ link.rel = 'next StyleSheet'
+ document.head.append(link)
+ await Promise.resolve()
+ paint()
+ reads.mockClear()
+ link.href = '/theme.css'
+ await Promise.resolve()
+ expect(frames.size).toBe(1)
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ reads.mockClear()
+ link.dispatchEvent(new Event('load'))
+ expect(frames.size).toBe(1)
+ paint()
+ expect(reads).toHaveBeenCalledOnce()
+ dispose()
+ link.dispatchEvent(new Event('load'))
+ expect(frames.size).toBe(0)
+ })
+
it('reports a root color-scheme change even when the chat body stays unchanged', async () => {
const { paint, post } = setup()
paint()
@@ -89,6 +248,7 @@ describe('desktop style reporting', () => {
expect(frames.size).toBe(0)
paint()
document.querySelector('main')!.textContent = 'Update after unload'
+ window.dispatchEvent(new Event('resize'))
await Promise.resolve()
paint()
expect(reads).not.toHaveBeenCalled()
diff --git a/packages/dsh-tauri/src/client/register/style.ts b/packages/dsh-tauri/src/client/register/style.ts
index 1940dc20..07e96466 100644
--- a/packages/dsh-tauri/src/client/register/style.ts
+++ b/packages/dsh-tauri/src/client/register/style.ts
@@ -1,14 +1,16 @@
import type { ClientContext } from '../types'
import { defineRegister } from '.'
import { invokeParent } from '../service/invoke-parent'
-import { getFrameStyle, getOverlayMarkedStyle, getSidebarStyle } from './style.utils'
+import { getFrameStyle, getOverlayMarkedStyle, getSidebarStyle, STYLE_INPUT_SELECTOR } from './style.utils'
export const registerStyle = defineRegister<ClientContext>((controller) => {
let pendingFrame: number | undefined
let previous: string | undefined
+ let inputs: Element[] = []
function reportSidebarBackground() {
pendingFrame = undefined
+ inputs = [...document.querySelectorAll(STYLE_INPUT_SELECTOR)]
const message = {
type: 'dsh://style',
sidebar: getSidebarStyle(),
@@ -28,16 +30,46 @@ export const registerStyle = defineRegister<ClientContext>((controller) => {
pendingFrame = requestAnimationFrame(reportSidebarBackground)
}
- // keep:effect 合并流式 DOM 更新的样式读取,并由 controller 回收尚未执行的帧。
+ function affectsStyle(record: MutationRecord) {
+ const target = record.target
+ if (record.type === 'characterData')
+ return target.parentElement?.matches('style') === true
+ if (inputs.some(input => target.contains(input)))
+ return true
+ if (target instanceof Element && target.matches(STYLE_INPUT_SELECTOR))
+ return true
+ if (record.type === 'attributes') {
+ if (target === document.documentElement || target === document.body)
+ return true
+ if (record.attributeName === 'class')
+ return /(?:^|\s)_mask_|_frame$/.test(record.oldValue ?? '')
+ return record.attributeName === 'data-slot' && record.oldValue === 'sidebar'
+ }
+ return [...record.addedNodes, ...record.removedNodes].some(node =>
+ node instanceof Element && (node.matches(STYLE_INPUT_SELECTOR) || node.querySelector(STYLE_INPUT_SELECTOR) !== null),
+ )
+ }
+
+ // keep:effect 合并相关 DOM 更新的样式读取,并由 controller 回收尚未执行的帧。
controller.add(() => {
if (pendingFrame !== undefined)
cancelAnimationFrame(pendingFrame)
})
- controller.observe(document.documentElement, scheduleReport, {
+ controller.observe(document.documentElement, (records) => {
+ if (pendingFrame === undefined && records.some(affectsStyle))
+ scheduleReport()
+ }, {
childList: true,
subtree: true,
+ characterData: true,
attributes: true,
- attributeFilter: ['style', 'class', 'data-theme'],
+ attributeOldValue: true,
+ attributeFilter: ['style', 'class', 'data-theme', 'data-slot', 'href', 'rel', 'media', 'disabled'],
})
+ controller.listen('load', (event) => {
+ if (event.target instanceof HTMLLinkElement && event.target.matches(STYLE_INPUT_SELECTOR))
+ scheduleReport()
+ }, { capture: true })
+ controller.listenWindow('resize', scheduleReport)
scheduleReport()
})
diff --git a/packages/dsh-tauri/src/client/register/style.utils.ts b/packages/dsh-tauri/src/client/register/style.utils.ts
index 2e2468b3..84ce7e82 100644
--- a/packages/dsh-tauri/src/client/register/style.utils.ts
+++ b/packages/dsh-tauri/src/client/register/style.utils.ts
@@ -4,6 +4,8 @@ const FRAME_SELECTOR = 'div[class$="_frame"]'
const COMPONENT_REGION_SELECTOR = '[data-slot]'
+export const STYLE_INPUT_SELECTOR = `${OVERLAY_SELECTORS}, ${FRAME_SELECTOR}, [data-slot="sidebar"], [data-slot="sidebar"] > div, style, link[rel~="stylesheet" i]`
+
/** 全透明底色的判定:`transparent` 与 `rgba(…, 0)`(含现代浏览器的空格/斜杠分隔)。 */
function isTransparent(color: string): boolean {
const value = color.trim().toLowerCase()