Skip to content
TypeScript

chore(lint): forbid declaring tests inside for loops (#14921)

Julius Marmingefd7ee2c30a7e
diff --git a/apps/desktop/scripts/browser-secret-native.test.mjs b/apps/desktop/scripts/browser-secret-native.test.mjs
index 754a91f1342..bba047636ba 100644
--- a/apps/desktop/scripts/browser-secret-native.test.mjs
+++ b/apps/desktop/scripts/browser-secret-native.test.mjs
@@ -78,7 +78,7 @@ describe.skipIf(hostPlatform !== "linux")("bundled libsecret helper", () => {
expect(result.stderr.length).toBe(0);
});
- for (const [scenario, code] of [
+ it.each([
["missing", 2],
["empty", 2],
["locked", 3],
@@ -86,13 +86,11 @@ describe.skipIf(hostPlatform !== "linux")("bundled libsecret helper", () => {
["denied", 3],
["unavailable", 4],
["unloaded", 4],
- ]) {
- it(`reports ${scenario} without emitting a secret`, () => {
- const result = run([scenario]);
- expect(result.status).toBe(code);
- expect(result.stdout.length).toBe(0);
- });
- }
+ ])("reports %s without emitting a secret", (scenario, code) => {
+ const result = run([scenario]);
+ expect(result.status).toBe(code);
+ expect(result.stdout.length).toBe(0);
+ });
it("rejects invalid arguments before accessing the keyring", () => {
for (const args of [[], [""], ["chrome", "extra"]]) {
const result = run(args);
diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts
index 339675bd65a..b629301b169 100644
--- a/apps/desktop/src/app/DesktopClerk.test.ts
+++ b/apps/desktop/src/app/DesktopClerk.test.ts
@@ -303,8 +303,9 @@ it.effect(
},
);
-for (const entry of ["startup", "open-url"] as const) {
- it.effect(`receives hosted web sign-in through the desktop ${entry} handler`, () =>
+it.effect.each(["startup", "open-url"] as const)(
+ "receives hosted web sign-in through the desktop %s handler",
+ (entry) =>
Effect.gen(function* () {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
@@ -382,5 +383,4 @@ for (const entry of ["startup", "open-url"] as const) {
),
);
}).pipe(Effect.scoped),
- );
-}
+);
diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts
index 33c74f5a8b9..9e24f9db3e0 100644
--- a/apps/desktop/src/app/DesktopLifecycle.test.ts
+++ b/apps/desktop/src/app/DesktopLifecycle.test.ts
@@ -101,8 +101,9 @@ function makeDesktopWindowLayer(
}
describe("DesktopLifecycle", () => {
- for (const platform of ["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>) {
- it.effect(`lets the updater's quit event proceed on ${platform}`, () => {
+ it.effect.each(["darwin", "win32", "linux"] satisfies ReadonlyArray<NodeJS.Platform>)(
+ "lets the updater's quit event proceed on %s",
+ (platform) => {
const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
let windowsDestroyed = false;
const environmentLayer = Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
@@ -152,8 +153,8 @@ describe("DesktopLifecycle", () => {
assert.isTrue(yield* Ref.get(state.quitting));
}),
).pipe(Effect.provide(layer));
- });
- }
+ },
+ );
it.effect("destroys windows before waiting for backend shutdown", () =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
index 7e859aaf981..a2d4483e6d2 100644
--- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
+++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts
@@ -81,54 +81,52 @@ describe("DesktopPreReadyPlatform", () => {
);
});
- for (const previousEntry of [undefined, 'Exec="/Applications/deleted-previous.AppImage" %U']) {
- it.effect(
- `prepares a ${previousEntry ? "stale" : "missing"} Linux desktop entry before startup yields`,
- () => {
- vi.stubEnv("VITE_DEV_SERVER_URL", "");
- vi.stubEnv("XDG_DATA_HOME", "/xdg");
- vi.stubEnv("APPIMAGE", "/Applications/current.AppImage");
- getSwitchValueMock.mockReturnValue("");
- let desktopName = "t3code.desktop";
- let desktopEntry = previousEntry;
- let iconInstalled = false;
- copyFileSyncMock.mockImplementation((_source: string, destination: string) => {
- iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png";
- });
- setDesktopNameMock.mockImplementation((name: string) => {
- desktopName = name;
- });
- writeFileSyncMock.mockImplementation((path: string, contents: string) => {
- if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents;
- });
+ it.effect.each([
+ { previousEntry: undefined, label: "missing" },
+ { previousEntry: 'Exec="/Applications/deleted-previous.AppImage" %U', label: "stale" },
+ ])("prepares a $label Linux desktop entry before startup yields", ({ previousEntry }) => {
+ vi.stubEnv("VITE_DEV_SERVER_URL", "");
+ vi.stubEnv("XDG_DATA_HOME", "/xdg");
+ vi.stubEnv("APPIMAGE", "/Applications/current.AppImage");
+ getSwitchValueMock.mockReturnValue("");
+ let desktopName = "t3code.desktop";
+ let desktopEntry = previousEntry;
+ let iconInstalled = false;
+ copyFileSyncMock.mockImplementation((_source: string, destination: string) => {
+ iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png";
+ });
+ setDesktopNameMock.mockImplementation((name: string) => {
+ desktopName = name;
+ });
+ writeFileSyncMock.mockImplementation((path: string, contents: string) => {
+ if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents;
+ });
- return Effect.scoped(
- Effect.gen(function* () {
- const portalIdentity = Promise.resolve().then(() => ({
- desktopName,
- desktopEntry,
- iconInstalled,
- }));
- yield* Layer.build(
- DesktopPreReadyPlatform.layer.pipe(
- Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
- ),
- );
- const identity = yield* Effect.promise(() => portalIdentity);
- assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop");
- assert.include(identity.desktopEntry ?? "", 'Exec="/Applications/current.AppImage" %U');
- assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Alpha)");
- assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;");
- assert.include(
- identity.desktopEntry ?? "",
- "Icon=/xdg/icons/com.t3tools.T3Code.desktop.png",
- );
- assert.isTrue(identity.iconInstalled);
- }),
- ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
- },
- );
- }
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const portalIdentity = Promise.resolve().then(() => ({
+ desktopName,
+ desktopEntry,
+ iconInstalled,
+ }));
+ yield* Layer.build(
+ DesktopPreReadyPlatform.layer.pipe(
+ Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
+ ),
+ );
+ const identity = yield* Effect.promise(() => portalIdentity);
+ assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop");
+ assert.include(identity.desktopEntry ?? "", 'Exec="/Applications/current.AppImage" %U');
+ assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Alpha)");
+ assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;");
+ assert.include(
+ identity.desktopEntry ?? "",
+ "Icon=/xdg/icons/com.t3tools.T3Code.desktop.png",
+ );
+ assert.isTrue(identity.iconInstalled);
+ }),
+ ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())));
+ });
it.effect("keeps startup available when the early desktop entry cannot be written", () => {
getSwitchValueMock.mockReturnValue("");
diff --git a/apps/desktop/src/app/DesktopUserData.test.ts b/apps/desktop/src/app/DesktopUserData.test.ts
index 374948ec921..41e497463a0 100644
--- a/apps/desktop/src/app/DesktopUserData.test.ts
+++ b/apps/desktop/src/app/DesktopUserData.test.ts
@@ -37,39 +37,37 @@ it.effect("identifies a failed source read and preserves its cause", () => {
);
});
-for (const sourceName of ["t3code", "T3 Code (Alpha)"]) {
- it.effect(
- `preserves Windows credential keys from ${sourceName} without copying browser databases`,
- () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-profile-" });
- const source = path.join(directory, sourceName);
- const destination = path.join(directory, "t3code-v2");
- const state = '{"os_crypt":{"encrypted_key":"test-encrypted-key"}}';
- yield* fs.makeDirectory(path.join(directory, "T3 Code (Alpha)"), { recursive: true });
- yield* fs.makeDirectory(path.join(source, "IndexedDB"), { recursive: true });
- yield* fs.writeFileString(path.join(source, "Local State"), state);
- yield* fs.writeFileString(path.join(source, "IndexedDB", "LOCK"), "V1 owns this database");
- yield* resolveUserDataPath({
- appDataDirectory: directory,
- isDevelopment: false,
- platform: "win32",
- });
- assert.equal(yield* fs.readFileString(path.join(destination, "Local State")), state);
- assert.equal(yield* fs.readFileString(path.join(source, "Local State")), state);
- assert.isFalse(yield* fs.exists(path.join(destination, "IndexedDB")));
- yield* fs.writeFileString(path.join(destination, "Local State"), "existing V2 state");
- yield* resolveUserDataPath({
- appDataDirectory: directory,
- isDevelopment: false,
- platform: "win32",
- });
- assert.equal(
- yield* fs.readFileString(path.join(destination, "Local State")),
- "existing V2 state",
- );
- }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
-}
+it.effect.each(["t3code", "T3 Code (Alpha)"])(
+ "preserves Windows credential keys from %s without copying browser databases",
+ (sourceName) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-profile-" });
+ const source = path.join(directory, sourceName);
+ const destination = path.join(directory, "t3code-v2");
+ const state = '{"os_crypt":{"encrypted_key":"test-encrypted-key"}}';
+ yield* fs.makeDirectory(path.join(directory, "T3 Code (Alpha)"), { recursive: true });
+ yield* fs.makeDirectory(path.join(source, "IndexedDB"), { recursive: true });
+ yield* fs.writeFileString(path.join(source, "Local State"), state);
+ yield* fs.writeFileString(path.join(source, "IndexedDB", "LOCK"), "V1 owns this database");
+ yield* resolveUserDataPath({
+ appDataDirectory: directory,
+ isDevelopment: false,
+ platform: "win32",
+ });
+ assert.equal(yield* fs.readFileString(path.join(destination, "Local State")), state);
+ assert.equal(yield* fs.readFileString(path.join(source, "Local State")), state);
+ assert.isFalse(yield* fs.exists(path.join(destination, "IndexedDB")));
+ yield* fs.writeFileString(path.join(destination, "Local State"), "existing V2 state");
+ yield* resolveUserDataPath({
+ appDataDirectory: directory,
+ isDevelopment: false,
+ platform: "win32",
+ });
+ assert.equal(
+ yield* fs.readFileString(path.join(destination, "Local State")),
+ "existing V2 state",
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
diff --git a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts
index 84e7678cce4..17f9ff9b986 100644
--- a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts
@@ -386,45 +386,43 @@ describe("parseFirefoxProfiles", () => {
}),
);
- for (const [platform, root] of [
- ["Linux", "/home/user/.mozilla/firefox"],
- ["macOS", "/Users/user/Library/Application Support/Firefox"],
- ] as const) {
- it.effect(`validates relative and absolute ${platform} profile paths`, () =>
- Effect.gen(function* () {
- const parsed = yield* parsePosixFirefoxProfiles(
- [
- "[Profile0]",
- "Name=Relative",
- "IsRelative=1",
- "Path=Profiles/relative.default",
- "[Profile1]",
- "Name=Custom",
- "IsRelative=0",
- "Path=/mnt/custom/firefox-profile",
- "[Profile2]",
- "IsRelative=1",
- "Path=../../escape",
- "[Profile3]",
- "IsRelative=1",
- "Path=/absolute-marked-relative",
- "[Profile4]",
- "IsRelative=0",
- "Path=relative-marked-absolute",
- "[Profile5]",
- "IsRelative=1",
- "Path=Profiles/nul\u0000escape",
- ].join("\n"),
- root,
- );
+ it.effect.each([
+ { platform: "Linux", root: "/home/user/.mozilla/firefox" },
+ { platform: "macOS", root: "/Users/user/Library/Application Support/Firefox" },
+ ])("validates relative and absolute $platform profile paths", ({ root }) =>
+ Effect.gen(function* () {
+ const parsed = yield* parsePosixFirefoxProfiles(
+ [
+ "[Profile0]",
+ "Name=Relative",
+ "IsRelative=1",
+ "Path=Profiles/relative.default",
+ "[Profile1]",
+ "Name=Custom",
+ "IsRelative=0",
+ "Path=/mnt/custom/firefox-profile",
+ "[Profile2]",
+ "IsRelative=1",
+ "Path=../../escape",
+ "[Profile3]",
+ "IsRelative=1",
+ "Path=/absolute-marked-relative",
+ "[Profile4]",
+ "IsRelative=0",
+ "Path=relative-marked-absolute",
+ "[Profile5]",
+ "IsRelative=1",
+ "Path=Profiles/nul\u0000escape",
+ ].join("\n"),
+ root,
+ );
- expect(parsed).toEqual([
- { directory: "Profiles/relative.default", name: "Relative" },
- { directory: "/mnt/custom/firefox-profile", name: "Custom" },
- ]);
- }),
- );
- }
+ expect(parsed).toEqual([
+ { directory: "Profiles/relative.default", name: "Relative" },
+ { directory: "/mnt/custom/firefox-profile", name: "Custom" },
+ ]);
+ }),
+ );
it.effect("uses Windows path rules for relative and absolute profiles", () =>
Effect.gen(function* () {
diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts
index a867f78497b..df27c4f96f1 100644
--- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts
+++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts
@@ -763,8 +763,9 @@ describe("listSourceProfiles Firefox fallback", () => {
{ platform: "win32" as const, profileDirectory: NodePath.join("Profiles", "windows.default") },
];
- for (const { platform, profileDirectory } of cases) {
- it.effect(`scans the ${platform} profile location and excludes stale entries`, () =>
+ it.effect.each(cases)(
+ "scans the $platform profile location and excludes stale entries",
+ ({ platform, profileDirectory }) =>
run(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -800,8 +801,7 @@ describe("listSourceProfiles Firefox fallback", () => {
]);
}),
),
- );
- }
+ );
it.effect("scans for profiles when profiles.ini declares only ones without cookies", () =>
run(
@@ -1166,8 +1166,9 @@ describe("Safari profiles", () => {
),
);
- for (const metadataState of ["missing", "corrupt"] as const) {
- it.effect(`recovers separate cookie stores when metadata is ${metadataState}`, () =>
+ it.effect.each(["missing", "corrupt"] as const)(
+ "recovers separate cookie stores when metadata is %s",
+ (metadataState) =>
run(
Effect.gen(function* () {
const { context, store, metadata } = yield* fixture();
@@ -1181,8 +1182,7 @@ describe("Safari profiles", () => {
assert.isTrue(yield* isSourceInstalled(safari, context));
}),
),
- );
- }
+ );
it.effect("keeps Safari without profiles available", () =>
run(
diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts
index e77d0834464..94fe587136e 100644
--- a/apps/desktop/src/settings/DesktopClientSettings.test.ts
+++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts
@@ -149,58 +149,56 @@ describe("DesktopClientSettings", () => {
),
);
- for (const failure of [
+ it.effect.each([
{ label: "permission", reason: "PermissionDenied" },
{ label: "I/O", reason: "Unknown" },
- ] as const) {
- it.effect(`preserves saved preferences across ${failure.label} read failures and retries`, () =>
- withClientSettings(
- Effect.gen(function* () {
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
- const fileSystem = yield* FileSystem.FileSystem;
- const settings = yield* DesktopClientSettings.DesktopClientSettings;
- const savedSettings = {
- ...clientSettings,
- onboardingCompletedAt: "2026-09-05T12:00:00.000Z",
- };
- yield* settings.set(savedSettings);
- const savedContents = yield* fileSystem.readFileString(environment.clientSettingsPath);
- const cause = PlatformError.systemError({
- _tag: failure.reason,
- module: "FileSystem",
- method: "readFileString",
- pathOrDescriptor: environment.clientSettingsPath,
- });
- let failRead = true;
- const retryableSettings = yield* DesktopClientSettings.make.pipe(
- Effect.provideService(
- FileSystem.FileSystem,
- FileSystem.FileSystem.of({
- ...fileSystem,
- readFileString: (path) =>
- Effect.suspend(() =>
- failRead ? Effect.fail(cause) : fileSystem.readFileString(path),
- ),
- }),
- ),
- );
+ ] as const)("preserves saved preferences across $label read failures and retries", (failure) =>
+ withClientSettings(
+ Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const settings = yield* DesktopClientSettings.DesktopClientSettings;
+ const savedSettings = {
+ ...clientSettings,
+ onboardingCompletedAt: "2026-09-05T12:00:00.000Z",
+ };
+ yield* settings.set(savedSettings);
+ const savedContents = yield* fileSystem.readFileString(environment.clientSettingsPath);
+ const cause = PlatformError.systemError({
+ _tag: failure.reason,
+ module: "FileSystem",
+ method: "readFileString",
+ pathOrDescriptor: environment.clientSettingsPath,
+ });
+ let failRead = true;
+ const retryableSettings = yield* DesktopClientSettings.make.pipe(
+ Effect.provideService(
+ FileSystem.FileSystem,
+ FileSystem.FileSystem.of({
+ ...fileSystem,
+ readFileString: (path) =>
+ Effect.suspend(() =>
+ failRead ? Effect.fail(cause) : fileSystem.readFileString(path),
+ ),
+ }),
+ ),
+ );
- const error = yield* retryableSettings.get.pipe(Effect.flip);
- assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
- assert.equal(error.operation, "read-file");
- assert.equal(error.path, environment.clientSettingsPath);
- assert.strictEqual(error.cause, cause);
- assert.equal(
- yield* fileSystem.readFileString(environment.clientSettingsPath),
- savedContents,
- );
+ const error = yield* retryableSettings.get.pipe(Effect.flip);
+ assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
+ assert.equal(error.operation, "read-file");
+ assert.equal(error.path, environment.clientSettingsPath);
+ assert.strictEqual(error.cause, cause);
+ assert.equal(
+ yield* fileSystem.readFileString(environment.clientSettingsPath),
+ savedContents,
+ );
- failRead = false;
- assert.deepEqual(yield* retryableSettings.get, Option.some(savedSettings));
- }),
- ),
- );
- }
+ failRead = false;
+ assert.deepEqual(yield* retryableSettings.get, Option.some(savedSettings));
+ }),
+ ),
+ );
it.effect("reports the failed client settings write operation and path", () =>
withClientSettings(
@@ -288,31 +286,29 @@ describe("DesktopClientSettings", () => {
),
);
- for (const document of [
+ it.effect.each([
{ label: "malformed JSON", contents: "{not-json" },
{ label: "invalid direct settings", contents: '{"fontSizeCode":"large"}' },
{ label: "invalid legacy settings", contents: '{"settings":{"fontSizeCode":"large"}}' },
- ]) {
- it.effect(`reports ${document.label} without treating the settings file as absent`, () =>
- withClientSettings(
- Effect.gen(function* () {
- const environment = yield* DesktopEnvironment.DesktopEnvironment;
- const fileSystem = yield* FileSystem.FileSystem;
- const settings = yield* DesktopClientSettings.DesktopClientSettings;
- yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
- yield* fileSystem.writeFileString(environment.clientSettingsPath, document.contents);
+ ])("reports $label without treating the settings file as absent", (document) =>
+ withClientSettings(
+ Effect.gen(function* () {
+ const environment = yield* DesktopEnvironment.DesktopEnvironment;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const settings = yield* DesktopClientSettings.DesktopClientSettings;
+ yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
+ yield* fileSystem.writeFileString(environment.clientSettingsPath, document.contents);
- const error = yield* settings.get.pipe(Effect.flip);
- assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
- assert.equal(error.operation, "decode-document");
- assert.equal(error.path, environment.clientSettingsPath);
- assert.instanceOf(error.cause, Schema.SchemaError);
- assert.equal(
- yield* fileSystem.readFileString(environment.clientSettingsPath),
- document.contents,
- );
- }),
- ),
- );
- }
+ const error = yield* settings.get.pipe(Effect.flip);
+ assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsReadError);
+ assert.equal(error.operation, "decode-document");
+ assert.equal(error.path, environment.clientSettingsPath);
+ assert.instanceOf(error.cause, Schema.SchemaError);
+ assert.equal(
+ yield* fileSystem.readFileString(environment.clientSettingsPath),
+ document.contents,
+ );
+ }),
+ ),
+ );
});
diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts
index 205a72a5526..b5ba16d614c 100644
--- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts
+++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts
@@ -3873,8 +3873,9 @@ it.effect("waits to apply settings while permissions are pending", () => {
).pipe(Effect.provide(layer));
});
-for (const fails of [false, true]) {
- it.effect(`tests macOS capture without publishing it and cleans up, failure=${fails}`, () => {
+it.effect.each([false, true])(
+ "tests macOS capture without publishing it and cleans up, failure=%s",
+ (fails) => {
const active = {
platform: "macos",
id: 42,
@@ -3915,8 +3916,8 @@ for (const fails of [false, true]) {
}),
),
);
- });
-}
+ },
+);
it.effect("rejects macOS test capture on other platforms", () =>
Effect.scoped(
diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
index 994f8852e17..836e529e596 100644
--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
+++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts
@@ -949,59 +949,57 @@ describe("makeRelayDeviceRegistrationRequest", () => {
await new Promise((resolve) => setTimeout(resolve, 0));
expect(widgetMocks.start).toHaveBeenCalledTimes(1);
});
- for (const os of ["ios", "android"] as const) {
- it.effect(
- `does not enable ${os} notifications when a token rotates after permission is revoked`,
- () => {
- vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
- vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
- vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
- type: os,
- data: "initial",
+ it.effect.each(["ios", "android"] as const)(
+ "does not enable %s notifications when a token rotates after permission is revoked",
+ (os) => {
+ vi.spyOn(Platform, "OS", "get").mockReturnValue(os);
+ vi.spyOn(Platform, "Version", "get").mockReturnValue(os === "ios" ? 18 : 36);
+ vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
+ type: os,
+ data: "initial",
+ });
+ const registrations: unknown[] = [];
+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init);
+ if (request.url.endsWith("/v1/client/dpop-token")) {
+ return Response.json({
+ access_token: "dpop",
+ issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
+ token_type: "DPoP",
+ expires_in: 300,
+ scope: "mobile:registration",
+ });
+ }
+ registrations.push(await request.json());
+ return Response.json({ ok: true });
+ });
+ Constants.expoConfig!.extra = { relay: { url: "https://permission-relay.example.test" } };
+ setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
+ return Effect.gen(function* () {
+ yield* runBackgroundOperations();
+ expect(registrations.at(-1)).toMatchObject({
+ preferences: { notificationsEnabled: true },
});
- const registrations: unknown[] = [];
- vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
- const request = new Request(input, init);
- if (request.url.endsWith("/v1/client/dpop-token")) {
- return Response.json({
- access_token: "dpop",
- issued_token_type: "urn:ietf:params:oauth:token-type:access_token",
- token_type: "DPoP",
- expires_in: 300,
- scope: "mobile:registration",
- });
- }
- registrations.push(await request.json());
- return Response.json({ ok: true });
+ vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
+ granted: false,
+ } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
+ const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
+ listener({ type: os, data: "rotated" });
+ yield* runBackgroundOperations();
+ expect(registrations.at(-1)).toMatchObject({
+ preferences: { notificationsEnabled: false },
});
- Constants.expoConfig!.extra = { relay: { url: "https://permission-relay.example.test" } };
- setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk"), "user-a");
- return Effect.gen(function* () {
- yield* runBackgroundOperations();
- expect(registrations.at(-1)).toMatchObject({
- preferences: { notificationsEnabled: true },
- });
- vi.mocked(Notifications.getPermissionsAsync).mockResolvedValueOnce({
- granted: false,
- } as Awaited<ReturnType<typeof Notifications.getPermissionsAsync>>);
- const listener = vi.mocked(Notifications.addPushTokenListener).mock.calls.at(-1)![0];
- listener({ type: os, data: "rotated" });
- yield* runBackgroundOperations();
- expect(registrations.at(-1)).toMatchObject({
- preferences: { notificationsEnabled: false },
- });
- expect(registrations.at(-1)).not.toHaveProperty("pushToken");
- }).pipe(
- Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
- Effect.provide(
- managedRelayClientLayer("https://permission-relay.example.test").pipe(
- Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
- ),
+ expect(registrations.at(-1)).not.toHaveProperty("pushToken");
+ }).pipe(
+ Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch),
+ Effect.provide(
+ managedRelayClientLayer("https://permission-relay.example.test").pipe(
+ Layer.provide(Layer.mergeAll(FetchHttpClient.layer, cryptoLayer)),
),
- );
- },
- );
- }
+ ),
+ );
+ },
+ );
it.effect("preserves relay rejection errors with React Native response headers", () => {
vi.spyOn(Platform, "OS", "get").mockReturnValue("android");
vi.mocked(Notifications.getDevicePushTokenAsync).mockResolvedValue({
diff --git a/apps/server/src/cli/app.test.ts b/apps/server/src/cli/app.test.ts
index fe5feadaf61..e478f66f073 100644
--- a/apps/server/src/cli/app.test.ts
+++ b/apps/server/src/cli/app.test.ts
@@ -256,8 +256,9 @@ describe("t3 app", () => {
),
);
- for (const responseKind of ["failure", "invalid"] as const) {
- it.effect(`never falls back after the default desktop sends a ${responseKind} response`, () =>
+ it.effect.each(["failure", "invalid"] as const)(
+ "never falls back after the default desktop sends a %s response",
+ (responseKind) =>
withTempDirectory("t3-app-response-test-", (root) =>
Effect.gen(function* () {
vi.mocked(NodeOS.homedir).mockReturnValue(root);
@@ -302,6 +303,5 @@ describe("t3 app", () => {
}
}).pipe(Effect.scoped),
),
- );
- }
+ );
});
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts
index 83a9d2f7e15..9a966353325 100644
--- a/apps/server/src/device/DeviceService.test.ts
+++ b/apps/server/src/device/DeviceService.test.ts
@@ -361,29 +361,39 @@ describe("device discovery after server restart", () => {
);
});
-for (const [diagnostic, reason, message] of [
- ["Insufficient disk space at /private/user/path", "disk_space", "not enough free disk space"],
- ["Timed out spawning /private/user/command", "timeout", "did not become ready in time"],
- ["Unexpected failure: secret-token", "launch_failed", "could not start"],
-] as const) {
- it.effect(`normalizes boot failure: ${reason}`, () =>
- Effect.gen(function* () {
- const { service } = yield* fixture(Effect.void, diagnostic);
- yield* service.configure({ enabled: true });
- const error = yield* service
- .open({
- threadId: ThreadId.make("boot-failure"),
- deviceId: "Pixel_API_35",
- platform: "android",
- })
- .pipe(Effect.flip);
- expect(error._tag).toBe("DeviceBootError");
- expect(error.message).toContain(message);
- expect(error.message).not.toContain(diagnostic);
- expect((yield* service.state).bootingDevices).toEqual([]);
- }).pipe(Effect.scoped),
- );
-}
+it.effect.each([
+ {
+ diagnostic: "Insufficient disk space at /private/user/path",
+ reason: "disk_space",
+ message: "not enough free disk space",
+ },
+ {
+ diagnostic: "Timed out spawning /private/user/command",
+ reason: "timeout",
+ message: "did not become ready in time",
+ },
+ {
+ diagnostic: "Unexpected failure: secret-token",
+ reason: "launch_failed",
+ message: "could not start",
+ },
+] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
+ Effect.gen(function* () {
+ const { service } = yield* fixture(Effect.void, diagnostic);
+ yield* service.configure({ enabled: true });
+ const error = yield* service
+ .open({
+ threadId: ThreadId.make("boot-failure"),
+ deviceId: "Pixel_API_35",
+ platform: "android",
+ })
+ .pipe(Effect.flip);
+ expect(error._tag).toBe("DeviceBootError");
+ expect(error.message).toContain(message);
+ expect(error.message).not.toContain(diagnostic);
+ expect((yield* service.state).bootingDevices).toEqual([]);
+ }).pipe(Effect.scoped),
+);
it.effect("keeps shutdown successful when subsequent discovery fails", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 33b91614b4d..14692458676 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -604,8 +604,9 @@ function makeTurnInput(input: {
}
describe("AcpAdapterV2", () => {
- for (const outcome of ["failed", "recovered", "completed", "cancelled"] as const) {
- it.live(`projects Mistral retry notices and their ${outcome} outcome`, () =>
+ it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
+ "projects Mistral retry notices and their %s outcome",
+ (outcome) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const instanceId = ProviderInstanceId.make(`vibe-retry-${outcome}`);
@@ -692,8 +693,7 @@ describe("AcpAdapterV2", () => {
assert.equal(retries.at(-1)?.title, "Provider recovered");
}
}).pipe(Effect.provide(testLayer), Effect.scoped),
- );
- }
+ );
it("preserves legacy ids and scopes v2 ids by provider instance", () => {
const instanceId = ProviderInstanceId.make("acp-identity-test");
@@ -2914,8 +2914,9 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(testLayer)),
);
- for (const model of ["grok-build", "composer-2"]) {
- it.effect(`Grok configures the native session for ${model}`, () =>
+ it.effect.each(["grok-build", "composer-2"])(
+ "Grok configures the native session for %s",
+ (model) =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
@@ -2968,8 +2969,7 @@ describe("AcpAdapterV2", () => {
model === "grok-build" ? 0 : 1,
);
}).pipe(Effect.provide(testLayer), Effect.scoped),
- );
- }
+ );
it.live("Grok reapplies an explicit return to the session's setup-time model", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 6d3d1f9cdd0..95f8753ae68 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -2252,78 +2252,78 @@ describe("ClaudeAdapterV2 background wake turns", () => {
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
);
- for (const terminalReason of ["aborted_tools", "aborted_streaming"] as const) {
- for (const steered of [true, false]) {
- it.effect(`handles ${terminalReason} with active steering=${steered}`, () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
- const attemptId = RunAttemptId.make("attempt-steering-abort");
- const input = makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- attemptId,
- text: "Audit the settings pages.",
+ it.effect.each(
+ (["aborted_tools", "aborted_streaming"] as const).flatMap((terminalReason) =>
+ [true, false].map((steered) => ({ terminalReason, steered })),
+ ),
+ )("handles $terminalReason with active steering=$steered", ({ terminalReason, steered }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const attemptId = RunAttemptId.make("attempt-steering-abort");
+ const input = makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId,
+ text: "Audit the settings pages.",
+ attachments: [],
+ });
+ yield* harness.runtime.startTurn(input);
+ if (steered) {
+ yield* harness.runtime.steerTurn({
+ threadId: harness.threadId,
+ runId: input.runId,
+ providerThread: harness.providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ }),
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make("message-steering-abort"),
+ text: "Include the hierarchy mock.",
attachments: [],
- });
- yield* harness.runtime.startTurn(input);
- if (steered) {
- yield* harness.runtime.steerTurn({
- threadId: harness.threadId,
- runId: input.runId,
- providerThread: harness.providerThread,
- providerTurnId: idAllocator.derive.providerTurn({
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
- nativeTurnId: `turn:${attemptId}`,
- }),
- message: {
- createdBy: "user",
- creationSource: "web",
- messageId: MessageId.make("message-steering-abort"),
- text: "Include the hierarchy mock.",
- attachments: [],
- },
- });
- assert.equal(harness.offeredMessages[1]?.priority, "now");
- }
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000901",
- result: "",
- terminalReason,
- }),
- );
- if (steered) {
- yield* Queue.offer(harness.sdkMessages, wakeAssistant);
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000902",
- result: "Audit finished after the steer.",
- }),
- );
- }
- const terminal = yield* Queue.take(harness.terminalReceipts);
- assert.equal(terminal.status, steered ? "completed" : "interrupted");
- if (steered) {
- assert.isTrue(
- harness.events.some(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "assistant_message" &&
- event.turnItem.text === WAKE_ASSISTANT_TEXT,
- ),
- );
- }
- assert.lengthOf(harness.terminalEvents(), 1);
- }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
- ),
- );
- }
- }
+ },
+ });
+ assert.equal(harness.offeredMessages[1]?.priority, "now");
+ }
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000901",
+ result: "",
+ terminalReason,
+ }),
+ );
+ if (steered) {
+ yield* Queue.offer(harness.sdkMessages, wakeAssistant);
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000902",
+ result: "Audit finished after the steer.",
+ }),
+ );
+ }
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal.status, steered ? "completed" : "interrupted");
+ if (steered) {
+ assert.isTrue(
+ harness.events.some(
+ (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.type === "assistant_message" &&
+ event.turnItem.text === WAKE_ASSISTANT_TEXT,
+ ),
+ );
+ }
+ assert.lengthOf(harness.terminalEvents(), 1);
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
it.effect("announces usage-limit pauses once per window and again on a new turn", () =>
Effect.gen(function* () {
@@ -3187,7 +3187,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
),
);
- for (const terminalReason of [
+ it.effect.each([
"api_error",
"malformed_tool_use_exhausted",
"budget_exhausted",
@@ -3200,56 +3200,54 @@ describe("ClaudeAdapterV2 background wake turns", () => {
"image_error",
"model_error",
"overloaded_status",
- ] as const) {
- it.effect(`fails a success-shaped Claude result with ${terminalReason}`, () =>
- Effect.scoped(
- Effect.gen(function* () {
- const harness = yield* makeWakeHarness;
- const now = yield* DateTime.now;
- yield* harness.runtime.startTurn(
- makeClaudeTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now,
- attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
- text: "Complete the task.",
- attachments: [],
- }),
- );
- yield* Queue.offer(
- harness.sdkMessages,
- makeResultFrame({
- uuid: "00000000-0000-4000-8000-000000000205",
- result: "Provider failure details.",
- isError: false,
- ...(terminalReason === "overloaded_status"
- ? { apiErrorStatus: 529 }
- : { terminalReason }),
- }),
- );
- const terminal = yield* Queue.take(harness.terminalReceipts);
- assert.equal(terminal.status, "failed");
- if (terminal.status !== "failed") return;
- assert.isNotEmpty(terminal.failure.message);
- assert.equal(
- terminal.failure.class,
- terminalReason === "blocking_limit" ? "usage_limit" : "provider_error",
- );
- assert.isFalse(
- harness.events.some(
- (event) =>
- event.type === "message.updated" &&
- event.message.text === "Provider failure details.",
- ),
- );
- assert.equal(
- terminal.failure.code,
- terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
- );
- }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
- ),
- );
- }
+ ] as const)("fails a success-shaped Claude result with %s", (terminalReason) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ const now = yield* DateTime.now;
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now,
+ attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
+ text: "Complete the task.",
+ attachments: [],
+ }),
+ );
+ yield* Queue.offer(
+ harness.sdkMessages,
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000205",
+ result: "Provider failure details.",
+ isError: false,
+ ...(terminalReason === "overloaded_status"
+ ? { apiErrorStatus: 529 }
+ : { terminalReason }),
+ }),
+ );
+ const terminal = yield* Queue.take(harness.terminalReceipts);
+ assert.equal(terminal.status, "failed");
+ if (terminal.status !== "failed") return;
+ assert.isNotEmpty(terminal.failure.message);
+ assert.equal(
+ terminal.failure.class,
+ terminalReason === "blocking_limit" ? "usage_limit" : "provider_error",
+ );
+ assert.isFalse(
+ harness.events.some(
+ (event) =>
+ event.type === "message.updated" &&
+ event.message.text === "Provider failure details.",
+ ),
+ );
+ assert.equal(
+ terminal.failure.code,
+ terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
+ );
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
const providerThreadRosterEvents = (events: ReadonlyArray<ProviderAdapterV2Event>) =>
events.filter(
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index 27fadf2c438..3145e33dabd 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -1728,8 +1728,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {
};
});
- for (const response of ["supported", "unsupported", "invalid"] as const) {
- it.effect(`delivers native history with ${response} app-server protocol`, () =>
+ it.effect.each(["supported", "unsupported", "invalid"] as const)(
+ "delivers native history with %s app-server protocol",
+ (response) =>
Effect.gen(function* () {
const nativeThreadId = `inject-${response}`;
const prompt = "Only the current request";
@@ -1830,8 +1831,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(requests.filter((method) => method === "turn/start").length, 1);
assert.isBelow(requests.indexOf("thread/inject_items"), requests.indexOf("turn/start"));
}).pipe(Effect.scoped, Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
- );
- }
+ );
it.effect("identifies sessions to Codex with the same client info as main", () =>
Effect.gen(function* () {
@@ -2926,8 +2926,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- for (const terminalStatus of ["completed", "interrupted"] as const) {
- it.effect(`retains Codex reasoning parts when the turn is ${terminalStatus}`, () =>
+ it.effect.each(["completed", "interrupted"] as const)(
+ "retains Codex reasoning parts when the turn is %s",
+ (terminalStatus) =>
Effect.scoped(
Effect.gen(function* () {
const scenario = `codex-reasoning-${terminalStatus}`;
@@ -3087,8 +3088,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.deepEqual(assistantMessages(harness.events), []);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
),
- );
- }
+ );
const finalAnswerTranscript = (
scenario: string,
@@ -3714,9 +3714,10 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- for (const terminated of [true, false, "still_running"] as const) {
+ const backgroundStopCases = [true, false, "still_running"] as const;
+ const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => {
const stillRunning = terminated === "still_running";
- const transcript = makeCodexReplayTranscript({
+ return makeCodexReplayTranscript({
scenario: `codex-bg-stop-${terminated}`,
entries: [
...backgroundExecTranscript.entries.slice(0, -1),
@@ -3796,9 +3797,14 @@ describe("CodexAdapterV2 post-settle continuation", () => {
backgroundExecTranscript.entries.at(-1)!,
],
});
+ };
- it.effect(`stops a command after root completion when termination returns ${terminated}`, () =>
- Effect.scoped(
+ it.effect.each(backgroundStopCases)(
+ "stops a command after root completion when termination returns %s",
+ (terminated) => {
+ const stillRunning = terminated === "still_running";
+ const transcript = makeBackgroundStopTranscript(terminated);
+ return Effect.scoped(
Effect.gen(function* () {
const stopped = yield* Deferred.make<void>();
const harness = yield* makeCodexReplayHarness(transcript, (event) =>
@@ -3852,140 +3858,137 @@ describe("CodexAdapterV2 post-settle continuation", () => {
assert.equal(harness.terminalEvents()[0]?.status, "completed");
assert.lengthOf(harness.continuationRequests, 0);
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
- ),
- );
- if (terminated === true) {
- it.effect("interrupts a completed run's background command through orchestration", () =>
- Effect.scoped(
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" });
- const localTranscript = yield* decodeReplayTranscriptJson(
- (yield* encodeReplayTranscriptJson(transcript)).replaceAll(
- yield* encodeStringJson("/workspace"),
- yield* encodeStringJson(cwd),
- ),
- );
- const replayDriver = yield* CodexReplay.makeReplayDriver(localTranscript);
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- assert.equal(
- Number(
- yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd })),
- ),
- 0,
- );
- assert.equal(
- Number(
- yield* spawner.exitCode(
- ChildProcess.make(
- "git",
- [
- "-c",
- "user.name=Test",
- "-c",
- "commit",
- "--allow-empty",
- "--quiet",
- "-m",
- "Initial commit",
- ],
- { cwd },
- ),
- ),
- ),
- 0,
- );
- yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const threadId = ThreadId.make("thread:background-stop");
- yield* orchestrator.dispatch({
- type: "thread.create",
- commandId: CommandId.make("create-background-stop"),
- threadId,
- projectId: ProjectId.make("project:background-stop"),
- title: "Background stop",
- modelSelection: CODEX_TEST_MODEL_SELECTION,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: cwd,
- createdBy: "user",
- creationSource: "web",
- });
- const waiting = yield* orchestrator.streamDomainEvents.pipe(
- Stream.filter(
- (event) => event.type === "run.updated" && event.payload.status === "waiting",
- ),
- Stream.runHead,
- Effect.forkChild({ startImmediately: true }),
- );
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make("start-background-stop"),
- threadId,
- messageId: MessageId.make("message:background-stop"),
- text: BG_PROMPT,
- attachments: [],
- createdBy: "user",
- creationSource: "web",
- dispatchMode: { type: "start_immediately" },
- });
- yield* worker.drain();
- assert.isNull((yield* Ref.get(replayDriver.state)).failure);
- yield* Fiber.join(waiting);
- yield* worker.drain();
- const projection = yield* orchestrator.getThreadProjection(threadId);
- const run = projection.runs.at(-1)!;
- assert.equal(run.status, "completed");
- assert.equal(
- (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length,
- 1,
- );
- const stopped = yield* orchestrator.streamDomainEvents.pipe(
- Stream.filter(
- (event) =>
- event.type === "turn-item.updated" &&
- event.payload.type === "command_execution" &&
- event.payload.status === "interrupted",
- ),
- Stream.runHead,
- Effect.forkChild({ startImmediately: true }),
- );
- yield* orchestrator.dispatch({
- type: "run.interrupt",
- commandId: CommandId.make("stop-background-command"),
- threadId,
- runId: run.id,
- });
- yield* worker.drain();
- yield* Fiber.join(stopped);
- assert.equal(
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
- "completed",
- );
- assert.deepEqual(
- (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks,
- [],
- );
- }).pipe(
- Effect.provide(
- makeOrchestratorV2ReplayLayerWithRegistry(
- { name: "codex-background-stop", runtimePolicyOverride: { cwd } },
- makeCodexProviderAdapterRegistryReplayLayer({
- transcript: localTranscript,
- driver: replayDriver,
- }),
- { runEffectWorker: false },
- ),
- ),
- );
- }).pipe(Effect.provide(NodeServices.layer)),
- ),
);
- }
- }
+ },
+ );
+ it.effect("interrupts a completed run's background command through orchestration", () => {
+ const transcript = makeBackgroundStopTranscript(true);
+ return Effect.scoped(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" });
+ const localTranscript = yield* decodeReplayTranscriptJson(
+ (yield* encodeReplayTranscriptJson(transcript)).replaceAll(
+ yield* encodeStringJson("/workspace"),
+ yield* encodeStringJson(cwd),
+ ),
+ );
+ const replayDriver = yield* CodexReplay.makeReplayDriver(localTranscript);
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ assert.equal(
+ Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))),
+ 0,
+ );
+ assert.equal(
+ Number(
+ yield* spawner.exitCode(
+ ChildProcess.make(
+ "git",
+ [
+ "-c",
+ "user.name=Test",
+ "-c",
+ "commit",
+ "--allow-empty",
+ "--quiet",
+ "-m",
+ "Initial commit",
+ ],
+ { cwd },
+ ),
+ ),
+ ),
+ 0,
+ );
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = ThreadId.make("thread:background-stop");
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create-background-stop"),
+ threadId,
+ projectId: ProjectId.make("project:background-stop"),
+ title: "Background stop",
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const waiting = yield* orchestrator.streamDomainEvents.pipe(
+ Stream.filter(
+ (event) => event.type === "run.updated" && event.payload.status === "waiting",
+ ),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("start-background-stop"),
+ threadId,
+ messageId: MessageId.make("message:background-stop"),
+ text: BG_PROMPT,
+ attachments: [],
+ createdBy: "user",
+ creationSource: "web",
+ dispatchMode: { type: "start_immediately" },
+ });
+ yield* worker.drain();
+ assert.isNull((yield* Ref.get(replayDriver.state)).failure);
+ yield* Fiber.join(waiting);
+ yield* worker.drain();
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ const run = projection.runs.at(-1)!;
+ assert.equal(run.status, "completed");
+ assert.equal(
+ (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length,
+ 1,
+ );
+ const stopped = yield* orchestrator.streamDomainEvents.pipe(
+ Stream.filter(
+ (event) =>
+ event.type === "turn-item.updated" &&
+ event.payload.type === "command_execution" &&
+ event.payload.status === "interrupted",
+ ),
+ Stream.runHead,
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* orchestrator.dispatch({
+ type: "run.interrupt",
+ commandId: CommandId.make("stop-background-command"),
+ threadId,
+ runId: run.id,
+ });
+ yield* worker.drain();
+ yield* Fiber.join(stopped);
+ assert.equal(
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
+ "completed",
+ );
+ assert.deepEqual(
+ (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks,
+ [],
+ );
+ }).pipe(
+ Effect.provide(
+ makeOrchestratorV2ReplayLayerWithRegistry(
+ { name: "codex-background-stop", runtimePolicyOverride: { cwd } },
+ makeCodexProviderAdapterRegistryReplayLayer({
+ transcript: localTranscript,
+ driver: replayDriver,
+ }),
+ { runEffectWorker: false },
+ ),
+ ),
+ );
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+ });
// The app-server exits after the root turn, before the command's own
// item/completed (Codex always sends one, so only a lost notification or a
@@ -5506,7 +5509,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- for (const scenario of [
+ it.effect.each([
{
name: "usage",
code: "usageLimitExceeded",
@@ -5557,192 +5560,190 @@ describe("CodexAdapterV2 post-settle continuation", () => {
expectedClass: "usage_limit",
},
{ name: "retry", code: "usageLimitExceeded", notification: true, expectedClass: "usage_limit" },
- ] as const) {
- it.effect(`classifies Codex terminal failures from ${scenario.name} evidence`, () =>
- Effect.scoped(
- Effect.gen(function* () {
- const nativeThreadId = `native-limit-${scenario.name}`;
- const nativeTurnId = `turn-limit-${scenario.name}`;
- const message = "Provider stopped this request.";
- const resetAt = "2033-05-19T07:20:00.000Z";
- const snapshot = {
- type: "emit_inbound" as const,
- label: "account/rateLimits/updated",
- frame: {
- method: "account/rateLimits/updated",
- params: {
- rateLimits: {
- limitId: "codex",
- primary: { usedPercent: 100, resetsAt: 2000100000, windowDurationMins: 300 },
- },
+ ] as const)("classifies Codex terminal failures from $name evidence", (scenario) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const nativeThreadId = `native-limit-${scenario.name}`;
+ const nativeTurnId = `turn-limit-${scenario.name}`;
+ const message = "Provider stopped this request.";
+ const resetAt = "2033-05-19T07:20:00.000Z";
+ const snapshot = {
+ type: "emit_inbound" as const,
+ label: "account/rateLimits/updated",
+ frame: {
+ method: "account/rateLimits/updated",
+ params: {
+ rateLimits: {
+ limitId: "codex",
+ primary: { usedPercent: 100, resetsAt: 2000100000, windowDurationMins: 300 },
},
},
- };
- const transcript = makeCodexReplayTranscript({
- scenario: `codex-limit-${scenario.name}`,
- entries: [
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
- ...(scenario.name === "known-reset" || scenario.name === "deferred-reset"
- ? [snapshot]
- : []),
- ...(scenario.name === "deferred-reset"
- ? [
- {
- type: "emit_inbound" as const,
- label: "item/completed/subAgentActivity-started",
- frame: {
- method: "item/completed",
- params: {
- threadId: nativeThreadId,
- turnId: nativeTurnId,
- item: {
- type: "subAgentActivity",
- id: "limit-child-spawn",
- kind: "started",
- agentThreadId: "native-limit-child",
- agentPath: "/root/limit_child",
- },
+ },
+ };
+ const transcript = makeCodexReplayTranscript({
+ scenario: `codex-limit-${scenario.name}`,
+ entries: [
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
+ ...(scenario.name === "known-reset" || scenario.name === "deferred-reset"
+ ? [snapshot]
+ : []),
+ ...(scenario.name === "deferred-reset"
+ ? [
+ {
+ type: "emit_inbound" as const,
+ label: "item/completed/subAgentActivity-started",
+ frame: {
+ method: "item/completed",
+ params: {
+ threadId: nativeThreadId,
+ turnId: nativeTurnId,
+ item: {
+ type: "subAgentActivity",
+ id: "limit-child-spawn",
+ kind: "started",
+ agentThreadId: "native-limit-child",
+ agentPath: "/root/limit_child",
},
},
},
- {
- type: "emit_inbound" as const,
- label: "turn/started/child",
- frame: {
- method: "turn/started",
- params: {
- threadId: "native-limit-child",
- turn: makeCodexReplayTurn({
- id: "limit-child-turn",
- status: "inProgress",
- }),
- },
+ },
+ {
+ type: "emit_inbound" as const,
+ label: "turn/started/child",
+ frame: {
+ method: "turn/started",
+ params: {
+ threadId: "native-limit-child",
+ turn: makeCodexReplayTurn({
+ id: "limit-child-turn",
+ status: "inProgress",
+ }),
},
},
- ]
- : []),
- ...(scenario.notification
- ? [
- {
- type: "emit_inbound" as const,
- label: "error",
- frame: {
- method: "error",
- params: {
- threadId: nativeThreadId,
- turnId: nativeTurnId,
- willRetry: scenario.name === "retry",
- error: {
- message,
- codexErrorInfo: scenario.code,
- additionalDetails:
- scenario.name === "matching-details"
- ? "Detailed provider allowance explanation."
- : null,
- },
+ },
+ ]
+ : []),
+ ...(scenario.notification
+ ? [
+ {
+ type: "emit_inbound" as const,
+ label: "error",
+ frame: {
+ method: "error",
+ params: {
+ threadId: nativeThreadId,
+ turnId: nativeTurnId,
+ willRetry: scenario.name === "retry",
+ error: {
+ message,
+ codexErrorInfo: scenario.code,
+ additionalDetails:
+ scenario.name === "matching-details"
+ ? "Detailed provider allowance explanation."
+ : null,
},
},
},
- ]
- : []),
- {
- type: "emit_inbound",
- label: "turn/completed",
- frame: {
- method: "turn/completed",
- params: {
- threadId: nativeThreadId,
- turn: {
- ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }),
- error: {
- message: scenario.name === "replacement" ? "A different failure." : message,
- ...(scenario.notification && scenario.name !== "matching-details"
- ? {}
- : { codexErrorInfo: scenario.code }),
- },
+ },
+ ]
+ : []),
+ {
+ type: "emit_inbound",
+ label: "turn/completed",
+ frame: {
+ method: "turn/completed",
+ params: {
+ threadId: nativeThreadId,
+ turn: {
+ ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }),
+ error: {
+ message: scenario.name === "replacement" ? "A different failure." : message,
+ ...(scenario.notification && scenario.name !== "matching-details"
+ ? {}
+ : { codexErrorInfo: scenario.code }),
},
},
},
},
- ...(scenario.name === "late-reset" ? [snapshot] : []),
- ...(scenario.name === "deferred-reset"
- ? [
- {
- ...snapshot,
- frame: {
- method: "account/rateLimits/updated",
- params: {
- rateLimits: {
- limitId: "codex",
- primary: {
- usedPercent: 100,
- resetsAt: 2000200000,
- windowDurationMins: 300,
- },
+ },
+ ...(scenario.name === "late-reset" ? [snapshot] : []),
+ ...(scenario.name === "deferred-reset"
+ ? [
+ {
+ ...snapshot,
+ frame: {
+ method: "account/rateLimits/updated",
+ params: {
+ rateLimits: {
+ limitId: "codex",
+ primary: {
+ usedPercent: 100,
+ resetsAt: 2000200000,
+ windowDurationMins: 300,
},
},
},
},
- {
- type: "emit_inbound" as const,
- label: "turn/completed/child",
- frame: {
- method: "turn/completed",
- params: {
- threadId: "native-limit-child",
- turn: makeCodexReplayTurn({
- id: "limit-child-turn",
- status: "completed",
- }),
- },
+ },
+ {
+ type: "emit_inbound" as const,
+ label: "turn/completed/child",
+ frame: {
+ method: "turn/completed",
+ params: {
+ threadId: "native-limit-child",
+ turn: makeCodexReplayTurn({
+ id: "limit-child-turn",
+ status: "completed",
+ }),
},
},
- ]
- : []),
- ],
- });
- const resetReceipt = yield* Deferred.make<void>();
- const harness = yield* makeCodexReplayHarness(transcript, (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "error" &&
- event.turnItem.failure.resetAt === resetAt
- ? Deferred.succeed(resetReceipt, undefined)
- : Effect.void,
- );
- yield* harness.runtime.startTurn(
- makeCodexTestTurnInput({
- threadId: harness.threadId,
- providerThread: harness.providerThread,
- now: yield* DateTime.now,
- text: "Continue.",
- attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`),
- }),
+ },
+ ]
+ : []),
+ ],
+ });
+ const resetReceipt = yield* Deferred.make<void>();
+ const harness = yield* makeCodexReplayHarness(transcript, (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.type === "error" &&
+ event.turnItem.failure.resetAt === resetAt
+ ? Deferred.succeed(resetReceipt, undefined)
+ : Effect.void,
+ );
+ yield* harness.runtime.startTurn(
+ makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ text: "Continue.",
+ attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`),
+ }),
+ );
+ yield* harness.firstTerminal;
+ const terminal = harness.terminalEvents()[0];
+ assert.equal(terminal?.status, "failed");
+ if (terminal?.status !== "failed") return;
+ assert.equal(terminal.failure.class, scenario.expectedClass);
+ assert.equal(terminal.threadDisposition, "reusable");
+ if (scenario.name === "known-reset" || scenario.name === "deferred-reset")
+ assert.equal(terminal.failure.resetAt, resetAt);
+ if (scenario.name === "matching-details")
+ assert.equal(terminal.failure.message, "Detailed provider allowance explanation.");
+ if (scenario.name === "late-reset") {
+ yield* Deferred.await(resetReceipt);
+ const item = harness.events.find(
+ (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.type === "error" &&
+ event.turnItem.failure.resetAt === resetAt,
);
- yield* harness.firstTerminal;
- const terminal = harness.terminalEvents()[0];
- assert.equal(terminal?.status, "failed");
- if (terminal?.status !== "failed") return;
- assert.equal(terminal.failure.class, scenario.expectedClass);
- assert.equal(terminal.threadDisposition, "reusable");
- if (scenario.name === "known-reset" || scenario.name === "deferred-reset")
- assert.equal(terminal.failure.resetAt, resetAt);
- if (scenario.name === "matching-details")
- assert.equal(terminal.failure.message, "Detailed provider allowance explanation.");
- if (scenario.name === "late-reset") {
- yield* Deferred.await(resetReceipt);
- const item = harness.events.find(
- (event) =>
- event.type === "turn_item.updated" &&
- event.turnItem.type === "error" &&
- event.turnItem.failure.resetAt === resetAt,
- );
- assert.isDefined(item);
- }
- if (scenario.name === "retry") assert.equal(terminal.retry?.attempt, 1);
- }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
- ),
- );
- }
+ assert.isDefined(item);
+ }
+ if (scenario.name === "retry") assert.equal(terminal.retry?.attempt, 1);
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
+ ),
+ );
const FAILED_SCENARIO = "codex-failed-mid-command";
const FAILED_NATIVE_THREAD = "native-codex-failed-thread";
@@ -6511,7 +6512,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
- for (const [nativeStatus, expectedStatus] of [
+ it.effect.each([
["pendingInit", "pending"],
["running", "running"],
["interrupted", "interrupted"],
@@ -6523,8 +6524,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {
["late-activity-completed", "completed"],
["stale-running", "completed"],
["duplicate-completed", "completed"],
- ] as const) {
- it.effect(`normalizes subagent ${nativeStatus} without losing its lifecycle`, () =>
+ ] as const)(
+ "normalizes subagent %s without losing its lifecycle",
+ ([nativeStatus, expectedStatus]) =>
Effect.scoped(
Effect.gen(function* () {
const marker = yield* Deferred.make<void>();
@@ -6670,8 +6672,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
}
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
),
- );
- }
+ );
const codexReplayThreadResult = (input: {
readonly nativeThreadId: string;
diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.test.ts
index d31e91eac08..3a172baa67c 100644
--- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.test.ts
@@ -39,12 +39,13 @@ import { isCursorCancellationError, loggedCursorAgentOptions } from "./CursorAge
const decodeCursorSettings = Schema.decodeEffect(CursorSettings);
describe("CursorAdapterV2", () => {
- for (const { status, model } of [
+ it.effect.each([
{ status: "finished", model: undefined },
{ status: "cancelled", model: "claude-opus-4-6" },
{ status: "error", model: "custom-fable" },
- ] as const) {
- it.effect(`settles missing task completions when the Cursor run is ${status}`, () =>
+ ] as const)(
+ "settles missing task completions when the Cursor run is $status",
+ ({ status, model }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -185,8 +186,7 @@ describe("CursorAdapterV2", () => {
);
assert.isNotNull(rows.at(-1)?.subagent.completedAt);
}).pipe(Effect.scoped, Effect.provide(Layer.merge(NodeServices.layer, IdAllocator.layer))),
- );
- }
+ );
it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
index 60be8b82f06..281882c9eb5 100644
--- a/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.test.ts
@@ -371,17 +371,19 @@ describe("Grok launch permission mode", () => {
...override,
});
- for (const [runtimeMode, args] of [
- ["approval-required", ["--permission-mode", "default", "agent", "stdio"]],
- ["auto", ["--permission-mode", "auto", "agent", "stdio"]],
- ["full-access", ["agent", "--always-approve", "stdio"]],
- ] as const) {
- it.effect(`launches ${runtimeMode} threads with ${args.join(" ")}`, () =>
- Effect.gen(function* () {
- assert.deepEqual(yield* launchArgs(policy(runtimeMode)), [args]);
- }),
- );
- }
+ it.effect.each(
+ (
+ [
+ ["approval-required", ["--permission-mode", "default", "agent", "stdio"]],
+ ["auto", ["--permission-mode", "auto", "agent", "stdio"]],
+ ["full-access", ["agent", "--always-approve", "stdio"]],
+ ] as const
+ ).map(([runtimeMode, args]) => [runtimeMode, args.join(" "), args] as const),
+ )("launches %s threads with %s", ([runtimeMode, , args]) =>
+ Effect.gen(function* () {
+ assert.deepEqual(yield* launchArgs(policy(runtimeMode)), [args]);
+ }),
+ );
it.effect("launches a thread stored as Auto-accept edits asking", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index e321a1369cc..b437ae9cf92 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -3090,81 +3090,78 @@ describe("OpenCode2 adapter", () => {
}).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)),
);
- for (const running of [true, false]) {
- it.effect(
- running
- ? "refuses a rollback while a timed-out Stop's run is still going"
- : "rolls back once a timed-out Stop's run has left the server",
- () =>
- Effect.gen(function* () {
- const prompt = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
- const { runtime, thread } = yield* resumed([
- ...stopTimedOut,
- // The server says whether the stopped run still goes.
- out("session.active"),
- reply("session.active", { data: running ? { [SESSION]: { type: "running" } } : {} }),
- // Gone: the cut is made. Running: nothing is read or cut meanwhile.
- ...(running
- ? []
- : [
- out("message.list", "<any>"),
- reply("message.list", {
- data: [{ id: prompt, time: { created: 1 }, text: "hi", type: "user" }],
- cursor: {},
- }),
- out("session.revert.stage", {
- sessionID: SESSION,
- messageID: prompt,
- files: false,
- }),
- replyData("session.revert.stage", { messageID: prompt, files: [] }),
- out("session.revert.commit", { sessionID: SESSION }),
- reply("session.revert.commit", null),
- out("message.list", "<any>"),
- reply("message.list", { data: [], cursor: {} }),
- ]),
- ]);
- yield* stopFirstTurn(runtime, thread);
- const now = yield* DateTime.now;
- const first = {
- id: yield* providerTurnId,
- providerThreadId: thread.id,
- nodeId: NodeId.make("node:opencode2-adapter"),
- runAttemptId: RunAttemptId.make("attempt:opencode2-adapter"),
- nativeTurnRef: {
- driver: OPENCODE_PROVIDER,
- nativeId: prompt,
- strength: "weak" as const,
- },
- ordinal: 1,
- status: "interrupted" as const,
- startedAt: now,
- completedAt: now,
- };
- const rollback = yield* runtime
- .rollbackThread({
- providerThread: thread,
- target: {
- type: "thread_start",
- checkpointId: CheckpointId.make("checkpoint:start"),
- appRunOrdinal: 0,
- },
- providerThreadTurns: [first],
- })
- .pipe(Effect.exit);
- if (running) {
- assert.isTrue(Exit.isFailure(rollback));
- const error = Exit.isFailure(rollback) ? Cause.squash(rollback.cause) : undefined;
- assert.equal(
- (error as { _tag?: string } | undefined)?._tag,
- "ProviderAdapterProtocolError",
- );
- } else {
- assert.isTrue(Exit.isSuccess(rollback));
- }
- }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
- );
- }
+ it.effect.each([
+ ["refuses a rollback while a timed-out Stop's run is still going", true],
+ ["rolls back once a timed-out Stop's run has left the server", false],
+ ] as const)("%s", ([, running]) =>
+ Effect.gen(function* () {
+ const prompt = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`;
+ const { runtime, thread } = yield* resumed([
+ ...stopTimedOut,
+ // The server says whether the stopped run still goes.
+ out("session.active"),
+ reply("session.active", { data: running ? { [SESSION]: { type: "running" } } : {} }),
+ // Gone: the cut is made. Running: nothing is read or cut meanwhile.
+ ...(running
+ ? []
+ : [
+ out("message.list", "<any>"),
+ reply("message.list", {
+ data: [{ id: prompt, time: { created: 1 }, text: "hi", type: "user" }],
+ cursor: {},
+ }),
+ out("session.revert.stage", {
+ sessionID: SESSION,
+ messageID: prompt,
+ files: false,
+ }),
+ replyData("session.revert.stage", { messageID: prompt, files: [] }),
+ out("session.revert.commit", { sessionID: SESSION }),
+ reply("session.revert.commit", null),
+ out("message.list", "<any>"),
+ reply("message.list", { data: [], cursor: {} }),
+ ]),
+ ]);
+ yield* stopFirstTurn(runtime, thread);
+ const now = yield* DateTime.now;
+ const first = {
+ id: yield* providerTurnId,
+ providerThreadId: thread.id,
+ nodeId: NodeId.make("node:opencode2-adapter"),
+ runAttemptId: RunAttemptId.make("attempt:opencode2-adapter"),
+ nativeTurnRef: {
+ driver: OPENCODE_PROVIDER,
+ nativeId: prompt,
+ strength: "weak" as const,
+ },
+ ordinal: 1,
+ status: "interrupted" as const,
+ startedAt: now,
+ completedAt: now,
+ };
+ const rollback = yield* runtime
+ .rollbackThread({
+ providerThread: thread,
+ target: {
+ type: "thread_start",
+ checkpointId: CheckpointId.make("checkpoint:start"),
+ appRunOrdinal: 0,
+ },
+ providerThreadTurns: [first],
+ })
+ .pipe(Effect.exit);
+ if (running) {
+ assert.isTrue(Exit.isFailure(rollback));
+ const error = Exit.isFailure(rollback) ? Cause.squash(rollback.cause) : undefined;
+ assert.equal(
+ (error as { _tag?: string } | undefined)?._tag,
+ "ProviderAdapterProtocolError",
+ );
+ } else {
+ assert.isTrue(Exit.isSuccess(rollback));
+ }
+ }).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
+ );
it.effect("takes back a stranded steer again when its first cancel failed", () =>
Effect.gen(function* () {
@@ -3376,92 +3373,92 @@ describe("OpenCode2 adapter", () => {
}).pipe(Effect.scoped),
);
- for (const running of [true, false]) {
- it.effect(
- running
- ? "refuses to roll back a session not loaded yet while the server runs it"
- : "keeps the recorded turns before the target when rolling back a session not loaded yet",
- () =>
- Effect.gen(function* () {
- const first = `msg_t3_turn_${SESSION}:attempt:first`;
- const second = `msg_t3_turn_${SESSION}:attempt:second`;
- // A runtime that never loaded the session, as after a T3 restart
- // against a server that kept running.
- const runtime = yield* openCode2ReplayRuntime([
- ...opening,
- out("session.active"),
- reply("session.active", { data: running ? { [SESSION]: { type: "running" } } : {} }),
- ...(running
- ? []
- : [
- out("session.get", { sessionID: SESSION }),
- replyData("session.get", sessionInfo()),
- ...noOpenRequests,
- out("message.list", "<any>"),
- reply("message.list", {
- data: [
- { id: second, time: { created: 2 }, text: "second", type: "user" },
- { id: first, time: { created: 1 }, text: "first", type: "user" },
- ],
- cursor: {},
- }),
- out("session.revert.stage", {
- sessionID: SESSION,
- messageID: second,
- files: false,
- }),
- replyData("session.revert.stage", { messageID: second, files: [] }),
- out("session.revert.commit", { sessionID: SESSION }),
- reply("session.revert.commit", null),
- out("message.list", "<any>"),
- reply("message.list", {
- data: [{ id: first, time: { created: 1 }, text: "first", type: "user" }],
- cursor: {},
- }),
- ]),
- ]);
- const thread = providerThread(yield* DateTime.now);
- const now = yield* DateTime.now;
- const recorded = (key: string, ordinal: number, nativeId: string) => ({
- id: ProviderTurnId.make(`provider-turn:${key}`),
- providerThreadId: thread.id,
- nodeId: NodeId.make(`node:${key}`),
- runAttemptId: RunAttemptId.make(`attempt:${key}`),
- nativeTurnRef: { driver: OPENCODE_PROVIDER, nativeId, strength: "weak" as const },
- ordinal,
- status: "completed" as const,
- startedAt: now,
- completedAt: now,
- });
- const kept = recorded("first", 1, first);
- const rollback = yield* runtime
- .rollbackThread({
- providerThread: thread,
- target: {
- type: "provider_turn",
- checkpointId: CheckpointId.make("checkpoint:first"),
- appRunOrdinal: 1,
- providerTurn: kept,
- },
- providerThreadTurns: [kept, recorded("second", 2, second)],
- })
- .pipe(Effect.exit);
- if (running) {
- const error = Exit.isFailure(rollback) ? Cause.squash(rollback.cause) : undefined;
- assert.equal(
- (error as { _tag?: string } | undefined)?._tag,
- "ProviderAdapterProtocolError",
- );
- } else {
- assert.isTrue(Exit.isSuccess(rollback));
- assert.deepEqual(
- Exit.isSuccess(rollback) ? rollback.value.providerTurns.map((turn) => turn.id) : [],
- [kept.id],
- );
- }
- }).pipe(Effect.scoped),
- );
- }
+ it.effect.each([
+ ["refuses to roll back a session not loaded yet while the server runs it", true],
+ [
+ "keeps the recorded turns before the target when rolling back a session not loaded yet",
+ false,
+ ],
+ ] as const)("%s", ([, running]) =>
+ Effect.gen(function* () {
+ const first = `msg_t3_turn_${SESSION}:attempt:first`;
+ const second = `msg_t3_turn_${SESSION}:attempt:second`;
+ // A runtime that never loaded the session, as after a T3 restart
+ // against a server that kept running.
+ const runtime = yield* openCode2ReplayRuntime([
+ ...opening,
+ out("session.active"),
+ reply("session.active", { data: running ? { [SESSION]: { type: "running" } } : {} }),
+ ...(running
+ ? []
+ : [
+ out("session.get", { sessionID: SESSION }),
+ replyData("session.get", sessionInfo()),
+ ...noOpenRequests,
+ out("message.list", "<any>"),
+ reply("message.list", {
+ data: [
+ { id: second, time: { created: 2 }, text: "second", type: "user" },
+ { id: first, time: { created: 1 }, text: "first", type: "user" },
+ ],
+ cursor: {},
+ }),
+ out("session.revert.stage", {
+ sessionID: SESSION,
+ messageID: second,
+ files: false,
+ }),
+ replyData("session.revert.stage", { messageID: second, files: [] }),
+ out("session.revert.commit", { sessionID: SESSION }),
+ reply("session.revert.commit", null),
+ out("message.list", "<any>"),
+ reply("message.list", {
+ data: [{ id: first, time: { created: 1 }, text: "first", type: "user" }],
+ cursor: {},
+ }),
+ ]),
+ ]);
+ const thread = providerThread(yield* DateTime.now);
+ const now = yield* DateTime.now;
+ const recorded = (key: string, ordinal: number, nativeId: string) => ({
+ id: ProviderTurnId.make(`provider-turn:${key}`),
+ providerThreadId: thread.id,
+ nodeId: NodeId.make(`node:${key}`),
+ runAttemptId: RunAttemptId.make(`attempt:${key}`),
+ nativeTurnRef: { driver: OPENCODE_PROVIDER, nativeId, strength: "weak" as const },
+ ordinal,
+ status: "completed" as const,
+ startedAt: now,
+ completedAt: now,
+ });
+ const kept = recorded("first", 1, first);
+ const rollback = yield* runtime
+ .rollbackThread({
+ providerThread: thread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint:first"),
+ appRunOrdinal: 1,
+ providerTurn: kept,
+ },
+ providerThreadTurns: [kept, recorded("second", 2, second)],
+ })
+ .pipe(Effect.exit);
+ if (running) {
+ const error = Exit.isFailure(rollback) ? Cause.squash(rollback.cause) : undefined;
+ assert.equal(
+ (error as { _tag?: string } | undefined)?._tag,
+ "ProviderAdapterProtocolError",
+ );
+ } else {
+ assert.isTrue(Exit.isSuccess(rollback));
+ assert.deepEqual(
+ Exit.isSuccess(rollback) ? rollback.value.providerTurns.map((turn) => turn.id) : [],
+ [kept.id],
+ );
+ }
+ }).pipe(Effect.scoped),
+ );
it.effect("refuses to fork a session while OpenCode runs a follow-up on it", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts
index 3a3f9a2af6c..eca4aa9115a 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.test.ts
@@ -237,8 +237,9 @@ const makeOpenCodeRuntimeHarness = Effect.fn("makeOpenCodeRuntimeHarness")(funct
});
describe("OpenCodeAdapterV2", () => {
- for (const ending of ["completed", "failed", "unresolved", "unavailable", "reconnect"] as const) {
- it.effect(`normalizes OpenCode step usage for ${ending} turns`, () =>
+ it.effect.each(["completed", "failed", "unresolved", "unavailable", "reconnect"] as const)(
+ "normalizes OpenCode step usage for %s turns",
+ (ending) =>
Effect.gen(function* () {
const nativeEvents = asyncEventStream();
let promptId = "";
@@ -375,11 +376,11 @@ describe("OpenCodeAdapterV2", () => {
},
);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
- );
- }
+ );
- for (const kind of ["permission", "question"] as const) {
- it.effect(`cancels an undelivered ${kind} reply at its deadline`, () =>
+ it.effect.each(["permission", "question"] as const)(
+ "cancels an undelivered %s reply at its deadline",
+ (kind) =>
Effect.gen(function* () {
const nativeEvents = asyncEventStream();
const called = promiseGate<void>();
@@ -453,8 +454,7 @@ describe("OpenCodeAdapterV2", () => {
// Failed delivery leaves the request available for an explicit retry.
yield* harness.runtime.respondToRuntimeRequest(response);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
- );
- }
+ );
it.effect("aborts external root and descendants before closing the event stream", () =>
Effect.gen(function* () {
@@ -494,8 +494,9 @@ describe("OpenCodeAdapterV2", () => {
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
);
- for (const failure of ["enumeration", "abort", "not-found", "timeout"] as const) {
- it.effect(`reports descendant cleanup ${failure}`, () =>
+ it.effect.each(["enumeration", "abort", "not-found", "timeout"] as const)(
+ "reports descendant cleanup %s",
+ (failure) =>
Effect.gen(function* () {
const nativeEvents = asyncEventStream();
const called = promiseGate<void>();
@@ -545,8 +546,7 @@ describe("OpenCodeAdapterV2", () => {
assert.equal(Exit.isSuccess(result), failure === "not-found");
if (failure === "timeout") assert.isTrue(childSignal?.aborted);
}).pipe(Effect.provide(IdAllocator.layer), Effect.scoped),
- );
- }
+ );
it.effect(
"preserves tool lifecycle, approval kinds, and late assistant text without cached tool payloads",
diff --git a/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.test.ts
index 9d1f11d6e28..fb912714f12 100644
--- a/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/PiAdapterV2.test.ts
@@ -589,8 +589,9 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(testLayer)),
);
- for (const invalidReplacement of ["veto", "same identity"] as const) {
- it.effect(`rejects a replacement with ${invalidReplacement}`, () =>
+ it.effect.each(["veto", "same identity"] as const)(
+ "rejects a replacement with %s",
+ (invalidReplacement) =>
Effect.gen(function* () {
const fake = yield* makeFakePi;
const { runtime } = yield* openRuntime(fake);
@@ -617,8 +618,7 @@ describe("PiAdapterV2", () => {
yield* startTurn(runtime, providerThread, "default").pipe(Effect.flip);
assert.isFalse(fake.allRequests().some((request) => request.type === "prompt"));
}).pipe(Effect.scoped, Effect.provide(testLayer)),
- );
- }
+ );
it.effect("retires a timed-out lifecycle process before a late switch can race replacement", () =>
Effect.gen(function* () {
@@ -983,90 +983,85 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(testLayer)),
);
- for (const historical of [false, true]) {
- it.effect(
- `natively forks ${historical ? "a historical turn" : "the latest turn"} into an independent session`,
- () =>
- Effect.gen(function* () {
- const fake = yield* makeFakePi;
- const forkFake = yield* makeFakePi;
- const forkFile = "/fake/forked.jsonl";
- const { runtime, takeEvent } = yield* openRuntime(
- fake,
- "default",
- THREAD_ID,
- SESSION_ID,
- forkFake,
- );
- const source = yield* runtime.ensureThread({
- threadId: THREAD_ID,
- modelSelection: modelSelection("default"),
- runtimePolicy,
- });
- const turn = (ordinal: number): OrchestrationV2ProviderTurn => ({
- id: ProviderTurnId.make(`turn-${ordinal}`),
- providerThreadId: source.id,
- nodeId: NodeId.make(`node-${ordinal}`),
- runAttemptId: null,
- nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" },
- ordinal,
- status: "completed",
- startedAt: null,
- completedAt: null,
- });
- forkFake.queueState({ sessionFile: forkFile });
- fake.queueState({ sessionFile: forkFile });
- const target = ThreadId.make("fork-target");
- const forked = yield* runtime.forkThread({
- sourceProviderThread: source,
- sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)],
- providerTurnId: turn(1).id,
- targetThreadId: target,
- });
- assert.equal(forked.appThreadId, target);
- assert.equal(forked.nativeThreadRef?.nativeId, forkFile);
- assert.notEqual(forked.id, source.id);
- assert.equal(source.nativeThreadRef?.nativeId, FAKE_SESSION_FILE);
- const args = forkFake.lastSpawn().args;
- assert.equal(args[args.indexOf("--fork") + 1], FAKE_SESSION_FILE);
- assert.include(args, "--no-extensions");
- assert.include(args, "--no-tools");
- assert.notInclude(args, "--no-session");
- assert.deepEqual(
- forkFake
- .allRequests()
- .filter((request) => request.type === "fork")
- .map((request) => request.entryId),
- historical ? ["u2"] : [],
- );
- assert.isFalse(
- fake
- .allRequests()
- .some((request) => request.type === "fork" || request.type === "clone"),
- );
- // ProviderTurnStartService adopts the fork into its pending row.
- const adopted = { ...forked, id: ProviderThreadId.make("pending-fork-row") };
- yield* startTurn(runtime, adopted, "default", [], "Continue", undefined, 1, target);
- yield* fake.emit({ type: "agent_start" });
- yield* fake.emit({ type: "agent_settled" });
- const updated = yield* takeEvent(
- (event) =>
- event.type === "provider_thread.updated" &&
- event.providerThread.appThreadId === target,
- );
- assert.isTrue(
- updated.type === "provider_thread.updated" && updated.providerThread.id === adopted.id,
- );
- yield* takeEvent((event) => event.type === "turn.terminal");
- yield* runtime.resumeThread({ providerThread: adopted });
- assert.equal(
- fake.allRequests().findLast((request) => request.type === "switch_session")
- ?.sessionPath,
- forkFile,
- );
- }).pipe(Effect.scoped, Effect.provide(testLayer)),
- );
- }
+ it.effect.each([
+ { historical: false, label: "the latest turn" },
+ { historical: true, label: "a historical turn" },
+ ])("natively forks $label into an independent session", ({ historical }) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const forkFake = yield* makeFakePi;
+ const forkFile = "/fake/forked.jsonl";
+ const { runtime, takeEvent } = yield* openRuntime(
+ fake,
+ "default",
+ THREAD_ID,
+ SESSION_ID,
+ forkFake,
+ );
+ const source = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ const turn = (ordinal: number): OrchestrationV2ProviderTurn => ({
+ id: ProviderTurnId.make(`turn-${ordinal}`),
+ providerThreadId: source.id,
+ nodeId: NodeId.make(`node-${ordinal}`),
+ runAttemptId: null,
+ nativeTurnRef: { driver: PI_PROVIDER, nativeId: `u${ordinal}`, strength: "strong" },
+ ordinal,
+ status: "completed",
+ startedAt: null,
+ completedAt: null,
+ });
+ forkFake.queueState({ sessionFile: forkFile });
+ fake.queueState({ sessionFile: forkFile });
+ const target = ThreadId.make("fork-target");
+ const forked = yield* runtime.forkThread({
+ sourceProviderThread: source,
+ sourceProviderTurns: historical ? [turn(1), turn(2)] : [turn(1)],
+ providerTurnId: turn(1).id,
+ targetThreadId: target,
+ });
+ assert.equal(forked.appThreadId, target);
+ assert.equal(forked.nativeThreadRef?.nativeId, forkFile);
+ assert.notEqual(forked.id, source.id);
+ assert.equal(source.nativeThreadRef?.nativeId, FAKE_SESSION_FILE);
+ const args = forkFake.lastSpawn().args;
+ assert.equal(args[args.indexOf("--fork") + 1], FAKE_SESSION_FILE);
+ assert.include(args, "--no-extensions");
+ assert.include(args, "--no-tools");
+ assert.notInclude(args, "--no-session");
+ assert.deepEqual(
+ forkFake
+ .allRequests()
+ .filter((request) => request.type === "fork")
+ .map((request) => request.entryId),
+ historical ? ["u2"] : [],
+ );
+ assert.isFalse(
+ fake.allRequests().some((request) => request.type === "fork" || request.type === "clone"),
+ );
+ // ProviderTurnStartService adopts the fork into its pending row.
+ const adopted = { ...forked, id: ProviderThreadId.make("pending-fork-row") };
+ yield* startTurn(runtime, adopted, "default", [], "Continue", undefined, 1, target);
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "agent_settled" });
+ const updated = yield* takeEvent(
+ (event) =>
+ event.type === "provider_thread.updated" && event.providerThread.appThreadId === target,
+ );
+ assert.isTrue(
+ updated.type === "provider_thread.updated" && updated.providerThread.id === adopted.id,
+ );
+ yield* takeEvent((event) => event.type === "turn.terminal");
+ yield* runtime.resumeThread({ providerThread: adopted });
+ assert.equal(
+ fake.allRequests().findLast((request) => request.type === "switch_session")?.sessionPath,
+ forkFile,
+ );
+ }).pipe(Effect.scoped, Effect.provide(testLayer)),
+ );
it.effect("observes official subagent results without inventing child threads", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts b/apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts
index 2d448e3b7a5..9dc9fa4526e 100644
--- a/apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/piT3McpExtensionSource.test.ts
@@ -28,8 +28,9 @@ async function loadRequestHook(): Promise<RequestHook> {
}
describe("Pi upstream output-budget workaround", () => {
- for (const key of ["max_tokens", "max_completion_tokens"]) {
- it(`caps ${key} without changing the conversation or tools`, async () => {
+ it.each(["max_tokens", "max_completion_tokens"])(
+ "caps %s without changing the conversation or tools",
+ async (key) => {
const hook = await loadRequestHook();
const payload = {
model: "moonshotai/kimi-k2.6",
@@ -43,8 +44,8 @@ describe("Pi upstream output-budget workaround", () => {
assert.strictEqual(result?.tools, payload.tools);
assert.equal(result?.model, payload.model);
assert.equal(payload[key], 231_969);
- });
- }
+ },
+ );
it("preserves smaller budgets and other providers' payloads", async () => {
const hook = await loadRequestHook();
diff --git a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts
index 067b851d6a1..2c6c878b25e 100644
--- a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts
+++ b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts
@@ -413,55 +413,51 @@ describe("handoff budget", () => {
});
describe("handoff delivery", () => {
- for (const native of [true, false]) {
- it.effect(
- `records omitted recovery coverage separately from ${native ? "injected" : "inline"} text`,
- () =>
- Effect.gen(function* () {
- const omittedBeforeDelivery = TurnItemId.make("item:omitted-during-preparation");
- const oversized = message("item:oversized", "user", "x".repeat(20_000));
- let durable: OrchestrationV2ContextHandoff = {
- ...handoff,
- history: {
- ...handoff.history!,
- messages: [...messages, oversized],
- omittedItems: 1,
- omittedItemIds: [omittedBeforeDelivery],
- },
- };
- const result = yield* deliverContextHandoffs({
- handoffs: [durable],
- providerThread,
- budget: 16_000,
- alreadyDeliveredItemIds: new Set(),
- inject: (value) => {
- assert.include(value.context, "omitted 2 items");
- assert.notInclude(
- value.messages.map((item) => item.itemId),
- oversized.itemId,
- );
- return Effect.succeed(native);
- },
- persist: (value) =>
- Effect.sync(() => {
- durable = value;
- }),
- });
- assert.equal(durable.delivery?.status, native ? "injected" : "pending");
- yield* result.delivered;
- assert.equal(durable.delivery?.status, native ? "injected" : "inline");
- assert.deepEqual(
- durable.delivery?.itemIds,
- messages.map((item) => item.itemId),
- );
- assert.deepEqual(durable.delivery?.omittedItemIds, [
- omittedBeforeDelivery,
+ it.effect.each([
+ { native: true, label: "injected" },
+ { native: false, label: "inline" },
+ ])("records omitted recovery coverage separately from $label text", ({ native }) =>
+ Effect.gen(function* () {
+ const omittedBeforeDelivery = TurnItemId.make("item:omitted-during-preparation");
+ const oversized = message("item:oversized", "user", "x".repeat(20_000));
+ let durable: OrchestrationV2ContextHandoff = {
+ ...handoff,
+ history: {
+ ...handoff.history!,
+ messages: [...messages, oversized],
+ omittedItems: 1,
+ omittedItemIds: [omittedBeforeDelivery],
+ },
+ };
+ const result = yield* deliverContextHandoffs({
+ handoffs: [durable],
+ providerThread,
+ budget: 16_000,
+ alreadyDeliveredItemIds: new Set(),
+ inject: (value) => {
+ assert.include(value.context, "omitted 2 items");
+ assert.notInclude(
+ value.messages.map((item) => item.itemId),
oversized.itemId,
- ]);
- assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
- }),
- );
- }
+ );
+ return Effect.succeed(native);
+ },
+ persist: (value) =>
+ Effect.sync(() => {
+ durable = value;
+ }),
+ });
+ assert.equal(durable.delivery?.status, native ? "injected" : "pending");
+ yield* result.delivered;
+ assert.equal(durable.delivery?.status, native ? "injected" : "inline");
+ assert.deepEqual(
+ durable.delivery?.itemIds,
+ messages.map((item) => item.itemId),
+ );
+ assert.deepEqual(durable.delivery?.omittedItemIds, [omittedBeforeDelivery, oversized.itemId]);
+ assert.deepEqual(decodeHandoff(durable).delivery, durable.delivery);
+ }),
+ );
it.effect("loads the history budget only when a handoff needs delivery", () =>
Effect.gen(function* () {
let reads = 0;
diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
index b7f6e642cff..22b93178711 100644
--- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts
@@ -433,8 +433,9 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
),
);
- for (const phase of ["high-water", "replay"] as const) {
- it.effect(`bounds live events while the V2 ${phase} query is blocked`, () =>
+ it.effect.each(["high-water", "replay"] as const)(
+ "bounds live events while the V2 %s query is blocked",
+ (phase) =>
Effect.scoped(
Effect.gen(function* () {
const sink = yield* EventSink.EventSinkV2;
@@ -486,8 +487,7 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}
}),
),
- );
- }
+ );
it.effect(
"keeps internal streams subscribed while replay is blocked beyond the RPC buffer cap",
@@ -2661,68 +2661,66 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => {
}),
);
- for (const replayRequest of [
+ it.effect.each([
{ type: "terminal.cleanup" },
{ type: "provider-runtime.continue", sourceRunId: RunId.make("run:restart-replay") },
- ] as const) {
- it.effect(
- `retires live provider effects and requeues ${replayRequest.type} after process loss`,
- () =>
- Effect.gen(function* () {
- const outbox = yield* EffectOutbox.EffectOutboxV2;
- const commandId = CommandId.make(
- `command:foundation-reclaim-running:${replayRequest.type}`,
- );
- yield* outbox.enqueue([
- {
- id: `effect:a-foundation-cancel-provider-turn:${replayRequest.type}`,
- commandId,
- threadId: ThreadId.make(`thread:foundation-reclaim-running:${replayRequest.type}`),
- request: {
- type: "provider-turn.start",
- runId: RunId.make(`run:foundation-reclaim-running:${replayRequest.type}`),
- },
- },
- {
- id: `effect:b-foundation-requeue-cleanup:${replayRequest.type}`,
- commandId,
- threadId: ThreadId.make(`thread:foundation-reclaim-cleanup:${replayRequest.type}`),
- request: replayRequest,
+ ] as const)(
+ "retires live provider effects and requeues $type after process loss",
+ (replayRequest) =>
+ Effect.gen(function* () {
+ const outbox = yield* EffectOutbox.EffectOutboxV2;
+ const commandId = CommandId.make(
+ `command:foundation-reclaim-running:${replayRequest.type}`,
+ );
+ yield* outbox.enqueue([
+ {
+ id: `effect:a-foundation-cancel-provider-turn:${replayRequest.type}`,
+ commandId,
+ threadId: ThreadId.make(`thread:foundation-reclaim-running:${replayRequest.type}`),
+ request: {
+ type: "provider-turn.start",
+ runId: RunId.make(`run:foundation-reclaim-running:${replayRequest.type}`),
},
- ]);
- assert.isTrue(
- Option.isSome(
- yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
- ),
- );
- assert.isTrue(
- Option.isSome(
- yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
- ),
- );
- assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, {
- cancelled: 1,
- requeued: 1,
- });
- const cancelled = yield* outbox.get(
- `effect:a-foundation-cancel-provider-turn:${replayRequest.type}`,
- );
- assert.isTrue(Option.isSome(cancelled));
- if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled");
+ },
+ {
+ id: `effect:b-foundation-requeue-cleanup:${replayRequest.type}`,
+ commandId,
+ threadId: ThreadId.make(`thread:foundation-reclaim-cleanup:${replayRequest.type}`),
+ request: replayRequest,
+ },
+ ]);
+ assert.isTrue(
+ Option.isSome(
+ yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
+ ),
+ );
+ assert.isTrue(
+ Option.isSome(
+ yield* outbox.claimNext({ workerId: "crashed-worker", leaseDurationMs: 30_000 }),
+ ),
+ );
+ assert.deepEqual(yield* outbox.reconcileAfterProcessLoss, {
+ cancelled: 1,
+ requeued: 1,
+ });
+ const cancelled = yield* outbox.get(
+ `effect:a-foundation-cancel-provider-turn:${replayRequest.type}`,
+ );
+ assert.isTrue(Option.isSome(cancelled));
+ if (Option.isSome(cancelled)) assert.equal(cancelled.value.status, "cancelled");
- const reclaimed = yield* outbox.claimNext({
- workerId: "recovery-worker",
- leaseDurationMs: 30_000,
- });
- assert.isTrue(Option.isSome(reclaimed));
- if (Option.isSome(reclaimed)) {
- assert.equal(reclaimed.value.request.type, replayRequest.type);
- assert.equal(reclaimed.value.attemptCount, 2);
- yield* outbox.succeed({ effectId: reclaimed.value.id, workerId: "recovery-worker" });
- }
- }),
- );
- }
+ const reclaimed = yield* outbox.claimNext({
+ workerId: "recovery-worker",
+ leaseDurationMs: 30_000,
+ });
+ assert.isTrue(Option.isSome(reclaimed));
+ if (Option.isSome(reclaimed)) {
+ assert.equal(reclaimed.value.request.type, replayRequest.type);
+ assert.equal(reclaimed.value.attemptCount, 2);
+ yield* outbox.succeed({ effectId: reclaimed.value.id, workerId: "recovery-worker" });
+ }
+ }),
+ );
it.effect("atomically cancels stale runs and their process-bound effects", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
index f003aea73db..ad50b410c90 100644
--- a/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
+++ b/apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
@@ -78,8 +78,9 @@ it.effect("stops draining a slow subscriber when its unacknowledged tail fills",
type Event = { readonly sequence: number; readonly text: string; readonly threadId?: string };
describe("replayAndBufferLiveEvents", () => {
- for (const phase of ["high-water", "replay"] as const) {
- it.effect(`unsubscribes and cancels a blocked ${phase} read on live overflow`, () =>
+ it.effect.each(["high-water", "replay"] as const)(
+ "unsubscribes and cancels a blocked %s read on live overflow",
+ (phase) =>
Effect.scoped(
Effect.gen(function* () {
const pubsub = yield* PubSub.unbounded<Event>();
@@ -121,11 +122,11 @@ describe("replayAndBufferLiveEvents", () => {
expect(yield* PubSub.size(pubsub)).toBe(0);
}),
),
- );
- }
+ );
- for (const limit of ["items", "bytes"] as const) {
- it.effect(`counts an unacknowledged replay batch toward the live ${limit} limit`, () =>
+ it.effect.each(["items", "bytes"] as const)(
+ "counts an unacknowledged replay batch toward the live %s limit",
+ (limit) =>
Effect.scoped(
Effect.gen(function* () {
const pubsub = yield* PubSub.unbounded<Event>();
@@ -158,8 +159,7 @@ describe("replayAndBufferLiveEvents", () => {
if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
}),
),
- );
- }
+ );
it.effect("lets a fast reader replay a database page larger than both buffer limits", () =>
Effect.scoped(
diff --git a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
index eb1fb203420..024b94c2423 100644
--- a/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
+++ b/apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
@@ -332,61 +332,59 @@ const runScenario = (input: {
});
describe("OpenCode 2 through the orchestrator", () => {
- for (const via of ["message", "thread settings"] as const) {
- it.effect(
- `switches the session's model before the next prompt when changed from the ${via}`,
- () =>
- Effect.gen(function* () {
- const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
- const cwd = yield* checkpointWorkspace(name);
- const thread = threadCommands({ name, worktreePath: cwd });
- const projection = yield* runScenario({
- name,
- threadId: thread.threadId,
- entries: [
- ...createdSession(cwd, name),
- ...instructionsWritten,
- ...answeredPrompt("FIRST"),
- // The next turn resumes the session at its new selection.
- out("session.get", { sessionID: SESSION }),
- reply("session.get", sessionInfo(cwd, t3Rules(name))),
- out("session.switchModel", {
- sessionID: SESSION,
- model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
- }),
- reply("session.switchModel", null),
- // The instructions name the model, so they are written again.
- ...instructionsWritten,
- ...answeredPrompt("SECOND"),
- ],
- commands: [
- thread.create,
- thread.message("first"),
- ...(via === "thread settings"
- ? [
- {
- type: "thread.model-selection.set",
- commandId: thread.command("model"),
- threadId: thread.threadId,
- modelSelection: mimo,
- } satisfies OrchestrationV2Command,
- ]
- : []),
- thread.message("second", mimo),
- ],
- });
- assert.deepEqual(
- projection.runs.map((run) => [run.status, run.modelSelection.model]),
- [
- ["completed", bigPickle.model],
- ["completed", mimo.model],
- ],
- );
- // One native session carried both turns.
- assert.lengthOf(projection.providerThreads, 1);
- }).pipe(Effect.scoped),
- );
- }
+ it.effect.each(["message", "thread settings"] as const)(
+ "switches the session's model before the next prompt when changed from the %s",
+ (via) =>
+ Effect.gen(function* () {
+ const name = `opencode2-model-switch-${via.replace(" ", "-")}`;
+ const cwd = yield* checkpointWorkspace(name);
+ const thread = threadCommands({ name, worktreePath: cwd });
+ const projection = yield* runScenario({
+ name,
+ threadId: thread.threadId,
+ entries: [
+ ...createdSession(cwd, name),
+ ...instructionsWritten,
+ ...answeredPrompt("FIRST"),
+ // The next turn resumes the session at its new selection.
+ out("session.get", { sessionID: SESSION }),
+ reply("session.get", sessionInfo(cwd, t3Rules(name))),
+ out("session.switchModel", {
+ sessionID: SESSION,
+ model: { providerID: "opencode", id: "mimo-v2.6-flash-free" },
+ }),
+ reply("session.switchModel", null),
+ // The instructions name the model, so they are written again.
+ ...instructionsWritten,
+ ...answeredPrompt("SECOND"),
+ ],
+ commands: [
+ thread.create,
+ thread.message("first"),
+ ...(via === "thread settings"
+ ? [
+ {
+ type: "thread.model-selection.set",
+ commandId: thread.command("model"),
+ threadId: thread.threadId,
+ modelSelection: mimo,
+ } satisfies OrchestrationV2Command,
+ ]
+ : []),
+ thread.message("second", mimo),
+ ],
+ });
+ assert.deepEqual(
+ projection.runs.map((run) => [run.status, run.modelSelection.model]),
+ [
+ ["completed", bigPickle.model],
+ ["completed", mimo.model],
+ ],
+ );
+ // One native session carried both turns.
+ assert.lengthOf(projection.providerThreads, 1);
+ }).pipe(Effect.scoped),
+ );
it.effect("moves the session to the thread's new worktree before the next prompt", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/ProjectCommands.test.ts b/apps/server/src/orchestration-v2/ProjectCommands.test.ts
index 55f2218fbd0..bcbc5a88956 100644
--- a/apps/server/src/orchestration-v2/ProjectCommands.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectCommands.test.ts
@@ -128,16 +128,17 @@ describe("planProjectCommand", () => {
assert.isNull(payloadOf(update({ defaultThreadEnvMode: null })).defaultThreadEnvMode);
});
- for (const id of ["install-javascript-dependencies", "A", "a.b", "a b", "-a", "a".repeat(25)]) {
- it(`rejects a new script ID that cannot have a shortcut: ${id}`, () => {
+ it.each(["install-javascript-dependencies", "A", "a.b", "a b", "-a", "a".repeat(25)])(
+ "rejects a new script ID that cannot have a shortcut: %s",
+ (id) => {
const failure = failureOf(update({ scripts: [script("lint"), script(id)] }));
assert.equal(failure._tag, "ProjectCommandInvariantError");
assert.include(failure.message, "Script ID");
assert.include(failure.message, "24");
// The detail is persisted in the rejected receipt, so it omits the raw ID.
assert.notInclude(failure.message, `'${id}'`);
- });
- }
+ },
+ );
it("accepts a script ID at the shortcut length limit", () => {
const scripts = [script("a".repeat(24))];
diff --git a/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts b/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts
index 221c773149a..4889a48b3d8 100644
--- a/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionControlReads.test.ts
@@ -186,12 +186,17 @@ function fixtureEvents(now: DateTime.Utc): ReadonlyArray<OrchestrationV2DomainEv
];
}
-for (const storage of ["sqlite", "memory"] as const) {
- const storeLayer =
+const storageCases = (["sqlite", "memory"] as const).map((storage) => ({
+ storage,
+ storeLayer:
storage === "sqlite"
? ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistenceMemory))
- : ProjectionStore.layerMemory;
- it.effect(`${storage}: finds the active root turn without an attempt reverse link`, () =>
+ : ProjectionStore.layerMemory,
+}));
+
+it.effect.each(storageCases)(
+ "$storage: finds the active root turn without an attempt reverse link",
+ ({ storeLayer }) =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
@@ -210,8 +215,10 @@ for (const storage of ["sqlite", "memory"] as const) {
});
assert.isUndefined((yield* store.getRunningTurnContext(threadId)).providerTurn);
}).pipe(Effect.provide(storeLayer)),
- );
- it.effect(`${storage}: controls and replies read only their exact durable targets`, () =>
+);
+it.effect.each(storageCases)(
+ "$storage: controls and replies read only their exact durable targets",
+ ({ storage, storeLayer }) =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
@@ -344,5 +351,4 @@ for (const storage of ["sqlite", "memory"] as const) {
),
);
}).pipe(Effect.provide(Layer.merge(storeLayer, SqlitePersistenceMemory))),
- );
-}
+);
diff --git a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
index 4fb806e61e9..eec1ad1c3f0 100644
--- a/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionSettlement.test.ts
@@ -140,159 +140,157 @@ const createItem = Effect.fn(function* (
});
});
-for (const [name, testLayer] of [
+it.effect.each([
["sql", SqlLayer],
["memory", ProjectionStore.layerMemory],
-] as const) {
- it.effect(
- `${name}: discovers settlement work with the same activity and background semantics as the shell`,
- () =>
- Effect.gen(function* () {
- const store = yield* ProjectionStore.ProjectionStoreV2;
- const idle = yield* createThread("idle");
- const completed = yield* createThread("completed");
- yield* createRun(completed);
- for (const [name, overrides] of [
- ["archived", { archivedAt: old }],
- ["deleted", { deletedAt: old }],
- ["settled", { settledOverride: "settled" }],
- ["unsettled", { settledOverride: "active" }],
- ["pinned", { pinnedAt: old }],
- ["auto-settle-disabled", { autoSettleDisabledAt: old }],
- ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
- yield* createRun(yield* createThread(name, overrides));
- }
- for (const status of ["preparing", "starting", "running", "waiting"] as const) {
- yield* createRun(yield* createThread(status), status);
- }
- const queued = yield* createThread("queued");
- yield* createRun(queued, "queued");
- const blocked = yield* createThread("blocked");
- yield* store.apply({
- id: EventId.make("event:settlement:request"),
- type: "runtime-request.updated",
- threadId: blocked,
- occurredAt: old,
- payload: {
- id: RuntimeRequestId.make("request:settlement"),
- nodeId: NodeId.make("node:settlement"),
- providerTurnId: null,
- nativeRequestRef: null,
- kind: "user_input",
- status: "pending",
- responseCapability: { type: "not_resumable", reason: "Process stopped" },
- createdAt: old,
- resolvedAt: null,
- },
- });
- const recent = yield* createThread("recent-message");
- yield* createRun(recent);
- yield* store.apply({
- id: EventId.make("event:settlement:message"),
- type: "message.updated",
+] as const)(
+ "%s: discovers settlement work with the same activity and background semantics as the shell",
+ ([, testLayer]) =>
+ Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const idle = yield* createThread("idle");
+ const completed = yield* createThread("completed");
+ yield* createRun(completed);
+ for (const [name, overrides] of [
+ ["archived", { archivedAt: old }],
+ ["deleted", { deletedAt: old }],
+ ["settled", { settledOverride: "settled" }],
+ ["unsettled", { settledOverride: "active" }],
+ ["pinned", { pinnedAt: old }],
+ ["auto-settle-disabled", { autoSettleDisabledAt: old }],
+ ] satisfies ReadonlyArray<readonly [string, Partial<OrchestrationV2AppThread>]>) {
+ yield* createRun(yield* createThread(name, overrides));
+ }
+ for (const status of ["preparing", "starting", "running", "waiting"] as const) {
+ yield* createRun(yield* createThread(status), status);
+ }
+ const queued = yield* createThread("queued");
+ yield* createRun(queued, "queued");
+ const blocked = yield* createThread("blocked");
+ yield* store.apply({
+ id: EventId.make("event:settlement:request"),
+ type: "runtime-request.updated",
+ threadId: blocked,
+ occurredAt: old,
+ payload: {
+ id: RuntimeRequestId.make("request:settlement"),
+ nodeId: NodeId.make("node:settlement"),
+ providerTurnId: null,
+ nativeRequestRef: null,
+ kind: "user_input",
+ status: "pending",
+ responseCapability: { type: "not_resumable", reason: "Process stopped" },
+ createdAt: old,
+ resolvedAt: null,
+ },
+ });
+ const recent = yield* createThread("recent-message");
+ yield* createRun(recent);
+ yield* store.apply({
+ id: EventId.make("event:settlement:message"),
+ type: "message.updated",
+ threadId: recent,
+ occurredAt: now,
+ payload: {
+ createdBy: "user",
+ creationSource: "web",
+ id: MessageId.make("message:settlement:recent"),
threadId: recent,
- occurredAt: now,
- payload: {
- createdBy: "user",
- creationSource: "web",
- id: MessageId.make("message:settlement:recent"),
- threadId: recent,
- runId: null,
- nodeId: null,
- role: "user",
- text: "Next turn",
- attachments: [],
- streaming: false,
- createdAt: now,
- updatedAt: now,
- },
- });
- yield* createRun(
- yield* createThread("snoozed", {
- snoozedUntil: DateTime.add(now, { days: 1 }),
- snoozedAt: now,
- }),
- );
- const woke = yield* createThread("woke", {
+ runId: null,
+ nodeId: null,
+ role: "user",
+ text: "Next turn",
+ attachments: [],
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ },
+ });
+ yield* createRun(
+ yield* createThread("snoozed", {
snoozedUntil: DateTime.add(now, { days: 1 }),
- snoozedAt: DateTime.subtract(old, { days: 1 }),
- });
- yield* createRun(woke);
- const background = yield* createThread("idle-background");
- yield* createItem(background, yield* createRun(background), "idle");
- const persistent = yield* createThread("persistent-monitor");
- yield* createItem(persistent, yield* createRun(persistent), "running", true);
- const rolledBack = yield* createThread("rolled-back-background");
- yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
- yield* createRun(rolledBack, "completed", 2);
- const roster = yield* createThread("provider-roster");
- yield* createRun(roster);
- yield* store.apply({
- id: EventId.make("event:settlement:roster"),
- type: "provider-thread.updated",
- threadId: roster,
- occurredAt: old,
- payload: {
- id: ProviderThreadId.make("provider-thread:settlement"),
- appThreadId: roster,
- ownerNodeId: null,
- driver: ProviderDriverKind.make("codex"),
- providerInstanceId,
- providerSessionId: null,
- nativeThreadRef: null,
- nativeConversationHeadRef: null,
- status: "idle",
- firstRunOrdinal: null,
- lastRunOrdinal: null,
- handoffIds: [],
- forkedFrom: null,
- createdAt: old,
- updatedAt: old,
- pendingBackgroundTasks: [{ taskId: "running-task", kind: "command" }],
- },
- });
- const candidates = yield* store.getSettlementCandidates();
- const shell = yield* store.getShellSnapshot({ location: "active" });
- const eligible = candidates.filter((thread) =>
- isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
- );
- assert.deepEqual(
- new Set(eligible.map((thread) => thread.id)),
- new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
- );
+ snoozedAt: now,
+ }),
+ );
+ const woke = yield* createThread("woke", {
+ snoozedUntil: DateTime.add(now, { days: 1 }),
+ snoozedAt: DateTime.subtract(old, { days: 1 }),
+ });
+ yield* createRun(woke);
+ const background = yield* createThread("idle-background");
+ yield* createItem(background, yield* createRun(background), "idle");
+ const persistent = yield* createThread("persistent-monitor");
+ yield* createItem(persistent, yield* createRun(persistent), "running", true);
+ const rolledBack = yield* createThread("rolled-back-background");
+ yield* createItem(rolledBack, yield* createRun(rolledBack, "rolled_back"), "running");
+ yield* createRun(rolledBack, "completed", 2);
+ const roster = yield* createThread("provider-roster");
+ yield* createRun(roster);
+ yield* store.apply({
+ id: EventId.make("event:settlement:roster"),
+ type: "provider-thread.updated",
+ threadId: roster,
+ occurredAt: old,
+ payload: {
+ id: ProviderThreadId.make("provider-thread:settlement"),
+ appThreadId: roster,
+ ownerNodeId: null,
+ driver: ProviderDriverKind.make("codex"),
+ providerInstanceId,
+ providerSessionId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: "idle",
+ firstRunOrdinal: null,
+ lastRunOrdinal: null,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: old,
+ updatedAt: old,
+ pendingBackgroundTasks: [{ taskId: "running-task", kind: "command" }],
+ },
+ });
+ const candidates = yield* store.getSettlementCandidates();
+ const shell = yield* store.getShellSnapshot({ location: "active" });
+ const eligible = candidates.filter((thread) =>
+ isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)),
+ );
+ assert.deepEqual(
+ new Set(eligible.map((thread) => thread.id)),
+ new Set([idle, completed, queued, woke, background, persistent, rolledBack]),
+ );
+ assert.deepEqual(
+ new Set(eligible.map((thread) => thread.id)),
+ new Set(
+ shell.threads
+ .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
+ .map((thread) => thread.id),
+ ),
+ );
+ for (const candidate of candidates) {
+ const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
+ assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
+ const settings = {
+ pullRequest: null,
+ nowMs: DateTime.toEpochMillis(now),
+ autoSettleAfterDays: 7,
+ autoSettleOnMerge: false,
+ };
assert.deepEqual(
- new Set(eligible.map((thread) => thread.id)),
- new Set(
- shell.threads
- .filter((thread) => isAutoSettlementCandidate(thread, DateTime.toEpochMillis(now)))
- .map((thread) => thread.id),
- ),
- );
- for (const candidate of candidates) {
- const expected = shell.threads.find((thread) => thread.id === candidate.id)!;
- assert.deepEqual(candidate.pendingBackgroundTasks, expected.pendingBackgroundTasks);
- const settings = {
- pullRequest: null,
- nowMs: DateTime.toEpochMillis(now),
- autoSettleAfterDays: 7,
- autoSettleOnMerge: false,
- };
- assert.deepEqual(
- resolveAutoSettlementAt({ ...settings, thread: candidate }),
- resolveAutoSettlementAt({ ...settings, thread: expected }),
- );
- }
- assert.equal(
- DateTime.formatIso((yield* store.getThread(completed)).createdAt),
- DateTime.formatIso(old),
- );
- assert.equal(
- (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
- "ProjectionStoreThreadNotFoundError",
+ resolveAutoSettlementAt({ ...settings, thread: candidate }),
+ resolveAutoSettlementAt({ ...settings, thread: expected }),
);
- }).pipe(Effect.provide(testLayer)),
- );
-}
+ }
+ assert.equal(
+ DateTime.formatIso((yield* store.getThread(completed)).createdAt),
+ DateTime.formatIso(old),
+ );
+ assert.equal(
+ (yield* store.getThread(ThreadId.make("missing")).pipe(Effect.flip))._tag,
+ "ProjectionStoreThreadNotFoundError",
+ );
+ }).pipe(Effect.provide(testLayer)),
+);
const pullRequestLink = (number: number) => ({
host: "github.com",
@@ -305,11 +303,12 @@ const pullRequestLink = (number: number) => ({
stack: null,
});
-for (const [name, testLayer] of [
+it.effect.each([
["sql", SqlLayer],
["memory", ProjectionStore.layerMemory],
-] as const) {
- it.effect(`${name}: lists only active threads with pull request links, oldest first`, () =>
+] as const)(
+ "%s: lists only active threads with pull request links, oldest first",
+ ([, testLayer]) =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
yield* createThread("no-links");
@@ -337,33 +336,27 @@ for (const [name, testLayer] of [
],
);
}).pipe(Effect.provide(testLayer)),
- );
-}
+);
-for (const [name, testLayer] of [
+it.effect.each([
["sql", SqlLayer],
["memory", ProjectionStore.layerMemory],
-] as const) {
- it.effect(`${name}: an unsettled-only shell read skips settled threads`, () =>
- Effect.gen(function* () {
- const store = yield* ProjectionStore.ProjectionStoreV2;
- const open = yield* createThread("unsettled-open");
- const reopened = yield* createThread("unsettled-reopened", { settledOverride: "active" });
- yield* createThread("unsettled-manual", { settledOverride: "settled", settledAt: old });
- yield* createThread("unsettled-auto", { settledAt: old });
- yield* createThread("unsettled-archived", { archivedAt: old });
+] as const)("%s: an unsettled-only shell read skips settled threads", ([, testLayer]) =>
+ Effect.gen(function* () {
+ const store = yield* ProjectionStore.ProjectionStoreV2;
+ const open = yield* createThread("unsettled-open");
+ const reopened = yield* createThread("unsettled-reopened", { settledOverride: "active" });
+ yield* createThread("unsettled-manual", { settledOverride: "settled", settledAt: old });
+ yield* createThread("unsettled-auto", { settledAt: old });
+ yield* createThread("unsettled-archived", { archivedAt: old });
- const shell = yield* store.getShellSnapshot({ location: "active", unsettledOnly: true });
- assert.deepEqual(
- new Set(shell.threads.map((thread) => thread.id)),
- new Set([open, reopened]),
- );
- assert.equal(shell.archivedThreads.length, 0);
- const all = yield* store.getShellSnapshot({ location: "active" });
- assert.equal(all.threads.length, 4);
- }).pipe(Effect.provide(testLayer)),
- );
-}
+ const shell = yield* store.getShellSnapshot({ location: "active", unsettledOnly: true });
+ assert.deepEqual(new Set(shell.threads.map((thread) => thread.id)), new Set([open, reopened]));
+ assert.equal(shell.archivedThreads.length, 0);
+ const all = yield* store.getShellSnapshot({ location: "active" });
+ assert.equal(all.threads.length, 4);
+ }).pipe(Effect.provide(testLayer)),
+);
it.effect(
"reads settlement candidates and thread metadata without loading historical or archived payloads",
diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
index f1470125a88..7b73b7d7f1d 100644
--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
@@ -724,8 +724,9 @@ layer("ProviderEventIngestorV2", (it) => {
}),
);
- for (const terminal of ["completed", "interrupted", "failed", "cancelled", "control"] as const) {
- it.effect(`dismisses only native questions when a provider turn ends with ${terminal}`, () =>
+ it.effect.each(["completed", "interrupted", "failed", "cancelled", "control"] as const)(
+ "dismisses only native questions when a provider turn ends with %s",
+ (terminal) =>
Effect.gen(function* () {
const now = yield* DateTime.now;
const eventSink = yield* EventSink.EventSinkV2;
@@ -909,8 +910,7 @@ layer("ProviderEventIngestorV2", (it) => {
const repeated = yield* ingestor.ingestNormalized(input);
assert.isFalse(repeated.some((entry) => entry.event.type === "runtime-request.updated"));
}),
- );
- }
+ );
it.effect(
"preserves an answer committed after terminal normalization reads a pending question",
diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
index 63d4c57fb66..46c4695bad1 100644
--- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
@@ -3007,8 +3007,9 @@ it.effect(
}),
);
-for (const workspaceState of ["missing", "file"] as const) {
- it.effect(`rejects a ${workspaceState} workspace before opening a provider session`, () =>
+it.effect.each(["missing", "file"] as const)(
+ "rejects a %s workspace before opening a provider session",
+ (workspaceState) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const root = yield* fileSystem.makeTempDirectoryScoped();
@@ -3053,8 +3054,7 @@ for (const workspaceState of ["missing", "file"] as const) {
);
}).pipe(Effect.provide(makeTestLayer({ state, idleTimeoutMs: 60_000 })));
}).pipe(Effect.provide(NodeServices.layer)),
- );
-}
+);
it.effect(
"rejects a deleted workspace before reusing a live session without changing its state",
diff --git a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
index b3a9fe9d617..d946bcd1976 100644
--- a/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderSwitchService.test.ts
@@ -120,32 +120,30 @@ it.effect(
),
);
-for (const deadStatus of ["stopped", "error"] as const) {
- it.effect(
- `restarts and releases the live session when a newer ${deadStatus} session exists`,
- () =>
- Effect.gen(function* () {
- const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
- const thread = projection();
- const result = yield* service.plan({
- projection: {
- ...thread,
- providerSessions: [
- ...thread.providerSessions,
- deadSessionRecord("dead_session", deadStatus),
- ],
- },
- targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
- });
- assert.equal(result.transition.type, "restart_and_resume");
- assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
- }).pipe(
- Effect.provide(
- testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
- ),
+it.effect.each(["stopped", "error"] as const)(
+ "restarts and releases the live session when a newer %s session exists",
+ (deadStatus) =>
+ Effect.gen(function* () {
+ const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
+ const thread = projection();
+ const result = yield* service.plan({
+ projection: {
+ ...thread,
+ providerSessions: [
+ ...thread.providerSessions,
+ deadSessionRecord("dead_session", deadStatus),
+ ],
+ },
+ targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
+ });
+ assert.equal(result.transition.type, "restart_and_resume");
+ assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
+ }).pipe(
+ Effect.provide(
+ testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
),
- );
-}
+ ),
+);
it.effect("releases the newest live session, not the newest record overall", () =>
Effect.gen(function* () {
@@ -275,32 +273,29 @@ it.effect("hands off from a native provider thread after its session detaches",
),
);
-for (const deadStatus of ["stopped", "error"] as const) {
- it.effect(
- `applies a model change on next turn when a ${deadStatus} session negotiated model switching`,
- () =>
- Effect.gen(function* () {
- const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
- const result = yield* service.plan({
- projection: deadNativeThreadProjection(deadStatus, CodexProviderCapabilitiesV2),
- targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
- });
- // Static capabilities report no in-session switch, but the dead
- // record's negotiated capabilities describe the provider: without
- // them the ACP classification rejects the selection instead of
- // reopening with the requested model on the next run.
- assert.equal(result.transition.type, "switch_model_in_session");
- assert.deepEqual(result.releaseProviderSessionIds, []);
- }).pipe(
- Effect.provide(
- testLayer(
- { [currentInstanceId]: { continuationKey: "codex:account:primary" } },
- (input) => Effect.succeed(acpSelectionTransition(input)),
- ),
+it.effect.each(["stopped", "error"] as const)(
+ "applies a model change on next turn when a %s session negotiated model switching",
+ (deadStatus) =>
+ Effect.gen(function* () {
+ const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
+ const result = yield* service.plan({
+ projection: deadNativeThreadProjection(deadStatus, CodexProviderCapabilitiesV2),
+ targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
+ });
+ // Static capabilities report no in-session switch, but the dead
+ // record's negotiated capabilities describe the provider: without
+ // them the ACP classification rejects the selection instead of
+ // reopening with the requested model on the next run.
+ assert.equal(result.transition.type, "switch_model_in_session");
+ assert.deepEqual(result.releaseProviderSessionIds, []);
+ }).pipe(
+ Effect.provide(
+ testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }, (input) =>
+ Effect.succeed(acpSelectionTransition(input)),
),
),
- );
-}
+ ),
+);
it.effect("rejects a model change the dead record never negotiated support for", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts
index f43f4cd0166..c282fa7a26d 100644
--- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts
+++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts
@@ -259,67 +259,65 @@ it.effect("does not continue a failed run that lost background work", () =>
}),
);
-for (const [enabled, projectOverride] of [
+it.effect.each([
[false, undefined],
[true, undefined],
[false, true],
[true, false],
-] as const) {
- it.effect(
- `atomically records restart intent with cancellation when opt-in is ${enabled} and project override is ${projectOverride}`,
- () =>
- Effect.gen(function* () {
- let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
- const recovery = yield* ProviderRuntimeRecovery.make.pipe(
- Effect.provide(
- Layer.mergeAll(
- ServerSettings.layerTest({
- continueThreadsAfterServerUpdate: enabled,
- projectSettingsOverrides:
- projectOverride === undefined
- ? {}
- : {
- [ProjectId.make("restart-project")]: {
- continueThreadsAfterServerUpdate: projectOverride,
- },
+] as const)(
+ "atomically records restart intent with cancellation when opt-in is %s and project override is %s",
+ ([enabled, projectOverride]) =>
+ Effect.gen(function* () {
+ let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
+ const recovery = yield* ProviderRuntimeRecovery.make.pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ ServerSettings.layerTest({
+ continueThreadsAfterServerUpdate: enabled,
+ projectSettingsOverrides:
+ projectOverride === undefined
+ ? {}
+ : {
+ [ProjectId.make("restart-project")]: {
+ continueThreadsAfterServerUpdate: projectOverride,
},
- }),
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getRecoveryThreadIds: () => Effect.succeed([threadId]),
- getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
- }),
- Layer.mock(EventSink.EventSinkV2)({
- commitCommand: (input) => {
- committed = input;
- return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
- },
- }),
- IdAllocator.layer,
- Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
- runRecoveryOnce: Effect.succeed(false),
- }),
- Layer.mock(EffectOutbox.EffectOutboxV2)({
- reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
- }),
- ),
- ),
- );
- yield* recovery.reconcile("startup");
- assert.isDefined(committed);
- assert.isTrue(
- committed!.events.some(
- (event) => event.type === "run.updated" && event.payload.status === "cancelled",
+ },
+ }),
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getRecoveryThreadIds: () => Effect.succeed([threadId]),
+ getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
+ }),
+ Layer.mock(EventSink.EventSinkV2)({
+ commitCommand: (input) => {
+ committed = input;
+ return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
+ },
+ }),
+ IdAllocator.layer,
+ Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
+ runRecoveryOnce: Effect.succeed(false),
+ }),
+ Layer.mock(EffectOutbox.EffectOutboxV2)({
+ reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
+ }),
),
- );
- assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
- if (projectOverride ?? enabled)
- assert.deepEqual(committed!.effects[0]?.request, {
- type: "provider-runtime.continue",
- sourceRunId: runId,
- });
- }),
- );
-}
+ ),
+ );
+ yield* recovery.reconcile("startup");
+ assert.isDefined(committed);
+ assert.isTrue(
+ committed!.events.some(
+ (event) => event.type === "run.updated" && event.payload.status === "cancelled",
+ ),
+ );
+ assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
+ if (projectOverride ?? enabled)
+ assert.deepEqual(committed!.effects[0]?.request, {
+ type: "provider-runtime.continue",
+ sourceRunId: runId,
+ });
+ }),
+);
it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
index ec292a02b86..370c3005834 100644
--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts
+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts
@@ -862,8 +862,9 @@ it.effect("starts the provider when checkpoint baseline capture fails", () =>
}),
);
-for (const scenario of ["failure", "interruption", "stale-attempt", "start-guard"] as const) {
- it.effect(`handles ${scenario} before the provider turn starts`, () =>
+it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as const)(
+ "handles %s before the provider turn starts",
+ (scenario) =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread:run-execution-settings-failure");
const runId = RunId.make("run:run-execution-settings-failure");
@@ -1030,8 +1031,7 @@ for (const scenario of ["failure", "interruption", "stale-attempt", "start-guard
assert.equal(errorItem.payload.failure.message, "Run preparation failed.");
}
}),
- );
-}
+);
it.effect("keeps ingesting owned child events after the root turn terminalizes", () =>
Effect.gen(function* () {
@@ -3149,8 +3149,9 @@ it.effect("emits run_interrupt_result when hard-stop finalizes the active attemp
}),
);
-for (const status of ["completed", "interrupted", "cancelled", "failed"] as const) {
- it.effect(`refreshes pull requests after the current root run ${status}`, () =>
+it.effect.each(["completed", "interrupted", "cancelled", "failed"] as const)(
+ "refreshes pull requests after the current root run %s",
+ (status) =>
Effect.gen(function* () {
const { observed } = yield* captureRootRunTermination({
key: `pull-request-refresh:${status}`,
@@ -3162,8 +3163,7 @@ for (const status of ["completed", "interrupted", "cancelled", "failed"] as cons
"pull-requests-refreshed",
]);
}),
- );
-}
+);
it.effect("does not refresh pull requests for auxiliary or stale provider terminals", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts
index 31b0039876c..a2e8f50901f 100644
--- a/apps/server/src/orchestration-v2/RunFinalizationService.test.ts
+++ b/apps/server/src/orchestration-v2/RunFinalizationService.test.ts
@@ -50,80 +50,82 @@ it.effect("refreshes workspace after checkpoint capture without reading history"
}).pipe(Effect.provide(layer));
});
-for (const scenario of [
- {
- label: "discovers a new PR for the completed run's branch",
- branch: "feature",
- checkedOut: "feature",
- activeRun: null,
- expected: ["/repo"],
- },
- {
- label: "leaves the default branch's PR cache alone",
- branch: "main",
- checkedOut: "main",
- activeRun: null,
- expected: [],
- },
- {
- label: "does not refresh another thread's checkout",
- branch: "feature",
- checkedOut: "other",
- activeRun: null,
- expected: [],
- },
- {
- label: "does not refresh during a newer active run",
- branch: "feature",
- checkedOut: "feature",
- activeRun: "newer-run",
- expected: [],
- },
-] as const) {
- it.effect(scenario.label, () => {
- const refreshed: string[] = [];
- const threadId = ThreadId.make("thread-pr-refresh");
- const runId = RunId.make("completed-run");
- const layer = RunFinalization.observerLive.pipe(
- Layer.provide(
- Layer.mergeAll(
- Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
- Layer.mock(PullRequestService.PullRequestService)({
- refreshAfterTurn: () => Effect.void,
- }),
- Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
- refreshLocalStatus: () =>
- Effect.succeed({
- isRepo: true,
- hasPrimaryRemote: true,
- isDefaultRef: scenario.checkedOut === "main",
- refName: scenario.checkedOut,
- hasWorkingTreeChanges: false,
- workingTree: { files: [], insertions: 0, deletions: 0 },
- }),
- refreshStatus: () =>
- Effect.die("turn completion must preserve known PRs and lookup backoff"),
- refreshPullRequestStatus: (cwd) =>
- Effect.sync(() => {
- refreshed.push(cwd);
- return null;
- }),
- }),
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
- getThreadShell: () =>
- Effect.succeed({
- id: threadId,
- branch: scenario.branch,
- activeRunId: scenario.activeRun === null ? null : RunId.make(scenario.activeRun),
- } as OrchestrationV2ThreadShell),
- }),
- ),
+it.effect.each(
+ (
+ [
+ {
+ label: "discovers a new PR for the completed run's branch",
+ branch: "feature",
+ checkedOut: "feature",
+ activeRun: null,
+ expected: ["/repo"],
+ },
+ {
+ label: "leaves the default branch's PR cache alone",
+ branch: "main",
+ checkedOut: "main",
+ activeRun: null,
+ expected: [],
+ },
+ {
+ label: "does not refresh another thread's checkout",
+ branch: "feature",
+ checkedOut: "other",
+ activeRun: null,
+ expected: [],
+ },
+ {
+ label: "does not refresh during a newer active run",
+ branch: "feature",
+ checkedOut: "feature",
+ activeRun: "newer-run",
+ expected: [],
+ },
+ ] as const
+ ).map((scenario) => [scenario.label, scenario] as const),
+)("%s", ([, scenario]) => {
+ const refreshed: string[] = [];
+ const threadId = ThreadId.make("thread-pr-refresh");
+ const runId = RunId.make("completed-run");
+ const layer = RunFinalization.observerLive.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.mock(WorkspaceEntries.WorkspaceEntries)({ refresh: () => Effect.void }),
+ Layer.mock(PullRequestService.PullRequestService)({
+ refreshAfterTurn: () => Effect.void,
+ }),
+ Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({
+ refreshLocalStatus: () =>
+ Effect.succeed({
+ isRepo: true,
+ hasPrimaryRemote: true,
+ isDefaultRef: scenario.checkedOut === "main",
+ refName: scenario.checkedOut,
+ hasWorkingTreeChanges: false,
+ workingTree: { files: [], insertions: 0, deletions: 0 },
+ }),
+ refreshStatus: () =>
+ Effect.die("turn completion must preserve known PRs and lookup backoff"),
+ refreshPullRequestStatus: (cwd) =>
+ Effect.sync(() => {
+ refreshed.push(cwd);
+ return null;
+ }),
+ }),
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getThreadShell: () =>
+ Effect.succeed({
+ id: threadId,
+ branch: scenario.branch,
+ activeRunId: scenario.activeRun === null ? null : RunId.make(scenario.activeRun),
+ } as OrchestrationV2ThreadShell),
+ }),
),
- );
- return Effect.gen(function* () {
- const observer = yield* RunFinalization.RunFinalizationObserver;
- yield* observer.refresh({ cwd: "/repo", threadId, runId });
- assert.deepEqual(refreshed, [...scenario.expected]);
- }).pipe(Effect.provide(layer));
- });
-}
+ ),
+ );
+ return Effect.gen(function* () {
+ const observer = yield* RunFinalization.RunFinalizationObserver;
+ yield* observer.refresh({ cwd: "/repo", threadId, runId });
+ assert.deepEqual(refreshed, [...scenario.expected]);
+ }).pipe(Effect.provide(layer));
+});
diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
index 414478b3906..012fb9c3c7a 100644
--- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
@@ -537,176 +537,174 @@ it.live("restarts selection as a new attempt and retries after old-session clean
),
);
-for (const deadStatus of ["stopped", "error"] as const) {
- it.live(
- `restarts the live session on a model change when a newer ${deadStatus} session record exists`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const name = `selection-restart-dead-${deadStatus}`;
- const cwd = yield* checkpointWorkspace(name);
- const threadId = ThreadId.make(`thread:${name}`);
- const state = yield* Ref.make<RestartAdapterState>({
- activeTurn: null,
- opened: [],
- started: [],
- closedSessionCount: 0,
- // The dead record is seeded directly, so the adapter's one-shot
- // simulated replacement-open failure is skipped.
- failedReplacementOpen: true,
- });
- const registry = ProviderAdapterRegistry.makeSingleLayer(
- makeRestartAdapter(state, exclusiveCapabilities),
- );
+it.live.each(["stopped", "error"] as const)(
+ "restarts the live session on a model change when a newer %s session record exists",
+ (deadStatus) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const name = `selection-restart-dead-${deadStatus}`;
+ const cwd = yield* checkpointWorkspace(name);
+ const threadId = ThreadId.make(`thread:${name}`);
+ const state = yield* Ref.make<RestartAdapterState>({
+ activeTurn: null,
+ opened: [],
+ started: [],
+ closedSessionCount: 0,
+ // The dead record is seeded directly, so the adapter's one-shot
+ // simulated replacement-open failure is skipped.
+ failedReplacementOpen: true,
+ });
+ const registry = ProviderAdapterRegistry.makeSingleLayer(
+ makeRestartAdapter(state, exclusiveCapabilities),
+ );
- const result = yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const eventSink = yield* EventSink.EventSinkV2;
- const dispatch = (step: string, modelSelection: ModelSelection) =>
- Effect.gen(function* () {
- const terminal = yield* orchestrator.streamDomainEvents.pipe(
- Stream.filter(
- (event) => event.type === "run.updated" && event.payload.status === "completed",
- ),
- Stream.take(1),
- Stream.runDrain,
- Effect.forkScoped,
- );
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`${name}:${step}`),
- threadId,
- messageId: MessageId.make(`${name}:${step}`),
- text: step,
- attachments: [],
- modelSelection,
- dispatchMode: { type: "start_immediately" },
- });
- yield* worker.drain();
- yield* Fiber.join(terminal);
- yield* worker.drain();
- return yield* orchestrator.getThreadProjection(threadId);
+ const result = yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const dispatch = (step: string, modelSelection: ModelSelection) =>
+ Effect.gen(function* () {
+ const terminal = yield* orchestrator.streamDomainEvents.pipe(
+ Stream.filter(
+ (event) => event.type === "run.updated" && event.payload.status === "completed",
+ ),
+ Stream.take(1),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${name}:${step}`),
+ threadId,
+ messageId: MessageId.make(`${name}:${step}`),
+ text: step,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
});
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`${name}:create`),
- threadId,
- projectId: ProjectId.make(`project:${name}`),
- title: name,
- modelSelection: seedSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: cwd,
+ yield* worker.drain();
+ yield* Fiber.join(terminal);
+ yield* worker.drain();
+ return yield* orchestrator.getThreadProjection(threadId);
});
- const first = yield* dispatch("first", seedSelection);
- const liveSession = first.providerSessions.find(
- (session) => session.status !== "stopped" && session.status !== "error",
- );
- assert.isDefined(liveSession);
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${name}:create`),
+ threadId,
+ projectId: ProjectId.make(`project:${name}`),
+ title: name,
+ modelSelection: seedSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ });
+ const first = yield* dispatch("first", seedSelection);
+ const liveSession = first.providerSessions.find(
+ (session) => session.status !== "stopped" && session.status !== "error",
+ );
+ assert.isDefined(liveSession);
- // Dead session records stay bound in the projection until
- // detachment. A stale stopped/error record written after the
- // live session attached must not hide it.
- const deadAt = yield* DateTime.now;
- const deadSession: OrchestrationV2ProviderSession = {
- id: ProviderSessionId.make(`session:${name}:dead`),
- driver,
- providerInstanceId,
- status: "ready",
- cwd,
- model: seedSelection.model,
- capabilities: exclusiveCapabilities,
- createdAt: deadAt,
- updatedAt: deadAt,
- lastError: null,
- };
- yield* eventSink.write({
- events: [
- {
- id: EventId.make(`event:${name}:dead-attached`),
- type: "provider-session.attached",
- threadId,
- driver,
- providerInstanceId,
- occurredAt: deadAt,
- payload: deadSession,
- },
- {
- id: EventId.make(`event:${name}:dead-updated`),
- type: "provider-session.updated",
- threadId,
- driver,
- providerInstanceId,
- occurredAt: deadAt,
- payload: {
- ...deadSession,
- status: deadStatus,
- updatedAt: deadAt,
- lastError: deadStatus === "error" ? "Simulated session failure." : null,
- },
+ // Dead session records stay bound in the projection until
+ // detachment. A stale stopped/error record written after the
+ // live session attached must not hide it.
+ const deadAt = yield* DateTime.now;
+ const deadSession: OrchestrationV2ProviderSession = {
+ id: ProviderSessionId.make(`session:${name}:dead`),
+ driver,
+ providerInstanceId,
+ status: "ready",
+ cwd,
+ model: seedSelection.model,
+ capabilities: exclusiveCapabilities,
+ createdAt: deadAt,
+ updatedAt: deadAt,
+ lastError: null,
+ };
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`event:${name}:dead-attached`),
+ type: "provider-session.attached",
+ threadId,
+ driver,
+ providerInstanceId,
+ occurredAt: deadAt,
+ payload: deadSession,
+ },
+ {
+ id: EventId.make(`event:${name}:dead-updated`),
+ type: "provider-session.updated",
+ threadId,
+ driver,
+ providerInstanceId,
+ occurredAt: deadAt,
+ payload: {
+ ...deadSession,
+ status: deadStatus,
+ updatedAt: deadAt,
+ lastError: deadStatus === "error" ? "Simulated session failure." : null,
},
- ],
- });
+ },
+ ],
+ });
- const switchCommandId = CommandId.make(`${name}:switch`);
- yield* orchestrator.dispatch({
- type: "thread.model-selection.set",
- commandId: switchCommandId,
- threadId,
- modelSelection: replacementSelection,
- });
- yield* worker.drain();
- const storedSwitchEvents = yield* eventSink
- .readByCommandId({ commandId: switchCommandId })
- .pipe(Stream.runCollect);
- const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
- stored.event.type === "provider-session.detached"
- ? [stored.event.payload.providerSessionId]
- : [],
- );
+ const switchCommandId = CommandId.make(`${name}:switch`);
+ yield* orchestrator.dispatch({
+ type: "thread.model-selection.set",
+ commandId: switchCommandId,
+ threadId,
+ modelSelection: replacementSelection,
+ });
+ yield* worker.drain();
+ const storedSwitchEvents = yield* eventSink
+ .readByCommandId({ commandId: switchCommandId })
+ .pipe(Stream.runCollect);
+ const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
+ stored.event.type === "provider-session.detached"
+ ? [stored.event.payload.providerSessionId]
+ : [],
+ );
- const second = yield* dispatch("second", replacementSelection);
- return {
- projection: second,
- captured: yield* Ref.get(state),
- liveSessionId: liveSession.id,
- detachedSessionIds,
- };
- }).pipe(Effect.provide(makeOrchestratorV2ReplayLayerWithRegistry({ name }, registry)));
+ const second = yield* dispatch("second", replacementSelection);
+ return {
+ projection: second,
+ captured: yield* Ref.get(state),
+ liveSessionId: liveSession.id,
+ detachedSessionIds,
+ };
+ }).pipe(Effect.provide(makeOrchestratorV2ReplayLayerWithRegistry({ name }, registry)));
- const { projection, captured } = result;
- assert.lengthOf(projection.runs, 2);
- assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
- // The exact released session is the older live one, never the newer
- // dead record.
- assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
- assert.equal(captured.closedSessionCount, 1);
- assert.deepEqual(
- captured.opened.map((open) => open.model),
- [seedSelection.model, replacementSelection.model],
- );
- assert.deepEqual(
- captured.started.map((turn) => turn.model),
- [seedSelection.model, replacementSelection.model],
- );
- const servingSession = projection.providerSessions.find(
- (session) =>
- session.id ===
- projection.providerThreads.find(
- (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
- )?.providerSessionId,
- );
- assert.equal(servingSession?.model, replacementSelection.model);
- }),
- ),
- );
-}
+ const { projection, captured } = result;
+ assert.lengthOf(projection.runs, 2);
+ assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
+ // The exact released session is the older live one, never the newer
+ // dead record.
+ assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
+ assert.equal(captured.closedSessionCount, 1);
+ assert.deepEqual(
+ captured.opened.map((open) => open.model),
+ [seedSelection.model, replacementSelection.model],
+ );
+ assert.deepEqual(
+ captured.started.map((turn) => turn.model),
+ [seedSelection.model, replacementSelection.model],
+ );
+ const servingSession = projection.providerSessions.find(
+ (session) =>
+ session.id ===
+ projection.providerThreads.find(
+ (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
+ )?.providerSessionId,
+ );
+ assert.equal(servingSession?.model, replacementSelection.model);
+ }),
+ ),
+);
it.live("detaches the old provider session after an active provider handoff", () =>
Effect.scoped(
@@ -822,8 +820,9 @@ it.live("detaches the old provider session after an active provider handoff", ()
),
);
-for (const mode of ["active", "idle", "selection-command", "pooled", "separate-home"] as const) {
- it.live(`preserves native history only for compatible account switches (${mode})`, () =>
+it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
+ "preserves native history only for compatible account switches (%s)",
+ (mode) =>
Effect.scoped(
Effect.gen(function* () {
const name = `shared-home-${mode}`;
@@ -994,5 +993,4 @@ for (const mode of ["active", "idle", "selection-command", "pooled", "separate-h
}).pipe(Effect.provide(makeOrchestratorV2ReplayLayerWithRegistry({ name }, registry)));
}),
),
- );
-}
+);
diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
index 6a360dd8b6b..6a8dded63ca 100644
--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
@@ -37,371 +37,373 @@ const driver = ProviderDriverKind.make("codex");
const instanceId = ProviderInstanceId.make("codex");
const modelSelection = { instanceId, model: "test-model" };
-for (const mailbox of [false, true]) {
- for (const timing of [
- "before delivery",
- "during delivery",
- "before dispatch",
- "after delivery",
- "without native steering",
- "settled only",
- ] as const) {
- if (!mailbox && (timing === "without native steering" || timing === "settled only")) continue;
- it.effect(
- `delivers ${mailbox ? "mailbox notification" : "steering"} when completion wins ${timing}`,
- () =>
- Effect.scoped(
+it.effect.each(
+ [false, true]
+ .flatMap((mailbox) =>
+ (
+ [
+ "before delivery",
+ "during delivery",
+ "before dispatch",
+ "after delivery",
+ "without native steering",
+ "settled only",
+ ] as const
+ ).map((timing) => ({
+ mailbox,
+ timing,
+ label: mailbox ? "mailbox notification" : "steering",
+ })),
+ )
+ .filter(
+ ({ mailbox, timing }) =>
+ mailbox || (timing !== "without native steering" && timing !== "settled only"),
+ ),
+)("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
+ const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
+ const started: ProviderAdapterV2TurnInput[] = [];
+ const steerEntered = yield* Deferred.make<void>();
+ const rejectSteer = yield* Deferred.make<void>();
+ let steerCalls = 0;
+ const capabilities = {
+ ...CodexProviderCapabilitiesV2,
+ turns: {
+ ...CodexProviderCapabilitiesV2.turns,
+ supportsActiveSteering: timing !== "without native steering",
+ },
+ };
+ const adapter: ProviderAdapterV2Shape = {
+ instanceId,
+ driver,
+ getCapabilities: () => Effect.succeed(capabilities),
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
+ openSession: (input) =>
Effect.gen(function* () {
- const cwd = yield* checkpointWorkspace(
- `steering-completion-${timing.replaceAll(" ", "-")}`,
- );
- const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
- const started: ProviderAdapterV2TurnInput[] = [];
- const steerEntered = yield* Deferred.make<void>();
- const rejectSteer = yield* Deferred.make<void>();
- let steerCalls = 0;
- const capabilities = {
- ...CodexProviderCapabilitiesV2,
- turns: {
- ...CodexProviderCapabilitiesV2.turns,
- supportsActiveSteering: timing !== "without native steering",
- },
- };
- const adapter: ProviderAdapterV2Shape = {
+ const now = yield* DateTime.now;
+ return {
instanceId,
driver,
- getCapabilities: () => Effect.succeed(capabilities),
- planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
- openSession: (input) =>
+ providerSessionId: input.providerSessionId,
+ providerSession: {
+ id: input.providerSessionId,
+ driver,
+ providerInstanceId: instanceId,
+ status: "ready",
+ cwd,
+ model: modelSelection.model,
+ capabilities,
+ createdAt: now,
+ updatedAt: now,
+ lastError: null,
+ },
+ events: Stream.fromQueue(events),
+ ensureThread: ({ threadId }) =>
+ Effect.succeed({
+ id: ProviderThreadId.make(`provider-thread:${threadId}`),
+ driver,
+ providerInstanceId: instanceId,
+ providerSessionId: input.providerSessionId,
+ appThreadId: threadId,
+ ownerNodeId: null,
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
+ nativeConversationHeadRef: null,
+ status: "idle",
+ firstRunOrdinal: null,
+ lastRunOrdinal: null,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ }),
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
+ startTurn: (turn) =>
Effect.gen(function* () {
- const now = yield* DateTime.now;
- return {
- instanceId,
+ started.push(turn);
+ yield* Queue.offer(events, {
+ type: "provider_turn.updated",
driver,
- providerSessionId: input.providerSessionId,
- providerSession: {
- id: input.providerSessionId,
- driver,
- providerInstanceId: instanceId,
- status: "ready",
- cwd,
- model: modelSelection.model,
- capabilities,
- createdAt: now,
- updatedAt: now,
- lastError: null,
- },
- events: Stream.fromQueue(events),
- ensureThread: ({ threadId }) =>
- Effect.succeed({
- id: ProviderThreadId.make(`provider-thread:${threadId}`),
+ providerTurn: {
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
+ providerThreadId: turn.providerThread.id,
+ nodeId: turn.rootNodeId,
+ runAttemptId: turn.attemptId,
+ nativeTurnRef: {
driver,
- providerInstanceId: instanceId,
- providerSessionId: input.providerSessionId,
- appThreadId: threadId,
- ownerNodeId: null,
- nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
- nativeConversationHeadRef: null,
- status: "idle",
- firstRunOrdinal: null,
- lastRunOrdinal: null,
- handoffIds: [],
- forkedFrom: null,
- createdAt: now,
- updatedAt: now,
- }),
- resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
- startTurn: (turn) =>
- Effect.gen(function* () {
- started.push(turn);
- yield* Queue.offer(events, {
- type: "provider_turn.updated",
- driver,
- providerTurn: {
- id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
- providerThreadId: turn.providerThread.id,
- nodeId: turn.rootNodeId,
- runAttemptId: turn.attemptId,
- nativeTurnRef: {
- driver,
- nativeId: `native:${turn.attemptId}`,
- strength: "strong",
- },
- ordinal: turn.providerTurnOrdinal,
- status: "running",
- startedAt: now,
- completedAt: null,
- },
- });
- }),
- steerTurn: (turn) =>
- Effect.gen(function* () {
- steerCalls += 1;
- if (timing === "after delivery") return;
- yield* Deferred.succeed(steerEntered, undefined);
- yield* Deferred.await(rejectSteer);
- return yield* new ProviderAdapterSteerRunError({
- driver,
- providerThreadId: turn.providerThread.id,
- providerTurnId: turn.providerTurnId,
- cause: "turn already completed",
- });
- }),
- interruptTurn: () => Effect.void,
- respondToRuntimeRequest: () => Effect.void,
- readThreadSnapshot: () => Effect.die("unused"),
- rollbackThread: () => Effect.die("unused"),
- forkThread: () => Effect.die("unused"),
- };
- }),
- };
- yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const threadId = ThreadId.make("thread:steering-completion");
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
- orchestrator.streamDomainEvents.pipe(
- Stream.filter(predicate),
- Stream.take(1),
- Stream.runDrain,
- Effect.forkScoped,
- );
- yield* orchestrator.dispatch({
- type: "thread.create",
- commandId: CommandId.make("create"),
- threadId,
- projectId: ProjectId.make("project:steering-completion"),
- title: "Steering race",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: cwd,
- createdBy: "user",
- creationSource: "web",
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make("first"),
- threadId,
- messageId: MessageId.make("message:first"),
- text: "first",
- attachments: [],
- dispatchMode: { type: "start_immediately" },
- createdBy: "user",
- creationSource: "web",
- });
- const running = yield* watch(
- (event) =>
- event.type === "provider-turn.updated" && event.payload.status === "running",
- );
- yield* worker.drain();
- yield* Fiber.join(running);
- const first = started[0]!;
- const messageId = MessageId.make("message:steering");
- const taskId = NodeId.make("task:mailbox");
- if (mailbox) {
- const sink = yield* EventSink.EventSinkV2;
- const current = yield* orchestrator.getThreadProjection(threadId);
- const parentRun = current.runs.find((run) => run.id === first.runId)!;
- const now = yield* DateTime.now;
- yield* sink.write({
- events: [
- {
- id: EventId.make("mailbox:cohort"),
- type: "run.updated",
- threadId,
- runId: first.runId,
- occurredAt: now,
- payload: {
- ...parentRun,
- delegatedCompletion: {
- disposition: "open",
- nextGeneration: 2,
- delivery: { generation: 1, messageId, taskIds: [taskId] },
- },
+ nativeId: `native:${turn.attemptId}`,
+ strength: "strong",
},
+ ordinal: turn.providerTurnOrdinal,
+ status: "running",
+ startedAt: now,
+ completedAt: null,
},
- {
- id: EventId.make("mailbox:task"),
- type: "subagent.updated",
- threadId,
- runId: first.runId,
- nodeId: taskId,
- occurredAt: now,
- payload: {
- id: taskId,
- threadId,
- runId: first.runId,
- parentNodeId: first.rootNodeId,
- origin: "app_owned",
- createdBy: "agent",
- driver,
- providerInstanceId: instanceId,
- providerThreadId: null,
- childThreadId: null,
- nativeTaskRef: null,
- prompt: "Do background work",
- title: "Background test",
- model: null,
- completionWake: timing === "settled only" ? "settled_only" : "always",
- completionDelivery: { state: "claimed", observedByRunId: null },
- status: "completed",
- result: "done",
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- },
- },
- ],
- });
- }
- const dispatchSteer = orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make("steer"),
- threadId,
- messageId,
- text: "fix the popover",
- attachments: [
- {
- type: "image",
- id: "steering-screenshot",
- name: "image.png",
- mimeType: "image/png",
- sizeBytes: 10,
- },
- ],
- dispatchMode: mailbox
- ? { type: "queue_after_active" }
- : { type: "steer_active", targetRunId: first.runId },
- createdBy: mailbox ? "agent" : "user",
- creationSource: mailbox ? "server" : "web",
- ...(mailbox
- ? {
- delegatedCompletion: {
- parentRunId: first.runId,
- generation: 1,
- taskIds: [taskId],
- },
- }
- : {}),
- });
- if (timing !== "before dispatch") yield* dispatchSteer;
- if (timing === "after delivery") yield* worker.drain();
- const delivery =
- timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
- if (delivery !== null) yield* Deferred.await(steerEntered);
- const completed = yield* watch(
- (event) =>
- event.type === "run.updated" &&
- event.payload.id === first.runId &&
- event.payload.status === "waiting",
- );
- const projection = yield* orchestrator.getThreadProjection(threadId);
- const turn = projection.providerTurns[0]!;
- yield* Queue.offer(events, {
- type: "provider_turn.updated",
- driver,
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
- });
- yield* Queue.offer(events, {
- type: "turn.terminal",
- driver,
- providerThreadId: turn.providerThreadId,
- providerTurnId: turn.id,
- runOrdinal: first.runOrdinal,
- status: "completed",
- failure: null,
- threadDisposition: "reusable",
- });
- yield* Fiber.join(completed);
- if (delivery !== null) {
- yield* Deferred.succeed(rejectSteer, undefined);
- yield* Fiber.join(delivery);
- }
- if (timing === "before dispatch") yield* dispatchSteer;
- yield* worker.drain();
- yield* orchestrator.resumeQueuedRuns;
- yield* worker.drain();
- if (timing === "after delivery") {
- assert.equal(steerCalls, 1);
- assert.equal(started.length, 1);
- if (mailbox) {
- const delivered = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
- assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
- assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
- assert.equal(
- delivered.turnItems.filter((item) => item.type === "notification").length,
- 1,
- );
- yield* orchestrator.dispatch({
- type: "notification.delivery.accept",
- commandId: CommandId.make("duplicate-acceptance"),
- threadId,
- messageId,
});
- yield* worker.drain();
- assert.equal(steerCalls, 1);
- yield* orchestrator.dispatch({
- type: "delegated_task.completion-delivery.acknowledge",
- commandId: CommandId.make("read-result"),
- parentThreadId: threadId,
- taskId,
- observedByRunId: first.runId,
+ }),
+ steerTurn: (turn) =>
+ Effect.gen(function* () {
+ steerCalls += 1;
+ if (timing === "after delivery") return;
+ yield* Deferred.succeed(steerEntered, undefined);
+ yield* Deferred.await(rejectSteer);
+ return yield* new ProviderAdapterSteerRunError({
+ driver,
+ providerThreadId: turn.providerThread.id,
+ providerTurnId: turn.providerTurnId,
+ cause: "turn already completed",
});
- const acknowledged = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(
- acknowledged.subagents[0]?.completionDelivery?.state,
- "acknowledged",
- );
- }
- return;
- }
- assert.equal(started.length, 2);
- assert.equal(started[1]?.message.messageId, messageId);
- if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
- else assert.equal(started[1]?.message.text, "fix the popover");
- assert.deepEqual(started[1]?.message.attachments, [
- {
- type: "image",
- id: "steering-screenshot",
- name: "image.png",
- mimeType: "image/png",
- sizeBytes: 10,
+ }),
+ interruptTurn: () => Effect.void,
+ respondToRuntimeRequest: () => Effect.void,
+ readThreadSnapshot: () => Effect.die("unused"),
+ rollbackThread: () => Effect.die("unused"),
+ forkThread: () => Effect.die("unused"),
+ };
+ }),
+ };
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = ThreadId.make("thread:steering-completion");
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
+ orchestrator.streamDomainEvents.pipe(
+ Stream.filter(predicate),
+ Stream.take(1),
+ Stream.runDrain,
+ Effect.forkScoped,
+ );
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create"),
+ threadId,
+ projectId: ProjectId.make("project:steering-completion"),
+ title: "Steering race",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("first"),
+ threadId,
+ messageId: MessageId.make("message:first"),
+ text: "first",
+ attachments: [],
+ dispatchMode: { type: "start_immediately" },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const running = yield* watch(
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
+ );
+ yield* worker.drain();
+ yield* Fiber.join(running);
+ const first = started[0]!;
+ const messageId = MessageId.make("message:steering");
+ const taskId = NodeId.make("task:mailbox");
+ if (mailbox) {
+ const sink = yield* EventSink.EventSinkV2;
+ const current = yield* orchestrator.getThreadProjection(threadId);
+ const parentRun = current.runs.find((run) => run.id === first.runId)!;
+ const now = yield* DateTime.now;
+ yield* sink.write({
+ events: [
+ {
+ id: EventId.make("mailbox:cohort"),
+ type: "run.updated",
+ threadId,
+ runId: first.runId,
+ occurredAt: now,
+ payload: {
+ ...parentRun,
+ delegatedCompletion: {
+ disposition: "open",
+ nextGeneration: 2,
+ delivery: { generation: 1, messageId, taskIds: [taskId] },
+ },
+ },
+ },
+ {
+ id: EventId.make("mailbox:task"),
+ type: "subagent.updated",
+ threadId,
+ runId: first.runId,
+ nodeId: taskId,
+ occurredAt: now,
+ payload: {
+ id: taskId,
+ threadId,
+ runId: first.runId,
+ parentNodeId: first.rootNodeId,
+ origin: "app_owned",
+ createdBy: "agent",
+ driver,
+ providerInstanceId: instanceId,
+ providerThreadId: null,
+ childThreadId: null,
+ nativeTaskRef: null,
+ prompt: "Do background work",
+ title: "Background test",
+ model: null,
+ completionWake: timing === "settled only" ? "settled_only" : "always",
+ completionDelivery: { state: "claimed", observedByRunId: null },
+ status: "completed",
+ result: "done",
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
},
- ]);
- assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
- const final = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
- assert.equal(
- final.messages.find((message) => message.id === messageId)?.runId,
- started[1]?.runId,
- );
- assert.equal(
- final.turnItems.filter((item) =>
- mailbox
- ? item.type === "notification"
- : item.type === "user_message" && item.messageId === messageId,
- ).length,
- 1,
- );
- yield* worker.drain();
- assert.equal(started.length, 2);
- }).pipe(
- Effect.provide(
- makeOrchestratorV2ReplayLayerWithRegistry(
- { name: `steering-completion-${timing}` },
- ProviderAdapterRegistry.makeSingleLayer(adapter),
- { runEffectWorker: false },
- ),
- ),
+ },
+ ],
+ });
+ }
+ const dispatchSteer = orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("steer"),
+ threadId,
+ messageId,
+ text: "fix the popover",
+ attachments: [
+ {
+ type: "image",
+ id: "steering-screenshot",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 10,
+ },
+ ],
+ dispatchMode: mailbox
+ ? { type: "queue_after_active" }
+ : { type: "steer_active", targetRunId: first.runId },
+ createdBy: mailbox ? "agent" : "user",
+ creationSource: mailbox ? "server" : "web",
+ ...(mailbox
+ ? {
+ delegatedCompletion: {
+ parentRunId: first.runId,
+ generation: 1,
+ taskIds: [taskId],
+ },
+ }
+ : {}),
+ });
+ if (timing !== "before dispatch") yield* dispatchSteer;
+ if (timing === "after delivery") yield* worker.drain();
+ const delivery =
+ timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
+ if (delivery !== null) yield* Deferred.await(steerEntered);
+ const completed = yield* watch(
+ (event) =>
+ event.type === "run.updated" &&
+ event.payload.id === first.runId &&
+ event.payload.status === "waiting",
+ );
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ const turn = projection.providerTurns[0]!;
+ yield* Queue.offer(events, {
+ type: "provider_turn.updated",
+ driver,
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
+ });
+ yield* Queue.offer(events, {
+ type: "turn.terminal",
+ driver,
+ providerThreadId: turn.providerThreadId,
+ providerTurnId: turn.id,
+ runOrdinal: first.runOrdinal,
+ status: "completed",
+ failure: null,
+ threadDisposition: "reusable",
+ });
+ yield* Fiber.join(completed);
+ if (delivery !== null) {
+ yield* Deferred.succeed(rejectSteer, undefined);
+ yield* Fiber.join(delivery);
+ }
+ if (timing === "before dispatch") yield* dispatchSteer;
+ yield* worker.drain();
+ yield* orchestrator.resumeQueuedRuns;
+ yield* worker.drain();
+ if (timing === "after delivery") {
+ assert.equal(steerCalls, 1);
+ assert.equal(started.length, 1);
+ if (mailbox) {
+ const delivered = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
+ assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
+ assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
+ assert.equal(
+ delivered.turnItems.filter((item) => item.type === "notification").length,
+ 1,
);
- }),
+ yield* orchestrator.dispatch({
+ type: "notification.delivery.accept",
+ commandId: CommandId.make("duplicate-acceptance"),
+ threadId,
+ messageId,
+ });
+ yield* worker.drain();
+ assert.equal(steerCalls, 1);
+ yield* orchestrator.dispatch({
+ type: "delegated_task.completion-delivery.acknowledge",
+ commandId: CommandId.make("read-result"),
+ parentThreadId: threadId,
+ taskId,
+ observedByRunId: first.runId,
+ });
+ const acknowledged = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
+ }
+ return;
+ }
+ assert.equal(started.length, 2);
+ assert.equal(started[1]?.message.messageId, messageId);
+ if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
+ else assert.equal(started[1]?.message.text, "fix the popover");
+ assert.deepEqual(started[1]?.message.attachments, [
+ {
+ type: "image",
+ id: "steering-screenshot",
+ name: "image.png",
+ mimeType: "image/png",
+ sizeBytes: 10,
+ },
+ ]);
+ assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
+ const final = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
+ assert.equal(
+ final.messages.find((message) => message.id === messageId)?.runId,
+ started[1]?.runId,
+ );
+ assert.equal(
+ final.turnItems.filter((item) =>
+ mailbox
+ ? item.type === "notification"
+ : item.type === "user_message" && item.messageId === messageId,
+ ).length,
+ 1,
+ );
+ yield* worker.drain();
+ assert.equal(started.length, 2);
+ }).pipe(
+ Effect.provide(
+ makeOrchestratorV2ReplayLayerWithRegistry(
+ { name: `steering-completion-${timing}` },
+ ProviderAdapterRegistry.makeSingleLayer(adapter),
+ { runEffectWorker: false },
+ ),
),
- );
- }
-}
+ );
+ }),
+ ),
+);
// Claude and Pi steer live but cannot interrupt-and-restart, so a changed
// selection waits for the next turn as the thread's saved selection.
diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
index 63bc1550b20..1badbe8dccd 100644
--- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
@@ -25,7 +25,7 @@ import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
-for (const driverName of ["codex", "claudeAgent"] as const) {
+const forkCases = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
const driver = ProviderDriverKind.make(driverName);
const instanceId = ProviderInstanceId.make(driver);
const modelSelection = { instanceId, model: "test-model" };
@@ -45,199 +45,207 @@ for (const driverName of ["codex", "claudeAgent"] as const) {
{ runEffectWorker: false },
);
- for (const status of ["failed", "interrupted", "cancelled"] as const) {
- it.effect(`bounds ${driver} context when continuing a fork of a ${status} run`, () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const eventSink = yield* EventSink.EventSinkV2;
- const now = yield* DateTime.now;
- const sourceThreadId = ThreadId.make("fork-boundary-source");
- const targetThreadId = ThreadId.make("fork-boundary-target");
- const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
- const sourceRunId = RunId.make("fork-boundary-source-run");
- const attemptId = RunAttemptId.make("interrupted-source-attempt");
- const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
- const rootNodeId = NodeId.make("interrupted-source-root");
+ return (["failed", "interrupted", "cancelled"] as const).map((status) => ({
+ driver,
+ status,
+ instanceId,
+ modelSelection,
+ layer,
+ }));
+});
- yield* orchestrator.dispatch({
- type: "thread.create",
- commandId: CommandId.make("create-source"),
- threadId: sourceThreadId,
- projectId: ProjectId.make("fork-boundary-project"),
- title: "Fork boundary source",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- createdBy: "user",
- creationSource: "web",
- });
+it.effect.each(forkCases)(
+ "bounds $driver context when continuing a fork of a $status run",
+ ({ driver, status, instanceId, modelSelection, layer }) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ const sourceThreadId = ThreadId.make("fork-boundary-source");
+ const targetThreadId = ThreadId.make("fork-boundary-target");
+ const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
+ const sourceRunId = RunId.make("fork-boundary-source-run");
+ const attemptId = RunAttemptId.make("interrupted-source-attempt");
+ const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
+ const rootNodeId = NodeId.make("interrupted-source-root");
+
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("create-source"),
+ threadId: sourceThreadId,
+ projectId: ProjectId.make("fork-boundary-project"),
+ title: "Fork boundary source",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("source-provider-thread"),
+ type: "provider-thread.updated",
+ threadId: sourceThreadId,
+ occurredAt: now,
+ payload: {
+ id: providerThreadId,
+ driver,
+ providerInstanceId: instanceId,
+ providerSessionId: null,
+ appThreadId: sourceThreadId,
+ ownerNodeId: null,
+ nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
+ nativeConversationHeadRef: null,
+ status: "idle",
+ firstRunOrdinal: 1,
+ lastRunOrdinal: 2,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ },
+ ],
+ });
+ // A cancelled queue entry has no provider turn; an early interruption
+ // can have a turn but no native assistant cursor.
+ if (status === "interrupted") {
yield* eventSink.write({
events: [
{
- id: EventId.make("source-provider-thread"),
- type: "provider-thread.updated",
+ id: EventId.make("source-attempt"),
+ type: "run-attempt.created",
threadId: sourceThreadId,
+ runId: sourceRunId,
occurredAt: now,
payload: {
- id: providerThreadId,
- driver,
+ id: attemptId,
+ runId: sourceRunId,
+ attemptOrdinal: 1,
+ rootNodeId,
providerInstanceId: instanceId,
- providerSessionId: null,
- appThreadId: sourceThreadId,
- ownerNodeId: null,
- nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
- nativeConversationHeadRef: null,
- status: "idle",
- firstRunOrdinal: 1,
- lastRunOrdinal: 2,
- handoffIds: [],
- forkedFrom: null,
- createdAt: now,
- updatedAt: now,
+ providerThreadId,
+ providerTurnId,
+ reason: "initial",
+ status,
+ startedAt: now,
+ completedAt: now,
+ },
+ },
+ {
+ id: EventId.make("source-provider-turn"),
+ type: "provider-turn.updated",
+ threadId: sourceThreadId,
+ occurredAt: now,
+ payload: {
+ id: providerTurnId,
+ providerThreadId,
+ nodeId: rootNodeId,
+ runAttemptId: attemptId,
+ nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
+ ordinal: 1,
+ status,
+ startedAt: now,
+ completedAt: now,
},
},
],
});
- // A cancelled queue entry has no provider turn; an early interruption
- // can have a turn but no native assistant cursor.
- if (status === "interrupted") {
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("source-attempt"),
- type: "run-attempt.created",
- threadId: sourceThreadId,
- runId: sourceRunId,
- occurredAt: now,
- payload: {
- id: attemptId,
- runId: sourceRunId,
- attemptOrdinal: 1,
- rootNodeId,
- providerInstanceId: instanceId,
- providerThreadId,
- providerTurnId,
- reason: "initial",
- status,
- startedAt: now,
- completedAt: now,
- },
- },
- {
- id: EventId.make("source-provider-turn"),
- type: "provider-turn.updated",
- threadId: sourceThreadId,
- occurredAt: now,
- payload: {
- id: providerTurnId,
- providerThreadId,
- nodeId: rootNodeId,
- runAttemptId: attemptId,
- nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
- ordinal: 1,
- status,
- startedAt: now,
- completedAt: now,
- },
- },
- ],
- });
- }
- for (const ordinal of [1, 2]) {
- const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
- const messageId = MessageId.make(`source-message-${ordinal}`);
- yield* eventSink.write({
- events: [
- {
- id: EventId.make(`run-${ordinal}`),
- type: "run.created",
+ }
+ for (const ordinal of [1, 2]) {
+ const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
+ const messageId = MessageId.make(`source-message-${ordinal}`);
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`run-${ordinal}`),
+ type: "run.created",
+ threadId: sourceThreadId,
+ runId,
+ occurredAt: now,
+ payload: {
+ id: runId,
threadId: sourceThreadId,
- runId,
- occurredAt: now,
- payload: {
- id: runId,
- threadId: sourceThreadId,
- ordinal,
- providerInstanceId: instanceId,
- modelSelection,
- providerThreadId,
- userMessageId: messageId,
- rootNodeId: null,
- activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
- status: ordinal === 1 ? status : "completed",
- queuePosition: null,
- requestedAt: now,
- startedAt: now,
- completedAt: now,
- checkpointId: null,
- contextHandoffId: null,
- },
+ ordinal,
+ providerInstanceId: instanceId,
+ modelSelection,
+ providerThreadId,
+ userMessageId: messageId,
+ rootNodeId: null,
+ activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
+ status: ordinal === 1 ? status : "completed",
+ queuePosition: null,
+ requestedAt: now,
+ startedAt: now,
+ completedAt: now,
+ checkpointId: null,
+ contextHandoffId: null,
},
- {
- id: EventId.make(`item-${ordinal}`),
- type: "turn-item.updated",
+ },
+ {
+ id: EventId.make(`item-${ordinal}`),
+ type: "turn-item.updated",
+ threadId: sourceThreadId,
+ runId,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`item-${ordinal}`),
threadId: sourceThreadId,
runId,
- occurredAt: now,
- payload: {
- id: TurnItemId.make(`item-${ordinal}`),
- threadId: sourceThreadId,
- runId,
- nodeId: null,
- providerThreadId,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal,
- status: "completed",
- title: null,
- startedAt: now,
- completedAt: now,
- updatedAt: now,
- type: "user_message",
- createdBy: "user",
- creationSource: "web",
- inputIntent: "turn_start",
- messageId,
- text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
- attachments: [],
- },
+ nodeId: null,
+ providerThreadId,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal,
+ status: "completed",
+ title: null,
+ startedAt: now,
+ completedAt: now,
+ updatedAt: now,
+ type: "user_message",
+ createdBy: "user",
+ creationSource: "web",
+ inputIntent: "turn_start",
+ messageId,
+ text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
+ attachments: [],
},
- ],
- });
- }
- yield* orchestrator.dispatch({
- type: "thread.fork",
- commandId: CommandId.make("fork-source"),
- sourceThreadId,
- targetThreadId,
- sourcePoint: { type: "run", runId: sourceRunId },
- createdBy: "user",
- creationSource: "web",
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make("continue-fork"),
- threadId: targetThreadId,
- messageId: MessageId.make("continue-fork"),
- text: "Continue from the selected source run",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "start_immediately" },
- createdBy: "user",
- creationSource: "web",
+ },
+ ],
});
- const target = yield* orchestrator.getThreadProjection(targetThreadId);
- assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
- assert.lengthOf(target.contextHandoffs, 1);
- const handoff = target.contextHandoffs[0]!;
- const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
- assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
- assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
- assert.isNull(target.providerThreads[0]?.forkedFrom);
- }).pipe(Effect.provide(layer)),
- );
- }
-}
+ }
+ yield* orchestrator.dispatch({
+ type: "thread.fork",
+ commandId: CommandId.make("fork-source"),
+ sourceThreadId,
+ targetThreadId,
+ sourcePoint: { type: "run", runId: sourceRunId },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("continue-fork"),
+ threadId: targetThreadId,
+ messageId: MessageId.make("continue-fork"),
+ text: "Continue from the selected source run",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const target = yield* orchestrator.getThreadProjection(targetThreadId);
+ assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
+ assert.lengthOf(target.contextHandoffs, 1);
+ const handoff = target.contextHandoffs[0]!;
+ const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
+ assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
+ assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
+ assert.isNull(target.providerThreads[0]?.forkedFrom);
+ }).pipe(Effect.provide(layer)),
+);
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index 7b33d6f6ec9..10eb4ac9485 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -271,64 +271,64 @@ function waitUntil<E, R>(predicate: () => Effect.Effect<boolean, E, R>): Effect.
});
}
-for (const target of ["new", "existing"] as const) {
- for (const createdBy of ["user", "agent"] as const) {
- it.effect(
- `attributes ${createdBy}-configured automations in ${target} threads without changing their prompt`,
- () => {
- const harness = makeHarness();
- const scheduledTasks = ScheduledTasks.layer.pipe(
- Layer.provide(Layer.mergeAll(harness.layer, NodeCrypto.layer, Scheduler.layer)),
- );
- return Effect.gen(function* () {
- const tasks = yield* ScheduledTasks.ScheduledTaskService;
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const threads = yield* ThreadManagement.ThreadManagementService;
- const existing =
- target === "existing"
- ? yield* launches.launch(
- launchInput({ command: "command:existing", thread: "thread:existing" }),
- )
- : null;
- const { task } = yield* tasks.upsert({
- id: ScheduledTaskId.make("scheduled-task:attribution"),
- title: "Daily audit",
- prompt: "Audit performance and crashes.",
- enabled: false,
- schedule: { type: "interval", everyMs: 60_000 },
- projectId,
- threadId: existing?.threadId ?? null,
- workspaceStrategy: { type: "root" },
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- createdBy,
- creationSource: createdBy === "agent" ? "mcp" : "web",
- });
- const result = yield* tasks.runNow({ id: task.id });
- assert.equal(result.task.lastRunStatus, "succeeded");
- const projectThreads = yield* threads.listProjectThreads({
- projectId,
- includeSubagents: false,
- });
- const thread =
- projectThreads.find((candidate) => candidate.id === existing?.threadId) ??
- projectThreads[0];
- assert.isDefined(thread);
- const projection = yield* threads.getThreadProjection(thread!.id);
- // Encoding the persisted projection exercises both message and turn-item wire schemas.
- const wire = yield* encodeThreadProjection(projection);
- assert.equal(wire.messages[0]?.text, task.prompt);
- assert.equal(wire.messages[0]?.scheduledTaskId, task.id);
- assert.equal(wire.messages[0]?.createdBy, createdBy);
- const turnItem = wire.turnItems.find((item) => item.type === "user_message");
- assert.equal(turnItem?.text, task.prompt);
- assert.equal(turnItem?.scheduledTaskId, task.id);
- }).pipe(Effect.provide(Layer.mergeAll(harness.layer, scheduledTasks)));
- },
+it.effect.each(
+ (["new", "existing"] as const).flatMap((target) =>
+ (["user", "agent"] as const).map((createdBy) => ({ target, createdBy })),
+ ),
+)(
+ "attributes $createdBy-configured automations in $target threads without changing their prompt",
+ ({ target, createdBy }) => {
+ const harness = makeHarness();
+ const scheduledTasks = ScheduledTasks.layer.pipe(
+ Layer.provide(Layer.mergeAll(harness.layer, NodeCrypto.layer, Scheduler.layer)),
);
- }
-}
+ return Effect.gen(function* () {
+ const tasks = yield* ScheduledTasks.ScheduledTaskService;
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
+ const threads = yield* ThreadManagement.ThreadManagementService;
+ const existing =
+ target === "existing"
+ ? yield* launches.launch(
+ launchInput({ command: "command:existing", thread: "thread:existing" }),
+ )
+ : null;
+ const { task } = yield* tasks.upsert({
+ id: ScheduledTaskId.make("scheduled-task:attribution"),
+ title: "Daily audit",
+ prompt: "Audit performance and crashes.",
+ enabled: false,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId,
+ threadId: existing?.threadId ?? null,
+ workspaceStrategy: { type: "root" },
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy,
+ creationSource: createdBy === "agent" ? "mcp" : "web",
+ });
+ const result = yield* tasks.runNow({ id: task.id });
+ assert.equal(result.task.lastRunStatus, "succeeded");
+ const projectThreads = yield* threads.listProjectThreads({
+ projectId,
+ includeSubagents: false,
+ });
+ const thread =
+ projectThreads.find((candidate) => candidate.id === existing?.threadId) ??
+ projectThreads[0];
+ assert.isDefined(thread);
+ const projection = yield* threads.getThreadProjection(thread!.id);
+ // Encoding the persisted projection exercises both message and turn-item wire schemas.
+ const wire = yield* encodeThreadProjection(projection);
+ assert.equal(wire.messages[0]?.text, task.prompt);
+ assert.equal(wire.messages[0]?.scheduledTaskId, task.id);
+ assert.equal(wire.messages[0]?.createdBy, createdBy);
+ const turnItem = wire.turnItems.find((item) => item.type === "user_message");
+ assert.equal(turnItem?.text, task.prompt);
+ assert.equal(turnItem?.scheduledTaskId, task.id);
+ }).pipe(Effect.provide(Layer.mergeAll(harness.layer, scheduledTasks)));
+ },
+);
it.effect("retains automation and sender attribution while a message waits in the queue", () => {
const harness = makeHarness({ runSetup: () => Effect.never });
@@ -603,8 +603,9 @@ it.effect(
}),
);
-for (const nativeCommand of [" /COMPACT ", "/logout"]) {
- it.effect(`uses the first conversation message for a title after ${nativeCommand}`, () =>
+it.effect.each([" /COMPACT ", "/logout"])(
+ "uses the first conversation message for a title after %s",
+ (nativeCommand) =>
Effect.gen(function* () {
const harness = makeHarness();
yield* Effect.gen(function* () {
@@ -653,8 +654,7 @@ for (const nativeCommand of [" /COMPACT ", "/logout"]) {
);
}).pipe(Effect.provide(harness.layer));
}),
- );
-}
+);
it.effect("keeps native maintenance commands out of steering and restart messages", () =>
Effect.gen(function* () {
@@ -1293,47 +1293,45 @@ it.effect("shows the fetch diagnosis when preparing a worktree from origin fails
}).pipe(Effect.provide(harness.layer));
});
-for (const failurePoint of ["worktree", "setup"] as const) {
- it.effect(
- `${failurePoint} failure keeps the thread and message visible and emits failure items`,
- () =>
- Effect.gen(function* () {
- const failure = new Error(`${failurePoint} failed`);
- const harness = makeHarness(
- failurePoint === "worktree"
- ? { createWorktree: () => Effect.fail(failure as never) }
- : { runSetup: () => Effect.fail(failure as never) },
+it.effect.each(["worktree", "setup"] as const)(
+ "%s failure keeps the thread and message visible and emits failure items",
+ (failurePoint) =>
+ Effect.gen(function* () {
+ const failure = new Error(`${failurePoint} failed`);
+ const harness = makeHarness(
+ failurePoint === "worktree"
+ ? { createWorktree: () => Effect.fail(failure as never) }
+ : { runSetup: () => Effect.fail(failure as never) },
+ );
+ yield* Effect.gen(function* () {
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
+ const threads = yield* ThreadManagement.ThreadManagementService;
+ const input = launchInput({
+ command: `command:launch:${failurePoint}-failure`,
+ thread: `thread:launch:${failurePoint}-failure`,
+ message: `Fail during ${failurePoint}`,
+ workspace: { type: "worktree", baseRef: "main" },
+ });
+ const launched = yield* launches.launch(input);
+ yield* waitUntil(() =>
+ threads
+ .getThreadProjection(launched.threadId)
+ .pipe(Effect.map((projection) => projection.runs[0]?.status === "failed")),
);
- yield* Effect.gen(function* () {
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const threads = yield* ThreadManagement.ThreadManagementService;
- const input = launchInput({
- command: `command:launch:${failurePoint}-failure`,
- thread: `thread:launch:${failurePoint}-failure`,
- message: `Fail during ${failurePoint}`,
- workspace: { type: "worktree", baseRef: "main" },
- });
- const launched = yield* launches.launch(input);
- yield* waitUntil(() =>
- threads
- .getThreadProjection(launched.threadId)
- .pipe(Effect.map((projection) => projection.runs[0]?.status === "failed")),
- );
- const projection = yield* threads.getThreadProjection(launched.threadId);
- assert.equal(projection.messages[0]?.text, `Fail during ${failurePoint}`);
- assert.equal(projection.runs[0]?.status, "failed");
- assert.equal(
- projection.turnItems.find((item) => item.type === "command_execution")?.status,
- "failed",
- );
- assert.match(
- projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "",
- new RegExp(`${failurePoint} failed`, "u"),
- );
- }).pipe(Effect.provide(harness.layer));
- }),
- );
-}
+ const projection = yield* threads.getThreadProjection(launched.threadId);
+ assert.equal(projection.messages[0]?.text, `Fail during ${failurePoint}`);
+ assert.equal(projection.runs[0]?.status, "failed");
+ assert.equal(
+ projection.turnItems.find((item) => item.type === "command_execution")?.status,
+ "failed",
+ );
+ assert.match(
+ projection.turnItems.find((item) => item.type === "error")?.failure.message ?? "",
+ new RegExp(`${failurePoint} failed`, "u"),
+ );
+ }).pipe(Effect.provide(harness.layer));
+ }),
+);
it.effect("replays a server-allocated launch", () =>
Effect.gen(function* () {
@@ -1989,61 +1987,59 @@ it.effect("cancels tracked setup before provider work is released", () =>
}),
);
-for (const exitCode of [0, 1]) {
- it.effect(`releases an async setup before its completion with exit ${exitCode}`, () =>
- Effect.gen(function* () {
- const completion = yield* Deferred.make<{ exitCode: number | null; durationMs: number }>();
- const harness = makeHarness({
- runSetup: () =>
- Effect.succeed({
- status: "started" as const,
- async: true,
- scriptId: "setup",
- scriptName: "Setup",
- scriptCommand: "vp install",
- terminalId: "setup",
- cwd: "/repo-worktrees/feature",
- completion: Deferred.await(completion),
- }),
- });
- yield* Effect.gen(function* () {
- const launches = yield* ThreadLaunch.ThreadLaunchService;
- const threads = yield* ThreadManagement.ThreadManagementService;
- const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
- const launched = yield* launches.launch(
- launchInput({
- command: `command:launch:async-${exitCode}`,
- thread: `thread:launch:async-${exitCode}`,
- message: "Start during setup",
- workspace: { type: "worktree", baseRef: "main" },
- }),
- );
- yield* tracker.stream(launched.threadId).pipe(
- Stream.filter(
- (snapshot) =>
- snapshot?.stages.some((stage) => stage.id === "agent" && stage.status === "done") ===
- true,
- ),
- Stream.runHead,
- );
- const running = yield* threads.getThreadProjection(launched.threadId);
- assert.equal(running.runs[0]?.status, "starting");
- assert.equal((yield* tracker.get(launched.threadId))?.phase, "running");
- yield* Deferred.succeed(completion, { exitCode, durationMs: 1 });
- yield* tracker.stream(launched.threadId).pipe(
- Stream.filter((snapshot) => snapshot?.phase === "done"),
- Stream.runHead,
- );
- const settled = yield* tracker.get(launched.threadId);
- assert.equal(
- settled?.stages.find((stage) => stage.id === "setup-script")?.status,
- exitCode === 0 ? "done" : "failed",
- );
- assert.equal(
- (yield* threads.getThreadProjection(launched.threadId)).runs[0]?.status,
- "starting",
- );
- }).pipe(Effect.provide(harness.layer));
- }),
- );
-}
+it.effect.each([0, 1])("releases an async setup before its completion with exit %s", (exitCode) =>
+ Effect.gen(function* () {
+ const completion = yield* Deferred.make<{ exitCode: number | null; durationMs: number }>();
+ const harness = makeHarness({
+ runSetup: () =>
+ Effect.succeed({
+ status: "started" as const,
+ async: true,
+ scriptId: "setup",
+ scriptName: "Setup",
+ scriptCommand: "vp install",
+ terminalId: "setup",
+ cwd: "/repo-worktrees/feature",
+ completion: Deferred.await(completion),
+ }),
+ });
+ yield* Effect.gen(function* () {
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
+ const threads = yield* ThreadManagement.ThreadManagementService;
+ const tracker = yield* WorktreeSetupTracker.WorktreeSetupTracker;
+ const launched = yield* launches.launch(
+ launchInput({
+ command: `command:launch:async-${exitCode}`,
+ thread: `thread:launch:async-${exitCode}`,
+ message: "Start during setup",
+ workspace: { type: "worktree", baseRef: "main" },
+ }),
+ );
+ yield* tracker.stream(launched.threadId).pipe(
+ Stream.filter(
+ (snapshot) =>
+ snapshot?.stages.some((stage) => stage.id === "agent" && stage.status === "done") ===
+ true,
+ ),
+ Stream.runHead,
+ );
+ const running = yield* threads.getThreadProjection(launched.threadId);
+ assert.equal(running.runs[0]?.status, "starting");
+ assert.equal((yield* tracker.get(launched.threadId))?.phase, "running");
+ yield* Deferred.succeed(completion, { exitCode, durationMs: 1 });
+ yield* tracker.stream(launched.threadId).pipe(
+ Stream.filter((snapshot) => snapshot?.phase === "done"),
+ Stream.runHead,
+ );
+ const settled = yield* tracker.get(launched.threadId);
+ assert.equal(
+ settled?.stages.find((stage) => stage.id === "setup-script")?.status,
+ exitCode === 0 ? "done" : "failed",
+ );
+ assert.equal(
+ (yield* threads.getThreadProjection(launched.threadId)).runs[0]?.status,
+ "starting",
+ );
+ }).pipe(Effect.provide(harness.layer));
+ }),
+);
diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
index 1df1c242700..7ff557c338d 100644
--- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts
@@ -344,7 +344,7 @@ it.effect("preserves failed legacy materialization when reading checkpoint conte
}).pipe(Effect.provide(testLayer));
});
-for (const scenario of [
+it.effect.each([
{ finalStatus: "completed" as const, timedOut: false },
{ finalStatus: "failed" as const, timedOut: false },
{ finalStatus: "cancelled" as const, timedOut: false },
@@ -352,72 +352,70 @@ for (const scenario of [
{ finalStatus: "rolled_back" as const, timedOut: false },
{ finalStatus: "running" as const, timedOut: true },
{ finalStatus: "missing" as const },
-]) {
- it.effect(`waitForThread timeout final read when selected run is ${scenario.finalStatus}`, () =>
- Effect.gen(function* () {
- const projectId = ProjectId.make("project:thread-management:wait-timeout");
- const threadId = ThreadId.make("thread:thread-management:wait-timeout");
- const runId = RunId.make("run:thread-management:wait-timeout");
- const loopRead = yield* Deferred.make<void>();
- let reads = 0;
- const projection = (status: OrchestrationV2Run["status"] | "missing") =>
- ({
- thread: { id: threadId, projectId, deletedAt: null },
- runs: status === "missing" ? [] : [{ id: runId, status }],
- }) as unknown as OrchestrationV2ThreadProjection;
- const testLayer = ThreadManagementService.layer.pipe(
- Layer.provide(
- Layer.mock(Orchestrator.OrchestratorV2)({
- getThreadRecords: () =>
- Effect.gen(function* () {
- reads += 1;
- if (reads === 1) {
- return projection("running");
- }
- if (reads === 2) {
- // Park inside the wait loop so the timeout path runs while a
- // final projection read can still observe a terminal run.
- yield* Deferred.succeed(loopRead, undefined);
- return yield* Effect.never;
- }
- return projection(scenario.finalStatus);
- }),
- }),
- ),
- );
- const service = yield* ThreadManagementService.ThreadManagementService.pipe(
- Effect.provide(testLayer),
- );
- const fiber = yield* service
- .waitForThread({
- projectId,
+])("waitForThread timeout final read when selected run is $finalStatus", (scenario) =>
+ Effect.gen(function* () {
+ const projectId = ProjectId.make("project:thread-management:wait-timeout");
+ const threadId = ThreadId.make("thread:thread-management:wait-timeout");
+ const runId = RunId.make("run:thread-management:wait-timeout");
+ const loopRead = yield* Deferred.make<void>();
+ let reads = 0;
+ const projection = (status: OrchestrationV2Run["status"] | "missing") =>
+ ({
+ thread: { id: threadId, projectId, deletedAt: null },
+ runs: status === "missing" ? [] : [{ id: runId, status }],
+ }) as unknown as OrchestrationV2ThreadProjection;
+ const testLayer = ThreadManagementService.layer.pipe(
+ Layer.provide(
+ Layer.mock(Orchestrator.OrchestratorV2)({
+ getThreadRecords: () =>
+ Effect.gen(function* () {
+ reads += 1;
+ if (reads === 1) {
+ return projection("running");
+ }
+ if (reads === 2) {
+ // Park inside the wait loop so the timeout path runs while a
+ // final projection read can still observe a terminal run.
+ yield* Deferred.succeed(loopRead, undefined);
+ return yield* Effect.never;
+ }
+ return projection(scenario.finalStatus);
+ }),
+ }),
+ ),
+ );
+ const service = yield* ThreadManagementService.ThreadManagementService.pipe(
+ Effect.provide(testLayer),
+ );
+ const fiber = yield* service
+ .waitForThread({
+ projectId,
+ threadId,
+ runId,
+ timeoutMs: 1,
+ })
+ .pipe(Effect.result, Effect.forkChild);
+ yield* Deferred.await(loopRead);
+ yield* TestClock.adjust(Duration.millis(1));
+ const result = yield* Fiber.join(fiber);
+
+ if (scenario.finalStatus === "missing") {
+ expect(result._tag).toBe("Failure");
+ expect(result).toMatchObject({
+ failure: expect.any(ThreadManagementService.ThreadManagementRunNotFoundError),
+ });
+ expect(result).toMatchObject({
+ failure: { threadId, runId },
+ });
+ } else {
+ expect(result._tag).toBe("Success");
+ expect(result).toMatchObject({
+ success: {
threadId,
- runId,
- timeoutMs: 1,
- })
- .pipe(Effect.result, Effect.forkChild);
- yield* Deferred.await(loopRead);
- yield* TestClock.adjust(Duration.millis(1));
- const result = yield* Fiber.join(fiber);
-
- if (scenario.finalStatus === "missing") {
- expect(result._tag).toBe("Failure");
- expect(result).toMatchObject({
- failure: expect.any(ThreadManagementService.ThreadManagementRunNotFoundError),
- });
- expect(result).toMatchObject({
- failure: { threadId, runId },
- });
- } else {
- expect(result._tag).toBe("Success");
- expect(result).toMatchObject({
- success: {
- threadId,
- timedOut: scenario.timedOut,
- run: { id: runId, status: scenario.finalStatus },
- },
- });
- }
- }),
- );
-}
+ timedOut: scenario.timedOut,
+ run: { id: runId, status: scenario.finalStatus },
+ },
+ });
+ }
+ }),
+);
diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
index 6b9d4a43cc2..21a22a60dd9 100644
--- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts
@@ -438,8 +438,9 @@ describe("ThreadTitleRegenerationService", () => {
);
});
-for (const outcome of ["success", "exhausted", "stale", "interrupted"] as const) {
- it.effect(`initial title retry: ${outcome}`, () =>
+it.effect.each(["success", "exhausted", "stale", "interrupted"] as const)(
+ "initial title retry: %s",
+ (outcome) =>
Effect.gen(function* () {
const attempted = yield* Deferred.make<void>();
let attempts = 0;
@@ -502,5 +503,4 @@ for (const outcome of ["success", "exhausted", "stale", "interrupted"] as const)
else assert.isNotOk(projection.thread.titleRegeneration);
}).pipe(Effect.provide(harness.layer));
}),
- );
-}
+);
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index c71f84709b2..7f66cebd27d 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -2599,210 +2599,206 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- for (const automatic of [false, true]) {
- it.effect(
- `promotes only one queued run after each terminal run (notification: ${automatic})`,
- () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const eventSink = yield* EventSink.EventSinkV2;
- const threadId = ThreadId.make(`runtime-layer-serialized-queue-thread-${automatic}`);
+ it.effect.each([false, true])(
+ "promotes only one queued run after each terminal run (notification: %s)",
+ (automatic) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const threadId = ThreadId.make(`runtime-layer-serialized-queue-thread-${automatic}`);
- yield* orchestrator.dispatch({
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`runtime-layer-serialized-queue-create-${automatic}`),
- threadId,
- projectId: ProjectId.make(`runtime-layer-serialized-queue-project-${automatic}`),
- title: "Serialized queue",
- modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: process.cwd(),
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`runtime-layer-serialized-queue-active-${automatic}`),
- threadId,
- messageId: MessageId.make(`runtime-layer-serialized-queue-active-${automatic}`),
- text: "Active",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "start_immediately" },
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: automatic ? "agent" : "user",
- creationSource: automatic ? "provider" : "web",
- ...(automatic
- ? {
- notification: {
- source: { kind: "monitor" as const },
- outcome: "updated" as const,
- summary: "Monitor updated",
- detail: "Build is green",
- },
- }
- : {}),
- commandId: CommandId.make(`runtime-layer-serialized-queue-first-${automatic}`),
- threadId,
- messageId: MessageId.make(`runtime-layer-serialized-queue-first-${automatic}`),
- text: "First queued",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "queue_after_active" },
- });
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`runtime-layer-serialized-queue-second-${automatic}`),
- threadId,
- messageId: MessageId.make(`runtime-layer-serialized-queue-second-${automatic}`),
- text: "Second queued",
- attachments: [],
- modelSelection,
- dispatchMode: { type: "queue_after_active" },
- });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`runtime-layer-serialized-queue-create-${automatic}`),
+ threadId,
+ projectId: ProjectId.make(`runtime-layer-serialized-queue-project-${automatic}`),
+ title: "Serialized queue",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`runtime-layer-serialized-queue-active-${automatic}`),
+ threadId,
+ messageId: MessageId.make(`runtime-layer-serialized-queue-active-${automatic}`),
+ text: "Active",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: automatic ? "agent" : "user",
+ creationSource: automatic ? "provider" : "web",
+ ...(automatic
+ ? {
+ notification: {
+ source: { kind: "monitor" as const },
+ outcome: "updated" as const,
+ summary: "Monitor updated",
+ detail: "Build is green",
+ },
+ }
+ : {}),
+ commandId: CommandId.make(`runtime-layer-serialized-queue-first-${automatic}`),
+ threadId,
+ messageId: MessageId.make(`runtime-layer-serialized-queue-first-${automatic}`),
+ text: "First queued",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "queue_after_active" },
+ });
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`runtime-layer-serialized-queue-second-${automatic}`),
+ threadId,
+ messageId: MessageId.make(`runtime-layer-serialized-queue-second-${automatic}`),
+ text: "Second queued",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "queue_after_active" },
+ });
- const before = yield* orchestrator.getThreadProjection(threadId);
- const activeRun = before.runs.find((run) => run.status === "starting");
- const queuedRuns = before.runs
- .filter((run) => run.status === "queued")
- .toSorted((left, right) => left.ordinal - right.ordinal);
- const firstQueuedRun = queuedRuns[0];
- const secondQueuedRun = queuedRuns[1];
- assert.isDefined(activeRun);
- assert.isDefined(firstQueuedRun);
- assert.isDefined(secondQueuedRun);
- assert.isFalse(
- before.turnItems.some(
- (item) =>
- item.type === "user_message" &&
- (item.messageId === firstQueuedRun.userMessageId ||
- item.messageId === secondQueuedRun.userMessageId),
- ),
- "queued messages must not exist as turn items before dispatch",
- );
+ const before = yield* orchestrator.getThreadProjection(threadId);
+ const activeRun = before.runs.find((run) => run.status === "starting");
+ const queuedRuns = before.runs
+ .filter((run) => run.status === "queued")
+ .toSorted((left, right) => left.ordinal - right.ordinal);
+ const firstQueuedRun = queuedRuns[0];
+ const secondQueuedRun = queuedRuns[1];
+ assert.isDefined(activeRun);
+ assert.isDefined(firstQueuedRun);
+ assert.isDefined(secondQueuedRun);
+ assert.isFalse(
+ before.turnItems.some(
+ (item) =>
+ item.type === "user_message" &&
+ (item.messageId === firstQueuedRun.userMessageId ||
+ item.messageId === secondQueuedRun.userMessageId),
+ ),
+ "queued messages must not exist as turn items before dispatch",
+ );
- const promotedRunIds = yield* Queue.unbounded<RunId>();
- const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
- yield* eventSink.stream({ threadId, afterSequence }).pipe(
- Stream.runForEach((stored) =>
- stored.event.type === "run.updated" && stored.event.payload.status === "starting"
- ? Queue.offer(promotedRunIds, stored.event.payload.id)
- : Effect.void,
- ),
- Effect.forkScoped,
- );
- yield* Effect.yieldNow;
+ const promotedRunIds = yield* Queue.unbounded<RunId>();
+ const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
+ yield* eventSink.stream({ threadId, afterSequence }).pipe(
+ Stream.runForEach((stored) =>
+ stored.event.type === "run.updated" && stored.event.payload.status === "starting"
+ ? Queue.offer(promotedRunIds, stored.event.payload.id)
+ : Effect.void,
+ ),
+ Effect.forkScoped,
+ );
+ yield* Effect.yieldNow;
- const activeCompletedAt = yield* DateTime.now;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make(`runtime-layer-serialized-queue-active-completed-${automatic}`),
- type: "run.updated",
- threadId,
- runId: activeRun.id,
- ...(activeRun.rootNodeId === null ? {} : { nodeId: activeRun.rootNodeId }),
- providerInstanceId: activeRun.providerInstanceId,
- occurredAt: activeCompletedAt,
- payload: {
- ...activeRun,
- status: "completed",
- completedAt: activeCompletedAt,
- },
+ const activeCompletedAt = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`runtime-layer-serialized-queue-active-completed-${automatic}`),
+ type: "run.updated",
+ threadId,
+ runId: activeRun.id,
+ ...(activeRun.rootNodeId === null ? {} : { nodeId: activeRun.rootNodeId }),
+ providerInstanceId: activeRun.providerInstanceId,
+ occurredAt: activeCompletedAt,
+ payload: {
+ ...activeRun,
+ status: "completed",
+ completedAt: activeCompletedAt,
},
- ],
- });
+ },
+ ],
+ });
- assert.equal(yield* Queue.take(promotedRunIds), firstQueuedRun.id);
- const afterFirstPromotion = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(yield* Queue.take(promotedRunIds), firstQueuedRun.id);
+ const afterFirstPromotion = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
+ "starting",
+ );
+ assert.equal(
+ afterFirstPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
+ "queued",
+ );
+ const promotedMessageItem = afterFirstPromotion.turnItems.find(
+ (item) =>
+ item.runId === firstQueuedRun.id &&
+ (item.type === "user_message" || item.type === "notification"),
+ );
+ assert.isDefined(promotedMessageItem);
+ if (automatic) {
+ assert.equal(promotedMessageItem.type, "notification");
assert.equal(
- afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
- "starting",
+ afterFirstPromotion.messages.find(
+ (message) => message.id === firstQueuedRun.userMessageId,
+ )?.text,
+ "First queued",
);
assert.equal(
- afterFirstPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
- "queued",
+ afterFirstPromotion.messages.find(
+ (message) => message.id === firstQueuedRun.userMessageId,
+ )?.notification?.summary,
+ "Monitor updated",
);
- const promotedMessageItem = afterFirstPromotion.turnItems.find(
- (item) =>
- item.runId === firstQueuedRun.id &&
- (item.type === "user_message" || item.type === "notification"),
- );
- assert.isDefined(promotedMessageItem);
- if (automatic) {
- assert.equal(promotedMessageItem.type, "notification");
- assert.equal(
- afterFirstPromotion.messages.find(
- (message) => message.id === firstQueuedRun.userMessageId,
- )?.text,
- "First queued",
- );
- assert.equal(
- afterFirstPromotion.messages.find(
- (message) => message.id === firstQueuedRun.userMessageId,
- )?.notification?.summary,
- "Monitor updated",
- );
- assert.isFalse(
- afterFirstPromotion.turnItems.some(
- (item) =>
- item.type === "user_message" && item.messageId === firstQueuedRun.userMessageId,
- ),
- );
- } else {
- assert.equal(promotedMessageItem.type, "user_message");
- }
- assert.isTrue(
- promotedMessageItem.startedAt !== null &&
- DateTime.toEpochMillis(promotedMessageItem.startedAt) >=
- DateTime.toEpochMillis(activeCompletedAt),
+ assert.isFalse(
+ afterFirstPromotion.turnItems.some(
+ (item) =>
+ item.type === "user_message" && item.messageId === firstQueuedRun.userMessageId,
+ ),
);
+ } else {
+ assert.equal(promotedMessageItem.type, "user_message");
+ }
+ assert.isTrue(
+ promotedMessageItem.startedAt !== null &&
+ DateTime.toEpochMillis(promotedMessageItem.startedAt) >=
+ DateTime.toEpochMillis(activeCompletedAt),
+ );
- const promotedFirst = afterFirstPromotion.runs.find(
- (run) => run.id === firstQueuedRun.id,
- );
- assert.isDefined(promotedFirst);
- const firstCompletedAt = yield* DateTime.now;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make(`runtime-layer-serialized-queue-first-completed-${automatic}`),
- type: "run.updated",
- threadId,
- runId: promotedFirst.id,
- ...(promotedFirst.rootNodeId === null ? {} : { nodeId: promotedFirst.rootNodeId }),
- providerInstanceId: promotedFirst.providerInstanceId,
- occurredAt: firstCompletedAt,
- payload: {
- ...promotedFirst,
- status: "completed",
- completedAt: firstCompletedAt,
- },
+ const promotedFirst = afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id);
+ assert.isDefined(promotedFirst);
+ const firstCompletedAt = yield* DateTime.now;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make(`runtime-layer-serialized-queue-first-completed-${automatic}`),
+ type: "run.updated",
+ threadId,
+ runId: promotedFirst.id,
+ ...(promotedFirst.rootNodeId === null ? {} : { nodeId: promotedFirst.rootNodeId }),
+ providerInstanceId: promotedFirst.providerInstanceId,
+ occurredAt: firstCompletedAt,
+ payload: {
+ ...promotedFirst,
+ status: "completed",
+ completedAt: firstCompletedAt,
},
- ],
- });
+ },
+ ],
+ });
- assert.equal(yield* Queue.take(promotedRunIds), secondQueuedRun.id);
- const afterSecondPromotion = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(
- afterSecondPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
- "completed",
- );
- assert.equal(
- afterSecondPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
- "starting",
- );
- }),
- );
- }
+ assert.equal(yield* Queue.take(promotedRunIds), secondQueuedRun.id);
+ const afterSecondPromotion = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ afterSecondPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status,
+ "completed",
+ );
+ assert.equal(
+ afterSecondPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status,
+ "starting",
+ );
+ }),
+ );
it.effect.each(["usage_limit", "provider_error"] as const)(
"handles a queued message after a %s failure",
@@ -2993,112 +2989,106 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => {
}),
);
- for (const trigger of ["startup", "shutdown"] as const) {
- it.effect(
- `preserves and holds queued messages across ${trigger} until explicitly resumed`,
- () =>
- Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const recovery = yield* ProviderRuntimeRecoveryService.ProviderRuntimeRecoveryService;
- const threadId = ThreadId.make(`queue-hold-${trigger}`);
+ it.effect.each(["startup", "shutdown"] as const)(
+ "preserves and holds queued messages across %s until explicitly resumed",
+ (trigger) =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const recovery = yield* ProviderRuntimeRecoveryService.ProviderRuntimeRecoveryService;
+ const threadId = ThreadId.make(`queue-hold-${trigger}`);
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}:create`),
+ threadId,
+ projectId: ProjectId.make(`${threadId}:project`),
+ title: "Recover queue",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: process.cwd(),
+ });
+ for (const [index, text] of ["Active", "First queued", "Second queued"].entries()) {
yield* orchestrator.dispatch({
- type: "thread.create",
+ type: "message.dispatch",
createdBy: "user",
creationSource: "web",
- commandId: CommandId.make(`${threadId}:create`),
+ commandId: CommandId.make(`${threadId}:message:${index}`),
threadId,
- projectId: ProjectId.make(`${threadId}:project`),
- title: "Recover queue",
+ messageId: MessageId.make(`${threadId}:message:${index}`),
+ text,
+ attachments: [],
modelSelection,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: process.cwd(),
+ dispatchMode: { type: index === 0 ? "start_immediately" : "queue_after_active" },
});
- for (const [index, text] of ["Active", "First queued", "Second queued"].entries()) {
- yield* orchestrator.dispatch({
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make(`${threadId}:message:${index}`),
- threadId,
- messageId: MessageId.make(`${threadId}:message:${index}`),
- text,
- attachments: [],
- modelSelection,
- dispatchMode: { type: index === 0 ? "start_immediately" : "queue_after_active" },
- });
- }
- const before = yield* orchestrator.getThreadProjection(threadId);
- const queued = before.runs.filter((run) => run.status === "queued");
- assert.equal(queued.length, 2);
- yield* recovery.reconcile(trigger);
- // A second boot must preserve the hold, even when only queued work remains.
- yield* recovery.reconcile("startup");
- const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
- assert.isTrue((yield* maintenance.rebuild).valid);
- assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
- const held = yield* orchestrator.getThreadProjection(threadId);
+ }
+ const before = yield* orchestrator.getThreadProjection(threadId);
+ const queued = before.runs.filter((run) => run.status === "queued");
+ assert.equal(queued.length, 2);
+ yield* recovery.reconcile(trigger);
+ // A second boot must preserve the hold, even when only queued work remains.
+ yield* recovery.reconcile("startup");
+ const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
+ assert.isTrue((yield* maintenance.rebuild).valid);
+ assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
+ const held = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(
+ held.runs.map((run) => run.status),
+ ["cancelled", "queued", "queued"],
+ );
+ for (const run of queued) {
assert.deepEqual(
- held.runs.map((run) => run.status),
- ["cancelled", "queued", "queued"],
+ held.runs.find((row) => row.id === run.id),
+ { ...run, queueHeld: true },
);
- for (const run of queued) {
- assert.deepEqual(
- held.runs.find((row) => row.id === run.id),
- { ...run, queueHeld: true },
- );
- assert.deepEqual(
- held.messages.find((row) => row.id === run.userMessageId),
- before.messages.find((row) => row.id === run.userMessageId),
- );
- assert.equal(
- held.attempts.find((row) => row.id === run.activeAttemptId)?.status,
- "pending",
- );
- assert.equal(held.nodes.find((row) => row.id === run.rootNodeId)?.status, "pending");
- }
- // Editing and reordering are allowed without releasing the hold.
- const first = queued[0]!;
- const second = queued[1]!;
- yield* orchestrator.dispatch({
- type: "queued-run.edit",
- commandId: CommandId.make(`${threadId}:edit`),
- threadId,
- runId: second.id,
- text: "Edited second message",
- });
- yield* orchestrator.dispatch({
- type: "queued-run.reorder",
- commandId: CommandId.make(`${threadId}:reorder`),
- threadId,
- runId: second.id,
- beforeRunId: first.id,
- });
- assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
- const resume = {
- type: "queue.resume" as const,
- commandId: CommandId.make(`${threadId}:resume`),
- threadId,
- };
- yield* orchestrator.dispatch(resume);
- yield* orchestrator.dispatch(resume);
- const resumed = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(resumed.runs.find((run) => run.id === second.id)?.status, "starting");
- assert.equal(resumed.runs.find((run) => run.id === first.id)?.status, "queued");
- assert.isFalse(resumed.runs.some((run) => run.status === "queued" && run.queueHeld));
- assert.equal(
- resumed.messages.find((row) => row.id === second.userMessageId)?.text,
- "Edited second message",
+ assert.deepEqual(
+ held.messages.find((row) => row.id === run.userMessageId),
+ before.messages.find((row) => row.id === run.userMessageId),
);
assert.equal(
- resumed.runs.length,
- 3,
- "resume retries must not duplicate messages or runs",
+ held.attempts.find((row) => row.id === run.activeAttemptId)?.status,
+ "pending",
);
- }),
- );
- }
+ assert.equal(held.nodes.find((row) => row.id === run.rootNodeId)?.status, "pending");
+ }
+ // Editing and reordering are allowed without releasing the hold.
+ const first = queued[0]!;
+ const second = queued[1]!;
+ yield* orchestrator.dispatch({
+ type: "queued-run.edit",
+ commandId: CommandId.make(`${threadId}:edit`),
+ threadId,
+ runId: second.id,
+ text: "Edited second message",
+ });
+ yield* orchestrator.dispatch({
+ type: "queued-run.reorder",
+ commandId: CommandId.make(`${threadId}:reorder`),
+ threadId,
+ runId: second.id,
+ beforeRunId: first.id,
+ });
+ assert.equal(yield* orchestrator.resumeQueuedRuns, 0);
+ const resume = {
+ type: "queue.resume" as const,
+ commandId: CommandId.make(`${threadId}:resume`),
+ threadId,
+ };
+ yield* orchestrator.dispatch(resume);
+ yield* orchestrator.dispatch(resume);
+ const resumed = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(resumed.runs.find((run) => run.id === second.id)?.status, "starting");
+ assert.equal(resumed.runs.find((run) => run.id === first.id)?.status, "queued");
+ assert.isFalse(resumed.runs.some((run) => run.status === "queued" && run.queueHeld));
+ assert.equal(
+ resumed.messages.find((row) => row.id === second.userMessageId)?.text,
+ "Edited second message",
+ );
+ assert.equal(resumed.runs.length, 3, "resume retries must not duplicate messages or runs");
+ }),
+ );
it.effect("edits and removes queued runs", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
index b60a5b553cb..dd417ef162e 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts
@@ -221,19 +221,19 @@ function runFixtureProviderWithRegisteredHarness(input: {
}
describe("orchestrator replay fixtures", () => {
- for (const fixture of ORCHESTRATOR_REPLAY_FIXTURES) {
- for (const provider of fixture.providers) {
- it.effect(
- `runs ${fixture.name}/${provider.driver} through OrchestratorV2 using deterministic replay`,
- () =>
- runFixtureProviderWithRegisteredHarness({
- fixtureName: fixture.name,
- buildInput: fixture.buildInput,
- driver: provider,
- }),
- );
- }
- }
+ it.effect.each(
+ ORCHESTRATOR_REPLAY_FIXTURES.flatMap((fixture) =>
+ fixture.providers.map(
+ (provider) => [fixture.name, provider.driver, fixture, provider] as const,
+ ),
+ ),
+ )("runs %s/%s through OrchestratorV2 using deterministic replay", ([, , fixture, provider]) =>
+ runFixtureProviderWithRegisteredHarness({
+ fixtureName: fixture.name,
+ buildInput: fixture.buildInput,
+ driver: provider,
+ }),
+ );
const steeringFixture = ORCHESTRATOR_REPLAY_FIXTURES.find(
(fixture) => fixture.name === "message_steering",
@@ -254,33 +254,38 @@ describe("orchestrator replay fixtures", () => {
// A later OpenCode may change an execution start's shape; the client then
// reads it as `unreadable.execution.started`. A subagent's turn and a
// background follow-up must still start from it.
- for (const [fixtureName, label] of [
- ["opencode2_subagent", "session.execution.started.2"],
- ["opencode2_background", "session.execution.started.3"],
- ] as const) {
- const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find(
- (candidate) => candidate.name === fixtureName,
- );
- const provider = fixture?.providers[0];
- if (fixture === undefined || provider === undefined) continue;
- it.effect(
- `runs ${fixtureName} when ${label} is an execution start this build cannot decode`,
- () =>
- runFixtureProviderWithRegisteredHarness({
- fixtureName,
- buildInput: fixture.buildInput,
- driver: provider,
- transformTranscript: (transcript) => ({
- ...transcript,
- entries: transcript.entries.map((entry) =>
- entry.type === "emit_inbound" && entry.label === label
- ? undecodableEvent(entry)
- : entry,
- ),
- }),
+ it.effect.each(
+ (
+ [
+ ["opencode2_subagent", "session.execution.started.2"],
+ ["opencode2_background", "session.execution.started.3"],
+ ] as const
+ ).flatMap(([fixtureName, label]) => {
+ const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find(
+ (candidate) => candidate.name === fixtureName,
+ );
+ const provider = fixture?.providers[0];
+ return fixture === undefined || provider === undefined
+ ? []
+ : [[fixtureName, label, fixture, provider] as const];
+ }),
+ )(
+ "runs %s when %s is an execution start this build cannot decode",
+ ([fixtureName, label, fixture, provider]) =>
+ runFixtureProviderWithRegisteredHarness({
+ fixtureName,
+ buildInput: fixture.buildInput,
+ driver: provider,
+ transformTranscript: (transcript) => ({
+ ...transcript,
+ entries: transcript.entries.map((entry) =>
+ entry.type === "emit_inbound" && entry.label === label
+ ? undecodableEvent(entry)
+ : entry,
+ ),
}),
- );
- }
+ }),
+ );
});
/** The same event with an envelope this build cannot decode, as a newer OpenCode may send. */
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
index cba4cc6fbf1..9d01f22fe6a 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
@@ -374,7 +374,7 @@ const waitForIdle = Effect.fn("ProviderSwitchTest.waitForIdle")(function* (
});
describe("orchestration v2 provider switching", () => {
- for (const scenario of [
+ it.live.each([
"compact-native",
"compact-fallback",
"compact-legacy",
@@ -408,35 +408,496 @@ describe("orchestration v2 provider switching", () => {
"prior-images-replacement-native",
"prior-images-legacy-replacement-native",
"delivery-write-failure",
- ] as const) {
- it.live(`preserves handoffs through ${scenario}`, () =>
+ ] as const)("preserves handoffs through %s", (scenario) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace(`handoff-${scenario}`);
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
+ const reasoningScenario = scenario.includes("reasoning-change");
+ const turnUsageScenario = reasoningScenario || scenario.includes("turn-usage");
+ const modelScenario =
+ scenario.includes("model") || scenario.includes("option-change") || reasoningScenario;
+ const failStartOnce = yield* Ref.make(false);
+ const failResumeOnce = yield* Ref.make(false);
+ const generation = yield* Ref.make(0);
+ const priorImages = scenario.includes("prior-images");
+ const replaceNative = scenario.includes("replacement");
+ const capacityScenario = modelScenario || scenario.includes("reported-capacity");
+ const returning =
+ scenario === "large-current-input" || scenario.includes("-change-") || priorImages;
+ const targetSelection: ModelSelection = !modelScenario
+ ? CLAUDE_MODEL_SELECTION
+ : {
+ ...CLAUDE_MODEL_SELECTION,
+ ...(reasoningScenario
+ ? { options: [{ id: "reasoningEffort", value: "low" }] }
+ : scenario.includes("option-change")
+ ? { options: [{ id: "contextWindow", value: "1m" }] }
+ : { model: `${CLAUDE_MODEL_SELECTION.model}-large` }),
+ };
+ const registry = ProviderAdapterRegistry.makeLayer([
+ makeTestAdapter({
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
+ driver: CODEX_DRIVER,
+ capabilities: CodexProviderCapabilitiesV2,
+ modelSelection: CODEX_MODEL_SELECTION,
+ responseByRunOrdinal: { 1: "Original partial work" },
+ capturedTurns,
+ }),
+ makeTestAdapter({
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
+ driver: CLAUDE_DRIVER,
+ capabilities: ClaudeProviderCapabilitiesV2,
+ modelSelection: CLAUDE_MODEL_SELECTION,
+ responseByRunOrdinal: {},
+ capturedTurns,
+ ...(scenario.includes("retry") || scenario.includes("unsent") ? { failStartOnce } : {}),
+ ...(replaceNative ? { failResumeOnce, nativeThreadGeneration: generation } : {}),
+ ...(scenario.includes("reported-capacity")
+ ? { initialContextUsage: { usedTokens: 999_999, maxTokens: 1_000_000 } }
+ : {}),
+ ...(turnUsageScenario
+ ? {
+ canReuseContextUsage: canReuseCodexContextUsage,
+ tokenUsageByRunOrdinal: {
+ 2: {
+ usedTokens: replaceNative ? 30_000 : 37_321,
+ maxTokens: replaceNative
+ ? scenario.includes("small")
+ ? 32_000
+ : 64_000
+ : 258_400,
+ },
+ },
+ }
+ : modelScenario
+ ? {
+ getModelContextWindow: (selection: ModelSelection) =>
+ selection.model.endsWith("-large") ||
+ selection.options?.some(
+ (option) => option.id === "contextWindow" && option.value === "1m",
+ )
+ ? 1_000_000
+ : 32_000,
+ }
+ : scenario === "large-current-input" || priorImages
+ ? { getModelContextWindow: () => 32_000 }
+ : {}),
+ ...(scenario.endsWith("-native") || scenario === "large-current-input"
+ ? { injectedHistory }
+ : {}),
+ }),
+ ]);
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const eventSink = yield* EventSink.EventSinkV2;
+ const screenshot: ChatAttachment = {
+ type: "image",
+ id: "screenshot",
+ name: "screenshot.png",
+ mimeType: "image/png",
+ sizeBytes: 100_000,
+ };
+ const screenshots = Array.from(
+ {
+ length:
+ scenario.includes("eight") || capacityScenario
+ ? 8
+ : scenario.includes("pair")
+ ? 2
+ : 1,
+ },
+ (_, index) => ({ ...screenshot, id: `screenshot-${index}` }),
+ );
+ const targetOrdinal = returning ? 4 : 2;
+ const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`regression:${ordinal}`),
+ threadId,
+ messageId: MessageId.make(`regression:${ordinal}`),
+ createdBy: "user",
+ creationSource: "web",
+ text,
+ attachments:
+ turnUsageScenario && ordinal === 2
+ ? Array.from({ length: 8 }, (_, index) => ({
+ ...screenshot,
+ id: `prior-${index}`,
+ }))
+ : turnUsageScenario && ordinal >= targetOrdinal
+ ? [screenshot, { ...screenshot, id: "current-2" }]
+ : scenario.startsWith("screenshot") && ordinal >= targetOrdinal
+ ? screenshots
+ : priorImages && ordinal === (scenario.startsWith("imported") ? 1 : 2)
+ ? [screenshot]
+ : [],
+ modelSelection: selection,
+ dispatchMode: { type: "start_immediately" },
+ });
+ const wait = (ordinal: number) =>
+ orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) =>
+ event.type === "run.updated" &&
+ event.payload.ordinal === ordinal &&
+ (event.payload.status === "completed" || event.payload.status === "failed"),
+ ),
+ Stream.runHead,
+ Effect.andThen(worker.drain()),
+ );
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("regression:create"),
+ threadId,
+ projectId,
+ createdBy: "user",
+ creationSource: "web",
+ title: "Handoff regression",
+ modelSelection: CODEX_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ });
+ yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
+ yield* wait(1);
+ const write = eventSink.write;
+ const spy =
+ scenario === "delivery-write-failure"
+ ? vi.spyOn(eventSink, "write").mockImplementation((input) =>
+ input.events.some(
+ (event) =>
+ event.type === "context-handoff.updated" &&
+ event.payload.delivery?.status === "inline",
+ )
+ ? Effect.fail(
+ new EventSink.EventSinkWriteError({
+ eventCount: input.events.length,
+ cause: "bookkeeping unavailable",
+ }),
+ )
+ : write(input),
+ )
+ : undefined;
+ yield* Effect.addFinalizer(() => Effect.sync(() => spy?.mockRestore()));
+ const current = scenario.startsWith("compact")
+ ? "/compact"
+ : capacityScenario && !turnUsageScenario
+ ? "x".repeat(70_000)
+ : scenario === "large-current-input"
+ ? "x".repeat(9_000)
+ : "Continue work";
+ // First establish the returning native thread: the current request must
+ // not be charged as existing context on the subsequent handoff.
+ if (returning) {
+ if (scenario.includes("unsent")) yield* Ref.set(failStartOnce, true);
+ yield* dispatch(
+ 2,
+ turnUsageScenario ? "x".repeat(27_460) : "Establish target",
+ CLAUDE_MODEL_SELECTION,
+ );
+ yield* wait(2);
+ if (modelScenario && !turnUsageScenario) {
+ const target = (yield* orchestrator.getThreadProjection(
+ threadId,
+ )).providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("old-model-usage"),
+ type: "provider-thread.updated",
+ threadId,
+ occurredAt: yield* DateTime.now,
+ payload: {
+ ...target,
+ contextUsage: {
+ usedTokens: 30_000,
+ maxTokens: 32_000,
+ autoCompactThreshold: 31_000,
+ },
+ },
+ },
+ ],
+ });
+ }
+ if (scenario.includes("legacy-replacement")) {
+ const existing = yield* orchestrator.getThreadProjection(threadId);
+ yield* eventSink.write({
+ events: existing.attempts.map(
+ ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
+ id: EventId.make(`legacy-attempt:${index}`),
+ type: "run-attempt.updated" as const,
+ threadId,
+ occurredAt: existing.thread.createdAt,
+ payload: legacy,
+ }),
+ ),
+ });
+ }
+ if (scenario.includes("telemetry")) {
+ const target = (yield* orchestrator.getThreadProjection(
+ threadId,
+ )).providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("compacted-context-usage"),
+ type: "provider-thread.updated",
+ threadId,
+ occurredAt: yield* DateTime.now,
+ payload: { ...target, contextUsage: { usedTokens: 100, maxTokens: 32_000 } },
+ },
+ ],
+ });
+ }
+ yield* dispatch(
+ 3,
+ priorImages && !replaceNative
+ ? "New source constraint " + "q".repeat(9_000)
+ : "New source constraint",
+ CODEX_MODEL_SELECTION,
+ );
+ yield* wait(3);
+ }
+ if (replaceNative) {
+ const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!;
+ yield* orchestrator.dispatch({
+ type: "provider-session.detach",
+ commandId: CommandId.make("detach-for-native-replacement"),
+ threadId,
+ providerSessionId: target.providerSessionId!,
+ });
+ yield* worker.drain();
+ yield* Ref.set(failResumeOnce, true);
+ }
+ if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true);
+ yield* dispatch(targetOrdinal, current, targetSelection);
+ yield* wait(targetOrdinal);
+ if (scenario.includes("retry")) {
+ const failed = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(failed.runs.at(-1)?.status, "failed");
+ const failedUsage = failed.providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!.contextUsage;
+ if (reasoningScenario || scenario.includes("turn-usage")) {
+ assert.deepEqual(failedUsage, { usedTokens: 37_321, maxTokens: 258_400 });
+ } else {
+ assert.deepEqual(failedUsage, { usedTokens: 30_000, maxTokens: 1_000_000 });
+ }
+ if (reasoningScenario) {
+ const target = failed.providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!;
+ yield* orchestrator.dispatch({
+ type: "provider-session.detach",
+ commandId: CommandId.make("detach-before-reasoning-retry"),
+ threadId,
+ providerSessionId: target.providerSessionId!,
+ });
+ yield* worker.drain();
+ }
+ yield* dispatch(targetOrdinal + 1, current, targetSelection);
+ yield* wait(targetOrdinal + 1);
+ }
+ if (reasoningScenario && replaceNative) {
+ const replaced = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(
+ replaced.runs.at(-1)?.status,
+ scenario.includes("small") ? "failed" : "completed",
+ );
+ const target = replaced.providerThreads.find(
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ )!;
+ assert.isNull(target.contextUsage);
+ assert.equal(yield* Ref.get(generation), 2);
+ assert.equal(
+ (yield* Ref.get(capturedTurns)).at(-1)!.driver,
+ scenario.includes("small") ? CODEX_DRIVER : CLAUDE_DRIVER,
+ );
+ return;
+ }
+ if (replaceNative) {
+ if (scenario.includes("legacy-replacement")) {
+ const recovered = yield* orchestrator.getThreadProjection(threadId);
+ const handoff = recovered.contextHandoffs.at(-1)!;
+ const { history: _history, ...legacyHandoff } = handoff;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("legacy-replacement-handoff"),
+ type: "context-handoff.updated",
+ threadId,
+ occurredAt: yield* DateTime.now,
+ payload: {
+ ...legacyHandoff,
+ delivery: {
+ nativeThreadId: handoff.delivery!.nativeThreadId,
+ status: handoff.delivery!.status,
+ itemIds: [],
+ },
+ },
+ },
+ ],
+ });
+ }
+ yield* dispatch(
+ targetOrdinal + 1,
+ "Continue after native replacement",
+ CLAUDE_MODEL_SELECTION,
+ );
+ yield* wait(targetOrdinal + 1);
+ yield* dispatch(
+ targetOrdinal + 2,
+ "Another source constraint " + "q".repeat(9_000),
+ CODEX_MODEL_SELECTION,
+ );
+ yield* wait(targetOrdinal + 2);
+ yield* dispatch(targetOrdinal + 3, current, CLAUDE_MODEL_SELECTION);
+ yield* wait(targetOrdinal + 3);
+ }
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(projection.runs.at(-1)?.status, "completed");
+ if (priorImages) {
+ const handoff = projection.contextHandoffs.at(-1)!;
+ const context = scenario.endsWith("-native")
+ ? yield* encodeJson(yield* Ref.get(injectedHistory))
+ : (yield* Ref.get(capturedTurns)).at(-1)!.text;
+ const shouldFit =
+ turnUsageScenario ||
+ scenario.startsWith("imported") ||
+ scenario.includes("telemetry") ||
+ scenario.includes("unsent") ||
+ replaceNative;
+ const sourceText =
+ `${replaceNative ? "Another" : "New"} source constraint ` + "q".repeat(9_000);
+ const sourceItem = projection.turnItems.find(
+ (item) => item.type === "user_message" && item.text === sourceText,
+ )!;
+ assert.isDefined(sourceItem);
+ if (shouldFit) {
+ assert.include(context, sourceText);
+ assert.include(
+ projection.contextHandoffs
+ .filter(
+ (record) =>
+ record.targetRunId ===
+ (scenario.includes("retry")
+ ? projection.runs.find((run) => run.ordinal === targetOrdinal)!.id
+ : projection.runs.at(-1)!.id),
+ )
+ .flatMap((record) => record.delivery?.itemIds ?? []),
+ sourceItem.id,
+ );
+ } else {
+ assert.notInclude(context, "q".repeat(9_000));
+ assert.isAbove(handoff.delivery!.omittedItemIds!.length, 0);
+ }
+ const latestRun = projection.runs.at(-1)!;
+ const latestAttempt = projection.attempts.find(
+ (attempt) => attempt.id === latestRun.activeAttemptId,
+ )!;
+ const target = projection.providerThreads.find(
+ (thread) => thread.id === latestAttempt.providerThreadId,
+ )!;
+ assert.equal(latestAttempt.nativeThreadId, target.nativeThreadRef!.nativeId);
+ if (turnUsageScenario) {
+ if (replaceNative) assert.isNull(target.contextUsage);
+ else
+ assert.deepEqual(target.contextUsage, { usedTokens: 37_321, maxTokens: 258_400 });
+ assert.lengthOf((yield* Ref.get(capturedTurns)).at(-1)!.attachments, 2);
+ }
+ if (replaceNative) assert.equal(yield* Ref.get(generation), 2);
+ return;
+ }
+ const handoff = projection.contextHandoffs.at(-1)!;
+ if (scenario.startsWith("screenshot")) {
+ assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
+ }
+ if (scenario === "compact-fallback" || scenario === "compact-legacy") {
+ if (scenario === "compact-legacy") {
+ const { history: _history, ...legacyHandoff } = handoff;
+ yield* eventSink.write({
+ events: [
+ {
+ id: EventId.make("legacy-handoff-shape"),
+ type: "context-handoff.updated",
+ threadId,
+ runId: handoff.targetRunId,
+ occurredAt: yield* DateTime.now,
+ payload: legacyHandoff,
+ },
+ ],
+ });
+ }
+ assert.isUndefined(handoff.delivery);
+ yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
+ yield* wait(3);
+ assert.include(
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
+ "Original request with constraints",
+ );
+ assert.equal(
+ (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.at(-1)?.delivery
+ ?.status,
+ "inline",
+ );
+ } else if (
+ scenario === "delivery-write-failure" ||
+ (scenario.startsWith("screenshot") && scenario.endsWith("fallback"))
+ ) {
+ assert.equal(
+ handoff.delivery?.status,
+ scenario.startsWith("screenshot") ? "inline" : "pending",
+ );
+ assert.include(
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
+ "Original request with constraints",
+ );
+ } else {
+ assert.equal(handoff.delivery?.status, "injected");
+ assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, current);
+ assert.include(
+ yield* encodeJson(yield* Ref.get(injectedHistory)),
+ "Original request with constraints",
+ );
+ }
+ }).pipe(
+ Effect.provide(
+ makeOrchestratorV2ReplayLayerWithRegistry(
+ {
+ name: `handoff-${scenario}`,
+ runtimePolicyOverride: {
+ cwd,
+ approvalPolicy: "never",
+ sandboxPolicy: { type: "readOnly" },
+ },
+ },
+ registry,
+ ),
+ ),
+ );
+ }),
+ ),
+ );
+ it.live.each(["turn-start", "injection", "large-missed-request"] as const)(
+ "recovers %s failure without duplicating history in the same native thread",
+ (failure) =>
Effect.scoped(
Effect.gen(function* () {
- const cwd = yield* checkpointWorkspace(`handoff-${scenario}`);
+ const cwd = yield* checkpointWorkspace(`handoff-retry-${failure}`);
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
- const reasoningScenario = scenario.includes("reasoning-change");
- const turnUsageScenario = reasoningScenario || scenario.includes("turn-usage");
- const modelScenario =
- scenario.includes("model") || scenario.includes("option-change") || reasoningScenario;
- const failStartOnce = yield* Ref.make(false);
- const failResumeOnce = yield* Ref.make(false);
+ const failOnce = yield* Ref.make(true);
const generation = yield* Ref.make(0);
- const priorImages = scenario.includes("prior-images");
- const replaceNative = scenario.includes("replacement");
- const capacityScenario = modelScenario || scenario.includes("reported-capacity");
- const returning =
- scenario === "large-current-input" || scenario.includes("-change-") || priorImages;
- const targetSelection: ModelSelection = !modelScenario
- ? CLAUDE_MODEL_SELECTION
- : {
- ...CLAUDE_MODEL_SELECTION,
- ...(reasoningScenario
- ? { options: [{ id: "reasoningEffort", value: "low" }] }
- : scenario.includes("option-change")
- ? { options: [{ id: "contextWindow", value: "1m" }] }
- : { model: `${CLAUDE_MODEL_SELECTION.model}-large` }),
- };
const registry = ProviderAdapterRegistry.makeLayer([
makeTestAdapter({
instanceId: CODEX_MODEL_SELECTION.instanceId,
@@ -453,94 +914,31 @@ describe("orchestration v2 provider switching", () => {
modelSelection: CLAUDE_MODEL_SELECTION,
responseByRunOrdinal: {},
capturedTurns,
- ...(scenario.includes("retry") || scenario.includes("unsent")
- ? { failStartOnce }
- : {}),
- ...(replaceNative ? { failResumeOnce, nativeThreadGeneration: generation } : {}),
- ...(scenario.includes("reported-capacity")
- ? { initialContextUsage: { usedTokens: 999_999, maxTokens: 1_000_000 } }
- : {}),
- ...(turnUsageScenario
- ? {
- canReuseContextUsage: canReuseCodexContextUsage,
- tokenUsageByRunOrdinal: {
- 2: {
- usedTokens: replaceNative ? 30_000 : 37_321,
- maxTokens: replaceNative
- ? scenario.includes("small")
- ? 32_000
- : 64_000
- : 258_400,
- },
- },
- }
- : modelScenario
- ? {
- getModelContextWindow: (selection: ModelSelection) =>
- selection.model.endsWith("-large") ||
- selection.options?.some(
- (option) => option.id === "contextWindow" && option.value === "1m",
- )
- ? 1_000_000
- : 32_000,
- }
- : scenario === "large-current-input" || priorImages
- ? { getModelContextWindow: () => 32_000 }
- : {}),
- ...(scenario.endsWith("-native") || scenario === "large-current-input"
- ? { injectedHistory }
- : {}),
+ injectedHistory,
+ nativeThreadGeneration: generation,
+ getModelContextWindow: () => 32_000,
+ ...(failure !== "injection"
+ ? { failStartOnce: failOnce }
+ : { failInjectionOnce: failOnce }),
}),
]);
yield* Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const eventSink = yield* EventSink.EventSinkV2;
- const screenshot: ChatAttachment = {
- type: "image",
- id: "screenshot",
- name: "screenshot.png",
- mimeType: "image/png",
- sizeBytes: 100_000,
- };
- const screenshots = Array.from(
- {
- length:
- scenario.includes("eight") || capacityScenario
- ? 8
- : scenario.includes("pair")
- ? 2
- : 1,
- },
- (_, index) => ({ ...screenshot, id: `screenshot-${index}` }),
- );
- const targetOrdinal = returning ? 4 : 2;
const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
orchestrator.dispatch({
type: "message.dispatch",
- commandId: CommandId.make(`regression:${ordinal}`),
+ commandId: CommandId.make(`retry:${ordinal}`),
threadId,
- messageId: MessageId.make(`regression:${ordinal}`),
+ messageId: MessageId.make(`retry:${ordinal}`),
createdBy: "user",
creationSource: "web",
text,
- attachments:
- turnUsageScenario && ordinal === 2
- ? Array.from({ length: 8 }, (_, index) => ({
- ...screenshot,
- id: `prior-${index}`,
- }))
- : turnUsageScenario && ordinal >= targetOrdinal
- ? [screenshot, { ...screenshot, id: "current-2" }]
- : scenario.startsWith("screenshot") && ordinal >= targetOrdinal
- ? screenshots
- : priorImages && ordinal === (scenario.startsWith("imported") ? 1 : 2)
- ? [screenshot]
- : [],
+ attachments: [],
modelSelection: selection,
dispatchMode: { type: "start_immediately" },
});
- const wait = (ordinal: number) =>
+ const wait = (ordinal: number, status: "failed" | "completed") =>
orchestrator.streamStoredEvents.pipe(
Stream.filter(
({ event }) =>
@@ -550,15 +948,23 @@ describe("orchestration v2 provider switching", () => {
),
Stream.runHead,
Effect.andThen(worker.drain()),
+ Effect.andThen(
+ Effect.gen(function* () {
+ assert.equal(
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
+ status,
+ );
+ }),
+ ),
);
yield* orchestrator.dispatch({
type: "thread.create",
- commandId: CommandId.make("regression:create"),
+ commandId: CommandId.make("retry:create"),
threadId,
projectId,
createdBy: "user",
creationSource: "web",
- title: "Handoff regression",
+ title: "Handoff retry",
modelSelection: CODEX_MODEL_SELECTION,
runtimeMode: "full-access",
interactionMode: "default",
@@ -566,320 +972,71 @@ describe("orchestration v2 provider switching", () => {
worktreePath: null,
});
yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
- yield* wait(1);
- const write = eventSink.write;
- const spy =
- scenario === "delivery-write-failure"
- ? vi.spyOn(eventSink, "write").mockImplementation((input) =>
- input.events.some(
- (event) =>
- event.type === "context-handoff.updated" &&
- event.payload.delivery?.status === "inline",
- )
- ? Effect.fail(
- new EventSink.EventSinkWriteError({
- eventCount: input.events.length,
- cause: "bookkeeping unavailable",
- }),
- )
- : write(input),
- )
- : undefined;
- yield* Effect.addFinalizer(() => Effect.sync(() => spy?.mockRestore()));
- const current = scenario.startsWith("compact")
- ? "/compact"
- : capacityScenario && !turnUsageScenario
- ? "x".repeat(70_000)
- : scenario === "large-current-input"
- ? "x".repeat(9_000)
- : "Continue work";
- // First establish the returning native thread: the current request must
- // not be charged as existing context on the subsequent handoff.
- if (returning) {
- if (scenario.includes("unsent")) yield* Ref.set(failStartOnce, true);
- yield* dispatch(
- 2,
- turnUsageScenario ? "x".repeat(27_460) : "Establish target",
- CLAUDE_MODEL_SELECTION,
+ yield* wait(1, "completed");
+ yield* dispatch(
+ 2,
+ failure === "large-missed-request" ? "x".repeat(7_000) : "First target request",
+ CLAUDE_MODEL_SELECTION,
+ );
+ yield* wait(2, "failed");
+ const failed = yield* orchestrator.getThreadProjection(threadId);
+ const failedHandoff = failed.contextHandoffs.at(-1)!;
+ assert.equal(
+ failedHandoff.delivery?.status,
+ failure !== "injection" ? "injected" : "pending",
+ );
+ const historyBeforeRetry = (yield* Ref.get(injectedHistory)).length;
+ const retryText =
+ failure === "large-missed-request" ? "y".repeat(10_000) : "Retry target request";
+ yield* dispatch(3, retryText, CLAUDE_MODEL_SELECTION);
+ yield* wait(3, "completed");
+ const retried = yield* orchestrator.getThreadProjection(threadId);
+ const lastTurn = (yield* Ref.get(capturedTurns)).at(-1)!;
+ assert.equal(lastTurn.text, retryText);
+ if (failure !== "injection") {
+ const delta = yield* encodeJson(
+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
);
- yield* wait(2);
- if (modelScenario && !turnUsageScenario) {
- const target = (yield* orchestrator.getThreadProjection(
- threadId,
- )).providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
+ if (failure === "large-missed-request") {
+ assert.include(delta, "omitted 1 items");
+ const missedRequest = retried.turnItems.find(
+ (item) => item.type === "user_message" && item.text === "x".repeat(7_000),
)!;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("old-model-usage"),
- type: "provider-thread.updated",
- threadId,
- occurredAt: yield* DateTime.now,
- payload: {
- ...target,
- contextUsage: {
- usedTokens: 30_000,
- maxTokens: 32_000,
- autoCompactThreshold: 31_000,
- },
- },
- },
- ],
- });
- }
- if (scenario.includes("legacy-replacement")) {
- const existing = yield* orchestrator.getThreadProjection(threadId);
- yield* eventSink.write({
- events: existing.attempts.map(
- ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
- id: EventId.make(`legacy-attempt:${index}`),
- type: "run-attempt.updated" as const,
- threadId,
- occurredAt: existing.thread.createdAt,
- payload: legacy,
- }),
- ),
- });
- }
- if (scenario.includes("telemetry")) {
- const target = (yield* orchestrator.getThreadProjection(
- threadId,
- )).providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
- )!;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("compacted-context-usage"),
- type: "provider-thread.updated",
- threadId,
- occurredAt: yield* DateTime.now,
- payload: { ...target, contextUsage: { usedTokens: 100, maxTokens: 32_000 } },
- },
- ],
- });
- }
- yield* dispatch(
- 3,
- priorImages && !replaceNative
- ? "New source constraint " + "q".repeat(9_000)
- : "New source constraint",
- CODEX_MODEL_SELECTION,
- );
- yield* wait(3);
- }
- if (replaceNative) {
- const target = (yield* orchestrator.getThreadProjection(
- threadId,
- )).providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
- )!;
- yield* orchestrator.dispatch({
- type: "provider-session.detach",
- commandId: CommandId.make("detach-for-native-replacement"),
- threadId,
- providerSessionId: target.providerSessionId!,
- });
- yield* worker.drain();
- yield* Ref.set(failResumeOnce, true);
- }
- if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true);
- yield* dispatch(targetOrdinal, current, targetSelection);
- yield* wait(targetOrdinal);
- if (scenario.includes("retry")) {
- const failed = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(failed.runs.at(-1)?.status, "failed");
- const failedUsage = failed.providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
- )!.contextUsage;
- if (reasoningScenario || scenario.includes("turn-usage")) {
- assert.deepEqual(failedUsage, { usedTokens: 37_321, maxTokens: 258_400 });
- } else {
- assert.deepEqual(failedUsage, { usedTokens: 30_000, maxTokens: 1_000_000 });
- }
- if (reasoningScenario) {
- const target = failed.providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
- )!;
- yield* orchestrator.dispatch({
- type: "provider-session.detach",
- commandId: CommandId.make("detach-before-reasoning-retry"),
- threadId,
- providerSessionId: target.providerSessionId!,
- });
- yield* worker.drain();
- }
- yield* dispatch(targetOrdinal + 1, current, targetSelection);
- yield* wait(targetOrdinal + 1);
- }
- if (reasoningScenario && replaceNative) {
- const replaced = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(
- replaced.runs.at(-1)?.status,
- scenario.includes("small") ? "failed" : "completed",
- );
- const target = replaced.providerThreads.find(
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
- )!;
- assert.isNull(target.contextUsage);
+ const delivery = retried.contextHandoffs.at(-1)!.delivery!;
+ assert.include(delivery.omittedItemIds ?? [], missedRequest.id);
+ assert.notInclude(delivery.itemIds, missedRequest.id);
+ } else assert.include(delta, "First target request");
+ assert.notInclude(delta, "Original request with constraints");
+ assert.notInclude(delta, "Original partial work");
+ assert.equal(yield* Ref.get(generation), 1);
+ } else {
assert.equal(yield* Ref.get(generation), 2);
- assert.equal(
- (yield* Ref.get(capturedTurns)).at(-1)!.driver,
- scenario.includes("small") ? CODEX_DRIVER : CLAUDE_DRIVER,
- );
- return;
- }
- if (replaceNative) {
- if (scenario.includes("legacy-replacement")) {
- const recovered = yield* orchestrator.getThreadProjection(threadId);
- const handoff = recovered.contextHandoffs.at(-1)!;
- const { history: _history, ...legacyHandoff } = handoff;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("legacy-replacement-handoff"),
- type: "context-handoff.updated",
- threadId,
- occurredAt: yield* DateTime.now,
- payload: {
- ...legacyHandoff,
- delivery: {
- nativeThreadId: handoff.delivery!.nativeThreadId,
- status: handoff.delivery!.status,
- itemIds: [],
- },
- },
- },
- ],
- });
- }
- yield* dispatch(
- targetOrdinal + 1,
- "Continue after native replacement",
- CLAUDE_MODEL_SELECTION,
- );
- yield* wait(targetOrdinal + 1);
- yield* dispatch(
- targetOrdinal + 2,
- "Another source constraint " + "q".repeat(9_000),
- CODEX_MODEL_SELECTION,
- );
- yield* wait(targetOrdinal + 2);
- yield* dispatch(targetOrdinal + 3, current, CLAUDE_MODEL_SELECTION);
- yield* wait(targetOrdinal + 3);
- }
- const projection = yield* orchestrator.getThreadProjection(threadId);
- assert.equal(projection.runs.at(-1)?.status, "completed");
- if (priorImages) {
- const handoff = projection.contextHandoffs.at(-1)!;
- const context = scenario.endsWith("-native")
- ? yield* encodeJson(yield* Ref.get(injectedHistory))
- : (yield* Ref.get(capturedTurns)).at(-1)!.text;
- const shouldFit =
- turnUsageScenario ||
- scenario.startsWith("imported") ||
- scenario.includes("telemetry") ||
- scenario.includes("unsent") ||
- replaceNative;
- const sourceText =
- `${replaceNative ? "Another" : "New"} source constraint ` + "q".repeat(9_000);
- const sourceItem = projection.turnItems.find(
- (item) => item.type === "user_message" && item.text === sourceText,
- )!;
- assert.isDefined(sourceItem);
- if (shouldFit) {
- assert.include(context, sourceText);
- assert.include(
- projection.contextHandoffs
- .filter(
- (record) =>
- record.targetRunId ===
- (scenario.includes("retry")
- ? projection.runs.find((run) => run.ordinal === targetOrdinal)!.id
- : projection.runs.at(-1)!.id),
- )
- .flatMap((record) => record.delivery?.itemIds ?? []),
- sourceItem.id,
- );
- } else {
- assert.notInclude(context, "q".repeat(9_000));
- assert.isAbove(handoff.delivery!.omittedItemIds!.length, 0);
- }
- const latestRun = projection.runs.at(-1)!;
- const latestAttempt = projection.attempts.find(
- (attempt) => attempt.id === latestRun.activeAttemptId,
- )!;
- const target = projection.providerThreads.find(
- (thread) => thread.id === latestAttempt.providerThreadId,
- )!;
- assert.equal(latestAttempt.nativeThreadId, target.nativeThreadRef!.nativeId);
- if (turnUsageScenario) {
- if (replaceNative) assert.isNull(target.contextUsage);
- else
- assert.deepEqual(target.contextUsage, { usedTokens: 37_321, maxTokens: 258_400 });
- assert.lengthOf((yield* Ref.get(capturedTurns)).at(-1)!.attachments, 2);
- }
- if (replaceNative) assert.equal(yield* Ref.get(generation), 2);
- return;
- }
- const handoff = projection.contextHandoffs.at(-1)!;
- if (scenario.startsWith("screenshot")) {
- assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
- }
- if (scenario === "compact-fallback" || scenario === "compact-legacy") {
- if (scenario === "compact-legacy") {
- const { history: _history, ...legacyHandoff } = handoff;
- yield* eventSink.write({
- events: [
- {
- id: EventId.make("legacy-handoff-shape"),
- type: "context-handoff.updated",
- threadId,
- runId: handoff.targetRunId,
- occurredAt: yield* DateTime.now,
- payload: legacyHandoff,
- },
- ],
- });
- }
- assert.isUndefined(handoff.delivery);
- yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
- yield* wait(3);
- assert.include(
- (yield* Ref.get(capturedTurns)).at(-1)!.text,
- "Original request with constraints",
- );
- assert.equal(
- (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.at(-1)?.delivery
- ?.status,
- "inline",
- );
- } else if (
- scenario === "delivery-write-failure" ||
- (scenario.startsWith("screenshot") && scenario.endsWith("fallback"))
- ) {
- assert.equal(
- handoff.delivery?.status,
- scenario.startsWith("screenshot") ? "inline" : "pending",
- );
- assert.include(
- (yield* Ref.get(capturedTurns)).at(-1)!.text,
- "Original request with constraints",
+ assert.notEqual(
+ retried.contextHandoffs.at(-1)?.delivery?.nativeThreadId,
+ failedHandoff.delivery?.nativeThreadId,
);
- } else {
- assert.equal(handoff.delivery?.status, "injected");
- assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, current);
- assert.include(
- yield* encodeJson(yield* Ref.get(injectedHistory)),
- "Original request with constraints",
+ const newHistory = yield* encodeJson(
+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
);
+ assert.include(newHistory, "Original request with constraints");
+ assert.include(newHistory, "Original partial work");
+ assert.notInclude(newHistory, "Retry target request");
}
+ const beforeFollowup = yield* Ref.get(injectedHistory);
+ const followup = "z".repeat(6_000);
+ yield* dispatch(4, followup, CLAUDE_MODEL_SELECTION);
+ yield* wait(4, "completed");
+ assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, followup);
+ assert.deepEqual(yield* Ref.get(injectedHistory), beforeFollowup);
+ assert.equal(
+ (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.length,
+ retried.contextHandoffs.length,
+ );
}).pipe(
Effect.provide(
makeOrchestratorV2ReplayLayerWithRegistry(
{
- name: `handoff-${scenario}`,
+ name: `handoff-retry-${failure}`,
runtimePolicyOverride: {
cwd,
approvalPolicy: "never",
@@ -892,368 +1049,194 @@ describe("orchestration v2 provider switching", () => {
);
}),
),
- );
- }
- for (const failure of ["turn-start", "injection", "large-missed-request"] as const) {
- it.live(
- `recovers ${failure} failure without duplicating history in the same native thread`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const cwd = yield* checkpointWorkspace(`handoff-retry-${failure}`);
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
- const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
- const failOnce = yield* Ref.make(true);
- const generation = yield* Ref.make(0);
- const registry = ProviderAdapterRegistry.makeLayer([
- makeTestAdapter({
- instanceId: CODEX_MODEL_SELECTION.instanceId,
- driver: CODEX_DRIVER,
- capabilities: CodexProviderCapabilitiesV2,
- modelSelection: CODEX_MODEL_SELECTION,
- responseByRunOrdinal: { 1: "Original partial work" },
- capturedTurns,
- }),
- makeTestAdapter({
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
- driver: CLAUDE_DRIVER,
- capabilities: ClaudeProviderCapabilitiesV2,
- modelSelection: CLAUDE_MODEL_SELECTION,
- responseByRunOrdinal: {},
- capturedTurns,
- injectedHistory,
- nativeThreadGeneration: generation,
- getModelContextWindow: () => 32_000,
- ...(failure !== "injection"
- ? { failStartOnce: failOnce }
- : { failInjectionOnce: failOnce }),
- }),
- ]);
- yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
- orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make(`retry:${ordinal}`),
- threadId,
- messageId: MessageId.make(`retry:${ordinal}`),
- createdBy: "user",
- creationSource: "web",
- text,
- attachments: [],
- modelSelection: selection,
- dispatchMode: { type: "start_immediately" },
- });
- const wait = (ordinal: number, status: "failed" | "completed") =>
- orchestrator.streamStoredEvents.pipe(
- Stream.filter(
- ({ event }) =>
- event.type === "run.updated" &&
- event.payload.ordinal === ordinal &&
- (event.payload.status === "completed" || event.payload.status === "failed"),
- ),
- Stream.runHead,
- Effect.andThen(worker.drain()),
- Effect.andThen(
- Effect.gen(function* () {
- assert.equal(
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
- status,
- );
- }),
- ),
- );
- yield* orchestrator.dispatch({
- type: "thread.create",
- commandId: CommandId.make("retry:create"),
- threadId,
- projectId,
- createdBy: "user",
- creationSource: "web",
- title: "Handoff retry",
- modelSelection: CODEX_MODEL_SELECTION,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- });
- yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
- yield* wait(1, "completed");
- yield* dispatch(
- 2,
- failure === "large-missed-request" ? "x".repeat(7_000) : "First target request",
- CLAUDE_MODEL_SELECTION,
- );
- yield* wait(2, "failed");
- const failed = yield* orchestrator.getThreadProjection(threadId);
- const failedHandoff = failed.contextHandoffs.at(-1)!;
- assert.equal(
- failedHandoff.delivery?.status,
- failure !== "injection" ? "injected" : "pending",
- );
- const historyBeforeRetry = (yield* Ref.get(injectedHistory)).length;
- const retryText =
- failure === "large-missed-request" ? "y".repeat(10_000) : "Retry target request";
- yield* dispatch(3, retryText, CLAUDE_MODEL_SELECTION);
- yield* wait(3, "completed");
- const retried = yield* orchestrator.getThreadProjection(threadId);
- const lastTurn = (yield* Ref.get(capturedTurns)).at(-1)!;
- assert.equal(lastTurn.text, retryText);
- if (failure !== "injection") {
- const delta = yield* encodeJson(
- (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
- );
- if (failure === "large-missed-request") {
- assert.include(delta, "omitted 1 items");
- const missedRequest = retried.turnItems.find(
- (item) => item.type === "user_message" && item.text === "x".repeat(7_000),
- )!;
- const delivery = retried.contextHandoffs.at(-1)!.delivery!;
- assert.include(delivery.omittedItemIds ?? [], missedRequest.id);
- assert.notInclude(delivery.itemIds, missedRequest.id);
- } else assert.include(delta, "First target request");
- assert.notInclude(delta, "Original request with constraints");
- assert.notInclude(delta, "Original partial work");
- assert.equal(yield* Ref.get(generation), 1);
- } else {
- assert.equal(yield* Ref.get(generation), 2);
- assert.notEqual(
- retried.contextHandoffs.at(-1)?.delivery?.nativeThreadId,
- failedHandoff.delivery?.nativeThreadId,
- );
- const newHistory = yield* encodeJson(
- (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
- );
- assert.include(newHistory, "Original request with constraints");
- assert.include(newHistory, "Original partial work");
- assert.notInclude(newHistory, "Retry target request");
- }
- const beforeFollowup = yield* Ref.get(injectedHistory);
- const followup = "z".repeat(6_000);
- yield* dispatch(4, followup, CLAUDE_MODEL_SELECTION);
- yield* wait(4, "completed");
- assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, followup);
- assert.deepEqual(yield* Ref.get(injectedHistory), beforeFollowup);
- assert.equal(
- (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.length,
- retried.contextHandoffs.length,
- );
- }).pipe(
- Effect.provide(
- makeOrchestratorV2ReplayLayerWithRegistry(
- {
- name: `handoff-retry-${failure}`,
- runtimePolicyOverride: {
- cwd,
- approvalPolicy: "never",
- sandboxPolicy: { type: "readOnly" },
- },
- },
- registry,
- ),
- ),
- );
- }),
- ),
- );
- }
+ );
- for (const status of ["failed", "interrupted"] as const) {
- for (const queued of [false, true]) {
- for (const returning of [false, true]) {
- for (const native of [false, true]) {
- it.live(
- `hands off ${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const cwd = yield* checkpointWorkspace(
- `handoff-${status}-${queued}-${returning}`,
- );
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
- const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
- const started = yield* Deferred.make<void>();
- const release = yield* Deferred.make<void>();
- const sourceOrdinal = returning ? 2 : 1;
- const sourceSelection = returning
- ? CLAUDE_MODEL_SELECTION
- : CODEX_MODEL_SELECTION;
- const targetSelection = returning
- ? CODEX_MODEL_SELECTION
- : CLAUDE_MODEL_SELECTION;
- const originalPrompt =
- "Keep the release marker violet and preserve the existing API.";
- const partialResponse = "I checked the API and found the release configuration.";
- const registryLayer = ProviderAdapterRegistry.makeLayer(
- (
- [
- [CODEX_MODEL_SELECTION, CODEX_DRIVER, CodexProviderCapabilitiesV2],
- [CLAUDE_MODEL_SELECTION, CLAUDE_DRIVER, ClaudeProviderCapabilitiesV2],
- ] as const
- ).map(([modelSelection, driver, capabilities]) =>
- makeTestAdapter({
- instanceId: modelSelection.instanceId,
- driver,
- capabilities,
- modelSelection,
- responseByRunOrdinal: { [sourceOrdinal]: partialResponse },
- capturedTurns,
- ...(native && modelSelection.instanceId === targetSelection.instanceId
- ? { injectedHistory }
- : {}),
- ...(modelSelection.instanceId === sourceSelection.instanceId
- ? {
- failedRunOrdinals: new Set(
- status === "failed" ? [sourceOrdinal] : [],
- ),
- interruptedRunOrdinals: new Set(
- status === "interrupted" ? [sourceOrdinal] : [],
- ),
- holdRunOrdinal: sourceOrdinal,
- holdFirstTurn: started,
- releaseFirstTurn: release,
- }
- : {}),
- }),
- ),
- );
- yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
- const waitForRun = (
- ordinal: number,
- expectedStatus: "completed" | "failed" | "interrupted",
- ) =>
- orchestrator.streamStoredEvents.pipe(
- Stream.filter(
- ({ event }) =>
- event.type === "run.updated" &&
- event.threadId === threadId &&
- event.payload.ordinal === ordinal &&
- event.payload.status === expectedStatus,
- ),
- Stream.runHead,
- Effect.andThen(worker.drain()),
- );
- const dispatch = (
- key: string,
- text: string,
- modelSelection: ModelSelection,
- queue = false,
- ) =>
- orchestrator.dispatch({
- type: "message.dispatch",
- commandId: CommandId.make(`command:handoff:${key}`),
- threadId,
- messageId: MessageId.make(`message:handoff:${key}`),
- createdBy: "user",
- creationSource: "web",
- text,
- attachments: [],
- modelSelection,
- dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" },
- });
- yield* orchestrator.dispatch({
- type: "thread.create",
- commandId: CommandId.make("command:handoff:create"),
- threadId,
- projectId,
- createdBy: "user",
- creationSource: "web",
- title: "Interrupted provider handoff",
- modelSelection: CODEX_MODEL_SELECTION,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- });
- if (returning) {
- yield* dispatch(
- "initial",
- "Earlier successful request.",
- CODEX_MODEL_SELECTION,
- );
- yield* waitForRun(1, "completed");
- }
- yield* dispatch("source", originalPrompt, sourceSelection);
- yield* Deferred.await(started);
- if (queued) {
- yield* dispatch("target", "Continue", targetSelection, true);
- assert.equal(
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
- "queued",
- );
- }
- yield* Deferred.succeed(release, undefined);
- yield* waitForRun(sourceOrdinal, status);
- if (!queued) {
- yield* dispatch("target", "Continue", targetSelection);
- }
- yield* waitForRun(sourceOrdinal + 1, "completed");
- const projection = yield* orchestrator.getThreadProjection(threadId);
- const targetRun = projection.runs.at(-1)!;
- const handoff = projection.contextHandoffs.find(
- (candidate) => candidate.id === targetRun.contextHandoffId,
- );
- assert.isDefined(handoff);
- assert.equal(
- handoff?.strategy,
- returning ? "delta_since_target_last_seen" : "full_thread_summary",
- );
- assert.deepEqual(handoff?.coveredRunOrdinals, {
- from: sourceOrdinal,
- to: sourceOrdinal,
- });
- const delivered = (yield* Ref.get(capturedTurns)).at(-1)!;
- const history = yield* Ref.get(injectedHistory);
- const deliveredHistory = native ? yield* encodeJson(history) : delivered.text;
- assert.include(deliveredHistory, originalPrompt);
- assert.include(deliveredHistory, partialResponse);
- assert.include(deliveredHistory, `run-status=${status}`);
- if (native) {
- assert.equal(delivered.text, "Continue");
- assert.notInclude(deliveredHistory, '"text":"Continue"');
- assert.include(deliveredHistory, '"role":"assistant"');
- assert.include(deliveredHistory, '"role":"user"');
- assert.equal(handoff?.delivery?.status, "injected");
- } else {
- assert.include(delivered.text, "User message:\nContinue");
- assert.equal(handoff?.delivery?.status, "inline");
- }
- assert.notInclude(deliveredHistory, "Earlier successful request.");
- // The returning source already has its own failed/interrupted native turn.
- yield* dispatch("back", "Finish the remaining work", sourceSelection);
- yield* waitForRun(sourceOrdinal + 2, "completed");
- const back = (yield* Ref.get(capturedTurns)).at(-1)!;
- assert.notInclude(back.text, originalPrompt);
- assert.notInclude(back.text, partialResponse);
- }).pipe(
- Effect.provide(
- makeOrchestratorV2ReplayLayerWithRegistry(
- {
- name: `handoff-${status}-${queued}-${returning}`,
- runtimePolicyOverride: {
- cwd,
- approvalPolicy: "never",
- sandboxPolicy: {
- type: "readOnly",
- access: { type: "fullAccess" },
- networkAccess: false,
- },
- },
- },
- registryLayer,
- ),
+ it.live.each(
+ (["failed", "interrupted"] as const).flatMap((status) =>
+ [false, true].flatMap((queued) =>
+ [false, true].flatMap((returning) =>
+ [false, true].map(
+ (native) =>
+ [
+ `${status} context ${queued ? "through the queue" : "immediately"} to ${returning ? "a returning" : "a new"} provider via ${native ? "native history" : "text"}`,
+ { status, queued, returning, native },
+ ] as const,
+ ),
+ ),
+ ),
+ ),
+ )("hands off %s", ([, { status, queued, returning, native }]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace(`handoff-${status}-${queued}-${returning}`);
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
+ const started = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const sourceOrdinal = returning ? 2 : 1;
+ const sourceSelection = returning ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION;
+ const targetSelection = returning ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION;
+ const originalPrompt = "Keep the release marker violet and preserve the existing API.";
+ const partialResponse = "I checked the API and found the release configuration.";
+ const registryLayer = ProviderAdapterRegistry.makeLayer(
+ (
+ [
+ [CODEX_MODEL_SELECTION, CODEX_DRIVER, CodexProviderCapabilitiesV2],
+ [CLAUDE_MODEL_SELECTION, CLAUDE_DRIVER, ClaudeProviderCapabilitiesV2],
+ ] as const
+ ).map(([modelSelection, driver, capabilities]) =>
+ makeTestAdapter({
+ instanceId: modelSelection.instanceId,
+ driver,
+ capabilities,
+ modelSelection,
+ responseByRunOrdinal: { [sourceOrdinal]: partialResponse },
+ capturedTurns,
+ ...(native && modelSelection.instanceId === targetSelection.instanceId
+ ? { injectedHistory }
+ : {}),
+ ...(modelSelection.instanceId === sourceSelection.instanceId
+ ? {
+ failedRunOrdinals: new Set(status === "failed" ? [sourceOrdinal] : []),
+ interruptedRunOrdinals: new Set(
+ status === "interrupted" ? [sourceOrdinal] : [],
),
- );
- }),
+ holdRunOrdinal: sourceOrdinal,
+ holdFirstTurn: started,
+ releaseFirstTurn: release,
+ }
+ : {}),
+ }),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const waitForRun = (
+ ordinal: number,
+ expectedStatus: "completed" | "failed" | "interrupted",
+ ) =>
+ orchestrator.streamStoredEvents.pipe(
+ Stream.filter(
+ ({ event }) =>
+ event.type === "run.updated" &&
+ event.threadId === threadId &&
+ event.payload.ordinal === ordinal &&
+ event.payload.status === expectedStatus,
),
+ Stream.runHead,
+ Effect.andThen(worker.drain()),
+ );
+ const dispatch = (
+ key: string,
+ text: string,
+ modelSelection: ModelSelection,
+ queue = false,
+ ) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`command:handoff:${key}`),
+ threadId,
+ messageId: MessageId.make(`message:handoff:${key}`),
+ createdBy: "user",
+ creationSource: "web",
+ text,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" },
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("command:handoff:create"),
+ threadId,
+ projectId,
+ createdBy: "user",
+ creationSource: "web",
+ title: "Interrupted provider handoff",
+ modelSelection: CODEX_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ });
+ if (returning) {
+ yield* dispatch("initial", "Earlier successful request.", CODEX_MODEL_SELECTION);
+ yield* waitForRun(1, "completed");
+ }
+ yield* dispatch("source", originalPrompt, sourceSelection);
+ yield* Deferred.await(started);
+ if (queued) {
+ yield* dispatch("target", "Continue", targetSelection, true);
+ assert.equal(
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
+ "queued",
+ );
+ }
+ yield* Deferred.succeed(release, undefined);
+ yield* waitForRun(sourceOrdinal, status);
+ if (!queued) {
+ yield* dispatch("target", "Continue", targetSelection);
+ }
+ yield* waitForRun(sourceOrdinal + 1, "completed");
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ const targetRun = projection.runs.at(-1)!;
+ const handoff = projection.contextHandoffs.find(
+ (candidate) => candidate.id === targetRun.contextHandoffId,
);
- }
- }
- }
- }
+ assert.isDefined(handoff);
+ assert.equal(
+ handoff?.strategy,
+ returning ? "delta_since_target_last_seen" : "full_thread_summary",
+ );
+ assert.deepEqual(handoff?.coveredRunOrdinals, {
+ from: sourceOrdinal,
+ to: sourceOrdinal,
+ });
+ const delivered = (yield* Ref.get(capturedTurns)).at(-1)!;
+ const history = yield* Ref.get(injectedHistory);
+ const deliveredHistory = native ? yield* encodeJson(history) : delivered.text;
+ assert.include(deliveredHistory, originalPrompt);
+ assert.include(deliveredHistory, partialResponse);
+ assert.include(deliveredHistory, `run-status=${status}`);
+ if (native) {
+ assert.equal(delivered.text, "Continue");
+ assert.notInclude(deliveredHistory, '"text":"Continue"');
+ assert.include(deliveredHistory, '"role":"assistant"');
+ assert.include(deliveredHistory, '"role":"user"');
+ assert.equal(handoff?.delivery?.status, "injected");
+ } else {
+ assert.include(delivered.text, "User message:\nContinue");
+ assert.equal(handoff?.delivery?.status, "inline");
+ }
+ assert.notInclude(deliveredHistory, "Earlier successful request.");
+ // The returning source already has its own failed/interrupted native turn.
+ yield* dispatch("back", "Finish the remaining work", sourceSelection);
+ yield* waitForRun(sourceOrdinal + 2, "completed");
+ const back = (yield* Ref.get(capturedTurns)).at(-1)!;
+ assert.notInclude(back.text, originalPrompt);
+ assert.notInclude(back.text, partialResponse);
+ }).pipe(
+ Effect.provide(
+ makeOrchestratorV2ReplayLayerWithRegistry(
+ {
+ name: `handoff-${status}-${queued}-${returning}`,
+ runtimePolicyOverride: {
+ cwd,
+ approvalPolicy: "never",
+ sandboxPolicy: {
+ type: "readOnly",
+ access: { type: "fullAccess" },
+ networkAccess: false,
+ },
+ },
+ },
+ registryLayer,
+ ),
+ ),
+ );
+ }),
+ ),
+ );
it.live("checks the queued provider's capability while the current provider stays running", () =>
Effect.scoped(
@@ -2998,229 +2981,226 @@ describe("orchestration v2 provider switching", () => {
),
);
- for (const failResume of [false, true]) {
- it.live(
- `switches providers while consuming a pending cross-provider merge-back (resume failure: ${failResume})`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
- const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
- const firstSourcePrompt = "Remember that the first source marker is amber.";
- const secondSourcePrompt = "Remember that the second source marker is violet.";
- const forkPrompt = "Remember that the fork marker is cobalt.";
- const mergePrompt = "Report all three remembered markers.";
- const cwd = yield* checkpointWorkspace("cross-provider-merge");
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
- const registryLayer = ProviderAdapterRegistry.makeLayer([
- makeTestAdapter({
- instanceId: ProviderInstanceId.make("codex"),
- driver: CODEX_DRIVER,
- capabilities: CodexProviderCapabilitiesV2,
- modelSelection: CODEX_MODEL_SELECTION,
- responseByRunOrdinal: {},
- responseByThreadId: {
- [sourceThreadId]: {
- 1: "I will remember amber.",
- 3: "The markers are amber, violet, and cobalt.",
- },
- [forkThreadId]: {
- 1: "I will remember cobalt.",
- },
+ it.live.each([false, true])(
+ "switches providers while consuming a pending cross-provider merge-back (resume failure: %s)",
+ (failResume) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const sourceThreadId = ThreadId.make("thread:cross-provider-merge:source");
+ const forkThreadId = ThreadId.make("thread:cross-provider-merge:fork");
+ const firstSourcePrompt = "Remember that the first source marker is amber.";
+ const secondSourcePrompt = "Remember that the second source marker is violet.";
+ const forkPrompt = "Remember that the fork marker is cobalt.";
+ const mergePrompt = "Report all three remembered markers.";
+ const cwd = yield* checkpointWorkspace("cross-provider-merge");
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
+ const registryLayer = ProviderAdapterRegistry.makeLayer([
+ makeTestAdapter({
+ instanceId: ProviderInstanceId.make("codex"),
+ driver: CODEX_DRIVER,
+ capabilities: CodexProviderCapabilitiesV2,
+ modelSelection: CODEX_MODEL_SELECTION,
+ responseByRunOrdinal: {},
+ responseByThreadId: {
+ [sourceThreadId]: {
+ 1: "I will remember amber.",
+ 3: "The markers are amber, violet, and cobalt.",
+ },
+ [forkThreadId]: {
+ 1: "I will remember cobalt.",
},
- capturedTurns,
- failResume,
- }),
- makeTestAdapter({
- instanceId: ProviderInstanceId.make("claudeAgent"),
- driver: CLAUDE_DRIVER,
- capabilities: ClaudeProviderCapabilitiesV2,
- modelSelection: CLAUDE_MODEL_SELECTION,
- responseByRunOrdinal: { 2: "I will remember violet." },
- capturedTurns,
- }),
- ]);
- const commands = [
- {
- type: "thread.create",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:create"),
- threadId: sourceThreadId,
- projectId,
- title: "Cross-provider merge source",
- modelSelection: CODEX_MODEL_SELECTION,
- runtimeMode: "full-access",
- interactionMode: "default",
- branch: null,
- worktreePath: null,
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:first-source"),
- threadId: sourceThreadId,
- messageId: MessageId.make("message:cross-provider-merge:first-source"),
- text: firstSourcePrompt,
- attachments: [],
- modelSelection: CODEX_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:second-source"),
- threadId: sourceThreadId,
- messageId: MessageId.make("message:cross-provider-merge:second-source"),
- text: secondSourcePrompt,
- attachments: [],
- modelSelection: CLAUDE_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "thread.fork",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:fork"),
- sourceThreadId,
- targetThreadId: forkThreadId,
- sourcePoint: { type: "latest_stable" },
- title: "Cross-provider merge fork",
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
- threadId: forkThreadId,
- messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
- text: forkPrompt,
- attachments: [],
- modelSelection: CODEX_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
- },
- {
- type: "thread.merge_back",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:merge"),
- sourceThreadId: forkThreadId,
- targetThreadId: sourceThreadId,
- sourcePoint: { type: "latest_stable" },
- },
- {
- type: "message.dispatch",
- createdBy: "user",
- creationSource: "web",
- commandId: CommandId.make("command:cross-provider-merge:consume"),
- threadId: sourceThreadId,
- messageId: MessageId.make("message:cross-provider-merge:consume"),
- text: mergePrompt,
- attachments: [],
- modelSelection: CODEX_MODEL_SELECTION,
- dispatchMode: { type: "start_immediately" },
},
- ] satisfies ReadonlyArray<OrchestrationV2Command>;
+ capturedTurns,
+ failResume,
+ }),
+ makeTestAdapter({
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ driver: CLAUDE_DRIVER,
+ capabilities: ClaudeProviderCapabilitiesV2,
+ modelSelection: CLAUDE_MODEL_SELECTION,
+ responseByRunOrdinal: { 2: "I will remember violet." },
+ capturedTurns,
+ }),
+ ]);
+ const commands = [
+ {
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:create"),
+ threadId: sourceThreadId,
+ projectId,
+ title: "Cross-provider merge source",
+ modelSelection: CODEX_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ },
+ {
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:first-source"),
+ threadId: sourceThreadId,
+ messageId: MessageId.make("message:cross-provider-merge:first-source"),
+ text: firstSourcePrompt,
+ attachments: [],
+ modelSelection: CODEX_MODEL_SELECTION,
+ dispatchMode: { type: "start_immediately" },
+ },
+ {
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:second-source"),
+ threadId: sourceThreadId,
+ messageId: MessageId.make("message:cross-provider-merge:second-source"),
+ text: secondSourcePrompt,
+ attachments: [],
+ modelSelection: CLAUDE_MODEL_SELECTION,
+ dispatchMode: { type: "start_immediately" },
+ },
+ {
+ type: "thread.fork",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:fork"),
+ sourceThreadId,
+ targetThreadId: forkThreadId,
+ sourcePoint: { type: "latest_stable" },
+ title: "Cross-provider merge fork",
+ },
+ {
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:fork-turn"),
+ threadId: forkThreadId,
+ messageId: MessageId.make("message:cross-provider-merge:fork-turn"),
+ text: forkPrompt,
+ attachments: [],
+ modelSelection: CODEX_MODEL_SELECTION,
+ dispatchMode: { type: "start_immediately" },
+ },
+ {
+ type: "thread.merge_back",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:merge"),
+ sourceThreadId: forkThreadId,
+ targetThreadId: sourceThreadId,
+ sourcePoint: { type: "latest_stable" },
+ },
+ {
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:cross-provider-merge:consume"),
+ threadId: sourceThreadId,
+ messageId: MessageId.make("message:cross-provider-merge:consume"),
+ text: mergePrompt,
+ attachments: [],
+ modelSelection: CODEX_MODEL_SELECTION,
+ dispatchMode: { type: "start_immediately" },
+ },
+ ] satisfies ReadonlyArray<OrchestrationV2Command>;
- const projection = yield* Effect.gen(function* () {
- const orchestrator = yield* Orchestrator.OrchestratorV2;
- yield* orchestrator.dispatch(commands[0]!);
- yield* orchestrator.dispatch(commands[1]!);
- yield* waitForIdle(sourceThreadId);
- yield* orchestrator.dispatch(commands[2]!);
- yield* waitForIdle(sourceThreadId);
- yield* orchestrator.dispatch(commands[3]!);
- yield* orchestrator.dispatch(commands[4]!);
- yield* waitForIdle(forkThreadId);
- yield* orchestrator.dispatch(commands[5]!);
- if (failResume) {
- // A persisted native ref that is not loaded in this process must
- // exercise resume rather than the session manager's warm cache.
- const beforeResume = yield* orchestrator.getThreadProjection(sourceThreadId);
- const codexThread = beforeResume.providerThreads.find(
- (thread) => thread.id === beforeResume.runs[0]?.providerThreadId,
- )!;
- yield* (yield* EventSink.EventSinkV2).write({
- events: [
- {
- id: EventId.make("unloaded-merge-target"),
- type: "provider-thread.updated",
- threadId: sourceThreadId,
- occurredAt: yield* DateTime.now,
- payload: {
- ...codexThread,
- nativeThreadRef: {
- ...codexThread.nativeThreadRef!,
- nativeId: "unloaded-native-merge-target",
- },
- },
- },
- ],
- });
- }
- yield* orchestrator.dispatch(commands[6]!);
- return yield* waitForIdle(sourceThreadId);
- }).pipe(
- Effect.provide(
- makeOrchestratorV2ReplayLayerWithRegistry(
+ const projection = yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ yield* orchestrator.dispatch(commands[0]!);
+ yield* orchestrator.dispatch(commands[1]!);
+ yield* waitForIdle(sourceThreadId);
+ yield* orchestrator.dispatch(commands[2]!);
+ yield* waitForIdle(sourceThreadId);
+ yield* orchestrator.dispatch(commands[3]!);
+ yield* orchestrator.dispatch(commands[4]!);
+ yield* waitForIdle(forkThreadId);
+ yield* orchestrator.dispatch(commands[5]!);
+ if (failResume) {
+ // A persisted native ref that is not loaded in this process must
+ // exercise resume rather than the session manager's warm cache.
+ const beforeResume = yield* orchestrator.getThreadProjection(sourceThreadId);
+ const codexThread = beforeResume.providerThreads.find(
+ (thread) => thread.id === beforeResume.runs[0]?.providerThreadId,
+ )!;
+ yield* (yield* EventSink.EventSinkV2).write({
+ events: [
{
- name: "cross-provider-merge",
- runtimePolicyOverride: {
- cwd,
- approvalPolicy: "never",
- sandboxPolicy: {
- type: "readOnly",
- access: { type: "fullAccess" },
- networkAccess: false,
+ id: EventId.make("unloaded-merge-target"),
+ type: "provider-thread.updated",
+ threadId: sourceThreadId,
+ occurredAt: yield* DateTime.now,
+ payload: {
+ ...codexThread,
+ nativeThreadRef: {
+ ...codexThread.nativeThreadRef!,
+ nativeId: "unloaded-native-merge-target",
},
},
},
- registryLayer,
- ),
+ ],
+ });
+ }
+ yield* orchestrator.dispatch(commands[6]!);
+ return yield* waitForIdle(sourceThreadId);
+ }).pipe(
+ Effect.provide(
+ makeOrchestratorV2ReplayLayerWithRegistry(
+ {
+ name: "cross-provider-merge",
+ runtimePolicyOverride: {
+ cwd,
+ approvalPolicy: "never",
+ sandboxPolicy: {
+ type: "readOnly",
+ access: { type: "fullAccess" },
+ networkAccess: false,
+ },
+ },
+ },
+ registryLayer,
),
+ ),
+ );
+ const turns = yield* Ref.get(capturedTurns);
+ const mergedTurn = turns.findLast(
+ (turn) => turn.threadId === sourceThreadId && turn.driver === "codex",
+ );
+ const mergeTransfer = projection.contextTransfers.find(
+ (transfer) => transfer.type === "merge_back",
+ );
+
+ if (failResume)
+ assert.isAtLeast(
+ projection.contextHandoffs.filter(
+ (handoff) => handoff.targetRunId === projection.runs.at(-1)?.id,
+ ).length,
+ 2,
);
- const turns = yield* Ref.get(capturedTurns);
- const mergedTurn = turns.findLast(
- (turn) => turn.threadId === sourceThreadId && turn.driver === "codex",
- );
- const mergeTransfer = projection.contextTransfers.find(
- (transfer) => transfer.type === "merge_back",
+ assert.isDefined(mergedTurn);
+ if (failResume)
+ assert.notEqual(
+ projection.providerThreads.find((thread) => thread.id === mergedTurn.providerThreadId)
+ ?.nativeThreadRef?.nativeId,
+ "unloaded-native-merge-target",
);
-
- if (failResume)
- assert.isAtLeast(
- projection.contextHandoffs.filter(
- (handoff) => handoff.targetRunId === projection.runs.at(-1)?.id,
- ).length,
- 2,
- );
- assert.isDefined(mergedTurn);
- if (failResume)
- assert.notEqual(
- projection.providerThreads.find(
- (thread) => thread.id === mergedTurn.providerThreadId,
- )?.nativeThreadRef?.nativeId,
- "unloaded-native-merge-target",
- );
- assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
- assert.include(mergedTurn.text, firstSourcePrompt);
- assert.include(mergedTurn.text, "I will remember amber.");
- assert.include(mergedTurn.text, secondSourcePrompt);
- assert.include(mergedTurn.text, "I will remember violet.");
- assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
- assert.include(mergedTurn.text, forkPrompt);
- assert.include(mergedTurn.text, "I will remember cobalt.");
- assert.include(mergedTurn.text, mergePrompt);
- assert.isDefined(mergeTransfer);
- assert.equal(mergeTransfer.status, "consumed");
- assert.equal(mergeTransfer.targetProviderInstanceId, "codex");
- assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
- }),
- ),
- );
- }
+ assert.include(mergedTurn.text, "Context handoff (full_thread_summary):");
+ assert.include(mergedTurn.text, firstSourcePrompt);
+ assert.include(mergedTurn.text, "I will remember amber.");
+ assert.include(mergedTurn.text, secondSourcePrompt);
+ assert.include(mergedTurn.text, "I will remember violet.");
+ assert.include(mergedTurn.text, "Context handoff (merge_back / fork_delta_summary):");
+ assert.include(mergedTurn.text, forkPrompt);
+ assert.include(mergedTurn.text, "I will remember cobalt.");
+ assert.include(mergedTurn.text, mergePrompt);
+ assert.isDefined(mergeTransfer);
+ assert.equal(mergeTransfer.status, "consumed");
+ assert.equal(mergeTransfer.targetProviderInstanceId, "codex");
+ assert.equal(mergeTransfer.resolution?.strategy, "fork_delta_context");
+ }),
+ ),
+ );
it.live("routes two custom instances of the same driver independently", () =>
Effect.scoped(
diff --git a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
index 92837e4974a..e22d847037a 100644
--- a/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts
@@ -257,8 +257,9 @@ function makeCreateCommand(input: {
}
describe("orchestration V2 merge-back provider replay", () => {
- for (const variant of PROVIDERS) {
- it.effect(`merges one fork delta back into the original ${variant.driver} thread`, () =>
+ it.effect.each(PROVIDERS)(
+ "merges one fork delta back into the original $driver thread",
+ (variant) =>
Effect.gen(function* () {
const rawTranscript = yield* readTranscript("thread_merge_back_continue", variant.driver);
const materialized = yield* Effect.gen(function* () {
@@ -452,9 +453,11 @@ describe("orchestration V2 merge-back provider replay", () => {
assert.notInclude(visibleConversationText(source), "Context handoff (");
assert.include(visibleConversationText(fork), "merge fork stored");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
+ );
- it.effect(`merges two sibling fork deltas into the original ${variant.driver} thread`, () =>
+ it.effect.each(PROVIDERS)(
+ "merges two sibling fork deltas into the original $driver thread",
+ (variant) =>
Effect.gen(function* () {
const rawTranscript = yield* readTranscript("thread_merge_back_siblings", variant.driver);
const materialized = yield* Effect.gen(function* () {
@@ -725,6 +728,5 @@ describe("orchestration V2 merge-back provider replay", () => {
assert.include(visibleConversationText(secondFork), "second merge sibling stored");
assert.notInclude(visibleConversationText(secondFork), "first merge sibling stored");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
- }
+ );
});
diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts
index b053c240340..fc43700b06a 100644
--- a/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts
+++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.test.ts
@@ -394,8 +394,9 @@ layer("OrchestrationEventStore", (it) => {
);
});
-for (const phase of ["high-water", "replay"] as const) {
- it.effect(`bounds application live events while the ${phase} query is blocked`, () =>
+it.effect.each(["high-water", "replay"] as const)(
+ "bounds application live events while the %s query is blocked",
+ (phase) =>
Effect.scoped(
Effect.gen(function* () {
const store = yield* OrchestrationEventStore.OrchestrationEventStore;
@@ -464,8 +465,7 @@ for (const phase of ["high-water", "replay"] as const) {
}
}),
).pipe(Effect.provide(Layer.fresh(TestLayer))),
- );
-}
+);
it.effect("releases consumed application replay pages", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index 88a393f8989..ecaec10e5b4 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -60,8 +60,9 @@ describe("V2 preview upgrade", () => {
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
- for (const withIndexes of [false, true]) {
- it.effect(`upgrades preview migration 54 with index cleanup ${withIndexes}`, () =>
+ it.effect.each([false, true])(
+ "upgrades preview migration 54 with index cleanup %s",
+ (withIndexes) =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 52 });
@@ -89,8 +90,7 @@ describe("V2 preview upgrade", () => {
}>`PRAGMA table_info(projection_threads)`;
assert.ok(columns.some((column) => column.name === "auto_settle_disabled_at"));
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
- );
- }
+ );
it.effect("rolls back schema and ledger together on failure and can retry", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts
index 725314b27e1..1bad9db0df1 100644
--- a/apps/server/src/provider/CodexChatGptAuth.test.ts
+++ b/apps/server/src/provider/CodexChatGptAuth.test.ts
@@ -426,36 +426,34 @@ it.effect(
}),
),
);
-for (const failure of ["identity", "sharing"] as const) {
- it.effect(
- `failed account change preserves the original credentials and registration: ${failure}`,
- () =>
- provision(
- Effect.gen(function* () {
- const h = yield* makeHarness;
- yield* h.signIn;
- yield* h.phase("succeeded");
- const before = h.storedRecords();
- h.setCallbackClientId("oaiapp_other_account");
- if (failure === "identity") h.setInvalidNonce();
- else h.declineSharing();
- yield* h.changeAccount;
- yield* h.phase("failed");
- assert.strictEqual(
- h.authorizationRequests[1]!.searchParams.get("client_id"),
- "dynamic_agent_client",
+it.effect.each(["identity", "sharing"] as const)(
+ "failed account change preserves the original credentials and registration: %s",
+ (failure) =>
+ provision(
+ Effect.gen(function* () {
+ const h = yield* makeHarness;
+ yield* h.signIn;
+ yield* h.phase("succeeded");
+ const before = h.storedRecords();
+ h.setCallbackClientId("oaiapp_other_account");
+ if (failure === "identity") h.setInvalidNonce();
+ else h.declineSharing();
+ yield* h.changeAccount;
+ yield* h.phase("failed");
+ assert.strictEqual(
+ h.authorizationRequests[1]!.searchParams.get("client_id"),
+ "dynamic_agent_client",
+ );
+ if (failure === "sharing") {
+ assert.deepEqual(
+ Option.getOrThrow(yield* h.auth.read),
+ before.find((record) => record.accessToken),
);
- if (failure === "sharing") {
- assert.deepEqual(
- Option.getOrThrow(yield* h.auth.read),
- before.find((record) => record.accessToken),
- );
- assert.lengthOf(h.storedRecords().find((record) => record.profiles).profiles, 2);
- } else assert.deepEqual(h.storedRecords(), before);
- }),
- ),
- );
-}
+ assert.lengthOf(h.storedRecords().find((record) => record.profiles).profiles, 2);
+ } else assert.deepEqual(h.storedRecords(), before);
+ }),
+ ),
+);
it.effect("retains the callback host and path after controller recreation and token removal", () =>
provision(
Effect.gen(function* () {
@@ -961,48 +959,42 @@ it.effect("rejects mismatched callback state before any token exchange or creden
}),
),
);
-for (const invalidClaim of ["issuer", "audience", "signature"] as const) {
- it.effect(
- `rejects ID token ${invalidClaim} verification before saving tokens or registration`,
- () =>
- provision(
- Effect.gen(function* () {
- const h = yield* makeHarness;
- h.setIdentityFailure(invalidClaim);
- yield* h.signIn;
- assert.include((yield* h.phase("failed")).message!, "could not be verified");
- assert.strictEqual(h.exchanges.length, 1);
- assert.deepEqual(h.storedRecords(), []);
- assert.isTrue(Option.isNone(yield* h.auth.read));
- }),
- ),
- );
-}
-for (const revoked of [false, true]) {
- it.effect(
- `rejects conflicting callback client ID on reauthorization ${revoked ? "after token removal" : "without changing the current account"}`,
- () =>
- provision(
- Effect.gen(function* () {
- const h = yield* makeHarness;
- yield* h.signIn;
- yield* h.phase("succeeded");
- if (revoked) yield* h.auth.revoke;
- const before = h.storedRecords();
- h.setCallbackClientId("oaiapp_untrusted_callback");
- yield* h.signIn;
- assert.include((yield* h.phase("failed")).message!, "registration is incomplete");
- assert.strictEqual(
- h.authorizationRequests[1]?.searchParams.get("client_id"),
- "oaiapp_test",
- );
- assert.strictEqual(h.exchanges.length, 1);
- assert.deepEqual(h.storedRecords(), before);
- assert.strictEqual(Option.isNone(yield* h.auth.read), revoked);
- }),
- ),
- );
-}
+it.effect.each(["issuer", "audience", "signature"] as const)(
+ "rejects ID token %s verification before saving tokens or registration",
+ (invalidClaim) =>
+ provision(
+ Effect.gen(function* () {
+ const h = yield* makeHarness;
+ h.setIdentityFailure(invalidClaim);
+ yield* h.signIn;
+ assert.include((yield* h.phase("failed")).message!, "could not be verified");
+ assert.strictEqual(h.exchanges.length, 1);
+ assert.deepEqual(h.storedRecords(), []);
+ assert.isTrue(Option.isNone(yield* h.auth.read));
+ }),
+ ),
+);
+it.effect.each([
+ { revoked: false, label: "without changing the current account" },
+ { revoked: true, label: "after token removal" },
+])("rejects conflicting callback client ID on reauthorization $label", ({ revoked }) =>
+ provision(
+ Effect.gen(function* () {
+ const h = yield* makeHarness;
+ yield* h.signIn;
+ yield* h.phase("succeeded");
+ if (revoked) yield* h.auth.revoke;
+ const before = h.storedRecords();
+ h.setCallbackClientId("oaiapp_untrusted_callback");
+ yield* h.signIn;
+ assert.include((yield* h.phase("failed")).message!, "registration is incomplete");
+ assert.strictEqual(h.authorizationRequests[1]?.searchParams.get("client_id"), "oaiapp_test");
+ assert.strictEqual(h.exchanges.length, 1);
+ assert.deepEqual(h.storedRecords(), before);
+ assert.strictEqual(Option.isNone(yield* h.auth.read), revoked);
+ }),
+ ),
+);
it.effect("returns successful desktop sign-in to the original Welcome step", () =>
provision(
@@ -1157,26 +1149,25 @@ it.effect(
),
);
-for (const disconnected of [false, true]) {
- it.effect(
- `rejects a different verified identity during saved-profile reauth ${disconnected ? "after Disconnect" : "while connected"}`,
- () =>
- provision(
- Effect.gen(function* () {
- const h = yield* makeHarness;
- yield* h.signIn;
- yield* h.phase("succeeded");
- if (disconnected) yield* h.auth.controller.logout(Effect.void);
- const before = h.storedRecords();
- h.setIdentity("another-user", "[email protected]");
- yield* h.signIn;
- assert.include((yield* h.phase("failed")).message!, "different ChatGPT account");
- assert.deepEqual(h.storedRecords(), before);
- assert.strictEqual(Option.isNone(yield* h.auth.read), disconnected);
- }),
- ),
- );
-}
+it.effect.each([
+ { disconnected: false, label: "while connected" },
+ { disconnected: true, label: "after Disconnect" },
+])("rejects a different verified identity during saved-profile reauth $label", ({ disconnected }) =>
+ provision(
+ Effect.gen(function* () {
+ const h = yield* makeHarness;
+ yield* h.signIn;
+ yield* h.phase("succeeded");
+ if (disconnected) yield* h.auth.controller.logout(Effect.void);
+ const before = h.storedRecords();
+ h.setIdentity("another-user", "[email protected]");
+ yield* h.signIn;
+ assert.include((yield* h.phase("failed")).message!, "different ChatGPT account");
+ assert.deepEqual(h.storedRecords(), before);
+ assert.strictEqual(Option.isNone(yield* h.auth.read), disconnected);
+ }),
+ ),
+);
it.effect(
"retains both profiles and reuses the original account's client and callback when returning from another account",
@@ -1427,7 +1418,7 @@ it.effect(
),
);
-for (const code of [
+it.effect.each([
"invalid_grant",
"invalid_refresh_token",
"token_expired",
@@ -1436,33 +1427,31 @@ for (const code of [
"refresh_token_reused",
"invalid_client",
"invalid_token",
-]) {
- it.effect(`refresh recovery follows the machine-readable code: ${code}`, () =>
- provision(
- Effect.gen(function* () {
- const h = yield* makeHarness;
- yield* h.signIn;
- yield* h.phase("succeeded");
- yield* h.seedExpired;
- h.setRefreshError(code);
- yield* Effect.flip(h.auth.access);
- assert.strictEqual(
- Option.isNone(yield* h.auth.read),
- !["invalid_client", "invalid_token"].includes(code),
- );
- assert.isTrue(
- h
- .storedRecords()
- .some((record) =>
- record.profiles?.some(
- (profile: { clientId: string }) => profile.clientId === "oaiapp_test",
- ),
+])("refresh recovery follows the machine-readable code: %s", (code) =>
+ provision(
+ Effect.gen(function* () {
+ const h = yield* makeHarness;
+ yield* h.signIn;
+ yield* h.phase("succeeded");
+ yield* h.seedExpired;
+ h.setRefreshError(code);
+ yield* Effect.flip(h.auth.access);
+ assert.strictEqual(
+ Option.isNone(yield* h.auth.read),
+ !["invalid_client", "invalid_token"].includes(code),
+ );
+ assert.isTrue(
+ h
+ .storedRecords()
+ .some((record) =>
+ record.profiles?.some(
+ (profile: { clientId: string }) => profile.clientId === "oaiapp_test",
),
- );
- }),
- ),
- );
-}
+ ),
+ );
+ }),
+ ),
+);
it.effect(
"logout revokes the latest refresh token with the selected client and clears its ID hint",
diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts
index a0d22decc0c..2cc54cf8328 100644
--- a/apps/server/src/provider/CodexInstallation.test.ts
+++ b/apps/server/src/provider/CodexInstallation.test.ts
@@ -92,8 +92,9 @@ const terminalState = (installation: CodexInstallation.CodexInstallation["Servic
Effect.map(Option.getOrThrow),
);
-for (const version of ["0.156.0", "0.156.1", "0.156.2", "0.157.0"]) {
- it.effect(`reuses installed Codex ${version} without downloading or taking ownership of it`, () =>
+it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
+ "reuses installed Codex %s without downloading or taking ownership of it",
+ (version) =>
Effect.gen(function* () {
const h = yield* makeHarness({ local: { version } });
expect(yield* h.installation.start).toMatchObject({
@@ -120,9 +121,8 @@ for (const version of ["0.156.0", "0.156.1", "0.156.2", "0.157.0"]) {
expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
expect((yield* h.installation.state).source).toBe("local");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
-}
-for (const local of [
+);
+it.effect.each([
{ version: "0.128.9" },
{ version: "0.145.0" },
{ version: "0.155.1" },
@@ -131,24 +131,20 @@ for (const local of [
{ version: "unknown" },
{ version: "0.156.1", appServerFails: true },
{ version: "0.156.1", versionFails: true },
-]) {
- it.effect(
- `downloads the pinned release when the local CLI is unsupported or broken: ${JSON.stringify(local)}`,
- () =>
- Effect.gen(function* () {
- const h = yield* makeHarness({ local });
- expect((yield* h.installation.state).installedVersion).toBeNull();
- yield* h.installation.start;
- const installed = yield* terminalState(h.installation);
- expect(installed.phase).toBe("succeeded");
- const executable = yield* h.installation.resolve();
- expect(executable.source).toBe("managed");
- expect(installed.executablePath).toBe(executable.executablePath);
- expect(h.downloads()).toBe(1);
- expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
- }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
-}
+])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
+ Effect.gen(function* () {
+ const h = yield* makeHarness({ local });
+ expect((yield* h.installation.state).installedVersion).toBeNull();
+ yield* h.installation.start;
+ const installed = yield* terminalState(h.installation);
+ expect(installed.phase).toBe("succeeded");
+ const executable = yield* h.installation.resolve();
+ expect(executable.source).toBe("managed");
+ expect(installed.executablePath).toBe(executable.executablePath);
+ expect(h.downloads()).toBe(1);
+ expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
it.effect("falls back to a managed download when the reused local executable disappears", () =>
Effect.gen(function* () {
const h = yield* makeHarness({ local: { version: "0.156.1" } });
diff --git a/apps/server/src/provider/CodexManagedRuntime.test.ts b/apps/server/src/provider/CodexManagedRuntime.test.ts
index 33ccaa13ea8..494ff88a229 100644
--- a/apps/server/src/provider/CodexManagedRuntime.test.ts
+++ b/apps/server/src/provider/CodexManagedRuntime.test.ts
@@ -48,178 +48,174 @@ it.effect("managed home defaults to the global Codex home and honors configured
assert.equal(configured.effectiveHomePath, "/custom/shadow");
}).pipe(Effect.provide(NodeServices.layer)),
);
-for (const source of ["managed", "local"] as const)
- for (const account of ["primary", "additional"] as const)
- it.effect(
- `${source} Codex ${account} account shares home state without routing owned tokens through ambient CLI overrides`,
- () =>
- Effect.gen(function* () {
- const instanceId = ProviderInstanceId.make(
- account === "primary" ? "codex" : "codex-personal",
- );
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-shared-home-" });
- yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged");
- yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n");
- const data = new Map<string, Uint8Array>();
- const secrets = ServerSecretStore.ServerSecretStore.of({
- get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))),
- set: (key, value) =>
- Effect.sync(() => {
- data.set(key, value);
- }),
- remove: (key) =>
+it.effect.each(
+ (["managed", "local"] as const).flatMap((source) =>
+ (["primary", "additional"] as const).map((account) => ({ source, account })),
+ ),
+)(
+ "$source Codex $account account shares home state without routing owned tokens through ambient CLI overrides",
+ ({ source, account }) =>
+ Effect.gen(function* () {
+ const instanceId = ProviderInstanceId.make(
+ account === "primary" ? "codex" : "codex-personal",
+ );
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const sharedHome = yield* fs.makeTempDirectoryScoped({ prefix: "codex-shared-home-" });
+ yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged");
+ yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n");
+ const data = new Map<string, Uint8Array>();
+ const secrets = ServerSecretStore.ServerSecretStore.of({
+ get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))),
+ set: (key, value) =>
+ Effect.sync(() => {
+ data.set(key, value);
+ }),
+ remove: (key) =>
+ Effect.sync(() => {
+ data.delete(key);
+ }),
+ create: () => Effect.die("unused"),
+ getOrCreateRandom: () => Effect.die("unused"),
+ });
+ let leases = 0;
+ const executable = {
+ executablePath:
+ source === "managed" ? "/isolated/tools/codex/0.156.1/bin/codex" : "/user/bin/codex",
+ managedVersionDirectory: source === "managed" ? "/isolated/tools/codex/0.156.1" : null,
+ source,
+ version: "0.156.1",
+ };
+ const installerLayer = Layer.mock(CodexInstallation.CodexInstallation)({
+ managedDirectory: "/isolated/tools/codex",
+ resolve: () => Effect.succeed(executable),
+ acquire: () =>
+ Effect.gen(function* () {
+ leases++;
+ yield* Effect.addFinalizer(() =>
Effect.sync(() => {
- data.delete(key);
+ leases--;
}),
- create: () => Effect.die("unused"),
- getOrCreateRandom: () => Effect.die("unused"),
- });
- let leases = 0;
- const executable = {
- executablePath:
- source === "managed" ? "/isolated/tools/codex/0.156.1/bin/codex" : "/user/bin/codex",
- managedVersionDirectory: source === "managed" ? "/isolated/tools/codex/0.156.1" : null,
- source,
- version: "0.156.1",
- };
- const installerLayer = Layer.mock(CodexInstallation.CodexInstallation)({
- managedDirectory: "/isolated/tools/codex",
- resolve: () => Effect.succeed(executable),
- acquire: () =>
- Effect.gen(function* () {
- leases++;
- yield* Effect.addFinalizer(() =>
- Effect.sync(() => {
- leases--;
- }),
- );
- return executable;
- }),
- });
- yield* Effect.gen(function* () {
- const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
- const json = yield* encodeJson({
- clientId: "oaiapp_test",
- accessToken: "dummy-owned-access",
- refreshToken: "dummy-refresh",
- expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000,
- earliestRefreshAt: null,
- scopes: ["chatgpt.tokens.use.direct"],
- subject: "test-user",
- email: null,
- });
- yield* store.set(new TextEncoder().encode(json));
- const ambient = {
- CODEX_HOME: "/user/.codex",
- OPENAI_API_KEY: "dummy-global-key",
- OPENAI_BASE_URL: "https://user-proxy.test",
- T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy",
- PATH: "/usr/bin",
- };
- const runtime = yield* makeCodexManagedRuntime({
- instanceId,
- enabled: true,
- config: decodeSettings({ setupMode: "managed", homePath: sharedHome }),
- environment: ambient,
- });
- yield* Effect.gen(function* () {
- const effective = yield* runtime.resolve;
- assert.strictEqual(leases, 1);
- assert.strictEqual(effective.config.binaryPath, executable.executablePath);
- assert.notStrictEqual(effective.config.homePath, ambient.CODEX_HOME);
- assert.equal(runtime.homeLayout.sharedHomePath, sharedHome);
- if (account === "primary") {
- assert.equal(effective.config.homePath, sharedHome);
- assert.equal(runtime.homeLayout.mode, "direct");
- } else {
- assert.include(effective.config.homePath, instanceId);
- assert.include(effective.config.homePath, "userdata/providers/codex");
- assert.equal(runtime.homeLayout.mode, "authOverlay");
- assert.equal(
- yield* fs.readLink(path.join(effective.config.homePath, "sessions")),
- path.join(sharedHome, "sessions"),
- );
- assert.equal(
- yield* fs.readLink(path.join(effective.config.homePath, "config.toml")),
- path.join(sharedHome, "config.toml"),
- );
- assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
- }
- assert.strictEqual(effective.environment.ACCESS_TOKEN, "dummy-owned-access");
- assert.isUndefined(effective.environment.OPENAI_API_KEY);
- assert.isUndefined(effective.environment.OPENAI_BASE_URL);
- assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS);
- const args = codexAppServerArgs(effective.config.launchArgs);
- assert.include(
- args,
- 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"',
- );
- assert.include(
- args,
- 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"',
- );
- assert.include(args, "features.api_key_model_discovery=true");
- assert.notInclude(effective.config.launchArgs, "model_catalog_json");
- assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test");
- assert.include(
- args,
- "model_providers.openai_token_sharing.supports_websockets=false",
- );
- assert.include(
- args,
- "model_providers.openai_token_sharing.requires_openai_auth=false",
- );
- assert.notInclude(effective.config.launchArgs, "dummy-owned-access");
- assert.strictEqual(ambient.CODEX_HOME, "/user/.codex");
- }).pipe(Effect.scoped);
- assert.strictEqual(leases, 0);
- yield* runtime.auth.controller.logout(Effect.void);
+ );
+ return executable;
+ }),
+ });
+ yield* Effect.gen(function* () {
+ const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
+ const json = yield* encodeJson({
+ clientId: "oaiapp_test",
+ accessToken: "dummy-owned-access",
+ refreshToken: "dummy-refresh",
+ expiresAt: (yield* Clock.currentTimeMillis) + 3_600_000,
+ earliestRefreshAt: null,
+ scopes: ["chatgpt.tokens.use.direct"],
+ subject: "test-user",
+ email: null,
+ });
+ yield* store.set(new TextEncoder().encode(json));
+ const ambient = {
+ CODEX_HOME: "/user/.codex",
+ OPENAI_API_KEY: "dummy-global-key",
+ OPENAI_BASE_URL: "https://user-proxy.test",
+ T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy",
+ PATH: "/usr/bin",
+ };
+ const runtime = yield* makeCodexManagedRuntime({
+ instanceId,
+ enabled: true,
+ config: decodeSettings({ setupMode: "managed", homePath: sharedHome }),
+ environment: ambient,
+ });
+ yield* Effect.gen(function* () {
+ const effective = yield* runtime.resolve;
+ assert.strictEqual(leases, 1);
+ assert.strictEqual(effective.config.binaryPath, executable.executablePath);
+ assert.notStrictEqual(effective.config.homePath, ambient.CODEX_HOME);
+ assert.equal(runtime.homeLayout.sharedHomePath, sharedHome);
+ if (account === "primary") {
+ assert.equal(effective.config.homePath, sharedHome);
+ assert.equal(runtime.homeLayout.mode, "direct");
+ } else {
+ assert.include(effective.config.homePath, instanceId);
+ assert.include(effective.config.homePath, "userdata/providers/codex");
+ assert.equal(runtime.homeLayout.mode, "authOverlay");
assert.equal(
- yield* fs.readFileString(path.join(sharedHome, "auth.json")),
- "native-auth-unchanged",
+ yield* fs.readLink(path.join(effective.config.homePath, "sessions")),
+ path.join(sharedHome, "sessions"),
);
- }).pipe(
- Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
- Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
- getEnvironmentId: Effect.succeed(
- EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
- ),
- }),
- Effect.provide(installerLayer),
- Effect.provideService(
- HttpClient.HttpClient,
- HttpClient.make((request) =>
- Effect.sync(() => {
- assert.isTrue(
- [
- "https://auth.openai.com/.well-known/openid-configuration",
- "https://auth.openai.com/revoke",
- ].includes(request.url),
- );
- return HttpClientResponse.fromWeb(
- request,
- request.url.endsWith("/revoke")
- ? new Response(null, { status: 200 })
- : Response.json({
- issuer: "https://auth.openai.com",
- authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
- token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
- jwks_uri: "https://auth.openai.com/jwks",
- revocation_endpoint: "https://auth.openai.com/revoke",
- }),
- );
- }),
- ),
- ),
+ assert.equal(
+ yield* fs.readLink(path.join(effective.config.homePath, "config.toml")),
+ path.join(sharedHome, "config.toml"),
+ );
+ assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json")));
+ }
+ assert.strictEqual(effective.environment.ACCESS_TOKEN, "dummy-owned-access");
+ assert.isUndefined(effective.environment.OPENAI_API_KEY);
+ assert.isUndefined(effective.environment.OPENAI_BASE_URL);
+ assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS);
+ const args = codexAppServerArgs(effective.config.launchArgs);
+ assert.include(
+ args,
+ 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"',
+ );
+ assert.include(
+ args,
+ 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"',
);
- }).pipe(
- Effect.scoped,
- Effect.provide(
- ServerConfig.layerTest(process.cwd(), {
- prefix: "t3-managed-runtime-",
- }).pipe(Layer.provideMerge(NodeServices.layer)),
+ assert.include(args, "features.api_key_model_discovery=true");
+ assert.notInclude(effective.config.launchArgs, "model_catalog_json");
+ assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test");
+ assert.include(args, "model_providers.openai_token_sharing.supports_websockets=false");
+ assert.include(args, "model_providers.openai_token_sharing.requires_openai_auth=false");
+ assert.notInclude(effective.config.launchArgs, "dummy-owned-access");
+ assert.strictEqual(ambient.CODEX_HOME, "/user/.codex");
+ }).pipe(Effect.scoped);
+ assert.strictEqual(leases, 0);
+ yield* runtime.auth.controller.logout(Effect.void);
+ assert.equal(
+ yield* fs.readFileString(path.join(sharedHome, "auth.json")),
+ "native-auth-unchanged",
+ );
+ }).pipe(
+ Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
+ Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
+ getEnvironmentId: Effect.succeed(
+ EnvironmentId.make("00000000-0000-4000-8000-000000000001"),
+ ),
+ }),
+ Effect.provide(installerLayer),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make((request) =>
+ Effect.sync(() => {
+ assert.isTrue(
+ [
+ "https://auth.openai.com/.well-known/openid-configuration",
+ "https://auth.openai.com/revoke",
+ ].includes(request.url),
+ );
+ return HttpClientResponse.fromWeb(
+ request,
+ request.url.endsWith("/revoke")
+ ? new Response(null, { status: 200 })
+ : Response.json({
+ issuer: "https://auth.openai.com",
+ authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
+ token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
+ jwks_uri: "https://auth.openai.com/jwks",
+ revocation_endpoint: "https://auth.openai.com/revoke",
+ }),
+ );
+ }),
),
),
- );
+ );
+ }).pipe(
+ Effect.scoped,
+ Effect.provide(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-managed-runtime-",
+ }).pipe(Layer.provideMerge(NodeServices.layer)),
+ ),
+ ),
+);
diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
index d881b5f22a4..32f207e2b62 100644
--- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
+++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts
@@ -33,8 +33,9 @@ const mockRuntimeOptions = {
} satisfies AcpSessionRuntime.AcpSessionRuntimeOptions;
describe("AcpSessionRuntime", () => {
- for (const setupMethod of ["session/new", "session/resume"] as const) {
- it.effect(`buffers root metadata while ${setupMethod} startup is still pending`, () =>
+ it.effect.each(["session/new", "session/resume"] as const)(
+ "buffers root metadata while %s startup is still pending",
+ (setupMethod) =>
Effect.gen(function* () {
const setupReplied = yield* Deferred.make<void>();
const allowStartup = yield* Deferred.make<void>();
@@ -91,8 +92,7 @@ describe("AcpSessionRuntime", () => {
(yield* runtime.getConfigOptions).find((option) => option.category === "model"),
).toMatchObject({ currentValue: "gpt-5.4" });
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
- );
- }
+ );
it.effect("publishes model changes returned by a config request and live notifications", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 0460eb82f8f..7415ae45bfa 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -2287,7 +2287,7 @@ it.effect("routes Azure reads and writes through the requested organization's ch
}),
);
-for (const checkout of [
+it.effect.each([
{
host: "ssh.dev.azure.com",
repository: "v3/org-b/project/web",
@@ -2303,57 +2303,55 @@ for (const checkout of [
repository: "DefaultCollection/project/_git/web",
remoteUrl: "https://org-b.visualstudio.com/DefaultCollection/project/_git/web",
},
-]) {
- it.effect(`routes Azure URL reads and writes through a ${checkout.host} checkout`, () =>
- Effect.gen(function* () {
- const seen: string[] = [];
- const target = project({
- id: "target",
- title: "target",
- workspaceRoot: "/target",
- provider: "azure-devops",
- ...checkout,
- });
- const service = yield* makeService({
- projects: [
- ...["org-a/project/_git/web", "org-b/other-project/_git/web"].map((repository) =>
- project({
- id: repository,
- title: repository,
- workspaceRoot: `/${repository}`,
- provider: "azure-devops",
- host: "dev.azure.com",
- repository,
- }),
- ),
- target,
- ],
- providers: [
- fakeProvider("azure-devops", {
- getChangeRequestSummary: (input) =>
- Effect.sync(() => {
- seen.push(`read ${input.cwd} ${input.repository}`);
- return changeRequest(7, "2026-07-02T00:00:00Z");
- }),
- runAction: (input) =>
- Effect.sync(() => {
- seen.push(`write ${input.cwd} ${input.repository}`);
- }),
+])("routes Azure URL reads and writes through a $host checkout", (checkout) =>
+ Effect.gen(function* () {
+ const seen: string[] = [];
+ const target = project({
+ id: "target",
+ title: "target",
+ workspaceRoot: "/target",
+ provider: "azure-devops",
+ ...checkout,
+ });
+ const service = yield* makeService({
+ projects: [
+ ...["org-a/project/_git/web", "org-b/other-project/_git/web"].map((repository) =>
+ project({
+ id: repository,
+ title: repository,
+ workspaceRoot: `/${repository}`,
+ provider: "azure-devops",
+ host: "dev.azure.com",
+ repository,
}),
- ],
- });
- const reference = {
- projectId: "org-a/project/_git/web" as ProjectId,
- host: "dev.azure.com",
- repository: "org-b/project/_git/web",
- number: 7,
- };
- yield* service.summary(reference, { recoverTransientFailure: false });
- yield* service.runAction({ ...reference, action: "merge" });
- assert.deepStrictEqual(seen, ["read /target web", "write /target web", "read /target web"]);
- }),
- );
-}
+ ),
+ target,
+ ],
+ providers: [
+ fakeProvider("azure-devops", {
+ getChangeRequestSummary: (input) =>
+ Effect.sync(() => {
+ seen.push(`read ${input.cwd} ${input.repository}`);
+ return changeRequest(7, "2026-07-02T00:00:00Z");
+ }),
+ runAction: (input) =>
+ Effect.sync(() => {
+ seen.push(`write ${input.cwd} ${input.repository}`);
+ }),
+ }),
+ ],
+ });
+ const reference = {
+ projectId: "org-a/project/_git/web" as ProjectId,
+ host: "dev.azure.com",
+ repository: "org-b/project/_git/web",
+ number: 7,
+ };
+ yield* service.summary(reference, { recoverTransientFailure: false });
+ yield* service.runAction({ ...reference, action: "merge" });
+ assert.deepStrictEqual(seen, ["read /target web", "write /target web", "read /target web"]);
+ }),
+);
it.effect("refuses Azure cross-organization reads and writes without its checkout", () =>
Effect.gen(function* () {
@@ -5042,104 +5040,102 @@ it.effect('resolves an author filter of "me" to the viewer before narrowing a ho
}),
);
-for (const crossHost of [false, true]) {
- it.effect(
- `authorizes stack rebases and refreshes sibling layers (cross-host: ${crossHost})`,
- () =>
- Effect.gen(function* () {
- let taken = 0;
- let summaryReads = 0;
- let mutationFails = false;
- let stackRebase = true;
- let stackActions = true;
- const capabilities = {
- diff: true,
- comment: true,
- actions: ["update-branch"] as const,
- mergeMethods: ["merge"] as const,
- updateMethods: ["rebase"] as const,
- get stackActions() {
- return stackActions;
- },
- search: true,
- reactions: true,
- review: FULL_REVIEW,
- reviewers: FULL_REVIEWERS,
- };
- const service = yield* makeService({
- projects: [
- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
- project({
- id: "p2",
- title: "enterprise",
- workspaceRoot: "/b",
- repository: "acme/web",
- host: "enterprise.test",
- }),
- ],
- providers: [
- fakeProvider("github", {
- capabilities,
- getViewerPermissions: () =>
- Effect.succeed({
- actions: [],
- stackRebase,
- comment: true,
- resolve: false,
- verdicts: [],
- requestReviewers: false,
- }),
- getChangeRequestSummary: () =>
- Effect.sync(() => {
- summaryReads++;
- return changeRequest(8, "2026-07-01T00:00:00Z");
- }),
- runAction: () =>
- Effect.gen(function* () {
- taken++;
- if (mutationFails) return yield* requestFailed;
- }),
- }),
- ],
- });
- const input = {
- ...(crossHost ? { host: "enterprise.test" } : {}),
- projectId: "p1" as ProjectId,
- repository: "acme/web",
- number: 3,
- action: "update-branch" as const,
- updateMethod: "rebase" as const,
- stackNumber: 50,
- expectedStackHeads: [{ number: 3, headSha: "ccc" }],
- };
- yield* service.runAction(input);
- assert.strictEqual(taken, 1);
- const unrelated = { ...input, number: 8 };
- yield* service.summary(unrelated);
- assert.strictEqual(summaryReads, 1);
- stackRebase = false;
- assert.strictEqual(
- (yield* Effect.flip(service.runAction(input)))._tag,
- "PullRequestOperationError",
- );
- stackRebase = true;
- stackActions = false;
- assert.strictEqual(
- (yield* Effect.flip(service.runAction(input)))._tag,
- "PullRequestOperationError",
- );
- assert.strictEqual(taken, 1);
- yield* service.summary(unrelated);
- assert.strictEqual(summaryReads, 1);
- stackActions = true;
- mutationFails = true;
- yield* Effect.flip(service.runAction(input));
- assert.strictEqual(taken, 2);
- yield* service.summary(unrelated);
- assert.strictEqual(summaryReads, 2);
- }),
- );
-}
+it.effect.each([false, true])(
+ "authorizes stack rebases and refreshes sibling layers (cross-host: %s)",
+ (crossHost) =>
+ Effect.gen(function* () {
+ let taken = 0;
+ let summaryReads = 0;
+ let mutationFails = false;
+ let stackRebase = true;
+ let stackActions = true;
+ const capabilities = {
+ diff: true,
+ comment: true,
+ actions: ["update-branch"] as const,
+ mergeMethods: ["merge"] as const,
+ updateMethods: ["rebase"] as const,
+ get stackActions() {
+ return stackActions;
+ },
+ search: true,
+ reactions: true,
+ review: FULL_REVIEW,
+ reviewers: FULL_REVIEWERS,
+ };
+ const service = yield* makeService({
+ projects: [
+ project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
+ project({
+ id: "p2",
+ title: "enterprise",
+ workspaceRoot: "/b",
+ repository: "acme/web",
+ host: "enterprise.test",
+ }),
+ ],
+ providers: [
+ fakeProvider("github", {
+ capabilities,
+ getViewerPermissions: () =>
+ Effect.succeed({
+ actions: [],
+ stackRebase,
+ comment: true,
+ resolve: false,
+ verdicts: [],
+ requestReviewers: false,
+ }),
+ getChangeRequestSummary: () =>
+ Effect.sync(() => {
+ summaryReads++;
+ return changeRequest(8, "2026-07-01T00:00:00Z");
+ }),
+ runAction: () =>
+ Effect.gen(function* () {
+ taken++;
+ if (mutationFails) return yield* requestFailed;
+ }),
+ }),
+ ],
+ });
+ const input = {
+ ...(crossHost ? { host: "enterprise.test" } : {}),
+ projectId: "p1" as ProjectId,
+ repository: "acme/web",
+ number: 3,
+ action: "update-branch" as const,
+ updateMethod: "rebase" as const,
+ stackNumber: 50,
+ expectedStackHeads: [{ number: 3, headSha: "ccc" }],
+ };
+ yield* service.runAction(input);
+ assert.strictEqual(taken, 1);
+ const unrelated = { ...input, number: 8 };
+ yield* service.summary(unrelated);
+ assert.strictEqual(summaryReads, 1);
+ stackRebase = false;
+ assert.strictEqual(
+ (yield* Effect.flip(service.runAction(input)))._tag,
+ "PullRequestOperationError",
+ );
+ stackRebase = true;
+ stackActions = false;
+ assert.strictEqual(
+ (yield* Effect.flip(service.runAction(input)))._tag,
+ "PullRequestOperationError",
+ );
+ assert.strictEqual(taken, 1);
+ yield* service.summary(unrelated);
+ assert.strictEqual(summaryReads, 1);
+ stackActions = true;
+ mutationFails = true;
+ yield* Effect.flip(service.runAction(input));
+ assert.strictEqual(taken, 2);
+ yield* service.summary(unrelated);
+ assert.strictEqual(summaryReads, 2);
+ }),
+);
it.effect("refuses a way of updating a branch that the host or the viewer does not allow", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts
index 17a77c126b2..5dea39e470e 100644
--- a/apps/server/src/serverSettings.test.ts
+++ b/apps/server/src/serverSettings.test.ts
@@ -1245,77 +1245,78 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}).pipe(Effect.provide(settingsLayer));
});
- for (const { label, variable, expected, duplicate } of [
- {
- label: "preserves an inline secret on a redacted settings save",
- variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
- expected: "inline-test-token",
- },
- {
- label: "preserves the effective last inline secret when names are duplicated",
- variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
- expected: "last-inline-test-token",
- duplicate: true,
- },
- {
- label: "replaces an inline secret with an explicit value",
- variable: { name: "API_TOKEN", value: "replacement-test-token", sensitive: true },
- expected: "replacement-test-token",
- },
- {
- label: "clears an inline secret with an explicit empty value",
- variable: { name: "API_TOKEN", value: "", sensitive: true },
- expected: "",
- },
- ]) {
- it.effect(label, () =>
- Effect.gen(function* () {
- const instanceId = ProviderInstanceId.make("codex_personal");
- const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
- const serverConfig = yield* ServerConfig.ServerConfig;
- const fileSystem = yield* FileSystem.FileSystem;
- yield* fileSystem.writeFileString(
- serverConfig.settingsPath,
- duplicate
- ? '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true},{"name":"API_TOKEN","value":"last-inline-test-token","sensitive":true}],"config":{}}}}'
- : '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true}],"config":{}}}}',
- );
- const initial = yield* serverSettings.getSettings;
- assert.equal(
- initial.providerInstances[instanceId]?.environment?.[0]?.value,
- "inline-test-token",
- );
+ it.effect.each(
+ [
+ {
+ label: "preserves an inline secret on a redacted settings save",
+ variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
+ expected: "inline-test-token",
+ },
+ {
+ label: "preserves the effective last inline secret when names are duplicated",
+ variable: { name: "API_TOKEN", value: "", sensitive: true, valueRedacted: true },
+ expected: "last-inline-test-token",
+ duplicate: true,
+ },
+ {
+ label: "replaces an inline secret with an explicit value",
+ variable: { name: "API_TOKEN", value: "replacement-test-token", sensitive: true },
+ expected: "replacement-test-token",
+ },
+ {
+ label: "clears an inline secret with an explicit empty value",
+ variable: { name: "API_TOKEN", value: "", sensitive: true },
+ expected: "",
+ },
+ ].map((testCase) => [testCase.label, testCase] as const),
+ )("%s", ([, { variable, expected, duplicate }]) =>
+ Effect.gen(function* () {
+ const instanceId = ProviderInstanceId.make("codex_personal");
+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
+ const serverConfig = yield* ServerConfig.ServerConfig;
+ const fileSystem = yield* FileSystem.FileSystem;
+ yield* fileSystem.writeFileString(
+ serverConfig.settingsPath,
+ duplicate
+ ? '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true},{"name":"API_TOKEN","value":"last-inline-test-token","sensitive":true}],"config":{}}}}'
+ : '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"API_TOKEN","value":"inline-test-token","sensitive":true}],"config":{}}}}',
+ );
+ const initial = yield* serverSettings.getSettings;
+ assert.equal(
+ initial.providerInstances[instanceId]?.environment?.[0]?.value,
+ "inline-test-token",
+ );
- const next = yield* serverSettings.updateSettings({
- providerInstances: {
- [instanceId]: {
- driver: ProviderDriverKind.make("codex"),
- displayName: "Renamed provider",
- environment: duplicate ? [variable, variable] : [variable],
- config: {},
- },
+ const next = yield* serverSettings.updateSettings({
+ providerInstances: {
+ [instanceId]: {
+ driver: ProviderDriverKind.make("codex"),
+ displayName: "Renamed provider",
+ environment: duplicate ? [variable, variable] : [variable],
+ config: {},
},
- });
- assert.equal(next.providerInstances[instanceId]?.environment?.[0]?.value, expected);
- const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
- assert.notInclude(raw, "inline-test-token");
- assert.notInclude(raw, "replacement-test-token");
-
- const reloaded = yield* Effect.gen(function* () {
- const fresh = yield* ServerSettingsModule.ServerSettingsService;
- return yield* fresh.getSettings;
- }).pipe(
- Effect.provide(
- Layer.fresh(ServerSettingsModule.layer).pipe(Layer.provide(ServerSecretStore.layer)),
- ),
- );
- assert.equal(reloaded.providerInstances[instanceId]?.environment?.[0]?.value, expected);
- }).pipe(Effect.provide(makeServerSettingsLayer())),
- );
- }
+ },
+ });
+ assert.equal(next.providerInstances[instanceId]?.environment?.[0]?.value, expected);
+ const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
+ assert.notInclude(raw, "inline-test-token");
+ assert.notInclude(raw, "replacement-test-token");
+
+ const reloaded = yield* Effect.gen(function* () {
+ const fresh = yield* ServerSettingsModule.ServerSettingsService;
+ return yield* fresh.getSettings;
+ }).pipe(
+ Effect.provide(
+ Layer.fresh(ServerSettingsModule.layer).pipe(Layer.provide(ServerSecretStore.layer)),
+ ),
+ );
+ assert.equal(reloaded.providerInstances[instanceId]?.environment?.[0]?.value, expected);
+ }).pipe(Effect.provide(makeServerSettingsLayer())),
+ );
- for (const sensitiveLast of [true, false]) {
- it.effect(`preserves duplicate secret operation order (sensitive last: ${sensitiveLast})`, () =>
+ it.effect.each([true, false])(
+ "preserves duplicate secret operation order (sensitive last: %s)",
+ (sensitiveLast) =>
Effect.gen(function* () {
const service = yield* ServerSettingsModule.ServerSettingsService;
const instanceId = ProviderInstanceId.make("codex_duplicate");
@@ -1339,8 +1340,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
sensitiveLast ? "secret-last" : "",
);
}).pipe(Effect.provide(makeServerSettingsLayer())),
- );
- }
+ );
it.effect("stores sensitive provider instance environment values outside settings.json", () =>
Effect.gen(function* () {
@@ -1630,8 +1630,9 @@ it.layer(NodeServices.layer)("server settings", (it) => {
}),
);
- for (const failure of ["response materialization", "partially committed write"] as const) {
- it.effect(`rolls back provider secret changes after ${failure} fails`, () => {
+ it.effect.each(["response materialization", "partially committed write"] as const)(
+ "rolls back provider secret changes after %s fails",
+ (failure) => {
const textDecoder = new TextDecoder();
const secrets = new Map<string, Uint8Array>();
let rejectNewSecret = false;
@@ -1734,8 +1735,8 @@ it.layer(NodeServices.layer)("server settings", (it) => {
"sk-kept",
);
}).pipe(Effect.provide(settingsLayer));
- });
- }
+ },
+ );
it.effect("folds legacy project overrides into projectSettingsOverrides once", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts
index 2a214fc800f..751420dfc5a 100644
--- a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts
+++ b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts
@@ -408,8 +408,9 @@ it("reports an update hint instead of unauthenticated when gh predates --json",
);
});
-for (const kind of ["pull", "issues"]) {
- it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
+it.effect.each(["pull", "issues"])(
+ "resolves %s subjects on the linked host without using the checkout",
+ (kind) =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: (input) => {
@@ -449,11 +450,11 @@ for (const kind of ["pull", "issues"]) {
undefined,
);
}),
- );
-}
+);
-for (const stage of ["read", "decode"] as const) {
- it.effect(`retains the ${stage} failure without exposing its raw contents`, () =>
+it.effect.each(["read", "decode"] as const)(
+ "retains the %s failure without exposing its raw contents",
+ (stage) =>
Effect.gen(function* () {
const cause = new GitHubCli.GitHubCliCommandError({
command: "gh",
@@ -484,5 +485,4 @@ for (const stage of ["read", "decode"] as const) {
if (stage === "read") assert.strictEqual(error.cause, cause);
else assert.propertyVal(error.cause, "_tag", "SchemaError");
}),
- );
-}
+);
diff --git a/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts b/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts
index deca59c48b9..de0e6bad76c 100644
--- a/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts
+++ b/apps/server/src/sourceControl/GitLabSourceControlProvider.test.ts
@@ -227,8 +227,9 @@ selfhosted
);
});
-for (const kind of ["merge_requests", "issues"]) {
- it.effect(`resolves ${kind} subjects on the linked host without using the checkout`, () =>
+it.effect.each(["merge_requests", "issues"])(
+ "resolves %s subjects on the linked host without using the checkout",
+ (kind) =>
Effect.gen(function* () {
const provider = yield* makeProvider({
execute: (input) => {
@@ -269,11 +270,11 @@ for (const kind of ["merge_requests", "issues"]) {
undefined,
);
}),
- );
-}
+);
-for (const stage of ["read", "decode"] as const) {
- it.effect(`retains the ${stage} failure without exposing its raw contents`, () =>
+it.effect.each(["read", "decode"] as const)(
+ "retains the %s failure without exposing its raw contents",
+ (stage) =>
Effect.gen(function* () {
const cause = new GitLabCli.GitLabCliCommandError({
command: "glab",
@@ -305,5 +306,4 @@ for (const stage of ["read", "decode"] as const) {
if (stage === "read") assert.strictEqual(error.cause, cause);
else assert.propertyVal(error.cause, "_tag", "SchemaError");
}),
- );
-}
+);
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index 29edb395b90..b2b379edb85 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -1461,8 +1461,9 @@ it.layer(
}),
);
- for (const source of ["current", "legacy"] as const) {
- it.effect(`reads only a Unicode-safe tail from oversized ${source} history`, () =>
+ it.effect.each(["current", "legacy"] as const)(
+ "reads only a Unicode-safe tail from oversized %s history",
+ (source) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -1513,8 +1514,7 @@ it.layer(
yield* manager.close({ threadId: "thread-1" });
expect((yield* manager.open(openInput())).history).toBe("\uFEFFnewest\ré");
}),
- );
- }
+ );
it.effect("strips replay-unsafe terminal query and reply sequences from persisted history", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/terminal/NodePtyAdapter.test.ts b/apps/server/src/terminal/NodePtyAdapter.test.ts
index 8107e19e616..7c6101dfa38 100644
--- a/apps/server/src/terminal/NodePtyAdapter.test.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.test.ts
@@ -110,8 +110,9 @@ it.effect("waits for the Windows PID without requiring output", () =>
}).pipe(Effect.provide(testLayer)),
);
-for (const failure of ["exit", "close", "error", "invalid-pid"] as const) {
- it.effect(`fails Windows startup on ${failure} and cleans up`, () =>
+it.effect.each(["exit", "close", "error", "invalid-pid"] as const)(
+ "fails Windows startup on %s and cleans up",
+ (failure) =>
Effect.gen(function* () {
const { nativeProcess, subscribed } = preparePendingProcess();
const adapter = yield* PtyAdapter.PtyAdapter;
@@ -129,8 +130,7 @@ for (const failure of ["exit", "close", "error", "invalid-pid"] as const) {
assert.equal(nativeProcess.events.listenerCount("exit"), 0);
assert.equal(nativeProcess._agent.kill.mock.calls.length, 1);
}).pipe(Effect.provide(testLayer)),
- );
-}
+);
it.effect("cancels the Windows connection without waiting for output", () =>
Effect.gen(function* () {
@@ -160,8 +160,9 @@ it.effect("reports an incompatible Windows readiness API instead of hanging", ()
}).pipe(Effect.provide(testLayer)),
);
-for (const platform of ["win32", "linux", "darwin"] as const) {
- it.effect(`terminates through node-pty using ${platform} semantics`, () =>
+it.effect.each(["win32", "linux", "darwin"] as const)(
+ "terminates through node-pty using %s semantics",
+ (platform) =>
Effect.gen(function* () {
const adapter = yield* PtyAdapter.PtyAdapter;
const process = yield* adapter.spawn({
@@ -189,8 +190,7 @@ for (const platform of ["win32", "linux", "darwin"] as const) {
: [["SIGTERM"], ["SIGKILL"], [undefined]],
);
}).pipe(Effect.provide(makeTestLayer(platform))),
- );
-}
+);
it.effect("spawns through the public adapter with the provided host references", () =>
Effect.gen(function* () {
@@ -279,8 +279,9 @@ it.effect("reports native module load failures as structured startup defects", (
),
);
-for (const budget of [2048, 8]) {
- it.effect(`preserves an exit during readiness handoff with scheduler budget ${budget}`, () =>
+it.effect.each([2048, 8])(
+ "preserves an exit during readiness handoff with scheduler budget %s",
+ (budget) =>
Effect.gen(function* () {
const { nativeProcess, subscribed } = preparePendingProcess();
const adapter = yield* PtyAdapter.PtyAdapter;
@@ -300,8 +301,7 @@ for (const budget of [2048, 8]) {
yield* Fiber.join(fiber);
assert.equal(exits.length, 1);
}).pipe(Effect.provide(testLayer)),
- );
-}
+);
it.effect("replays an exit to late subscribers and respects unsubscription", () =>
Effect.gen(function* () {
@@ -320,8 +320,9 @@ it.effect("replays an exit to late subscribers and respects unsubscription", ()
}).pipe(Effect.provide(testLayer)),
);
-for (const failure of ["spawn", "interrupt"] as const) {
- it.effect(`logs cleanup failures without replacing ${failure}`, () =>
+it.effect.each(["spawn", "interrupt"] as const)(
+ "logs cleanup failures without replacing %s",
+ (failure) =>
Effect.gen(function* () {
const { nativeProcess, subscribed } = preparePendingProcess();
const killError = new Error("native kill failed");
@@ -361,5 +362,4 @@ for (const failure of ["spawn", "interrupt"] as const) {
assert.equal(nativeProcess.events.listenerCount("exit"), 0);
assert.equal(nativeProcess._socket.listenerCount("ready_datapipe"), 0);
}).pipe(Effect.provide(testLayer)),
- );
-}
+);
diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts
index 76629cbf618..58fa9e3d74d 100644
--- a/apps/server/src/terminal/OutputProtocol.test.ts
+++ b/apps/server/src/terminal/OutputProtocol.test.ts
@@ -11,69 +11,67 @@ import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/u
import { withTerminalOutputWindow } from "./OutputProtocol.ts";
describe("terminal output window", () => {
- for (const { tag, size, limit } of [
+ it.effect.each([
{ tag: WS_METHODS.terminalAttach, size: 1, limit: 8 },
{ tag: WS_METHODS.subscribeTerminalEvents, size: 1, limit: 8 },
{ tag: WS_METHODS.terminalAttach, size: 64 * 1024, limit: 1 },
{ tag: WS_METHODS.subscribeTerminalMetadata, size: 1, limit: 1 },
- ]) {
- it.effect(`limits ${tag} with ${size}-byte values to ${limit} pending chunks`, () =>
- Effect.gen(function* () {
- const group = RpcGroup.make(Rpc.make(tag, { success: Schema.String, stream: true }));
- const output = yield* Queue.unbounded<string>();
- const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
- const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
- const protocol = yield* RpcServer.Protocol.make((write) =>
- Effect.gen(function* () {
- yield* Deferred.succeed(receive, write);
- const serialization = yield* RpcSerialization.RpcSerialization;
- return {
- disconnects: yield* Queue.unbounded<number>(),
- send: (_clientId, response) => Queue.offer(responses, response),
- end: () => Effect.void,
- clientIds: Effect.succeed(new Set([0])),
- initialMessage: Effect.succeedNone,
- supportsAck: true,
- supportsTransferables: false,
- supportsSpanPropagation: false,
- supportsNotifications: true,
- codecFor: serialization.codecFor,
- };
- }),
- );
- yield* RpcServer.make(group).pipe(
- Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))),
- Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
- Effect.forkScoped,
- );
- const write = yield* Deferred.await(receive);
- yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
+ ])("limits $tag with $size-byte values to $limit pending chunks", ({ tag, size, limit }) =>
+ Effect.gen(function* () {
+ const group = RpcGroup.make(Rpc.make(tag, { success: Schema.String, stream: true }));
+ const output = yield* Queue.unbounded<string>();
+ const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
+ const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>();
+ const protocol = yield* RpcServer.Protocol.make((write) =>
+ Effect.gen(function* () {
+ yield* Deferred.succeed(receive, write);
+ const serialization = yield* RpcSerialization.RpcSerialization;
+ return {
+ disconnects: yield* Queue.unbounded<number>(),
+ send: (_clientId, response) => Queue.offer(responses, response),
+ end: () => Effect.void,
+ clientIds: Effect.succeed(new Set([0])),
+ initialMessage: Effect.succeedNone,
+ supportsAck: true,
+ supportsTransferables: false,
+ supportsSpanPropagation: false,
+ supportsNotifications: true,
+ codecFor: serialization.codecFor,
+ };
+ }),
+ );
+ yield* RpcServer.make(group).pipe(
+ Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))),
+ Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
+ Effect.forkScoped,
+ );
+ const write = yield* Deferred.await(receive);
+ yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] });
- for (let index = 0; index < limit; index++) {
- const value = String(index).repeat(size);
- yield* Queue.offer(output, value);
- yield* TestClock.adjust(0);
- assert.equal(yield* Queue.size(responses), 1);
- assert.deepEqual(yield* Queue.take(responses), {
- _tag: "Chunk",
- requestId: "1",
- values: [value],
- });
- }
- yield* Queue.offer(output, "i".repeat(size));
+ for (let index = 0; index < limit; index++) {
+ const value = String(index).repeat(size);
+ yield* Queue.offer(output, value);
yield* TestClock.adjust(0);
- assert.equal(yield* Queue.size(responses), 0);
- yield* write(0, { _tag: "Ack", requestId: "1" });
- const resumed = yield* Queue.take(responses);
- assert.equal(resumed._tag, "Chunk");
- if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, ["i".repeat(size)]);
+ assert.equal(yield* Queue.size(responses), 1);
+ assert.deepEqual(yield* Queue.take(responses), {
+ _tag: "Chunk",
+ requestId: "1",
+ values: [value],
+ });
+ }
+ yield* Queue.offer(output, "i".repeat(size));
+ yield* TestClock.adjust(0);
+ assert.equal(yield* Queue.size(responses), 0);
+ yield* write(0, { _tag: "Ack", requestId: "1" });
+ const resumed = yield* Queue.take(responses);
+ assert.equal(resumed._tag, "Chunk");
+ if (resumed._tag === "Chunk") assert.deepEqual(resumed.values, ["i".repeat(size)]);
- yield* Queue.offer(output, "j");
- yield* TestClock.adjust(0);
- assert.equal(yield* Queue.size(responses), 0);
- yield* write(0, { _tag: "Interrupt", requestId: "1" });
- assert.equal((yield* Queue.take(responses))._tag, "Exit");
- }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
- );
- }
+ yield* Queue.offer(output, "j");
+ yield* TestClock.adjust(0);
+ assert.equal(yield* Queue.size(responses), 0);
+ yield* write(0, { _tag: "Interrupt", requestId: "1" });
+ assert.equal((yield* Queue.take(responses))._tag, "Exit");
+ }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
+ );
});
diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
index 8fe5152d345..fc51a7248ad 100644
--- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
+++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts
@@ -461,69 +461,69 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
}),
);
- for (const verbose of [false, true]) {
- it.effect(`unwraps a JSON title in ${verbose ? "verbose" : "normal"} Claude output`, () => {
- const result = {
- type: "result",
- structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
- };
- return withFakeClaudeEnv(
- { output: JSON.stringify(verbose ? [result] : result) },
- (textGeneration) =>
- Effect.gen(function* () {
- const generated = yield* textGeneration.generateThreadTitle({
- cwd: process.cwd(),
- message: "Refresh ev-stg APP ASG instances",
- modelSelection: {
- instanceId: ProviderInstanceId.make("claudeAgent"),
- model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
- },
- });
+ it.effect.each([
+ { verbose: false, label: "normal" },
+ { verbose: true, label: "verbose" },
+ ])("unwraps a JSON title in $label Claude output", ({ verbose }) => {
+ const result = {
+ type: "result",
+ structured_output: { title: '{"title": "Refresh ev-stg APP ASG instances"}' },
+ };
+ return withFakeClaudeEnv(
+ { output: JSON.stringify(verbose ? [result] : result) },
+ (textGeneration) =>
+ Effect.gen(function* () {
+ const generated = yield* textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Refresh ev-stg APP ASG instances",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ });
- expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
- }),
- );
- });
- }
+ expect(generated.title).toBe("Refresh ev-stg APP ASG instances");
+ }),
+ );
+ });
- for (const previousTitle of [undefined, "Old thread title"]) {
- it.effect(
- `reads the result from verbose Claude output when ${previousTitle ? "regenerating" : "generating"} a title`,
- () =>
- withFakeClaudeEnv(
+ it.effect.each([
+ { previousTitle: undefined, label: "generating" },
+ { previousTitle: "Old thread title", label: "regenerating" },
+ ])("reads the result from verbose Claude output when $label a title", ({ previousTitle }) =>
+ withFakeClaudeEnv(
+ {
+ output: JSON.stringify([
+ { type: "system", subtype: "init" },
+ { type: "assistant", message: { content: [] } },
+ { type: "user", message: { content: [] } },
+ { type: "rate_limit_event" },
{
- output: JSON.stringify([
- { type: "system", subtype: "init" },
- { type: "assistant", message: { content: [] } },
- { type: "user", message: { content: [] } },
- { type: "rate_limit_event" },
- {
- type: "result",
- subtype: "success",
- result: '{"title":"Refresh ev-stg APP ASG Instances"}',
- structured_output: { title: "Refresh ev-stg APP ASG Instances" },
- },
- ]),
+ type: "result",
+ subtype: "success",
+ result: '{"title":"Refresh ev-stg APP ASG Instances"}',
+ structured_output: { title: "Refresh ev-stg APP ASG Instances" },
},
- (textGeneration) =>
- Effect.gen(function* () {
- const generated = yield* textGeneration.generateThreadTitle({
- cwd: process.cwd(),
- message: "Refresh ev-stg APP ASG instances",
- previousTitle,
- modelSelection: {
- instanceId: ProviderInstanceId.make("claudeAgent"),
- model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
- },
- });
-
- expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
- }),
- ),
- );
- }
+ ]),
+ },
+ (textGeneration) =>
+ Effect.gen(function* () {
+ const generated = yield* textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Refresh ev-stg APP ASG instances",
+ previousTitle,
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ });
- for (const [name, output] of [
+ expect(generated.title).toBe("Refresh ev-stg APP ASG Instances");
+ }),
+ ),
+ );
+
+ it.effect.each([
["empty message array", []],
["missing result", [{ type: "assistant", structured_output: { title: "Not a result" } }]],
["invalid title", [{ type: "result", structured_output: { title: 42 } }]],
@@ -534,26 +534,24 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGeneration", (it) => {
{ type: "result", subtype: "error_max_structured_output_retries" },
],
],
- ] as const) {
- it.effect(`rejects verbose Claude output with ${name}`, () =>
- withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
- Effect.gen(function* () {
- const error = yield* Effect.flip(
- textGeneration.generateThreadTitle({
- cwd: process.cwd(),
- message: "Name this thread",
- modelSelection: {
- instanceId: ProviderInstanceId.make("claudeAgent"),
- model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
- },
- }),
- );
+ ] as const)("rejects verbose Claude output with %s", ([, output]) =>
+ withFakeClaudeEnv({ output: JSON.stringify(output) }, (textGeneration) =>
+ Effect.gen(function* () {
+ const error = yield* Effect.flip(
+ textGeneration.generateThreadTitle({
+ cwd: process.cwd(),
+ message: "Name this thread",
+ modelSelection: {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ model: SYNTHETIC_CLAUDE_STANDARD_MODEL,
+ },
+ }),
+ );
- expect(error._tag).toBe("TextGenerationError");
- }),
- ),
- );
- }
+ expect(error._tag).toBe("TextGenerationError");
+ }),
+ ),
+ );
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts
index 6d1ecbfdcf3..98f0c9836e4 100644
--- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts
+++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts
@@ -170,8 +170,9 @@ function withFakeCodexEnv<A, E, R>(
}
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
- for (const selectedModel of ["gpt-5.6-luna", "openai.gpt-5.6-luna"]) {
- it.effect(`dispatches the qualified live model for ${selectedModel}`, () =>
+ it.effect.each(["gpt-5.6-luna", "openai.gpt-5.6-luna"])(
+ "dispatches the qualified live model for %s",
+ (selectedModel) =>
withFakeCodexEnv(
{
output: JSON.stringify({ title: "Bedrock title" }),
@@ -189,8 +190,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
expect(result.title).toBe("Bedrock title");
}),
),
- );
- }
+ );
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
{
@@ -406,7 +406,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
),
);
- for (const example of [
+ it.effect.each([
{
mode: "static",
output: "Add Search",
@@ -425,30 +425,28 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
expected: "Julius/ABC-123.v2",
instruction: "Preserve the issue ID and capitalization.",
},
- ] as const) {
- it.effect(`generates a branch using ${example.mode} naming`, () =>
- withFakeCodexEnv(
- {
- output: JSON.stringify({ branch: example.output }),
- stdinMustContain: example.instruction,
- },
- (textGeneration) =>
- Effect.gen(function* () {
- const generated = yield* textGeneration.generateBranchName({
- cwd: process.cwd(),
- message: "Add search",
- modelSelection: DEFAULT_TEST_MODEL_SELECTION,
- naming: {
- mode: example.mode,
- prefix: "team/",
- instructions: "Preserve the issue ID and capitalization.",
- },
- });
- expect(generated.branch).toBe(example.expected);
- }),
- ),
- );
- }
+ ] as const)("generates a branch using $mode naming", (example) =>
+ withFakeCodexEnv(
+ {
+ output: JSON.stringify({ branch: example.output }),
+ stdinMustContain: example.instruction,
+ },
+ (textGeneration) =>
+ Effect.gen(function* () {
+ const generated = yield* textGeneration.generateBranchName({
+ cwd: process.cwd(),
+ message: "Add search",
+ modelSelection: DEFAULT_TEST_MODEL_SELECTION,
+ naming: {
+ mode: example.mode,
+ prefix: "team/",
+ instructions: "Preserve the issue ID and capitalization.",
+ },
+ });
+ expect(generated.branch).toBe(example.expected);
+ }),
+ ),
+ );
it.effect("generates branch names even when the ambient scope is already closed", () =>
withFakeCodexEnv(
diff --git a/apps/server/src/textGeneration/CursorTextGeneration.test.ts b/apps/server/src/textGeneration/CursorTextGeneration.test.ts
index fff76988e97..684d173463f 100644
--- a/apps/server/src/textGeneration/CursorTextGeneration.test.ts
+++ b/apps/server/src/textGeneration/CursorTextGeneration.test.ts
@@ -253,8 +253,9 @@ describe("CursorTextGeneration", () => {
}).pipe(Effect.provide(fsLayer)),
);
- for (const status of ["error", "cancelled"] as const) {
- it.effect(`rejects a ${status} Cursor SDK run that includes valid title JSON`, () =>
+ it.effect.each(["error", "cancelled"] as const)(
+ "rejects a %s Cursor SDK run that includes valid title JSON",
+ (status) =>
Effect.gen(function* () {
const promptResult = {
id: "run-cursor-partial-title-test",
@@ -284,8 +285,7 @@ describe("CursorTextGeneration", () => {
);
expect(cursorSdkMock.close).toHaveBeenCalledOnce();
}).pipe(Effect.provide(fsLayer)),
- );
- }
+ );
it.effect("fails closed when ambient sandbox policy can expand write access", () =>
Effect.gen(function* () {
@@ -329,8 +329,9 @@ describe("CursorTextGeneration", () => {
}).pipe(Effect.provide(fsLayer), Effect.scoped),
);
- for (const phase of ["create", "send"] as const) {
- it.effect(`times out pending ${phase} and releases its late SDK resource`, () =>
+ it.effect.each(["create", "send"] as const)(
+ "times out pending %s and releases its late SDK resource",
+ (phase) =>
Effect.gen(function* () {
let started!: () => void;
const called = new Promise<void>((resolve) => {
@@ -388,8 +389,7 @@ describe("CursorTextGeneration", () => {
expect(wait).not.toHaveBeenCalled();
if (phase === "send") expect(cursorSdkMock.cancel).toHaveBeenCalledOnce();
}).pipe(Effect.provide(fsLayer), Effect.scoped),
- );
- }
+ );
it.effect("requires CURSOR_API_KEY before calling the SDK", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts
index f7286a11b60..29fcecdc234 100644
--- a/apps/server/src/usage/UsageService.test.ts
+++ b/apps/server/src/usage/UsageService.test.ts
@@ -121,95 +121,96 @@ function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens
}
describe("UsageService", () => {
- for (const explicitDefault of [true, false]) {
- it.live(
- `reads shared managed ${explicitDefault ? "explicit" : "legacy"} default and disabled extra account history once`,
- () =>
- Effect.gen(function* () {
- const { home, settings } = yield* setup;
- const summary = yield* Effect.gen(function* () {
- for (const [id, output] of [
- ["codex", 17],
- ["codex-personal", 23],
- ] as const) {
- const sessions = NodePath.join(home, "shared-codex", "sessions");
- yield* Effect.promise(async () => {
- await NodeFSP.mkdir(sessions, { recursive: true });
- await NodeFSP.writeFile(
- NodePath.join(sessions, `${id}-rollout.jsonl`),
- [
- { type: "session_meta", payload: { id } },
- { type: "turn_context", payload: { model: "gpt-5.6-sol" } },
- {
- type: "event_msg",
- timestamp: "2026-08-01T10:00:00Z",
- payload: {
- type: "token_count",
- info: { last_token_usage: { input_tokens: 10, output_tokens: output } },
- },
+ it.live.each([
+ { explicitDefault: true, label: "explicit" },
+ { explicitDefault: false, label: "legacy" },
+ ])(
+ "reads shared managed $label default and disabled extra account history once",
+ ({ explicitDefault }) =>
+ Effect.gen(function* () {
+ const { home, settings } = yield* setup;
+ const summary = yield* Effect.gen(function* () {
+ for (const [id, output] of [
+ ["codex", 17],
+ ["codex-personal", 23],
+ ] as const) {
+ const sessions = NodePath.join(home, "shared-codex", "sessions");
+ yield* Effect.promise(async () => {
+ await NodeFSP.mkdir(sessions, { recursive: true });
+ await NodeFSP.writeFile(
+ NodePath.join(sessions, `${id}-rollout.jsonl`),
+ [
+ { type: "session_meta", payload: { id } },
+ { type: "turn_context", payload: { model: "gpt-5.6-sol" } },
+ {
+ type: "event_msg",
+ timestamp: "2026-08-01T10:00:00Z",
+ payload: {
+ type: "token_count",
+ info: { last_token_usage: { input_tokens: 10, output_tokens: output } },
},
- ]
- .map((line) => encodeUnknownJsonString(line))
- .join("\n") + "\n",
- );
- });
- }
- const service = yield* UsageService.make;
- return yield* service.readSummary(WINDOW);
- }).pipe(
- Effect.provide(
- serviceLayers({
- prefix: "usage-managed-accounts",
- home,
- settings: {
- ...settings,
- providers: {
- ...settings.providers,
- codex: { setupMode: "managed", homePath: NodePath.join(home, "shared-codex") },
},
- providerInstances: {
- ...(explicitDefault
- ? {
- [ProviderInstanceId.make("codex")]: {
- driver: ProviderDriverKind.make("codex"),
- config: {
- setupMode: "managed",
- homePath: NodePath.join(home, "shared-codex"),
- },
+ ]
+ .map((line) => encodeUnknownJsonString(line))
+ .join("\n") + "\n",
+ );
+ });
+ }
+ const service = yield* UsageService.make;
+ return yield* service.readSummary(WINDOW);
+ }).pipe(
+ Effect.provide(
+ serviceLayers({
+ prefix: "usage-managed-accounts",
+ home,
+ settings: {
+ ...settings,
+ providers: {
+ ...settings.providers,
+ codex: { setupMode: "managed", homePath: NodePath.join(home, "shared-codex") },
+ },
+ providerInstances: {
+ ...(explicitDefault
+ ? {
+ [ProviderInstanceId.make("codex")]: {
+ driver: ProviderDriverKind.make("codex"),
+ config: {
+ setupMode: "managed",
+ homePath: NodePath.join(home, "shared-codex"),
},
- }
- : {}),
- [ProviderInstanceId.make("codex-personal")]: {
- driver: ProviderDriverKind.make("codex"),
- enabled: false,
- config: {
- setupMode: "managed",
- homePath: NodePath.join(home, "shared-codex"),
- shadowHomePath: NodePath.join(home, "personal-shadow"),
- },
- environment: [
- {
- name: "CODEX_HOME",
- value: NodePath.join(home, "ignored-environment"),
- sensitive: false,
},
- ],
+ }
+ : {}),
+ [ProviderInstanceId.make("codex-personal")]: {
+ driver: ProviderDriverKind.make("codex"),
+ enabled: false,
+ config: {
+ setupMode: "managed",
+ homePath: NodePath.join(home, "shared-codex"),
+ shadowHomePath: NodePath.join(home, "personal-shadow"),
},
+ environment: [
+ {
+ name: "CODEX_HOME",
+ value: NodePath.join(home, "ignored-environment"),
+ sensitive: false,
+ },
+ ],
},
},
- }),
- ),
- );
- assert.strictEqual(totalOutputTokens(summary), 40);
- assert.strictEqual(
- summary.sources.filter(
- (source) => source.fingerprint.provider === "codex" && source.status === "ok",
- ).length,
- 1,
- );
- }).pipe(Effect.scoped),
- );
- }
+ },
+ }),
+ ),
+ );
+ assert.strictEqual(totalOutputTokens(summary), 40);
+ assert.strictEqual(
+ summary.sources.filter(
+ (source) => source.fingerprint.provider === "codex" && source.status === "ok",
+ ).length,
+ 1,
+ );
+ }).pipe(Effect.scoped),
+ );
it.live("omits Cursor account usage when no file login is saved", () =>
Effect.gen(function* () {
const { settings, home } = yield* setup;
diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts
index b0fee363828..10ce966ef1e 100644
--- a/apps/server/src/usage/cliproxyApi.test.ts
+++ b/apps/server/src/usage/cliproxyApi.test.ts
@@ -234,22 +234,20 @@ describe("CLIProxyAPI built-in management API", () => {
}),
);
- for (const [code, outcome] of [
+ it.effect.each([
["nothing_to_reset", "nothingToReset"],
["no_credit", "noCredit"],
["already_redeemed", "alreadyRedeemed"],
- ] as const) {
- it.effect(`reports ${code} accurately`, () =>
- Effect.gen(function* () {
- const test = fixture({ upstream: () => ({ status: 200, body: { code } }) });
- const api = yield* test.api;
- expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome });
- expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe(
- code === "already_redeemed",
- );
- }),
- );
- }
+ ] as const)("reports %s accurately", ([code, outcome]) =>
+ Effect.gen(function* () {
+ const test = fixture({ upstream: () => ({ status: 200, body: { code } }) });
+ const api = yield* test.api;
+ expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome });
+ expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe(
+ code === "already_redeemed",
+ );
+ }),
+ );
it.effect("reports redemption success even if cooldown clearing fails", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts
index 1bba13cd4bd..6b892050128 100644
--- a/apps/server/src/vcs/GitVcsDriver.test.ts
+++ b/apps/server/src/vcs/GitVcsDriver.test.ts
@@ -392,8 +392,9 @@ it.effect.each([
}).pipe(Effect.scoped, Effect.provide(GitCaptureContractLayer)),
);
-for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
- it.effect(`checkpoint recovery has one deadline including ${blockedPhase}`, () =>
+it.effect.each(["discovery", "probe", "retry"] as const)(
+ "checkpoint recovery has one deadline including %s",
+ (blockedPhase) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -478,8 +479,7 @@ for (const blockedPhase of ["discovery", "probe", "retry"] as const) {
assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef }));
assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex);
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
-}
+);
it.effect("checkpoint recovery preserves interruption and removes the private index", () =>
Effect.gen(function* () {
@@ -548,116 +548,103 @@ it.effect("checkpoint capture does not rerun clean filters for unchanged indexed
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
-for (const nested of [false, true]) {
- for (const indexState of [
- "sparse",
- "flags",
- "manual-skip",
- "missing",
- "non-cone-missing",
- ] as const) {
- it.effect(
- `sparse checkpoint preserves two captures (nested=${nested}, index=${indexState})`,
- () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const driver = yield* GitVcsDriver.makeVcsDriverShape();
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
- const { git } = yield* makeCheckpointFixture(driver, cwd);
- const write = Effect.fn(function* (name: string, contents: string) {
- yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
- yield* fs.writeFileString(path.join(cwd, name), contents);
- });
- for (const name of [
- "scope/in/edit",
- "scope/in/delete",
- "scope/out/deep/absent",
- "scope/out/present",
- "elsewhere/file",
- ]) {
- yield* write(name, "original\n");
- }
- yield* git(["add", "."]);
- yield* git(["commit", "-m", "sparse fixture"]);
- yield* git([
- "sparse-checkout",
- "set",
- "--cone",
- "--sparse-index",
- "scope/in",
- "elsewhere",
- ]);
- if (indexState === "non-cone-missing")
- yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
- yield* write("scope/in/edit", "staged\n");
- yield* write("elsewhere/file", "staged outside\n");
- yield* git(["add", "."]);
- if (indexState === "flags")
- yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
- if (indexState === "manual-skip")
- yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
- yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
- yield* write("scope/in/edit", "working\n");
- yield* write("scope/out/present", "modified skipped\n");
- yield* write("scope/out/new file", "new outside cone\n");
- yield* write("elsewhere/file", "working outside\n");
- yield* fs.remove(path.join(cwd, "scope/in/delete"));
- const indexPath = path.join(cwd, ".git/index");
- if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
- const originalIndex = yield* fs
- .readFile(indexPath)
- .pipe(Effect.orElseSucceed(() => null));
- const captureCwd = nested ? path.join(cwd, "scope") : cwd;
- for (const turn of [1, 2]) {
- const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
- if (turn === 2) {
- yield* write("scope/in/edit", "second\n");
- yield* fs.remove(path.join(cwd, "scope/out/new file"));
- yield* write("scope/out/second", "second addition\n");
- }
- const capture = driver.checkpoints.captureCheckpoint({
- cwd: captureCwd,
- checkpointRef: ref,
- });
- if (indexState === "non-cone-missing") {
- assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
- assert.isFalse(
- yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
- );
- assert.isFalse(yield* fs.exists(indexPath));
- break;
- }
- yield* capture;
- for (const [name, content] of [
- ["scope/out/deep/absent", "original\n"],
- ["scope/out/present", "modified skipped\n"],
- ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
- ["elsewhere/file", nested ? "original\n" : "working outside\n"],
- [
- turn === 1 ? "scope/out/new file" : "scope/out/second",
- turn === 1 ? "new outside cone\n" : "second addition\n",
- ],
- ]) {
- assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
- }
- const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
- assert.notInclude(files, "scope/in/delete");
- if (turn === 2) assert.notInclude(files, "scope/out/new file");
- assert.deepEqual(
- yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
- originalIndex,
- );
- assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
- assert.strictEqual(
- yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
- "working outside\n",
- );
- }
- }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
- }
-}
+it.effect.each(
+ [false, true].flatMap((nested) =>
+ (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map(
+ (indexState) => ({ nested, indexState }),
+ ),
+ ),
+)(
+ "sparse checkpoint preserves two captures (nested=$nested, index=$indexState)",
+ ({ nested, indexState }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const driver = yield* GitVcsDriver.makeVcsDriverShape();
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
+ const { git } = yield* makeCheckpointFixture(driver, cwd);
+ const write = Effect.fn(function* (name: string, contents: string) {
+ yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
+ yield* fs.writeFileString(path.join(cwd, name), contents);
+ });
+ for (const name of [
+ "scope/in/edit",
+ "scope/in/delete",
+ "scope/out/deep/absent",
+ "scope/out/present",
+ "elsewhere/file",
+ ]) {
+ yield* write(name, "original\n");
+ }
+ yield* git(["add", "."]);
+ yield* git(["commit", "-m", "sparse fixture"]);
+ yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "scope/in", "elsewhere"]);
+ if (indexState === "non-cone-missing")
+ yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
+ yield* write("scope/in/edit", "staged\n");
+ yield* write("elsewhere/file", "staged outside\n");
+ yield* git(["add", "."]);
+ if (indexState === "flags")
+ yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
+ if (indexState === "manual-skip")
+ yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
+ yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
+ yield* write("scope/in/edit", "working\n");
+ yield* write("scope/out/present", "modified skipped\n");
+ yield* write("scope/out/new file", "new outside cone\n");
+ yield* write("elsewhere/file", "working outside\n");
+ yield* fs.remove(path.join(cwd, "scope/in/delete"));
+ const indexPath = path.join(cwd, ".git/index");
+ if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
+ const originalIndex = yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null));
+ const captureCwd = nested ? path.join(cwd, "scope") : cwd;
+ for (const turn of [1, 2]) {
+ const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
+ if (turn === 2) {
+ yield* write("scope/in/edit", "second\n");
+ yield* fs.remove(path.join(cwd, "scope/out/new file"));
+ yield* write("scope/out/second", "second addition\n");
+ }
+ const capture = driver.checkpoints.captureCheckpoint({
+ cwd: captureCwd,
+ checkpointRef: ref,
+ });
+ if (indexState === "non-cone-missing") {
+ assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
+ assert.isFalse(
+ yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
+ );
+ assert.isFalse(yield* fs.exists(indexPath));
+ break;
+ }
+ yield* capture;
+ for (const [name, content] of [
+ ["scope/out/deep/absent", "original\n"],
+ ["scope/out/present", "modified skipped\n"],
+ ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
+ ["elsewhere/file", nested ? "original\n" : "working outside\n"],
+ [
+ turn === 1 ? "scope/out/new file" : "scope/out/second",
+ turn === 1 ? "new outside cone\n" : "second addition\n",
+ ],
+ ]) {
+ assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
+ }
+ const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
+ assert.notInclude(files, "scope/in/delete");
+ if (turn === 2) assert.notInclude(files, "scope/out/new file");
+ assert.deepEqual(
+ yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
+ originalIndex,
+ );
+ assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
+ assert.strictEqual(
+ yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
+ "working outside\n",
+ );
+ }
+ }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
+);
it.effect("checkpoint capture keeps the legacy path when Git lacks add --sparse", () =>
Effect.gen(function* () {
@@ -699,206 +686,186 @@ it.effect("checkpoint capture keeps the legacy path when Git lacks add --sparse"
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
-for (const indexMode of ["normal", "flags", "sparse"] as const) {
- it.effect(
- `checkpoint index inspection handles entries beyond the output cap (index=${indexMode})`,
- () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const liveProcess = yield* VcsProcess.VcsProcess;
- const driver = yield* GitVcsDriver.makeVcsDriverShape();
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
- const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
- yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
- yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
- yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
- yield* fs.makeDirectory(path.join(cwd, "excluded"));
- yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
- yield* fs.writeFileString(
- path.join(cwd, ".git/filter.cjs"),
- 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
- );
- yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
- yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
- yield* git(["add", "."]);
- yield* git(["commit", "-m", "inspection fixture"]);
- if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
- if (indexMode === "sparse")
- yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
- yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
- yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
- const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
- const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
- Effect.provideService(VcsProcess.VcsProcess, {
- run: (input) =>
- liveProcess.run(
- input.args.includes("ls-files")
- ? {
- ...input,
- maxOutputBytes: 8,
- onStdoutChunk: (chunk) => {
- for (let i = 0; i < chunk.length; i++)
- input.onStdoutChunk?.(chunk.subarray(i, i + 1));
- },
- }
- : input,
- ),
- }),
- );
- yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
- assert.strictEqual(
- (yield* git(["show", `${checkpointRef}:z-skipped`])).stdout,
- "modified\n",
- );
- if (indexMode !== "flags")
- assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
- assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
- }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
-}
+it.effect.each(["normal", "flags", "sparse"] as const)(
+ "checkpoint index inspection handles entries beyond the output cap (index=%s)",
+ (indexMode) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const liveProcess = yield* VcsProcess.VcsProcess;
+ const driver = yield* GitVcsDriver.makeVcsDriverShape();
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-inspection-" });
+ const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
+ yield* fs.writeFileString(path.join(cwd, ".gitattributes"), "stable filter=probe\n");
+ yield* fs.writeFileString(path.join(cwd, "stable"), "unchanged\n");
+ yield* fs.writeFileString(path.join(cwd, "z-skipped"), "original\n");
+ yield* fs.makeDirectory(path.join(cwd, "excluded"));
+ yield* fs.writeFileString(path.join(cwd, "excluded/file"), "absent\n");
+ yield* fs.writeFileString(
+ path.join(cwd, ".git/filter.cjs"),
+ 'require("node:fs").appendFileSync(".git/reads", "read\\n"); process.stdin.pipe(process.stdout);',
+ );
+ yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]);
+ yield* fs.utimes(path.join(cwd, "stable"), 1_700_000_000, 1_700_000_000);
+ yield* git(["add", "."]);
+ yield* git(["commit", "-m", "inspection fixture"]);
+ if (indexMode === "flags") yield* git(["update-index", "--skip-worktree", "z-skipped"]);
+ if (indexMode === "sparse")
+ yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "included"]);
+ yield* fs.writeFileString(path.join(cwd, "z-skipped"), "modified\n");
+ yield* fs.writeFileString(path.join(cwd, ".git/reads"), "");
+ const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index"));
+ const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe(
+ Effect.provideService(VcsProcess.VcsProcess, {
+ run: (input) =>
+ liveProcess.run(
+ input.args.includes("ls-files")
+ ? {
+ ...input,
+ maxOutputBytes: 8,
+ onStdoutChunk: (chunk) => {
+ for (let i = 0; i < chunk.length; i++)
+ input.onStdoutChunk?.(chunk.subarray(i, i + 1));
+ },
+ }
+ : input,
+ ),
+ }),
+ );
+ yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
+ assert.strictEqual((yield* git(["show", `${checkpointRef}:z-skipped`])).stdout, "modified\n");
+ if (indexMode !== "flags")
+ assert.strictEqual(yield* fs.readFileString(path.join(cwd, ".git/reads")), "");
+ assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex);
+ }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
+);
-for (const timestamp of [1_700_000_000, 1_700_000_000.9999]) {
- it.effect(
- `checkpoint capture preserves same-size edits with racy index timestamps (${timestamp})`,
- () =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const driver = yield* GitVcsDriver.makeVcsDriverShape();
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
- const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
- const filePath = path.join(cwd, "file.txt");
- const indexPath = path.join(cwd, ".git", "index");
- yield* git(["config", "core.trustctime", "false"]);
- yield* fileSystem.writeFileString(filePath, "before\n");
- yield* fileSystem.utimes(filePath, timestamp, timestamp);
- yield* git(["add", "file.txt"]);
- yield* git(["commit", "-m", "record racy file"]);
- yield* fileSystem.utimes(indexPath, timestamp, timestamp);
- const originalIndex = yield* fileSystem.readFile(indexPath);
- const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
- yield* fileSystem.writeFileString(filePath, "after!\n");
- yield* fileSystem.utimes(filePath, timestamp, timestamp);
+it.effect.each([1_700_000_000, 1_700_000_000.9999])(
+ "checkpoint capture preserves same-size edits with racy index timestamps (%s)",
+ (timestamp) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const driver = yield* GitVcsDriver.makeVcsDriverShape();
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-racy-" });
+ const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd);
+ const filePath = path.join(cwd, "file.txt");
+ const indexPath = path.join(cwd, ".git", "index");
+ yield* git(["config", "core.trustctime", "false"]);
+ yield* fileSystem.writeFileString(filePath, "before\n");
+ yield* fileSystem.utimes(filePath, timestamp, timestamp);
+ yield* git(["add", "file.txt"]);
+ yield* git(["commit", "-m", "record racy file"]);
+ yield* fileSystem.utimes(indexPath, timestamp, timestamp);
+ const originalIndex = yield* fileSystem.readFile(indexPath);
+ const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
+ yield* fileSystem.writeFileString(filePath, "after!\n");
+ yield* fileSystem.utimes(filePath, timestamp, timestamp);
- yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
+ yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef });
- assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
- assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
- assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
- }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
-}
-for (const nested of [false, true]) {
- for (const indexState of [
- "sparse",
- "flags",
- "manual-skip",
- "missing",
- "non-cone-missing",
- ] as const) {
- it.effect(
- `sparse checkpoint preserves two captures (nested=${nested}, index=${indexState})`,
- () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const driver = yield* GitVcsDriver.makeVcsDriverShape();
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
- const { git } = yield* makeCheckpointFixture(driver, cwd);
- const write = Effect.fn(function* (name: string, contents: string) {
- yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
- yield* fs.writeFileString(path.join(cwd, name), contents);
- });
- for (const name of [
- "scope/in/edit",
- "scope/in/delete",
- "scope/out/deep/absent",
- "scope/out/present",
- "elsewhere/file",
- ]) {
- yield* write(name, "original\n");
- }
- yield* git(["add", "."]);
- yield* git(["commit", "-m", "sparse fixture"]);
- yield* git([
- "sparse-checkout",
- "set",
- "--cone",
- "--sparse-index",
- "scope/in",
- "elsewhere",
- ]);
- if (indexState === "non-cone-missing")
- yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
- yield* write("scope/in/edit", "staged\n");
- yield* write("elsewhere/file", "staged outside\n");
- yield* git(["add", "."]);
- if (indexState === "flags")
- yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
- if (indexState === "manual-skip")
- yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
- yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
- yield* write("scope/in/edit", "working\n");
- yield* write("scope/out/present", "modified skipped\n");
- yield* write("scope/out/new file", "new outside cone\n");
- yield* write("elsewhere/file", "working outside\n");
- yield* fs.remove(path.join(cwd, "scope/in/delete"));
- const indexPath = path.join(cwd, ".git/index");
- if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
- const originalIndex = yield* fs
- .readFile(indexPath)
- .pipe(Effect.orElseSucceed(() => null));
- const captureCwd = nested ? path.join(cwd, "scope") : cwd;
- for (const turn of [1, 2]) {
- const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
- if (turn === 2) {
- yield* write("scope/in/edit", "second\n");
- yield* fs.remove(path.join(cwd, "scope/out/new file"));
- yield* write("scope/out/second", "second addition\n");
- }
- const capture = driver.checkpoints.captureCheckpoint({
- cwd: captureCwd,
- checkpointRef: ref,
- });
- if (indexState === "non-cone-missing") {
- assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
- assert.isFalse(
- yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
- );
- assert.isFalse(yield* fs.exists(indexPath));
- break;
- }
- yield* capture;
- for (const [name, content] of [
- ["scope/out/deep/absent", "original\n"],
- ["scope/out/present", "modified skipped\n"],
- ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
- ["elsewhere/file", nested ? "original\n" : "working outside\n"],
- [
- turn === 1 ? "scope/out/new file" : "scope/out/second",
- turn === 1 ? "new outside cone\n" : "second addition\n",
- ],
- ]) {
- assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
- }
- const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
- assert.notInclude(files, "scope/in/delete");
- if (turn === 2) assert.notInclude(files, "scope/out/new file");
- assert.deepEqual(
- yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
- originalIndex,
- );
- assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
- assert.strictEqual(
- yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
- "working outside\n",
- );
- }
- }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
- }
-}
+ assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "after!\n");
+ assert.deepEqual(yield* fileSystem.readFile(indexPath), originalIndex);
+ assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
+ }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
+);
+it.effect.each(
+ [false, true].flatMap((nested) =>
+ (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map(
+ (indexState) => ({ nested, indexState }),
+ ),
+ ),
+)(
+ "sparse checkpoint preserves two captures (nested=$nested, index=$indexState)",
+ ({ nested, indexState }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const driver = yield* GitVcsDriver.makeVcsDriverShape();
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" });
+ const { git } = yield* makeCheckpointFixture(driver, cwd);
+ const write = Effect.fn(function* (name: string, contents: string) {
+ yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true });
+ yield* fs.writeFileString(path.join(cwd, name), contents);
+ });
+ for (const name of [
+ "scope/in/edit",
+ "scope/in/delete",
+ "scope/out/deep/absent",
+ "scope/out/present",
+ "elsewhere/file",
+ ]) {
+ yield* write(name, "original\n");
+ }
+ yield* git(["add", "."]);
+ yield* git(["commit", "-m", "sparse fixture"]);
+ yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "scope/in", "elsewhere"]);
+ if (indexState === "non-cone-missing")
+ yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]);
+ yield* write("scope/in/edit", "staged\n");
+ yield* write("elsewhere/file", "staged outside\n");
+ yield* git(["add", "."]);
+ if (indexState === "flags")
+ yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]);
+ if (indexState === "manual-skip")
+ yield* git(["update-index", "--skip-worktree", "scope/in/delete"]);
+ yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]);
+ yield* write("scope/in/edit", "working\n");
+ yield* write("scope/out/present", "modified skipped\n");
+ yield* write("scope/out/new file", "new outside cone\n");
+ yield* write("elsewhere/file", "working outside\n");
+ yield* fs.remove(path.join(cwd, "scope/in/delete"));
+ const indexPath = path.join(cwd, ".git/index");
+ if (indexState.endsWith("missing")) yield* fs.remove(indexPath);
+ const originalIndex = yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null));
+ const captureCwd = nested ? path.join(cwd, "scope") : cwd;
+ for (const turn of [1, 2]) {
+ const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`);
+ if (turn === 2) {
+ yield* write("scope/in/edit", "second\n");
+ yield* fs.remove(path.join(cwd, "scope/out/new file"));
+ yield* write("scope/out/second", "second addition\n");
+ }
+ const capture = driver.checkpoints.captureCheckpoint({
+ cwd: captureCwd,
+ checkpointRef: ref,
+ });
+ if (indexState === "non-cone-missing") {
+ assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError");
+ assert.isFalse(
+ yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }),
+ );
+ assert.isFalse(yield* fs.exists(indexPath));
+ break;
+ }
+ yield* capture;
+ for (const [name, content] of [
+ ["scope/out/deep/absent", "original\n"],
+ ["scope/out/present", "modified skipped\n"],
+ ["scope/in/edit", turn === 1 ? "working\n" : "second\n"],
+ ["elsewhere/file", nested ? "original\n" : "working outside\n"],
+ [
+ turn === 1 ? "scope/out/new file" : "scope/out/second",
+ turn === 1 ? "new outside cone\n" : "second addition\n",
+ ],
+ ]) {
+ assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content);
+ }
+ const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0");
+ assert.notInclude(files, "scope/in/delete");
+ if (turn === 2) assert.notInclude(files, "scope/out/new file");
+ assert.deepEqual(
+ yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)),
+ originalIndex,
+ );
+ assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent")));
+ assert.strictEqual(
+ yield* fs.readFileString(path.join(cwd, "elsewhere/file")),
+ "working outside\n",
+ );
+ }
+ }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
+);
it.effect("checkpoint capture preserves racy edits made after resetting the index", () =>
Effect.gen(function* () {
@@ -943,89 +910,87 @@ it.effect("checkpoint capture preserves racy edits made after resetting the inde
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
);
-for (const nested of [false, true]) {
- for (const indexMode of ["normal", "flags", "split"] as const) {
- it.effect(
- `checkpoint index reuse preserves two turns (nested=${nested}, index=${indexMode})`,
- () =>
- Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const driver = yield* GitVcsDriver.makeVcsDriverShape();
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
- const { git } = yield* makeCheckpointFixture(driver, cwd);
- const write = (name: string, contents: string) =>
- fileSystem.writeFileString(path.join(cwd, name), contents);
- yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
- for (const name of [
- "scope/staged",
- "scope/deleted",
- "scope/assumed",
- "scope/skipped",
- "outside",
- ]) {
- yield* write(name, "original\n");
- }
- yield* git(["add", "."]);
- yield* git(["commit", "-m", "initial scoped files"]);
- yield* write("scope/staged", "staged\n");
- yield* write("scope/new-deleted", "staged then deleted\n");
- yield* write("outside", "staged outside\n");
- yield* git(["add", "."]);
- if (indexMode === "flags") {
- yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
- yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
- }
- if (indexMode === "split") {
- yield* git(["update-index", "--split-index"]);
- }
- const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
- for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
- yield* write(name, "working\n");
- }
- yield* write("scope/new", "first\n");
- yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
- yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
- const captureCwd = nested ? path.join(cwd, "scope") : cwd;
- const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
- const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
- yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
- for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
- assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
- }
- assert.strictEqual(
- (yield* git(["show", `${first}:outside`])).stdout,
- nested ? "original\n" : "working\n",
- );
- const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
- assert.notInclude(files, "scope/deleted");
- assert.notInclude(files, "scope/new-deleted");
- assert.include(files, "scope/new");
+it.effect.each(
+ [false, true].flatMap((nested) =>
+ (["normal", "flags", "split"] as const).map((indexMode) => ({ nested, indexMode })),
+ ),
+)(
+ "checkpoint index reuse preserves two turns (nested=$nested, index=$indexMode)",
+ ({ nested, indexMode }) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const driver = yield* GitVcsDriver.makeVcsDriverShape();
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-turns-" });
+ const { git } = yield* makeCheckpointFixture(driver, cwd);
+ const write = (name: string, contents: string) =>
+ fileSystem.writeFileString(path.join(cwd, name), contents);
+ yield* fileSystem.makeDirectory(path.join(cwd, "scope"));
+ for (const name of [
+ "scope/staged",
+ "scope/deleted",
+ "scope/assumed",
+ "scope/skipped",
+ "outside",
+ ]) {
+ yield* write(name, "original\n");
+ }
+ yield* git(["add", "."]);
+ yield* git(["commit", "-m", "initial scoped files"]);
+ yield* write("scope/staged", "staged\n");
+ yield* write("scope/new-deleted", "staged then deleted\n");
+ yield* write("outside", "staged outside\n");
+ yield* git(["add", "."]);
+ if (indexMode === "flags") {
+ yield* git(["update-index", "--assume-unchanged", "scope/assumed"]);
+ yield* git(["update-index", "--skip-worktree", "scope/skipped"]);
+ }
+ if (indexMode === "split") {
+ yield* git(["update-index", "--split-index"]);
+ }
+ const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index"));
+ for (const name of ["scope/staged", "scope/assumed", "scope/skipped", "outside"]) {
+ yield* write(name, "working\n");
+ }
+ yield* write("scope/new", "first\n");
+ yield* fileSystem.remove(path.join(cwd, "scope/deleted"));
+ yield* fileSystem.remove(path.join(cwd, "scope/new-deleted"));
+ const captureCwd = nested ? path.join(cwd, "scope") : cwd;
+ const first = CheckpointRef.make("refs/t3/checkpoints/turns/1");
+ const second = CheckpointRef.make("refs/t3/checkpoints/turns/2");
+ yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: first });
+ for (const name of ["scope/staged", "scope/assumed", "scope/skipped"]) {
+ assert.strictEqual((yield* git(["show", `${first}:${name}`])).stdout, "working\n");
+ }
+ assert.strictEqual(
+ (yield* git(["show", `${first}:outside`])).stdout,
+ nested ? "original\n" : "working\n",
+ );
+ const files = (yield* git(["ls-tree", "-r", "--name-only", first])).stdout.split("\n");
+ assert.notInclude(files, "scope/deleted");
+ assert.notInclude(files, "scope/new-deleted");
+ assert.include(files, "scope/new");
- yield* write("scope/staged", "second\n");
- yield* fileSystem.remove(path.join(cwd, "scope/new"));
- yield* write("scope/second", "added in second turn\n");
- yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
- assert.strictEqual(
- (yield* git(["diff", "--name-only", first, second])).stdout,
- "scope/new\nscope/second\nscope/staged\n",
- );
- assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
- assert.strictEqual(
- (yield* git(["show", `${second}:scope/second`])).stdout,
- "added in second turn\n",
- );
- assert.deepEqual(
- yield* fileSystem.readFile(path.join(cwd, ".git", "index")),
- originalIndex,
- );
- }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
- }
-}
+ yield* write("scope/staged", "second\n");
+ yield* fileSystem.remove(path.join(cwd, "scope/new"));
+ yield* write("scope/second", "added in second turn\n");
+ yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef: second });
+ assert.strictEqual(
+ (yield* git(["diff", "--name-only", first, second])).stdout,
+ "scope/new\nscope/second\nscope/staged\n",
+ );
+ assert.strictEqual((yield* git(["show", `${second}:scope/staged`])).stdout, "second\n");
+ assert.strictEqual(
+ (yield* git(["show", `${second}:scope/second`])).stdout,
+ "added in second turn\n",
+ );
+ assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex);
+ }).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
+);
-for (const indexState of ["missing", "invalid"] as const) {
- it.effect(`checkpoint capture falls back when the user index is ${indexState}`, () =>
+it.effect.each(["missing", "invalid"] as const)(
+ "checkpoint capture falls back when the user index is %s",
+ (indexState) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -1048,8 +1013,7 @@ for (const indexState of ["missing", "invalid"] as const) {
assert.strictEqual(yield* fileSystem.readFileString(indexPath), "invalid index");
}
}).pipe(Effect.scoped, Effect.provide(GitContractLayer)),
- );
-}
+);
it.effect("restores empty checkpoints without changing paths outside the workspace", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts
index 53a18551aaf..32dc3441dd6 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts
@@ -254,50 +254,48 @@ it.effect.each([{ timeoutMs: null }, { timeoutMs: 30_001 }])(
}).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
);
-for (const location of ["root", "nested", "worktree"] as const) {
- it.effect(
- `skips clean filters while the ${location} index is locked and resumes after unlock`,
- () =>
- Effect.gen(function* () {
- const driver = yield* GitVcsDriver.GitVcsDriver;
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const repository = yield* makeTmpDir();
- yield* initRepoWithCommit(repository);
- const cwd = location === "worktree" ? yield* makeTmpDir() : repository;
- if (location === "worktree") {
- yield* git(repository, ["worktree", "add", "--detach", cwd]);
- }
- yield* git(cwd, ["config", "filter.probe.clean", "echo clean >> .filter-runs; cat"]);
- yield* writeTextFile(cwd, ".gitattributes", "asset.bin filter=probe\n");
- yield* writeTextFile(cwd, ".gitignore", ".filter-runs\n");
- yield* writeTextFile(cwd, "asset.bin", "original\n");
- yield* git(cwd, ["add", "."]);
- yield* git(cwd, ["commit", "-m", "filtered asset"]);
- NodeFS.utimesSync(path.join(cwd, "asset.bin"), 1, 1);
- const runsPath = path.join(cwd, ".filter-runs");
- yield* fs.remove(runsPath, { force: true });
- const indexPath = yield* git(cwd, ["rev-parse", "--git-path", "index"]);
- const lockPath = `${path.resolve(cwd, indexPath)}.lock`;
- yield* fs.writeFileString(lockPath, "");
- const statusCwd = location === "nested" ? path.join(cwd, "nested") : cwd;
- yield* fs.makeDirectory(statusCwd, { recursive: true });
-
- for (let poll = 0; poll < 3; poll++) {
- const result = yield* driver.statusDetailsLocal(statusCwd).pipe(Effect.result);
- assert.isTrue(Result.isFailure(result));
- if (Result.isFailure(result)) assert.include(result.failure.detail, "index is locked");
- }
- assert.isFalse(yield* fs.exists(runsPath));
- assert.isTrue(yield* fs.exists(lockPath));
-
- yield* fs.remove(lockPath);
- const status = yield* driver.statusDetailsLocal(statusCwd);
- assert.isFalse(status.hasWorkingTreeChanges);
- assert.include(yield* fs.readFileString(runsPath), "clean");
- }).pipe(Effect.provide(TestLayer)),
- );
-}
+it.effect.each(["root", "nested", "worktree"] as const)(
+ "skips clean filters while the %s index is locked and resumes after unlock",
+ (location) =>
+ Effect.gen(function* () {
+ const driver = yield* GitVcsDriver.GitVcsDriver;
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const repository = yield* makeTmpDir();
+ yield* initRepoWithCommit(repository);
+ const cwd = location === "worktree" ? yield* makeTmpDir() : repository;
+ if (location === "worktree") {
+ yield* git(repository, ["worktree", "add", "--detach", cwd]);
+ }
+ yield* git(cwd, ["config", "filter.probe.clean", "echo clean >> .filter-runs; cat"]);
+ yield* writeTextFile(cwd, ".gitattributes", "asset.bin filter=probe\n");
+ yield* writeTextFile(cwd, ".gitignore", ".filter-runs\n");
+ yield* writeTextFile(cwd, "asset.bin", "original\n");
+ yield* git(cwd, ["add", "."]);
+ yield* git(cwd, ["commit", "-m", "filtered asset"]);
+ NodeFS.utimesSync(path.join(cwd, "asset.bin"), 1, 1);
+ const runsPath = path.join(cwd, ".filter-runs");
+ yield* fs.remove(runsPath, { force: true });
+ const indexPath = yield* git(cwd, ["rev-parse", "--git-path", "index"]);
+ const lockPath = `${path.resolve(cwd, indexPath)}.lock`;
+ yield* fs.writeFileString(lockPath, "");
+ const statusCwd = location === "nested" ? path.join(cwd, "nested") : cwd;
+ yield* fs.makeDirectory(statusCwd, { recursive: true });
+
+ for (let poll = 0; poll < 3; poll++) {
+ const result = yield* driver.statusDetailsLocal(statusCwd).pipe(Effect.result);
+ assert.isTrue(Result.isFailure(result));
+ if (Result.isFailure(result)) assert.include(result.failure.detail, "index is locked");
+ }
+ assert.isFalse(yield* fs.exists(runsPath));
+ assert.isTrue(yield* fs.exists(lockPath));
+
+ yield* fs.remove(lockPath);
+ const status = yield* driver.statusDetailsLocal(statusCwd);
+ assert.isFalse(status.hasWorkingTreeChanges);
+ assert.include(yield* fs.readFileString(runsPath), "clean");
+ }).pipe(Effect.provide(TestLayer)),
+);
it.effect("uses stable diagnostics for every parsed non-repository command", () => {
const commands: Array<{ readonly args: ReadonlyArray<string>; readonly lcAll?: string }> = [];
@@ -822,7 +820,7 @@ it.effect("backs off and logs failed fetch attempts across linked worktrees", ()
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
);
-for (const scenario of [
+it.effect.each([
{
name: "HTTPS credentials",
stderr: "fatal: Authentication failed for",
@@ -885,53 +883,51 @@ for (const scenario of [
stderr: "fatal: unexpected remote failure",
expected: "git fetch origin failed",
},
-] as const) {
- it.effect(`reports ${scenario.name} during fetch without retaining remote output`, () =>
- Effect.gen(function* () {
- const secret = "secret-fetch-token";
- const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`;
- const attempts = yield* Ref.make(0);
- const spawner = ChildProcessSpawner.make((command) =>
- Effect.gen(function* () {
- if (!ChildProcess.isStandardCommand(command))
- return yield* Effect.die("expected Git command");
- if (command.args[0] !== "fetch") return makeNonRepositoryHandle();
- assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);
- assert.equal(command.options.env?.LC_ALL, "C");
- assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");
- yield* Ref.update(attempts, (count) => count + 1);
- return ChildProcessSpawner.makeHandle({
- pid: ChildProcessSpawner.ProcessId(1),
- exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
- isRunning: Effect.succeed(false),
- kill: () => Effect.void,
- unref: Effect.succeed(Effect.void),
- stdin: Sink.drain,
- stdout: Stream.encodeText(Stream.make(secret)),
- stderr: Stream.encodeText(Stream.make(stderr)),
- all: Stream.empty,
- getInputFd: () => Sink.drain,
- getOutputFd: () => Stream.empty,
- });
- }),
- );
- const driver = yield* makeGitVcsDriverCore().pipe(
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
- );
- const cwd = yield* makeTmpDir();
- const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
- assert.include(error.detail, scenario.expected);
- assert.equal(error.exitCode, 128);
- assert.equal(error.stderrLength, stderr.length);
- assert.equal(error.stdoutLength, secret.length);
- assert.notInclude(error.message, secret);
- assert.notInclude(yield* encodeGitCommandError(error), secret);
- assert.notProperty(error, "stderr");
- assert.notProperty(error, "args");
- assert.equal(yield* Ref.get(attempts), 1);
- }).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
- );
-}
+] as const)("reports $name during fetch without retaining remote output", (scenario) =>
+ Effect.gen(function* () {
+ const secret = "secret-fetch-token";
+ const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`;
+ const attempts = yield* Ref.make(0);
+ const spawner = ChildProcessSpawner.make((command) =>
+ Effect.gen(function* () {
+ if (!ChildProcess.isStandardCommand(command))
+ return yield* Effect.die("expected Git command");
+ if (command.args[0] !== "fetch") return makeNonRepositoryHandle();
+ assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);
+ assert.equal(command.options.env?.LC_ALL, "C");
+ assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");
+ yield* Ref.update(attempts, (count) => count + 1);
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.encodeText(Stream.make(secret)),
+ stderr: Stream.encodeText(Stream.make(stderr)),
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ });
+ }),
+ );
+ const driver = yield* makeGitVcsDriverCore().pipe(
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ );
+ const cwd = yield* makeTmpDir();
+ const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
+ assert.include(error.detail, scenario.expected);
+ assert.equal(error.exitCode, 128);
+ assert.equal(error.stderrLength, stderr.length);
+ assert.equal(error.stdoutLength, secret.length);
+ assert.notInclude(error.message, secret);
+ assert.notInclude(yield* encodeGitCommandError(error), secret);
+ assert.notProperty(error, "stderr");
+ assert.notProperty(error, "args");
+ assert.equal(yield* Ref.get(attempts), 1);
+ }).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
+);
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
describe("process environment", () => {
@@ -1449,8 +1445,9 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
- for (const splitIndex of [false, true]) {
- it.effect(`keeps the preceding second cached in review previews (split: ${splitIndex})`, () =>
+ it.effect.each([false, true])(
+ "keeps the preceding second cached in review previews (split: %s)",
+ (splitIndex) =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
yield* initRepoWithCommit(cwd);
@@ -1484,53 +1481,50 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
assert.deepStrictEqual(yield* fs.readFile(indexPath), originalIndex);
assert.deepStrictEqual((yield* fs.stat(indexPath)).mtime, originalMtime);
}),
- );
- }
+ );
- for (const [timestamp, splitIndex] of [
+ it.effect.each([
[1_700_000_000, false],
[1_700_000_000.9999, false],
[1_700_000_000, true],
[1_700_000_000.9999, true],
- ] as const) {
- it.effect(
- `preserves same-size edits with a racy review index (${timestamp}, split: ${splitIndex})`,
- () =>
- Effect.gen(function* () {
- const cwd = yield* makeTmpDir();
- yield* initRepoWithCommit(cwd);
- const driver = yield* GitVcsDriver.GitVcsDriver;
- const fileSystem = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const filePath = path.join(cwd, "tracked.txt");
- const indexPath = path.join(cwd, ".git", "index");
- // Reproduce a same-timestamp edit without relying on filesystem clock resolution.
- yield* git(cwd, ["config", "core.trustctime", "false"]);
- yield* writeTextFile(cwd, "tracked.txt", "before\n");
- yield* fileSystem.utimes(filePath, timestamp, timestamp);
- yield* git(cwd, ["add", "tracked.txt"]);
- yield* git(cwd, ["commit", "-m", "record racy file"]);
- if (splitIndex) yield* git(cwd, ["update-index", "--split-index"]);
- yield* fileSystem.utimes(indexPath, timestamp, timestamp);
- const originalIndex = yield* fileSystem.readFile(indexPath);
- const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
- yield* writeTextFile(cwd, "tracked.txt", "after!\n");
- yield* fileSystem.utimes(filePath, timestamp, timestamp);
- yield* writeTextFile(cwd, "untracked.txt", "new\n");
-
- const preview = yield* driver.getReviewDiffPreview({ cwd });
- const dirty = preview.sources.find((source) => source.kind === "working-tree")!;
- assert.deepStrictEqual(dirty.files, [
- { path: "tracked.txt", previousPath: null, additions: 1, deletions: 1 },
- { path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 },
- ]);
- assert.include(dirty.diff, "-before");
- assert.include(dirty.diff, "+after!");
- assert.deepStrictEqual(yield* fileSystem.readFile(indexPath), originalIndex);
- assert.deepStrictEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
- }),
- );
- }
+ ] as const)(
+ "preserves same-size edits with a racy review index (%s, split: %s)",
+ ([timestamp, splitIndex]) =>
+ Effect.gen(function* () {
+ const cwd = yield* makeTmpDir();
+ yield* initRepoWithCommit(cwd);
+ const driver = yield* GitVcsDriver.GitVcsDriver;
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const filePath = path.join(cwd, "tracked.txt");
+ const indexPath = path.join(cwd, ".git", "index");
+ // Reproduce a same-timestamp edit without relying on filesystem clock resolution.
+ yield* git(cwd, ["config", "core.trustctime", "false"]);
+ yield* writeTextFile(cwd, "tracked.txt", "before\n");
+ yield* fileSystem.utimes(filePath, timestamp, timestamp);
+ yield* git(cwd, ["add", "tracked.txt"]);
+ yield* git(cwd, ["commit", "-m", "record racy file"]);
+ if (splitIndex) yield* git(cwd, ["update-index", "--split-index"]);
+ yield* fileSystem.utimes(indexPath, timestamp, timestamp);
+ const originalIndex = yield* fileSystem.readFile(indexPath);
+ const originalIndexMtime = (yield* fileSystem.stat(indexPath)).mtime;
+ yield* writeTextFile(cwd, "tracked.txt", "after!\n");
+ yield* fileSystem.utimes(filePath, timestamp, timestamp);
+ yield* writeTextFile(cwd, "untracked.txt", "new\n");
+
+ const preview = yield* driver.getReviewDiffPreview({ cwd });
+ const dirty = preview.sources.find((source) => source.kind === "working-tree")!;
+ assert.deepStrictEqual(dirty.files, [
+ { path: "tracked.txt", previousPath: null, additions: 1, deletions: 1 },
+ { path: "untracked.txt", previousPath: null, additions: 1, deletions: 0 },
+ ]);
+ assert.include(dirty.diff, "-before");
+ assert.include(dirty.diff, "+after!");
+ assert.deepStrictEqual(yield* fileSystem.readFile(indexPath), originalIndex);
+ assert.deepStrictEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime);
+ }),
+ );
it.effect("keeps complete stats for files beyond the combined patch limit", () =>
Effect.gen(function* () {
@@ -2940,8 +2934,9 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
describe("remote operations", () => {
- for (const failure of ["offline", "auth", "timeout"] as const) {
- it.effect(`does not retry a scoped fetch after ${failure}`, () =>
+ it.effect.each(["offline", "auth", "timeout"] as const)(
+ "does not retry a scoped fetch after %s",
+ (failure) =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -2996,8 +2991,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
);
}
}),
- );
- }
+ );
it.effect("creates a worktree from the latest fetched remote commit", () =>
Effect.gen(function* () {
diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts
index 579b546fb65..50e9e469c17 100644
--- a/apps/web/src/components/chat/queuedMessageEdit.test.ts
+++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts
@@ -42,24 +42,25 @@ describe("queued message file edits", () => {
useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
});
- for (const images of [[], [image]]) {
- it(`preserves a generic file in a ${images.length === 0 ? "file-only" : "mixed"} save`, async () => {
- const attachments = await prepareQueuedEditAttachments({
- existingAttachments: [],
- images,
- files: [file],
- uploadFiles: async () => [uploadedFile],
- readImage: async () => "data:image/png;base64,aW1hZ2U=",
- });
- expect(attachments.at(-1)).toEqual(uploadedFile);
- expect(attachments.length).toBe(images.length + 1);
- if (images.length > 0)
- expect(attachments[0]).toMatchObject({
- type: "image",
- dataUrl: "data:image/png;base64,aW1hZ2U=",
- });
+ it.each([
+ { images: [], label: "file-only" },
+ { images: [image], label: "mixed" },
+ ])("preserves a generic file in a $label save", async ({ images }) => {
+ const attachments = await prepareQueuedEditAttachments({
+ existingAttachments: [],
+ images,
+ files: [file],
+ uploadFiles: async () => [uploadedFile],
+ readImage: async () => "data:image/png;base64,aW1hZ2U=",
});
- }
+ expect(attachments.at(-1)).toEqual(uploadedFile);
+ expect(attachments.length).toBe(images.length + 1);
+ if (images.length > 0)
+ expect(attachments[0]).toMatchObject({
+ type: "image",
+ dataUrl: "data:image/png;base64,aW1hZ2U=",
+ });
+ });
it("retains saved attachments alongside newly uploaded files", async () => {
const saved = { ...uploadedFile, id: "saved:earlier" };
diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts
index 6b347f4e263..18604e44e19 100644
--- a/apps/web/src/keybindings.test.ts
+++ b/apps/web/src/keybindings.test.ts
@@ -1279,8 +1279,9 @@ describe("composer and pull request shortcuts", () => {
["Enter", "thread.steerQueuedMessage"],
] as const;
- for (const platform of ["MacIntel", "Win32", "Linux"]) {
- it(`separates queued steering and background start on ${platform}`, () => {
+ it.each(["MacIntel", "Win32", "Linux"])(
+ "separates queued steering and background start on %s",
+ (platform) => {
const modifier = {
metaKey: platform === "MacIntel",
ctrlKey: platform !== "MacIntel",
@@ -1301,8 +1302,8 @@ describe("composer and pull request shortcuts", () => {
}),
"composer.sendBackground",
);
- });
- }
+ },
+ );
for (const platform of ["MacIntel", "Win32", "Linux"]) {
it.each(shortcuts)(
@@ -1331,8 +1332,9 @@ describe("composer and pull request shortcuts", () => {
);
}
- for (const platform of ["MacIntel", "Win32", "Linux"]) {
- it(`edits the last queued message with Alt+ArrowUp from the composer on ${platform}`, () => {
+ it.each(["MacIntel", "Win32", "Linux"])(
+ "edits the last queued message with Alt+ArrowUp from the composer on %s",
+ (platform) => {
const input = event({ key: "ArrowUp", altKey: true });
assert.strictEqual(
resolveShortcutCommand(input, DEFAULT_RESOLVED_KEYBINDINGS, {
@@ -1347,8 +1349,8 @@ describe("composer and pull request shortcuts", () => {
context: { composerFocus: false },
}),
);
- });
- }
+ },
+ );
for (const platform of ["MacIntel", "Win32", "Linux"]) {
it.each([
diff --git a/infra/relay/src/agentActivity/ApnsClient.test.ts b/infra/relay/src/agentActivity/ApnsClient.test.ts
index 6c54600e054..9031c7df18a 100644
--- a/infra/relay/src/agentActivity/ApnsClient.test.ts
+++ b/infra/relay/src/agentActivity/ApnsClient.test.ts
@@ -366,79 +366,79 @@ describe("ApnsClient", () => {
}).pipe(Effect.provide(layer));
});
- for (const requestKind of ["live-activity", "push-notification"] as const) {
- for (const stage of ["send", "read-response"] as const) {
- it.effect(`aborts a stalled ${requestKind} ${stage} after ten seconds`, () =>
- Effect.gen(function* () {
- const started = yield* Deferred.make<void>();
- const signals: AbortSignal[] = [];
- const stalledHttpClient = HttpClient.make((request, _url, signal) => {
- signals.push(signal);
- const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
- if (stage === "send") return stall;
- const response = HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
- Object.defineProperty(response, "text", { value: stall });
- return Effect.succeed(response);
- });
- const layer = ApnsClient.layer.pipe(
- Layer.provide(Layer.succeed(HttpClient.HttpClient, stalledHttpClient)),
- Layer.provide(
- Layer.succeed(ApnsProviderTokens.ApnsProviderTokens, {
- getJwt: () => Effect.succeed("test-jwt"),
- }),
- ),
- );
- const apns = yield* ApnsClient.ApnsClient.pipe(Effect.provide(layer));
- const credentials = {
- teamId: "team-timeout",
- keyId: "key-timeout",
- privateKey: Redacted.make("unused-test-key"),
- bundleId: "com.t3tools.test",
- environment: "sandbox",
- } satisfies ApnsCredentials;
- const send =
- requestKind === "live-activity"
- ? apns.sendLiveActivityRequest({
- credentials,
- issuedAtUnixSeconds: 123,
- request: apns.makeLiveActivityRequest({
- event: "update",
- token: "long-push-token",
- state,
- nowEpochSeconds: 123,
- nowIso: DateTime.formatIso(now),
- }),
- })
- : apns.sendPushNotificationRequest({
- credentials,
- issuedAtUnixSeconds: 123,
- request: apns.makePushNotificationRequest({
- token: "long-push-token",
- notification: {
- title: "Thread",
- body: "Done",
- environmentId: "env",
- threadId: "thread",
- deepLink: "/",
- },
- }),
- });
- const fiber = yield* send.pipe(Effect.flip, Effect.forkChild);
- yield* Deferred.await(started);
- yield* TestClock.adjust("10 seconds");
- expect(signals[0]?.aborted).toBe(true);
- const error = yield* Fiber.join(fiber);
- expect(error).toMatchObject({
- _tag: "ApnsHttpRequestError",
- requestKind,
- event: requestKind === "live-activity" ? "update" : null,
- stage,
- status: stage === "read-response" ? 200 : null,
- tokenSuffix: "sh-token",
- cause: { _tag: "TimeoutError" },
- });
- }),
+ it.effect.each(
+ (["live-activity", "push-notification"] as const).flatMap((requestKind) =>
+ (["send", "read-response"] as const).map((stage) => ({ requestKind, stage })),
+ ),
+ )("aborts a stalled $requestKind $stage after ten seconds", ({ requestKind, stage }) =>
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const signals: AbortSignal[] = [];
+ const stalledHttpClient = HttpClient.make((request, _url, signal) => {
+ signals.push(signal);
+ const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
+ if (stage === "send") return stall;
+ const response = HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
+ Object.defineProperty(response, "text", { value: stall });
+ return Effect.succeed(response);
+ });
+ const layer = ApnsClient.layer.pipe(
+ Layer.provide(Layer.succeed(HttpClient.HttpClient, stalledHttpClient)),
+ Layer.provide(
+ Layer.succeed(ApnsProviderTokens.ApnsProviderTokens, {
+ getJwt: () => Effect.succeed("test-jwt"),
+ }),
+ ),
);
- }
- }
+ const apns = yield* ApnsClient.ApnsClient.pipe(Effect.provide(layer));
+ const credentials = {
+ teamId: "team-timeout",
+ keyId: "key-timeout",
+ privateKey: Redacted.make("unused-test-key"),
+ bundleId: "com.t3tools.test",
+ environment: "sandbox",
+ } satisfies ApnsCredentials;
+ const send =
+ requestKind === "live-activity"
+ ? apns.sendLiveActivityRequest({
+ credentials,
+ issuedAtUnixSeconds: 123,
+ request: apns.makeLiveActivityRequest({
+ event: "update",
+ token: "long-push-token",
+ state,
+ nowEpochSeconds: 123,
+ nowIso: DateTime.formatIso(now),
+ }),
+ })
+ : apns.sendPushNotificationRequest({
+ credentials,
+ issuedAtUnixSeconds: 123,
+ request: apns.makePushNotificationRequest({
+ token: "long-push-token",
+ notification: {
+ title: "Thread",
+ body: "Done",
+ environmentId: "env",
+ threadId: "thread",
+ deepLink: "/",
+ },
+ }),
+ });
+ const fiber = yield* send.pipe(Effect.flip, Effect.forkChild);
+ yield* Deferred.await(started);
+ yield* TestClock.adjust("10 seconds");
+ expect(signals[0]?.aborted).toBe(true);
+ const error = yield* Fiber.join(fiber);
+ expect(error).toMatchObject({
+ _tag: "ApnsHttpRequestError",
+ requestKind,
+ event: requestKind === "live-activity" ? "update" : null,
+ stage,
+ status: stage === "read-response" ? 200 : null,
+ tokenSuffix: "sh-token",
+ cause: { _tag: "TimeoutError" },
+ });
+ }),
+ );
});
diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts
index e98c2b63959..934ebfdb442 100644
--- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts
+++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts
@@ -1909,8 +1909,9 @@ describe("live activity alert decisions", () => {
});
describe("queued iOS alert policy", () => {
- for (const scenario of ["enabled", "muted", "late"] as const) {
- it.effect(`checks the current policy for a ${scenario} completion`, () => {
+ it.effect.each(["enabled", "muted", "late"] as const)(
+ "checks the current policy for a %s completion",
+ (scenario) => {
let sent = 0;
const completed = { ...state, phase: "completed" as const };
const prefs = JSON.parse(enabledPreferences);
@@ -1957,8 +1958,8 @@ describe("queued iOS alert policy", () => {
}),
),
);
- });
- }
+ },
+ );
});
describe("fast completion delivery", () => {
@@ -2019,74 +2020,74 @@ describe("fast completion delivery", () => {
});
describe("signed APNs registration metadata", () => {
- for (const kind of ["live_activity_update", "push_notification"] as const) {
- for (const changed of ["bundle", "environment", "legacy"] as const) {
- it.effect(`routes ${kind} using current registration with ${changed} job metadata`, () => {
- const attempts: DeliveryAttempts.DeliveryAttemptInput[] = [];
- const requests: HttpClientRequest.HttpClientRequest[] = [];
- const payload = makeApnsDeliveryJobPayload({
- kind,
- userId: target.user_id,
- deviceId: target.device_id,
- token: "unchanged-token",
- ...(changed === "legacy"
- ? {}
- : { bundleId: "com.t3tools.t3code.dev", apsEnvironment: "sandbox" as const }),
- aggregate: kind === "live_activity_update" ? aggregate : null,
- ...(kind === "push_notification"
- ? {
- notification: {
- title: "Thread",
- body: "Input: Project",
- environmentId: "env",
- threadId: "thread",
- deepLink: "/",
- },
- }
- : {}),
- createdAt: "1970-01-01T00:00:00.000Z",
- expiresAt: "1970-01-01T00:10:00.000Z",
- jobId: `metadata-${kind}-${changed}`,
- });
- const signed = signApnsDeliveryJob({
- secret: config.apnsDeliveryJobSigningSecret,
- payload,
- });
- return Effect.gen(function* () {
- const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
- const result = yield* deliveries.processSignedJob(signed);
- expect(result.ok).toBe(true);
- expect(requests).toHaveLength(1);
- expect(requests[0]?.url).toBe(
- `${changed === "environment" ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"}/3/device/unchanged-token`,
- );
- expect(requests[0]?.headers["apns-topic"]).toBe(
- `${changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev"}${kind === "live_activity_update" ? ".push-type.liveactivity" : ""}`,
- );
- }).pipe(
- Effect.provide(
- makeLayer({
- attempts,
- config: signingConfig,
- currentTargets: [
- {
- ...target,
- push_token: "unchanged-token",
- activity_push_token: "unchanged-token",
- bundle_id:
- changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev",
- aps_environment: changed === "environment" ? "production" : "sandbox",
- },
- ],
- execute: (request) =>
- Effect.sync(() => {
- requests.push(request);
- return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
- }),
+ it.effect.each(
+ (["live_activity_update", "push_notification"] as const).flatMap((kind) =>
+ (["bundle", "environment", "legacy"] as const).map((changed) => ({ kind, changed })),
+ ),
+ )("routes $kind using current registration with $changed job metadata", ({ kind, changed }) => {
+ const attempts: DeliveryAttempts.DeliveryAttemptInput[] = [];
+ const requests: HttpClientRequest.HttpClientRequest[] = [];
+ const payload = makeApnsDeliveryJobPayload({
+ kind,
+ userId: target.user_id,
+ deviceId: target.device_id,
+ token: "unchanged-token",
+ ...(changed === "legacy"
+ ? {}
+ : { bundleId: "com.t3tools.t3code.dev", apsEnvironment: "sandbox" as const }),
+ aggregate: kind === "live_activity_update" ? aggregate : null,
+ ...(kind === "push_notification"
+ ? {
+ notification: {
+ title: "Thread",
+ body: "Input: Project",
+ environmentId: "env",
+ threadId: "thread",
+ deepLink: "/",
+ },
+ }
+ : {}),
+ createdAt: "1970-01-01T00:00:00.000Z",
+ expiresAt: "1970-01-01T00:10:00.000Z",
+ jobId: `metadata-${kind}-${changed}`,
+ });
+ const signed = signApnsDeliveryJob({
+ secret: config.apnsDeliveryJobSigningSecret,
+ payload,
+ });
+ return Effect.gen(function* () {
+ const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
+ const result = yield* deliveries.processSignedJob(signed);
+ expect(result.ok).toBe(true);
+ expect(requests).toHaveLength(1);
+ expect(requests[0]?.url).toBe(
+ `${changed === "environment" ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"}/3/device/unchanged-token`,
+ );
+ expect(requests[0]?.headers["apns-topic"]).toBe(
+ `${changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev"}${kind === "live_activity_update" ? ".push-type.liveactivity" : ""}`,
+ );
+ }).pipe(
+ Effect.provide(
+ makeLayer({
+ attempts,
+ config: signingConfig,
+ currentTargets: [
+ {
+ ...target,
+ push_token: "unchanged-token",
+ activity_push_token: "unchanged-token",
+ bundle_id:
+ changed === "bundle" ? "com.t3tools.t3code.preview" : "com.t3tools.t3code.dev",
+ aps_environment: changed === "environment" ? "production" : "sandbox",
+ },
+ ],
+ execute: (request) =>
+ Effect.sync(() => {
+ requests.push(request);
+ return HttpClientResponse.fromWeb(request, new Response("", { status: 200 }));
}),
- ),
- );
- });
- }
- }
+ }),
+ ),
+ );
+ });
});
diff --git a/infra/relay/src/agentActivity/FcmDeliveries.test.ts b/infra/relay/src/agentActivity/FcmDeliveries.test.ts
index a32819f39b5..b42a4348a2c 100644
--- a/infra/relay/src/agentActivity/FcmDeliveries.test.ts
+++ b/infra/relay/src/agentActivity/FcmDeliveries.test.ts
@@ -215,36 +215,39 @@ describe("Android delivery routing", () => {
deepLink: "/threads/env/second-thread",
};
- for (const [firstPhase, secondPhase, title, active] of [
- ["waiting_for_approval", "waiting_for_input", "2 agents need attention", "true"],
- ["completed", "failed", "2 agents finished", "false"],
- ] as const) {
- it.effect(
- `routes grouped ${firstPhase} and ${secondPhase} to the overview once across their queued jobs`,
- () => {
- const h = harness();
- h.current.otherStates = [secondState];
- return Effect.gen(function* () {
- const delivery = yield* FcmDeliveries.FcmDeliveries;
- yield* delivery.process(h.job);
- h.current.state = { ...state, phase: firstPhase };
- h.current.otherStates = [{ ...secondState, phase: secondPhase }];
- yield* delivery.process({ ...h.job, state: h.current.state });
- yield* delivery.process({ ...h.job, state: h.current.otherStates[0] });
- yield* delivery.process({ ...h.job, state: h.current.state });
- const alerts = h.sent.filter((message) => message.alert);
- expect(alerts).toHaveLength(1);
- expect(alerts[0]?.data).toMatchObject({
- alert_title: title,
- alert_body: "Fix notifications, Second thread",
- alert_path: "/",
- active,
- });
- expect(h.marked.at(-1)?.aggregate?.activities).toHaveLength(2);
- }).pipe(Effect.provide(h.layer));
- },
- );
- }
+ it.effect.each([
+ {
+ firstPhase: "waiting_for_approval",
+ secondPhase: "waiting_for_input",
+ title: "2 agents need attention",
+ active: "true",
+ },
+ { firstPhase: "completed", secondPhase: "failed", title: "2 agents finished", active: "false" },
+ ] as const)(
+ "routes grouped $firstPhase and $secondPhase to the overview once across their queued jobs",
+ ({ firstPhase, secondPhase, title, active }) => {
+ const h = harness();
+ h.current.otherStates = [secondState];
+ return Effect.gen(function* () {
+ const delivery = yield* FcmDeliveries.FcmDeliveries;
+ yield* delivery.process(h.job);
+ h.current.state = { ...state, phase: firstPhase };
+ h.current.otherStates = [{ ...secondState, phase: secondPhase }];
+ yield* delivery.process({ ...h.job, state: h.current.state });
+ yield* delivery.process({ ...h.job, state: h.current.otherStates[0] });
+ yield* delivery.process({ ...h.job, state: h.current.state });
+ const alerts = h.sent.filter((message) => message.alert);
+ expect(alerts).toHaveLength(1);
+ expect(alerts[0]?.data).toMatchObject({
+ alert_title: title,
+ alert_body: "Fix notifications, Second thread",
+ alert_path: "/",
+ active,
+ });
+ expect(h.marked.at(-1)?.aggregate?.activities).toHaveLength(2);
+ }).pipe(Effect.provide(h.layer));
+ },
+ );
it.effect("filters disabled event types before counting a group", () => {
const h = harness();
@@ -294,13 +297,9 @@ describe("Android delivery routing", () => {
}).pipe(Effect.provide(h.layer));
});
- for (const phase of [
- "completed",
- "waiting_for_approval",
- "waiting_for_input",
- "failed",
- ] as const) {
- it.effect(`deleting one thread preserves another thread's ${phase} alert`, () => {
+ it.effect.each(["completed", "waiting_for_approval", "waiting_for_input", "failed"] as const)(
+ "deleting one thread preserves another thread's %s alert",
+ (phase) => {
const h = harness();
h.current.otherStates = [secondState];
return Effect.gen(function* () {
@@ -316,8 +315,8 @@ describe("Android delivery routing", () => {
yield* delivery.process({ ...h.job, state: h.current.state });
expect(h.sent.filter((message) => message.alert)).toHaveLength(1);
}).pipe(Effect.provide(h.layer));
- });
- }
+ },
+ );
it.effect("registration replay establishes a baseline without alerting", () => {
const h = harness();
@@ -333,8 +332,9 @@ describe("Android delivery routing", () => {
}).pipe(Effect.provide(h.layer));
});
- for (const restriction of ["mutedEnvironments", "revokedEnvironments"] as const) {
- it.effect(`excludes ${restriction} when forming cross-environment groups`, () => {
+ it.effect.each(["mutedEnvironments", "revokedEnvironments"] as const)(
+ "excludes %s when forming cross-environment groups",
+ (restriction) => {
const h = harness();
const other = { ...secondState, environmentId: EnvironmentId.make("other-env") };
h.current.target.last_aggregate_json = encodeJson(aggregateFor([state, other]));
@@ -349,8 +349,8 @@ describe("Android delivery routing", () => {
alert_body: "Approval: Project",
});
}).pipe(Effect.provide(h.layer));
- });
- }
+ },
+ );
it("gives a group a stable retry identity independent of row order", () => {
const other = {
@@ -409,13 +409,14 @@ describe("Android delivery routing", () => {
).toMatchObject({ alert_title: "Second thread", alert_body: "Input: Project" });
});
- for (const [phase, body, preference] of [
- ["waiting_for_approval", "Approval: Project", "notifyOnApproval"],
- ["waiting_for_input", "Input: Project", "notifyOnInput"],
- ["completed", "Done: Project", "notifyOnCompletion"],
- ["failed", "Failed: Project", "notifyOnFailure"],
- ] as const) {
- it.effect(`uses iOS alert wording for ${phase} and honors its preference`, () => {
+ it.effect.each([
+ { phase: "waiting_for_approval", body: "Approval: Project", preference: "notifyOnApproval" },
+ { phase: "waiting_for_input", body: "Input: Project", preference: "notifyOnInput" },
+ { phase: "completed", body: "Done: Project", preference: "notifyOnCompletion" },
+ { phase: "failed", body: "Failed: Project", preference: "notifyOnFailure" },
+ ] as const)(
+ "uses iOS alert wording for $phase and honors its preference",
+ ({ phase, body, preference }) => {
const h = harness();
h.current.state = { ...state, phase };
return Effect.gen(function* () {
@@ -433,8 +434,8 @@ describe("Android delivery routing", () => {
yield* delivery.process({ ...h.job, state: h.current.state });
expect(h.sent.slice(1).every((sent) => !sent.alert && !sent.data.alert_id)).toBe(true);
}).pipe(Effect.provide(h.layer));
- });
- }
+ },
+ );
it("trims and truncates alert text like iOS", () => {
expect(
@@ -572,23 +573,23 @@ describe("Android delivery routing", () => {
expect(h.sent[1]?.data.alert_id).toBeUndefined();
}).pipe(Effect.provide(h.layer));
});
- for (const ongoing of [true, false]) {
- for (const phase of ["completed", "failed"] as const) {
- it.effect(`does not alert a stale ${phase} without a baseline (ongoing=${ongoing})`, () => {
- const h = harness();
- h.current.state = { ...state, phase, updatedAt: "1969-12-31T23:57:00.000Z" };
- h.current.target.preferences_json = encodeJson({
- ...preferences,
- liveActivitiesEnabled: ongoing,
- });
- return Effect.gen(function* () {
- const delivery = yield* FcmDeliveries.FcmDeliveries;
- yield* delivery.process({ ...h.job, state: h.current.state });
- expect(h.sent.every((message) => !message.alert)).toBe(true);
- }).pipe(Effect.provide(h.layer));
- });
- }
- }
+ it.effect.each(
+ [true, false].flatMap((ongoing) =>
+ (["completed", "failed"] as const).map((phase) => ({ ongoing, phase })),
+ ),
+ )("does not alert a stale $phase without a baseline (ongoing=$ongoing)", ({ ongoing, phase }) => {
+ const h = harness();
+ h.current.state = { ...state, phase, updatedAt: "1969-12-31T23:57:00.000Z" };
+ h.current.target.preferences_json = encodeJson({
+ ...preferences,
+ liveActivitiesEnabled: ongoing,
+ });
+ return Effect.gen(function* () {
+ const delivery = yield* FcmDeliveries.FcmDeliveries;
+ yield* delivery.process({ ...h.job, state: h.current.state });
+ expect(h.sent.every((message) => !message.alert)).toBe(true);
+ }).pipe(Effect.provide(h.layer));
+ });
it.effect(
"retains finished results without extending expiry on replay and clears expired cards",
@@ -821,8 +822,9 @@ it("stops reducing five-character row fields and fits the remaining alert", () =
});
describe("FCM queue message isolation", () => {
- for (const failure of ["invalid-job", "fcm-rejection"] as const) {
- it.effect(`retries only the ${failure} message and delivers the rest of its batch`, () => {
+ it.effect.each(["invalid-job", "fcm-rejection"] as const)(
+ "retries only the %s message and delivers the rest of its batch",
+ (failure) => {
const h = harness();
const outcomes = new Map<string, "ack" | "retry">();
const message = (id: string, body: unknown): Cloudflare.Queues.Message<unknown> => ({
@@ -863,6 +865,6 @@ describe("FCM queue message isolation", () => {
expect(h.sent).toHaveLength(1);
expect(h.marked).toHaveLength(1);
}).pipe(Effect.provide(h.layer));
- });
- }
+ },
+ );
});
diff --git a/oxlint-plugin-t3code/index.ts b/oxlint-plugin-t3code/index.ts
index 075d16d5b39..f4669f588f6 100644
--- a/oxlint-plugin-t3code/index.ts
+++ b/oxlint-plugin-t3code/index.ts
@@ -7,6 +7,7 @@ import noInlineSchemaCompile from "./rules/no-inline-schema-compile.ts";
import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";
import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-escape-hatches.ts";
import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
+import noTestInLoop from "./rules/no-test-in-loop.ts";
export default definePlugin({
meta: {
@@ -20,5 +21,6 @@ export default definePlugin({
"no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
"no-mobile-uniwind-theme-escape-hatches": noMobileUniwindThemeEscapeHatches,
"no-native-title-tooltip": noNativeTitleTooltip,
+ "no-test-in-loop": noTestInLoop,
},
});
diff --git a/oxlint-plugin-t3code/rules/no-test-in-loop.test.ts b/oxlint-plugin-t3code/rules/no-test-in-loop.test.ts
new file mode 100644
index 00000000000..39efb80f895
--- /dev/null
+++ b/oxlint-plugin-t3code/rules/no-test-in-loop.test.ts
@@ -0,0 +1,114 @@
+import { assert, describe } from "@effect/vitest";
+
+import { createOxlintRuleHarness } from "../test/utils.ts";
+
+const rule = createOxlintRuleHarness("t3code/no-test-in-loop", {
+ filename: "fixture.test.ts",
+});
+
+describe("t3code/no-test-in-loop", () => {
+ rule.valid(
+ "allows it.each and it.effect.each",
+ `
+ import { it } from "@effect/vitest";
+ import * as Effect from "effect/Effect";
+
+ it.each([1, 2])("handles %s", (value) => {});
+ it.effect.each([1, 2])("handles %s", (value) => Effect.succeed(value));
+ `,
+ );
+
+ rule.valid(
+ "allows loops inside a test body",
+ `
+ import { it } from "@effect/vitest";
+
+ it("checks every value", () => {
+ for (const value of [1, 2]) {
+ if (value < 0) throw new Error("negative");
+ }
+ });
+ `,
+ );
+
+ rule.valid(
+ "ignores node:test files, which have no .each",
+ `
+ import { test } from "node:test";
+
+ for (const value of [1, 2]) {
+ test(\`handles \${value}\`, () => {});
+ }
+ `,
+ );
+
+ rule.invalid(
+ "reports it inside a for...of loop",
+ `
+ import { it } from "@effect/vitest";
+
+ for (const value of [1, 2]) {
+ it(\`handles \${value}\`, () => {});
+ }
+ `,
+ (output) => {
+ assert.match(output, /Use it\.each\(cases\)/);
+ },
+ );
+
+ rule.invalid(
+ "reports it.effect inside a for loop nested in describe",
+ `
+ import { describe, it } from "@effect/vitest";
+ import * as Effect from "effect/Effect";
+
+ describe("cases", () => {
+ for (let index = 0; index < 2; index++) {
+ it.effect(\`handles \${index}\`, () => Effect.void);
+ }
+ });
+ `,
+ (output) => {
+ assert.match(output, /Use it\.effect\.each\(cases\)/);
+ },
+ );
+
+ rule.invalid(
+ "reports test inside a for...in loop",
+ `
+ import { test } from "vitest";
+
+ for (const key in { a: 1 }) {
+ test(key, () => {});
+ }
+ `,
+ );
+
+ rule.invalid(
+ "reports a describe inside a loop once, not the tests inside it",
+ `
+ import { describe, it } from "vitest";
+
+ for (const bundle of ["a.js", "b.js"]) {
+ describe(bundle, () => {
+ it("first", () => {});
+ it("second", () => {});
+ });
+ }
+ `,
+ (output) => {
+ assert.match(output, /Use describe\.each\(cases\)/);
+ assert.equal(output.match(/no-test-in-loop/g)?.length, 1);
+ },
+ );
+});
+
+const productionRule = createOxlintRuleHarness("t3code/no-test-in-loop");
+
+productionRule.valid(
+ "ignores non-test files",
+ `
+ const it = (_name: string) => {};
+ for (const value of ["a"]) it(value);
+ `,
+);
diff --git a/oxlint-plugin-t3code/rules/no-test-in-loop.ts b/oxlint-plugin-t3code/rules/no-test-in-loop.ts
new file mode 100644
index 00000000000..b963fdee62d
--- /dev/null
+++ b/oxlint-plugin-t3code/rules/no-test-in-loop.ts
@@ -0,0 +1,79 @@
+import { defineRule, type ESTree } from "@oxlint/plugins";
+import * as Option from "effect/Option";
+
+import { getPropertyName, unwrapExpression } from "../utils.ts";
+
+const TEST_FILE_PATTERN = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
+// node:test has no `.each`, so files written against it keep their loops.
+const NODE_TEST_IMPORT_PATTERN = /["']node:test["']/u;
+// Calls that declare a test or a group of tests; all of them expose `.each`.
+const TEST_FUNCTIONS = new Set(["describe", "it", "suite", "test"]);
+// Modifiers whose tester also exposes `.each` (@effect/vitest's `it.effect` and `it.live`).
+const EACH_CAPABLE_MODIFIERS = new Set(["effect", "live"]);
+const LOOPS = new Set(["ForStatement", "ForInStatement", "ForOfStatement"]);
+const FUNCTIONS = new Set(["ArrowFunctionExpression", "FunctionExpression", "FunctionDeclaration"]);
+
+/** Returns the reported name for `it(…)`, `describe(…)`, `it.effect(…)`, and friends. */
+const testCallName = (callee: unknown): Option.Option<string> => {
+ const expression = unwrapExpression(callee);
+ if (Option.isNone(expression)) return Option.none();
+
+ if (expression.value.type === "Identifier") {
+ return TEST_FUNCTIONS.has(expression.value.name)
+ ? Option.some(expression.value.name)
+ : Option.none();
+ }
+
+ if (expression.value.type !== "MemberExpression") return Option.none();
+ const object = unwrapExpression(expression.value.object);
+ const property = getPropertyName(expression.value.property);
+ if (Option.isNone(object) || Option.isNone(property)) return Option.none();
+ if (!EACH_CAPABLE_MODIFIERS.has(property.value)) return Option.none();
+ if (object.value.type !== "Identifier" || !TEST_FUNCTIONS.has(object.value.name)) {
+ return Option.none();
+ }
+ return Option.some(`${object.value.name}.${property.value}`);
+};
+
+/**
+ * Reports a test declaration that runs once per loop iteration. A loop around a
+ * `describe` is reported on the `describe`, so the tests inside it stay quiet.
+ */
+const isInsideLoop = (node: ESTree.Node): boolean => {
+ let current = node.parent;
+ while (current) {
+ if (LOOPS.has(current.type)) return true;
+ // Anything inside a function (a describe body, a helper, a test body) runs
+ // once per call of that function, not once per iteration.
+ if (FUNCTIONS.has(current.type)) return false;
+ current = current.parent;
+ }
+ return false;
+};
+
+export default defineRule({
+ meta: {
+ type: "suggestion",
+ docs: {
+ description:
+ "Disallow declaring tests inside a for loop; use it.each / it.effect.each / describe.each instead.",
+ },
+ },
+ create(context) {
+ if (!TEST_FILE_PATTERN.test(context.filename)) return {};
+ if (NODE_TEST_IMPORT_PATTERN.test(context.sourceCode.text)) return {};
+
+ return {
+ CallExpression(node) {
+ const name = testCallName(node.callee);
+ if (Option.isNone(name)) return;
+ if (!isInsideLoop(node)) return;
+
+ context.report({
+ node: node.callee,
+ message: `Do not call ${name.value}(…) inside a for loop. Use ${name.value}.each(cases)(name, …) instead.`,
+ });
+ },
+ };
+ },
+});
diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts
index 0a5b72b3023..7f42a631cab 100644
--- a/packages/client-runtime/src/connection/resolver.test.ts
+++ b/packages/client-runtime/src/connection/resolver.test.ts
@@ -444,8 +444,9 @@ describe("ConnectionResolver", () => {
}),
);
- for (const scenario of ["unchanged", "changed", "revocation-failed"] as const) {
- it.effect(`handles ${scenario} SSH routing consent before saving or authorizing`, () =>
+ it.effect.each(["unchanged", "changed", "revocation-failed"] as const)(
+ "handles %s SSH routing consent before saving or authorizing",
+ (scenario) =>
Effect.gen(function* () {
const calls: string[] = [];
const target = new SshConnectionTarget({
@@ -537,8 +538,7 @@ describe("ConnectionResolver", () => {
}
expect(yield* permissions.get(entry)).toBe(scenario === "changed" ? "off" : "read-write");
}),
- );
- }
+ );
it.effect("preserves relay authorization failure classification and trace details", () =>
Effect.gen(function* () {
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index a7d7d960efe..a9833f7499d 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -502,83 +502,81 @@ describe("V2 environment commands", () => {
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
- for (const status of [
+ it.effect.each([
"waiting",
"completed",
"failed",
"interrupted",
"cancelled",
"rolled_back",
- ] as const) {
- it.effect(`dispatches Stop for ${status} runs with background commands except rollback`, () =>
- Effect.gen(function* () {
- const waitingRunId = RunId.make("run-waiting");
- const projection: OrchestrationV2ThreadProjection = {
- ...v2Projection,
- runs: [
- {
- id: waitingRunId,
- threadId: v2ThreadId,
- ordinal: 1,
- providerInstanceId: v2Projection.thread.providerInstanceId,
- modelSelection: v2Projection.thread.modelSelection,
- providerThreadId: null,
- userMessageId: MessageId.make("message-waiting"),
- rootNodeId: null,
- activeAttemptId: null,
- status,
- requestedAt: v2Now,
- startedAt: v2Now,
- completedAt: null,
- checkpointId: null,
- contextHandoffId: null,
- },
- ],
- turnItems: [
- {
- id: TurnItemId.make("background-command"),
- threadId: v2ThreadId,
- runId: waitingRunId,
- nodeId: null,
- providerThreadId: null,
- providerTurnId: null,
- nativeItemRef: null,
- parentItemId: null,
- ordinal: 1,
- status: "running",
- title: null,
- startedAt: v2Now,
- completedAt: null,
- updatedAt: v2Now,
- type: "command_execution",
- input: "vp run dev",
- },
- ],
- };
- const commands: OrchestrationV2Command[] = [];
- const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
+ ] as const)("dispatches Stop for %s runs with background commands except rollback", (status) =>
+ Effect.gen(function* () {
+ const waitingRunId = RunId.make("run-waiting");
+ const projection: OrchestrationV2ThreadProjection = {
+ ...v2Projection,
+ runs: [
+ {
+ id: waitingRunId,
+ threadId: v2ThreadId,
+ ordinal: 1,
+ providerInstanceId: v2Projection.thread.providerInstanceId,
+ modelSelection: v2Projection.thread.modelSelection,
+ providerThreadId: null,
+ userMessageId: MessageId.make("message-waiting"),
+ rootNodeId: null,
+ activeAttemptId: null,
+ status,
+ requestedAt: v2Now,
+ startedAt: v2Now,
+ completedAt: null,
+ checkpointId: null,
+ contextHandoffId: null,
+ },
+ ],
+ turnItems: [
+ {
+ id: TurnItemId.make("background-command"),
+ threadId: v2ThreadId,
+ runId: waitingRunId,
+ nodeId: null,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 1,
+ status: "running",
+ title: null,
+ startedAt: v2Now,
+ completedAt: null,
+ updatedAt: v2Now,
+ type: "command_execution",
+ input: "vp run dev",
+ },
+ ],
+ };
+ const commands: OrchestrationV2Command[] = [];
+ const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
- const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
- );
+ const result = yield* interruptThreadTurn({ threadId: v2ThreadId }).pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ );
- expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
- expect(commands).toEqual(
- status === "rolled_back"
- ? []
- : [
- {
- type: "run.interrupt",
- commandId: expect.any(String),
- threadId: v2ThreadId,
- runId: waitingRunId,
- holdQueue: true,
- },
- ],
- );
- }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
- );
- }
+ expect(result).toEqual({ sequence: status === "rolled_back" ? 0 : 1 });
+ expect(commands).toEqual(
+ status === "rolled_back"
+ ? []
+ : [
+ {
+ type: "run.interrupt",
+ commandId: expect.any(String),
+ threadId: v2ThreadId,
+ runId: waitingRunId,
+ holdQueue: true,
+ },
+ ],
+ );
+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
+ );
it.effect(
"dispatches V2-native relationship and queue commands without compatibility shaping",
diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts
index d2baa592747..246e4f58518 100644
--- a/packages/client-runtime/src/rpc/session.test.ts
+++ b/packages/client-runtime/src/rpc/session.test.ts
@@ -429,59 +429,55 @@ describe("RpcSessionFactory", () => {
),
);
- for (const options of [
+ it.effect.each([
{ environmentThemes: true },
{ usageLimitSources: true },
{ environmentThemes: true, usageLimitSources: true },
- ]) {
- it.effect(
- `shares only a config subscription with the same opt-ins: ${JSON.stringify(options)}`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const { factory, sockets } = yield* makeFactory(options);
- const session = yield* factory.connect(PREPARED);
- const readyFiber = yield* Effect.forkChild(session.ready);
- const socket = yield* awaitSocket(sockets);
- socket.open();
- yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, options);
- yield* Fiber.join(readyFiber);
-
- const shared = yield* session.subscribeServerConfig(options).pipe(Stream.runHead);
- expect(shared).toMatchObject({ _tag: "Some", value: { type: "snapshot" } });
- expect(
- socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest),
- ).toHaveLength(1);
-
- const fallbackFiber = yield* session
- .subscribeServerConfig({})
- .pipe(Stream.runHead, Effect.forkChild);
- const fallbackRequest = yield* awaitRequest(socket, 1);
- expect(fallbackRequest).toMatchObject({
- tag: WS_METHODS.subscribeServerConfig,
- payload: {},
- });
- socket.serverMessage(
- encodeJson({
- _tag: "Chunk",
- requestId: fallbackRequest.id,
- values: [
- {
- version: 1,
- type: "snapshot",
- config: ENCODED_THEME_SERVER_CONFIG,
- },
- ],
- }),
- );
- expect(yield* Fiber.join(fallbackFiber)).toMatchObject({
- _tag: "Some",
- value: { type: "snapshot" },
- });
+ ])("shares only a config subscription with the same opt-ins: %j", (options) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { factory, sockets } = yield* makeFactory(options);
+ const session = yield* factory.connect(PREPARED);
+ const readyFiber = yield* Effect.forkChild(session.ready);
+ const socket = yield* awaitSocket(sockets);
+ socket.open();
+ yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, options);
+ yield* Fiber.join(readyFiber);
+
+ const shared = yield* session.subscribeServerConfig(options).pipe(Stream.runHead);
+ expect(shared).toMatchObject({ _tag: "Some", value: { type: "snapshot" } });
+ expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
+ 1,
+ );
+
+ const fallbackFiber = yield* session
+ .subscribeServerConfig({})
+ .pipe(Stream.runHead, Effect.forkChild);
+ const fallbackRequest = yield* awaitRequest(socket, 1);
+ expect(fallbackRequest).toMatchObject({
+ tag: WS_METHODS.subscribeServerConfig,
+ payload: {},
+ });
+ socket.serverMessage(
+ encodeJson({
+ _tag: "Chunk",
+ requestId: fallbackRequest.id,
+ values: [
+ {
+ version: 1,
+ type: "snapshot",
+ config: ENCODED_THEME_SERVER_CONFIG,
+ },
+ ],
}),
- ),
- );
- }
+ );
+ expect(yield* Fiber.join(fallbackFiber)).toMatchObject({
+ _tag: "Some",
+ value: { type: "snapshot" },
+ });
+ }),
+ ),
+ );
it.effect.each([
{ usageLimitSources: true },
@@ -1191,37 +1187,38 @@ describe("RpcSessionFactory", () => {
),
);
- for (const relay of [false, true]) {
- it.effect(`fails readiness when the ${relay ? "relay" : "direct"} websocket never opens`, () =>
- Effect.gen(function* () {
- const { factory, sockets } = yield* makeFactory();
+ it.effect.each([
+ { relay: false, label: "direct" },
+ { relay: true, label: "relay" },
+ ])("fails readiness when the $label websocket never opens", ({ relay }) =>
+ Effect.gen(function* () {
+ const { factory, sockets } = yield* makeFactory();
- const error = yield* Effect.scoped(
- Effect.gen(function* () {
- const session = yield* factory.connect({
- ...PREPARED,
- target: relay
- ? new RelayConnectionTarget({
- environmentId: TARGET.environmentId,
- label: TARGET.label,
- })
- : TARGET,
- });
- const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready));
- yield* awaitSocket(sockets);
-
- yield* TestClock.adjust("15 seconds");
- return yield* Fiber.join(readyFiber);
- }),
- );
+ const error = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const session = yield* factory.connect({
+ ...PREPARED,
+ target: relay
+ ? new RelayConnectionTarget({
+ environmentId: TARGET.environmentId,
+ label: TARGET.label,
+ })
+ : TARGET,
+ });
+ const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready));
+ yield* awaitSocket(sockets);
- expect(error).toBeInstanceOf(ConnectionTransientError);
- expect(error).toMatchObject({
- reason: "transport",
- message: `Test environment could not establish a WebSocket connection.${relay ? ` ${NETWORK_BLOCKING_HINT}` : ""}`,
- });
- expect(sockets[0]?.readyState).toBe(TestWebSocket.CLOSED);
- }).pipe(Effect.provide(TestClock.layer())),
- );
- }
+ yield* TestClock.adjust("15 seconds");
+ return yield* Fiber.join(readyFiber);
+ }),
+ );
+
+ expect(error).toBeInstanceOf(ConnectionTransientError);
+ expect(error).toMatchObject({
+ reason: "transport",
+ message: `Test environment could not establish a WebSocket connection.${relay ? ` ${NETWORK_BLOCKING_HINT}` : ""}`,
+ });
+ expect(sockets[0]?.readyState).toBe(TestWebSocket.CLOSED);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
});
diff --git a/packages/client-runtime/src/state/assets.test.ts b/packages/client-runtime/src/state/assets.test.ts
index 95c7622c8c1..d1407fe7959 100644
--- a/packages/client-runtime/src/state/assets.test.ts
+++ b/packages/client-runtime/src/state/assets.test.ts
@@ -60,7 +60,7 @@ describe("asset collection keys", () => {
});
describe("createAssetEnvironmentAtoms", () => {
- for (const scenario of [
+ it.effect.each([
{ name: "missing video", path: "/tmp/clip.mp4", fallback: true },
{ name: "literal filename characters", path: "/tmp/frame#one?two.png", fallback: true },
{ name: "windows path", path: "C:\\Users\\demo\\clip.mp4", fallback: true },
@@ -73,113 +73,111 @@ describe("createAssetEnvironmentAtoms", () => {
{ name: "same environment", path: "/tmp/clip.mp4", primary: "same" },
{ name: "non-media", path: "/tmp/report.html" },
{ name: "authorization failure", path: "/tmp/clip.mp4", error: "auth" },
- ]) {
- it.effect(`uses the correct environment for ${scenario.name}`, () =>
- Effect.gen(function* () {
- const remoteId = EnvironmentId.make("remote");
- const localId = EnvironmentId.make("local");
- const resource = {
- _tag: "media-file" as const,
- threadId: ThreadId.make("foreign-thread"),
- path: scenario.path,
- };
- const error =
- scenario.error === "auth"
- ? new EnvironmentAuthorizationError({
- message: "denied",
- requiredScope: "orchestration:read",
- })
- : scenario.error === "inspection"
- ? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
- : scenario.error === "context"
- ? new AssetWorkspaceContextNotFoundError({ resource })
- : new AssetWorkspaceAssetNotFoundError({ resource });
- const calls: EnvironmentId[] = [];
- const supervisors = new Map<
- EnvironmentId,
- EnvironmentSupervisor.EnvironmentSupervisor["Service"]
- >();
- for (const environmentId of [remoteId, localId]) {
- const client = {
- [WS_METHODS.assetsCreateUrl]: () => {
- calls.push(environmentId);
- return environmentId === remoteId && !scenario.success
- ? Effect.fail(error)
- : Effect.succeed({
- relativeUrl: `/api/assets/${environmentId}/media`,
- expiresAt: 999999,
- });
- },
- } as unknown as WsRpcProtocolClient;
- const session = { client } as RpcSession;
- supervisors.set(
- environmentId,
- EnvironmentSupervisor.EnvironmentSupervisor.of({
- target: new PrimaryConnectionTarget({
- environmentId,
- label: environmentId,
- httpBaseUrl: `https://${environmentId}.test`,
- wsBaseUrl: `wss://${environmentId}.test`,
- }),
- state: yield* SubscriptionRef.make<SupervisorConnectionState>({
- ...AVAILABLE_CONNECTION_STATE,
- phase: "connected" as const,
- }),
- session: yield* SubscriptionRef.make(Option.some(session)),
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
- connect: Effect.void,
- disconnect: Effect.void,
- retryNow: Effect.void,
+ ])("uses the correct environment for $name", (scenario) =>
+ Effect.gen(function* () {
+ const remoteId = EnvironmentId.make("remote");
+ const localId = EnvironmentId.make("local");
+ const resource = {
+ _tag: "media-file" as const,
+ threadId: ThreadId.make("foreign-thread"),
+ path: scenario.path,
+ };
+ const error =
+ scenario.error === "auth"
+ ? new EnvironmentAuthorizationError({
+ message: "denied",
+ requiredScope: "orchestration:read",
+ })
+ : scenario.error === "inspection"
+ ? new AssetWorkspaceAssetInspectionError({ resource, cause: new Error("unreadable") })
+ : scenario.error === "context"
+ ? new AssetWorkspaceContextNotFoundError({ resource })
+ : new AssetWorkspaceAssetNotFoundError({ resource });
+ const calls: EnvironmentId[] = [];
+ const supervisors = new Map<
+ EnvironmentId,
+ EnvironmentSupervisor.EnvironmentSupervisor["Service"]
+ >();
+ for (const environmentId of [remoteId, localId]) {
+ const client = {
+ [WS_METHODS.assetsCreateUrl]: () => {
+ calls.push(environmentId);
+ return environmentId === remoteId && !scenario.success
+ ? Effect.fail(error)
+ : Effect.succeed({
+ relativeUrl: `/api/assets/${environmentId}/media`,
+ expiresAt: 999999,
+ });
+ },
+ } as unknown as WsRpcProtocolClient;
+ const session = { client } as RpcSession;
+ supervisors.set(
+ environmentId,
+ EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target: new PrimaryConnectionTarget({
+ environmentId,
+ label: environmentId,
+ httpBaseUrl: `https://${environmentId}.test`,
+ wsBaseUrl: `wss://${environmentId}.test`,
+ }),
+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({
+ ...AVAILABLE_CONNECTION_STATE,
+ phase: "connected" as const,
}),
- );
- }
- const environments = EnvironmentRegistry.EnvironmentRegistry.of({
- run: (id, effect) =>
- Effect.provideService(
- effect,
- EnvironmentSupervisor.EnvironmentSupervisor,
- supervisors.get(id)!,
- ),
- followStream: (id, stream) =>
- Stream.provideService(
- stream,
- EnvironmentSupervisor.EnvironmentSupervisor,
- supervisors.get(id)!,
- ),
- } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
- const registry = AtomRegistry.make();
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
- const localTarget = {
- environmentId: scenario.primary === "same" ? remoteId : localId,
- httpBaseUrl: "https://local.test",
- };
- const localEnvironment = Atom.make<typeof localTarget | null>(
- scenario.primary === "none" || scenario.primary === "reconnecting" ? null : localTarget,
+ session: yield* SubscriptionRef.make(Option.some(session)),
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ }),
);
- const assets = createAssetEnvironmentAtoms(
- Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments)),
- localEnvironment,
+ }
+ const environments = EnvironmentRegistry.EnvironmentRegistry.of({
+ run: (id, effect) =>
+ Effect.provideService(
+ effect,
+ EnvironmentSupervisor.EnvironmentSupervisor,
+ supervisors.get(id)!,
+ ),
+ followStream: (id, stream) =>
+ Stream.provideService(
+ stream,
+ EnvironmentSupervisor.EnvironmentSupervisor,
+ supervisors.get(id)!,
+ ),
+ } as EnvironmentRegistry.EnvironmentRegistry["Service"]);
+ const registry = AtomRegistry.make();
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
+ const localTarget = {
+ environmentId: scenario.primary === "same" ? remoteId : localId,
+ httpBaseUrl: "https://local.test",
+ };
+ const localEnvironment = Atom.make<typeof localTarget | null>(
+ scenario.primary === "none" || scenario.primary === "reconnecting" ? null : localTarget,
+ );
+ const assets = createAssetEnvironmentAtoms(
+ Atom.runtime(Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environments)),
+ localEnvironment,
+ );
+ const query = assets.createUrl({ environmentId: remoteId, input: { resource } });
+ const result = AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
+ if (scenario.fallback || scenario.success) {
+ expect((yield* result).relativeUrl).toBe(
+ scenario.fallback
+ ? "https://local.test/api/assets/local/media"
+ : "/api/assets/remote/media",
);
- const query = assets.createUrl({ environmentId: remoteId, input: { resource } });
- const result = AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
- if (scenario.fallback || scenario.success) {
- expect((yield* result).relativeUrl).toBe(
- scenario.fallback
- ? "https://local.test/api/assets/local/media"
- : "/api/assets/remote/media",
- );
- } else {
- expect(yield* Effect.flip(result)).toEqual(error);
- }
- expect(calls).toEqual(scenario.fallback ? [remoteId, localId] : [remoteId]);
- if (scenario.primary === "reconnecting") {
- registry.set(localEnvironment, localTarget);
- expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
- expect(calls).toEqual([remoteId, remoteId, localId]);
- }
- }).pipe(Effect.scoped),
- );
- }
+ } else {
+ expect(yield* Effect.flip(result)).toEqual(error);
+ }
+ expect(calls).toEqual(scenario.fallback ? [remoteId, localId] : [remoteId]);
+ if (scenario.primary === "reconnecting") {
+ registry.set(localEnvironment, localTarget);
+ expect((yield* result).relativeUrl).toBe("https://local.test/api/assets/local/media");
+ expect(calls).toEqual([remoteId, remoteId, localId]);
+ }
+ }).pipe(Effect.scoped),
+ );
it("keys asset URL queries by environment and resource", () => {
const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
diff --git a/packages/client-runtime/src/state/pullRequests.test.ts b/packages/client-runtime/src/state/pullRequests.test.ts
index 86e4ad51196..c33623bbe1b 100644
--- a/packages/client-runtime/src/state/pullRequests.test.ts
+++ b/packages/client-runtime/src/state/pullRequests.test.ts
@@ -236,8 +236,9 @@ for (const scenario of [
);
}
-for (const provider of ["github", "gitlab", "bitbucket", "azure-devops"] as const) {
- it.effect(`routes ${provider} viewed marks to their storage environment`, () =>
+it.effect.each(["github", "gitlab", "bitbucket", "azure-devops"] as const)(
+ "routes %s viewed marks to their storage environment",
+ (provider) =>
Effect.scoped(
Effect.gen(function* () {
const reference = {
@@ -311,8 +312,7 @@ for (const provider of ["github", "gitlab", "bitbucket", "azure-devops"] as cons
}
}),
),
- );
-}
+);
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -420,8 +420,9 @@ const makeTestRuntime = Effect.fn("makeTestRuntime")(function* (
return { runtime, atoms, registry, environmentRegistry, supervisor };
});
-for (const permission of ["default", "origin-off", "destination-off", "read-only"] as const) {
- it.effect(`does not probe another environment with ${permission} routing permission`, () =>
+it.effect.each(["default", "origin-off", "destination-off", "read-only"] as const)(
+ "does not probe another environment with %s routing permission",
+ (permission) =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
@@ -480,125 +481,128 @@ for (const permission of ["default", "origin-off", "destination-off", "read-only
);
}),
),
- );
-}
+);
-for (const side of ["origin", "destination"] as const) {
- for (const stored of ["matching", "changed", "missing", "unavailable", "failed"] as const) {
- it.effect(`checks the current ${side} SSH profile before routing with ${stored} storage`, () =>
- Effect.scoped(
- Effect.gen(function* () {
- const calls: string[] = [];
- const identity = {
- host: "github.com",
- provider: "github",
- viewer: "maria",
- accountId: "123",
- };
- const client = {
- [WS_METHODS.pullRequestsRouting]: () =>
- Effect.sync(() => {
- calls.push("source-probe");
- return identity;
- }),
- [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
- Effect.gen(function* () {
- if (input.expectedAccountId !== undefined) {
- return yield* new PullRequestOperationError({
- operation: "routeIdentity",
- detail: "Source guard refused.",
- });
- }
- calls.push("source-write");
- }),
- [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
- } as unknown as WsRpcProtocolClient;
- const alternate = {
- [WS_METHODS.pullRequestsRoutingIdentity]: () =>
- Effect.sync(() => {
- calls.push("alternate-probe");
- return identity;
- }),
- [WS_METHODS.pullRequestsRunAction]: () =>
- Effect.sync(() => {
- calls.push("alternate-write");
- }),
- [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
- } as unknown as WsRpcProtocolClient;
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
- const environmentId =
- side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
- const profile = new SshConnectionProfile({
- connectionId: "ssh-1",
+it.effect.each(
+ (["origin", "destination"] as const).flatMap((side) =>
+ (["matching", "changed", "missing", "unavailable", "failed"] as const).map((stored) => ({
+ side,
+ stored,
+ })),
+ ),
+)("checks the current $side SSH profile before routing with $stored storage", ({ side, stored }) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const calls: string[] = [];
+ const identity = {
+ host: "github.com",
+ provider: "github",
+ viewer: "maria",
+ accountId: "123",
+ };
+ const client = {
+ [WS_METHODS.pullRequestsRouting]: () =>
+ Effect.sync(() => {
+ calls.push("source-probe");
+ return identity;
+ }),
+ [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
+ Effect.gen(function* () {
+ if (input.expectedAccountId !== undefined) {
+ return yield* new PullRequestOperationError({
+ operation: "routeIdentity",
+ detail: "Source guard refused.",
+ });
+ }
+ calls.push("source-write");
+ }),
+ [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
+ } as unknown as WsRpcProtocolClient;
+ const alternate = {
+ [WS_METHODS.pullRequestsRoutingIdentity]: () =>
+ Effect.sync(() => {
+ calls.push("alternate-probe");
+ return identity;
+ }),
+ [WS_METHODS.pullRequestsRunAction]: () =>
+ Effect.sync(() => {
+ calls.push("alternate-write");
+ }),
+ [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
+ } as unknown as WsRpcProtocolClient;
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
+ const environmentId =
+ side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
+ const profile = new SshConnectionProfile({
+ connectionId: "ssh-1",
+ environmentId,
+ label: "SSH",
+ target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
+ });
+ yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
+ new Map(entries).set(environmentId, {
+ target: new SshConnectionTarget({
environmentId,
+ connectionId: profile.connectionId,
label: "SSH",
- target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
- });
- yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
- new Map(entries).set(environmentId, {
- target: new SshConnectionTarget({
- environmentId,
- connectionId: profile.connectionId,
- label: "SSH",
+ }),
+ profile: Option.some(profile),
+ enabled: true,
+ }),
+ );
+ const read = Effect.suspend(() =>
+ stored === "failed"
+ ? Effect.fail(
+ new ConnectionTransientError({
+ reason: "remote-unavailable",
+ detail: "Profile storage unavailable.",
}),
- profile: Option.some(profile),
- enabled: true,
+ )
+ : Effect.succeed(
+ stored === "missing"
+ ? Option.none()
+ : Option.some(
+ stored === "changed"
+ ? new SshConnectionProfile({
+ ...profile,
+ target: { ...profile.target, hostname: "replacement.example.test" },
+ })
+ : profile,
+ ),
+ ),
+ );
+ const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
+ projectId: ProjectId.make("project-1"),
+ repository: "private/repo",
+ number: 7,
+ action: "merge",
+ }).pipe(
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ // This also represents a user enabling the stale catalog entry after re-resolution.
+ Effect.provideService(GitHubRoutingPermissions, trustedRouting),
+ );
+ yield* stored === "unavailable"
+ ? route
+ : route.pipe(
+ Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, {
+ get: () => read,
+ put: () => Effect.die("unused"),
+ remove: () => Effect.die("unused"),
}),
);
- const read = Effect.suspend(() =>
- stored === "failed"
- ? Effect.fail(
- new ConnectionTransientError({
- reason: "remote-unavailable",
- detail: "Profile storage unavailable.",
- }),
- )
- : Effect.succeed(
- stored === "missing"
- ? Option.none()
- : Option.some(
- stored === "changed"
- ? new SshConnectionProfile({
- ...profile,
- target: { ...profile.target, hostname: "replacement.example.test" },
- })
- : profile,
- ),
- ),
- );
- const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
- projectId: ProjectId.make("project-1"),
- repository: "private/repo",
- number: 7,
- action: "merge",
- }).pipe(
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
- // This also represents a user enabling the stale catalog entry after re-resolution.
- Effect.provideService(GitHubRoutingPermissions, trustedRouting),
- );
- yield* stored === "unavailable"
- ? route
- : route.pipe(
- Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, {
- get: () => read,
- put: () => Effect.die("unused"),
- remove: () => Effect.die("unused"),
- }),
- );
- expect(calls).toEqual(
- stored === "matching"
- ? ["source-probe", "alternate-probe", "alternate-write"]
- : ["source-write"],
- );
- }),
- ),
- );
- }
-}
+ expect(calls).toEqual(
+ stored === "matching"
+ ? ["source-probe", "alternate-probe", "alternate-write"]
+ : ["source-write"],
+ );
+ }),
+ ),
+);
-for (const probe of ["origin", "alternate"] as const) {
- it.live(`bounds a stalled ${probe} metadata probe without repeating a strict source read`, () =>
+it.live.each(["origin", "alternate"] as const)(
+ "bounds a stalled %s metadata probe without repeating a strict source read",
+ (probe) =>
Effect.scoped(
Effect.gen(function* () {
let sourceReads = 0;
@@ -638,81 +642,81 @@ for (const probe of ["origin", "alternate"] as const) {
expect(sourceReads).toBe(1);
}),
),
- );
-}
+);
-for (const source of ["pending", "pending-local", "failed-local", "failed", "offline"] as const) {
- it.effect(
- source === "offline"
- ? "returns held source data only after both fresh paths fail"
- : `uses one shared reader with a ${source} source`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const started = yield* Deferred.make<void>();
- const calls: string[] = [];
- const clientFor = (local: boolean) =>
- ({
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]:
- () =>
- Effect.succeed({
- host: "github.com",
- provider: "github",
- viewer: "maria-rcks",
- accountId: "123",
- }),
- [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
- Effect.gen(function* () {
- calls.push(local ? "local" : input.allowStale === false ? "origin" : "held");
- if (source === "offline" && !local && input.allowStale === undefined) {
- return { state: "open" };
- }
- expect(input.allowStale).toBe(false);
- if (local && source !== "offline") return null;
- if (source !== "pending" && source !== "pending-local")
- return yield* new PullRequestOperationError({
- operation: "summary",
- detail: "github unreachable",
- });
- yield* Deferred.succeed(started, undefined);
- return yield* Effect.never;
- }),
- }) as unknown as WsRpcProtocolClient;
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
- clientFor(false),
- clientFor(true),
- source === "failed-local" || source === "pending-local",
- );
- const request = createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
- projectId: ProjectId.make("project-1"),
- repository: "acme/web",
- number: 7,
- }).pipe(
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
- Effect.provideService(GitHubRoutingPermissions, trustedRouting),
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
- );
- const fiber = yield* request.pipe(Effect.forkChild);
- if (source === "pending-local") {
- yield* Deferred.await(started);
- yield* TestClock.adjust("30 seconds");
- }
- const result = yield* Fiber.join(fiber);
- if (source === "offline") {
- expect(result).toEqual({ state: "open" });
- expect(calls).toEqual(["local", "origin", "held"]);
- } else {
- expect(result).toBeNull();
- expect(calls).toEqual(
- source === "failed-local" || source === "pending-local"
- ? ["origin", "local"]
- : ["local"],
- );
- }
- }),
- ),
- );
-}
+it.effect.each(
+ (["pending", "pending-local", "failed-local", "failed", "offline"] as const).map(
+ (source) =>
+ [
+ source === "offline"
+ ? "returns held source data only after both fresh paths fail"
+ : `uses one shared reader with a ${source} source`,
+ source,
+ ] as const,
+ ),
+)("%s", ([, source]) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const started = yield* Deferred.make<void>();
+ const calls: string[] = [];
+ const clientFor = (local: boolean) =>
+ ({
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
+ Effect.succeed({
+ host: "github.com",
+ provider: "github",
+ viewer: "maria-rcks",
+ accountId: "123",
+ }),
+ [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
+ Effect.gen(function* () {
+ calls.push(local ? "local" : input.allowStale === false ? "origin" : "held");
+ if (source === "offline" && !local && input.allowStale === undefined) {
+ return { state: "open" };
+ }
+ expect(input.allowStale).toBe(false);
+ if (local && source !== "offline") return null;
+ if (source !== "pending" && source !== "pending-local")
+ return yield* new PullRequestOperationError({
+ operation: "summary",
+ detail: "github unreachable",
+ });
+ yield* Deferred.succeed(started, undefined);
+ return yield* Effect.never;
+ }),
+ }) as unknown as WsRpcProtocolClient;
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
+ clientFor(false),
+ clientFor(true),
+ source === "failed-local" || source === "pending-local",
+ );
+ const request = createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
+ projectId: ProjectId.make("project-1"),
+ repository: "acme/web",
+ number: 7,
+ }).pipe(
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
+ Effect.provideService(GitHubRoutingPermissions, trustedRouting),
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ );
+ const fiber = yield* request.pipe(Effect.forkChild);
+ if (source === "pending-local") {
+ yield* Deferred.await(started);
+ yield* TestClock.adjust("30 seconds");
+ }
+ const result = yield* Fiber.join(fiber);
+ if (source === "offline") {
+ expect(result).toEqual({ state: "open" });
+ expect(calls).toEqual(["local", "origin", "held"]);
+ } else {
+ expect(result).toBeNull();
+ expect(calls).toEqual(
+ source === "failed-local" || source === "pending-local" ? ["origin", "local"] : ["local"],
+ );
+ }
+ }),
+ ),
+);
it.live("keeps source workspace metadata when an alternate answers a detail read", () =>
Effect.scoped(
@@ -1191,8 +1195,9 @@ it.effect("refreshes checks without refreshing full detail", () =>
),
);
-for (const oldAlternate of [false, true]) {
- it.effect(`routes checks through one reader with old alternate: ${oldAlternate}`, () =>
+it.effect.each([false, true])(
+ "routes checks through one reader with old alternate: %s",
+ (oldAlternate) =>
Effect.scoped(
Effect.gen(function* () {
const calls: string[] = [];
@@ -1236,8 +1241,7 @@ for (const oldAlternate of [false, true]) {
expect(calls).toEqual(oldAlternate ? ["origin"] : ["local"]);
}),
),
- );
-}
+);
it.effect("keeps live detail reads separate from reads that allow stale data", () =>
Effect.scoped(
diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts
index 14ff5efbeab..c0c45a1e2e3 100644
--- a/packages/client-runtime/src/state/threadCommands.test.ts
+++ b/packages/client-runtime/src/state/threadCommands.test.ts
@@ -137,8 +137,9 @@ describe("remote thread lifecycle commands", () => {
["reorderActive", { orderKey: "b" }, { activeOrderKey: "b" }],
] as const;
- for (const [action, input, expected] of actions) {
- it.effect(`shows ${action} before a delayed remote reply and rolls back a rejection`, () =>
+ it.effect.each(actions)(
+ "shows %s before a delayed remote reply and rolls back a rejection",
+ ([action, input, expected]) =>
Effect.gen(function* () {
const h = yield* makeHarness();
const source = h.snapshotAtom(ENVIRONMENT_ID);
@@ -179,8 +180,7 @@ describe("remote thread lifecycle commands", () => {
expect((yield* Effect.promise(() => result))._tag).toBe("Failure");
expect(h.registry.get(h.visibleAtom)).toBe(initial);
}),
- );
- }
+ );
it.effect("keeps the preview after acknowledgement until the matching shell update arrives", () =>
Effect.gen(function* () {
@@ -290,44 +290,45 @@ describe("remote thread lifecycle commands", () => {
}),
);
- for (const action of ["settle", "snooze"] as const) {
- it.effect(`restores a confirmed ${action} when a queued undo fails`, () =>
- Effect.gen(function* () {
- const h = yield* makeHarness();
- const parked =
- action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
- const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
- const result = h.commands[action].run(h.registry, {
- environmentId: ENVIRONMENT_ID,
- input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
- });
- const first = yield* Queue.take(h.requests);
- const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
- environmentId: ENVIRONMENT_ID,
- input: { threadId: THREAD_ID, reason: "user" },
- });
- expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
- yield* Deferred.succeed(first.reply, { sequence: 2 });
- expect((yield* Effect.promise(() => result))._tag).toBe("Success");
- expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
- const confirmed = {
- ...SNAPSHOT,
- snapshotSequence: 2,
- threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
- };
- h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
- expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
- const second = yield* Queue.take(h.requests);
- expect(second.command.type).toBe(
- action === "settle" ? "thread.unsettle" : "thread.unsnooze",
- );
- yield* Deferred.fail(second.reply, new Error("Undo rejected"));
- expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
- expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
- }),
- );
+ const undoableActions = ["settle", "snooze"] as const;
- it.effect(`preserves a newer approval when the ${action} reply arrives after the shell`, () =>
+ it.effect.each(undoableActions)("restores a confirmed %s when a queued undo fails", (action) =>
+ Effect.gen(function* () {
+ const h = yield* makeHarness();
+ const parked =
+ action === "settle" ? { settledOverride: "settled" as const } : { snoozedUntil: FUTURE };
+ const awake = action === "settle" ? { settledOverride: "active" } : { snoozedUntil: null };
+ const result = h.commands[action].run(h.registry, {
+ environmentId: ENVIRONMENT_ID,
+ input: { threadId: THREAD_ID, snoozedUntil: "2099-01-01T00:00:00.000Z" },
+ });
+ const first = yield* Queue.take(h.requests);
+ const undo = h.commands[action === "settle" ? "unsettle" : "unsnooze"].run(h.registry, {
+ environmentId: ENVIRONMENT_ID,
+ input: { threadId: THREAD_ID, reason: "user" },
+ });
+ expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
+ yield* Deferred.succeed(first.reply, { sequence: 2 });
+ expect((yield* Effect.promise(() => result))._tag).toBe("Success");
+ expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
+ const confirmed = {
+ ...SNAPSHOT,
+ snapshotSequence: 2,
+ threads: [{ ...SNAPSHOT.threads[0]!, ...parked }],
+ };
+ h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), confirmed);
+ expect(h.registry.get(h.visibleAtom)?.threads[0]).toMatchObject(awake);
+ const second = yield* Queue.take(h.requests);
+ expect(second.command.type).toBe(action === "settle" ? "thread.unsettle" : "thread.unsnooze");
+ yield* Deferred.fail(second.reply, new Error("Undo rejected"));
+ expect((yield* Effect.promise(() => undo))._tag).toBe("Failure");
+ expect(h.registry.get(h.visibleAtom)).toBe(confirmed);
+ }),
+ );
+
+ it.effect.each(undoableActions)(
+ "preserves a newer approval when the %s reply arrives after the shell",
+ (action) =>
Effect.gen(function* () {
const h = yield* makeHarness();
const result = h.commands[action].run(h.registry, {
@@ -346,9 +347,11 @@ describe("remote thread lifecycle commands", () => {
expect((yield* Effect.promise(() => result))._tag).toBe("Success");
expect(h.registry.get(h.visibleAtom)).toBe(newer);
}),
- );
+ );
- it.effect(`shows an accepted ${action} while the shell still has an old input request`, () =>
+ it.effect.each(undoableActions)(
+ "shows an accepted %s while the shell still has an old input request",
+ (action) =>
Effect.gen(function* () {
const h = yield* makeHarness();
const stale = {
@@ -370,6 +373,5 @@ describe("remote thread lifecycle commands", () => {
expect(h.registry.get(h.visibleAtom)?.threads[0]?.pendingRuntimeRequest).toBeNull();
expect(h.registry.get(h.snapshotAtom(ENVIRONMENT_ID))).toBe(stale);
}),
- );
- }
+ );
});
diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts
index 0c1619a52b1..61bd092a4b2 100644
--- a/packages/client-runtime/src/state/threads-sync.test.ts
+++ b/packages/client-runtime/src/state/threads-sync.test.ts
@@ -315,8 +315,9 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => {
};
describe("EnvironmentThreads", () => {
- for (const source of ["disk", "HTTP"] as const) {
- it.effect(`does not rewrite an unchanged ${source} snapshot on navigation or warm return`, () =>
+ it.effect.each(["disk", "HTTP"] as const)(
+ "does not rewrite an unchanged %s snapshot on navigation or warm return",
+ (source) =>
Effect.gen(function* () {
const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
snapshot: undefined,
@@ -350,8 +351,7 @@ describe("EnvironmentThreads", () => {
);
expect(yield* Ref.get(nextSaved)).toEqual([]);
}),
- );
- }
+ );
it.effect("persists a complete bounded HTTP window only once", () =>
Effect.gen(function* () {
@@ -1012,8 +1012,9 @@ describe("EnvironmentThreads", () => {
}),
);
- for (const cacheKind of ["disk", "retained"] as const) {
- it.effect(`retains paging support through a complete bounded ${cacheKind} cache`, () =>
+ it.effect.each(["disk", "retained"] as const)(
+ "retains paging support through a complete bounded %s cache",
+ (cacheKind) =>
Effect.gen(function* () {
const resumeCache: NonNullable<Parameters<typeof makeEnvironmentThreadState>[1]> = {
snapshot: undefined,
@@ -1071,11 +1072,11 @@ describe("EnvironmentThreads", () => {
expect(yield* Ref.get(warm.lastSubscribeAfterSequence)).toBe(5);
expect(yield* Ref.get(warm.lastAcceptBoundedSnapshot)).toBe(true);
}),
- );
- }
+ );
- for (const historyPaging of ["no-http", "no-controller"] as const) {
- it.effect(`does not negotiate bounded fallbacks with ${historyPaging}`, () =>
+ it.effect.each(["no-http", "no-controller"] as const)(
+ "does not negotiate bounded fallbacks with %s",
+ (historyPaging) =>
Effect.gen(function* () {
for (const source of ["cache", "http"] as const) {
const history = {
@@ -1105,8 +1106,7 @@ describe("EnvironmentThreads", () => {
expect(yield* Ref.get(harness.lastAcceptBoundedSnapshot)).toBeUndefined();
}
}),
- );
- }
+ );
it.effect("socket snapshot clears progressive history meta left from a bounded window", () =>
Effect.gen(function* () {
diff --git a/packages/contracts/src/providerInstance.test.ts b/packages/contracts/src/providerInstance.test.ts
index 1645eae4825..ef96d1d147b 100644
--- a/packages/contracts/src/providerInstance.test.ts
+++ b/packages/contracts/src/providerInstance.test.ts
@@ -21,39 +21,37 @@ describe("provider slug validation (shared by driver + instance ids)", () => {
{ schemaName: "ProviderDriverKind", decode: decodeProviderDriverKind },
] as const;
- for (const { schemaName, decode } of cases) {
- describe(schemaName, () => {
- it.each(["codex", "codex_personal", "codex-work", "claudeAgent", "x", "abc123", "ollama"])(
- "accepts %s",
- (id) => {
- expect(decode(id)).toBe(id);
- },
- );
-
- it.each([
- ["empty string", ""],
- ["leading digit", "1codex"],
- ["leading dash", "-codex"],
- ["leading underscore", "_codex"],
- ["whitespace inside", "codex personal"],
- ["dot inside", "codex.personal"],
- ["slash inside", "codex/personal"],
- ])("rejects %s", (_label, value) => {
- expect(() => decode(value)).toThrow();
- });
-
- it("trims surrounding whitespace before validating", () => {
- expect(decode(" codex_work ")).toBe("codex_work");
- });
-
- it("rejects ids longer than 64 characters", () => {
- const tooLong = "a".repeat(65);
- expect(() => decode(tooLong)).toThrow();
- const justRight = "a".repeat(64);
- expect(decode(justRight)).toBe(justRight);
- });
+ describe.each(cases)("$schemaName", ({ decode }) => {
+ it.each(["codex", "codex_personal", "codex-work", "claudeAgent", "x", "abc123", "ollama"])(
+ "accepts %s",
+ (id) => {
+ expect(decode(id)).toBe(id);
+ },
+ );
+
+ it.each([
+ ["empty string", ""],
+ ["leading digit", "1codex"],
+ ["leading dash", "-codex"],
+ ["leading underscore", "_codex"],
+ ["whitespace inside", "codex personal"],
+ ["dot inside", "codex.personal"],
+ ["slash inside", "codex/personal"],
+ ])("rejects %s", (_label, value) => {
+ expect(() => decode(value)).toThrow();
+ });
+
+ it("trims surrounding whitespace before validating", () => {
+ expect(decode(" codex_work ")).toBe("codex_work");
+ });
+
+ it("rejects ids longer than 64 characters", () => {
+ const tooLong = "a".repeat(65);
+ expect(() => decode(tooLong)).toThrow();
+ const justRight = "a".repeat(64);
+ expect(decode(justRight)).toBe(justRight);
});
- }
+ });
});
describe("ProviderInstanceRef", () => {
diff --git a/packages/effect-acp/src/protocol.test.ts b/packages/effect-acp/src/protocol.test.ts
index d42fc08c3f4..051f03627f0 100644
--- a/packages/effect-acp/src/protocol.test.ts
+++ b/packages/effect-acp/src/protocol.test.ts
@@ -1088,8 +1088,9 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
}),
);
- for (const operation of ["request", "notification"] as const) {
- it.effect(`rejects a ${operation} if the connection ends while its logger is running`, () =>
+ it.effect.each(["request", "notification"] as const)(
+ "rejects a %s if the connection ends while its logger is running",
+ (operation) =>
Effect.gen(function* () {
const { stdio, input, output } = yield* makeInMemoryStdio();
const writeStarted = yield* Deferred.make<void>();
@@ -1127,6 +1128,5 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
assert.strictEqual(failure, error);
assert.equal(yield* Queue.size(output), 0);
}),
- );
- }
+ );
});
diff --git a/packages/shared/src/gitPatchPath.test.ts b/packages/shared/src/gitPatchPath.test.ts
index 20c5065729f..c1592a92acf 100644
--- a/packages/shared/src/gitPatchPath.test.ts
+++ b/packages/shared/src/gitPatchPath.test.ts
@@ -46,15 +46,13 @@ describe("a name written into a header and read back out", () => {
`every\t\n\r"\\${BELL}.txt`,
];
- for (const name of names) {
- it(`is the name that went in: ${JSON.stringify(name)}`, () => {
- const written = quoteGitPatchPath(name);
- expect(unquoteGitPatchPath(written)).toBe(name);
- // A parser that takes the quotes off itself, as the clients' one does, gets there too.
- const unwrapped = written.startsWith('"') ? written.slice(1, -1) : written;
- expect(unquoteGitPatchPath(unwrapped)).toBe(name);
- });
- }
+ it.each(names)("is the name that went in: %j", (name) => {
+ const written = quoteGitPatchPath(name);
+ expect(unquoteGitPatchPath(written)).toBe(name);
+ // A parser that takes the quotes off itself, as the clients' one does, gets there too.
+ const unwrapped = written.startsWith('"') ? written.slice(1, -1) : written;
+ expect(unquoteGitPatchPath(unwrapped)).toBe(name);
+ });
it("carries the whole name past the first thing a header stops at", () => {
const written = quoteGitPatchPath("tab\tfile.txt");
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index e69017ccfbc..38417a2e4f0 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -1269,8 +1269,9 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
).pipe(Effect.provideService(HostProcessPlatform, "linux")),
);
- for (const targetArch of ["x64", "arm64"] as const) {
- it.effect(`accepts an embedded archive with the Linux ${targetArch} node-pty prebuild`, () =>
+ it.effect.each(["x64", "arm64"] as const)(
+ "accepts an embedded archive with the Linux %s node-pty prebuild",
+ (targetArch) =>
Effect.scoped(
Effect.gen(function* () {
const fixture = yield* makeWindowsPayloadFixture({
@@ -1290,33 +1291,32 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => {
assert.equal(result.packagedAppDir, fixture.packagedAppDir);
}),
).pipe(Effect.provideService(HostProcessPlatform, "linux")),
- );
+ );
- it.effect(
- `rejects a node-pty prebuild for the wrong architecture in a Linux ${targetArch} archive`,
- () =>
- Effect.scoped(
- Effect.gen(function* () {
- const fixture = yield* makeWindowsPayloadFixture({
- copyUnpackedNatives: true,
- wslRuntime: "valid",
- targetArch,
- ptyPrebuildArch: targetArch === "x64" ? "arm64" : "x64",
- });
- const error = yield* validateWindowsPackagedPayload({
- stageDistDir: fixture.stageDistDir,
- appExecutableName: fixture.appExecutableName,
- targetArch,
- appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
- expectWslRuntime: true,
- }).pipe(Effect.flip);
-
- assert.instanceOf(error, WindowsPackagedPayloadValidationError);
- assert.equal(error.reason, "wsl-runtime-invalid");
- }),
- ),
- );
- }
+ it.effect.each(["x64", "arm64"] as const)(
+ "rejects a node-pty prebuild for the wrong architecture in a Linux %s archive",
+ (targetArch) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const fixture = yield* makeWindowsPayloadFixture({
+ copyUnpackedNatives: true,
+ wslRuntime: "valid",
+ targetArch,
+ ptyPrebuildArch: targetArch === "x64" ? "arm64" : "x64",
+ });
+ const error = yield* validateWindowsPackagedPayload({
+ stageDistDir: fixture.stageDistDir,
+ appExecutableName: fixture.appExecutableName,
+ targetArch,
+ appVersion: WINDOWS_PAYLOAD_FIXTURE_VERSION,
+ expectWslRuntime: true,
+ }).pipe(Effect.flip);
+
+ assert.instanceOf(error, WindowsPackagedPayloadValidationError);
+ assert.equal(error.reason, "wsl-runtime-invalid");
+ }),
+ ),
+ );
it.effect("rejects an embedded archive built for a different release version", () =>
Effect.scoped(
diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts
index 5a270386a30..be58bcecde0 100644
--- a/scripts/dev-runner.test.ts
+++ b/scripts/dev-runner.test.ts
@@ -414,8 +414,9 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
// Browser dev is single-origin: Vite proxies the backend, and the client
// resolves it from window.location.origin. Baking a localhost URL here is
// what breaks sharing a dev server to another device.
- for (const mode of ["dev", "dev:web"] as const) {
- it.effect(`leaves the client backend URLs unset in ${mode} mode`, () =>
+ it.effect.each(["dev", "dev:web"] as const)(
+ "leaves the client backend URLs unset in %s mode",
+ (mode) =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode,
@@ -442,8 +443,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
// the intent has to be stated positively.
assert.equal(env.T3CODE_SINGLE_ORIGIN_DEV, "1");
}),
- );
- }
+ );
// Desktop pins the renderer at loopback deliberately; an ambient marker
// must not make Vite discard those URLs.
@@ -492,27 +492,25 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
// HOST is Vite's bind address and gates the HMR pin in vite.config.ts. An
// inherited one would survive into browser dev and point HMR at the wrong
// interface — invisible over a shared origin, since the page still loads.
- for (const mode of ["dev", "dev:web"] as const) {
- it.effect(`drops an inherited HOST in ${mode} mode`, () =>
- Effect.gen(function* () {
- const env = yield* createDevRunnerEnv({
- mode,
- baseEnv: { HOST: "0.0.0.0" },
- serverOffset: 0,
- webOffset: 0,
- t3Home: undefined,
- browser: undefined,
- autoBootstrapProjectFromCwd: undefined,
- logWebSocketEvents: undefined,
- host: undefined,
- port: undefined,
- devUrl: undefined,
- });
+ it.effect.each(["dev", "dev:web"] as const)("drops an inherited HOST in %s mode", (mode) =>
+ Effect.gen(function* () {
+ const env = yield* createDevRunnerEnv({
+ mode,
+ baseEnv: { HOST: "0.0.0.0" },
+ serverOffset: 0,
+ webOffset: 0,
+ t3Home: undefined,
+ browser: undefined,
+ autoBootstrapProjectFromCwd: undefined,
+ logWebSocketEvents: undefined,
+ host: undefined,
+ port: undefined,
+ devUrl: undefined,
+ });
- assert.equal(env.HOST, undefined);
- }),
- );
- }
+ assert.equal(env.HOST, undefined);
+ }),
+ );
// --host configures the *backend* (T3CODE_HOST). It must not become Vite's
// bind address by way of an inherited HOST that happens to agree with it.
diff --git a/scripts/legend-list-initial-reveal.test.ts b/scripts/legend-list-initial-reveal.test.ts
index 15ebc3f597e..00e3e30594a 100644
--- a/scripts/legend-list-initial-reveal.test.ts
+++ b/scripts/legend-list-initial-reveal.test.ts
@@ -78,8 +78,9 @@ function createList(bundle: string) {
};
}
-for (const bundle of ["react-native.js", "react-native.mjs"]) {
- describe(`initial inset end reveal (${bundle})`, () => {
+describe.each(["react-native.js", "react-native.mjs"])(
+ "initial inset end reveal (%s)",
+ (bundle) => {
it("waits for the native offset instead of the optimistic scroll target", () => {
const list = createList(bundle);
list.start();
@@ -210,5 +211,5 @@ for (const bundle of ["react-native.js", "react-native.mjs"]) {
empty.complete();
expect(empty.ready()).toBe(true);
});
- });
-}
+ },
+);
diff --git a/vite.config.ts b/vite.config.ts
index 6845af15094..5961c106d64 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -167,6 +167,7 @@ export default defineConfig({
"t3code/no-inline-schema-compile": "warn",
"t3code/no-manual-effect-runtime-in-tests": "error",
"t3code/no-native-title-tooltip": "error",
+ "t3code/no-test-in-loop": "error",
"t3code/namespace-node-imports": "error",
},
overrides: [