Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(test): scope fake timer exemptions to tests and hooks

MagicLizi4237234f2115
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
index 19f74649ad..94a1b3efb6 100644
--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
@@ -3870,11 +3870,13 @@ describe('Pi package executable-code boundary', () => {
// Recover the old legacy baseline while runtime observation stays down.
legacyReadBlocked = false;
await fs.writeFile(legacyToken, 'runtime:old\n');
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
// Simulate another Main publishing only the runtime edge while its legacy
// mirror write fails. The legacy file intentionally stays on the old token.
await fs.writeFile(runtimeToken, 'runtime:peer-edge\n');
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 300));
runtimeReadBlocked = false;
await fs.writeFile(runtimeToken, 'runtime:peer-edge\n');
@@ -3944,6 +3946,7 @@ describe('Pi package executable-code boundary', () => {
'runtime-refresh',
expect.objectContaining({ afterCurrentTurn: true }),
));
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 300));
expect(originListener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
expect(maker.advanceLocalPiPackageRuntimeGeneration).toHaveBeenCalledOnce();
@@ -3981,6 +3984,7 @@ describe('Pi package executable-code boundary', () => {
));
runtimeReadBlocked = false;
await fs.writeFile(runtimeToken, 'runtime:already-present\n');
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener).not.toHaveBeenCalled();
} finally {
@@ -4024,6 +4028,7 @@ describe('Pi package executable-code boundary', () => {
runtimeReadBlocked = false;
await fs.writeFile(runtimeToken, 'runtime:old\n');
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
} finally {
@@ -4066,11 +4071,13 @@ describe('Pi package executable-code boundary', () => {
expect(listener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
// Keep runtime observation down for another poll. The already-notified
// legacy edge must not become a new recovery comparison baseline.
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
runtimeReadBlocked = false;
await fs.writeFile(runtimeToken, 'runtime:old\n');
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
} finally {
@@ -4115,6 +4122,7 @@ describe('Pi package executable-code boundary', () => {
await vi.waitFor(() => expect(delayedRuntimeRead).toBe(true));
await mutateAuthorized(store, { action: 'install', source: 'npm:local-publication' });
releaseRuntimeRead();
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener).toHaveBeenCalledWith('local');
@@ -4188,6 +4196,7 @@ describe('Pi package executable-code boundary', () => {
'runtime-refresh',
expect.objectContaining({ afterCurrentTurn: true }),
), { timeout: 2_000 });
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 300));
expect(originListener.mock.calls.filter(([origin]) => origin === 'external-runtime')).toHaveLength(1);
expect(maker.advanceLocalPiPackageRuntimeGeneration).toHaveBeenCalledOnce();
@@ -4222,6 +4231,7 @@ describe('Pi package executable-code boundary', () => {
const listener = vi.fn();
const unsubscribe = store.onPiPackagesChanged(listener);
try {
+ // real-wait: observe a full filesystem polling window to reject duplicate or stale runtime events.
await new Promise((resolve) => setTimeout(resolve, 500));
expect(listener).not.toHaveBeenCalled();
} finally {
@@ -4259,6 +4269,7 @@ describe('Pi package executable-code boundary', () => {
const tokenPath = path.resolve(String(target));
if (!tokenPaths.delete(tokenPath)) return originalOpen(target, flags, mode);
// Exercise slow initial I/O: a 50 ms sleep must not stand in for readiness.
+ // real-wait: inject slow initial filesystem I/O before the observer establishes its baseline.
await new Promise((resolve) => setTimeout(resolve, 100));
const handle = await originalOpen(target, flags, mode);
return {
diff --git a/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
index 78d94a2149..518bc7008f 100644
--- a/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
@@ -234,6 +234,7 @@ describe('enableRemoteCollabForSession', () => {
// 链路「可连但每个 invoke 都黑洞」:每次回查自己要走满 30s 隧道超时。只限次数的话
// 6 次串行 ≈ 3 分钟,而这段时间 composer 是锁住的、首轮压着不发(codex P2 第五轮)。
enableOrca.mockRejectedValue(timeoutError());
+ vi.useFakeTimers();
listWorkersByLead.mockImplementation(
() =>
new Promise((_resolve, reject) => {
@@ -241,7 +242,6 @@ describe('enableRemoteCollabForSession', () => {
}),
);
- vi.useFakeTimers();
const pending = enableRemoteCollabForSession(params);
const assertion = expect(pending).rejects.toThrow('DEVICE_LINK_TIMEOUT');
// 推进远超 6×(30s+3s) 的时间,确认它早就按 deadline 停了而不是跑满次数。
diff --git a/scripts/__tests__/check-test-hygiene.test.mjs b/scripts/__tests__/check-test-hygiene.test.mjs
index bf61127f83..951d8b7436 100644
--- a/scripts/__tests__/check-test-hygiene.test.mjs
+++ b/scripts/__tests__/check-test-hygiene.test.mjs
@@ -40,6 +40,16 @@ test("scanTestSource counts only unjustified hits for each rule", () => {
"vi.useFakeTimers();\nvi.useRealTimers();\nsetTimeout(tick, 5_000);",
{ realWaits: 1 },
],
+ [
+ "fake timers in a sibling test do not hide a real wait after cleanup",
+ "afterEach(() => vi.useRealTimers());\nit('fake', () => { vi.useFakeTimers(); setTimeout(done, 100); });\nit('real', () => { setTimeout(done, 100); });",
+ { realWaits: 1 },
+ ],
+ [
+ "beforeEach fake timers apply to their own describe, not a sibling suite",
+ "describe('fake', () => { beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); it('one', () => setTimeout(done, 100)); });\ndescribe('real', () => { it('two', () => setTimeout(done, 100)); });",
+ { realWaits: 1 },
+ ],
[
"multi-line real wait",
"await new Promise((resolve) => setTimeout(\n resolve,\n 250,\n));",
diff --git a/scripts/check-test-hygiene.mjs b/scripts/check-test-hygiene.mjs
index cdd7fbe804..41802a229f 100644
--- a/scripts/check-test-hygiene.mjs
+++ b/scripts/check-test-hygiene.mjs
@@ -20,6 +20,7 @@
import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
+import { createRequire } from 'node:module';
import process from 'node:process';
import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -32,6 +33,10 @@ const NON_UNIT_TEST = /(?:^|[-.])(?:integration|e2e|git-integration)\.(?:test|sp
export const RULES = ['resetModules', 'realWaits', 'sourceReads'];
const REAL_WAIT_MIN_MS = 100;
const REAL_WAIT_PATTERN = /\b(?:sleep|delay|wait|waitMs|pause)\s*\(\s*(\d[\d_]*)\s*\)/g;
+// Reuse Desktop's declared parser only for files that mix fake and real timers.
+// No type checking or module loading is needed to locate test/hook callbacks.
+const requireDesktop = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+let typescript;
/** Replace comments with spaces (keeping newlines) so matches ignore commented-out code. */
export function stripComments(source) {
@@ -160,10 +165,67 @@ function setTimeoutCalls(code) {
return calls;
}
+function timerScopes(code) {
+ const ts = typescript ??= requireDesktop('typescript');
+ const source = ts.createSourceFile('test.tsx', code, ts.ScriptTarget.Latest, false, ts.ScriptKind.TSX);
+ const scopes = [];
+ function rootName(expression) {
+ if (ts.isIdentifier(expression)) return expression.text;
+ if (ts.isPropertyAccessExpression(expression) || ts.isCallExpression(expression)) return rootName(expression.expression);
+ if (ts.isTaggedTemplateExpression(expression)) return rootName(expression.tag);
+ return '';
+ }
+ function visit(node) {
+ if (ts.isCallExpression(node)) {
+ const kind = rootName(node.expression);
+ if (/^(?:describe|it|test|beforeEach|beforeAll|afterEach|afterAll)$/.test(kind)) {
+ for (const argument of node.arguments) {
+ if (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)) {
+ scopes.push({ kind, start: argument.getStart(source), end: argument.end });
+ }
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ return scopes.sort((a, b) => (a.end - a.start) - (b.end - b.start));
+}
+
+function timerStateAt(index, timerEvents, scopes) {
+ const scopeAt = (position) => scopes.find(s => s.start <= position && position < s.end);
+ const waitScope = scopeAt(index);
+ const describeAt = (scope) => scopes.find(s => s.kind === 'describe' && s.start < scope.start && scope.end < s.end);
+ const belongsToWait = (scope) => !scope || scope.kind === 'describe' && scope.start < index && index < scope.end;
+ const events = timerEvents.map(event => ({ event, scope: scopeAt(event.index) }));
+ let fake = false;
+ // Registration-time calls and before hooks are distinct from calls in a
+ // sibling test or an after hook. Inherit hooks from outer describes first.
+ const inherited = events.filter(({ event, scope }) => event.index < index && belongsToWait(scope));
+ for (const { event } of inherited) fake = event[1] === 'useFakeTimers';
+ if (waitScope && /^(?:it|test)$/.test(waitScope.kind)) {
+ const hooks = events.filter(({ scope }) => scope && /^(?:beforeAll|beforeEach)$/.test(scope.kind) && belongsToWait(describeAt(scope)))
+ .sort((a, b) => {
+ const depthA = scopes.filter(s => s.kind === 'describe' && s.start < a.scope.start && a.scope.end < s.end).length;
+ const depthB = scopes.filter(s => s.kind === 'describe' && s.start < b.scope.start && b.scope.end < s.end).length;
+ return depthA - depthB || (a.scope.kind === b.scope.kind ? a.event.index - b.event.index : a.scope.kind === 'beforeAll' ? -1 : 1);
+ });
+ for (const { event, scope } of hooks) {
+ // An afterEach restoring real timers invalidates beforeAll-only setup
+ // for subsequent tests. Be conservative rather than exempt a real wait.
+ if (scope.kind === 'beforeAll' && events.some(entry => entry.scope?.kind === 'afterEach' && entry.event[1] === 'useRealTimers' && belongsToWait(describeAt(entry.scope)))) continue;
+ fake = event[1] === 'useFakeTimers';
+ }
+ }
+ for (const { event, scope } of events) {
+ if (scope === waitScope && event.index < index) fake = event[1] === 'useFakeTimers';
+ }
+ return fake;
+}
+
function countRealWaits(code, lines) {
const timerEvents = [...code.matchAll(/\bvi\.(useFakeTimers|useRealTimers)\s*\(/g)];
- let timerIndex = 0;
- let fakeTimers = false;
+ const scopes = timerEvents.length > 0 ? timerScopes(code) : [];
let count = 0;
const waits = [
...setTimeoutCalls(code).map(({ index, duration }) => ({ index, duration })),
@@ -173,11 +235,7 @@ function countRealWaits(code, lines) {
})),
].sort((a, b) => a.index - b.index);
for (const wait of waits) {
- while (timerIndex < timerEvents.length && timerEvents[timerIndex].index < wait.index) {
- fakeTimers = timerEvents[timerIndex][1] === 'useFakeTimers';
- timerIndex += 1;
- }
- if (fakeTimers) continue;
+ if (timerStateAt(wait.index, timerEvents, scopes)) continue;
if (Number(wait.duration.replaceAll('_', '')) < REAL_WAIT_MIN_MS) continue;
const line = lineOf(code, wait.index);
if (!hasJustification(lines, line, 'real-wait')) count += 1;