Skip to content

Commit 4564386

Browse files
authored
fix(test): isolate shared state between test files (#118781)
* fix(test): isolate session suspension state * fix(test): isolate nonzero worker exit coverage * fix(test): keep suspension reset generations monotonic * fix(test): isolate archived session UI mocks * fix(deps): patch fast-uri and undici advisories * fix(test): isolate stateful UI suites
1 parent 32c5f02 commit 4564386

7 files changed

Lines changed: 132 additions & 1 deletion

‎pnpm-lock.yaml‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,7 @@ overrides:
128128
"@hono/node-server": 2.0.12
129129
axios: 1.18.1
130130
fast-uri: 4.1.2
131+
"undici@7": 7.29.0
131132
follow-redirects: 1.16.0
132133
defu: 6.1.7
133134
fast-xml-parser: 5.10.1

‎src/agents/session-suspension.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,33 @@ describe("session suspension", () => {
353353
expect(commandQueueMocks.setCommandLaneConcurrency).not.toHaveBeenCalled();
354354
});
355355

356+
it("does not let a pending suspension regain ownership after test state resets", async () => {
357+
let resolvePatch: (() => void) | undefined;
358+
let writtenQuotaSuspension: unknown;
359+
sessionAccessorMocks.patchSessionEntry.mockImplementationOnce(async (_scope, update) => {
360+
await new Promise<void>((resolve) => {
361+
resolvePatch = resolve;
362+
});
363+
const patch = update({});
364+
writtenQuotaSuspension = patch?.quotaSuspension;
365+
return patch;
366+
});
367+
368+
const suspension = suspendLane(100, {} as OpenClawConfig, CommandLane.Main);
369+
await vi.waitFor(() => {
370+
expect(resolvePatch).toBeTypeOf("function");
371+
});
372+
373+
const { resetSessionSuspensionStateForTest } =
374+
await import("./session-suspension.test-support.js");
375+
resetSessionSuspensionStateForTest();
376+
resolvePatch?.();
377+
await suspension;
378+
379+
expect(writtenQuotaSuspension).toBeUndefined();
380+
expect(commandQueueMocks.setCommandLaneConcurrency).not.toHaveBeenCalled();
381+
});
382+
356383
it("serializes suspension writes so cleanup cannot leave an intermediate write", async () => {
357384
vi.useFakeTimers();
358385
vi.setSystemTime(1_000);

‎src/agents/session-suspension.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -451,6 +451,9 @@ async function suspendSessionQueued(params: SessionSuspensionParams, queuedGener
451451

452452
function resetSessionSuspensionStateForTest(): void {
453453
const state = getSessionSuspensionState();
454+
// Invalidate in-flight writes before clearing test state. Rewinding to a
455+
// reused generation lets a fire-and-forget suspension regain ownership.
456+
state.cleanupGeneration += 1;
454457
for (const entry of state.laneResumeTimers.values()) {
455458
clearTimeout(entry.timer);
456459
}
@@ -459,7 +462,6 @@ function resetSessionSuspensionStateForTest(): void {
459462
state.gatewayLaneResumeConcurrencies.clear();
460463
state.pendingSuspensionWrites.clear();
461464
state.suspensionWriteChain = Promise.resolve();
462-
state.cleanupGeneration = 0;
463465
state.cleanupActive = false;
464466
}
465467

‎test/non-isolated-runner.test.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,88 @@ it("clears named plugin runtime slots between files", async () => {
195195
await fs.rm(root, { recursive: true, force: true });
196196
}
197197
});
198+
199+
it("clears session suspension state between files", async () => {
200+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-session-suspension-runner-"));
201+
try {
202+
const write = (name: string, content: string) =>
203+
fs.writeFile(path.join(root, name), content, "utf-8");
204+
const sessionSuspensionPath = JSON.stringify(
205+
path.join(repoRoot, "src", "agents", "session-suspension.ts"),
206+
);
207+
const sessionSuspensionTestSupportPath = JSON.stringify(
208+
path.join(repoRoot, "src", "agents", "session-suspension.test-support.ts"),
209+
);
210+
const sharedVitestConfigPath = JSON.stringify(
211+
path.join(repoRoot, "test", "vitest", "vitest.shared.config.ts"),
212+
);
213+
await fs.symlink(
214+
path.join(repoRoot, "node_modules"),
215+
path.join(root, "node_modules"),
216+
"junction",
217+
);
218+
await write(
219+
"a-seed.test.ts",
220+
[
221+
`import { getSuspendedLaneIdsForGatewayPublication } from ${sessionSuspensionPath};`,
222+
`import { seedClearedLaneResumeForTest } from ${sessionSuspensionTestSupportPath};`,
223+
'import { expect, it } from "vitest";',
224+
'const laneId = "plugin:test:session-suspension";',
225+
'it("seeds real process-global suspension state", () => {',
226+
" seedClearedLaneResumeForTest(laneId, {",
227+
" resumeConcurrency: 1,",
228+
" resumeAtMs: Date.now() + 10_000,",
229+
" });",
230+
" expect(getSuspendedLaneIdsForGatewayPublication()).toContain(laneId);",
231+
"});",
232+
"",
233+
].join("\n"),
234+
);
235+
await write(
236+
"b-observe.test.ts",
237+
[
238+
`import { getSuspendedLaneIdsForGatewayPublication } from ${sessionSuspensionPath};`,
239+
'import { expect, it } from "vitest";',
240+
'it("starts without real suspension state from the previous file", () => {',
241+
" expect(getSuspendedLaneIdsForGatewayPublication()).toEqual(new Set());",
242+
"});",
243+
"",
244+
].join("\n"),
245+
);
246+
await write(
247+
"vitest.config.ts",
248+
[
249+
`import { sharedVitestConfig } from ${sharedVitestConfigPath};`,
250+
'import { defineConfig } from "vitest/config";',
251+
'import { BaseSequencer } from "vitest/node";',
252+
"class AlphabeticalSequencer extends BaseSequencer {",
253+
' override async sort(files: Parameters<BaseSequencer["sort"]>[0]) {',
254+
" return [...files].sort((a, b) => a.moduleId.localeCompare(b.moduleId));",
255+
" }",
256+
"}",
257+
"export default defineConfig({",
258+
` cacheDir: ${JSON.stringify(path.join(root, ".vite"))},`,
259+
" resolve: sharedVitestConfig.resolve,",
260+
" test: {",
261+
" isolate: false,",
262+
" fileParallelism: false,",
263+
" maxWorkers: 1,",
264+
" sequence: { sequencer: AlphabeticalSequencer },",
265+
` runner: ${JSON.stringify(path.join(repoRoot, "test", "non-isolated-runner.ts"))},`,
266+
" },",
267+
"});",
268+
"",
269+
].join("\n"),
270+
);
271+
272+
const vitestEntry = path.join(repoRoot, "node_modules", "vitest", "vitest.mjs");
273+
const result = await execFileAsync(
274+
process.execPath,
275+
[vitestEntry, "run", "--root", root, "--config", path.join(root, "vitest.config.ts")],
276+
{ cwd: repoRoot, env: childEnv(), maxBuffer: 16 * 1024 * 1024 },
277+
);
278+
expect(`${result.stdout}\n${result.stderr}`).toContain("2 passed");
279+
} finally {
280+
await fs.rm(root, { recursive: true, force: true });
281+
}
282+
});

‎test/non-isolated-runner.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const DIAGNOSTIC_EVENTS_STATE = Symbol.for("openclaw.diagnosticEvents.state.v1")
3232
const DIAGNOSTIC_EVENT_LISTENER_PRESENCE = Symbol.for(
3333
"openclaw.diagnosticEventListenerPresence.v1",
3434
);
35+
const SESSION_SUSPENSION_TEST_API = Symbol.for("openclaw.sessionSuspensionTestApi");
3536
const nativeTimerGlobals = {
3637
setTimeout: globalThis.setTimeout,
3738
clearTimeout: globalThis.clearTimeout,
@@ -151,6 +152,10 @@ type DiagnosticEventsStateForTest = {
151152
asyncQueue?: unknown[];
152153
};
153154

155+
type SessionSuspensionTestApi = {
156+
resetSessionSuspensionStateForTest?: () => void;
157+
};
158+
154159
function runCleanupActions(actions: CleanupAction[]): unknown {
155160
let firstError: unknown;
156161
for (const action of actions) {
@@ -247,6 +252,12 @@ function resetOpenClawGlobalDiagnosticState(): void {
247252
}
248253
}
249254

255+
function resetOpenClawSessionSuspensionState(): void {
256+
const globalStore = globalThis as Record<PropertyKey, unknown>;
257+
const api = globalStore[SESSION_SUSPENSION_TEST_API] as SessionSuspensionTestApi | undefined;
258+
api?.resetSessionSuspensionStateForTest?.();
259+
}
260+
250261
const SERIALIZED_RESOLVE_MOCKS = Symbol.for("openclaw.serializedResolveMocks");
251262

252263
// Vitest's BareModuleMocker.resolveMocks has no in-flight guard: pendingIds is
@@ -364,6 +375,7 @@ export default class OpenClawNonIsolatedRunner extends TestRunner {
364375
vi.clearAllMocks();
365376
resetOpenClawGlobalRunState();
366377
resetOpenClawGlobalDiagnosticState();
378+
resetOpenClawSessionSuspensionState();
367379
// Named plugin runtimes intentionally survive duplicate module evaluation in production.
368380
// Clear their shared slots here so one test file cannot lend a partial runtime to the next.
369381
clearNamedPluginRuntimeStoresForTest();

‎test/vitest/vitest.ui-isolated-paths.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export const uiIsolatedTestFiles = [
77
"ui/src/app/router-outlet.test.ts",
88
"ui/src/components/resizable-divider.test.ts",
99
"ui/src/components/viewer-facepile.test.ts",
10+
"ui/src/pages/agents/memory/memory-panel.test.ts",
1011
"ui/src/pages/chat/chat-pane-board.test.ts",
1112
"ui/src/pages/chat/chat-pane-history.test.ts",
1213
"ui/src/pages/chat/chat-pane-identity.test.ts",
@@ -17,8 +18,10 @@ export const uiIsolatedTestFiles = [
1718
"ui/src/pages/chat/chat-pane.session-discussion.test.ts",
1819
"ui/src/pages/chat/chat-pane.test.ts",
1920
"ui/src/pages/chat/components/chat-thread.measure.test.ts",
21+
"ui/src/pages/config/config-page.custom-theme.test.ts",
2022
"ui/src/pages/config/memory-mutation-owner.test.ts",
2123
"ui/src/pages/config/memory-page.test.ts",
24+
"ui/src/pages/sessions/sessions-page.archived.test.ts",
2225
"ui/src/pages/workboard/view.test.ts",
2326
];
2427

0 commit comments

Comments
 (0)