From e2b0f83ea9f3d9f5056effa10a39fd8f1a37b736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A4=A7=E7=8C=AB?= <16399091+binaricat@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:39:17 +0800 Subject: [PATCH] fix(ai): detach global window listeners and mark completion when aiMarkdownWarmup fires (#4373) --- components/ai/aiMarkdownWarmup.test.ts | 219 +++++++++++++++++++++++++ components/ai/aiMarkdownWarmup.ts | 30 ++-- 2 files changed, 238 insertions(+), 11 deletions(-) diff --git a/components/ai/aiMarkdownWarmup.test.ts b/components/ai/aiMarkdownWarmup.test.ts index d3a46bab8..0656e3e64 100644 --- a/components/ai/aiMarkdownWarmup.test.ts +++ b/components/ai/aiMarkdownWarmup.test.ts @@ -10,6 +10,8 @@ import { isAiComposerTarget, markAiComposerActivity, resolveAiMarkdownWarmupDelay, + scheduleAiMarkdownWarmup, + scheduleWhenAiComposerIdle, shouldDeferAiMarkdownWarmup, } from './aiMarkdownWarmup'; @@ -85,3 +87,220 @@ test('LazyMessageResponse warms immediately by default and still supports opt-in assert.match(source, /isAiMarkdownRendererReady/); assert.doesNotMatch(source, /scheduleWhenAiComposerIdle/); }); + +function createFakeWarmupWindow() { + type ListenerEntry = { + type: string; + listener: EventListenerOrEventListenerObject; + capture: boolean; + }; + const listeners: ListenerEntry[] = []; + const timeouts = new Map void>(); + const idleCallbacks = new Map void>(); + let nextTimeoutId = 1; + let nextIdleId = 1; + let removeCalls = 0; + + const toCapture = (options?: boolean | AddEventListenerOptions) => + typeof options === 'boolean' ? options : Boolean(options?.capture); + + const fakeWindow = { + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ) { + listeners.push({ type, listener, capture: toCapture(options) }); + }, + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ) { + removeCalls += 1; + const capture = toCapture(options); + const index = listeners.findIndex( + (entry) => entry.type === type && entry.listener === listener && entry.capture === capture, + ); + if (index >= 0) listeners.splice(index, 1); + }, + setTimeout(callback: () => void) { + const id = nextTimeoutId++; + timeouts.set(id, callback); + return id; + }, + clearTimeout(id: number) { + timeouts.delete(id); + }, + }; + + const dispatch = (type: string, target: EventTarget) => { + const event = { target } as unknown as Event; + for (const entry of [...listeners]) { + if (entry.type !== type) continue; + if (typeof entry.listener === 'function') { + entry.listener(event); + } else { + entry.listener.handleEvent(event); + } + } + }; + + const flushNextTimeout = () => { + const next = timeouts.entries().next().value; + if (!next) return false; + const [id, fn] = next; + timeouts.delete(id); + fn(); + return true; + }; + + const flushNextIdle = () => { + const next = idleCallbacks.entries().next().value; + if (!next) return false; + const [id, fn] = next; + idleCallbacks.delete(id); + fn(); + return true; + }; + + return { + fakeWindow, + requestIdleCallback: (callback: () => void) => { + const id = nextIdleId++; + idleCallbacks.set(id, callback); + return id; + }, + cancelIdleCallback: (id: number) => { + idleCallbacks.delete(id); + }, + dispatch, + flushNextTimeout, + flushNextIdle, + getListenerCount: () => listeners.length, + getListenerKeys: () => listeners.map((entry) => `${entry.type}:${entry.capture}`).sort(), + getPendingTimerCount: () => timeouts.size + idleCallbacks.size, + getRemoveCalls: () => removeCalls, + }; +} + +test('scheduleAiMarkdownWarmup removes all 5 window listeners and runs load strictly once', () => { + const globals = globalThis as typeof globalThis & { + window?: Window; + requestIdleCallback?: typeof globalThis.requestIdleCallback; + cancelIdleCallback?: typeof globalThis.cancelIdleCallback; + }; + const originalWindow = globals.window; + const originalRequestIdle = globals.requestIdleCallback; + const originalCancelIdle = globals.cancelIdleCallback; + + const env = createFakeWarmupWindow(); + globals.window = env.fakeWindow as unknown as Window & typeof globalThis; + globals.requestIdleCallback = env.requestIdleCallback as unknown as typeof globalThis.requestIdleCallback; + globals.cancelIdleCallback = env.cancelIdleCallback as unknown as typeof globalThis.cancelIdleCallback; + + const composerTarget = { + closest: (selector: string) => (selector.includes('ai-chat-input-body') ? {} : null), + } as unknown as EventTarget; + + try { + let busy = true; + let loadCalls = 0; + let listenersRemainingDuringLoad = -1; + + const cancel = scheduleAiMarkdownWarmup({ + isBusy: () => busy, + load: () => { + loadCalls += 1; + listenersRemainingDuringLoad = env.getListenerCount(); + }, + initialDelayMs: 4000, + resumeDelayMs: 600, + }); + + assert.deepEqual(env.getListenerKeys(), [ + 'compositionstart:true', + 'compositionupdate:true', + 'focusin:false', + 'focusout:false', + 'keydown:true', + ]); + + // While busy, timer/idle callbacks defer without removing listeners or calling load. + assert.equal(env.flushNextTimeout(), true); + assert.equal(env.flushNextIdle(), true); + assert.equal(loadCalls, 0); + assert.equal(env.getListenerCount(), 5); + + // Once idle, firing load immediately detaches all 5 window listeners before load() runs. + busy = false; + assert.equal(env.flushNextTimeout(), true); + assert.equal(env.flushNextIdle(), true); + assert.equal(loadCalls, 1); + assert.equal(listenersRemainingDuringLoad, 0); + assert.equal(env.getListenerCount(), 0); + assert.equal(env.getPendingTimerCount(), 0); + + // Subsequent composer events must not re-arm timers or re-execute load(). + env.dispatch('focusin', composerTarget); + env.dispatch('keydown', composerTarget); + env.dispatch('compositionstart', composerTarget); + env.dispatch('compositionupdate', composerTarget); + env.dispatch('focusout', composerTarget); + assert.equal(env.getPendingTimerCount(), 0); + assert.equal(loadCalls, 1); + + // Unmount cancel after completion is an idempotent no-op. + const removeCallsAfterLoad = env.getRemoveCalls(); + cancel(); + assert.equal(env.getRemoveCalls(), removeCallsAfterLoad); + } finally { + if (originalWindow !== undefined) globals.window = originalWindow; + else delete globals.window; + if (originalRequestIdle !== undefined) globals.requestIdleCallback = originalRequestIdle; + else delete globals.requestIdleCallback; + if (originalCancelIdle !== undefined) globals.cancelIdleCallback = originalCancelIdle; + else delete globals.cancelIdleCallback; + } +}); + +test('scheduleWhenAiComposerIdle cancel detaches listeners and prevents execution', () => { + const globals = globalThis as typeof globalThis & { + window?: Window; + requestIdleCallback?: typeof globalThis.requestIdleCallback; + cancelIdleCallback?: typeof globalThis.cancelIdleCallback; + }; + const originalWindow = globals.window; + const originalRequestIdle = globals.requestIdleCallback; + const originalCancelIdle = globals.cancelIdleCallback; + + const env = createFakeWarmupWindow(); + globals.window = env.fakeWindow as unknown as Window & typeof globalThis; + globals.requestIdleCallback = env.requestIdleCallback as unknown as typeof globalThis.requestIdleCallback; + globals.cancelIdleCallback = env.cancelIdleCallback as unknown as typeof globalThis.cancelIdleCallback; + + try { + let ran = 0; + const cancel = scheduleWhenAiComposerIdle(() => { + ran += 1; + }, { isBusy: () => false }); + + assert.equal(env.getListenerCount(), 5); + assert.equal(env.getPendingTimerCount(), 1); + + cancel(); + + assert.equal(env.getListenerCount(), 0); + assert.equal(env.getPendingTimerCount(), 0); + assert.equal(env.flushNextTimeout(), false); + assert.equal(env.flushNextIdle(), false); + assert.equal(ran, 0); + } finally { + if (originalWindow !== undefined) globals.window = originalWindow; + else delete globals.window; + if (originalRequestIdle !== undefined) globals.requestIdleCallback = originalRequestIdle; + else delete globals.requestIdleCallback; + if (originalCancelIdle !== undefined) globals.cancelIdleCallback = originalCancelIdle; + else delete globals.cancelIdleCallback; + } +}); diff --git a/components/ai/aiMarkdownWarmup.ts b/components/ai/aiMarkdownWarmup.ts index 97ab22126..ce59d8bcf 100644 --- a/components/ai/aiMarkdownWarmup.ts +++ b/components/ai/aiMarkdownWarmup.ts @@ -199,6 +199,22 @@ export function scheduleAiMarkdownWarmup(options?: { } }; + const removeListeners = () => { + if (typeof window === 'undefined') return; + window.removeEventListener('focusin', onFocusIn); + window.removeEventListener('focusout', onFocusOut); + window.removeEventListener('keydown', onComposerEvent, true); + window.removeEventListener('compositionstart', onComposerEvent, true); + window.removeEventListener('compositionupdate', onComposerEvent, true); + }; + + const cleanup = () => { + if (cancelled) return; + cancelled = true; + clearTimers(); + removeListeners(); + }; + const tryLoad = () => { idleId = null; timeoutId = null; @@ -207,7 +223,8 @@ export function scheduleAiMarkdownWarmup(options?: { timeoutId = window.setTimeout(armIdle, Math.max(resumeDelayMs, AI_COMPOSER_IDLE_MS)); return; } - load(); + cleanup(); + void load(); }; const armIdle = () => { @@ -262,14 +279,5 @@ export function scheduleAiMarkdownWarmup(options?: { } arm(); - return () => { - cancelled = true; - clearTimers(); - if (typeof window === 'undefined') return; - window.removeEventListener('focusin', onFocusIn); - window.removeEventListener('focusout', onFocusOut); - window.removeEventListener('keydown', onComposerEvent, true); - window.removeEventListener('compositionstart', onComposerEvent, true); - window.removeEventListener('compositionupdate', onComposerEvent, true); - }; + return cleanup; }