Skip to content
TypeScript

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

Julius Marminge695f5c9963f5
diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
index f1d223cf637..d2ce9ca5580 100644
--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
@@ -219,6 +219,7 @@ const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pip
const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")(
function* () {
let idlePasses = 0;
+ // 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.
for (;;) {
yield* Effect.promise(() => Promise.resolve());
const pending = backgroundRuntime.pending.shift();
diff --git a/apps/server/src/background/HostPowerMonitor.test.ts b/apps/server/src/background/HostPowerMonitor.test.ts
index 8b6034f7e0c..15ab578d222 100644
--- a/apps/server/src/background/HostPowerMonitor.test.ts
+++ b/apps/server/src/background/HostPowerMonitor.test.ts
@@ -1,6 +1,7 @@
import type { DesktopHostTelemetrySnapshot } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
@@ -114,6 +115,7 @@ describe("HostPowerMonitor", () => {
},
};
const desktopChanges = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(1);
+ const changeApplied = yield* Deferred.make<void>();
const layerReceiver = DesktopTelemetryReceiver.layerTest({
latest: Effect.succeedSome(initial),
changes: Stream.empty,
@@ -122,7 +124,10 @@ describe("HostPowerMonitor", () => {
yield* PubSub.publish(desktopChanges, updated);
return {
latest: Option.some(initial),
- changes: Stream.fromSubscription(subscription),
+ changes: Stream.fromSubscription(subscription).pipe(
+ Stream.take(1),
+ Stream.ensuring(Deferred.succeed(changeApplied, undefined)),
+ ),
};
}),
});
@@ -130,13 +135,7 @@ describe("HostPowerMonitor", () => {
yield* Effect.gen(function* () {
const monitor = yield* HostPowerMonitor.HostPowerMonitor;
- for (
- let attempt = 0;
- attempt < 100 && (yield* monitor.snapshot).onBattery !== "true";
- attempt += 1
- ) {
- yield* Effect.yieldNow;
- }
+ yield* Deferred.await(changeApplied);
expect((yield* monitor.snapshot).onBattery).toBe("true");
}).pipe(Effect.provide(layer));
}),
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index e199720c314..1cb40e1fab2 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -4169,6 +4169,7 @@ describe("AcpAdapterV2", () => {
const responseWritten = yield* Deferred.make<void>();
const releaseResponseAcknowledgement = yield* Deferred.make<void>();
const responseLifecycle: Array<string> = [];
+ const responseFailed = yield* Deferred.make<void>();
const instanceId = ProviderInstanceId.make("acp-test-normal-close-held-response");
const adapter = yield* makeAcpAdapterV2({
instanceId,
@@ -4191,6 +4192,7 @@ describe("AcpAdapterV2", () => {
onNativeResponseLifecycle: (event) =>
Effect.sync(() => {
responseLifecycle.push(event.type);
+ if (event.type === "failed") Deferred.doneUnsafe(responseFailed, Effect.void);
}),
},
});
@@ -4244,9 +4246,7 @@ describe("AcpAdapterV2", () => {
yield* Deferred.await(responseWritten);
const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped);
- while (!responseLifecycle.includes("failed")) {
- yield* Effect.yieldNow;
- }
+ yield* Deferred.await(responseFailed);
const responseExit = yield* Fiber.join(responseFiber);
if (Exit.isSuccess(responseExit)) {
assert.fail("normal close must fail a response whose transport acknowledgement is held");
@@ -6234,6 +6234,7 @@ describe("AcpAdapterV2", () => {
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
const promptGates: Array<Deferred.Deferred<EffectAcpSchema.PromptResponse, never>> = [];
+ const promptStarted = yield* Queue.unbounded<void>();
const capturedMutation: {
current:
| ((mutation: {
@@ -6304,6 +6305,7 @@ describe("AcpAdapterV2", () => {
Effect.gen(function* () {
const gate = yield* Deferred.make<EffectAcpSchema.PromptResponse>();
promptGates.push(gate);
+ yield* Queue.offer(promptStarted, undefined);
return yield* Deferred.await(gate);
}),
}),
@@ -6354,9 +6356,7 @@ describe("AcpAdapterV2", () => {
makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }),
)
.pipe(Effect.forkScoped);
- while (promptGates.length < 1) {
- yield* Effect.yieldNow;
- }
+ yield* Queue.take(promptStarted);
assert.isDefined(sessionUpdateHandler, "session update handler must be wired");
const applyMutation = capturedMutation.current;
if (applyMutation === null) {
@@ -6489,9 +6489,7 @@ describe("AcpAdapterV2", () => {
}),
)
.pipe(Effect.forkScoped);
- while (promptGates.length < 2) {
- yield* Effect.yieldNow;
- }
+ yield* Queue.take(promptStarted);
if (sessionUpdateHandler === undefined || capturedMutation.current === null) {
return yield* Effect.die("extensions and session handler must be wired for turn 2");
}
diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
index 2ce2b5ae5e4..b21f76b3244 100644
--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
@@ -737,6 +737,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
});
let afterSequence = created[0]!.sequence;
+ // 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.
for (let index = 1; index <= 32; index += 1) {
const nextEvent = {
id: EventId.make(`event:foundation-stream-race:${index}`),
@@ -2426,6 +2427,8 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
const releaseA1 = yield* Deferred.make<void>();
const releaseA2 = yield* Deferred.make<void>();
const releaseB1 = yield* Deferred.make<void>();
+ const settled = yield* Deferred.make<void>();
+ const completed = yield* Ref.make(0);
const gates = new Map([
[effectA1, { started: startedA1, release: releaseA1 }],
[effectA2, { started: startedA2, release: releaseA2 }],
@@ -2447,7 +2450,24 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
workerId: "concurrency-worker",
}).pipe(
Layer.provide(
- Layer.merge(Layer.succeed(EffectOutbox.EffectOutboxV2, outbox), layerExecutor),
+ Layer.merge(
+ Layer.succeed(EffectOutbox.EffectOutboxV2, {
+ ...outbox,
+ succeed: (input) =>
+ outbox
+ .succeed(input)
+ .pipe(
+ Effect.tap(() =>
+ Ref.updateAndGet(completed, (count) => count + 1).pipe(
+ Effect.flatMap((count) =>
+ count === 3 ? Deferred.succeed(settled, undefined) : Effect.void,
+ ),
+ ),
+ ),
+ ),
+ }),
+ layerExecutor,
+ ),
),
);
@@ -2493,13 +2513,12 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
yield* Deferred.succeed(releaseB1, undefined);
yield* Deferred.await(startedA2);
yield* Deferred.succeed(releaseA2, undefined);
- let settled = false;
- while (!settled) {
- settled = (yield* outbox.listByCommandId(commandId)).every(
+ yield* Deferred.await(settled);
+ assert.isTrue(
+ (yield* outbox.listByCommandId(commandId)).every(
(effect) => effect.status === "succeeded",
- );
- if (!settled) yield* Effect.yieldNow;
- }
+ ),
+ );
}).pipe(Effect.provide(layerWorker), Effect.scoped);
}),
);
diff --git a/apps/server/src/project/ProjectEnrichmentService.test.ts b/apps/server/src/project/ProjectEnrichmentService.test.ts
index 492d1c43419..6da9ae31203 100644
--- a/apps/server/src/project/ProjectEnrichmentService.test.ts
+++ b/apps/server/src/project/ProjectEnrichmentService.test.ts
@@ -25,12 +25,16 @@ const waitForAvailable = Effect.fn("ProjectEnrichmentServiceTest.waitForAvailabl
workspaceRoot: string,
predicate: (value: ProjectEnrichment.ProjectEnrichment) => boolean,
) {
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const available = yield* service.peek(workspaceRoot);
- if (predicate(available)) return available;
- yield* Effect.yieldNow;
- }
- return yield* Effect.die(`Project metadata for ${workspaceRoot} was not resolved in time.`);
+ return yield* Effect.scoped(
+ Effect.gen(function* () {
+ const changes = yield* service.subscribeChanges;
+ for (;;) {
+ const available = yield* service.peek(workspaceRoot);
+ if (predicate(available)) return available;
+ yield* PubSub.take(changes);
+ }
+ }),
+ );
});
const layer = (
diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts
index 5ea7871e94e..331332a84bc 100644
--- a/apps/server/src/project/ProjectService.test.ts
+++ b/apps/server/src/project/ProjectService.test.ts
@@ -1,3 +1,6 @@
+import * as Context from "effect/Context";
+import * as Queue from "effect/Queue";
+import * as Tracer from "effect/Tracer";
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { CommandId, type Project, ProjectId, ProviderInstanceId } from "@t3tools/contracts";
@@ -56,6 +59,35 @@ const layerMetadata = Layer.merge(
}),
);
+class EnrichmentCompletions extends Context.Service<EnrichmentCompletions, Queue.Queue<void>>()(
+ "t3/project/ProjectService.test/EnrichmentCompletions",
+) {}
+
+const layerEnrichmentCompletions = Layer.effectContext(
+ Effect.gen(function* () {
+ const completions = yield* Queue.unbounded<void>();
+ const tracer = Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ const end = span.end.bind(span);
+ span.end = (...args) => {
+ end(...args);
+ if (
+ span.name === "ProjectEnrichmentService.resolveRepositoryIdentity" ||
+ span.name === "ProjectEnrichmentService.resolveFavicon"
+ ) {
+ Queue.offerUnsafe(completions, undefined);
+ }
+ };
+ return span;
+ },
+ });
+ return Context.make(EnrichmentCompletions, completions).pipe(
+ Context.add(Tracer.Tracer, tracer),
+ );
+ }),
+);
+
const layerTestFor = (
projectMetadataLayer: Layer.Layer<
| ProjectFaviconResolver.ProjectFaviconResolver
@@ -70,6 +102,7 @@ const layerTestFor = (
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })),
Layer.provide(NodeServices.layer),
+ Layer.provideMerge(layerEnrichmentCompletions),
);
const layerTest = layerTestFor(layerMetadata);
@@ -96,12 +129,16 @@ const waitForProject = Effect.fn("ProjectServiceTest.waitForProject")(function*
projectId: ProjectId,
predicate: (project: Project) => boolean,
) {
- for (let attempt = 0; attempt < 100; attempt += 1) {
- const project = Option.getOrThrow(yield* service.getById(projectId));
- if (predicate(project)) return project;
- yield* Effect.yieldNow;
- }
- return yield* Effect.die(`Project ${projectId} was not enriched in time.`);
+ return yield* Effect.scoped(
+ Effect.gen(function* () {
+ const completions = yield* EnrichmentCompletions;
+ for (;;) {
+ const project = Option.getOrThrow(yield* service.getById(projectId));
+ if (predicate(project)) return project;
+ yield* Queue.take(completions);
+ }
+ }),
+ );
});
it.layer(layerTest)("ProjectService", (it) => {
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
index 127f6144402..48d3024d4f9 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts
@@ -503,6 +503,20 @@ it.effect.each(queuedDeliveryCases)(
({ reason, apply }) =>
Effect.gen(function* () {
const gate = yield* Deferred.make<void>();
+ const deliveryReleased = yield* Deferred.make<void>();
+ const tracer = Tracer.make({
+ span: (options) => {
+ const span = new Tracer.NativeSpan(options);
+ const end = span.end.bind(span);
+ span.end = (...args) => {
+ end(...args);
+ if (span.name === "ScheduledTaskService.releaseFailedDelivery") {
+ Deferred.doneUnsafe(deliveryReleased, Effect.void);
+ }
+ };
+ return span;
+ },
+ });
yield* withService(
({ service, launches }) =>
Effect.gen(function* () {
@@ -513,23 +527,17 @@ it.effect.each(queuedDeliveryCases)(
yield* apply(service, task.id);
yield* Deferred.succeed(gate, undefined);
const deliveryId = queued._tag === "accepted" ? queued.deliveryId : undefined;
- let delivery = (yield* service.getWebhookDelivery({
+ yield* Deferred.await(deliveryReleased);
+ const delivery = (yield* service.getWebhookDelivery({
id: task.id,
deliveryId: deliveryId!,
})).delivery;
- while (delivery.outcome === "accepted") {
- yield* Effect.yieldNow;
- delivery = (yield* service.getWebhookDelivery({
- id: task.id,
- deliveryId: deliveryId!,
- })).delivery;
- }
assert.equal(delivery.outcome, "dispatch_failed");
assert.equal(delivery.error, reason);
assert.equal(yield* Queue.size(launches), 0);
}),
{ gate },
- );
+ ).pipe(Effect.withTracer(tracer));
}),
);
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index 948d512b6cc..4cd1143ac37 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -2610,6 +2610,7 @@ describe("UsageService", () => {
);
let orphanedAt: number | undefined;
+ // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- Fixed-count scheduler interruption matrix; each iteration exercises a different interruption point.
for (let interruptAt = 1; interruptAt <= 31; interruptAt += 1) {
const tasks: Array<() => void> = [];
const dispatcher: Scheduler.SchedulerDispatcher = {
diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts
index 0306a86ef49..cfdf8f63369 100644
--- a/packages/client-runtime/src/connection/supervisor.test.ts
+++ b/packages/client-runtime/src/connection/supervisor.test.ts
@@ -127,25 +127,6 @@ function awaitState(
);
}
-const eventuallyState = Effect.fn("TestConnectionHarness.eventuallyState")(function* (
- state: SubscriptionRef.SubscriptionRef<SupervisorConnectionState>,
- predicate: (value: SupervisorConnectionState) => boolean,
-) {
- let lastState = yield* SubscriptionRef.get(state);
- for (let iteration = 0; iteration < 100; iteration += 1) {
- lastState = yield* SubscriptionRef.get(state);
- if (predicate(lastState)) {
- return lastState;
- }
- yield* Effect.yieldNow;
- }
- return yield* Effect.die(
- new Error(
- `Expected supervisor state was not observed. Last state: phase=${lastState.phase}, stage=${lastState.stage ?? "none"}, attempt=${lastState.attempt}, generation=${lastState.generation}`,
- ),
- );
-});
-
const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?: {
readonly networkStatus?: NetworkStatus;
readonly prepare?: (
@@ -477,7 +458,7 @@ describe("EnvironmentSupervisor", () => {
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
yield* TestClock.adjust("15 seconds");
- const retrying = yield* eventuallyState(
+ const retrying = yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" && state.attempt === 1,
);
diff --git a/packages/client-runtime/src/rpc/client.test.ts b/packages/client-runtime/src/rpc/client.test.ts
index bbd86f2f791..78ad44aca19 100644
--- a/packages/client-runtime/src/rpc/client.test.ts
+++ b/packages/client-runtime/src/rpc/client.test.ts
@@ -112,15 +112,18 @@ describe("environment RPC", () => {
it.effect("switches durable subscriptions when the supervisor replaces the session", () =>
Effect.gen(function* () {
const subscriptions: string[] = [];
+ const subscriptionChanges = yield* Queue.make<void>();
const firstClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("first");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.never;
},
} as unknown as WsRpcProtocolClient;
const secondClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("second");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.never;
},
} as unknown as WsRpcProtocolClient;
@@ -128,13 +131,12 @@ describe("environment RPC", () => {
const awaitSubscriptions = Effect.fn("TestEnvironmentRpc.awaitSubscriptions")(function* (
count: number,
) {
- for (let attempt = 0; attempt < 100; attempt += 1) {
+ for (;;) {
if (subscriptions.length >= count) {
return;
}
- yield* Effect.yieldNow;
+ yield* Queue.take(subscriptionChanges);
}
- return yield* Effect.die(new Error(`Expected ${count} durable subscriptions.`));
});
const subscriptionFiber = yield* subscribe(WS_METHODS.subscribeTerminalEvents, {}).pipe(
@@ -222,9 +224,11 @@ describe("environment RPC", () => {
it.effect("keeps durable subscriptions alive across a transport failure and new session", () =>
Effect.gen(function* () {
const subscriptions: string[] = [];
+ const subscriptionChanges = yield* Queue.make<void>();
const firstClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("first");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.fail(
new RpcClientError.RpcClientError({
reason: new RpcClientError.RpcClientDefect({
@@ -238,6 +242,7 @@ describe("environment RPC", () => {
const secondClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("second");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.never;
},
} as unknown as WsRpcProtocolClient;
@@ -249,14 +254,14 @@ describe("environment RPC", () => {
Effect.forkChild,
);
yield* SubscriptionRef.set(activeSession, Option.some(session(firstClient)));
- for (let attempt = 0; attempt < 100 && subscriptions.length < 1; attempt += 1) {
- yield* Effect.yieldNow;
+ while (subscriptions.length < 1) {
+ yield* Queue.take(subscriptionChanges);
}
yield* SubscriptionRef.set(activeSession, Option.none());
yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient)));
- for (let attempt = 0; attempt < 100 && subscriptions.length < 2; attempt += 1) {
- yield* Effect.yieldNow;
+ while (subscriptions.length < 2) {
+ yield* Queue.take(subscriptionChanges);
}
yield* Fiber.interrupt(subscriptionFiber);
@@ -289,16 +294,20 @@ describe("environment RPC", () => {
Effect.gen(function* () {
const domainError = new Error("terminal subscription rejected");
const subscriptions: string[] = [];
+ const subscriptionChanges = yield* Queue.make<void>();
const observedFailures: Error[] = [];
+ const failureObserved = yield* Deferred.make<void>();
const firstClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("first");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.fail(domainError);
},
} as unknown as WsRpcProtocolClient;
const secondClient = {
[WS_METHODS.subscribeTerminalEvents]: () => {
subscriptions.push("second");
+ Queue.offerUnsafe(subscriptionChanges, undefined);
return Stream.never;
},
} as unknown as WsRpcProtocolClient;
@@ -312,6 +321,7 @@ describe("environment RPC", () => {
onExpectedFailure: (cause) =>
Effect.sync(() => {
observedFailures.push(Cause.squash(cause) as Error);
+ Deferred.doneUnsafe(failureObserved, Effect.void);
}),
},
).pipe(
@@ -319,16 +329,14 @@ describe("environment RPC", () => {
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.forkChild,
);
- for (let attempt = 0; attempt < 100 && observedFailures.length < 1; attempt += 1) {
- yield* Effect.yieldNow;
- }
+ yield* Deferred.await(failureObserved);
expect(subscriptions).toEqual(["first"]);
expect(observedFailures).toEqual([domainError]);
yield* SubscriptionRef.set(activeSession, Option.some(session(secondClient)));
- for (let attempt = 0; attempt < 100 && subscriptions.length < 2; attempt += 1) {
- yield* Effect.yieldNow;
+ while (subscriptions.length < 2) {
+ yield* Queue.take(subscriptionChanges);
}
yield* Fiber.interrupt(subscriptionFiber);
diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts
index 3d024b9dc75..b0c5857ca9c 100644
--- a/packages/client-runtime/src/rpc/session.test.ts
+++ b/packages/client-runtime/src/rpc/session.test.ts
@@ -53,10 +53,12 @@ class TestWebSocket {
readyState = TestWebSocket.CONNECTING;
readonly sent: string[] = [];
readonly url: string;
+ readonly sentChanges: Queue.Queue<void>;
private readonly listeners = new Map<SocketEventType, Set<SocketListener>>();
- constructor(url: string) {
+ constructor(url: string, sentChanges: Queue.Queue<void>) {
this.url = url;
+ this.sentChanges = sentChanges;
}
addEventListener(type: SocketEventType, listener: SocketListener) {
@@ -71,6 +73,7 @@ class TestWebSocket {
send(data: string) {
this.sent.push(data);
+ Queue.offerUnsafe(this.sentChanges, undefined);
}
close(code = 1000, reason = "") {
@@ -208,10 +211,12 @@ const LEGACY_SERVER_CONFIG = {
const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* (
options: RpcSession.RpcSessionOptions = {},
) {
- const sockets: TestWebSocket[] = [];
+ const sentChanges = yield* Queue.unbounded<void>();
+ const sockets = Object.assign([] as TestWebSocket[], { changes: yield* Queue.unbounded<void>() });
const layerConstructor = Layer.succeed(Socket.WebSocketConstructor, (url) => {
- const socket = new TestWebSocket(url);
+ const socket = new TestWebSocket(url, sentChanges);
sockets.push(socket);
+ Queue.offerUnsafe(sockets.changes, undefined);
return socket as unknown as globalThis.WebSocket;
});
const layer = RpcSession.layer(options).pipe(Layer.provide(layerConstructor));
@@ -220,31 +225,29 @@ const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* (
});
const awaitSocket = Effect.fn("TestRpcSessionFactory.awaitSocket")(function* (
- sockets: ReadonlyArray<TestWebSocket>,
+ sockets: ReadonlyArray<TestWebSocket> & { readonly changes: Queue.Queue<void> },
index = 0,
) {
- for (let attempt = 0; attempt < 100; attempt += 1) {
+ for (;;) {
const socket = sockets[index];
if (socket) {
return socket;
}
- yield* Effect.yieldNow;
+ yield* Queue.take(sockets.changes);
}
- return yield* Effect.die(new Error("Expected the RPC protocol to create a websocket."));
});
const awaitRequest = Effect.fn("TestRpcSessionFactory.awaitRequest")(function* (
socket: TestWebSocket,
index = 0,
) {
- for (let attempt = 0; attempt < 100; attempt += 1) {
+ for (;;) {
const request = socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)[index];
if (request) {
return request;
}
- yield* Effect.yieldNow;
+ yield* Queue.take(socket.sentChanges);
}
- return yield* Effect.die(new Error("Expected the RPC protocol to send a request."));
});
const completeInitialConfig = Effect.fn("TestRpcSessionFactory.completeInitialConfig")(function* (
diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts
index b9b2e343fa5..2941e812787 100644
--- a/packages/client-runtime/src/state/shell-sync.test.ts
+++ b/packages/client-runtime/src/state/shell-sync.test.ts
@@ -124,11 +124,11 @@ const makePersistenceHarness = Effect.fn("test.makeShellPersistenceHarness")(fun
describe("environment shell synchronization", () => {
it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>
Effect.gen(function* () {
- const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
+ const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
yield* Effect.scoped(
Effect.gen(function* () {
const h = yield* makePersistenceHarness((_id, snapshot) =>
- Ref.update(saved, (values) => [...values, snapshot]),
+ SubscriptionRef.update(saved, (values) => [...values, snapshot]),
);
yield* TestClock.adjust("500 millis");
yield* h.send(
@@ -136,7 +136,9 @@ describe("environment shell synchronization", () => {
(snapshot) => snapshot.snapshotSequence === 10,
);
yield* TestClock.adjust("10 seconds");
- expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);
+ expect(
+ (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
+ ).toEqual([1]);
const live = Option.getOrThrow((yield* SubscriptionRef.get(h.state)).snapshot);
expect(live.snapshotSequence).toBe(10);
const enriched = yield* h.send(
@@ -152,7 +154,9 @@ describe("environment shell synchronization", () => {
expect(enriched.projects).toEqual(live.projects);
expect(enriched.snapshotSequence).toBe(10);
yield* TestClock.adjust("10 seconds");
- expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);
+ expect(
+ (yield* SubscriptionRef.get(saved)).map((snapshot) => snapshot.snapshotSequence),
+ ).toEqual([1]);
yield* h.send(
{ kind: "snapshot", snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 4 } },
(snapshot) => snapshot.snapshotSequence === 4,
@@ -172,7 +176,7 @@ describe("environment shell synchronization", () => {
}),
);
expect(
- (yield* Ref.get(saved)).map((snapshot) => [
+ (yield* SubscriptionRef.get(saved)).map((snapshot) => [
snapshot.snapshotSequence,
snapshot.projects[0]?.title,
]),
@@ -217,7 +221,7 @@ describe("environment shell synchronization", () => {
it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
Effect.gen(function* () {
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
- const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
+ const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const saveStarted = yield* Deferred.make<void>();
const releaseSave = yield* Deferred.make<void>();
const client = {
@@ -241,7 +245,7 @@ describe("environment shell synchronization", () => {
saveShell: (_environmentId, snapshot) =>
Deferred.succeed(saveStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseSave)),
- Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
+ Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
),
loadThread: () => Effect.succeedNone,
saveThread: () => Effect.void,
@@ -316,21 +320,21 @@ describe("environment shell synchronization", () => {
lastFailure: null,
retryAt: null,
});
- for (let index = 0; index < 100; index += 1) {
- if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
- yield* Effect.yieldNow;
- }
+ yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.filter((state) => state.status === "synchronizing"),
+ Stream.runHead,
+ );
expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
- expect(yield* Ref.get(saved)).toEqual([]);
+ expect(yield* SubscriptionRef.get(saved)).toEqual([]);
yield* Deferred.succeed(releaseSave, undefined);
- for (let index = 0; index < 100; index += 1) {
- if ((yield* Ref.get(saved)).length > 0) break;
- yield* Effect.yieldNow;
- }
+ yield* SubscriptionRef.changes(saved).pipe(
+ Stream.filter((values) => values.length > 0),
+ Stream.runHead,
+ );
- expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
+ expect(yield* SubscriptionRef.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
}),
);
@@ -356,7 +360,7 @@ describe("environment shell synchronization", () => {
};
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
- const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
+ const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const unenrichedSaveStarted = yield* Deferred.make<void>();
const releaseUnenrichedSave = yield* Deferred.make<void>();
const client = {
@@ -383,7 +387,7 @@ describe("environment shell synchronization", () => {
yield* Deferred.succeed(unenrichedSaveStarted, undefined);
yield* Deferred.await(releaseUnenrichedSave);
}
- yield* Ref.update(saved, (values) => [...values, snapshot]);
+ yield* SubscriptionRef.update(saved, (values) => [...values, snapshot]);
}),
loadThread: () => Effect.succeedNone,
saveThread: () => Effect.void,
@@ -454,15 +458,12 @@ describe("environment shell synchronization", () => {
);
yield* Deferred.succeed(releaseUnenrichedSave, undefined);
- for (let index = 0; index < 100; index += 1) {
- const values = yield* Ref.get(saved);
- if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
- break;
- }
- yield* Effect.yieldNow;
- }
+ yield* SubscriptionRef.changes(saved).pipe(
+ Stream.filter((values) => values.at(-1)?.projects[0]?.repositoryIdentity != null),
+ Stream.runHead,
+ );
- const finalSaved = (yield* Ref.get(saved)).at(-1);
+ const finalSaved = (yield* SubscriptionRef.get(saved)).at(-1);
expect(finalSaved?.snapshotSequence).toBe(1);
expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
}),
@@ -476,7 +477,7 @@ describe("environment shell synchronization", () => {
projects: [{ ...v2Project, title: "Late stream event" }],
};
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
- const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
+ const saved = yield* SubscriptionRef.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
const saveStarted = yield* Deferred.make<void>();
const releaseSave = yield* Deferred.make<void>();
const client = {
@@ -500,7 +501,7 @@ describe("environment shell synchronization", () => {
saveShell: (_environmentId, snapshot) =>
Deferred.succeed(saveStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseSave)),
- Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
+ Effect.andThen(SubscriptionRef.update(saved, (values) => [...values, snapshot])),
),
loadThread: () => Effect.succeedNone,
saveThread: () => Effect.void,
@@ -557,7 +558,7 @@ describe("environment shell synchronization", () => {
yield* Deferred.succeed(releaseSave, undefined);
yield* Fiber.join(closeFiber);
- const values = yield* Ref.get(saved);
+ const values = yield* SubscriptionRef.get(saved);
expect(values.length).toBeGreaterThan(0);
expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts
index 44e746bee1d..9095f48da7d 100644
--- a/packages/client-runtime/src/state/threads-sync.test.ts
+++ b/packages/client-runtime/src/state/threads-sync.test.ts
@@ -128,7 +128,7 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
const observed = yield* Queue.unbounded<EnvironmentThreadState>();
const latest = yield* Ref.make<EnvironmentThreadState>(EMPTY_ENVIRONMENT_THREAD_STATE);
const retryCount = yield* Ref.make(0);
- const subscriptionCount = yield* Ref.make(0);
+ const subscriptionCount = yield* SubscriptionRef.make(0);
const loaderCalls = yield* Ref.make(0);
const lastSubscribeAfterSequence = yield* Ref.make<number | undefined>(undefined);
const lastRequestCompletionMarker = yield* Ref.make(false);
@@ -154,13 +154,13 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o
readonly acceptCompactTurnItems?: true;
}) =>
Stream.unwrap(
- Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe(
- Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)),
+ Ref.set(lastSubscribeAfterSequence, input.afterSequence).pipe(
Effect.andThen(
Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true),
),
Effect.andThen(Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot)),
Effect.andThen(Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems)),
+ Effect.andThen(SubscriptionRef.update(subscriptionCount, (count) => count + 1)),
Effect.as(streamFrom(inputs)),
),
),
@@ -416,7 +416,7 @@ describe("EnvironmentThreads", () => {
const state = yield* awaitThreadState(h.observed, (value) => value.status === "live");
expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION);
expect(yield* Ref.get(h.loaderCalls)).toBe(1);
- expect(yield* Ref.get(h.subscriptionCount)).toBe(1);
+ expect(yield* SubscriptionRef.get(h.subscriptionCount)).toBe(1);
}),
);
@@ -1692,7 +1692,7 @@ describe("EnvironmentThreads", () => {
expect(Option.getOrThrow(state.data).thread.title).toBe("Socket title");
expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1);
- expect(yield* Ref.get(harness.subscriptionCount)).toBe(1);
+ expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(1);
expect(yield* Ref.get(harness.removedThreads)).toEqual([]);
}),
);
@@ -1742,12 +1742,10 @@ describe("EnvironmentThreads", () => {
expect(yield* Ref.get(harness.retryCount)).toBe(0);
yield* harness.replaceSession;
- for (let attempt = 0; attempt < 100; attempt += 1) {
- if ((yield* Ref.get(harness.subscriptionCount)) >= 2) {
- break;
- }
- yield* Effect.yieldNow;
- }
+ yield* SubscriptionRef.changes(harness.subscriptionCount).pipe(
+ Stream.filter((count) => count >= 2),
+ Stream.runHead,
+ );
yield* Queue.offer(
harness.inputs,
snapshot({
@@ -1764,7 +1762,7 @@ describe("EnvironmentThreads", () => {
);
expect(Option.isNone(recovered.error)).toBe(true);
- expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
+ expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(2);
}),
);
@@ -1851,11 +1849,11 @@ describe("EnvironmentThreads", () => {
]);
yield* harness.replaceSession;
- for (let attempt = 0; attempt < 100; attempt += 1) {
- if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break;
- yield* Effect.yieldNow;
- }
- expect(yield* Ref.get(harness.subscriptionCount)).toBe(2);
+ yield* SubscriptionRef.changes(harness.subscriptionCount).pipe(
+ Stream.filter((count) => count >= 2),
+ Stream.runHead,
+ );
+ expect(yield* SubscriptionRef.get(harness.subscriptionCount)).toBe(2);
expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE + 4);
}),
);
diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.ts
index 7338519ab5f..366009f8331 100644
--- a/packages/shared/src/atomicWrite.test.ts
+++ b/packages/shared/src/atomicWrite.test.ts
@@ -124,24 +124,14 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => {
yield* Deferred.await(firstAttempt);
yield* writeFileStringAtomically({ filePath, contents: "newer" });
- assert.isTrue(Exit.isFailure(yield* advanceUntilDone(stale)));
+ yield* TestClock.adjust("100 millis");
+ assert.isTrue(Exit.isFailure(yield* Fiber.join(stale)));
assert.strictEqual(yield* fs.readFileString(filePath), "newer");
assert.deepStrictEqual(yield* fs.readDirectory(root), ["settings.json"]);
}),
);
});
-// Advance one retry at a time because real target-stat I/O runs outside the test clock.
-const advanceUntilDone = <A, E>(fiber: Fiber.Fiber<A, E>) =>
- Effect.gen(function* () {
- while (fiber.pollUnsafe() === undefined) {
- yield* TestClock.adjust("100 millis");
- // 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
- yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve)));
- }
- return yield* Fiber.join(fiber);
- });
-
const renameError = (code: string, path: string) =>
PlatformError.systemError({
_tag: "Unknown",
diff --git a/vite.config.ts b/vite.config.ts
index 22ddea7ed35..2ed89c178d4 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -315,28 +315,6 @@ export default defineConfig({
files: ["apps/web/src/**/*.browser.test.{ts,tsx}"],
rules: { "t3code/no-frame-waits-in-browser-tests": "error" },
},
- {
- // Burn-down list: these files still have polling loops, so they stay at "warn".
- // Remove a file when you convert its loops. New polling loops in all other
- // test files fail lint. Do not add new files to this list.
- files: [
- "apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts",
- "apps/server/src/background/HostPowerMonitor.test.ts",
- "apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts",
- "apps/server/src/orchestration-v2/FoundationPersistence.test.ts",
- "apps/server/src/project/ProjectEnrichmentService.test.ts",
- "apps/server/src/project/ProjectService.test.ts",
- "apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts",
- "apps/server/src/usage/UsageService.test.ts",
- "packages/client-runtime/src/connection/supervisor.test.ts",
- "packages/client-runtime/src/rpc/client.test.ts",
- "packages/client-runtime/src/rpc/session.test.ts",
- "packages/client-runtime/src/state/shell-sync.test.ts",
- "packages/client-runtime/src/state/threads-sync.test.ts",
- "packages/shared/src/atomicWrite.test.ts",
- ],
- rules: { "t3code/no-polling-loop-in-tests": "warn" },
- },
{
files: ["apps/**/src/**", "packages/**/src/**"],
excludeFiles: DOM_TEST_ENVIRONMENT_ALLOWLIST,