@devries-cameron20 / t3code Mirror · read-only / commits / 695f5c9963
Fork 0

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, 15:45 UTC

chore(lint): enforce t3code/no-polling-loop-in-tests (#25120)

Julius Marminge committed Oct 25, 2026 at 23:01 UTC 695f5c9963f59da6229e7386f9e45e64e91153c4
15 files changed +194 -168
apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+1
@@ -219,6 +219,7 @@ const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pip
219 const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
220 function* () {
221 let idlePasses = 0;
222 + // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- This harness drains mocked runtime jobs and their promise continuations, not external I/O or elapsed time.
223 for (;;) {
224 yield* Effect.promise(() => Promise.resolve());
225 const pending = backgroundRuntime.pending.shift();
apps/server/src/background/HostPowerMonitor.test.ts
+7 -8
@@ -1,6 +1,7 @@
1 import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
2 import { describe, expect, it } from "@effect/vitest";
3 import * as DateTime from "effect/DateTime";
4 +import * as Deferred from "effect/Deferred";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
@@ -114,6 +115,7 @@ describe("HostPowerMonitor", () => {
115 },
116 };
117 const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
118 + const changeApplied = yield* Deferred.make<void>();
119 const layerReceiver = DesktopTelemetryReceiver.layerTest({
120 latest: Effect.succeedSome(initial),
121 changes: Stream.empty,
@@ -122,7 +124,10 @@ describe("HostPowerMonitor", () => {
124 yield* PubSub.publish(desktopChanges, updated);
125 return {
126 latest: Option.some(initial),
125 - changes: Stream.fromSubscription(subscription),
127 + changes: Stream.fromSubscription(subscription).pipe(
128 + Stream.take(1),
129 + Stream.ensuring(Deferred.succeed(changeApplied, undefined)),
130 + ),
131 };
132 }),
133 });
@@ -130,13 +135,7 @@ describe("HostPowerMonitor", () => {
135
136 yield* Effect.gen(function* () {
137 const monitor = yield* HostPowerMonitor.HostPowerMonitor;
133 - for (
134 - let attempt = 0;
135 - attempt < 100 && (yield* monitor.snapshot).onBattery !== "true";
136 - attempt += 1
137 - ) {
138 - yield* Effect.yieldNow;
139 - }
138 + yield* Deferred.await(changeApplied);
139 expect((yield* monitor.snapshot).onBattery).toBe("true");
140 }).pipe(Effect.provide(layer));
141 }),
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+7 -9
@@ -4169,6 +4169,7 @@ describe("AcpAdapterV2", () => {
4169 const responseWritten = yield* Deferred.make<void>();
4170 const releaseResponseAcknowledgement = yield* Deferred.make<void>();
4171 const responseLifecycle: Array<string> = [];
4172 + const responseFailed = yield* Deferred.make<void>();
4173 const instanceId = ProviderInstanceId.make("acp-test-normal-close-held-response");
4174 const adapter = yield* makeAcpAdapterV2({
4175 instanceId,
@@ -4191,6 +4192,7 @@ describe("AcpAdapterV2", () => {
4192 onNativeResponseLifecycle: (event) =>
4193 Effect.sync(() => {
4194 responseLifecycle.push(event.type);
4195 + if (event.type === "failed") Deferred.doneUnsafe(responseFailed, Effect.void);
4196 }),
4197 },
4198 });
@@ -4244,9 +4246,7 @@ describe("AcpAdapterV2", () => {
4246 yield* Deferred.await(responseWritten);
4247
4248 const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped);
4247 - while (!responseLifecycle.includes("failed")) {
4248 - yield* Effect.yieldNow;
4249 - }
4249 + yield* Deferred.await(responseFailed);
4250 const responseExit = yield* Fiber.join(responseFiber);
4251 if (Exit.isSuccess(responseExit)) {
4252 assert.fail("normal close must fail a response whose transport acknowledgement is held");
@@ -6234,6 +6234,7 @@ describe("AcpAdapterV2", () => {
6234 type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
6235 let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
6236 const promptGates: Array<Deferred.Deferred<EffectAcpSchema.PromptResponse, never>> = [];
6237 + const promptStarted = yield* Queue.unbounded<void>();
6238 const capturedMutation: {
6239 current:
6240 | ((mutation: {
@@ -6304,6 +6305,7 @@ describe("AcpAdapterV2", () => {
6305 Effect.gen(function* () {
6306 const gate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
6307 promptGates.push(gate);
6308 + yield* Queue.offer(promptStarted, undefined);
6309 return yield* Deferred.await(gate);
6310 }),
6311 }),
@@ -6354,9 +6356,7 @@ describe("AcpAdapterV2", () => {
6356 makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
6357 )
6358 .pipe(Effect.forkScoped);
6357 - while (promptGates.length < 1) {
6358 - yield* Effect.yieldNow;
6359 - }
6359 + yield* Queue.take(promptStarted);
6360 assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
6361 const applyMutation = capturedMutation.current;
6362 if (applyMutation === null) {
@@ -6489,9 +6489,7 @@ describe("AcpAdapterV2", () => {
6489 }),
6490 )
6491 .pipe(Effect.forkScoped);
6492 - while (promptGates.length < 2) {
6493 - yield* Effect.yieldNow;
6494 - }
6492 + yield* Queue.take(promptStarted);
6493 if (sessionUpdateHandler === undefined || capturedMutation.current === null) {
6494 return yield* Effect.die("extensions and session handler must be wired for turn 2");
6495 }
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+26 -7
@@ -737,6 +737,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
737 });
738
739 let afterSequence = created[0]!.sequence;
740 + // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- Fixed-count writes exercise the catch-up/live handoff; each iteration awaits its event rather than polling.
741 for (let index = 1; index <= 32; index += 1) {
742 const nextEvent = {
743 id: EventId.make(`event:foundation-stream-race:${index}`),
@@ -2426,6 +2427,8 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
2427 const releaseA1 = yield* Deferred.make<void>();
2428 const releaseA2 = yield* Deferred.make<void>();
2429 const releaseB1 = yield* Deferred.make<void>();
2430 + const settled = yield* Deferred.make<void>();
2431 + const completed = yield* Ref.make(0);
2432 const gates = new Map([
2433 [effectA1, { started: startedA1, release: releaseA1 }],
2434 [effectA2, { started: startedA2, release: releaseA2 }],
@@ -2447,7 +2450,24 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
2450 workerId: "concurrency-worker",
2451 }).pipe(
2452 Layer.provide(
2450 - Layer.merge(Layer.succeed(EffectOutbox.EffectOutboxV2, outbox), layerExecutor),
2453 + Layer.merge(
2454 + Layer.succeed(EffectOutbox.EffectOutboxV2, {
2455 + ...outbox,
2456 + succeed: (input) =>
2457 + outbox
2458 + .succeed(input)
2459 + .pipe(
2460 + Effect.tap(() =>
2461 + Ref.updateAndGet(completed, (count) => count + 1).pipe(
2462 + Effect.flatMap((count) =>
2463 + count === 3 ? Deferred.succeed(settled, undefined) : Effect.void,
2464 + ),
2465 + ),
2466 + ),
2467 + ),
2468 + }),
2469 + layerExecutor,
2470 + ),
2471 ),
2472 );
2473
@@ -2493,13 +2513,12 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
2513 yield* Deferred.succeed(releaseB1, undefined);
2514 yield* Deferred.await(startedA2);
2515 yield* Deferred.succeed(releaseA2, undefined);
2496 - let settled = false;
2497 - while (!settled) {
2498 - settled = (yield* outbox.listByCommandId(commandId)).every(
2516 + yield* Deferred.await(settled);
2517 + assert.isTrue(
2518 + (yield* outbox.listByCommandId(commandId)).every(
2519 (effect) => effect.status === "succeeded",
2500 - );
2501 - if (!settled) yield* Effect.yieldNow;
2502 - }
2520 + ),
2521 + );
2522 }).pipe(Effect.provide(layerWorker), Effect.scoped);
2523 }),
2524 );
apps/server/src/project/ProjectEnrichmentService.test.ts
+10 -6
@@ -25,12 +25,16 @@ const waitForAvailable = Effect.fn("ProjectEnrichmentServiceTest.waitForAvailabl
25 workspaceRoot: string,
26 predicate: (value: ProjectEnrichment.ProjectEnrichment) => boolean,
27 ) {
28 - for (let attempt = 0; attempt < 100; attempt += 1) {
29 - const available = yield* service.peek(workspaceRoot);
30 - if (predicate(available)) return available;
31 - yield* Effect.yieldNow;
32 - }
33 - return yield* Effect.die(`Project metadata for ${workspaceRoot} was not resolved in time.`);
28 + return yield* Effect.scoped(
29 + Effect.gen(function* () {
30 + const changes = yield* service.subscribeChanges;
31 + for (;;) {
32 + const available = yield* service.peek(workspaceRoot);
33 + if (predicate(available)) return available;
34 + yield* PubSub.take(changes);
35 + }
36 + }),
37 + );
38 });
39
40 const layer = (
apps/server/src/project/ProjectService.test.ts
+43 -6
@@ -1,3 +1,6 @@
1 +import * as Context from "effect/Context";
2 +import * as Queue from "effect/Queue";
3 +import * as Tracer from "effect/Tracer";
4 import { assert, it } from "@effect/vitest";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import { CommandId, type Project, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
@@ -56,6 +59,35 @@ const layerMetadata = Layer.merge(
59 }),
60 );
61
62 +class EnrichmentCompletions extends Context.Service<EnrichmentCompletions, Queue.Queue<void>>()(
63 + "t3/project/ProjectService.test/EnrichmentCompletions",
64 +) {}
65 +
66 +const layerEnrichmentCompletions = Layer.effectContext(
67 + Effect.gen(function* () {
68 + const completions = yield* Queue.unbounded<void>();
69 + const tracer = Tracer.make({
70 + span: (options) => {
71 + const span = new Tracer.NativeSpan(options);
72 + const end = span.end.bind(span);
73 + span.end = (...args) => {
74 + end(...args);
75 + if (
76 + span.name === "ProjectEnrichmentService.resolveRepositoryIdentity" ||
77 + span.name === "ProjectEnrichmentService.resolveFavicon"
78 + ) {
79 + Queue.offerUnsafe(completions, undefined);
80 + }
81 + };
82 + return span;
83 + },
84 + });
85 + return Context.make(EnrichmentCompletions, completions).pipe(
86 + Context.add(Tracer.Tracer, tracer),
87 + );
88 + }),
89 +);
90 +
91 const layerTestFor = (
92 projectMetadataLayer: Layer.Layer<
93 | ProjectFaviconResolver.ProjectFaviconResolver
@@ -70,6 +102,7 @@ const layerTestFor = (
102 Layer.provideMerge(ServerSettings.layerTest()),
103 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })),
104 Layer.provide(NodeServices.layer),
105 + Layer.provideMerge(layerEnrichmentCompletions),
106 );
107
108 const layerTest = layerTestFor(layerMetadata);
@@ -96,12 +129,16 @@ const waitForProject = Effect.fn("ProjectServiceTest.waitForProject")(function*
129 projectId: ProjectId,
130 predicate: (project: Project) => boolean,
131 ) {
99 - for (let attempt = 0; attempt < 100; attempt += 1) {
100 - const project = Option.getOrThrow(yield* service.getById(projectId));
101 - if (predicate(project)) return project;
102 - yield* Effect.yieldNow;
103 - }
104 - return yield* Effect.die(`Project ${projectId} was not enriched in time.`);
132 + return yield* Effect.scoped(
133 + Effect.gen(function* () {
134 + const completions = yield* EnrichmentCompletions;
135 + for (;;) {
136 + const project = Option.getOrThrow(yield* service.getById(projectId));
137 + if (predicate(project)) return project;
138 + yield* Queue.take(completions);
139 + }
140 + }),
141 + );
142 });
143
144 it.layer(layerTest)("ProjectService", (it) => {
apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+17 -9
@@ -503,6 +503,20 @@ it.effect.each(queuedDeliveryCases)(
503 ({ reason, apply }) =>
504 Effect.gen(function* () {
505 const gate = yield* Deferred.make<void>();
506 + const deliveryReleased = yield* Deferred.make<void>();
507 + const tracer = Tracer.make({
508 + span: (options) => {
509 + const span = new Tracer.NativeSpan(options);
510 + const end = span.end.bind(span);
511 + span.end = (...args) => {
512 + end(...args);
513 + if (span.name === "ScheduledTaskService.releaseFailedDelivery") {
514 + Deferred.doneUnsafe(deliveryReleased, Effect.void);
515 + }
516 + };
517 + return span;
518 + },
519 + });
520 yield* withService(
521 ({ service, launches }) =>
522 Effect.gen(function* () {
@@ -513,23 +527,17 @@ it.effect.each(queuedDeliveryCases)(
527 yield* apply(service, task.id);
528 yield* Deferred.succeed(gate, undefined);
529 const deliveryId = queued._tag === "accepted" ? queued.deliveryId : undefined;
516 - let delivery = (yield* service.getWebhookDelivery({
530 + yield* Deferred.await(deliveryReleased);
531 + const delivery = (yield* service.getWebhookDelivery({
532 id: task.id,
533 deliveryId: deliveryId!,
534 })).delivery;
520 - while (delivery.outcome === "accepted") {
521 - yield* Effect.yieldNow;
522 - delivery = (yield* service.getWebhookDelivery({
523 - id: task.id,
524 - deliveryId: deliveryId!,
525 - })).delivery;
526 - }
535 assert.equal(delivery.outcome, "dispatch_failed");
536 assert.equal(delivery.error, reason);
537 assert.equal(yield* Queue.size(launches), 0);
538 }),
539 { gate },
532 - );
540 + ).pipe(Effect.withTracer(tracer));
541 }),
542 );
543
apps/server/src/usage/UsageService.test.ts
+1
@@ -2610,6 +2610,7 @@ describe("UsageService", () => {
2610 );
2611
2612 let orphanedAt: number | undefined;
2613 + // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- Fixed-count scheduler interruption matrix; each iteration exercises a different interruption point.
2614 for (let interruptAt = 1; interruptAt <= 31; interruptAt += 1) {
2615 const tasks: Array<() => void> = [];
2616 const dispatcher: Scheduler.SchedulerDispatcher = {
packages/client-runtime/src/connection/supervisor.test.ts
+1 -20
@@ -127,25 +127,6 @@ function awaitState(
127 );
128 }
129
130 -const eventuallyState = Effect.fn("TestConnectionHarness.eventuallyState")(function* (
131 - state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
132 - predicate: (value: SupervisorConnectionState) => boolean,
133 -) {
134 - let lastState = yield* SubscriptionRef.get(state);
135 - for (let iteration = 0; iteration < 100; iteration += 1) {
136 - lastState = yield* SubscriptionRef.get(state);
137 - if (predicate(lastState)) {
138 - return lastState;
139 - }
140 - yield* Effect.yieldNow;
141 - }
142 - return yield* Effect.die(
143 - new Error(
144 - `Expected supervisor state was not observed. Last state: phase=${lastState.phase}, stage=${lastState.stage ?? "none"}, attempt=${lastState.attempt}, generation=${lastState.generation}`,
145 - ),
146 - );
147 -});
148 -
130 const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: {
131 readonly networkStatus?: NetworkStatus;
132 readonly prepare?: (
@@ -477,7 +458,7 @@ describe("EnvironmentSupervisor", () => {
458 expect(yield* Ref.get(harness.prepareCount)).toBe(1);
459
460 yield* TestClock.adjust("15 seconds");
480 - const retrying = yield* eventuallyState(
461 + const retrying = yield* awaitState(
462 supervisor.state,
463 (state) => state.phase === "backoff" && state.attempt === 1,
464 );
packages/client-runtime/src/rpc/client.test.ts
+20 -12
@@ -112,15 +112,18 @@ describe("environment RPC", () => {
112 it.effect("switches durable subscriptions when the supervisor replaces the session", () =>
113 Effect.gen(function* () {
114 const subscriptions: string[] = [];
115 + const subscriptionChanges = yield* Queue.make<void>();
116 const firstClient = {
117 [WS_METHODS.subscribeTerminalEvents]: () => {
118 subscriptions.push("first");
119 + Queue.offerUnsafe(subscriptionChanges, undefined);
120 return Stream.never;
121 },
122 } as unknown as WsRpcProtocolClient;
123 const secondClient = {
124 [WS_METHODS.subscribeTerminalEvents]: () => {
125 subscriptions.push("second");
126 + Queue.offerUnsafe(subscriptionChanges, undefined);
127 return Stream.never;
128 },
129 } as unknown as WsRpcProtocolClient;
@@ -128,13 +131,12 @@ describe("environment RPC", () => {
131 const awaitSubscriptions = Effect.fn("TestEnvironmentRpc.awaitSubscriptions")(function* (
132 count: number,
133 ) {
131 - for (let attempt = 0; attempt < 100; attempt += 1) {
134 + for (;;) {
135 if (subscriptions.length >= count) {
136 return;
137 }
135 - yield* Effect.yieldNow;
138 + yield* Queue.take(subscriptionChanges);
139 }
137 - return yield* Effect.die(new Error(`Expected ${count} durable subscriptions.`));
140 });
141
142 const subscriptionFiber = yield* subscribe(WS_METHODS.subscribeTerminalEvents, {}).pipe(
@@ -222,9 +224,11 @@ describe("environment RPC", () => {
224 it.effect("keeps durable subscriptions alive across a transport failure and new session", () =>
225 Effect.gen(function* () {
226 const subscriptions: string[] = [];
227 + const subscriptionChanges = yield* Queue.make<void>();
228 const firstClient = {
229 [WS_METHODS.subscribeTerminalEvents]: () => {
230 subscriptions.push("first");
231 + Queue.offerUnsafe(subscriptionChanges, undefined);
232 return Stream.fail(
233 new RpcClientError.RpcClientError({
234 reason: new RpcClientError.RpcClientDefect({
@@ -238,6 +242,7 @@ describe("environment RPC", () => {
242 const secondClient = {
243 [WS_METHODS.subscribeTerminalEvents]: () => {
244 subscriptions.push("second");
245 + Queue.offerUnsafe(subscriptionChanges, undefined);
246 return Stream.never;
247 },
248 } as unknown as WsRpcProtocolClient;
@@ -249,14 +254,14 @@ describe("environment RPC", () => {
254 Effect.forkChild,
255 );
256 yield* SubscriptionRef.set(activeSession, Option.some(session(firstClient)));
252 - for (let attempt = 0; attempt < 100 && subscriptions.length < 1; attempt += 1) {
253 - yield* Effect.yieldNow;
257 + while (subscriptions.length < 1) {
258 + yield* Queue.take(subscriptionChanges);
259 }
260 yield* SubscriptionRef.set(activeSession, Option.none());
261 yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient)));
262
258 - for (let attempt = 0; attempt < 100 && subscriptions.length < 2; attempt += 1) {
259 - yield* Effect.yieldNow;
263 + while (subscriptions.length < 2) {
264 + yield* Queue.take(subscriptionChanges);
265 }
266 yield* Fiber.interrupt(subscriptionFiber);
267
@@ -289,16 +294,20 @@ describe("environment RPC", () => {
294 Effect.gen(function* () {
295 const domainError = new Error("terminal subscription rejected");
296 const subscriptions: string[] = [];
297 + const subscriptionChanges = yield* Queue.make<void>();
298 const observedFailures: Error[] = [];
299 + const failureObserved = yield* Deferred.make<void>();
300 const firstClient = {
301 [WS_METHODS.subscribeTerminalEvents]: () => {
302 subscriptions.push("first");
303 + Queue.offerUnsafe(subscriptionChanges, undefined);
304 return Stream.fail(domainError);
305 },
306 } as unknown as WsRpcProtocolClient;
307 const secondClient = {
308 [WS_METHODS.subscribeTerminalEvents]: () => {
309 subscriptions.push("second");
310 + Queue.offerUnsafe(subscriptionChanges, undefined);
311 return Stream.never;
312 },
313 } as unknown as WsRpcProtocolClient;
@@ -312,6 +321,7 @@ describe("environment RPC", () => {
321 onExpectedFailure: (cause) =>
322 Effect.sync(() => {
323 observedFailures.push(Cause.squash(cause) as Error);
324 + Deferred.doneUnsafe(failureObserved, Effect.void);
325 }),
326 },
327 ).pipe(
@@ -319,16 +329,14 @@ describe("environment RPC", () => {
329 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
330 Effect.forkChild,
331 );
322 - for (let attempt = 0; attempt < 100 && observedFailures.length < 1; attempt += 1) {
323 - yield* Effect.yieldNow;
324 - }
332 + yield* Deferred.await(failureObserved);
333
334 expect(subscriptions).toEqual(["first"]);
335 expect(observedFailures).toEqual([domainError]);
336
337 yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient)));
330 - for (let attempt = 0; attempt < 100 && subscriptions.length < 2; attempt += 1) {
331 - yield* Effect.yieldNow;
338 + while (subscriptions.length < 2) {
339 + yield* Queue.take(subscriptionChanges);
340 }
341 yield* Fiber.interrupt(subscriptionFiber);
342
packages/client-runtime/src/rpc/session.test.ts
+13 -10
@@ -53,10 +53,12 @@ class TestWebSocket {
53 readyState = TestWebSocket.CONNECTING;
54 readonly sent: string[] = [];
55 readonly url: string;
56 + readonly sentChanges: Queue.Queue<void>;
57 private readonly listeners = new Map<SocketEventType, Set<SocketListener>>();
58
58 - constructor(url: string) {
59 + constructor(url: string, sentChanges: Queue.Queue<void>) {
60 this.url = url;
61 + this.sentChanges = sentChanges;
62 }
63
64 addEventListener(type: SocketEventType, listener: SocketListener) {
@@ -71,6 +73,7 @@ class TestWebSocket {
73
74 send(data: string) {
75 this.sent.push(data);
76 + Queue.offerUnsafe(this.sentChanges, undefined);
77 }
78
79 close(code = 1000, reason = "") {
@@ -208,10 +211,12 @@ const LEGACY_SERVER_CONFIG = {
211 const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* (
212 options: RpcSession.RpcSessionOptions = {},
213 ) {
211 - const sockets: TestWebSocket[] = [];
214 + const sentChanges = yield* Queue.unbounded<void>();
215 + const sockets = Object.assign([] as TestWebSocket[], { changes: yield* Queue.unbounded<void>() });
216 const layerConstructor = Layer.succeed(Socket.WebSocketConstructor, (url) => {
213 - const socket = new TestWebSocket(url);
217 + const socket = new TestWebSocket(url, sentChanges);
218 sockets.push(socket);
219 + Queue.offerUnsafe(sockets.changes, undefined);
220 return socket as unknown as globalThis.WebSocket;
221 });
222 const layer = RpcSession.layer(options).pipe(Layer.provide(layerConstructor));
@@ -220,31 +225,29 @@ const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* (
225 });
226
227 const awaitSocket = Effect.fn("TestRpcSessionFactory.awaitSocket")(function* (
223 - sockets: ReadonlyArray<TestWebSocket>,
228 + sockets: ReadonlyArray<TestWebSocket> & { readonly changes: Queue.Queue<void> },
229 index = 0,
230 ) {
226 - for (let attempt = 0; attempt < 100; attempt += 1) {
231 + for (;;) {
232 const socket = sockets[index];
233 if (socket) {
234 return socket;
235 }
231 - yield* Effect.yieldNow;
236 + yield* Queue.take(sockets.changes);
237 }
233 - return yield* Effect.die(new Error("Expected the RPC protocol to create a websocket."));
238 });
239
240 const awaitRequest = Effect.fn("TestRpcSessionFactory.awaitRequest")(function* (
241 socket: TestWebSocket,
242 index = 0,
243 ) {
240 - for (let attempt = 0; attempt < 100; attempt += 1) {
244 + for (;;) {
245 const request = socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)[index];
246 if (request) {
247 return request;
248 }
245 - yield* Effect.yieldNow;
249 + yield* Queue.take(socket.sentChanges);
250 }
247 - return yield* Effect.die(new Error("Expected the RPC protocol to send a request."));
251 });
252
253 const completeInitialConfig = Effect.fn("TestRpcSessionFactory.completeInitialConfig")(function* (
packages/client-runtime/src/state/shell-sync.test.ts
+31 -30
@@ -124,11 +124,11 @@ const makePersistenceHarness = Effect.fn("test.makeShellPersistenceHarness")(fun
124 describe("environment shell synchronization", () => {
125 it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>
126 Effect.gen(function* () {
127 - const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
127 + const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
128 yield* Effect.scoped(
129 Effect.gen(function* () {
130 const h = yield* makePersistenceHarness((_id, snapshot) =>
131 - Ref.update(saved, (values) => [...values, snapshot]),
131 + SubscriptionRef.update(saved, (values) => [...values, snapshot]),
132 );
133 yield* TestClock.adjust("500 millis");
134 yield* h.send(
@@ -136,7 +136,9 @@ describe("environment shell synchronization", () => {
136 (snapshot) => snapshot.snapshotSequence === 10,
137 );
138 yield* TestClock.adjust("10 seconds");
139 - expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);
139 + expect(
140 + (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
141 + ).toEqual([1]);
142 const live = Option.getOrThrow((yield* SubscriptionRef.get(h.state)).snapshot);
143 expect(live.snapshotSequence).toBe(10);
144 const enriched = yield* h.send(
@@ -152,7 +154,9 @@ describe("environment shell synchronization", () => {
154 expect(enriched.projects).toEqual(live.projects);
155 expect(enriched.snapshotSequence).toBe(10);
156 yield* TestClock.adjust("10 seconds");
155 - expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);
157 + expect(
158 + (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
159 + ).toEqual([1]);
160 yield* h.send(
161 { kind: "snapshot", snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 4 } },
162 (snapshot) => snapshot.snapshotSequence === 4,
@@ -172,7 +176,7 @@ describe("environment shell synchronization", () => {
176 }),
177 );
178 expect(
175 - (yield* Ref.get(saved)).map((snapshot) => [
179 + (yield* SubscriptionRef.get(saved)).map((snapshot) => [
180 snapshot.snapshotSequence,
181 snapshot.projects[0]?.title,
182 ]),
@@ -217,7 +221,7 @@ describe("environment shell synchronization", () => {
221 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
222 Effect.gen(function* () {
223 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
220 - const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
224 + const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
225 const saveStarted = yield* Deferred.make<void>();
226 const releaseSave = yield* Deferred.make<void>();
227 const client = {
@@ -241,7 +245,7 @@ describe("environment shell synchronization", () => {
245 saveShell: (_environmentId, snapshot) =>
246 Deferred.succeed(saveStarted, undefined).pipe(
247 Effect.andThen(Deferred.await(releaseSave)),
244 - Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
248 + Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
249 ),
250 loadThread: () => Effect.succeedNone,
251 saveThread: () => Effect.void,
@@ -316,21 +320,21 @@ describe("environment shell synchronization", () => {
320 lastFailure: null,
321 retryAt: null,
322 });
319 - for (let index = 0; index < 100; index += 1) {
320 - if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
321 - yield* Effect.yieldNow;
322 - }
323 + yield* SubscriptionRef.changes(shellState).pipe(
324 + Stream.filter((state) => state.status === "synchronizing"),
325 + Stream.runHead,
326 + );
327
328 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
325 - expect(yield* Ref.get(saved)).toEqual([]);
329 + expect(yield* SubscriptionRef.get(saved)).toEqual([]);
330
331 yield* Deferred.succeed(releaseSave, undefined);
328 - for (let index = 0; index < 100; index += 1) {
329 - if ((yield* Ref.get(saved)).length > 0) break;
330 - yield* Effect.yieldNow;
331 - }
332 + yield* SubscriptionRef.changes(saved).pipe(
333 + Stream.filter((values) => values.length > 0),
334 + Stream.runHead,
335 + );
336
333 - expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
337 + expect(yield* SubscriptionRef.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
338 }),
339 );
340
@@ -356,7 +360,7 @@ describe("environment shell synchronization", () => {
360 };
361
362 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
359 - const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
363 + const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
364 const unenrichedSaveStarted = yield* Deferred.make<void>();
365 const releaseUnenrichedSave = yield* Deferred.make<void>();
366 const client = {
@@ -383,7 +387,7 @@ describe("environment shell synchronization", () => {
387 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
388 yield* Deferred.await(releaseUnenrichedSave);
389 }
386 - yield* Ref.update(saved, (values) => [...values, snapshot]);
390 + yield* SubscriptionRef.update(saved, (values) => [...values, snapshot]);
391 }),
392 loadThread: () => Effect.succeedNone,
393 saveThread: () => Effect.void,
@@ -454,15 +458,12 @@ describe("environment shell synchronization", () => {
458 );
459
460 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
457 - for (let index = 0; index < 100; index += 1) {
458 - const values = yield* Ref.get(saved);
459 - if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
460 - break;
461 - }
462 - yield* Effect.yieldNow;
463 - }
461 + yield* SubscriptionRef.changes(saved).pipe(
462 + Stream.filter((values) => values.at(-1)?.projects[0]?.repositoryIdentity != null),
463 + Stream.runHead,
464 + );
465
465 - const finalSaved = (yield* Ref.get(saved)).at(-1);
466 + const finalSaved = (yield* SubscriptionRef.get(saved)).at(-1);
467 expect(finalSaved?.snapshotSequence).toBe(1);
468 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
469 }),
@@ -476,7 +477,7 @@ describe("environment shell synchronization", () => {
477 projects: [{ ...v2Project, title: "Late stream event" }],
478 };
479 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
479 - const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
480 + const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
481 const saveStarted = yield* Deferred.make<void>();
482 const releaseSave = yield* Deferred.make<void>();
483 const client = {
@@ -500,7 +501,7 @@ describe("environment shell synchronization", () => {
501 saveShell: (_environmentId, snapshot) =>
502 Deferred.succeed(saveStarted, undefined).pipe(
503 Effect.andThen(Deferred.await(releaseSave)),
503 - Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
504 + Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
505 ),
506 loadThread: () => Effect.succeedNone,
507 saveThread: () => Effect.void,
@@ -557,7 +558,7 @@ describe("environment shell synchronization", () => {
558 yield* Deferred.succeed(releaseSave, undefined);
559 yield* Fiber.join(closeFiber);
560
560 - const values = yield* Ref.get(saved);
561 + const values = yield* SubscriptionRef.get(saved);
562 expect(values.length).toBeGreaterThan(0);
563 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
564 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
packages/client-runtime/src/state/threads-sync.test.ts
+15 -17
@@ -128,7 +128,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
128 const observed = yield* Queue.unbounded<EnvironmentThreadState>();
129 const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
130 const retryCount = yield* Ref.make(0);
131 - const subscriptionCount = yield* Ref.make(0);
131 + const subscriptionCount = yield* SubscriptionRef.make(0);
132 const loaderCalls = yield* Ref.make(0);
133 const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
134 const lastRequestCompletionMarker = yield* Ref.make(false);
@@ -154,13 +154,13 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
154 readonly acceptCompactTurnItems?: true;
155 }) =>
156 Stream.unwrap(
157 - Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
158 - Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
157 + Ref.set(lastSubscribeAfterSequence, input.afterSequence).pipe(
158 Effect.andThen(
159 Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true),
160 ),
161 Effect.andThen(Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot)),
162 Effect.andThen(Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems)),
163 + Effect.andThen(SubscriptionRef.update(subscriptionCount, (count) => count + 1)),
164 Effect.as(streamFrom(inputs)),
165 ),
166 ),
@@ -416,7 +416,7 @@ describe("EnvironmentThreads", () => {
416 const state = yield* awaitThreadState(h.observed, (value) => value.status === "live");
417 expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
418 expect(yield* Ref.get(h.loaderCalls)).toBe(1);
419 - expect(yield* Ref.get(h.subscriptionCount)).toBe(1);
419 + expect(yield* SubscriptionRef.get(h.subscriptionCount)).toBe(1);
420 }),
421 );
422
@@ -1692,7 +1692,7 @@ describe("EnvironmentThreads", () => {
1692
1693 expect(Option.getOrThrow(state.data).thread.title).toBe("Socket title");
1694 expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
1695 - expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
1695 + expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(1);
1696 expect(yield* Ref.get(harness.removedThreads)).toEqual([]);
1697 }),
1698 );
@@ -1742,12 +1742,10 @@ describe("EnvironmentThreads", () => {
1742 expect(yield* Ref.get(harness.retryCount)).toBe(0);
1743
1744 yield* harness.replaceSession;
1745 - for (let attempt = 0; attempt < 100; attempt += 1) {
1746 - if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
1747 - break;
1748 - }
1749 - yield* Effect.yieldNow;
1750 - }
1745 + yield* SubscriptionRef.changes(harness.subscriptionCount).pipe(
1746 + Stream.filter((count) => count >= 2),
1747 + Stream.runHead,
1748 + );
1749 yield* Queue.offer(
1750 harness.inputs,
1751 snapshot({
@@ -1764,7 +1762,7 @@ describe("EnvironmentThreads", () => {
1762 );
1763
1764 expect(Option.isNone(recovered.error)).toBe(true);
1767 - expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1765 + expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(2);
1766 }),
1767 );
1768
@@ -1851,11 +1849,11 @@ describe("EnvironmentThreads", () => {
1849 ]);
1850
1851 yield* harness.replaceSession;
1854 - for (let attempt = 0; attempt < 100; attempt += 1) {
1855 - if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
1856 - yield* Effect.yieldNow;
1857 - }
1858 - expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
1852 + yield* SubscriptionRef.changes(harness.subscriptionCount).pipe(
1853 + Stream.filter((count) => count >= 2),
1854 + Stream.runHead,
1855 + );
1856 + expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(2);
1857 expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 4);
1858 }),
1859 );
packages/shared/src/atomicWrite.test.ts
+2 -12
@@ -124,24 +124,14 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
124 yield* Deferred.await(firstAttempt);
125 yield* writeFileStringAtomically({ filePath, contents: "newer" });
126
127 - assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
127 + yield* TestClock.adjust("100 millis");
128 + assert.isTrue(Exit.isFailure(yield* Fiber.join(stale)));
129 assert.strictEqual(yield* fs.readFileString(filePath), "newer");
130 assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
131 }),
132 );
133 });
134
134 -// Advance one retry at a time because real target-stat I/O runs outside the test clock.
135 -const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
136 - Effect.gen(function* () {
137 - while (fiber.pollUnsafe() === undefined) {
138 - yield* TestClock.adjust("100 millis");
139 - // 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
140 - yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
141 - }
142 - return yield* Fiber.join(fiber);
143 - });
144 -
135 const renameError = (code: string, path: string) =>
136 PlatformError.systemError({
137 _tag: "Unknown",
vite.config.ts
-22
@@ -315,28 +315,6 @@ export default defineConfig({
315 files: ["apps/web/src/**/*.browser.test.{ts,tsx}"],
316 rules: { "t3code/no-frame-waits-in-browser-tests": "error" },
317 },
318 - {
319 - // Burn-down list: these files still have polling loops, so they stay at "warn".
320 - // Remove a file when you convert its loops. New polling loops in all other
321 - // test files fail lint. Do not add new files to this list.
322 - files: [
323 - "apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts",
324 - "apps/server/src/background/HostPowerMonitor.test.ts",
325 - "apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts",
326 - "apps/server/src/orchestration-v2/FoundationPersistence.test.ts",
327 - "apps/server/src/project/ProjectEnrichmentService.test.ts",
328 - "apps/server/src/project/ProjectService.test.ts",
329 - "apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts",
330 - "apps/server/src/usage/UsageService.test.ts",
331 - "packages/client-runtime/src/connection/supervisor.test.ts",
332 - "packages/client-runtime/src/rpc/client.test.ts",
333 - "packages/client-runtime/src/rpc/session.test.ts",
334 - "packages/client-runtime/src/state/shell-sync.test.ts",
335 - "packages/client-runtime/src/state/threads-sync.test.ts",
336 - "packages/shared/src/atomicWrite.test.ts",
337 - ],
338 - rules: { "t3code/no-polling-loop-in-tests": "warn" },
339 - },
318 {
319 files: ["apps/**/src/**", "packages/**/src/**"],
320 excludeFiles: DOM_TEST_ENVIRONMENT_ALLOWLIST,