@devries-cameron20 / t3code-1 / commits / 08dbf834d9
Fork 0

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

test: warn on polling loops in tests and make adapter test harnesses event-driven (#22565)

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

Julius Marminge committed Oct 20, 2026 at 18:05 UTC 08dbf834d9ad9644305a40a6bece14279ec75bc1
8 files changed +927 -576
apps/desktop/src/preview/Manager.test.ts
+73 -26
@@ -376,6 +376,7 @@ const makeSourcePng = (width = 1, height = 1): Buffer => {
376 };
377
378 const makeFaviconWebContents = (options?: {
379 + readonly changes?: ChangeSignal;
380 readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
381 readonly id?: number;
382 readonly rasterize?: (code: string) => Promise<unknown>;
@@ -386,16 +387,25 @@ const makeFaviconWebContents = (options?: {
387 let currentUrl = options?.url ?? "http://localhost:3200/";
388 let destroyed = false;
389 let loading = false;
389 - const fetch = vi.fn(
390 + const fetchImpl =
391 options?.fetch ??
391 - (async () =>
392 - new Response(new Uint8Array(sourcePng), {
393 - headers: { "content-type": "image/png" },
394 - })),
395 - );
392 + (async () =>
393 + new Response(new Uint8Array(sourcePng), {
394 + headers: { "content-type": "image/png" },
395 + }));
396 + const fetch = vi.fn((url: string, init?: RequestInit) => {
397 + const response = fetchImpl(url, init);
398 + options?.changes?.notify();
399 + return response;
400 + });
401 const executeJavaScriptInIsolatedWorld = vi.fn(
397 - async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
398 - options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
402 + (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) => {
403 + const result = options?.rasterize
404 + ? options.rasterize(scripts[0]?.code ?? "")
405 + : Promise.resolve(TEST_FAVICON);
406 + options?.changes?.notify();
407 + return result;
408 + },
409 );
410 const reload = vi.fn();
411 const loadURL = vi.fn(async (url: string) => {
@@ -460,10 +470,33 @@ const makeFaviconWebContents = (options?: {
470 };
471 };
472
463 -const settle = function* (until: () => boolean) {
464 - for (let attempt = 0; attempt < 30 && !until(); attempt++) {
465 - yield* Effect.promise(() => Promise.resolve());
466 - }
473 +// Electron mocks and state subscribers call `notify`, so a wait re-checks its
474 +// predicate exactly when the state it reads changes.
475 +const makeChangeSignal = () => {
476 + const waiters = new Set<() => void>();
477 + return {
478 + notify: () => {
479 + for (const wake of waiters) wake();
480 + },
481 + until: (predicate: () => boolean) =>
482 + Effect.callback<void>((resume) => {
483 + if (predicate()) return resume(Effect.void);
484 + const wake = () => {
485 + if (!predicate()) return;
486 + waiters.delete(wake);
487 + resume(Effect.void);
488 + };
489 + waiters.add(wake);
490 + return Effect.sync(() => void waiters.delete(wake));
491 + }),
492 + };
493 +};
494 +type ChangeSignal = ReturnType<typeof makeChangeSignal>;
495 +
496 +// Favicon captures run detached from the Electron listener, so asserting that
497 +// one published nothing can only give its promise chain a fixed number of turns.
498 +const flushMicrotasks = function* () {
499 + for (let turn = 0; turn < 30; turn++) yield* Effect.promise(() => Promise.resolve());
500 };
501
502 const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
@@ -843,11 +876,13 @@ describe("PreviewManager", () => {
876 effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
877 withManager((manager) =>
878 Effect.gen(function* () {
879 + const changes = makeChangeSignal();
880 let resolveFirst!: (response: Response) => void;
881 const firstResponse = new Promise<Response>((resolve) => {
882 resolveFirst = resolve;
883 });
884 const preview = makeFaviconWebContents({
885 + changes,
886 fetch: (url) =>
887 url.endsWith("first.png")
888 ? firstResponse
@@ -862,6 +897,7 @@ describe("PreviewManager", () => {
897 yield* manager.subscribeStateChanges((_tabId, state) =>
898 Effect.sync(() => {
899 states.push(state);
900 + changes.notify();
901 }),
902 );
903 yield* manager.createTab("tab_favicon_latest");
@@ -870,15 +906,15 @@ describe("PreviewManager", () => {
906 const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
907 faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
908 faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
873 - yield* settle(() => preview.fetch.mock.calls.length === 1);
909 + yield* changes.until(() => preview.fetch.mock.calls.length === 1);
910 faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
875 - yield* settle(() => states.at(-1)?.favicon !== undefined);
911 + yield* changes.until(() => states.at(-1)?.favicon !== undefined);
912 resolveFirst(
913 new Response(new Uint8Array(makeSourcePng()), {
914 headers: { "content-type": "image/png" },
915 }),
916 );
881 - yield* settle(() => false);
917 + yield* flushMicrotasks();
918
919 expect(preview.fetch).toHaveBeenCalledTimes(2);
920 expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
@@ -889,8 +925,10 @@ describe("PreviewManager", () => {
925 effectIt.effect("allows an identical retry after an undecodable capture", () =>
926 withManager((manager) =>
927 Effect.gen(function* () {
928 + const changes = makeChangeSignal();
929 let rasterizations = 0;
930 const preview = makeFaviconWebContents({
931 + changes,
932 rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
933 });
934 fromId.mockReturnValue(preview.webContents);
@@ -898,6 +936,7 @@ describe("PreviewManager", () => {
936 yield* manager.subscribeStateChanges((_tabId, state) =>
937 Effect.sync(() => {
938 states.push(state);
939 + changes.notify();
940 }),
941 );
942 yield* manager.createTab("tab_favicon_retry");
@@ -905,10 +944,10 @@ describe("PreviewManager", () => {
944 const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
945
946 faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
908 - yield* settle(() => rasterizations === 1);
909 - yield* settle(() => false);
947 + yield* changes.until(() => rasterizations === 1);
948 + yield* flushMicrotasks();
949 faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
911 - yield* settle(() => states.at(-1)?.favicon !== undefined);
950 + yield* changes.until(() => states.at(-1)?.favicon !== undefined);
951
952 expect(rasterizations).toBe(2);
953 expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
@@ -919,8 +958,10 @@ describe("PreviewManager", () => {
958 effectIt.effect("does not publish a capture invalidated by navigation", () =>
959 withManager((manager) =>
960 Effect.gen(function* () {
961 + const changes = makeChangeSignal();
962 let resolveFetch!: (response: Response) => void;
963 const preview = makeFaviconWebContents({
964 + changes,
965 fetch: () =>
966 new Promise<Response>((resolve) => {
967 resolveFetch = resolve;
@@ -931,6 +972,7 @@ describe("PreviewManager", () => {
972 yield* manager.subscribeStateChanges((_tabId, state) =>
973 Effect.sync(() => {
974 states.push(state);
975 + changes.notify();
976 }),
977 );
978 yield* manager.createTab("tab_favicon_navigation");
@@ -939,7 +981,7 @@ describe("PreviewManager", () => {
981 {} as never,
982 ["http://localhost:3200/favicon.png"] as never,
983 );
942 - yield* settle(() => preview.fetch.mock.calls.length === 1);
984 + yield* changes.until(() => preview.fetch.mock.calls.length === 1);
985 preview.listeners.get("did-start-navigation")?.({
986 isMainFrame: true,
987 isSameDocument: false,
@@ -950,7 +992,7 @@ describe("PreviewManager", () => {
992 headers: { "content-type": "image/png" },
993 }),
994 );
953 - yield* settle(() => false);
995 + yield* flushMicrotasks();
996
997 expect(states.some((state) => state.favicon !== undefined)).toBe(false);
998 }),
@@ -960,15 +1002,17 @@ describe("PreviewManager", () => {
1002 effectIt.effect("ignores an old capture that completes after webview replacement", () =>
1003 withManager((manager) =>
1004 Effect.gen(function* () {
1005 + const changes = makeChangeSignal();
1006 let resolveFetch!: (response: Response) => void;
1007 const initial = makeFaviconWebContents({
1008 + changes,
1009 id: 42,
1010 fetch: () =>
1011 new Promise<Response>((resolve) => {
1012 resolveFetch = resolve;
1013 }),
1014 });
971 - const replacement = makeFaviconWebContents({ id: 43 });
1015 + const replacement = makeFaviconWebContents({ changes, id: 43 });
1016 fromId.mockImplementation((id?: number) =>
1017 id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
1018 );
@@ -976,6 +1020,7 @@ describe("PreviewManager", () => {
1020 yield* manager.subscribeStateChanges((_tabId, state) =>
1021 Effect.sync(() => {
1022 states.push(state);
1023 + changes.notify();
1024 }),
1025 );
1026 yield* manager.createTab("tab_favicon_late_replace");
@@ -984,7 +1029,7 @@ describe("PreviewManager", () => {
1029 {} as never,
1030 ["http://localhost:3200/favicon.png"] as never,
1031 );
987 - yield* settle(() => initial.fetch.mock.calls.length === 1);
1032 + yield* changes.until(() => initial.fetch.mock.calls.length === 1);
1033
1034 yield* manager.registerWebview("tab_favicon_late_replace", 43);
1035 resolveFetch(
@@ -992,7 +1037,7 @@ describe("PreviewManager", () => {
1037 headers: { "content-type": "image/png" },
1038 }),
1039 );
995 - yield* settle(() => false);
1040 + yield* flushMicrotasks();
1041
1042 expect(states.at(-1)?.webContentsId).toBe(43);
1043 expect(
@@ -1005,14 +1050,16 @@ describe("PreviewManager", () => {
1050 effectIt.effect("treats a reused WebContents id as a new attachment", () =>
1051 withManager((manager) =>
1052 Effect.gen(function* () {
1008 - const initial = makeFaviconWebContents({ id: 42 });
1009 - const replacement = makeFaviconWebContents({ id: 42 });
1053 + const changes = makeChangeSignal();
1054 + const initial = makeFaviconWebContents({ changes, id: 42 });
1055 + const replacement = makeFaviconWebContents({ changes, id: 42 });
1056 let active = initial.webContents;
1057 fromId.mockImplementation(() => active);
1058 const states: PreviewManager.PreviewTabState[] = [];
1059 yield* manager.subscribeStateChanges((_tabId, state) =>
1060 Effect.sync(() => {
1061 states.push(state);
1062 + changes.notify();
1063 }),
1064 );
1065 yield* manager.createTab("tab_favicon_reused_id");
@@ -1021,7 +1068,7 @@ describe("PreviewManager", () => {
1068 {} as never,
1069 ["http://localhost:3200/favicon.png"] as never,
1070 );
1024 - yield* settle(() => states.at(-1)?.favicon !== undefined);
1071 + yield* changes.until(() => states.at(-1)?.favicon !== undefined);
1072
1073 active = replacement.webContents;
1074 yield* manager.registerWebview("tab_favicon_reused_id", 42);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+276 -384
@@ -61,6 +61,7 @@ import * as Fiber from "effect/Fiber";
61 import * as Layer from "effect/Layer";
62 import * as Option from "effect/Option";
63 import * as Path from "effect/Path";
64 +import * as PubSub from "effect/PubSub";
65 import * as Queue from "effect/Queue";
66 import * as Schema from "effect/Schema";
67 import * as Scope from "effect/Scope";
@@ -2273,15 +2274,26 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2274 terminalReason: null,
2275 });
2276
2276 - const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect<void> =>
2277 + // Harnesses notify after every recorded event, continuation, or prompt, so a
2278 + // wait re-checks exactly when the state it reads changes. Subscribing before
2279 + // the first check means a change that lands in between is not lost.
2280 + const makeChangeSignal = Effect.gen(function* () {
2281 + const changes = yield* PubSub.unbounded<void>();
2282 + const until = (predicate: () => boolean): Effect.Effect<void> =>
2283 + Effect.scoped(
2284 + Effect.gen(function* () {
2285 + const subscription = yield* PubSub.subscribe(changes);
2286 + while (!predicate()) yield* PubSub.take(subscription);
2287 + }),
2288 + );
2289 + return { notify: PubSub.publish(changes, undefined), until };
2290 + });
2291 +
2292 + // Fixed quiet windows for asserting that nothing happens after input the
2293 + // harness cannot observe being handled (a shut-down query, a replaced process).
2294 + const yieldTicks = (ticks: number): Effect.Effect<void> =>
2295 Effect.gen(function* () {
2278 - for (let attempt = 0; attempt < 5000; attempt++) {
2279 - if (predicate()) {
2280 - return;
2281 - }
2282 - yield* Effect.yieldNow;
2283 - }
2284 - return yield* Effect.die(`Timed out waiting for ${label}.`);
2296 + for (let tick = 0; tick < ticks; tick++) yield* Effect.yieldNow;
2297 });
2298
2299 const makeWakeHarnessWithOptions = (options?: {
@@ -2321,6 +2333,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2333 if (offered !== undefined) yield* Deferred.succeed(offered, undefined);
2334 yield* Deferred.await(processed);
2335 });
2336 + const changes = yield* makeChangeSignal;
2337 const offeredMessages: Array<SDKUserMessage> = [];
2338 const permissionModeChanges: Array<string> = [];
2339 const liveSelectionChanges: Array<unknown> = [];
@@ -2362,7 +2375,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2375 offer: (request) =>
2376 Effect.sync(() => {
2377 continuationRequests.push(request);
2365 - }).pipe(Effect.andThen(Queue.offer(continuationReceipts, request))),
2378 + }).pipe(
2379 + Effect.andThen(Queue.offer(continuationReceipts, request)),
2380 + Effect.andThen(changes.notify),
2381 + ),
2382 },
2383 queryRunner: {
2384 allocateSessionId:
@@ -2398,7 +2414,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2414 offer: (message: SDKUserMessage) =>
2415 Effect.sync(() => {
2416 offeredMessages.push(message);
2401 - }),
2417 + }).pipe(Effect.andThen(changes.notify)),
2418 setModel: () => Effect.void,
2419 applyFlagSettings: () => Effect.void,
2420 setPermissionMode: (mode) =>
@@ -2419,7 +2435,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2435 offer: (message) =>
2436 Effect.sync(() => {
2437 offeredMessages.push(message);
2422 - }),
2438 + }).pipe(Effect.andThen(changes.notify)),
2439 setModel: (model) =>
2440 Effect.sync(() => {
2441 liveSelectionChanges.push({ model });
@@ -2475,6 +2491,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2491 if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") {
2492 yield* Queue.offer(systemNoticeReceipts, event);
2493 }
2494 + yield* changes.notify;
2495 }),
2496 ),
2497 Effect.forkScoped,
@@ -2517,6 +2534,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2534 getOpenedOptions: () => openedOptions,
2535 terminalEvents,
2536 hasPendingBackgroundWork,
2537 + until: changes.until,
2538 + awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count),
2539 + awaitContinuation: (count: number) =>
2540 + changes.until(() => continuationRequests.length >= count),
2541 };
2542 });
2543 const makeWakeHarness = makeWakeHarnessWithOptions();
@@ -6226,7 +6247,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6247 ? [event.turnItem]
6248 : [],
6249 );
6229 - yield* awaitUntil(() => retryItems().length === 1, "Claude retry item");
6250 + yield* harness.until(() => retryItems().length === 1);
6251 const runningRetry = retryItems()[0];
6252 assert.equal(runningRetry?.status, "running");
6253 assert.equal(runningRetry?.failure.code, "api_error_529");
@@ -6243,7 +6264,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6264 text: "Opening GitHub.",
6265 }),
6266 );
6246 - yield* awaitUntil(() => retryItems().length === 2, "resolved Claude retry item");
6267 + yield* harness.until(() => retryItems().length === 2);
6268 assert.lengthOf(harness.terminalEvents(), 0);
6269 const recoveredRetry = retryItems()[1];
6270 assert.equal(recoveredRetry?.id, runningRetry?.id);
@@ -6257,7 +6278,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6278 result: "Opened GitHub.",
6279 }),
6280 );
6260 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "recovered Claude turn");
6281 + yield* harness.awaitTerminal(1);
6282 }).pipe(
6283 Effect.provide(
6284 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -6304,7 +6325,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6325 apiErrorStatus: 529,
6326 }),
6327 );
6307 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed Claude turn");
6328 + yield* harness.awaitTerminal(1);
6329
6330 const terminal = harness.terminalEvents()[0];
6331 assert.equal(terminal?.status, "failed");
@@ -6490,7 +6511,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6511 );
6512 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
6513 yield* Queue.offer(harness.sdkMessages, turnOneResult);
6493 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
6514 + yield* harness.awaitTerminal(1);
6515
6516 const afterStart = providerThreadRosterEvents(harness.events).filter(
6517 (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
@@ -6519,24 +6540,20 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6540 session_id: WAKE_NATIVE_SESSION,
6541 }),
6542 );
6522 - yield* awaitUntil(
6523 - () =>
6524 - providerThreadRosterEvents(harness.events).some(
6525 - (event) =>
6526 - event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1",
6527 - ),
6528 - "subagent shell roster",
6543 + yield* harness.until(() =>
6544 + providerThreadRosterEvents(harness.events).some(
6545 + (event) =>
6546 + event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1",
6547 + ),
6548 );
6549
6550 yield* Queue.offer(harness.sdkMessages, emptyRoster);
6532 - yield* awaitUntil(
6533 - () =>
6534 - providerThreadRosterEvents(harness.events).some(
6535 - (event) =>
6536 - event.providerThread.status === "idle" &&
6537 - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0,
6538 - ),
6539 - "empty roster clear",
6551 + yield* harness.until(() =>
6552 + providerThreadRosterEvents(harness.events).some(
6553 + (event) =>
6554 + event.providerThread.status === "idle" &&
6555 + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0,
6556 + ),
6557 );
6558 assert.isFalse(yield* harness.hasPendingBackgroundWork);
6559 }).pipe(
@@ -6668,7 +6685,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6685 harness.sdkMessages,
6686 makeResultFrame({ uuid: nextUuid(), result: "Watching." }),
6687 );
6671 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
6688 + yield* harness.awaitTerminal(1);
6689
6690 const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread
6691 .pendingBackgroundTasks;
@@ -6707,7 +6724,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6724 );
6725 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
6726 yield* Queue.offer(harness.sdkMessages, turnOneResult);
6710 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
6727 + yield* harness.awaitTerminal(1);
6728 const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread;
6729 assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID);
6730 assert.isTrue(yield* harness.hasPendingBackgroundWork);
@@ -6719,11 +6736,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6736 });
6737
6738 assert.equal(closes, 1, "Stop must close the CLI process that owns the task");
6722 - yield* awaitUntil(
6739 + yield* harness.until(
6740 () =>
6741 (providerThreadRosterEvents(harness.events).at(-1)?.providerThread
6742 .pendingBackgroundTasks?.length ?? 0) === 0,
6726 - "roster clear after Stop",
6743 );
6744 assert.isFalse(yield* harness.hasPendingBackgroundWork);
6745 assert.lengthOf(harness.continuationRequests, 0);
@@ -6738,6 +6754,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6754 it.effect("a settled Stop leaves a turn that replaced the closing process alone", () =>
6755 Effect.scoped(
6756 Effect.gen(function* () {
6757 + const changes = yield* makeChangeSignal;
6758 const fileSystem = yield* FileSystem.FileSystem;
6759 const idAllocator = yield* IdAllocator.IdAllocatorV2;
6760 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -6761,7 +6778,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6778 offer: (request) =>
6779 Effect.sync(() => {
6780 continuationRequests.push(request);
6764 - }),
6781 + }).pipe(Effect.andThen(changes.notify)),
6782 },
6783 queryRunner: {
6784 allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
@@ -6805,7 +6822,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6822 Stream.runForEach((event) =>
6823 Effect.sync(() => {
6824 events.push(event);
6808 - }),
6825 + }).pipe(Effect.andThen(changes.notify)),
6826 ),
6827 Effect.forkScoped,
6828 );
@@ -6828,7 +6845,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6845 );
6846 yield* Queue.offer(processQueues[0]!, wakeTaskStarted);
6847 yield* Queue.offer(processQueues[0]!, turnOneResult);
6831 - yield* awaitUntil(() => terminals().length === 1, "first turn terminal");
6848 + yield* changes.until(() => terminals().length === 1);
6849 const settledThread = providerThreadRosterEvents(events).at(-1)?.providerThread;
6850 const settledTurn = terminals()[0];
6851 assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID);
@@ -6867,18 +6884,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6884 uuid: "00000000-0000-4000-8000-000000000905",
6885 }),
6886 );
6870 - yield* awaitUntil(
6887 + yield* changes.until(
6888 () =>
6889 providerThreadRosterEvents(events).at(-1)?.providerThread.pendingBackgroundTasks?.[0]
6890 ?.taskId === replacementTaskId,
6874 - "replacement roster",
6891 );
6892
6893 yield* Queue.shutdown(processQueues[0]!);
6894 yield* Fiber.join(stop);
6895 assert.isTrue(yield* hasPendingBackgroundWork);
6880 - let quietYields = 0;
6881 - yield* awaitUntil(() => quietYields++ >= 50, "late roster events");
6896 + yield* yieldTicks(50);
6897 const latestThread = providerThreadRosterEvents(events).at(-1)?.providerThread;
6898 assert.equal(latestThread?.status, "active");
6899 assert.deepEqual(
@@ -6893,7 +6908,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6908 result: "Started another build.",
6909 }),
6910 );
6896 - yield* awaitUntil(() => terminals().length === 2, "replacement turn terminal");
6911 + yield* changes.until(() => terminals().length === 2);
6912 yield* Queue.offer(
6913 processQueues[1]!,
6914 claudeSdkFrame({
@@ -6909,7 +6924,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6924 text: WAKE_ASSISTANT_TEXT,
6925 }),
6926 );
6912 - yield* awaitUntil(() => continuationRequests.length === 1, "replacement wake");
6927 + yield* changes.until(() => continuationRequests.length === 1);
6928 }).pipe(
6929 Effect.provide(
6930 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -6923,6 +6938,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6938 () =>
6939 Effect.scoped(
6940 Effect.gen(function* () {
6941 + const changes = yield* makeChangeSignal;
6942 const fileSystem = yield* FileSystem.FileSystem;
6943 const idAllocator = yield* IdAllocator.IdAllocatorV2;
6944 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -7007,7 +7023,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7023 Stream.runForEach((event) =>
7024 Effect.sync(() => {
7025 events.push(event);
7010 - }),
7026 + }).pipe(Effect.andThen(changes.notify)),
7027 ),
7028 Effect.forkScoped,
7029 );
@@ -7060,15 +7076,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7076 result: "A settled with background work.",
7077 }),
7078 );
7063 - yield* awaitUntil(
7064 - () =>
7065 - events.some(
7066 - (event) =>
7067 - event.type === "turn.terminal" &&
7068 - event.providerThreadId === providerThreadA.id &&
7069 - event.status === "completed",
7070 - ),
7071 - "thread A terminal",
7079 + yield* changes.until(() =>
7080 + events.some(
7081 + (event) =>
7082 + event.type === "turn.terminal" &&
7083 + event.providerThreadId === providerThreadA.id &&
7084 + event.status === "completed",
7085 + ),
7086 );
7087 const rosterAAfterSettle = providerThreadRosterEvents(events).findLast(
7088 (event) => event.providerThread.id === providerThreadA.id,
@@ -7091,15 +7105,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7105 }),
7106 );
7107 assert.equal(processQueues.length, 2);
7094 - yield* awaitUntil(
7095 - () =>
7096 - providerThreadRosterEvents(events).some(
7097 - (event) =>
7098 - event.providerThread.id === providerThreadA.id &&
7099 - event.providerThread.status === "idle" &&
7100 - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0,
7101 - ),
7102 - "sibling A roster cleared idle on process replacement",
7108 + yield* changes.until(() =>
7109 + providerThreadRosterEvents(events).some(
7110 + (event) =>
7111 + event.providerThread.id === providerThreadA.id &&
7112 + event.providerThread.status === "idle" &&
7113 + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0,
7114 + ),
7115 );
7116 assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA));
7117
@@ -7118,14 +7130,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7130 session_id: nativeIds[1],
7131 }),
7132 );
7121 - yield* awaitUntil(
7122 - () =>
7123 - providerThreadRosterEvents(events).some(
7124 - (event) =>
7125 - event.providerThread.id === providerThreadB.id &&
7126 - (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
7127 - ),
7128 - "thread B roster populated",
7133 + yield* changes.until(() =>
7134 + providerThreadRosterEvents(events).some(
7135 + (event) =>
7136 + event.providerThread.id === providerThreadB.id &&
7137 + (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
7138 + ),
7139 );
7140 assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadB));
7141 assert.isTrue(yield* hasPendingBackgroundWork);
@@ -7157,15 +7167,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7167 session_id: nativeIds[1],
7168 }),
7169 );
7160 - yield* awaitUntil(
7161 - () =>
7162 - events.some(
7163 - (event) =>
7164 - event.type === "turn.terminal" &&
7165 - event.providerThreadId === providerThreadB.id &&
7166 - event.status === "failed",
7167 - ),
7168 - "thread B failed terminal",
7170 + yield* changes.until(() =>
7171 + events.some(
7172 + (event) =>
7173 + event.type === "turn.terminal" &&
7174 + event.providerThreadId === providerThreadB.id &&
7175 + event.status === "failed",
7176 + ),
7177 );
7178
7179 const rosterBAfterFail = providerThreadRosterEvents(events).findLast(
@@ -7264,7 +7272,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7272 0,
7273 ),
7274 );
7267 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7275 + yield* harness.awaitTerminal(1);
7276
7277 yield* harness.runtime.startTurn(
7278 makeClaudeTestTurnInput({
@@ -7279,14 +7287,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7287 }),
7288 );
7289 yield* Queue.offer(harness.sdkMessages, wakeNotification);
7282 - yield* Queue.offer(harness.sdkMessages, planToolUse);
7290 // The SDK asks for permission only after streaming the tool_use.
7284 - yield* awaitUntil(
7285 - () => Queue.sizeUnsafe(harness.sdkMessages) === 0,
7286 - "the tool_use frame to be consumed",
7287 - );
7288 - let settleYields = 0;
7289 - yield* awaitUntil(() => settleYields++ >= 50, "the tool_use frame to be handled");
7291 + yield* harness.offerAndWait(planToolUse);
7292 const canUseTool = harness.getOpenedOptions()?.canUseTool;
7293 assert.isFunction(canUseTool);
7294 const callback = yield* Effect.promise(() =>
@@ -7307,10 +7309,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7309 );
7310 yield* Queue.offer(harness.sdkMessages, planToolResult);
7311 yield* Queue.offer(harness.sdkMessages, wakeResult);
7310 - yield* awaitUntil(
7311 - () => harness.continuationRequests.length === 1,
7312 - "continuation request",
7313 - );
7312 + yield* harness.awaitContinuation(1);
7313
7314 yield* Queue.offer(
7315 harness.sdkMessages,
@@ -7332,7 +7331,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7331 1,
7332 ),
7333 );
7335 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal");
7334 + yield* harness.awaitTerminal(2);
7335
7336 yield* harness.runtime.startTurn(
7337 makeClaudeTestTurnInput({
@@ -7348,7 +7347,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7347 messageCreationSource: "provider",
7348 }),
7349 );
7351 - yield* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal");
7350 + yield* harness.awaitTerminal(3);
7351
7352 const latestItems = new Map(
7353 harness.events.flatMap((event) =>
@@ -7464,7 +7463,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7463 harness.sdkMessages,
7464 makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000792", result: "Done." }),
7465 );
7467 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
7466 + yield* harness.awaitTerminal(1);
7467
7468 const bash = harness.events.findLast(
7469 (event) =>
@@ -7529,7 +7528,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7528 0,
7529 ),
7530 );
7532 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7531 + yield* harness.awaitTerminal(1);
7532
7533 yield* harness.runtime.startTurn(
7534 makeClaudeTestTurnInput({
@@ -7543,8 +7542,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7542 runtimePolicy: approvalPolicy,
7543 }),
7544 );
7546 - yield* Queue.offer(
7547 - harness.sdkMessages,
7545 + yield* harness.offerAndWait(
7546 claudeSdkFrame({
7547 type: "assistant",
7548 message: {
@@ -7566,12 +7564,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7564 session_id: WAKE_NATIVE_SESSION,
7565 }),
7566 );
7569 - yield* awaitUntil(
7570 - () => Queue.sizeUnsafe(harness.sdkMessages) === 0,
7571 - "the tool_use frame to be consumed",
7572 - );
7573 - let settleYields = 0;
7574 - yield* awaitUntil(() => settleYields++ >= 50, "the tool_use frame to be held");
7567 const permission = yield* Effect.promise(() =>
7568 harness.getOpenedOptions()!.canUseTool!(
7569 "Bash",
@@ -7584,9 +7576,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7576 ),
7577 ).pipe(Effect.forkScoped);
7578
7587 - yield* awaitUntil(
7588 - () => harness.events.some((event) => event.type === "runtime_request.updated"),
7589 - "the approval request",
7579 + yield* harness.until(() =>
7580 + harness.events.some((event) => event.type === "runtime_request.updated"),
7581 );
7582 const request = harness.events.findLast(
7583 (event) => event.type === "runtime_request.updated",
@@ -7651,7 +7642,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7642 0,
7643 ),
7644 );
7654 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7645 + yield* harness.awaitTerminal(1);
7646
7647 yield* harness.runtime.startTurn(
7648 makeClaudeTestTurnInput({
@@ -7683,7 +7674,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7674 1,
7675 ),
7676 );
7686 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal");
7677 + yield* harness.awaitTerminal(2);
7678 assert.equal(harness.terminalEvents()[1]?.status, "completed");
7679 assert.lengthOf(harness.continuationRequests, 0);
7680 assert.deepEqual(
@@ -7754,7 +7745,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7745 0,
7746 ),
7747 );
7757 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7748 + yield* harness.awaitTerminal(1);
7749
7750 yield* harness.runtime.startTurn(
7751 makeClaudeTestTurnInput({
@@ -7767,16 +7758,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7758 providerTurnOrdinal: 2,
7759 }),
7760 );
7770 - yield* Queue.offer(
7771 - harness.sdkMessages,
7761 + yield* harness.offerAndWait(
7762 makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000703", text: "Two." }),
7763 );
7774 - let heldYields = 0;
7775 - yield* awaitUntil(() => heldYields++ >= 50, "unechoed frame to be held");
7764 assert.deepEqual(assistantTexts(), ["One."]);
7765
7766 yield* Queue.shutdown(harness.sdkMessages);
7779 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal");
7767 + yield* harness.awaitTerminal(2);
7768 assert.deepEqual(assistantTexts(), ["One.", "Two."]);
7769 assert.equal(harness.terminalEvents()[1]?.status, "failed");
7770 }).pipe(
@@ -7814,7 +7802,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7802 session_id: WAKE_NATIVE_SESSION,
7803 }),
7804 );
7817 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
7805 + yield* harness.awaitTerminal(1);
7806 const [terminal] = harness.terminalEvents();
7807 assert.equal(terminal?.status, "failed");
7808 if (terminal?.status !== "failed") return;
@@ -7871,7 +7859,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7859 user_message_uuid: harness.promptUuid(0),
7860 }),
7861 );
7874 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
7862 + yield* harness.awaitTerminal(1);
7863 assert.equal(harness.terminalEvents()[0]?.status, "completed");
7864 }).pipe(
7865 Effect.provide(
@@ -7899,27 +7887,23 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7887 );
7888 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
7889 yield* Queue.offer(harness.sdkMessages, turnOneResult);
7902 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7890 + yield* harness.awaitTerminal(1);
7891 assert.equal(harness.terminalEvents()[0]?.status, "completed");
7892 assert.isTrue(yield* harness.hasPendingBackgroundWork);
7893 assert.lengthOf(harness.continuationRequests, 0);
7894
7907 - yield* Queue.offer(harness.sdkMessages, wakeNotification);
7908 - let quietYields = 0;
7909 - yield* awaitUntil(() => quietYields++ >= 50, "notification-only quiet window");
7895 + yield* harness.offerAndWait(wakeNotification);
7896 assert.lengthOf(harness.continuationRequests, 0);
7897 assert.isFalse(yield* harness.hasPendingBackgroundWork);
7898
7899 yield* Queue.offer(harness.sdkMessages, wakeAssistant);
7914 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
7900 + yield* harness.awaitContinuation(1);
7901 assert.equal(harness.continuationRequests[0]?.threadId, harness.threadId);
7902 assert.equal(harness.continuationRequests[0]?.providerThreadId, harness.providerThread.id);
7903 assert.equal(harness.continuationRequests[0]?.driver, ClaudeAdapterV2.CLAUDE_PROVIDER);
7904 assert.equal(harness.continuationRequests[0]?.detail, WAKE_SUMMARY);
7905
7920 - yield* Queue.offer(harness.sdkMessages, wakeResult);
7921 - let settleYields = 0;
7922 - yield* awaitUntil(() => settleYields++ >= 50, "wake result to settle into the buffer");
7906 + yield* harness.offerAndWait(wakeResult);
7907 assert.lengthOf(harness.continuationRequests, 1);
7908 assert.lengthOf(harness.terminalEvents(), 1);
7909 assert.isTrue(yield* harness.hasPendingBackgroundWork);
@@ -7949,7 +7933,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7933 );
7934 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
7935 yield* Queue.offer(harness.sdkMessages, turnOneResult);
7952 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
7936 + yield* harness.awaitTerminal(1);
7937
7938 yield* harness.offerAndWait(wakeNotification);
7939 assert.lengthOf(harness.continuationRequests, 0);
@@ -7974,7 +7958,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7958
7959 yield* harness.offerAndWait(wakeAssistant);
7960 yield* harness.offerAndWait(wakeResult);
7977 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "wake run terminal");
7961 + yield* harness.awaitTerminal(2);
7962 assert.equal(harness.terminalEvents()[1]?.status, "completed");
7963 assert.lengthOf(harness.continuationRequests, 1);
7964 assert.isTrue(
@@ -8120,10 +8104,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8104 );
8105 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
8106 yield* Queue.offer(harness.sdkMessages, turnOneResult);
8123 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
8107 + yield* harness.awaitTerminal(1);
8108 yield* Queue.offer(harness.sdkMessages, wakeNotification);
8109 yield* Queue.offer(harness.sdkMessages, wakeResult);
8126 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
8110 + yield* harness.awaitContinuation(1);
8111
8112 yield* harness.runtime.startTurn(
8113 makeClaudeTestTurnInput({
@@ -8137,7 +8121,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8121 }),
8122 );
8123
8140 - yield* awaitUntil(() => harness.offeredMessages.length === 2, "user prompt offered");
8124 + yield* harness.until(() => harness.offeredMessages.length === 2);
8125 assert.lengthOf(harness.terminalEvents(), 1);
8126 assert.isTrue(yield* harness.hasPendingBackgroundWork);
8127
@@ -8148,7 +8132,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8132 result: "The build passed; nothing else pending.",
8133 }),
8134 );
8151 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal");
8135 + yield* harness.awaitTerminal(2);
8136 assert.equal(harness.terminalEvents()[1]?.status, "completed");
8137 assert.isFalse(
8138 harness.events.some(
@@ -8169,7 +8153,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8153 messageCreationSource: "provider",
8154 }),
8155 );
8172 - yield* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal");
8156 + yield* harness.awaitTerminal(3);
8157 assert.equal(harness.terminalEvents()[2]?.status, "completed");
8158 assert.lengthOf(harness.offeredMessages, 2);
8159 assert.isTrue(
@@ -8228,7 +8212,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8212 origin: { kind: "task-notification" },
8213 }),
8214 );
8231 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "server wake terminal");
8215 + yield* harness.awaitTerminal(1);
8216 assert.equal(harness.terminalEvents()[0]?.status, "completed");
8217
8218 yield* harness.runtime.startTurn(
@@ -8249,7 +8233,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8233 result: "The background command finished.",
8234 }),
8235 );
8252 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "queued turn terminal");
8236 + yield* harness.awaitTerminal(2);
8237 assert.equal(harness.terminalEvents()[1]?.status, "completed");
8238 }).pipe(
8239 Effect.provide(
@@ -8282,7 +8266,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8266 attachments: [],
8267 }),
8268 );
8285 - yield* awaitUntil(() => harness.offeredMessages.length === 1, "recovery prompt offered");
8269 + yield* harness.until(() => harness.offeredMessages.length === 1);
8270
8271 // Live interleaving seen after interrupt recovery: a stale stopped
8272 // task_notification and its task-notification-origin result arrive
@@ -8310,10 +8294,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8294 }),
8295 );
8296
8313 - yield* awaitUntil(
8314 - () => hasMessageText(probeAssistantText),
8315 - "probe assistant after stale task-notification result",
8316 - );
8297 + yield* harness.until(() => hasMessageText(probeAssistantText));
8298 assert.lengthOf(harness.terminalEvents(), 0);
8299 assert.isFalse(hasMessageText(staleResultText));
8300
@@ -8332,7 +8313,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8313 }),
8314 );
8315
8335 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "user turn terminal");
8316 + yield* harness.awaitTerminal(1);
8317 assert.equal(harness.terminalEvents()[0]?.status, "completed");
8318 assert.isTrue(hasMessageText(recoveryAssistantText));
8319 assert.isFalse(hasMessageText(staleResultText));
@@ -8390,12 +8371,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8371 origin: { kind: "task-notification" },
8372 }),
8373 );
8393 - const terminalized = Exit.isSuccess(
8394 - yield* awaitUntil(
8395 - () => harness.terminalEvents().length === 1,
8396 - "interrupted terminal",
8397 - ).pipe(Effect.exit),
8398 - );
8374 + const terminalized = Exit.isSuccess(yield* harness.awaitTerminal(1).pipe(Effect.exit));
8375 yield* Deferred.succeed(closeGate, undefined);
8376 assert.isTrue(terminalized);
8377 assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
@@ -8427,7 +8403,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8403 }),
8404 );
8405
8430 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "spurious terminal");
8406 + yield* harness.awaitTerminal(1);
8407 assert.equal(harness.terminalEvents()[0]?.status, "completed");
8408 assert.lengthOf(harness.offeredMessages, 0);
8409 }).pipe(
@@ -8590,7 +8566,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8566 harness.sdkMessages,
8567 makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000952", result: "Started." }),
8568 );
8593 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
8569 + yield* harness.awaitTerminal(1);
8570
8571 // Both subagents end together. Claude runs an empty turn for the first
8572 // notification and opens the real one a millisecond later, all before
@@ -8660,7 +8636,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8636
8637 yield* harness.offerAndWait(wakeAssistant);
8638 yield* harness.offerAndWait(wakeResult);
8663 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "wake run terminal");
8639 + yield* harness.awaitTerminal(2);
8640 assert.equal(harness.terminalEvents()[1]?.status, "completed");
8641 assert.lengthOf(harness.continuationRequests, 1);
8642 assert.isTrue(
@@ -8712,9 +8688,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8688 }),
8689 );
8690 yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000902"));
8715 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
8691 + yield* harness.awaitTerminal(1);
8692 yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000903"));
8717 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake");
8693 + yield* harness.awaitContinuation(1);
8694 yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000904"));
8695 yield* harness.runtime.startTurn(
8696 makeClaudeTestTurnInput({
@@ -8729,7 +8705,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8705 messageCreationSource: "provider",
8706 }),
8707 );
8732 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "wake terminal");
8708 + yield* harness.awaitTerminal(2);
8709
8710 yield* userTurn("attempt-rerun-3", 3);
8711 yield* Queue.offer(
@@ -8746,11 +8722,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8722 yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000906"));
8723 yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
8724 yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000907"));
8749 - yield* awaitUntil(() => harness.terminalEvents().length === 3, "third turn terminal");
8725 + yield* harness.awaitTerminal(3);
8726
8727 yield* Queue.offer(harness.sdkMessages, wakeNotification);
8728 yield* Queue.offer(harness.sdkMessages, wakeAssistant);
8753 - yield* awaitUntil(() => harness.continuationRequests.length === 2, "command wake");
8729 + yield* harness.awaitContinuation(2);
8730 assert.equal(
8731 harness.continuationRequests[1]?.notification?.summary,
8732 `Command "${WAKE_TASK_DESCRIPTION}" finished`,
@@ -8860,7 +8836,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8836 0,
8837 ),
8838 );
8863 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
8839 + yield* harness.awaitTerminal(1);
8840
8841 yield* harness.runtime.startTurn(
8842 makeClaudeTestTurnInput({
@@ -8937,7 +8913,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8913 for (const frame of wakeFrames) {
8914 yield* Queue.offer(harness.sdkMessages, frame);
8915 }
8940 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal");
8916 + yield* harness.awaitTerminal(2);
8917
8918 yield* harness.runtime.startTurn(
8919 makeClaudeTestTurnInput({
@@ -8952,7 +8928,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8928 messageCreationSource: "provider",
8929 }),
8930 );
8955 - yield* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal");
8931 + yield* harness.awaitTerminal(3);
8932
8933 const subagentRuns = harness.events.flatMap((event) =>
8934 event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID
@@ -9008,7 +8984,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8984 result: "Waiting in the background.",
8985 }),
8986 );
9011 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
8987 + yield* harness.awaitTerminal(1);
8988
8989 const idleFrames = [
8990 makeSubagentTaskStartedFrame({
@@ -9042,7 +9018,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9018 for (const frame of idleFrames) {
9019 yield* Queue.offer(harness.sdkMessages, frame);
9020 }
9045 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
9021 + yield* harness.awaitContinuation(1);
9022 yield* Queue.offer(
9023 harness.sdkMessages,
9024 makeResultFrame({
@@ -9063,7 +9039,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9039 messageCreationSource: "provider",
9040 }),
9041 );
9066 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
9042 + yield* harness.awaitTerminal(2);
9043
9044 const routing = subagentRouting(harness.events, ["toolu-idle-bash"]);
9045 assert.isDefined(routing.childThreadId);
@@ -9135,7 +9111,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9111 ]) {
9112 yield* Queue.offer(harness.sdkMessages, frame);
9113 }
9138 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
9114 + yield* harness.awaitTerminal(1);
9115
9116 for (const frame of [
9117 makeSubagentToolResultFrame({
@@ -9160,18 +9136,16 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9136 ]) {
9137 yield* Queue.offer(harness.sdkMessages, frame);
9138 }
9163 - yield* awaitUntil(() => {
9139 + yield* harness.until(() => {
9140 const event = latestToolItem(IDLE_BASH);
9141 return event?.type === "turn_item.updated" && event.turnItem.status === "running";
9166 - }, "idle Bash call");
9167 - yield* awaitUntil(
9168 - () =>
9169 - harness.events.some(
9170 - (event) =>
9171 - event.type === "subagent.updated" &&
9172 - event.subagent.progress === "Reading the last commits",
9173 - ),
9174 - "idle progress",
9142 + });
9143 + yield* harness.until(() =>
9144 + harness.events.some(
9145 + (event) =>
9146 + event.type === "subagent.updated" &&
9147 + event.subagent.progress === "Reading the last commits",
9148 + ),
9149 );
9150 const routing = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
9151 assert.deepEqual(routing.assistantTexts(routing.childThreadId), ["Still auditing."]);
@@ -9200,7 +9174,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9174 ]) {
9175 yield* Queue.offer(harness.sdkMessages, frame);
9176 }
9203 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
9177 + yield* harness.awaitContinuation(1);
9178 yield* Queue.offer(
9179 harness.sdkMessages,
9180 makeResultFrame({
@@ -9221,7 +9195,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9195 messageCreationSource: "provider",
9196 }),
9197 );
9224 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
9198 + yield* harness.awaitTerminal(2);
9199
9200 const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]);
9201 assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [
@@ -9285,7 +9259,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9259 ]) {
9260 yield* Queue.offer(harness.sdkMessages, frame);
9261 }
9288 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
9262 + yield* harness.awaitTerminal(1);
9263
9264 for (const frame of [
9265 claudeSdkFrame({
@@ -9339,12 +9313,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9313 ]) {
9314 yield* Queue.offer(harness.sdkMessages, frame);
9315 }
9342 - yield* awaitUntil(
9343 - () =>
9344 - harness.events.some(
9345 - (event) => event.type === "message.updated" && event.message.text === "OUTER_WORKING",
9346 - ),
9347 - "outer work while the nested start waits",
9316 + yield* harness.until(() =>
9317 + harness.events.some(
9318 + (event) => event.type === "message.updated" && event.message.text === "OUTER_WORKING",
9319 + ),
9320 );
9321 assert.lengthOf(harness.continuationRequests, 0);
9322 for (const frame of [
@@ -9378,15 +9350,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9350 ]) {
9351 yield* Queue.offer(harness.sdkMessages, frame);
9352 }
9381 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
9382 - yield* awaitUntil(
9383 - () =>
9384 - harness.events.some(
9385 - (event) =>
9386 - event.type === "subagent.updated" &&
9387 - event.subagent.progress === "Waiting on the nested check",
9388 - ),
9389 - "outer progress",
9353 + yield* harness.awaitContinuation(1);
9354 + yield* harness.until(() =>
9355 + harness.events.some(
9356 + (event) =>
9357 + event.type === "subagent.updated" &&
9358 + event.subagent.progress === "Waiting on the nested check",
9359 + ),
9360 );
9361 yield* Queue.offer(
9362 harness.sdkMessages,
@@ -9408,7 +9378,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9378 messageCreationSource: "provider",
9379 }),
9380 );
9411 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
9381 + yield* harness.awaitTerminal(2);
9382
9383 assert.isFalse(
9384 harness.events.some(
@@ -9510,13 +9480,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9480 ]) {
9481 yield* Queue.offer(harness.sdkMessages, frame);
9482 }
9513 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
9483 + yield* harness.awaitTerminal(1);
9484 yield* userTurn("attempt-claude-earlier-nested-2", 2);
9485 yield* Queue.offer(
9486 harness.sdkMessages,
9487 makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a05", result: "Still on it." }),
9488 );
9519 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal");
9489 + yield* harness.awaitTerminal(2);
9490
9491 for (const frame of [
9492 makeSubagentNotificationFrame({
@@ -9538,13 +9508,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9508 ]) {
9509 yield* Queue.offer(harness.sdkMessages, frame);
9510 }
9541 - yield* awaitUntil(
9542 - () =>
9543 - harness.events.some(
9544 - (event) =>
9545 - event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED",
9546 - ),
9547 - "outer work after the nested call returns",
9511 + yield* harness.until(() =>
9512 + harness.events.some(
9513 + (event) =>
9514 + event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED",
9515 + ),
9516 );
9517
9518 assert.isFalse(
@@ -9692,7 +9660,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9660 ]) {
9661 yield* Queue.offer(harness.sdkMessages, frame);
9662 }
9695 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
9663 + yield* harness.awaitTerminal(1);
9664
9665 for (const frame of makeSubagentAssistantFrames({
9666 parentToolUseId: OUTER_TOOL_USE_ID,
@@ -9701,7 +9669,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9669 })) {
9670 yield* Queue.offer(harness.sdkMessages, frame);
9671 }
9704 - yield* awaitUntil(() => bashItems().length === 1, "idle Bash call");
9672 + yield* harness.until(() => bashItems().length === 1);
9673
9674 const bashResultFrame = makeSubagentToolResultFrame({
9675 parentToolUseId: OUTER_TOOL_USE_ID,
@@ -9770,14 +9738,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9738 ]) {
9739 yield* Queue.offer(harness.sdkMessages, frame);
9740 }
9773 - yield* awaitUntil(
9774 - () => harness.continuationRequests.length === 1,
9775 - "continuation request",
9776 - );
9741 + yield* harness.awaitContinuation(1);
9742
9743 yield* Queue.shutdown(harness.sdkMessages);
9779 - let quietYields = 0;
9780 - yield* awaitUntil(() => quietYields++ >= 50, "query exit");
9744 + yield* yieldTicks(50);
9745 yield* harness.runtime.startTurn(
9746 makeClaudeTestTurnInput({
9747 threadId: harness.threadId,
@@ -9799,7 +9763,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9763 result: "The audit finished.",
9764 }),
9765 );
9802 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
9766 + yield* harness.awaitTerminal(2);
9767
9768 const input = JSON.stringify("git log -5");
9769 assert.deepEqual(bashItems(), [
@@ -9869,7 +9833,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9833 ]) {
9834 yield* Queue.offer(harness.sdkMessages, frame);
9835 }
9872 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
9836 + yield* harness.awaitTerminal(1);
9837
9838 yield* Queue.offer(
9839 harness.sdkMessages,
@@ -9887,7 +9851,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9851 session_id: WAKE_NATIVE_SESSION,
9852 }),
9853 );
9890 - yield* awaitUntil(() => sendItems().length >= 1, "idle SendMessage call");
9854 + yield* harness.until(() => sendItems().length >= 1);
9855
9856 for (const frame of [
9857 claudeSdkFrame({
@@ -9921,15 +9885,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9885 ]) {
9886 yield* Queue.offer(harness.sdkMessages, frame);
9887 }
9924 - yield* awaitUntil(
9925 - () => harness.continuationRequests.length === 1,
9926 - "continuation request",
9927 - );
9888 + yield* harness.awaitContinuation(1);
9889 const beforeExit = sendItems();
9890
9891 yield* Queue.shutdown(harness.sdkMessages);
9931 - let quietYields = 0;
9932 - yield* awaitUntil(() => quietYields++ >= 50, "query exit");
9892 + yield* yieldTicks(50);
9893 yield* harness.runtime.startTurn(
9894 makeClaudeTestTurnInput({
9895 threadId: harness.threadId,
@@ -9951,7 +9911,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9911 result: "The audit finished.",
9912 }),
9913 );
9954 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
9914 + yield* harness.awaitTerminal(2);
9915
9916 const input = JSON.stringify(SEND_INPUT);
9917 assert.deepEqual(beforeExit, [`dynamic_tool:running:${input}`]);
@@ -10017,7 +9977,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9977 ]) {
9978 yield* Queue.offer(harness.sdkMessages, frame);
9979 }
10020 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal");
9980 + yield* harness.awaitTerminal(1);
9981
9982 const otherStartFrame = claudeSdkFrame({
9983 type: "system",
@@ -10071,10 +10031,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10031 ]) {
10032 yield* Queue.offer(harness.sdkMessages, frame);
10033 }
10074 - yield* awaitUntil(
10075 - () => harness.continuationRequests.length === 1,
10076 - "continuation request",
10077 - );
10034 + yield* harness.awaitContinuation(1);
10035 yield* Queue.offer(
10036 harness.sdkMessages,
10037 makeResultFrame({
@@ -10095,7 +10052,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10052 messageCreationSource: "provider",
10053 }),
10054 );
10098 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
10055 + yield* harness.awaitTerminal(2);
10056
10057 const routing = subagentRouting(harness.events, [BASH]);
10058 const childTexts = routing.assistantTexts(routing.childThreadId);
@@ -10185,7 +10142,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10142 ? []
10143 : routing.assistantTexts(routing.childThreadId);
10144 };
10188 - yield* awaitUntil(() => childTexts().length === 1, "replayed subagent text");
10145 + yield* harness.until(() => childTexts().length === 1);
10146 const retryStatuses = harness.events.flatMap((event) =>
10147 event.type === "turn_item.updated" &&
10148 event.turnItem.type === "error" &&
@@ -10271,7 +10228,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10228 for (const frame of frames) {
10229 yield* Queue.offer(harness.sdkMessages, frame);
10230 }
10274 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
10231 + yield* harness.awaitTerminal(1);
10232
10233 const routing = subagentRouting(harness.events, ["toolu-early-bash"]);
10234 assert.isDefined(routing.childThreadId);
@@ -10992,7 +10949,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10949 session_id: WAKE_NATIVE_SESSION,
10950 }),
10951 );
10995 - yield* awaitUntil(() => subagentEvents().length === 1, "subagent node created");
10952 + yield* harness.until(() => subagentEvents().length === 1);
10953
10954 yield* Queue.offer(
10955 harness.sdkMessages,
@@ -11016,10 +10973,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10973 session_id: WAKE_NATIVE_SESSION,
10974 }),
10975 );
11019 - yield* awaitUntil(
11020 - () => subagentEvents().at(-1)?.subagent.status === "completed",
11021 - "subagent terminal",
11022 - );
10976 + yield* harness.until(() => subagentEvents().at(-1)?.subagent.status === "completed");
10977
10978 assert.equal(subagentEvents().at(-1)?.subagent.result, "First line.\nSecond line.");
10979
@@ -11030,7 +10984,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10984 result: "Delegation completed.",
10985 }),
10986 );
11033 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal");
10987 + yield* harness.awaitTerminal(1);
10988 }).pipe(
10989 Effect.provide(
10990 Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -11090,7 +11044,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11044 }),
11045 );
11046 yield* Queue.offer(harness.sdkMessages, subagentTaskStarted);
11093 - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created");
11047 + yield* harness.until(() => subagentEvents().length >= 1);
11048 yield* Queue.offer(
11049 harness.sdkMessages,
11050 makeResultFrame({
@@ -11098,11 +11052,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11052 result: "Spawned the subagent in the background.",
11053 }),
11054 );
11101 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
11055 + yield* harness.awaitTerminal(1);
11056 assert.isTrue(yield* harness.hasPendingBackgroundWork);
11057
11058 yield* Queue.offer(harness.sdkMessages, subagentStoppedNotification);
11105 - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request");
11059 + yield* harness.awaitContinuation(1);
11060
11061 yield* Queue.offer(
11062 harness.sdkMessages,
@@ -11124,7 +11078,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11078 messageCreationSource: "provider",
11079 }),
11080 );
11127 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
11081 + yield* harness.awaitTerminal(2);
11082
11083 assert.equal(subagentEvents().at(-1)?.subagent.status, "cancelled");
11084 assert.isFalse(yield* harness.hasPendingBackgroundWork);
@@ -11213,7 +11167,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11167 }),
11168 );
11169 yield* Queue.offer(harness.sdkMessages, subagentTaskStarted);
11216 - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created");
11170 + yield* harness.until(() => subagentEvents().length >= 1);
11171 yield* Queue.offer(
11172 harness.sdkMessages,
11173 makeResultFrame({
@@ -11221,13 +11175,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11175 result: "Spawned the subagent in the background.",
11176 }),
11177 );
11224 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal");
11178 + yield* harness.awaitTerminal(1);
11179
11180 yield* Queue.offer(harness.sdkMessages, firstNotification);
11227 - yield* awaitUntil(
11228 - () => harness.continuationRequests.length === 1,
11229 - "first continuation request",
11230 - );
11181 + yield* harness.awaitContinuation(1);
11182 yield* Queue.offer(
11183 harness.sdkMessages,
11184 makeResultFrame({
@@ -11248,7 +11199,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11199 messageCreationSource: "provider",
11200 }),
11201 );
11251 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal");
11202 + yield* harness.awaitTerminal(2);
11203 assert.equal(subagentEvents().at(-1)?.subagent.status, "completed");
11204 assert.equal(subagentEvents().at(-1)?.subagent.result, FIRST_SUMMARY);
11205 assert.isFalse(yield* harness.hasPendingBackgroundWork);
@@ -11331,10 +11282,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11282 yield* Queue.offer(harness.sdkMessages, frame);
11283 }
11284 yield* Queue.offer(harness.sdkMessages, secondNotification);
11334 - yield* awaitUntil(
11335 - () => harness.continuationRequests.length === 2,
11336 - "second continuation request",
11337 - );
11285 + yield* harness.awaitContinuation(2);
11286 assert.equal(harness.continuationRequests[1]?.detail, SECOND_SUMMARY);
11287 assert.isTrue(yield* harness.hasPendingBackgroundWork);
11288
@@ -11358,10 +11306,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11306 messageCreationSource: "provider",
11307 }),
11308 );
11361 - yield* awaitUntil(
11362 - () => harness.terminalEvents().length === 3,
11363 - "resume continuation terminal",
11364 - );
11309 + yield* harness.awaitTerminal(3);
11310
11311 const statuses = subagentEvents().map((event) => event.subagent.status);
11312 const firstCompleted = statuses.indexOf("completed");
@@ -11408,6 +11353,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11353 it.effect("resets Waiting roster and wake eligibility when the CLI process is replaced", () =>
11354 Effect.scoped(
11355 Effect.gen(function* () {
11356 + const changes = yield* makeChangeSignal;
11357 const fileSystem = yield* FileSystem.FileSystem;
11358 const idAllocator = yield* IdAllocator.IdAllocatorV2;
11359 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -11430,7 +11376,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11376 offer: (request) =>
11377 Effect.sync(() => {
11378 continuationRequests.push(request);
11433 - }),
11379 + }).pipe(Effect.andThen(changes.notify)),
11380 },
11381 queryRunner: {
11382 allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
@@ -11471,7 +11417,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11417 Stream.runForEach((event) =>
11418 Effect.sync(() => {
11419 events.push(event);
11474 - }),
11420 + }).pipe(Effect.andThen(changes.notify)),
11421 ),
11422 Effect.forkScoped,
11423 );
@@ -11505,10 +11451,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11451 }),
11452 );
11453 yield* Queue.offer(firstProcess, turnOneResult);
11508 - yield* awaitUntil(
11509 - () => events.some((event) => event.type === "turn.terminal"),
11510 - "first turn terminal",
11511 - );
11454 + yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
11455 assert.isFalse(yield* hasPendingBackgroundWork);
11456
11457 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -11530,15 +11473,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11473 );
11474 assert.equal(processQueues.length, 2);
11475
11533 - yield* awaitUntil(
11534 - () =>
11535 - providerThreadRosterEvents(events).some(
11536 - (event) =>
11537 - event.providerThread.status === "active" &&
11538 - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0 &&
11539 - event.providerThread.updatedAt !== undefined,
11540 - ),
11541 - "roster cleared on process replace while remaining active",
11476 + yield* changes.until(() =>
11477 + providerThreadRosterEvents(events).some(
11478 + (event) =>
11479 + event.providerThread.status === "active" &&
11480 + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0 &&
11481 + event.providerThread.updatedAt !== undefined,
11482 + ),
11483 );
11484 assert.isFalse(yield* hasPendingBackgroundWork);
11485 const emptyActiveRosterEvents = providerThreadRosterEvents(events).filter(
@@ -11555,8 +11496,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11496
11497 const secondProcess = processQueues[1]!;
11498 yield* Queue.offer(secondProcess, wakeNotification);
11558 - let settleYields = 0;
11559 - yield* awaitUntil(() => settleYields++ >= 50, "stale notification settle");
11499 + yield* yieldTicks(50);
11500 assert.lengthOf(continuationRequests, 0);
11501
11502 yield* Queue.offer(
@@ -11566,9 +11506,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11506 result: "Process restart turn finished.",
11507 }),
11508 );
11569 - yield* awaitUntil(
11509 + yield* changes.until(
11510 () => events.filter((event) => event.type === "turn.terminal").length === 2,
11571 - "second turn terminal",
11511 );
11512 }).pipe(
11513 Effect.provide(
@@ -11583,6 +11522,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11522 () =>
11523 Effect.scoped(
11524 Effect.gen(function* () {
11525 + const changes = yield* makeChangeSignal;
11526 const fileSystem = yield* FileSystem.FileSystem;
11527 const idAllocator = yield* IdAllocator.IdAllocatorV2;
11528 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -11605,7 +11545,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11545 offer: (request) =>
11546 Effect.sync(() => {
11547 continuationRequests.push(request);
11608 - }),
11548 + }).pipe(Effect.andThen(changes.notify)),
11549 },
11550 queryRunner: {
11551 allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
@@ -11646,7 +11586,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11586 Stream.runForEach((event) =>
11587 Effect.sync(() => {
11588 events.push(event);
11649 - }),
11589 + }).pipe(Effect.andThen(changes.notify)),
11590 ),
11591 Effect.forkScoped,
11592 );
@@ -11672,15 +11612,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11612 const firstProcess = processQueues[0]!;
11613 yield* Queue.offer(firstProcess, wakeTaskStarted);
11614 yield* Queue.offer(firstProcess, turnOneResult);
11675 - yield* awaitUntil(
11676 - () => events.some((event) => event.type === "turn.terminal"),
11677 - "first turn terminal",
11678 - );
11615 + yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
11616 assert.isTrue(yield* hasPendingBackgroundWork);
11617
11618 yield* Queue.offer(firstProcess, wakeNotification);
11682 - let quietYields = 0;
11683 - yield* awaitUntil(() => quietYields++ >= 50, "notification-only quiet window");
11619 + yield* yieldTicks(50);
11620 assert.lengthOf(continuationRequests, 0);
11621
11622 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -11705,15 +11641,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11641 result: "User turn finished after model switch.",
11642 }),
11643 );
11708 - yield* awaitUntil(
11644 + yield* changes.until(
11645 () => events.filter((event) => event.type === "turn.terminal").length === 2,
11710 - "user turn terminal after replace",
11646 );
11647 assert.isFalse(yield* hasPendingBackgroundWork);
11648 assert.lengthOf(continuationRequests, 0);
11649
11650 yield* Queue.offer(secondProcess, wakeResult);
11716 - yield* awaitUntil(() => continuationRequests.length === 1, "continuation after result");
11651 + yield* changes.until(() => continuationRequests.length === 1);
11652 assert.equal(continuationRequests[0]?.detail, WAKE_SUMMARY);
11653 yield* runtime.startTurn(
11654 makeClaudeTestTurnInput({
@@ -11729,9 +11664,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11664 messageCreationSource: "provider",
11665 }),
11666 );
11732 - yield* awaitUntil(
11667 + yield* changes.until(
11668 () => events.filter((event) => event.type === "turn.terminal").length === 3,
11734 - "continuation terminal after buffered drain",
11669 );
11670 assert.isTrue(
11671 events.some(
@@ -11767,6 +11701,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11701 () =>
11702 Effect.scoped(
11703 Effect.gen(function* () {
11704 + const changes = yield* makeChangeSignal;
11705 const SUBAGENT_TASK_ID = "task-buffer-replace-subagent";
11706 const SUBAGENT_TOOL_USE_ID = "toolu-buffer-replace-subagent";
11707 const SUBAGENT_SUMMARY = "SUB_BUFFER_REPLACE_DONE";
@@ -11838,7 +11773,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11773 offer: (request) =>
11774 Effect.sync(() => {
11775 continuationRequests.push(request);
11841 - }),
11776 + }).pipe(Effect.andThen(changes.notify)),
11777 },
11778 queryRunner: {
11779 allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
@@ -11881,7 +11816,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11816 Stream.runForEach((event) =>
11817 Effect.sync(() => {
11818 events.push(event);
11884 - }),
11819 + }).pipe(Effect.andThen(changes.notify)),
11820 ),
11821 Effect.forkScoped,
11822 );
@@ -11915,7 +11850,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11850 assert.equal(processQueues.length, 1);
11851 const firstProcess = processQueues[0]!;
11852 yield* Queue.offer(firstProcess, subagentTaskStarted);
11918 - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created");
11853 + yield* changes.until(() => subagentEvents().length >= 1);
11854 assert.equal(subagentEvents()[0]?.subagent.status, "running");
11855 yield* Queue.offer(firstProcess, subagentAsyncAck);
11856 yield* Queue.offer(
@@ -11925,14 +11860,11 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11860 result: "Spawned the subagent in the background.",
11861 }),
11862 );
11928 - yield* awaitUntil(
11929 - () => events.some((event) => event.type === "turn.terminal"),
11930 - "first turn terminal",
11931 - );
11863 + yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
11864 assert.isTrue(yield* hasPendingBackgroundWork);
11865
11866 yield* Queue.offer(firstProcess, subagentNotification);
11935 - yield* awaitUntil(() => continuationRequests.length === 1, "continuation after notify");
11867 + yield* changes.until(() => continuationRequests.length === 1);
11868 assert.equal(continuationRequests[0]?.detail, SUBAGENT_SUMMARY);
11869
11870 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -11957,9 +11889,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11889 result: "User turn finished after model switch.",
11890 }),
11891 );
11960 - yield* awaitUntil(
11892 + yield* changes.until(
11893 () => events.filter((event) => event.type === "turn.terminal").length === 2,
11962 - "user turn terminal after replace",
11894 );
11895 assert.isFalse(yield* hasPendingBackgroundWork);
11896 assert.equal(subagentEvents().at(-1)?.subagent.status, "completed");
@@ -11986,9 +11917,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11917 messageCreationSource: "provider",
11918 }),
11919 );
11989 - yield* awaitUntil(
11920 + yield* changes.until(
11921 () => events.filter((event) => event.type === "turn.terminal").length === 3,
11991 - "continuation terminal after buffered subagent drain",
11922 );
11923
11924 const finalSubagent = subagentEvents().at(-1)?.subagent;
@@ -12016,6 +11946,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11946 it.effect("refuses a thinking change that would kill a running background subagent", () =>
11947 Effect.scoped(
11948 Effect.gen(function* () {
11949 + const changes = yield* makeChangeSignal;
11950 const SUBAGENT_TASK_ID = "task-model-change-running-subagent";
11951 const SUBAGENT_TOOL_USE_ID = "toolu-model-change-running-subagent";
11952 const fileSystem = yield* FileSystem.FileSystem;
@@ -12076,7 +12007,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12007 Stream.runForEach((event) =>
12008 Effect.sync(() => {
12009 events.push(event);
12079 - }),
12010 + }).pipe(Effect.andThen(changes.notify)),
12011 ),
12012 Effect.forkScoped,
12013 );
@@ -12116,7 +12047,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12047 result: "Spawned the subagent in the background.",
12048 }),
12049 );
12119 - yield* awaitUntil(() => terminals().length === 1, "first turn terminal");
12050 + yield* changes.until(() => terminals().length === 1);
12051 const settledTurn = terminals()[0]!;
12052
12053 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -12157,7 +12088,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12088 result: "Switched model.",
12089 }),
12090 );
12160 - yield* awaitUntil(() => terminals().length === 2, "switched turn terminal");
12091 + yield* changes.until(() => terminals().length === 2);
12092 yield* runtime.startTurn(
12093 makeClaudeTestTurnInput({
12094 threadId,
@@ -12313,6 +12244,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12244 () =>
12245 Effect.scoped(
12246 Effect.gen(function* () {
12247 + const changes = yield* makeChangeSignal;
12248 const fileSystem = yield* FileSystem.FileSystem;
12249 const idAllocator = yield* IdAllocator.IdAllocatorV2;
12250 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -12382,7 +12314,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12314 Stream.runForEach((event) =>
12315 Effect.sync(() => {
12316 events.push(event);
12385 - }),
12317 + }).pipe(Effect.andThen(changes.notify)),
12318 ),
12319 Effect.forkScoped,
12320 );
@@ -12407,10 +12339,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12339 assert.equal(processQueues.length, 1);
12340 yield* Queue.offer(processQueues[0]!, wakeTaskStarted);
12341 yield* Queue.offer(processQueues[0]!, turnOneResult);
12410 - yield* awaitUntil(
12411 - () => events.some((event) => event.type === "turn.terminal"),
12412 - "first turn terminal",
12413 - );
12342 + yield* changes.until(() => events.some((event) => event.type === "turn.terminal"));
12343 assert.isTrue(yield* hasPendingBackgroundWork);
12344
12345 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -12444,6 +12373,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12373 () =>
12374 Effect.scoped(
12375 Effect.gen(function* () {
12376 + const changes = yield* makeChangeSignal;
12377 const fileSystem = yield* FileSystem.FileSystem;
12378 const idAllocator = yield* IdAllocator.IdAllocatorV2;
12379 const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
@@ -12467,7 +12397,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12397 offer: (request) =>
12398 Effect.sync(() => {
12399 continuationRequests.push(request);
12470 - }),
12400 + }).pipe(Effect.andThen(changes.notify)),
12401 },
12402 queryRunner: {
12403 allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION),
@@ -12520,7 +12450,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12450 Stream.runForEach((event) =>
12451 Effect.sync(() => {
12452 events.push(event);
12523 - }),
12453 + }).pipe(Effect.andThen(changes.notify)),
12454 ),
12455 Effect.forkScoped,
12456 );
@@ -12544,13 +12474,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12474 );
12475 yield* Queue.offer(processQueues[0]!, wakeTaskStarted);
12476 yield* Queue.offer(processQueues[0]!, turnOneResult);
12547 - yield* awaitUntil(
12477 + yield* changes.until(
12478 () => events.filter((event) => event.type === "turn.terminal").length === 1,
12549 - "first turn terminal",
12479 );
12480 yield* Queue.offer(processQueues[0]!, wakeNotification);
12481 yield* Queue.offer(processQueues[0]!, wakeAssistant);
12553 - yield* awaitUntil(() => continuationRequests.length === 1, "first continuation request");
12482 + yield* changes.until(() => continuationRequests.length === 1);
12483 assert.isTrue(yield* hasPendingBackgroundWork);
12484
12485 const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION;
@@ -12606,9 +12535,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12535 result: "Kicked off the retry build in the background.",
12536 }),
12537 );
12609 - yield* awaitUntil(
12538 + yield* changes.until(
12539 () => events.filter((event) => event.type === "turn.terminal").length === 2,
12611 - "retry turn terminal",
12540 );
12541 yield* Queue.offer(
12542 retryProcess,
@@ -12631,10 +12559,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12559 text: "The retry build has finished.",
12560 }),
12561 );
12634 - yield* awaitUntil(
12635 - () => continuationRequests.length === 2,
12636 - "continuation request after retry",
12637 - );
12562 + yield* changes.until(() => continuationRequests.length === 2);
12563 assert.equal(continuationRequests[1]?.detail, "Retry build completed successfully");
12564 }).pipe(
12565 Effect.provide(
@@ -12828,10 +12753,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12753 yield* input.harness.offerAndWait(
12754 workflowSnapshot({ uuid: input.snapshotUuid, state: input.state ?? "start" }),
12755 );
12831 - yield* awaitUntil(
12832 - () => workflowMemberEvents(input.harness.events, 2).length === 1,
12833 - "workflow members projected",
12834 - );
12756 + yield* input.harness.until(() => workflowMemberEvents(input.harness.events, 2).length === 1);
12757 });
12758
12759 it.effect.each(["Agent", "Workflow"] as const)(
@@ -12961,16 +12883,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12883 session_id: WAKE_NATIVE_SESSION,
12884 }),
12885 );
12964 - yield* awaitUntil(
12965 - () =>
12966 - workflowCoordinatorEvents(harness.events).length > 0 &&
12967 - harness.events.some(
12968 - (event) =>
12969 - event.type === "subagent.updated" &&
12970 - event.subagent.nativeTaskRef?.nativeId === "task-plain-auditor",
12971 - ),
12972 - "workflow coordinator and auditor projected",
12973 - );
12886 const subagentPrompt = (nativeTaskId: string) => {
12887 const subagent = harness.events.flatMap((event) =>
12888 event.type === "subagent.updated" &&
@@ -12978,7 +12890,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12890 ? [event.subagent]
12891 : [],
12892 )[0];
12981 - assert.isDefined(subagent);
12893 const message = threadMessages(harness.events, subagent?.childThreadId).find(
12894 (event) => event.message.role === "user",
12895 )?.message;
@@ -12997,6 +12908,13 @@ describe("ClaudeAdapterV2 background wake turns", () => {
12908 : undefined,
12909 };
12910 };
12911 + // The user message item lands after the subagent node, so wait on the item itself.
12912 + yield* harness.until(
12913 + () =>
12914 + workflowCoordinatorEvents(harness.events).length > 0 &&
12915 + subagentPrompt(WORKFLOW_TASK_ID).itemMark !== undefined &&
12916 + subagentPrompt("task-plain-auditor").itemMark !== undefined,
12917 + );
12918 assert.deepEqual(subagentPrompt(WORKFLOW_TASK_ID), {
12919 text: script,
12920 messageMark: true,
@@ -13321,10 +13239,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13239 secondState: "queued",
13240 }),
13241 );
13324 - yield* awaitUntil(
13325 - () => coordinatorTurnItems().length > turnItemsBeforeRepeat,
13326 - "repeated workflow snapshot",
13327 - );
13242 + yield* harness.until(() => coordinatorTurnItems().length > turnItemsBeforeRepeat);
13243 assert.lengthOf(workflowMemberEvents(harness.events, 1), 2);
13244 assert.lengthOf(workflowMemberEvents(harness.events, 2), 1);
13245
@@ -13350,9 +13265,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13265 model: "claude-sonnet-4-6",
13266 }),
13267 );
13353 - yield* awaitUntil(
13354 - () => coordinatorTurnItems().length > turnItemsBeforeMetadata,
13355 - "updated workflow member metadata",
13268 + // The member's node and app thread pick up the metadata after the coordinator item.
13269 + yield* harness.until(
13270 + () =>
13271 + coordinatorTurnItems().length > turnItemsBeforeMetadata &&
13272 + workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title === "alpha:review" &&
13273 + firstThreadEvents().at(-1)?.appThread.title === "alpha:review",
13274 );
13275 assert.equal(
13276 workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title,
@@ -13575,7 +13493,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13493 harness.sdkMessages,
13494 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001121", state: "start" }),
13495 );
13578 - yield* awaitUntil(() => coordinatorCount() > inTurnCount, "in-turn workflow snapshot");
13496 + yield* harness.until(() => coordinatorCount() > inTurnCount);
13497 assert.equal(coordinatorCount(), inTurnCount + 1);
13498
13499 yield* Queue.offer(
@@ -13593,10 +13511,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13511 harness.sdkMessages,
13512 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001123", state: "done" }),
13513 );
13596 - yield* awaitUntil(
13597 - () => coordinatorCount() > betweenTurnCount,
13598 - "between-turn workflow snapshot",
13599 - );
13514 + yield* harness.until(() => coordinatorCount() > betweenTurnCount);
13515 assert.equal(coordinatorCount(), betweenTurnCount + 1);
13516 }).pipe(
13517 Effect.provide(
@@ -13648,7 +13563,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13563 })) {
13564 yield* harness.offerAndWait(frame);
13565 }
13651 - yield* awaitUntil(() => toolUpdates(oldBash).length === 1, "old workflow tool running");
13566 + yield* harness.until(() => toolUpdates(oldBash).length === 1);
13567 readsUntilPause = 2;
13568 const stop = yield* harness.runtime
13569 .interruptTurn({
@@ -13692,10 +13607,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13607 })) {
13608 yield* Queue.offer(resumedQueue, frame);
13609 }
13695 - yield* awaitUntil(
13696 - () => toolUpdates(newBash).length === 1,
13697 - "resumed workflow tool running",
13698 - );
13610 + yield* harness.until(() => toolUpdates(newBash).length === 1);
13611 yield* Deferred.succeed(releaseCleanup, undefined);
13612 yield* Queue.take(harness.terminalReceipts);
13613 assert.lengthOf(toolUpdates(oldBash), oldToolCount);
@@ -13711,10 +13623,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
13623 toolUseId: newBash,
13624 }),
13625 );
13714 - yield* awaitUntil(
13715 - () => toolUpdates(newBash).at(-1)?.status === "completed",
13716 - "resumed workflow tool completed",
13717 - );
13626 + yield* harness.until(() => toolUpdates(newBash).at(-1)?.status === "completed");
13627 assert.equal(toolUpdates(newBash).at(-1)?.output, "ok");
13628 }).pipe(
13629 Effect.provideService(Clock.Clock, {
@@ -14516,25 +14425,20 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14425 harness.sdkMessages,
14426 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001031", state: "done" }),
14427 );
14519 - yield* awaitUntil(
14520 - () => threadMessages(harness.events, secondThreadId).length === 2,
14521 - "workflow member excerpt",
14522 - );
14428 + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2);
14429 const notification = workflowNotification({
14430 uuid: "00000000-0000-4000-8000-000000001032",
14431 status: "completed",
14432 });
14433 yield* Queue.offer(harness.sdkMessages, notification);
14528 - yield* awaitUntil(
14529 - () =>
14530 - harness.events.some(
14531 - (event) =>
14532 - event.type === "turn_item.updated" &&
14533 - event.turnItem.type === "subagent" &&
14534 - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID &&
14535 - event.turnItem.status === "completed",
14536 - ),
14537 - "terminal workflow notification",
14434 + yield* harness.until(() =>
14435 + harness.events.some(
14436 + (event) =>
14437 + event.type === "turn_item.updated" &&
14438 + event.turnItem.type === "subagent" &&
14439 + event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID &&
14440 + event.turnItem.status === "completed",
14441 + ),
14442 );
14443 NodeFS.writeFileSync(
14444 NodePath.join(harness.transcriptDir, "agent-a2.jsonl"),
@@ -14544,11 +14448,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14448 harness.sdkMessages,
14449 claudeSdkFrame({ ...notification, uuid: "00000000-0000-4000-8000-000000001033" }),
14450 );
14547 - yield* awaitUntil(
14451 + yield* harness.until(
14452 () =>
14453 threadMessages(harness.events, secondThreadId).at(-1)?.message.text ===
14454 "A2 final answer",
14551 - "late terminal transcript answer",
14455 );
14456 yield* Queue.offer(
14457 harness.sdkMessages,
@@ -14625,10 +14528,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14528 harness.sdkMessages,
14529 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001009", state: "done" }),
14530 );
14628 - yield* awaitUntil(
14629 - () => threadMessages(harness.events, secondThreadId).length === 2,
14630 - "settled workflow member answers",
14631 - );
14531 + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2);
14532
14533 const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent;
14534 assert.deepEqual(
@@ -14658,14 +14558,12 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14558 yield* harness.offerAndWait(
14559 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }),
14560 );
14661 - yield* awaitUntil(
14561 + yield* harness.until(
14562 () => workflowCoordinatorEvents(harness.events).length > coordinatorEventsBeforeRepeat,
14663 - "repeated settled workflow snapshot",
14563 );
14665 - yield* awaitUntil(
14564 + yield* harness.until(
14565 () =>
14566 threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued",
14668 - "continued workflow transcript answer",
14567 );
14568 assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat);
14569 assert.lengthOf(threadMessages(harness.events, secondThreadId), 2);
@@ -14677,10 +14575,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14575 yield* harness.offerAndWait(
14576 workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }),
14577 );
14680 - yield* awaitUntil(
14681 - () => threadMessages(harness.events, secondThreadId).length === 3,
14682 - "late workflow transcript answer",
14683 - );
14578 + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 3);
14579 assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat);
14580 assert.equal(
14581 threadMessages(harness.events, secondThreadId).at(-1)?.message.text,
@@ -14706,9 +14601,8 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14601 lastProgressAt: 4432,
14602 }),
14603 );
14709 - yield* awaitUntil(
14710 - () => currentAssistantAnswers().join("\n\n").includes("Second answer"),
14711 - "two-turn workflow member answer",
14604 + yield* harness.until(() =>
14605 + currentAssistantAnswers().join("\n\n").includes("Second answer"),
14606 );
14607 assert.deepEqual(currentAssistantAnswers().slice(-2), ["First answer", "Second answer"]);
14608 const completedMember = workflowMemberEvents(harness.events, 1).at(-1)?.subagent;
@@ -14749,11 +14643,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14643 attempt: 3,
14644 }),
14645 );
14752 - yield* awaitUntil(
14646 + yield* harness.until(
14647 () =>
14648 threadMessages(harness.events, firstThreadId).at(-1)?.message.text ===
14649 "A1 retry answer",
14756 - "retried workflow member answer",
14650 );
14651 assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer");
14652 NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl"));
@@ -14765,11 +14658,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
14658 attempt: 4,
14659 }),
14660 );
14768 - yield* awaitUntil(
14661 + yield* harness.until(
14662 () =>
14663 workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0]
14664 ?.attempt === 4,
14772 - "fourth workflow member attempt",
14665 );
14666 const answersBeforeEmptyAttempt = currentAssistantAnswers();
14667 yield* harness.offerAndWait(
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+130 -155
@@ -45,6 +45,7 @@ import { resolveAttachmentPathById } from "../../attachmentStore.ts";
45 import * as Fiber from "effect/Fiber";
46 import * as Layer from "effect/Layer";
47 import * as PlatformError from "effect/PlatformError";
48 +import * as PubSub from "effect/PubSub";
49 import * as Queue from "effect/Queue";
50 import * as Ref from "effect/Ref";
51 import * as Schema from "effect/Schema";
@@ -1120,16 +1121,20 @@ describe("CodexAdapterV2 session initialize", () => {
1121 });
1122
1123 describe("CodexAdapterV2 post-settle continuation", () => {
1123 - const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect<void> =>
1124 - Effect.gen(function* () {
1125 - for (let attempt = 0; attempt < 5000; attempt++) {
1126 - if (predicate()) {
1127 - return;
1128 - }
1129 - yield* Effect.yieldNow;
1130 - }
1131 - return yield* Effect.die(`Timed out waiting for ${label}.`);
1132 - });
1124 + // The harness notifies after every recorded event or continuation, so a wait
1125 + // re-checks exactly when the state it reads changes. Subscribing before the
1126 + // first check means a change that lands in between is not lost.
1127 + const makeChangeSignal = Effect.gen(function* () {
1128 + const changes = yield* PubSub.unbounded<void>();
1129 + const until = (predicate: () => boolean): Effect.Effect<void> =>
1130 + Effect.scoped(
1131 + Effect.gen(function* () {
1132 + const subscription = yield* PubSub.subscribe(changes);
1133 + while (!predicate()) yield* PubSub.take(subscription);
1134 + }),
1135 + );
1136 + return { notify: PubSub.publish(changes, undefined), until };
1137 + });
1138
1139 const makeCodexReplayHarness = (
1140 transcript: CodexReplay.CodexAppServerReplayTranscript,
@@ -1142,6 +1147,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1147 const fileSystem = yield* FileSystem.FileSystem;
1148 const idAllocator = yield* IdAllocator.IdAllocatorV2;
1149 const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie);
1150 + const changes = yield* makeChangeSignal;
1151 const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
1152 [];
1153 const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = {
@@ -1188,7 +1194,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1194 offer: (request) =>
1195 Effect.sync(() => {
1196 continuationRequests.push(request);
1191 - }),
1197 + }).pipe(Effect.andThen(changes.notify)),
1198 },
1199 });
1200 const threadId = ThreadId.make(`thread-${transcript.scenario}`);
@@ -1215,6 +1221,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1221 ? Deferred.succeed(firstTerminal, undefined)
1222 : Effect.void,
1223 ),
1224 + Effect.andThen(changes.notify),
1225 Effect.andThen(onEvent(event)),
1226 ),
1227 ),
@@ -1251,6 +1258,8 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1258 subagentUpdates,
1259 hasPendingBackgroundWork,
1260 firstTerminal: Deferred.await(firstTerminal),
1261 + until: changes.until,
1262 + awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count),
1263 };
1264 });
1265
@@ -2021,7 +2030,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2030 decision: ProviderApprovalDecision,
2031 ) =>
2032 Effect.gen(function* () {
2024 - yield* awaitUntil(() => requests().length === count, `approval request ${count}`);
2033 + yield* harness.until(() => requests().length === count);
2034 const request = requests()[count - 1]!;
2035 assert.equal(request.kind, kind);
2036 yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision });
@@ -2045,15 +2054,15 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2054
2055 yield* runTurn(0);
2056 yield* answer(1, "command", "acceptForSession");
2048 - yield* awaitUntil(() => requests().length === 2, "file change request");
2049 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn 1");
2057 + yield* harness.until(() => requests().length === 2);
2058 + yield* harness.awaitTerminal(1);
2059 yield* runTurn(1);
2060 yield* answer(2, "file-change", "acceptForSession");
2052 - yield* awaitUntil(() => harness.terminalEvents().length === 2, "turn 2");
2061 + yield* harness.awaitTerminal(2);
2062 yield* runTurn(2);
2063 yield* answer(3, "command", "accept");
2064 yield* answer(4, "file-change", "accept");
2056 - yield* awaitUntil(() => harness.terminalEvents().length === 3, "turn 3");
2065 + yield* harness.awaitTerminal(3);
2066 assert.lengthOf(requests(), 4);
2067 }).pipe(
2068 Effect.provide(
@@ -2696,7 +2705,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2705 text: "Open github.com.",
2706 }),
2707 );
2699 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "Codex retry recovery");
2708 + yield* harness.awaitTerminal(1);
2709
2710 const retryItems = harness.events.flatMap((event) =>
2711 event.type === "turn_item.updated" &&
@@ -2817,7 +2826,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2826 text: "Run two commands.",
2827 }),
2828 );
2820 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "Codex item start times");
2829 + yield* harness.awaitTerminal(1);
2830
2831 const startedAtByItem = harness.events.flatMap((event) =>
2832 event.type === "turn_item.updated" &&
@@ -3131,7 +3140,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3140 text: "Reply with the requested recovery marker.",
3141 }),
3142 );
3134 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
3143 + yield* harness.awaitTerminal(1);
3144
3145 assert.deepEqual(
3146 assistantMessages(harness.events).map((event) => event.message.text),
@@ -3164,7 +3173,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3173 text: "Reply with the requested recovery marker.",
3174 }),
3175 );
3167 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
3176 + yield* harness.awaitTerminal(1);
3177
3178 assert.deepEqual(
3179 assistantMessages(harness.events).map((event) => event.message.text),
@@ -3969,15 +3978,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3978 }),
3979 );
3980
3972 - yield* awaitUntil(
3973 - () =>
3974 - harness.events.some(
3975 - (event) =>
3976 - event.type === "turn_item.updated" &&
3977 - event.turnItem.type === "command_execution" &&
3978 - event.turnItem.status === "running",
3979 - ),
3980 - "running command item",
3981 + yield* harness.until(() =>
3982 + harness.events.some(
3983 + (event) =>
3984 + event.type === "turn_item.updated" &&
3985 + event.turnItem.type === "command_execution" &&
3986 + event.turnItem.status === "running",
3987 + ),
3988 );
3989
3990 const providerTurnId = harness.events.find(
@@ -3995,7 +4002,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4002 providerTurnId,
4003 });
4004
3998 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal");
4005 + yield* harness.awaitTerminal(1);
4006 assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
4007
4008 const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
@@ -4264,16 +4271,14 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4271 text: INTERRUPT_PROMPT,
4272 }),
4273 );
4267 - yield* awaitUntil(
4268 - () =>
4269 - harness.events.some(
4270 - (event) =>
4271 - event.type === "turn_item.updated" &&
4272 - event.turnItem.type === "command_execution" &&
4273 - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4274 - event.turnItem.status === "running",
4275 - ),
4276 - "running child command item",
4274 + yield* harness.until(() =>
4275 + harness.events.some(
4276 + (event) =>
4277 + event.type === "turn_item.updated" &&
4278 + event.turnItem.type === "command_execution" &&
4279 + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4280 + event.turnItem.status === "running",
4281 + ),
4282 );
4283 const providerTurnId = harness.events.find(
4284 (
@@ -4290,7 +4295,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4295 providerTurnId,
4296 });
4297
4293 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal");
4298 + yield* harness.awaitTerminal(1);
4299 assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
4300 const childCommandUpdates = harness.events.filter(
4301 (
@@ -4367,16 +4372,14 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4372 text: INTERRUPT_PROMPT,
4373 }),
4374 );
4370 - yield* awaitUntil(
4371 - () =>
4372 - harness.events.some(
4373 - (event) =>
4374 - event.type === "turn_item.updated" &&
4375 - event.turnItem.type === "command_execution" &&
4376 - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4377 - event.turnItem.status === "running",
4378 - ),
4379 - "running child command item",
4375 + yield* harness.until(() =>
4376 + harness.events.some(
4377 + (event) =>
4378 + event.type === "turn_item.updated" &&
4379 + event.turnItem.type === "command_execution" &&
4380 + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4381 + event.turnItem.status === "running",
4382 + ),
4383 );
4384 const providerTurnId = harness.events.find(
4385 (
@@ -4393,7 +4396,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4396 .pipe(Effect.exit);
4397
4398 assert.equal(interruptExit._tag, "Failure");
4396 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal");
4399 + yield* harness.awaitTerminal(1);
4400 assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId);
4401 assert.isFalse(yield* harness.hasPendingBackgroundWork);
4402 }).pipe(
@@ -4462,16 +4465,14 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4465 text: INTERRUPT_PROMPT,
4466 }),
4467 );
4465 - yield* awaitUntil(
4466 - () =>
4467 - harness.events.some(
4468 - (event) =>
4469 - event.type === "turn_item.updated" &&
4470 - event.turnItem.type === "command_execution" &&
4471 - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4472 - event.turnItem.status === "running",
4473 - ),
4474 - "running child command item",
4468 + yield* harness.until(() =>
4469 + harness.events.some(
4470 + (event) =>
4471 + event.type === "turn_item.updated" &&
4472 + event.turnItem.type === "command_execution" &&
4473 + event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM &&
4474 + event.turnItem.status === "running",
4475 + ),
4476 );
4477 const providerTurnId = harness.events.find(
4478 (
@@ -4486,18 +4487,16 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4487 const interruptFiber = yield* harness.runtime
4488 .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
4489 .pipe(Effect.forkScoped);
4489 - yield* awaitUntil(
4490 - () =>
4491 - harness.events.some(
4492 - (event) =>
4493 - event.type === "provider_turn.updated" &&
4494 - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN,
4495 - ),
4496 - "late child provider turn",
4490 + yield* harness.until(() =>
4491 + harness.events.some(
4492 + (event) =>
4493 + event.type === "provider_turn.updated" &&
4494 + event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN,
4495 + ),
4496 );
4497 yield* Fiber.join(interruptFiber);
4498
4500 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal");
4499 + yield* harness.awaitTerminal(1);
4500 const lateChildUpdates = harness.events.filter(
4501 (
4502 event,
@@ -4591,15 +4590,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4590 text: INTERRUPT_PROMPT,
4591 }),
4592 );
4594 - yield* awaitUntil(
4595 - () =>
4596 - harness.events.some(
4597 - (event) =>
4598 - event.type === "turn_item.updated" &&
4599 - event.turnItem.type === "command_execution" &&
4600 - event.turnItem.status === "running",
4601 - ),
4602 - "running command item",
4593 + yield* harness.until(() =>
4594 + harness.events.some(
4595 + (event) =>
4596 + event.type === "turn_item.updated" &&
4597 + event.turnItem.type === "command_execution" &&
4598 + event.turnItem.status === "running",
4599 + ),
4600 );
4601 const providerTurnId = harness.events.find(
4602 (
@@ -4619,7 +4616,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4616 .pipe(Effect.exit);
4617
4618 assert.equal(interruptExit._tag, "Failure");
4622 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal");
4619 + yield* harness.awaitTerminal(1);
4620 assert.equal(harness.terminalEvents()[0]?.status, "interrupted");
4621 assert.isFalse(yield* harness.hasPendingBackgroundWork);
4622 }).pipe(
@@ -5070,7 +5067,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5067 text: FAILED_PROMPT,
5068 }),
5069 );
5073 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal");
5070 + yield* harness.awaitTerminal(1);
5071 assert.equal(harness.terminalEvents()[0]?.status, "failed");
5072
5073 const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
@@ -5785,17 +5782,15 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5782 text: RESUME_PROMPT,
5783 }),
5784 );
5788 - yield* awaitUntil(
5789 - () =>
5790 - harness.subagentUpdates().some((event) => event.subagent.result === "CODEX_FIRST_DONE"),
5791 - "first subagent result",
5785 + yield* harness.until(() =>
5786 + harness.subagentUpdates().some((event) => event.subagent.result === "CODEX_FIRST_DONE"),
5787 );
5788 assert.lengthOf(
5789 harness.subagentUpdates().filter((event) => event.subagent.result === "CODEX_FIRST_DONE"),
5790 1,
5791 );
5792 yield* TestClock.adjust("100 millis");
5798 - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal");
5793 + yield* harness.awaitTerminal(1);
5794 assert.equal(harness.terminalEvents()[0]?.status, "completed");
5795 const settledUpdates = harness.subagentUpdates();
5796 const firstCompletion = settledUpdates[settledUpdates.length - 1];
@@ -5805,10 +5800,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5800 const settledUpdateCount = settledUpdates.length;
5801
5802 yield* TestClock.adjust("30 seconds");
5808 - yield* awaitUntil(
5809 - () => harness.subagentUpdates().length > settledUpdateCount,
5810 - "subagent re-open",
5811 - );
5803 + yield* harness.until(() => harness.subagentUpdates().length > settledUpdateCount);
5804 const reopened = harness.subagentUpdates()[settledUpdateCount];
5805 assert.equal(reopened?.subagent.status, "running");
5806 assert.equal(DateTime.toEpochMillis(reopened!.subagent.startedAt!), 1782622470000);
@@ -5816,7 +5808,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5808 assert.isTrue(yield* harness.hasPendingBackgroundWork);
5809
5810 yield* TestClock.adjust("30 seconds");
5819 - yield* awaitUntil(() => {
5811 + yield* harness.until(() => {
5812 const updates = harness.subagentUpdates();
5813 const latest = updates[updates.length - 1];
5814 return (
@@ -5824,7 +5816,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5816 latest.subagent.status === "completed" &&
5817 latest.subagent.result === "CODEX_RESUME_DONE"
5818 );
5827 - }, "resumed subagent completion");
5819 + });
5820 assert.isFalse(yield* harness.hasPendingBackgroundWork);
5821 assert.lengthOf(harness.terminalEvents(), 1);
5822 assert.lengthOf(harness.continuationRequests, 0);
@@ -6647,14 +6639,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6639 ? [event.providerTurn.status]
6640 : [],
6641 );
6650 - yield* awaitUntil(
6651 - () =>
6652 - harness.events.some(
6653 - (event) =>
6654 - event.type === "provider_thread.updated" &&
6655 - event.providerThread.goal?.tokensUsed === 11,
6656 - ),
6657 - "the completed turn to be held",
6642 + yield* harness.until(() =>
6643 + harness.events.some(
6644 + (event) =>
6645 + event.type === "provider_thread.updated" &&
6646 + event.providerThread.goal?.tokensUsed === 11,
6647 + ),
6648 );
6649 assert.deepEqual(turnStatuses(), ["running"]);
6650 assert.lengthOf(harness.terminalEvents(), 0);
@@ -6732,14 +6722,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6722 text: prompt,
6723 }),
6724 );
6735 - yield* awaitUntil(
6736 - () =>
6737 - harness.events.some(
6738 - (event) =>
6739 - event.type === "provider_thread.updated" &&
6740 - event.providerThread.goal?.tokensUsed === 11,
6741 - ),
6742 - "the continuation to be adopted",
6725 + yield* harness.until(() =>
6726 + harness.events.some(
6727 + (event) =>
6728 + event.type === "provider_thread.updated" &&
6729 + event.providerThread.goal?.tokensUsed === 11,
6730 + ),
6731 );
6732 yield* harness.runtime.interruptTurn({
6733 providerThread: harness.providerThread,
@@ -6827,14 +6815,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6815 text: prompt,
6816 }),
6817 );
6830 - yield* awaitUntil(
6831 - () =>
6832 - harness.events.some(
6833 - (event) =>
6834 - event.type === "provider_thread.updated" &&
6835 - event.providerThread.goal?.tokensUsed === 11,
6836 - ),
6837 - "the completed turn to be held",
6818 + yield* harness.until(() =>
6819 + harness.events.some(
6820 + (event) =>
6821 + event.type === "provider_thread.updated" &&
6822 + event.providerThread.goal?.tokensUsed === 11,
6823 + ),
6824 );
6825 yield* harness.runtime.interruptTurn({
6826 providerThread: harness.providerThread,
@@ -6849,15 +6835,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6835 harness.terminalEvents().map((event) => event.status),
6836 ["interrupted"],
6837 );
6852 - yield* awaitUntil(
6853 - () =>
6854 - harness.events.some(
6855 - (event) =>
6856 - event.type === "turn_item.updated" &&
6857 - event.turnItem.type === "command_execution" &&
6858 - event.turnItem.status === "interrupted",
6859 - ),
6860 - "the background command to be interrupted",
6838 + yield* harness.until(() =>
6839 + harness.events.some(
6840 + (event) =>
6841 + event.type === "turn_item.updated" &&
6842 + event.turnItem.type === "command_execution" &&
6843 + event.turnItem.status === "interrupted",
6844 + ),
6845 );
6846 }).pipe(
6847 Effect.scoped,
@@ -6923,14 +6907,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
6907 text: prompt,
6908 }),
6909 );
6926 - yield* awaitUntil(
6927 - () =>
6928 - harness.events.some(
6929 - (event) =>
6930 - event.type === "provider_thread.updated" &&
6931 - event.providerThread.goal?.status === "active",
6932 - ),
6933 - "the goal to be active",
6910 + yield* harness.until(() =>
6911 + harness.events.some(
6912 + (event) =>
6913 + event.type === "provider_thread.updated" &&
6914 + event.providerThread.goal?.status === "active",
6915 + ),
6916 );
6917 yield* harness.runtime.interruptTurn({
6918 providerThread: harness.providerThread,
@@ -7036,14 +7018,12 @@ describe("CodexAdapterV2 post-settle continuation", () => {
7018 text: prompt,
7019 }),
7020 );
7039 - yield* awaitUntil(
7040 - () =>
7041 - harness.events.some(
7042 - (event) =>
7043 - event.type === "provider_thread.updated" &&
7044 - event.providerThread.goal?.tokensUsed === 11,
7045 - ),
7046 - "the continuation to be adopted",
7021 + yield* harness.until(() =>
7022 + harness.events.some(
7023 + (event) =>
7024 + event.type === "provider_thread.updated" &&
7025 + event.providerThread.goal?.tokensUsed === 11,
7026 + ),
7027 );
7028 yield* harness.runtime.interruptTurn({
7029 providerThread: harness.providerThread,
@@ -7053,15 +7033,13 @@ describe("CodexAdapterV2 post-settle continuation", () => {
7033 }),
7034 requestRuntimeRestart: true,
7035 });
7056 - yield* awaitUntil(
7057 - () =>
7058 - harness.events.some(
7059 - (event) =>
7060 - event.type === "provider_turn.updated" &&
7061 - event.providerTurn.nativeTurnRef?.nativeId === childTurnId &&
7062 - event.providerTurn.status === "interrupted",
7063 - ),
7064 - "the subagent turn to be interrupted",
7036 + yield* harness.until(() =>
7037 + harness.events.some(
7038 + (event) =>
7039 + event.type === "provider_turn.updated" &&
7040 + event.providerTurn.nativeTurnRef?.nativeId === childTurnId &&
7041 + event.providerTurn.status === "interrupted",
7042 + ),
7043 );
7044 }).pipe(
7045 Effect.scoped,
@@ -7114,10 +7092,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
7092 text: prompt,
7093 }),
7094 );
7117 - yield* awaitUntil(
7118 - () => providerGoals(harness.events).includes("active"),
7119 - "the active goal to reach the provider thread",
7120 - );
7095 + yield* harness.until(() => providerGoals(harness.events).includes("active"));
7096 yield* harness.runtime.interruptTurn({
7097 providerThread: harness.providerThread,
7098 providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+17 -11
@@ -4075,12 +4075,14 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4075 }),
4076 ]);
4077 const turns: Array<OrchestrationV2ProviderTurn> = [];
4078 + const firstEnded = yield* Deferred.make<void>();
4079 const bothEnded = yield* Deferred.make<void>();
4080 yield* runtime.events.pipe(
4081 Stream.tap((event) =>
4082 Effect.gen(function* () {
4083 if (event.type === "provider_turn.updated" && event.providerTurn.status !== "running") {
4084 turns.push(event.providerTurn);
4085 + if (turns.length === 1) yield* Deferred.succeed(firstEnded, undefined);
4086 if (turns.length === 2) yield* Deferred.succeed(bothEnded, undefined);
4087 }
4088 }),
@@ -4089,9 +4091,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4091 Effect.forkScoped,
4092 );
4093 yield* runtime.startTurn(turnInput(thread));
4092 - yield* Effect.gen(function* () {
4093 - while (turns.length === 0) yield* Effect.yieldNow;
4094 - });
4094 + yield* Deferred.await(firstEnded);
4095 yield* runtime.startTurn(secondTurn(thread));
4096 yield* Deferred.await(bothEnded);
4097 const [first, second] = turns;
@@ -4319,6 +4319,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4319 const continued = (after: ReadonlyArray<ProviderReplayEntry>) =>
4320 Effect.gen(function* () {
4321 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
4322 + const offered = yield* Deferred.make<void>();
4323 const { runtime, thread } = yield* resumed([
4324 ...backgroundLaunch(CHILD),
4325 event("session.execution.succeeded", { sessionID: SESSION }),
@@ -4353,7 +4354,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4354 ...after,
4355 ]).pipe(
4356 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
4356 - offer: (request) => Effect.sync(() => void offers.push(request)),
4357 + offer: (request) =>
4358 + Effect.sync(() => void offers.push(request)).pipe(
4359 + Effect.andThen(Deferred.succeed(offered, undefined)),
4360 + Effect.asVoid,
4361 + ),
4362 take: Effect.never,
4363 }),
4364 );
@@ -4372,9 +4377,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4377 Effect.forkScoped,
4378 );
4379 yield* runtime.startTurn(withLineage(thread));
4375 - yield* Effect.gen(function* () {
4376 - while (offers.length === 0) yield* Effect.yieldNow;
4377 - }).pipe(Effect.timeout("2 seconds"), Effect.orDie);
4380 + yield* Deferred.await(offered);
4381 yield* runtime.startTurn(continuationTurn(thread, offers[0]!));
4382 yield* Deferred.await(bothEnded);
4383 const [first, second] = turns;
@@ -4821,6 +4824,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4824 const reportText = `<subagent sessionID="${CHILD}" state="completed" description="Sleep">\nCHILD_OK\n</subagent>`;
4825 const steerId = `msg_t3_steer_${SESSION}:message:opencode2-adapter:steer`;
4826 const offers: Array<ProviderContinuationRequests.ProviderContinuationRequest> = [];
4827 + const offered = yield* Deferred.make<void>();
4828 const { runtime, thread } = yield* resumed([
4829 ...backgroundLaunch(CHILD),
4830 event("session.execution.succeeded", { sessionID: SESSION }),
@@ -4869,7 +4873,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4873 event("session.execution.succeeded", { sessionID: SESSION }),
4874 ]).pipe(
4875 Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, {
4872 - offer: (request) => Effect.sync(() => void offers.push(request)),
4876 + offer: (request) =>
4877 + Effect.sync(() => void offers.push(request)).pipe(
4878 + Effect.andThen(Deferred.succeed(offered, undefined)),
4879 + Effect.asVoid,
4880 + ),
4881 take: Effect.never,
4882 }),
4883 );
@@ -4887,9 +4895,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4895 Effect.forkScoped,
4896 );
4897 yield* runtime.startTurn(withLineage(thread));
4890 - yield* Effect.gen(function* () {
4891 - while (offers.length === 0) yield* Effect.yieldNow;
4892 - }).pipe(Effect.timeout("2 seconds"), Effect.orDie);
4898 + yield* Deferred.await(offered);
4899 const followUp = continuationTurn(thread, offers[0]!);
4900 yield* runtime.startTurn(followUp);
4901 const followUpTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
oxlint-plugin-t3code/index.ts
+2
@@ -14,6 +14,7 @@ import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-e
14 import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts";
15 import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
16 import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";
17 +import noPollingLoopInTests from "./rules/no-polling-loop-in-tests.ts";
18 import noRawMcpRegistration from "./rules/no-raw-mcp-registration.ts";
19 import noRawResizeObserver from "./rules/no-raw-resize-observer.ts";
20 import noRealTimeWaitInTests from "./rules/no-real-time-wait-in-tests.ts";
@@ -47,6 +48,7 @@ export default definePlugin({
48 "no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals,
49 "no-native-title-tooltip": noNativeTitleTooltip,
50 "no-outset-state-indicators": noOutsetStateIndicators,
51 + "no-polling-loop-in-tests": noPollingLoopInTests,
52 "no-raw-mcp-registration": noRawMcpRegistration,
53 "no-raw-resize-observer": noRawResizeObserver,
54 "no-real-time-wait-in-tests": noRealTimeWaitInTests,
oxlint-plugin-t3code/rules/no-polling-loop-in-tests.test.ts new
+231
@@ -0,0 +1,231 @@
1 +import { assert, describe } from "@effect/vitest";
2 +
3 +import { createOxlintRuleHarness } from "../test/utils.ts";
4 +
5 +const rule = createOxlintRuleHarness("t3code/no-polling-loop-in-tests", {
6 + filename: "fixture.test.ts",
7 +});
8 +
9 +describe("t3code/no-polling-loop-in-tests", () => {
10 + rule.valid(
11 + "allows a fixed-count flush followed by unrelated error handling",
12 + `
13 + import { it } from "@effect/vitest";
14 + import * as Effect from "effect/Effect";
15 + it.effect("flushes", () =>
16 + Effect.gen(function* () {
17 + for (let i = 0; i < 3; i++) yield* Effect.yieldNow;
18 + if (!ready()) return yield* Effect.die("not ready");
19 + }),
20 + );
21 + `,
22 + );
23 +
24 + rule.valid(
25 + "allows a fixed-N flush with a literal bound",
26 + `
27 + import * as Effect from "effect/Effect";
28 +
29 + export const flush = Effect.gen(function* () {
30 + for (let i = 0; i < 3; i++) yield* Effect.yieldNow;
31 + });
32 + `,
33 + );
34 +
35 + rule.valid(
36 + "allows a fixed-N while flush with a counter bound",
37 + `
38 + import * as Effect from "effect/Effect";
39 +
40 + export const flush = Effect.gen(function* () {
41 + let i = 0;
42 + while (i < 3) {
43 + yield* Effect.yieldNow;
44 + i++;
45 + }
46 + });
47 + `,
48 + );
49 +
50 + rule.valid(
51 + "allows a fixed-N do-while flush against a named bound",
52 + `
53 + import * as Effect from "effect/Effect";
54 +
55 + export const flush = (turns: number) =>
56 + Effect.gen(function* () {
57 + let i = 0;
58 + do {
59 + yield* Effect.yieldNow;
60 + i += 1;
61 + } while (i < turns);
62 + });
63 + `,
64 + );
65 +
66 + rule.valid(
67 + "allows a loop that takes from a queue",
68 + `
69 + import * as Effect from "effect/Effect";
70 + import * as Queue from "effect/Queue";
71 +
72 + export const until = (events: Queue.Queue<number>) =>
73 + Effect.gen(function* () {
74 + while (true) {
75 + const event = yield* Queue.take(events);
76 + if (event > 2) return event;
77 + }
78 + });
79 + `,
80 + );
81 +
82 + rule.valid(
83 + "ignores waits inside nested callbacks",
84 + `
85 + import * as Effect from "effect/Effect";
86 +
87 + export const run = (items: ReadonlyArray<number>, done: () => boolean) =>
88 + Effect.gen(function* () {
89 + for (let i = 0; i < items.length; i++) {
90 + if (done()) return;
91 + yield* Effect.forkChild(Effect.gen(function* () {
92 + yield* Effect.yieldNow;
93 + }));
94 + }
95 + });
96 + `,
97 + );
98 +
99 + rule.invalid(
100 + "reports a budgeted yieldNow poll that dies after the loop",
101 + `
102 + import * as Effect from "effect/Effect";
103 +
104 + export const awaitUntil = (predicate: () => boolean) =>
105 + Effect.gen(function* () {
106 + for (let attempt = 0; attempt < 5000; attempt++) {
107 + if (predicate()) return;
108 + yield* Effect.yieldNow;
109 + }
110 + return yield* Effect.die("Timed out");
111 + });
112 + `,
113 + (output) => {
114 + assert.match(output, /Await the `Deferred`/);
115 + },
116 + );
117 +
118 + rule.invalid(
119 + "reports a while loop spinning on a predicate",
120 + `
121 + import * as Effect from "effect/Effect";
122 +
123 + export const wait = (turns: Array<number>) =>
124 + Effect.gen(function* () {
125 + while (turns.length === 0) yield* Effect.yieldNow;
126 + });
127 + `,
128 + );
129 +
130 + rule.invalid(
131 + "reports a while loop bounded by a length predicate",
132 + `
133 + import * as Effect from "effect/Effect";
134 +
135 + export const wait = (events: Array<number>) =>
136 + Effect.gen(function* () {
137 + while (events.length < 1) yield* Effect.yieldNow;
138 + });
139 + `,
140 + );
141 +
142 + rule.invalid(
143 + "reports a comparison against an identifier the loop never advances",
144 + `
145 + import * as Effect from "effect/Effect";
146 +
147 + export const wait = (state: { count: number }) =>
148 + Effect.gen(function* () {
149 + let seen = state.count;
150 + while (seen < 3) {
151 + yield* Effect.yieldNow;
152 + seen = state.count;
153 + }
154 + });
155 + `,
156 + );
157 +
158 + rule.invalid(
159 + "reports a for loop bounded by a length predicate",
160 + `
161 + import * as Effect from "effect/Effect";
162 +
163 + export const wait = (events: Array<number>) =>
164 + Effect.gen(function* () {
165 + for (; events.length < 1; ) yield* Effect.yieldNow;
166 + });
167 + `,
168 + );
169 +
170 + rule.invalid(
171 + "reports a sleep poll with a counter bound and an early return",
172 + `
173 + import * as Effect from "effect/Effect";
174 +
175 + export const waitFor = (done: () => boolean) =>
176 + Effect.gen(function* () {
177 + for (let attempt = 0; attempt < 240; attempt += 1) {
178 + if (done()) return;
179 + yield* Effect.sleep("500 millis");
180 + }
181 + });
182 + `,
183 + );
184 +
185 + rule.invalid(
186 + "reports a microtask poll keyed on the loop condition",
187 + `
188 + import * as Effect from "effect/Effect";
189 +
190 + export const settle = function* (until: () => boolean) {
191 + for (let attempt = 0; attempt < 30 && !until(); attempt++) {
192 + yield* Effect.promise(() => Promise.resolve());
193 + }
194 + };
195 + `,
196 + );
197 +
198 + rule.invalid(
199 + "reports an awaited setTimeout poll",
200 + `
201 + export const waitFor = async (done: () => boolean) => {
202 + do {
203 + await new Promise((resolve) => setTimeout(resolve, 10));
204 + } while (!done());
205 + };
206 + `,
207 + );
208 +
209 + rule.invalid(
210 + "reports an awaited Promise.resolve poll that breaks",
211 + `
212 + export const waitFor = async (done: () => boolean) => {
213 + while (true) {
214 + if (done()) break;
215 + await Promise.resolve();
216 + }
217 + };
218 + `,
219 + );
220 +});
221 +
222 +const productionRule = createOxlintRuleHarness("t3code/no-polling-loop-in-tests");
223 +
224 +productionRule.valid(
225 + "ignores non-test files",
226 + `
227 + export const waitFor = async (done: () => boolean) => {
228 + while (!done()) await Promise.resolve();
229 + };
230 + `,
231 +);
oxlint-plugin-t3code/rules/no-polling-loop-in-tests.ts new
+196
@@ -0,0 +1,196 @@
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 FUNCTIONS = new Set(["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"]);
8 +const COUNTER_OPERATORS = new Set(["<", "<=", ">", ">="]);
9 +const TIMERS = new Set(["setImmediate", "setTimeout"]);
10 +const MESSAGE =
11 + "Polling loop in a test. Spinning on `yieldNow`/`sleep` is scheduler- and load-dependent. Await the `Deferred`, `Queue.take`, `Stream` element, `drain()`, or `expect.poll` that marks the milestone.";
12 +
13 +type LoopNode = ESTree.ForStatement | ESTree.WhileStatement | ESTree.DoWhileStatement;
14 +
15 +const isNode = (value: unknown): value is ESTree.Node =>
16 + typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
17 +
18 +// Visits `node` and its descendants, skipping nested functions: a wait or exit
19 +// inside a callback runs on the callback's schedule, not the loop's.
20 +const someDescendant = (node: unknown, match: (node: ESTree.Node) => boolean): boolean => {
21 + if (Array.isArray(node)) return node.some((child) => someDescendant(child, match));
22 + if (!isNode(node)) return false;
23 + if (match(node)) return true;
24 + if (FUNCTIONS.has(node.type)) return false;
25 + for (const [key, value] of Object.entries(node)) {
26 + if (key === "parent") continue;
27 + if (someDescendant(value, match)) return true;
28 + }
29 + return false;
30 +};
31 +
32 +const memberName = (node: unknown): Option.Option<readonly [string, string]> => {
33 + const expression = unwrapExpression(node);
34 + if (Option.isNone(expression) || expression.value.type !== "MemberExpression") {
35 + return Option.none();
36 + }
37 + const object = unwrapExpression(expression.value.object);
38 + const property = getPropertyName(expression.value.property);
39 + if (Option.isNone(object) || object.value.type !== "Identifier" || Option.isNone(property)) {
40 + return Option.none();
41 + }
42 + return Option.some([object.value.name, property.value] as const);
43 +};
44 +
45 +const isMember = (node: unknown, object: string, property: string): boolean =>
46 + Option.match(memberName(node), {
47 + onNone: () => false,
48 + onSome: ([name, key]) => name === object && key === property,
49 + });
50 +
51 +const isTimerReference = (node: unknown): boolean => {
52 + const expression = unwrapExpression(node);
53 + return (
54 + Option.isSome(expression) &&
55 + expression.value.type === "Identifier" &&
56 + TIMERS.has(expression.value.name)
57 + );
58 +};
59 +
60 +// `Promise.resolve()`, or a `new Promise` whose executor schedules a timer.
61 +const isTickPromise = (node: unknown): boolean => {
62 + const expression = unwrapExpression(node);
63 + if (Option.isNone(expression)) return false;
64 + const value = expression.value;
65 + if (value.type === "CallExpression") return isMember(value.callee, "Promise", "resolve");
66 + if (value.type !== "NewExpression" || !isIdentifier(Option.some(value.callee), "Promise")) {
67 + return false;
68 + }
69 + const [executor] = value.arguments;
70 + if (isTimerReference(executor)) return true;
71 + if (!isNode(executor) || !FUNCTIONS.has(executor.type)) return false;
72 + return someDescendant(
73 + (executor as ESTree.ArrowFunctionExpression).body,
74 + (child) => child.type === "CallExpression" && isTimerReference(child.callee),
75 + );
76 +};
77 +
78 +const thunkReturnsTick = (node: unknown): boolean => {
79 + if (!isNode(node) || node.type !== "ArrowFunctionExpression") return false;
80 + const body = node.body;
81 + if (body.type !== "BlockStatement") return isTickPromise(body);
82 + const last = body.body.at(-1);
83 + return last?.type === "ReturnStatement" && isTickPromise(last.argument);
84 +};
85 +
86 +const isWait = (node: ESTree.Node): boolean => {
87 + if (node.type === "MemberExpression") return isMember(node, "Effect", "yieldNow");
88 + if (node.type === "AwaitExpression") return isTickPromise(node.argument);
89 + if (node.type === "NewExpression") return isTickPromise(node);
90 + if (node.type !== "CallExpression") return false;
91 + if (isMember(node.callee, "Effect", "sleep")) return true;
92 + if (isIdentifier(unwrapExpression(node.callee), "setImmediate")) return true;
93 + if (isMember(node.callee, "Effect", "promise")) return thunkReturnsTick(node.arguments[0]);
94 + return false;
95 +};
96 +
97 +const hasConditionalExit = (body: ESTree.Node): boolean =>
98 + someDescendant(
99 + body,
100 + (node) =>
101 + node.type === "IfStatement" &&
102 + someDescendant(
103 + [node.consequent, node.alternate],
104 + (child) =>
105 + child.type === "ReturnStatement" ||
106 + child.type === "BreakStatement" ||
107 + child.type === "ThrowStatement",
108 + ),
109 + );
110 +
111 +const isNumericBound = (node: unknown): boolean => {
112 + const expression = unwrapExpression(node);
113 + if (Option.isNone(expression)) return false;
114 + const value = expression.value;
115 + return (
116 + value.type === "Identifier" || (value.type === "Literal" && typeof value.value === "number")
117 + );
118 +};
119 +
120 +const updatesCounter = (node: unknown, name: string): boolean =>
121 + someDescendant(
122 + node,
123 + (child) =>
124 + (child.type === "UpdateExpression" && isIdentifier(unwrapExpression(child.argument), name)) ||
125 + (child.type === "AssignmentExpression" &&
126 + (child.operator === "+=" || child.operator === "-=") &&
127 + isIdentifier(unwrapExpression(child.left), name)),
128 + );
129 +
130 +// A bare counter (`i < 3`, `attempt < max`) that the loop itself advances
131 +// bounds the loop without asking anything about the system under test.
132 +// `events.length < 1` or a counter nobody increments is a predicate.
133 +const isCounterTest = (loop: LoopNode): boolean => {
134 + if (loop.test == null) return false;
135 + const expression = unwrapExpression(loop.test);
136 + if (Option.isNone(expression) || expression.value.type !== "BinaryExpression") return false;
137 + if (!COUNTER_OPERATORS.has(expression.value.operator)) return false;
138 + const { left, right } = expression.value;
139 + const advances = [loop.body, loop.type === "ForStatement" ? loop.update : null];
140 + return [
141 + [left, right],
142 + [right, left],
143 + ].some(([counter, bound]) => {
144 + const name = unwrapExpression(counter);
145 + return (
146 + Option.isSome(name) &&
147 + name.value.type === "Identifier" &&
148 + isNumericBound(bound) &&
149 + updatesCounter(advances, name.value.name)
150 + );
151 + });
152 +};
153 +
154 +const isTrueLiteral = (test: ESTree.Expression): boolean => {
155 + const expression = unwrapExpression(test);
156 + return (
157 + Option.isSome(expression) &&
158 + expression.value.type === "Literal" &&
159 + expression.value.value === true
160 + );
161 +};
162 +
163 +// `for (...) { yield* Effect.yieldNow } return yield* Effect.die("timed out")`
164 +// keys a failure on the loop running out, which makes the bound a budget.
165 +// A loop is polling when a predicate decides whether it keeps going: a conditional exit in the
166 +// body, or a test that is neither `true` nor a counter the loop advances. A fixed-count flush
167 +// followed by unrelated error handling is not polling, so what comes after the loop is ignored.
168 +const hasPredicateExit = (loop: LoopNode): boolean =>
169 + hasConditionalExit(loop.body) ||
170 + (loop.test != null && !isTrueLiteral(loop.test) && !isCounterTest(loop));
171 +
172 +export default defineRule({
173 + meta: {
174 + type: "problem",
175 + docs: {
176 + description:
177 + "Disallow loops in tests that spin on yieldNow/sleep/timer ticks until a predicate holds; await the milestone instead.",
178 + },
179 + schema: [],
180 + },
181 + create(context) {
182 + if (!TEST_FILE_PATTERN.test(context.filename)) return {};
183 +
184 + const check = (loop: LoopNode) => {
185 + if (!someDescendant(loop.body, isWait)) return;
186 + if (!hasPredicateExit(loop)) return;
187 + context.report({ node: loop, message: MESSAGE });
188 + };
189 +
190 + return {
191 + ForStatement: check,
192 + WhileStatement: check,
193 + DoWhileStatement: check,
194 + };
195 + },
196 +});
vite.config.ts
+2
@@ -187,6 +187,8 @@ export default defineConfig({
187 "t3code/no-low-value-comments": "error",
188 "t3code/no-manual-effect-runtime-in-tests": "error",
189 "t3code/no-native-title-tooltip": "error",
190 + // Test files only (the rule checks the filename). Becomes an error once existing polls are converted.
191 + "t3code/no-polling-loop-in-tests": "warn",
192 "t3code/no-raw-mcp-registration": "error",
193 "t3code/no-real-time-wait-in-tests": "error",
194 "t3code/no-test-in-loop": "error",