diff --git a/src/client/session-phase.ts b/src/client/session-phase.ts index 510ff18d..c4a8faf7 100644 --- a/src/client/session-phase.ts +++ b/src/client/session-phase.ts @@ -7,8 +7,14 @@ * 判定来自插件 host 半区的只读路由(与会话对象同源),**不做任何 DOM 探测**。 * 轮询策略:仅在 blank 期间每 1s 重取一次;翻转为非 blank(发出第一条消息)即停止; * 路由/宿主不支持时按非 blank 降级(入口留在会话头,行为与今天一致)。 + * + * 两条稳态约束(v0.25 的稳态开销治理): + * - **页面不可见时不发请求**(隐藏的标签页没有要服务的相位),回到可见时由 + * `visibilitychange` 立刻补一次; + * - **值没变就不写 state**:相位对象每次都是新的 JSON,无条件 `setPhase(next)` 会让 + * 一个开着不管的 blank 会话每秒重渲染一次。只有 `blank` 真的翻转才提交。 */ -import { useEffect, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { sessionPhase, type SessionPhase } from './api.ts' /** 轮询间隔:blank 是一次性状态(发一条消息即翻转),无需更快。 */ @@ -21,8 +27,12 @@ const POLL_MS = 1_000 */ export function useSessionPhase(sessionId: string | undefined): SessionPhase | undefined { const [phase, setPhase] = useState(undefined) + // 最近一次提交过的相位:轮询读回来的都是**新解析的 JSON 对象**,靠 state 自己没法 + // 「同值不写」(`setPhase(updater)` 返回同一个对象时 React 仍可能重跑一次组件体)。 + const pushedRef = useRef(undefined) useEffect(() => { if (sessionId === undefined) { + pushedRef.current = undefined setPhase(undefined) return } @@ -33,23 +43,38 @@ export function useSessionPhase(sessionId: string | undefined): SessionPhase | u clearInterval(timer) timer = undefined } + /** 只有 `blank` 真的翻转才提交(见 pushedRef 的注释)。 */ + const push = (next: SessionPhase): void => { + const previous = pushedRef.current + if (previous !== undefined && previous.blank === next.blank) return + pushedRef.current = next + setPhase(next) + } const tick = (): void => { + // 页面不可见时不发请求(相位是 blank 期间的一次性探测,隐藏的页面没有服务对象)。 + if (document.hidden) return sessionPhase(sessionId).then((next) => { if (!alive) return - setPhase(next) + push(next) if (!next.blank) stop() }).catch(() => { // 路由/宿主不支持:按非 blank 降级(不渲染备用入口,入口留在会话头)。 if (!alive) return - setPhase({ blank: false }) + push({ blank: false }) stop() }) } + // 回到可见立刻补一次;已经停表(相位已定:非 blank / 已降级)就不再唤醒。 + const onVisibilityChange = (): void => { + if (!document.hidden && timer !== undefined) tick() + } void tick() timer = setInterval(tick, POLL_MS) + document.addEventListener('visibilitychange', onVisibilityChange) return () => { alive = false stop() + document.removeEventListener('visibilitychange', onVisibilityChange) } }, [sessionId]) return phase diff --git a/src/client/settings-nav-icon.ts b/src/client/settings-nav-icon.ts index e2b574e4..eb3a4e17 100644 --- a/src/client/settings-nav-icon.ts +++ b/src/client/settings-nav-icon.ts @@ -8,6 +8,10 @@ * an icon field, the plugin identifies only its own localized row after the * dialog mounts. The marker owns no shell structure and is removed on fiber * disposal, so the adaptation remains HMR-safe. + * + * Mutation bursts are coalesced into one sync per animation frame: the + * observer watches the whole body, so chat streaming would otherwise run the + * document-wide row query at microtask cadence. */ export const SETTINGS_NAV_MARKER = 'data-dsh-better-sidebar-settings-nav' @@ -20,6 +24,7 @@ export const SETTINGS_NAV_MARKER = 'data-dsh-better-sidebar-settings-nav' */ export function registerSettingsNavIcon(label: () => string): () => void { let disposed = false + let frame: number | null = null const sync = (): void => { if (disposed) return @@ -32,13 +37,31 @@ export function registerSettingsNavIcon(label: () => string): () => void { } } + /** One sync per frame at most: the first mutation of a burst schedules it. */ + const schedule = (): void => { + if (disposed || frame !== null) return + frame = requestAnimationFrame(() => { + frame = null + sync() + }) + } + sync() - const observer = new MutationObserver(sync) - observer.observe(document.body, { childList: true, subtree: true, characterData: true }) + // No `characterData`: the marker is a function of the mounted buttons and + // their text, and every dialog mount/unmount or row insert/remove already + // changes childList. Watching character data made this observer fire for + // every streamed token in the main conversation — a document-wide + // `querySelectorAll('[role="dialog"] nav button')` per token burst. + const observer = new MutationObserver(schedule) + observer.observe(document.body, { childList: true, subtree: true }) return () => { disposed = true observer.disconnect() + if (frame !== null) { + cancelAnimationFrame(frame) + frame = null + } document.querySelectorAll(`[${SETTINGS_NAV_MARKER}]`) .forEach(element => { element.removeAttribute(SETTINGS_NAV_MARKER) }) } diff --git a/src/client/sidebar/dock-fallback.tsx b/src/client/sidebar/dock-fallback.tsx index 8e2ca631..1009b994 100644 --- a/src/client/sidebar/dock-fallback.tsx +++ b/src/client/sidebar/dock-fallback.tsx @@ -5,6 +5,10 @@ * 这里把同一个开关以 `position: fixed` 放到宿主「Open right sidebar」按钮的**左侧紧邻** * (按该按钮的 rect 对齐,随窗口 resize 与 500ms 周期重对齐)。 * + * **重对齐的周期表只在入口真的渲染时存在**(v0.25 的稳态开销治理):正常会话里本组件 + * 返回 `null`,而 `measure()` 的让位走查要做命中测试——表挂在早退之前时,一个看不见的 + * 入口会一直烧着这些测量。窗口 resize 监听则是常驻的(见下面的两个 effect)。 + * * **相位不足以判定互斥**:相位是每 1s 轮询来的,而会话头的入口由宿主在它认为合适的 * 时机渲染,两者之间必然有窗口;相位读取失败时还会按「非 blank」降级,一个从未成功 * 读到的会话可能一直停在 blank。而两套入口在版面上是**同一个位置**——真同时在场就是 @@ -27,6 +31,12 @@ const GAP = 8 /** 让位时的搜索步长(像素):够细以免跨过窄芯片,够粗以免几百次命中测试。 */ const STEP_PX = 4 +/** 周期重对齐间隔:与宿主角落控件出现的时机无关,500ms 足够跟上版面漂移。 */ +const REALIGN_MS = 500 + +/** 让位走查的步数上限:100 步 × 4px = 400px。 */ +const MAX_RETREAT_STEPS = 100 + /** * 整个槽位是否空着——**必须采样多个点**。 * @@ -121,8 +131,11 @@ function slotOccupiedByRect(cx: number, cy: number): boolean { * 3. **占位与否要真的去问页面**——见 {@link slotOccupied}:页签芯片会把那一排填满, * 按角色筛元素是筛不干净的。 * - * 因此这里从锚点左侧起逐像素左移,取**最近的一个真的空着**的槽位;一直退到视口 - * 左缘仍被占时停在最左(宁可贴边,也不叠在宿主控件上)。 + * 因此这里从锚点左侧起逐像素左移,取**最近的一个真的空着**的槽位。走查是**有界**的: + * 最多 {@link MAX_RETREAT_STEPS} 步(400px)——真实的宿主编簇只有几个 28px 按钮,退过 + * 400px 说明整排都被占着,而每一步都要采样 5 个点做命中测试,不封顶的走查(旧值 400 步) + * 会把一次 tick 变成上千次命中测试。到达上限仍未找到空位就接受当前槽位;一直退到 + * 视口左缘(`left <= 4`)仍被占时停在最左(宁可贴边,也不叠在宿主控件上)。 * @returns 视口坐标下的 top/left。 */ function measure(): { top: number; left: number } { @@ -131,7 +144,7 @@ function measure(): { top: number; left: number } { const rect = anchor.getBoundingClientRect() const top = Math.max(4, rect.top + (rect.height - BUTTON_SIZE) / 2) let left = Math.max(4, rect.left - GAP - BUTTON_SIZE) - for (let step = 0; step < 400; step++) { + for (let step = 0; step < MAX_RETREAT_STEPS; step++) { if (slotFree(left, top)) break left -= STEP_PX if (left <= 4) { left = 4; break } @@ -148,20 +161,37 @@ export function DockFallback({ store }: { store: SidebarStore }): ReactNode { const rightOpen = useRightPanelOpen() const [pos, setPos] = useState(measure) const [headerEntry, setHeaderEntry] = useState(headerEntryPresent) - useEffect(() => { - const onResize = (): void => { - // 坐标没变就不换 state 对象:500ms 的周期重测在版面静止时不该引起重渲染。 - const next = measure() - setPos(prev => (prev.top === next.top && prev.left === next.left ? prev : next)) - setHeaderEntry(headerEntryPresent()) - } - window.addEventListener('resize', onResize) - const timer = setInterval(onResize, 500) - return () => { - window.removeEventListener('resize', onResize) - clearInterval(timer) - } + // 渲染条件(顺序即下面早退的顺序):相位已读到 blank、会话头那套入口不在场、右侧面板收起。 + const rendered = phase !== undefined && phase.blank && !headerEntry && !rightOpen + const onResize = useCallback((): void => { + // 页面不可见时什么都不做:看不到的版面不值得测量,state 也不需要写。 + if (document.hidden) return + // 坐标没变就不换 state 对象:周期重测在版面静止时不该引起重渲染。 + const next = measure() + setPos(prev => (prev.top === next.top && prev.left === next.left ? prev : next)) + setHeaderEntry(headerEntryPresent()) }, []) + // 窗口 resize 常驻(不随渲染门控):入口此刻没渲染(非 blank 会话 / 面板展开)时的一次 + // 尺寸变化也必须落到 state 里,等它重新出现时坐标才是对的。 + useEffect(() => { + window.addEventListener('resize', onResize) + return () => { window.removeEventListener('resize', onResize) } + }, [onResize]) + // 500ms 周期重对齐只在入口**真的渲染**时建表:正常会话里本组件返回 null,那条表 + // (连同 measure() 里最多 100 步的命中测试走查)绝不能还在跑。 + useEffect(() => { + if (!rendered) return + // 进入可见的那一刻先补一次:让位/展开态的切换不一定伴随 resize 事件。 + onResize() + const timer = setInterval(onResize, REALIGN_MS) + // 回到前台立刻补测一次(onResize 自身在隐藏期间是空转的)。 + const onVisibilityChange = (): void => { if (!document.hidden) onResize() } + document.addEventListener('visibilitychange', onVisibilityChange) + return () => { + clearInterval(timer) + document.removeEventListener('visibilitychange', onVisibilityChange) + } + }, [rendered, onResize]) // 相位判定在组件内部完成:非 blank(或尚未读到)时整个不渲染 —— // 会话头里的入口此时是唯一一套。 if (phase === undefined || !phase.blank) return null diff --git a/src/client/sidebar/right-panel-open.ts b/src/client/sidebar/right-panel-open.ts index c44a627b..027ed1e7 100644 --- a/src/client/sidebar/right-panel-open.ts +++ b/src/client/sidebar/right-panel-open.ts @@ -11,12 +11,48 @@ * 两个条件都要求,是为了让**失败方向安全**:宿主哪天改了命名,这里读成 `false` * (= 不隐藏),按钮照旧出现、位置由 {@link ./dock-fallback.tsx} 的让位逻辑兜住; * 而不是读成「永远展开」把按钮永久藏掉。 + * + * **全模块只有一份答案、一条表**(v0.25 的稳态开销治理):早先每个消费者各建一条 + * 500ms 的表、各做两趟全文档 `querySelectorAll`(本文件 + `dock-fallback.tsx` 共两条), + * 与挂载了多少个消费者成正比。现在订阅者只是引用计数——0 → 1 才起表并立刻读一次, + * 1 → 0 就停表;消费者再多也只有一条表。 + * + * **页面不可见时表本身不存在**(不是「tick 进来再早退」):隐藏的页面没有要服务的 + * 版面,`visibilitychange` 回到可见时才立刻读一次并重新起表。 */ import { useEffect, useState } from 'react' /** 复核间隔:与备用入口的位置对齐同一节拍(500ms)。 */ const POLL_MS = 500 +/** 共享的展开态答案;所有消费者读同一份。 */ +let open = false + +/** 当前订阅者;0 → 1 起表(并立刻读一次),1 → 0 停表。 */ +const listeners = new Set<(next: boolean) => void>() + +/** 全模块**唯一**的定时器:消费者再多也只有这一条。 */ +let timer: ReturnType | undefined + +/** 真实浏览器里的 document;SSR / 极端环境缺席。 */ +function pageDocument(): Document | undefined { + return typeof document === 'undefined' ? undefined : document +} + +/** 页面是否可见(document 缺席时按可见处理,与旧行为一致)。 */ +function pageVisible(): boolean { + const doc = pageDocument() + return doc === undefined || doc.visibilityState !== 'hidden' +} + +/** 读一次宿主角落控件:这个元素**可见**才算数(见 {@link readRightPanelOpen})。 */ +function isVisible(element: Element): boolean { + const rect = element.getBoundingClientRect() + if (rect.width <= 0 || rect.height <= 0) return false + const style = getComputedStyle(element) + return style.visibility !== 'hidden' && style.display !== 'none' +} + /** * 读取一次宿主右侧面板的展开态。 * @@ -25,29 +61,94 @@ const POLL_MS = 500 * 各 1 个、面板明明已经展开),只有**可见性**才区分得开——展开时可见的是 * Collapse(`data-sidebar-right-toggle`),收起时可见的是 Open(`data-sidebar-right-expand`)。 * 早先按「属性在不在」判定会一直读成「没展开」,按钮于是照旧出现在宿主编簇旁边。 + * + * **先问「收起态」再问「展开态」**:收起时可见的是 Open 控件(`expand`),一旦量到它 + * 就能立刻返回 `false` —— 展开态那批 toggle 一次都不用碰,而它们在 DOM 里始终存在, + * 量它们纯属白做。只有当 expand 全都不可见时才轮到 toggle(`true` = 至少一个可见)。 + * 两趟各是一趟循环,不建临时数组,也不对没参与判定的元素读布局。 * @returns 展开时为 true;`document` 缺席(SSR/极端环境)时为 false。 */ function readRightPanelOpen(): boolean { - if (typeof document === 'undefined') return false - const visible = (element: Element): boolean => { - const rect = element.getBoundingClientRect() - if (rect.width <= 0 || rect.height <= 0) return false - const style = getComputedStyle(element) - return style.visibility !== 'hidden' && style.display !== 'none' + const doc = pageDocument() + if (doc === undefined) return false + for (const element of doc.querySelectorAll('[data-sidebar-right-expand]')) { + if (isVisible(element)) return false } - return [...document.querySelectorAll('[data-sidebar-right-toggle]')].some(visible) - && ![...document.querySelectorAll('[data-sidebar-right-expand]')].some(visible) + for (const element of doc.querySelectorAll('[data-sidebar-right-toggle]')) { + if (isVisible(element)) return true + } + return false +} + +/** 读一次并广播——答案没变时连 `open` 都不动(订阅者的 setState 会自然 bail out)。 */ +function publish(): void { + const next = readRightPanelOpen() + if (next === open) return + open = next + for (const listener of listeners) listener(next) +} + +function stopTimer(): void { + if (timer === undefined) return + clearInterval(timer) + timer = undefined +} + +/** 起表;页面不可见时**不建表**(不是建了再早退)。 */ +function startTimer(): void { + if (timer !== undefined) return + if (!pageVisible()) return + timer = setInterval(publish, POLL_MS) +} + +function onVisibilityChange(): void { + if (!pageVisible()) { + // 隐藏即停表:没有要服务的版面,让这条表彻底消失。 + stopTimer() + return + } + if (listeners.size === 0) return + // 回到可见:先补一次(隐藏期间面板可能已经开合),再把表接回去。 + publish() + startTimer() +} + +function subscribe(listener: (next: boolean) => void): () => void { + const first = listeners.size === 0 + listeners.add(listener) + if (first) { + pageDocument()?.addEventListener('visibilitychange', onVisibilityChange) + // 第一个消费者挂上时立刻读一次;隐藏的页面跳过(`open` 保持上一次的答案, + // 回到可见时 onVisibilityChange 会补上)。 + if (pageVisible()) publish() + startTimer() + } + return () => { + listeners.delete(listener) + if (listeners.size > 0) return + stopTimer() + pageDocument()?.removeEventListener('visibilitychange', onVisibilityChange) + } +} + +/** + * 首帧同步读取(与旧实现同为渲染期读一次):可见时读一次并更新共享缓存,但不广播—— + * 渲染期不能触发别人的更新,其他消费者各自的 state 会在下一次 tick 或订阅时对齐。 + * 页面不可见时直接用缓存,一次版都不量。 + */ +function primeOpen(): boolean { + if (!pageVisible()) return open + open = readRightPanelOpen() + return open } /** * 跟踪宿主右侧面板的展开态。 - * @returns 展开时为 true(首帧同步读取,之后每 500ms 复核一次)。 + * @returns 展开时为 true(首帧同步读取,之后由模块级共享 poller 每 500ms 复核; + * 订阅者归零即停表,页面隐藏期间不起表)。 */ export function useRightPanelOpen(): boolean { - const [open, setOpen] = useState(readRightPanelOpen) - useEffect(() => { - const timer = setInterval(() => { setOpen(readRightPanelOpen()) }, POLL_MS) - return () => { clearInterval(timer) } - }, []) - return open + const [isOpen, setIsOpen] = useState(primeOpen) + useEffect(() => subscribe(setIsOpen), []) + return isOpen } diff --git a/src/client/sidebar/use-center-column.ts b/src/client/sidebar/use-center-column.ts index 62d7c788..298bb317 100644 --- a/src/client/sidebar/use-center-column.ts +++ b/src/client/sidebar/use-center-column.ts @@ -94,8 +94,17 @@ export function useCenterColumn( observer?.disconnect() observer = undefined } + // No usable column: keep the slow safety net armed — this is the + // state (boot before the AppFrame exists, HMR swap) that has no other + // convergence path. + startRetry() return } + // A usable column is cached: the safety net stops. Its window equals the + // old tick period, so a running table would re-validate on EVERY tick and + // the query-free fast path could never apply. The two observers above + // remain the recovery path (a swapped node mutates #root / ). + stopRetry() if (centerColRef.current !== col) { // A NEW column node (boot swap, HMR re-render, or a previous locate // that found nothing): attach the ResizeObserver to THIS node and @@ -115,6 +124,28 @@ export function useCenterColumn( measureCenter() } } + // Last-resort safety net (issue #248): the slow re-locate runs ONLY while + // no usable column is cached. It used to run unconditionally every 1.5s, + // which is exactly CENTER_COLUMN_REVALIDATE_MS — so the cached-node fast + // path could never apply: every tick fell due the moment it fired and paid + // the full document selector + computed-style ancestor walk. Now the + // cached column stops this table, and a detached/missing column starts it + // again: the no-column state is the one that has no other convergence path + // (boot before the AppFrame exists, HMR re-renders, #root swaps). + // + // `window.setInterval` (not the bare global): the client runs in the + // browser, where the id is a number — the bare global resolves to Node's + // Timeout under this tsconfig. + let retry: number | undefined + const stopRetry = (): void => { + if (retry === undefined) return + window.clearInterval(retry) + retry = undefined + } + const startRetry = (): void => { + if (retry !== undefined) return + retry = window.setInterval(locate, 1500) + } locate() // rAF-debounce the mutation watchers: #root's subtree changes at chat // cadence (streaming turns), and locate() itself must stay cheap. @@ -125,7 +156,7 @@ export function useCenterColumn( // attribute, which is the mutation this watcher observes — relocating // per drag frame is pointless (the center column node cannot change // while the pointer is captured) and adds locator work to every - // frame's budget (#315). The 1.5s retry below still covers any node + // frame's budget (#315). The slow safety net still covers any node // swap that somehow lands mid-drag. if (draggingRef.current) return locateFrame = requestAnimationFrame(() => { @@ -146,19 +177,10 @@ export function useCenterColumn( // instead of staying hidden on a stale {0,0} center rect. const htmlStyleWatcher = new MutationObserver(scheduleLocate) htmlStyleWatcher.observe(document.documentElement, { attributes: true, attributeFilter: ['style'] }) - // Last-resort safety net (issue #248): no watcher is guaranteed to fire - // for every HMR teardown/setup interleaving (e.g. the style attribute - // may end up byte-identical, and the col may be swapped before the - // subtree watcher attaches). A slow unconditional re-locate makes the - // panel converge on the real column within a couple of seconds no - // matter what sequence the shell used. locate() is query-free while the - // cached column stays connected; only a detached/missing cache falls - // back to the document selector. - const retry = window.setInterval(locate, 1500) return () => { disposed = true if (locateFrame !== null) cancelAnimationFrame(locateFrame) - window.clearInterval(retry) + stopRetry() observer?.disconnect() watcher.disconnect() htmlStyleWatcher.disconnect() diff --git a/tests/center-column-locator.spec.ts b/tests/center-column-locator.spec.ts index cdf55dbc..4bfce74e 100644 --- a/tests/center-column-locator.spec.ts +++ b/tests/center-column-locator.spec.ts @@ -1,9 +1,15 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' +import { createElement, type ReactElement } from 'react' +import { act } from 'react-dom/test-utils' +import { renderRoot, setupReactAct } from './test-utils.ts' import { CENTER_COLUMN_REVALIDATE_MS, resolveCenterColumn, } from '../src/client/center-column.ts' +import { useCenterColumn } from '../src/client/sidebar/use-center-column.ts' + +setupReactAct() interface Fixture { doc: Document @@ -44,7 +50,6 @@ function alphaColumn(hostSlot: string): { col: HTMLDivElement; host: HTMLDivElem afterEach(() => { for (const root of document.body.querySelectorAll('div#root')) root.remove() }) - describe('center-column anchor keys (DSH 0.1.5-alpha.2)', () => { it('skips display:contents slot hosts above a main.conversation host', () => { const { col } = alphaColumn('main.conversation') @@ -138,3 +143,161 @@ describe('center-column locator (issue #403)', () => { })).toBeUndefined() }) }) + +// --------------------------------------------------------------------------- +// useCenterColumn 的兜底重试阶梯(v0.25 稳态开销治理) +// +// 定位器本身没变(上面的用例钉住它);变的是**谁来驱动它**:1.5s 的表原来无条件常驻, +// 而它的周期与 CENTER_COLUMN_REVALIDATE_MS 等长 → 每次 tick 都恰好到期,缓存命中的 +// 「query-free 快速路径」永远走不到。现在:缓存到可用列即停表,列被摘掉(HMR / #root +// 换节点)才重新起表,MutationObserver 仍是恢复路径。 +// --------------------------------------------------------------------------- + +const resizeObservers: Element[] = [] + +class FakeResizeObserver { + constructor(_callback: ResizeObserverCallback) { /* 只需要构造成功 */ } + observe(target: Element): void { resizeObservers.push(target) } + unobserve(): void { /* noop */ } + disconnect(): void { /* noop */ } +} + +/** 账本式定时器:`window.setInterval` 的 id 是假的,起没起表直接断言。 */ +const timers = new Map void; ms: number | undefined }>() +let timerSeq = 0 + +/** 确定性 rAF:只有 flushFrame() 才推进一帧(观察者回调是微任务,先 await 一拍)。 */ +const frames = new Map() +let frameSeq = 0 + +function flushFrame(): void { + const callbacks = [...frames.values()] + frames.clear() + for (const callback of callbacks) callback(0) +} + +function retryTables(): number { + return [...timers.values()].filter(entry => entry.ms === 1500).length +} + +const bottomElement = document.createElement('div') +/** 稳定的 ref 对象:每次渲染换新对象会让 useCenterColumn 的 effect 每帧重跑。 */ +const bottomRef = { current: bottomElement } + +function CenterColumnProbe(): ReactElement { + useCenterColumn(bottomRef, true) + return createElement('div') +} + +/** 把上面的 alpha.2 fixture(#root > col > wrapper[contents] > host)建好。 */ +function renderTrackedColumn(): { unmount: () => void; col: HTMLDivElement; root: HTMLElement } { + const { col } = alphaColumn('main.conversation') + const root = document.getElementById('root') + if (root === null) throw new Error('missing element: #root fixture') + const view = renderRoot(createElement(CenterColumnProbe)) + return { unmount: view.unmount, col, root } +} + +/** 往**同一个** #root 里再塞一列(换节点,而不是新建一棵树)。 */ +function appendTrackedColumn(root: HTMLElement): HTMLDivElement { + const col = document.createElement('div') + const wrapper = document.createElement('div') + wrapper.style.display = 'contents' + const host = document.createElement('div') + host.dataset.slot = 'main.conversation' + wrapper.append(host) + col.append(wrapper) + root.append(col) + return col +} + +describe('useCenterColumn retry ladder', () => { + function withHarness(body: () => void | Promise): Promise { + const originalResizeObserver = globalThis.ResizeObserver + globalThis.ResizeObserver = FakeResizeObserver as unknown as typeof ResizeObserver + vi.spyOn(globalThis, 'setInterval').mockImplementation(((fn: () => void, ms?: number) => { + const id = ++timerSeq + timers.set(id, { fn, ms }) + return id + }) as never) + vi.spyOn(globalThis, 'clearInterval').mockImplementation(((id: number) => { + timers.delete(id) + }) as never) + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(++frameSeq, callback) + return frameSeq + }) + vi.stubGlobal('cancelAnimationFrame', (id: number) => { frames.delete(id) }) + timers.clear() + frames.clear() + return Promise.resolve() + .then(body) + .finally(() => { + vi.unstubAllGlobals() + vi.restoreAllMocks() + if (originalResizeObserver === undefined) Reflect.deleteProperty(globalThis, 'ResizeObserver') + else globalThis.ResizeObserver = originalResizeObserver + timers.clear() + frames.clear() + }) + } + + it('never creates the 1.5s table while a column is cached', async () => { + await withHarness(() => { + const { unmount, col } = renderTrackedColumn() + try { + // 非空洞断言:首帧 locate() 真的采纳了这个列(ResizeObserver 挂在它上面), + // 所以「没有周期表」不是因为压根没找到列。 + expect(resizeObservers, '列必须已被采纳').toContain(col) + expect(retryTables(), '缓存到可用列就不该有周期表').toBe(0) + } finally { + unmount() + } + }) + }) + + it('keeps the cached path free of document queries across streaming mutations', async () => { + await withHarness(async () => { + const { unmount } = renderTrackedColumn() + try { + const query = vi.spyOn(document, 'querySelector') + // 流式输出:一串子节点增删落在 #root 里,每次都驱动一次 locate()。 + for (let index = 0; index < 5; index++) { + const row = document.createElement('div') + document.getElementById('root')!.append(row) + await Promise.resolve() + act(() => { flushFrame() }) + row.remove() + await Promise.resolve() + act(() => { flushFrame() }) + } + expect(query, '列还在 → 缓存命中,一次 document.querySelector 都不该有').not.toHaveBeenCalled() + expect(retryTables(), '列还在 → 兜底表也不该建').toBe(0) + } finally { + unmount() + } + }) + }) + + it('restarts the table when the cached column detaches, and stops it on the new column', async () => { + await withHarness(async () => { + const { unmount, col, root } = renderTrackedColumn() + try { + expect(retryTables()).toBe(0) + // HMR / 换节点:列被摘掉(观察者看到 #root 的 childList 变化)。 + col.remove() + await Promise.resolve() + act(() => { flushFrame() }) + expect(retryTables(), '没有可用列 → 慢速兜底表必须重新起').toBe(1) + + // 新列出现:观察者驱动的这一次 locate() 采纳它,兜底表随之停掉。 + appendTrackedColumn(root) + await Promise.resolve() + act(() => { flushFrame() }) + expect(retryTables(), '重新缓存到列 → 兜底表停掉').toBe(0) + } finally { + unmount() + } + }) + }) +}) diff --git a/tests/dock-fallback.spec.tsx b/tests/dock-fallback.spec.tsx index 4a0c270d..33cf0467 100644 --- a/tests/dock-fallback.spec.tsx +++ b/tests/dock-fallback.spec.tsx @@ -12,7 +12,7 @@ * document 出发;afterEach 清理 body 上的残留,避免跨用例串扰。 */ // @vitest-environment jsdom -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createElement } from 'react' import { act } from 'react-dom/test-utils' // First import: browser globals before the primitive-carrying sidebar graph loads. @@ -52,10 +52,83 @@ function clickFallbackToggle(): void { act(() => { element.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) } +/** + * 周期表账本:`setInterval` 被换成记账的假表,测试因此不用真的等 500ms, + * 也能直接断言「这条表到底建没建」。`clearInterval` 一起换掉(id 是假的)。 + */ +const intervals = new Map void; ms: number | undefined }>() +let intervalSeq = 0 + +/** 触发所有指定间隔的周期表回调(在 act 里调)。 */ +function runIntervals(ms: number): void { + for (const entry of [...intervals.values()]) { + if (entry.ms === ms) entry.fn() + } +} + +/** 隐藏/恢复页面:实现分别读 `document.hidden` 与 `document.visibilityState`。 */ +function setPageHidden(hidden: boolean): void { + Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden }) + Object.defineProperty(document, 'visibilityState', { + configurable: true, + get: () => (hidden ? 'hidden' : 'visible'), + }) +} + +/** + * 命中测试桩:每次调用计数并返回给定的「占位栈」。 + * @returns 还原函数(必须在 finally 里调)。 + */ +function stubHitTest(stack: () => Element[]): { hits: () => number; reset: () => void; restore: () => void } { + const original = document.elementsFromPoint + const spy = vi.fn(() => stack()) + Object.defineProperty(document, 'elementsFromPoint', { configurable: true, writable: true, value: spy }) + return { + hits: () => spy.mock.calls.length, + reset: () => { spy.mockClear() }, + restore: () => { + if (original === undefined) Reflect.deleteProperty(document, 'elementsFromPoint') + else Object.defineProperty(document, 'elementsFromPoint', { configurable: true, writable: true, value: original }) + }, + } +} + +/** 宿主角落锚点(收起形态),rect 固定在指定位置。 */ +function appendAnchor(left: number, top = 10): HTMLButtonElement { + const anchor = document.createElement('button') + anchor.setAttribute('data-sidebar-right-expand', 'true') + anchor.getBoundingClientRect = () => ({ + x: left, y: top, left, top, width: 28, height: 28, right: left + 28, bottom: top + 28, + toJSON: () => ({}), + }) as DOMRect + document.body.append(anchor) + return anchor +} + +/** 等相位(与其它异步 mock)落地。 */ +async function settle(): Promise { + await act(async () => { await new Promise(resolve => { setTimeout(resolve, 0) }) }) +} + describe('dock fallback(空白会话入口)', () => { + beforeEach(() => { + intervals.clear() + vi.spyOn(globalThis, 'setInterval').mockImplementation(((fn: () => void, ms?: number) => { + const id = ++intervalSeq + intervals.set(id, { fn, ms }) + return id + }) as never) + vi.spyOn(globalThis, 'clearInterval').mockImplementation(((id: number) => { + intervals.delete(id) + }) as never) + }) + // 失败用例可能把 portal 节点留在 body 上:每个用例后清干净,避免串扰。 afterEach(() => { for (const element of document.querySelectorAll('[data-dsh-dock-fallback]')) element.remove() + Reflect.deleteProperty(document, 'hidden') + Reflect.deleteProperty(document, 'visibilityState') + vi.restoreAllMocks() }) it('renders the fallback entry and flips the bottom workbench through the store', async () => { @@ -226,4 +299,108 @@ describe('dock fallback(空白会话入口)', () => { unmount() } }) + + // ==== 稳态开销(v0.25 回归:常驻轮询、隐藏页面、无界走查)==== + // 500ms 周期表原来注册在早退之前:一个正常(非 blank)会话里组件始终返回 null, + // 表却一直在跑,每次还带一遍最多 400 步的命中测试退让走查。 + + it('does not create the realign interval in a non-blank session', async () => { + phaseIs(false) + const anchor = appendAnchor(500) + const hit = stubHitTest(() => []) + const { unmount } = renderDockFallback() + try { + await settle() + expect(vi.mocked(sessionPhase), '相位必须已经读过一次').toHaveBeenCalled() + expect(document.querySelector('[data-dsh-dock-fallback]')).toBeNull() + // 组件返回 null,但页面里仍有一条 500ms 表(DockFallback 自己也订阅的 + // 右侧面板展开态共享 poller)。判别点不是「表的总数」而是「有没有人测量」: + // 让位走查是这条表唯一会读布局的动作。 + const atMount = hit.hits() + act(() => { runIntervals(500) }) + expect(hit.hits(), '非 blank 会话里重对齐表不该存在,更不该测量').toBe(atMount) + } finally { + unmount() + hit.restore() + anchor.remove() + } + }) + + it('does not measure on the 500ms tick while the page is hidden', async () => { + phaseIs(true) + const anchor = appendAnchor(500) + const hit = stubHitTest(() => []) + const { unmount } = renderDockFallback() + try { + await settle() + expect(document.querySelector('[data-dsh-dock-fallback]'), '相位已读到 blank').not.toBeNull() + // 切到后台:相位是隐藏前读到的,入口仍在渲染(渲染条件本身不看可见性)。 + act(() => { + setPageHidden(true) + document.dispatchEvent(new Event('visibilitychange')) + }) + const atMount = hit.hits() + act(() => { runIntervals(500) }) + expect(hit.hits(), '隐藏期间的 tick 不得测量').toBe(atMount) + } finally { + unmount() + hit.restore() + anchor.remove() + } + }) + + it('re-measures exactly once when the page becomes visible again', async () => { + phaseIs(true) + const anchor = appendAnchor(500) + const hit = stubHitTest(() => []) + const { unmount } = renderDockFallback() + try { + await settle() + act(() => { + setPageHidden(true) + document.dispatchEvent(new Event('visibilitychange')) + }) + hit.reset() + act(() => { + setPageHidden(false) + document.dispatchEvent(new Event('visibilitychange')) + }) + // 槽位空着时一次 measure() 采样 5 个点(slotFree 的 5 个 dx),即 5 次命中测试。 + expect(hit.hits(), '回到可见必须立刻补测一次,且只补一次').toBe(5) + // 周期表还在:再走一个 tick 就再测一次(隐藏时它是空转的,不是被拆掉的)。 + act(() => { runIntervals(500) }) + expect(hit.hits(), '恢复后周期表必须继续跑').toBe(10) + } finally { + unmount() + hit.restore() + anchor.remove() + } + }) + + it('bounds the retreat walk at 100 steps (400px)', async () => { + phaseIs(true) + const anchor = appendAnchor(500) + // 一个「整排都被占着」的页面:每个采样点都被同一个不透明芯片盖住。 + const chip = document.createElement('div') + chip.style.backgroundColor = 'rgb(40, 40, 40)' + document.body.append(chip) + const hit = stubHitTest(() => [chip]) + const { unmount } = renderDockFallback() + try { + await settle() + hit.reset() + act(() => { runIntervals(500) }) + // 走查每步的**第一个**采样点就被占 → 一次 tick 恰好 100 次命中测试。 + expect(hit.hits(), '让位走查必须封顶在 100 步(400px)').toBe(100) + const shell = document.querySelector('[data-dsh-dock-fallback]') + // 锚点在 500、按钮 28px、间距 8px → 起点 464;100 步 × 4px = 400px → 64。 + // 旧上限(400 步)会一路退到视口左缘并停成 4px。 + expect(shell!.style.left, '耗尽上限后停在 464 - 400,而不是视口左缘').toBe('64px') + } finally { + unmount() + hit.restore() + anchor.remove() + chip.remove() + } + }) }) diff --git a/tests/right-panel-open.spec.tsx b/tests/right-panel-open.spec.tsx new file mode 100644 index 00000000..6d4b5216 --- /dev/null +++ b/tests/right-panel-open.spec.tsx @@ -0,0 +1,224 @@ +/** + * 宿主右侧面板展开态的共享轮询器(v0.25 稳态开销治理)。 + * + * 早先每个 `useRightPanelOpen()` 消费者各建一条 500ms 的表、各做两趟全文档 + * `querySelectorAll`(本插件里有两个消费者:`Sidebar.tsx` 的会话头入口与 + * `dock-fallback.tsx` 的空白会话入口)。这里钉住四件事: + * 1. 两个消费者只建**一条**表; + * 2. 页面隐藏时表**根本不存在**(不是 tick 进来再早退)、也不读布局,回到可见补读一次; + * 3. 全部卸载后表被清掉(引用计数归零); + * 4. 宿主改属性名时读成 `false`(失败方向安全:按钮照旧出现)。 + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement, type ReactElement, type ReactNode } from 'react' +import { act } from 'react-dom/test-utils' +import './browser-globals.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { useRightPanelOpen } from '../src/client/sidebar/right-panel-open.ts' + +setupReactAct() + +/** + * 账本式定时器:id 是假的,表建没建、还在不在都能直接断言,且测试不用等 500ms。 + * 账本里的条目即「还活着的表」(`clearInterval` 删除)。 + */ +const intervals = new Map void>() +let intervalSeq = 0 + +/** 「读布局」与「扫文档」的计数(poller 的两类开销)。 */ +let layoutReads = 0 +let documentQueries = 0 + +/** 所有挂载过的 root 与页面节点的清理器:用例半途失败也不会把订阅者留给下一条。 */ +const mounted: Array<() => void> = [] +const cleanups: Array<() => void> = [] + +/** 幂等的清理包装(renderRoot 的 unmount 不防重复调用)。 */ +function once(fn: () => void): () => void { + let done = false + return () => { + if (done) return + done = true + fn() + } +} + +/** 挂载并登记清理;返回容器与幂等卸载。 */ +function mount(node: ReactNode): { container: HTMLDivElement; unmount: () => void } { + const view = renderRoot(node) + const unmount = once(view.unmount) + mounted.push(unmount) + return { container: view.container, unmount } +} + +/** 触发所有还活着的表(在 act 里调)。 */ +function runIntervals(): void { + for (const fn of [...intervals.values()]) fn() +} + +/** 一个真实消费者:把 hook 的答案渲染到 DOM 上。 */ +function Consumer({ label }: { label: string }): ReactElement { + const open = useRightPanelOpen() + return createElement('span', { 'data-consumer': label, 'data-open': String(open) }, label) +} + +function openOf(container: HTMLElement, label: string): string | null { + return container.querySelector(`[data-consumer="${label}"]`)?.getAttribute('data-open') ?? null +} + +/** + * 宿主角落控件的矩形(非零 → 可见)。 + * 宿主控件自带 rect 覆写(jsdom 没有布局),因此原型上的 `getBoundingClientRect` + * spy 看不到它——「读布局」的计数在这里一起记。 + */ +function hostRect(): DOMRect { + layoutReads += 1 + return { + x: 2000, y: 10, left: 2000, top: 10, width: 28, height: 28, right: 2028, bottom: 38, + toJSON: () => ({}), + } as DOMRect +} + +/** 宿主的角落控件:展开态是**可见**的 `[data-sidebar-right-toggle]`。 */ +function appendExpandedToggle(): void { + const toggle = document.createElement('button') + toggle.setAttribute('data-sidebar-right-toggle', 'true') + toggle.getBoundingClientRect = hostRect + document.body.append(toggle) + cleanups.push(() => { toggle.remove() }) +} + +/** 隐藏/恢复页面:实现读 `document.visibilityState`。 */ +function setPageHidden(hidden: boolean): void { + Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden }) + Object.defineProperty(document, 'visibilityState', { + configurable: true, + get: () => (hidden ? 'hidden' : 'visible'), + }) +} + +describe('useRightPanelOpen(共享 poller)', () => { + beforeEach(() => { + intervals.clear() + layoutReads = 0 + documentQueries = 0 + vi.spyOn(globalThis, 'setInterval').mockImplementation(((fn: () => void) => { + const id = ++intervalSeq + intervals.set(id, fn) + return id + }) as never) + vi.spyOn(globalThis, 'clearInterval').mockImplementation(((id: number) => { + intervals.delete(id) + }) as never) + // 「扫文档」= querySelectorAll,「读布局」= getBoundingClientRect。两条都只统计 + // poller 的读取(本用例里没有别的 DOM 读取方)。 + const originalQuery = document.querySelectorAll.bind(document) + vi.spyOn(document, 'querySelectorAll').mockImplementation(((selector: string) => { + documentQueries += 1 + return originalQuery(selector) + }) as never) + const originalRect = Element.prototype.getBoundingClientRect + vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function ( + this: Element, + ): DOMRect { + layoutReads += 1 + return originalRect.call(this) + }) + }) + + afterEach(() => { + for (const unmount of mounted.splice(0).reverse()) unmount() + for (const cleanup of cleanups.splice(0).reverse()) cleanup() + // 引用计数归零后表必须已经清掉:订阅者/表泄漏到下一条用例是真实 bug。 + expect(intervals.size, '卸载后不得留下任何周期表').toBe(0) + Reflect.deleteProperty(document, 'hidden') + Reflect.deleteProperty(document, 'visibilityState') + vi.restoreAllMocks() + }) + + it('creates exactly one interval for two mounted consumers', () => { + appendExpandedToggle() + const view = mount(createElement('div', null, + createElement(Consumer, { label: 'header' }), + createElement(Consumer, { label: 'dock' }), + )) + expect(intervals.size, '两个消费者共享一条表').toBe(1) + // 起表时立刻读一次:两个消费者在首帧就拿到真答案(不是等 500ms 后才对)。 + expect(openOf(view.container, 'header')).toBe('true') + expect(openOf(view.container, 'dock')).toBe('true') + const queriesBefore = documentQueries + act(() => { runIntervals() }) + // 一个 tick = 一趟「收起态」查询 + 一趟「展开态」查询(收起态先问,命中即短路); + // 两个消费者不会各扫一遍。 + expect(documentQueries - queriesBefore, '一个 tick 只扫一趟文档').toBe(2) + }) + + it('holds no interval and reads nothing while hidden, then reads once on show', () => { + // 先让共享缓存在可见状态下定成「收起」:宿主此刻没有展开态控件。 + const priming = mount(createElement(Consumer, { label: 'prime' })) + expect(openOf(priming.container, 'prime')).toBe('false') + priming.unmount() + appendExpandedToggle() + + setPageHidden(true) + layoutReads = 0 + documentQueries = 0 + const view = mount(createElement(Consumer, { label: 'dock' })) + expect(intervals.size, '隐藏的页面没有要服务的版面:表根本不该建').toBe(0) + expect(documentQueries, '隐藏时不扫文档(连首帧都不扫,读缓存)').toBe(0) + expect(layoutReads, '隐藏时不读布局').toBe(0) + expect(openOf(view.container, 'dock'), '隐藏期间保持上一次的答案').toBe('false') + + act(() => { runIntervals() }) + expect(documentQueries + layoutReads, '没有表,自然一次都不读').toBe(0) + + // 回到可见:立刻读一次(隐藏期间面板可能已经开合),并把表接回去。 + act(() => { + setPageHidden(false) + document.dispatchEvent(new Event('visibilitychange')) + }) + expect(openOf(view.container, 'dock'), '补读必须落地').toBe('true') + expect(documentQueries, '一次补读 = 一趟收起态 + 一趟展开态查询').toBe(2) + expect(layoutReads, '只量展开态那一个元素').toBe(1) + expect(intervals.size, '补读之后表回到账本上').toBe(1) + }) + + it('stops polling the moment the page goes hidden again', () => { + appendExpandedToggle() + mount(createElement(Consumer, { label: 'dock' })) + expect(intervals.size).toBe(1) + act(() => { + setPageHidden(true) + document.dispatchEvent(new Event('visibilitychange')) + }) + expect(intervals.size, '隐藏即停表(不是 tick 里早退)').toBe(0) + const reads = documentQueries + layoutReads + act(() => { runIntervals() }) + expect(documentQueries + layoutReads, '停表之后一次都不读').toBe(reads) + }) + + it('clears the shared interval only after the last consumer unmounts', () => { + appendExpandedToggle() + const header = mount(createElement(Consumer, { label: 'header' })) + const dock = mount(createElement(Consumer, { label: 'dock' })) + expect(intervals.size, '两条挂载路径共用同一条表').toBe(1) + header.unmount() + expect(intervals.size, '还剩一个消费者,表必须留着').toBe(1) + dock.unmount() + expect(intervals.size, '引用计数归零 → 表清掉').toBe(0) + }) + + it('fails safe (false) when the host renames its attributes', () => { + // 宿主改名的形态:两个属性一个都不认 → 必须读成「未展开」(不隐藏按钮)。 + const renamed = document.createElement('button') + renamed.setAttribute('data-right-sidebar-collapse', 'true') + renamed.getBoundingClientRect = hostRect + document.body.append(renamed) + cleanups.push(() => { renamed.remove() }) + const view = mount(createElement(Consumer, { label: 'dock' })) + expect(openOf(view.container, 'dock'), '认不出来就读 false').toBe('false') + act(() => { runIntervals() }) + expect(openOf(view.container, 'dock'), 'tick 之后仍是 false').toBe('false') + }) +}) diff --git a/tests/session-phase.spec.tsx b/tests/session-phase.spec.tsx new file mode 100644 index 00000000..a54d8f28 --- /dev/null +++ b/tests/session-phase.spec.tsx @@ -0,0 +1,141 @@ +/** + * 会话相位的 1s 轮询(v0.25 稳态开销治理)。 + * + * 这条轮询每 tick 发一次 HTTP 请求,然后把**新解析出来的 JSON 对象**塞进 state —— + * 一个开着不管的 blank 会话于是每秒重渲染一次;而且它不看页面可见性。这里钉住: + * 1. 隐藏的页面不发请求,回到可见立刻补一次; + * 2. 答案没变就不写 state(渲染次数不涨),但轮询本身仍在跑; + * 3. 相位翻成非 blank 停表之后,「回到可见」不得把它唤醒。 + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement, type ReactElement } from 'react' +import { act } from 'react-dom/test-utils' +import './browser-globals.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { useSessionPhase } from '../src/client/session-phase.ts' +import { sessionPhase } from '../src/client/api.ts' + +setupReactAct() + +vi.mock('../src/client/api.ts', () => ({ + sessionPhase: vi.fn(async () => ({ blank: true })), +})) + +/** 渲染次数:state 没变时 React 不该重跑组件体。 */ +let renders = 0 + +function Probe({ sessionId }: { sessionId: string | undefined }): ReactElement { + const phase = useSessionPhase(sessionId) + renders += 1 + return createElement('span', { + 'data-phase': phase === undefined ? 'pending' : String(phase.blank), + }) +} + +/** 让已发出的 promise 落地(假表下 1s 周期不会自己走)。 */ +async function settle(): Promise { + await act(async () => { await vi.advanceTimersByTimeAsync(0) }) +} + +async function advance(ms: number): Promise { + await act(async () => { await vi.advanceTimersByTimeAsync(ms) }) +} + +function phaseText(container: HTMLElement): string | null { + return container.querySelector('[data-phase]')?.getAttribute('data-phase') ?? null +} + +/** 隐藏/恢复页面:实现读 `document.hidden`。 */ +function setPageHidden(hidden: boolean): void { + Object.defineProperty(document, 'hidden', { configurable: true, get: () => hidden }) + Object.defineProperty(document, 'visibilityState', { + configurable: true, + get: () => (hidden ? 'hidden' : 'visible'), + }) +} + +describe('useSessionPhase', () => { + let unmount: (() => void) | undefined + + beforeEach(() => { + vi.useFakeTimers() + renders = 0 + vi.mocked(sessionPhase).mockReset() + vi.mocked(sessionPhase).mockImplementation(async () => ({ blank: true })) + }) + + afterEach(() => { + act(() => { unmount?.() }) + unmount = undefined + Reflect.deleteProperty(document, 'hidden') + Reflect.deleteProperty(document, 'visibilityState') + vi.useRealTimers() + }) + + it('does not write state when the phase answer is unchanged', async () => { + const view = renderRoot(createElement(Probe, { sessionId: 's1' })) + unmount = view.unmount + await settle() + expect(phaseText(view.container)).toBe('true') + expect(vi.mocked(sessionPhase)).toHaveBeenCalledTimes(1) + const rendersAfterFirstRead = renders + + // 一个 tick 一次 act:React 不会把 5 次 tick 的更新并成一批,因此「每秒重渲染一次」 + // 在旧实现下会实打实地涨 5 次。 + for (let tick = 0; tick < 5; tick++) await advance(1_000) + expect(vi.mocked(sessionPhase), '轮询本身仍在跑').toHaveBeenCalledTimes(6) + expect(renders, 'blank 没翻转 → 一次都不该重渲染').toBe(rendersAfterFirstRead) + expect(phaseText(view.container)).toBe('true') + }) + + it('skips the fetch while the page is hidden and resumes on visibilitychange', async () => { + setPageHidden(true) + const view = renderRoot(createElement(Probe, { sessionId: 's1' })) + unmount = view.unmount + await settle() + await advance(5_000) + expect(vi.mocked(sessionPhase), '隐藏期间一次请求都不发').not.toHaveBeenCalled() + expect(phaseText(view.container), '没读到就停在 pending').toBe('pending') + + act(() => { + setPageHidden(false) + document.dispatchEvent(new Event('visibilitychange')) + }) + await settle() + expect(vi.mocked(sessionPhase), '回到可见立刻补一次').toHaveBeenCalledTimes(1) + expect(phaseText(view.container)).toBe('true') + }) + + it('does not wake a poller that already stopped on a non-blank phase', async () => { + vi.mocked(sessionPhase).mockImplementation(async () => ({ blank: false })) + const view = renderRoot(createElement(Probe, { sessionId: 's1' })) + unmount = view.unmount + await settle() + expect(phaseText(view.container)).toBe('false') + expect(vi.mocked(sessionPhase), '非 blank 即停表').toHaveBeenCalledTimes(1) + const rendersAfterFirstRead = renders + + act(() => { + setPageHidden(true) + document.dispatchEvent(new Event('visibilitychange')) + }) + act(() => { + setPageHidden(false) + document.dispatchEvent(new Event('visibilitychange')) + }) + await advance(3_000) + expect(vi.mocked(sessionPhase), '停表之后不得被可见性事件唤醒').toHaveBeenCalledTimes(1) + expect(renders).toBe(rendersAfterFirstRead) + }) + + it('degrades to non-blank when the route is unavailable', async () => { + vi.mocked(sessionPhase).mockRejectedValue(new Error('unsupported')) + const view = renderRoot(createElement(Probe, { sessionId: 's1' })) + unmount = view.unmount + await settle() + expect(phaseText(view.container), '降级为非 blank').toBe('false') + await advance(3_000) + expect(vi.mocked(sessionPhase), '降级即停表').toHaveBeenCalledTimes(1) + }) +}) diff --git a/tests/settings-nav-icon.spec.ts b/tests/settings-nav-icon.spec.ts index 74f48399..d3112cfc 100644 --- a/tests/settings-nav-icon.spec.ts +++ b/tests/settings-nav-icon.spec.ts @@ -1,8 +1,28 @@ // @vitest-environment jsdom -/** Settings-navigation icon marker tests (including delayed dialog mount). */ -import { afterEach, describe, expect, it } from 'vitest' +/** + * Settings-navigation icon marker tests (including delayed dialog mount). + * + * v0.25 的稳态开销治理:观察者改 rAF 合帧 + 去掉 `characterData`。三条契约: + * 1. 标记仍然落在本地化标签匹配的那一行上(挂载/改标签的既有用例); + * 2. 同一帧里的一串 DOM 文本 mutation 只做**一次**全文档行查询; + * 3. 纯文本节点内容变化(对话流式输出就是它)不再触发任何查询。 + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { registerSettingsNavIcon, SETTINGS_NAV_MARKER } from '../src/client/settings-nav-icon.ts' +/** 被观察者查询的行选择器(统计它,而不是 disposer 的标记清理查询)。 */ +const NAV_SELECTOR = '[role="dialog"] nav button' + +/** 确定性 rAF:只有在 flushFrame() 里才推进一帧。 */ +let frames: Map +let nextFrameId: number + +function flushFrame(): void { + const callbacks = [...frames.values()] + frames.clear() + for (const callback of callbacks) callback(0) +} + function navButton(label: string): HTMLButtonElement { const button = document.createElement('button') button.innerHTML = `${label}` @@ -22,8 +42,33 @@ async function mutationTick(): Promise { await new Promise(resolve => { setTimeout(resolve, 0) }) } +/** 一次 mutation 走到「观察者回调(微任务)→ 合帧后的一次 sync」。 */ +async function settleMarker(): Promise { + await mutationTick() + flushFrame() +} + +/** 观察者查询行的次数(标记清理的查询不算)。 */ +function navQueries(spy: { mock: { calls: unknown[][] } }): number { + return spy.mock.calls.filter(call => call[0] === NAV_SELECTOR).length +} + +beforeEach(() => { + frames = new Map() + nextFrameId = 1 + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { + frames.set(nextFrameId, callback) + return nextFrameId++ + }) + vi.stubGlobal('cancelAnimationFrame', (id: number) => { + frames.delete(id) + }) +}) + afterEach(() => { document.body.innerHTML = '' + vi.unstubAllGlobals() + vi.restoreAllMocks() }) describe('registerSettingsNavIcon', () => { @@ -48,17 +93,74 @@ describe('registerSettingsNavIcon', () => { const chinese = navButton('侧边卡片') const dialog = dialogWith(english, chinese) document.body.append(dialog) - await mutationTick() + await settleMarker() expect(english.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true) expect(chinese.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false) label = '侧边卡片' chinese.querySelector('span')!.textContent = '侧边卡片 ' - await mutationTick() + await settleMarker() expect(english.hasAttribute(SETTINGS_NAV_MARKER)).toBe(false) expect(chinese.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true) dispose() }) + + it('coalesces a burst of mutations into one sync per frame', async () => { + const dispose = registerSettingsNavIcon(() => 'Side card') + const button = navButton('Side card') + document.body.append(dialogWith(button)) + // 对话正文的形态:转写每来一个 token 就往正文容器里插一个文本节点,而设置行本身 + // 一动不动。观察者盯的是整个 body,所以这些 mutation 都会打到它身上。 + const stream = document.createElement('div') + document.body.append(stream) + await settleMarker() + + const query = vi.spyOn(document, 'querySelectorAll') + for (let index = 0; index < 6; index++) { + stream.append(document.createTextNode(`token ${index}`)) + // 每个 token 一个宏任务(流式输出的节拍):观察者是同步回调时,每次都会跑一次 + // 全文档行查询。 + await mutationTick() + } + expect(navQueries(query), '还没到帧,一次都不该查').toBe(0) + flushFrame() + expect(navQueries(query), '同一帧内的一串 mutation 只查一次').toBe(1) + // 合帧不改变结果:帧末那次 sync 仍把标记留在唯一匹配的行上。 + expect(button.hasAttribute(SETTINGS_NAV_MARKER)).toBe(true) + dispose() + }) + + it('ignores characterData-only mutations (streamed conversation tokens)', async () => { + const dispose = registerSettingsNavIcon(() => 'Side card') + const button = navButton('Side card') + document.body.append(dialogWith(button)) + // 对话正文那样的一串文本节点:先排掉挂载那一次观察者回调。 + const streamed = document.createTextNode('streaming 0') + document.body.append(streamed) + await settleMarker() + + const query = vi.spyOn(document, 'querySelectorAll') + for (let index = 1; index <= 5; index++) { + streamed.data = `streaming ${index}` + await mutationTick() + } + flushFrame() + expect(navQueries(query), 'characterData 已被移出观察面').toBe(0) + expect(button.hasAttribute(SETTINGS_NAV_MARKER), '标记不受正文影响').toBe(true) + dispose() + }) + + it('cancels a pending frame when disposed', async () => { + const dispose = registerSettingsNavIcon(() => 'Side card') + document.body.append(dialogWith(navButton('Side card'))) + // 观察到 mutation,但帧还没到就 dispose:回调必须被取消,不能再查一次。 + await mutationTick() + const query = vi.spyOn(document, 'querySelectorAll') + dispose() + expect(frames.size, '待处理的那一帧被取消').toBe(0) + flushFrame() + expect(navQueries(query)).toBe(0) + }) })