The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 17:15 UTC
test: run clock-free live tests on TestClock (#35868)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 12, 2026 at 21:07 UTC
43ce39595bfcea4af4b99b1fa77c7e1a73256da2
13 files changed
+771
-731
apps/mobile/src/connection/environment-cache-store.test.ts
+9
-5
@@ -24,6 +24,7 @@ import * as Fiber from "effect/Fiber";
24
import * as Logger from "effect/Logger";
25
import * as Option from "effect/Option";
26
import * as Schema from "effect/Schema";
27
+import * as TestClock from "effect/testing/TestClock";
28
29
import * as MobileDatabase from "../persistence/mobile-database";
30
import { make } from "./environment-cache-store";
@@ -567,7 +568,7 @@ describe("mobile SQLite environment cache store", () => {
568
}),
569
);
570
570
- it.live("returns cached threads before their pull request links, which load after", () =>
571
+ it.effect("returns cached threads before their pull request links, which load after", () =>
572
Effect.gen(function* () {
573
const memory = makeDatabase();
574
const store = yield* make().pipe(
@@ -592,12 +593,13 @@ describe("mobile SQLite environment cache store", () => {
593
594
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
595
expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]);
595
- const links = yield* shell.loadPullRequests!;
596
- expect([...links]).toEqual([[THREAD_ID, [link]]]);
596
+ const links = yield* Effect.forkChild(shell.loadPullRequests!);
597
+ yield* TestClock.adjust("1 millis");
598
+ expect([...(yield* Fiber.join(links))]).toEqual([[THREAD_ID, [link]]]);
599
}),
600
);
601
600
- it.live("keeps cached threads when their pull request links cannot be read", () => {
602
+ it.effect("keeps cached threads when their pull request links cannot be read", () => {
603
const messages: Array<unknown> = [];
604
const logger = Logger.make(({ message }) => {
605
messages.push(message);
@@ -633,7 +635,9 @@ describe("mobile SQLite environment cache store", () => {
635
636
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
637
expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]);
636
- expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]);
638
+ const links = yield* Effect.forkChild(shell.loadPullRequests!);
639
+ yield* TestClock.adjust("1 millis");
640
+ expect([...(yield* Fiber.join(links))]).toEqual([[readable.id, [link]]]);
641
expect(messages).toHaveLength(1);
642
expect(memory.removed).toEqual([]);
643
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
apps/server/src/auth/McpOAuth.test.ts
+3
-3
@@ -193,7 +193,7 @@ const authorizeParams = (clientId: string, redirect = "http://localhost:51234/ca
193
resource: `${ORIGIN}/mcp`,
194
});
195
196
-it.live("derives discovery metadata from the origin the client reached", () =>
196
+it.effect("derives discovery metadata from the origin the client reached", () =>
197
withRoutes((handler) =>
198
Effect.gen(function* () {
199
const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp"));
@@ -215,7 +215,7 @@ it.live("derives discovery metadata from the origin the client reached", () =>
215
),
216
);
217
218
-it.live("registers loopback and https clients and never redirects for an unverified client", () =>
218
+it.effect("registers loopback and https clients and never redirects for an unverified client", () =>
219
withRoutes((handler) =>
220
Effect.gen(function* () {
221
for (const refused of [
@@ -622,7 +622,7 @@ it.live("an app approval code approves only an app sign-in, at its own level", (
622
),
623
);
624
625
-it.live(
625
+it.effect(
626
"sends an app sign-in on the linked tunnel to the hosted app, and a link to its own page",
627
() =>
628
Effect.gen(function* () {
apps/server/src/mcp/OrchestratorMcpService.test.ts
+1
-1
@@ -2202,7 +2202,7 @@ describe("OrchestratorMcpService provider resolution", () => {
2202
}),
2203
);
2204
2205
- it.live.each([
2205
+ it.effect.each([
2206
{ name: "parent instance", parentEnabled: true, model: "gpt-5.4" },
2207
{ name: "alternate instance", parentEnabled: false, model: "gpt-5.5" },
2208
])(
apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts
+1
-1
@@ -101,7 +101,7 @@ describe("tailClaudeTaskOutput", () => {
101
).pipe(Effect.provide(NodeServices.layer)),
102
);
103
104
- it.live("reads what was written last when the tool result stops it", () =>
104
+ it.effect("reads what was written last when the tool result stops it", () =>
105
Effect.scoped(
106
Effect.gen(function* () {
107
const fileSystem = yield* FileSystem.FileSystem;
apps/server/src/preview/ServerBrowser.test.ts
+277
-264
@@ -594,7 +594,7 @@ beforeEach(() => {
594
desktopConnections.length = 0;
595
});
596
597
-it.live("tells the desktop once per thread when its agent turns start and end", () =>
597
+it.effect("tells the desktop once per thread when its agent turns start and end", () =>
598
Effect.gen(function* () {
599
yield* ServerBrowser.ServerBrowser;
600
const activity = yield* PreviewAgentActivity.PreviewAgentActivity;
@@ -616,7 +616,7 @@ it.live("tells the desktop once per thread when its agent turns start and end",
616
}).pipe(Effect.scoped, Effect.provide(layer)),
617
);
618
619
-it.live("preview_open reports its navigation timeout instead of the request budget", () =>
619
+it.effect("preview_open reports its navigation timeout instead of the request budget", () =>
620
Effect.scoped(
621
Effect.gen(function* () {
622
const { broker, tabId } = yield* ready;
@@ -652,48 +652,54 @@ it.live("preview_open reports its navigation timeout instead of the request budg
652
).pipe(Effect.provide(layer)),
653
);
654
655
-it.live("an initial download stays available after preview_open reports the navigation error", () =>
656
- Effect.scoped(
657
- Effect.gen(function* () {
658
- const { broker, tabId } = yield* ready;
659
- const manager = yield* Manager.PreviewManager;
660
- const released = Promise.withResolvers<void>();
661
- initialNavigation = async () => {
662
- contexts[1]!.page.emit("download", {
663
- failure: async () => null,
664
- delete: async () => released.resolve(),
665
- saveAs: (path: string) => NodeFSP.writeFile(path, "a,b"),
666
- suggestedFilename: () => "report.csv",
667
- url: () => "http://localhost:1337/report.csv",
668
- });
669
- throw new Error("page.goto: Download is starting");
670
- };
671
- const error = yield* broker
672
- .invoke<PreviewAutomationStatus>({
655
+it.effect(
656
+ "an initial download stays available after preview_open reports the navigation error",
657
+ () =>
658
+ Effect.scoped(
659
+ Effect.gen(function* () {
660
+ const { broker, tabId } = yield* ready;
661
+ const manager = yield* Manager.PreviewManager;
662
+ const released = Promise.withResolvers<void>();
663
+ initialNavigation = async () => {
664
+ contexts[1]!.page.emit("download", {
665
+ failure: async () => null,
666
+ delete: async () => released.resolve(),
667
+ saveAs: (path: string) => NodeFSP.writeFile(path, "a,b"),
668
+ suggestedFilename: () => "report.csv",
669
+ url: () => "http://localhost:1337/report.csv",
670
+ });
671
+ throw new Error("page.goto: Download is starting");
672
+ };
673
+ const error = yield* broker
674
+ .invoke<PreviewAutomationStatus>({
675
+ scope,
676
+ operation: "open",
677
+ input: {
678
+ url: "http://localhost:1337/report.csv",
679
+ reuseExistingTab: false,
680
+ open: false,
681
+ },
682
+ })
683
+ .pipe(Effect.flip);
684
+ expect(error.message).toContain("Download is starting");
685
+ yield* Effect.promise(() => released.promise);
686
+ const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
687
+ expect(sessions).toHaveLength(2);
688
+ const downloadTabId = PreviewTabId.make(sessions.find((tab) => tab.tabId !== tabId)!.tabId);
689
+ const status = yield* broker.invoke<PreviewAutomationStatus>({
690
scope,
674
- operation: "open",
675
- input: { url: "http://localhost:1337/report.csv", reuseExistingTab: false, open: false },
676
- })
677
- .pipe(Effect.flip);
678
- expect(error.message).toContain("Download is starting");
679
- yield* Effect.promise(() => released.promise);
680
- const { sessions } = yield* manager.list({ threadId: scope.thread.threadId });
681
- expect(sessions).toHaveLength(2);
682
- const downloadTabId = PreviewTabId.make(sessions.find((tab) => tab.tabId !== tabId)!.tabId);
683
- const status = yield* broker.invoke<PreviewAutomationStatus>({
684
- scope,
685
- tabId: downloadTabId,
686
- operation: "status",
687
- input: {},
688
- });
689
- expect(status.downloads).toEqual([
690
- expect.objectContaining({ fileName: "report.csv", sizeBytes: 3 }),
691
- ]);
692
- expect(yield* (yield* FileSystem.FileSystem).readFileString(status.downloads![0]!.path)).toBe(
693
- "a,b",
694
- );
695
- }),
696
- ).pipe(Effect.provide(layer)),
691
+ tabId: downloadTabId,
692
+ operation: "status",
693
+ input: {},
694
+ });
695
+ expect(status.downloads).toEqual([
696
+ expect.objectContaining({ fileName: "report.csv", sizeBytes: 3 }),
697
+ ]);
698
+ expect(
699
+ yield* (yield* FileSystem.FileSystem).readFileString(status.downloads![0]!.path),
700
+ ).toBe("a,b");
701
+ }),
702
+ ).pipe(Effect.provide(layer)),
703
);
704
705
it.effect.each([
@@ -820,7 +826,7 @@ it.live("navigate fails when the page never commits within its timeout", () =>
826
).pipe(Effect.provide(layer)),
827
);
828
823
-it.live.each(["desktop" as const, undefined])(
829
+it.effect.each(["desktop" as const, undefined])(
830
"explicit desktop targets ($0 runtime) fail without creating a server tab",
831
(runtime) =>
832
Effect.scoped(
@@ -992,7 +998,7 @@ it.effect("a desktop page that loaded before the server attached reports its loa
998
).pipe(Effect.provide(layer)),
999
);
1000
995
-it.live.each([
1001
+it.effect.each([
1002
{ method: "goto" as const, message: { type: "navigate", url: "http://10.255.255.1/" } },
1003
{ method: "goBack" as const, message: { type: "history", delta: -1 } },
1004
{ method: "goForward" as const, message: { type: "history", delta: 1 } },
@@ -1041,7 +1047,7 @@ it.live.each([
1047
);
1048
1049
// The fake encoder decodes every frame at 1280x800, so 30 fps hits the bitrate floor.
1044
-it.live.each([
1050
+it.effect.each([
1051
{ reports: [], frameRate: 30, bitsPerSecond: 2.5e6 },
1052
{ reports: [30], frameRate: 30, bitsPerSecond: 2.5e6 },
1053
{ reports: [60], frameRate: 60, bitsPerSecond: 1280 * 800 * 60 * 0.05 },
@@ -1071,7 +1077,7 @@ it.live.each([
1077
).pipe(Effect.provide(layer)),
1078
);
1079
1074
-it.live.each([{ truncated: false }, { truncated: true }])(
1080
+it.effect.each([{ truncated: false }, { truncated: true }])(
1081
"saves a large recording as a binary download and removes its staged file (truncated: $truncated)",
1082
({ truncated }) =>
1083
Effect.scoped(
@@ -1129,7 +1135,7 @@ it.live.each([{ truncated: false }, { truncated: true }])(
1135
).pipe(Effect.provide(layer)),
1136
);
1137
1132
-it.live.each([
1138
+it.effect.each([
1139
{ refreshFails: false, expected: "final frame" },
1140
{ refreshFails: true, expected: "frame" },
1141
])(
@@ -1160,7 +1166,7 @@ it.live.each([
1166
).pipe(Effect.provide(layer)),
1167
);
1168
1163
-it.live("enforces provider ownership and explicit targets when a session has multiple tabs", () =>
1169
+it.effect("enforces provider ownership and explicit targets when a session has multiple tabs", () =>
1170
Effect.scoped(
1171
Effect.gen(function* () {
1172
const { broker, tabId } = yield* ready;
@@ -1292,49 +1298,51 @@ it.effect("a first still that never returns does not stall the tab's later captu
1298
).pipe(Effect.provide(layer)),
1299
);
1300
1295
-it.live("streams to a read-only viewer without allowing takeover, input, or viewport changes", () =>
1296
- Effect.scoped(
1297
- Effect.gen(function* () {
1298
- const { browser, tabId } = yield* ready;
1299
- const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
1300
- const page = contexts[0]!.page;
1301
- page.setViewportSize.mockClear();
1302
- const session = contexts[0]!.sessions.at(-1)!;
1303
- session.send.mockClear();
1304
- for (const message of [
1305
- { type: "takeControl" },
1306
- { type: "key", action: "down", key: "a", text: "a" },
1307
- { type: "resize", width: 390, height: 844 },
1308
- { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } },
1309
- ])
1310
- yield* viewer.input(message);
1311
- expect(page.setViewportSize).not.toHaveBeenCalled();
1312
- expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false);
1313
- const outputs = yield* Stream.fromQueue(viewer.output).pipe(
1314
- Stream.takeUntil((output) => output._tag === "frame"),
1315
- Stream.runCollect,
1316
- );
1317
- expect(outputs).toContainEqual(
1318
- expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }),
1319
- );
1320
- expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" }));
1321
- expect(outputs).toContainEqual(
1322
- expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }),
1323
- );
1324
- const operator = yield* browser.attachViewer(viewerInput(tabId, true));
1325
- yield* operator.input({ type: "takeControl" });
1326
- yield* operator.input({ type: "text", text: "typed" });
1327
- yield* operator.input({ type: "resize", width: 390, height: 844 });
1328
- expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
1329
- text: "typed",
1330
- });
1331
- expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
1332
- yield* operator.input({ type: "releaseControl" });
1333
- }),
1334
- ).pipe(Effect.provide(layer)),
1301
+it.effect(
1302
+ "streams to a read-only viewer without allowing takeover, input, or viewport changes",
1303
+ () =>
1304
+ Effect.scoped(
1305
+ Effect.gen(function* () {
1306
+ const { browser, tabId } = yield* ready;
1307
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, false));
1308
+ const page = contexts[0]!.page;
1309
+ page.setViewportSize.mockClear();
1310
+ const session = contexts[0]!.sessions.at(-1)!;
1311
+ session.send.mockClear();
1312
+ for (const message of [
1313
+ { type: "takeControl" },
1314
+ { type: "key", action: "down", key: "a", text: "a" },
1315
+ { type: "resize", width: 390, height: 844 },
1316
+ { type: "viewport", setting: { _tag: "freeform", width: 390, height: 844 } },
1317
+ ])
1318
+ yield* viewer.input(message);
1319
+ expect(page.setViewportSize).not.toHaveBeenCalled();
1320
+ expect(session.send.mock.calls.some(([method]) => method.startsWith("Input."))).toBe(false);
1321
+ const outputs = yield* Stream.fromQueue(viewer.output).pipe(
1322
+ Stream.takeUntil((output) => output._tag === "frame"),
1323
+ Stream.runCollect,
1324
+ );
1325
+ expect(outputs).toContainEqual(
1326
+ expect.objectContaining({ _tag: "frame", data: Buffer.from("frame") }),
1327
+ );
1328
+ expect(outputs).toContainEqual(expect.objectContaining({ _tag: "viewport" }));
1329
+ expect(outputs).toContainEqual(
1330
+ expect.objectContaining({ _tag: "control", canOperate: false, controller: "agent" }),
1331
+ );
1332
+ const operator = yield* browser.attachViewer(viewerInput(tabId, true));
1333
+ yield* operator.input({ type: "takeControl" });
1334
+ yield* operator.input({ type: "text", text: "typed" });
1335
+ yield* operator.input({ type: "resize", width: 390, height: 844 });
1336
+ expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", {
1337
+ text: "typed",
1338
+ });
1339
+ expect(page.setViewportSize).toHaveBeenCalledWith({ width: 390, height: 844 });
1340
+ yield* operator.input({ type: "releaseControl" });
1341
+ }),
1342
+ ).pipe(Effect.provide(layer)),
1343
);
1344
1337
-it.live(
1345
+it.effect(
1346
"takeover waits for the running agent and revokes snapshot refs before returning control",
1347
() =>
1348
Effect.scoped(
@@ -1395,7 +1403,7 @@ it.live(
1403
).pipe(Effect.provide(layer)),
1404
);
1405
1398
-it.live(
1406
+it.effect(
1407
"reports a valid CSS selector that matches several elements as ambiguous, not invalid",
1408
() =>
1409
Effect.scoped(
@@ -1429,7 +1437,7 @@ it.live(
1437
).pipe(Effect.provide(layer)),
1438
);
1439
1432
-it.live("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
1440
+it.effect("reports a pending dialog without evaluating the page and resolves it explicitly", () =>
1441
Effect.scoped(
1442
Effect.gen(function* () {
1443
const { broker, tabId } = yield* ready;
@@ -1508,7 +1516,7 @@ it.live("reports a pending dialog without evaluating the page and resolves it ex
1516
).pipe(Effect.provide(layer)),
1517
);
1518
1511
-it.live("closing an isolated tab closes its context only after the page closes", () =>
1519
+it.effect("closing an isolated tab closes its context only after the page closes", () =>
1520
Effect.scoped(
1521
Effect.gen(function* () {
1522
const { broker, tabId } = yield* ready;
@@ -1527,7 +1535,7 @@ it.live("closing an isolated tab closes its context only after the page closes",
1535
).pipe(Effect.provide(layer)),
1536
);
1537
1530
-it.live("closing a tab force-closes a page that never finishes unloading", () =>
1538
+it.effect("closing a tab force-closes a page that never finishes unloading", () =>
1539
Effect.scoped(
1540
Effect.gen(function* () {
1541
const { broker, tabId } = yield* ready;
@@ -1548,7 +1556,7 @@ it.live("closing a tab force-closes a page that never finishes unloading", () =>
1556
).pipe(Effect.provide(layer)),
1557
);
1558
1551
-it.live("closing a desktop tab waits for its page to unload before the desktop removes it", () =>
1559
+it.effect("closing a desktop tab waits for its page to unload before the desktop removes it", () =>
1560
Effect.scoped(
1561
Effect.gen(function* () {
1562
const { broker } = yield* ready;
@@ -1588,7 +1596,7 @@ it.live("closing a desktop tab waits for its page to unload before the desktop r
1596
).pipe(Effect.provide(layer)),
1597
);
1598
1591
-it.live("closing a tab with an unsaved-changes guard still closes it", () =>
1599
+it.effect("closing a tab with an unsaved-changes guard still closes it", () =>
1600
Effect.scoped(
1601
Effect.gen(function* () {
1602
const browser = yield* ServerBrowser.ServerBrowser;
@@ -1619,7 +1627,7 @@ it.live("closing a tab with an unsaved-changes guard still closes it", () =>
1627
).pipe(Effect.provide(layer)),
1628
);
1629
1622
-it.live("a tab opened to a file the browser cannot show reports the file to download", () =>
1630
+it.effect("a tab opened to a file the browser cannot show reports the file to download", () =>
1631
Effect.scoped(
1632
Effect.gen(function* () {
1633
const browser = yield* ServerBrowser.ServerBrowser;
@@ -1683,7 +1691,7 @@ it.live("a tab opened to a file the browser cannot show reports the file to down
1691
).pipe(Effect.provide(layer)),
1692
);
1693
1686
-it.live(
1694
+it.effect(
1695
"a late failure from a request that predates tracking leaves a newer navigation loading",
1696
() =>
1697
Effect.scoped(
@@ -1918,7 +1926,7 @@ it.effect.each([
1926
).pipe(Effect.provide(layer)),
1927
);
1928
1921
-it.live("only the controlling viewer's copy and cut keys reach its clipboard", () =>
1929
+it.effect("only the controlling viewer's copy and cut keys reach its clipboard", () =>
1930
Effect.scoped(
1931
Effect.gen(function* () {
1932
const { browser, tabId } = yield* ready;
@@ -1955,7 +1963,7 @@ it.live("only the controlling viewer's copy and cut keys reach its clipboard", (
1963
).pipe(Effect.provide(layer)),
1964
);
1965
1958
-it.live("a busy embedded frame does not hold a copy key back from the page", () =>
1966
+it.effect("a busy embedded frame does not hold a copy key back from the page", () =>
1967
Effect.scoped(
1968
Effect.gen(function* () {
1969
const { browser, tabId } = yield* ready;
@@ -2003,7 +2011,7 @@ it.live("a busy embedded frame does not hold a copy key back from the page", ()
2011
).pipe(Effect.provide(layer)),
2012
);
2013
2006
-it.live.each([false, true])(
2014
+it.effect.each([false, true])(
2015
"a page download is saved, offered to the controller, and listed for the agent (delete fails: %s)",
2016
(deleteFails) =>
2017
Effect.scoped(
@@ -2125,7 +2133,7 @@ it.effect("a tab showing a data: page reports its URL without the content", () =
2133
).pipe(Effect.provide(layer)),
2134
);
2135
2128
-it.live.each(["save failed", "oversized"])(
2136
+it.effect.each(["save failed", "oversized"])(
2137
"a rejected download releases the original and keeps no saved copy (%s)",
2138
(outcome) =>
2139
Effect.scoped(
@@ -2166,7 +2174,7 @@ it.live.each(["save failed", "oversized"])(
2174
).pipe(Effect.provide(layer)),
2175
);
2176
2169
-it.live("a restarted server removes the previous run's downloads and keeps its profiles", () =>
2177
+it.effect("a restarted server removes the previous run's downloads and keeps its profiles", () =>
2178
Effect.scoped(
2179
Effect.gen(function* () {
2180
const { stateDir } = yield* ServerConfig.ServerConfig;
@@ -2187,7 +2195,7 @@ it.live("a restarted server removes the previous run's downloads and keeps its p
2195
).pipe(Effect.provide(dependencies)),
2196
);
2197
2190
-it.live("a page's file picker goes to the controller and takes its uploaded files", () =>
2198
+it.effect("a page's file picker goes to the controller and takes its uploaded files", () =>
2199
Effect.scoped(
2200
Effect.gen(function* () {
2201
const { browser, tabId } = yield* ready;
@@ -2222,7 +2230,7 @@ it.live("a page's file picker goes to the controller and takes its uploaded file
2230
).pipe(Effect.provide(layer)),
2231
);
2232
2225
-it.live("overlapping file pickers keep the newer offer answerable", () =>
2233
+it.effect("overlapping file pickers keep the newer offer answerable", () =>
2234
Effect.scoped(
2235
Effect.gen(function* () {
2236
const { browser, tabId } = yield* ready;
@@ -2262,7 +2270,7 @@ it.live("overlapping file pickers keep the newer offer answerable", () =>
2270
).pipe(Effect.provide(layer)),
2271
);
2272
2265
-it.live("a detached file picker stays open across same-document navigation", () =>
2273
+it.effect("a detached file picker stays open across same-document navigation", () =>
2274
Effect.scoped(
2275
Effect.gen(function* () {
2276
const { browser, tabId } = yield* ready;
@@ -2327,7 +2335,7 @@ it.live("a detached file picker stays open across same-document navigation", ()
2335
).pipe(Effect.provide(layer)),
2336
);
2337
2330
-it.live.each(["main", "iframe"])(
2338
+it.effect.each(["main", "iframe"])(
2339
"a file picker closes at %s document commit before DOMContentLoaded",
2340
(frame) =>
2341
Effect.scoped(
@@ -2377,7 +2385,7 @@ it.live.each(["main", "iframe"])(
2385
).pipe(Effect.provide(layer)),
2386
);
2387
2380
-it.live("a file picker closes when its page is replaced while control changes hands", () =>
2388
+it.effect("a file picker closes when its page is replaced while control changes hands", () =>
2389
Effect.scoped(
2390
Effect.gen(function* () {
2391
const { broker, browser, tabId } = yield* ready;
@@ -2425,7 +2433,7 @@ it.live("a file picker closes when its page is replaced while control changes ha
2433
).pipe(Effect.provide(layer)),
2434
);
2435
2428
-it.live("a file picker is not offered after its document changes while reading accept", () =>
2436
+it.effect("a file picker is not offered after its document changes while reading accept", () =>
2437
Effect.scoped(
2438
Effect.gen(function* () {
2439
const { broker, browser, tabId } = yield* ready;
@@ -2469,7 +2477,7 @@ it.live("a file picker is not offered after its document changes while reading a
2477
).pipe(Effect.provide(layer)),
2478
);
2479
2472
-it.live("only the current controller can answer a file picker", () =>
2480
+it.effect("only the current controller can answer a file picker", () =>
2481
Effect.scoped(
2482
Effect.gen(function* () {
2483
const { browser, tabId } = yield* ready;
@@ -2768,7 +2776,7 @@ it.effect("a stalled desktop viewer still gets its size, control and reconnect",
2776
).pipe(Effect.provide(layer)),
2777
);
2778
2771
-it.live("the tab the desktop shows is visible and picked for agents without a tab", () =>
2779
+it.effect("the tab the desktop shows is visible and picked for agents without a tab", () =>
2780
Effect.scoped(
2781
Effect.gen(function* () {
2782
const broker = yield* Broker.PreviewAutomationBroker;
@@ -2809,85 +2817,87 @@ it.live("the tab the desktop shows is visible and picked for agents without a ta
2817
).pipe(Effect.provide(layer)),
2818
);
2819
2812
-it.live("agents read a human's tab with no arguments and act on it only while nobody drives", () =>
2813
- Effect.scoped(
2814
- Effect.gen(function* () {
2815
- const browser = yield* ServerBrowser.ServerBrowser;
2816
- const broker = yield* Broker.PreviewAutomationBroker;
2817
- const manager = yield* Manager.PreviewManager;
2818
- yield* Effect.yieldNow;
2819
- const opened = yield* manager.open({
2820
- threadId: scope.thread.threadId,
2821
- url: "http://localhost:5173/mine",
2822
- runtime: "server",
2823
- });
2824
- const tabId = PreviewTabId.make(opened.tabId);
2825
- const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
2826
- const status = yield* broker.invoke<PreviewAutomationStatus>({
2827
- scope,
2828
- operation: "status",
2829
- input: {},
2830
- });
2831
- expect(status).toMatchObject({
2832
- tabId,
2833
- control: { owner: "human", ownedByCaller: false },
2834
- });
2835
- expect(status.tabs).toEqual([
2836
- expect.objectContaining({ tabId, owner: "human", ownedByCaller: false, visible: true }),
2837
- ]);
2838
- const evaluated = yield* broker
2839
- .invoke<void>({ scope, operation: "evaluate", input: { expression: "read()" } })
2840
- .pipe(Effect.flip);
2841
- expect(evaluated).toMatchObject({
2842
- _tag: "PreviewAutomationControlInterruptedError",
2843
- reason: "humanControl",
2844
- });
2845
- yield* broker.invoke<PreviewAutomationSnapshot>({
2846
- scope,
2847
- tabId,
2848
- operation: "snapshot",
2849
- input: {},
2850
- });
2851
- const refused = yield* broker
2852
- .invoke<void>({
2820
+it.effect(
2821
+ "agents read a human's tab with no arguments and act on it only while nobody drives",
2822
+ () =>
2823
+ Effect.scoped(
2824
+ Effect.gen(function* () {
2825
+ const browser = yield* ServerBrowser.ServerBrowser;
2826
+ const broker = yield* Broker.PreviewAutomationBroker;
2827
+ const manager = yield* Manager.PreviewManager;
2828
+ yield* Effect.yieldNow;
2829
+ const opened = yield* manager.open({
2830
+ threadId: scope.thread.threadId,
2831
+ url: "http://localhost:5173/mine",
2832
+ runtime: "server",
2833
+ });
2834
+ const tabId = PreviewTabId.make(opened.tabId);
2835
+ const viewer = yield* browser.attachViewer(viewerInput(tabId, true));
2836
+ const status = yield* broker.invoke<PreviewAutomationStatus>({
2837
+ scope,
2838
+ operation: "status",
2839
+ input: {},
2840
+ });
2841
+ expect(status).toMatchObject({
2842
+ tabId,
2843
+ control: { owner: "human", ownedByCaller: false },
2844
+ });
2845
+ expect(status.tabs).toEqual([
2846
+ expect.objectContaining({ tabId, owner: "human", ownedByCaller: false, visible: true }),
2847
+ ]);
2848
+ const evaluated = yield* broker
2849
+ .invoke<void>({ scope, operation: "evaluate", input: { expression: "read()" } })
2850
+ .pipe(Effect.flip);
2851
+ expect(evaluated).toMatchObject({
2852
+ _tag: "PreviewAutomationControlInterruptedError",
2853
+ reason: "humanControl",
2854
+ });
2855
+ yield* broker.invoke<PreviewAutomationSnapshot>({
2856
+ scope,
2857
+ tabId,
2858
+ operation: "snapshot",
2859
+ input: {},
2860
+ });
2861
+ const refused = yield* broker
2862
+ .invoke<void>({
2863
+ scope,
2864
+ tabId,
2865
+ operation: "navigate",
2866
+ input: { url: "http://localhost:5173/agent" },
2867
+ })
2868
+ .pipe(Effect.flip);
2869
+ expect(refused).toMatchObject({
2870
+ _tag: "PreviewAutomationControlInterruptedError",
2871
+ reason: "humanControl",
2872
+ });
2873
+ yield* viewer.input({ type: "releaseControl" });
2874
+ const released = yield* broker.invoke<PreviewAutomationStatus>({
2875
+ scope,
2876
+ tabId,
2877
+ operation: "status",
2878
+ input: {},
2879
+ });
2880
+ expect(released.control).toMatchObject({ owner: "unclaimed", ownedByCaller: false });
2881
+ yield* broker.invoke({
2882
scope,
2883
tabId,
2884
operation: "navigate",
2885
input: { url: "http://localhost:5173/agent" },
2857
- })
2858
- .pipe(Effect.flip);
2859
- expect(refused).toMatchObject({
2860
- _tag: "PreviewAutomationControlInterruptedError",
2861
- reason: "humanControl",
2862
- });
2863
- yield* viewer.input({ type: "releaseControl" });
2864
- const released = yield* broker.invoke<PreviewAutomationStatus>({
2865
- scope,
2866
- tabId,
2867
- operation: "status",
2868
- input: {},
2869
- });
2870
- expect(released.control).toMatchObject({ owner: "unclaimed", ownedByCaller: false });
2871
- yield* broker.invoke({
2872
- scope,
2873
- tabId,
2874
- operation: "navigate",
2875
- input: { url: "http://localhost:5173/agent" },
2876
- });
2877
- expect(contexts[0]!.page.goto).toHaveBeenCalledWith(
2878
- "http://localhost:5173/agent",
2879
- expect.anything(),
2880
- );
2881
- yield* viewer.input({ type: "takeControl" });
2882
- const retaken = yield* broker
2883
- .invoke<void>({ scope, tabId, operation: "press", input: { key: "Enter" } })
2884
- .pipe(Effect.flip);
2885
- expect(retaken).toMatchObject({ reason: "humanControl" });
2886
- }),
2887
- ).pipe(Effect.provide(layer)),
2886
+ });
2887
+ expect(contexts[0]!.page.goto).toHaveBeenCalledWith(
2888
+ "http://localhost:5173/agent",
2889
+ expect.anything(),
2890
+ );
2891
+ yield* viewer.input({ type: "takeControl" });
2892
+ const retaken = yield* broker
2893
+ .invoke<void>({ scope, tabId, operation: "press", input: { key: "Enter" } })
2894
+ .pipe(Effect.flip);
2895
+ expect(retaken).toMatchObject({ reason: "humanControl" });
2896
+ }),
2897
+ ).pipe(Effect.provide(layer)),
2898
);
2899
2890
-it.live("preview_open reports a tab it shows as visible once the client attaches", () =>
2900
+it.effect("preview_open reports a tab it shows as visible once the client attaches", () =>
2901
Effect.scoped(
2902
Effect.gen(function* () {
2903
const browser = yield* ServerBrowser.ServerBrowser;
@@ -2914,7 +2924,7 @@ it.live("preview_open reports a tab it shows as visible once the client attaches
2924
).pipe(Effect.provide(layer)),
2925
);
2926
2917
-it.live("a session's own tab stays its default while other sessions' tabs are listed", () =>
2927
+it.effect("a session's own tab stays its default while other sessions' tabs are listed", () =>
2928
Effect.scoped(
2929
Effect.gen(function* () {
2930
const { broker, tabId } = yield* ready;
@@ -2939,7 +2949,7 @@ it.live("a session's own tab stays its default while other sessions' tabs are li
2949
).pipe(Effect.provide(layer)),
2950
);
2951
2942
-it.live(
2952
+it.effect(
2953
"preview_open picks a reported profile by id or name and defaults to the reported one",
2954
() =>
2955
Effect.scoped(
@@ -3023,83 +3033,86 @@ const gateSaveCleanup = Effect.gen(function* () {
3033
};
3034
});
3035
3026
-it.live("an agent opens a reported profile after a restart, before any client reports again", () =>
3027
- Effect.gen(function* () {
3028
- const gate = yield* gateSaveCleanup;
3029
- const persistent = (name: string) =>
3030
- ({ id: `profile-${name.toLowerCase()}`, name, kind: "persistent" }) as const;
3031
- // Together the two clients report more profiles than one report may hold.
3032
- const fromA = [
3033
- persistent("Work"),
3034
- ...Array.from({ length: 12 }, (_, n) => persistent(`A${n}`)),
3035
- ];
3036
- const fromB = [
3037
- persistent("Shared"),
3038
- ...Array.from({ length: 12 }, (_, n) => persistent(`B${n}`)),
3039
- ];
3040
- yield* Effect.gen(function* () {
3041
- const browser = yield* ServerBrowser.ServerBrowser;
3042
- const clientA = yield* Scope.make();
3043
- const reportFromA = yield* browser.profileReporter.pipe(
3044
- Effect.provideService(Scope.Scope, clientA),
3045
- );
3046
- const reportFromB = yield* browser.profileReporter;
3047
- const reportFromC = yield* browser.profileReporter;
3048
- yield* reportFromA({ profiles: fromA, defaultProfileId: "profile-work" });
3049
- gate.pauseNext();
3050
- const savingB = yield* reportFromB({
3051
- profiles: fromB,
3052
- defaultProfileId: "profile-shared",
3053
- }).pipe(Effect.forkScoped({ startImmediately: true }));
3054
- // A save that ends without reaching the gate fails the test instead of hanging it.
3055
- yield* Effect.raceFirst(
3056
- Deferred.await(gate.cleanupStarted),
3057
- Fiber.join(savingB).pipe(
3058
- Effect.andThen(Effect.die("save finished before the cleanup gate")),
3036
+it.effect(
3037
+ "an agent opens a reported profile after a restart, before any client reports again",
3038
+ () =>
3039
+ Effect.gen(function* () {
3040
+ const gate = yield* gateSaveCleanup;
3041
+ const persistent = (name: string) =>
3042
+ ({ id: `profile-${name.toLowerCase()}`, name, kind: "persistent" }) as const;
3043
+ // Together the two clients report more profiles than one report may hold.
3044
+ const fromA = [
3045
+ persistent("Work"),
3046
+ ...Array.from({ length: 12 }, (_, n) => persistent(`A${n}`)),
3047
+ ];
3048
+ const fromB = [
3049
+ persistent("Shared"),
3050
+ ...Array.from({ length: 12 }, (_, n) => persistent(`B${n}`)),
3051
+ ];
3052
+ yield* Effect.gen(function* () {
3053
+ const browser = yield* ServerBrowser.ServerBrowser;
3054
+ const clientA = yield* Scope.make();
3055
+ const reportFromA = yield* browser.profileReporter.pipe(
3056
+ Effect.provideService(Scope.Scope, clientA),
3057
+ );
3058
+ const reportFromB = yield* browser.profileReporter;
3059
+ const reportFromC = yield* browser.profileReporter;
3060
+ yield* reportFromA({ profiles: fromA, defaultProfileId: "profile-work" });
3061
+ gate.pauseNext();
3062
+ const savingB = yield* reportFromB({
3063
+ profiles: fromB,
3064
+ defaultProfileId: "profile-shared",
3065
+ }).pipe(Effect.forkScoped({ startImmediately: true }));
3066
+ // A save that ends without reaching the gate fails the test instead of hanging it.
3067
+ yield* Effect.raceFirst(
3068
+ Deferred.await(gate.cleanupStarted),
3069
+ Fiber.join(savingB).pipe(
3070
+ Effect.andThen(Effect.die("save finished before the cleanup gate")),
3071
+ ),
3072
+ );
3073
+ // C's save waits behind B's while the client that reported Work disconnects, as at shutdown.
3074
+ const savingC = yield* reportFromC({
3075
+ profiles: [],
3076
+ defaultProfileId: "profile-shared",
3077
+ }).pipe(Effect.forkScoped({ startImmediately: true }));
3078
+ yield* Scope.close(clientA, Exit.void);
3079
+ yield* Deferred.succeed(gate.releaseCleanup, undefined);
3080
+ yield* Fiber.join(savingB);
3081
+ yield* Fiber.join(savingC);
3082
+ }).pipe(
3083
+ Effect.scoped,
3084
+ Effect.provide(
3085
+ Layer.fresh(ServerBrowser.layer).pipe(
3086
+ Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)),
3087
+ ),
3088
),
3089
);
3061
- // C's save waits behind B's while the client that reported Work disconnects, as at shutdown.
3062
- const savingC = yield* reportFromC({ profiles: [], defaultProfileId: "profile-shared" }).pipe(
3063
- Effect.forkScoped({ startImmediately: true }),
3064
- );
3065
- yield* Scope.close(clientA, Exit.void);
3066
- yield* Deferred.succeed(gate.releaseCleanup, undefined);
3067
- yield* Fiber.join(savingB);
3068
- yield* Fiber.join(savingC);
3069
- }).pipe(
3070
- Effect.scoped,
3071
- Effect.provide(
3072
- Layer.fresh(ServerBrowser.layer).pipe(
3073
- Layer.provide(Layer.succeed(FileSystem.FileSystem, gate.fs)),
3074
- ),
3075
- ),
3076
- );
3090
3078
- const restarted = yield* Effect.gen(function* () {
3079
- const broker = yield* Broker.PreviewAutomationBroker;
3080
- yield* ServerBrowser.ServerBrowser;
3081
- yield* Effect.yieldNow;
3082
- return yield* broker.invoke<PreviewAutomationStatus>({
3083
- scope,
3084
- operation: "open",
3085
- input: { reuseExistingTab: false, show: false, profileId: "Work" },
3086
- });
3087
- }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer)));
3091
+ const restarted = yield* Effect.gen(function* () {
3092
+ const broker = yield* Broker.PreviewAutomationBroker;
3093
+ yield* ServerBrowser.ServerBrowser;
3094
+ yield* Effect.yieldNow;
3095
+ return yield* broker.invoke<PreviewAutomationStatus>({
3096
+ scope,
3097
+ operation: "open",
3098
+ input: { reuseExistingTab: false, show: false, profileId: "Work" },
3099
+ });
3100
+ }).pipe(Effect.provide(Layer.fresh(ServerBrowser.layer)));
3101
3089
- expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]);
3090
- expect(restarted.tabs).toMatchObject([{ profileId: "profile-work" }]);
3091
- expect(restarted).toMatchObject({
3092
- defaultProfileId: "profile-shared",
3093
- profiles: [
3094
- { id: "default", name: "Default" },
3095
- { id: "incognito", name: "Incognito", incognito: true },
3096
- ...[...fromA, ...fromB].map(({ id, name }) => ({ id, name })),
3097
- ],
3098
- });
3099
- }).pipe(Effect.provide(dependencies)),
3102
+ expect(contextRequests).toEqual([{ profileId: "profile-work", isolated: false }]);
3103
+ expect(restarted.tabs).toMatchObject([{ profileId: "profile-work" }]);
3104
+ expect(restarted).toMatchObject({
3105
+ defaultProfileId: "profile-shared",
3106
+ profiles: [
3107
+ { id: "default", name: "Default" },
3108
+ { id: "incognito", name: "Incognito", incognito: true },
3109
+ ...[...fromA, ...fromB].map(({ id, name }) => ({ id, name })),
3110
+ ],
3111
+ });
3112
+ }).pipe(Effect.provide(dependencies)),
3113
);
3114
3102
-it.live("warns at startup about a saved profile catalog it cannot read or decode", () =>
3115
+it.effect("warns at startup about a saved profile catalog it cannot read or decode", () =>
3116
Effect.gen(function* () {
3117
const fs = yield* FileSystem.FileSystem;
3118
const path = yield* Path.Path;
@@ -3137,7 +3150,7 @@ it.live("warns at startup about a saved profile catalog it cannot read or decode
3150
}).pipe(Effect.provide(dependencies)),
3151
);
3152
3140
-it.live("a report interrupted while an earlier save holds the lock is still saved", () =>
3153
+it.effect("a report interrupted while an earlier save holds the lock is still saved", () =>
3154
Effect.gen(function* () {
3155
const gate = yield* gateSaveCleanup;
3156
const work = { id: "profile-work", name: "Work", kind: "persistent" } as const;
@@ -3190,7 +3203,7 @@ it.live("a report interrupted while an earlier save holds the lock is still save
3203
}).pipe(Effect.provide(dependencies)),
3204
);
3205
3193
-it.live("profiles reported by one client survive another client's report", () =>
3206
+it.effect("profiles reported by one client survive another client's report", () =>
3207
Effect.scoped(
3208
Effect.gen(function* () {
3209
const { browser, broker } = yield* ready;
@@ -3233,7 +3246,7 @@ it.live("profiles reported by one client survive another client's report", () =>
3246
).pipe(Effect.provide(layer)),
3247
);
3248
3236
-it.live.each([
3249
+it.effect.each([
3250
{ budget: "agent", limit: 8 },
3251
{ budget: "server", limit: 32 },
3252
])("opens and popups reserve the $budget budget before session creation", ({ budget, limit }) =>
@@ -3341,7 +3354,7 @@ it.live.each([
3354
).pipe(Effect.provide(layer)),
3355
);
3356
3344
-it.live("failed session and browser launches release capacity, as does closing a tab", () =>
3357
+it.effect("failed session and browser launches release capacity, as does closing a tab", () =>
3358
Effect.scoped(
3359
Effect.gen(function* () {
3360
const { broker, tabId } = yield* ready;
@@ -3401,7 +3414,7 @@ it.live("failed session and browser launches release capacity, as does closing a
3414
).pipe(Effect.provide(layer)),
3415
);
3416
3404
-it.live("a full server takes back the slot of the longest idle agent tab nobody views", () =>
3417
+it.effect("a full server takes back the slot of the longest idle agent tab nobody views", () =>
3418
Effect.scoped(
3419
Effect.gen(function* () {
3420
const broker = yield* Broker.PreviewAutomationBroker;
@@ -3477,7 +3490,7 @@ const certificateError = {
3490
};
3491
const dataUrl = `data:text/html,${"PAYLOAD".repeat(300)}`;
3492
3480
-it.live("reports why a page failed to load while the tab shows the error page", () =>
3493
+it.effect("reports why a page failed to load while the tab shows the error page", () =>
3494
Effect.scoped(
3495
Effect.gen(function* () {
3496
const { broker, tabId } = yield* ready;
@@ -3584,7 +3597,7 @@ it.effect("preview_open rejects a desktop navigation that failed before automati
3597
).pipe(Effect.provide(layer)),
3598
);
3599
3587
-it.live("reports a desktop tab's load failure from before the server connected", () =>
3600
+it.effect("reports a desktop tab's load failure from before the server connected", () =>
3601
Effect.scoped(
3602
Effect.gen(function* () {
3603
const browser = yield* ServerBrowser.ServerBrowser;
apps/server/src/provider/ModelManifest.test.ts
+28
-25
@@ -266,7 +266,7 @@ const layerService = (input: {
266
);
267
268
describe("ModelManifest service", () => {
269
- it.live("prefers a fetched manifest over the bundle and caches it to disk", () =>
269
+ it.effect("prefers a fetched manifest over the bundle and caches it to disk", () =>
270
Effect.gen(function* () {
271
const service = yield* ModelManifest.make;
272
const refreshed = yield* service.refresh;
@@ -285,29 +285,32 @@ describe("ModelManifest service", () => {
285
),
286
);
287
288
- it.live("ignores older remote edits without replacing the current manifest or disk cache", () => {
289
- let remote = { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" };
290
- return Effect.gen(function* () {
291
- const service = yield* ModelManifest.make;
292
- assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST);
293
- assert.deepStrictEqual(yield* service.current, ModelManifest.BUNDLED_MODEL_MANIFEST);
288
+ it.effect(
289
+ "ignores older remote edits without replacing the current manifest or disk cache",
290
+ () => {
291
+ let remote = { ...REMOTE_MANIFEST, updatedAt: "2000-01-01T00:00:00Z" };
292
+ return Effect.gen(function* () {
293
+ const service = yield* ModelManifest.make;
294
+ assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST);
295
+ assert.deepStrictEqual(yield* service.current, ModelManifest.BUNDLED_MODEL_MANIFEST);
296
295
- remote = { ...REMOTE_MANIFEST, updatedAt: REMOTE_UPDATED_AT };
296
- assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
297
- remote = { ...REMOTE_MANIFEST, updatedAt: ModelManifest.BUNDLED_MODEL_MANIFEST.updatedAt! };
298
- assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
299
- const rebooted = yield* ModelManifest.make;
300
- assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST);
301
- }).pipe(
302
- Effect.scoped,
303
- Effect.provide(
304
- layerService({
305
- prefix: "model-manifest-stale-fetch-test",
306
- response: () => Response.json(remote),
307
- }),
308
- ),
309
- );
310
- });
297
+ remote = { ...REMOTE_MANIFEST, updatedAt: REMOTE_UPDATED_AT };
298
+ assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
299
+ remote = { ...REMOTE_MANIFEST, updatedAt: ModelManifest.BUNDLED_MODEL_MANIFEST.updatedAt! };
300
+ assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST);
301
+ const rebooted = yield* ModelManifest.make;
302
+ assert.deepStrictEqual(yield* rebooted.current, REMOTE_MANIFEST);
303
+ }).pipe(
304
+ Effect.scoped,
305
+ Effect.provide(
306
+ layerService({
307
+ prefix: "model-manifest-stale-fetch-test",
308
+ response: () => Response.json(remote),
309
+ }),
310
+ ),
311
+ );
312
+ },
313
+ );
314
315
it.effect("preserves the last-good remote cache when later payloads are invalid", () => {
316
let responseIndex = 0;
@@ -364,7 +367,7 @@ describe("ModelManifest service", () => {
367
);
368
});
369
367
- it.live("drops a disk cache of a manifest older than the bundled one", () =>
370
+ it.effect("drops a disk cache of a manifest older than the bundled one", () =>
371
Effect.gen(function* () {
372
const fs = yield* FileSystem.FileSystem;
373
const path = yield* Path.Path;
@@ -400,7 +403,7 @@ describe("ModelManifest service", () => {
403
),
404
);
405
403
- it.live("does not fetch when provider update checks are disabled", () =>
406
+ it.effect("does not fetch when provider update checks are disabled", () =>
407
Effect.gen(function* () {
408
let fetchCount = 0;
409
const service = yield* ModelManifest.make.pipe(
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+3
-3
@@ -346,7 +346,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
346
}).pipe(Effect.provide(layerTest)),
347
);
348
349
- it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
349
+ it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () =>
350
Effect.gen(function* () {
351
const staleId = ProviderInstanceId.make("codex_stale");
352
const configMap: ProviderInstanceConfigMap = {
@@ -370,7 +370,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
370
}).pipe(Effect.provide(layerTest)),
371
);
372
373
- it.live("lists a blocked driver's instances as unavailable without running them", () =>
373
+ it.effect("lists a blocked driver's instances as unavailable without running them", () =>
374
Effect.gen(function* () {
375
const instanceId = ProviderInstanceId.make("codex");
376
const reason = "Example Corp's policy does not allow the Codex provider.";
@@ -862,7 +862,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => {
862
);
863
}
864
865
- it.live(
865
+ it.effect(
866
"shadows instances whose driver is not registered in this build without failing boot",
867
() =>
868
Effect.gen(function* () {
apps/server/src/storageCleanup.test.ts
+21
-12
@@ -1008,7 +1008,7 @@ describe("subagent worktree ownership", () => {
1008
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1009
);
1010
1011
- it.live.each([
1011
+ it.effect.each([
1012
"parent-unsettled",
1013
"parent-resettled",
1014
"child-unsettled",
@@ -1017,6 +1017,7 @@ describe("subagent worktree ownership", () => {
1017
] as const)("cancels inherited settlement during measurement (%s)", (change) =>
1018
runCleanupTest(
1019
Effect.gen(function* () {
1020
+ yield* TestClock.setTime(NOW_MS);
1021
const fixture = yield* pausedMeasurementFixture({
1022
...DEFAULT_SERVER_SETTINGS.storageCleanup,
1023
worktreeSettledAfterDays: 0,
@@ -1258,7 +1259,7 @@ describe("subagent worktree ownership", () => {
1259
}).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1260
);
1261
1261
- it.live.each([
1262
+ it.effect.each([
1263
"running",
1264
"pending",
1265
"activity",
@@ -1270,6 +1271,7 @@ describe("subagent worktree ownership", () => {
1271
] as const)("cancels removal when a child changes during measurement (%s)", (change) =>
1272
runCleanupTest(
1273
Effect.gen(function* () {
1274
+ yield* TestClock.setTime(NOW_MS);
1275
const fixture = yield* pausedMeasurementFixture();
1276
const root = shell({ branch: "feature", worktreePath: fixture.worktree });
1277
const child = {
@@ -2502,12 +2504,13 @@ describe("storage cleanup reports and local file policies", () => {
2504
}),
2505
),
2506
);
2505
- it.live.each([
2507
+ it.effect.each([
2508
{ days: 8, reason: "Inactive for 1 of 8 days" },
2509
{ days: null, reason: "No rules apply" },
2510
])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) =>
2511
runCleanupTest(
2512
Effect.gen(function* () {
2513
+ yield* TestClock.setTime(NOW_MS);
2514
const fixture = yield* cleanupFixture({
2515
...DEFAULT_SERVER_SETTINGS.storageCleanup,
2516
worktreeAfterDays: days,
@@ -2517,9 +2520,7 @@ describe("storage cleanup reports and local file policies", () => {
2520
shell({
2521
branch: "feature",
2522
worktreePath: fixture.worktree,
2520
- latestUserMessageAt: DateTime.makeUnsafe(
2521
- DateTime.toEpochMillis(yield* DateTime.now) - DAY_MS,
2522
- ),
2523
+ latestUserMessageAt: at(-DAY_MS),
2524
}),
2525
]);
2526
yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n");
@@ -2585,7 +2586,7 @@ describe("storage cleanup reports and local file policies", () => {
2586
}),
2587
),
2588
);
2588
- it.live.each([
2589
+ it.effect.each([
2590
[
2591
"its owner's branch is cleared",
2592
(worktree: string) => [shell({ branch: null, worktreePath: worktree, updatedAt: at(0) })],
@@ -2622,6 +2623,7 @@ describe("storage cleanup reports and local file policies", () => {
2623
] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) =>
2624
runCleanupTest(
2625
Effect.gen(function* () {
2626
+ yield* TestClock.setTime(NOW_MS);
2627
const fixture = yield* pausedMeasurementFixture();
2628
const { fs, worktree } = fixture;
2629
fixture.setPolicy("tracked-changes");
@@ -2769,7 +2771,7 @@ describe("storage cleanup reports and local file policies", () => {
2771
}),
2772
),
2773
);
2772
- it.live.each([
2774
+ it.effect.each([
2775
["unchanged", "removed", "No commits beyond the project branch"],
2776
["unmerged", "kept", "Has commits beyond the project branch"],
2777
["detached", "kept", "Project branch is unavailable"],
@@ -2777,6 +2779,7 @@ describe("storage cleanup reports and local file policies", () => {
2779
] as const)("cleans archived local-only worktrees: %s", ([state, outcome, reason]) =>
2780
runCleanupTest(
2781
Effect.gen(function* () {
2782
+ yield* TestClock.setTime(NOW_MS);
2783
const { service, fs, repo, worktree, command, setThreads } = yield* cleanupFixture({
2784
...DEFAULT_SERVER_SETTINGS.storageCleanup,
2785
worktreeUnchanged: state !== "merged-only",
@@ -3210,11 +3213,12 @@ describe("storage cleanup reports and local file policies", () => {
3213
});
3214
3215
describe("settled worktree rechecks", () => {
3213
- it.live.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)(
3216
+ it.effect.each(["autoResumeLimitedThreads", "snoozeLimitedThreads"] as const)(
3217
"keeps a usage-limited checkout when %s is enabled during measurement",
3218
(preference) =>
3219
runCleanupTest(
3220
Effect.gen(function* () {
3221
+ yield* TestClock.setTime(NOW_MS);
3222
const fixture = yield* pausedMeasurementFixture();
3223
fixture.setSettings({ autoResumeLimitedThreads: false, snoozeLimitedThreads: false });
3224
fixture.setThreads([
@@ -3232,16 +3236,20 @@ describe("settled worktree rechecks", () => {
3236
fixture.setSettings({ [preference]: true });
3237
yield* Deferred.succeed(fixture.resume, undefined);
3238
const report = yield* Fiber.join(run);
3235
- expect(report.entries[0]?.outcome).toBe("kept");
3239
+ expect(report.entries[0]).toMatchObject({
3240
+ outcome: "kept",
3241
+ reason: "Settings changed since check",
3242
+ });
3243
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
3244
}),
3245
),
3246
);
3240
- it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])(
3247
+ it.effect.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])(
3248
"keeps a checkout changed during measurement (%j)",
3249
(change) =>
3250
runCleanupTest(
3251
Effect.gen(function* () {
3252
+ yield* TestClock.setTime(NOW_MS);
3253
const fixture = yield* pausedMeasurementFixture();
3254
const thread = shell({
3255
branch: "feature",
@@ -3269,9 +3277,10 @@ describe("settled worktree rechecks", () => {
3277
);
3278
});
3279
3272
-it.live("keeps saved usage data when removing a settled checkout", () =>
3280
+it.effect("keeps saved usage data when removing a settled checkout", () =>
3281
runCleanupTest(
3282
Effect.gen(function* () {
3283
+ yield* TestClock.setTime(NOW_MS);
3284
const fixture = yield* cleanupFixture();
3285
fixture.setSettings({
3286
storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 },
apps/server/src/usage/UsageService.test.ts
+151
-145
@@ -521,7 +521,7 @@ describe("Codex usage history", () => {
521
});
522
523
describe("UsageService", () => {
524
- it.live("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () =>
524
+ it.effect("counts compressed Codex rollouts across refresh, rewrites, and cache restarts", () =>
525
Effect.gen(function* () {
526
const { home, settings } = yield* setup;
527
const sessions = NodePath.join(home, "codex", "sessions");
@@ -634,7 +634,7 @@ describe("UsageService", () => {
634
}).pipe(Effect.scoped),
635
);
636
637
- it.live("keeps the first host identity across recreation and explicit override removal", () =>
637
+ it.effect("keeps the first host identity across recreation and explicit override removal", () =>
638
Effect.gen(function* () {
639
const { transcript, settings, home } = yield* setup;
640
yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
@@ -665,7 +665,7 @@ describe("UsageService", () => {
665
}).pipe(Effect.scoped),
666
);
667
668
- it.live("concurrent initialization keeps one host identity across service recreation", () =>
668
+ it.effect("concurrent initialization keeps one host identity across service recreation", () =>
669
Effect.gen(function* () {
670
const { transcript, settings, home } = yield* setup;
671
yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
@@ -721,7 +721,7 @@ describe("UsageService", () => {
721
}).pipe(Effect.scoped),
722
);
723
724
- it.live(
724
+ it.effect(
725
"repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers",
726
() =>
727
Effect.gen(function* () {
@@ -873,7 +873,7 @@ describe("UsageService", () => {
873
}).pipe(Effect.scoped),
874
);
875
876
- it.live(
876
+ it.effect(
877
"keeps resolved Codex tiers when a grown pre-v15 cache entry re-parses without history",
878
() =>
879
Effect.gen(function* () {
@@ -969,7 +969,7 @@ describe("UsageService", () => {
969
}).pipe(Effect.scoped),
970
);
971
972
- it.live(
972
+ it.effect(
973
"reads Pi per-model usage and auxiliary costs once across forks and repeated entries",
974
() =>
975
Effect.gen(function* () {
@@ -1158,7 +1158,7 @@ describe("UsageService", () => {
1158
}).pipe(Effect.scoped),
1159
);
1160
1161
- it.live(
1161
+ it.effect(
1162
"reads Muse inference history once, persists appended usage, and reprices unknown models",
1163
() =>
1164
Effect.gen(function* () {
@@ -1380,7 +1380,7 @@ describe("UsageService", () => {
1380
}).pipe(Effect.scoped),
1381
);
1382
1383
- it.live("returns other providers' usage while Muse home discovery is still pending", () =>
1383
+ it.effect("returns other providers' usage while Muse home discovery is still pending", () =>
1384
Effect.gen(function* () {
1385
const { transcript, settings, home } = yield* setup;
1386
yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5)));
@@ -1440,70 +1440,72 @@ describe("UsageService", () => {
1440
}).pipe(Effect.scoped),
1441
);
1442
1443
- it.live("reports missing Pi history and skips malformed records without losing valid usage", () =>
1444
- Effect.gen(function* () {
1445
- const { home, settings } = yield* setup;
1446
- yield* Effect.gen(function* () {
1447
- const service = yield* UsageService.make;
1448
- const missing = yield* service.readSummary(WINDOW);
1449
- assert.strictEqual(
1450
- missing.sources.find((source) => source.fingerprint.provider === "pi")?.status,
1451
- "missing",
1452
- );
1453
- const dir = NodePath.join(home, "pi", "sessions");
1454
- yield* Effect.promise(async () => {
1455
- await NodeFSP.mkdir(dir, { recursive: true });
1456
- await NodeFSP.writeFile(
1457
- NodePath.join(dir, "session.jsonl"),
1458
- [
1459
- "{broken",
1460
- "null",
1461
- encodeUnknownJsonString({ type: "session", id: "valid" }),
1462
- encodeUnknownJsonString({
1463
- type: "message",
1464
- id: "bad",
1465
- timestamp: "invalid",
1466
- message: {
1467
- role: "assistant",
1468
- provider: "openai",
1469
- model: "model",
1470
- usage: { input: 100 },
1471
- },
1472
- }),
1473
- encodeUnknownJsonString({
1474
- type: "message",
1475
- id: "valid",
1476
- timestamp: "2026-08-01T10:00:00Z",
1477
- message: {
1478
- role: "assistant",
1479
- provider: "openai",
1480
- model: "model",
1481
- usage: {
1482
- input: -1,
1483
- cacheRead: "100",
1484
- output: 7,
1485
- reasoning: 50,
1486
- cost: { total: -1 },
1487
- },
1488
- },
1489
- }),
1490
- ].join("\n") + "\n",
1443
+ it.effect(
1444
+ "reports missing Pi history and skips malformed records without losing valid usage",
1445
+ () =>
1446
+ Effect.gen(function* () {
1447
+ const { home, settings } = yield* setup;
1448
+ yield* Effect.gen(function* () {
1449
+ const service = yield* UsageService.make;
1450
+ const missing = yield* service.readSummary(WINDOW);
1451
+ assert.strictEqual(
1452
+ missing.sources.find((source) => source.fingerprint.provider === "pi")?.status,
1453
+ "missing",
1454
);
1492
- });
1493
- const summary = yield* service.readSummary(WINDOW);
1494
- const pi = summary.buckets.filter((bucket) => bucket.provider === "pi");
1495
- assert.strictEqual(pi.length, 1);
1496
- assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7);
1497
- assert.strictEqual(pi[0]?.totals.reasoningTokens, 7);
1498
- assert.strictEqual(pi[0]?.costSource, "unpriced");
1499
- }).pipe(
1500
- Effect.scoped,
1501
- Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })),
1502
- );
1503
- }).pipe(Effect.scoped),
1455
+ const dir = NodePath.join(home, "pi", "sessions");
1456
+ yield* Effect.promise(async () => {
1457
+ await NodeFSP.mkdir(dir, { recursive: true });
1458
+ await NodeFSP.writeFile(
1459
+ NodePath.join(dir, "session.jsonl"),
1460
+ [
1461
+ "{broken",
1462
+ "null",
1463
+ encodeUnknownJsonString({ type: "session", id: "valid" }),
1464
+ encodeUnknownJsonString({
1465
+ type: "message",
1466
+ id: "bad",
1467
+ timestamp: "invalid",
1468
+ message: {
1469
+ role: "assistant",
1470
+ provider: "openai",
1471
+ model: "model",
1472
+ usage: { input: 100 },
1473
+ },
1474
+ }),
1475
+ encodeUnknownJsonString({
1476
+ type: "message",
1477
+ id: "valid",
1478
+ timestamp: "2026-08-01T10:00:00Z",
1479
+ message: {
1480
+ role: "assistant",
1481
+ provider: "openai",
1482
+ model: "model",
1483
+ usage: {
1484
+ input: -1,
1485
+ cacheRead: "100",
1486
+ output: 7,
1487
+ reasoning: 50,
1488
+ cost: { total: -1 },
1489
+ },
1490
+ },
1491
+ }),
1492
+ ].join("\n") + "\n",
1493
+ );
1494
+ });
1495
+ const summary = yield* service.readSummary(WINDOW);
1496
+ const pi = summary.buckets.filter((bucket) => bucket.provider === "pi");
1497
+ assert.strictEqual(pi.length, 1);
1498
+ assert.strictEqual(pi[0] && totalTokens(pi[0].totals), 7);
1499
+ assert.strictEqual(pi[0]?.totals.reasoningTokens, 7);
1500
+ assert.strictEqual(pi[0]?.costSource, "unpriced");
1501
+ }).pipe(
1502
+ Effect.scoped,
1503
+ Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })),
1504
+ );
1505
+ }).pipe(Effect.scoped),
1506
);
1507
1506
- it.live("discovers Pi history in its default home and directory overrides", () =>
1508
+ it.effect("discovers Pi history in its default home and directory overrides", () =>
1509
Effect.gen(function* () {
1510
const { home, settings } = yield* setup;
1511
for (const [agentDir, sessionDir, relativeDir, launchArgs, instanceHome, platform] of [
@@ -1610,7 +1612,7 @@ describe("UsageService", () => {
1612
}).pipe(Effect.scoped),
1613
);
1614
1613
- it.live("reads shared managed default and disabled extra account history once", () =>
1615
+ it.effect("reads shared managed default and disabled extra account history once", () =>
1616
Effect.gen(function* () {
1617
const { home, settings } = yield* setup;
1618
const summary = yield* Effect.gen(function* () {
@@ -1690,7 +1692,7 @@ describe("UsageService", () => {
1692
}).pipe(Effect.scoped),
1693
);
1694
1693
- it.live("restores the Cursor account cache after a restart", () =>
1695
+ it.effect("restores the Cursor account cache after a restart", () =>
1696
Effect.gen(function* () {
1697
const { settings, home } = yield* setup;
1698
yield* TestClock.setTime(CURSOR_NOW);
@@ -1729,10 +1731,10 @@ describe("UsageService", () => {
1731
}),
1732
),
1733
);
1732
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1734
+ }).pipe(Effect.scoped),
1735
);
1736
1735
- it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
1737
+ it.effect("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
1738
Effect.gen(function* () {
1739
const { settings, home } = yield* setup;
1740
const signIn = new TextEncoder().encode(
@@ -1784,7 +1786,7 @@ describe("UsageService", () => {
1786
}).pipe(Effect.scoped),
1787
);
1788
1787
- it.live("does not show a previous Cursor account's history after the API key changes", () =>
1789
+ it.effect("does not show a previous Cursor account's history after the API key changes", () =>
1790
Effect.gen(function* () {
1791
const { settings, home } = yield* setup;
1792
yield* TestClock.setTime(CURSOR_NOW);
@@ -1823,10 +1825,10 @@ describe("UsageService", () => {
1825
}),
1826
),
1827
);
1826
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1828
+ }).pipe(Effect.scoped),
1829
);
1830
1829
- it.live("keeps a new Cursor key's refresh visible beside a failing key", () =>
1831
+ it.effect("keeps a new Cursor key's refresh visible beside a failing key", () =>
1832
Effect.gen(function* () {
1833
const { settings, home } = yield* setup;
1834
const cursor = makeFakeCursor();
@@ -1911,7 +1913,7 @@ describe("UsageService", () => {
1913
}).pipe(Effect.scoped),
1914
);
1915
1914
- it.live("reports one Cursor source when two API keys belong to the same account", () =>
1916
+ it.effect("reports one Cursor source when two API keys belong to the same account", () =>
1917
Effect.gen(function* () {
1918
const { settings, home } = yield* setup;
1919
yield* TestClock.setTime(CURSOR_NOW);
@@ -1970,10 +1972,10 @@ describe("UsageService", () => {
1972
}),
1973
),
1974
);
1973
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
1975
+ }).pipe(Effect.scoped),
1976
);
1977
1976
- it.live(
1978
+ it.effect(
1979
"includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account",
1980
() =>
1981
Effect.gen(function* () {
@@ -2030,7 +2032,7 @@ describe("UsageService", () => {
2032
}).pipe(Effect.scoped),
2033
);
2034
2033
- it.live("counts unpriced tokens from the unpriced records of a mixed model", () =>
2035
+ it.effect("counts unpriced tokens from the unpriced records of a mixed model", () =>
2036
Effect.gen(function* () {
2037
const { settings, home } = yield* setup;
2038
const message = (id: string, cost: number, input: number, output: number, minute: number) =>
@@ -2067,7 +2069,7 @@ describe("UsageService", () => {
2069
}).pipe(Effect.scoped),
2070
);
2071
2070
- it.live("includes host and merged OpenCode instance histories once across list aliases", () =>
2072
+ it.effect("includes host and merged OpenCode instance histories once across list aliases", () =>
2073
Effect.gen(function* () {
2074
const { settings, home } = yield* setup;
2075
const hostRoot = NodePath.join(home, "opencode");
@@ -2146,7 +2148,7 @@ describe("UsageService", () => {
2148
}).pipe(Effect.scoped),
2149
);
2150
2149
- it.live("counts aliased OpenCode and Antigravity directories once", () =>
2151
+ it.effect("counts aliased OpenCode and Antigravity directories once", () =>
2152
Effect.gen(function* () {
2153
const { settings, home } = yield* setup;
2154
const opencode = NodePath.join(home, "opencode-store");
@@ -2200,7 +2202,7 @@ describe("UsageService", () => {
2202
}).pipe(Effect.scoped),
2203
);
2204
2203
- it.live("reads Antigravity history from each instance's data directory", () =>
2205
+ it.effect("reads Antigravity history from each instance's data directory", () =>
2206
Effect.gen(function* () {
2207
const { settings, home } = yield* setup;
2208
const first = NodePath.join(home, "antigravity-first");
@@ -2271,7 +2273,7 @@ describe("UsageService", () => {
2273
}).pipe(Effect.scoped),
2274
);
2275
2274
- it.live("reads configured and disabled accounts once across shared and aliased homes", () =>
2276
+ it.effect("reads configured and disabled accounts once across shared and aliased homes", () =>
2277
Effect.gen(function* () {
2278
const { transcript, settings, home } = yield* setup;
2279
const codexHome = NodePath.join(home, "codex-account");
@@ -2390,7 +2392,7 @@ describe("UsageService", () => {
2392
}).pipe(Effect.scoped),
2393
);
2394
2393
- it.live(
2395
+ it.effect(
2396
"uses explicit account settings before environment and default homes, then refreshes them",
2397
() =>
2398
Effect.gen(function* () {
@@ -2473,7 +2475,7 @@ describe("UsageService", () => {
2475
}).pipe(Effect.scoped),
2476
);
2477
2476
- it.live(
2478
+ it.effect(
2479
"uses inherited home variables when explicit default accounts have no home settings",
2480
() =>
2481
Effect.gen(function* () {
@@ -2519,7 +2521,7 @@ describe("UsageService", () => {
2521
}).pipe(Effect.scoped),
2522
);
2523
2522
- it.live.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
2524
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
2525
"reports unreadable transcripts as partial and recovers once they can be read",
2526
() =>
2527
Effect.gen(function* () {
@@ -2547,7 +2549,7 @@ describe("UsageService", () => {
2549
}).pipe(Effect.scoped),
2550
);
2551
2550
- it.live(
2552
+ it.effect(
2553
"answers a provisional read from the last scan, then the exact read adds what changed",
2554
() =>
2555
Effect.gen(function* () {
@@ -2616,7 +2618,7 @@ describe("UsageService", () => {
2618
}).pipe(Effect.scoped),
2619
);
2620
2619
- it.live("filters original model IDs before aliases, pricing, buckets and session counts", () =>
2621
+ it.effect("filters original model IDs before aliases, pricing, buckets and session counts", () =>
2622
Effect.gen(function* () {
2623
const { transcript, settings, home } = yield* setup;
2624
yield* Effect.promise(() =>
@@ -2721,7 +2723,7 @@ describe("UsageService", () => {
2723
}).pipe(Effect.scoped),
2724
);
2725
2724
- it.live("reprices unchanged transcripts when custom prices are added, edited, or removed", () =>
2726
+ it.effect("reprices unchanged transcripts when custom prices are added, edited, or removed", () =>
2727
Effect.gen(function* () {
2728
const { transcript, settings, home } = yield* setup;
2729
yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model")));
@@ -2765,7 +2767,7 @@ describe("UsageService", () => {
2767
}).pipe(Effect.scoped),
2768
);
2769
2768
- it.live(
2770
+ it.effect(
2771
"retains Codex reconciliation and partial coverage through persisted restart, append and repair",
2772
() =>
2773
Effect.gen(function* () {
@@ -2888,7 +2890,7 @@ describe("UsageService", () => {
2890
}).pipe(Effect.scoped),
2891
);
2892
2891
- it.live(
2893
+ it.effect(
2894
"merges partial Claude copies through tail replacement, newline completion and restart",
2895
() =>
2896
Effect.gen(function* () {
@@ -2947,7 +2949,7 @@ describe("UsageService", () => {
2949
}).pipe(Effect.scoped),
2950
);
2951
2950
- it.live(
2952
+ it.effect(
2953
"keeps large-record totals and costs exact through append, dedupe, restart and cleanup",
2954
() =>
2955
Effect.gen(function* () {
@@ -3002,10 +3004,11 @@ describe("UsageService", () => {
3004
}).pipe(Effect.scoped),
3005
);
3006
3005
- it.live.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])(
3007
+ it.effect.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])(
3008
"upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts, removes the old file",
3009
(version) =>
3010
Effect.gen(function* () {
3011
+ yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z"));
3012
const { home, settings } = yield* setup;
3013
const sessions = NodePath.join(home, "codex", "sessions");
3014
const rollout = (sessionId: string, outputTokens: number) =>
@@ -3132,7 +3135,7 @@ describe("UsageService", () => {
3135
}).pipe(Effect.scoped),
3136
);
3137
3135
- it.live("re-parses a clean v10 Codex rollout that grew after an interrupted request", () =>
3138
+ it.effect("re-parses a clean v10 Codex rollout that grew after an interrupted request", () =>
3139
Effect.gen(function* () {
3140
const { home, settings } = yield* setup;
3141
const sessions = NodePath.join(home, "codex", "sessions");
@@ -3232,7 +3235,7 @@ describe("UsageService", () => {
3235
}).pipe(Effect.scoped),
3236
);
3237
3235
- it.live("preserves saved tokens, costs and sessions after transcript cleanup and restart", () =>
3238
+ it.effect("preserves saved tokens, costs and sessions after transcript cleanup and restart", () =>
3239
Effect.gen(function* () {
3240
const { transcript, settings, home } = yield* setup;
3241
const alias = NodePath.join(home, "claude-alias");
@@ -3333,7 +3336,7 @@ describe("UsageService", () => {
3336
}).pipe(Effect.scoped),
3337
);
3338
3336
- it.live("credits the same copy of a duplicate after its transcripts are deleted", () =>
3339
+ it.effect("credits the same copy of a duplicate after its transcripts are deleted", () =>
3340
Effect.gen(function* () {
3341
const { transcript, settings, home } = yield* setup;
3342
const dir = NodePath.dirname(transcript);
@@ -3371,7 +3374,7 @@ describe("UsageService", () => {
3374
}).pipe(Effect.scoped),
3375
);
3376
3374
- it.live("credits the same copy of a duplicate from the last scan as an exact read does", () =>
3377
+ it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () =>
3378
Effect.gen(function* () {
3379
yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z"));
3380
const { transcript, settings, home } = yield* setup;
@@ -3426,10 +3429,10 @@ describe("UsageService", () => {
3429
}).pipe(
3430
Effect.provide(layerService({ prefix: "usage-service-narrow-order-test", home, settings })),
3431
);
3429
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
3432
+ }).pipe(Effect.scoped),
3433
);
3434
3432
- it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")(
3435
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
3436
"keeps a newer cached read when a slower scan of another window finishes later",
3437
() =>
3438
Effect.gen(function* () {
@@ -3459,50 +3462,53 @@ describe("UsageService", () => {
3462
}).pipe(Effect.scoped),
3463
);
3464
3462
- it.live("keeps an absent directory missing when its cached files only contain diagnostics", () =>
3463
- Effect.gen(function* () {
3464
- const { transcript, settings, home } = yield* setup;
3465
- yield* Effect.promise(() =>
3466
- NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }),
3467
- );
3468
- yield* Effect.gen(function* () {
3469
- const { stateDir } = yield* ServerConfig.ServerConfig;
3470
- const mtimeMs = yield* Clock.currentTimeMillis;
3471
- const cache = makeScanCacheWriter()(
3472
- new Map([
3473
- [
3474
- transcript,
3475
- {
3476
- size: 0,
3477
- mtimeMs,
3478
- provider: "claude" as const,
3479
- records: [],
3480
- tailRecords: [],
3481
- malformedRecords: 2,
3482
- position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
3483
- },
3484
- ],
3485
- ]),
3486
- {},
3465
+ it.effect(
3466
+ "keeps an absent directory missing when its cached files only contain diagnostics",
3467
+ () =>
3468
+ Effect.gen(function* () {
3469
+ yield* TestClock.setTime(Date.parse("2026-08-02T12:00:00Z"));
3470
+ const { transcript, settings, home } = yield* setup;
3471
+ yield* Effect.promise(() =>
3472
+ NodeFSP.rm(NodePath.join(home, "claude", "projects"), { recursive: true }),
3473
);
3488
- yield* Effect.promise(async () => {
3489
- await NodeFSP.mkdir(stateDir, { recursive: true });
3490
- await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache);
3491
- });
3492
- const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
3493
- const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
3494
- assert.strictEqual(source?.status, "missing");
3495
- assert.strictEqual(source?.scannedFiles, 0);
3496
- assert.strictEqual(source?.malformedRecords, 2);
3497
- }).pipe(
3498
- Effect.provide(
3499
- layerService({ prefix: "usage-service-missing-diagnostics", home, settings }),
3500
- ),
3501
- );
3502
- }).pipe(Effect.scoped),
3474
+ yield* Effect.gen(function* () {
3475
+ const { stateDir } = yield* ServerConfig.ServerConfig;
3476
+ const mtimeMs = yield* Clock.currentTimeMillis;
3477
+ const cache = makeScanCacheWriter()(
3478
+ new Map([
3479
+ [
3480
+ transcript,
3481
+ {
3482
+ size: 0,
3483
+ mtimeMs,
3484
+ provider: "claude" as const,
3485
+ records: [],
3486
+ tailRecords: [],
3487
+ malformedRecords: 2,
3488
+ position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null },
3489
+ },
3490
+ ],
3491
+ ]),
3492
+ {},
3493
+ );
3494
+ yield* Effect.promise(async () => {
3495
+ await NodeFSP.mkdir(stateDir, { recursive: true });
3496
+ await NodeFSP.writeFile(NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), cache);
3497
+ });
3498
+ const summary = yield* (yield* UsageService.make).readSummary(WINDOW);
3499
+ const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
3500
+ assert.strictEqual(source?.status, "missing");
3501
+ assert.strictEqual(source?.scannedFiles, 0);
3502
+ assert.strictEqual(source?.malformedRecords, 2);
3503
+ }).pipe(
3504
+ Effect.provide(
3505
+ layerService({ prefix: "usage-service-missing-diagnostics", home, settings }),
3506
+ ),
3507
+ );
3508
+ }).pipe(Effect.scoped),
3509
);
3510
3505
- it.live("reports saved usage of a removed directory only for windows it reaches", () =>
3511
+ it.effect("reports saved usage of a removed directory only for windows it reaches", () =>
3512
Effect.gen(function* () {
3513
yield* TestClock.setTime(Date.parse("2026-08-12T00:00:00Z"));
3514
const { transcript, settings, home } = yield* setup;
@@ -3533,10 +3539,10 @@ describe("UsageService", () => {
3539
assert.deepStrictEqual(later.buckets, []);
3540
assert.strictEqual(later.sources[0]?.status, "missing");
3541
assert.strictEqual(later.sources[0]?.scannedFiles, 0);
3536
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
3542
+ }).pipe(Effect.scoped),
3543
);
3544
3539
- it.live("does not share an in-flight scan after custom prices change", () =>
3545
+ it.effect("does not share an in-flight scan after custom prices change", () =>
3546
Effect.gen(function* () {
3547
const { transcript, settings, home } = yield* setup;
3548
yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5, "example-model")));
@@ -3605,7 +3611,7 @@ describe("UsageService", () => {
3611
}).pipe(Effect.scoped),
3612
);
3613
3608
- it.live.each(["network", "http", "invalidJson", "empty"] as const)(
3614
+ it.effect.each(["network", "http", "invalidJson", "empty"] as const)(
3615
"recovers pricing through the GitHub API after a %s failure",
3616
(failure) =>
3617
Effect.gen(function* () {
@@ -3664,7 +3670,7 @@ describe("UsageService", () => {
3670
}).pipe(Effect.scoped),
3671
);
3672
3667
- it.live("does not orphan an in-flight scan when its first caller is interrupted", () =>
3673
+ it.effect("does not orphan an in-flight scan when its first caller is interrupted", () =>
3674
Effect.gen(function* () {
3675
const { settings, home } = yield* setup;
3676
const service = yield* UsageService.make.pipe(
apps/server/src/ws.test.ts
+101
-97
@@ -276,25 +276,23 @@ const ReplayTestLayer = OrchestrationEventStore.layer.pipe(
276
Layer.provideMerge(SqlitePersistence.layerMemory),
277
);
278
279
-it.live.each(["thread", "shell"] as const)(
280
- "%s resume skips unknown types, synchronizes, and receives the live tail",
281
- (scope) =>
282
- Effect.gen(function* () {
283
- const store = yield* OrchestrationEventStore.OrchestrationEventStore;
284
- const sql = yield* SqlClient.SqlClient;
285
- const now = "2026-01-05T00:00:00.000Z";
286
- const threadId = ThreadId.make("thread:replay");
287
- const projectId = ProjectId.make("project:replay");
288
- const project = {
289
- id: projectId,
290
- title: "Replay",
291
- workspaceRoot: "/tmp/replay",
292
- defaultModelSelection: null,
293
- scripts: [],
294
- createdAt: now,
295
- updatedAt: now,
296
- } satisfies OrchestrationProjectShell;
297
- const insert = (version: number, unknown = false) => sql<{ sequence: number }>`
279
+const resumeSkipsUnknownTypes = (scope: "thread" | "shell") =>
280
+ Effect.gen(function* () {
281
+ const store = yield* OrchestrationEventStore.OrchestrationEventStore;
282
+ const sql = yield* SqlClient.SqlClient;
283
+ const now = "2026-01-05T00:00:00.000Z";
284
+ const threadId = ThreadId.make("thread:replay");
285
+ const projectId = ProjectId.make("project:replay");
286
+ const project = {
287
+ id: projectId,
288
+ title: "Replay",
289
+ workspaceRoot: "/tmp/replay",
290
+ defaultModelSelection: null,
291
+ scripts: [],
292
+ createdAt: now,
293
+ updatedAt: now,
294
+ } satisfies OrchestrationProjectShell;
295
+ const insert = (version: number, unknown = false) => sql<{ sequence: number }>`
296
INSERT INTO orchestration_events (
297
event_id, aggregate_kind, stream_id, stream_version, event_type,
298
occurred_at, actor_kind, payload_json, metadata_json, application_event_version
@@ -309,85 +307,91 @@ it.live.each(["thread", "shell"] as const)(
307
)}, '{}', 2
308
) RETURNING sequence
309
`;
312
- const [before] = yield* insert(0);
313
- yield* insert(1, true);
314
- const [after] = yield* insert(2);
315
- const [highWater] = yield* insert(3, true);
316
- const updates = yield* PubSub.unbounded();
317
- let liveSequence = 0;
318
- const consume = <A extends { readonly kind: string; readonly sequence?: number }, E, R>(
319
- stream: Stream.Stream<A, E, R>,
320
- ) =>
321
- stream.pipe(
322
- Stream.tap((item) =>
323
- Effect.gen(function* () {
324
- if (item.kind !== "synchronized") return;
325
- const [live] = yield* insert(4);
326
- liveSequence = live!.sequence;
327
- const events = yield* store
328
- .readApplicationEvents({
329
- afterSequence: highWater!.sequence,
330
- throughSequence: liveSequence,
331
- })
332
- .pipe(Stream.runCollect);
333
- yield* store.publishCommitted(events);
334
- }),
335
- ),
336
- Stream.takeUntil((item) => item.sequence === liveSequence),
337
- Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })),
338
- Stream.runCollect,
339
- );
340
- const subscription = Effect.gen(function* () {
341
- return scope === "thread"
342
- ? yield* subscribeOrchestrationV2Thread({
343
- threadId,
344
- afterSequence: before!.sequence,
345
- requestCompletionMarker: true,
346
- }).pipe(Effect.flatMap(consume))
347
- : yield* subscribeOrchestrationV2Shell({
348
- afterSequence: before!.sequence,
349
- requestCompletionMarker: true,
350
- }).pipe(Effect.flatMap(consume));
351
- });
352
- const items = yield* subscription.pipe(
353
- Effect.provideService(ThreadManagement.ThreadManagementService, {
354
- ensureLegacyTranscript: () => Effect.void,
355
- getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"),
356
- listActiveSubagentThreadIds: () => Effect.succeed([]),
357
- streamStoredEventsFrom: (
358
- input: Parameters<
359
- ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]
360
- >[0],
361
- ) => {
362
- assert.equal(input?.afterSequence, highWater!.sequence);
363
- return store
364
- .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 })
365
- .pipe(
366
- Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event),
367
- );
368
- },
369
- } as unknown as ThreadManagement.ThreadManagementService["Service"]),
370
- Effect.provideService(ProjectStore.ProjectStoreV2, {
371
- listShells: () => Effect.succeed([]),
372
- } as unknown as ProjectStore.ProjectStoreV2["Service"]),
373
- Effect.provideService(ProjectService.ProjectService, {
374
- getShell: () => Effect.succeedSome(project),
375
- } as unknown as ProjectService.ProjectService["Service"]),
376
- Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
377
- subscribeChanges: PubSub.subscribe(updates),
378
- } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
379
- );
380
- assert.deepEqual(
381
- items.map((item) => item.kind),
382
- scope === "thread"
383
- ? ["event", "synchronized", "event"]
384
- : ["project.updated", "synchronized", "project.updated"],
385
- );
386
- assert.deepEqual(
387
- items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])),
388
- [after!.sequence, liveSequence],
310
+ const [before] = yield* insert(0);
311
+ yield* insert(1, true);
312
+ const [after] = yield* insert(2);
313
+ const [highWater] = yield* insert(3, true);
314
+ const updates = yield* PubSub.unbounded();
315
+ let liveSequence = 0;
316
+ const consume = <A extends { readonly kind: string; readonly sequence?: number }, E, R>(
317
+ stream: Stream.Stream<A, E, R>,
318
+ ) =>
319
+ stream.pipe(
320
+ Stream.tap((item) =>
321
+ Effect.gen(function* () {
322
+ if (item.kind !== "synchronized") return;
323
+ const [live] = yield* insert(4);
324
+ liveSequence = live!.sequence;
325
+ const events = yield* store
326
+ .readApplicationEvents({
327
+ afterSequence: highWater!.sequence,
328
+ throughSequence: liveSequence,
329
+ })
330
+ .pipe(Stream.runCollect);
331
+ yield* store.publishCommitted(events);
332
+ }),
333
+ ),
334
+ Stream.takeUntil((item) => item.sequence === liveSequence),
335
+ Stream.map((item) => ({ kind: item.kind as string, sequence: item.sequence })),
336
+ Stream.runCollect,
337
);
390
- }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),
338
+ const subscription = Effect.gen(function* () {
339
+ return scope === "thread"
340
+ ? yield* subscribeOrchestrationV2Thread({
341
+ threadId,
342
+ afterSequence: before!.sequence,
343
+ requestCompletionMarker: true,
344
+ }).pipe(Effect.flatMap(consume))
345
+ : yield* subscribeOrchestrationV2Shell({
346
+ afterSequence: before!.sequence,
347
+ requestCompletionMarker: true,
348
+ }).pipe(Effect.flatMap(consume));
349
+ });
350
+ const items = yield* subscription.pipe(
351
+ Effect.provideService(ThreadManagement.ThreadManagementService, {
352
+ ensureLegacyTranscript: () => Effect.void,
353
+ getShellSnapshot: () => Effect.die("shell resume must not load a full snapshot"),
354
+ listActiveSubagentThreadIds: () => Effect.succeed([]),
355
+ streamStoredEventsFrom: (
356
+ input: Parameters<
357
+ ThreadManagement.ThreadManagementService["Service"]["streamStoredEventsFrom"]
358
+ >[0],
359
+ ) => {
360
+ assert.equal(input?.afterSequence, highWater!.sequence);
361
+ return store
362
+ .streamApplicationEvents({ afterSequence: input?.afterSequence ?? 0 })
363
+ .pipe(Stream.filter((event): event is OrchestrationV2StoredEvent => "event" in event));
364
+ },
365
+ } as unknown as ThreadManagement.ThreadManagementService["Service"]),
366
+ Effect.provideService(ProjectStore.ProjectStoreV2, {
367
+ listShells: () => Effect.succeed([]),
368
+ } as unknown as ProjectStore.ProjectStoreV2["Service"]),
369
+ Effect.provideService(ProjectService.ProjectService, {
370
+ getShell: () => Effect.succeedSome(project),
371
+ } as unknown as ProjectService.ProjectService["Service"]),
372
+ Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, {
373
+ subscribeChanges: PubSub.subscribe(updates),
374
+ } as ProjectEnrichment.ProjectEnrichmentService["Service"]),
375
+ );
376
+ assert.deepEqual(
377
+ items.map((item) => item.kind),
378
+ scope === "thread"
379
+ ? ["event", "synchronized", "event"]
380
+ : ["project.updated", "synchronized", "project.updated"],
381
+ );
382
+ assert.deepEqual(
383
+ items.flatMap((item) => (item.sequence === undefined ? [] : [item.sequence])),
384
+ [after!.sequence, liveSequence],
385
+ );
386
+ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer));
387
+
388
+it.effect("thread resume skips unknown types, synchronizes, and receives the live tail", () =>
389
+ resumeSkipsUnknownTypes("thread"),
390
+);
391
+
392
+// Shell updates batch through `Stream.groupedWithin`, whose window needs real time to close.
393
+it.live("shell resume skips unknown types, synchronizes, and receives the live tail", () =>
394
+ resumeSkipsUnknownTypes("shell"),
395
);
396
397
it.effect("coalesces streaming replay before synchronization and the live tail", () =>
packages/client-runtime/src/state/pullRequests.test.ts
+171
-170
@@ -15,6 +15,7 @@ import { expect, it } from "@effect/vitest";
15
import * as Schema from "effect/Schema";
16
import * as Deferred from "effect/Deferred";
17
import * as Fiber from "effect/Fiber";
18
+import * as TestClock from "effect/testing/TestClock";
19
import * as Effect from "effect/Effect";
20
import * as Latch from "effect/Latch";
21
import * as Layer from "effect/Layer";
@@ -57,7 +58,7 @@ const trustedRouting = {
58
59
class MutationRefused extends Schema.TaggedError<MutationRefused>()("MutationRefused", {}) {}
60
60
-for (const scenario of [
61
+it.effect.each([
62
"prefers the local environment with the same github account",
63
"falls back before mutation when the local account differs",
64
"never retries an ambiguous mutation failure",
@@ -71,176 +72,176 @@ for (const scenario of [
72
"keeps mutations on the origin when the alternate is disabled",
73
"does not dispatch after the alternate is disabled during the probe",
74
"preserves a local source account rejection when alternate accounts differ",
74
-] as const) {
75
- (scenario === "returns a successful mutation when source invalidation stalls"
76
- ? it.live
77
- : it.effect)(scenario, () =>
78
- Effect.scoped(
79
- Effect.gen(function* () {
80
- const calls: string[] = [];
81
- const inputs: unknown[] = [];
82
- let trusted = true;
83
- let disableAlternate = Effect.void;
84
- const switchedAccount =
85
- scenario === "preserves a local source account rejection when alternate accounts differ";
86
- const mismatch =
87
- scenario === "falls back before mutation when the local account differs" ||
88
- switchedAccount;
89
- const ambiguous = scenario === "never retries an ambiguous mutation failure";
90
- const reading =
91
- scenario === "returns a fast local source read without checking alternate identities";
92
- const single = scenario === "keeps single-environment requests free of identity lookups";
93
- const localOrigin =
94
- scenario === "keeps a local origin ahead of another local environment" ||
95
- switchedAccount ||
96
- reading;
97
- const oldOrigin =
98
- scenario === "keeps mutations on an old origin server without retrying them";
99
- const oldAlternate =
100
- scenario === "skips an old alternate server before dispatching a mutation";
101
- const failure = new PullRequestOperationError({
102
- operation: switchedAccount ? "routeIdentity" : "runAction",
103
- detail: "connection lost after dispatch",
104
- });
105
- const clientFor = (local: boolean) => {
106
- const name = local ? "local" : "origin";
107
- return {
108
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
109
- input: unknown,
110
- ) =>
111
- Effect.gen(function* () {
112
- if (local) expect(input).toEqual({ host: "github.com" });
113
- calls.push(`${name}:identity`);
114
- if (
115
- local &&
116
- scenario === "does not dispatch after the alternate is disabled during the probe"
117
- )
118
- yield* disableAlternate;
119
- if (
120
- local &&
121
- scenario ===
122
- "does not dispatch after routing permission is revoked during the probe"
123
- )
124
- trusted = false;
125
- if ((!local && oldOrigin) || (local && oldAlternate)) {
126
- return yield* Effect.die(
127
- `Unknown request tag: ${WS_METHODS.pullRequestsRouting}`,
128
- );
129
- }
130
- return {
131
- host: "github.com",
132
- provider: "github",
133
- viewer: "maria-rcks",
134
- accountId: local && mismatch ? "456" : "123",
135
- };
136
- }),
137
- [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
138
- Effect.gen(function* () {
139
- calls.push(`${name}:mutation`);
140
- inputs.push(input);
141
- if (
142
- !local &&
143
- switchedAccount &&
144
- (input as { expectedAccountId?: string }).expectedAccountId === "123"
145
- )
146
- return yield* failure;
147
- if (local && ambiguous) return yield* failure;
148
- }),
149
- [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
150
- Effect.gen(function* () {
151
- calls.push(`${name}:read`);
152
- expect(input.allowStale).toBe(false);
153
- if (local) return yield* failure;
154
- return null;
155
- }),
156
- [WS_METHODS.pullRequestsInvalidate]: () =>
157
- Effect.gen(function* () {
158
- calls.push(`${name}:invalidate`);
159
- if (
160
- !local &&
161
- scenario === "returns a successful mutation when source invalidation stalls"
162
- ) {
163
- return yield* Effect.never;
164
- }
165
- }),
166
- } as unknown as WsRpcProtocolClient;
167
- };
168
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
169
- clientFor(false),
170
- single ? undefined : clientFor(true),
171
- localOrigin,
172
- );
173
- disableAlternate = SubscriptionRef.update(
174
- environmentRegistry.entries,
175
- (entries) =>
176
- new Map(
177
- [...entries].map(([id, entry]) => [
178
- id,
179
- id === TARGET.environmentId ? entry : { ...entry, enabled: false },
180
- ]),
181
- ),
182
- );
183
- const disabled =
184
- scenario === "keeps mutations on the origin when the alternate is disabled";
185
- const disabledDuringProbe =
186
- scenario === "does not dispatch after the alternate is disabled during the probe";
187
- if (disabled) yield* disableAlternate;
188
- const input = {
189
- projectId: ProjectId.make("project-1"),
190
- host: "github.com",
191
- repository: "acme/web",
192
- number: 7,
193
- action: "merge" as const,
194
- };
195
- const route = createPullRequestRouter();
196
- const result = yield* (
197
- reading
198
- ? route(WS_METHODS.pullRequestsSummary, input)
199
- : route(WS_METHODS.pullRequestsRunAction, input)
200
- ).pipe(
201
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
202
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
203
- Effect.provideService(PullRequestRoutingPermissions, {
204
- ...trustedRouting,
205
- get: () => Effect.succeed(trusted ? "read-write" : "off"),
206
- }),
207
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
208
- Effect.result,
209
- );
210
-
211
- if (switchedAccount) {
212
- expect(result).toMatchObject({ _tag: "Failure", failure });
75
+] as const)("%s", (scenario) =>
76
+ Effect.scoped(
77
+ Effect.gen(function* () {
78
+ const stalls = scenario === "returns a successful mutation when source invalidation stalls";
79
+ const invalidationStalled = yield* Deferred.make<void>();
80
+ const calls: string[] = [];
81
+ const inputs: unknown[] = [];
82
+ let trusted = true;
83
+ let disableAlternate = Effect.void;
84
+ const switchedAccount =
85
+ scenario === "preserves a local source account rejection when alternate accounts differ";
86
+ const mismatch =
87
+ scenario === "falls back before mutation when the local account differs" || switchedAccount;
88
+ const ambiguous = scenario === "never retries an ambiguous mutation failure";
89
+ const reading =
90
+ scenario === "returns a fast local source read without checking alternate identities";
91
+ const single = scenario === "keeps single-environment requests free of identity lookups";
92
+ const localOrigin =
93
+ scenario === "keeps a local origin ahead of another local environment" ||
94
+ switchedAccount ||
95
+ reading;
96
+ const oldOrigin =
97
+ scenario === "keeps mutations on an old origin server without retrying them";
98
+ const oldAlternate =
99
+ scenario === "skips an old alternate server before dispatching a mutation";
100
+ const failure = new PullRequestOperationError({
101
+ operation: switchedAccount ? "routeIdentity" : "runAction",
102
+ detail: "connection lost after dispatch",
103
+ });
104
+ const clientFor = (local: boolean) => {
105
+ const name = local ? "local" : "origin";
106
+ return {
107
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
108
+ input: unknown,
109
+ ) =>
110
+ Effect.gen(function* () {
111
+ if (local) expect(input).toEqual({ host: "github.com" });
112
+ calls.push(`${name}:identity`);
113
+ if (
114
+ local &&
115
+ scenario === "does not dispatch after the alternate is disabled during the probe"
116
+ )
117
+ yield* disableAlternate;
118
+ if (
119
+ local &&
120
+ scenario ===
121
+ "does not dispatch after routing permission is revoked during the probe"
122
+ )
123
+ trusted = false;
124
+ if ((!local && oldOrigin) || (local && oldAlternate)) {
125
+ return yield* Effect.die(`Unknown request tag: ${WS_METHODS.pullRequestsRouting}`);
126
+ }
127
+ return {
128
+ host: "github.com",
129
+ provider: "github",
130
+ viewer: "maria-rcks",
131
+ accountId: local && mismatch ? "456" : "123",
132
+ };
133
+ }),
134
+ [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
135
+ Effect.gen(function* () {
136
+ calls.push(`${name}:mutation`);
137
+ inputs.push(input);
138
+ if (
139
+ !local &&
140
+ switchedAccount &&
141
+ (input as { expectedAccountId?: string }).expectedAccountId === "123"
142
+ )
143
+ return yield* failure;
144
+ if (local && ambiguous) return yield* failure;
145
+ }),
146
+ [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
147
+ Effect.gen(function* () {
148
+ calls.push(`${name}:read`);
149
+ expect(input.allowStale).toBe(false);
150
+ if (local) return yield* failure;
151
+ return null;
152
+ }),
153
+ [WS_METHODS.pullRequestsInvalidate]: () =>
154
+ Effect.gen(function* () {
155
+ calls.push(`${name}:invalidate`);
156
+ if (!local && stalls) {
157
+ yield* Deferred.succeed(invalidationStalled, undefined);
158
+ return yield* Effect.never;
159
+ }
160
+ }),
161
+ } as unknown as WsRpcProtocolClient;
162
+ };
163
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
164
+ clientFor(false),
165
+ single ? undefined : clientFor(true),
166
+ localOrigin,
167
+ );
168
+ disableAlternate = SubscriptionRef.update(
169
+ environmentRegistry.entries,
170
+ (entries) =>
171
+ new Map(
172
+ [...entries].map(([id, entry]) => [
173
+ id,
174
+ id === TARGET.environmentId ? entry : { ...entry, enabled: false },
175
+ ]),
176
+ ),
177
+ );
178
+ const disabled = scenario === "keeps mutations on the origin when the alternate is disabled";
179
+ const disabledDuringProbe =
180
+ scenario === "does not dispatch after the alternate is disabled during the probe";
181
+ if (disabled) yield* disableAlternate;
182
+ const input = {
183
+ projectId: ProjectId.make("project-1"),
184
+ host: "github.com",
185
+ repository: "acme/web",
186
+ number: 7,
187
+ action: "merge" as const,
188
+ };
189
+ const route = createPullRequestRouter();
190
+ const routed = (
191
+ reading
192
+ ? route(WS_METHODS.pullRequestsSummary, input)
193
+ : route(WS_METHODS.pullRequestsRunAction, input)
194
+ ).pipe(
195
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
196
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
197
+ Effect.provideService(PullRequestRoutingPermissions, {
198
+ ...trustedRouting,
199
+ get: () => Effect.succeed(trusted ? "read-write" : "off"),
200
+ }),
201
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
202
+ Effect.result,
203
+ );
204
+ const result = stalls
205
+ ? yield* Effect.gen(function* () {
206
+ const fiber = yield* Effect.forkChild(routed);
207
+ yield* Deferred.await(invalidationStalled);
208
+ yield* TestClock.adjust("1 second");
209
+ return yield* Fiber.join(fiber);
210
+ })
211
+ : yield* routed;
212
+
213
+ if (switchedAccount) {
214
+ expect(result).toMatchObject({ _tag: "Failure", failure });
215
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
216
+ expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
217
+ } else if (ambiguous) {
218
+ expect(result).toMatchObject({ _tag: "Failure", failure });
219
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
220
+ } else {
221
+ expect(result._tag).toBe("Success");
222
+ if (single || disabled) {
223
+ expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual([
224
+ "origin:mutation",
225
+ ]);
226
+ } else if (reading) expect(calls).toEqual(["origin:read"]);
227
+ else if (
228
+ mismatch ||
229
+ localOrigin ||
230
+ oldOrigin ||
231
+ oldAlternate ||
232
+ !trusted ||
233
+ disabledDuringProbe
234
+ )
235
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
214
- expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
215
- } else if (ambiguous) {
216
- expect(result).toMatchObject({ _tag: "Failure", failure });
236
+ else {
237
expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
218
- } else {
219
- expect(result._tag).toBe("Success");
220
- if (single || disabled) {
221
- expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual([
222
- "origin:mutation",
223
- ]);
224
- } else if (reading) expect(calls).toEqual(["origin:read"]);
225
- else if (
226
- mismatch ||
227
- localOrigin ||
228
- oldOrigin ||
229
- oldAlternate ||
230
- !trusted ||
231
- disabledDuringProbe
232
- )
233
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
234
- else {
235
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
236
- expect(calls).toContain("origin:invalidate");
237
- expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
238
- }
238
+ expect(calls).toContain("origin:invalidate");
239
+ expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
240
}
240
- }),
241
- ),
242
- );
243
-}
241
+ }
242
+ }),
243
+ ),
244
+);
245
246
it.effect.each([
247
{ probe: "origin", cancelled: "first" },
@@ -824,7 +825,7 @@ it.effect.each(
825
),
826
);
827
827
-it.live.each([undefined, true, false])(
828
+it.effect.each([undefined, true, false])(
829
"keeps source workspace metadata and reports draft %s when an alternate answers a detail read",
830
(isDraft) =>
831
Effect.scoped(
@@ -888,7 +889,7 @@ it.live.each([undefined, true, false])(
889
),
890
);
891
891
-it.live(
892
+it.effect(
893
"refreshes identity before writes and invalidates prior readers across router instances",
894
() =>
895
Effect.scoped(
packages/shared/src/DrainableWorker.test.ts
+1
-1
@@ -80,7 +80,7 @@ describe("makeDrainableWorker", () => {
80
}).pipe(Effect.provide(loggerLayer));
81
});
82
83
- it.live("waits for work enqueued during active processing before draining", () =>
83
+ it.effect("waits for work enqueued during active processing before draining", () =>
84
Effect.scoped(
85
Effect.gen(function* () {
86
const processed: string[] = [];
packages/shared/src/KeyedCoalescingWorker.test.ts
+4
-4
@@ -6,7 +6,7 @@ import * as Effect from "effect/Effect";
6
import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker.ts";
7
8
describe("makeKeyedCoalescingWorker", () => {
9
- it.live("lets a queued key drain before a continuously updated key finishes", () =>
9
+ it.effect("lets a queued key drain before a continuously updated key finishes", () =>
10
Effect.scoped(
11
Effect.gen(function* () {
12
const processed: string[] = [];
@@ -40,7 +40,7 @@ describe("makeKeyedCoalescingWorker", () => {
40
),
41
);
42
43
- it.live("merges updates while waiting behind another key and drains the merged batch", () =>
43
+ it.effect("merges updates while waiting behind another key and drains the merged batch", () =>
44
Effect.scoped(
45
Effect.gen(function* () {
46
const processed: string[] = [];
@@ -98,7 +98,7 @@ describe("makeKeyedCoalescingWorker", () => {
98
),
99
);
100
101
- it.live("waits for latest work enqueued during active processing before draining the key", () =>
101
+ it.effect("waits for latest work enqueued during active processing before draining the key", () =>
102
Effect.scoped(
103
Effect.gen(function* () {
104
const processed: string[] = [];
@@ -149,7 +149,7 @@ describe("makeKeyedCoalescingWorker", () => {
149
),
150
);
151
152
- it.live("requeues pending work for a key after a processor failure and keeps draining", () =>
152
+ it.effect("requeues pending work for a key after a processor failure and keeps draining", () =>
153
Effect.scoped(
154
Effect.gen(function* () {
155
const processed: string[] = [];