fix(ai): detach global window listeners and mark completion when aiMarkdownWarmup fires (#4373)

This commit is contained in:
陈大猫 authored and GitHub committed 2026-11-25 21:39:17 +08:00
1 parent 4d7906a710
commit e2b0f83ea9
2 files changed
+238 -11

No files matched your search

+219
View File
@@ -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<number, () => void>();
const idleCallbacks = new Map<number, () => 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;
}
});
+19 -11
View File
@@ -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;
}