@devries-cameron20 / t3code-1 / commits / bde62061d2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

test(server): ban real-clock waits in tests (#22564)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 20, 2026 at 18:05 UTC bde62061d2a2074d250b1715da5eaacc50ec6a71
18 files changed +680 -106
apps/desktop/src/preview/CdpRelay.test.ts
+1
@@ -15,6 +15,7 @@ const makeTarget = (
15 });
16
17 // Each relay reply resolves after a few microtasks; one macrotask lets them all land.
18 +// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
19 const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
20
21 describe("CDP relay", () => {
apps/desktop/src/preview/DesktopBrowserHost.test.ts
-1
@@ -82,7 +82,6 @@ describe("DesktopBrowserHost", () => {
82 yield* host.handleCommandLine(encodeJson({ type: "release", ...key }));
83 yield* command(2, "DOM.enable");
84 debuggee.release();
85 - yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
85 const [, reply] = yield* Fiber.join(reader);
86
87 expect(reply).toMatchObject({ type: "cdp" });
apps/desktop/src/preview/Passkeys.test.ts
+6 -2
@@ -257,9 +257,13 @@ describe("PreviewPasskeys", () => {
257
258 page.state.focused = true;
259 let finish: (value: unknown) => void = () => {};
260 - webauthn.getCredential.mockReturnValueOnce(new Promise((resolve) => (finish = resolve)));
260 + const ceremonyStarted = Promise.withResolvers<void>();
261 + webauthn.getCredential.mockImplementationOnce(() => {
262 + ceremonyStarted.resolve();
263 + return new Promise((resolve) => (finish = resolve));
264 + });
265 const first = yield* Effect.forkChild(page.call(PASSKEY_GET_CHANNEL, publicKey));
262 - yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
266 + yield* Effect.promise(() => ceremonyStarted.promise);
267 assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed);
268
269 page.mainFrame.origin = "https://other.example";
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+14 -5
@@ -405,15 +405,24 @@ describe("makeRelayDeviceRegistrationRequest", () => {
405 yield* Effect.promise(() => oldRequestArrived);
406
407 tokenListener?.({ pushToken: "rotated-activity-token" });
408 - const listenerRegistration = yield* Effect.forkChild(runBackgroundOperations());
409 - for (let pass = 0; pass < 5; pass++) {
410 - yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
411 - }
408 + const deviceIdLookups = vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls.length;
409 + const rotated = backgroundRuntime.pending.shift()!;
410 + // Starting immediately runs the listener's registration until it suspends: on the
411 + // activity lock, or, without one, at its device-id lookup.
412 + const rotatedRegistration = yield* Effect.forkChild(
413 + Effect.exit(
414 + rotated.operation as Effect.Effect<unknown, unknown, ManagedRelay.ManagedRelayClient>,
415 + ),
416 + { startImmediately: true },
417 + );
418 + expect(vi.mocked(loadOrCreateAgentAwarenessDeviceId).mock.calls).toHaveLength(
419 + deviceIdLookups,
420 + );
421 expect(arrivals).toEqual(["activity-token"]);
422
423 openOldRequest?.();
424 yield* Fiber.join(lookup);
416 - yield* Fiber.join(listenerRegistration);
425 + rotated.resolve(yield* Fiber.join(rotatedRegistration));
426 expect(arrivals).toEqual(["activity-token", "rotated-activity-token"]);
427 }).pipe(
428 Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
apps/server/src/orchestration-v2/legacy/LegacyV1Cutover.integration.test.ts
+22 -11
@@ -559,18 +559,29 @@ const makeCodexAdapter = (capturedTurns: Ref.Ref<ReadonlyArray<CapturedTurn>>) =
559
560 const waitForIdle = Effect.fn("LegacyV1Cutover.waitForIdle")(function* (threadId: ThreadId) {
561 const orchestrator = yield* Orchestrator.OrchestratorV2;
562 - for (let attempt = 0; attempt < 1_000; attempt += 1) {
563 - const projection = yield* orchestrator.getThreadProjection(threadId);
564 - if (
565 - projection.runs.every(
566 - (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
567 - )
568 - ) {
569 - return projection;
570 - }
571 - yield* Effect.sleep("5 millis");
562 + const eventSink = yield* EventSink.EventSinkV2;
563 + const isIdle = (projection: OrchestrationV2ThreadProjection) =>
564 + projection.runs.every(
565 + (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
566 + );
567 + const afterSequence = yield* eventSink.latestSequence();
568 + const current = yield* orchestrator.getThreadProjection(threadId);
569 + if (isIdle(current)) {
570 + return current;
571 }
573 - return yield* Effect.die(new Error("Cutover test timed out waiting for idle"));
572 + // Projections commit with their events, so each later event is the only time to re-read.
573 + const [idle] = yield* eventSink.stream({ afterSequence }).pipe(
574 + Stream.mapEffect(() => orchestrator.getThreadProjection(threadId)),
575 + Stream.filter(isIdle),
576 + Stream.take(1),
577 + Stream.runCollect,
578 + );
579 + if (idle === undefined) {
580 + return yield* Effect.die(
581 + new Error("Cutover test event stream ended before the thread went idle"),
582 + );
583 + }
584 + return idle;
585 });
586
587 const layerBoot = (input: {
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+23 -11
@@ -12,6 +12,7 @@ import {
12 type OrchestrationV2ProviderSession,
13 type OrchestrationV2ProviderThread,
14 type OrchestrationV2ProviderTurnTokenUsage,
15 + type OrchestrationV2ThreadProjection,
16 ProjectId,
17 ProviderInstanceId,
18 ProviderSessionId,
@@ -379,18 +380,29 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
380 targetThreadId: ThreadId,
381 ) {
382 const orchestrator = yield* Orchestrator.OrchestratorV2;
382 - for (let attempt = 0; attempt < 1_000; attempt += 1) {
383 - const projection = yield* orchestrator.getThreadProjection(targetThreadId);
384 - if (
385 - projection.runs.every(
386 - (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
387 - )
388 - ) {
389 - return projection;
390 - }
391 - yield* Effect.sleep("5 millis");
383 + const eventSink = yield* EventSink.EventSinkV2;
384 + const isIdle = (projection: OrchestrationV2ThreadProjection) =>
385 + projection.runs.every(
386 + (run) => !["queued", "starting", "running", "waiting"].includes(run.status),
387 + );
388 + const afterSequence = yield* eventSink.latestSequence();
389 + const current = yield* orchestrator.getThreadProjection(targetThreadId);
390 + if (isIdle(current)) {
391 + return current;
392 + }
393 + // Projections commit with their events, so each later event is the only time to re-read.
394 + const [idle] = yield* eventSink.stream({ afterSequence }).pipe(
395 + Stream.mapEffect(() => orchestrator.getThreadProjection(targetThreadId)),
396 + Stream.filter(isIdle),
397 + Stream.take(1),
398 + Stream.runCollect,
399 + );
400 + if (idle === undefined) {
401 + return yield* Effect.die(
402 + new Error("Provider switch test event stream ended before the thread went idle"),
403 + );
404 }
393 - return yield* Effect.die(new Error("Provider switch test timed out waiting for idle"));
405 + return idle;
406 });
407
408 describe("orchestration v2 provider switching", () => {
apps/server/src/preview/ServerBrowser.test.ts
+9 -2
@@ -390,13 +390,20 @@ it.live.each([
390 });
391 const navigation = yield* viewer.input(message).pipe(Effect.forkScoped);
392 yield* Effect.promise(() => started.promise);
393 + const cdp = contexts[0]!.sessions.at(-1)!;
394 + const send = cdp.send.getMockImplementation()!;
395 + const typed = Promise.withResolvers<void>();
396 + cdp.send.mockImplementation(async (operation, input) => {
397 + if (operation === "Input.insertText") typed.resolve();
398 + return send(operation, input);
399 + });
400 const correction = yield* Effect.gen(function* () {
401 yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" });
402 yield* viewer.input({ type: "text", text: "hello" });
403 }).pipe(Effect.forkScoped);
404 yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve()));
398 - // Check after runnable promises drain, without waiting for navigation or a timeout.
399 - yield* Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
405 + // The text reaches the page while the first navigation is still uncommitted.
406 + yield* Effect.promise(() => typed.promise);
407 expect(page.goto).toHaveBeenLastCalledWith(
408 "http://localhost:5173/fixed",
409 expect.objectContaining({ waitUntil: "commit" }),
apps/server/src/preview/ServerBrowserPage.test.ts
+4 -2
@@ -273,8 +273,10 @@ describe("server browser drag", () => {
273 );
274 void settled.then(() => (finished = true));
275 // Two macrotask turns: Node reports a rejection nobody observed after the first.
276 - await new Promise((resolve) => setImmediate(resolve));
277 - await new Promise((resolve) => setImmediate(resolve));
276 + for (let turn = 0; turn < 2; turn++) {
277 + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point.
278 + await new Promise((resolve) => setImmediate(resolve));
279 + }
280 expect(finished).toBe(false);
281 targetBox.resolve(box);
282
apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
+36 -19
@@ -7,7 +7,8 @@ import * as Fiber from "effect/Fiber";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 import * as Ref from "effect/Ref";
10 -import * as Schedule from "effect/Schedule";
10 +import * as Queue from "effect/Queue";
11 +import * as Tracer from "effect/Tracer";
12 import {
13 ProjectId,
14 GitCommandError,
@@ -223,18 +224,33 @@ const layerBase = Layer.mergeAll(
224
225 type Repositories = Effect.Success<typeof makeRepositories>;
226
226 -const awaitRunFailure = (
227 - service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
228 - input: PullRequestRef,
229 -) =>
230 - service.get(input).pipe(
231 - Effect.flatMap((result) =>
232 - result.run?._tag === "Failed"
233 - ? Effect.succeed(result.run.detail)
234 - : Effect.fail("still running" as const),
235 - ),
236 - Effect.retry(Schedule.spaced("20 millis")),
237 - );
227 +// A run forks into the service's scope, so a test learns it settled when the run's `write` span
228 +// ends; the run records its outcome synchronously right after.
229 +const watchRuns = Effect.gen(function* () {
230 + const ended = yield* Queue.unbounded<void>();
231 + const tracer = Tracer.make({
232 + span: (options) => {
233 + const span = new Tracer.NativeSpan(options);
234 + if (options.name !== "PullRequestReviewGuideService.write") return span;
235 + const end = span.end.bind(span);
236 + span.end = (endTime, exit) => {
237 + end(endTime, exit);
238 + Queue.offerUnsafe(ended, undefined);
239 + };
240 + return span;
241 + },
242 + });
243 + return {
244 + generate: (
245 + service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
246 + input: PullRequestRef,
247 + ) => service.generate(input).pipe(Effect.withTracer(tracer)),
248 + settled: (
249 + service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"],
250 + input: PullRequestRef,
251 + ) => Queue.take(ended).pipe(Effect.andThen(service.get(input))),
252 + };
253 +});
254
255 const startSingleBranchRun = (input: {
256 readonly repositoryName: string;
@@ -330,7 +346,8 @@ const startSingleBranchRun = (input: {
346 PullRequestReviewGuideService.PullRequestReviewGuideService,
347 );
348 const guideReference = { ...reference, repository: `acme/${input.repositoryName}` };
333 - yield* service.generate(guideReference);
349 + const runs = yield* watchRuns;
350 + yield* runs.generate(service, guideReference);
351 return {
352 repositories,
353 reportedHead,
@@ -339,10 +356,10 @@ const startSingleBranchRun = (input: {
356 stored,
357 fetchedRefs,
358 observed,
359 + settled: runs.settled(service, guideReference),
360 };
361 });
362
345 -// Runs drive real git, which the test clock does not advance, so waits use real time.
363 it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => {
364 it.effect.each([
365 {
@@ -393,10 +410,10 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
410 Effect.asVoid,
411 ),
412 });
396 - const detail = yield* Effect.raceFirst(
397 - awaitRunFailure(run.service, run.reference),
398 - Deferred.await(run.stored).pipe(Effect.andThen(Effect.die("a guide was written"))),
399 - );
413 + const result = yield* run.settled;
414 + assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
415 + assert.strictEqual(result.run?._tag, "Failed");
416 + const detail = result.run?._tag === "Failed" ? result.run.detail : "";
417 for (const part of expected) assert.include(detail, part);
418 assert.deepStrictEqual(run.observed, []);
419 assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
apps/server/src/terminal/Manager.test.ts
+9 -32
@@ -12,20 +12,16 @@ import {
12 TerminalProviderInstanceNotFoundError,
13 } from "@t3tools/contracts";
14 import * as HostProcess from "@t3tools/shared/HostProcess";
15 -import * as Data from "effect/Data";
15 import * as Deferred from "effect/Deferred";
17 -import * as Duration from "effect/Duration";
16 import * as Effect from "effect/Effect";
17 import * as Base64Url from "effect/encoding/Base64Url";
18 import * as Exit from "effect/Exit";
19 import * as Fiber from "effect/Fiber";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Layer from "effect/Layer";
24 -import * as Option from "effect/Option";
22 import * as PlatformError from "effect/PlatformError";
23 import * as Path from "effect/Path";
24 import * as Ref from "effect/Ref";
28 -import * as Schedule from "effect/Schedule";
25 import * as Schema from "effect/Schema";
26 import * as Scope from "effect/Scope";
27 import * as Stream from "effect/Stream";
@@ -50,10 +46,6 @@ vi.mock("effect/SynchronizedRef", async (importOriginal) => {
46
47 const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
48
53 -class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
54 - readonly message: string;
55 -}> {}
56 -
49 class FakePtyProcess implements PtyAdapter.PtyProcess {
50 readonly writes: string[] = [];
51 readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
@@ -205,26 +197,6 @@ class GatedPtyAdapter extends FakePtyAdapter {
197 }
198 }
199
208 -const waitFor = <E, R>(
209 - predicate: Effect.Effect<boolean, E, R>,
210 - timeout: Duration.Input = 800,
211 -): Effect.Effect<void, WaitForConditionError | E, R> =>
212 - predicate.pipe(
213 - Effect.filterOrFail(
214 - (done) => done,
215 - () => new WaitForConditionError({ message: "Condition not met" }),
216 - ),
217 - Effect.retry(Schedule.spaced("15 millis")),
218 - Effect.timeoutOption(timeout),
219 - Effect.flatMap((result) =>
220 - Option.match(result, {
221 - onNone: () =>
222 - Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })),
223 - onSome: () => Effect.void,
224 - }),
225 - ),
226 - );
227 -
200 function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
201 return {
202 threadId: "thread-1",
@@ -773,7 +745,7 @@ it.layer(
745 Effect.gen(function* () {
746 const ptyAdapter = new FakePtyAdapter();
747 let duringCheck: (pid: number) => Effect.Effect<void> = () => Effect.void;
776 - const { manager, getEvents } = yield* createManager(5, {
748 + const { manager } = yield* createManager(5, {
749 ptyAdapter,
750 subprocessPollIntervalMs: 60_000,
751 subprocessInspector: (pid) =>
@@ -781,6 +753,13 @@ it.layer(
753 Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }),
754 ),
755 });
756 + const outputSeen = yield* Deferred.make<void>();
757 + const unsubscribeOutput = yield* manager.subscribe((event) =>
758 + event.type === "output"
759 + ? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid)
760 + : Effect.void,
761 + );
762 + yield* Effect.addFinalizer(() => Effect.sync(unsubscribeOutput));
763 yield* manager.open(openInput({ terminalId: "typed" }));
764 yield* manager.open(openInput({ terminalId: "echoed" }));
765 const [typed, echoed] = ptyAdapter.processes;
@@ -791,9 +770,7 @@ it.layer(
770 .pipe(Effect.orDie)
771 : Effect.gen(function* () {
772 echoed!.emitData("make build\r\n");
794 - yield* waitFor(
795 - Effect.map(getEvents, (events) => events.some((event) => event.type === "output")),
796 - );
773 + yield* Deferred.await(outputSeen);
774 }).pipe(Effect.orDie);
775
776 yield* manager.closeIdle({ threadId: "thread-1" });
oxlint-plugin-t3code/index.ts
+2
@@ -16,6 +16,7 @@ import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
16 import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";
17 import noRawMcpRegistration from "./rules/no-raw-mcp-registration.ts";
18 import noRawResizeObserver from "./rules/no-raw-resize-observer.ts";
19 +import noRealTimeWaitInTests from "./rules/no-real-time-wait-in-tests.ts";
20 import noTestInLoop from "./rules/no-test-in-loop.ts";
21 import noTestTimeoutOrUnreasonedSkip from "./rules/no-test-timeout-or-unreasoned-skip.ts";
22 import noRpcPermissionBypass from "./rules/no-rpc-permission-bypass.ts";
@@ -48,6 +49,7 @@ export default definePlugin({
49 "no-outset-state-indicators": noOutsetStateIndicators,
50 "no-raw-mcp-registration": noRawMcpRegistration,
51 "no-raw-resize-observer": noRawResizeObserver,
52 + "no-real-time-wait-in-tests": noRealTimeWaitInTests,
53 "no-test-in-loop": noTestInLoop,
54 "no-test-timeout-or-unreasoned-skip": noTestTimeoutOrUnreasonedSkip,
55 "no-rpc-permission-bypass": noRpcPermissionBypass,
oxlint-plugin-t3code/rules/no-real-time-wait-in-tests.test.ts new
+268
@@ -0,0 +1,268 @@
1 +import { assert, describe } from "@effect/vitest";
2 +
3 +import { createOxlintRuleHarness } from "../test/utils.ts";
4 +
5 +const rule = createOxlintRuleHarness("t3code/no-real-time-wait-in-tests", {
6 + filename: "fixture.test.ts",
7 +});
8 +
9 +const REAL_CLOCK = /Real-clock wait in a test/;
10 +const UNDRIVEN = /never fire without `TestClock.adjust`/;
11 +const MIXED = /they never meet/;
12 +
13 +describe("t3code/no-real-time-wait-in-tests", () => {
14 + rule.valid(
15 + "allows TestClock-driven sleeps and timeout safety nets",
16 + `
17 + import { it } from "@effect/vitest";
18 + import * as Effect from "effect/Effect";
19 + import * as TestClock from "effect/testing/TestClock";
20 +
21 + it.effect("fires after a minute", () =>
22 + Effect.gen(function* () {
23 + const fiber = yield* Effect.sleep("1 minute").pipe(Effect.forkChild);
24 + yield* TestClock.adjust("1 minute");
25 + yield* fiber.await;
26 + }),
27 + );
28 +
29 + it.live("spawns a fixture", () => Effect.void.pipe(Effect.timeout("5 seconds")));
30 + `,
31 + );
32 +
33 + rule.valid(
34 + "ignores sleeps inside strings and child-process script templates",
35 + `
36 + import { it } from "@effect/vitest";
37 + import * as Effect from "effect/Effect";
38 +
39 + it.live("runs a script", () =>
40 + Effect.sync(() => [
41 + "setTimeout(() => process.exit(0), 50)",
42 + \`await new Promise((resolve) => setTimeout(resolve, 10)); Effect.sleep(1)\`,
43 + ]),
44 + );
45 + `,
46 + );
47 +
48 + rule.valid(
49 + "ignores shared helpers in files that drive the TestClock",
50 + `
51 + import { it } from "@effect/vitest";
52 + import * as Effect from "effect/Effect";
53 + import * as TestClock from "effect/testing/TestClock";
54 +
55 + const slowStep = (delay: number) =>
56 + Effect.gen(function* () {
57 + if (delay > 0) yield* Effect.sleep(delay);
58 + });
59 +
60 + it.effect("advances", () => slowStep(5).pipe(Effect.andThen(TestClock.adjust(5))));
61 + `,
62 + );
63 +
64 + rule.valid(
65 + "ignores bare setTimeout callbacks outside promise executors",
66 + `
67 + import { it } from "vitest";
68 +
69 + it("schedules work", () => {
70 + const handle = setTimeout(() => {}, 1000);
71 + clearTimeout(handle);
72 + });
73 + `,
74 + );
75 +
76 + rule.invalid(
77 + "reports Effect.sleep under it.live",
78 + `
79 + import { it } from "@effect/vitest";
80 + import * as Effect from "effect/Effect";
81 +
82 + it.live("waits", () => Effect.sleep("50 millis"));
83 + `,
84 + (output) => {
85 + assert.match(output, REAL_CLOCK);
86 + },
87 + );
88 +
89 + rule.invalid(
90 + "reports retry schedules under curried testers",
91 + `
92 + import { it } from "@effect/vitest";
93 + import * as Effect from "effect/Effect";
94 + import * as Schedule from "effect/Schedule";
95 +
96 + it.live.skipIf(false)("polls", () =>
97 + Effect.void.pipe(Effect.retry(Schedule.spaced("10 millis"))),
98 + );
99 + `,
100 + (output) => {
101 + assert.match(output, REAL_CLOCK);
102 + },
103 + );
104 +
105 + rule.invalid(
106 + "reports Effect.delay under plain it",
107 + `
108 + import { it } from "vitest";
109 + import * as Effect from "effect/Effect";
110 +
111 + it("delays", async () => {
112 + await Effect.runPromise(Effect.void.pipe(Effect.delay("10 millis")));
113 + });
114 + `,
115 + (output) => {
116 + assert.match(output, REAL_CLOCK);
117 + },
118 + );
119 +
120 + rule.invalid(
121 + "reports it.effect inside an excludeTestServices layer as a real-clock wait",
122 + `
123 + import { it } from "@effect/vitest";
124 + import * as Effect from "effect/Effect";
125 + import * as Layer from "effect/Layer";
126 + import * as TestClock from "effect/testing/TestClock";
127 +
128 + it.layer(Layer.empty, { excludeTestServices: true })("live services", (it) => {
129 + it.effect("waits", () => Effect.sleep("10 millis"));
130 + });
131 +
132 + it.effect("advances", () => TestClock.adjust(1));
133 + `,
134 + (output) => {
135 + assert.match(output, REAL_CLOCK);
136 + },
137 + );
138 +
139 + rule.invalid(
140 + "reports it.effect sleeps in files that never adjust the TestClock",
141 + `
142 + import { it } from "@effect/vitest";
143 + import * as Effect from "effect/Effect";
144 +
145 + it.effect("hangs", () => Effect.sleep("200 millis"));
146 + `,
147 + (output) => {
148 + assert.match(output, UNDRIVEN);
149 + },
150 + );
151 +
152 + rule.invalid(
153 + "reports polling helpers even when the file drives the TestClock",
154 + `
155 + import { it } from "@effect/vitest";
156 + import * as Effect from "effect/Effect";
157 + import * as TestClock from "effect/testing/TestClock";
158 +
159 + let ready = false;
160 + const waitUntilReady = Effect.gen(function* () {
161 + while (!ready) {
162 + yield* Effect.sleep("10 millis");
163 + }
164 + });
165 +
166 + it.effect("advances", () => TestClock.adjust(1));
167 + it.live("waits", () => waitUntilReady);
168 + `,
169 + (output) => {
170 + assert.match(output, REAL_CLOCK);
171 + },
172 + );
173 +
174 + rule.invalid(
175 + "reports promise-wrapped setTimeout in vitest tests",
176 + `
177 + import { it } from "vitest";
178 +
179 + it.each([1])("waits %s", async () => {
180 + await new Promise((resolve) => setTimeout(resolve, 10));
181 + });
182 + `,
183 + (output) => {
184 + assert.match(output, REAL_CLOCK);
185 + assert.notMatch(output, MIXED);
186 + },
187 + );
188 +
189 + rule.invalid(
190 + "reports promise-wrapped setTimeout under it.effect as a mixed clock",
191 + `
192 + import { it } from "@effect/vitest";
193 + import * as Effect from "effect/Effect";
194 +
195 + it.effect("waits", () =>
196 + Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 10))),
197 + );
198 + `,
199 + (output) => {
200 + assert.match(output, REAL_CLOCK);
201 + assert.match(output, MIXED);
202 + },
203 + );
204 +
205 + rule.invalid(
206 + "reports TestClock sleeps when TestClock.adjust appears only in a comment",
207 + `
208 + import { it } from "@effect/vitest";
209 + import * as Effect from "effect/Effect";
210 +
211 + // Callers would normally TestClock.adjust("1 minute") here.
212 + const note = "TestClock.setTime";
213 + it.effect("hangs", () => Effect.sleep("1 minute"));
214 + `,
215 + (output) => {
216 + assert.match(output, UNDRIVEN);
217 + },
218 + );
219 +
220 + rule.invalid(
221 + "reports timers hidden in module-level helpers",
222 + `
223 + import { setTimeout as delay } from "node:timers/promises";
224 + import { it } from "vitest";
225 +
226 + const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
227 + const pause = () => delay(10);
228 +
229 + it("waits", async () => {
230 + await sleep(10);
231 + await pause();
232 + });
233 + `,
234 + (output) => {
235 + assert.equal(output.match(/Real-clock wait in a test/g)?.length, 2);
236 + assert.notMatch(output, MIXED);
237 + },
238 + );
239 +
240 + rule.invalid(
241 + "reports awaited timers/promises sleeps",
242 + `
243 + import * as NodeTimers from "node:timers/promises";
244 + import { setTimeout as sleep } from "node:timers/promises";
245 + import { it } from "vitest";
246 +
247 + it("waits", async () => {
248 + await NodeTimers.setTimeout(10);
249 + await sleep(10);
250 + });
251 + `,
252 + (output) => {
253 + assert.equal(output.match(/Real-clock wait in a test/g)?.length, 2);
254 + },
255 + );
256 +});
257 +
258 +const productionRule = createOxlintRuleHarness("t3code/no-real-time-wait-in-tests");
259 +
260 +productionRule.valid(
261 + "ignores non-test files",
262 + `
263 + import * as Effect from "effect/Effect";
264 +
265 + const it = { live: (_name: string, run: () => unknown) => run() };
266 + it.live("waits", () => Effect.sleep("1 second"));
267 + `,
268 +);
oxlint-plugin-t3code/rules/no-real-time-wait-in-tests.ts new
+277
@@ -0,0 +1,277 @@
1 +import { defineRule, type ESTree } from "@oxlint/plugins";
2 +import * as Option from "effect/Option";
3 +
4 +import { getPropertyName, isIdentifier, unwrapExpression } from "../utils.ts";
5 +
6 +const TEST_FILE_PATTERN = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
7 +const TEST_CLOCK_DRIVERS = new Set(["adjust", "setTime"]);
8 +const TIMER_PROMISES_MODULES = new Set(["node:timers/promises", "timers/promises"]);
9 +const TIMER_FUNCTIONS = new Set(["setTimeout", "setInterval", "setImmediate"]);
10 +const SCHEDULE_WAITS = new Set(["spaced", "fixed", "exponential"]);
11 +const TESTER_ROOTS = new Set(["it", "test"]);
12 +const FUNCTIONS = new Set(["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"]);
13 +
14 +const REAL_CLOCK_MESSAGE =
15 + "Real-clock wait in a test. Await the `Deferred`/`Queue`/event that marks the milestone, or run under `it.effect` and `TestClock.adjust`. `it.live` is for subprocess/network fixtures, not for sleeping.";
16 +const UNDRIVEN_TEST_CLOCK_MESSAGE =
17 + "Sleeps on the TestClock never fire without `TestClock.adjust`; this test can only time out.";
18 +const MIXED_CLOCK_MESSAGE =
19 + "`setTimeout` is wall-clock while `Effect.sleep` here is TestClock; they never meet.";
20 +
21 +type Tester = "effect" | "live" | "plain";
22 +
23 +interface CalleeChain {
24 + readonly root: string;
25 + readonly members: ReadonlyArray<string>;
26 + readonly calls: ReadonlyArray<ESTree.CallExpression>;
27 +}
28 +
29 +// Flattens `it.live.skipIf(cond)` or `it.layer(L, opts)` into the root name, the member
30 +// names, and the curried calls whose arguments carry options like `excludeTestServices`.
31 +const calleeChain = (callee: unknown): Option.Option<CalleeChain> => {
32 + const members: Array<string> = [];
33 + const calls: Array<ESTree.CallExpression> = [];
34 + let current = unwrapExpression(callee);
35 + while (Option.isSome(current)) {
36 + const node = current.value;
37 + if (node.type === "Identifier") {
38 + return Option.some({ root: node.name, members: members.toReversed(), calls });
39 + }
40 + if (node.type === "CallExpression") {
41 + calls.push(node);
42 + current = unwrapExpression(node.callee);
43 + continue;
44 + }
45 + if (node.type === "MemberExpression") {
46 + const name = getPropertyName(node.property);
47 + if (Option.isNone(name)) return Option.none();
48 + members.push(name.value);
49 + current = unwrapExpression(node.object);
50 + continue;
51 + }
52 + return Option.none();
53 + }
54 + return Option.none();
55 +};
56 +
57 +const isLayerBlock = (chain: CalleeChain) =>
58 + chain.root === "layer" || (TESTER_ROOTS.has(chain.root) && chain.members.includes("layer"));
59 +
60 +const testerKind = (chain: CalleeChain): Option.Option<Tester> => {
61 + if (!TESTER_ROOTS.has(chain.root) || chain.members.includes("layer")) return Option.none();
62 + if (chain.members.includes("live") || chain.members.includes("scopedLive")) {
63 + return Option.some("live");
64 + }
65 + if (chain.members.includes("effect") || chain.members.includes("scoped")) {
66 + return Option.some("effect");
67 + }
68 + return Option.some("plain");
69 +};
70 +
71 +const excludesTestServices = (chain: CalleeChain) =>
72 + chain.calls.some((call) =>
73 + call.arguments.some((argument) => {
74 + const expression = unwrapExpression(argument);
75 + if (Option.isNone(expression) || expression.value.type !== "ObjectExpression") return false;
76 + return expression.value.properties.some((property) => {
77 + if (property.type !== "Property") return false;
78 + const key = getPropertyName(property.key);
79 + const value = unwrapExpression(property.value);
80 + return (
81 + Option.isSome(key) &&
82 + key.value === "excludeTestServices" &&
83 + Option.isSome(value) &&
84 + value.value.type === "Literal" &&
85 + value.value.value === true
86 + );
87 + });
88 + }),
89 + );
90 +
91 +// The clock a call runs on: the nearest enclosing test call decides, and an enclosing
92 +// `it.layer(_, { excludeTestServices: true })` block strips the TestClock from `it.effect`.
93 +const enclosingTester = (node: ESTree.Node): Option.Option<Tester> => {
94 + let child: ESTree.Node = node;
95 + let current = node.parent;
96 + let tester: Option.Option<Tester> = Option.none();
97 + while (current) {
98 + if (
99 + current.type === "CallExpression" &&
100 + current.arguments.some((argument) => argument === child)
101 + ) {
102 + const chain = calleeChain(current.callee);
103 + if (Option.isSome(chain)) {
104 + if (Option.isNone(tester)) {
105 + tester = testerKind(chain.value);
106 + if (Option.isSome(tester) && tester.value !== "effect") return tester;
107 + } else if (isLayerBlock(chain.value) && excludesTestServices(chain.value)) {
108 + return Option.some("live");
109 + }
110 + }
111 + }
112 + child = current;
113 + current = current.parent;
114 + }
115 + return tester;
116 +};
117 +
118 +const memberCallName = (callee: unknown): Option.Option<readonly [string, string]> => {
119 + const expression = unwrapExpression(callee);
120 + if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
121 + return Option.none();
122 + }
123 + const object = unwrapExpression(expression.value.object);
124 + const property = getPropertyName(expression.value.property);
125 + if (Option.isNone(property) || Option.isNone(object) || object.value.type !== "Identifier") {
126 + return Option.none();
127 + }
128 + return Option.some([object.value.name, property.value] as const);
129 +};
130 +
131 +const LOOPS = new Set([
132 + "DoWhileStatement",
133 + "ForInStatement",
134 + "ForOfStatement",
135 + "ForStatement",
136 + "WhileStatement",
137 +]);
138 +
139 +// `while (...) { yield* Effect.sleep(...) }`: a statement of the loop body itself, not a
140 +// conditional delay inside it.
141 +const isPollingLoopStep = (node: ESTree.Node): boolean => {
142 + let statement: ESTree.Node | null = node.parent;
143 + while (statement && statement.type !== "ExpressionStatement") {
144 + if (FUNCTIONS.has(statement.type)) return false;
145 + statement = statement.parent;
146 + }
147 + const block = statement?.parent;
148 + if (!block) return false;
149 + if (LOOPS.has(block.type)) return true;
150 + return block.type === "BlockStatement" && block.parent !== null && LOOPS.has(block.parent.type);
151 +};
152 +
153 +const isPromiseExecutor = (fn: ESTree.Node) => {
154 + const parent = fn.parent;
155 + return (
156 + parent?.type === "NewExpression" &&
157 + parent.arguments[0] === fn &&
158 + isIdentifier(unwrapExpression(parent.callee), "Promise")
159 + );
160 +};
161 +
162 +const isInsidePromiseExecutor = (node: ESTree.Node): boolean => {
163 + let current = node.parent;
164 + while (current) {
165 + if (FUNCTIONS.has(current.type)) return isPromiseExecutor(current);
166 + current = current.parent;
167 + }
168 + return false;
169 +};
170 +
171 +export default defineRule({
172 + meta: {
173 + type: "problem",
174 + docs: {
175 + description:
176 + "Disallow real-clock waits in tests; await the milestone or drive the TestClock instead.",
177 + },
178 + },
179 + create(context) {
180 + if (!TEST_FILE_PATTERN.test(context.filename)) return {};
181 + let drivesTestClock = false;
182 + // Whether the file drives the TestClock is only known after the whole file is walked.
183 + const untilDrivenReports: Array<{ node: ESTree.Node; message: string }> = [];
184 + const timerPromiseLocals = new Set<string>();
185 + const timerPromiseNamespaces = new Set<string>();
186 +
187 + const isTimerPromiseCall = (callee: unknown) => {
188 + const expression = unwrapExpression(callee);
189 + if (Option.isNone(expression)) return false;
190 + if (expression.value.type === "Identifier") {
191 + return timerPromiseLocals.has(expression.value.name);
192 + }
193 + return Option.match(memberCallName(callee), {
194 + onNone: () => false,
195 + onSome: ([object, property]) =>
196 + timerPromiseNamespaces.has(object) && TIMER_FUNCTIONS.has(property),
197 + });
198 + };
199 +
200 + const isCallbackTimer = (callee: unknown) => {
201 + const expression = unwrapExpression(callee);
202 + return (
203 + Option.isSome(expression) &&
204 + expression.value.type === "Identifier" &&
205 + TIMER_FUNCTIONS.has(expression.value.name) &&
206 + !timerPromiseLocals.has(expression.value.name)
207 + );
208 + };
209 +
210 + return {
211 + ImportDeclaration(node) {
212 + if (!TIMER_PROMISES_MODULES.has(node.source.value)) return;
213 + for (const specifier of node.specifiers) {
214 + if (specifier.type === "ImportNamespaceSpecifier") {
215 + timerPromiseNamespaces.add(specifier.local.name);
216 + } else if (specifier.type === "ImportSpecifier") {
217 + const imported = getPropertyName(specifier.imported);
218 + if (Option.isSome(imported) && TIMER_FUNCTIONS.has(imported.value)) {
219 + timerPromiseLocals.add(specifier.local.name);
220 + }
221 + }
222 + }
223 + },
224 + CallExpression(node) {
225 + const reportFor = (message: string) => context.report({ node: node.callee, message });
226 +
227 + if (
228 + isTimerPromiseCall(node.callee) ||
229 + (isCallbackTimer(node.callee) && isInsidePromiseExecutor(node))
230 + ) {
231 + const tester = enclosingTester(node);
232 + reportFor(
233 + Option.isSome(tester) && tester.value === "effect"
234 + ? `${REAL_CLOCK_MESSAGE} ${MIXED_CLOCK_MESSAGE}`
235 + : REAL_CLOCK_MESSAGE,
236 + );
237 + return;
238 + }
239 +
240 + const name = memberCallName(node.callee);
241 + if (Option.isNone(name)) return;
242 + const [object, property] = name.value;
243 + if (object === "TestClock" && TEST_CLOCK_DRIVERS.has(property)) {
244 + drivesTestClock = true;
245 + return;
246 + }
247 + const isSleep = object === "Effect" && property === "sleep";
248 + const isWait =
249 + isSleep ||
250 + (object === "Effect" && property === "delay") ||
251 + (object === "Schedule" && SCHEDULE_WAITS.has(property));
252 + if (!isWait) return;
253 +
254 + const tester = enclosingTester(node);
255 + if (Option.isNone(tester)) {
256 + // A shared helper can serve TestClock tests, so only report it when nothing in
257 + // the file drives the TestClock or it polls in a loop, which only a real clock ends.
258 + if (isPollingLoopStep(node)) {
259 + reportFor(REAL_CLOCK_MESSAGE);
260 + } else {
261 + untilDrivenReports.push({ node: node.callee, message: REAL_CLOCK_MESSAGE });
262 + }
263 + return;
264 + }
265 + if (tester.value !== "effect") {
266 + reportFor(REAL_CLOCK_MESSAGE);
267 + } else if (isSleep) {
268 + untilDrivenReports.push({ node: node.callee, message: UNDRIVEN_TEST_CLOCK_MESSAGE });
269 + }
270 + },
271 + "Program:exit"() {
272 + if (drivesTestClock) return;
273 + for (const report of untilDrivenReports) context.report(report);
274 + },
275 + };
276 + },
277 +});
packages/provider-opencode/src/server/status.test.ts
+1 -8
@@ -4,7 +4,6 @@ import * as NodeSqlite from "node:sqlite";
4 import * as NodeServices from "@effect/platform-node/NodeServices";
5 import { it } from "@effect/vitest";
6 import * as Deferred from "effect/Deferred";
7 -import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import * as Fiber from "effect/Fiber";
9 import * as FileSystem from "effect/FileSystem";
@@ -288,7 +287,6 @@ const runtimeMock = {
287 state: {
288 runVersionError: null as Error | null,
289 runVersionPending: false,
291 - runVersionDelay: null as Duration.Input | null,
290 versionStdout: DEFAULT_VERSION_STDOUT,
291 inventoryError: null as Error | null,
292 connectionError: null as Error | null,
@@ -309,7 +307,6 @@ const runtimeMock = {
307 reset() {
308 this.state.runVersionError = null;
309 this.state.runVersionPending = false;
312 - this.state.runVersionDelay = null;
310 this.state.versionStdout = DEFAULT_VERSION_STDOUT;
311 this.state.inventoryError = null;
312 this.state.connectionError = null;
@@ -384,11 +381,7 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntime.OpenCodeRuntime["Service"] = {
381 cause: runtimeMock.state.runVersionError,
382 }),
383 )
387 - : runtimeMock.state.runVersionDelay
388 - ? Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }).pipe(
389 - Effect.delay(runtimeMock.state.runVersionDelay),
390 - )
391 - : Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
384 + : Effect.succeed({ stdout: runtimeMock.state.versionStdout, stderr: "", code: 0 }),
385 createOpenCodeSdkClient: (input) => {
386 runtimeMock.state.sdkClientInputs.push(input);
387 return {} as unknown as ReturnType<
packages/provider-pi/src/server/status.test.ts
+1 -13
@@ -1,8 +1,6 @@
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import * as Cause from "effect/Cause";
4 -import * as Deferred from "effect/Deferred";
5 -import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import * as Queue from "effect/Queue";
6 import * as Schema from "effect/Schema";
@@ -54,13 +52,7 @@ function piProbeSpawner(version: string) {
52 });
53 }
54
57 -const piDiscoverySpawner = (
58 - inventory: unknown,
59 - slowStartup?: {
60 - readonly delay: Duration.Input;
61 - readonly getStateReceived: Deferred.Deferred<void>;
62 - },
63 -) =>
55 +const piDiscoverySpawner = (inventory: unknown) =>
56 Effect.gen(function* () {
57 const stdout = yield* Queue.unbounded<Uint8Array, Cause.Done>();
58 let stdinBuffer = "";
@@ -74,10 +66,6 @@ const piDiscoverySpawner = (
66 stdinBuffer = stdinBuffer.slice(newline + 1);
67 if (line.length === 0) continue;
68 const request = decodeRpcRequest(line);
77 - if (request.type === "get_state" && slowStartup !== undefined) {
78 - yield* Deferred.succeed(slowStartup.getStateReceived, undefined);
79 - yield* Effect.sleep(slowStartup.delay);
80 - }
69 const data =
70 request.type === "get_available_models"
71 ? inventory
packages/shared/src/atomicWrite.test.ts
+1
@@ -138,6 +138,7 @@ const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
138 Effect.gen(function* () {
139 while (fiber.pollUnsafe() === undefined) {
140 yield* TestClock.adjust("100 millis");
141 + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a macrotask boundary so the real stat I/O can finish; time moves only via TestClock
142 yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
143 }
144 return yield* Fiber.join(fiber);
packages/shared/src/nodeSqliteClient.test.ts
+1
@@ -327,6 +327,7 @@ it.effect("finishes masked database cleanup after its caller is interrupted", ()
327 }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))),
328 );
329
330 +// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary that lets the worker's queued messages land, not a wait for time
331 const eventLoopTurn = Effect.promise(() => new Promise<void>((resolve) => setImmediate(resolve)));
332
333 it.effect.each([
vite.config.ts
+5
@@ -188,6 +188,7 @@ export default defineConfig({
188 "t3code/no-manual-effect-runtime-in-tests": "error",
189 "t3code/no-native-title-tooltip": "error",
190 "t3code/no-raw-mcp-registration": "error",
191 + "t3code/no-real-time-wait-in-tests": "error",
192 "t3code/no-test-in-loop": "error",
193 "t3code/no-test-timeout-or-unreasoned-skip": "error",
194 "t3code/no-rpc-permission-bypass": ["error", { allowRawClientAccess: true }],
@@ -216,6 +217,10 @@ export default defineConfig({
217 files: ["apps/web/src/**/*.browser.test.{ts,tsx}"],
218 rules: { "t3code/no-frame-waits-in-browser-tests": "error" },
219 },
220 + {
221 + files: ["**/*.browser.test.*"],
222 + rules: { "t3code/no-real-time-wait-in-tests": "off" },
223 + },
224 {
225 files: ["apps/**/src/**", "packages/**/src/**"],
226 excludeFiles: DOM_TEST_ENVIRONMENT_ALLOWLIST,