The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
test: ban wall-clock readings in tests (#22562)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 20, 2026 at 18:05 UTC
dd4506a1308b2c7cae7dc3377aa4509c4dbfb8ef
8 files changed
+218
-7
apps/mobile/src/features/home/useThreadListActions.test.ts
+2
-1
@@ -391,7 +391,8 @@ describe("thread action undo", () => {
391
await useThreadListActions().unpinThread(thread);
392
expect(readThreadUndoNotice()?.action).toBe("Unpinned");
393
await readThreadUndoNotice()!.undo();
394
- const restoresSnooze = snoozedUntil != null && Date.parse(snoozedUntil) > Date.now();
394
+ // 2099 is the unexpired case; 2000 has long passed.
395
+ const restoresSnooze = snoozedUntil === "2099-01-01T09:00:00.000Z";
396
expect(state.requests.map(({ action }) => action)).toEqual(
397
restoresSnooze ? ["unpin", "pin", "snooze"] : ["unpin", "pin"],
398
);
apps/server/src/serverRuntimeState.test.ts
+2
-2
@@ -206,8 +206,8 @@ describe("server ownership", () => {
206
const state = yield* makeState;
207
yield* ServerRuntimeState.persistServerRuntimeState({
208
path: statePath,
209
- // @effect-diagnostics-next-line globalDateInEffect:off - Legacy identity uses the real process start time, not TestClock.
210
- state: { ...state, startedAt: new Date().toISOString() },
209
+ // Any record time after this process started proves the PID was not reused.
210
+ state: { ...state, startedAt: "2100-01-01T00:00:00.000Z" },
211
});
212
const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe(
213
Effect.flip,
apps/web/src/components/onboarding/WelcomeWizard.import.browser.test.tsx
+9
-3
@@ -164,13 +164,16 @@ function setGrant(environmentId: EnvironmentId, allowed: boolean) {
164
);
165
}
166
167
+// Default selection only picks recently active projects, so pin "now".
168
+const NOW = Date.parse("2026-01-01T00:00:00.000Z");
169
+
170
function candidate(path: string): AgentSessionProjectCandidate {
171
return {
172
path,
173
title: path.split("/").at(-1)!,
174
sources: ["codex"],
175
threadCount: 10,
173
- lastActiveAt: new Date(Date.now() - 60_000).toISOString(),
176
+ lastActiveAt: new Date(NOW - 60_000).toISOString(),
177
alreadyImported: false,
178
};
179
}
@@ -227,7 +230,9 @@ async function mountImport(remote = false) {
230
}
231
232
// The mocked modules read `state`, so every test starts by replacing all of it.
233
+// Returns the clock spy so each test can `using` it; the spy would otherwise outlive the test.
234
function setup() {
235
+ const now = vi.spyOn(Date, "now").mockReturnValue(NOW);
236
state.sessions.clear();
237
for (const id of [primaryId, remoteId]) {
238
state.sessions.set(
@@ -253,10 +258,11 @@ function setup() {
258
state.onDone.mockReset();
259
state.scan.mockReset();
260
state.refreshScan.mockReset();
261
+ return now;
262
}
263
264
it("rechecks after project creation and can retry its history without recreating the project", async () => {
259
- setup();
265
+ using _now = setup();
266
const creation = deferred<void>();
267
state.createProject.mockImplementationOnce(async (input: CreateProjectInput) => {
268
await creation.promise;
@@ -283,7 +289,7 @@ it("rechecks after project creation and can retry its history without recreating
289
});
290
291
it("completes accepted imports when permission is revoked after the final server write", async () => {
286
- setup();
292
+ using _now = setup();
293
state.candidates = state.candidates.slice(0, 1);
294
const imported = deferred<{ importedCount: number; skippedCount: number }>();
295
state.importThreads.mockImplementationOnce(async () =>
apps/web/src/hooks/useThreadActions.undo.test.ts
+1
-1
@@ -265,7 +265,7 @@ describe("settle and snooze Undo", () => {
265
it("wakes the thread from the snooze notice", async () => {
266
const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
267
const actions = useThreadActions();
268
- await actions.snoozeThread(target, new Date(Date.now() + 60_000).toISOString());
268
+ await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
269
expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
270
expect(add).not.toHaveBeenCalled();
271
await currentUndo()();
oxlint-plugin-t3code/index.ts
+2
@@ -20,6 +20,7 @@ import noTestInLoop from "./rules/no-test-in-loop.ts";
20
import noTestTimeoutOrUnreasonedSkip from "./rules/no-test-timeout-or-unreasoned-skip.ts";
21
import noRpcPermissionBypass from "./rules/no-rpc-permission-bypass.ts";
22
import noUnscopedHas from "./rules/no-unscoped-has.ts";
23
+import noWallClockInTests from "./rules/no-wall-clock-in-tests.ts";
24
import preferCatchTags from "./rules/prefer-catch-tags.ts";
25
import preferEffectFn from "./rules/prefer-effect-fn.ts";
26
import requireCenteredScrollGutter from "./rules/require-centered-scroll-gutter.ts";
@@ -51,6 +52,7 @@ export default definePlugin({
52
"no-test-timeout-or-unreasoned-skip": noTestTimeoutOrUnreasonedSkip,
53
"no-rpc-permission-bypass": noRpcPermissionBypass,
54
"no-unscoped-has": noUnscopedHas,
55
+ "no-wall-clock-in-tests": noWallClockInTests,
56
"prefer-catch-tags": preferCatchTags,
57
"prefer-effect-fn": preferEffectFn,
58
"require-centered-scroll-gutter": requireCenteredScrollGutter,
oxlint-plugin-t3code/rules/no-wall-clock-in-tests.test.ts
new
+94
@@ -0,0 +1,94 @@
1
+import { assert, describe } from "@effect/vitest";
2
+
3
+import { createOxlintRuleHarness } from "../test/utils.ts";
4
+
5
+const rule = createOxlintRuleHarness("t3code/no-wall-clock-in-tests", {
6
+ filename: "fixture.test.ts",
7
+});
8
+
9
+describe("t3code/no-wall-clock-in-tests", () => {
10
+ rule.valid(
11
+ "ignores a computed member with a variable key",
12
+ `
13
+ import { it } from "vitest";
14
+ it("parses", () => {
15
+ const now = "parse";
16
+ const parsed = Date[now]("2026-01-01");
17
+ const literal = Date["parse"]("2026-01-01");
18
+ });
19
+ `,
20
+ );
21
+
22
+ rule.valid(
23
+ "allows fixed dates and readings that seed mocks",
24
+ `
25
+ import { vi } from "vitest";
26
+
27
+ const epoch = new Date("2026-01-01T00:00:00.000Z");
28
+ export const later = new Date(epoch.getTime() + 1_000);
29
+ vi.setSystemTime(new Date());
30
+ vi.spyOn(Date, "now").mockReturnValue(Date.now() + 5_000);
31
+ const clock = vi.fn(() => performance.now());
32
+ clock.mockImplementation(() => Number(process.hrtime.bigint()));
33
+ vi.mock("./clock", () => ({ now: () => Date.now() }));
34
+ `,
35
+ );
36
+
37
+ rule.invalid(
38
+ "reports elapsed-time measurement",
39
+ `
40
+ const startedAt = performance.now();
41
+ const elapsed = performance.now() - startedAt;
42
+ if (elapsed > 10_000) throw new Error("slow");
43
+ `,
44
+ (output) => {
45
+ assert.match(output, /Wall-clock reading in a test/);
46
+ assert.equal(output.match(/no-wall-clock-in-tests/g)?.length, 2);
47
+ },
48
+ );
49
+
50
+ rule.invalid(
51
+ "reports Date.now fixtures",
52
+ `
53
+ export const session = { expiresAt: Date.now() + 60_000 };
54
+ `,
55
+ );
56
+
57
+ rule.invalid(
58
+ "reports new Date() with no arguments",
59
+ `
60
+ export const createdAt = new Date().toISOString();
61
+ `,
62
+ );
63
+
64
+ rule.invalid(
65
+ "reports process.hrtime and process.hrtime.bigint",
66
+ `
67
+ export const a = process.hrtime();
68
+ export const b = process.hrtime.bigint();
69
+ `,
70
+ (output) => {
71
+ assert.equal(output.match(/no-wall-clock-in-tests/g)?.length, 2);
72
+ },
73
+ );
74
+
75
+ rule.invalid(
76
+ "reports a reading outside the mock's arguments",
77
+ `
78
+ import { vi } from "vitest";
79
+
80
+ const mock = vi.fn();
81
+ mock.mockReturnValue(1);
82
+ export const now = Date.now();
83
+ `,
84
+ );
85
+});
86
+
87
+const productionRule = createOxlintRuleHarness("t3code/no-wall-clock-in-tests");
88
+
89
+productionRule.valid(
90
+ "ignores non-test files",
91
+ `
92
+ export const now = Date.now();
93
+ `,
94
+);
oxlint-plugin-t3code/rules/no-wall-clock-in-tests.ts
new
+107
@@ -0,0 +1,107 @@
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 WALL_CLOCK_CALLS = new Set([
8
+ "Date.now",
9
+ "performance.now",
10
+ "process.hrtime",
11
+ "process.hrtime.bigint",
12
+]);
13
+const VI_MOCKING_FUNCTIONS = new Set(["fn", "mock", "setSystemTime", "spyOn"]);
14
+const MOCK_METHODS = new Set([
15
+ "mockImplementation",
16
+ "mockImplementationOnce",
17
+ "mockResolvedValue",
18
+ "mockResolvedValueOnce",
19
+ "mockReturnValue",
20
+ "mockReturnValueOnce",
21
+]);
22
+
23
+const MESSAGE =
24
+ "Wall-clock reading in a test; elapsed-time assertions pass or fail with runner load. Use TestClock/`Clock` under `it.effect`, `vi.setSystemTime`, or a fixed epoch. Benchmarks live behind an env gate.";
25
+
26
+const isStringLiteral = (node: unknown) =>
27
+ Option.exists(
28
+ unwrapExpression(node),
29
+ (expression) => expression.type === "Literal" && typeof expression.value === "string",
30
+ );
31
+
32
+const memberPath = (node: unknown): Option.Option<ReadonlyArray<string>> => {
33
+ const expression = unwrapExpression(node);
34
+ if (Option.isNone(expression)) return Option.none();
35
+ if (expression.value.type === "Identifier") return Option.some([expression.value.name]);
36
+ if (expression.value.type !== "MemberExpression") return Option.none();
37
+ // `Date[now]` with a variable key is unknowable; only a literal key names a member.
38
+ if (expression.value.computed && !isStringLiteral(expression.value.property))
39
+ return Option.none();
40
+ const property = getPropertyName(expression.value.property);
41
+ if (Option.isNone(property)) return Option.none();
42
+ return Option.map(memberPath(expression.value.object), (path) => [...path, property.value]);
43
+};
44
+
45
+const isWallClockCall = (callee: unknown): boolean =>
46
+ Option.match(memberPath(callee), {
47
+ onNone: () => false,
48
+ onSome: (path) => WALL_CLOCK_CALLS.has(path.join(".")),
49
+ });
50
+
51
+const isMockingCall = (callee: unknown): boolean => {
52
+ const expression = unwrapExpression(callee);
53
+ if (Option.isNone(expression) || expression.value.type !== "MemberExpression") return false;
54
+ const property = getPropertyName(expression.value.property);
55
+ if (Option.isNone(property)) return false;
56
+ if (MOCK_METHODS.has(property.value)) return true;
57
+ return (
58
+ VI_MOCKING_FUNCTIONS.has(property.value) &&
59
+ isIdentifier(unwrapExpression(expression.value.object), "vi")
60
+ );
61
+};
62
+
63
+// Readings that feed a mock (or live in a vi.mock factory) seed fake time
64
+// rather than measure the runner, so they stay allowed.
65
+const isMockArgument = (node: ESTree.Node): boolean => {
66
+ let child: ESTree.Node = node;
67
+ let current = node.parent;
68
+ while (current) {
69
+ if (
70
+ current.type === "CallExpression" &&
71
+ current.callee !== child &&
72
+ isMockingCall(current.callee)
73
+ ) {
74
+ return true;
75
+ }
76
+ child = current;
77
+ current = current.parent;
78
+ }
79
+ return false;
80
+};
81
+
82
+export default defineRule({
83
+ meta: {
84
+ type: "problem",
85
+ docs: {
86
+ description:
87
+ "Disallow wall-clock readings (Date.now, new Date(), performance.now, process.hrtime) in tests.",
88
+ },
89
+ },
90
+ create(context) {
91
+ if (!TEST_FILE_PATTERN.test(context.filename)) return {};
92
+
93
+ return {
94
+ CallExpression(node) {
95
+ if (!isWallClockCall(node.callee)) return;
96
+ if (isMockArgument(node)) return;
97
+ context.report({ node, message: MESSAGE });
98
+ },
99
+ NewExpression(node) {
100
+ if (node.arguments.length > 0) return;
101
+ if (!isIdentifier(unwrapExpression(node.callee), "Date")) return;
102
+ if (isMockArgument(node)) return;
103
+ context.report({ node, message: MESSAGE });
104
+ },
105
+ };
106
+ },
107
+});
vite.config.ts
+1
@@ -192,6 +192,7 @@ export default defineConfig({
192
"t3code/no-test-timeout-or-unreasoned-skip": "error",
193
"t3code/no-rpc-permission-bypass": ["error", { allowRawClientAccess: true }],
194
"t3code/no-unscoped-has": "error",
195
+ "t3code/no-wall-clock-in-tests": "error",
196
"t3code/namespace-node-imports": "error",
197
"t3code/prefer-catch-tags": "error",
198
"t3code/prefer-effect-fn": "error",