The best way to control Claude Code, Codex and more from any computer or phone
test: drop Effect.scoped wrappers that @effect/vitest already applies (#35993)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 12, 2026 at 21:27 UTC
ee645553a970976f663c22d19a74871fd65a18b7
171 files changed
+37554
-39085
apps/desktop/src/app/DesktopClerk.test.ts
+2
-2
@@ -424,7 +424,7 @@ it.effect.each(["startup", "open-url", "early-second-instance"] as const)(
424
),
425
Effect.provideService(DesktopWebLinks.DesktopWebLinks, ignoreWebLinks),
426
);
427
- }).pipe(Effect.scoped),
427
+ }),
428
);
429
430
it.effect("hands web and app links to the renderer and leaves other links alone", () =>
@@ -481,5 +481,5 @@ it.effect("hands web and app links to the renderer and leaves other links alone"
481
}),
482
),
483
);
484
- }).pipe(Effect.scoped),
484
+ }),
485
);
apps/desktop/src/app/DesktopCliCommand.test.ts
+8
-8
@@ -160,7 +160,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
160
expect(yield* fs.exists(upgradedLink)).toBe(false);
161
expect((yield* upgraded.install).installedPath).toBe(upgradedLink);
162
}
163
- }).pipe(Effect.scoped),
163
+ }),
164
);
165
166
it.effect("never replaces or removes a t3 it did not create", () =>
@@ -202,7 +202,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
202
expect((yield* Effect.flip(command.install)).message).toContain("Could not set up");
203
yield* command.uninstall;
204
expect(yield* fs.readFileString(launcher)).toBe("npm's t3\n");
205
- }).pipe(Effect.scoped),
205
+ }),
206
);
207
208
it.effect("finds and removes a link left by a previous T3 home", () =>
@@ -259,7 +259,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
259
);
260
expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
261
expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine");
262
- }).pipe(Effect.scoped),
262
+ }),
263
);
264
265
it.effect("refuses to install behind another t3 that runs first", () =>
@@ -309,7 +309,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
309
installedPath: path.join(home, ".local", "bin", "t3"),
310
});
311
expect(installed.shadowedBy).toBeUndefined();
312
- }).pipe(Effect.scoped),
312
+ }),
313
);
314
315
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
@@ -343,7 +343,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
343
onPath: true,
344
installedPath: path.join(home, ".local", "bin", "t3"),
345
});
346
- }).pipe(Effect.scoped),
346
+ }),
347
);
348
349
it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () =>
@@ -372,7 +372,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
372
expect(yield* command.state).toEqual(removed);
373
expect(yield* fs.exists(installed.installedPath!)).toBe(false);
374
expect(yield* fs.exists(launcher)).toBe(true);
375
- }).pipe(Effect.scoped),
375
+ }),
376
);
377
378
it.effect("leaves the Windows PATH alone when it cannot be read", () =>
@@ -411,7 +411,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
411
const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner);
412
yield* reader.install;
413
expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 });
414
- }).pipe(Effect.scoped),
414
+ }),
415
);
416
417
it.effect("does not claim or remove a Windows PATH entry the user added", () =>
@@ -441,6 +441,6 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
441
yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner))
442
.installOnFirstLaunch;
443
expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 });
444
- }).pipe(Effect.scoped),
444
+ }),
445
);
446
});
apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts
+2
-2
@@ -99,7 +99,7 @@ const withStore = <A, E, R>(
99
prefix: "t3-desktop-connection-catalog-test-",
100
});
101
return yield* effect.pipe(Effect.provide(layerFor(baseDir, encryptionAvailable)));
102
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
102
+ }).pipe(Effect.provide(NodeServices.layer));
103
104
describe("DesktopConnectionCatalogStore", () => {
105
it.effect("persists and reads an encrypted connection catalog", () =>
@@ -298,6 +298,6 @@ describe("DesktopConnectionCatalogStore", () => {
298
assert.notEqual(error.message, decryptError.message);
299
yield* Ref.set(failDecrypt, false);
300
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
301
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
301
+ }).pipe(Effect.provide(NodeServices.layer)),
302
);
303
});
apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts
+5
-5
@@ -602,7 +602,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
602
}
603
assert.isFalse(yield* fileSystem.exists(fixture.cachePath));
604
assert.equal(iconCacheRuns(run), 0);
605
- }).pipe(Effect.scoped),
605
+ }),
606
);
607
608
it.effect("replaces same-length stale icons and refreshes an existing cache once", () =>
@@ -634,7 +634,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
634
run.commands.filter(({ command }) => command === "gtk-update-icon-cache"),
635
[{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }],
636
);
637
- }).pipe(Effect.scoped),
637
+ }),
638
);
639
640
it.effect("refreshes when this launch changed an icon even if the cache looks newer", () =>
@@ -655,7 +655,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
655
656
assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png")));
657
assert.equal(iconCacheRuns(run), 1);
658
- }).pipe(Effect.scoped),
658
+ }),
659
);
660
661
it.effect("retries a failed icon cache refresh on the next launch", () =>
@@ -678,7 +678,7 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
678
yield* registerWithRealFileSystem(recovering);
679
yield* registerWithRealFileSystem(recovering);
680
assert.equal(iconCacheRuns(recovering), 1);
681
- }).pipe(Effect.scoped),
681
+ }),
682
);
683
684
it.effect("still registers the handler when the theme icon install fails", () =>
@@ -702,6 +702,6 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
702
missingTool.commands.map(({ command }) => command),
703
["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
704
);
705
- }).pipe(Effect.scoped),
705
+ }),
706
);
707
});
apps/desktop/src/backend/DesktopBackendManager.test.ts
+493
-520
@@ -199,129 +199,125 @@ function makeTestInstance(input: MakeInstanceInput) {
199
200
describe("DesktopBackendManager", () => {
201
it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () =>
202
- Effect.scoped(
203
- Effect.gen(function* () {
204
- const probe = yield* Deferred.make<void>();
205
- const ready = yield* Deferred.make<void>();
206
- const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
207
- const instance = yield* makeTestInstance({
208
- spawnerLayer: Layer.succeed(
209
- ChildProcessSpawner.ChildProcessSpawner,
210
- ChildProcessSpawner.make(() =>
211
- Effect.acquireRelease(
212
- Effect.succeed(
213
- makeProcess({
214
- exitCode: Deferred.await(exit),
215
- kill: () =>
216
- Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
217
- }),
218
- ),
219
- () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
202
+ Effect.gen(function* () {
203
+ const probe = yield* Deferred.make<void>();
204
+ const ready = yield* Deferred.make<void>();
205
+ const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
206
+ const instance = yield* makeTestInstance({
207
+ spawnerLayer: Layer.succeed(
208
+ ChildProcessSpawner.ChildProcessSpawner,
209
+ ChildProcessSpawner.make(() =>
210
+ Effect.acquireRelease(
211
+ Effect.succeed(
212
+ makeProcess({
213
+ exitCode: Deferred.await(exit),
214
+ kill: () =>
215
+ Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
216
+ }),
217
),
218
+ () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
219
),
220
),
223
- httpClientLayer: Layer.succeed(
224
- HttpClient.HttpClient,
225
- HttpClient.make((request) =>
226
- Deferred.succeed(probe, undefined).pipe(
227
- Effect.andThen(Deferred.await(ready)),
228
- Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
229
- ),
221
+ ),
222
+ httpClientLayer: Layer.succeed(
223
+ HttpClient.HttpClient,
224
+ HttpClient.make((request) =>
225
+ Deferred.succeed(probe, undefined).pipe(
226
+ Effect.andThen(Deferred.await(ready)),
227
+ Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
228
),
229
),
232
- });
233
- yield* instance.start;
234
- yield* Deferred.await(probe);
235
- const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
236
- yield* Deferred.succeed(ready, undefined);
237
- assert.isTrue(yield* Fiber.join(waiter));
238
- yield* instance.stop();
239
- assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
240
- }),
241
- ),
230
+ ),
231
+ });
232
+ yield* instance.start;
233
+ yield* Deferred.await(probe);
234
+ const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
235
+ yield* Deferred.succeed(ready, undefined);
236
+ assert.isTrue(yield* Fiber.join(waiter));
237
+ yield* instance.stop();
238
+ assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
239
+ }),
240
);
241
242
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
245
- Effect.scoped(
246
- Effect.gen(function* () {
247
- let spawnedCommand: ChildProcess.Command | undefined;
248
- let bootstrapJson = "";
249
- let telemetryJson = "";
250
- let readyCount = 0;
251
- const ready = yield* Deferred.make<void>();
252
- const exited = yield* Queue.unbounded<void>();
253
-
254
- const layerSpawner = Layer.succeed(
255
- ChildProcessSpawner.ChildProcessSpawner,
256
- ChildProcessSpawner.make((command) =>
257
- Effect.gen(function* () {
258
- spawnedCommand = command;
259
- if (command._tag === "StandardCommand") {
260
- const fd3 = command.options.additionalFds?.fd3;
261
- if (fd3?.type === "input" && fd3.stream) {
262
- bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
263
- }
264
- const fd4 = command.options.additionalFds?.fd4;
265
- if (fd4?.type === "input" && fd4.stream) {
266
- telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
267
- }
243
+ Effect.gen(function* () {
244
+ let spawnedCommand: ChildProcess.Command | undefined;
245
+ let bootstrapJson = "";
246
+ let telemetryJson = "";
247
+ let readyCount = 0;
248
+ const ready = yield* Deferred.make<void>();
249
+ const exited = yield* Queue.unbounded<void>();
250
+
251
+ const layerSpawner = Layer.succeed(
252
+ ChildProcessSpawner.ChildProcessSpawner,
253
+ ChildProcessSpawner.make((command) =>
254
+ Effect.gen(function* () {
255
+ spawnedCommand = command;
256
+ if (command._tag === "StandardCommand") {
257
+ const fd3 = command.options.additionalFds?.fd3;
258
+ if (fd3?.type === "input" && fd3.stream) {
259
+ bootstrapJson = yield* fd3.stream.pipe(Stream.decodeText(), Stream.mkString);
260
}
261
+ const fd4 = command.options.additionalFds?.fd4;
262
+ if (fd4?.type === "input" && fd4.stream) {
263
+ telemetryJson = yield* fd4.stream.pipe(Stream.decodeText(), Stream.mkString);
264
+ }
265
+ }
266
270
- return makeProcess({
271
- exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
272
- });
273
- }),
274
- ),
275
- );
267
+ return makeProcess({
268
+ exitCode: Deferred.await(ready).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
269
+ });
270
+ }),
271
+ ),
272
+ );
273
277
- const instance = yield* makeTestInstance({
278
- config: {
279
- ...baseConfig,
280
- bootstrap: configWithObservability,
281
- },
282
- spawnerLayer: layerSpawner,
283
- desktopTelemetryStream: Stream.encodeText(
284
- Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
285
- ),
286
- onReady: Effect.sync(() => {
287
- readyCount += 1;
288
- }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
289
- backendOutputLog: {
290
- persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
291
- },
292
- });
274
+ const instance = yield* makeTestInstance({
275
+ config: {
276
+ ...baseConfig,
277
+ bootstrap: configWithObservability,
278
+ },
279
+ spawnerLayer: layerSpawner,
280
+ desktopTelemetryStream: Stream.encodeText(
281
+ Stream.make('{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n'),
282
+ ),
283
+ onReady: Effect.sync(() => {
284
+ readyCount += 1;
285
+ }).pipe(Effect.andThen(Deferred.succeed(ready, void 0)), Effect.asVoid),
286
+ backendOutputLog: {
287
+ persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid),
288
+ },
289
+ });
290
294
- yield* instance.start;
295
- yield* Queue.take(exited);
296
-
297
- assert.equal(readyCount, 1);
298
- assert.isDefined(spawnedCommand);
299
- if (spawnedCommand._tag !== "StandardCommand") {
300
- throw new Error("Expected backend to spawn a standard command.");
301
- }
302
-
303
- assert.equal(spawnedCommand.command, "/electron");
304
- assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
305
- assert.equal(spawnedCommand.options.cwd, "/server");
306
- assert.equal(spawnedCommand.options.extendEnv, true);
307
- assert.equal(spawnedCommand.options.stdout, "pipe");
308
- assert.equal(spawnedCommand.options.stderr, "pipe");
309
- assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
310
- assert.isDefined(spawnedCommand.options.forceKillAfter);
311
- assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
312
- assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
313
- assert.equal(
314
- Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
315
- 5_000,
316
- );
317
-
318
- assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
319
- assert.equal(
320
- telemetryJson,
321
- '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
322
- );
323
- }),
324
- ),
291
+ yield* instance.start;
292
+ yield* Queue.take(exited);
293
+
294
+ assert.equal(readyCount, 1);
295
+ assert.isDefined(spawnedCommand);
296
+ if (spawnedCommand._tag !== "StandardCommand") {
297
+ throw new Error("Expected backend to spawn a standard command.");
298
+ }
299
+
300
+ assert.equal(spawnedCommand.command, "/electron");
301
+ assert.deepEqual(spawnedCommand.args, ["/server/bin.mjs", "--bootstrap-fd", "3"]);
302
+ assert.equal(spawnedCommand.options.cwd, "/server");
303
+ assert.equal(spawnedCommand.options.extendEnv, true);
304
+ assert.equal(spawnedCommand.options.stdout, "pipe");
305
+ assert.equal(spawnedCommand.options.stderr, "pipe");
306
+ assert.equal(spawnedCommand.options.killSignal, "SIGTERM");
307
+ assert.isDefined(spawnedCommand.options.forceKillAfter);
308
+ assert.equal(spawnedCommand.options.additionalFds?.fd4?.type, "input");
309
+ assert.equal(spawnedCommand.options.additionalFds?.fd5?.type, "output");
310
+ assert.equal(
311
+ Duration.toMillis(Duration.fromInputUnsafe(spawnedCommand.options.forceKillAfter)),
312
+ 5_000,
313
+ );
314
+
315
+ assert.deepEqual(yield* decodeBootstrap(bootstrapJson), configWithObservability);
316
+ assert.equal(
317
+ telemetryJson,
318
+ '{"version":1,"type":"desktopTelemetryHello","electronPid":123}\n',
319
+ );
320
+ }),
321
);
322
323
it.effect("reports a SIGKILL exit without an exit code", () =>
@@ -349,285 +345,272 @@ describe("DesktopBackendManager", () => {
345
);
346
347
it.effect("reports child exit before waiting for trailing output to drain", () =>
352
- Effect.scoped(
353
- Effect.gen(function* () {
354
- const exitObserved = yield* Deferred.make<void>();
355
- const finishOutputDrain = yield* Deferred.make<void>();
356
- const layerSpawner = Layer.succeed(
357
- ChildProcessSpawner.ChildProcessSpawner,
358
- ChildProcessSpawner.make(() =>
359
- Effect.succeed(
360
- makeProcess({
361
- stdout: Stream.fromEffect(
362
- Deferred.await(finishOutputDrain).pipe(
363
- Effect.as(new TextEncoder().encode("trailing output\n")),
364
- ),
348
+ Effect.gen(function* () {
349
+ const exitObserved = yield* Deferred.make<void>();
350
+ const finishOutputDrain = yield* Deferred.make<void>();
351
+ const layerSpawner = Layer.succeed(
352
+ ChildProcessSpawner.ChildProcessSpawner,
353
+ ChildProcessSpawner.make(() =>
354
+ Effect.succeed(
355
+ makeProcess({
356
+ stdout: Stream.fromEffect(
357
+ Deferred.await(finishOutputDrain).pipe(
358
+ Effect.as(new TextEncoder().encode("trailing output\n")),
359
),
366
- exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
367
- }),
368
- ),
360
+ ),
361
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
362
+ }),
363
),
370
- );
364
+ ),
365
+ );
366
372
- const runFiber = yield* DesktopBackendManager.runBackendProcess({
373
- ...baseConfig,
374
- desktopTelemetryStream: Stream.empty,
375
- onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
376
- }).pipe(
377
- Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)),
378
- Effect.forkChild,
379
- );
380
-
381
- yield* Deferred.await(exitObserved);
382
- assert.isUndefined(runFiber.pollUnsafe());
383
-
384
- yield* Deferred.succeed(finishOutputDrain, void 0);
385
- assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
386
- }),
387
- ),
367
+ const runFiber = yield* DesktopBackendManager.runBackendProcess({
368
+ ...baseConfig,
369
+ desktopTelemetryStream: Stream.empty,
370
+ onExitObserved: () => Deferred.succeed(exitObserved, void 0).pipe(Effect.asVoid),
371
+ }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), Effect.forkChild);
372
+
373
+ yield* Deferred.await(exitObserved);
374
+ assert.isUndefined(runFiber.pollUnsafe());
375
+
376
+ yield* Deferred.succeed(finishOutputDrain, void 0);
377
+ assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 1);
378
+ }),
379
);
380
381
it.effect("continues routing desktop telemetry control messages after an invalid line", () =>
391
- Effect.scoped(
392
- Effect.gen(function* () {
393
- const handled = yield* Deferred.make<boolean>();
394
- const controlMessage = encodeDesktopTelemetryControl({
395
- version: 1,
396
- type: "setDiagnosticsDemand",
397
- enabled: true,
398
- });
399
- const layerSpawner = Layer.succeed(
400
- ChildProcessSpawner.ChildProcessSpawner,
401
- ChildProcessSpawner.make(() =>
402
- Effect.succeed(
403
- makeProcess({
404
- getOutputFd: (fd) =>
405
- fd === 5
406
- ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
407
- : Stream.empty,
408
- exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
409
- }),
410
- ),
382
+ Effect.gen(function* () {
383
+ const handled = yield* Deferred.make<boolean>();
384
+ const controlMessage = encodeDesktopTelemetryControl({
385
+ version: 1,
386
+ type: "setDiagnosticsDemand",
387
+ enabled: true,
388
+ });
389
+ const layerSpawner = Layer.succeed(
390
+ ChildProcessSpawner.ChildProcessSpawner,
391
+ ChildProcessSpawner.make(() =>
392
+ Effect.succeed(
393
+ makeProcess({
394
+ getOutputFd: (fd) =>
395
+ fd === 5
396
+ ? Stream.encodeText(Stream.make(`not-json\n${controlMessage}\n`))
397
+ : Stream.empty,
398
+ exitCode: Deferred.await(handled).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
399
+ }),
400
),
412
- );
413
- const instance = yield* makeTestInstance({
414
- spawnerLayer: layerSpawner,
415
- desktopTelemetryPublisher: {
416
- handleControlForSource: (_sourceId, message) =>
417
- message.type === "setDiagnosticsDemand"
418
- ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
419
- : Effect.void,
420
- },
421
- });
401
+ ),
402
+ );
403
+ const instance = yield* makeTestInstance({
404
+ spawnerLayer: layerSpawner,
405
+ desktopTelemetryPublisher: {
406
+ handleControlForSource: (_sourceId, message) =>
407
+ message.type === "setDiagnosticsDemand"
408
+ ? Deferred.succeed(handled, message.enabled).pipe(Effect.asVoid)
409
+ : Effect.void,
410
+ },
411
+ });
412
423
- yield* instance.start;
424
- assert.isTrue(yield* Deferred.await(handled));
425
- }),
426
- ),
413
+ yield* instance.start;
414
+ assert.isTrue(yield* Deferred.await(handled));
415
+ }),
416
);
417
418
it.effect("stops the scoped process with output still pending", () =>
430
- Effect.scoped(
431
- Effect.gen(function* () {
432
- let startCount = 0;
433
- let closedCount = 0;
434
- const closed = yield* Deferred.make<void>();
435
- const teardownStarted = yield* Deferred.make<void>();
436
- const finishTeardown = yield* Deferred.make<void>();
437
- const startedPids = yield* Queue.unbounded<number>();
438
- const ready = yield* Deferred.make<void>();
439
- const backendReadyFlag = yield* Ref.make(false);
440
- let shutdownCount = 0;
441
- let persistedFailureCount = 0;
442
- let discardedSessionCount = 0;
443
- let removedTelemetrySources = 0;
444
-
445
- const layerSpawner = Layer.succeed(
446
- ChildProcessSpawner.ChildProcessSpawner,
447
- ChildProcessSpawner.make(() =>
448
- Effect.gen(function* () {
449
- const scope = yield* Scope.Scope;
450
- startCount += 1;
451
- yield* Queue.offer(startedPids, 123);
452
- const close = Deferred.succeed(teardownStarted, undefined).pipe(
453
- Effect.andThen(Deferred.await(finishTeardown)),
454
- Effect.andThen(
455
- Effect.sync(() => {
456
- closedCount += 1;
457
- }),
458
- ),
459
- Effect.andThen(Deferred.succeed(closed, void 0)),
460
- Effect.asVoid,
461
- );
419
+ Effect.gen(function* () {
420
+ let startCount = 0;
421
+ let closedCount = 0;
422
+ const closed = yield* Deferred.make<void>();
423
+ const teardownStarted = yield* Deferred.make<void>();
424
+ const finishTeardown = yield* Deferred.make<void>();
425
+ const startedPids = yield* Queue.unbounded<number>();
426
+ const ready = yield* Deferred.make<void>();
427
+ const backendReadyFlag = yield* Ref.make(false);
428
+ let shutdownCount = 0;
429
+ let persistedFailureCount = 0;
430
+ let discardedSessionCount = 0;
431
+ let removedTelemetrySources = 0;
432
463
- yield* Scope.addFinalizer(scope, close);
433
+ const layerSpawner = Layer.succeed(
434
+ ChildProcessSpawner.ChildProcessSpawner,
435
+ ChildProcessSpawner.make(() =>
436
+ Effect.gen(function* () {
437
+ const scope = yield* Scope.Scope;
438
+ startCount += 1;
439
+ yield* Queue.offer(startedPids, 123);
440
+ const close = Deferred.succeed(teardownStarted, undefined).pipe(
441
+ Effect.andThen(Deferred.await(finishTeardown)),
442
+ Effect.andThen(
443
+ Effect.sync(() => {
444
+ closedCount += 1;
445
+ }),
446
+ ),
447
+ Effect.andThen(Deferred.succeed(closed, void 0)),
448
+ Effect.asVoid,
449
+ );
450
+
451
+ yield* Scope.addFinalizer(scope, close);
452
+
453
+ return makeProcess({
454
+ stdout: Stream.never,
455
+ exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
456
+ kill: () => close,
457
+ });
458
+ }),
459
+ ),
460
+ );
461
465
- return makeProcess({
466
- stdout: Stream.never,
467
- exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
468
- kill: () => close,
469
- });
462
+ const instance = yield* makeTestInstance({
463
+ spawnerLayer: layerSpawner,
464
+ onReady: Ref.set(backendReadyFlag, true).pipe(
465
+ Effect.andThen(Deferred.succeed(ready, void 0)),
466
+ Effect.asVoid,
467
+ ),
468
+ onShutdown: Ref.set(backendReadyFlag, false).pipe(
469
+ Effect.andThen(
470
+ Effect.sync(() => {
471
+ shutdownCount += 1;
472
}),
473
),
472
- );
473
-
474
- const instance = yield* makeTestInstance({
475
- spawnerLayer: layerSpawner,
476
- onReady: Ref.set(backendReadyFlag, true).pipe(
477
- Effect.andThen(Deferred.succeed(ready, void 0)),
478
- Effect.asVoid,
479
- ),
480
- onShutdown: Ref.set(backendReadyFlag, false).pipe(
481
- Effect.andThen(
482
- Effect.sync(() => {
483
- shutdownCount += 1;
484
- }),
485
- ),
486
- ),
487
- backendOutputLog: {
488
- persistFailure: () =>
489
- Effect.sync(() => {
490
- persistedFailureCount += 1;
491
- }),
492
- discardSession: Effect.sync(() => {
493
- discardedSessionCount += 1;
474
+ ),
475
+ backendOutputLog: {
476
+ persistFailure: () =>
477
+ Effect.sync(() => {
478
+ persistedFailureCount += 1;
479
}),
495
- },
496
- desktopTelemetryPublisher: {
497
- removeControlSource: () =>
498
- Effect.sync(() => {
499
- removedTelemetrySources += 1;
500
- }),
501
- },
502
- });
503
- assert.isTrue(Option.isNone(yield* instance.currentConfig));
504
-
505
- yield* instance.start;
506
- assert.equal(yield* Queue.take(startedPids), 123);
507
- yield* Deferred.await(ready);
508
- assert.isTrue(yield* Ref.get(backendReadyFlag));
509
- assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
510
-
511
- const runningSnapshot = yield* instance.snapshot;
512
- assert.equal(runningSnapshot.ready, true);
513
- assert.deepEqual(runningSnapshot.activePid, Option.some(123));
514
-
515
- const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
516
- yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
517
- assert.isFalse(yield* Ref.get(backendReadyFlag));
518
- assert.equal(shutdownCount, 1);
519
- yield* Deferred.succeed(finishTeardown, undefined);
520
- yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
521
- assert.equal(startCount, 1);
522
- assert.equal(closedCount, 1);
523
- assert.equal(persistedFailureCount, 0);
524
- assert.equal(discardedSessionCount, 1);
525
- assert.equal(removedTelemetrySources, 1);
526
-
527
- const stoppedSnapshot = yield* instance.snapshot;
528
- assert.isFalse(yield* Ref.get(backendReadyFlag));
529
- assert.equal(shutdownCount, 1);
530
- assert.equal(stoppedSnapshot.desiredRunning, false);
531
- assert.equal(stoppedSnapshot.ready, false);
532
- assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
533
- }),
534
- ),
480
+ discardSession: Effect.sync(() => {
481
+ discardedSessionCount += 1;
482
+ }),
483
+ },
484
+ desktopTelemetryPublisher: {
485
+ removeControlSource: () =>
486
+ Effect.sync(() => {
487
+ removedTelemetrySources += 1;
488
+ }),
489
+ },
490
+ });
491
+ assert.isTrue(Option.isNone(yield* instance.currentConfig));
492
+
493
+ yield* instance.start;
494
+ assert.equal(yield* Queue.take(startedPids), 123);
495
+ yield* Deferred.await(ready);
496
+ assert.isTrue(yield* Ref.get(backendReadyFlag));
497
+ assert.deepEqual(yield* instance.currentConfig, Option.some(baseConfig));
498
+
499
+ const runningSnapshot = yield* instance.snapshot;
500
+ assert.equal(runningSnapshot.ready, true);
501
+ assert.deepEqual(runningSnapshot.activePid, Option.some(123));
502
+
503
+ const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
504
+ yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
505
+ assert.isFalse(yield* Ref.get(backendReadyFlag));
506
+ assert.equal(shutdownCount, 1);
507
+ yield* Deferred.succeed(finishTeardown, undefined);
508
+ yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
509
+ assert.equal(startCount, 1);
510
+ assert.equal(closedCount, 1);
511
+ assert.equal(persistedFailureCount, 0);
512
+ assert.equal(discardedSessionCount, 1);
513
+ assert.equal(removedTelemetrySources, 1);
514
+
515
+ const stoppedSnapshot = yield* instance.snapshot;
516
+ assert.isFalse(yield* Ref.get(backendReadyFlag));
517
+ assert.equal(shutdownCount, 1);
518
+ assert.equal(stoppedSnapshot.desiredRunning, false);
519
+ assert.equal(stoppedSnapshot.ready, false);
520
+ assert.equal(Option.isNone(stoppedSnapshot.activePid), true);
521
+ }),
522
);
523
524
it.effect("restarts when start is requested during stop teardown", () =>
538
- Effect.scoped(
539
- Effect.gen(function* () {
540
- const starts = yield* Queue.unbounded<number>();
541
- const teardownStarted = yield* Deferred.make<void>();
542
- const finishTeardown = yield* Deferred.make<void>();
543
- let startCount = 0;
525
+ Effect.gen(function* () {
526
+ const starts = yield* Queue.unbounded<number>();
527
+ const teardownStarted = yield* Deferred.make<void>();
528
+ const finishTeardown = yield* Deferred.make<void>();
529
+ let startCount = 0;
530
545
- const layerSpawner = Layer.succeed(
546
- ChildProcessSpawner.ChildProcessSpawner,
547
- ChildProcessSpawner.make(() =>
548
- Effect.gen(function* () {
549
- const scope = yield* Scope.Scope;
550
- const closed = yield* Deferred.make<void>();
551
- startCount += 1;
552
- yield* Queue.offer(starts, startCount);
553
- if (startCount === 1) {
554
- yield* Scope.addFinalizer(
555
- scope,
556
- Deferred.succeed(teardownStarted, undefined).pipe(
557
- Effect.andThen(Deferred.await(finishTeardown)),
558
- Effect.andThen(Deferred.succeed(closed, undefined)),
559
- Effect.asVoid,
560
- ),
561
- );
562
- } else {
563
- yield* Scope.addFinalizer(
564
- scope,
565
- Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
566
- );
567
- }
568
- return makeProcess({
569
- exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
570
- });
571
- }),
572
- ),
573
- );
531
+ const layerSpawner = Layer.succeed(
532
+ ChildProcessSpawner.ChildProcessSpawner,
533
+ ChildProcessSpawner.make(() =>
534
+ Effect.gen(function* () {
535
+ const scope = yield* Scope.Scope;
536
+ const closed = yield* Deferred.make<void>();
537
+ startCount += 1;
538
+ yield* Queue.offer(starts, startCount);
539
+ if (startCount === 1) {
540
+ yield* Scope.addFinalizer(
541
+ scope,
542
+ Deferred.succeed(teardownStarted, undefined).pipe(
543
+ Effect.andThen(Deferred.await(finishTeardown)),
544
+ Effect.andThen(Deferred.succeed(closed, undefined)),
545
+ Effect.asVoid,
546
+ ),
547
+ );
548
+ } else {
549
+ yield* Scope.addFinalizer(
550
+ scope,
551
+ Deferred.succeed(closed, undefined).pipe(Effect.asVoid),
552
+ );
553
+ }
554
+ return makeProcess({
555
+ exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
556
+ });
557
+ }),
558
+ ),
559
+ );
560
575
- const instance = yield* makeTestInstance({
576
- spawnerLayer: layerSpawner,
577
- httpClientLayer: layerHttpClient(() => Effect.never),
578
- });
561
+ const instance = yield* makeTestInstance({
562
+ spawnerLayer: layerSpawner,
563
+ httpClientLayer: layerHttpClient(() => Effect.never),
564
+ });
565
580
- yield* instance.start;
581
- assert.equal(yield* Queue.take(starts), 1);
566
+ yield* instance.start;
567
+ assert.equal(yield* Queue.take(starts), 1);
568
583
- const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
584
- yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
585
- yield* instance.start;
586
- assert.equal((yield* instance.snapshot).desiredRunning, true);
569
+ const stopFiber = yield* instance.stop().pipe(Effect.forkChild);
570
+ yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second"));
571
+ yield* instance.start;
572
+ assert.equal((yield* instance.snapshot).desiredRunning, true);
573
588
- yield* Deferred.succeed(finishTeardown, undefined);
589
- yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
590
- yield* TestClock.adjust(Duration.millis(500));
574
+ yield* Deferred.succeed(finishTeardown, undefined);
575
+ yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second"));
576
+ yield* TestClock.adjust(Duration.millis(500));
577
592
- assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
593
- const restarted = yield* instance.snapshot;
594
- assert.equal(restarted.desiredRunning, true);
595
- assert.deepEqual(restarted.activePid, Option.some(123));
596
- }).pipe(Effect.provide(TestClock.layer())),
597
- ),
578
+ assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2);
579
+ const restarted = yield* instance.snapshot;
580
+ assert.equal(restarted.desiredRunning, true);
581
+ assert.deepEqual(restarted.activePid, Option.some(123));
582
+ }).pipe(Effect.provide(TestClock.layer())),
583
);
584
585
it.effect("reports state-directory ownership once without scheduling another backend", () =>
601
- Effect.scoped(
602
- Effect.gen(function* () {
603
- let startCount = 0;
604
- const refused = yield* Deferred.make<void>();
605
- const instance = yield* makeTestInstance({
606
- spawnerLayer: Layer.succeed(
607
- ChildProcessSpawner.ChildProcessSpawner,
608
- ChildProcessSpawner.make(() =>
609
- Effect.sync(() => {
610
- startCount += 1;
611
- return makeProcess({
612
- exitCode: Effect.succeed(
613
- ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
614
- ),
615
- });
616
- }),
617
- ),
586
+ Effect.gen(function* () {
587
+ let startCount = 0;
588
+ const refused = yield* Deferred.make<void>();
589
+ const instance = yield* makeTestInstance({
590
+ spawnerLayer: Layer.succeed(
591
+ ChildProcessSpawner.ChildProcessSpawner,
592
+ ChildProcessSpawner.make(() =>
593
+ Effect.sync(() => {
594
+ startCount += 1;
595
+ return makeProcess({
596
+ exitCode: Effect.succeed(
597
+ ChildProcessSpawner.ExitCode(SERVER_EXIT_CODE_STATE_DIR_OWNED),
598
+ ),
599
+ });
600
+ }),
601
),
619
- httpClientLayer: layerHttpClient(() => Effect.never),
620
- onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
621
- });
622
- yield* instance.start;
623
- yield* Deferred.await(refused);
624
- const snapshot = yield* instance.snapshot;
625
- assert.isFalse(snapshot.desiredRunning);
626
- assert.isFalse(snapshot.restartScheduled);
627
- yield* TestClock.adjust(Duration.minutes(1));
628
- assert.equal(startCount, 1);
629
- }).pipe(Effect.provide(TestClock.layer())),
630
- ),
602
+ ),
603
+ httpClientLayer: layerHttpClient(() => Effect.never),
604
+ onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid),
605
+ });
606
+ yield* instance.start;
607
+ yield* Deferred.await(refused);
608
+ const snapshot = yield* instance.snapshot;
609
+ assert.isFalse(snapshot.desiredRunning);
610
+ assert.isFalse(snapshot.restartScheduled);
611
+ yield* TestClock.adjust(Duration.minutes(1));
612
+ assert.equal(startCount, 1);
613
+ }).pipe(Effect.provide(TestClock.layer())),
614
);
615
616
// A policy refusal is reported on the first exit, since retrying cannot fix it.
@@ -637,177 +620,167 @@ describe("DesktopBackendManager", () => {
620
])(
621
"reports exit $code with the server output after $exits exits",
622
({ code, exits, managedPolicy }) =>
640
- Effect.scoped(
641
- Effect.gen(function* () {
642
- const message = "Error: Cannot find module 'zod/v4' in /Users/René";
643
- let exitCount = 0;
644
- const firstExit = yield* Deferred.make<void>();
645
- const reports = yield* Queue.unbounded<{
646
- readonly exitCount: number;
647
- readonly failure: DesktopBackendManager.BackendStartupFailure;
648
- }>();
649
- const instance = yield* makeTestInstance({
650
- spawnerLayer: Layer.succeed(
651
- ChildProcessSpawner.ChildProcessSpawner,
652
- ChildProcessSpawner.make(() =>
653
- Effect.succeed(
654
- makeProcess({
655
- // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
656
- // lands inside the emoji's surrogate pair.
657
- stderr: Stream.make(
658
- new TextEncoder().encode(
659
- `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
660
- ),
661
- new Uint8Array([0xc3]),
662
- new Uint8Array([0xa9]),
623
+ Effect.gen(function* () {
624
+ const message = "Error: Cannot find module 'zod/v4' in /Users/René";
625
+ let exitCount = 0;
626
+ const firstExit = yield* Deferred.make<void>();
627
+ const reports = yield* Queue.unbounded<{
628
+ readonly exitCount: number;
629
+ readonly failure: DesktopBackendManager.BackendStartupFailure;
630
+ }>();
631
+ const instance = yield* makeTestInstance({
632
+ spawnerLayer: Layer.succeed(
633
+ ChildProcessSpawner.ChildProcessSpawner,
634
+ ChildProcessSpawner.make(() =>
635
+ Effect.succeed(
636
+ makeProcess({
637
+ // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
638
+ // lands inside the emoji's surrogate pair.
639
+ stderr: Stream.make(
640
+ new TextEncoder().encode(
641
+ `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
642
),
664
- exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
665
- }),
666
- ),
643
+ new Uint8Array([0xc3]),
644
+ new Uint8Array([0xa9]),
645
+ ),
646
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
647
+ }),
648
),
649
),
669
- httpClientLayer: layerHttpClient(() => Effect.never),
670
- backendOutputLog: {
671
- persistFailure: () => {
672
- exitCount += 1;
673
- return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
674
- },
650
+ ),
651
+ httpClientLayer: layerHttpClient(() => Effect.never),
652
+ backendOutputLog: {
653
+ persistFailure: () => {
654
+ exitCount += 1;
655
+ return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
656
},
676
- onStartupFailure: (failure) =>
677
- Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
678
- });
679
- yield* instance.start;
680
- yield* Deferred.await(firstExit);
681
- yield* TestClock.adjust(Duration.minutes(1));
682
- const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
683
- assert.equal(exitsWhenReported, exits);
684
- assert.equal(failure.reason, `The server could not start (code=${code}).`);
685
- assert.equal(failure.managedPolicy, managedPolicy);
686
- assert.isTrue(failure.output.endsWith(message));
687
- assert.isTrue(failure.output.isWellFormed());
688
- }).pipe(Effect.provide(TestClock.layer())),
689
- ),
657
+ },
658
+ onStartupFailure: (failure) =>
659
+ Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
660
+ });
661
+ yield* instance.start;
662
+ yield* Deferred.await(firstExit);
663
+ yield* TestClock.adjust(Duration.minutes(1));
664
+ const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
665
+ assert.equal(exitsWhenReported, exits);
666
+ assert.equal(failure.reason, `The server could not start (code=${code}).`);
667
+ assert.equal(failure.managedPolicy, managedPolicy);
668
+ assert.isTrue(failure.output.endsWith(message));
669
+ assert.isTrue(failure.output.isWellFormed());
670
+ }).pipe(Effect.provide(TestClock.layer())),
671
);
672
673
it.effect("waits out a slow startup and reports one that never becomes ready", () =>
693
- Effect.scoped(
694
- Effect.gen(function* () {
695
- const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
696
- const startInstance = (
697
- status: Ref.Ref<number>,
698
- onReady?: Effect.Effect<void>,
699
- stdout = "",
700
- ) =>
701
- makeTestInstance({
702
- spawnerLayer: Layer.succeed(
703
- ChildProcessSpawner.ChildProcessSpawner,
704
- ChildProcessSpawner.make(() =>
705
- Effect.succeed(
706
- makeProcess({
707
- exitCode: Effect.never,
708
- stdout: Stream.make(new TextEncoder().encode(stdout)),
709
- }),
710
- ),
674
+ Effect.gen(function* () {
675
+ const reports = yield* Queue.unbounded<DesktopBackendManager.BackendStartupFailure>();
676
+ const startInstance = (status: Ref.Ref<number>, onReady?: Effect.Effect<void>, stdout = "") =>
677
+ makeTestInstance({
678
+ spawnerLayer: Layer.succeed(
679
+ ChildProcessSpawner.ChildProcessSpawner,
680
+ ChildProcessSpawner.make(() =>
681
+ Effect.succeed(
682
+ makeProcess({
683
+ exitCode: Effect.never,
684
+ stdout: Stream.make(new TextEncoder().encode(stdout)),
685
+ }),
686
),
687
),
713
- httpClientLayer: layerHttpClient((request) =>
714
- Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
715
- ),
716
- onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
717
- ...(onReady ? { onReady } : {}),
718
- }).pipe(Effect.tap((instance) => instance.start));
719
-
720
- const slowStatus = yield* Ref.make(503);
721
- const ready = yield* Deferred.make<void>();
722
- yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
723
- yield* TestClock.adjust(Duration.seconds(66));
724
- yield* Ref.set(slowStatus, 200);
725
- yield* TestClock.adjust(Duration.millis(100));
726
- yield* Deferred.await(ready);
727
- assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
728
-
729
- const migratingStatus = yield* Ref.make(503);
730
- const migrated = yield* Deferred.make<void>();
731
- yield* startInstance(
732
- migratingStatus,
733
- Deferred.succeed(migrated, undefined).pipe(Effect.asVoid),
734
- // Enough progress lines that the start line scrolls out of the output tail.
735
- `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` +
736
- Array.from(
737
- { length: 80 },
738
- (_, index) =>
739
- `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`,
740
- ).join(""),
741
- );
742
- yield* TestClock.adjust(Duration.minutes(10));
743
- assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
744
- yield* Ref.set(migratingStatus, 200);
745
- yield* TestClock.adjust(Duration.millis(100));
746
- yield* Deferred.await(migrated);
747
-
748
- yield* startInstance(
749
- yield* Ref.make(503),
750
- undefined,
751
- `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`,
752
- );
753
- yield* TestClock.adjust(Duration.seconds(179));
754
- assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
755
- yield* TestClock.adjust(Duration.seconds(1));
756
- const failure = yield* Queue.take(reports);
757
- assert.equal(failure.reason, "The server started but did not become ready in time.");
758
- }).pipe(Effect.provide(TestClock.layer())),
759
- ),
688
+ ),
689
+ httpClientLayer: layerHttpClient((request) =>
690
+ Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))),
691
+ ),
692
+ onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid),
693
+ ...(onReady ? { onReady } : {}),
694
+ }).pipe(Effect.tap((instance) => instance.start));
695
+
696
+ const slowStatus = yield* Ref.make(503);
697
+ const ready = yield* Deferred.make<void>();
698
+ yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid));
699
+ yield* TestClock.adjust(Duration.seconds(66));
700
+ yield* Ref.set(slowStatus, 200);
701
+ yield* TestClock.adjust(Duration.millis(100));
702
+ yield* Deferred.await(ready);
703
+ assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
704
+
705
+ const migratingStatus = yield* Ref.make(503);
706
+ const migrated = yield* Deferred.make<void>();
707
+ yield* startInstance(
708
+ migratingStatus,
709
+ Deferred.succeed(migrated, undefined).pipe(Effect.asVoid),
710
+ // Enough progress lines that the start line scrolls out of the output tail.
711
+ `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` +
712
+ Array.from(
713
+ { length: 80 },
714
+ (_, index) =>
715
+ `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`,
716
+ ).join(""),
717
+ );
718
+ yield* TestClock.adjust(Duration.minutes(10));
719
+ assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
720
+ yield* Ref.set(migratingStatus, 200);
721
+ yield* TestClock.adjust(Duration.millis(100));
722
+ yield* Deferred.await(migrated);
723
+
724
+ yield* startInstance(
725
+ yield* Ref.make(503),
726
+ undefined,
727
+ `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATIONS_FINISHED_MESSAGE}\n`,
728
+ );
729
+ yield* TestClock.adjust(Duration.seconds(179));
730
+ assert.isTrue(Option.isNone(yield* Queue.poll(reports)));
731
+ yield* TestClock.adjust(Duration.seconds(1));
732
+ const failure = yield* Queue.take(reports);
733
+ assert.equal(failure.reason, "The server started but did not become ready in time.");
734
+ }).pipe(Effect.provide(TestClock.layer())),
735
);
736
737
it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () =>
763
- Effect.scoped(
764
- Effect.gen(function* () {
765
- const spawned = yield* Deferred.make<void>();
766
- const teardownStarted = yield* Deferred.make<void>();
767
- const teardownFinished = yield* Deferred.make<void>();
768
- const instance = yield* makeTestInstance({
769
- spawnerLayer: Layer.succeed(
770
- ChildProcessSpawner.ChildProcessSpawner,
771
- ChildProcessSpawner.make(() =>
772
- Effect.gen(function* () {
773
- const scope = yield* Scope.Scope;
774
- yield* Deferred.succeed(spawned, undefined);
775
- yield* Scope.addFinalizer(
776
- scope,
777
- Deferred.succeed(teardownStarted, undefined).pipe(
778
- Effect.andThen(Effect.sleep(Duration.seconds(10))),
779
- Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
780
- Effect.asVoid,
781
- ),
782
- );
783
- return makeProcess({
784
- exitCode: Deferred.await(teardownFinished).pipe(
785
- Effect.as(ChildProcessSpawner.ExitCode(0)),
786
- ),
787
- });
788
- }),
789
- ),
738
+ Effect.gen(function* () {
739
+ const spawned = yield* Deferred.make<void>();
740
+ const teardownStarted = yield* Deferred.make<void>();
741
+ const teardownFinished = yield* Deferred.make<void>();
742
+ const instance = yield* makeTestInstance({
743
+ spawnerLayer: Layer.succeed(
744
+ ChildProcessSpawner.ChildProcessSpawner,
745
+ ChildProcessSpawner.make(() =>
746
+ Effect.gen(function* () {
747
+ const scope = yield* Scope.Scope;
748
+ yield* Deferred.succeed(spawned, undefined);
749
+ yield* Scope.addFinalizer(
750
+ scope,
751
+ Deferred.succeed(teardownStarted, undefined).pipe(
752
+ Effect.andThen(Effect.sleep(Duration.seconds(10))),
753
+ Effect.andThen(Deferred.succeed(teardownFinished, undefined)),
754
+ Effect.asVoid,
755
+ ),
756
+ );
757
+ return makeProcess({
758
+ exitCode: Deferred.await(teardownFinished).pipe(
759
+ Effect.as(ChildProcessSpawner.ExitCode(0)),
760
+ ),
761
+ });
762
+ }),
763
),
791
- httpClientLayer: layerHttpClient(() => Effect.never),
792
- });
793
- yield* instance.start;
794
- yield* Deferred.await(spawned);
795
-
796
- // App quit and the updater stop every backend with this deadline.
797
- const quitDone = yield* Deferred.make<void>();
798
- const quitFiber = yield* instance
799
- .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
800
- .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
801
-
802
- yield* Deferred.await(teardownStarted);
803
- // Past the quit deadline, quit must still wait for the backend to exit.
804
- yield* TestClock.adjust(Duration.seconds(9));
805
- assert.isFalse(yield* Deferred.isDone(quitDone));
806
-
807
- yield* TestClock.adjust(Duration.seconds(1));
808
- yield* Fiber.join(quitFiber);
809
- assert.isTrue(yield* Deferred.isDone(teardownFinished));
810
- }).pipe(Effect.provide(TestClock.layer())),
811
- ),
764
+ ),
765
+ httpClientLayer: layerHttpClient(() => Effect.never),
766
+ });
767
+ yield* instance.start;
768
+ yield* Deferred.await(spawned);
769
+
770
+ // App quit and the updater stop every backend with this deadline.
771
+ const quitDone = yield* Deferred.make<void>();
772
+ const quitFiber = yield* instance
773
+ .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT })
774
+ .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild);
775
+
776
+ yield* Deferred.await(teardownStarted);
777
+ // Past the quit deadline, quit must still wait for the backend to exit.
778
+ yield* TestClock.adjust(Duration.seconds(9));
779
+ assert.isFalse(yield* Deferred.isDone(quitDone));
780
+
781
+ yield* TestClock.adjust(Duration.seconds(1));
782
+ yield* Fiber.join(quitFiber);
783
+ assert.isTrue(yield* Deferred.isDone(teardownFinished));
784
+ }).pipe(Effect.provide(TestClock.layer())),
785
);
786
});
apps/desktop/src/backend/DesktopBackendPool.test.ts
+124
-134
@@ -324,61 +324,6 @@ describe("DesktopBackendPool", () => {
324
it.effect(
325
"keeps the update marker after HTTP readiness until the backend publishes its runtime",
326
() =>
327
- Effect.scoped(
328
- Effect.gen(function* () {
329
- const fixture = yield* makeUpdateMarkerFixture();
330
- yield* Effect.gen(function* () {
331
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
332
- const primary = yield* pool.primary;
333
- yield* primary.start;
334
- yield* Deferred.succeed(fixture.allowReady, undefined);
335
- yield* Queue.take(fixture.readyRuns);
336
- assert.isTrue(
337
- fixture.files.has(markerPath),
338
- "a launcher could neither wait nor adopt between readiness and publication",
339
- );
340
- yield* Deferred.await(fixture.runtimeChecked);
341
- yield* TestClock.adjust(Duration.seconds(5));
342
- assert.isTrue(fixture.files.has(markerPath));
343
- fixture.publishRuntime(456);
344
- yield* TestClock.adjust(Duration.seconds(1));
345
- assert.isTrue(
346
- fixture.files.has(markerPath),
347
- "another process's runtime is not the replacement",
348
- );
349
- fixture.publishRuntime(123);
350
- yield* TestClock.adjust(Duration.seconds(1));
351
- yield* Deferred.await(fixture.markerRemoved);
352
- assert.deepEqual(fixture.removed, [markerPath]);
353
- }).pipe(Effect.provide(fixture.layer));
354
- }),
355
- ),
356
- );
357
-
358
- it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
359
- Effect.scoped(
360
- Effect.gen(function* () {
361
- const fixture = yield* makeUpdateMarkerFixture();
362
- yield* Effect.gen(function* () {
363
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
364
- const primary = yield* pool.primary;
365
- yield* primary.start;
366
- yield* Deferred.succeed(fixture.allowReady, undefined);
367
- yield* Queue.take(fixture.readyRuns);
368
- yield* Deferred.await(fixture.runtimeChecked);
369
- yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
370
- const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
371
- fixture.files.set(markerPath, replacement);
372
- yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
373
- assert.equal(fixture.files.get(markerPath), replacement);
374
- assert.deepEqual(fixture.removed, []);
375
- }).pipe(Effect.provide(fixture.layer));
376
- }),
377
- ),
378
- );
379
-
380
- it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
381
- Effect.scoped(
327
Effect.gen(function* () {
328
const fixture = yield* makeUpdateMarkerFixture();
329
yield* Effect.gen(function* () {
@@ -387,105 +332,150 @@ describe("DesktopBackendPool", () => {
332
yield* primary.start;
333
yield* Deferred.succeed(fixture.allowReady, undefined);
334
yield* Queue.take(fixture.readyRuns);
335
+ assert.isTrue(
336
+ fixture.files.has(markerPath),
337
+ "a launcher could neither wait nor adopt between readiness and publication",
338
+ );
339
yield* Deferred.await(fixture.runtimeChecked);
391
- yield* TestClock.adjust(Duration.seconds(30));
392
- yield* primary.stop();
393
- yield* primary.start;
394
- yield* Queue.take(fixture.readyRuns);
395
- yield* TestClock.adjust(Duration.seconds(31));
340
+ yield* TestClock.adjust(Duration.seconds(5));
341
+ assert.isTrue(fixture.files.has(markerPath));
342
+ fixture.publishRuntime(456);
343
+ yield* TestClock.adjust(Duration.seconds(1));
344
assert.isTrue(
345
fixture.files.has(markerPath),
398
- "the earlier run's wait must not end the later run's handoff",
346
+ "another process's runtime is not the replacement",
347
);
400
- assert.deepEqual(fixture.removed, []);
401
- fixture.publishRuntime(124);
402
- yield* TestClock.adjust(Duration.millis(100));
348
+ fixture.publishRuntime(123);
349
+ yield* TestClock.adjust(Duration.seconds(1));
350
yield* Deferred.await(fixture.markerRemoved);
351
assert.deepEqual(fixture.removed, [markerPath]);
352
}).pipe(Effect.provide(fixture.layer));
353
}),
407
- ),
354
);
355
410
- it.effect("unregister during pool quit does not interrupt sibling stops", () =>
411
- Effect.scoped(
412
- Effect.gen(function* () {
413
- const backend = yield* makeFakeBackendProcess();
414
- yield* Effect.gen(function* () {
415
- const pool = yield* DesktopBackendPool.DesktopBackendPool;
416
- const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
417
- const ready = yield* Deferred.make<void>();
418
- const siblingStarted = yield* Deferred.make<void>();
419
- const finishSibling = yield* Deferred.make<void>();
420
- let siblingCompleted = false;
421
- const instance = yield* pool.register({
422
- id,
423
- label: Effect.succeed("WSL (Ubuntu)"),
424
- configResolve: Effect.succeed(runningConfig),
425
- onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
426
- });
427
- yield* instance.start;
428
- yield* backend.started;
429
- yield* Deferred.await(ready);
430
- const quitFiber = yield* Effect.all(
431
- [
432
- instance.stop({ timeout: Duration.seconds(5) }),
433
- Deferred.succeed(siblingStarted, undefined).pipe(
434
- Effect.andThen(Deferred.await(finishSibling)),
435
- Effect.andThen(
436
- Effect.sync(() => {
437
- siblingCompleted = true;
438
- }),
439
- ),
440
- ),
441
- ],
442
- { concurrency: "unbounded" },
443
- ).pipe(Effect.forkChild);
444
- yield* Deferred.await(siblingStarted);
445
- assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
446
- const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
447
- yield* TestClock.adjust(Duration.seconds(5));
448
- assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
449
- assert.isUndefined(quitFiber.pollUnsafe());
450
- assert.isUndefined(unregisterFiber.pollUnsafe());
451
- assert.isTrue(yield* backend.isRunning);
452
- yield* TestClock.adjust(backend.killWait);
453
- yield* Fiber.join(unregisterFiber);
454
- yield* Deferred.succeed(finishSibling, undefined);
455
- yield* Fiber.join(quitFiber);
356
+ it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
357
+ Effect.gen(function* () {
358
+ const fixture = yield* makeUpdateMarkerFixture();
359
+ yield* Effect.gen(function* () {
360
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
361
+ const primary = yield* pool.primary;
362
+ yield* primary.start;
363
+ yield* Deferred.succeed(fixture.allowReady, undefined);
364
+ yield* Queue.take(fixture.readyRuns);
365
+ yield* Deferred.await(fixture.runtimeChecked);
366
+ yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
367
+ const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
368
+ fixture.files.set(markerPath, replacement);
369
+ yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
370
+ assert.equal(fixture.files.get(markerPath), replacement);
371
+ assert.deepEqual(fixture.removed, []);
372
+ }).pipe(Effect.provide(fixture.layer));
373
+ }),
374
+ );
375
457
- assert.isTrue(siblingCompleted);
458
- assert.isFalse(yield* backend.isRunning);
459
- assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
460
- assert.isTrue(Option.isNone(yield* pool.get(id)));
461
- }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
462
- }),
463
- ),
376
+ it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
377
+ Effect.gen(function* () {
378
+ const fixture = yield* makeUpdateMarkerFixture();
379
+ yield* Effect.gen(function* () {
380
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
381
+ const primary = yield* pool.primary;
382
+ yield* primary.start;
383
+ yield* Deferred.succeed(fixture.allowReady, undefined);
384
+ yield* Queue.take(fixture.readyRuns);
385
+ yield* Deferred.await(fixture.runtimeChecked);
386
+ yield* TestClock.adjust(Duration.seconds(30));
387
+ yield* primary.stop();
388
+ yield* primary.start;
389
+ yield* Queue.take(fixture.readyRuns);
390
+ yield* TestClock.adjust(Duration.seconds(31));
391
+ assert.isTrue(
392
+ fixture.files.has(markerPath),
393
+ "the earlier run's wait must not end the later run's handoff",
394
+ );
395
+ assert.deepEqual(fixture.removed, []);
396
+ fixture.publishRuntime(124);
397
+ yield* TestClock.adjust(Duration.millis(100));
398
+ yield* Deferred.await(fixture.markerRemoved);
399
+ assert.deepEqual(fixture.removed, [markerPath]);
400
+ }).pipe(Effect.provide(fixture.layer));
401
+ }),
402
);
403
466
- it.effect("unregister stops the registered instance", () =>
467
- Effect.scoped(
468
- Effect.gen(function* () {
469
- const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
404
+ it.effect("unregister during pool quit does not interrupt sibling stops", () =>
405
+ Effect.gen(function* () {
406
+ const backend = yield* makeFakeBackendProcess();
407
+ yield* Effect.gen(function* () {
408
const pool = yield* DesktopBackendPool.DesktopBackendPool;
409
+ const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
410
+ const ready = yield* Deferred.make<void>();
411
+ const siblingStarted = yield* Deferred.make<void>();
412
+ const finishSibling = yield* Deferred.make<void>();
413
+ let siblingCompleted = false;
414
const instance = yield* pool.register({
415
id,
416
label: Effect.succeed("WSL (Ubuntu)"),
474
- configResolve: Effect.succeed({
475
- ...runningConfig,
476
- preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
477
- }),
417
+ configResolve: Effect.succeed(runningConfig),
418
+ onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
419
});
420
yield* instance.start;
480
- assert.equal((yield* instance.snapshot).restartScheduled, true);
421
+ yield* backend.started;
422
+ yield* Deferred.await(ready);
423
+ const quitFiber = yield* Effect.all(
424
+ [
425
+ instance.stop({ timeout: Duration.seconds(5) }),
426
+ Deferred.succeed(siblingStarted, undefined).pipe(
427
+ Effect.andThen(Deferred.await(finishSibling)),
428
+ Effect.andThen(
429
+ Effect.sync(() => {
430
+ siblingCompleted = true;
431
+ }),
432
+ ),
433
+ ),
434
+ ],
435
+ { concurrency: "unbounded" },
436
+ ).pipe(Effect.forkChild);
437
+ yield* Deferred.await(siblingStarted);
438
+ assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
439
+ const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
440
+ yield* TestClock.adjust(Duration.seconds(5));
441
+ assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
442
+ assert.isUndefined(quitFiber.pollUnsafe());
443
+ assert.isUndefined(unregisterFiber.pollUnsafe());
444
+ assert.isTrue(yield* backend.isRunning);
445
+ yield* TestClock.adjust(backend.killWait);
446
+ yield* Fiber.join(unregisterFiber);
447
+ yield* Deferred.succeed(finishSibling, undefined);
448
+ yield* Fiber.join(quitFiber);
449
482
- yield* pool.unregister(id);
450
+ assert.isTrue(siblingCompleted);
451
+ assert.isFalse(yield* backend.isRunning);
452
+ assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
453
+ assert.isTrue(Option.isNone(yield* pool.get(id)));
454
+ }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
455
+ }),
456
+ );
457
484
- const stopped = yield* instance.snapshot;
485
- assert.equal(stopped.desiredRunning, false);
486
- assert.equal(stopped.restartScheduled, false);
487
- assert.equal(Option.isNone(yield* pool.get(id)), true);
488
- }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
489
- ),
458
+ it.effect("unregister stops the registered instance", () =>
459
+ Effect.gen(function* () {
460
+ const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
461
+ const pool = yield* DesktopBackendPool.DesktopBackendPool;
462
+ const instance = yield* pool.register({
463
+ id,
464
+ label: Effect.succeed("WSL (Ubuntu)"),
465
+ configResolve: Effect.succeed({
466
+ ...runningConfig,
467
+ preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
468
+ }),
469
+ });
470
+ yield* instance.start;
471
+ assert.equal((yield* instance.snapshot).restartScheduled, true);
472
+
473
+ yield* pool.unregister(id);
474
+
475
+ const stopped = yield* instance.snapshot;
476
+ assert.equal(stopped.desiredRunning, false);
477
+ assert.equal(stopped.restartScheduled, false);
478
+ assert.equal(Option.isNone(yield* pool.get(id)), true);
479
+ }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
480
);
481
});
apps/desktop/src/electron/ElectronProtocol.test.ts
+1
-1
@@ -63,7 +63,7 @@ describe("ElectronProtocol", () => {
63
assert.equal((yield* request("/%invalid")).status, 400);
64
assert.equal((yield* request("/", { method: "POST" })).status, 405);
65
assert.equal(netFetchMock.mock.calls.length, 0);
66
- }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer)), Effect.scoped),
66
+ }).pipe(Effect.provide(Layer.merge(layerProtocol, NodeServices.layer))),
67
);
68
69
it.effect("proxies the stable renderer origin to the current app server", () =>
apps/desktop/src/electron/ElectronTheme.test.ts
+3
-3
@@ -42,7 +42,7 @@ describe("ElectronTheme", () => {
42
assert.equal(nativeTheme.themeSource, "light");
43
portal.report(null);
44
assert.equal(nativeTheme.themeSource, "system");
45
- }).pipe(Effect.scoped),
45
+ }),
46
);
47
48
it.effect("keeps an explicit appearance over the desktop color scheme", () =>
@@ -57,7 +57,7 @@ describe("ElectronTheme", () => {
57
58
yield* theme.setSource("system");
59
assert.equal(nativeTheme.themeSource, "dark");
60
- }).pipe(Effect.scoped),
60
+ }),
61
);
62
63
it.effect("stops following the desktop when the layer is released", () =>
@@ -76,6 +76,6 @@ describe("ElectronTheme", () => {
76
});
77
yield* theme.setSource("system");
78
assert.equal(nativeTheme.themeSource, "system");
79
- }).pipe(Effect.scoped),
79
+ }),
80
);
81
});
apps/desktop/src/ipc/DesktopIpc.test.ts
+1
-1
@@ -63,5 +63,5 @@ it.effect("answers only the main window's top frame", () =>
63
appSubframe: ["rejected", undefined],
64
previewGuest: ["rejected", undefined],
65
});
66
- }).pipe(Effect.scoped),
66
+ }),
67
);
apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts
+2
-2
@@ -89,7 +89,7 @@ describe("BrowserImport.importCookies", () => {
89
90
assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
91
assert.equal(error.reason, "unknownSourceProfile");
92
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
92
+ }).pipe(Effect.provide(NodeServices.layer)),
93
);
94
95
it.effect.skipIf(!symlinksSupported)(
@@ -114,7 +114,7 @@ describe("BrowserImport.importCookies", () => {
114
115
assert.instanceOf(error, BrowserImport.BrowserImportFailedError);
116
assert.equal(error.reason, "browserRunning");
117
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
117
+ }).pipe(Effect.provide(NodeServices.layer)),
118
);
119
});
120
apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts
+7
-7
@@ -134,7 +134,7 @@ describe("readChromiumCookieDatabase", () => {
134
const partitioned = yield* readChromiumCookieDatabase(filename, keys, "linux");
135
expect(partitioned.cookies).toEqual([]);
136
expect(partitioned.undecryptable).toBe(1);
137
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
137
+ }).pipe(Effect.provide(NodeServices.layer)),
138
);
139
140
it.effect("reads plaintext, encrypted, and genuinely empty cookie values", () =>
@@ -186,7 +186,7 @@ describe("readChromiumCookieDatabase", () => {
186
{ name: "encrypted", value: "stored encrypted" },
187
{ name: "empty", value: "" },
188
]);
189
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
189
+ }).pipe(Effect.provide(NodeServices.layer)),
190
);
191
192
it.effect("enforces domain binding only for schema 24 and newer", () =>
@@ -227,7 +227,7 @@ describe("readChromiumCookieDatabase", () => {
227
]);
228
expect(result.undecryptable).toBe(2);
229
expect(result.undecryptableHosts).toEqual(["wrong.example", "short.example"]);
230
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
230
+ }).pipe(Effect.provide(NodeServices.layer)),
231
);
232
233
it.effect("decrypts mixed v10 and v11 cookies with their respective keys", () =>
@@ -273,7 +273,7 @@ describe("readChromiumCookieDatabase", () => {
273
]);
274
expect(v10Only.undecryptable).toBe(1);
275
expect(v10Only.undecryptableHosts).toEqual(["v11.example"]);
276
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
276
+ }).pipe(Effect.provide(NodeServices.layer)),
277
);
278
279
it.effect("recovers records written with the empty-passphrase key", () =>
@@ -320,7 +320,7 @@ describe("readChromiumCookieDatabase", () => {
320
const noV11 = yield* readChromiumCookieDatabase(filename, { cbcV10, cbcEmpty }, "linux");
321
expect(noV11.cookies.map(({ name }) => name)).toEqual(["empty-v10"]);
322
expect(noV11.undecryptableHosts).toEqual(["ev11.example"]);
323
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
323
+ }).pipe(Effect.provide(NodeServices.layer)),
324
);
325
326
it.effect("treats unversioned encrypted values as legacy plaintext on macOS and Linux", () =>
@@ -355,7 +355,7 @@ describe("readChromiumCookieDatabase", () => {
355
expect(mac.undecryptable).toBe(0);
356
expect(linux.cookies[0]?.value).toBe("legacy cleartext");
357
expect(linux.undecryptable).toBe(0);
358
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
358
+ }).pipe(Effect.provide(NodeServices.layer)),
359
);
360
361
it.effect("skips partitioned cookies without breaking pre-CHIPS schemas", () =>
@@ -409,6 +409,6 @@ describe("readChromiumCookieDatabase", () => {
409
expect(chips.cookies.map(({ name }) => name)).toEqual(["plain"]);
410
expect(chips.undecryptable).toBe(1);
411
expect(chips.undecryptableHosts).toEqual(["partitioned.example"]);
412
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
412
+ }).pipe(Effect.provide(NodeServices.layer)),
413
);
414
});
apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts
+1
-1
@@ -11,7 +11,7 @@ import { snapshotCookieDatabase } from "./CookieDatabase.ts";
11
12
const runNode = <A, E>(
13
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>,
14
-) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
14
+) => effect.pipe(Effect.provide(NodeServices.layer));
15
16
describe("snapshotCookieDatabase", () => {
17
it.effect("includes committed WAL data in one consistent database", () =>
apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts
+1
-1
@@ -78,7 +78,7 @@ const writeFirefoxCookieDatabase = Effect.fnUntraced(function* (
78
});
79
80
const run = <A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | Scope.Scope>) =>
81
- effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
81
+ effect.pipe(Effect.provide(NodeServices.layer));
82
83
describe("readFirefoxCookies", () => {
84
it.effect("converts millisecond expiries from schema 16 and newer", () =>
apps/desktop/src/preview/BrowserImport/LinuxBrowserSecret.test.ts
+1
-1
@@ -64,6 +64,6 @@ it.layer(NodeServices.layer)("Linux browser secret path", (it) => {
64
assert.isUndefined(yield* resolve(false, "win32"));
65
yield* fileSystem.remove(staged);
66
assert.isUndefined(yield* resolve(false));
67
- }).pipe(Effect.scoped),
67
+ }),
68
);
69
});
apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts
+1
-1
@@ -240,7 +240,7 @@ describe("safariAccessDenied", () => {
240
yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b]));
241
assert.isFalse(yield* safariAccessDenied(jar));
242
assert.isFalse(yield* safariAccessDenied(`${directory}/absent.binarycookies`));
243
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
243
+ }).pipe(Effect.provide(NodeServices.layer)),
244
);
245
});
246
apps/desktop/src/preview/BrowserImport/SafariPermission.test.ts
+2
-2
@@ -39,7 +39,7 @@ it.effect("detects Safari access becoming available without reading or importing
39
assert.isTrue(yield* Effect.promise(check));
40
yield* fs.remove(jar);
41
assert.isFalse(yield* Effect.promise(check));
42
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
42
+ }).pipe(Effect.provide(NodeServices.layer)),
43
);
44
45
it.effect("recognizes access when cookies exist only in a named Safari profile", () =>
@@ -55,5 +55,5 @@ it.effect("recognizes access when cookies exist only in a named Safari profile",
55
yield* fs.makeDirectory(directory, { recursive: true });
56
yield* fs.writeFileString(`${directory}/Cookies.binarycookies`, "not parsed");
57
assert.isTrue(yield* Effect.promise(check));
58
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
58
+ }).pipe(Effect.provide(NodeServices.layer)),
59
);
apps/desktop/src/preview/BrowserImport/Sources.test.ts
+1
-1
@@ -51,7 +51,7 @@ const run = <A, E>(
51
E,
52
FileSystem.FileSystem | Path.Path | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner
53
>,
54
-) => effect.pipe(Effect.provide(NodeServices.layer), Effect.scoped);
54
+) => effect.pipe(Effect.provide(NodeServices.layer));
55
56
const writeCookieDatabase = (file: string, count: number) =>
57
Effect.sync(() => {
apps/desktop/src/preview/DesktopBrowserHost.test.ts
+25
-25
@@ -308,7 +308,7 @@ describe("DesktopBrowserHost", () => {
308
309
expect(reply).toMatchObject({ type: "cdp" });
310
expect(decodeCdpReply((reply as { message: string }).message).id).toBe(2);
311
- }).pipe(Effect.scoped),
311
+ }),
312
);
313
314
it.effect("sends a page one screenshot at a time", () =>
@@ -327,7 +327,7 @@ describe("DesktopBrowserHost", () => {
327
debuggee.releaseFirst();
328
expect(yield* Queue.take(replies)).toBe(1);
329
expect(debuggee.sent).toEqual([1, 3, 2]);
330
- }).pipe(Effect.scoped),
330
+ }),
331
);
332
333
it.effect("stops waiting on a screenshot the page navigated away from", () =>
@@ -352,7 +352,7 @@ describe("DesktopBrowserHost", () => {
352
debuggee.releaseFirst();
353
expect(yield* Queue.take(replies)).toBe(2);
354
expect(debuggee.sent).toEqual([1, 2, 3]);
355
- }).pipe(Effect.scoped),
355
+ }),
356
);
357
358
it.effect("drops screenshots a released relay left waiting", () =>
@@ -424,7 +424,7 @@ describe("DesktopBrowserHost", () => {
424
expect(yield* Queue.take(replies)).toBe(1);
425
yield* TestClock.adjust("1 minute");
426
expect(debuggee.focusEmulation).toEqual([true, false]);
427
- }).pipe(Effect.scoped),
427
+ }),
428
);
429
430
it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () =>
@@ -612,7 +612,7 @@ describe("DesktopBrowserHost", () => {
612
yield* turn(false);
613
yield* TestClock.adjust("1 minute");
614
expect(debuggee.focusEmulation).toEqual([true, false, true]);
615
- }).pipe(Effect.scoped),
615
+ }),
616
);
617
618
it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () =>
@@ -650,7 +650,7 @@ describe("DesktopBrowserHost", () => {
650
expect(yield* Queue.take(replies)).toBe(4);
651
yield* settle;
652
expect(painting).toEqual([true, false]);
653
- }).pipe(Effect.scoped),
653
+ }),
654
);
655
656
it.effect("stops painting for a queued screenshot once its session detaches", () =>
@@ -689,7 +689,7 @@ describe("DesktopBrowserHost", () => {
689
expect(painting).toEqual([true, false]);
690
yield* TestClock.adjust("1 minute");
691
expect(debuggee.focusEmulation).toEqual([true, false]);
692
- }).pipe(Effect.scoped),
692
+ }),
693
);
694
695
it.effect("never sends a screenshot whose session detached while focus was changing", () =>
@@ -713,7 +713,7 @@ describe("DesktopBrowserHost", () => {
713
debuggee.settleFocus();
714
yield* settle;
715
expect(debuggee.sent).toEqual([]);
716
- }).pipe(Effect.scoped),
716
+ }),
717
);
718
719
it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () =>
@@ -743,7 +743,7 @@ describe("DesktopBrowserHost", () => {
743
debuggee.release();
744
yield* settle;
745
expect(painting).toEqual([true, false]);
746
- }).pipe(Effect.scoped),
746
+ }),
747
);
748
749
it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () =>
@@ -764,7 +764,7 @@ describe("DesktopBrowserHost", () => {
764
expect(painting).toEqual([true, false]);
765
yield* TestClock.adjust("1 minute");
766
expect(debuggee.focusEmulation).toEqual([true, false]);
767
- }).pipe(Effect.scoped),
767
+ }),
768
);
769
770
it.effect("lets a guest throttle after a person's input through a viewer that then closed", () =>
@@ -793,7 +793,7 @@ describe("DesktopBrowserHost", () => {
793
yield* settle;
794
yield* TestClock.adjust("1 minute");
795
expect(debuggee.focusEmulation).toEqual([true, false]);
796
- }).pipe(Effect.scoped),
796
+ }),
797
);
798
799
it.effect("keeps a page's screencast when a child session's screencast is refused", () =>
@@ -815,7 +815,7 @@ describe("DesktopBrowserHost", () => {
815
expect(yield* Queue.take(replies)).toBe(2);
816
yield* TestClock.adjust("1 minute");
817
expect(debuggee.focusEmulation).toEqual([true]);
818
- }).pipe(Effect.scoped),
818
+ }),
819
);
820
821
it.effect("ignores a screencast that arrives on a session after it detached", () =>
@@ -841,7 +841,7 @@ describe("DesktopBrowserHost", () => {
841
yield* settle;
842
yield* TestClock.adjust("1 minute");
843
expect(debuggee.focusEmulation).toEqual([true, false]);
844
- }).pipe(Effect.scoped),
844
+ }),
845
);
846
847
it.effect("lets a guest throttle once the session waiting on its command detaches", () =>
@@ -868,7 +868,7 @@ describe("DesktopBrowserHost", () => {
868
});
869
yield* TestClock.adjust("1 minute");
870
expect(debuggee.focusEmulation).toEqual([true, false]);
871
- }).pipe(Effect.scoped),
871
+ }),
872
);
873
874
it.effect("never sends a screenshot queued by a session that has since detached", () =>
@@ -899,7 +899,7 @@ describe("DesktopBrowserHost", () => {
899
900
yield* TestClock.adjust("1 minute");
901
expect(debuggee.focusEmulation).toEqual([true, false]);
902
- }).pipe(Effect.scoped),
902
+ }),
903
);
904
905
it.effect("keeps a streamed guest focused until its screencast ends", () =>
@@ -960,7 +960,7 @@ describe("DesktopBrowserHost", () => {
960
});
961
yield* TestClock.adjust("1 minute");
962
expect(debuggee.focusEmulation).toEqual([true, false]);
963
- }).pipe(Effect.scoped),
963
+ }),
964
);
965
966
it.effect("paints a hidden guest only while the screenshot it is taking is pending", () =>
@@ -986,7 +986,7 @@ describe("DesktopBrowserHost", () => {
986
debuggee.release();
987
yield* settle;
988
expect(painting).toEqual([true, false]);
989
- }).pipe(Effect.scoped),
989
+ }),
990
);
991
992
it.effect("stops painting for a screenshot Chromium never answers once its document goes", () =>
@@ -1031,7 +1031,7 @@ describe("DesktopBrowserHost", () => {
1031
host.detach(key);
1032
yield* settle;
1033
expect(painting).toEqual([true, false, true, false, true, false, true, false]);
1034
- }).pipe(Effect.scoped),
1034
+ }),
1035
);
1036
1037
it.effect("paints a streamed guest until its last screencast ends", () =>
@@ -1062,7 +1062,7 @@ describe("DesktopBrowserHost", () => {
1062
});
1063
yield* settle;
1064
expect(painting).toEqual([true, false]);
1065
- }).pipe(Effect.scoped),
1065
+ }),
1066
);
1067
1068
it.effect("keeps a guest's one screencast running until its last streaming session stops", () =>
@@ -1099,7 +1099,7 @@ describe("DesktopBrowserHost", () => {
1099
yield* raw({ id: 6, method: "Page.stopScreencast", sessionId: "t3-preview-page-2" });
1100
yield* settle;
1101
expect(nativeStops()).toBe(1);
1102
- }).pipe(Effect.scoped),
1102
+ }),
1103
);
1104
1105
it.effect("keeps a session's screencast when another of its starts is refused", () =>
@@ -1162,7 +1162,7 @@ describe("DesktopBrowserHost", () => {
1162
debuggee.emit("Page.screencastFrame", { data: "frame", sessionId: 2 });
1163
yield* settle;
1164
expect(frames).toEqual(["t3-preview-page-1", "t3-preview-page-2"]);
1165
- }).pipe(Effect.scoped),
1165
+ }),
1166
);
1167
1168
it.effect("stops a guest's screencast once its last streaming session detaches", () =>
@@ -1201,7 +1201,7 @@ describe("DesktopBrowserHost", () => {
1201
expect(answered.toSorted()).toEqual([3, 4, 5, 6]);
1202
yield* settle;
1203
expect(nativeStops()).toBe(1);
1204
- }).pipe(Effect.scoped),
1204
+ }),
1205
);
1206
1207
it.effect("stops a screencast whose start lands after its session detached", () =>
@@ -1231,7 +1231,7 @@ describe("DesktopBrowserHost", () => {
1231
expect(debuggee.methods.at(-1), "left the late screencast running").toBe(
1232
"Page.stopScreencast",
1233
);
1234
- }).pipe(Effect.scoped),
1234
+ }),
1235
);
1236
1237
it.effect("saves a server tab's download under its CDP guid where the server asked", () =>
@@ -1266,7 +1266,7 @@ describe("DesktopBrowserHost", () => {
1266
expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(true);
1267
expect(paths).toEqual(["/srv/downloads/guid-1"]);
1268
expect(host.placeDownload(debuggee.tab.webContents, item)).toBe(false);
1269
- }).pipe(Effect.scoped),
1269
+ }),
1270
);
1271
1272
it.effect("tells a download the person clicked from one the agent's input started", () =>
@@ -1364,6 +1364,6 @@ describe("DesktopBrowserHost", () => {
1364
expect(JSON.parse((next as { message: string }).message)).toMatchObject({
1365
method: "Page.loadEventFired",
1366
});
1367
- }).pipe(Effect.scoped),
1367
+ }),
1368
);
1369
});
apps/desktop/src/preview/Manager.test.ts
+4
-4
@@ -671,7 +671,7 @@ describe("PreviewManager", () => {
671
if (existing) {
672
expect(yield* fs.readFileString(`${downloads}/report.txt`)).toBe("existing download");
673
}
674
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped),
674
+ }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
675
);
676
677
effectIt.effect.each([
@@ -2071,7 +2071,7 @@ describe("PreviewManager", () => {
2071
expect(yield* nextType).toBe("attached");
2072
yield* manager.closeTab("tab_1");
2073
expect(yield* nextType).toBe("detached");
2074
- }).pipe(Effect.provide(managerLayer()), Effect.scoped),
2074
+ }).pipe(Effect.provide(managerLayer())),
2075
);
2076
2077
effectIt.effect(
@@ -2130,7 +2130,7 @@ describe("PreviewManager", () => {
2130
expect(yield* Queue.take(capturing)).toBe(true);
2131
screenshot.resolve({ data: "" });
2132
expect(yield* Queue.take(capturing)).toBe(false);
2133
- }).pipe(Effect.provide(managerLayer()), Effect.scoped),
2133
+ }).pipe(Effect.provide(managerLayer())),
2134
);
2135
2136
effectIt.effect("reports early and subsequent load failures for the current guest", () =>
@@ -2221,7 +2221,7 @@ describe("PreviewManager", () => {
2221
expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "detached", ...serverTab });
2222
expect(JSON.parse(yield* Queue.take(lines))).toEqual({ type: "attached", ...serverTab });
2223
expect(statuses.at(-1)?.kind).toBe("Success");
2224
- }).pipe(Effect.provide(managerLayer()), Effect.scoped),
2224
+ }).pipe(Effect.provide(managerLayer())),
2225
);
2226
2227
effectIt.effect("discards a screenshot that resolves after its guest is replaced", () =>
apps/desktop/src/settings/DesktopClientSettings.test.ts
+1
-1
@@ -110,7 +110,7 @@ const withClientSettings = <A, E, R>(
110
prefix: "t3-desktop-client-settings-test-",
111
});
112
return yield* effect.pipe(Effect.provide(layer(baseDir)));
113
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped);
113
+ }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
114
115
describe("DesktopClientSettings", () => {
116
it.effect("saves through a symlinked client settings file without replacing the link", () =>
apps/desktop/src/settings/DesktopSavedEnvironments.test.ts
+1
-1
@@ -150,7 +150,7 @@ const withSavedEnvironments = <A, E, R>(
150
prefix: "t3-desktop-saved-environments-test-",
151
});
152
return yield* effect.pipe(Effect.provide(layer(baseDir, options)));
153
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
153
+ }).pipe(Effect.provide(NodeServices.layer));
154
155
describe("DesktopSavedEnvironments", () => {
156
it.effect("loads lenient saved environment registry documents", () =>
apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts
+3
-3
@@ -144,7 +144,7 @@ describe("DesktopSshPasswordPrompts", () => {
144
145
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
146
assert.equal(yield* Fiber.join(fiber), "secret");
147
- }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped);
147
+ }).pipe(Effect.provide(layer(testWindow.window)));
148
});
149
150
it.effect.each(["answered", "cancelled", "timed out", "interrupted"] as const)(
@@ -189,7 +189,7 @@ describe("DesktopSshPasswordPrompts", () => {
189
.map((message) => message.args),
190
[[request.requestId]],
191
);
192
- }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped);
192
+ }).pipe(Effect.provide(layer(testWindow.window)));
193
},
194
);
195
@@ -219,6 +219,6 @@ describe("DesktopSshPasswordPrompts", () => {
219
assert.equal(password, "secret");
220
assert.equal(testWindow.isFocused(), false);
221
assert.equal(testWindow.closedListenerCount(), 0);
222
- }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped);
222
+ }).pipe(Effect.provide(layer(testWindow.window)));
223
});
224
});
apps/desktop/src/wsl/DesktopWslServerTree.test.ts
+2
-9
@@ -6,7 +6,6 @@ import * as Layer from "effect/Layer";
6
import * as Path from "effect/Path";
7
import * as PlatformError from "effect/PlatformError";
8
import * as Ref from "effect/Ref";
9
-import * as Scope from "effect/Scope";
9
10
import * as DesktopConfig from "../app/DesktopConfig.ts";
11
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -42,20 +41,14 @@ const layerEnvironment = (input: {
41
),
42
);
43
45
-const withTempDir = <A, E, R>(
46
- run: (tempDir: string) => Effect.Effect<A, E, R>,
47
-): Effect.Effect<
48
- A,
49
- E | PlatformError.PlatformError,
50
- FileSystem.FileSystem | Exclude<R, Scope.Scope>
51
-> =>
44
+const withTempDir = <A, E, R>(run: (tempDir: string) => Effect.Effect<A, E, R>) =>
45
Effect.gen(function* () {
46
const fileSystem = yield* FileSystem.FileSystem;
47
const tempDir = yield* fileSystem.makeTempDirectoryScoped({
48
prefix: "t3-wsl-server-tree-test-",
49
});
50
return yield* run(tempDir);
58
- }).pipe(Effect.scoped);
51
+ });
52
53
const ensureWith = (input: {
54
readonly baseDir: string;
apps/mobile/src/native/nativeWebSocket.ios.test.ts
+1
-1
@@ -126,6 +126,6 @@ describe("NativeWebSocket", () => {
126
code: 1011,
127
closeReason: "boom",
128
});
129
- }).pipe(Effect.scoped),
129
+ }),
130
);
131
});
apps/mobile/src/persistence/mobile-database.test.ts
+16
-18
@@ -39,23 +39,21 @@ describe("offline pull request cache", () => {
39
}
40
41
it.effect("restores saved records and clears them with the environment", () =>
42
- Effect.scoped(
43
- Effect.gen(function* () {
44
- yield* Effect.promise(sqliteDatabase);
45
- const database = yield* MobileDatabase.make;
46
- yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}');
47
- yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other");
48
- expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual(
49
- Option.some('{"entries":[]}'),
50
- );
51
- yield* database.clearEnvironmentCache(environmentId);
52
- expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe(
53
- "None",
54
- );
55
- expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe(
56
- "Some",
57
- );
58
- }),
59
- ),
42
+ Effect.gen(function* () {
43
+ yield* Effect.promise(sqliteDatabase);
44
+ const database = yield* MobileDatabase.make;
45
+ yield* database.saveCache(environmentId, "pull-request", "v1:list", 1, '{"entries":[]}');
46
+ yield* database.saveCache(otherEnvironment, "pull-request", "v1:list", 1, "other");
47
+ expect(yield* database.loadCache(environmentId, "pull-request", "v1:list")).toEqual(
48
+ Option.some('{"entries":[]}'),
49
+ );
50
+ yield* database.clearEnvironmentCache(environmentId);
51
+ expect((yield* database.loadCache(environmentId, "pull-request", "v1:list"))._tag).toBe(
52
+ "None",
53
+ );
54
+ expect((yield* database.loadCache(otherEnvironment, "pull-request", "v1:list"))._tag).toBe(
55
+ "Some",
56
+ );
57
+ }),
58
);
59
});
apps/server/src/assets/AssetAccess.test.ts
+1
-4
@@ -1566,10 +1566,7 @@ describe("AssetAccess", () => {
1566
// A pull request's own repository wins over the checkout it is shown in.
1567
yield* sourceControlMediaResponse({ ...asset, repository: "enterprise/private" }, {});
1568
expect(fetched.at(-1)?.repository).toBe("enterprise/private");
1569
- }).pipe(
1570
- Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities)),
1571
- Effect.scoped,
1572
- );
1569
+ }).pipe(Effect.provide(Layer.mergeAll(layerTest, layerDrivers, layerIdentities)));
1570
});
1571
1572
it.effect("refuses media no host keeps behind a credential, without echoing the URL", () =>
apps/server/src/auth/RpcAuthorization.test.ts
+8
-8
@@ -135,7 +135,7 @@ describe("RPC scope middleware", () => {
135
requiredPermission: missing,
136
});
137
expect(handled).toEqual([]);
138
- }).pipe(Effect.scoped),
138
+ }),
139
);
140
});
141
@@ -191,7 +191,7 @@ it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as
191
: granted[method]({ cwd: "/repo" }).pipe(Stream.drain),
192
);
193
expect(handled).toBe(1);
194
- }).pipe(Effect.scoped),
194
+ }),
195
);
196
197
describe("settings mutation authorization", () => {
@@ -260,7 +260,7 @@ describe("settings mutation authorization", () => {
260
}).pipe(Effect.flip),
261
).toMatchObject({ requiredPermission: AuthSettingsWriteScope });
262
expect(handled).toBe(2);
263
- }).pipe(Effect.scoped),
263
+ }),
264
);
265
266
it.effect("does not let a settings grant create or remove providers or secret providers", () =>
@@ -291,7 +291,7 @@ describe("settings mutation authorization", () => {
291
}).pipe(Effect.flip),
292
).toMatchObject({ requiredPermission: AuthProvidersManageScope });
293
expect(handled).toBe(false);
294
- }).pipe(Effect.scoped),
294
+ }),
295
);
296
});
297
@@ -329,7 +329,7 @@ it.effect("requires task permission before attaching a prepared worktree to a th
329
}).pipe(Effect.flip),
330
).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope });
331
expect(handled).toBe(false);
332
- }).pipe(Effect.scoped),
332
+ }),
333
);
334
335
describe("thread context authorization", () => {
@@ -381,7 +381,7 @@ describe("thread context authorization", () => {
381
reader[WS_METHODS.gitRunStackedAction]({ ...withThread, actionId: "allowed" }),
382
);
383
expect(handled.at(-1)).toBe("allowed");
384
- }).pipe(Effect.scoped),
384
+ }),
385
);
386
});
387
@@ -429,7 +429,7 @@ it.effect("separates host file URLs from readable attachment URLs", () =>
429
});
430
}
431
expect(handled).toBe(2);
432
- }).pipe(Effect.scoped),
432
+ }),
433
);
434
435
it.effect("denies manual cleanup before the handler without settings permission", () =>
@@ -470,5 +470,5 @@ it.effect("denies manual cleanup before the handler without settings permission"
470
requiredPermission: AuthSettingsWriteScope,
471
});
472
expect(handled).toBe(false);
473
- }).pipe(Effect.scoped),
473
+ }),
474
);
apps/server/src/checkpointing/CheckpointDiffQuery.test.ts
+1
-1
@@ -300,7 +300,7 @@ it.effect("shares the turn and full-thread diff budget across real Git batches",
300
turnPatchSizes.reduce((sum, size) => sum + size, 0),
301
10_000_001,
302
);
303
- }).pipe(Effect.provide(layerTest), Effect.scoped),
303
+ }).pipe(Effect.provide(layerTest)),
304
);
305
306
it.effect("truncates a storage-cut UTF-8 character without replacement text", () => {
apps/server/src/cli/install.test.ts
+2
-2
@@ -162,7 +162,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => {
162
),
163
).pipe(Effect.flip);
164
assert.include(unrunnable.message, "has % or non-ASCII characters");
165
- }).pipe(Effect.scoped),
165
+ }),
166
);
167
168
it.effect("asks npx users without a t3 command once per minor release and installs on yes", () =>
@@ -267,7 +267,7 @@ it.layer(NodeServices.layer)("t3 install", (it) => {
267
assert.isTrue(yield* Fiber.join(unanswered));
268
assert.isTrue(yield* fs.exists(declined));
269
assert.isFalse(yield* fs.exists(link));
270
- }).pipe(Effect.scoped),
270
+ }),
271
);
272
273
it.effect("reads the terminal's foreground group from /proc and ps", () =>
apps/server/src/cli/invocation.test.ts
+4
-4
@@ -53,7 +53,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => {
53
path: yield* pathWithT3,
54
}),
55
).toBe('sudo env "PATH=$PATH" t3 browser setup');
56
- }).pipe(Effect.scoped),
56
+ }),
57
);
58
59
it.effect("keeps the arguments, so root runs setup on the same T3 home", () =>
@@ -70,7 +70,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => {
70
expect(
71
yield* rootCommand({ node: "/opt/t3/t3", entry: "/opt/t3/t3", executable: true, args }),
72
).toBe("sudo /opt/t3/t3 browser setup --base-dir '/srv/t3 home'");
73
- }).pipe(Effect.scoped),
73
+ }),
74
);
75
76
it.effect("names this install's launcher when t3 is not on PATH", () =>
@@ -143,7 +143,7 @@ it.layer(NodeServices.layer)("root CLI commands", (it) => {
143
expect(
144
yield* rootCommand({ ...desktop, env: { T3CODE_CLI_PATH: path.join(home, "gone") } }),
145
).toBe('sudo env "PATH=$PATH" t3 browser setup');
146
- }).pipe(Effect.scoped),
146
+ }),
147
);
148
});
149
@@ -184,7 +184,7 @@ it.layer(NodeServices.layer)("host CLI commands", (it) => {
184
expect((yield* hostCommand("linux", { T3CODE_CLI_PATH: shim })).command).toMatch(
185
/ doctor --base-dir 'C:\\Users\\Jane Doe\\\.t3'$/,
186
);
187
- }).pipe(Effect.scoped),
187
+ }),
188
);
189
});
190
apps/server/src/cli/project.test.ts
+2
-2
@@ -191,7 +191,7 @@ it.effect.each(["snapshot", "mutation"] as const)(
191
assert.equal(snapshotRequests, 2);
192
assert.equal(mutations, 1);
193
assert.deepEqual((yield* readProjects(baseDir)).projects, []);
194
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
194
+ }).pipe(Effect.provide(NodeServices.layer)),
195
);
196
197
it.effect("does not send a token to whatever took over a dead server's port", () =>
@@ -222,7 +222,7 @@ it.effect("does not send a token to whatever took over a dead server's port", ()
222
223
assert.equal(requests, 0);
224
assert.equal((yield* readProjects(baseDir)).projects[0]?.workspaceRoot, workspaceRoot);
225
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
225
+ }).pipe(Effect.provide(NodeServices.layer)),
226
);
227
228
const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () {
apps/server/src/cli/uninstall.test.ts
+1
-1
@@ -149,7 +149,7 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => {
149
),
150
[cmd],
151
);
152
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
152
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
153
);
154
});
155
apps/server/src/cli/update.test.ts
+7
-8
@@ -219,7 +219,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
219
220
assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
221
assert.equal(yield* fs.readLink(launcher), newExe);
222
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
222
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
223
);
224
225
it.effect.each([
@@ -285,7 +285,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
285
yield* fs.realPath(launcher),
286
yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")),
287
);
288
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
288
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
289
);
290
291
const launcherFixture = Effect.fnUntraced(function* () {
@@ -316,7 +316,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
316
});
317
318
assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
319
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
319
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
320
);
321
322
it.effect("fails instead of repointing a launcher it cannot record", () =>
@@ -334,7 +334,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
334
335
assert.isTrue(Exit.isFailure(result));
336
assert.equal(yield* fs.readLink(launcher), oldExe);
337
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
337
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
338
);
339
340
it.effect.each(["recording", "repointing"] as const)(
@@ -370,7 +370,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
370
.split("\n")
371
.includes(launcher);
372
assert.isFalse(repointed && !recorded);
373
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
373
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
374
);
375
376
it.effect("leaves a plain copy or a foreign symlink alone", () =>
@@ -403,7 +403,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
403
}
404
assert.equal(yield* fs.readLink(foreign), elsewhere);
405
assert.equal(yield* fs.readLink(otherLauncher), otherHome);
406
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
406
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
407
);
408
409
it.effect("finds the launcher a bare command name resolved to on PATH", () =>
@@ -437,7 +437,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
437
assert.equal(bare, launcher);
438
assert.equal(relative, launcher);
439
assert.equal(absent, undefined);
440
- }).pipe(Effect.scoped),
440
+ }),
441
);
442
});
443
@@ -527,7 +527,6 @@ it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
527
`Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
528
);
529
}).pipe(
530
- Effect.scoped,
530
Effect.provideService(HostProcess.Platform, "linux"),
531
Effect.provideService(HostProcess.Environment, { PATH: "" }),
532
),
apps/server/src/cloud/serviceLauncherClient.test.ts
+3
-3
@@ -238,7 +238,7 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => {
238
239
assert.equal(yield* fs.readLink(installed), exe("2.0.0"));
240
assert.equal(yield* fs.readLink(onPath), exe("2.0.0"));
241
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
241
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
242
);
243
244
it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () =>
@@ -292,7 +292,7 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => {
292
assert.include(JSON.stringify(warnings), installed);
293
assert.equal(yield* fs.readLink(installed), exe("1.0.0"));
294
assert.equal(yield* fs.readLink(onPath), exe("2.0.0"));
295
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
295
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
296
);
297
298
it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () =>
@@ -321,6 +321,6 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => {
321
322
assert.equal(yield* fs.readFileString(installed), "user-owned file");
323
assert.equal(yield* fs.readLink(onPath), foreign);
324
- }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
324
+ }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
325
);
326
});
apps/server/src/device/DeviceService.test.ts
+28
-31
@@ -379,7 +379,7 @@ describe("device setup consent", () => {
379
status: "failed",
380
detail: startupError.message,
381
});
382
- }).pipe(Effect.scoped),
382
+ }),
383
);
384
385
it.effect("names the missing npm in the host status when device support cannot install", () =>
@@ -473,7 +473,7 @@ describe("device setup consent", () => {
473
detail: expected,
474
});
475
}
476
- }).pipe(Effect.scoped),
476
+ }),
477
);
478
479
it.effect("listing and provider startup do not start helpers before consent", () =>
@@ -485,7 +485,7 @@ describe("device setup consent", () => {
485
expect(readiness._tag).toBe("Failure");
486
expect(starts).toEqual([]);
487
expect(requests).toEqual([]);
488
- }).pipe(Effect.scoped),
488
+ }),
489
);
490
491
it.effect(
@@ -505,7 +505,7 @@ describe("device setup consent", () => {
505
expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
506
expect(yield* service.readinessIfSupported()).toBeNull();
507
expect(starts).toEqual(["start", "stop"]);
508
- }).pipe(Effect.scoped),
508
+ }),
509
);
510
511
it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
@@ -522,7 +522,7 @@ describe("device setup consent", () => {
522
const state = yield* service.state;
523
expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
524
expect(state.bootingDevices).toEqual([]);
525
- }).pipe(Effect.scoped),
525
+ }),
526
);
527
528
it.effect("blocks only emulator video until ffmpeg is usable, then allows retry", () =>
@@ -604,7 +604,7 @@ describe("device setup consent", () => {
604
const emulator = yield* openEmulator;
605
expect(emulator.deviceId).toBe("emulator-5554");
606
expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
607
- }).pipe(Effect.scoped),
607
+ }),
608
);
609
610
it.effect("opens emulators on hosts that route their own streams without ffmpeg", () =>
@@ -627,7 +627,7 @@ describe("device setup consent", () => {
627
});
628
expect(session.deviceId).toBe("emulator-5554");
629
expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
630
- }).pipe(Effect.scoped),
630
+ }),
631
);
632
633
it.effect("installs agent support only after the separate agent permission", () =>
@@ -646,7 +646,7 @@ describe("device setup consent", () => {
646
expect(agentStops).toEqual(["stop"]);
647
expect((yield* service.state).onboardingCompleted).toBe(true);
648
expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
649
- }).pipe(Effect.scoped),
649
+ }),
650
);
651
});
652
@@ -726,7 +726,6 @@ it.effect.each([1, 9009])(
726
NetService.layer,
727
).pipe(Layer.provideMerge(NodeServices.layer)),
728
),
729
- Effect.scoped,
729
),
730
);
731
@@ -753,7 +752,7 @@ it.effect("publishes boot progress and does not restore sessions after support i
752
expect(state.devices).toEqual([]);
753
expect(state.sessions).toEqual([]);
754
expect(state.bootingDevices).toEqual([]);
756
- }).pipe(Effect.scoped),
755
+ }),
756
);
757
758
it.effect.each([
@@ -783,7 +782,7 @@ it.effect.each([
782
endDevice();
783
yield* service.list;
784
expect((yield* service.state).sessions).toHaveLength(kept);
786
- }).pipe(Effect.scoped),
785
+ }),
786
);
787
788
describe("device discovery after server restart", () => {
@@ -796,7 +795,7 @@ describe("device discovery after server restart", () => {
795
expect(capture.device.id).toBe("Pixel_API_35");
796
expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
797
expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
799
- }).pipe(Effect.scoped),
798
+ }),
799
);
800
});
801
@@ -817,7 +816,7 @@ it.effect("keeps other discovery warnings and clears them when only a deleted pl
816
const refreshed = yield* service.list;
817
expect(refreshed.hostStatusDetail).toBeUndefined();
818
expect(refreshed.hostStatuses.local?.detail).toBeUndefined();
820
- }).pipe(Effect.scoped),
819
+ }),
820
);
821
822
it.effect("hides Android discovery failures when the host has no Android SDK", () =>
@@ -831,7 +830,7 @@ it.effect("hides Android discovery failures when the host has no Android SDK", (
830
yield* Ref.set(androidAvailable, true);
831
const withSdk = yield* service.list;
832
expect(withSdk.hostStatusDetail).toBe(`${avdmanagerFailure.message}\niOS discovery failed.`);
834
- }).pipe(Effect.scoped),
833
+ }),
834
);
835
836
// The hub reports `error` as a util.inspect of Node's exec error.
@@ -882,7 +881,7 @@ it.effect("keeps the cause from the hub's error in discovery warnings, without t
881
);
882
expect(state.hostStatusDetail).not.toContain(" at ");
883
expect(state.hostStatusDetail).not.toContain("stderr:");
885
- }).pipe(Effect.scoped),
884
+ }),
885
);
886
887
it.effect(
@@ -916,7 +915,7 @@ it.effect(
915
const recovered = yield* service.list;
916
expect(recovered.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]);
917
expect(recovered.hostStatuses.local).toEqual({ status: "ready" });
919
- }).pipe(Effect.scoped),
918
+ }),
919
);
920
921
it.effect.each([
@@ -955,7 +954,7 @@ it.effect.each([
954
detail: "The device hub did not answer within 40 seconds.",
955
incompletePlatforms,
956
});
958
- }).pipe(Effect.scoped),
957
+ }),
958
);
959
960
it.effect("does not open a retained pre-boot entry when the post-boot listing is incomplete", () =>
@@ -977,7 +976,7 @@ it.effect("does not open a retained pre-boot entry when the post-boot listing is
976
yield* TestClock.adjust("40 seconds");
977
expect((yield* Fiber.join(opening))._tag).toBe("DeviceNotFoundError");
978
expect((yield* android.service.state).sessions).toEqual([]);
980
- }).pipe(Effect.scoped),
979
+ }),
980
);
981
982
it.effect.each([
@@ -1012,7 +1011,7 @@ it.effect.each([
1011
expect(error.message).toContain(message);
1012
expect(error.message).toContain(diagnostic);
1013
expect((yield* service.state).bootingDevices).toEqual([]);
1015
- }).pipe(Effect.scoped),
1014
+ }),
1015
);
1016
1017
// regression: #22012 report Android emulator boot failures
@@ -1040,7 +1039,7 @@ it.effect("includes nested hub boot diagnostics and bounds them to 2,000 charact
1039
const roundTrip = decodeBootError(encodeBootError(error));
1040
expect(roundTrip.message).toBe(error.message);
1041
expect((yield* service.state).bootingDevices).toEqual([]);
1043
- }).pipe(Effect.scoped),
1042
+ }),
1043
);
1044
1045
it.effect("keeps shutdown successful when subsequent discovery fails", () =>
@@ -1057,7 +1056,7 @@ it.effect("keeps shutdown successful when subsequent discovery fails", () =>
1056
const state = yield* service.state;
1057
expect(state.sessions).toEqual([]);
1058
expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
1060
- }).pipe(Effect.scoped),
1059
+ }),
1060
);
1061
1062
it.effect.each(["shutdown", "close"] as const)(
@@ -1239,7 +1238,7 @@ it.effect.each(["shutdown", "close"] as const)(
1238
yield* Fiber.join(binding);
1239
yield* Fiber.await(retiring);
1240
expect(launchers).toEqual(new Set());
1242
- }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
1241
+ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1242
);
1243
1244
it.effect("leaves a session its host leases to every thread open when one thread closes", () =>
@@ -1335,7 +1334,6 @@ it.effect("leaves a session its host leases to every thread open when one thread
1334
Effect.provide(
1335
ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
1336
),
1338
- Effect.scoped,
1337
),
1338
);
1339
@@ -1441,7 +1439,7 @@ it.effect.each([
1439
(yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
1440
).toBe(true);
1441
}
1444
- }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
1442
+ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1443
);
1444
1445
it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
@@ -1527,7 +1525,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
1525
]);
1526
expect(recovered.hostStatuses[hostId]).toEqual({ status: "ready" });
1527
if (hostId === LOCAL_DEVICE_HOST_ID) expect(recovered.hostStatusDetail).toBeUndefined();
1530
- }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
1528
+ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1529
);
1530
1531
it.effect("retry keeps device and agent consent unchanged", () =>
@@ -1543,7 +1541,7 @@ it.effect("retry keeps device and agent consent unchanged", () =>
1541
const before = agentStarts.length;
1542
yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
1543
expect(agentStarts.length).toBe(before + 1);
1546
- }).pipe(Effect.scoped),
1544
+ }),
1545
);
1546
1547
it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
@@ -1555,7 +1553,7 @@ it.effect("failed read-only discovery preserves lifecycle status and installed i
1553
expect(state.hosts[0]?.hubInstalled).toBe(true);
1554
expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
1555
expect(starts).toEqual([]);
1558
- }).pipe(Effect.scoped),
1556
+ }),
1557
);
1558
1559
it.effect(
@@ -1586,7 +1584,7 @@ it.effect(
1584
expect(requests).toEqual([]);
1585
yield* service.updateTool("hub");
1586
expect(installed).toEqual(["agent", "hub"]);
1589
- }).pipe(Effect.scoped),
1587
+ }),
1588
);
1589
1590
it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
@@ -1619,7 +1617,7 @@ it.effect("failed manual installation leaves lifecycle state unchanged and can b
1617
expect(attempts).toBe(2);
1618
expect(starts).toEqual([]);
1619
expect(agentStarts).toEqual([]);
1622
- }).pipe(Effect.scoped),
1620
+ }),
1621
);
1622
1623
it.effect("reconciles SSH host settings without publishing no-op changes", () =>
@@ -1798,7 +1796,6 @@ it.effect("a failed tool update reports npm's exit code but not its output", ()
1796
NetService.layer,
1797
).pipe(Layer.provideMerge(NodeServices.layer)),
1798
),
1801
- Effect.scoped,
1799
),
1800
);
1801
@@ -2021,7 +2018,7 @@ describe("agent session release on close", () => {
2018
)
2019
.filter((label, index, labels) => label !== labels[index - 1]);
2020
expect(published).toEqual(["none", "reopened"]);
2024
- }).pipe(Effect.scoped),
2021
+ }),
2022
);
2023
});
2024
apps/server/src/environment/DirectEndpoints.test.ts
+1
-1
@@ -366,7 +366,7 @@ describe("DirectEndpoints Tailscale Serve", () => {
366
yield* Deferred.succeed(finishRevalidation, undefined);
367
expect(yield* Fiber.join(revalidating)).toEqual([bound]);
368
expect(yield* service.resolveAvailable()).toEqual([bound]);
369
- }).pipe(Effect.scoped),
369
+ }),
370
);
371
372
effectIt.effect("leaves the tailnet name out when Serve is not forwarding", () =>
apps/server/src/environment/staleWhileRevalidate.test.ts
+4
-4
@@ -21,7 +21,7 @@ it.effect("computes once, then answers from memory until the ttl lapses", () =>
21
yield* TestClock.adjust("59 seconds");
22
assert.equal(yield* read, 1);
23
assert.equal(yield* Ref.get(calls), 1);
24
- }).pipe(Effect.scoped),
24
+ }),
25
);
26
27
it.effect("serves the stale value while one background refresh replaces it", () =>
@@ -80,7 +80,7 @@ it.effect("shares one first scan that an interrupted caller does not cancel", ()
80
yield* Deferred.succeed(release, undefined);
81
assert.equal(yield* Fiber.join(next), 1);
82
assert.equal(yield* Ref.get(calls), 1);
83
- }).pipe(Effect.scoped),
83
+ }),
84
);
85
86
it.effect("starts over after a failed first scan", () =>
@@ -98,7 +98,7 @@ it.effect("starts over after a failed first scan", () =>
98
99
assert.isTrue(Exit.isFailure(yield* Effect.exit(read)));
100
assert.equal(yield* read, 2);
101
- }).pipe(Effect.scoped),
101
+ }),
102
);
103
104
it.effect("abandons a hung refresh so a later call can start another", () =>
@@ -144,7 +144,7 @@ it.effect("abandons a hung refresh so a later call can start another", () =>
144
yield* Fiber.await(yield* Deferred.await(refreshed));
145
assert.equal(yield* Ref.get(calls), 3);
146
assert.equal(yield* read, 3);
147
- }).pipe(Effect.scoped),
147
+ }),
148
);
149
150
it.effect("interrupts a background refresh when the owning scope closes", () =>
apps/server/src/environmentTheme.test.ts
+1
-1
@@ -59,7 +59,7 @@ const withEnvironmentThemes = <A, E>(
59
),
60
),
61
);
62
- }).pipe(Effect.scoped);
62
+ });
63
64
const currentThemes = Effect.gen(function* () {
65
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
apps/server/src/htmlRender/HtmlRender.test.ts
+1
-1
@@ -622,6 +622,6 @@ fs.createReadStream(null, { fd: 3 }).on("end", quit).on("data", (chunk) => {
622
}).pipe(Effect.provide(layerHtmlRender(executable)));
623
expect(requests).toEqual([]);
624
expect(datagrams).toEqual([]);
625
- }).pipe(Effect.scoped),
625
+ }),
626
);
627
});
apps/server/src/htmlRender/publicProxy.test.ts
+3
-3
@@ -121,7 +121,7 @@ describe("publicProxy", () => {
121
const { code, socket } = yield* connectThrough(port, ipv4Target("1.1.1.1", 0));
122
socket.destroy();
123
expect(code).toBe(7);
124
- }).pipe(Effect.scoped),
124
+ }),
125
);
126
127
it.effect("refuses fake-IP names and records hosts whose every address is fake", () =>
@@ -133,7 +133,7 @@ describe("publicProxy", () => {
133
expect(code).toBe(2);
134
}
135
expect([...fakeIpHosts]).toEqual([["cdn.fake-ip.test", "198.18.2.40"]]);
136
- }).pipe(Effect.scoped),
136
+ }),
137
);
138
139
it.effect("refuses every address this machine holds, even a public one", () =>
@@ -156,7 +156,7 @@ describe("publicProxy", () => {
156
socket.destroy();
157
expect(code).toBe(2);
158
}
159
- }).pipe(Effect.scoped),
159
+ }),
160
);
161
162
it.effect("closes every connection when its scope closes", () =>
apps/server/src/mcp/McpHttpServer.test.ts
-1
@@ -268,7 +268,6 @@ it.effect.each([
268
Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
269
),
270
),
271
- Effect.scoped,
271
),
272
);
273
apps/server/src/mcp/OrchestratorMcpService.test.ts
+277
-285
@@ -2208,170 +2208,165 @@ describe("OrchestratorMcpService provider resolution", () => {
2208
])(
2209
"replays accepted creation on the $name without authorizing new disabled work",
2210
({ parentEnabled, model }) =>
2211
- Effect.scoped(
2212
- Effect.gen(function* () {
2213
- const altInstanceId = ProviderInstanceId.make("codex-alt");
2214
- const driver = ProviderDriverKind.make("codex");
2215
- const cwd = yield* checkpointWorkspace("mcp-create-retry");
2216
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(
2217
- [codexInstanceId, altInstanceId].map((instanceId) => ({
2218
- instanceId,
2219
- driver,
2220
- getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2221
- planSelectionTransition: () =>
2222
- Effect.succeed({ type: "apply_on_next_turn" as const }),
2223
- openSession: () =>
2224
- Effect.die("These tests exercise committed commands before provider execution."),
2225
- })),
2226
- );
2227
- const layerDatabase = SqlitePersistence.layerMemory;
2228
- const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
2229
- { name: "mcp-create-retry", runtimePolicyOverride: { cwd } },
2230
- layerRegistry,
2231
- { databaseLayer: layerDatabase, runEffectWorker: false },
2232
- );
2233
- const layerSettings = ServerSettings.layerTest({
2234
- providerInstances: {
2235
- [codexInstanceId]: { driver: "codex", enabled: true },
2236
- [altInstanceId]: { driver: "codex", enabled: true },
2237
- },
2238
- projectSettingsOverrides: {
2239
- [projectId]: { providerInstances: { [codexInstanceId]: { enabled: parentEnabled } } },
2240
- },
2241
- });
2242
- const layerThreads = ThreadManagementService.layer.pipe(
2243
- Layer.provideMerge(layerOrchestrator),
2244
- Layer.provide(
2245
- LegacyV1ThreadImporter.layer.pipe(
2246
- Layer.provide(layerOrchestrator),
2247
- Layer.provide(layerDatabase),
2248
- ),
2211
+ Effect.gen(function* () {
2212
+ const altInstanceId = ProviderInstanceId.make("codex-alt");
2213
+ const driver = ProviderDriverKind.make("codex");
2214
+ const cwd = yield* checkpointWorkspace("mcp-create-retry");
2215
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(
2216
+ [codexInstanceId, altInstanceId].map((instanceId) => ({
2217
+ instanceId,
2218
+ driver,
2219
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
2220
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
2221
+ openSession: () =>
2222
+ Effect.die("These tests exercise committed commands before provider execution."),
2223
+ })),
2224
+ );
2225
+ const layerDatabase = SqlitePersistence.layerMemory;
2226
+ const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
2227
+ { name: "mcp-create-retry", runtimePolicyOverride: { cwd } },
2228
+ layerRegistry,
2229
+ { databaseLayer: layerDatabase, runEffectWorker: false },
2230
+ );
2231
+ const layerSettings = ServerSettings.layerTest({
2232
+ providerInstances: {
2233
+ [codexInstanceId]: { driver: "codex", enabled: true },
2234
+ [altInstanceId]: { driver: "codex", enabled: true },
2235
+ },
2236
+ projectSettingsOverrides: {
2237
+ [projectId]: { providerInstances: { [codexInstanceId]: { enabled: parentEnabled } } },
2238
+ },
2239
+ });
2240
+ const layerThreads = ThreadManagementService.layer.pipe(
2241
+ Layer.provideMerge(layerOrchestrator),
2242
+ Layer.provide(
2243
+ LegacyV1ThreadImporter.layer.pipe(
2244
+ Layer.provide(layerOrchestrator),
2245
+ Layer.provide(layerDatabase),
2246
),
2250
- Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
2251
- Layer.provideMerge(layerSettings),
2252
- );
2253
- const layerTest = layerOrchestratorService.pipe(
2254
- Layer.provideMerge(layerThreads),
2255
- Layer.provide(
2256
- Layer.mergeAll(
2257
- NodeServices.layer,
2258
- NodeCrypto.layer,
2259
- layerRegistry,
2260
- layerSettings,
2261
- providerRegistryLayer([
2262
- providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }),
2263
- providerSnapshot({ instanceId: altInstanceId, driver, model: "gpt-5.5" }),
2264
- ]),
2265
- Layer.mock(ProjectService.ProjectService)({}),
2266
- Layer.mock(SecretRequests.SecretRequests)({}),
2267
- Layer.mock(RemoteDelegation.RemoteDelegation)({}),
2268
- Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
2269
- ),
2247
+ ),
2248
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
2249
+ Layer.provideMerge(layerSettings),
2250
+ );
2251
+ const layerTest = layerOrchestratorService.pipe(
2252
+ Layer.provideMerge(layerThreads),
2253
+ Layer.provide(
2254
+ Layer.mergeAll(
2255
+ NodeServices.layer,
2256
+ NodeCrypto.layer,
2257
+ layerRegistry,
2258
+ layerSettings,
2259
+ providerRegistryLayer([
2260
+ providerSnapshot({ instanceId: codexInstanceId, driver, model: "gpt-5.4" }),
2261
+ providerSnapshot({ instanceId: altInstanceId, driver, model: "gpt-5.5" }),
2262
+ ]),
2263
+ Layer.mock(ProjectService.ProjectService)({}),
2264
+ Layer.mock(SecretRequests.SecretRequests)({}),
2265
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
2266
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
2267
),
2271
- );
2272
- yield* Effect.gen(function* () {
2273
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2274
- const service = yield* OrchestratorMcpService.OrchestratorMcpService;
2275
- const settings = yield* ServerSettings.ServerSettingsService;
2276
- yield* orchestrator.dispatch({
2277
- type: "thread.create",
2278
- createdBy: "user",
2279
- creationSource: "web",
2280
- commandId: CommandId.make("parent:create"),
2281
- threadId: parentThreadId,
2282
- projectId,
2283
- title: "MCP parent",
2284
- modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" },
2285
- runtimeMode: "full-access",
2286
- interactionMode: "default",
2287
- branch: null,
2288
- worktreePath: cwd,
2289
- });
2290
- yield* orchestrator.dispatch({
2291
- type: "message.dispatch",
2292
- createdBy: "user",
2293
- creationSource: "web",
2294
- commandId: CommandId.make("parent:start"),
2295
- threadId: parentThreadId,
2296
- messageId: MessageId.make("parent:message"),
2297
- text: "Create a thread.",
2298
- attachments: [],
2299
- dispatchMode: { type: "start_immediately" },
2300
- });
2301
- const request = {
2302
- threads: [{ target: { driverKind: driver, model } }],
2303
- clientRequestId: "create-retry",
2304
- };
2305
- const first = yield* service.createThreads(scope, request);
2306
- const child = first.threads[0]!;
2307
- const selection = parentEnabled
2308
- ? { instanceId: codexInstanceId, model: "gpt-5.4" }
2309
- : { instanceId: altInstanceId, model: "gpt-5.5" };
2310
- assert.equal(first.threads.length, 1);
2311
- assert.equal(child.providerInstanceId, selection.instanceId);
2312
- assert.equal(child.model, selection.model);
2313
- assert.deepEqual(yield* service.createThreads(scope, request), first);
2268
+ ),
2269
+ );
2270
+ yield* Effect.gen(function* () {
2271
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2272
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
2273
+ const settings = yield* ServerSettings.ServerSettingsService;
2274
+ yield* orchestrator.dispatch({
2275
+ type: "thread.create",
2276
+ createdBy: "user",
2277
+ creationSource: "web",
2278
+ commandId: CommandId.make("parent:create"),
2279
+ threadId: parentThreadId,
2280
+ projectId,
2281
+ title: "MCP parent",
2282
+ modelSelection: { instanceId: codexInstanceId, model: "gpt-5.4" },
2283
+ runtimeMode: "full-access",
2284
+ interactionMode: "default",
2285
+ branch: null,
2286
+ worktreePath: cwd,
2287
+ });
2288
+ yield* orchestrator.dispatch({
2289
+ type: "message.dispatch",
2290
+ createdBy: "user",
2291
+ creationSource: "web",
2292
+ commandId: CommandId.make("parent:start"),
2293
+ threadId: parentThreadId,
2294
+ messageId: MessageId.make("parent:message"),
2295
+ text: "Create a thread.",
2296
+ attachments: [],
2297
+ dispatchMode: { type: "start_immediately" },
2298
+ });
2299
+ const request = {
2300
+ threads: [{ target: { driverKind: driver, model } }],
2301
+ clientRequestId: "create-retry",
2302
+ };
2303
+ const first = yield* service.createThreads(scope, request);
2304
+ const child = first.threads[0]!;
2305
+ const selection = parentEnabled
2306
+ ? { instanceId: codexInstanceId, model: "gpt-5.4" }
2307
+ : { instanceId: altInstanceId, model: "gpt-5.5" };
2308
+ assert.equal(first.threads.length, 1);
2309
+ assert.equal(child.providerInstanceId, selection.instanceId);
2310
+ assert.equal(child.model, selection.model);
2311
+ assert.deepEqual(yield* service.createThreads(scope, request), first);
2312
2315
- // The creation receipt exists, but this prompt has not been accepted yet.
2316
- const withPrompt = {
2317
- ...request,
2318
- threads: [{ ...request.threads[0]!, prompt: "Start work." }],
2319
- };
2320
- const started = yield* service.createThreads(scope, withPrompt);
2321
- assert.equal(started.threads[0]?.threadId, child.threadId);
2322
- const before = yield* orchestrator.getThreadProjection(child.threadId);
2323
- assert.deepEqual(before.runs[0]?.modelSelection, selection);
2324
- assert.equal(before.messages.length, 1);
2325
- const empty = yield* service.createThreads(scope, {
2326
- ...request,
2327
- clientRequestId: "empty",
2328
- });
2329
- const emojiAtLimit = yield* service.createThreads(scope, {
2330
- threads: [{ ...request.threads[0]!, prompt: `${"a".repeat(76)}😀 and more work.` }],
2331
- clientRequestId: "emoji-title",
2332
- });
2333
- const titled = yield* orchestrator.getThreadProjection(
2334
- emojiAtLimit.threads[0]!.threadId,
2335
- );
2336
- assert.equal(titled.thread.title, `${"a".repeat(76)}...`);
2313
+ // The creation receipt exists, but this prompt has not been accepted yet.
2314
+ const withPrompt = {
2315
+ ...request,
2316
+ threads: [{ ...request.threads[0]!, prompt: "Start work." }],
2317
+ };
2318
+ const started = yield* service.createThreads(scope, withPrompt);
2319
+ assert.equal(started.threads[0]?.threadId, child.threadId);
2320
+ const before = yield* orchestrator.getThreadProjection(child.threadId);
2321
+ assert.deepEqual(before.runs[0]?.modelSelection, selection);
2322
+ assert.equal(before.messages.length, 1);
2323
+ const empty = yield* service.createThreads(scope, {
2324
+ ...request,
2325
+ clientRequestId: "empty",
2326
+ });
2327
+ const emojiAtLimit = yield* service.createThreads(scope, {
2328
+ threads: [{ ...request.threads[0]!, prompt: `${"a".repeat(76)}😀 and more work.` }],
2329
+ clientRequestId: "emoji-title",
2330
+ });
2331
+ const titled = yield* orchestrator.getThreadProjection(emojiAtLimit.threads[0]!.threadId);
2332
+ assert.equal(titled.thread.title, `${"a".repeat(76)}...`);
2333
2338
- yield* settings.updateSettings({
2339
- projectSettingsOverrides: {
2340
- [projectId]: {
2341
- providerInstances: {
2342
- [codexInstanceId]: { enabled: false },
2343
- [altInstanceId]: { enabled: false },
2344
- },
2334
+ yield* settings.updateSettings({
2335
+ projectSettingsOverrides: {
2336
+ [projectId]: {
2337
+ providerInstances: {
2338
+ [codexInstanceId]: { enabled: false },
2339
+ [altInstanceId]: { enabled: false },
2340
},
2341
},
2347
- });
2348
- assert.deepEqual(yield* service.createThreads(scope, withPrompt), started);
2349
- const after = yield* orchestrator.getThreadProjection(child.threadId);
2350
- assert.deepEqual(after.thread.modelSelection, selection);
2351
- assert.deepEqual(after.runs, before.runs);
2352
- assert.deepEqual(after.messages, before.messages);
2342
+ },
2343
+ });
2344
+ assert.deepEqual(yield* service.createThreads(scope, withPrompt), started);
2345
+ const after = yield* orchestrator.getThreadProjection(child.threadId);
2346
+ assert.deepEqual(after.thread.modelSelection, selection);
2347
+ assert.deepEqual(after.runs, before.runs);
2348
+ assert.deepEqual(after.messages, before.messages);
2349
2354
- const freshError = yield* service
2355
- .createThreads(scope, {
2356
- ...request,
2357
- clientRequestId: "fresh",
2358
- })
2359
- .pipe(Effect.flip);
2360
- assert.equal(freshError.code, "provider_unavailable");
2361
- const promptError = yield* service
2362
- .createThreads(scope, {
2363
- ...withPrompt,
2364
- clientRequestId: "empty",
2365
- })
2366
- .pipe(Effect.flip);
2367
- assert.equal(promptError.code, "invalid_request");
2368
- assert.include(promptError.message, "disabled");
2369
- const untouched = yield* orchestrator.getThreadProjection(empty.threads[0]!.threadId);
2370
- assert.equal(untouched.messages.length, 0);
2371
- assert.equal(untouched.runs.length, 0);
2372
- }).pipe(Effect.provide(layerTest));
2373
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
2374
- ),
2350
+ const freshError = yield* service
2351
+ .createThreads(scope, {
2352
+ ...request,
2353
+ clientRequestId: "fresh",
2354
+ })
2355
+ .pipe(Effect.flip);
2356
+ assert.equal(freshError.code, "provider_unavailable");
2357
+ const promptError = yield* service
2358
+ .createThreads(scope, {
2359
+ ...withPrompt,
2360
+ clientRequestId: "empty",
2361
+ })
2362
+ .pipe(Effect.flip);
2363
+ assert.equal(promptError.code, "invalid_request");
2364
+ assert.include(promptError.message, "disabled");
2365
+ const untouched = yield* orchestrator.getThreadProjection(empty.threads[0]!.threadId);
2366
+ assert.equal(untouched.messages.length, 0);
2367
+ assert.equal(untouched.runs.length, 0);
2368
+ }).pipe(Effect.provide(layerTest));
2369
+ }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
2370
);
2371
2372
it.effect.each(["local", "remote"] as const)(
@@ -4193,140 +4188,137 @@ describe("OrchestratorMcpService thread stop", () => {
4188
stop: { reason: "Make room", message: "Stopped by an agent: Make room" },
4189
},
4190
])("t3_thread_interrupt stop reports the run it interrupted on $name", ({ queued, stop }) =>
4196
- Effect.scoped(
4197
- Effect.gen(function* () {
4198
- const cwd = yield* checkpointWorkspace("mcp-thread-stop");
4199
- const layerAdapters = ProviderAdapterRegistry.layerSingle(liveAdapter(cwd));
4200
- const layerDatabase = SqlitePersistence.layerMemory;
4201
- const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
4202
- { name: "mcp-thread-stop" },
4203
- layerAdapters,
4204
- { databaseLayer: layerDatabase, runEffectWorker: false },
4205
- );
4206
- const layerThreads = ThreadManagementService.layer.pipe(
4207
- Layer.provideMerge(layerOrchestrator),
4208
- Layer.provide(ServerSettings.layerTest()),
4209
- Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
4210
- );
4211
- const layerTest = layerOrchestratorService.pipe(
4212
- Layer.provideMerge(layerThreads),
4213
- Layer.provide(
4214
- Layer.mergeAll(
4215
- NodeServices.layer,
4216
- NodeCrypto.layer,
4217
- layerAdapters,
4218
- ServerSettings.layerTest(),
4219
- Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
4220
- Layer.mock(ProjectService.ProjectService)({}),
4221
- Layer.mock(SecretRequests.SecretRequests)({}),
4222
- Layer.mock(RemoteDelegation.RemoteDelegation)({}),
4223
- Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
4224
- ),
4191
+ Effect.gen(function* () {
4192
+ const cwd = yield* checkpointWorkspace("mcp-thread-stop");
4193
+ const layerAdapters = ProviderAdapterRegistry.layerSingle(liveAdapter(cwd));
4194
+ const layerDatabase = SqlitePersistence.layerMemory;
4195
+ const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
4196
+ { name: "mcp-thread-stop" },
4197
+ layerAdapters,
4198
+ { databaseLayer: layerDatabase, runEffectWorker: false },
4199
+ );
4200
+ const layerThreads = ThreadManagementService.layer.pipe(
4201
+ Layer.provideMerge(layerOrchestrator),
4202
+ Layer.provide(ServerSettings.layerTest()),
4203
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
4204
+ );
4205
+ const layerTest = layerOrchestratorService.pipe(
4206
+ Layer.provideMerge(layerThreads),
4207
+ Layer.provide(
4208
+ Layer.mergeAll(
4209
+ NodeServices.layer,
4210
+ NodeCrypto.layer,
4211
+ layerAdapters,
4212
+ ServerSettings.layerTest(),
4213
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
4214
+ Layer.mock(ProjectService.ProjectService)({}),
4215
+ Layer.mock(SecretRequests.SecretRequests)({}),
4216
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
4217
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
4218
),
4226
- );
4227
- yield* Effect.gen(function* () {
4228
- const orchestrator = yield* Orchestrator.OrchestratorV2;
4229
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4230
- const service = yield* OrchestratorMcpService.OrchestratorMcpService;
4231
- const send = (text: string, type: "start_immediately" | "queue_after_active") =>
4232
- orchestrator.dispatch({
4233
- type: "message.dispatch",
4234
- commandId: CommandId.make(`send:${text}`),
4235
- threadId,
4236
- messageId: MessageId.make(`message:${text}`),
4237
- text,
4238
- attachments: [],
4239
- dispatchMode: { type },
4240
- createdBy: "user",
4241
- creationSource: "web",
4242
- });
4243
- yield* orchestrator.dispatch({
4244
- type: "thread.create",
4245
- commandId: CommandId.make("create"),
4219
+ ),
4220
+ );
4221
+ yield* Effect.gen(function* () {
4222
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4223
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4224
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
4225
+ const send = (text: string, type: "start_immediately" | "queue_after_active") =>
4226
+ orchestrator.dispatch({
4227
+ type: "message.dispatch",
4228
+ commandId: CommandId.make(`send:${text}`),
4229
threadId,
4247
- projectId: ProjectId.make("project:mcp-stop"),
4248
- title: "Stop",
4249
- modelSelection,
4250
- runtimeMode: "full-access",
4251
- interactionMode: "default",
4252
- branch: null,
4253
- worktreePath: cwd,
4230
+ messageId: MessageId.make(`message:${text}`),
4231
+ text,
4232
+ attachments: [],
4233
+ dispatchMode: { type },
4234
createdBy: "user",
4235
creationSource: "web",
4236
});
4257
- const running = yield* orchestrator.streamDomainEvents.pipe(
4258
- Stream.filter(
4259
- (event) =>
4260
- event.type === "provider-turn.updated" && event.payload.status === "running",
4261
- ),
4262
- Stream.take(1),
4263
- Stream.runDrain,
4264
- Effect.forkScoped,
4265
- );
4266
- yield* send("work", "start_immediately");
4267
- yield* worker.drain();
4268
- yield* Fiber.join(running);
4269
- if (queued) yield* send("later", "queue_after_active");
4270
- const before = yield* orchestrator.getThreadProjection(threadId);
4271
- const runningRun = before.runs.find((run) => run.status === "running")!;
4272
- assert.equal(before.runs.filter((run) => run.status === "queued").length, queued ? 1 : 0);
4273
- // A task the thread delegated, running when the thread is stopped.
4274
- const childRunning = yield* orchestrator.streamDomainEvents.pipe(
4275
- Stream.filter(
4276
- (event) =>
4277
- event.type === "provider-turn.updated" &&
4278
- event.threadId !== threadId &&
4279
- event.payload.status === "running",
4280
- ),
4281
- Stream.take(1),
4282
- Stream.runDrain,
4283
- Effect.forkScoped,
4284
- );
4285
- yield* orchestrator.dispatch({
4286
- type: "delegated_task.request",
4287
- commandId: CommandId.make("delegate"),
4288
- parentThreadId: threadId,
4289
- parentRunId: runningRun.id,
4290
- parentNodeId: runningRun.rootNodeId!,
4291
- task: "child work",
4292
- modelSelection,
4293
- runtimeMode: "full-access",
4294
- interactionMode: "default",
4295
- completionWake: "always",
4296
- createdBy: "agent",
4297
- creationSource: "mcp",
4298
- });
4299
- yield* worker.drain();
4300
- yield* Fiber.join(childRunning);
4301
- const childThreadId = (yield* orchestrator.getThreadProjection(threadId)).subagents[0]!
4302
- .childThreadId!;
4237
+ yield* orchestrator.dispatch({
4238
+ type: "thread.create",
4239
+ commandId: CommandId.make("create"),
4240
+ threadId,
4241
+ projectId: ProjectId.make("project:mcp-stop"),
4242
+ title: "Stop",
4243
+ modelSelection,
4244
+ runtimeMode: "full-access",
4245
+ interactionMode: "default",
4246
+ branch: null,
4247
+ worktreePath: cwd,
4248
+ createdBy: "user",
4249
+ creationSource: "web",
4250
+ });
4251
+ const running = yield* orchestrator.streamDomainEvents.pipe(
4252
+ Stream.filter(
4253
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
4254
+ ),
4255
+ Stream.take(1),
4256
+ Stream.runDrain,
4257
+ Effect.forkScoped,
4258
+ );
4259
+ yield* send("work", "start_immediately");
4260
+ yield* worker.drain();
4261
+ yield* Fiber.join(running);
4262
+ if (queued) yield* send("later", "queue_after_active");
4263
+ const before = yield* orchestrator.getThreadProjection(threadId);
4264
+ const runningRun = before.runs.find((run) => run.status === "running")!;
4265
+ assert.equal(before.runs.filter((run) => run.status === "queued").length, queued ? 1 : 0);
4266
+ // A task the thread delegated, running when the thread is stopped.
4267
+ const childRunning = yield* orchestrator.streamDomainEvents.pipe(
4268
+ Stream.filter(
4269
+ (event) =>
4270
+ event.type === "provider-turn.updated" &&
4271
+ event.threadId !== threadId &&
4272
+ event.payload.status === "running",
4273
+ ),
4274
+ Stream.take(1),
4275
+ Stream.runDrain,
4276
+ Effect.forkScoped,
4277
+ );
4278
+ yield* orchestrator.dispatch({
4279
+ type: "delegated_task.request",
4280
+ commandId: CommandId.make("delegate"),
4281
+ parentThreadId: threadId,
4282
+ parentRunId: runningRun.id,
4283
+ parentNodeId: runningRun.rootNodeId!,
4284
+ task: "child work",
4285
+ modelSelection,
4286
+ runtimeMode: "full-access",
4287
+ interactionMode: "default",
4288
+ completionWake: "always",
4289
+ createdBy: "agent",
4290
+ creationSource: "mcp",
4291
+ });
4292
+ yield* worker.drain();
4293
+ yield* Fiber.join(childRunning);
4294
+ const childThreadId = (yield* orchestrator.getThreadProjection(threadId)).subagents[0]!
4295
+ .childThreadId!;
4296
4304
- const stopped = yield* service.interruptThread(client, {
4305
- threadId,
4306
- stop: true,
4307
- clientRequestId: "stop",
4308
- ...(stop.reason === undefined ? {} : { reason: stop.reason }),
4309
- });
4310
- assert.deepEqual(stopped, {
4311
- threadId,
4312
- runId: runningRun.id,
4313
- status: "interrupt_requested",
4314
- });
4315
- // An agent's Stop must not read as the user's, on its thread or a task it delegated.
4316
- const interruptMessages = (id: ThreadId) =>
4317
- orchestrator
4318
- .getThreadProjection(id)
4319
- .pipe(
4320
- Effect.map(({ turnItems }) =>
4321
- turnItems.flatMap((item) =>
4322
- item.type === "run_interrupt_request" ? [item.message] : [],
4323
- ),
4297
+ const stopped = yield* service.interruptThread(client, {
4298
+ threadId,
4299
+ stop: true,
4300
+ clientRequestId: "stop",
4301
+ ...(stop.reason === undefined ? {} : { reason: stop.reason }),
4302
+ });
4303
+ assert.deepEqual(stopped, {
4304
+ threadId,
4305
+ runId: runningRun.id,
4306
+ status: "interrupt_requested",
4307
+ });
4308
+ // An agent's Stop must not read as the user's, on its thread or a task it delegated.
4309
+ const interruptMessages = (id: ThreadId) =>
4310
+ orchestrator
4311
+ .getThreadProjection(id)
4312
+ .pipe(
4313
+ Effect.map(({ turnItems }) =>
4314
+ turnItems.flatMap((item) =>
4315
+ item.type === "run_interrupt_request" ? [item.message] : [],
4316
),
4325
- );
4326
- assert.deepEqual(yield* interruptMessages(threadId), [stop.message]);
4327
- assert.deepEqual(yield* interruptMessages(childThreadId), [stop.message]);
4328
- }).pipe(Effect.provide(layerTest));
4329
- }),
4330
- ),
4317
+ ),
4318
+ );
4319
+ assert.deepEqual(yield* interruptMessages(threadId), [stop.message]);
4320
+ assert.deepEqual(yield* interruptMessages(childThreadId), [stop.message]);
4321
+ }).pipe(Effect.provide(layerTest));
4322
+ }),
4323
);
4324
});
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+560
-571
@@ -207,613 +207,602 @@ describe("orchestrator MCP toolkit", () => {
207
latestSummary: "git safety ".repeat(120),
208
},
209
])("reports $label child results", ({ result, latestSummary }) =>
210
- Effect.scoped(
211
- Effect.gen(function* () {
212
- const cwd = yield* checkpointWorkspace("delegated-task-status");
213
- const rawTranscript = yield* readDelegatedTaskStatusTranscript(result);
214
- const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
215
- materializeReplayTranscriptWorkspace(rawTranscript, cwd),
216
- );
217
- const layerOrchestrator = ProviderReplayHarness.layerProviderReplay(
218
- {
219
- name: "delegated-task-status/codex",
220
- transcript,
221
- commands: [],
222
- runtimePolicyOverride: { cwd },
223
- },
224
- CodexOrchestratorReplayHarness,
225
- );
226
- // SQL spans carry no bound parameters, so this records which thread each tool read.
227
- const threadRecordReads: Array<{
228
- readonly threadId: ThreadId;
229
- readonly fields: ReadonlyArray<string>;
230
- }> = [];
231
- const layerOrchestration = Layer.merge(
232
- layerOrchestrator,
233
- Layer.effect(
234
- ThreadManagementService.ThreadManagementService,
235
- Effect.gen(function* () {
236
- const service = yield* ThreadManagementService.ThreadManagementService;
237
- return ThreadManagementService.ThreadManagementService.of({
238
- ...service,
239
- getThreadRecords: (threadId, fields, filter) =>
240
- Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe(
241
- Effect.andThen(service.getThreadRecords(threadId, fields, filter)),
242
- ),
243
- });
244
- }),
245
- ).pipe(
246
- Layer.provide(
247
- ThreadManagementService.layer.pipe(
248
- Layer.provide(layerOrchestrator),
249
- Layer.provide(ServerSettings.layerTest()),
250
- Layer.provide(
251
- CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
210
+ Effect.gen(function* () {
211
+ const cwd = yield* checkpointWorkspace("delegated-task-status");
212
+ const rawTranscript = yield* readDelegatedTaskStatusTranscript(result);
213
+ const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
214
+ materializeReplayTranscriptWorkspace(rawTranscript, cwd),
215
+ );
216
+ const layerOrchestrator = ProviderReplayHarness.layerProviderReplay(
217
+ {
218
+ name: "delegated-task-status/codex",
219
+ transcript,
220
+ commands: [],
221
+ runtimePolicyOverride: { cwd },
222
+ },
223
+ CodexOrchestratorReplayHarness,
224
+ );
225
+ // SQL spans carry no bound parameters, so this records which thread each tool read.
226
+ const threadRecordReads: Array<{
227
+ readonly threadId: ThreadId;
228
+ readonly fields: ReadonlyArray<string>;
229
+ }> = [];
230
+ const layerOrchestration = Layer.merge(
231
+ layerOrchestrator,
232
+ Layer.effect(
233
+ ThreadManagementService.ThreadManagementService,
234
+ Effect.gen(function* () {
235
+ const service = yield* ThreadManagementService.ThreadManagementService;
236
+ return ThreadManagementService.ThreadManagementService.of({
237
+ ...service,
238
+ getThreadRecords: (threadId, fields, filter) =>
239
+ Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe(
240
+ Effect.andThen(service.getThreadRecords(threadId, fields, filter)),
241
),
253
- ),
254
- ),
255
- ),
256
- );
257
- const layerProviderRegistry = ProviderRegistryMock.layer([
258
- makeProviderSnapshot({
259
- instanceId: codexInstanceId,
260
- driver: ProviderDriverKind.make("codex"),
261
- model: codexModel,
242
+ });
243
}),
263
- ]);
264
- const layerTest = layerOrchestratorToolkit.pipe(
265
- Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
266
- Layer.provideMerge(layerOrchestration),
244
+ ).pipe(
245
Layer.provide(
268
- CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe(
269
- Layer.provide(McpProviderSessions.layer),
246
+ ThreadManagementService.layer.pipe(
247
+ Layer.provide(layerOrchestrator),
248
+ Layer.provide(ServerSettings.layerTest()),
249
+ Layer.provide(
250
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
251
+ ),
252
),
253
),
272
- Layer.provide(layerProviderRegistry),
273
- Layer.provide(ServerSettings.layerTest()),
274
- Layer.provide(layerUnusedScheduledTaskStub),
275
- Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
276
- Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
277
- Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
278
- Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
279
- Layer.provideMerge(
280
- SecretRequests.layer.pipe(
281
- Layer.provide(layerMemorySecretStore),
282
- Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
283
- Layer.provide(layerOrchestration),
284
- ),
254
+ ),
255
+ );
256
+ const layerProviderRegistry = ProviderRegistryMock.layer([
257
+ makeProviderSnapshot({
258
+ instanceId: codexInstanceId,
259
+ driver: ProviderDriverKind.make("codex"),
260
+ model: codexModel,
261
+ }),
262
+ ]);
263
+ const layerTest = layerOrchestratorToolkit.pipe(
264
+ Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
265
+ Layer.provideMerge(layerOrchestration),
266
+ Layer.provide(
267
+ CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe(
268
+ Layer.provide(McpProviderSessions.layer),
269
),
286
- Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
287
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
288
- );
270
+ ),
271
+ Layer.provide(layerProviderRegistry),
272
+ Layer.provide(ServerSettings.layerTest()),
273
+ Layer.provide(layerUnusedScheduledTaskStub),
274
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
275
+ Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
276
+ Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
277
+ Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
278
+ Layer.provideMerge(
279
+ SecretRequests.layer.pipe(
280
+ Layer.provide(layerMemorySecretStore),
281
+ Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
282
+ Layer.provide(layerOrchestration),
283
+ ),
284
+ ),
285
+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
286
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
287
+ );
288
290
- yield* Effect.gen(function* () {
291
- const orchestrator = yield* Orchestrator.OrchestratorV2;
292
- const server = yield* McpServer.McpServer;
293
- const parentCreate = yield* orchestrator.dispatch({
294
- type: "thread.create",
295
- createdBy: "user",
296
- creationSource: "web",
297
- commandId: CommandId.make("command:mcp-replay-parent:create"),
289
+ yield* Effect.gen(function* () {
290
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
291
+ const server = yield* McpServer.McpServer;
292
+ const parentCreate = yield* orchestrator.dispatch({
293
+ type: "thread.create",
294
+ createdBy: "user",
295
+ creationSource: "web",
296
+ commandId: CommandId.make("command:mcp-replay-parent:create"),
297
+ threadId: parentThreadId,
298
+ projectId,
299
+ title: "MCP replay parent",
300
+ modelSelection: codexSelection,
301
+ runtimeMode: "full-access",
302
+ interactionMode: "default",
303
+ branch: null,
304
+ worktreePath: cwd,
305
+ });
306
+ yield* orchestrator.dispatch({
307
+ type: "message.dispatch",
308
+ createdBy: "user",
309
+ creationSource: "web",
310
+ commandId: CommandId.make("command:mcp-replay-parent:start"),
311
+ threadId: parentThreadId,
312
+ messageId: MessageId.make("message:mcp-replay-parent:start"),
313
+ text: parentPrompt,
314
+ attachments: [],
315
+ modelSelection: codexSelection,
316
+ dispatchMode: { type: "start_immediately" },
317
+ });
318
+ yield* orchestrator
319
+ .streamStoredEventsFrom({
320
threadId: parentThreadId,
299
- projectId,
300
- title: "MCP replay parent",
301
- modelSelection: codexSelection,
302
- runtimeMode: "full-access",
303
- interactionMode: "default",
304
- branch: null,
305
- worktreePath: cwd,
306
- });
307
- yield* orchestrator.dispatch({
308
- type: "message.dispatch",
309
- createdBy: "user",
310
- creationSource: "web",
311
- commandId: CommandId.make("command:mcp-replay-parent:start"),
321
+ afterSequence: parentCreate.sequence,
322
+ })
323
+ .pipe(
324
+ Stream.filter(
325
+ (stored) =>
326
+ stored.event.type === "provider-turn.updated" &&
327
+ stored.event.payload.status === "running",
328
+ ),
329
+ Stream.runHead,
330
+ Effect.flatMap(
331
+ Option.match({
332
+ onNone: () => Effect.die("Parent provider turn did not start."),
333
+ onSome: () => Effect.void,
334
+ }),
335
+ ),
336
+ );
337
+
338
+ const invocation: McpInvocationContext.McpInvocationScope = {
339
+ environmentId: EnvironmentId.make("environment:mcp-replay"),
340
+ requestNamespace: "mcp-provider-session-replay-parent",
341
+ thread: {
342
threadId: parentThreadId,
313
- messageId: MessageId.make("message:mcp-replay-parent:start"),
314
- text: parentPrompt,
315
- attachments: [],
316
- modelSelection: codexSelection,
317
- dispatchMode: { type: "start_immediately" },
318
- });
319
- yield* orchestrator
320
- .streamStoredEventsFrom({
321
- threadId: parentThreadId,
322
- afterSequence: parentCreate.sequence,
323
- })
343
+ providerSessionId: "mcp-provider-session-replay-parent",
344
+ providerInstanceId: codexInstanceId,
345
+ },
346
+ client: undefined,
347
+ capabilities: new Set(["orchestration"]),
348
+ issuedAt: 1,
349
+ };
350
+ const invoke = (name: string, args: Record<string, unknown>, scope = invocation) =>
351
+ server
352
+ .callTool({ name, arguments: args })
353
.pipe(
325
- Stream.filter(
326
- (stored) =>
327
- stored.event.type === "provider-turn.updated" &&
328
- stored.event.payload.status === "running",
329
- ),
330
- Stream.runHead,
331
- Effect.flatMap(
332
- Option.match({
333
- onNone: () => Effect.die("Parent provider turn did not start."),
334
- onSome: () => Effect.void,
335
- }),
336
- ),
354
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
355
+ Effect.provideService(McpSchema.McpServerClient, client),
356
);
357
339
- const invocation: McpInvocationContext.McpInvocationScope = {
340
- environmentId: EnvironmentId.make("environment:mcp-replay"),
341
- requestNamespace: "mcp-provider-session-replay-parent",
342
- thread: {
343
- threadId: parentThreadId,
344
- providerSessionId: "mcp-provider-session-replay-parent",
345
- providerInstanceId: codexInstanceId,
346
- },
347
- client: undefined,
348
- capabilities: new Set(["orchestration"]),
349
- issuedAt: 1,
350
- };
351
- const invoke = (name: string, args: Record<string, unknown>, scope = invocation) =>
352
- server
353
- .callTool({ name, arguments: args })
354
- .pipe(
355
- Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
356
- Effect.provideService(McpSchema.McpServerClient, client),
357
- );
358
-
359
- const delegationStartSequence =
360
- yield* orchestrator.getThreadEventSequence(parentThreadId);
361
- const delegatedCall = yield* invoke("delegate_task", {
362
- task: delegatedPrompt,
363
- target: {
364
- providerInstanceId: codexInstanceId,
365
- model: codexModel,
366
- },
367
- mode: "async",
368
- clientRequestId: "delegate-codex-replay-1",
369
- });
370
- const delegatedStart = yield* decodeDelegateTaskResult(
371
- delegatedCall.structuredContent,
372
- ).pipe(Effect.orDie);
373
- expect(delegatedStart.childRunId).not.toBeNull();
374
- yield* orchestrator
375
- .streamStoredEventsFrom({
376
- threadId: parentThreadId,
377
- afterSequence: delegationStartSequence,
378
- })
379
- .pipe(
380
- Stream.filter(
381
- (stored) =>
382
- stored.event.type === "context-transfer.created" &&
383
- stored.event.payload.type === "subagent_result" &&
384
- stored.event.payload.sourceThreadId === delegatedStart.childThreadId &&
385
- stored.event.payload.sourcePoint.runId === delegatedStart.childRunId,
386
- ),
387
- Stream.runHead,
388
- Effect.flatMap(
389
- Option.match({
390
- onNone: () => Effect.die("Delegated result transfer was not created."),
391
- onSome: () => Effect.void,
392
- }),
393
- ),
394
- );
395
- const delegatedStatusCall = yield* invoke("task_status", {
396
- taskId: delegatedStart.taskId,
397
- });
398
- const delegated = yield* decodeDelegateTaskResult(
399
- delegatedStatusCall.structuredContent,
400
- ).pipe(Effect.orDie);
401
- expect(delegated).toMatchObject({
402
- status: "completed",
403
- summary: delegatedResult,
358
+ const delegationStartSequence = yield* orchestrator.getThreadEventSequence(parentThreadId);
359
+ const delegatedCall = yield* invoke("delegate_task", {
360
+ task: delegatedPrompt,
361
+ target: {
362
providerInstanceId: codexInstanceId,
405
- hasPendingChildRuns: false,
406
- latestTerminalRunId: delegated.childRunId,
407
- latestTerminalStatus: "completed",
408
- latestTerminalSummary: null,
409
- latestTerminalResultContextTransferId: null,
410
- });
411
- expect(delegated.resultContextTransferId).not.toBeNull();
412
-
413
- const delegatedChild = yield* orchestrator.getThreadProjection(
414
- localChild(delegated.childThreadId),
415
- );
416
- expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent");
417
- expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false);
418
- const followupStartSequence = yield* orchestrator.getThreadEventSequence(
419
- localChild(delegated.childThreadId),
363
+ model: codexModel,
364
+ },
365
+ mode: "async",
366
+ clientRequestId: "delegate-codex-replay-1",
367
+ });
368
+ const delegatedStart = yield* decodeDelegateTaskResult(
369
+ delegatedCall.structuredContent,
370
+ ).pipe(Effect.orDie);
371
+ expect(delegatedStart.childRunId).not.toBeNull();
372
+ yield* orchestrator
373
+ .streamStoredEventsFrom({
374
+ threadId: parentThreadId,
375
+ afterSequence: delegationStartSequence,
376
+ })
377
+ .pipe(
378
+ Stream.filter(
379
+ (stored) =>
380
+ stored.event.type === "context-transfer.created" &&
381
+ stored.event.payload.type === "subagent_result" &&
382
+ stored.event.payload.sourceThreadId === delegatedStart.childThreadId &&
383
+ stored.event.payload.sourcePoint.runId === delegatedStart.childRunId,
384
+ ),
385
+ Stream.runHead,
386
+ Effect.flatMap(
387
+ Option.match({
388
+ onNone: () => Effect.die("Delegated result transfer was not created."),
389
+ onSome: () => Effect.void,
390
+ }),
391
+ ),
392
);
421
- const runningFollowupCall = yield* invoke("t3_thread_send", {
422
- threadId: localChild(delegated.childThreadId),
423
- message: cancellationPrompt,
424
- clientRequestId: "delegated-child-replay-running-1",
425
- });
426
- const runningFollowup = yield* decodeThreadSendResult(
427
- runningFollowupCall.structuredContent,
428
- ).pipe(Effect.orDie);
429
- yield* orchestrator
430
- .streamStoredEventsFrom({
431
- threadId: localChild(delegated.childThreadId),
432
- afterSequence: followupStartSequence,
433
- })
434
- .pipe(
435
- Stream.filter(
436
- (stored) =>
437
- stored.event.type === "provider-turn.updated" &&
438
- stored.event.payload.status === "running",
439
- ),
440
- Stream.runHead,
441
- Effect.flatMap(
442
- Option.match({
443
- onNone: () => Effect.die("Follow-up provider turn did not start."),
444
- onSome: () => Effect.void,
445
- }),
446
- ),
447
- );
393
+ const delegatedStatusCall = yield* invoke("task_status", {
394
+ taskId: delegatedStart.taskId,
395
+ });
396
+ const delegated = yield* decodeDelegateTaskResult(
397
+ delegatedStatusCall.structuredContent,
398
+ ).pipe(Effect.orDie);
399
+ expect(delegated).toMatchObject({
400
+ status: "completed",
401
+ summary: delegatedResult,
402
+ providerInstanceId: codexInstanceId,
403
+ hasPendingChildRuns: false,
404
+ latestTerminalRunId: delegated.childRunId,
405
+ latestTerminalStatus: "completed",
406
+ latestTerminalSummary: null,
407
+ latestTerminalResultContextTransferId: null,
408
+ });
409
+ expect(delegated.resultContextTransferId).not.toBeNull();
410
449
- const queuedFollowupCall = yield* invoke("t3_thread_send", {
411
+ const delegatedChild = yield* orchestrator.getThreadProjection(
412
+ localChild(delegated.childThreadId),
413
+ );
414
+ expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent");
415
+ expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false);
416
+ const followupStartSequence = yield* orchestrator.getThreadEventSequence(
417
+ localChild(delegated.childThreadId),
418
+ );
419
+ const runningFollowupCall = yield* invoke("t3_thread_send", {
420
+ threadId: localChild(delegated.childThreadId),
421
+ message: cancellationPrompt,
422
+ clientRequestId: "delegated-child-replay-running-1",
423
+ });
424
+ const runningFollowup = yield* decodeThreadSendResult(
425
+ runningFollowupCall.structuredContent,
426
+ ).pipe(Effect.orDie);
427
+ yield* orchestrator
428
+ .streamStoredEventsFrom({
429
threadId: localChild(delegated.childThreadId),
451
- message: queuedFollowupPrompt,
452
- mode: "queue",
453
- clientRequestId: "delegated-child-replay-queued-1",
454
- });
455
- const queuedFollowup = yield* decodeThreadSendResult(
456
- queuedFollowupCall.structuredContent,
457
- ).pipe(Effect.orDie);
458
- expect(queuedFollowup).toMatchObject({
459
- status: "queued",
460
- delivery: "queued",
461
- });
462
-
463
- const pendingProjection = yield* orchestrator.getThreadProjection(
464
- localChild(delegated.childThreadId),
465
- );
466
- const followupTasks = (yield* orchestrator.getThreadProjection(
467
- parentThreadId,
468
- )).subagents.filter(
469
- (task) =>
470
- task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId,
471
- );
472
- expect(followupTasks).toHaveLength(2);
473
- expect(followupTasks.every((task) => task.result === null)).toBe(true);
474
- expect(followupTasks.map((task) => task.id)).toEqual([
475
- runningFollowup.taskId,
476
- queuedFollowup.taskId,
477
- ]);
478
- expect(
479
- pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status,
480
- ).toBe("completed");
481
- expect(
482
- pendingProjection.runs.find((run) => run.id === runningFollowup.runId)?.status,
483
- ).toBe("running");
484
- expect(
485
- pendingProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status,
486
- ).toBe("queued");
487
- expect(
488
- (yield* orchestrator.getThreadProjection(parentThreadId)).runs.some(
489
- (run) => run.status === "running",
430
+ afterSequence: followupStartSequence,
431
+ })
432
+ .pipe(
433
+ Stream.filter(
434
+ (stored) =>
435
+ stored.event.type === "provider-turn.updated" &&
436
+ stored.event.payload.status === "running",
437
+ ),
438
+ Stream.runHead,
439
+ Effect.flatMap(
440
+ Option.match({
441
+ onNone: () => Effect.die("Follow-up provider turn did not start."),
442
+ onSome: () => Effect.void,
443
+ }),
444
),
491
- ).toBe(true);
445
+ );
446
493
- const pendingStatusCall = yield* invoke("task_status", {
494
- taskId: delegated.taskId,
495
- });
496
- const pendingStatus = yield* decodeDelegateTaskResult(
497
- pendingStatusCall.structuredContent,
498
- ).pipe(Effect.orDie);
499
- expect(pendingStatus).toMatchObject({
500
- childRunId: delegated.childRunId,
501
- status: "completed",
502
- summary: delegatedResult,
503
- resultContextTransferId: delegated.resultContextTransferId,
504
- hasPendingChildRuns: true,
505
- latestTerminalRunId: delegated.childRunId,
506
- latestTerminalStatus: "completed",
507
- latestTerminalSummary: null,
508
- latestTerminalResultContextTransferId: null,
509
- });
447
+ const queuedFollowupCall = yield* invoke("t3_thread_send", {
448
+ threadId: localChild(delegated.childThreadId),
449
+ message: queuedFollowupPrompt,
450
+ mode: "queue",
451
+ clientRequestId: "delegated-child-replay-queued-1",
452
+ });
453
+ const queuedFollowup = yield* decodeThreadSendResult(
454
+ queuedFollowupCall.structuredContent,
455
+ ).pipe(Effect.orDie);
456
+ expect(queuedFollowup).toMatchObject({
457
+ status: "queued",
458
+ delivery: "queued",
459
+ });
460
511
- const finalSequence = yield* orchestrator.getThreadEventSequence(
512
- localChild(delegated.childThreadId),
513
- );
514
- const interruptCall = yield* invoke("t3_thread_interrupt", {
515
- threadId: localChild(delegated.childThreadId),
516
- runId: runningFollowup.runId,
517
- reason: "Allow the queued replay follow-up to run.",
518
- clientRequestId: "interrupt-delegated-child-replay-1",
519
- });
520
- const interrupt = yield* decodeThreadInterruptResult(
521
- interruptCall.structuredContent,
522
- ).pipe(Effect.orDie);
523
- expect(interrupt).toMatchObject({
524
- runId: runningFollowup.runId,
525
- status: "interrupt_requested",
526
- });
527
- yield* orchestrator
528
- .streamStoredEventsFrom({
529
- threadId: localChild(delegated.childThreadId),
530
- afterSequence: finalSequence,
531
- })
532
- .pipe(
533
- Stream.filter(
534
- (stored) =>
535
- stored.event.type === "run.updated" &&
536
- stored.event.payload.id === queuedFollowup.runId &&
537
- stored.event.payload.status === "completed",
538
- ),
539
- Stream.runHead,
540
- Effect.flatMap(
541
- Option.match({
542
- onNone: () => Effect.die("Queued follow-up did not complete."),
543
- onSome: () => Effect.void,
544
- }),
545
- ),
546
- );
461
+ const pendingProjection = yield* orchestrator.getThreadProjection(
462
+ localChild(delegated.childThreadId),
463
+ );
464
+ const followupTasks = (yield* orchestrator.getThreadProjection(
465
+ parentThreadId,
466
+ )).subagents.filter(
467
+ (task) => task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId,
468
+ );
469
+ expect(followupTasks).toHaveLength(2);
470
+ expect(followupTasks.every((task) => task.result === null)).toBe(true);
471
+ expect(followupTasks.map((task) => task.id)).toEqual([
472
+ runningFollowup.taskId,
473
+ queuedFollowup.taskId,
474
+ ]);
475
+ expect(pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status).toBe(
476
+ "completed",
477
+ );
478
+ expect(pendingProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe(
479
+ "running",
480
+ );
481
+ expect(pendingProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
482
+ "queued",
483
+ );
484
+ expect(
485
+ (yield* orchestrator.getThreadProjection(parentThreadId)).runs.some(
486
+ (run) => run.status === "running",
487
+ ),
488
+ ).toBe(true);
489
548
- const finalProjection = yield* orchestrator.getThreadProjection(
549
- localChild(delegated.childThreadId),
550
- );
551
- expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe(
552
- "interrupted",
553
- );
554
- expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
555
- "completed",
490
+ const pendingStatusCall = yield* invoke("task_status", {
491
+ taskId: delegated.taskId,
492
+ });
493
+ const pendingStatus = yield* decodeDelegateTaskResult(
494
+ pendingStatusCall.structuredContent,
495
+ ).pipe(Effect.orDie);
496
+ expect(pendingStatus).toMatchObject({
497
+ childRunId: delegated.childRunId,
498
+ status: "completed",
499
+ summary: delegatedResult,
500
+ resultContextTransferId: delegated.resultContextTransferId,
501
+ hasPendingChildRuns: true,
502
+ latestTerminalRunId: delegated.childRunId,
503
+ latestTerminalStatus: "completed",
504
+ latestTerminalSummary: null,
505
+ latestTerminalResultContextTransferId: null,
506
+ });
507
+
508
+ const finalSequence = yield* orchestrator.getThreadEventSequence(
509
+ localChild(delegated.childThreadId),
510
+ );
511
+ const interruptCall = yield* invoke("t3_thread_interrupt", {
512
+ threadId: localChild(delegated.childThreadId),
513
+ runId: runningFollowup.runId,
514
+ reason: "Allow the queued replay follow-up to run.",
515
+ clientRequestId: "interrupt-delegated-child-replay-1",
516
+ });
517
+ const interrupt = yield* decodeThreadInterruptResult(interruptCall.structuredContent).pipe(
518
+ Effect.orDie,
519
+ );
520
+ expect(interrupt).toMatchObject({
521
+ runId: runningFollowup.runId,
522
+ status: "interrupt_requested",
523
+ });
524
+ yield* orchestrator
525
+ .streamStoredEventsFrom({
526
+ threadId: localChild(delegated.childThreadId),
527
+ afterSequence: finalSequence,
528
+ })
529
+ .pipe(
530
+ Stream.filter(
531
+ (stored) =>
532
+ stored.event.type === "run.updated" &&
533
+ stored.event.payload.id === queuedFollowup.runId &&
534
+ stored.event.payload.status === "completed",
535
+ ),
536
+ Stream.runHead,
537
+ Effect.flatMap(
538
+ Option.match({
539
+ onNone: () => Effect.die("Queued follow-up did not complete."),
540
+ onSome: () => Effect.void,
541
+ }),
542
+ ),
543
);
557
- expect(
558
- finalProjection.turnItems.find(
559
- (item) =>
560
- item.runId === runningFollowup.runId && item.type === "run_interrupt_result",
544
+
545
+ const finalProjection = yield* orchestrator.getThreadProjection(
546
+ localChild(delegated.childThreadId),
547
+ );
548
+ expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe(
549
+ "interrupted",
550
+ );
551
+ expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
552
+ "completed",
553
+ );
554
+ expect(
555
+ finalProjection.turnItems.find(
556
+ (item) => item.runId === runningFollowup.runId && item.type === "run_interrupt_result",
557
+ ),
558
+ ).toMatchObject({
559
+ message: "Stopped by an agent: Allow the queued replay follow-up to run.",
560
+ });
561
+ yield* orchestrator
562
+ .streamStoredEventsFrom({
563
+ threadId: parentThreadId,
564
+ afterSequence: finalSequence,
565
+ })
566
+ .pipe(
567
+ Stream.filter(
568
+ (stored) =>
569
+ stored.event.type === "subagent.updated" &&
570
+ stored.event.payload.id === followupTasks[1]!.id &&
571
+ stored.event.payload.status === "completed",
572
),
562
- ).toMatchObject({
563
- message: "Stopped by an agent: Allow the queued replay follow-up to run.",
564
- });
565
- yield* orchestrator
566
- .streamStoredEventsFrom({
567
- threadId: parentThreadId,
568
- afterSequence: finalSequence,
569
- })
570
- .pipe(
571
- Stream.filter(
572
- (stored) =>
573
- stored.event.type === "subagent.updated" &&
574
- stored.event.payload.id === followupTasks[1]!.id &&
575
- stored.event.payload.status === "completed",
576
- ),
577
- Stream.runHead,
578
- Effect.flatMap(
579
- Option.match({
580
- onNone: () => Effect.die("Follow-up task did not settle."),
581
- onSome: () => Effect.void,
582
- }),
583
- ),
584
- );
585
- const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId);
586
- expect(
587
- finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status,
588
- ).toBe("interrupted");
589
- expect(
590
- finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id),
591
- ).toMatchObject({
592
- status: "completed",
593
- result,
594
- });
595
- expect(
596
- finishedParent.contextTransfers.filter(
597
- (transfer) =>
598
- transfer.type === "subagent_result" &&
599
- transfer.sourceThreadId === delegated.childThreadId,
573
+ Stream.runHead,
574
+ Effect.flatMap(
575
+ Option.match({
576
+ onNone: () => Effect.die("Follow-up task did not settle."),
577
+ onSome: () => Effect.void,
578
+ }),
579
),
601
- ).toHaveLength(3);
602
- expect(
603
- finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id)
604
- ?.completionDelivery?.state,
605
- ).toBe("claimed");
606
- const finalStatusCall = yield* invoke("task_status", {
607
- taskId: delegated.taskId,
608
- });
609
- const finalStatus = yield* decodeDelegateTaskResult(
610
- finalStatusCall.structuredContent,
611
- ).pipe(Effect.orDie);
612
- expect(finalStatus).toMatchObject({
613
- childRunId: delegated.childRunId,
614
- status: "completed",
615
- summary: delegatedResult,
616
- resultContextTransferId: delegated.resultContextTransferId,
617
- hasPendingChildRuns: false,
618
- latestTerminalRunId: queuedFollowup.runId,
619
- latestTerminalStatus: "completed",
620
- latestTerminalSummary: latestSummary,
621
- });
622
- const followupTransfer = finishedParent.contextTransfers.find(
580
+ );
581
+ const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId);
582
+ expect(
583
+ finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status,
584
+ ).toBe("interrupted");
585
+ expect(
586
+ finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id),
587
+ ).toMatchObject({
588
+ status: "completed",
589
+ result,
590
+ });
591
+ expect(
592
+ finishedParent.contextTransfers.filter(
593
(transfer) =>
594
transfer.type === "subagent_result" &&
625
- transfer.sourcePoint.runId === queuedFollowup.runId,
626
- );
627
- expect(followupTransfer).toBeDefined();
628
- expect(finalStatus.latestTerminalResultContextTransferId).toBe(followupTransfer?.id);
629
- expect(finalStatus.latestTerminalResultContextTransferId).not.toBe(
630
- delegated.resultContextTransferId,
631
- );
632
- const transferReads: Array<string> = [];
633
- const messageReads: Array<string> = [];
634
- const runReads: Array<string> = [];
635
- const projectionTableReads: Array<string> = [];
636
- const acknowledgementReads: Array<string> = [];
637
- const tracer = Tracer.make({
638
- span(options) {
639
- const span = new Tracer.NativeSpan(options);
640
- const end = span.end.bind(span);
641
- span.end = (endTime, exit) => {
642
- end(endTime, exit);
643
- const query = span.attributes.get("db.query.text");
644
- if (typeof query !== "string") return;
645
- let parent = Option.getOrUndefined(span.parent);
646
- while (parent?._tag === "Span") {
647
- if (
648
- parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution"
649
- ) {
650
- acknowledgementReads.push(query);
651
- break;
652
- }
653
- parent = Option.getOrUndefined(parent.parent);
654
- }
655
- for (const [, table] of query.matchAll(
656
- /FROM orchestration_v2_projection_(\w+)/gi,
657
- )) {
658
- projectionTableReads.push(table!);
659
- }
660
- if (
661
- /SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query)
662
- ) {
663
- transferReads.push(query);
664
- }
665
- if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) {
666
- runReads.push(query);
667
- }
595
+ transfer.sourceThreadId === delegated.childThreadId,
596
+ ),
597
+ ).toHaveLength(3);
598
+ expect(
599
+ finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id)
600
+ ?.completionDelivery?.state,
601
+ ).toBe("claimed");
602
+ const finalStatusCall = yield* invoke("task_status", {
603
+ taskId: delegated.taskId,
604
+ });
605
+ const finalStatus = yield* decodeDelegateTaskResult(finalStatusCall.structuredContent).pipe(
606
+ Effect.orDie,
607
+ );
608
+ expect(finalStatus).toMatchObject({
609
+ childRunId: delegated.childRunId,
610
+ status: "completed",
611
+ summary: delegatedResult,
612
+ resultContextTransferId: delegated.resultContextTransferId,
613
+ hasPendingChildRuns: false,
614
+ latestTerminalRunId: queuedFollowup.runId,
615
+ latestTerminalStatus: "completed",
616
+ latestTerminalSummary: latestSummary,
617
+ });
618
+ const followupTransfer = finishedParent.contextTransfers.find(
619
+ (transfer) =>
620
+ transfer.type === "subagent_result" &&
621
+ transfer.sourcePoint.runId === queuedFollowup.runId,
622
+ );
623
+ expect(followupTransfer).toBeDefined();
624
+ expect(finalStatus.latestTerminalResultContextTransferId).toBe(followupTransfer?.id);
625
+ expect(finalStatus.latestTerminalResultContextTransferId).not.toBe(
626
+ delegated.resultContextTransferId,
627
+ );
628
+ const transferReads: Array<string> = [];
629
+ const messageReads: Array<string> = [];
630
+ const runReads: Array<string> = [];
631
+ const projectionTableReads: Array<string> = [];
632
+ const acknowledgementReads: Array<string> = [];
633
+ const tracer = Tracer.make({
634
+ span(options) {
635
+ const span = new Tracer.NativeSpan(options);
636
+ const end = span.end.bind(span);
637
+ span.end = (endTime, exit) => {
638
+ end(endTime, exit);
639
+ const query = span.attributes.get("db.query.text");
640
+ if (typeof query !== "string") return;
641
+ let parent = Option.getOrUndefined(span.parent);
642
+ while (parent?._tag === "Span") {
643
if (
669
- /SELECT\s+payload_json\s+FROM orchestration_v2_projection_messages/i.test(query)
644
+ parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution"
645
) {
671
- messageReads.push(query);
646
+ acknowledgementReads.push(query);
647
+ break;
648
}
673
- };
674
- return span;
675
- },
676
- });
677
- const wait = yield* invoke(
678
- "t3_thread_wait",
679
- { threadId: delegated.childThreadId, runId: queuedFollowup.runId },
680
- { ...invocation, thread: undefined },
681
- ).pipe(Effect.withTracer(tracer));
682
- expect(wait.isError).not.toBe(true);
683
- const expectedWait = {
649
+ parent = Option.getOrUndefined(parent.parent);
650
+ }
651
+ for (const [, table] of query.matchAll(/FROM orchestration_v2_projection_(\w+)/gi)) {
652
+ projectionTableReads.push(table!);
653
+ }
654
+ if (/SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query)) {
655
+ transferReads.push(query);
656
+ }
657
+ if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) {
658
+ runReads.push(query);
659
+ }
660
+ if (
661
+ /SELECT\s+payload_json\s+FROM orchestration_v2_projection_messages/i.test(query)
662
+ ) {
663
+ messageReads.push(query);
664
+ }
665
+ };
666
+ return span;
667
+ },
668
+ });
669
+ const wait = yield* invoke(
670
+ "t3_thread_wait",
671
+ { threadId: delegated.childThreadId, runId: queuedFollowup.runId },
672
+ { ...invocation, thread: undefined },
673
+ ).pipe(Effect.withTracer(tracer));
674
+ expect(wait.isError).not.toBe(true);
675
+ const expectedWait = {
676
+ threadId: delegated.childThreadId,
677
+ runId: queuedFollowup.runId,
678
+ status: "completed",
679
+ timedOut: false,
680
+ };
681
+ expect(wait.structuredContent).toEqual(expectedWait);
682
+ expect(messageReads).toEqual([]);
683
+ expect(transferReads).toHaveLength(0);
684
+ const settledWait = yield* invoke(
685
+ "t3_thread_wait",
686
+ {
687
threadId: delegated.childThreadId,
688
runId: queuedFollowup.runId,
686
- status: "completed",
687
- timedOut: false,
688
- };
689
- expect(wait.structuredContent).toEqual(expectedWait);
690
- expect(messageReads).toEqual([]);
691
- expect(transferReads).toHaveLength(0);
692
- const settledWait = yield* invoke(
693
- "t3_thread_wait",
694
- {
695
- threadId: delegated.childThreadId,
696
- runId: queuedFollowup.runId,
697
- untilDelegatedWorkSettled: true,
698
- },
699
- { ...invocation, thread: undefined },
700
- ).pipe(Effect.withTracer(tracer));
701
- expect(settledWait.isError).not.toBe(true);
702
- expect(settledWait.structuredContent).toMatchObject({
703
- ...expectedWait,
704
- resultRun: { runId: queuedFollowup.runId, status: "completed" },
689
+ untilDelegatedWorkSettled: true,
690
+ },
691
+ { ...invocation, thread: undefined },
692
+ ).pipe(Effect.withTracer(tracer));
693
+ expect(settledWait.isError).not.toBe(true);
694
+ expect(settledWait.structuredContent).toMatchObject({
695
+ ...expectedWait,
696
+ resultRun: { runId: queuedFollowup.runId, status: "completed" },
697
+ });
698
+ expect(messageReads.length).toBeGreaterThan(0);
699
+ expect(
700
+ messageReads.filter((query) => query.includes("$.notification.source.kind")),
701
+ ).toHaveLength(1);
702
+ // The orchestrator's restart-continuation guard still reads its own records.
703
+ expect(
704
+ messageReads.filter((query) => !query.includes("$.notification.source.kind")),
705
+ ).toHaveLength(1);
706
+ const parentlessRead = yield* invoke(
707
+ "t3_thread_read",
708
+ {
709
+ threadId: delegated.childThreadId,
710
+ limit: 100,
711
+ maxCharsPerItem: result === "😀" ? 1 : 20_000,
712
+ },
713
+ { ...invocation, thread: undefined },
714
+ ).pipe(Effect.withTracer(tracer));
715
+ expect(parentlessRead.isError).not.toBe(true);
716
+ expect(transferReads).toHaveLength(0);
717
+ const afterParentlessRead = yield* orchestrator.getThreadProjection(parentThreadId);
718
+ expect(
719
+ afterParentlessRead.subagents.find((task) => task.id === queuedFollowup.taskId)
720
+ ?.completionDelivery?.state,
721
+ ).toBe("claimed");
722
+
723
+ const read = yield* invoke("t3_thread_read", {
724
+ threadId: delegated.childThreadId,
725
+ limit: 100,
726
+ ...(result === "😀" ? { maxCharsPerItem: 1 } : {}),
727
+ }).pipe(Effect.withTracer(tracer));
728
+ expect(read.isError).not.toBe(true);
729
+ expect(transferReads.length).toBeGreaterThan(0);
730
+ const firstPage = yield* decodeThreadRead(read.structuredContent);
731
+ const finalItem = firstPage.items.find((item) => item.text === result.slice(0, 500));
732
+ expect(finalItem).toBeDefined();
733
+ if (result.length > 500) {
734
+ yield* invoke("t3_thread_read", {
735
+ threadId: delegated.childThreadId,
736
+ itemId: finalItem!.itemId,
737
+ textOffset: result.length,
738
});
706
- expect(messageReads.length).toBeGreaterThan(0);
739
+ } else {
740
+ expect(read.structuredContent).toEqual(parentlessRead.structuredContent);
741
+ }
742
+ let text = finalItem!.text ?? "";
743
+ let nextTextOffset = finalItem?.nextTextOffset ?? null;
744
+ while (nextTextOffset !== null) {
745
+ const beforeContinuation = yield* orchestrator.getThreadProjection(parentThreadId);
746
expect(
708
- messageReads.filter((query) => query.includes("$.notification.source.kind")),
709
- ).toHaveLength(1);
710
- // The orchestrator's restart-continuation guard still reads its own records.
711
- expect(
712
- messageReads.filter((query) => !query.includes("$.notification.source.kind")),
713
- ).toHaveLength(1);
714
- const parentlessRead = yield* invoke(
715
- "t3_thread_read",
716
- {
717
- threadId: delegated.childThreadId,
718
- limit: 100,
719
- maxCharsPerItem: result === "😀" ? 1 : 20_000,
720
- },
721
- { ...invocation, thread: undefined },
722
- ).pipe(Effect.withTracer(tracer));
723
- expect(parentlessRead.isError).not.toBe(true);
724
- expect(transferReads).toHaveLength(0);
725
- const afterParentlessRead = yield* orchestrator.getThreadProjection(parentThreadId);
726
- expect(
727
- afterParentlessRead.subagents.find((task) => task.id === queuedFollowup.taskId)
747
+ beforeContinuation.subagents.find((task) => task.id === queuedFollowup.taskId)
748
?.completionDelivery?.state,
749
).toBe("claimed");
730
-
731
- const read = yield* invoke("t3_thread_read", {
750
+ const continuation = yield* invoke("t3_thread_read", {
751
threadId: delegated.childThreadId,
733
- limit: 100,
734
- ...(result === "😀" ? { maxCharsPerItem: 1 } : {}),
752
+ itemId: finalItem!.itemId,
753
+ textOffset: nextTextOffset,
754
}).pipe(Effect.withTracer(tracer));
736
- expect(read.isError).not.toBe(true);
737
- expect(transferReads.length).toBeGreaterThan(0);
738
- const firstPage = yield* decodeThreadRead(read.structuredContent);
739
- const finalItem = firstPage.items.find((item) => item.text === result.slice(0, 500));
740
- expect(finalItem).toBeDefined();
741
- if (result.length > 500) {
742
- yield* invoke("t3_thread_read", {
743
- threadId: delegated.childThreadId,
744
- itemId: finalItem!.itemId,
745
- textOffset: result.length,
746
- });
747
- } else {
748
- expect(read.structuredContent).toEqual(parentlessRead.structuredContent);
749
- }
750
- let text = finalItem!.text ?? "";
751
- let nextTextOffset = finalItem?.nextTextOffset ?? null;
752
- while (nextTextOffset !== null) {
753
- const beforeContinuation = yield* orchestrator.getThreadProjection(parentThreadId);
754
- expect(
755
- beforeContinuation.subagents.find((task) => task.id === queuedFollowup.taskId)
756
- ?.completionDelivery?.state,
757
- ).toBe("claimed");
758
- const continuation = yield* invoke("t3_thread_read", {
759
- threadId: delegated.childThreadId,
760
- itemId: finalItem!.itemId,
761
- textOffset: nextTextOffset,
762
- }).pipe(Effect.withTracer(tracer));
763
- const nextPage = yield* decodeThreadRead(continuation.structuredContent);
764
- text += nextPage.items[0]?.text ?? "";
765
- nextTextOffset = nextPage.items[0]?.nextTextOffset ?? null;
766
- }
767
- expect(text).toBe(result);
768
- // The acknowledgement reads the task and its spawning run by id, not the parent's history.
769
- expect(acknowledgementReads.length).toBeGreaterThan(0);
770
- expect(
771
- acknowledgementReads.filter(
772
- (query) =>
773
- /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) ||
774
- (/FROM orchestration_v2_projection_runs\b/.test(query) &&
775
- !query.includes("AND run_id IN")) ||
776
- (/FROM orchestration_v2_projection_subagents\b/.test(query) &&
777
- !query.includes("AND subagent_id IN")),
778
- ),
779
- ).toEqual([]);
780
- const afterRead = yield* orchestrator.getThreadProjection(parentThreadId);
781
- expect(
782
- afterRead.subagents.find((task) => task.id === queuedFollowup.taskId)
783
- ?.completionDelivery?.state,
784
- ).toBe("acknowledged");
755
+ const nextPage = yield* decodeThreadRead(continuation.structuredContent);
756
+ text += nextPage.items[0]?.text ?? "";
757
+ nextTextOffset = nextPage.items[0]?.nextTextOffset ?? null;
758
+ }
759
+ expect(text).toBe(result);
760
+ // The acknowledgement reads the task and its spawning run by id, not the parent's history.
761
+ expect(acknowledgementReads.length).toBeGreaterThan(0);
762
+ expect(
763
+ acknowledgementReads.filter(
764
+ (query) =>
765
+ /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) ||
766
+ (/FROM orchestration_v2_projection_runs\b/.test(query) &&
767
+ !query.includes("AND run_id IN")) ||
768
+ (/FROM orchestration_v2_projection_subagents\b/.test(query) &&
769
+ !query.includes("AND subagent_id IN")),
770
+ ),
771
+ ).toEqual([]);
772
+ const afterRead = yield* orchestrator.getThreadProjection(parentThreadId);
773
+ expect(
774
+ afterRead.subagents.find((task) => task.id === queuedFollowup.taskId)?.completionDelivery
775
+ ?.state,
776
+ ).toBe("acknowledged");
777
786
- const messageReadsBeforeCapabilities = messageReads.length;
787
- const tableReadsBeforeCapabilities = projectionTableReads.length;
788
- const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe(
789
- Effect.withTracer(tracer),
790
- );
791
- expect(capabilities.isError).not.toBe(true);
792
- expect(messageReads).toHaveLength(messageReadsBeforeCapabilities);
793
- // The caller check reads only the thread row, never its history.
794
- expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual(
795
- new Set(["threads"]),
796
- );
797
- const runReadsBeforeStatus = runReads.length;
798
- const transferReadsBeforeStatus = transferReads.length;
799
- const threadRecordReadsBeforeStatus = threadRecordReads.length;
800
- const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe(
801
- Effect.withTracer(tracer),
802
- );
803
- expect(statusAgain.isError).not.toBe(true);
804
- // A task wait reads result transfers and runs from the child; the parent's stay unread.
805
- expect(runReads).toHaveLength(runReadsBeforeStatus + 1);
806
- expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1);
807
- expect(
808
- threadRecordReads
809
- .slice(threadRecordReadsBeforeStatus)
810
- .filter(
811
- ({ fields }) => fields.includes("runs") || fields.includes("contextTransfers"),
812
- )
813
- .map(({ threadId }) => threadId),
814
- ).toEqual([delegated.childThreadId]);
815
- }).pipe(Effect.provide(layerTest));
816
- }),
817
- ),
778
+ const messageReadsBeforeCapabilities = messageReads.length;
779
+ const tableReadsBeforeCapabilities = projectionTableReads.length;
780
+ const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe(
781
+ Effect.withTracer(tracer),
782
+ );
783
+ expect(capabilities.isError).not.toBe(true);
784
+ expect(messageReads).toHaveLength(messageReadsBeforeCapabilities);
785
+ // The caller check reads only the thread row, never its history.
786
+ expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual(
787
+ new Set(["threads"]),
788
+ );
789
+ const runReadsBeforeStatus = runReads.length;
790
+ const transferReadsBeforeStatus = transferReads.length;
791
+ const threadRecordReadsBeforeStatus = threadRecordReads.length;
792
+ const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe(
793
+ Effect.withTracer(tracer),
794
+ );
795
+ expect(statusAgain.isError).not.toBe(true);
796
+ // A task wait reads result transfers and runs from the child; the parent's stay unread.
797
+ expect(runReads).toHaveLength(runReadsBeforeStatus + 1);
798
+ expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1);
799
+ expect(
800
+ threadRecordReads
801
+ .slice(threadRecordReadsBeforeStatus)
802
+ .filter(({ fields }) => fields.includes("runs") || fields.includes("contextTransfers"))
803
+ .map(({ threadId }) => threadId),
804
+ ).toEqual([delegated.childThreadId]);
805
+ }).pipe(Effect.provide(layerTest));
806
+ }),
807
);
808
});
apps/server/src/mcp/PreviewAutomationBroker.test.ts
+790
-854
@@ -66,230 +66,220 @@ const requestsFrom = (
66
);
67
68
it.effect("atomically registers a connected host and correlates its response", () =>
69
- Effect.scoped(
70
- Effect.gen(function* () {
71
- const broker = yield* makeBroker;
72
- const requests = requestsFrom(yield* broker.connect(makeHost()));
73
- yield* Stream.runForEach(requests, (request) =>
74
- broker.respond({
75
- clientId: "client-1",
76
- connectionId: request.connectionId,
77
- requestId: request.requestId,
78
- ok: true,
79
- result: { available: true },
80
- }),
81
- ).pipe(Effect.forkScoped);
82
- yield* Effect.yieldNow;
69
+ Effect.gen(function* () {
70
+ const broker = yield* makeBroker;
71
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
72
+ yield* Stream.runForEach(requests, (request) =>
73
+ broker.respond({
74
+ clientId: "client-1",
75
+ connectionId: request.connectionId,
76
+ requestId: request.requestId,
77
+ ok: true,
78
+ result: { available: true },
79
+ }),
80
+ ).pipe(Effect.forkScoped);
81
+ yield* Effect.yieldNow;
82
84
- const result = yield* broker.invoke<{ available: boolean }>({
85
- scope,
86
- operation: "open",
87
- input: {},
88
- });
83
+ const result = yield* broker.invoke<{ available: boolean }>({
84
+ scope,
85
+ operation: "open",
86
+ input: {},
87
+ });
88
90
- expect(result).toEqual({ available: true });
91
- }),
92
- ),
89
+ expect(result).toEqual({ available: true });
90
+ }),
91
);
92
93
it.effect("targets multiple tabs explicitly while retaining a default tab", () =>
96
- Effect.scoped(
97
- Effect.gen(function* () {
98
- const broker = yield* makeBroker;
99
- const appTabId = PreviewTabId.make("tab-web-app");
100
- const simulatorTabId = PreviewTabId.make("tab-ios-simulator");
101
- const openedTabIds = [appTabId, simulatorTabId];
102
- let openIndex = 0;
103
- const routedRequests: RoutedRequest[] = [];
104
- const requests = requestsFrom(yield* broker.connect(makeHost()));
105
- yield* Stream.runForEach(requests, (request) => {
106
- routedRequests.push(request);
107
- return broker.respond({
108
- clientId: "client-1",
109
- connectionId: request.connectionId,
110
- requestId: request.requestId,
111
- ok: true,
112
- result:
113
- request.operation === "open"
114
- ? { available: true, tabId: openedTabIds[openIndex++] }
115
- : { url: "http://localhost:3200" },
116
- });
117
- }).pipe(Effect.forkScoped);
118
- yield* Effect.yieldNow;
119
-
120
- yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
121
- yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
122
- yield* broker.invoke({ scope, operation: "snapshot", input: {} });
123
- yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId });
124
- yield* broker.invoke({ scope, operation: "snapshot", input: {} });
125
-
126
- expect(routedRequests).toHaveLength(5);
127
- expect(routedRequests[0]?.tabId).toBeUndefined();
128
- expect(routedRequests[1]?.tabId).toBe(appTabId);
129
- expect(routedRequests[2]?.tabId).toBe(simulatorTabId);
130
- expect(routedRequests[2]?.tabIdExplicit).toBe(false);
131
- expect(routedRequests[3]?.tabId).toBe(appTabId);
132
- expect(routedRequests[3]?.tabIdExplicit).toBe(true);
133
- expect(routedRequests[4]?.tabId).toBe(appTabId);
134
- }),
135
- ),
94
+ Effect.gen(function* () {
95
+ const broker = yield* makeBroker;
96
+ const appTabId = PreviewTabId.make("tab-web-app");
97
+ const simulatorTabId = PreviewTabId.make("tab-ios-simulator");
98
+ const openedTabIds = [appTabId, simulatorTabId];
99
+ let openIndex = 0;
100
+ const routedRequests: RoutedRequest[] = [];
101
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
102
+ yield* Stream.runForEach(requests, (request) => {
103
+ routedRequests.push(request);
104
+ return broker.respond({
105
+ clientId: "client-1",
106
+ connectionId: request.connectionId,
107
+ requestId: request.requestId,
108
+ ok: true,
109
+ result:
110
+ request.operation === "open"
111
+ ? { available: true, tabId: openedTabIds[openIndex++] }
112
+ : { url: "http://localhost:3200" },
113
+ });
114
+ }).pipe(Effect.forkScoped);
115
+ yield* Effect.yieldNow;
116
+
117
+ yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
118
+ yield* broker.invoke({ scope, operation: "open", input: { reuseExistingTab: false } });
119
+ yield* broker.invoke({ scope, operation: "snapshot", input: {} });
120
+ yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: appTabId });
121
+ yield* broker.invoke({ scope, operation: "snapshot", input: {} });
122
+
123
+ expect(routedRequests).toHaveLength(5);
124
+ expect(routedRequests[0]?.tabId).toBeUndefined();
125
+ expect(routedRequests[1]?.tabId).toBe(appTabId);
126
+ expect(routedRequests[2]?.tabId).toBe(simulatorTabId);
127
+ expect(routedRequests[2]?.tabIdExplicit).toBe(false);
128
+ expect(routedRequests[3]?.tabId).toBe(appTabId);
129
+ expect(routedRequests[3]?.tabIdExplicit).toBe(true);
130
+ expect(routedRequests[4]?.tabId).toBe(appTabId);
131
+ }),
132
);
133
134
it.effect.each([true, false])(
135
"keeps an older target stable while a newer explicit tab responds (implicit: %s)",
136
(implicit) =>
141
- Effect.scoped(
142
- Effect.gen(function* () {
143
- const broker = yield* makeBroker;
144
- const olderTabId = PreviewTabId.make("tab-older-request");
145
- const newerTabId = PreviewTabId.make("tab-newer-request");
146
- const releaseOlderResponse = yield* Deferred.make<void>();
147
- const routedRequests: RoutedRequest[] = [];
148
- const requests = requestsFrom(yield* broker.connect(makeHost()));
149
- yield* Stream.runForEach(requests, (request) => {
150
- routedRequests.push(request);
151
- const response = Effect.gen(function* () {
152
- if (request.tabId === olderTabId && request.operation === "snapshot") {
153
- yield* Deferred.await(releaseOlderResponse);
154
- }
155
- yield* broker.respond({
156
- clientId: "client-1",
157
- connectionId: request.connectionId,
158
- requestId: request.requestId,
159
- ok: true,
160
- result: { url: "http://localhost:3200" },
161
- });
162
- if (request.tabId === newerTabId) {
163
- yield* Deferred.succeed(releaseOlderResponse, undefined);
164
- }
165
- });
166
- return response.pipe(Effect.forkScoped, Effect.asVoid);
167
- }).pipe(Effect.forkScoped);
168
- yield* Effect.yieldNow;
169
-
170
- yield* broker.invoke({ scope, operation: "status", input: {}, tabId: olderTabId });
171
- let capturedTabId: PreviewTabId | undefined;
172
- const older = yield* broker
173
- .invoke({
174
- scope,
175
- operation: "snapshot",
176
- input: {},
177
- ...(implicit ? {} : { tabId: olderTabId }),
178
- onTargetTab: (tabId) => {
179
- capturedTabId = tabId;
180
- },
181
- })
182
- .pipe(Effect.forkScoped);
183
- yield* Effect.yieldNow;
184
- const newer = yield* broker
185
- .invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId })
186
- .pipe(Effect.forkScoped);
187
- yield* Fiber.join(newer);
188
- yield* Fiber.join(older);
189
- yield* broker.invoke({
190
- scope,
191
- operation: "status",
192
- input: {},
193
- tabId: olderTabId,
194
- updateCurrentTab: false,
195
- });
196
- yield* broker.invoke({ scope, operation: "snapshot", input: {} });
197
-
198
- expect(routedRequests.at(-1)?.tabId).toBe(newerTabId);
199
- expect(capturedTabId).toBe(olderTabId);
200
- }),
201
- ),
202
-);
203
-
204
-it.effect("does not let a no-tab response suppress an earlier tab decision", () =>
205
- Effect.scoped(
137
Effect.gen(function* () {
138
const broker = yield* makeBroker;
208
- const initialTabId = PreviewTabId.make("tab-initial");
209
- const openedTabId = PreviewTabId.make("tab-opened-late");
210
- const releaseOpenResponse = yield* Deferred.make<void>();
139
+ const olderTabId = PreviewTabId.make("tab-older-request");
140
+ const newerTabId = PreviewTabId.make("tab-newer-request");
141
+ const releaseOlderResponse = yield* Deferred.make<void>();
142
const routedRequests: RoutedRequest[] = [];
143
const requests = requestsFrom(yield* broker.connect(makeHost()));
144
yield* Stream.runForEach(requests, (request) => {
145
routedRequests.push(request);
215
- const marker =
216
- typeof request.input === "object" && request.input !== null && "marker" in request.input
217
- ? request.input.marker
218
- : undefined;
146
const response = Effect.gen(function* () {
220
- if (marker === "older") {
221
- yield* Deferred.await(releaseOpenResponse);
147
+ if (request.tabId === olderTabId && request.operation === "snapshot") {
148
+ yield* Deferred.await(releaseOlderResponse);
149
}
150
yield* broker.respond({
151
clientId: "client-1",
152
connectionId: request.connectionId,
153
requestId: request.requestId,
154
ok: true,
228
- result:
229
- request.operation === "open"
230
- ? { available: true, tabId: marker === "older" ? openedTabId : initialTabId }
231
- : { url: "http://localhost:3200" },
155
+ result: { url: "http://localhost:3200" },
156
});
233
- if (marker === "newer") {
234
- yield* Deferred.succeed(releaseOpenResponse, undefined);
157
+ if (request.tabId === newerTabId) {
158
+ yield* Deferred.succeed(releaseOlderResponse, undefined);
159
}
160
});
161
return response.pipe(Effect.forkScoped, Effect.asVoid);
162
}).pipe(Effect.forkScoped);
163
yield* Effect.yieldNow;
164
241
- yield* broker.invoke({ scope, operation: "open", input: {} });
165
+ yield* broker.invoke({ scope, operation: "status", input: {}, tabId: olderTabId });
166
+ let capturedTabId: PreviewTabId | undefined;
167
const older = yield* broker
168
.invoke({
169
scope,
245
- operation: "open",
246
- input: { marker: "older", reuseExistingTab: false },
170
+ operation: "snapshot",
171
+ input: {},
172
+ ...(implicit ? {} : { tabId: olderTabId }),
173
+ onTargetTab: (tabId) => {
174
+ capturedTabId = tabId;
175
+ },
176
})
177
.pipe(Effect.forkScoped);
178
yield* Effect.yieldNow;
179
const newer = yield* broker
251
- .invoke({ scope, operation: "snapshot", input: { marker: "newer" } })
180
+ .invoke({ scope, operation: "snapshot", input: {}, tabId: newerTabId })
181
.pipe(Effect.forkScoped);
182
yield* Fiber.join(newer);
183
yield* Fiber.join(older);
184
+ yield* broker.invoke({
185
+ scope,
186
+ operation: "status",
187
+ input: {},
188
+ tabId: olderTabId,
189
+ updateCurrentTab: false,
190
+ });
191
yield* broker.invoke({ scope, operation: "snapshot", input: {} });
192
257
- expect(routedRequests.at(-1)?.tabId).toBe(openedTabId);
193
+ expect(routedRequests.at(-1)?.tabId).toBe(newerTabId);
194
+ expect(capturedTabId).toBe(olderTabId);
195
}),
259
- ),
196
+);
197
+
198
+it.effect("does not let a no-tab response suppress an earlier tab decision", () =>
199
+ Effect.gen(function* () {
200
+ const broker = yield* makeBroker;
201
+ const initialTabId = PreviewTabId.make("tab-initial");
202
+ const openedTabId = PreviewTabId.make("tab-opened-late");
203
+ const releaseOpenResponse = yield* Deferred.make<void>();
204
+ const routedRequests: RoutedRequest[] = [];
205
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
206
+ yield* Stream.runForEach(requests, (request) => {
207
+ routedRequests.push(request);
208
+ const marker =
209
+ typeof request.input === "object" && request.input !== null && "marker" in request.input
210
+ ? request.input.marker
211
+ : undefined;
212
+ const response = Effect.gen(function* () {
213
+ if (marker === "older") {
214
+ yield* Deferred.await(releaseOpenResponse);
215
+ }
216
+ yield* broker.respond({
217
+ clientId: "client-1",
218
+ connectionId: request.connectionId,
219
+ requestId: request.requestId,
220
+ ok: true,
221
+ result:
222
+ request.operation === "open"
223
+ ? { available: true, tabId: marker === "older" ? openedTabId : initialTabId }
224
+ : { url: "http://localhost:3200" },
225
+ });
226
+ if (marker === "newer") {
227
+ yield* Deferred.succeed(releaseOpenResponse, undefined);
228
+ }
229
+ });
230
+ return response.pipe(Effect.forkScoped, Effect.asVoid);
231
+ }).pipe(Effect.forkScoped);
232
+ yield* Effect.yieldNow;
233
+
234
+ yield* broker.invoke({ scope, operation: "open", input: {} });
235
+ const older = yield* broker
236
+ .invoke({
237
+ scope,
238
+ operation: "open",
239
+ input: { marker: "older", reuseExistingTab: false },
240
+ })
241
+ .pipe(Effect.forkScoped);
242
+ yield* Effect.yieldNow;
243
+ const newer = yield* broker
244
+ .invoke({ scope, operation: "snapshot", input: { marker: "newer" } })
245
+ .pipe(Effect.forkScoped);
246
+ yield* Fiber.join(newer);
247
+ yield* Fiber.join(older);
248
+ yield* broker.invoke({ scope, operation: "snapshot", input: {} });
249
+
250
+ expect(routedRequests.at(-1)?.tabId).toBe(openedTabId);
251
+ }),
252
);
253
254
it.effect("announces a live replacement stream before delivering requests", () =>
263
- Effect.scoped(
264
- Effect.gen(function* () {
265
- const broker = yield* makeBroker;
266
- const events = yield* broker.connect(makeHost());
267
- const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
268
- const consumer = yield* events.pipe(
269
- Stream.take(2),
270
- Stream.runForEach((event) => {
271
- receivedTypes.push(event.type);
272
- return event.type === "connected"
273
- ? Effect.void
274
- : broker.respond({
275
- clientId: "client-1",
276
- connectionId: event.connectionId,
277
- requestId: event.request.requestId,
278
- ok: true,
279
- result: "ready",
280
- });
281
- }),
282
- Effect.forkScoped,
283
- );
284
- yield* Effect.yieldNow;
255
+ Effect.gen(function* () {
256
+ const broker = yield* makeBroker;
257
+ const events = yield* broker.connect(makeHost());
258
+ const receivedTypes: PreviewAutomationStreamEvent["type"][] = [];
259
+ const consumer = yield* events.pipe(
260
+ Stream.take(2),
261
+ Stream.runForEach((event) => {
262
+ receivedTypes.push(event.type);
263
+ return event.type === "connected"
264
+ ? Effect.void
265
+ : broker.respond({
266
+ clientId: "client-1",
267
+ connectionId: event.connectionId,
268
+ requestId: event.request.requestId,
269
+ ok: true,
270
+ result: "ready",
271
+ });
272
+ }),
273
+ Effect.forkScoped,
274
+ );
275
+ yield* Effect.yieldNow;
276
286
- const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
287
- yield* Fiber.join(consumer);
277
+ const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
278
+ yield* Fiber.join(consumer);
279
289
- expect(receivedTypes).toEqual(["connected", "request"]);
290
- expect(result).toBe("ready");
291
- }),
292
- ),
280
+ expect(receivedTypes).toEqual(["connected", "request"]);
281
+ expect(result).toBe("ready");
282
+ }),
283
);
284
285
it.effect.each([
@@ -309,101 +299,95 @@ it.effect.each([
299
message: new PreviewBrowserRootError().message,
300
},
301
])("preserves server browser failure guidance ($clientId)", ({ clientId, shown, message }) =>
312
- Effect.scoped(
313
- Effect.gen(function* () {
314
- const broker = yield* makeBroker;
315
- const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
316
- yield* Stream.runForEach(requests, (request) =>
317
- broker.respond({
318
- clientId,
319
- connectionId: request.connectionId,
320
- requestId: request.requestId,
321
- ok: false,
322
- error: {
323
- _tag: "PreviewAutomationExecutionError",
324
- message,
325
- },
326
- }),
327
- ).pipe(Effect.forkScoped);
328
- yield* Effect.yieldNow;
329
- const error = yield* broker
330
- .invoke<void>({ scope, operation: "open", input: {} })
331
- .pipe(Effect.flip);
332
- expect(error._tag).toBe("PreviewAutomationExecutionError");
333
- expect(error.message.includes(message)).toBe(shown);
334
- }),
335
- ),
302
+ Effect.gen(function* () {
303
+ const broker = yield* makeBroker;
304
+ const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
305
+ yield* Stream.runForEach(requests, (request) =>
306
+ broker.respond({
307
+ clientId,
308
+ connectionId: request.connectionId,
309
+ requestId: request.requestId,
310
+ ok: false,
311
+ error: {
312
+ _tag: "PreviewAutomationExecutionError",
313
+ message,
314
+ },
315
+ }),
316
+ ).pipe(Effect.forkScoped);
317
+ yield* Effect.yieldNow;
318
+ const error = yield* broker
319
+ .invoke<void>({ scope, operation: "open", input: {} })
320
+ .pipe(Effect.flip);
321
+ expect(error._tag).toBe("PreviewAutomationExecutionError");
322
+ expect(error.message.includes(message)).toBe(shown);
323
+ }),
324
);
325
326
it.effect("names the click target that matched nothing when the server browser times out", () =>
339
- Effect.scoped(
340
- Effect.gen(function* () {
341
- const broker = yield* makeBroker;
342
- const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
343
- const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
344
- yield* Stream.runForEach(requests, (request) =>
345
- broker.respond({
346
- clientId,
347
- connectionId: request.connectionId,
348
- requestId: request.requestId,
349
- ok: false,
350
- error: {
351
- _tag: "PreviewAutomationTimeoutError",
352
- message: "No element matches the target.",
353
- detail: { reason: 'No element matches ".definitely-no-such-t3-target".' },
354
- },
355
- }),
356
- ).pipe(Effect.forkScoped);
357
- yield* Effect.yieldNow;
327
+ Effect.gen(function* () {
328
+ const broker = yield* makeBroker;
329
+ const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID;
330
+ const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })));
331
+ yield* Stream.runForEach(requests, (request) =>
332
+ broker.respond({
333
+ clientId,
334
+ connectionId: request.connectionId,
335
+ requestId: request.requestId,
336
+ ok: false,
337
+ error: {
338
+ _tag: "PreviewAutomationTimeoutError",
339
+ message: "No element matches the target.",
340
+ detail: { reason: 'No element matches ".definitely-no-such-t3-target".' },
341
+ },
342
+ }),
343
+ ).pipe(Effect.forkScoped);
344
+ yield* Effect.yieldNow;
345
359
- const error = yield* broker
360
- .invoke<void>({
361
- scope,
362
- operation: "click",
363
- input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 },
364
- })
365
- .pipe(Effect.flip);
346
+ const error = yield* broker
347
+ .invoke<void>({
348
+ scope,
349
+ operation: "click",
350
+ input: { selector: ".definitely-no-such-t3-target", timeoutMs: 15_000 },
351
+ })
352
+ .pipe(Effect.flip);
353
367
- expect(error._tag).toBe("PreviewAutomationTimeoutError");
368
- expect(error.message).toBe(
369
- 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".',
370
- );
371
- }),
372
- ),
354
+ expect(error._tag).toBe("PreviewAutomationTimeoutError");
355
+ expect(error.message).toBe(
356
+ 'Preview automation click timed out after 15000ms. No element matches ".definitely-no-such-t3-target".',
357
+ );
358
+ }),
359
);
360
361
it.effect("distinguishes malformed remote failures", () =>
376
- Effect.scoped(
377
- Effect.gen(function* () {
378
- const broker = yield* makeBroker;
379
- const requests = requestsFrom(yield* broker.connect(makeHost()));
380
- yield* Stream.runForEach(requests, (request) =>
381
- broker.respond({
382
- clientId: "client-1",
383
- connectionId: request.connectionId,
384
- requestId: request.requestId,
385
- ok: false,
386
- }),
387
- ).pipe(Effect.forkScoped);
388
- yield* Effect.yieldNow;
362
+ Effect.gen(function* () {
363
+ const broker = yield* makeBroker;
364
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
365
+ yield* Stream.runForEach(requests, (request) =>
366
+ broker.respond({
367
+ clientId: "client-1",
368
+ connectionId: request.connectionId,
369
+ requestId: request.requestId,
370
+ ok: false,
371
+ }),
372
+ ).pipe(Effect.forkScoped);
373
+ yield* Effect.yieldNow;
374
390
- const error = yield* broker
391
- .invoke<void>({ scope, operation: "status", input: {}, timeoutMs: 2_000 })
392
- .pipe(Effect.flip);
375
+ const error = yield* broker
376
+ .invoke<void>({ scope, operation: "status", input: {}, timeoutMs: 2_000 })
377
+ .pipe(Effect.flip);
378
394
- expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);
395
- expect(error).toMatchObject({
396
- operation: "status",
397
- environmentId: scope.environmentId,
398
- threadId: scope.thread.threadId,
399
- providerSessionId: scope.thread.providerSessionId,
400
- providerInstanceId: scope.thread.providerInstanceId,
401
- clientId: "client-1",
402
- requestId: "preview-0",
403
- timeoutMs: 2_000,
404
- });
405
- }),
406
- ),
379
+ expect(error).toBeInstanceOf(PreviewAutomationMalformedResponseError);
380
+ expect(error).toMatchObject({
381
+ operation: "status",
382
+ environmentId: scope.environmentId,
383
+ threadId: scope.thread.threadId,
384
+ providerSessionId: scope.thread.providerSessionId,
385
+ providerInstanceId: scope.thread.providerInstanceId,
386
+ clientId: "client-1",
387
+ requestId: "preview-0",
388
+ timeoutMs: 2_000,
389
+ });
390
+ }),
391
);
392
393
it.effect("does not create host state from focus updates without a live stream", () =>
@@ -424,665 +408,617 @@ it.effect("does not create host state from focus updates without a live stream",
408
);
409
410
it.effect("removes host availability when the authoritative request stream disconnects", () =>
427
- Effect.scoped(
428
- Effect.gen(function* () {
429
- const broker = yield* makeBroker;
430
- const requests = requestsFrom(yield* broker.connect(makeHost()));
431
- const beforeAcquisition = yield* broker
432
- .invoke<void>({ scope, operation: "status", input: {} })
433
- .pipe(Effect.flip);
434
- expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
411
+ Effect.gen(function* () {
412
+ const broker = yield* makeBroker;
413
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
414
+ const beforeAcquisition = yield* broker
415
+ .invoke<void>({ scope, operation: "status", input: {} })
416
+ .pipe(Effect.flip);
417
+ expect(beforeAcquisition).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
418
436
- const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
437
- yield* Effect.yieldNow;
438
- yield* Fiber.interrupt(consumer);
419
+ const consumer = yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
420
+ yield* Effect.yieldNow;
421
+ yield* Fiber.interrupt(consumer);
422
440
- const error = yield* broker
441
- .invoke<void>({ scope, operation: "status", input: {} })
442
- .pipe(Effect.flip);
443
- expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
444
- }),
445
- ),
423
+ const error = yield* broker
424
+ .invoke<void>({ scope, operation: "status", input: {} })
425
+ .pipe(Effect.flip);
426
+ expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
427
+ }),
428
);
429
430
it.effect("routes requests for background threads through an environment-level host", () =>
449
- Effect.scoped(
450
- Effect.gen(function* () {
451
- const broker = yield* makeBroker;
452
- const backgroundThreadId = ThreadId.make("thread-background");
453
- const requests = requestsFrom(yield* broker.connect(makeHost()));
454
- let routedThreadId: string | undefined;
455
- yield* Stream.runForEach(requests, (request) => {
456
- routedThreadId = request.threadId;
457
- return broker.respond({
458
- clientId: "client-1",
459
- connectionId: request.connectionId,
460
- requestId: request.requestId,
461
- ok: true,
462
- result: "background",
463
- });
464
- }).pipe(Effect.forkScoped);
465
- yield* Effect.yieldNow;
431
+ Effect.gen(function* () {
432
+ const broker = yield* makeBroker;
433
+ const backgroundThreadId = ThreadId.make("thread-background");
434
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
435
+ let routedThreadId: string | undefined;
436
+ yield* Stream.runForEach(requests, (request) => {
437
+ routedThreadId = request.threadId;
438
+ return broker.respond({
439
+ clientId: "client-1",
440
+ connectionId: request.connectionId,
441
+ requestId: request.requestId,
442
+ ok: true,
443
+ result: "background",
444
+ });
445
+ }).pipe(Effect.forkScoped);
446
+ yield* Effect.yieldNow;
447
+
448
+ const result = yield* broker.invoke<string>({
449
+ scope: {
450
+ ...scope,
451
+ thread: {
452
+ ...scope.thread,
453
+ threadId: backgroundThreadId,
454
+ providerSessionId: "provider-session-background",
455
+ },
456
+ },
457
+ operation: "status",
458
+ input: {},
459
+ });
460
+
461
+ expect(result).toBe("background");
462
+ expect(routedThreadId).toBe(backgroundThreadId);
463
+ }),
464
+);
465
+
466
+it.effect("never routes a provider session to a host from another environment", () =>
467
+ Effect.gen(function* () {
468
+ const broker = yield* makeBroker;
469
+ const matchingRequests = requestsFrom(
470
+ yield* broker.connect(makeHost({ clientId: "client-matching" })),
471
+ );
472
+ const foreignRequests = requestsFrom(
473
+ yield* broker.connect(
474
+ makeHost({
475
+ clientId: "client-foreign",
476
+ environmentId: EnvironmentId.make("environment-foreign"),
477
+ }),
478
+ ),
479
+ );
480
+ yield* Stream.runForEach(matchingRequests, (request) =>
481
+ broker.respond({
482
+ clientId: "client-matching",
483
+ connectionId: request.connectionId,
484
+ requestId: request.requestId,
485
+ ok: true,
486
+ result: "matching",
487
+ }),
488
+ ).pipe(Effect.forkScoped);
489
+ yield* Stream.runForEach(foreignRequests, (request) =>
490
+ broker.respond({
491
+ clientId: "client-foreign",
492
+ connectionId: request.connectionId,
493
+ requestId: request.requestId,
494
+ ok: true,
495
+ result: "foreign",
496
+ }),
497
+ ).pipe(Effect.forkScoped);
498
+ yield* Effect.yieldNow;
499
+
500
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
501
+ "matching",
502
+ );
503
+ }),
504
+);
505
+
506
+it.effect("pins a provider session to its initial host despite later focus changes", () =>
507
+ Effect.gen(function* () {
508
+ const broker = yield* makeBroker;
509
+ let firstConnectionId = "";
510
+ let secondConnectionId = "";
511
+ const firstRequests = requestsFrom(
512
+ yield* broker.connect(makeHost({ clientId: "client-first" })),
513
+ (connectionId) => {
514
+ firstConnectionId = connectionId;
515
+ },
516
+ );
517
+ const secondRequests = requestsFrom(
518
+ yield* broker.connect(makeHost({ clientId: "client-second" })),
519
+ (connectionId) => {
520
+ secondConnectionId = connectionId;
521
+ },
522
+ );
523
+ yield* Stream.runForEach(firstRequests, (request) =>
524
+ broker.respond({
525
+ clientId: "client-first",
526
+ connectionId: request.connectionId,
527
+ requestId: request.requestId,
528
+ ok: true,
529
+ result: "first",
530
+ }),
531
+ ).pipe(Effect.forkScoped);
532
+ yield* Stream.runForEach(secondRequests, (request) =>
533
+ broker.respond({
534
+ clientId: "client-second",
535
+ connectionId: request.connectionId,
536
+ requestId: request.requestId,
537
+ ok: true,
538
+ result: "second",
539
+ }),
540
+ ).pipe(Effect.forkScoped);
541
+ yield* Effect.yieldNow;
542
+
543
+ yield* broker.focusHost({
544
+ clientId: "client-first",
545
+ environmentId: scope.environmentId,
546
+ connectionId: "connection-stale",
547
+ focused: true,
548
+ liveTabs: [{ threadId: scope.thread.threadId, tabId: PreviewTabId.make("stale-tab") }],
549
+ });
550
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
551
+ yield* broker.focusHost({
552
+ clientId: "client-first",
553
+ environmentId: scope.environmentId,
554
+ connectionId: firstConnectionId,
555
+ focused: true,
556
+ });
557
467
- const result = yield* broker.invoke<string>({
558
+ const firstPinnedScope = {
559
+ ...scope,
560
+ thread: { ...scope.thread, providerSessionId: "provider-session-first-pinned" },
561
+ };
562
+ expect(
563
+ yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
564
+ ).toBe("first");
565
+
566
+ yield* broker.focusHost({
567
+ clientId: "client-second",
568
+ environmentId: scope.environmentId,
569
+ connectionId: secondConnectionId,
570
+ focused: true,
571
+ });
572
+
573
+ expect(
574
+ yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
575
+ ).toBe("first");
576
+ expect(
577
+ yield* broker.invoke<string>({
578
scope: {
579
...scope,
470
- thread: {
471
- ...scope.thread,
472
- threadId: backgroundThreadId,
473
- providerSessionId: "provider-session-background",
474
- },
580
+ thread: { ...scope.thread, providerSessionId: "provider-session-second-pinned" },
581
},
582
operation: "status",
583
input: {},
478
- });
479
-
480
- expect(result).toBe("background");
481
- expect(routedThreadId).toBe(backgroundThreadId);
482
- }),
483
- ),
584
+ }),
585
+ ).toBe("second");
586
+ }),
587
);
588
486
-it.effect("never routes a provider session to a host from another environment", () =>
487
- Effect.scoped(
488
- Effect.gen(function* () {
489
- const broker = yield* makeBroker;
490
- const matchingRequests = requestsFrom(
491
- yield* broker.connect(makeHost({ clientId: "client-matching" })),
492
- );
493
- const foreignRequests = requestsFrom(
494
- yield* broker.connect(
495
- makeHost({
496
- clientId: "client-foreign",
497
- environmentId: EnvironmentId.make("environment-foreign"),
498
- }),
499
- ),
589
+it.effect("prefers the live tab owner for new sessions without moving existing leases", () =>
590
+ Effect.gen(function* () {
591
+ const broker = yield* makeBroker;
592
+ const connections = new Map<string, string>();
593
+ for (const clientId of ["owner", "other"]) {
594
+ const requests = requestsFrom(yield* broker.connect(makeHost({ clientId })), (connectionId) =>
595
+ connections.set(clientId, connectionId),
596
);
501
- yield* Stream.runForEach(matchingRequests, (request) =>
597
+ yield* Stream.runForEach(requests, (request) =>
598
broker.respond({
503
- clientId: "client-matching",
599
+ clientId,
600
connectionId: request.connectionId,
601
requestId: request.requestId,
602
ok: true,
507
- result: "matching",
603
+ result: clientId,
604
}),
605
).pipe(Effect.forkScoped);
510
- yield* Stream.runForEach(foreignRequests, (request) =>
511
- broker.respond({
512
- clientId: "client-foreign",
513
- connectionId: request.connectionId,
514
- requestId: request.requestId,
515
- ok: true,
516
- result: "foreign",
517
- }),
518
- ).pipe(Effect.forkScoped);
519
- yield* Effect.yieldNow;
520
-
521
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
522
- "matching",
523
- );
524
- }),
525
- ),
526
-);
527
-
528
-it.effect("pins a provider session to its initial host despite later focus changes", () =>
529
- Effect.scoped(
530
- Effect.gen(function* () {
531
- const broker = yield* makeBroker;
532
- let firstConnectionId = "";
533
- let secondConnectionId = "";
534
- const firstRequests = requestsFrom(
535
- yield* broker.connect(makeHost({ clientId: "client-first" })),
536
- (connectionId) => {
537
- firstConnectionId = connectionId;
606
+ }
607
+ yield* Effect.yieldNow;
608
+ yield* broker.focusHost({
609
+ clientId: "owner",
610
+ environmentId: scope.environmentId,
611
+ connectionId: connections.get("owner")!,
612
+ focused: false,
613
+ liveTabs: [
614
+ { threadId: scope.thread.threadId, tabId: PreviewTabId.make("signed-in"), visible: true },
615
+ ],
616
+ });
617
+ yield* broker.focusHost({
618
+ clientId: "other",
619
+ environmentId: scope.environmentId,
620
+ connectionId: connections.get("other")!,
621
+ focused: true,
622
+ liveTabs: [
623
+ {
624
+ threadId: scope.thread.threadId,
625
+ tabId: PreviewTabId.make("signed-in"),
626
+ visible: false,
627
},
539
- );
540
- const secondRequests = requestsFrom(
541
- yield* broker.connect(makeHost({ clientId: "client-second" })),
542
- (connectionId) => {
543
- secondConnectionId = connectionId;
628
+ {
629
+ threadId: ThreadId.make("another-thread"),
630
+ tabId: PreviewTabId.make("different-tab"),
631
+ visible: true,
632
},
545
- );
546
- yield* Stream.runForEach(firstRequests, (request) =>
547
- broker.respond({
548
- clientId: "client-first",
549
- connectionId: request.connectionId,
550
- requestId: request.requestId,
551
- ok: true,
552
- result: "first",
553
- }),
554
- ).pipe(Effect.forkScoped);
555
- yield* Stream.runForEach(secondRequests, (request) =>
556
- broker.respond({
557
- clientId: "client-second",
558
- connectionId: request.connectionId,
559
- requestId: request.requestId,
560
- ok: true,
561
- result: "second",
562
- }),
563
- ).pipe(Effect.forkScoped);
564
- yield* Effect.yieldNow;
565
-
566
- yield* broker.focusHost({
567
- clientId: "client-first",
568
- environmentId: scope.environmentId,
569
- connectionId: "connection-stale",
570
- focused: true,
571
- liveTabs: [{ threadId: scope.thread.threadId, tabId: PreviewTabId.make("stale-tab") }],
572
- });
573
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
574
- "second",
575
- );
576
- yield* broker.focusHost({
577
- clientId: "client-first",
578
- environmentId: scope.environmentId,
579
- connectionId: firstConnectionId,
580
- focused: true,
581
- });
582
-
583
- const firstPinnedScope = {
584
- ...scope,
585
- thread: { ...scope.thread, providerSessionId: "provider-session-first-pinned" },
586
- };
587
- expect(
588
- yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
589
- ).toBe("first");
590
-
591
- yield* broker.focusHost({
592
- clientId: "client-second",
593
- environmentId: scope.environmentId,
594
- connectionId: secondConnectionId,
595
- focused: true,
596
- });
597
-
598
- expect(
599
- yield* broker.invoke<string>({ scope: firstPinnedScope, operation: "status", input: {} }),
600
- ).toBe("first");
601
- expect(
602
- yield* broker.invoke<string>({
603
- scope: {
604
- ...scope,
605
- thread: { ...scope.thread, providerSessionId: "provider-session-second-pinned" },
606
- },
607
- operation: "status",
608
- input: {},
609
- }),
610
- ).toBe("second");
611
- }),
612
- ),
613
-);
633
+ ],
634
+ });
635
+ expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe("owner");
636
+ expect(
637
+ yield* broker.invoke<string>({
638
+ scope: { ...scope, thread: { ...scope.thread, providerSessionId: "explicit-owner" } },
639
+ tabId: PreviewTabId.make("signed-in"),
640
+ operation: "snapshot",
641
+ input: {},
642
+ }),
643
+ ).toBe("owner");
644
+ expect(
645
+ yield* broker.invoke<string>({
646
+ scope: { ...scope, thread: { ...scope.thread, providerSessionId: "other-tab" } },
647
+ tabId: PreviewTabId.make("different-tab"),
648
+ operation: "evaluate",
649
+ input: {},
650
+ }),
651
+ ).toBe("other");
652
615
-it.effect("prefers the live tab owner for new sessions without moving existing leases", () =>
616
- Effect.scoped(
617
- Effect.gen(function* () {
618
- const broker = yield* makeBroker;
619
- const connections = new Map<string, string>();
620
- for (const clientId of ["owner", "other"]) {
621
- const requests = requestsFrom(
622
- yield* broker.connect(makeHost({ clientId })),
623
- (connectionId) => connections.set(clientId, connectionId),
624
- );
625
- yield* Stream.runForEach(requests, (request) =>
626
- broker.respond({
627
- clientId,
628
- connectionId: request.connectionId,
629
- requestId: request.requestId,
630
- ok: true,
631
- result: clientId,
632
- }),
633
- ).pipe(Effect.forkScoped);
634
- }
635
- yield* Effect.yieldNow;
636
- yield* broker.focusHost({
637
- clientId: "owner",
638
- environmentId: scope.environmentId,
639
- connectionId: connections.get("owner")!,
640
- focused: false,
641
- liveTabs: [
642
- { threadId: scope.thread.threadId, tabId: PreviewTabId.make("signed-in"), visible: true },
643
- ],
644
- });
645
- yield* broker.focusHost({
646
- clientId: "other",
647
- environmentId: scope.environmentId,
648
- connectionId: connections.get("other")!,
649
- focused: true,
650
- liveTabs: [
651
- {
652
- threadId: scope.thread.threadId,
653
- tabId: PreviewTabId.make("signed-in"),
654
- visible: false,
655
- },
656
- {
657
- threadId: ThreadId.make("another-thread"),
658
- tabId: PreviewTabId.make("different-tab"),
659
- visible: true,
660
- },
661
- ],
662
- });
663
- expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe(
664
- "owner",
665
- );
666
- expect(
667
- yield* broker.invoke<string>({
668
- scope: { ...scope, thread: { ...scope.thread, providerSessionId: "explicit-owner" } },
669
- tabId: PreviewTabId.make("signed-in"),
670
- operation: "snapshot",
671
- input: {},
672
- }),
673
- ).toBe("owner");
674
- expect(
675
- yield* broker.invoke<string>({
676
- scope: { ...scope, thread: { ...scope.thread, providerSessionId: "other-tab" } },
677
- tabId: PreviewTabId.make("different-tab"),
678
- operation: "evaluate",
679
- input: {},
680
- }),
681
- ).toBe("other");
682
-
683
- yield* broker.focusHost({
684
- clientId: "owner",
685
- environmentId: scope.environmentId,
686
- connectionId: connections.get("owner")!,
687
- focused: false,
688
- liveTabs: [],
689
- });
690
- expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe(
691
- "owner",
692
- );
693
- expect(
694
- yield* broker.invoke<string>({
695
- scope: { ...scope, thread: { ...scope.thread, providerSessionId: "after-tab-closed" } },
696
- operation: "evaluate",
697
- input: {},
698
- }),
699
- ).toBe("other");
700
- }),
701
- ),
653
+ yield* broker.focusHost({
654
+ clientId: "owner",
655
+ environmentId: scope.environmentId,
656
+ connectionId: connections.get("owner")!,
657
+ focused: false,
658
+ liveTabs: [],
659
+ });
660
+ expect(yield* broker.invoke<string>({ scope, operation: "evaluate", input: {} })).toBe("owner");
661
+ expect(
662
+ yield* broker.invoke<string>({
663
+ scope: { ...scope, thread: { ...scope.thread, providerSessionId: "after-tab-closed" } },
664
+ operation: "evaluate",
665
+ input: {},
666
+ }),
667
+ ).toBe("other");
668
+ }),
669
);
670
671
it.effect("routes resize to a capable host instead of a newer legacy connection", () =>
705
- Effect.scoped(
706
- Effect.gen(function* () {
707
- const broker = yield* makeBroker;
708
- const capableRequests = requestsFrom(
709
- yield* broker.connect(
710
- makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
711
- ),
712
- );
713
- const legacyRequests = requestsFrom(
714
- yield* broker.connect(makeHost({ clientId: "client-legacy" })),
715
- );
716
- yield* Stream.runForEach(capableRequests, (request) =>
717
- broker.respond({
718
- clientId: "client-capable",
719
- connectionId: request.connectionId,
720
- requestId: request.requestId,
721
- ok: true,
722
- result: "capable",
723
- }),
724
- ).pipe(Effect.forkScoped);
725
- yield* Stream.runForEach(legacyRequests, (request) =>
726
- broker.respond({
727
- clientId: "client-legacy",
728
- connectionId: request.connectionId,
729
- requestId: request.requestId,
730
- ok: true,
731
- result: "legacy",
732
- }),
733
- ).pipe(Effect.forkScoped);
734
- yield* Effect.yieldNow;
672
+ Effect.gen(function* () {
673
+ const broker = yield* makeBroker;
674
+ const capableRequests = requestsFrom(
675
+ yield* broker.connect(
676
+ makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
677
+ ),
678
+ );
679
+ const legacyRequests = requestsFrom(
680
+ yield* broker.connect(makeHost({ clientId: "client-legacy" })),
681
+ );
682
+ yield* Stream.runForEach(capableRequests, (request) =>
683
+ broker.respond({
684
+ clientId: "client-capable",
685
+ connectionId: request.connectionId,
686
+ requestId: request.requestId,
687
+ ok: true,
688
+ result: "capable",
689
+ }),
690
+ ).pipe(Effect.forkScoped);
691
+ yield* Stream.runForEach(legacyRequests, (request) =>
692
+ broker.respond({
693
+ clientId: "client-legacy",
694
+ connectionId: request.connectionId,
695
+ requestId: request.requestId,
696
+ ok: true,
697
+ result: "legacy",
698
+ }),
699
+ ).pipe(Effect.forkScoped);
700
+ yield* Effect.yieldNow;
701
736
- expect(
737
- yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
738
- ).toBe("capable");
739
- }),
740
- ),
702
+ expect(
703
+ yield* broker.invoke<string>({ scope, operation: "resize", input: { mode: "fill" } }),
704
+ ).toBe("capable");
705
+ }),
706
);
707
708
it.effect("does not move a live legacy assignment to another runtime for resize", () =>
744
- Effect.scoped(
745
- Effect.gen(function* () {
746
- const broker = yield* makeBroker;
747
- const legacyRequests = requestsFrom(
748
- yield* broker.connect(makeHost({ clientId: "client-legacy" })),
749
- );
750
- yield* Stream.runForEach(legacyRequests, (request) =>
751
- broker.respond({
752
- clientId: "client-legacy",
753
- connectionId: request.connectionId,
754
- requestId: request.requestId,
755
- ok: true,
756
- result: "legacy",
757
- }),
758
- ).pipe(Effect.forkScoped);
759
- yield* Effect.yieldNow;
760
-
761
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
762
- "legacy",
763
- );
764
-
765
- const capableRequests = requestsFrom(
766
- yield* broker.connect(
767
- makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
768
- ),
769
- );
770
- yield* Stream.runForEach(capableRequests, (request) =>
771
- broker.respond({
772
- clientId: "client-capable",
773
- connectionId: request.connectionId,
774
- requestId: request.requestId,
775
- ok: true,
776
- result: "capable",
777
- }),
778
- ).pipe(Effect.forkScoped);
779
- yield* Effect.yieldNow;
709
+ Effect.gen(function* () {
710
+ const broker = yield* makeBroker;
711
+ const legacyRequests = requestsFrom(
712
+ yield* broker.connect(makeHost({ clientId: "client-legacy" })),
713
+ );
714
+ yield* Stream.runForEach(legacyRequests, (request) =>
715
+ broker.respond({
716
+ clientId: "client-legacy",
717
+ connectionId: request.connectionId,
718
+ requestId: request.requestId,
719
+ ok: true,
720
+ result: "legacy",
721
+ }),
722
+ ).pipe(Effect.forkScoped);
723
+ yield* Effect.yieldNow;
724
+
725
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("legacy");
726
+
727
+ const capableRequests = requestsFrom(
728
+ yield* broker.connect(
729
+ makeHost({ clientId: "client-capable", supportedOperations: ["resize"] }),
730
+ ),
731
+ );
732
+ yield* Stream.runForEach(capableRequests, (request) =>
733
+ broker.respond({
734
+ clientId: "client-capable",
735
+ connectionId: request.connectionId,
736
+ requestId: request.requestId,
737
+ ok: true,
738
+ result: "capable",
739
+ }),
740
+ ).pipe(Effect.forkScoped);
741
+ yield* Effect.yieldNow;
742
781
- const error = yield* broker
782
- .invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
783
- .pipe(Effect.flip);
784
- expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
785
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
786
- "legacy",
787
- );
788
- }),
789
- ),
743
+ const error = yield* broker
744
+ .invoke<void>({ scope, operation: "resize", input: { mode: "fill" } })
745
+ .pipe(Effect.flip);
746
+ expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError);
747
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("legacy");
748
+ }),
749
);
750
751
it.effect("ignores stale focus updates for a different environment", () =>
793
- Effect.scoped(
794
- Effect.gen(function* () {
795
- const broker = yield* makeBroker;
796
- let firstConnectionId = "";
797
- const firstRequests = requestsFrom(
798
- yield* broker.connect(makeHost({ clientId: "client-first" })),
799
- (connectionId) => {
800
- firstConnectionId = connectionId;
801
- },
802
- );
803
- const secondRequests = requestsFrom(
804
- yield* broker.connect(makeHost({ clientId: "client-second" })),
805
- );
806
- yield* Stream.runForEach(firstRequests, (request) =>
807
- broker.respond({
808
- clientId: "client-first",
809
- connectionId: request.connectionId,
810
- requestId: request.requestId,
811
- ok: true,
812
- result: "first",
813
- }),
814
- ).pipe(Effect.forkScoped);
815
- yield* Stream.runForEach(secondRequests, (request) =>
816
- broker.respond({
817
- clientId: "client-second",
818
- connectionId: request.connectionId,
819
- requestId: request.requestId,
820
- ok: true,
821
- result: "second",
822
- }),
823
- ).pipe(Effect.forkScoped);
824
- yield* Effect.yieldNow;
825
-
826
- yield* broker.focusHost({
752
+ Effect.gen(function* () {
753
+ const broker = yield* makeBroker;
754
+ let firstConnectionId = "";
755
+ const firstRequests = requestsFrom(
756
+ yield* broker.connect(makeHost({ clientId: "client-first" })),
757
+ (connectionId) => {
758
+ firstConnectionId = connectionId;
759
+ },
760
+ );
761
+ const secondRequests = requestsFrom(
762
+ yield* broker.connect(makeHost({ clientId: "client-second" })),
763
+ );
764
+ yield* Stream.runForEach(firstRequests, (request) =>
765
+ broker.respond({
766
clientId: "client-first",
828
- environmentId: EnvironmentId.make("environment-stale"),
829
- connectionId: firstConnectionId,
830
- focused: true,
831
- });
767
+ connectionId: request.connectionId,
768
+ requestId: request.requestId,
769
+ ok: true,
770
+ result: "first",
771
+ }),
772
+ ).pipe(Effect.forkScoped);
773
+ yield* Stream.runForEach(secondRequests, (request) =>
774
+ broker.respond({
775
+ clientId: "client-second",
776
+ connectionId: request.connectionId,
777
+ requestId: request.requestId,
778
+ ok: true,
779
+ result: "second",
780
+ }),
781
+ ).pipe(Effect.forkScoped);
782
+ yield* Effect.yieldNow;
783
833
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
834
- "second",
835
- );
836
- }),
837
- ),
784
+ yield* broker.focusHost({
785
+ clientId: "client-first",
786
+ environmentId: EnvironmentId.make("environment-stale"),
787
+ connectionId: firstConnectionId,
788
+ focused: true,
789
+ });
790
+
791
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
792
+ }),
793
);
794
795
it.effect("fails over a pinned provider session only after its host disconnects", () =>
841
- Effect.scoped(
842
- Effect.gen(function* () {
843
- const broker = yield* makeBroker;
844
- const firstTabId = PreviewTabId.make("tab-on-first-host");
845
- let firstConnectionId = "";
846
- let secondRoutedTabId: PreviewTabId | undefined;
847
- const firstRequests = requestsFrom(
848
- yield* broker.connect(makeHost({ clientId: "client-first" })),
849
- (connectionId) => {
850
- firstConnectionId = connectionId;
851
- },
852
- );
853
- const secondRequests = requestsFrom(
854
- yield* broker.connect(makeHost({ clientId: "client-second" })),
855
- );
856
- const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
857
- broker.respond({
858
- clientId: "client-first",
859
- connectionId: request.connectionId,
860
- requestId: request.requestId,
861
- ok: true,
862
- result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first",
863
- }),
864
- ).pipe(Effect.forkScoped);
865
- yield* Stream.runForEach(secondRequests, (request) => {
866
- secondRoutedTabId = request.tabId;
867
- return broker.respond({
868
- clientId: "client-second",
869
- connectionId: request.connectionId,
870
- requestId: request.requestId,
871
- ok: true,
872
- result: "second",
873
- });
874
- }).pipe(Effect.forkScoped);
875
- yield* Effect.yieldNow;
876
-
877
- yield* broker.focusHost({
796
+ Effect.gen(function* () {
797
+ const broker = yield* makeBroker;
798
+ const firstTabId = PreviewTabId.make("tab-on-first-host");
799
+ let firstConnectionId = "";
800
+ let secondRoutedTabId: PreviewTabId | undefined;
801
+ const firstRequests = requestsFrom(
802
+ yield* broker.connect(makeHost({ clientId: "client-first" })),
803
+ (connectionId) => {
804
+ firstConnectionId = connectionId;
805
+ },
806
+ );
807
+ const secondRequests = requestsFrom(
808
+ yield* broker.connect(makeHost({ clientId: "client-second" })),
809
+ );
810
+ const firstConsumer = yield* Stream.runForEach(firstRequests, (request) =>
811
+ broker.respond({
812
clientId: "client-first",
879
- environmentId: scope.environmentId,
880
- connectionId: firstConnectionId,
881
- focused: true,
882
- liveTabs: [{ threadId: scope.thread.threadId, tabId: firstTabId }],
883
- });
884
- expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
885
- host: "first",
886
- tabId: firstTabId,
813
+ connectionId: request.connectionId,
814
+ requestId: request.requestId,
815
+ ok: true,
816
+ result: request.operation === "open" ? { host: "first", tabId: firstTabId } : "first",
817
+ }),
818
+ ).pipe(Effect.forkScoped);
819
+ yield* Stream.runForEach(secondRequests, (request) => {
820
+ secondRoutedTabId = request.tabId;
821
+ return broker.respond({
822
+ clientId: "client-second",
823
+ connectionId: request.connectionId,
824
+ requestId: request.requestId,
825
+ ok: true,
826
+ result: "second",
827
});
828
+ }).pipe(Effect.forkScoped);
829
+ yield* Effect.yieldNow;
830
889
- yield* Fiber.interrupt(firstConsumer);
890
- yield* Effect.yieldNow;
831
+ yield* broker.focusHost({
832
+ clientId: "client-first",
833
+ environmentId: scope.environmentId,
834
+ connectionId: firstConnectionId,
835
+ focused: true,
836
+ liveTabs: [{ threadId: scope.thread.threadId, tabId: firstTabId }],
837
+ });
838
+ expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
839
+ host: "first",
840
+ tabId: firstTabId,
841
+ });
842
892
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
893
- "second",
894
- );
895
- expect(secondRoutedTabId).toBeUndefined();
896
- }),
897
- ),
843
+ yield* Fiber.interrupt(firstConsumer);
844
+ yield* Effect.yieldNow;
845
+
846
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe("second");
847
+ expect(secondRoutedTabId).toBeUndefined();
848
+ }),
849
);
850
851
it.effect("keeps a replacement stream authoritative when the old stream finalizes", () =>
901
- Effect.scoped(
902
- Effect.gen(function* () {
903
- const broker = yield* makeBroker;
904
- let firstConnectionId = "";
905
- let replacementConnectionId = "";
906
- const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
907
- firstConnectionId = connectionId;
908
- });
909
- yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
910
- yield* Effect.yieldNow;
852
+ Effect.gen(function* () {
853
+ const broker = yield* makeBroker;
854
+ let firstConnectionId = "";
855
+ let replacementConnectionId = "";
856
+ const firstRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
857
+ firstConnectionId = connectionId;
858
+ });
859
+ yield* Stream.runDrain(firstRequests).pipe(Effect.forkScoped);
860
+ yield* Effect.yieldNow;
861
912
- const replacementRequests = requestsFrom(
913
- yield* broker.connect(makeHost()),
914
- (connectionId) => {
915
- replacementConnectionId = connectionId;
916
- },
917
- );
918
- yield* Stream.runForEach(replacementRequests, (request) =>
919
- broker.respond({
920
- clientId: "client-1",
921
- connectionId: request.connectionId,
922
- requestId: request.requestId,
923
- ok: true,
924
- result: "replacement",
925
- }),
926
- ).pipe(Effect.forkScoped);
927
- yield* Effect.yieldNow;
862
+ const replacementRequests = requestsFrom(yield* broker.connect(makeHost()), (connectionId) => {
863
+ replacementConnectionId = connectionId;
864
+ });
865
+ yield* Stream.runForEach(replacementRequests, (request) =>
866
+ broker.respond({
867
+ clientId: "client-1",
868
+ connectionId: request.connectionId,
869
+ requestId: request.requestId,
870
+ ok: true,
871
+ result: "replacement",
872
+ }),
873
+ ).pipe(Effect.forkScoped);
874
+ yield* Effect.yieldNow;
875
929
- expect(replacementConnectionId).not.toBe(firstConnectionId);
930
- const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
931
- expect(result).toBe("replacement");
932
- }),
933
- ),
876
+ expect(replacementConnectionId).not.toBe(firstConnectionId);
877
+ const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
878
+ expect(result).toBe("replacement");
879
+ }),
880
);
881
882
it.effect("does not carry a tab id across a replacement automation stream", () =>
937
- Effect.scoped(
938
- Effect.gen(function* () {
939
- const broker = yield* makeBroker;
940
- const openedTabId = PreviewTabId.make("tab-first-webcontents");
941
- const firstRequests = requestsFrom(yield* broker.connect(makeHost()));
942
- yield* Stream.runForEach(firstRequests, (request) =>
943
- broker.respond({
944
- clientId: "client-1",
945
- connectionId: request.connectionId,
946
- requestId: request.requestId,
947
- ok: true,
948
- result:
949
- request.operation === "open"
950
- ? { host: "first", tabId: openedTabId }
951
- : { host: "first" },
952
- }),
953
- ).pipe(Effect.forkScoped);
954
- yield* Effect.yieldNow;
883
+ Effect.gen(function* () {
884
+ const broker = yield* makeBroker;
885
+ const openedTabId = PreviewTabId.make("tab-first-webcontents");
886
+ const firstRequests = requestsFrom(yield* broker.connect(makeHost()));
887
+ yield* Stream.runForEach(firstRequests, (request) =>
888
+ broker.respond({
889
+ clientId: "client-1",
890
+ connectionId: request.connectionId,
891
+ requestId: request.requestId,
892
+ ok: true,
893
+ result:
894
+ request.operation === "open" ? { host: "first", tabId: openedTabId } : { host: "first" },
895
+ }),
896
+ ).pipe(Effect.forkScoped);
897
+ yield* Effect.yieldNow;
898
956
- expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
957
- host: "first",
958
- tabId: openedTabId,
959
- });
899
+ expect(yield* broker.invoke({ scope, operation: "open", input: {} })).toEqual({
900
+ host: "first",
901
+ tabId: openedTabId,
902
+ });
903
961
- const routedRequests: RoutedRequest[] = [];
962
- const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
963
- yield* Stream.runForEach(replacementRequests, (request) => {
964
- routedRequests.push(request);
965
- return broker.respond({
966
- clientId: "client-1",
967
- connectionId: request.connectionId,
968
- requestId: request.requestId,
969
- ok: true,
970
- result: "replacement",
971
- });
972
- }).pipe(Effect.forkScoped);
973
- yield* Effect.yieldNow;
904
+ const routedRequests: RoutedRequest[] = [];
905
+ const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
906
+ yield* Stream.runForEach(replacementRequests, (request) => {
907
+ routedRequests.push(request);
908
+ return broker.respond({
909
+ clientId: "client-1",
910
+ connectionId: request.connectionId,
911
+ requestId: request.requestId,
912
+ ok: true,
913
+ result: "replacement",
914
+ });
915
+ }).pipe(Effect.forkScoped);
916
+ yield* Effect.yieldNow;
917
975
- expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
976
- "replacement",
977
- );
978
- expect(routedRequests.at(-1)?.tabId).toBeUndefined();
979
- }),
980
- ),
918
+ expect(yield* broker.invoke<string>({ scope, operation: "status", input: {} })).toBe(
919
+ "replacement",
920
+ );
921
+ expect(routedRequests.at(-1)?.tabId).toBeUndefined();
922
+ }),
923
);
924
925
it.effect("fails requests assigned to the stream that is replaced", () =>
984
- Effect.scoped(
985
- Effect.gen(function* () {
986
- const broker = yield* makeBroker;
987
- const requests = requestsFrom(yield* broker.connect(makeHost()));
988
- yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
989
- const pending = yield* broker
990
- .invoke<void>({ scope, operation: "status", input: {} })
991
- .pipe(Effect.flip, Effect.forkScoped);
992
- yield* Effect.yieldNow;
926
+ Effect.gen(function* () {
927
+ const broker = yield* makeBroker;
928
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
929
+ yield* Stream.runDrain(requests).pipe(Effect.forkScoped);
930
+ const pending = yield* broker
931
+ .invoke<void>({ scope, operation: "status", input: {} })
932
+ .pipe(Effect.flip, Effect.forkScoped);
933
+ yield* Effect.yieldNow;
934
994
- const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
995
- yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
935
+ const replacementRequests = requestsFrom(yield* broker.connect(makeHost()));
936
+ yield* Stream.runDrain(replacementRequests).pipe(Effect.forkScoped);
937
997
- const error = yield* Fiber.join(pending);
998
- expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
999
- expect(error).toMatchObject({
1000
- operation: "status",
1001
- environmentId: scope.environmentId,
1002
- threadId: scope.thread.threadId,
1003
- providerSessionId: scope.thread.providerSessionId,
1004
- providerInstanceId: scope.thread.providerInstanceId,
1005
- clientId: "client-1",
1006
- requestId: "preview-0",
1007
- timeoutMs: 15_000,
1008
- });
1009
- }),
1010
- ),
938
+ const error = yield* Fiber.join(pending);
939
+ expect(error).toBeInstanceOf(PreviewAutomationClientDisconnectedError);
940
+ expect(error).toMatchObject({
941
+ operation: "status",
942
+ environmentId: scope.environmentId,
943
+ threadId: scope.thread.threadId,
944
+ providerSessionId: scope.thread.providerSessionId,
945
+ providerInstanceId: scope.thread.providerInstanceId,
946
+ clientId: "client-1",
947
+ requestId: "preview-0",
948
+ timeoutMs: 15_000,
949
+ });
950
+ }),
951
);
952
953
it.effect("accepts responses only from the host that received the request", () =>
1014
- Effect.scoped(
1015
- Effect.gen(function* () {
1016
- const broker = yield* makeBroker;
1017
- const requests = requestsFrom(yield* broker.connect(makeHost()));
1018
- yield* Stream.runForEach(requests, (request) =>
1019
- Effect.gen(function* () {
1020
- yield* broker.respond({
1021
- clientId: "client-foreign",
1022
- connectionId: request.connectionId,
1023
- requestId: request.requestId,
1024
- ok: true,
1025
- result: "foreign",
1026
- });
1027
- yield* broker.respond({
1028
- clientId: "client-1",
1029
- connectionId: "connection-stale",
1030
- requestId: request.requestId,
1031
- ok: true,
1032
- result: "stale",
1033
- });
1034
- yield* broker.respond({
1035
- clientId: "client-1",
1036
- connectionId: request.connectionId,
1037
- requestId: request.requestId,
1038
- ok: true,
1039
- result: "owner",
1040
- });
1041
- }),
1042
- ).pipe(Effect.forkScoped);
1043
- yield* Effect.yieldNow;
1044
-
1045
- const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
1046
- expect(result).toBe("owner");
1047
- }),
1048
- ),
1049
-);
1050
-
1051
-it.effect("keeps each thread's current tab when threads share a provider session", () =>
1052
- Effect.scoped(
1053
- Effect.gen(function* () {
1054
- const broker = yield* makeBroker;
1055
- const routed: Array<RoutedRequest> = [];
1056
- const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true }));
1057
- yield* Stream.runForEach(requests, (request) => {
1058
- routed.push(request);
1059
- return broker.respond({
954
+ Effect.gen(function* () {
955
+ const broker = yield* makeBroker;
956
+ const requests = requestsFrom(yield* broker.connect(makeHost()));
957
+ yield* Stream.runForEach(requests, (request) =>
958
+ Effect.gen(function* () {
959
+ yield* broker.respond({
960
+ clientId: "client-foreign",
961
+ connectionId: request.connectionId,
962
+ requestId: request.requestId,
963
+ ok: true,
964
+ result: "foreign",
965
+ });
966
+ yield* broker.respond({
967
+ clientId: "client-1",
968
+ connectionId: "connection-stale",
969
+ requestId: request.requestId,
970
+ ok: true,
971
+ result: "stale",
972
+ });
973
+ yield* broker.respond({
974
clientId: "client-1",
975
connectionId: request.connectionId,
976
requestId: request.requestId,
977
ok: true,
1064
- result: { tabId: request.tabId ?? `tab-${request.threadId}` },
978
+ result: "owner",
979
});
1066
- }).pipe(Effect.forkScoped);
1067
- yield* Effect.yieldNow;
1068
- // Codex runs every thread of an instance in one provider session.
1069
- const otherThread = {
1070
- ...scope,
1071
- thread: { ...scope.thread, threadId: ThreadId.make("thread-2") },
1072
- };
980
+ }),
981
+ ).pipe(Effect.forkScoped);
982
+ yield* Effect.yieldNow;
983
1074
- yield* broker.invoke({ scope, operation: "open", input: {} });
1075
- yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1076
- yield* broker.invoke({ scope, operation: "snapshot", input: {} });
1077
- yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1078
-
1079
- expect(routed.map(({ threadId, tabId }) => [threadId, tabId])).toEqual([
1080
- ["thread-1", undefined],
1081
- ["thread-2", undefined],
1082
- ["thread-1", "tab-thread-1"],
1083
- ["thread-2", "tab-thread-2"],
1084
- ]);
1085
- expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId);
1086
- }),
1087
- ),
984
+ const result = yield* broker.invoke<string>({ scope, operation: "status", input: {} });
985
+ expect(result).toBe("owner");
986
+ }),
987
+);
988
+
989
+it.effect("keeps each thread's current tab when threads share a provider session", () =>
990
+ Effect.gen(function* () {
991
+ const broker = yield* makeBroker;
992
+ const routed: Array<RoutedRequest> = [];
993
+ const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true }));
994
+ yield* Stream.runForEach(requests, (request) => {
995
+ routed.push(request);
996
+ return broker.respond({
997
+ clientId: "client-1",
998
+ connectionId: request.connectionId,
999
+ requestId: request.requestId,
1000
+ ok: true,
1001
+ result: { tabId: request.tabId ?? `tab-${request.threadId}` },
1002
+ });
1003
+ }).pipe(Effect.forkScoped);
1004
+ yield* Effect.yieldNow;
1005
+ // Codex runs every thread of an instance in one provider session.
1006
+ const otherThread = {
1007
+ ...scope,
1008
+ thread: { ...scope.thread, threadId: ThreadId.make("thread-2") },
1009
+ };
1010
+
1011
+ yield* broker.invoke({ scope, operation: "open", input: {} });
1012
+ yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1013
+ yield* broker.invoke({ scope, operation: "snapshot", input: {} });
1014
+ yield* broker.invoke({ scope: otherThread, operation: "snapshot", input: {} });
1015
+
1016
+ expect(routed.map(({ threadId, tabId }) => [threadId, tabId])).toEqual([
1017
+ ["thread-1", undefined],
1018
+ ["thread-2", undefined],
1019
+ ["thread-1", "tab-thread-1"],
1020
+ ["thread-2", "tab-thread-2"],
1021
+ ]);
1022
+ expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId);
1023
+ }),
1024
);
apps/server/src/mcp/TaskCancelUsageLimit.integration.test.ts
+269
-274
@@ -58,298 +58,293 @@ it.effect.each([
58
] as const)(
59
"a delegated child whose task is cancelled $cancel resumes at the reset: $resumed",
60
({ cancel, cancelStatus, resumed }) =>
61
- Effect.scoped(
62
- Effect.gen(function* () {
63
- const cwd = yield* checkpointWorkspace("task-cancel-usage-limit");
64
- // Set while the provider's usage-limit result is already on its way.
65
- let limitInFlight: Effect.Effect<void> = Effect.void;
66
- const turns: Array<{
67
- readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
68
- readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
69
- }> = [];
70
- const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
71
- instanceId,
72
- driver,
73
- getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
74
- planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
75
- openSession: (input) =>
76
- Effect.gen(function* () {
77
- const now = yield* DateTime.now;
78
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
79
- return {
80
- instanceId,
61
+ Effect.gen(function* () {
62
+ const cwd = yield* checkpointWorkspace("task-cancel-usage-limit");
63
+ // Set while the provider's usage-limit result is already on its way.
64
+ let limitInFlight: Effect.Effect<void> = Effect.void;
65
+ const turns: Array<{
66
+ readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
67
+ readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
68
+ }> = [];
69
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
70
+ instanceId,
71
+ driver,
72
+ getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
73
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
74
+ openSession: (input) =>
75
+ Effect.gen(function* () {
76
+ const now = yield* DateTime.now;
77
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
78
+ return {
79
+ instanceId,
80
+ driver,
81
+ providerSessionId: input.providerSessionId,
82
+ providerSession: {
83
+ id: input.providerSessionId,
84
driver,
82
- providerSessionId: input.providerSessionId,
83
- providerSession: {
84
- id: input.providerSessionId,
85
+ providerInstanceId: instanceId,
86
+ status: "ready",
87
+ cwd,
88
+ model: modelSelection.model,
89
+ capabilities: ClaudeProviderCapabilitiesV2,
90
+ createdAt: now,
91
+ updatedAt: now,
92
+ lastError: null,
93
+ },
94
+ events: Stream.fromQueue(events),
95
+ ensureThread: ({ threadId }) =>
96
+ Effect.succeed({
97
+ id: ProviderThreadId.make(`provider-thread:${threadId}`),
98
driver,
99
providerInstanceId: instanceId,
87
- status: "ready",
88
- cwd,
89
- model: modelSelection.model,
90
- capabilities: ClaudeProviderCapabilitiesV2,
100
+ providerSessionId: input.providerSessionId,
101
+ appThreadId: threadId,
102
+ ownerNodeId: null,
103
+ nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" },
104
+ nativeConversationHeadRef: null,
105
+ status: "idle",
106
+ firstRunOrdinal: null,
107
+ lastRunOrdinal: null,
108
+ handoffIds: [],
109
+ forkedFrom: null,
110
createdAt: now,
111
updatedAt: now,
93
- lastError: null,
94
- },
95
- events: Stream.fromQueue(events),
96
- ensureThread: ({ threadId }) =>
97
- Effect.succeed({
98
- id: ProviderThreadId.make(`provider-thread:${threadId}`),
112
+ }),
113
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
114
+ startTurn: (turn) =>
115
+ Effect.gen(function* () {
116
+ turns.push({ turn, events });
117
+ yield* Queue.offer(events, {
118
+ type: "provider_turn.updated",
119
driver,
100
- providerInstanceId: instanceId,
101
- providerSessionId: input.providerSessionId,
102
- appThreadId: threadId,
103
- ownerNodeId: null,
104
- nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" },
105
- nativeConversationHeadRef: null,
106
- status: "idle",
107
- firstRunOrdinal: null,
108
- lastRunOrdinal: null,
109
- handoffIds: [],
110
- forkedFrom: null,
111
- createdAt: now,
112
- updatedAt: now,
113
- }),
114
- resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
115
- startTurn: (turn) =>
116
- Effect.gen(function* () {
117
- turns.push({ turn, events });
118
- yield* Queue.offer(events, {
119
- type: "provider_turn.updated",
120
- driver,
121
- providerTurn: {
122
- id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
123
- providerThreadId: turn.providerThread.id,
124
- nodeId: turn.rootNodeId,
125
- runAttemptId: turn.attemptId,
126
- nativeTurnRef: null,
127
- ordinal: turn.providerTurnOrdinal,
128
- status: "running",
129
- startedAt: now,
130
- completedAt: null,
131
- },
132
- });
133
- }),
134
- steerTurn: () => Effect.die("unused"),
135
- interruptTurn: () => Effect.suspend(() => limitInFlight),
136
- respondToRuntimeRequest: () => Effect.die("unused"),
137
- readThreadSnapshot: () => Effect.die("unused"),
138
- rollbackThread: () => Effect.die("unused"),
139
- forkThread: () => Effect.die("unused"),
140
- };
141
- }),
142
- };
143
- const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter);
144
- const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
145
- { name: "task-cancel-usage-limit" },
146
- layerAdapters,
147
- { runEffectWorker: false },
148
- );
149
- const layerOrchestration = Layer.merge(
150
- layerOrchestrator,
151
- ThreadManagementService.layer.pipe(
152
- Layer.provide(layerOrchestrator),
153
- Layer.provide(ServerSettings.layerTest()),
154
- Layer.provide(
155
- CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
156
- ),
157
- ),
158
- );
159
- const sweeps = new Map<string, Effect.Effect<void>>();
160
- const layerRecovery = UsageLimitRecoveryWorker.layer.pipe(
120
+ providerTurn: {
121
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
122
+ providerThreadId: turn.providerThread.id,
123
+ nodeId: turn.rootNodeId,
124
+ runAttemptId: turn.attemptId,
125
+ nativeTurnRef: null,
126
+ ordinal: turn.providerTurnOrdinal,
127
+ status: "running",
128
+ startedAt: now,
129
+ completedAt: null,
130
+ },
131
+ });
132
+ }),
133
+ steerTurn: () => Effect.die("unused"),
134
+ interruptTurn: () => Effect.suspend(() => limitInFlight),
135
+ respondToRuntimeRequest: () => Effect.die("unused"),
136
+ readThreadSnapshot: () => Effect.die("unused"),
137
+ rollbackThread: () => Effect.die("unused"),
138
+ forkThread: () => Effect.die("unused"),
139
+ };
140
+ }),
141
+ };
142
+ const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter);
143
+ const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
144
+ { name: "task-cancel-usage-limit" },
145
+ layerAdapters,
146
+ { runEffectWorker: false },
147
+ );
148
+ const layerOrchestration = Layer.merge(
149
+ layerOrchestrator,
150
+ ThreadManagementService.layer.pipe(
151
+ Layer.provide(layerOrchestrator),
152
+ Layer.provide(ServerSettings.layerTest()),
153
Layer.provide(
162
- Layer.mergeAll(
163
- Layer.succeed(Scheduler.Scheduler, {
164
- register: <E, R>(name: string, work: Effect.Effect<void, E, R>) =>
165
- Effect.gen(function* () {
166
- const context = yield* Effect.context<R>();
167
- sweeps.set(name, work.pipe(Effect.provideContext(context), Effect.orDie));
168
- }),
169
- }),
170
- ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
171
- ServerSettings.layerTest({ autoResumeLimitedThreads: true }),
172
- ),
154
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
155
),
174
- );
175
- const layerTest = Layer.merge(
176
- OrchestratorMcpService.layer.pipe(
177
- Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
178
- Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
156
+ ),
157
+ );
158
+ const sweeps = new Map<string, Effect.Effect<void>>();
159
+ const layerRecovery = UsageLimitRecoveryWorker.layer.pipe(
160
+ Layer.provide(
161
+ Layer.mergeAll(
162
+ Layer.succeed(Scheduler.Scheduler, {
163
+ register: <E, R>(name: string, work: Effect.Effect<void, E, R>) =>
164
+ Effect.gen(function* () {
165
+ const context = yield* Effect.context<R>();
166
+ sweeps.set(name, work.pipe(Effect.provideContext(context), Effect.orDie));
167
+ }),
168
+ }),
169
+ ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
170
+ ServerSettings.layerTest({ autoResumeLimitedThreads: true }),
171
),
180
- layerRecovery,
181
- ).pipe(
182
- Layer.provideMerge(layerOrchestration),
183
- Layer.provide(
184
- Layer.mergeAll(
185
- layerAdapters,
186
- Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
187
- Layer.mock(ProjectService.ProjectService)({}),
188
- Layer.mock(SecretRequests.SecretRequests)({}),
189
- Layer.mock(RemoteDelegation.RemoteDelegation)({}),
190
- ServerSettings.layerTest(),
191
- Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
192
- NodeServices.layer,
193
- NodeCrypto.layer,
194
- ),
172
+ ),
173
+ );
174
+ const layerTest = Layer.merge(
175
+ OrchestratorMcpService.layer.pipe(
176
+ Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
177
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
178
+ ),
179
+ layerRecovery,
180
+ ).pipe(
181
+ Layer.provideMerge(layerOrchestration),
182
+ Layer.provide(
183
+ Layer.mergeAll(
184
+ layerAdapters,
185
+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
186
+ Layer.mock(ProjectService.ProjectService)({}),
187
+ Layer.mock(SecretRequests.SecretRequests)({}),
188
+ Layer.mock(RemoteDelegation.RemoteDelegation)({}),
189
+ ServerSettings.layerTest(),
190
+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
191
+ NodeServices.layer,
192
+ NodeCrypto.layer,
193
),
196
- );
194
+ ),
195
+ );
196
198
- yield* Effect.gen(function* () {
199
- const orchestrator = yield* Orchestrator.OrchestratorV2;
200
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
201
- const service = yield* OrchestratorMcpService.OrchestratorMcpService;
202
- const sweep = Effect.andThen(
203
- Effect.suspend(() => sweeps.get("usage-limit-recovery")!),
204
- worker.drain(),
197
+ yield* Effect.gen(function* () {
198
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
199
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
200
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
201
+ const sweep = Effect.andThen(
202
+ Effect.suspend(() => sweeps.get("usage-limit-recovery")!),
203
+ worker.drain(),
204
+ );
205
+ const parentThreadId = ThreadId.make("thread:task-cancel-limit-parent");
206
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
207
+ orchestrator.streamDomainEvents.pipe(
208
+ Stream.filter(predicate),
209
+ Stream.take(1),
210
+ Stream.runDrain,
211
+ Effect.forkScoped,
212
);
206
- const parentThreadId = ThreadId.make("thread:task-cancel-limit-parent");
207
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
208
- orchestrator.streamDomainEvents.pipe(
209
- Stream.filter(predicate),
210
- Stream.take(1),
211
- Stream.runDrain,
212
- Effect.forkScoped,
213
- );
214
- const turnRunning = () =>
215
- watch(
216
- (event) =>
217
- event.type === "provider-turn.updated" && event.payload.status === "running",
218
- );
219
- yield* orchestrator.dispatch({
220
- type: "thread.create",
221
- commandId: CommandId.make("create-parent"),
222
- threadId: parentThreadId,
223
- projectId: ProjectId.make("project:task-cancel-limit"),
224
- title: "Parent",
225
- modelSelection,
226
- runtimeMode: "full-access",
227
- interactionMode: "default",
228
- branch: null,
229
- worktreePath: cwd,
230
- createdBy: "user",
231
- creationSource: "web",
232
- });
233
- const parentRunning = yield* turnRunning();
234
- yield* orchestrator.dispatch({
235
- type: "message.dispatch",
236
- commandId: CommandId.make("start-parent"),
237
- threadId: parentThreadId,
238
- messageId: MessageId.make("message:start-parent"),
239
- text: "Delegate a review",
240
- attachments: [],
241
- dispatchMode: { type: "start_immediately" },
242
- createdBy: "user",
243
- creationSource: "web",
244
- });
245
- yield* worker.drain();
246
- yield* Fiber.join(parentRunning);
213
+ const turnRunning = () =>
214
+ watch(
215
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
216
+ );
217
+ yield* orchestrator.dispatch({
218
+ type: "thread.create",
219
+ commandId: CommandId.make("create-parent"),
220
+ threadId: parentThreadId,
221
+ projectId: ProjectId.make("project:task-cancel-limit"),
222
+ title: "Parent",
223
+ modelSelection,
224
+ runtimeMode: "full-access",
225
+ interactionMode: "default",
226
+ branch: null,
227
+ worktreePath: cwd,
228
+ createdBy: "user",
229
+ creationSource: "web",
230
+ });
231
+ const parentRunning = yield* turnRunning();
232
+ yield* orchestrator.dispatch({
233
+ type: "message.dispatch",
234
+ commandId: CommandId.make("start-parent"),
235
+ threadId: parentThreadId,
236
+ messageId: MessageId.make("message:start-parent"),
237
+ text: "Delegate a review",
238
+ attachments: [],
239
+ dispatchMode: { type: "start_immediately" },
240
+ createdBy: "user",
241
+ creationSource: "web",
242
+ });
243
+ yield* worker.drain();
244
+ yield* Fiber.join(parentRunning);
245
248
- const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
249
- const childRunning = yield* turnRunning();
250
- yield* orchestrator.dispatch({
251
- type: "delegated_task.request",
252
- commandId: CommandId.make("delegate"),
253
- parentThreadId,
254
- parentRunId: parentRun.id,
255
- parentNodeId: parentRun.rootNodeId!,
256
- task: "Review the change",
257
- modelSelection,
258
- runtimeMode: "full-access",
259
- interactionMode: "default",
260
- completionWake: "always",
261
- createdBy: "agent",
262
- creationSource: "mcp",
246
+ const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
247
+ const childRunning = yield* turnRunning();
248
+ yield* orchestrator.dispatch({
249
+ type: "delegated_task.request",
250
+ commandId: CommandId.make("delegate"),
251
+ parentThreadId,
252
+ parentRunId: parentRun.id,
253
+ parentNodeId: parentRun.rootNodeId!,
254
+ task: "Review the change",
255
+ modelSelection,
256
+ runtimeMode: "full-access",
257
+ interactionMode: "default",
258
+ completionWake: "always",
259
+ createdBy: "agent",
260
+ creationSource: "mcp",
261
+ });
262
+ yield* worker.drain();
263
+ yield* Fiber.join(childRunning);
264
+ const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
265
+ const childThreadId = task.childThreadId!;
266
+ const child = turns.find((entry) => entry.turn.threadId === childThreadId)!;
267
+ const childTurn = (yield* orchestrator.getThreadProjection(childThreadId))
268
+ .providerTurns[0]!;
269
+
270
+ const scope: McpInvocationScope = {
271
+ environmentId: EnvironmentId.make("environment:task-cancel-limit"),
272
+ requestNamespace: "provider-session:task-cancel-limit",
273
+ thread: {
274
+ threadId: parentThreadId,
275
+ providerSessionId: "provider-session:task-cancel-limit",
276
+ providerInstanceId: instanceId,
277
+ },
278
+ client: undefined,
279
+ capabilities: new Set(["orchestration"]),
280
+ issuedAt: 1,
281
+ };
282
+ const cancelTask = Effect.gen(function* () {
283
+ const result = yield* service.cancelTask(scope, {
284
+ taskId: task.id,
285
+ clientRequestId: "cancel-task",
286
});
287
yield* worker.drain();
265
- yield* Fiber.join(childRunning);
266
- const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
267
- const childThreadId = task.childThreadId!;
268
- const child = turns.find((entry) => entry.turn.threadId === childThreadId)!;
269
- const childTurn = (yield* orchestrator.getThreadProjection(childThreadId))
270
- .providerTurns[0]!;
288
+ return result.status;
289
+ });
290
272
- const scope: McpInvocationScope = {
273
- environmentId: EnvironmentId.make("environment:task-cancel-limit"),
274
- requestNamespace: "provider-session:task-cancel-limit",
275
- thread: {
276
- threadId: parentThreadId,
277
- providerSessionId: "provider-session:task-cancel-limit",
278
- providerInstanceId: instanceId,
291
+ const now = yield* DateTime.now;
292
+ const childFailed = yield* watch(
293
+ (event) =>
294
+ event.type === "run.updated" &&
295
+ event.payload.id === child.turn.runId &&
296
+ event.payload.status === "failed",
297
+ );
298
+ const hitLimit = Effect.forEach(
299
+ [
300
+ {
301
+ type: "provider_turn.updated",
302
+ driver,
303
+ providerTurn: { ...childTurn, status: "failed", completedAt: now },
304
},
280
- client: undefined,
281
- capabilities: new Set(["orchestration"]),
282
- issuedAt: 1,
283
- };
284
- const cancelTask = Effect.gen(function* () {
285
- const result = yield* service.cancelTask(scope, {
286
- taskId: task.id,
287
- clientRequestId: "cancel-task",
288
- });
289
- yield* worker.drain();
290
- return result.status;
291
- });
292
-
293
- const now = yield* DateTime.now;
294
- const childFailed = yield* watch(
295
- (event) =>
296
- event.type === "run.updated" &&
297
- event.payload.id === child.turn.runId &&
298
- event.payload.status === "failed",
299
- );
300
- const hitLimit = Effect.forEach(
301
- [
302
- {
303
- type: "provider_turn.updated",
304
- driver,
305
- providerTurn: { ...childTurn, status: "failed", completedAt: now },
305
+ {
306
+ type: "turn.terminal",
307
+ driver,
308
+ providerThreadId: childTurn.providerThreadId,
309
+ providerTurnId: childTurn.id,
310
+ runOrdinal: child.turn.runOrdinal,
311
+ failureItemOrdinal: 1,
312
+ status: "failed",
313
+ failure: {
314
+ class: "usage_limit",
315
+ message: "Claude usage limit reached.",
316
+ code: null,
317
+ retryable: null,
318
+ resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 1 })),
319
},
307
- {
308
- type: "turn.terminal",
309
- driver,
310
- providerThreadId: childTurn.providerThreadId,
311
- providerTurnId: childTurn.id,
312
- runOrdinal: child.turn.runOrdinal,
313
- failureItemOrdinal: 1,
314
- status: "failed",
315
- failure: {
316
- class: "usage_limit",
317
- message: "Claude usage limit reached.",
318
- code: null,
319
- retryable: null,
320
- resetAt: DateTime.formatIso(DateTime.add(now, { minutes: 1 })),
321
- },
322
- threadDisposition: "reusable",
323
- },
324
- ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
325
- (event) => Queue.offer(child.events, event),
326
- { discard: true },
327
- );
328
- let cancelled: string | null = null;
329
- if (cancel === "as its limit lands") {
330
- limitInFlight = hitLimit;
331
- cancelled = yield* cancelTask;
332
- } else {
333
- yield* hitLimit;
334
- }
335
- yield* Fiber.join(childFailed);
336
- yield* worker.drain();
320
+ threadDisposition: "reusable",
321
+ },
322
+ ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>,
323
+ (event) => Queue.offer(child.events, event),
324
+ { discard: true },
325
+ );
326
+ let cancelled: string | null = null;
327
+ if (cancel === "as its limit lands") {
328
+ limitInFlight = hitLimit;
329
+ cancelled = yield* cancelTask;
330
+ } else {
331
+ yield* hitLimit;
332
+ }
333
+ yield* Fiber.join(childFailed);
334
+ yield* worker.drain();
335
338
- // The sweep runs every few seconds, so it arms the child before a parent reacts.
339
- yield* sweep;
340
- if (cancel === "after its limit") cancelled = yield* cancelTask;
341
- assert.equal(cancelled, cancelStatus);
336
+ // The sweep runs every few seconds, so it arms the child before a parent reacts.
337
+ yield* sweep;
338
+ if (cancel === "after its limit") cancelled = yield* cancelTask;
339
+ assert.equal(cancelled, cancelStatus);
340
343
- yield* TestClock.adjust("1 minute");
344
- yield* sweep;
345
- const childAfter = yield* orchestrator.getThreadProjection(childThreadId);
346
- assert.deepEqual(
347
- childAfter.messages.flatMap((message) =>
348
- message.role === "user" ? [message.text] : [],
349
- ),
350
- resumed ? ["Review the change", "Continue where you left off."] : ["Review the change"],
351
- );
352
- }).pipe(Effect.provide(layerTest));
353
- }),
354
- ),
341
+ yield* TestClock.adjust("1 minute");
342
+ yield* sweep;
343
+ const childAfter = yield* orchestrator.getThreadProjection(childThreadId);
344
+ assert.deepEqual(
345
+ childAfter.messages.flatMap((message) => (message.role === "user" ? [message.text] : [])),
346
+ resumed ? ["Review the change", "Continue where you left off."] : ["Review the change"],
347
+ );
348
+ }).pipe(Effect.provide(layerTest));
349
+ }),
350
);
apps/server/src/mcp/toolkits/preview/handlers.test.ts
+67
-69
@@ -28,77 +28,75 @@ import { claimPreviewRecording, layerStandard } from "./handlers.ts";
28
import { PreviewStandardToolkit } from "./tools.ts";
29
30
it.effect("preview_open navigates the opened tab to a dev server in one tool call", () =>
31
- Effect.scoped(
32
- Effect.gen(function* () {
33
- const scope = yield* McpInvocationContext.McpInvocationContext;
34
- const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
35
- const connected = yield* Deferred.make<void>();
36
- const tabId = PreviewTabId.make("opened-tab");
37
- const target = {
38
- kind: "environment-port" as const,
39
- port: 3000,
40
- path: "/settings?tab=account",
41
- };
42
- const requests: PreviewAutomationRequest[] = [];
43
- const status = {
44
- available: true,
45
- visible: false,
46
- tabId,
47
- url: "http://localhost:3000/settings?tab=account",
48
- title: "Settings",
49
- loading: false,
50
- };
51
- const events = yield* broker.connect({
31
+ Effect.gen(function* () {
32
+ const scope = yield* McpInvocationContext.McpInvocationContext;
33
+ const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
34
+ const connected = yield* Deferred.make<void>();
35
+ const tabId = PreviewTabId.make("opened-tab");
36
+ const target = {
37
+ kind: "environment-port" as const,
38
+ port: 3000,
39
+ path: "/settings?tab=account",
40
+ };
41
+ const requests: PreviewAutomationRequest[] = [];
42
+ const status = {
43
+ available: true,
44
+ visible: false,
45
+ tabId,
46
+ url: "http://localhost:3000/settings?tab=account",
47
+ title: "Settings",
48
+ loading: false,
49
+ };
50
+ const events = yield* broker.connect({
51
+ clientId: "client-1",
52
+ environmentId: scope.environmentId,
53
+ });
54
+ yield* Stream.runForEach(events, (event) => {
55
+ if (event.type === "connected") return Deferred.succeed(connected, undefined);
56
+ requests.push(event.request);
57
+ return broker.respond({
58
clientId: "client-1",
53
- environmentId: scope.environmentId,
59
+ connectionId: event.connectionId,
60
+ requestId: event.request.requestId,
61
+ ok: true,
62
+ result: event.request.operation === "open" ? { ...status, url: "about:blank" } : status,
63
});
55
- yield* Stream.runForEach(events, (event) => {
56
- if (event.type === "connected") return Deferred.succeed(connected, undefined);
57
- requests.push(event.request);
58
- return broker.respond({
59
- clientId: "client-1",
60
- connectionId: event.connectionId,
61
- requestId: event.request.requestId,
62
- ok: true,
63
- result: event.request.operation === "open" ? { ...status, url: "about:blank" } : status,
64
- });
65
- }).pipe(Effect.forkScoped);
66
- yield* Deferred.await(connected);
67
- const toolkit = yield* PreviewStandardToolkit.pipe(
68
- Effect.provide(McpToolAccess.HandlersLayer.layer(layerStandard)),
69
- );
70
- const results = yield* toolkit
71
- .handle("preview_open", {
72
- url: "http://localhost:3000",
73
- target,
74
- open: false,
75
- reuseExistingTab: false,
76
- })
77
- .pipe(Stream.unwrap, Stream.runCollect);
78
- expect(results.at(-1)?.result).toEqual(status);
79
- expect(requests.map(({ operation, input }) => ({ operation, input }))).toEqual([
80
- { operation: "open", input: { open: false, show: false, reuseExistingTab: false } },
81
- { operation: "navigate", input: { target } },
82
- ]);
83
- expect(requests[1]?.tabId).toBe(tabId);
84
- expect(requests[1]?.tabIdExplicit).toBe(true);
85
- }).pipe(
86
- Effect.provideService(McpInvocationContext.McpInvocationContext, {
87
- environmentId: EnvironmentId.make("environment-1"),
88
- requestNamespace: "provider-session-1",
89
- thread: {
90
- threadId: ThreadId.make("thread-1"),
91
- providerSessionId: "provider-session-1",
92
- providerInstanceId: ProviderInstanceId.make("codex"),
93
- },
94
- client: undefined,
95
- capabilities: new Set(["preview"] as const),
96
- issuedAt: 1,
97
- }),
98
- Effect.provide(
99
- Layer.mergeAll(PreviewAutomationBroker.layer, liveThreadsLayer).pipe(
100
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
101
- ),
64
+ }).pipe(Effect.forkScoped);
65
+ yield* Deferred.await(connected);
66
+ const toolkit = yield* PreviewStandardToolkit.pipe(
67
+ Effect.provide(McpToolAccess.HandlersLayer.layer(layerStandard)),
68
+ );
69
+ const results = yield* toolkit
70
+ .handle("preview_open", {
71
+ url: "http://localhost:3000",
72
+ target,
73
+ open: false,
74
+ reuseExistingTab: false,
75
+ })
76
+ .pipe(Stream.unwrap, Stream.runCollect);
77
+ expect(results.at(-1)?.result).toEqual(status);
78
+ expect(requests.map(({ operation, input }) => ({ operation, input }))).toEqual([
79
+ { operation: "open", input: { open: false, show: false, reuseExistingTab: false } },
80
+ { operation: "navigate", input: { target } },
81
+ ]);
82
+ expect(requests[1]?.tabId).toBe(tabId);
83
+ expect(requests[1]?.tabIdExplicit).toBe(true);
84
+ }).pipe(
85
+ Effect.provideService(McpInvocationContext.McpInvocationContext, {
86
+ environmentId: EnvironmentId.make("environment-1"),
87
+ requestNamespace: "provider-session-1",
88
+ thread: {
89
+ threadId: ThreadId.make("thread-1"),
90
+ providerSessionId: "provider-session-1",
91
+ providerInstanceId: ProviderInstanceId.make("codex"),
92
+ },
93
+ client: undefined,
94
+ capabilities: new Set(["preview"] as const),
95
+ issuedAt: 1,
96
+ }),
97
+ Effect.provide(
98
+ Layer.mergeAll(PreviewAutomationBroker.layer, liveThreadsLayer).pipe(
99
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
100
),
101
),
102
),
apps/server/src/mcp/toolkits/previewControls/handlers.test.ts
+69
-71
@@ -27,79 +27,77 @@ it.effect.each([
27
{ name: "project opt-in", globalAccess: false, projectAccess: true },
28
{ name: "project opt-out", globalAccess: true, projectAccess: false },
29
])("list and close respect the credential for a $name", ({ globalAccess, projectAccess }) =>
30
- Effect.scoped(
31
- Effect.gen(function* () {
32
- const projectId = ProjectId.make("preview-controls-project");
33
- const threadId = ThreadId.make("preview-controls-thread");
34
- const settings = {
35
- ...DEFAULT_SERVER_SETTINGS,
36
- enableAgentBrowserAccess: globalAccess,
37
- projectSettingsOverrides: {
38
- [projectId]: { enableAgentBrowserAccess: projectAccess },
39
- },
40
- };
41
- const effective = resolveProjectSettings(settings, projectId).settings;
42
- const scope: McpInvocationContext.McpInvocationScope = {
43
- environmentId: EnvironmentId.make("preview-controls-environment"),
44
- requestNamespace: "preview-controls-provider-session",
45
- thread: {
46
- threadId,
47
- providerSessionId: "preview-controls-provider-session",
48
- providerInstanceId: ProviderInstanceId.make("codex"),
49
- },
50
- client: undefined,
51
- capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []),
52
- issuedAt: 0,
53
- };
54
- const manager = yield* Preview.make.pipe(
55
- Effect.provide(
56
- Layer.merge(
57
- ServerConfig.layerTest(process.cwd(), { prefix: "t3-preview-controls-" }).pipe(
58
- Layer.provide(NodeServices.layer),
59
- ),
60
- NodeCrypto.layer,
30
+ Effect.gen(function* () {
31
+ const projectId = ProjectId.make("preview-controls-project");
32
+ const threadId = ThreadId.make("preview-controls-thread");
33
+ const settings = {
34
+ ...DEFAULT_SERVER_SETTINGS,
35
+ enableAgentBrowserAccess: globalAccess,
36
+ projectSettingsOverrides: {
37
+ [projectId]: { enableAgentBrowserAccess: projectAccess },
38
+ },
39
+ };
40
+ const effective = resolveProjectSettings(settings, projectId).settings;
41
+ const scope: McpInvocationContext.McpInvocationScope = {
42
+ environmentId: EnvironmentId.make("preview-controls-environment"),
43
+ requestNamespace: "preview-controls-provider-session",
44
+ thread: {
45
+ threadId,
46
+ providerSessionId: "preview-controls-provider-session",
47
+ providerInstanceId: ProviderInstanceId.make("codex"),
48
+ },
49
+ client: undefined,
50
+ capabilities: new Set(effective.enableAgentBrowserAccess ? ["preview"] : []),
51
+ issuedAt: 0,
52
+ };
53
+ const manager = yield* Preview.make.pipe(
54
+ Effect.provide(
55
+ Layer.merge(
56
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-preview-controls-" }).pipe(
57
+ Layer.provide(NodeServices.layer),
58
),
59
+ NodeCrypto.layer,
60
),
63
- );
64
- const tab = yield* manager.open({ threadId, url: "http://localhost:3000" });
65
- const layerDependencies = Layer.mergeAll(
66
- PreviewAutomationBroker.layer.pipe(
67
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
68
- ),
69
- Layer.succeed(Preview.PreviewManager, manager),
70
- Layer.succeed(McpInvocationContext.McpInvocationContext, scope),
71
- McpToolAccessTestkit.liveThreadsLayer,
72
- Layer.mock(ServerSettings.ServerSettingsService)({
73
- getSettings: Effect.succeed(settings),
74
- }),
75
- );
76
- const toolkit = yield* PreviewControlsToolkit.pipe(
77
- Effect.provide(
78
- McpToolAccess.HandlersLayer.layer(PreviewControlsHandlers.layer).pipe(
79
- Layer.provide(layerDependencies),
80
- ),
61
+ ),
62
+ );
63
+ const tab = yield* manager.open({ threadId, url: "http://localhost:3000" });
64
+ const layerDependencies = Layer.mergeAll(
65
+ PreviewAutomationBroker.layer.pipe(
66
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
67
+ ),
68
+ Layer.succeed(Preview.PreviewManager, manager),
69
+ Layer.succeed(McpInvocationContext.McpInvocationContext, scope),
70
+ McpToolAccessTestkit.liveThreadsLayer,
71
+ Layer.mock(ServerSettings.ServerSettingsService)({
72
+ getSettings: Effect.succeed(settings),
73
+ }),
74
+ );
75
+ const toolkit = yield* PreviewControlsToolkit.pipe(
76
+ Effect.provide(
77
+ McpToolAccess.HandlersLayer.layer(PreviewControlsHandlers.layer).pipe(
78
+ Layer.provide(layerDependencies),
79
),
82
- );
83
- const listed = yield* toolkit
84
- .handle("t3_preview_list", {})
85
- .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
86
- const closed = yield* toolkit
87
- .handle("t3_preview_close", { tabId: tab.tabId })
88
- .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
89
- if (projectAccess) {
90
- expect(listed.at(-1)?.result).toMatchObject({ sessions: [tab], nextCursor: null });
91
- expect(closed.at(-1)?.result).toEqual({});
92
- expect((yield* manager.list({ threadId })).sessions).toEqual([]);
93
- } else {
94
- for (const result of [listed, closed]) {
95
- expect(result.at(-1)?.result).toMatchObject({
96
- _tag: "PreviewAutomationUnavailableError",
97
- capability: "preview",
98
- threadId,
99
- });
100
- }
101
- expect((yield* manager.list({ threadId })).sessions).toEqual([tab]);
80
+ ),
81
+ );
82
+ const listed = yield* toolkit
83
+ .handle("t3_preview_list", {})
84
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
85
+ const closed = yield* toolkit
86
+ .handle("t3_preview_close", { tabId: tab.tabId })
87
+ .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies));
88
+ if (projectAccess) {
89
+ expect(listed.at(-1)?.result).toMatchObject({ sessions: [tab], nextCursor: null });
90
+ expect(closed.at(-1)?.result).toEqual({});
91
+ expect((yield* manager.list({ threadId })).sessions).toEqual([]);
92
+ } else {
93
+ for (const result of [listed, closed]) {
94
+ expect(result.at(-1)?.result).toMatchObject({
95
+ _tag: "PreviewAutomationUnavailableError",
96
+ capability: "preview",
97
+ threadId,
98
+ });
99
}
103
- }),
104
- ),
100
+ expect((yield* manager.list({ threadId })).sessions).toEqual([tab]);
101
+ }
102
+ }),
103
);
apps/server/src/observability/DefectReporter.test.ts
+1
-1
@@ -78,6 +78,6 @@ describe("DefectReporter", () => {
78
assert.equal(next, 2);
79
assert.equal(yield* Queue.size(logs), 0);
80
}),
81
- ).pipe(Effect.scoped),
81
+ ),
82
);
83
});
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+80
-80
@@ -1174,7 +1174,7 @@ describe("AcpAdapterV2", () => {
1174
items.map(() => "completed"),
1175
"terminal output must not reopen a tool the agent completed",
1176
);
1177
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1177
+ }).pipe(Effect.provide(layerTest)),
1178
);
1179
1180
it.live("reports per-turn usage unavailable on a continuation turn that never prompts", () =>
@@ -1294,7 +1294,7 @@ describe("AcpAdapterV2", () => {
1294
outputTokens: 30,
1295
});
1296
assert.equal(promptOrdinal, 2, "continuation turn must not dispatch session/prompt");
1297
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1297
+ }).pipe(Effect.provide(layerTest)),
1298
);
1299
it.live("fails an end_turn the outcome check rejects and restarts before the next turn", () =>
1300
Effect.gen(function* () {
@@ -1391,7 +1391,7 @@ describe("AcpAdapterV2", () => {
1391
assert.include(promptTexts[1] ?? "", "T3 Code interaction mode: Default");
1392
assert.equal(watchedSessions.length, 2);
1393
assert.equal(watchedSessions[0], watchedSessions[1]);
1394
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1394
+ }).pipe(Effect.provide(layerTest)),
1395
);
1396
it.live("retains returned usage when Stop finalizes before the prompt callback", () =>
1397
Effect.gen(function* () {
@@ -1480,7 +1480,7 @@ describe("AcpAdapterV2", () => {
1480
},
1481
);
1482
yield* Deferred.succeed(releaseCompletion, undefined);
1483
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1483
+ }).pipe(Effect.provide(layerTest)),
1484
);
1485
1486
it.live("drops a late prompt response that lands after the turn finalized", () =>
@@ -1606,7 +1606,7 @@ describe("AcpAdapterV2", () => {
1606
});
1607
stopCollector = true;
1608
yield* Fiber.interrupt(collector);
1609
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1609
+ }).pipe(Effect.provide(layerTest)),
1610
);
1611
1612
it.live("keeps usage unavailable for undeclared agents even when they report usage", () =>
@@ -1674,7 +1674,7 @@ describe("AcpAdapterV2", () => {
1674
{ usageScope: "main_agent", usageStatus: "unavailable", hasSubagents: false },
1675
);
1676
}
1677
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1677
+ }).pipe(Effect.provide(layerTest)),
1678
);
1679
1680
it.live.each(["details", "none"] as const)(
@@ -1816,7 +1816,7 @@ describe("AcpAdapterV2", () => {
1816
const nextEvents = yield* runTurn(2);
1817
const next = nextEvents.at(-1);
1818
assert.equal(next?.type === "turn.terminal" ? next.status : undefined, "completed");
1819
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1819
+ }).pipe(Effect.provide(layerTest)),
1820
);
1821
1822
// Droid 0.243.0 and OpenCode 2.1 pair each choice with an optional free-form companion field.
@@ -2158,7 +2158,7 @@ describe("AcpAdapterV2", () => {
2158
Stream.runHead,
2159
);
2160
assert.equal(Option.getOrThrow(terminal).status, "completed");
2161
- }).pipe(Effect.provide(layerTest), Effect.scoped);
2161
+ }).pipe(Effect.provide(layerTest));
2162
});
2163
2164
it.live.each(["failed", "recovered", "cancelled"] as const)(
@@ -2242,7 +2242,7 @@ describe("AcpAdapterV2", () => {
2242
assert.equal(retries.at(-1)?.status, "completed");
2243
assert.equal(retries.at(-1)?.title, "Provider recovered");
2244
}
2245
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2245
+ }).pipe(Effect.provide(layerTest)),
2246
);
2247
2248
it.live.each([
@@ -2405,7 +2405,7 @@ describe("AcpAdapterV2", () => {
2405
});
2406
assert.equal(switchedModel.textBlockCount, 2);
2407
assert.include(switchedModel.prompt, "as composer-2");
2408
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2408
+ }).pipe(Effect.provide(layerTest)),
2409
);
2410
2411
it.live.each(["cancelled", "refusal", "error"] as const)(
@@ -2541,7 +2541,7 @@ describe("AcpAdapterV2", () => {
2541
yield* runTurn("Continue after the undelivered prompt."),
2542
"Continue after the undelivered prompt.",
2543
);
2544
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2544
+ }).pipe(Effect.provide(layerTest)),
2545
);
2546
2547
it.live(
@@ -2570,7 +2570,7 @@ describe("AcpAdapterV2", () => {
2570
yield* runTurn("Continue after the focused compact."),
2571
"Continue after the focused compact.",
2572
);
2573
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2573
+ }).pipe(Effect.provide(layerTest)),
2574
);
2575
2576
it.live.each([false, true])(
@@ -2613,7 +2613,7 @@ describe("AcpAdapterV2", () => {
2613
),
2614
1,
2615
);
2616
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2616
+ }).pipe(Effect.provide(layerTest)),
2617
);
2618
2619
it.live.each([
@@ -2644,7 +2644,7 @@ describe("AcpAdapterV2", () => {
2644
ProviderAdapter.ProviderCompactionUnsupportedError,
2645
);
2646
}
2647
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2647
+ }).pipe(Effect.provide(layerTest)),
2648
);
2649
2650
it.live("reapplies a selection after a switch away from it failed partway", () =>
@@ -2729,7 +2729,7 @@ describe("AcpAdapterV2", () => {
2729
["composer-2"],
2730
"the native model was left on B, so the turn on A must set it back first",
2731
);
2732
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2732
+ }).pipe(Effect.provide(layerTest)),
2733
);
2734
2735
// regression: #21499 turns blocked only on T3 thread waits must show as waiting
@@ -2860,7 +2860,7 @@ describe("AcpAdapterV2", () => {
2860
);
2861
}
2862
assert.deepEqual(states, [true, false, true, false]);
2863
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2863
+ }).pipe(Effect.provide(layerTest)),
2864
);
2865
2866
const textChunk = (
@@ -3018,7 +3018,7 @@ describe("AcpAdapterV2", () => {
3018
assert.equal(new Set(snapshots.map((item) => DateTime.formatIso(item.startedAt!))).size, 1);
3019
assert.equal(snapshots.at(-1)?.status, "completed");
3020
}
3021
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3021
+ }).pipe(Effect.provide(layerTest)),
3022
);
3023
3024
it.effect("ignores a text flush scheduled before an ACP segment resumed", () =>
@@ -3046,7 +3046,7 @@ describe("AcpAdapterV2", () => {
3046
["ABCDE", true],
3047
["ABCDE", false],
3048
]);
3049
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3049
+ }).pipe(Effect.provide(layerTest)),
3050
);
3051
3052
it.effect("starts a new replay message after ACP v2 plan boundaries", () =>
@@ -3146,7 +3146,7 @@ describe("AcpAdapterV2", () => {
3146
snapshot.reasoningMessageIds,
3147
snapshot.messages.slice(2).map((message) => message.id),
3148
);
3149
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3149
+ }).pipe(Effect.provide(layerTest)),
3150
);
3151
3152
it.effect("persists a bounded subset of streamed root and child tool updates", () =>
@@ -3315,7 +3315,7 @@ describe("AcpAdapterV2", () => {
3315
);
3316
}
3317
}
3318
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3318
+ }).pipe(Effect.provide(layerTest)),
3319
);
3320
3321
it.effect("keeps Devin parent paragraphs intact while projecting native child work", () =>
@@ -3636,7 +3636,7 @@ describe("AcpAdapterV2", () => {
3636
);
3637
assert.equal(parentTools.length, 2);
3638
assert.equal(parentTools[0]?.title, "Parent tool finished");
3639
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3639
+ }).pipe(Effect.provide(layerTest)),
3640
);
3641
3642
it.effect("routes interleaved Copilot subagent output into subagent threads", () =>
@@ -3831,7 +3831,7 @@ describe("AcpAdapterV2", () => {
3831
assert.isFalse(
3832
items.some((item) => item.threadId === threadId && item.type === "dynamic_tool"),
3833
);
3834
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3834
+ }).pipe(Effect.provide(layerTest)),
3835
);
3836
3837
it.effect("keeps protocol diagnostics off unless a protocol logger is supplied", () =>
@@ -3914,7 +3914,7 @@ describe("AcpAdapterV2", () => {
3914
}));
3915
assert.isTrue(explicit.some((e) => e.direction === "incoming" && e.stage === "raw"));
3916
assert.isTrue(explicit.some((e) => e.direction === "outgoing"));
3917
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3917
+ }).pipe(Effect.provide(layerTest)),
3918
);
3919
3920
it.effect("advertises ACP session notices and shows them as system notices", () =>
@@ -3993,7 +3993,7 @@ describe("AcpAdapterV2", () => {
3993
["before the notice, after the notice"],
3994
"a notice neither joins the reply nor splits it",
3995
);
3996
- }).pipe(Effect.provide(layerTest), Effect.scoped),
3996
+ }).pipe(Effect.provide(layerTest)),
3997
);
3998
3999
it.effect("projects ACP v2 fidelity updates into first-class orchestration items", () =>
@@ -4188,7 +4188,7 @@ describe("AcpAdapterV2", () => {
4188
afterOmittedPatch.messages.some((message) => message.text === "late authoritative text"),
4189
"omitted late message content must preserve the authoritative text",
4190
);
4191
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4191
+ }).pipe(Effect.provide(layerTest)),
4192
);
4193
4194
it.effect("projects only the tail of long ACP terminal output", () =>
@@ -4249,7 +4249,7 @@ describe("AcpAdapterV2", () => {
4249
assert.isAtLeast(outputs.length, 2);
4250
assert.isAtMost(Math.max(...outputs.map((output) => output.length)), 320 * 1024);
4251
assert.equal(outputs.at(-1), fullOutput.slice(-320 * 1024));
4252
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4252
+ }).pipe(Effect.provide(layerTest)),
4253
);
4254
4255
it.live(
@@ -4327,7 +4327,7 @@ describe("AcpAdapterV2", () => {
4327
nativeTurnId: "persisted-session:turn:1",
4328
}),
4329
);
4330
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4330
+ }).pipe(Effect.provide(layerTest)),
4331
);
4332
4333
it.live("creates a fresh ACP identity when recovering an exhausted target", () =>
@@ -4417,7 +4417,7 @@ describe("AcpAdapterV2", () => {
4417
);
4418
const methods = yield* pollProtocolMethods(protocolEvents);
4419
assert.equal(methods.filter((method) => method === "session/new").length, 2);
4420
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4420
+ }).pipe(Effect.provide(layerTest)),
4421
);
4422
4423
it.live("preserves new-session fallback when an eager ACP session load is stale", () =>
@@ -4515,7 +4515,7 @@ describe("AcpAdapterV2", () => {
4515
),
4516
}),
4517
);
4518
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4518
+ }).pipe(Effect.provide(layerTest)),
4519
);
4520
4521
it.live("replaces an unexpectedly terminated ACP runtime before the next turn", () =>
@@ -4587,7 +4587,7 @@ describe("AcpAdapterV2", () => {
4587
);
4588
assert.equal(runtimeOrdinalSeen, 2);
4589
assert.lengthOf(runtimeInputs, 2);
4590
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4590
+ }).pipe(Effect.provide(layerTest)),
4591
);
4592
4593
it.effect("fails a prompt its agent leaves silent past the inactivity timeout", () =>
@@ -4623,7 +4623,7 @@ describe("AcpAdapterV2", () => {
4623
assert.include(silent?.failure?.message, "15 minutes");
4624
assert.equal(next?.status, "completed");
4625
assert.lengthOf(harness.natives, 2);
4626
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4626
+ }).pipe(Effect.provide(layerTest)),
4627
);
4628
4629
it.effect(
@@ -4661,7 +4661,7 @@ describe("AcpAdapterV2", () => {
4661
const [silent, next] = yield* harness.terminals(2);
4662
assert.equal(silent?.status, "failed");
4663
assert.equal(next?.status, "completed");
4664
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4664
+ }).pipe(Effect.provide(layerTest)),
4665
);
4666
4667
it.effect("delivers a follow-up the agent rejects while it is still processing", () =>
@@ -4697,7 +4697,7 @@ describe("AcpAdapterV2", () => {
4697
const [delivered] = yield* Fiber.join(followUp);
4698
assert.equal(delivered?.status, "completed");
4699
assert.equal(promptCalls, 3);
4700
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4700
+ }).pipe(Effect.provide(layerTest)),
4701
);
4702
4703
it.effect("sends no more prompts once a follow-up waiting on a busy agent is stopped", () =>
@@ -4745,7 +4745,7 @@ describe("AcpAdapterV2", () => {
4745
yield* Fiber.join(interrupt);
4746
assert.equal(terminal?.status, "interrupted");
4747
assert.equal(promptCalls, 2);
4748
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4748
+ }).pipe(Effect.provide(layerTest)),
4749
);
4750
4751
it.effect("holds the inactivity timeout while the agent waits on an approval", () =>
@@ -4786,7 +4786,7 @@ describe("AcpAdapterV2", () => {
4786
const [approved] = yield* harness.terminals(1);
4787
assert.equal(approved?.status, "completed");
4788
assert.lengthOf(harness.natives, 1);
4789
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4789
+ }).pipe(Effect.provide(layerTest)),
4790
);
4791
4792
it.effect("fails a running prompt once when its agent process exits", () =>
@@ -4822,7 +4822,7 @@ describe("AcpAdapterV2", () => {
4822
assert.notEqual(silent?.providerTurnId, exited?.providerTurnId);
4823
assert.equal(next?.status, "completed");
4824
assert.lengthOf(harness.natives, 3);
4825
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4825
+ }).pipe(Effect.provide(layerTest)),
4826
);
4827
4828
it.live("does not poll the process ledger while a cgroup lease owns teardown", () =>
@@ -4919,7 +4919,7 @@ describe("AcpAdapterV2", () => {
4919
yield* Scope.close(sessionScope, Exit.void);
4920
assert.isFalse(isLive(agentPid!), "closing the session must still tear the agent down");
4921
assert.isFalse(leaseExists, "closing the session must remove the lease");
4922
- }).pipe(Effect.provide(layerTest), Effect.scoped),
4922
+ }).pipe(Effect.provide(layerTest)),
4923
);
4924
4925
it.effect("negotiates and executes optional native session forks through the ACP runtime", () =>
@@ -5117,7 +5117,7 @@ describe("AcpAdapterV2", () => {
5117
terminalOutput.output,
5118
"thread-acp-native-fork-target\nBearer target-thread-token",
5119
);
5120
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5120
+ }).pipe(Effect.provide(layerTest)),
5121
);
5122
5123
it.effect(
@@ -5208,7 +5208,7 @@ describe("AcpAdapterV2", () => {
5208
{ method: "fs/read_text_file", errorCode: -32601 },
5209
]);
5210
assert.isFalse(yield* fileSystem.exists(probePath));
5211
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5211
+ }).pipe(Effect.provide(layerTest)),
5212
);
5213
5214
it.effect("does not turn an unknown permission approval into an execute grant", () =>
@@ -5335,7 +5335,7 @@ describe("AcpAdapterV2", () => {
5335
providerTurnId: pending.runtimeRequest.providerTurnId,
5336
});
5337
yield* Fiber.join(turnFiber);
5338
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5338
+ }).pipe(Effect.provide(layerTest)),
5339
);
5340
5341
it.effect.each([
@@ -5506,7 +5506,7 @@ describe("AcpAdapterV2", () => {
5506
5507
yield* runtime.interruptTurn({ providerThread, providerTurnId });
5508
yield* Fiber.join(turnFiber);
5509
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5509
+ }).pipe(Effect.provide(layerTest)),
5510
);
5511
5512
it.effect.each([
@@ -5637,7 +5637,7 @@ describe("AcpAdapterV2", () => {
5637
});
5638
yield* Fiber.join(turnFiber);
5639
assert.deepEqual(outcome, { outcome: "selected", optionId });
5640
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5640
+ }).pipe(Effect.provide(layerTest)),
5641
);
5642
5643
it.effect("replaces the ACP session and clears conversation state on rollback", () =>
@@ -5820,7 +5820,7 @@ describe("AcpAdapterV2", () => {
5820
assert.lengthOf(prompts, 2);
5821
// The mock agent reuses its session id, so only the rollback reset resends these notes.
5822
assert.include(prompts[1]?.at(-1)?.text ?? "", "<runtime_info>");
5823
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5823
+ }).pipe(Effect.provide(layerTest)),
5824
);
5825
5826
it.effect("resends T3 notes after rollback when the replaced runtime's prompt settles late", () =>
@@ -5948,7 +5948,7 @@ describe("AcpAdapterV2", () => {
5948
const replacementPrompt = yield* Deferred.await(replacementPromptText);
5949
assert.include(replacementPrompt, "T3 Code interaction mode: Default");
5950
assert.include(replacementPrompt, "<runtime_info>");
5951
- }).pipe(Effect.provide(layerTest), Effect.scoped),
5951
+ }).pipe(Effect.provide(layerTest)),
5952
);
5953
5954
it.effect("quarantines callbacks from a failed rollback replacement before retrying", () =>
@@ -6097,7 +6097,7 @@ describe("AcpAdapterV2", () => {
6097
status: "running",
6098
});
6099
assert.isFalse(yield* hasPendingBackgroundWork);
6100
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6100
+ }).pipe(Effect.provide(layerTest)),
6101
);
6102
6103
it.live("settles a Grok background command that completed before an ACP v2 idle error", () =>
@@ -6160,7 +6160,7 @@ describe("AcpAdapterV2", () => {
6160
command?.type === "turn_item.updated" ? command.turnItem.status : undefined,
6161
"completed",
6162
);
6163
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6163
+ }).pipe(Effect.provide(layerTest)),
6164
);
6165
6166
it.effect("closes the ACP runtime when the agent never answers session/close", () =>
@@ -6303,7 +6303,7 @@ describe("AcpAdapterV2", () => {
6303
items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"),
6304
"command TaskOutput must retain its normal tool frame",
6305
);
6306
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6306
+ }).pipe(Effect.provide(layerTest)),
6307
);
6308
6309
// Grok expands only a leading `/name`, so a picked leading `$name`
@@ -6383,7 +6383,7 @@ describe("AcpAdapterV2", () => {
6383
assert.isTrue(blocks.some((block) => block.text.includes(sent)));
6384
assert.isFalse(blocks.some((block) => block.text.trimStart().startsWith("/")));
6385
}
6386
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6386
+ }).pipe(Effect.provide(layerTest)),
6387
);
6388
6389
// Command completion must release the turn even when the CLI keeps the prompt RPC and process
@@ -6479,7 +6479,7 @@ describe("AcpAdapterV2", () => {
6479
items.some((item) => item.nativeItemRef?.nativeId === "kill-command"),
6480
"KillTask must retain its normal tool frame",
6481
);
6482
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6482
+ }).pipe(Effect.provide(layerTest)),
6483
);
6484
6485
it.effect("keeps an agent's empty-valued default choice selectable", () =>
@@ -6575,7 +6575,7 @@ describe("AcpAdapterV2", () => {
6575
)
6576
.map((event) => rawProtocolRequestParam(event, "value"));
6577
assert.deepEqual(sentAgentValues, ["example", ""]);
6578
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6578
+ }).pipe(Effect.provide(layerTest)),
6579
);
6580
6581
it.live("terminalizes an empty successful foreground Bash tool when the turn completes", () =>
@@ -6714,7 +6714,7 @@ describe("AcpAdapterV2", () => {
6714
Stream.runHead,
6715
);
6716
assert.isTrue(Option.isSome(loadAfterRestart));
6717
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6717
+ }).pipe(Effect.provide(layerTest)),
6718
);
6719
6720
it.effect("drains native ACP cancellation before admitting the next prompt", () =>
@@ -6818,7 +6818,7 @@ describe("AcpAdapterV2", () => {
6818
),
6819
);
6820
assert.equal(nextTerminal.type === "turn.terminal" && nextTerminal.status, "completed");
6821
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6821
+ }).pipe(Effect.provide(layerTest)),
6822
);
6823
6824
it.effect("cancels pending permission requests while interrupting an ACP turn", () =>
@@ -6909,7 +6909,7 @@ describe("AcpAdapterV2", () => {
6909
),
6910
);
6911
assert.equal(terminal.type, "turn.terminal");
6912
- }).pipe(Effect.provide(layerTest), Effect.scoped),
6912
+ }).pipe(Effect.provide(layerTest)),
6913
);
6914
6915
it.live("keeps hard teardown excluded until a permission response is enqueued", () =>
@@ -6998,7 +6998,7 @@ describe("AcpAdapterV2", () => {
6998
yield* Deferred.succeed(releaseResponseAcknowledgement, undefined);
6999
yield* Fiber.join(responseFiber);
7000
yield* Fiber.join(interruptFiber);
7001
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7001
+ }).pipe(Effect.provide(layerTest)),
7002
);
7003
7004
it.live("asks form fields with their fixed choices and answers in the declared types", () =>
@@ -7117,7 +7117,7 @@ describe("AcpAdapterV2", () => {
7117
note: "hi",
7118
},
7119
});
7120
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7120
+ }).pipe(Effect.provide(layerTest)),
7121
);
7122
7123
it.live("keeps explicit empty selections and checks selection counts", () =>
@@ -7167,7 +7167,7 @@ describe("AcpAdapterV2", () => {
7167
answer: () => ({ all: ["a"], some: ["a"] }),
7168
});
7169
assert.deepStrictEqual(requiredOmitted.response, { action: "cancel" });
7170
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7170
+ }).pipe(Effect.provide(layerTest)),
7171
);
7172
7173
it.live("answers a field named __proto__ like any other field", () =>
@@ -7192,7 +7192,7 @@ describe("AcpAdapterV2", () => {
7192
action: "accept",
7193
content: { ["__proto__"]: "b", name: "hi" },
7194
});
7195
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7195
+ }).pipe(Effect.provide(layerTest)),
7196
);
7197
7198
it.live("declines a form whose selection counts the client cannot answer, without asking", () =>
@@ -7214,7 +7214,7 @@ describe("AcpAdapterV2", () => {
7214
assert.isUndefined(questions);
7215
assert.deepStrictEqual(response, { action: "decline" });
7216
}
7217
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7217
+ }).pipe(Effect.provide(layerTest)),
7218
);
7219
7220
it.live("cancels a form whose required answer does not fit, or that is dismissed", () =>
@@ -7236,7 +7236,7 @@ describe("AcpAdapterV2", () => {
7236
answer: () => undefined,
7237
});
7238
assert.deepStrictEqual(dismissed.response, { action: "cancel" });
7239
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7239
+ }).pipe(Effect.provide(layerTest)),
7240
);
7241
7242
it.live("declines a form with a field it cannot ask for, without asking", () =>
@@ -7254,7 +7254,7 @@ describe("AcpAdapterV2", () => {
7254
});
7255
assert.isUndefined(questions);
7256
assert.deepStrictEqual(response, { action: "decline" });
7257
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7257
+ }).pipe(Effect.provide(layerTest)),
7258
);
7259
7260
it.live("auto-approves tagged MCP elicitations under full-access policy", () =>
@@ -7312,7 +7312,7 @@ describe("AcpAdapterV2", () => {
7312
7313
assert.isFalse(events.some((event) => event.type === "runtime_request.updated"));
7314
assert.isTrue(events.some((event) => event.type === "turn.terminal"));
7315
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7315
+ }).pipe(Effect.provide(layerTest)),
7316
);
7317
7318
it.live("fails a held native response acknowledgement before normal session close", () =>
@@ -7410,7 +7410,7 @@ describe("AcpAdapterV2", () => {
7410
assert.include(responseLifecycle, "failed");
7411
yield* Deferred.succeed(releaseResponseAcknowledgement, undefined);
7412
yield* Fiber.join(closeFiber);
7413
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7413
+ }).pipe(Effect.provide(layerTest)),
7414
);
7415
7416
it.live("treats a second hard Stop as success when the turn is already gone", () =>
@@ -7499,7 +7499,7 @@ describe("AcpAdapterV2", () => {
7499
}
7500
}
7501
assert.equal(terminal, "interrupted");
7502
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7502
+ }).pipe(Effect.provide(layerTest)),
7503
);
7504
7505
it.effect(
@@ -7635,7 +7635,7 @@ describe("AcpAdapterV2", () => {
7635
}
7636
assert.equal(carriedItemStatus, "completed");
7637
assert.equal(secondTerminalStatus, "completed");
7638
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7638
+ }).pipe(Effect.provide(layerTest)),
7639
);
7640
7641
it.effect(
@@ -7845,7 +7845,7 @@ describe("AcpAdapterV2", () => {
7845
"finalize-window terminal must clear the carryover pin",
7846
);
7847
}).pipe(Effect.provideService(Clock.Clock, blockingClock));
7848
- }).pipe(Effect.provide(layerTest), Effect.scoped),
7848
+ }).pipe(Effect.provide(layerTest)),
7849
);
7850
7851
it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () =>
@@ -8083,7 +8083,7 @@ describe("AcpAdapterV2", () => {
8083
"buffered spawn ACK must not create a continuation-owned turn item",
8084
);
8085
assert.isFalse(yield* hasPendingBackgroundWork);
8086
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8086
+ }).pipe(Effect.provide(layerTest)),
8087
);
8088
8089
it.effect(
@@ -8374,7 +8374,7 @@ describe("AcpAdapterV2", () => {
8374
"queued continuation must drain the wake content after the user run",
8375
);
8376
assert.isFalse(yield* hasPendingBackgroundWork);
8377
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8377
+ }).pipe(Effect.provide(layerTest)),
8378
);
8379
8380
it.effect(
@@ -8532,7 +8532,7 @@ describe("AcpAdapterV2", () => {
8532
1,
8533
"settled soft steer must not respawn the ACP runtime process",
8534
);
8535
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8535
+ }).pipe(Effect.provide(layerTest)),
8536
);
8537
8538
it.live("preserveRuntimeOnSettledInterrupt does not soften a mid-prompt steering interrupt", () =>
@@ -8605,7 +8605,7 @@ describe("AcpAdapterV2", () => {
8605
assert.fail("mid-prompt steering interrupt must still take the hard teardown path");
8606
}
8607
assert.include(Cause.pretty(interruptExit.cause), "session is poisoned");
8608
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8608
+ }).pipe(Effect.provide(layerTest)),
8609
);
8610
8611
it.live("direct Stop quarantine drops late background task mutations from the stopped run", () =>
@@ -8738,7 +8738,7 @@ describe("AcpAdapterV2", () => {
8738
yield* hasPendingBackgroundWork,
8739
"direct Stop quarantine must drop residual background task mutations from the stopped run",
8740
);
8741
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8741
+ }).pipe(Effect.provide(layerTest)),
8742
);
8743
8744
it.effect(
@@ -8877,7 +8877,7 @@ describe("AcpAdapterV2", () => {
8877
yield* hasPendingBackgroundWork,
8878
"wake buffer must not stay non-empty and pin idle release after an already-handled re-report",
8879
);
8880
- }).pipe(Effect.provide(layerTest), Effect.scoped),
8880
+ }).pipe(Effect.provide(layerTest)),
8881
);
8882
8883
it.effect("keeps a buffered continuation current when a user turn starts before dispatch", () =>
@@ -9076,7 +9076,7 @@ describe("AcpAdapterV2", () => {
9076
assert.equal(continuationTerminalStatus, "completed");
9077
assert.isTrue(bufferedTextSeen, "continuation must drain the wake buffer after the user run");
9078
assert.isFalse(yield* hasPendingBackgroundWork);
9079
- }).pipe(Effect.provide(layerTest), Effect.scoped),
9079
+ }).pipe(Effect.provide(layerTest)),
9080
);
9081
9082
it.effect(
@@ -9280,7 +9280,7 @@ describe("AcpAdapterV2", () => {
9280
1,
9281
"exactly one continuation when the last running task ends post-finalize with kept midTurn marks",
9282
);
9283
- }).pipe(Effect.provide(layerTest), Effect.scoped),
9283
+ }).pipe(Effect.provide(layerTest)),
9284
);
9285
9286
it.effect(
@@ -9641,7 +9641,7 @@ describe("AcpAdapterV2", () => {
9641
yield* hasPendingBackgroundWork,
9642
"wake buffer must not retain turn-1 or turn-2 in-turn-handled ack residue",
9643
);
9644
- }).pipe(Effect.provide(layerTest), Effect.scoped),
9644
+ }).pipe(Effect.provide(layerTest)),
9645
);
9646
9647
it.effect("a wake names work that ended while the previous wake was queued", () =>
@@ -9785,7 +9785,7 @@ describe("AcpAdapterV2", () => {
9785
outcome: "completed",
9786
summary: 'Command "sleep b" finished',
9787
});
9788
- }).pipe(Effect.provide(layerTest), Effect.scoped),
9788
+ }).pipe(Effect.provide(layerTest)),
9789
);
9790
9791
it.effect.each([
@@ -10003,7 +10003,7 @@ describe("AcpAdapterV2", () => {
10003
1,
10004
"duplicate completions must not offer another continuation",
10005
);
10006
- }).pipe(Effect.provide(layerTest), Effect.scoped),
10006
+ }).pipe(Effect.provide(layerTest)),
10007
);
10008
10009
it.live("durably poisons start and resume when required hard teardown is unavailable", () =>
@@ -10083,7 +10083,7 @@ describe("AcpAdapterV2", () => {
10083
.pipe(Effect.exit);
10084
if (Exit.isSuccess(resumeExit)) assert.fail("poisoned session must reject resumeThread");
10085
assert.include(Cause.pretty(resumeExit.cause), "session is poisoned");
10086
- }).pipe(Effect.provide(layerTest), Effect.scoped),
10086
+ }).pipe(Effect.provide(layerTest)),
10087
);
10088
10089
it.live("holds concurrent startTurn behind successful hard teardown and reloads once", () =>
@@ -10187,7 +10187,7 @@ describe("AcpAdapterV2", () => {
10187
Stream.runHead,
10188
);
10189
}
10190
- }).pipe(Effect.provide(layerTest), Effect.scoped),
10190
+ }).pipe(Effect.provide(layerTest)),
10191
);
10192
10193
it.live("lets a caller abandon Stop while hard teardown stalls, and finishes the teardown", () =>
@@ -10274,7 +10274,7 @@ describe("AcpAdapterV2", () => {
10274
assert.equal(runtimeOrdinalSeen, 2);
10275
const replacementMethods = yield* pollProtocolMethods(protocolEvents);
10276
assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1);
10277
- }).pipe(Effect.provide(layerTest), Effect.scoped),
10277
+ }).pipe(Effect.provide(layerTest)),
10278
);
10279
10280
it.effect(
@@ -10420,7 +10420,7 @@ describe("AcpAdapterV2", () => {
10420
carriedCompleted,
10421
"Direct Stop must not carry a stopped subagent into the follow-up run",
10422
);
10423
- }).pipe(Effect.provide(layerTest), Effect.scoped),
10423
+ }).pipe(Effect.provide(layerTest)),
10424
);
10425
});
10426
apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts
+23
-23
@@ -656,7 +656,7 @@ describe("AcpRegistryAdapterV2", () => {
656
answer("session/set_mode", {}),
657
],
658
storedModePick: "autoEdit",
659
- }).pipe(Effect.provide(layerTest), Effect.scoped),
659
+ }).pipe(Effect.provide(layerTest)),
660
);
661
662
it.effect("switches a mode config option under its own id", () =>
@@ -671,7 +671,7 @@ describe("AcpRegistryAdapterV2", () => {
671
answer("session/set_config_option", { configOptions: [permissionModeOption("auto")] }),
672
],
673
storedModePick: "auto",
674
- }).pipe(Effect.provide(layerTest), Effect.scoped),
674
+ }).pipe(Effect.provide(layerTest)),
675
);
676
677
const modelOption = (id: string, currentValue: string, grouped = false) => ({
@@ -801,7 +801,7 @@ describe("AcpRegistryAdapterV2", () => {
801
{ models: ["hermes", "auto", "default"], current: "hermes" },
802
],
803
);
804
- }).pipe(Effect.provide(layerTest), Effect.scoped),
804
+ }).pipe(Effect.provide(layerTest)),
805
);
806
807
// Copilot's session/new reports its built-in default, not the model it will run
@@ -879,7 +879,7 @@ describe("AcpRegistryAdapterV2", () => {
879
configOptions: [copilotModel("claude-sonnet-5.5"), effort("xhigh")],
880
}),
881
],
882
- }).pipe(Effect.provide(layerTest), Effect.scoped);
882
+ }).pipe(Effect.provide(layerTest));
883
},
884
);
885
@@ -941,7 +941,7 @@ describe("AcpRegistryAdapterV2", () => {
941
}),
942
]
943
: [],
944
- }).pipe(Effect.provide(layerTest), Effect.scoped);
944
+ }).pipe(Effect.provide(layerTest));
945
},
946
);
947
@@ -992,7 +992,7 @@ describe("AcpRegistryAdapterV2", () => {
992
configurations.map((configuration) => configuration?.currentModelId),
993
["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"],
994
);
995
- }).pipe(Effect.provide(layerTest), Effect.scoped),
995
+ }).pipe(Effect.provide(layerTest)),
996
);
997
it.effect(
998
"fails configuration when an option write errors for a reason other than refusal",
@@ -1040,7 +1040,7 @@ describe("AcpRegistryAdapterV2", () => {
1040
},
1041
},
1042
],
1043
- }).pipe(Effect.provide(layerTest), Effect.scoped);
1043
+ }).pipe(Effect.provide(layerTest));
1044
},
1045
);
1046
const modelOptions = [
@@ -1124,7 +1124,7 @@ describe("AcpRegistryAdapterV2", () => {
1124
storedModel: model,
1125
});
1126
assert.equal(opened.configurations.at(-1)?.currentModelId, "codex");
1127
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1127
+ }).pipe(Effect.provide(layerTest)),
1128
);
1129
});
1130
@@ -1220,7 +1220,7 @@ describe("AcpRegistryAdapterV2", () => {
1220
const terminal = completed.at(-1)!;
1221
if (terminal.type !== "turn.terminal") throw new Error("Missing fallback terminal");
1222
assert.equal(terminal.status, "completed");
1223
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1223
+ }).pipe(Effect.provide(layerTest)),
1224
);
1225
1226
// regression: #26695 cancelling a Copilot prompt kills its background agents
@@ -1256,7 +1256,7 @@ describe("AcpRegistryAdapterV2", () => {
1256
...copilot,
1257
supportsSteeringByInterruptRestart: true,
1258
});
1259
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1259
+ }).pipe(Effect.provide(layerTest)),
1260
);
1261
1262
it.effect("gives Copilot T3's MCP server over HTTP when it advertises HTTP", () =>
@@ -1389,7 +1389,7 @@ describe("AcpRegistryAdapterV2", () => {
1389
new: stdio("Bearer opened-token"),
1390
load: stdio("Bearer rotated-token"),
1391
});
1392
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1392
+ }).pipe(Effect.provide(layerTest)),
1393
);
1394
1395
it.effect("the agent process env names the thread it serves", () =>
@@ -1468,7 +1468,7 @@ describe("AcpRegistryAdapterV2", () => {
1468
assert.equal(agentEnvironment?.T3CODE_THREAD_ID, "thread-acp-registry-thread-env");
1469
assert.equal(agentEnvironment?.T3_ACP_MCP_ENDPOINT, endpoint);
1470
assert.equal(agentEnvironment?.T3_ACP_MCP_AUTHORIZATION, "Bearer thread-env-token");
1471
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1471
+ }).pipe(Effect.provide(layerTest)),
1472
);
1473
1474
it.effect.each(["before", "after"] as const)(
@@ -1561,7 +1561,7 @@ describe("AcpRegistryAdapterV2", () => {
1561
);
1562
}
1563
}
1564
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1564
+ }).pipe(Effect.provide(layerTest)),
1565
);
1566
1567
it.effect("settles Claude's accepted foreground reply while retaining child output", () =>
@@ -1765,7 +1765,7 @@ describe("AcpRegistryAdapterV2", () => {
1765
),
1766
"autonomous root echoes only signal acceptance",
1767
);
1768
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1768
+ }).pipe(Effect.provide(layerTest)),
1769
);
1770
1771
it.effect.each([
@@ -1950,7 +1950,7 @@ describe("AcpRegistryAdapterV2", () => {
1950
),
1951
"detached requests are cancelled before turn admission",
1952
);
1953
- }).pipe(Effect.provide(layerTest), Effect.scoped),
1953
+ }).pipe(Effect.provide(layerTest)),
1954
);
1955
1956
it.effect("retains streamed child tool output through the generic Devin route", () =>
@@ -2087,7 +2087,7 @@ describe("AcpRegistryAdapterV2", () => {
2087
(event) => event.type === "message.updated" && event.message.text.includes("onetwo"),
2088
),
2089
);
2090
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2090
+ }).pipe(Effect.provide(layerTest)),
2091
);
2092
2093
it.effect("replaces streamed root tool output with a later content list", () =>
@@ -2150,7 +2150,7 @@ describe("AcpRegistryAdapterV2", () => {
2150
text("replacement-more"),
2151
{ type: "Text", text: "replacement-morePATCH" },
2152
]);
2153
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2153
+ }).pipe(Effect.provide(layerTest)),
2154
);
2155
2156
it.effect("keeps stopped child tools interrupted when a late output chunk arrives", () =>
@@ -2257,7 +2257,7 @@ describe("AcpRegistryAdapterV2", () => {
2257
assert.deepEqual(tools.at(-1)?.output, [
2258
{ type: "content", content: { type: "text", text: "stoppingcancelled" } },
2259
]);
2260
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2260
+ }).pipe(Effect.provide(layerTest)),
2261
);
2262
2263
it.effect("keeps native child tools interrupted after idle and late output", () =>
@@ -2297,7 +2297,7 @@ describe("AcpRegistryAdapterV2", () => {
2297
assert.deepEqual(tools.at(-1)?.output, [
2298
{ type: "content", content: { type: "text", text: "late" } },
2299
]);
2300
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2300
+ }).pipe(Effect.provide(layerTest)),
2301
);
2302
2303
it.effect.each(["error", "end_turn"])(
@@ -2593,7 +2593,7 @@ describe("AcpRegistryAdapterV2", () => {
2593
"a new execution does not append the previous execution's text",
2594
);
2595
assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!);
2596
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2596
+ }).pipe(Effect.provide(layerTest)),
2597
);
2598
2599
it.effect("fails active Claude work and releases its children when the process exits", () =>
@@ -2663,7 +2663,7 @@ describe("AcpRegistryAdapterV2", () => {
2663
event.turnItem.status === "interrupted",
2664
),
2665
);
2666
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2666
+ }).pipe(Effect.provide(layerTest)),
2667
);
2668
2669
it.effect("keeps Claude activity after a refused Stop and closes it on retry", () =>
@@ -2781,7 +2781,7 @@ describe("AcpRegistryAdapterV2", () => {
2781
assert.equal(queuedTerminal.status, "interrupted");
2782
assert.isNull(queuedTerminal.failure);
2783
assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!);
2784
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2784
+ }).pipe(Effect.provide(layerTest)),
2785
);
2786
2787
it.effect.each([
@@ -2950,6 +2950,6 @@ describe("AcpRegistryAdapterV2", () => {
2950
assert.equal(yield* runTurn(1), "failed");
2951
assert.equal(yield* runTurn(2), "completed");
2952
assert.equal(spawned, restarts ? 2 : 1);
2953
- }).pipe(Effect.provide(layerTest), Effect.scoped),
2953
+ }).pipe(Effect.provide(layerTest)),
2954
);
2955
});
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+7
-7
@@ -214,7 +214,7 @@ describe("AntigravityAdapterV2 compaction", () => {
214
assert.isUndefined(session.compactThread);
215
assert.equal(session.providerSession.capabilities.turns.supportsNativeGoals, nativeGoals);
216
assert.equal((yield* adapter.getCapabilities()).turns.supportsNativeGoals, nativeGoals);
217
- }).pipe(Effect.provide(layerSession), Effect.scoped),
217
+ }).pipe(Effect.provide(layerSession)),
218
);
219
});
220
@@ -270,7 +270,7 @@ describe("AntigravityAdapterV2 session open", () => {
270
error._tag === "ProviderAdapterOpenSessionError" && error.requiresSignIn,
271
requiresSignIn,
272
);
273
- }).pipe(Effect.provide(layerSession), Effect.scoped),
273
+ }).pipe(Effect.provide(layerSession)),
274
);
275
});
276
@@ -416,7 +416,7 @@ describe("AntigravityAdapterV2 client file system", () => {
416
context("fs/read_text_file"),
417
);
418
assert.equal(viaInsideLink.content, "inside");
419
- }).pipe(Effect.provide(layerSession), Effect.scoped),
419
+ }).pipe(Effect.provide(layerSession)),
420
);
421
});
422
@@ -586,7 +586,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
586
context,
587
).pipe(Effect.exit);
588
assert.isTrue(Exit.isFailure(fromA), "the previous workspace is no longer readable");
589
- }).pipe(Effect.provide(layerSession), Effect.scoped),
589
+ }).pipe(Effect.provide(layerSession)),
590
);
591
});
592
@@ -866,7 +866,7 @@ describe("AntigravityAdapterV2 html_render pages", () => {
866
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, report), undefined);
867
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined);
868
assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined);
869
- }).pipe(Effect.provide(layerSession), Effect.scoped),
869
+ }).pipe(Effect.provide(layerSession)),
870
);
871
});
872
@@ -1074,7 +1074,7 @@ describe("AntigravityAdapterV2 subagent reads", () => {
1074
assert.deepEqual(read("call_missing"), failed);
1075
assert.deepEqual(read("call_denied"), failed);
1076
assert.deepEqual(read("call_unseen"), failed);
1077
- }).pipe(Effect.provide(layerSession), Effect.scoped),
1077
+ }).pipe(Effect.provide(layerSession)),
1078
);
1079
});
1080
@@ -1271,6 +1271,6 @@ describe("AntigravityAdapterV2 session system prompt", () => {
1271
assert.notInclude(append, "systemPrompt");
1272
assert.include(sent, "<pull_request_linking>");
1273
}
1274
- }).pipe(Effect.provide(layerSession), Effect.scoped),
1274
+ }).pipe(Effect.provide(layerSession)),
1275
);
1276
});
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+10728
-11061
@@ -972,131 +972,125 @@ describe("ClaudeAdapterV2 session permissions", () => {
972
973
describe("ClaudeAdapterV2 Auto-accept edits", () => {
974
it.effect("asks before a command instead of allowing it", () =>
975
- Effect.scoped(
976
- Effect.gen(function* () {
977
- const fileSystem = yield* FileSystem.FileSystem;
978
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
979
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
980
- prefix: "t3-claude-accept-edits-",
981
- });
982
- let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
983
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
984
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
985
- settings: DEFAULT_CLAUDE_SETTINGS,
986
- environment: {},
987
- attachmentsDir,
988
- fileSystem,
989
- path: yield* Path.Path,
990
- random: yield* SecureRandom.SecureRandom,
991
- idAllocator,
992
- queryRunner: {
993
- allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"),
994
- open: (input) =>
995
- Effect.sync(() => {
996
- openedOptions = input.options;
997
- return {
998
- messages: Stream.never,
999
- offer: () => Effect.void,
1000
- setModel: () => Effect.void,
1001
- applyFlagSettings: () => Effect.void,
1002
- setPermissionMode: () => Effect.void,
1003
- backgroundTasks: () => Effect.succeed(false),
1004
- mcpServerStatus: Effect.succeed([]),
1005
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
1006
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
1007
- listPermissionRules: Effect.die("unexpected permission rules read"),
1008
- stopTask: () => Effect.void,
1009
- interrupt: Effect.void,
1010
- close: Effect.void,
1011
- };
1012
- }),
1013
- forkSession: () => Effect.die("unused"),
1014
- subagentLaunchToolUseId: () => Effect.succeed(null),
1015
- subagentModel: () => Effect.succeed(null),
1016
- assertComplete: Effect.void,
1017
- },
1018
- });
1019
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1020
- runtimeMode: "auto-accept-edits",
1021
- interactionMode: "default",
1022
- cwd: "/workspace",
1023
- });
1024
- const threadId = ThreadId.make("thread-claude-accept-edits");
1025
- const runtime = yield* adapter.openSession({
1026
- threadId,
1027
- providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"),
1028
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1029
- runtimePolicy,
1030
- });
1031
- const providerThread = yield* runtime.ensureThread({
975
+ Effect.gen(function* () {
976
+ const fileSystem = yield* FileSystem.FileSystem;
977
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
978
+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
979
+ prefix: "t3-claude-accept-edits-",
980
+ });
981
+ let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
982
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
983
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
984
+ settings: DEFAULT_CLAUDE_SETTINGS,
985
+ environment: {},
986
+ attachmentsDir,
987
+ fileSystem,
988
+ path: yield* Path.Path,
989
+ random: yield* SecureRandom.SecureRandom,
990
+ idAllocator,
991
+ queryRunner: {
992
+ allocateSessionId: Effect.succeed("native-thread-claude-accept-edits"),
993
+ open: (input) =>
994
+ Effect.sync(() => {
995
+ openedOptions = input.options;
996
+ return {
997
+ messages: Stream.never,
998
+ offer: () => Effect.void,
999
+ setModel: () => Effect.void,
1000
+ applyFlagSettings: () => Effect.void,
1001
+ setPermissionMode: () => Effect.void,
1002
+ backgroundTasks: () => Effect.succeed(false),
1003
+ mcpServerStatus: Effect.succeed([]),
1004
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
1005
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
1006
+ listPermissionRules: Effect.die("unexpected permission rules read"),
1007
+ stopTask: () => Effect.void,
1008
+ interrupt: Effect.void,
1009
+ close: Effect.void,
1010
+ };
1011
+ }),
1012
+ forkSession: () => Effect.die("unused"),
1013
+ subagentLaunchToolUseId: () => Effect.succeed(null),
1014
+ subagentModel: () => Effect.succeed(null),
1015
+ assertComplete: Effect.void,
1016
+ },
1017
+ });
1018
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1019
+ runtimeMode: "auto-accept-edits",
1020
+ interactionMode: "default",
1021
+ cwd: "/workspace",
1022
+ });
1023
+ const threadId = ThreadId.make("thread-claude-accept-edits");
1024
+ const runtime = yield* adapter.openSession({
1025
+ threadId,
1026
+ providerSessionId: ProviderSessionId.make("provider-session-claude-accept-edits"),
1027
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1028
+ runtimePolicy,
1029
+ });
1030
+ const providerThread = yield* runtime.ensureThread({
1031
+ threadId,
1032
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1033
+ runtimePolicy,
1034
+ });
1035
+ const now = yield* DateTime.now;
1036
+ yield* runtime.startTurn(
1037
+ makeClaudeTestTurnInput({
1038
threadId,
1033
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1039
+ providerThread,
1040
+ now,
1041
+ attemptId: RunAttemptId.make("attempt-claude-accept-edits"),
1042
+ text: "Run node.",
1043
+ attachments: [],
1044
runtimePolicy,
1035
- });
1036
- const now = yield* DateTime.now;
1037
- yield* runtime.startTurn(
1038
- makeClaudeTestTurnInput({
1039
- threadId,
1040
- providerThread,
1041
- now,
1042
- attemptId: RunAttemptId.make("attempt-claude-accept-edits"),
1043
- text: "Run node.",
1044
- attachments: [],
1045
- runtimePolicy,
1046
- }),
1047
- );
1048
- assert.equal(openedOptions?.permissionMode, "acceptEdits");
1049
- const canUseTool = openedOptions?.canUseTool;
1050
- assert.isFunction(canUseTool);
1045
+ }),
1046
+ );
1047
+ assert.equal(openedOptions?.permissionMode, "acceptEdits");
1048
+ const canUseTool = openedOptions?.canUseTool;
1049
+ assert.isFunction(canUseTool);
1050
1052
- const requestEvent = yield* runtime.events.pipe(
1053
- Stream.takeUntil(
1054
- (event) =>
1055
- event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
1056
- ),
1057
- Stream.runCollect,
1058
- Effect.forkScoped,
1059
- );
1060
- const command = { command: "node -e 'console.log(42)'" };
1061
- const decision = yield* Effect.promise(() =>
1062
- canUseTool!("Bash", command, {
1063
- signal: new AbortController().signal,
1064
- toolUseID: "tool-bash-accept-edits",
1065
- requestId: "request-bash-accept-edits",
1066
- description: "Check the Node runtime",
1067
- }),
1068
- ).pipe(Effect.forkScoped);
1069
- const first = yield* Effect.raceFirst(
1070
- Fiber.join(requestEvent).pipe(
1071
- Effect.map((event) => ({ type: "request", event }) as const),
1072
- ),
1073
- Fiber.join(decision).pipe(
1074
- Effect.map((result) => ({ type: "decision", result }) as const),
1075
- ),
1076
- );
1077
- assert.equal(first.type, "request", "the command ran without asking");
1078
- if (first.type !== "request") return;
1079
- const event = first.event.find((event) => event.type === "runtime_request.updated");
1080
- assert.equal(event?.runtimeRequest.kind, "command");
1081
- const approval = first.event.findLast((event) => event.type === "turn_item.updated");
1082
- assert.equal(
1083
- approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined,
1084
- command.command,
1085
- );
1051
+ const requestEvent = yield* runtime.events.pipe(
1052
+ Stream.takeUntil(
1053
+ (event) =>
1054
+ event.type === "turn_item.updated" && event.turnItem.type === "approval_request",
1055
+ ),
1056
+ Stream.runCollect,
1057
+ Effect.forkScoped,
1058
+ );
1059
+ const command = { command: "node -e 'console.log(42)'" };
1060
+ const decision = yield* Effect.promise(() =>
1061
+ canUseTool!("Bash", command, {
1062
+ signal: new AbortController().signal,
1063
+ toolUseID: "tool-bash-accept-edits",
1064
+ requestId: "request-bash-accept-edits",
1065
+ description: "Check the Node runtime",
1066
+ }),
1067
+ ).pipe(Effect.forkScoped);
1068
+ const first = yield* Effect.raceFirst(
1069
+ Fiber.join(requestEvent).pipe(Effect.map((event) => ({ type: "request", event }) as const)),
1070
+ Fiber.join(decision).pipe(Effect.map((result) => ({ type: "decision", result }) as const)),
1071
+ );
1072
+ assert.equal(first.type, "request", "the command ran without asking");
1073
+ if (first.type !== "request") return;
1074
+ const event = first.event.find((event) => event.type === "runtime_request.updated");
1075
+ assert.equal(event?.runtimeRequest.kind, "command");
1076
+ const approval = first.event.findLast((event) => event.type === "turn_item.updated");
1077
+ assert.equal(
1078
+ approval?.turnItem.type === "approval_request" ? approval.turnItem.prompt : undefined,
1079
+ command.command,
1080
+ );
1081
1087
- yield* runtime.respondToRuntimeRequest({
1088
- requestId: event!.runtimeRequest.id,
1089
- decision: "accept",
1090
- });
1091
- assert.equal((yield* Fiber.join(decision))?.behavior, "allow");
1092
- }).pipe(
1093
- Effect.provide(
1094
- Layer.mergeAll(
1095
- IdAllocator.layer,
1096
- McpProviderSessions.layer,
1097
- NodeServices.layer,
1098
- NodeCrypto.layer,
1099
- ),
1082
+ yield* runtime.respondToRuntimeRequest({
1083
+ requestId: event!.runtimeRequest.id,
1084
+ decision: "accept",
1085
+ });
1086
+ assert.equal((yield* Fiber.join(decision))?.behavior, "allow");
1087
+ }).pipe(
1088
+ Effect.provide(
1089
+ Layer.mergeAll(
1090
+ IdAllocator.layer,
1091
+ McpProviderSessions.layer,
1092
+ NodeServices.layer,
1093
+ NodeCrypto.layer,
1094
),
1095
),
1096
),
@@ -1180,33 +1174,31 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1174
(options?.systemPrompt as { readonly append?: string } | undefined)?.append;
1175
1176
it.effect("sends append launch arguments to Claude after the T3 instructions", () =>
1183
- Effect.scoped(
1184
- Effect.gen(function* () {
1185
- const fileSystem = yield* FileSystem.FileSystem;
1186
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1187
- yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n");
1188
- const plain = yield* startTurnWithLaunchArgs("", cwd);
1189
- const { exit, opened } = yield* startTurnWithLaunchArgs(
1190
- '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement',
1191
- cwd,
1192
- );
1193
- assert.isTrue(Exit.isSuccess(exit));
1194
- assert.lengthOf(opened, 1);
1195
- assert.equal(
1196
- appendSystemPrompt(opened[0]),
1197
- `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`,
1198
- );
1199
- assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]);
1200
- assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]);
1201
- assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement");
1202
- }).pipe(
1203
- Effect.provide(
1204
- Layer.mergeAll(
1205
- IdAllocator.layer,
1206
- McpProviderSessions.layer,
1207
- NodeServices.layer,
1208
- NodeCrypto.layer,
1209
- ),
1177
+ Effect.gen(function* () {
1178
+ const fileSystem = yield* FileSystem.FileSystem;
1179
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1180
+ yield* fileSystem.writeFileString(NodePath.join(cwd, "rules.md"), "File sentinel\n");
1181
+ const plain = yield* startTurnWithLaunchArgs("", cwd);
1182
+ const { exit, opened } = yield* startTurnWithLaunchArgs(
1183
+ '--append-system-prompt "Inline sentinel" --append-system-prompt-file rules.md --system-prompt Replacement',
1184
+ cwd,
1185
+ );
1186
+ assert.isTrue(Exit.isSuccess(exit));
1187
+ assert.lengthOf(opened, 1);
1188
+ assert.equal(
1189
+ appendSystemPrompt(opened[0]),
1190
+ `${appendSystemPrompt(plain.opened[0])}\n\nFile sentinel\n\nInline sentinel`,
1191
+ );
1192
+ assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt"]);
1193
+ assert.isUndefined(opened[0]!.extraArgs?.["append-system-prompt-file"]);
1194
+ assert.equal(opened[0]!.extraArgs?.["system-prompt"], "Replacement");
1195
+ }).pipe(
1196
+ Effect.provide(
1197
+ Layer.mergeAll(
1198
+ IdAllocator.layer,
1199
+ McpProviderSessions.layer,
1200
+ NodeServices.layer,
1201
+ NodeCrypto.layer,
1202
),
1203
),
1204
),
@@ -1217,29 +1209,27 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1209
`--settings '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}'`,
1210
"--settings user-settings.json",
1211
])("merges %s beneath T3's settings", (launchArgs) =>
1220
- Effect.scoped(
1221
- Effect.gen(function* () {
1222
- const fileSystem = yield* FileSystem.FileSystem;
1223
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" });
1224
- yield* fileSystem.writeFileString(
1225
- NodePath.join(cwd, "user-settings.json"),
1226
- '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}',
1227
- );
1228
- const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1229
- assert.isTrue(Exit.isSuccess(exit));
1230
- assert.deepInclude(opened[0]!.settings, {
1231
- skillOverrides: { lint: "off" },
1232
- showThinkingSummaries: true,
1233
- });
1234
- assert.isUndefined(opened[0]!.extraArgs?.["settings"]);
1235
- }).pipe(
1236
- Effect.provide(
1237
- Layer.mergeAll(
1238
- IdAllocator.layer,
1239
- McpProviderSessions.layer,
1240
- NodeServices.layer,
1241
- NodeCrypto.layer,
1242
- ),
1212
+ Effect.gen(function* () {
1213
+ const fileSystem = yield* FileSystem.FileSystem;
1214
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-settings-" });
1215
+ yield* fileSystem.writeFileString(
1216
+ NodePath.join(cwd, "user-settings.json"),
1217
+ '{"skillOverrides":{"lint":"off"},"showThinkingSummaries":false}',
1218
+ );
1219
+ const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1220
+ assert.isTrue(Exit.isSuccess(exit));
1221
+ assert.deepInclude(opened[0]!.settings, {
1222
+ skillOverrides: { lint: "off" },
1223
+ showThinkingSummaries: true,
1224
+ });
1225
+ assert.isUndefined(opened[0]!.extraArgs?.["settings"]);
1226
+ }).pipe(
1227
+ Effect.provide(
1228
+ Layer.mergeAll(
1229
+ IdAllocator.layer,
1230
+ McpProviderSessions.layer,
1231
+ NodeServices.layer,
1232
+ NodeCrypto.layer,
1233
),
1234
),
1235
),
@@ -1258,32 +1248,30 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1248
assert.include(appendSystemPrompt(options), '{"skillOverrides":{"lint":"off"}}'),
1249
],
1250
] as const)("reads %s from the home directory", ([launchArgs, assertOptions]) =>
1261
- Effect.scoped(
1262
- Effect.gen(function* () {
1263
- const fileSystem = yield* FileSystem.FileSystem;
1264
- const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" });
1265
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-cwd-" });
1266
- yield* fileSystem.makeDirectory(NodePath.join(home, ".claude"));
1267
- yield* fileSystem.writeFileString(
1268
- NodePath.join(home, ".claude", "settings.json"),
1269
- '{"skillOverrides":{"lint":"off"}}',
1270
- );
1271
- const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd).pipe(
1272
- Effect.provideService(HostProcess.HomeDirectory, home),
1273
- );
1274
- if (Exit.isFailure(exit)) {
1275
- assert.fail(makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message);
1276
- }
1277
- assert.lengthOf(opened, 1);
1278
- assertOptions(opened[0]!);
1279
- }).pipe(
1280
- Effect.provide(
1281
- Layer.mergeAll(
1282
- IdAllocator.layer,
1283
- McpProviderSessions.layer,
1284
- NodeServices.layer,
1285
- NodeCrypto.layer,
1286
- ),
1251
+ Effect.gen(function* () {
1252
+ const fileSystem = yield* FileSystem.FileSystem;
1253
+ const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" });
1254
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-cwd-" });
1255
+ yield* fileSystem.makeDirectory(NodePath.join(home, ".claude"));
1256
+ yield* fileSystem.writeFileString(
1257
+ NodePath.join(home, ".claude", "settings.json"),
1258
+ '{"skillOverrides":{"lint":"off"}}',
1259
+ );
1260
+ const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd).pipe(
1261
+ Effect.provideService(HostProcess.HomeDirectory, home),
1262
+ );
1263
+ if (Exit.isFailure(exit)) {
1264
+ assert.fail(makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message);
1265
+ }
1266
+ assert.lengthOf(opened, 1);
1267
+ assertOptions(opened[0]!);
1268
+ }).pipe(
1269
+ Effect.provide(
1270
+ Layer.mergeAll(
1271
+ IdAllocator.layer,
1272
+ McpProviderSessions.layer,
1273
+ NodeServices.layer,
1274
+ NodeCrypto.layer,
1275
),
1276
),
1277
),
@@ -1333,26 +1321,24 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1321
() => new ClaudeAdapterV2.ClaudeSettingsLaunchArgError({}).message,
1322
],
1323
] as const)("fails the turn before opening Claude for %s", ([launchArgs, expectedMessage]) =>
1336
- Effect.scoped(
1337
- Effect.gen(function* () {
1338
- const fileSystem = yield* FileSystem.FileSystem;
1339
- const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1340
- const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1341
- assert.lengthOf(opened, 0);
1342
- assert.isTrue(Exit.isFailure(exit));
1343
- if (!Exit.isFailure(exit)) return;
1344
- assert.equal(
1345
- makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message,
1346
- expectedMessage(cwd),
1347
- );
1348
- }).pipe(
1349
- Effect.provide(
1350
- Layer.mergeAll(
1351
- IdAllocator.layer,
1352
- McpProviderSessions.layer,
1353
- NodeServices.layer,
1354
- NodeCrypto.layer,
1355
- ),
1324
+ Effect.gen(function* () {
1325
+ const fileSystem = yield* FileSystem.FileSystem;
1326
+ const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-cwd-" });
1327
+ const { exit, opened } = yield* startTurnWithLaunchArgs(launchArgs, cwd);
1328
+ assert.lengthOf(opened, 0);
1329
+ assert.isTrue(Exit.isFailure(exit));
1330
+ if (!Exit.isFailure(exit)) return;
1331
+ assert.equal(
1332
+ makeProviderFailure({ cause: exit.cause, class: "provider_error" }).message,
1333
+ expectedMessage(cwd),
1334
+ );
1335
+ }).pipe(
1336
+ Effect.provide(
1337
+ Layer.mergeAll(
1338
+ IdAllocator.layer,
1339
+ McpProviderSessions.layer,
1340
+ NodeServices.layer,
1341
+ NodeCrypto.layer,
1342
),
1343
),
1344
),
@@ -1361,95 +1347,93 @@ describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => {
1347
1348
describe("ClaudeAdapterV2 provider installation gate", () => {
1349
it.effect("opens each turn's Claude process inside the installation gate", () =>
1364
- Effect.scoped(
1365
- Effect.gen(function* () {
1366
- const fileSystem = yield* FileSystem.FileSystem;
1367
- const log: Array<string> = [];
1368
- const instanceId = ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID;
1369
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1370
- instanceId,
1371
- settings: DEFAULT_CLAUDE_SETTINGS,
1372
- environment: {},
1373
- attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-" }),
1374
- fileSystem,
1375
- path: yield* Path.Path,
1376
- random: yield* SecureRandom.SecureRandom,
1377
- idAllocator: yield* IdAllocator.IdAllocatorV2,
1378
- installationGate: ProviderInstallationGate.ProviderInstallationGate.of({
1379
- execute: (gatedInstanceId, effect) =>
1380
- Effect.sync(() => log.push(`enter ${gatedInstanceId}`)).pipe(
1381
- Effect.andThen(effect),
1382
- Effect.ensuring(Effect.sync(() => log.push("exit"))),
1383
- ),
1384
- update: () => Effect.die("unused"),
1385
- }),
1386
- queryRunner: {
1387
- allocateSessionId: Effect.succeed("native-thread-claude-gate"),
1388
- open: () =>
1389
- Effect.sync(() => {
1390
- log.push("open query");
1391
- return {
1392
- messages: Stream.never,
1393
- offer: () => Effect.void,
1394
- setModel: () => Effect.void,
1395
- applyFlagSettings: () => Effect.void,
1396
- setPermissionMode: () => Effect.void,
1397
- backgroundTasks: () => Effect.succeed(false),
1398
- mcpServerStatus: Effect.succeed([]),
1399
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
1400
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
1401
- listPermissionRules: Effect.die("unexpected permission rules read"),
1402
- stopTask: () => Effect.void,
1403
- interrupt: Effect.void,
1404
- close: Effect.void,
1405
- };
1406
- }),
1407
- forkSession: () => Effect.die("unused"),
1408
- subagentLaunchToolUseId: () => Effect.succeed(null),
1409
- subagentModel: () => Effect.succeed(null),
1410
- assertComplete: Effect.void,
1411
- },
1412
- });
1413
- const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1414
- runtimeMode: "full-access",
1415
- interactionMode: "default",
1416
- cwd: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-cwd-" }),
1417
- });
1418
- const threadId = ThreadId.make("thread-claude-gate");
1419
- const runtime = yield* adapter.openSession({
1420
- threadId,
1421
- providerSessionId: ProviderSessionId.make("provider-session-claude-gate"),
1422
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1423
- runtimePolicy,
1424
- });
1425
- const providerThread = yield* runtime.ensureThread({
1350
+ Effect.gen(function* () {
1351
+ const fileSystem = yield* FileSystem.FileSystem;
1352
+ const log: Array<string> = [];
1353
+ const instanceId = ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID;
1354
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1355
+ instanceId,
1356
+ settings: DEFAULT_CLAUDE_SETTINGS,
1357
+ environment: {},
1358
+ attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-" }),
1359
+ fileSystem,
1360
+ path: yield* Path.Path,
1361
+ random: yield* SecureRandom.SecureRandom,
1362
+ idAllocator: yield* IdAllocator.IdAllocatorV2,
1363
+ installationGate: ProviderInstallationGate.ProviderInstallationGate.of({
1364
+ execute: (gatedInstanceId, effect) =>
1365
+ Effect.sync(() => log.push(`enter ${gatedInstanceId}`)).pipe(
1366
+ Effect.andThen(effect),
1367
+ Effect.ensuring(Effect.sync(() => log.push("exit"))),
1368
+ ),
1369
+ update: () => Effect.die("unused"),
1370
+ }),
1371
+ queryRunner: {
1372
+ allocateSessionId: Effect.succeed("native-thread-claude-gate"),
1373
+ open: () =>
1374
+ Effect.sync(() => {
1375
+ log.push("open query");
1376
+ return {
1377
+ messages: Stream.never,
1378
+ offer: () => Effect.void,
1379
+ setModel: () => Effect.void,
1380
+ applyFlagSettings: () => Effect.void,
1381
+ setPermissionMode: () => Effect.void,
1382
+ backgroundTasks: () => Effect.succeed(false),
1383
+ mcpServerStatus: Effect.succeed([]),
1384
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
1385
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
1386
+ listPermissionRules: Effect.die("unexpected permission rules read"),
1387
+ stopTask: () => Effect.void,
1388
+ interrupt: Effect.void,
1389
+ close: Effect.void,
1390
+ };
1391
+ }),
1392
+ forkSession: () => Effect.die("unused"),
1393
+ subagentLaunchToolUseId: () => Effect.succeed(null),
1394
+ subagentModel: () => Effect.succeed(null),
1395
+ assertComplete: Effect.void,
1396
+ },
1397
+ });
1398
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
1399
+ runtimeMode: "full-access",
1400
+ interactionMode: "default",
1401
+ cwd: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-gate-cwd-" }),
1402
+ });
1403
+ const threadId = ThreadId.make("thread-claude-gate");
1404
+ const runtime = yield* adapter.openSession({
1405
+ threadId,
1406
+ providerSessionId: ProviderSessionId.make("provider-session-claude-gate"),
1407
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1408
+ runtimePolicy,
1409
+ });
1410
+ const providerThread = yield* runtime.ensureThread({
1411
+ threadId,
1412
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1413
+ runtimePolicy,
1414
+ });
1415
+ assert.deepStrictEqual(log, []);
1416
+
1417
+ yield* runtime.startTurn(
1418
+ makeClaudeTestTurnInput({
1419
threadId,
1427
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1420
+ providerThread,
1421
+ now: yield* DateTime.now,
1422
+ attemptId: RunAttemptId.make("attempt-claude-gate"),
1423
+ text: "Hello",
1424
+ attachments: [],
1425
runtimePolicy,
1429
- });
1430
- assert.deepStrictEqual(log, []);
1431
-
1432
- yield* runtime.startTurn(
1433
- makeClaudeTestTurnInput({
1434
- threadId,
1435
- providerThread,
1436
- now: yield* DateTime.now,
1437
- attemptId: RunAttemptId.make("attempt-claude-gate"),
1438
- text: "Hello",
1439
- attachments: [],
1440
- runtimePolicy,
1441
- }),
1442
- );
1426
+ }),
1427
+ );
1428
1444
- assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]);
1445
- }).pipe(
1446
- Effect.provide(
1447
- Layer.mergeAll(
1448
- IdAllocator.layer,
1449
- McpProviderSessions.layer,
1450
- NodeServices.layer,
1451
- NodeCrypto.layer,
1452
- ),
1429
+ assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]);
1430
+ }).pipe(
1431
+ Effect.provide(
1432
+ Layer.mergeAll(
1433
+ IdAllocator.layer,
1434
+ McpProviderSessions.layer,
1435
+ NodeServices.layer,
1436
+ NodeCrypto.layer,
1437
),
1438
),
1439
),
@@ -1748,189 +1732,154 @@ describe("ClaudeAdapterV2 resumeThread", () => {
1732
1733
describe("ClaudeAdapterV2 resume compaction", () => {
1734
it.effect("resolves and cancels the SDK resume dialog through structured runtime input", () =>
1751
- Effect.scoped(
1752
- Effect.gen(function* () {
1753
- const fileSystem = yield* FileSystem.FileSystem;
1754
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
1755
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
1756
- prefix: "t3-claude-resume-",
1757
- });
1758
- let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
1759
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1760
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1761
- settings: DEFAULT_CLAUDE_SETTINGS,
1762
- environment: {},
1763
- attachmentsDir,
1764
- fileSystem,
1765
- path: yield* Path.Path,
1766
- random: yield* SecureRandom.SecureRandom,
1767
- idAllocator,
1768
- queryRunner: {
1769
- allocateSessionId: Effect.succeed("native-thread-claude-resume"),
1770
- open: (input) =>
1771
- Effect.sync(() => {
1772
- openedOptions = input.options;
1773
- return {
1774
- messages: Stream.never,
1775
- offer: () => Effect.void,
1776
- setModel: () => Effect.void,
1777
- applyFlagSettings: () => Effect.void,
1778
- setPermissionMode: () => Effect.void,
1779
- backgroundTasks: () => Effect.succeed(false),
1780
- mcpServerStatus: Effect.succeed([]),
1781
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
1782
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
1783
- listPermissionRules: Effect.die("unexpected permission rules read"),
1784
- stopTask: () => Effect.void,
1785
- interrupt: Effect.void,
1786
- close: Effect.void,
1787
- };
1788
- }),
1789
- forkSession: () => Effect.die("unused"),
1790
- subagentLaunchToolUseId: () => Effect.succeed(null),
1791
- subagentModel: () => Effect.succeed(null),
1792
- assertComplete: Effect.void,
1793
- },
1794
- });
1795
- const threadId = ThreadId.make("thread-claude-resume");
1796
- const runtime = yield* adapter.openSession({
1797
- threadId,
1798
- providerSessionId: ProviderSessionId.make("provider-session-claude-resume"),
1799
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1800
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1801
- });
1802
- const providerThread = yield* runtime.ensureThread({
1735
+ Effect.gen(function* () {
1736
+ const fileSystem = yield* FileSystem.FileSystem;
1737
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
1738
+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
1739
+ prefix: "t3-claude-resume-",
1740
+ });
1741
+ let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined;
1742
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1743
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1744
+ settings: DEFAULT_CLAUDE_SETTINGS,
1745
+ environment: {},
1746
+ attachmentsDir,
1747
+ fileSystem,
1748
+ path: yield* Path.Path,
1749
+ random: yield* SecureRandom.SecureRandom,
1750
+ idAllocator,
1751
+ queryRunner: {
1752
+ allocateSessionId: Effect.succeed("native-thread-claude-resume"),
1753
+ open: (input) =>
1754
+ Effect.sync(() => {
1755
+ openedOptions = input.options;
1756
+ return {
1757
+ messages: Stream.never,
1758
+ offer: () => Effect.void,
1759
+ setModel: () => Effect.void,
1760
+ applyFlagSettings: () => Effect.void,
1761
+ setPermissionMode: () => Effect.void,
1762
+ backgroundTasks: () => Effect.succeed(false),
1763
+ mcpServerStatus: Effect.succeed([]),
1764
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
1765
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
1766
+ listPermissionRules: Effect.die("unexpected permission rules read"),
1767
+ stopTask: () => Effect.void,
1768
+ interrupt: Effect.void,
1769
+ close: Effect.void,
1770
+ };
1771
+ }),
1772
+ forkSession: () => Effect.die("unused"),
1773
+ subagentLaunchToolUseId: () => Effect.succeed(null),
1774
+ subagentModel: () => Effect.succeed(null),
1775
+ assertComplete: Effect.void,
1776
+ },
1777
+ });
1778
+ const threadId = ThreadId.make("thread-claude-resume");
1779
+ const runtime = yield* adapter.openSession({
1780
+ threadId,
1781
+ providerSessionId: ProviderSessionId.make("provider-session-claude-resume"),
1782
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1783
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1784
+ });
1785
+ const providerThread = yield* runtime.ensureThread({
1786
+ threadId,
1787
+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1788
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1789
+ });
1790
+ const now = yield* DateTime.now;
1791
+ yield* runtime.startTurn(
1792
+ makeClaudeTestTurnInput({
1793
threadId,
1804
- modelSelection: CLAUDE_TEST_MODEL_SELECTION,
1805
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
1806
- });
1807
- const now = yield* DateTime.now;
1808
- yield* runtime.startTurn(
1809
- makeClaudeTestTurnInput({
1810
- threadId,
1811
- providerThread,
1812
- now,
1813
- attemptId: RunAttemptId.make("attempt-claude-resume"),
1814
- text: "continue",
1815
- attachments: [],
1816
- }),
1817
- );
1818
- const callback = openedOptions?.onUserDialog;
1819
- assert.isFunction(callback);
1820
- const canUseTool = openedOptions?.canUseTool;
1821
- assert.isFunction(canUseTool);
1822
- const shellSafetyReason =
1823
- "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed";
1824
- for (const [safetyIndex, { askRule, reason }] of [
1825
- { askRule: false, reason: shellSafetyReason },
1826
- { askRule: true, reason: shellSafetyReason },
1827
- {
1828
- askRule: false,
1829
- reason:
1830
- "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.",
1831
- },
1832
- { askRule: false, reason: "This shell -c script runs rm and could not be checked" },
1833
- { askRule: false, reason: "A permission rule denies a command in this shell -c script" },
1834
- ].entries()) {
1835
- const safetyRequest = yield* runtime.events.pipe(
1836
- Stream.filter((event) => event.type === "runtime_request.updated"),
1837
- Stream.runHead,
1838
- Effect.forkScoped,
1839
- );
1840
- const safetySignal = yield* Effect.abortSignal;
1841
- const safetyDecision = yield* Effect.promise(() =>
1842
- canUseTool!(
1843
- "Bash",
1844
- { command: "for pair in a b; do echo $pair; done" },
1845
- {
1846
- signal: safetySignal,
1847
- toolUseID: `tool-shell-safety-${safetyIndex}`,
1848
- requestId: `request-shell-safety-${safetyIndex}`,
1849
- decisionReason: `\u001b[33m${reason}\u001b[39m`,
1850
- suppressAlwaysAllowRule: true,
1851
- ...(askRule
1852
- ? {
1853
- matchedAskRule: {
1854
- source: "userSettings" as const,
1855
- toolName: "Bash",
1856
- ruleContent: "*",
1857
- },
1858
- }
1859
- : {}),
1860
- },
1861
- ),
1862
- ).pipe(Effect.forkScoped);
1863
- const safety = yield* Effect.raceFirst(
1864
- Fiber.join(safetyDecision).pipe(
1865
- Effect.map((result) => ({ type: "decision", result }) as const),
1866
- ),
1867
- Fiber.join(safetyRequest).pipe(
1868
- Effect.map((event) => ({ type: "approval", event }) as const),
1869
- ),
1870
- );
1871
- assert.equal(safety.type, askRule ? "approval" : "decision");
1872
- if (safety.type === "decision") {
1873
- assert.equal(safety.result?.behavior, "deny");
1874
- if (safety.result?.behavior === "deny") {
1875
- assert.include(safety.result.message, reason);
1876
- assert.notInclude(safety.result.message, "\u001b[");
1877
- }
1878
- } else if (
1879
- Option.isSome(safety.event) &&
1880
- safety.event.value.type === "runtime_request.updated"
1881
- ) {
1882
- yield* runtime.respondToRuntimeRequest({
1883
- requestId: safety.event.value.runtimeRequest.id,
1884
- decision: "decline",
1885
- });
1886
- assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny");
1887
- }
1888
- yield* Fiber.interrupt(safetyRequest);
1889
- }
1890
- const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
1891
- const questionRequestEvent = yield* runtime.events.pipe(
1794
+ providerThread,
1795
+ now,
1796
+ attemptId: RunAttemptId.make("attempt-claude-resume"),
1797
+ text: "continue",
1798
+ attachments: [],
1799
+ }),
1800
+ );
1801
+ const callback = openedOptions?.onUserDialog;
1802
+ assert.isFunction(callback);
1803
+ const canUseTool = openedOptions?.canUseTool;
1804
+ assert.isFunction(canUseTool);
1805
+ const shellSafetyReason =
1806
+ "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed";
1807
+ for (const [safetyIndex, { askRule, reason }] of [
1808
+ { askRule: false, reason: shellSafetyReason },
1809
+ { askRule: true, reason: shellSafetyReason },
1810
+ {
1811
+ askRule: false,
1812
+ reason:
1813
+ "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.",
1814
+ },
1815
+ { askRule: false, reason: "This shell -c script runs rm and could not be checked" },
1816
+ { askRule: false, reason: "A permission rule denies a command in this shell -c script" },
1817
+ ].entries()) {
1818
+ const safetyRequest = yield* runtime.events.pipe(
1819
Stream.filter((event) => event.type === "runtime_request.updated"),
1820
Stream.runHead,
1821
Effect.forkScoped,
1822
);
1896
- const questionResult = yield* Effect.promise(() =>
1823
+ const safetySignal = yield* Effect.abortSignal;
1824
+ const safetyDecision = yield* Effect.promise(() =>
1825
canUseTool!(
1898
- "AskUserQuestion",
1899
- {
1900
- questions: [
1901
- {
1902
- header: "Target",
1903
- question: longQuestion,
1904
- options: [
1905
- { label: "Production", description: "Deploy to production." },
1906
- { label: "Staging", description: "Deploy to staging." },
1907
- ],
1908
- multiSelect: true,
1909
- },
1910
- ],
1911
- },
1826
+ "Bash",
1827
+ { command: "for pair in a b; do echo $pair; done" },
1828
{
1913
- signal: new AbortController().signal,
1914
- toolUseID: "tool-question-full-access",
1915
- requestId: "request-question-full-access",
1829
+ signal: safetySignal,
1830
+ toolUseID: `tool-shell-safety-${safetyIndex}`,
1831
+ requestId: `request-shell-safety-${safetyIndex}`,
1832
+ decisionReason: `\u001b[33m${reason}\u001b[39m`,
1833
+ suppressAlwaysAllowRule: true,
1834
+ ...(askRule
1835
+ ? {
1836
+ matchedAskRule: {
1837
+ source: "userSettings" as const,
1838
+ toolName: "Bash",
1839
+ ruleContent: "*",
1840
+ },
1841
+ }
1842
+ : {}),
1843
},
1844
),
1845
).pipe(Effect.forkScoped);
1919
- const questionEvent = yield* Fiber.join(questionRequestEvent);
1920
- assert.isTrue(Option.isSome(questionEvent));
1921
- if (
1922
- Option.isNone(questionEvent) ||
1923
- questionEvent.value.type !== "runtime_request.updated"
1846
+ const safety = yield* Effect.raceFirst(
1847
+ Fiber.join(safetyDecision).pipe(
1848
+ Effect.map((result) => ({ type: "decision", result }) as const),
1849
+ ),
1850
+ Fiber.join(safetyRequest).pipe(
1851
+ Effect.map((event) => ({ type: "approval", event }) as const),
1852
+ ),
1853
+ );
1854
+ assert.equal(safety.type, askRule ? "approval" : "decision");
1855
+ if (safety.type === "decision") {
1856
+ assert.equal(safety.result?.behavior, "deny");
1857
+ if (safety.result?.behavior === "deny") {
1858
+ assert.include(safety.result.message, reason);
1859
+ assert.notInclude(safety.result.message, "\u001b[");
1860
+ }
1861
+ } else if (
1862
+ Option.isSome(safety.event) &&
1863
+ safety.event.value.type === "runtime_request.updated"
1864
) {
1925
- return;
1865
+ yield* runtime.respondToRuntimeRequest({
1866
+ requestId: safety.event.value.runtimeRequest.id,
1867
+ decision: "decline",
1868
+ });
1869
+ assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny");
1870
}
1927
- yield* runtime.respondToRuntimeRequest({
1928
- requestId: questionEvent.value.runtimeRequest.id,
1929
- answers: { [longQuestion]: ["Production", "Staging"] },
1930
- });
1931
- assert.deepEqual(yield* Fiber.join(questionResult), {
1932
- behavior: "allow",
1933
- updatedInput: {
1871
+ yield* Fiber.interrupt(safetyRequest);
1872
+ }
1873
+ const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`;
1874
+ const questionRequestEvent = yield* runtime.events.pipe(
1875
+ Stream.filter((event) => event.type === "runtime_request.updated"),
1876
+ Stream.runHead,
1877
+ Effect.forkScoped,
1878
+ );
1879
+ const questionResult = yield* Effect.promise(() =>
1880
+ canUseTool!(
1881
+ "AskUserQuestion",
1882
+ {
1883
questions: [
1884
{
1885
header: "Target",
@@ -1942,90 +1891,120 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1891
multiSelect: true,
1892
},
1893
],
1945
- answers: { [longQuestion]: "Production, Staging" },
1894
},
1947
- toolUseID: "tool-question-full-access",
1948
- });
1949
- const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`;
1950
- const proposedPlanEvent = yield* runtime.events.pipe(
1951
- Stream.filter((event) => event.type === "plan.updated"),
1952
- Stream.runHead,
1953
- Effect.forkScoped,
1954
- );
1955
- const exitPlanResult = yield* Effect.promise(() =>
1956
- canUseTool!(
1957
- "ExitPlanMode",
1958
- { plan: longPlan },
1895
+ {
1896
+ signal: new AbortController().signal,
1897
+ toolUseID: "tool-question-full-access",
1898
+ requestId: "request-question-full-access",
1899
+ },
1900
+ ),
1901
+ ).pipe(Effect.forkScoped);
1902
+ const questionEvent = yield* Fiber.join(questionRequestEvent);
1903
+ assert.isTrue(Option.isSome(questionEvent));
1904
+ if (Option.isNone(questionEvent) || questionEvent.value.type !== "runtime_request.updated") {
1905
+ return;
1906
+ }
1907
+ yield* runtime.respondToRuntimeRequest({
1908
+ requestId: questionEvent.value.runtimeRequest.id,
1909
+ answers: { [longQuestion]: ["Production", "Staging"] },
1910
+ });
1911
+ assert.deepEqual(yield* Fiber.join(questionResult), {
1912
+ behavior: "allow",
1913
+ updatedInput: {
1914
+ questions: [
1915
{
1960
- signal: new AbortController().signal,
1961
- toolUseID: "tool-exit-plan-full-access",
1962
- requestId: "request-exit-plan-full-access",
1916
+ header: "Target",
1917
+ question: longQuestion,
1918
+ options: [
1919
+ { label: "Production", description: "Deploy to production." },
1920
+ { label: "Staging", description: "Deploy to staging." },
1921
+ ],
1922
+ multiSelect: true,
1923
},
1964
- ),
1965
- );
1966
- assert.deepEqual(exitPlanResult, {
1967
- behavior: "deny",
1968
- message:
1969
- "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
1970
- toolUseID: "tool-exit-plan-full-access",
1971
- });
1972
- const planEvent = yield* Fiber.join(proposedPlanEvent);
1973
- assert.isTrue(Option.isSome(planEvent));
1974
- if (Option.isSome(planEvent) && planEvent.value.type === "plan.updated") {
1975
- assert.equal(planEvent.value.plan.kind, "proposed_plan");
1976
- if (planEvent.value.plan.kind === "proposed_plan") {
1977
- assert.equal(planEvent.value.plan.markdown, longPlan.trim());
1978
- }
1924
+ ],
1925
+ answers: { [longQuestion]: "Production, Staging" },
1926
+ },
1927
+ toolUseID: "tool-question-full-access",
1928
+ });
1929
+ const longPlan = `# Deployment plan\n\n${"Validate every region before promotion.\n".repeat(120)}`;
1930
+ const proposedPlanEvent = yield* runtime.events.pipe(
1931
+ Stream.filter((event) => event.type === "plan.updated"),
1932
+ Stream.runHead,
1933
+ Effect.forkScoped,
1934
+ );
1935
+ const exitPlanResult = yield* Effect.promise(() =>
1936
+ canUseTool!(
1937
+ "ExitPlanMode",
1938
+ { plan: longPlan },
1939
+ {
1940
+ signal: new AbortController().signal,
1941
+ toolUseID: "tool-exit-plan-full-access",
1942
+ requestId: "request-exit-plan-full-access",
1943
+ },
1944
+ ),
1945
+ );
1946
+ assert.deepEqual(exitPlanResult, {
1947
+ behavior: "deny",
1948
+ message:
1949
+ "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
1950
+ toolUseID: "tool-exit-plan-full-access",
1951
+ });
1952
+ const planEvent = yield* Fiber.join(proposedPlanEvent);
1953
+ assert.isTrue(Option.isSome(planEvent));
1954
+ if (Option.isSome(planEvent) && planEvent.value.type === "plan.updated") {
1955
+ assert.equal(planEvent.value.plan.kind, "proposed_plan");
1956
+ if (planEvent.value.plan.kind === "proposed_plan") {
1957
+ assert.equal(planEvent.value.plan.markdown, longPlan.trim());
1958
}
1980
- const requestEvent = yield* runtime.events.pipe(
1981
- Stream.filter((event) => event.type === "runtime_request.updated"),
1982
- Stream.runHead,
1983
- Effect.forkScoped,
1984
- );
1985
- const signal = yield* Effect.abortSignal;
1986
- const dialog = yield* Effect.promise(() =>
1959
+ }
1960
+ const requestEvent = yield* runtime.events.pipe(
1961
+ Stream.filter((event) => event.type === "runtime_request.updated"),
1962
+ Stream.runHead,
1963
+ Effect.forkScoped,
1964
+ );
1965
+ const signal = yield* Effect.abortSignal;
1966
+ const dialog = yield* Effect.promise(() =>
1967
+ callback!(
1968
+ {
1969
+ dialogKind: "resume_return",
1970
+ payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
1971
+ },
1972
+ { signal, requestId: "dialog-resume-1" },
1973
+ ),
1974
+ ).pipe(Effect.forkScoped);
1975
+ const event = yield* Fiber.join(requestEvent);
1976
+ assert.isTrue(Option.isSome(event));
1977
+ if (Option.isNone(event) || event.value.type !== "runtime_request.updated") return;
1978
+ const question = formatClaudeResumeCompactionQuestion({
1979
+ ageMinutes: 90,
1980
+ estimatedTokens: 120000,
1981
+ });
1982
+ yield* runtime.respondToRuntimeRequest({
1983
+ requestId: event.value.runtimeRequest.id,
1984
+ answers: { [question]: "Compact and continue" },
1985
+ });
1986
+ assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" });
1987
+
1988
+ assert.deepEqual(
1989
+ yield* Effect.promise(() =>
1990
callback!(
1991
{
1992
dialogKind: "resume_return",
1993
payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
1994
},
1992
- { signal, requestId: "dialog-resume-1" },
1993
- ),
1994
- ).pipe(Effect.forkScoped);
1995
- const event = yield* Fiber.join(requestEvent);
1996
- assert.isTrue(Option.isSome(event));
1997
- if (Option.isNone(event) || event.value.type !== "runtime_request.updated") return;
1998
- const question = formatClaudeResumeCompactionQuestion({
1999
- ageMinutes: 90,
2000
- estimatedTokens: 120000,
2001
- });
2002
- yield* runtime.respondToRuntimeRequest({
2003
- requestId: event.value.runtimeRequest.id,
2004
- answers: { [question]: "Compact and continue" },
2005
- });
2006
- assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" });
2007
-
2008
- assert.deepEqual(
2009
- yield* Effect.promise(() =>
2010
- callback!(
2011
- {
2012
- dialogKind: "resume_return",
2013
- payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
2014
- },
2015
- { signal: AbortSignal.abort(), requestId: "dialog-resume-2" },
2016
- ),
2017
- ),
2018
- { behavior: "cancelled" },
2019
- );
2020
- }).pipe(
2021
- Effect.provide(
2022
- Layer.mergeAll(
2023
- IdAllocator.layer,
2024
- McpProviderSessions.layer,
2025
- NodeServices.layer,
2026
- NodeCrypto.layer,
1995
+ { signal: AbortSignal.abort(), requestId: "dialog-resume-2" },
1996
),
1997
),
1998
+ { behavior: "cancelled" },
1999
+ );
2000
+ }).pipe(
2001
+ Effect.provide(
2002
+ Layer.mergeAll(
2003
+ IdAllocator.layer,
2004
+ McpProviderSessions.layer,
2005
+ NodeServices.layer,
2006
+ NodeCrypto.layer,
2007
+ ),
2008
),
2009
),
2010
);
@@ -2090,555 +2069,543 @@ describe("ClaudeAdapterV2 attachments", () => {
2069
])(
2070
"preserves $name with native PDFs, images, and paths on sends and steering",
2071
({ prompt, expectedText, command, ultrathink, resumed, budget }) =>
2093
- Effect.scoped(
2094
- Effect.gen(function* () {
2095
- const fileSystem = yield* FileSystem.FileSystem;
2096
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
2097
- const path = yield* Path.Path;
2098
- const claudeHome = yield* fileSystem.makeTempDirectoryScoped({
2099
- prefix: "t3-claude-v2-skills-home-",
2100
- });
2101
- yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), {
2102
- recursive: true,
2103
- });
2104
- yield* fileSystem.writeFileString(
2105
- path.join(claudeHome, "skills", "implement", "SKILL.md"),
2106
- "---\ndescription: Implement the requested change\n---\nImplement it.\n",
2107
- );
2108
- const modelSelection = {
2109
- ...CLAUDE_TEST_MODEL_SELECTION,
2110
- options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [],
2111
- };
2112
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2113
- prefix: "t3-claude-v2-attachments-",
2114
- });
2115
- const offeredMessages: Array<SDKUserMessage> = [];
2116
- let failOpen = false;
2117
- let failOffer = false;
2118
- let cancelAfterQueue = false;
2119
- const queued = yield* Deferred.make<void>();
2120
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2121
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2122
- settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },
2123
- environment: {},
2124
- attachmentsDir,
2125
- fileSystem,
2126
- path: yield* Path.Path,
2127
- random: yield* SecureRandom.SecureRandom,
2128
- idAllocator,
2129
- queryRunner: {
2130
- allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
2131
- open: () =>
2132
- Effect.gen(function* () {
2133
- if (failOpen) {
2134
- failOpen = false;
2135
- return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2136
- method: "open",
2137
- cause: "rejected open",
2138
- });
2139
- }
2140
- const messages = yield* Queue.unbounded<SDKMessage>();
2141
- return {
2142
- messages: Stream.fromQueue(messages),
2143
- offer: (message, onQueued) =>
2144
- Effect.suspend(() => {
2145
- if (failOffer) {
2146
- failOffer = false;
2147
- return Effect.fail(
2148
- new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2149
- method: "offer",
2150
- cause: "rejected offer",
2151
- }),
2152
- );
2153
- }
2154
- return Effect.sync(() => {
2155
- offeredMessages.push(message);
2156
- onQueued?.();
2157
- }).pipe(
2158
- Effect.andThen(() =>
2159
- cancelAfterQueue
2160
- ? Deferred.succeed(queued, undefined).pipe(
2161
- Effect.andThen(Effect.never),
2162
- )
2163
- : Effect.void,
2164
- ),
2072
+ Effect.gen(function* () {
2073
+ const fileSystem = yield* FileSystem.FileSystem;
2074
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
2075
+ const path = yield* Path.Path;
2076
+ const claudeHome = yield* fileSystem.makeTempDirectoryScoped({
2077
+ prefix: "t3-claude-v2-skills-home-",
2078
+ });
2079
+ yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), {
2080
+ recursive: true,
2081
+ });
2082
+ yield* fileSystem.writeFileString(
2083
+ path.join(claudeHome, "skills", "implement", "SKILL.md"),
2084
+ "---\ndescription: Implement the requested change\n---\nImplement it.\n",
2085
+ );
2086
+ const modelSelection = {
2087
+ ...CLAUDE_TEST_MODEL_SELECTION,
2088
+ options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [],
2089
+ };
2090
+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2091
+ prefix: "t3-claude-v2-attachments-",
2092
+ });
2093
+ const offeredMessages: Array<SDKUserMessage> = [];
2094
+ let failOpen = false;
2095
+ let failOffer = false;
2096
+ let cancelAfterQueue = false;
2097
+ const queued = yield* Deferred.make<void>();
2098
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2099
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2100
+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },
2101
+ environment: {},
2102
+ attachmentsDir,
2103
+ fileSystem,
2104
+ path: yield* Path.Path,
2105
+ random: yield* SecureRandom.SecureRandom,
2106
+ idAllocator,
2107
+ queryRunner: {
2108
+ allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
2109
+ open: () =>
2110
+ Effect.gen(function* () {
2111
+ if (failOpen) {
2112
+ failOpen = false;
2113
+ return yield* new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2114
+ method: "open",
2115
+ cause: "rejected open",
2116
+ });
2117
+ }
2118
+ const messages = yield* Queue.unbounded<SDKMessage>();
2119
+ return {
2120
+ messages: Stream.fromQueue(messages),
2121
+ offer: (message, onQueued) =>
2122
+ Effect.suspend(() => {
2123
+ if (failOffer) {
2124
+ failOffer = false;
2125
+ return Effect.fail(
2126
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
2127
+ method: "offer",
2128
+ cause: "rejected offer",
2129
+ }),
2130
);
2166
- }),
2167
- setModel: () => Effect.void,
2168
- applyFlagSettings: () => Effect.void,
2169
- setPermissionMode: () => Effect.void,
2170
- backgroundTasks: () => Effect.succeed(false),
2171
- mcpServerStatus: Effect.succeed([]),
2172
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
2173
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
2174
- listPermissionRules: Effect.die("unexpected permission rules read"),
2175
- stopTask: () => Effect.void,
2176
- interrupt: Effect.void,
2177
- close: Queue.shutdown(messages),
2178
- };
2179
- }),
2180
- forkSession: () => Effect.die("unused forkSession"),
2181
- subagentLaunchToolUseId: () => Effect.succeed(null),
2182
- subagentModel: () => Effect.succeed(null),
2183
- assertComplete: Effect.void,
2184
- },
2185
- });
2186
- const threadId = ThreadId.make("thread-claude-attachments");
2187
- const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments");
2188
- const runtime = yield* adapter.openSession({
2189
- threadId,
2190
- providerSessionId,
2191
- modelSelection,
2192
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2193
- });
2194
- const providerThread = yield* runtime.ensureThread({
2131
+ }
2132
+ return Effect.sync(() => {
2133
+ offeredMessages.push(message);
2134
+ onQueued?.();
2135
+ }).pipe(
2136
+ Effect.andThen(() =>
2137
+ cancelAfterQueue
2138
+ ? Deferred.succeed(queued, undefined).pipe(Effect.andThen(Effect.never))
2139
+ : Effect.void,
2140
+ ),
2141
+ );
2142
+ }),
2143
+ setModel: () => Effect.void,
2144
+ applyFlagSettings: () => Effect.void,
2145
+ setPermissionMode: () => Effect.void,
2146
+ backgroundTasks: () => Effect.succeed(false),
2147
+ mcpServerStatus: Effect.succeed([]),
2148
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
2149
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
2150
+ listPermissionRules: Effect.die("unexpected permission rules read"),
2151
+ stopTask: () => Effect.void,
2152
+ interrupt: Effect.void,
2153
+ close: Queue.shutdown(messages),
2154
+ };
2155
+ }),
2156
+ forkSession: () => Effect.die("unused forkSession"),
2157
+ subagentLaunchToolUseId: () => Effect.succeed(null),
2158
+ subagentModel: () => Effect.succeed(null),
2159
+ assertComplete: Effect.void,
2160
+ },
2161
+ });
2162
+ const threadId = ThreadId.make("thread-claude-attachments");
2163
+ const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments");
2164
+ const runtime = yield* adapter.openSession({
2165
+ threadId,
2166
+ providerSessionId,
2167
+ modelSelection,
2168
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2169
+ });
2170
+ const providerThread = yield* runtime.ensureThread({
2171
+ threadId,
2172
+ modelSelection,
2173
+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2174
+ });
2175
+ const attachment = ChatImageAttachment.make({
2176
+ type: "image",
2177
+ id: ChatAttachmentId.make(
2178
+ "thread-claude-attachments-12345678-1234-1234-1234-123456789abc",
2179
+ ),
2180
+ name: "diagram.png",
2181
+ mimeType: "image/png",
2182
+ sizeBytes: 4,
2183
+ });
2184
+ const document = ChatFileAttachment.make({
2185
+ type: "file",
2186
+ id: ChatAttachmentId.make(
2187
+ "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc",
2188
+ ),
2189
+ name: "requirements.pdf",
2190
+ mimeType: "application/pdf",
2191
+ sizeBytes: 4,
2192
+ });
2193
+ yield* fileSystem.writeFile(
2194
+ path.join(attachmentsDir, attachmentRelativePath(attachment)!),
2195
+ Uint8Array.from([1, 2, 3, 4]),
2196
+ );
2197
+ const pdfBytes = Buffer.from(
2198
+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
2199
+ );
2200
+ yield* fileSystem.writeFile(
2201
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
2202
+ pdfBytes,
2203
+ );
2204
+ const attemptId = RunAttemptId.make("attempt-claude-attachments");
2205
+ const now = yield* DateTime.now;
2206
+
2207
+ const turnInput = {
2208
+ ...makeClaudeTestTurnInput({
2209
threadId,
2210
+ providerThread,
2211
+ now,
2212
+ attemptId,
2213
modelSelection,
2197
- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
2198
- });
2199
- const attachment = ChatImageAttachment.make({
2200
- type: "image",
2201
- id: ChatAttachmentId.make(
2202
- "thread-claude-attachments-12345678-1234-1234-1234-123456789abc",
2203
- ),
2204
- name: "diagram.png",
2205
- mimeType: "image/png",
2206
- sizeBytes: 4,
2207
- });
2208
- const document = ChatFileAttachment.make({
2209
- type: "file",
2210
- id: ChatAttachmentId.make(
2211
- "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc",
2212
- ),
2213
- name: "requirements.pdf",
2214
- mimeType: "application/pdf",
2215
- sizeBytes: 4,
2216
- });
2217
- yield* fileSystem.writeFile(
2218
- path.join(attachmentsDir, attachmentRelativePath(attachment)!),
2219
- Uint8Array.from([1, 2, 3, 4]),
2220
- );
2221
- const pdfBytes = Buffer.from(
2222
- "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
2214
+ text: prompt,
2215
+ attachments: resumed ? [attachment] : [attachment, document],
2216
+ }),
2217
+ nativeThreadHasTurns: resumed,
2218
+ };
2219
+ if (budget === "cancelled-send" || budget === "cancelled-steer") {
2220
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2221
+ const pages = Buffer.from(
2222
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
2223
);
2224
yield* fileSystem.writeFile(
2225
- path.join(attachmentsDir, attachmentRelativePath(document)!),
2226
- pdfBytes,
2225
+ documentPath,
2226
+ Buffer.concat([
2227
+ pages,
2228
+ Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32),
2229
+ Buffer.from("%%EOF"),
2230
+ ]),
2231
);
2228
- const attemptId = RunAttemptId.make("attempt-claude-attachments");
2229
- const now = yield* DateTime.now;
2230
-
2231
- const turnInput = {
2232
- ...makeClaudeTestTurnInput({
2233
- threadId,
2234
- providerThread,
2235
- now,
2236
- attemptId,
2237
- modelSelection,
2238
- text: prompt,
2239
- attachments: resumed ? [attachment] : [attachment, document],
2240
- }),
2241
- nativeThreadHasTurns: resumed,
2242
- };
2243
- if (budget === "cancelled-send" || budget === "cancelled-steer") {
2232
+ const message = { ...turnInput.message, attachments: [document] };
2233
+ if (budget === "cancelled-steer") {
2234
+ yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } });
2235
+ }
2236
+ const deliver =
2237
+ budget === "cancelled-send"
2238
+ ? runtime.startTurn({ ...turnInput, message })
2239
+ : runtime.steerTurn({
2240
+ threadId,
2241
+ runId: turnInput.runId,
2242
+ providerThread,
2243
+ providerTurnId: idAllocator.derive.providerTurn({
2244
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2245
+ nativeTurnId: `turn:${attemptId}`,
2246
+ }),
2247
+ message,
2248
+ });
2249
+ cancelAfterQueue = true;
2250
+ const delivering = yield* deliver.pipe(Effect.forkChild);
2251
+ yield* Deferred.await(queued);
2252
+ yield* Fiber.interrupt(delivering);
2253
+ const delivered = offeredMessages.at(-1)!.message.content;
2254
+ assert.include(JSON.stringify(delivered), '"type":"document"');
2255
+ cancelAfterQueue = false;
2256
+ if (budget === "cancelled-send") {
2257
+ yield* runtime.interruptTurn({
2258
+ providerThread,
2259
+ providerTurnId: idAllocator.derive.providerTurn({
2260
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2261
+ nativeTurnId: `turn:${attemptId}`,
2262
+ }),
2263
+ });
2264
+ }
2265
+ yield* deliver;
2266
+ const retried = offeredMessages.at(-1)!.message.content;
2267
+ assert.notInclude(JSON.stringify(retried), '"type":"document"');
2268
+ assert.include(JSON.stringify(retried), JSON.stringify(documentPath).slice(1, -1));
2269
+ assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000);
2270
+ return;
2271
+ }
2272
+ if (budget !== "none") {
2273
+ const providerTurnId = idAllocator.derive.providerTurn({
2274
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2275
+ nativeTurnId: `turn:${attemptId}`,
2276
+ });
2277
+ const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!);
2278
+ // The on-disk length deliberately disagrees with sizeBytes.
2279
+ yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024));
2280
+ if (["later-images", "partial-images"].includes(budget)) {
2281
const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2245
- const pages = Buffer.from(
2246
- `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
2247
- );
2282
yield* fileSystem.writeFile(
2283
documentPath,
2284
Buffer.concat([
2251
- pages,
2252
- Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32),
2285
+ pdfBytes.subarray(0, -5),
2286
+ Buffer.alloc(
2287
+ (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length,
2288
+ 32,
2289
+ ),
2290
Buffer.from("%%EOF"),
2291
]),
2292
);
2256
- const message = { ...turnInput.message, attachments: [document] };
2257
- if (budget === "cancelled-steer") {
2258
- yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } });
2259
- }
2260
- const deliver =
2261
- budget === "cancelled-send"
2262
- ? runtime.startTurn({ ...turnInput, message })
2263
- : runtime.steerTurn({
2264
- threadId,
2265
- runId: turnInput.runId,
2266
- providerThread,
2267
- providerTurnId: idAllocator.derive.providerTurn({
2268
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2269
- nativeTurnId: `turn:${attemptId}`,
2270
- }),
2271
- message,
2272
- });
2273
- cancelAfterQueue = true;
2274
- const delivering = yield* deliver.pipe(Effect.forkChild);
2275
- yield* Deferred.await(queued);
2276
- yield* Fiber.interrupt(delivering);
2277
- const delivered = offeredMessages.at(-1)!.message.content;
2278
- assert.include(JSON.stringify(delivered), '"type":"document"');
2279
- cancelAfterQueue = false;
2280
- if (budget === "cancelled-send") {
2281
- yield* runtime.interruptTurn({
2282
- providerThread,
2283
- providerTurnId: idAllocator.derive.providerTurn({
2284
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2285
- nativeTurnId: `turn:${attemptId}`,
2286
- }),
2287
- });
2288
- }
2289
- yield* deliver;
2290
- const retried = offeredMessages.at(-1)!.message.content;
2291
- assert.notInclude(JSON.stringify(retried), '"type":"document"');
2292
- assert.include(JSON.stringify(retried), JSON.stringify(documentPath).slice(1, -1));
2293
- assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000);
2294
- return;
2295
- }
2296
- if (budget !== "none") {
2297
- const providerTurnId = idAllocator.derive.providerTurn({
2298
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2299
- nativeTurnId: `turn:${attemptId}`,
2293
+ yield* runtime.startTurn({
2294
+ ...turnInput,
2295
+ message: { ...turnInput.message, attachments: [document] },
2296
});
2301
- const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!);
2302
- // The on-disk length deliberately disagrees with sizeBytes.
2303
- yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024));
2304
- if (["later-images", "partial-images"].includes(budget)) {
2305
- const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2306
- yield* fileSystem.writeFile(
2307
- documentPath,
2308
- Buffer.concat([
2309
- pdfBytes.subarray(0, -5),
2310
- Buffer.alloc(
2311
- (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length,
2312
- 32,
2313
- ),
2314
- Buffer.from("%%EOF"),
2315
- ]),
2316
- );
2317
- yield* runtime.startTurn({
2318
- ...turnInput,
2319
- message: { ...turnInput.message, attachments: [document] },
2320
- });
2321
- assert.include(
2322
- JSON.stringify(offeredMessages[0]!.message.content),
2323
- '"type":"document"',
2324
- );
2325
- const message = { ...turnInput.message, attachments: [attachment, attachment] };
2326
- yield* runtime.interruptTurn({ providerThread, providerTurnId });
2327
- const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later");
2328
- yield* runtime.startTurn({
2329
- ...turnInput,
2330
- attemptId: laterAttemptId,
2331
- providerTurnOrdinal: 2,
2332
- nativeThreadHasTurns: true,
2333
- message,
2334
- });
2335
- const sent = offeredMessages.at(-1)!.message.content;
2336
- assert.isArray(sent);
2337
- assert.lengthOf(
2338
- typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"),
2339
- budget === "partial-images" ? 1 : 0,
2340
- );
2341
- assert.include(JSON.stringify(sent), JSON.stringify(imagePath).slice(1, -1));
2342
- yield* runtime.steerTurn({
2343
- threadId,
2344
- runId: RunId.make("run-claude-attachments"),
2345
- providerThread,
2346
- providerTurnId: idAllocator.derive.providerTurn({
2347
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2348
- nativeTurnId: `turn:${laterAttemptId}`,
2349
- }),
2350
- message,
2351
- });
2352
- const steered = offeredMessages.at(-1)!.message.content;
2353
- assert.isArray(steered);
2354
- assert.lengthOf(
2355
- typeof steered === "string"
2356
- ? []
2357
- : steered.filter((block) => block.type === "image"),
2358
- 0,
2359
- );
2360
- assert.include(JSON.stringify(steered), JSON.stringify(imagePath).slice(1, -1));
2361
- assert.isBelow(
2362
- Buffer.byteLength(
2363
- JSON.stringify(offeredMessages.map((message) => message.message)),
2364
- ),
2365
- 32_000_000,
2366
- );
2367
- return;
2368
- }
2369
- if (budget === "retained-documents") {
2370
- yield* fileSystem.writeFile(
2371
- path.join(attachmentsDir, attachmentRelativePath(document)!),
2372
- Buffer.concat([
2373
- pdfBytes.subarray(0, pdfBytes.length - 5),
2374
- Buffer.alloc(10 * 1024 * 1024, 32),
2375
- Buffer.from("%%EOF"),
2376
- ]),
2377
- );
2378
- }
2297
+ assert.include(
2298
+ JSON.stringify(offeredMessages[0]!.message.content),
2299
+ '"type":"document"',
2300
+ );
2301
+ const message = { ...turnInput.message, attachments: [attachment, attachment] };
2302
+ yield* runtime.interruptTurn({ providerThread, providerTurnId });
2303
+ const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later");
2304
yield* runtime.startTurn({
2305
...turnInput,
2381
- message: {
2382
- ...turnInput.message,
2383
- text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt,
2384
- attachments:
2385
- budget === "retained-text"
2386
- ? []
2387
- : budget === "retained-documents"
2388
- ? [document]
2389
- : [attachment, attachment],
2390
- },
2306
+ attemptId: laterAttemptId,
2307
+ providerTurnOrdinal: 2,
2308
+ nativeThreadHasTurns: true,
2309
+ message,
2310
});
2392
- const largePdf = Buffer.concat([
2393
- pdfBytes.subarray(0, pdfBytes.length - 5),
2394
- Buffer.alloc(
2395
- (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length,
2396
- 32,
2397
- ),
2398
- Buffer.from("%%EOF"),
2399
- ]);
2400
- const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2401
- yield* fileSystem.writeFile(documentPath, largePdf);
2311
+ const sent = offeredMessages.at(-1)!.message.content;
2312
+ assert.isArray(sent);
2313
+ assert.lengthOf(
2314
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"),
2315
+ budget === "partial-images" ? 1 : 0,
2316
+ );
2317
+ assert.include(JSON.stringify(sent), JSON.stringify(imagePath).slice(1, -1));
2318
yield* runtime.steerTurn({
2319
threadId,
2320
runId: RunId.make("run-claude-attachments"),
2321
providerThread,
2406
- providerTurnId,
2407
- message: {
2408
- ...turnInput.message,
2409
- attachments:
2410
- budget === "same-message-images"
2411
- ? [document, attachment, attachment]
2412
- : [document],
2413
- },
2322
+ providerTurnId: idAllocator.derive.providerTurn({
2323
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2324
+ nativeTurnId: `turn:${laterAttemptId}`,
2325
+ }),
2326
+ message,
2327
});
2415
- const sent = offeredMessages.at(-1)!.message.content;
2416
- assert.isArray(sent);
2328
+ const steered = offeredMessages.at(-1)!.message.content;
2329
+ assert.isArray(steered);
2330
assert.lengthOf(
2418
- typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"),
2331
+ typeof steered === "string" ? [] : steered.filter((block) => block.type === "image"),
2332
0,
2420
- budget,
2333
);
2422
- assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2334
+ assert.include(JSON.stringify(steered), JSON.stringify(imagePath).slice(1, -1));
2335
+ assert.isBelow(
2336
+ Buffer.byteLength(JSON.stringify(offeredMessages.map((message) => message.message))),
2337
+ 32_000_000,
2338
+ );
2339
return;
2340
}
2425
- if (!resumed) {
2426
- const undelivered = Buffer.from(
2427
- `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2428
- );
2429
- yield* fileSystem.writeFile(
2430
- path.join(attachmentsDir, attachmentRelativePath(document)!),
2431
- undelivered,
2432
- );
2433
- failOpen = true;
2434
- assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit)));
2435
- assert.lengthOf(offeredMessages, 0);
2341
+ if (budget === "retained-documents") {
2342
yield* fileSystem.writeFile(
2343
path.join(attachmentsDir, attachmentRelativePath(document)!),
2438
- pdfBytes,
2344
+ Buffer.concat([
2345
+ pdfBytes.subarray(0, pdfBytes.length - 5),
2346
+ Buffer.alloc(10 * 1024 * 1024, 32),
2347
+ Buffer.from("%%EOF"),
2348
+ ]),
2349
);
2350
}
2441
- yield* runtime.startTurn(turnInput);
2442
-
2443
- const expectedImageBlock = {
2444
- type: "image",
2445
- source: {
2446
- type: "base64",
2447
- media_type: "image/png",
2448
- data: "AQIDBA==",
2449
- },
2450
- } as const;
2451
- const expectedDocumentBlock = {
2452
- type: "document",
2453
- source: {
2454
- type: "base64",
2455
- media_type: "application/pdf",
2456
- data: Buffer.from(pdfBytes).toString("base64"),
2351
+ yield* runtime.startTurn({
2352
+ ...turnInput,
2353
+ message: {
2354
+ ...turnInput.message,
2355
+ text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt,
2356
+ attachments:
2357
+ budget === "retained-text"
2358
+ ? []
2359
+ : budget === "retained-documents"
2360
+ ? [document]
2361
+ : [attachment, attachment],
2362
},
2458
- } as const;
2459
- const expectedAttachmentPath = path.join(
2460
- attachmentsDir,
2461
- attachmentRelativePath(attachment)!,
2462
- );
2463
- const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2464
- const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`;
2465
- const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };
2466
- const expectedContent = command
2467
- ? [
2468
- requestBlock,
2469
- expectedImageBlock,
2470
- ...(!resumed ? [expectedDocumentBlock] : []),
2471
- { type: "text" as const, text: command + attachmentNotes },
2472
- ]
2473
- : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock];
2474
- assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);
2475
-
2476
- const providerTurnId = idAllocator.derive.providerTurn({
2477
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2478
- nativeTurnId: `turn:${attemptId}`,
2363
});
2364
+ const largePdf = Buffer.concat([
2365
+ pdfBytes.subarray(0, pdfBytes.length - 5),
2366
+ Buffer.alloc(
2367
+ (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length,
2368
+ 32,
2369
+ ),
2370
+ Buffer.from("%%EOF"),
2371
+ ]);
2372
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2373
+ yield* fileSystem.writeFile(documentPath, largePdf);
2374
yield* runtime.steerTurn({
2375
threadId,
2376
runId: RunId.make("run-claude-attachments"),
2377
providerThread,
2378
providerTurnId,
2379
message: {
2486
- createdBy: "user",
2487
- creationSource: "web",
2488
- messageId: MessageId.make("message-claude-attachments-steer"),
2489
- text: prompt,
2490
- attachments: resumed ? [attachment] : [attachment, document],
2380
+ ...turnInput.message,
2381
+ attachments:
2382
+ budget === "same-message-images" ? [document, attachment, attachment] : [document],
2383
},
2384
});
2385
+ const sent = offeredMessages.at(-1)!.message.content;
2386
+ assert.isArray(sent);
2387
+ assert.lengthOf(
2388
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"),
2389
+ 0,
2390
+ budget,
2391
+ );
2392
+ assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2393
+ return;
2394
+ }
2395
+ if (!resumed) {
2396
+ const undelivered = Buffer.from(
2397
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2398
+ );
2399
+ yield* fileSystem.writeFile(
2400
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
2401
+ undelivered,
2402
+ );
2403
+ failOpen = true;
2404
+ assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit)));
2405
+ assert.lengthOf(offeredMessages, 0);
2406
+ yield* fileSystem.writeFile(
2407
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
2408
+ pdfBytes,
2409
+ );
2410
+ }
2411
+ yield* runtime.startTurn(turnInput);
2412
2494
- assert.equal(offeredMessages[1]?.priority, "now");
2495
- assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
2496
- const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2497
- for (const scenario of [
2498
- "pages",
2499
- "bytes",
2500
- "invalid",
2501
- "invalid-page-tree",
2502
- "object-stream",
2503
- "encrypted",
2504
- "cyclic-tree",
2505
- "unterminated-string",
2506
- "missing-eof",
2507
- "escaped-name",
2508
- "incremental",
2509
- "indirect-count",
2510
- "indirect-type",
2511
- "indirect-kids",
2512
- "indirect-101-pages",
2513
- "aggregate-pages",
2514
- "retained-pages",
2515
- "delivery-failure",
2516
- "pasted-text",
2517
- "text-only",
2518
- ]) {
2519
- let attachments: ReadonlyArray<ChatAttachment> = [document];
2520
- if (
2521
- ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario)
2522
- ) {
2523
- const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60;
2524
- const large = Buffer.from(
2525
- `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2526
- );
2527
- yield* fileSystem.writeFile(documentPath, large);
2528
- if (scenario === "aggregate-pages") {
2529
- const second = {
2530
- ...document,
2531
- id: ChatAttachmentId.make("second-pdf"),
2532
- name: "second.pdf",
2533
- };
2534
- yield* fileSystem.copyFile(
2535
- documentPath,
2536
- path.join(attachmentsDir, attachmentRelativePath(second)!),
2537
- );
2538
- attachments = [document, second];
2539
- }
2540
- } else if (scenario.startsWith("indirect-")) {
2541
- const raw =
2542
- scenario === "indirect-count" || scenario === "indirect-101-pages"
2543
- ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF`
2544
- : scenario === "indirect-type"
2545
- ? pdfBytes
2546
- .toString()
2547
- .replace(
2548
- "%%EOF",
2549
- "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF",
2550
- )
2551
- : pdfBytes
2552
- .toString()
2553
- .replace("/Kids [3 0 R]", "/Kids 4 0 R")
2554
- .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF");
2555
- yield* fileSystem.writeFileString(documentPath, raw);
2556
- } else if (scenario === "bytes") {
2557
- yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1);
2558
- } else if (scenario === "invalid") {
2559
- yield* fileSystem.writeFileString(documentPath, "This is not a PDF");
2560
- } else if (scenario === "invalid-page-tree") {
2561
- const malformedBytes = Buffer.from(
2562
- "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF",
2563
- );
2564
- yield* fileSystem.writeFile(documentPath, malformedBytes);
2565
- } else if (["object-stream", "encrypted", "cyclic-tree"].includes(scenario)) {
2566
- const suffix =
2567
- scenario === "encrypted"
2568
- ? "/Encrypt 9 0 R"
2569
- : scenario === "cyclic-tree"
2570
- ? "/Count 0 /Kids [2 0 R]"
2571
- : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000";
2572
- yield* fileSystem.writeFile(
2573
- documentPath,
2574
- Buffer.concat([
2575
- pdfBytes.subarray(0, pdfBytes.length - 5),
2576
- Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`),
2577
- ]),
2578
- );
2579
- } else if (
2580
- ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(
2581
- scenario,
2582
- )
2583
- ) {
2584
- const raw = pdfBytes.toString();
2585
- yield* fileSystem.writeFileString(
2413
+ const expectedImageBlock = {
2414
+ type: "image",
2415
+ source: {
2416
+ type: "base64",
2417
+ media_type: "image/png",
2418
+ data: "AQIDBA==",
2419
+ },
2420
+ } as const;
2421
+ const expectedDocumentBlock = {
2422
+ type: "document",
2423
+ source: {
2424
+ type: "base64",
2425
+ media_type: "application/pdf",
2426
+ data: Buffer.from(pdfBytes).toString("base64"),
2427
+ },
2428
+ } as const;
2429
+ const expectedAttachmentPath = path.join(
2430
+ attachmentsDir,
2431
+ attachmentRelativePath(attachment)!,
2432
+ );
2433
+ const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2434
+ const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`;
2435
+ const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };
2436
+ const expectedContent = command
2437
+ ? [
2438
+ requestBlock,
2439
+ expectedImageBlock,
2440
+ ...(!resumed ? [expectedDocumentBlock] : []),
2441
+ { type: "text" as const, text: command + attachmentNotes },
2442
+ ]
2443
+ : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock];
2444
+ assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);
2445
+
2446
+ const providerTurnId = idAllocator.derive.providerTurn({
2447
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2448
+ nativeTurnId: `turn:${attemptId}`,
2449
+ });
2450
+ yield* runtime.steerTurn({
2451
+ threadId,
2452
+ runId: RunId.make("run-claude-attachments"),
2453
+ providerThread,
2454
+ providerTurnId,
2455
+ message: {
2456
+ createdBy: "user",
2457
+ creationSource: "web",
2458
+ messageId: MessageId.make("message-claude-attachments-steer"),
2459
+ text: prompt,
2460
+ attachments: resumed ? [attachment] : [attachment, document],
2461
+ },
2462
+ });
2463
+
2464
+ assert.equal(offeredMessages[1]?.priority, "now");
2465
+ assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
2466
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2467
+ for (const scenario of [
2468
+ "pages",
2469
+ "bytes",
2470
+ "invalid",
2471
+ "invalid-page-tree",
2472
+ "object-stream",
2473
+ "encrypted",
2474
+ "cyclic-tree",
2475
+ "unterminated-string",
2476
+ "missing-eof",
2477
+ "escaped-name",
2478
+ "incremental",
2479
+ "indirect-count",
2480
+ "indirect-type",
2481
+ "indirect-kids",
2482
+ "indirect-101-pages",
2483
+ "aggregate-pages",
2484
+ "retained-pages",
2485
+ "delivery-failure",
2486
+ "pasted-text",
2487
+ "text-only",
2488
+ ]) {
2489
+ let attachments: ReadonlyArray<ChatAttachment> = [document];
2490
+ if (
2491
+ ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario)
2492
+ ) {
2493
+ const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60;
2494
+ const large = Buffer.from(
2495
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
2496
+ );
2497
+ yield* fileSystem.writeFile(documentPath, large);
2498
+ if (scenario === "aggregate-pages") {
2499
+ const second = {
2500
+ ...document,
2501
+ id: ChatAttachmentId.make("second-pdf"),
2502
+ name: "second.pdf",
2503
+ };
2504
+ yield* fileSystem.copyFile(
2505
documentPath,
2587
- scenario === "missing-eof"
2588
- ? raw.slice(0, -5)
2589
- : scenario === "escaped-name"
2590
- ? raw.replace("/Type /Page ", "/Type /Pa#67e ")
2591
- : raw.replace(
2592
- "%%EOF",
2593
- scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF",
2594
- ),
2506
+ path.join(attachmentsDir, attachmentRelativePath(second)!),
2507
);
2596
- } else if (scenario === "pasted-text") {
2597
- yield* fileSystem.writeFile(documentPath, pdfBytes);
2598
- attachments = [{ ...document, source: { _tag: "pasted-text" } }];
2599
- } else {
2600
- attachments = [];
2601
- yield* fileSystem.remove(documentPath);
2602
- }
2603
- const steering = {
2604
- threadId,
2605
- runId: RunId.make("run-claude-attachments"),
2606
- providerThread,
2607
- providerTurnId,
2608
- message: {
2609
- createdBy: "user",
2610
- creationSource: "web",
2611
- messageId: MessageId.make(`message-${scenario}`),
2612
- text: "Continue.",
2613
- attachments,
2614
- },
2615
- } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
2616
- if (scenario === "delivery-failure") {
2617
- failOffer = true;
2618
- assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit)));
2508
+ attachments = [document, second];
2509
}
2620
- yield* runtime.steerTurn(steering);
2621
-
2622
- const sent = offeredMessages.at(-1)!.message.content;
2623
- const documents =
2624
- typeof sent === "string" ? [] : sent.filter((block) => block.type === "document");
2625
- assert.lengthOf(
2626
- documents,
2627
- ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0,
2628
- scenario,
2510
+ } else if (scenario.startsWith("indirect-")) {
2511
+ const raw =
2512
+ scenario === "indirect-count" || scenario === "indirect-101-pages"
2513
+ ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF`
2514
+ : scenario === "indirect-type"
2515
+ ? pdfBytes
2516
+ .toString()
2517
+ .replace(
2518
+ "%%EOF",
2519
+ "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF",
2520
+ )
2521
+ : pdfBytes
2522
+ .toString()
2523
+ .replace("/Kids [3 0 R]", "/Kids 4 0 R")
2524
+ .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF");
2525
+ yield* fileSystem.writeFileString(documentPath, raw);
2526
+ } else if (scenario === "bytes") {
2527
+ yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1);
2528
+ } else if (scenario === "invalid") {
2529
+ yield* fileSystem.writeFileString(documentPath, "This is not a PDF");
2530
+ } else if (scenario === "invalid-page-tree") {
2531
+ const malformedBytes = Buffer.from(
2532
+ "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF",
2533
+ );
2534
+ yield* fileSystem.writeFile(documentPath, malformedBytes);
2535
+ } else if (["object-stream", "encrypted", "cyclic-tree"].includes(scenario)) {
2536
+ const suffix =
2537
+ scenario === "encrypted"
2538
+ ? "/Encrypt 9 0 R"
2539
+ : scenario === "cyclic-tree"
2540
+ ? "/Count 0 /Kids [2 0 R]"
2541
+ : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000";
2542
+ yield* fileSystem.writeFile(
2543
+ documentPath,
2544
+ Buffer.concat([
2545
+ pdfBytes.subarray(0, pdfBytes.length - 5),
2546
+ Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`),
2547
+ ]),
2548
+ );
2549
+ } else if (
2550
+ ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(scenario)
2551
+ ) {
2552
+ const raw = pdfBytes.toString();
2553
+ yield* fileSystem.writeFileString(
2554
+ documentPath,
2555
+ scenario === "missing-eof"
2556
+ ? raw.slice(0, -5)
2557
+ : scenario === "escaped-name"
2558
+ ? raw.replace("/Type /Page ", "/Type /Pa#67e ")
2559
+ : raw.replace(
2560
+ "%%EOF",
2561
+ scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF",
2562
+ ),
2563
);
2630
- if (scenario === "text-only")
2631
- assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue.");
2632
- else assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2564
+ } else if (scenario === "pasted-text") {
2565
+ yield* fileSystem.writeFile(documentPath, pdfBytes);
2566
+ attachments = [{ ...document, source: { _tag: "pasted-text" } }];
2567
+ } else {
2568
+ attachments = [];
2569
+ yield* fileSystem.remove(documentPath);
2570
}
2634
- }).pipe(
2635
- Effect.provide(
2636
- Layer.mergeAll(
2637
- IdAllocator.layer,
2638
- McpProviderSessions.layer,
2639
- NodeServices.layer,
2640
- NodeCrypto.layer,
2641
- ),
2571
+ const steering = {
2572
+ threadId,
2573
+ runId: RunId.make("run-claude-attachments"),
2574
+ providerThread,
2575
+ providerTurnId,
2576
+ message: {
2577
+ createdBy: "user",
2578
+ creationSource: "web",
2579
+ messageId: MessageId.make(`message-${scenario}`),
2580
+ text: "Continue.",
2581
+ attachments,
2582
+ },
2583
+ } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
2584
+ if (scenario === "delivery-failure") {
2585
+ failOffer = true;
2586
+ assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit)));
2587
+ }
2588
+ yield* runtime.steerTurn(steering);
2589
+
2590
+ const sent = offeredMessages.at(-1)!.message.content;
2591
+ const documents =
2592
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document");
2593
+ assert.lengthOf(
2594
+ documents,
2595
+ ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0,
2596
+ scenario,
2597
+ );
2598
+ if (scenario === "text-only")
2599
+ assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue.");
2600
+ else assert.include(JSON.stringify(sent), JSON.stringify(documentPath).slice(1, -1));
2601
+ }
2602
+ }).pipe(
2603
+ Effect.provide(
2604
+ Layer.mergeAll(
2605
+ IdAllocator.layer,
2606
+ McpProviderSessions.layer,
2607
+ NodeServices.layer,
2608
+ NodeCrypto.layer,
2609
),
2610
),
2611
),
@@ -2647,238 +2614,236 @@ describe("ClaudeAdapterV2 attachments", () => {
2614
2615
describe("ClaudeAdapterV2 native fork", () => {
2616
it.effect("forks a session from its original directory after the workspace root changes", () =>
2650
- Effect.scoped(
2651
- Effect.gen(function* () {
2652
- const fileSystem = yield* FileSystem.FileSystem;
2653
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
2654
- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2655
- prefix: "t3-claude-v2-fork-attachments-",
2656
- });
2657
- const configDir = yield* fileSystem.makeTempDirectoryScoped({
2658
- prefix: "t3-claude-root-change-",
2659
- });
2660
- const sourceSessionId = "11111111-1111-4111-8111-111111111111";
2661
- const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002";
2662
- const projectDir = NodePath.join(configDir, "projects", "-old-workspace");
2663
- yield* fileSystem.makeDirectory(projectDir, { recursive: true });
2664
- const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
2665
- type: parentUuid === null ? "user" : "assistant",
2666
- uuid,
2667
- parentUuid,
2668
- sessionId: sourceSessionId,
2669
- cwd: "/old-workspace",
2670
- isSidechain: false,
2671
- timestamp: "2026-10-01T00:00:00.000Z",
2672
- message,
2673
- });
2674
- yield* fileSystem.writeFileString(
2675
- NodePath.join(projectDir, `${sourceSessionId}.jsonl`),
2676
- [
2677
- entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
2678
- entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", {
2679
- role: "assistant",
2680
- content: [{ type: "text", text: "inherited answer" }],
2681
- }),
2682
- ]
2683
- .map((line) => JSON.stringify(line))
2684
- .join("\n"),
2685
- );
2686
- const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe(
2687
- Effect.provide(
2688
- ClaudeAdapterV2.layerQueryRunner.pipe(
2689
- Layer.provide(PortScanner.layerTest),
2690
- Layer.provide(
2691
- Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
2692
- native: undefined,
2693
- canonical: undefined,
2694
- }),
2695
- ),
2617
+ Effect.gen(function* () {
2618
+ const fileSystem = yield* FileSystem.FileSystem;
2619
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
2620
+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({
2621
+ prefix: "t3-claude-v2-fork-attachments-",
2622
+ });
2623
+ const configDir = yield* fileSystem.makeTempDirectoryScoped({
2624
+ prefix: "t3-claude-root-change-",
2625
+ });
2626
+ const sourceSessionId = "11111111-1111-4111-8111-111111111111";
2627
+ const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002";
2628
+ const projectDir = NodePath.join(configDir, "projects", "-old-workspace");
2629
+ yield* fileSystem.makeDirectory(projectDir, { recursive: true });
2630
+ const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({
2631
+ type: parentUuid === null ? "user" : "assistant",
2632
+ uuid,
2633
+ parentUuid,
2634
+ sessionId: sourceSessionId,
2635
+ cwd: "/old-workspace",
2636
+ isSidechain: false,
2637
+ timestamp: "2026-10-01T00:00:00.000Z",
2638
+ message,
2639
+ });
2640
+ yield* fileSystem.writeFileString(
2641
+ NodePath.join(projectDir, `${sourceSessionId}.jsonl`),
2642
+ [
2643
+ entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }),
2644
+ entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", {
2645
+ role: "assistant",
2646
+ content: [{ type: "text", text: "inherited answer" }],
2647
+ }),
2648
+ ]
2649
+ .map((line) => JSON.stringify(line))
2650
+ .join("\n"),
2651
+ );
2652
+ const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe(
2653
+ Effect.provide(
2654
+ ClaudeAdapterV2.layerQueryRunner.pipe(
2655
+ Layer.provide(PortScanner.layerTest),
2656
+ Layer.provide(
2657
+ Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, {
2658
+ native: undefined,
2659
+ canonical: undefined,
2660
+ }),
2661
),
2662
),
2698
- );
2699
- const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
2700
- const forkCalls: Array<ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput> = [];
2701
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2702
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2703
- settings: DEFAULT_CLAUDE_SETTINGS,
2704
- environment: { CLAUDE_CONFIG_DIR: configDir },
2705
- attachmentsDir,
2706
- fileSystem,
2707
- path: yield* Path.Path,
2708
- random: yield* SecureRandom.SecureRandom,
2709
- idAllocator,
2710
- queryRunner: {
2711
- allocateSessionId: Effect.succeed(sourceSessionId),
2712
- open: (input) =>
2713
- Effect.sync(() => {
2714
- openedQueries.push(input);
2715
- return {
2716
- messages: Stream.never,
2717
- offer: () => Effect.void,
2718
- setModel: () => Effect.void,
2719
- applyFlagSettings: () => Effect.void,
2720
- setPermissionMode: () => Effect.void,
2721
- backgroundTasks: () => Effect.succeed(false),
2722
- mcpServerStatus: Effect.succeed([]),
2723
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
2724
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
2725
- listPermissionRules: Effect.die("unexpected permission rules read"),
2726
- stopTask: () => Effect.void,
2727
- interrupt: Effect.void,
2728
- close: Effect.void,
2729
- };
2730
- }),
2731
- forkSession: (input) =>
2732
- Effect.gen(function* () {
2733
- forkCalls.push(input);
2734
- return yield* realRunner.forkSession(input);
2735
- }),
2736
- subagentLaunchToolUseId: () => Effect.succeed(null),
2737
- subagentModel: () => Effect.succeed(null),
2738
- assertComplete: Effect.void,
2739
- },
2740
- });
2741
- const providerSessionId = ProviderSessionId.make("provider-session-claude-fork");
2742
- const sourceThreadId = ThreadId.make("thread-claude-fork-source");
2743
- const targetThreadId = ThreadId.make("thread-claude-fork-target");
2744
- const runtime = yield* adapter.openSession({
2745
- threadId: sourceThreadId,
2746
- providerSessionId,
2747
- modelSelection: {
2748
- instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2749
- model: "claude-sonnet-4-6",
2750
- },
2751
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2752
- runtimeMode: "full-access",
2753
- interactionMode: "default",
2754
- cwd: "/workspace",
2755
- }),
2756
- });
2757
- const sourceProviderThread = yield* runtime.ensureThread({
2758
- threadId: sourceThreadId,
2759
- modelSelection: {
2760
- instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2761
- model: "claude-sonnet-4-6",
2762
- },
2763
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2764
- runtimeMode: "full-access",
2765
- interactionMode: "default",
2766
- cwd: "/workspace",
2767
- }),
2768
- });
2769
- const now = yield* DateTime.now;
2770
- const providerTurnId = ProviderTurnId.make("provider-turn-claude-source");
2771
- const forkedProviderThread = yield* runtime.forkThread({
2772
- sourceProviderThread,
2773
- sourceProviderTurns: [
2774
- {
2775
- id: providerTurnId,
2776
- providerThreadId: sourceProviderThread.id,
2777
- nodeId: NodeId.make("node-claude-source"),
2778
- runAttemptId: RunAttemptId.make("run-attempt-claude-source"),
2779
- nativeTurnRef: {
2780
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2781
- nativeId: sourceCursor,
2782
- strength: "weak",
2783
- },
2784
- ordinal: 1,
2785
- status: "completed",
2786
- startedAt: now,
2787
- completedAt: now,
2788
- },
2789
- ],
2790
- providerTurnId,
2791
- targetThreadId,
2792
- });
2793
-
2794
- assert.deepEqual(forkCalls, [
2663
+ ),
2664
+ );
2665
+ const openedQueries: Array<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput> = [];
2666
+ const forkCalls: Array<ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput> = [];
2667
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
2668
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
2669
+ settings: DEFAULT_CLAUDE_SETTINGS,
2670
+ environment: { CLAUDE_CONFIG_DIR: configDir },
2671
+ attachmentsDir,
2672
+ fileSystem,
2673
+ path: yield* Path.Path,
2674
+ random: yield* SecureRandom.SecureRandom,
2675
+ idAllocator,
2676
+ queryRunner: {
2677
+ allocateSessionId: Effect.succeed(sourceSessionId),
2678
+ open: (input) =>
2679
+ Effect.sync(() => {
2680
+ openedQueries.push(input);
2681
+ return {
2682
+ messages: Stream.never,
2683
+ offer: () => Effect.void,
2684
+ setModel: () => Effect.void,
2685
+ applyFlagSettings: () => Effect.void,
2686
+ setPermissionMode: () => Effect.void,
2687
+ backgroundTasks: () => Effect.succeed(false),
2688
+ mcpServerStatus: Effect.succeed([]),
2689
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
2690
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
2691
+ listPermissionRules: Effect.die("unexpected permission rules read"),
2692
+ stopTask: () => Effect.void,
2693
+ interrupt: Effect.void,
2694
+ close: Effect.void,
2695
+ };
2696
+ }),
2697
+ forkSession: (input) =>
2698
+ Effect.gen(function* () {
2699
+ forkCalls.push(input);
2700
+ return yield* realRunner.forkSession(input);
2701
+ }),
2702
+ subagentLaunchToolUseId: () => Effect.succeed(null),
2703
+ subagentModel: () => Effect.succeed(null),
2704
+ assertComplete: Effect.void,
2705
+ },
2706
+ });
2707
+ const providerSessionId = ProviderSessionId.make("provider-session-claude-fork");
2708
+ const sourceThreadId = ThreadId.make("thread-claude-fork-source");
2709
+ const targetThreadId = ThreadId.make("thread-claude-fork-target");
2710
+ const runtime = yield* adapter.openSession({
2711
+ threadId: sourceThreadId,
2712
+ providerSessionId,
2713
+ modelSelection: {
2714
+ instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2715
+ model: "claude-sonnet-4-6",
2716
+ },
2717
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2718
+ runtimeMode: "full-access",
2719
+ interactionMode: "default",
2720
+ cwd: "/workspace",
2721
+ }),
2722
+ });
2723
+ const sourceProviderThread = yield* runtime.ensureThread({
2724
+ threadId: sourceThreadId,
2725
+ modelSelection: {
2726
+ instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2727
+ model: "claude-sonnet-4-6",
2728
+ },
2729
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2730
+ runtimeMode: "full-access",
2731
+ interactionMode: "default",
2732
+ cwd: "/workspace",
2733
+ }),
2734
+ });
2735
+ const now = yield* DateTime.now;
2736
+ const providerTurnId = ProviderTurnId.make("provider-turn-claude-source");
2737
+ const forkedProviderThread = yield* runtime.forkThread({
2738
+ sourceProviderThread,
2739
+ sourceProviderTurns: [
2740
{
2796
- sessionId: sourceSessionId,
2797
- options: {
2798
- upToMessageId: sourceCursor,
2741
+ id: providerTurnId,
2742
+ providerThreadId: sourceProviderThread.id,
2743
+ nodeId: NodeId.make("node-claude-source"),
2744
+ runAttemptId: RunAttemptId.make("run-attempt-claude-source"),
2745
+ nativeTurnRef: {
2746
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2747
+ nativeId: sourceCursor,
2748
+ strength: "weak",
2749
},
2800
- environment: { CLAUDE_CONFIG_DIR: configDir },
2801
- threadId: targetThreadId,
2802
- providerSessionId,
2750
+ ordinal: 1,
2751
+ status: "completed",
2752
+ startedAt: now,
2753
+ completedAt: now,
2754
},
2804
- ]);
2805
- const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId;
2806
- assert.isString(forkedSessionId);
2807
- assert.notEqual(forkedSessionId, sourceSessionId);
2808
- const forkedTranscript = yield* fileSystem.readFileString(
2809
- NodePath.join(projectDir, `${forkedSessionId}.jsonl`),
2810
- );
2811
- assert.include(forkedTranscript, "inherited answer");
2812
- assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
2813
- assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
2814
-
2815
- yield* runtime.startTurn({
2816
- appThread: {
2817
- createdBy: "user",
2818
- creationSource: "web",
2819
- id: targetThreadId,
2820
- projectId: ProjectId.make("project-claude-fork-target"),
2821
- title: "Claude fork target",
2822
- providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2823
- modelSelection: {
2824
- instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2825
- model: "claude-sonnet-4-6",
2826
- },
2827
- runtimeMode: "full-access",
2828
- interactionMode: "default",
2829
- branch: null,
2830
- worktreePath: null,
2831
- activeProviderThreadId: forkedProviderThread.id,
2832
- lineage: {
2833
- parentThreadId: sourceThreadId,
2834
- relationshipToParent: "fork",
2835
- rootThreadId: sourceThreadId,
2836
- },
2837
- forkedFrom: null,
2838
- createdAt: now,
2839
- updatedAt: now,
2840
- archivedAt: null,
2841
- settledOverride: null,
2842
- settledAt: null,
2843
- lastVisitedAt: null,
2844
- deletedAt: null,
2755
+ ],
2756
+ providerTurnId,
2757
+ targetThreadId,
2758
+ });
2759
+
2760
+ assert.deepEqual(forkCalls, [
2761
+ {
2762
+ sessionId: sourceSessionId,
2763
+ options: {
2764
+ upToMessageId: sourceCursor,
2765
},
2766
+ environment: { CLAUDE_CONFIG_DIR: configDir },
2767
threadId: targetThreadId,
2847
- runId: RunId.make("run-claude-fork-target"),
2848
- runOrdinal: 1,
2849
- providerTurnOrdinal: 1,
2850
- attemptId: RunAttemptId.make("run-attempt-claude-fork-target"),
2851
- rootNodeId: NodeId.make("node-claude-fork-target-root"),
2852
- providerThread: forkedProviderThread,
2853
- message: {
2854
- createdBy: "user",
2855
- creationSource: "web",
2856
- messageId: MessageId.make("message-claude-fork-target"),
2857
- text: "Respond with fork ok",
2858
- attachments: [],
2859
- },
2768
+ providerSessionId,
2769
+ },
2770
+ ]);
2771
+ const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId;
2772
+ assert.isString(forkedSessionId);
2773
+ assert.notEqual(forkedSessionId, sourceSessionId);
2774
+ const forkedTranscript = yield* fileSystem.readFileString(
2775
+ NodePath.join(projectDir, `${forkedSessionId}.jsonl`),
2776
+ );
2777
+ assert.include(forkedTranscript, "inherited answer");
2778
+ assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
2779
+ assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
2780
+
2781
+ yield* runtime.startTurn({
2782
+ appThread: {
2783
+ createdBy: "user",
2784
+ creationSource: "web",
2785
+ id: targetThreadId,
2786
+ projectId: ProjectId.make("project-claude-fork-target"),
2787
+ title: "Claude fork target",
2788
+ providerInstanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2789
modelSelection: {
2790
instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2791
model: "claude-sonnet-4-6",
2792
},
2864
- runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2865
- runtimeMode: "full-access",
2866
- interactionMode: "default",
2867
- cwd: "/workspace",
2868
- }),
2869
- });
2793
+ runtimeMode: "full-access",
2794
+ interactionMode: "default",
2795
+ branch: null,
2796
+ worktreePath: null,
2797
+ activeProviderThreadId: forkedProviderThread.id,
2798
+ lineage: {
2799
+ parentThreadId: sourceThreadId,
2800
+ relationshipToParent: "fork",
2801
+ rootThreadId: sourceThreadId,
2802
+ },
2803
+ forkedFrom: null,
2804
+ createdAt: now,
2805
+ updatedAt: now,
2806
+ archivedAt: null,
2807
+ settledOverride: null,
2808
+ settledAt: null,
2809
+ lastVisitedAt: null,
2810
+ deletedAt: null,
2811
+ },
2812
+ threadId: targetThreadId,
2813
+ runId: RunId.make("run-claude-fork-target"),
2814
+ runOrdinal: 1,
2815
+ providerTurnOrdinal: 1,
2816
+ attemptId: RunAttemptId.make("run-attempt-claude-fork-target"),
2817
+ rootNodeId: NodeId.make("node-claude-fork-target-root"),
2818
+ providerThread: forkedProviderThread,
2819
+ message: {
2820
+ createdBy: "user",
2821
+ creationSource: "web",
2822
+ messageId: MessageId.make("message-claude-fork-target"),
2823
+ text: "Respond with fork ok",
2824
+ attachments: [],
2825
+ },
2826
+ modelSelection: {
2827
+ instanceId: ProviderInstanceId.make(ClaudeAdapterV2.CLAUDE_PROVIDER),
2828
+ model: "claude-sonnet-4-6",
2829
+ },
2830
+ runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
2831
+ runtimeMode: "full-access",
2832
+ interactionMode: "default",
2833
+ cwd: "/workspace",
2834
+ }),
2835
+ });
2836
2871
- assert.equal(openedQueries[0]?.options.resume, forkedSessionId);
2872
- assert.equal(openedQueries[0]?.options.sessionId, undefined);
2873
- assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace"));
2874
- }).pipe(
2875
- Effect.provide(
2876
- Layer.mergeAll(
2877
- IdAllocator.layer,
2878
- McpProviderSessions.layer,
2879
- NodeServices.layer,
2880
- NodeCrypto.layer,
2881
- ),
2837
+ assert.equal(openedQueries[0]?.options.resume, forkedSessionId);
2838
+ assert.equal(openedQueries[0]?.options.sessionId, undefined);
2839
+ assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace"));
2840
+ }).pipe(
2841
+ Effect.provide(
2842
+ Layer.mergeAll(
2843
+ IdAllocator.layer,
2844
+ McpProviderSessions.layer,
2845
+ NodeServices.layer,
2846
+ NodeCrypto.layer,
2847
),
2848
),
2849
),
@@ -6511,89 +6476,87 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6476
it.effect(
6477
"applies model, effort and Fast changes to a process running a background shell, but not thinking or a cleared effort",
6478
() =>
6514
- Effect.scoped(
6515
- Effect.gen(function* () {
6516
- const harness = yield* makeWakeHarness;
6517
- const now = yield* DateTime.now;
6518
- const normal = {
6519
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6520
- model: "claude-opus-5-5",
6521
- } satisfies ModelSelection;
6522
- const turn = (ordinal: number, modelSelection: ModelSelection) =>
6523
- makeClaudeTestTurnInput({
6524
- threadId: harness.threadId,
6525
- providerThread: harness.providerThread,
6526
- now,
6527
- attemptId: RunAttemptId.make(`attempt-normal-background:${ordinal}`),
6528
- text: `Request ${ordinal}`,
6529
- attachments: [],
6530
- providerTurnOrdinal: ordinal,
6531
- modelSelection,
6532
- });
6533
- const settle = Effect.gen(function* () {
6534
- yield* harness.offerAndWait(turnOneResult);
6535
- yield* Queue.take(harness.terminalReceipts);
6479
+ Effect.gen(function* () {
6480
+ const harness = yield* makeWakeHarness;
6481
+ const now = yield* DateTime.now;
6482
+ const normal = {
6483
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6484
+ model: "claude-opus-5-5",
6485
+ } satisfies ModelSelection;
6486
+ const turn = (ordinal: number, modelSelection: ModelSelection) =>
6487
+ makeClaudeTestTurnInput({
6488
+ threadId: harness.threadId,
6489
+ providerThread: harness.providerThread,
6490
+ now,
6491
+ attemptId: RunAttemptId.make(`attempt-normal-background:${ordinal}`),
6492
+ text: `Request ${ordinal}`,
6493
+ attachments: [],
6494
+ providerTurnOrdinal: ordinal,
6495
+ modelSelection,
6496
});
6537
- yield* harness.runtime.startTurn(turn(1, normal));
6538
- const originalOptions = harness.getOpenedOptions();
6539
- yield* harness.offerAndWait(wakeTaskStarted);
6540
- yield* settle;
6541
- assert.isTrue(yield* harness.hasPendingBackgroundWork);
6497
+ const settle = Effect.gen(function* () {
6498
+ yield* harness.offerAndWait(turnOneResult);
6499
+ yield* Queue.take(harness.terminalReceipts);
6500
+ });
6501
+ yield* harness.runtime.startTurn(turn(1, normal));
6502
+ const originalOptions = harness.getOpenedOptions();
6503
+ yield* harness.offerAndWait(wakeTaskStarted);
6504
+ yield* settle;
6505
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
6506
6543
- yield* harness.runtime.startTurn(
6544
- turn(2, { ...normal, options: [{ id: "fastMode", value: false }] }),
6545
- );
6546
- yield* settle;
6547
- assert.deepEqual(harness.liveSelectionChanges, []);
6507
+ yield* harness.runtime.startTurn(
6508
+ turn(2, { ...normal, options: [{ id: "fastMode", value: false }] }),
6509
+ );
6510
+ yield* settle;
6511
+ assert.deepEqual(harness.liveSelectionChanges, []);
6512
6549
- yield* harness.runtime.startTurn(
6550
- turn(3, {
6551
- ...normal,
6552
- options: [
6553
- { id: "effort", value: "high" },
6554
- { id: "ultracode", value: true },
6555
- { id: "fastMode", value: true },
6556
- ],
6557
- }),
6558
- );
6559
- yield* settle;
6560
- yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" }));
6561
- yield* settle;
6562
- assert.deepEqual(harness.liveSelectionChanges, [
6563
- { effortLevel: "high", fastMode: true, ultracode: true },
6564
- { model: "claude-sonnet-4-6" },
6565
- { effortLevel: "high", fastMode: null, ultracode: null },
6566
- ]);
6567
- assert.strictEqual(harness.getOpenedOptions(), originalOptions);
6568
- assert.lengthOf(harness.offeredMessages, 4);
6569
-
6570
- for (const [ordinal, selection] of [
6571
- [5, CLAUDE_TEST_RESTART_MODEL_SELECTION],
6572
- [6, { ...normal, model: "claude-haiku-4-5-20251001" }],
6573
- ] as const) {
6574
- const refused = yield* harness.runtime
6575
- .startTurn(turn(ordinal, selection))
6576
- .pipe(Effect.result);
6577
- assert.equal(refused._tag, "Failure");
6578
- if (refused._tag === "Failure") {
6579
- assert.instanceOf(
6580
- refused.failure.cause,
6581
- ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError,
6582
- );
6583
- }
6513
+ yield* harness.runtime.startTurn(
6514
+ turn(3, {
6515
+ ...normal,
6516
+ options: [
6517
+ { id: "effort", value: "high" },
6518
+ { id: "ultracode", value: true },
6519
+ { id: "fastMode", value: true },
6520
+ ],
6521
+ }),
6522
+ );
6523
+ yield* settle;
6524
+ yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" }));
6525
+ yield* settle;
6526
+ assert.deepEqual(harness.liveSelectionChanges, [
6527
+ { effortLevel: "high", fastMode: true, ultracode: true },
6528
+ { model: "claude-sonnet-4-6" },
6529
+ { effortLevel: "high", fastMode: null, ultracode: null },
6530
+ ]);
6531
+ assert.strictEqual(harness.getOpenedOptions(), originalOptions);
6532
+ assert.lengthOf(harness.offeredMessages, 4);
6533
+
6534
+ for (const [ordinal, selection] of [
6535
+ [5, CLAUDE_TEST_RESTART_MODEL_SELECTION],
6536
+ [6, { ...normal, model: "claude-haiku-4-5-20251001" }],
6537
+ ] as const) {
6538
+ const refused = yield* harness.runtime
6539
+ .startTurn(turn(ordinal, selection))
6540
+ .pipe(Effect.result);
6541
+ assert.equal(refused._tag, "Failure");
6542
+ if (refused._tag === "Failure") {
6543
+ assert.instanceOf(
6544
+ refused.failure.cause,
6545
+ ClaudeAdapterV2.ClaudeBackgroundWorkBlocksQueryReplacementError,
6546
+ );
6547
}
6585
- assert.strictEqual(harness.getOpenedOptions(), originalOptions);
6586
- assert.lengthOf(harness.offeredMessages, 4);
6587
- assert.lengthOf(harness.liveSelectionChanges, 3);
6588
- assert.isTrue(yield* harness.hasPendingBackgroundWork);
6589
- }).pipe(
6590
- Effect.provide(
6591
- Layer.mergeAll(
6592
- IdAllocator.layer,
6593
- McpProviderSessions.layer,
6594
- NodeServices.layer,
6595
- NodeCrypto.layer,
6596
- ),
6548
+ }
6549
+ assert.strictEqual(harness.getOpenedOptions(), originalOptions);
6550
+ assert.lengthOf(harness.offeredMessages, 4);
6551
+ assert.lengthOf(harness.liveSelectionChanges, 3);
6552
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
6553
+ }).pipe(
6554
+ Effect.provide(
6555
+ Layer.mergeAll(
6556
+ IdAllocator.layer,
6557
+ McpProviderSessions.layer,
6558
+ NodeServices.layer,
6559
+ NodeCrypto.layer,
6560
),
6561
),
6562
),
@@ -6601,25 +6564,83 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6564
6565
// regression: #34549 a model change sent with a steer was shown but never applied to the turn.
6566
it.effect("applies a model change sent with a steer to the running turn", () =>
6604
- Effect.scoped(
6605
- Effect.gen(function* () {
6606
- const harness = yield* makeWakeHarness;
6607
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
6608
- const opus = {
6609
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6610
- model: "claude-opus-5-5",
6611
- } satisfies ModelSelection;
6612
- const input = makeClaudeTestTurnInput({
6613
- threadId: harness.threadId,
6614
- providerThread: harness.providerThread,
6615
- now: yield* DateTime.now,
6616
- attemptId: RunAttemptId.make("attempt-steer-model-change"),
6617
- text: "Run the slow build.",
6567
+ Effect.gen(function* () {
6568
+ const harness = yield* makeWakeHarness;
6569
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
6570
+ const opus = {
6571
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6572
+ model: "claude-opus-5-5",
6573
+ } satisfies ModelSelection;
6574
+ const input = makeClaudeTestTurnInput({
6575
+ threadId: harness.threadId,
6576
+ providerThread: harness.providerThread,
6577
+ now: yield* DateTime.now,
6578
+ attemptId: RunAttemptId.make("attempt-steer-model-change"),
6579
+ text: "Run the slow build.",
6580
+ attachments: [],
6581
+ modelSelection: opus,
6582
+ });
6583
+ yield* harness.runtime.startTurn(input);
6584
+ yield* harness.runtime.steerTurn({
6585
+ threadId: harness.threadId,
6586
+ runId: input.runId,
6587
+ providerThread: harness.providerThread,
6588
+ providerTurnId: idAllocator.derive.providerTurn({
6589
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6590
+ nativeTurnId: `turn:${input.attemptId}`,
6591
+ }),
6592
+ modelSelection: { ...opus, model: "claude-sonnet-4-6" },
6593
+ message: {
6594
+ createdBy: "user",
6595
+ creationSource: "web",
6596
+ messageId: MessageId.make("steer-model-change"),
6597
+ text: "Which model are you?",
6598
attachments: [],
6619
- modelSelection: opus,
6620
- });
6621
- yield* harness.runtime.startTurn(input);
6622
- yield* harness.runtime.steerTurn({
6599
+ },
6600
+ });
6601
+ assert.deepEqual(harness.liveSelectionChanges, [
6602
+ { model: "claude-sonnet-4-6" },
6603
+ { effortLevel: "high", fastMode: null, ultracode: null },
6604
+ ]);
6605
+ assert.lengthOf(harness.offeredMessages, 2);
6606
+ }).pipe(
6607
+ Effect.provide(
6608
+ Layer.mergeAll(
6609
+ IdAllocator.layer,
6610
+ McpProviderSessions.layer,
6611
+ NodeServices.layer,
6612
+ NodeCrypto.layer,
6613
+ ),
6614
+ ),
6615
+ ),
6616
+ );
6617
+
6618
+ it.effect("fails a model-changing steer when the turn ends during the selection change", () =>
6619
+ Effect.gen(function* () {
6620
+ let duringFlags: Effect.Effect<void> = Effect.void;
6621
+ const harness = yield* makeWakeHarnessWithOptions({
6622
+ applyFlagSettings: () => Effect.suspend(() => duringFlags),
6623
+ });
6624
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
6625
+ const opus = {
6626
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6627
+ model: "claude-opus-5-5",
6628
+ } satisfies ModelSelection;
6629
+ const input = makeClaudeTestTurnInput({
6630
+ threadId: harness.threadId,
6631
+ providerThread: harness.providerThread,
6632
+ now: yield* DateTime.now,
6633
+ attemptId: RunAttemptId.make("attempt-steer-model-change-race"),
6634
+ text: "Run the slow build.",
6635
+ attachments: [],
6636
+ modelSelection: opus,
6637
+ });
6638
+ yield* harness.runtime.startTurn(input);
6639
+ duringFlags = harness
6640
+ .offerAndWait(turnOneResult)
6641
+ .pipe(Effect.andThen(Queue.take(harness.terminalReceipts)), Effect.asVoid);
6642
+ const steer = yield* harness.runtime
6643
+ .steerTurn({
6644
threadId: harness.threadId,
6645
runId: input.runId,
6646
providerThread: harness.providerThread,
@@ -6631,146 +6652,82 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6652
message: {
6653
createdBy: "user",
6654
creationSource: "web",
6634
- messageId: MessageId.make("steer-model-change"),
6655
+ messageId: MessageId.make("steer-model-change-race"),
6656
text: "Which model are you?",
6657
attachments: [],
6658
},
6638
- });
6639
- assert.deepEqual(harness.liveSelectionChanges, [
6640
- { model: "claude-sonnet-4-6" },
6641
- { effortLevel: "high", fastMode: null, ultracode: null },
6642
- ]);
6643
- assert.lengthOf(harness.offeredMessages, 2);
6644
- }).pipe(
6645
- Effect.provide(
6646
- Layer.mergeAll(
6647
- IdAllocator.layer,
6648
- McpProviderSessions.layer,
6649
- NodeServices.layer,
6650
- NodeCrypto.layer,
6651
- ),
6659
+ })
6660
+ .pipe(Effect.result);
6661
+ assert.equal(steer._tag, "Failure");
6662
+ assert.lengthOf(harness.offeredMessages, 1);
6663
+ }).pipe(
6664
+ Effect.provide(
6665
+ Layer.mergeAll(
6666
+ IdAllocator.layer,
6667
+ McpProviderSessions.layer,
6668
+ NodeServices.layer,
6669
+ NodeCrypto.layer,
6670
),
6671
),
6672
),
6673
);
6674
6657
- it.effect("fails a model-changing steer when the turn ends during the selection change", () =>
6658
- Effect.scoped(
6659
- Effect.gen(function* () {
6660
- let duringFlags: Effect.Effect<void> = Effect.void;
6661
- const harness = yield* makeWakeHarnessWithOptions({
6662
- applyFlagSettings: () => Effect.suspend(() => duringFlags),
6663
- });
6664
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
6665
- const opus = {
6666
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6667
- model: "claude-opus-5-5",
6668
- } satisfies ModelSelection;
6669
- const input = makeClaudeTestTurnInput({
6675
+ it.effect("re-sends the model on the turn after a live selection change fails", () =>
6676
+ Effect.gen(function* () {
6677
+ let failFlags = true;
6678
+ const harness = yield* makeWakeHarnessWithOptions({
6679
+ applyFlagSettings: () =>
6680
+ Effect.suspend(() => {
6681
+ if (!failFlags) return Effect.void;
6682
+ failFlags = false;
6683
+ return Effect.fail(
6684
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
6685
+ method: "applyFlagSettings",
6686
+ cause: new Error("control request failed"),
6687
+ }),
6688
+ );
6689
+ }),
6690
+ });
6691
+ const now = yield* DateTime.now;
6692
+ const opus = {
6693
+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6694
+ model: "claude-opus-5-5",
6695
+ } satisfies ModelSelection;
6696
+ const turn = (ordinal: number, modelSelection: ModelSelection) =>
6697
+ makeClaudeTestTurnInput({
6698
threadId: harness.threadId,
6699
providerThread: harness.providerThread,
6672
- now: yield* DateTime.now,
6673
- attemptId: RunAttemptId.make("attempt-steer-model-change-race"),
6674
- text: "Run the slow build.",
6700
+ now,
6701
+ attemptId: RunAttemptId.make(`attempt-failed-live-change:${ordinal}`),
6702
+ text: `Request ${ordinal}`,
6703
attachments: [],
6676
- modelSelection: opus,
6677
- });
6678
- yield* harness.runtime.startTurn(input);
6679
- duringFlags = harness
6680
- .offerAndWait(turnOneResult)
6681
- .pipe(Effect.andThen(Queue.take(harness.terminalReceipts)), Effect.asVoid);
6682
- const steer = yield* harness.runtime
6683
- .steerTurn({
6684
- threadId: harness.threadId,
6685
- runId: input.runId,
6686
- providerThread: harness.providerThread,
6687
- providerTurnId: idAllocator.derive.providerTurn({
6688
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6689
- nativeTurnId: `turn:${input.attemptId}`,
6690
- }),
6691
- modelSelection: { ...opus, model: "claude-sonnet-4-6" },
6692
- message: {
6693
- createdBy: "user",
6694
- creationSource: "web",
6695
- messageId: MessageId.make("steer-model-change-race"),
6696
- text: "Which model are you?",
6697
- attachments: [],
6698
- },
6699
- })
6700
- .pipe(Effect.result);
6701
- assert.equal(steer._tag, "Failure");
6702
- assert.lengthOf(harness.offeredMessages, 1);
6703
- }).pipe(
6704
- Effect.provide(
6705
- Layer.mergeAll(
6706
- IdAllocator.layer,
6707
- McpProviderSessions.layer,
6708
- NodeServices.layer,
6709
- NodeCrypto.layer,
6710
- ),
6711
- ),
6712
- ),
6713
- ),
6714
- );
6715
-
6716
- it.effect("re-sends the model on the turn after a live selection change fails", () =>
6717
- Effect.scoped(
6718
- Effect.gen(function* () {
6719
- let failFlags = true;
6720
- const harness = yield* makeWakeHarnessWithOptions({
6721
- applyFlagSettings: () =>
6722
- Effect.suspend(() => {
6723
- if (!failFlags) return Effect.void;
6724
- failFlags = false;
6725
- return Effect.fail(
6726
- new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
6727
- method: "applyFlagSettings",
6728
- cause: new Error("control request failed"),
6729
- }),
6730
- );
6731
- }),
6704
+ providerTurnOrdinal: ordinal,
6705
+ modelSelection,
6706
});
6733
- const now = yield* DateTime.now;
6734
- const opus = {
6735
- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
6736
- model: "claude-opus-5-5",
6737
- } satisfies ModelSelection;
6738
- const turn = (ordinal: number, modelSelection: ModelSelection) =>
6739
- makeClaudeTestTurnInput({
6740
- threadId: harness.threadId,
6741
- providerThread: harness.providerThread,
6742
- now,
6743
- attemptId: RunAttemptId.make(`attempt-failed-live-change:${ordinal}`),
6744
- text: `Request ${ordinal}`,
6745
- attachments: [],
6746
- providerTurnOrdinal: ordinal,
6747
- modelSelection,
6748
- });
6749
- yield* harness.runtime.startTurn(turn(1, opus));
6750
- yield* harness.offerAndWait(turnOneResult);
6751
- yield* Queue.take(harness.terminalReceipts);
6752
-
6753
- const failed = yield* harness.runtime
6754
- .startTurn(turn(2, { ...opus, model: "claude-sonnet-4-6" }))
6755
- .pipe(Effect.result);
6756
- assert.equal(failed._tag, "Failure");
6707
+ yield* harness.runtime.startTurn(turn(1, opus));
6708
+ yield* harness.offerAndWait(turnOneResult);
6709
+ yield* Queue.take(harness.terminalReceipts);
6710
6758
- // The process may now run Sonnet, so returning to Opus must send it.
6759
- yield* harness.runtime.startTurn(turn(3, opus));
6760
- assert.deepEqual(harness.liveSelectionChanges, [
6761
- { model: "claude-sonnet-4-6" },
6762
- { effortLevel: "high", fastMode: null, ultracode: null },
6763
- { model: "claude-opus-5-5" },
6764
- { effortLevel: "medium", fastMode: false, ultracode: null },
6765
- ]);
6766
- }).pipe(
6767
- Effect.provide(
6768
- Layer.mergeAll(
6769
- IdAllocator.layer,
6770
- McpProviderSessions.layer,
6771
- NodeServices.layer,
6772
- NodeCrypto.layer,
6773
- ),
6711
+ const failed = yield* harness.runtime
6712
+ .startTurn(turn(2, { ...opus, model: "claude-sonnet-4-6" }))
6713
+ .pipe(Effect.result);
6714
+ assert.equal(failed._tag, "Failure");
6715
+
6716
+ // The process may now run Sonnet, so returning to Opus must send it.
6717
+ yield* harness.runtime.startTurn(turn(3, opus));
6718
+ assert.deepEqual(harness.liveSelectionChanges, [
6719
+ { model: "claude-sonnet-4-6" },
6720
+ { effortLevel: "high", fastMode: null, ultracode: null },
6721
+ { model: "claude-opus-5-5" },
6722
+ { effortLevel: "medium", fastMode: false, ultracode: null },
6723
+ ]);
6724
+ }).pipe(
6725
+ Effect.provide(
6726
+ Layer.mergeAll(
6727
+ IdAllocator.layer,
6728
+ McpProviderSessions.layer,
6729
+ NodeServices.layer,
6730
+ NodeCrypto.layer,
6731
),
6732
),
6733
),
@@ -6996,86 +6953,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6953
it.effect.each(["cancelled", "interrupted", "denied", "permission_denied", undefined])(
6954
"preserves native tool non-execution metadata %s without inferring a denial from text",
6955
(kind) =>
6999
- Effect.scoped(
7000
- Effect.gen(function* () {
7001
- const harness = yield* makeWakeHarness;
7002
- yield* harness.runtime.startTurn(
7003
- makeClaudeTestTurnInput({
7004
- threadId: harness.threadId,
7005
- providerThread: harness.providerThread,
7006
- now: yield* DateTime.now,
7007
- attemptId: RunAttemptId.make("attempt-tool-non-execution"),
7008
- text: "Run the tool.",
7009
- attachments: [],
7010
- }),
7011
- );
7012
- yield* harness.offerAndWait(
7013
- claudeSdkFrame({
7014
- type: "user",
7015
- uuid: "tool-non-execution",
7016
- session_id: WAKE_NATIVE_SESSION,
7017
- parent_tool_use_id: null,
7018
- message: {
7019
- role: "user",
7020
- content: [
7021
- {
7022
- type: "tool_result",
7023
- tool_use_id: "tool-error",
7024
- is_error: true,
7025
- content: "STOP and wait for the user.",
7026
- },
7027
- { type: "tool_result", tool_use_id: "tool-ok", is_error: false, content: "OK" },
7028
- ],
7029
- },
7030
- ...(kind === undefined
7031
- ? {}
7032
- : {
7033
- tool_result_meta: [
7034
- { id: "tool-error", non_execution_kind: kind },
7035
- { id: "tool-ok", non_execution_kind: null },
7036
- ],
7037
- }),
7038
- }),
7039
- );
7040
- yield* Queue.offer(
7041
- harness.sdkMessages,
7042
- makeResultFrame({ uuid: "result-non-execution", result: "Done" }),
7043
- );
7044
- yield* Queue.take(harness.terminalReceipts);
7045
- const items = harness.events.flatMap((event) =>
7046
- event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
7047
- ? [event.turnItem]
7048
- : [],
7049
- );
7050
- const failed = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-error")!;
7051
- assert.equal(
7052
- failed.status,
7053
- kind === "cancelled" || kind === "interrupted" ? kind : "failed",
7054
- );
7055
- assert.equal(failed.toolNonExecutionKind, kind);
7056
- const ok = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-ok")!;
7057
- assert.equal(ok.status, "completed");
7058
- assert.equal(ok.toolNonExecutionKind, undefined);
7059
- const node = harness.events.findLast(
7060
- (event) =>
7061
- event.type === "node.updated" && event.node.nativeItemRef?.nativeId === "tool-error",
7062
- );
7063
- assert.equal(node?.type === "node.updated" ? node.node.status : undefined, failed.status);
7064
- }).pipe(
7065
- Effect.provide(
7066
- Layer.mergeAll(
7067
- IdAllocator.layer,
7068
- McpProviderSessions.layer,
7069
- NodeServices.layer,
7070
- NodeCrypto.layer,
7071
- ),
7072
- ),
7073
- ),
7074
- ),
7075
- );
7076
-
7077
- it.effect("completes a turn after the resume dialog without a failed tool row", () =>
7078
- Effect.scoped(
6956
Effect.gen(function* () {
6957
const harness = yield* makeWakeHarness;
6958
yield* harness.runtime.startTurn(
@@ -7083,52 +6960,63 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6960
threadId: harness.threadId,
6961
providerThread: harness.providerThread,
6962
now: yield* DateTime.now,
7086
- attemptId: RunAttemptId.make("attempt-resume-dialog"),
7087
- text: "continue",
6963
+ attemptId: RunAttemptId.make("attempt-tool-non-execution"),
6964
+ text: "Run the tool.",
6965
attachments: [],
6966
}),
6967
);
7091
- const dialog = yield* Effect.promise(() =>
7092
- harness.getOpenedOptions()!.onUserDialog!(
7093
- {
7094
- dialogKind: "resume_return",
7095
- payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
6968
+ yield* harness.offerAndWait(
6969
+ claudeSdkFrame({
6970
+ type: "user",
6971
+ uuid: "tool-non-execution",
6972
+ session_id: WAKE_NATIVE_SESSION,
6973
+ parent_tool_use_id: null,
6974
+ message: {
6975
+ role: "user",
6976
+ content: [
6977
+ {
6978
+ type: "tool_result",
6979
+ tool_use_id: "tool-error",
6980
+ is_error: true,
6981
+ content: "STOP and wait for the user.",
6982
+ },
6983
+ { type: "tool_result", tool_use_id: "tool-ok", is_error: false, content: "OK" },
6984
+ ],
6985
},
7097
- { signal: new AbortController().signal, requestId: "dialog-resume" },
7098
- ),
7099
- ).pipe(Effect.forkScoped);
7100
- const request = yield* Queue.take(harness.runtimeRequestReceipts);
7101
- assert.deepEqual(
7102
- harness.events.flatMap((event) =>
7103
- event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId
7104
- ? [event.node.parentNodeId]
7105
- : [],
7106
- ),
7107
- [NodeId.make("node-attempt-resume-dialog")],
6986
+ ...(kind === undefined
6987
+ ? {}
6988
+ : {
6989
+ tool_result_meta: [
6990
+ { id: "tool-error", non_execution_kind: kind },
6991
+ { id: "tool-ok", non_execution_kind: null },
6992
+ ],
6993
+ }),
6994
+ }),
6995
);
7109
- yield* harness.runtime.respondToRuntimeRequest({
7110
- requestId: request.runtimeRequest.id,
7111
- answers: {
7112
- [formatClaudeResumeCompactionQuestion({ ageMinutes: 90, estimatedTokens: 120000 })]:
7113
- "Keep full history",
7114
- },
7115
- });
7116
- assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "continue" });
6996
yield* Queue.offer(
6997
harness.sdkMessages,
7119
- makeResultFrame({ uuid: "result-resume-dialog", result: "Done" }),
6998
+ makeResultFrame({ uuid: "result-non-execution", result: "Done" }),
6999
);
7121
- assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
7122
- assert.deepEqual(
7123
- harness.events.flatMap((event) =>
7124
- event.type === "turn_item.updated" &&
7125
- event.turnItem.type === "dynamic_tool" &&
7126
- event.turnItem.nativeItemRef?.nativeId === "dialog-resume"
7127
- ? [event.turnItem.status]
7128
- : [],
7129
- ),
7130
- [],
7000
+ yield* Queue.take(harness.terminalReceipts);
7001
+ const items = harness.events.flatMap((event) =>
7002
+ event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool"
7003
+ ? [event.turnItem]
7004
+ : [],
7005
+ );
7006
+ const failed = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-error")!;
7007
+ assert.equal(
7008
+ failed.status,
7009
+ kind === "cancelled" || kind === "interrupted" ? kind : "failed",
7010
+ );
7011
+ assert.equal(failed.toolNonExecutionKind, kind);
7012
+ const ok = items.findLast((item) => item.nativeItemRef?.nativeId === "tool-ok")!;
7013
+ assert.equal(ok.status, "completed");
7014
+ assert.equal(ok.toolNonExecutionKind, undefined);
7015
+ const node = harness.events.findLast(
7016
+ (event) =>
7017
+ event.type === "node.updated" && event.node.nativeItemRef?.nativeId === "tool-error",
7018
);
7019
+ assert.equal(node?.type === "node.updated" ? node.node.status : undefined, failed.status);
7020
}).pipe(
7021
Effect.provide(
7022
Layer.mergeAll(
@@ -7139,6 +7027,71 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7027
),
7028
),
7029
),
7030
+ );
7031
+
7032
+ it.effect("completes a turn after the resume dialog without a failed tool row", () =>
7033
+ Effect.gen(function* () {
7034
+ const harness = yield* makeWakeHarness;
7035
+ yield* harness.runtime.startTurn(
7036
+ makeClaudeTestTurnInput({
7037
+ threadId: harness.threadId,
7038
+ providerThread: harness.providerThread,
7039
+ now: yield* DateTime.now,
7040
+ attemptId: RunAttemptId.make("attempt-resume-dialog"),
7041
+ text: "continue",
7042
+ attachments: [],
7043
+ }),
7044
+ );
7045
+ const dialog = yield* Effect.promise(() =>
7046
+ harness.getOpenedOptions()!.onUserDialog!(
7047
+ {
7048
+ dialogKind: "resume_return",
7049
+ payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 },
7050
+ },
7051
+ { signal: new AbortController().signal, requestId: "dialog-resume" },
7052
+ ),
7053
+ ).pipe(Effect.forkScoped);
7054
+ const request = yield* Queue.take(harness.runtimeRequestReceipts);
7055
+ assert.deepEqual(
7056
+ harness.events.flatMap((event) =>
7057
+ event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId
7058
+ ? [event.node.parentNodeId]
7059
+ : [],
7060
+ ),
7061
+ [NodeId.make("node-attempt-resume-dialog")],
7062
+ );
7063
+ yield* harness.runtime.respondToRuntimeRequest({
7064
+ requestId: request.runtimeRequest.id,
7065
+ answers: {
7066
+ [formatClaudeResumeCompactionQuestion({ ageMinutes: 90, estimatedTokens: 120000 })]:
7067
+ "Keep full history",
7068
+ },
7069
+ });
7070
+ assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "continue" });
7071
+ yield* Queue.offer(
7072
+ harness.sdkMessages,
7073
+ makeResultFrame({ uuid: "result-resume-dialog", result: "Done" }),
7074
+ );
7075
+ assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed");
7076
+ assert.deepEqual(
7077
+ harness.events.flatMap((event) =>
7078
+ event.type === "turn_item.updated" &&
7079
+ event.turnItem.type === "dynamic_tool" &&
7080
+ event.turnItem.nativeItemRef?.nativeId === "dialog-resume"
7081
+ ? [event.turnItem.status]
7082
+ : [],
7083
+ ),
7084
+ [],
7085
+ );
7086
+ }).pipe(
7087
+ Effect.provide(
7088
+ Layer.mergeAll(
7089
+ IdAllocator.layer,
7090
+ McpProviderSessions.layer,
7091
+ NodeServices.layer,
7092
+ NodeCrypto.layer,
7093
+ ),
7094
+ ),
7095
),
7096
);
7097
@@ -7151,136 +7104,131 @@ describe("ClaudeAdapterV2 background wake turns", () => {
7104
].map((scenario) => ({ terminalReason, ...scenario })),
7105
),
7106
)("handles $terminalReason (steered=$steered, exits=$queryExits)", (scenario) =>
7154
- Effect.scoped(
7155
- Effect.gen(function* () {
7156
- const { terminalReason, steered, queryExits } = scenario;
7157
- const harness = yield* makeWakeHarness;
7158
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
7159
- const attemptId = RunAttemptId.make("attempt-steering-abort");
7160
- const input = makeClaudeTestTurnInput({
7107
+ Effect.gen(function* () {
7108
+ const { terminalReason, steered, queryExits } = scenario;
7109
+ const harness = yield* makeWakeHarness;
7110
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
7111
+ const attemptId = RunAttemptId.make("attempt-steering-abort");
7112
+ const input = makeClaudeTestTurnInput({
7113
+ threadId: harness.threadId,
7114
+ providerThread: harness.providerThread,
7115
+ now: yield* DateTime.now,
7116
+ attemptId,
7117
+ text: "Audit the settings pages.",
7118
+ attachments: [],
7119
+ });
7120
+ yield* harness.runtime.startTurn(input);
7121
+ if (steered) {
7122
+ yield* harness.runtime.steerTurn({
7123
threadId: harness.threadId,
7124
+ runId: input.runId,
7125
providerThread: harness.providerThread,
7163
- now: yield* DateTime.now,
7164
- attemptId,
7165
- text: "Audit the settings pages.",
7166
- attachments: [],
7126
+ providerTurnId: idAllocator.derive.providerTurn({
7127
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
7128
+ nativeTurnId: `turn:${attemptId}`,
7129
+ }),
7130
+ message: {
7131
+ createdBy: "user",
7132
+ creationSource: "web",
7133
+ messageId: MessageId.make("message-steering-abort"),
7134
+ text: "Include the hierarchy mock.",
7135
+ attachments: [],
7136
+ },
7137
});
7168
- yield* harness.runtime.startTurn(input);
7169
- if (steered) {
7170
- yield* harness.runtime.steerTurn({
7171
- threadId: harness.threadId,
7172
- runId: input.runId,
7173
- providerThread: harness.providerThread,
7174
- providerTurnId: idAllocator.derive.providerTurn({
7175
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
7176
- nativeTurnId: `turn:${attemptId}`,
7177
- }),
7178
- message: {
7179
- createdBy: "user",
7180
- creationSource: "web",
7181
- messageId: MessageId.make("message-steering-abort"),
7182
- text: "Include the hierarchy mock.",
7183
- attachments: [],
7184
- },
7185
- });
7186
- assert.equal(harness.offeredMessages[1]?.priority, "now");
7187
- }
7188
- const partialText = "The audit covers the `integ";
7189
- if (!queryExits)
7190
- yield* Queue.offer(
7191
- harness.sdkMessages,
7192
- makeAssistantTextFrame({
7193
- uuid: "00000000-0000-4000-8000-000000000900",
7194
- text: partialText,
7195
- }),
7196
- );
7197
- yield* harness.offerAndWait(
7138
+ assert.equal(harness.offeredMessages[1]?.priority, "now");
7139
+ }
7140
+ const partialText = "The audit covers the `integ";
7141
+ if (!queryExits)
7142
+ yield* Queue.offer(
7143
+ harness.sdkMessages,
7144
+ makeAssistantTextFrame({
7145
+ uuid: "00000000-0000-4000-8000-000000000900",
7146
+ text: partialText,
7147
+ }),
7148
+ );
7149
+ yield* harness.offerAndWait(
7150
+ makeResultFrame({
7151
+ uuid: "00000000-0000-4000-8000-000000000901",
7152
+ result: "",
7153
+ terminalReason,
7154
+ usage: {
7155
+ input_tokens: 600,
7156
+ output_tokens: 40,
7157
+ cache_creation_input_tokens: 500,
7158
+ cache_read_input_tokens: 2000,
7159
+ },
7160
+ }),
7161
+ );
7162
+ if (queryExits) {
7163
+ yield* Queue.shutdown(harness.sdkMessages);
7164
+ } else if (steered) {
7165
+ yield* Queue.offer(harness.sdkMessages, wakeAssistant);
7166
+ yield* Queue.offer(
7167
+ harness.sdkMessages,
7168
makeResultFrame({
7199
- uuid: "00000000-0000-4000-8000-000000000901",
7200
- result: "",
7201
- terminalReason,
7169
+ uuid: "00000000-0000-4000-8000-000000000902",
7170
+ result: "Audit finished after the steer.",
7171
usage: {
7203
- input_tokens: 600,
7204
- output_tokens: 40,
7205
- cache_creation_input_tokens: 500,
7206
- cache_read_input_tokens: 2000,
7172
+ input_tokens: 3,
7173
+ output_tokens: 6,
7174
+ cache_creation_input_tokens: 2347,
7175
+ cache_read_input_tokens: 9455,
7176
},
7177
}),
7178
);
7210
- if (queryExits) {
7211
- yield* Queue.shutdown(harness.sdkMessages);
7212
- } else if (steered) {
7213
- yield* Queue.offer(harness.sdkMessages, wakeAssistant);
7214
- yield* Queue.offer(
7215
- harness.sdkMessages,
7216
- makeResultFrame({
7217
- uuid: "00000000-0000-4000-8000-000000000902",
7218
- result: "Audit finished after the steer.",
7219
- usage: {
7220
- input_tokens: 3,
7221
- output_tokens: 6,
7222
- cache_creation_input_tokens: 2347,
7223
- cache_read_input_tokens: 9455,
7224
- },
7225
- }),
7226
- );
7227
- }
7228
- const terminal = yield* Queue.take(harness.terminalReceipts);
7179
+ }
7180
+ const terminal = yield* Queue.take(harness.terminalReceipts);
7181
+ assert.equal(terminal.status, queryExits ? "failed" : steered ? "completed" : "interrupted");
7182
+ if (steered && !queryExits && terminalReason === "aborted_streaming") {
7183
+ // The steer cut this reply off mid-stream; it must not read as a finished answer.
7184
+ const partial = harness.events.findLast(
7185
+ (event) =>
7186
+ event.type === "turn_item.updated" &&
7187
+ event.turnItem.type === "assistant_message" &&
7188
+ event.turnItem.text === partialText,
7189
+ );
7190
assert.equal(
7230
- terminal.status,
7231
- queryExits ? "failed" : steered ? "completed" : "interrupted",
7191
+ partial?.type === "turn_item.updated" ? partial.turnItem.status : undefined,
7192
+ "interrupted",
7193
);
7233
- if (steered && !queryExits && terminalReason === "aborted_streaming") {
7234
- // The steer cut this reply off mid-stream; it must not read as a finished answer.
7235
- const partial = harness.events.findLast(
7236
- (event) =>
7237
- event.type === "turn_item.updated" &&
7238
- event.turnItem.type === "assistant_message" &&
7239
- event.turnItem.text === partialText,
7240
- );
7241
- assert.equal(
7242
- partial?.type === "turn_item.updated" ? partial.turnItem.status : undefined,
7243
- "interrupted",
7244
- );
7245
- }
7246
- if (steered) {
7247
- if (!queryExits)
7248
- assert.isTrue(
7249
- harness.events.some(
7250
- (event) =>
7251
- event.type === "turn_item.updated" &&
7252
- event.turnItem.type === "assistant_message" &&
7253
- event.turnItem.text === WAKE_ASSISTANT_TEXT,
7254
- ),
7255
- );
7256
- const completed = harness.events.findLast(
7257
- (event) => event.type === "provider_turn.updated",
7258
- );
7259
- assert.deepEqual(
7260
- completed?.type === "provider_turn.updated"
7261
- ? completed.providerTurn.turnTokenUsage
7262
- : undefined,
7263
- {
7264
- usageScope: "main_agent",
7265
- usageStatus: queryExits ? "partial" : "complete",
7266
- hasSubagents: false,
7267
- inputTokens: queryExits ? 3100 : 603 + 2847 + 11455,
7268
- outputTokens: queryExits ? 40 : 46,
7269
- cachedInputTokens: queryExits ? 2000 : 11455,
7270
- cacheCreationTokens: queryExits ? 500 : 2847,
7271
- ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }),
7272
- },
7194
+ }
7195
+ if (steered) {
7196
+ if (!queryExits)
7197
+ assert.isTrue(
7198
+ harness.events.some(
7199
+ (event) =>
7200
+ event.type === "turn_item.updated" &&
7201
+ event.turnItem.type === "assistant_message" &&
7202
+ event.turnItem.text === WAKE_ASSISTANT_TEXT,
7203
+ ),
7204
);
7274
- }
7275
- assert.lengthOf(harness.terminalEvents(), 1);
7276
- }).pipe(
7277
- Effect.provide(
7278
- Layer.mergeAll(
7279
- IdAllocator.layer,
7280
- McpProviderSessions.layer,
7281
- NodeServices.layer,
7282
- NodeCrypto.layer,
7283
- ),
7205
+ const completed = harness.events.findLast(
7206
+ (event) => event.type === "provider_turn.updated",
7207
+ );
7208
+ assert.deepEqual(
7209
+ completed?.type === "provider_turn.updated"
7210
+ ? completed.providerTurn.turnTokenUsage
7211
+ : undefined,
7212
+ {
7213
+ usageScope: "main_agent",
7214
+ usageStatus: queryExits ? "partial" : "complete",
7215
+ hasSubagents: false,
7216
+ inputTokens: queryExits ? 3100 : 603 + 2847 + 11455,
7217
+ outputTokens: queryExits ? 40 : 46,
7218
+ cachedInputTokens: queryExits ? 2000 : 11455,
7219
+ cacheCreationTokens: queryExits ? 500 : 2847,
7220
+ ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }),
7221
+ },
7222
+ );
7223
+ }
7224
+ assert.lengthOf(harness.terminalEvents(), 1);
7225
+ }).pipe(
7226
+ Effect.provide(
7227
+ Layer.mergeAll(
7228
+ IdAllocator.layer,
7229
+ McpProviderSessions.layer,
7230
+ NodeServices.layer,
7231
+ NodeCrypto.layer,
7232
),
7233
),
7234
),
@@ -10036,248 +9984,243 @@ describe("ClaudeAdapterV2 background wake turns", () => {
9984
);
9985
9986
it.effect("preserves typed Claude plans and todos through generic tool completion", () =>
10039
- Effect.scoped(
10040
- Effect.gen(function* () {
10041
- const harness = yield* makeWakeHarness;
10042
- const now = yield* DateTime.now;
10043
- const assistantTools = (
10044
- uuid: string,
10045
- tools: ReadonlyArray<Record<string, unknown>>,
10046
- parentToolUseId: string | null = null,
10047
- ) =>
10048
- claudeSdkFrame({
10049
- type: "assistant",
10050
- message: {
10051
- model: "claude-sonnet-4-6",
10052
- id: `msg_${uuid}`,
10053
- type: "message",
10054
- role: "assistant",
10055
- content: tools.map((tool) => ({ type: "tool_use", ...tool })),
10056
- stop_reason: "tool_use",
10057
- stop_sequence: null,
10058
- usage: {
10059
- input_tokens: 1,
10060
- output_tokens: 1,
10061
- cache_creation_input_tokens: 0,
10062
- cache_read_input_tokens: 0,
10063
- },
10064
- },
10065
- parent_tool_use_id: parentToolUseId,
10066
- uuid,
10067
- session_id: WAKE_NATIVE_SESSION,
10068
- });
10069
- const toolResults = (uuid: string, toolUseIds: ReadonlyArray<string>) =>
10070
- claudeSdkFrame({
10071
- type: "user",
10072
- message: {
10073
- role: "user",
10074
- content: toolUseIds.map((toolUseId) => ({
10075
- type: "tool_result",
10076
- tool_use_id: toolUseId,
10077
- content: "ok",
10078
- })),
10079
- },
10080
- parent_tool_use_id: null,
10081
- uuid,
10082
- session_id: WAKE_NATIVE_SESSION,
10083
- });
10084
-
10085
- yield* harness.runtime.startTurn(
10086
- makeClaudeTestTurnInput({
10087
- threadId: harness.threadId,
10088
- providerThread: harness.providerThread,
10089
- now,
10090
- attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-1"),
10091
- text: "Plan the work.",
10092
- attachments: [],
10093
- }),
10094
- );
10095
- yield* Queue.offer(
10096
- harness.sdkMessages,
10097
- assistantTools("00000000-0000-4000-8000-000000000501", [
10098
- {
10099
- id: "tool-todo-1",
10100
- name: "TodoWrite",
10101
- input: { todos: [{ content: "Inspect", status: "in_progress" }] },
9987
+ Effect.gen(function* () {
9988
+ const harness = yield* makeWakeHarness;
9989
+ const now = yield* DateTime.now;
9990
+ const assistantTools = (
9991
+ uuid: string,
9992
+ tools: ReadonlyArray<Record<string, unknown>>,
9993
+ parentToolUseId: string | null = null,
9994
+ ) =>
9995
+ claudeSdkFrame({
9996
+ type: "assistant",
9997
+ message: {
9998
+ model: "claude-sonnet-4-6",
9999
+ id: `msg_${uuid}`,
10000
+ type: "message",
10001
+ role: "assistant",
10002
+ content: tools.map((tool) => ({ type: "tool_use", ...tool })),
10003
+ stop_reason: "tool_use",
10004
+ stop_sequence: null,
10005
+ usage: {
10006
+ input_tokens: 1,
10007
+ output_tokens: 1,
10008
+ cache_creation_input_tokens: 0,
10009
+ cache_read_input_tokens: 0,
10010
},
10103
- ]),
10104
- );
10105
- yield* Queue.offer(
10106
- harness.sdkMessages,
10107
- assistantTools("00000000-0000-4000-8000-000000000501", [
10108
- {
10109
- id: "tool-todo-1",
10110
- name: "TodoWrite",
10111
- input: { todos: [{ content: "Inspect", status: "in_progress" }] },
10112
- },
10113
- ]),
10114
- );
10115
- yield* Queue.offer(
10116
- harness.sdkMessages,
10117
- toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]),
10118
- );
10119
- yield* harness.offerAndWait(
10120
- claudeSdkFrame({ ...wakeTurnInit, permissionMode: "bypassPermissions" }),
10121
- );
10122
- yield* Queue.offer(
10123
- harness.sdkMessages,
10124
- claudeSdkFrame({
10125
- type: "system",
10126
- subtype: "status",
10127
- status: null,
10128
- permissionMode: "plan",
10129
- uuid: "00000000-0000-4000-8000-000000000508",
10130
- session_id: WAKE_NATIVE_SESSION,
10131
- }),
10132
- );
10133
- yield* harness.offerAndWait(
10134
- claudeSdkFrame({
10135
- ...wakeTurnInit,
10136
- uuid: "00000000-0000-4000-8000-000000000509",
10137
- permissionMode: "plan",
10138
- }),
10139
- );
10140
- yield* Queue.offer(
10141
- harness.sdkMessages,
10142
- makeResultFrame({
10143
- uuid: "00000000-0000-4000-8000-000000000503",
10144
- result: "Todo recorded.",
10145
- }),
10146
- );
10147
- yield* Queue.take(harness.terminalReceipts);
10011
+ },
10012
+ parent_tool_use_id: parentToolUseId,
10013
+ uuid,
10014
+ session_id: WAKE_NATIVE_SESSION,
10015
+ });
10016
+ const toolResults = (uuid: string, toolUseIds: ReadonlyArray<string>) =>
10017
+ claudeSdkFrame({
10018
+ type: "user",
10019
+ message: {
10020
+ role: "user",
10021
+ content: toolUseIds.map((toolUseId) => ({
10022
+ type: "tool_result",
10023
+ tool_use_id: toolUseId,
10024
+ content: "ok",
10025
+ })),
10026
+ },
10027
+ parent_tool_use_id: null,
10028
+ uuid,
10029
+ session_id: WAKE_NATIVE_SESSION,
10030
+ });
10031
10149
- yield* harness.runtime.startTurn(
10150
- makeClaudeTestTurnInput({
10151
- threadId: harness.threadId,
10152
- providerThread: harness.providerThread,
10153
- now,
10154
- attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-2"),
10155
- providerTurnOrdinal: 2,
10156
- text: "Finish the plan.",
10157
- attachments: [],
10158
- }),
10159
- );
10160
- const canUseTool = harness.getOpenedOptions()?.canUseTool;
10161
- assert.isFunction(canUseTool);
10162
- const planMarkdown = "# Ready to implement\n\n1. Ship it.";
10163
- yield* Effect.promise(() =>
10164
- canUseTool!(
10165
- "ExitPlanMode",
10166
- { plan: planMarkdown },
10167
- {
10168
- signal: new AbortController().signal,
10169
- toolUseID: "tool-exit-plan-1",
10170
- requestId: "request-exit-plan-1",
10171
- },
10172
- ),
10173
- );
10174
- yield* Queue.offer(
10175
- harness.sdkMessages,
10176
- assistantTools("00000000-0000-4000-8000-000000000504", [
10177
- {
10178
- id: "tool-todo-2",
10179
- name: "TodoWrite",
10180
- input: { todos: [{ content: "Inspect", status: "completed" }] },
10181
- },
10182
- { id: "tool-exit-plan-1", name: "ExitPlanMode", input: { plan: planMarkdown } },
10183
- ]),
10184
- );
10185
- yield* Queue.offer(
10186
- harness.sdkMessages,
10187
- assistantTools(
10188
- "00000000-0000-4000-8000-000000000507",
10189
- [
10190
- {
10191
- id: "tool-subagent-todo",
10192
- name: "TodoWrite",
10193
- input: { todos: [{ content: "Child-only work", status: "in_progress" }] },
10194
- },
10195
- ],
10196
- "tool-parent-agent",
10197
- ),
10198
- );
10199
- yield* Queue.offer(
10200
- harness.sdkMessages,
10201
- toolResults("00000000-0000-4000-8000-000000000505", ["tool-todo-2", "tool-exit-plan-1"]),
10202
- );
10203
- yield* Queue.offer(
10204
- harness.sdkMessages,
10205
- assistantTools("00000000-0000-4000-8000-000000000509", [
10032
+ yield* harness.runtime.startTurn(
10033
+ makeClaudeTestTurnInput({
10034
+ threadId: harness.threadId,
10035
+ providerThread: harness.providerThread,
10036
+ now,
10037
+ attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-1"),
10038
+ text: "Plan the work.",
10039
+ attachments: [],
10040
+ }),
10041
+ );
10042
+ yield* Queue.offer(
10043
+ harness.sdkMessages,
10044
+ assistantTools("00000000-0000-4000-8000-000000000501", [
10045
+ {
10046
+ id: "tool-todo-1",
10047
+ name: "TodoWrite",
10048
+ input: { todos: [{ content: "Inspect", status: "in_progress" }] },
10049
+ },
10050
+ ]),
10051
+ );
10052
+ yield* Queue.offer(
10053
+ harness.sdkMessages,
10054
+ assistantTools("00000000-0000-4000-8000-000000000501", [
10055
+ {
10056
+ id: "tool-todo-1",
10057
+ name: "TodoWrite",
10058
+ input: { todos: [{ content: "Inspect", status: "in_progress" }] },
10059
+ },
10060
+ ]),
10061
+ );
10062
+ yield* Queue.offer(
10063
+ harness.sdkMessages,
10064
+ toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]),
10065
+ );
10066
+ yield* harness.offerAndWait(
10067
+ claudeSdkFrame({ ...wakeTurnInit, permissionMode: "bypassPermissions" }),
10068
+ );
10069
+ yield* Queue.offer(
10070
+ harness.sdkMessages,
10071
+ claudeSdkFrame({
10072
+ type: "system",
10073
+ subtype: "status",
10074
+ status: null,
10075
+ permissionMode: "plan",
10076
+ uuid: "00000000-0000-4000-8000-000000000508",
10077
+ session_id: WAKE_NATIVE_SESSION,
10078
+ }),
10079
+ );
10080
+ yield* harness.offerAndWait(
10081
+ claudeSdkFrame({
10082
+ ...wakeTurnInit,
10083
+ uuid: "00000000-0000-4000-8000-000000000509",
10084
+ permissionMode: "plan",
10085
+ }),
10086
+ );
10087
+ yield* Queue.offer(
10088
+ harness.sdkMessages,
10089
+ makeResultFrame({
10090
+ uuid: "00000000-0000-4000-8000-000000000503",
10091
+ result: "Todo recorded.",
10092
+ }),
10093
+ );
10094
+ yield* Queue.take(harness.terminalReceipts);
10095
+
10096
+ yield* harness.runtime.startTurn(
10097
+ makeClaudeTestTurnInput({
10098
+ threadId: harness.threadId,
10099
+ providerThread: harness.providerThread,
10100
+ now,
10101
+ attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-2"),
10102
+ providerTurnOrdinal: 2,
10103
+ text: "Finish the plan.",
10104
+ attachments: [],
10105
+ }),
10106
+ );
10107
+ const canUseTool = harness.getOpenedOptions()?.canUseTool;
10108
+ assert.isFunction(canUseTool);
10109
+ const planMarkdown = "# Ready to implement\n\n1. Ship it.";
10110
+ yield* Effect.promise(() =>
10111
+ canUseTool!(
10112
+ "ExitPlanMode",
10113
+ { plan: planMarkdown },
10114
+ {
10115
+ signal: new AbortController().signal,
10116
+ toolUseID: "tool-exit-plan-1",
10117
+ requestId: "request-exit-plan-1",
10118
+ },
10119
+ ),
10120
+ );
10121
+ yield* Queue.offer(
10122
+ harness.sdkMessages,
10123
+ assistantTools("00000000-0000-4000-8000-000000000504", [
10124
+ {
10125
+ id: "tool-todo-2",
10126
+ name: "TodoWrite",
10127
+ input: { todos: [{ content: "Inspect", status: "completed" }] },
10128
+ },
10129
+ { id: "tool-exit-plan-1", name: "ExitPlanMode", input: { plan: planMarkdown } },
10130
+ ]),
10131
+ );
10132
+ yield* Queue.offer(
10133
+ harness.sdkMessages,
10134
+ assistantTools(
10135
+ "00000000-0000-4000-8000-000000000507",
10136
+ [
10137
{
10207
- id: "tool-todo-3",
10138
+ id: "tool-subagent-todo",
10139
name: "TodoWrite",
10209
- input: { todos: [{ content: "Implement", status: "pending" }] },
10140
+ input: { todos: [{ content: "Child-only work", status: "in_progress" }] },
10141
},
10211
- ]),
10212
- );
10213
- yield* Queue.offer(
10214
- harness.sdkMessages,
10215
- toolResults("00000000-0000-4000-8000-000000000510", ["tool-todo-3"]),
10216
- );
10217
- yield* Queue.offer(
10218
- harness.sdkMessages,
10219
- makeResultFrame({
10220
- uuid: "00000000-0000-4000-8000-000000000506",
10221
- result: "Plan captured.",
10222
- }),
10223
- );
10224
- yield* Queue.take(harness.terminalReceipts);
10142
+ ],
10143
+ "tool-parent-agent",
10144
+ ),
10145
+ );
10146
+ yield* Queue.offer(
10147
+ harness.sdkMessages,
10148
+ toolResults("00000000-0000-4000-8000-000000000505", ["tool-todo-2", "tool-exit-plan-1"]),
10149
+ );
10150
+ yield* Queue.offer(
10151
+ harness.sdkMessages,
10152
+ assistantTools("00000000-0000-4000-8000-000000000509", [
10153
+ {
10154
+ id: "tool-todo-3",
10155
+ name: "TodoWrite",
10156
+ input: { todos: [{ content: "Implement", status: "pending" }] },
10157
+ },
10158
+ ]),
10159
+ );
10160
+ yield* Queue.offer(
10161
+ harness.sdkMessages,
10162
+ toolResults("00000000-0000-4000-8000-000000000510", ["tool-todo-3"]),
10163
+ );
10164
+ yield* Queue.offer(
10165
+ harness.sdkMessages,
10166
+ makeResultFrame({
10167
+ uuid: "00000000-0000-4000-8000-000000000506",
10168
+ result: "Plan captured.",
10169
+ }),
10170
+ );
10171
+ yield* Queue.take(harness.terminalReceipts);
10172
10226
- const items = new Map(
10227
- harness.events.flatMap((event) =>
10228
- event.type === "turn_item.updated" ? [[String(event.turnItem.id), event.turnItem]] : [],
10229
- ),
10230
- );
10231
- const plans = new Map(
10232
- harness.events.flatMap((event) =>
10233
- event.type === "plan.updated" ? [[String(event.plan.id), event.plan]] : [],
10234
- ),
10235
- );
10236
- const todoItems = [...items.values()].filter((item) => item.type === "todo_list");
10237
- const proposedItems = [...items.values()].filter((item) => item.type === "proposed_plan");
10238
- assert.lengthOf(todoItems, 3);
10239
- assert.equal(todoItems[1]?.status, "completed");
10240
- assert.deepEqual(todoItems[1]?.steps, [
10241
- { id: "todo-0", text: "Inspect", status: "completed" },
10242
- ]);
10243
- assert.deepEqual(todoItems[2]?.steps, [
10244
- { id: "todo-0", text: "Implement", status: "pending" },
10245
- ]);
10246
- assert.equal(todoItems[1]?.runId, todoItems[2]?.runId);
10247
- assert.lengthOf(proposedItems, 1);
10248
- assert.equal(
10249
- proposedItems[0]?.type === "proposed_plan" && proposedItems[0].markdown,
10250
- planMarkdown,
10251
- );
10252
- assert.isTrue(
10253
- [...items.values()].some(
10254
- (item) =>
10255
- item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-todo-2",
10256
- ),
10257
- );
10258
- assert.isTrue(
10259
- [...items.values()].some(
10260
- (item) =>
10261
- item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-exit-plan-1",
10262
- ),
10263
- );
10264
- const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan");
10265
- assert.equal(proposedPlan?.status, "active");
10266
- assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]);
10267
- assert.deepEqual(
10268
- [...plans.values()]
10269
- .filter((plan) => plan.kind === "todo_list")
10270
- .map((plan) => plan.status),
10271
- ["superseded", "superseded", "active"],
10272
- );
10273
- }).pipe(
10274
- Effect.provide(
10275
- Layer.mergeAll(
10276
- IdAllocator.layer,
10277
- McpProviderSessions.layer,
10278
- NodeServices.layer,
10279
- NodeCrypto.layer,
10280
- ),
10173
+ const items = new Map(
10174
+ harness.events.flatMap((event) =>
10175
+ event.type === "turn_item.updated" ? [[String(event.turnItem.id), event.turnItem]] : [],
10176
+ ),
10177
+ );
10178
+ const plans = new Map(
10179
+ harness.events.flatMap((event) =>
10180
+ event.type === "plan.updated" ? [[String(event.plan.id), event.plan]] : [],
10181
+ ),
10182
+ );
10183
+ const todoItems = [...items.values()].filter((item) => item.type === "todo_list");
10184
+ const proposedItems = [...items.values()].filter((item) => item.type === "proposed_plan");
10185
+ assert.lengthOf(todoItems, 3);
10186
+ assert.equal(todoItems[1]?.status, "completed");
10187
+ assert.deepEqual(todoItems[1]?.steps, [
10188
+ { id: "todo-0", text: "Inspect", status: "completed" },
10189
+ ]);
10190
+ assert.deepEqual(todoItems[2]?.steps, [
10191
+ { id: "todo-0", text: "Implement", status: "pending" },
10192
+ ]);
10193
+ assert.equal(todoItems[1]?.runId, todoItems[2]?.runId);
10194
+ assert.lengthOf(proposedItems, 1);
10195
+ assert.equal(
10196
+ proposedItems[0]?.type === "proposed_plan" && proposedItems[0].markdown,
10197
+ planMarkdown,
10198
+ );
10199
+ assert.isTrue(
10200
+ [...items.values()].some(
10201
+ (item) => item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-todo-2",
10202
+ ),
10203
+ );
10204
+ assert.isTrue(
10205
+ [...items.values()].some(
10206
+ (item) =>
10207
+ item.type === "dynamic_tool" && item.nativeItemRef?.nativeId === "tool-exit-plan-1",
10208
+ ),
10209
+ );
10210
+ const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan");
10211
+ assert.equal(proposedPlan?.status, "active");
10212
+ assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]);
10213
+ assert.deepEqual(
10214
+ [...plans.values()].filter((plan) => plan.kind === "todo_list").map((plan) => plan.status),
10215
+ ["superseded", "superseded", "active"],
10216
+ );
10217
+ }).pipe(
10218
+ Effect.provide(
10219
+ Layer.mergeAll(
10220
+ IdAllocator.layer,
10221
+ McpProviderSessions.layer,
10222
+ NodeServices.layer,
10223
+ NodeCrypto.layer,
10224
),
10225
),
10226
),
@@ -10843,86 +10786,140 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10786
);
10787
10788
it.effect("resolves API retries on resumed assistant activity", () =>
10846
- Effect.scoped(
10847
- Effect.gen(function* () {
10848
- const harness = yield* makeWakeHarness;
10849
- const now = yield* DateTime.now;
10850
- yield* harness.runtime.startTurn(
10851
- makeClaudeTestTurnInput({
10852
- threadId: harness.threadId,
10853
- providerThread: harness.providerThread,
10854
- now,
10855
- attemptId: RunAttemptId.make("attempt-claude-api-retry"),
10856
- text: "Open github.com.",
10857
- attachments: [],
10858
- }),
10859
- );
10860
-
10861
- yield* Queue.offer(
10862
- harness.sdkMessages,
10863
- claudeSdkFrame({
10864
- type: "system",
10865
- subtype: "api_retry",
10866
- attempt: 2,
10867
- max_retries: 10,
10868
- retry_delay_ms: 1_500,
10869
- error_status: 529,
10870
- error: "overloaded",
10871
- uuid: "00000000-0000-4000-8000-000000000201",
10872
- session_id: WAKE_NATIVE_SESSION,
10873
- }),
10874
- );
10875
- const retryItems = () =>
10876
- harness.events.flatMap((event) =>
10877
- event.type === "turn_item.updated" &&
10878
- event.turnItem.type === "error" &&
10879
- event.turnItem.retry !== undefined
10880
- ? [event.turnItem]
10881
- : [],
10882
- );
10883
- yield* harness.until(() => retryItems().length === 1);
10884
- const runningRetry = retryItems()[0];
10885
- assert.equal(runningRetry?.status, "running");
10886
- assert.equal(runningRetry?.failure.code, "api_error_529");
10887
- assert.deepEqual(runningRetry?.retry, {
10888
- attempt: 2,
10889
- maxAttempts: 10,
10890
- retryDelayMs: 1_500,
10891
- });
10789
+ Effect.gen(function* () {
10790
+ const harness = yield* makeWakeHarness;
10791
+ const now = yield* DateTime.now;
10792
+ yield* harness.runtime.startTurn(
10793
+ makeClaudeTestTurnInput({
10794
+ threadId: harness.threadId,
10795
+ providerThread: harness.providerThread,
10796
+ now,
10797
+ attemptId: RunAttemptId.make("attempt-claude-api-retry"),
10798
+ text: "Open github.com.",
10799
+ attachments: [],
10800
+ }),
10801
+ );
10802
10893
- // The stream starting again settles the retry before any assistant message completes.
10894
- yield* Queue.offer(
10895
- harness.sdkMessages,
10896
- claudeSdkFrame({
10897
- type: "stream_event",
10898
- event: { type: "message_start", message: { id: "api-retry-recovered-message" } },
10899
- parent_tool_use_id: null,
10900
- session_id: WAKE_NATIVE_SESSION,
10901
- uuid: "00000000-0000-4000-8000-000000000204",
10902
- }),
10803
+ yield* Queue.offer(
10804
+ harness.sdkMessages,
10805
+ claudeSdkFrame({
10806
+ type: "system",
10807
+ subtype: "api_retry",
10808
+ attempt: 2,
10809
+ max_retries: 10,
10810
+ retry_delay_ms: 1_500,
10811
+ error_status: 529,
10812
+ error: "overloaded",
10813
+ uuid: "00000000-0000-4000-8000-000000000201",
10814
+ session_id: WAKE_NATIVE_SESSION,
10815
+ }),
10816
+ );
10817
+ const retryItems = () =>
10818
+ harness.events.flatMap((event) =>
10819
+ event.type === "turn_item.updated" &&
10820
+ event.turnItem.type === "error" &&
10821
+ event.turnItem.retry !== undefined
10822
+ ? [event.turnItem]
10823
+ : [],
10824
);
10904
- yield* harness.until(() => retryItems().length === 2);
10905
- assert.lengthOf(harness.terminalEvents(), 0);
10906
- const recoveredRetry = retryItems()[1];
10907
- assert.equal(recoveredRetry?.id, runningRetry?.id);
10908
- assert.equal(recoveredRetry?.status, "completed");
10909
- assert.equal(recoveredRetry?.title, "Provider recovered");
10910
- yield* Queue.offer(
10911
- harness.sdkMessages,
10912
- makeAssistantTextFrame({
10913
- uuid: "00000000-0000-4000-8000-000000000202",
10914
- text: "Opening GitHub.",
10825
+ yield* harness.until(() => retryItems().length === 1);
10826
+ const runningRetry = retryItems()[0];
10827
+ assert.equal(runningRetry?.status, "running");
10828
+ assert.equal(runningRetry?.failure.code, "api_error_529");
10829
+ assert.deepEqual(runningRetry?.retry, {
10830
+ attempt: 2,
10831
+ maxAttempts: 10,
10832
+ retryDelayMs: 1_500,
10833
+ });
10834
+
10835
+ // The stream starting again settles the retry before any assistant message completes.
10836
+ yield* Queue.offer(
10837
+ harness.sdkMessages,
10838
+ claudeSdkFrame({
10839
+ type: "stream_event",
10840
+ event: { type: "message_start", message: { id: "api-retry-recovered-message" } },
10841
+ parent_tool_use_id: null,
10842
+ session_id: WAKE_NATIVE_SESSION,
10843
+ uuid: "00000000-0000-4000-8000-000000000204",
10844
+ }),
10845
+ );
10846
+ yield* harness.until(() => retryItems().length === 2);
10847
+ assert.lengthOf(harness.terminalEvents(), 0);
10848
+ const recoveredRetry = retryItems()[1];
10849
+ assert.equal(recoveredRetry?.id, runningRetry?.id);
10850
+ assert.equal(recoveredRetry?.status, "completed");
10851
+ assert.equal(recoveredRetry?.title, "Provider recovered");
10852
+ yield* Queue.offer(
10853
+ harness.sdkMessages,
10854
+ makeAssistantTextFrame({
10855
+ uuid: "00000000-0000-4000-8000-000000000202",
10856
+ text: "Opening GitHub.",
10857
+ }),
10858
+ );
10859
+
10860
+ yield* Queue.offer(
10861
+ harness.sdkMessages,
10862
+ makeResultFrame({
10863
+ uuid: "00000000-0000-4000-8000-000000000203",
10864
+ result: "Opened GitHub.",
10865
+ }),
10866
+ );
10867
+ yield* harness.awaitTerminal(1);
10868
+ }).pipe(
10869
+ Effect.provide(
10870
+ Layer.mergeAll(
10871
+ IdAllocator.layer,
10872
+ McpProviderSessions.layer,
10873
+ NodeServices.layer,
10874
+ NodeCrypto.layer,
10875
+ ),
10876
+ ),
10877
+ ),
10878
+ );
10879
+
10880
+ it.effect.each(["api_error", "overloaded_status"] as const)(
10881
+ "fails a success-shaped Claude result with %s",
10882
+ (terminalReason) =>
10883
+ Effect.gen(function* () {
10884
+ const harness = yield* makeWakeHarness;
10885
+ const now = yield* DateTime.now;
10886
+ yield* harness.runtime.startTurn(
10887
+ makeClaudeTestTurnInput({
10888
+ threadId: harness.threadId,
10889
+ providerThread: harness.providerThread,
10890
+ now,
10891
+ attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
10892
+ text: "Complete the task.",
10893
+ attachments: [],
10894
}),
10895
);
10917
-
10896
yield* Queue.offer(
10897
harness.sdkMessages,
10898
makeResultFrame({
10921
- uuid: "00000000-0000-4000-8000-000000000203",
10922
- result: "Opened GitHub.",
10899
+ uuid: "00000000-0000-4000-8000-000000000205",
10900
+ result: "Provider failure details.",
10901
+ isError: false,
10902
+ ...(terminalReason === "overloaded_status"
10903
+ ? { apiErrorStatus: 529 }
10904
+ : { terminalReason }),
10905
}),
10906
);
10925
- yield* harness.awaitTerminal(1);
10907
+ const terminal = yield* Queue.take(harness.terminalReceipts);
10908
+ assert.equal(terminal.status, "failed");
10909
+ if (terminal.status !== "failed") return;
10910
+ assert.isNotEmpty(terminal.failure.message);
10911
+ assert.equal(terminal.failure.class, "provider_error");
10912
+ assert.isFalse(
10913
+ harness.events.some(
10914
+ (event) =>
10915
+ event.type === "message.updated" &&
10916
+ event.message.text === "Provider failure details.",
10917
+ ),
10918
+ );
10919
+ assert.equal(
10920
+ terminal.failure.code,
10921
+ terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
10922
+ );
10923
}).pipe(
10924
Effect.provide(
10925
Layer.mergeAll(
@@ -10933,64 +10930,6 @@ describe("ClaudeAdapterV2 background wake turns", () => {
10930
),
10931
),
10932
),
10936
- ),
10937
- );
10938
-
10939
- it.effect.each(["api_error", "overloaded_status"] as const)(
10940
- "fails a success-shaped Claude result with %s",
10941
- (terminalReason) =>
10942
- Effect.scoped(
10943
- Effect.gen(function* () {
10944
- const harness = yield* makeWakeHarness;
10945
- const now = yield* DateTime.now;
10946
- yield* harness.runtime.startTurn(
10947
- makeClaudeTestTurnInput({
10948
- threadId: harness.threadId,
10949
- providerThread: harness.providerThread,
10950
- now,
10951
- attemptId: RunAttemptId.make("attempt-structured-terminal-failure"),
10952
- text: "Complete the task.",
10953
- attachments: [],
10954
- }),
10955
- );
10956
- yield* Queue.offer(
10957
- harness.sdkMessages,
10958
- makeResultFrame({
10959
- uuid: "00000000-0000-4000-8000-000000000205",
10960
- result: "Provider failure details.",
10961
- isError: false,
10962
- ...(terminalReason === "overloaded_status"
10963
- ? { apiErrorStatus: 529 }
10964
- : { terminalReason }),
10965
- }),
10966
- );
10967
- const terminal = yield* Queue.take(harness.terminalReceipts);
10968
- assert.equal(terminal.status, "failed");
10969
- if (terminal.status !== "failed") return;
10970
- assert.isNotEmpty(terminal.failure.message);
10971
- assert.equal(terminal.failure.class, "provider_error");
10972
- assert.isFalse(
10973
- harness.events.some(
10974
- (event) =>
10975
- event.type === "message.updated" &&
10976
- event.message.text === "Provider failure details.",
10977
- ),
10978
- );
10979
- assert.equal(
10980
- terminal.failure.code,
10981
- terminalReason === "overloaded_status" ? "api_error_529" : terminalReason,
10982
- );
10983
- }).pipe(
10984
- Effect.provide(
10985
- Layer.mergeAll(
10986
- IdAllocator.layer,
10987
- McpProviderSessions.layer,
10988
- NodeServices.layer,
10989
- NodeCrypto.layer,
10990
- ),
10991
- ),
10992
- ),
10993
- ),
10933
);
10934
10935
// Context exhaustion reports blocking_limit even when the rate-limit window is allowed.
@@ -11076,402 +11015,108 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11015
it.effect(
11016
"uses task_started as an incremental roster fallback, keeps its tool call, and clears internal work on empty snapshot",
11017
() =>
11079
- Effect.scoped(
11080
- Effect.gen(function* () {
11081
- const harness = yield* makeWakeHarness;
11082
- const now = yield* DateTime.now;
11083
- const emptyRoster = claudeSdkFrame({
11084
- type: "system",
11085
- subtype: "background_tasks_changed",
11086
- tasks: [],
11087
- uuid: "00000000-0000-4000-8000-000000000202",
11088
- session_id: WAKE_NATIVE_SESSION,
11089
- });
11018
+ Effect.gen(function* () {
11019
+ const harness = yield* makeWakeHarness;
11020
+ const now = yield* DateTime.now;
11021
+ const emptyRoster = claudeSdkFrame({
11022
+ type: "system",
11023
+ subtype: "background_tasks_changed",
11024
+ tasks: [],
11025
+ uuid: "00000000-0000-4000-8000-000000000202",
11026
+ session_id: WAKE_NATIVE_SESSION,
11027
+ });
11028
11091
- yield* harness.runtime.startTurn(
11092
- makeClaudeTestTurnInput({
11093
- threadId: harness.threadId,
11094
- providerThread: harness.providerThread,
11095
- now,
11096
- attemptId: RunAttemptId.make("attempt-claude-roster-fallback"),
11097
- text: "Run the build in the background.",
11098
- attachments: [],
11099
- }),
11100
- );
11101
- yield* Queue.offer(
11102
- harness.sdkMessages,
11103
- claudeSdkFrame({
11104
- type: "assistant",
11105
- message: {
11106
- model: "claude-sonnet-4-6",
11107
- id: "msg_background_command",
11108
- type: "message",
11109
- role: "assistant",
11110
- content: [
11111
- {
11112
- type: "tool_use",
11113
- id: WAKE_TOOL_USE_ID,
11114
- name: "Bash",
11115
- input: {
11116
- command: "python3 audit.py > audit.log 2>&1",
11117
- run_in_background: true,
11118
- },
11029
+ yield* harness.runtime.startTurn(
11030
+ makeClaudeTestTurnInput({
11031
+ threadId: harness.threadId,
11032
+ providerThread: harness.providerThread,
11033
+ now,
11034
+ attemptId: RunAttemptId.make("attempt-claude-roster-fallback"),
11035
+ text: "Run the build in the background.",
11036
+ attachments: [],
11037
+ }),
11038
+ );
11039
+ yield* Queue.offer(
11040
+ harness.sdkMessages,
11041
+ claudeSdkFrame({
11042
+ type: "assistant",
11043
+ message: {
11044
+ model: "claude-sonnet-4-6",
11045
+ id: "msg_background_command",
11046
+ type: "message",
11047
+ role: "assistant",
11048
+ content: [
11049
+ {
11050
+ type: "tool_use",
11051
+ id: WAKE_TOOL_USE_ID,
11052
+ name: "Bash",
11053
+ input: {
11054
+ command: "python3 audit.py > audit.log 2>&1",
11055
+ run_in_background: true,
11056
},
11120
- ],
11121
- },
11122
- parent_tool_use_id: null,
11123
- uuid: "background-command-launch",
11124
- session_id: WAKE_NATIVE_SESSION,
11125
- }),
11126
- );
11127
- yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
11128
- yield* Queue.offer(harness.sdkMessages, turnOneResult);
11129
- yield* harness.awaitTerminal(1);
11057
+ },
11058
+ ],
11059
+ },
11060
+ parent_tool_use_id: null,
11061
+ uuid: "background-command-launch",
11062
+ session_id: WAKE_NATIVE_SESSION,
11063
+ }),
11064
+ );
11065
+ yield* Queue.offer(harness.sdkMessages, wakeTaskStarted);
11066
+ yield* Queue.offer(harness.sdkMessages, turnOneResult);
11067
+ yield* harness.awaitTerminal(1);
11068
11131
- const afterStart = providerThreadRosterEvents(harness.events).filter(
11132
- (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
11133
- );
11134
- assert.isAtLeast(afterStart.length, 1);
11135
- const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0];
11136
- assert.equal(started?.taskId, WAKE_TASK_ID);
11137
- assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID);
11069
+ const afterStart = providerThreadRosterEvents(harness.events).filter(
11070
+ (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
11071
+ );
11072
+ assert.isAtLeast(afterStart.length, 1);
11073
+ const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0];
11074
+ assert.equal(started?.taskId, WAKE_TASK_ID);
11075
+ assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID);
11076
11139
- const command = harness.events.find(
11140
- (event) =>
11141
- event.type === "turn_item.updated" &&
11142
- event.turnItem.type === "command_execution" &&
11143
- event.turnItem.nativeItemRef?.nativeId === WAKE_TOOL_USE_ID,
11144
- );
11145
- assert.equal(command?.type, "turn_item.updated");
11146
- if (command?.type !== "turn_item.updated") return;
11147
- const details = {
11148
- command: "python3 audit.py > audit.log 2>&1",
11149
- itemId: command.turnItem.id,
11150
- };
11151
- assert.deepInclude(
11152
- afterStart.at(-1)?.providerThread.pendingBackgroundTasks?.[0],
11153
- details,
11154
- );
11155
- yield* harness.offerAndWait(
11156
- claudeSdkFrame({
11157
- type: "system",
11158
- subtype: "background_tasks_changed",
11159
- tasks: [{ task_id: WAKE_TASK_ID, task_type: "local_bash", description: "Audit" }],
11160
- uuid: "background-command-snapshot",
11161
- session_id: WAKE_NATIVE_SESSION,
11162
- }),
11163
- );
11164
- assert.deepInclude(
11165
- providerThreadRosterEvents(harness.events).at(-1)?.providerThread
11166
- .pendingBackgroundTasks?.[0],
11167
- details,
11168
- );
11077
+ const command = harness.events.find(
11078
+ (event) =>
11079
+ event.type === "turn_item.updated" &&
11080
+ event.turnItem.type === "command_execution" &&
11081
+ event.turnItem.nativeItemRef?.nativeId === WAKE_TOOL_USE_ID,
11082
+ );
11083
+ assert.equal(command?.type, "turn_item.updated");
11084
+ if (command?.type !== "turn_item.updated") return;
11085
+ const details = {
11086
+ command: "python3 audit.py > audit.log 2>&1",
11087
+ itemId: command.turnItem.id,
11088
+ };
11089
+ assert.deepInclude(afterStart.at(-1)?.providerThread.pendingBackgroundTasks?.[0], details);
11090
+ yield* harness.offerAndWait(
11091
+ claudeSdkFrame({
11092
+ type: "system",
11093
+ subtype: "background_tasks_changed",
11094
+ tasks: [{ task_id: WAKE_TASK_ID, task_type: "local_bash", description: "Audit" }],
11095
+ uuid: "background-command-snapshot",
11096
+ session_id: WAKE_NATIVE_SESSION,
11097
+ }),
11098
+ );
11099
+ assert.deepInclude(
11100
+ providerThreadRosterEvents(harness.events).at(-1)?.providerThread
11101
+ .pendingBackgroundTasks?.[0],
11102
+ details,
11103
+ );
11104
11170
- // A foreground command that later moves to the background keeps its tool call too.
11171
- yield* Queue.offer(
11172
- harness.sdkMessages,
11173
- claudeSdkFrame({
11174
- type: "system",
11175
- subtype: "task_started",
11176
- task_id: "moved-shell",
11177
- tool_use_id: "toolu_moved_shell",
11178
- description: "Foreground build",
11179
- is_backgrounded: false,
11180
- task_type: "local_bash",
11181
- uuid: "00000000-0000-4000-8000-000000000204",
11182
- session_id: WAKE_NATIVE_SESSION,
11183
- }),
11184
- );
11185
- yield* Queue.offer(
11186
- harness.sdkMessages,
11187
- claudeSdkFrame({
11188
- type: "system",
11189
- subtype: "background_tasks_changed",
11190
- tasks: [
11191
- {
11192
- task_id: "subagent-shell",
11193
- task_type: "local_bash",
11194
- description: "sleep 150",
11195
- parent_task_id: "agent-1",
11196
- },
11197
- {
11198
- task_id: WAKE_TASK_ID,
11199
- task_type: "local_bash",
11200
- description: WAKE_TASK_DESCRIPTION,
11201
- },
11202
- {
11203
- task_id: "moved-shell",
11204
- task_type: "local_bash",
11205
- description: "Foreground build",
11206
- },
11207
- ],
11208
- uuid: "00000000-0000-4000-8000-000000000203",
11209
- session_id: WAKE_NATIVE_SESSION,
11210
- }),
11211
- );
11212
- yield* harness.until(() =>
11213
- providerThreadRosterEvents(harness.events).some(
11214
- (event) =>
11215
- event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1" &&
11216
- event.providerThread.pendingBackgroundTasks[1]?.nativeItemId === WAKE_TOOL_USE_ID &&
11217
- event.providerThread.pendingBackgroundTasks[2]?.nativeItemId ===
11218
- "toolu_moved_shell",
11219
- ),
11220
- );
11221
-
11222
- yield* harness.offerAndWait(emptyRoster);
11223
- assert.include(
11224
- (
11225
- providerThreadRosterEvents(harness.events).at(-1)?.providerThread
11226
- .pendingBackgroundTasks ?? []
11227
- ).map((task) => task.taskId),
11228
- WAKE_TASK_ID,
11229
- );
11230
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
11231
- }).pipe(
11232
- Effect.provide(
11233
- Layer.mergeAll(
11234
- IdAllocator.layer,
11235
- McpProviderSessions.layer,
11236
- NodeServices.layer,
11237
- NodeCrypto.layer,
11238
- ),
11239
- ),
11240
- ),
11241
- ),
11242
- );
11243
-
11244
- it.effect("holds only the background tasks the agent marks awaited, until they end", () =>
11245
- Effect.scoped(
11246
- Effect.gen(function* () {
11247
- const harness = yield* makeWakeHarness;
11248
- const now = yield* DateTime.now;
11249
- const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks;
11250
- if (awaitBackgroundTasks === undefined) {
11251
- throw new Error("Claude adapter runtime must expose awaitBackgroundTasks.");
11252
- }
11253
- const roster = (tasks: ReadonlyArray<string>, uuid: string) =>
11105
+ // A foreground command that later moves to the background keeps its tool call too.
11106
+ yield* Queue.offer(
11107
+ harness.sdkMessages,
11108
claudeSdkFrame({
11109
type: "system",
11256
- subtype: "background_tasks_changed",
11257
- tasks: tasks.map((taskId) => ({
11258
- task_id: taskId,
11259
- task_type: "local_bash",
11260
- description: taskId,
11261
- })),
11262
- uuid,
11110
+ subtype: "task_started",
11111
+ task_id: "moved-shell",
11112
+ tool_use_id: "toolu_moved_shell",
11113
+ description: "Foreground build",
11114
+ is_backgrounded: false,
11115
+ task_type: "local_bash",
11116
+ uuid: "00000000-0000-4000-8000-000000000204",
11117
session_id: WAKE_NATIVE_SESSION,
11264
- });
11265
- const nextRoster = Effect.fn("nextRoster")(function* (
11266
- matches: (tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>) => boolean,
11267
- ) {
11268
- while (true) {
11269
- const { providerThread } = yield* Queue.take(harness.providerThreadReceipts);
11270
- const tasks = providerThread.pendingBackgroundTasks ?? [];
11271
- if (matches(tasks)) return tasks;
11272
- }
11273
- });
11274
- const marks = (tasks: ReadonlyArray<OrchestrationV2PendingBackgroundTask>) =>
11275
- tasks.map((task) => [task.taskId, task.awaited === true]);
11276
-
11277
- yield* harness.runtime.startTurn(
11278
- makeClaudeTestTurnInput({
11279
- threadId: harness.threadId,
11280
- providerThread: harness.providerThread,
11281
- now,
11282
- attemptId: RunAttemptId.make("attempt-claude-awaited-roster"),
11283
- text: "Run the tests in the background and the dev server.",
11284
- attachments: [],
11285
- }),
11286
- );
11287
- yield* Queue.offer(
11288
- harness.sdkMessages,
11289
- roster([WAKE_TASK_ID, "dev-server"], "00000000-0000-4000-8000-000000000301"),
11290
- );
11291
- yield* nextRoster((tasks) => tasks.length === 2);
11292
-
11293
- const marked = yield* awaitBackgroundTasks({
11294
- providerThread: harness.providerThread,
11295
- taskIds: [WAKE_TASK_ID, "already-finished"],
11296
- awaited: true,
11297
- });
11298
- assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]);
11299
- assert.deepStrictEqual(
11300
- marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))),
11301
- [
11302
- [WAKE_TASK_ID, true],
11303
- ["dev-server", false],
11304
- ],
11305
- );
11306
- // A replacing level rebuilds every entry; the mark must survive it.
11307
- yield* Queue.offer(
11308
- harness.sdkMessages,
11309
- roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000302"),
11310
- );
11311
- assert.deepStrictEqual(
11312
- marks(yield* nextRoster((tasks) => tasks[0]?.taskId === "dev-server")),
11313
- [
11314
- ["dev-server", false],
11315
- [WAKE_TASK_ID, true],
11316
- ],
11317
- );
11318
-
11319
- // Once the task ends, a reused id starts unmarked.
11320
- yield* Queue.offer(
11321
- harness.sdkMessages,
11322
- claudeSdkFrame({ ...wakeNotification, uuid: "00000000-0000-4000-8000-000000000303" }),
11323
- );
11324
- yield* nextRoster((tasks) => tasks.length === 1);
11325
- yield* Queue.offer(
11326
- harness.sdkMessages,
11327
- roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"),
11328
- );
11329
- assert.deepStrictEqual(marks(yield* nextRoster((tasks) => tasks.length === 2)), [
11330
- ["dev-server", false],
11331
- [WAKE_TASK_ID, false],
11332
- ]);
11333
-
11334
- yield* awaitBackgroundTasks({
11335
- providerThread: harness.providerThread,
11336
- taskIds: ["dev-server"],
11337
- awaited: true,
11338
- });
11339
- assert.deepStrictEqual(
11340
- marks(yield* nextRoster((tasks) => tasks.some((task) => task.awaited === true))),
11341
- [
11342
- ["dev-server", true],
11343
- [WAKE_TASK_ID, false],
11344
- ],
11345
- );
11346
- const released = yield* awaitBackgroundTasks({
11347
- providerThread: harness.providerThread,
11348
- taskIds: ["dev-server"],
11349
- awaited: false,
11350
- });
11351
- assert.deepStrictEqual(released.matched, ["dev-server"]);
11352
- assert.deepStrictEqual(
11353
- marks(yield* nextRoster((tasks) => !tasks.some((task) => task.awaited === true))),
11354
- [
11355
- ["dev-server", false],
11356
- [WAKE_TASK_ID, false],
11357
- ],
11358
- );
11359
- yield* Queue.offer(harness.sdkMessages, turnOneResult);
11360
- yield* Queue.take(harness.terminalReceipts);
11361
- }).pipe(
11362
- Effect.provide(
11363
- Layer.mergeAll(
11364
- IdAllocator.layer,
11365
- McpProviderSessions.layer,
11366
- NodeServices.layer,
11367
- NodeCrypto.layer,
11368
- ),
11369
- ),
11370
- ),
11371
- ),
11372
- );
11373
-
11374
- it.effect("keeps a running Claude monitor typed after many newer monitors end", () =>
11375
- Effect.scoped(
11376
- Effect.gen(function* () {
11377
- const harness = yield* makeWakeHarness;
11378
- const now = yield* DateTime.now;
11379
- let frameNumber = 0;
11380
- const nextUuid = () => `00000000-0000-4000-8000-${String(++frameNumber).padStart(12, "0")}`;
11381
- const monitorFrames = (index: number) => {
11382
- const taskId = `monitor-task-${index}`;
11383
- const toolUseId = `toolu_monitor_${index}`;
11384
- const description = `Monitor ${index}`;
11385
- return {
11386
- taskId,
11387
- start: [
11388
- claudeSdkFrame({
11389
- type: "assistant",
11390
- message: {
11391
- model: "claude-sonnet-4-6",
11392
- id: `msg_monitor_${index}`,
11393
- type: "message",
11394
- role: "assistant",
11395
- content: [
11396
- {
11397
- type: "tool_use",
11398
- id: toolUseId,
11399
- name: "Monitor",
11400
- input: { description, command: "sleep 8 && echo MONITOR_DONE" },
11401
- },
11402
- ],
11403
- stop_reason: null,
11404
- stop_sequence: null,
11405
- usage: { input_tokens: 1, output_tokens: 1 },
11406
- },
11407
- parent_tool_use_id: null,
11408
- uuid: nextUuid(),
11409
- session_id: WAKE_NATIVE_SESSION,
11410
- }),
11411
- claudeSdkFrame({
11412
- type: "system",
11413
- subtype: "task_started",
11414
- task_id: taskId,
11415
- tool_use_id: toolUseId,
11416
- description,
11417
- is_backgrounded: true,
11418
- task_type: "local_bash",
11419
- uuid: nextUuid(),
11420
- session_id: WAKE_NATIVE_SESSION,
11421
- }),
11422
- claudeSdkFrame({
11423
- type: "user",
11424
- message: {
11425
- role: "user",
11426
- content: [
11427
- {
11428
- type: "tool_result",
11429
- tool_use_id: toolUseId,
11430
- content: `Monitor started (task ${taskId}).`,
11431
- },
11432
- ],
11433
- },
11434
- parent_tool_use_id: null,
11435
- uuid: nextUuid(),
11436
- session_id: WAKE_NATIVE_SESSION,
11437
- tool_use_result: { taskId, persistent: false },
11438
- }),
11439
- ],
11440
- end: claudeSdkFrame({
11441
- type: "system",
11442
- subtype: "task_notification",
11443
- task_id: taskId,
11444
- tool_use_id: toolUseId,
11445
- status: "completed",
11446
- output_file: `/tmp/claude-replay/tasks/${taskId}.output`,
11447
- summary: `Monitor "${description}" stream ended`,
11448
- uuid: nextUuid(),
11449
- session_id: WAKE_NATIVE_SESSION,
11450
- }),
11451
- };
11452
- };
11453
-
11454
- yield* harness.runtime.startTurn(
11455
- makeClaudeTestTurnInput({
11456
- threadId: harness.threadId,
11457
- providerThread: harness.providerThread,
11458
- now,
11459
- attemptId: RunAttemptId.make("attempt-claude-many-monitors"),
11460
- text: "Watch the deploy, then re-arm short watches.",
11461
- attachments: [],
11118
}),
11119
);
11464
- const longRunning = monitorFrames(0);
11465
- for (const frame of longRunning.start) {
11466
- yield* Queue.offer(harness.sdkMessages, frame);
11467
- }
11468
- for (let index = 1; index <= 65; index++) {
11469
- const monitor = monitorFrames(index);
11470
- for (const frame of monitor.start) {
11471
- yield* Queue.offer(harness.sdkMessages, frame);
11472
- }
11473
- yield* Queue.offer(harness.sdkMessages, monitor.end);
11474
- }
11120
yield* Queue.offer(
11121
harness.sdkMessages,
11122
claudeSdkFrame({
@@ -11479,31 +11124,44 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11124
subtype: "background_tasks_changed",
11125
tasks: [
11126
{
11482
- task_id: longRunning.taskId,
11127
+ task_id: "subagent-shell",
11128
+ task_type: "local_bash",
11129
+ description: "sleep 150",
11130
+ parent_task_id: "agent-1",
11131
+ },
11132
+ {
11133
+ task_id: WAKE_TASK_ID,
11134
task_type: "local_bash",
11484
- description: "Monitor 0",
11135
+ description: WAKE_TASK_DESCRIPTION,
11136
+ },
11137
+ {
11138
+ task_id: "moved-shell",
11139
+ task_type: "local_bash",
11140
+ description: "Foreground build",
11141
},
11142
],
11487
- uuid: nextUuid(),
11143
+ uuid: "00000000-0000-4000-8000-000000000203",
11144
session_id: WAKE_NATIVE_SESSION,
11145
}),
11146
);
11491
- yield* Queue.offer(
11492
- harness.sdkMessages,
11493
- makeResultFrame({ uuid: nextUuid(), result: "Watching." }),
11147
+ yield* harness.until(() =>
11148
+ providerThreadRosterEvents(harness.events).some(
11149
+ (event) =>
11150
+ event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1" &&
11151
+ event.providerThread.pendingBackgroundTasks[1]?.nativeItemId === WAKE_TOOL_USE_ID &&
11152
+ event.providerThread.pendingBackgroundTasks[2]?.nativeItemId === "toolu_moved_shell",
11153
+ ),
11154
);
11495
- yield* harness.awaitTerminal(1);
11155
11497
- const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread
11498
- .pendingBackgroundTasks;
11499
- assert.deepEqual(roster, [
11500
- {
11501
- taskId: longRunning.taskId,
11502
- kind: "monitor",
11503
- description: "Monitor 0",
11504
- nativeItemId: "toolu_monitor_0",
11505
- },
11506
- ]);
11156
+ yield* harness.offerAndWait(emptyRoster);
11157
+ assert.include(
11158
+ (
11159
+ providerThreadRosterEvents(harness.events).at(-1)?.providerThread
11160
+ .pendingBackgroundTasks ?? []
11161
+ ).map((task) => task.taskId),
11162
+ WAKE_TASK_ID,
11163
+ );
11164
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
11165
}).pipe(
11166
Effect.provide(
11167
Layer.mergeAll(
@@ -11514,51 +11172,322 @@ describe("ClaudeAdapterV2 background wake turns", () => {
11172
),
11173
),
11174
),
11517
- ),
11175
);
11176
11520
- const scheduleWakeupFrames = (input: {
11521
- readonly toolUseId: string;
11522
- readonly uuids: readonly [string, string];
11523
- readonly toolInput: Record<string, unknown>;
11524
- readonly scheduledFor: number;
11525
- }) => [
11526
- claudeSdkFrame({
11527
- type: "assistant",
11528
- message: {
11529
- model: "claude-sonnet-4-6",
11530
- id: `msg_${input.toolUseId}`,
11531
- type: "message",
11532
- role: "assistant",
11533
- content: [
11534
- { type: "tool_use", id: input.toolUseId, name: "ScheduleWakeup", input: input.toolInput },
11535
- ],
11536
- stop_reason: null,
11537
- stop_sequence: null,
11538
- usage: { input_tokens: 1, output_tokens: 1 },
11539
- },
11540
- parent_tool_use_id: null,
11541
- uuid: input.uuids[0],
11542
- session_id: WAKE_NATIVE_SESSION,
11543
- }),
11544
- claudeSdkFrame({
11545
- type: "user",
11546
- message: {
This file is too large to show in full.
apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts
+282
-298
@@ -232,70 +232,68 @@ const resumedMcpQueryInput = {
232
} satisfies ClaudeAgentSdkQueryOpenInput;
233
234
it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () =>
235
- Effect.scoped(
236
- Effect.gen(function* () {
237
- const registrationStarted = Promise.withResolvers<void>();
238
- const disposalStarted = Promise.withResolvers<void>();
239
- const finishDisposal = Promise.withResolvers<void>();
240
- const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = [];
241
- const firstClose = vi.fn();
242
- const secondClose = vi.fn();
243
- const firstRegistration = vi.fn(() => {
244
- registrationStarted.resolve();
245
- return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
246
- });
247
- const secondRegistration = vi.fn(async () => ({
248
- added: ["t3-code"],
249
- removed: [],
250
- errors: {},
251
- }));
252
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => {
253
- assert.notTypeOf(prompt, "string");
254
- if (typeof prompt === "string") throw new Error("Expected streaming input");
255
- prompts.push(prompt);
256
- return {
257
- initializationResult: async () => ({}),
258
- setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
259
- close: prompts.length === 1 ? firstClose : secondClose,
260
- [Symbol.asyncDispose]: async () => {
261
- firstClose();
262
- disposalStarted.resolve();
263
- await finishDisposal.promise;
264
- },
265
- } as unknown as ClaudeSdk.Query;
266
- });
267
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
268
- const runner = yield* ClaudeAgentSdkQueryRunner;
269
- const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
270
- yield* Effect.promise(() => registrationStarted.promise);
271
- yield* TestClock.adjust("90 seconds");
272
- yield* Effect.promise(() => disposalStarted.promise);
273
- assert.equal(querySpy.mock.calls.length, 1);
274
- finishDisposal.resolve();
275
- const session = yield* Fiber.join(opening);
276
- yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
277
-
278
- assert.equal(firstClose.mock.calls.length, 1);
279
- assert.equal(secondClose.mock.calls.length, 0);
280
- assert.equal(querySpy.mock.calls.length, 2);
281
- for (const [call] of querySpy.mock.calls) {
282
- assert.equal(call.options?.resume, FORK_SESSION_ID);
283
- assert.isUndefined(call.options?.mcpServers);
284
- }
285
- assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]);
286
- const message = {
287
- type: "user",
288
- message: { role: "user", content: "Continue where you left off." },
289
- parent_tool_use_id: null,
290
- session_id: FORK_SESSION_ID,
291
- } satisfies ClaudeSdk.SDKUserMessage;
292
- yield* session.offer(message);
293
- assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done);
294
- const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next());
295
- assert.deepEqual(delivered.value, message);
296
- assert.isFalse(delivered.done);
297
- }).pipe(Effect.provide(realQueryRunner)),
298
- ),
235
+ Effect.gen(function* () {
236
+ const registrationStarted = Promise.withResolvers<void>();
237
+ const disposalStarted = Promise.withResolvers<void>();
238
+ const finishDisposal = Promise.withResolvers<void>();
239
+ const prompts: AsyncIterable<ClaudeSdk.SDKUserMessage>[] = [];
240
+ const firstClose = vi.fn();
241
+ const secondClose = vi.fn();
242
+ const firstRegistration = vi.fn(() => {
243
+ registrationStarted.resolve();
244
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
245
+ });
246
+ const secondRegistration = vi.fn(async () => ({
247
+ added: ["t3-code"],
248
+ removed: [],
249
+ errors: {},
250
+ }));
251
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ prompt }) => {
252
+ assert.notTypeOf(prompt, "string");
253
+ if (typeof prompt === "string") throw new Error("Expected streaming input");
254
+ prompts.push(prompt);
255
+ return {
256
+ initializationResult: async () => ({}),
257
+ setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration,
258
+ close: prompts.length === 1 ? firstClose : secondClose,
259
+ [Symbol.asyncDispose]: async () => {
260
+ firstClose();
261
+ disposalStarted.resolve();
262
+ await finishDisposal.promise;
263
+ },
264
+ } as unknown as ClaudeSdk.Query;
265
+ });
266
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
267
+ const runner = yield* ClaudeAgentSdkQueryRunner;
268
+ const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
269
+ yield* Effect.promise(() => registrationStarted.promise);
270
+ yield* TestClock.adjust("90 seconds");
271
+ yield* Effect.promise(() => disposalStarted.promise);
272
+ assert.equal(querySpy.mock.calls.length, 1);
273
+ finishDisposal.resolve();
274
+ const session = yield* Fiber.join(opening);
275
+ yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
276
+
277
+ assert.equal(firstClose.mock.calls.length, 1);
278
+ assert.equal(secondClose.mock.calls.length, 0);
279
+ assert.equal(querySpy.mock.calls.length, 2);
280
+ for (const [call] of querySpy.mock.calls) {
281
+ assert.equal(call.options?.resume, FORK_SESSION_ID);
282
+ assert.isUndefined(call.options?.mcpServers);
283
+ }
284
+ assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]);
285
+ const message = {
286
+ type: "user",
287
+ message: { role: "user", content: "Continue where you left off." },
288
+ parent_tool_use_id: null,
289
+ session_id: FORK_SESSION_ID,
290
+ } satisfies ClaudeSdk.SDKUserMessage;
291
+ yield* session.offer(message);
292
+ assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done);
293
+ const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next());
294
+ assert.deepEqual(delivered.value, message);
295
+ assert.isFalse(delivered.done);
296
+ }).pipe(Effect.provide(realQueryRunner)),
297
);
298
299
it.effect.each([
@@ -303,262 +301,248 @@ it.effect.each([
301
{ case: "a settings file Claude skipped", errors: [{ file: "settings.json" }], readable: false },
302
{ case: "a reply without a rule list", response: {}, readable: false },
303
])("reads Claude's permission rules only when no settings file was skipped: $case", (testCase) =>
306
- Effect.scoped(
307
- Effect.gen(function* () {
308
- const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }];
309
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
310
- () =>
311
- ({
312
- close: vi.fn(),
313
- request: async () => ({
314
- response:
315
- "response" in testCase
316
- ? testCase.response
317
- : { state: { rules, errors: testCase.errors } },
318
- }),
319
- }) as unknown as ClaudeSdk.Query,
320
- );
321
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
322
- const runner = yield* ClaudeAgentSdkQueryRunner;
323
- const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options;
324
- const session = yield* runner.open({ ...resumedMcpQueryInput, options });
325
- yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
326
- const exit = yield* Effect.exit(session.listPermissionRules);
327
- if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules));
328
- else assert.isTrue(Exit.isFailure(exit));
329
- }).pipe(Effect.provide(realQueryRunner)),
330
- ),
304
+ Effect.gen(function* () {
305
+ const rules = [{ behavior: "deny" as const, rule: "mcp__probe__redeploy" }];
306
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
307
+ () =>
308
+ ({
309
+ close: vi.fn(),
310
+ request: async () => ({
311
+ response:
312
+ "response" in testCase
313
+ ? testCase.response
314
+ : { state: { rules, errors: testCase.errors } },
315
+ }),
316
+ }) as unknown as ClaudeSdk.Query,
317
+ );
318
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
319
+ const runner = yield* ClaudeAgentSdkQueryRunner;
320
+ const { mcpServers: _mcpServers, ...options } = resumedMcpQueryInput.options;
321
+ const session = yield* runner.open({ ...resumedMcpQueryInput, options });
322
+ yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie));
323
+ const exit = yield* Effect.exit(session.listPermissionRules);
324
+ if (testCase.readable) assert.deepEqual(exit, Exit.succeed(rules));
325
+ else assert.isTrue(Exit.isFailure(exit));
326
+ }).pipe(Effect.provide(realQueryRunner)),
327
);
328
329
it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) =>
334
- Effect.scoped(
335
- Effect.gen(function* () {
336
- const registrationStarted = Promise.withResolvers<void>();
337
- const cleanupProgress = Promise.withResolvers<"kill" | "retry">();
338
- const events = new NodeEvents.EventEmitter();
339
- const stdin = new NodeStream.PassThrough();
340
- const stdout = new NodeStream.PassThrough();
341
- const child = {
342
- stdin,
343
- stdout,
344
- killed: false,
345
- exitCode: null,
346
- kill: vi.fn(() => {
347
- cleanupProgress.resolve("kill");
348
- return true;
349
- }),
350
- on: events.on.bind(events),
351
- once: events.once.bind(events),
352
- off: events.off.bind(events),
353
- } satisfies ClaudeSdk.SpawnedProcess;
354
- const signal = yield* Effect.abortSignal;
355
- const disposed = vi.fn(async () => {});
356
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
357
- const first = querySpy.mock.calls.length === 1;
358
- if (first) {
359
- options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
360
- } else {
361
- cleanupProgress.resolve("retry");
362
- }
363
- return {
330
+ Effect.gen(function* () {
331
+ const registrationStarted = Promise.withResolvers<void>();
332
+ const cleanupProgress = Promise.withResolvers<"kill" | "retry">();
333
+ const events = new NodeEvents.EventEmitter();
334
+ const stdin = new NodeStream.PassThrough();
335
+ const stdout = new NodeStream.PassThrough();
336
+ const child = {
337
+ stdin,
338
+ stdout,
339
+ killed: false,
340
+ exitCode: null,
341
+ kill: vi.fn(() => {
342
+ cleanupProgress.resolve("kill");
343
+ return true;
344
+ }),
345
+ on: events.on.bind(events),
346
+ once: events.once.bind(events),
347
+ off: events.off.bind(events),
348
+ } satisfies ClaudeSdk.SpawnedProcess;
349
+ const signal = yield* Effect.abortSignal;
350
+ const disposed = vi.fn(async () => {});
351
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => {
352
+ const first = querySpy.mock.calls.length === 1;
353
+ if (first) {
354
+ options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal });
355
+ } else {
356
+ cleanupProgress.resolve("retry");
357
+ }
358
+ return {
359
+ initializationResult: async () => ({}),
360
+ setMcpServers: () => {
361
+ registrationStarted.resolve();
362
+ return first
363
+ ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
364
+ : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
365
+ },
366
+ close: vi.fn(),
367
+ [Symbol.asyncDispose]: disposed,
368
+ } as unknown as ClaudeSdk.Query;
369
+ });
370
+ yield* Effect.addFinalizer(() =>
371
+ Effect.sync(() => {
372
+ querySpy.mockRestore();
373
+ stdin.destroy();
374
+ stdout.destroy();
375
+ }),
376
+ );
377
+ const runner = yield* ClaudeAgentSdkQueryRunner;
378
+ const opening = yield* runner
379
+ .open({
380
+ ...resumedMcpQueryInput,
381
+ options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child },
382
+ })
383
+ .pipe(Effect.exit, Effect.forkChild);
384
+ yield* Effect.promise(() => registrationStarted.promise);
385
+ yield* TestClock.adjust("90 seconds");
386
+
387
+ assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
388
+ assert.equal(querySpy.mock.calls.length, 1);
389
+ assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]);
390
+ if (exits) events.emit("exit", null, "SIGKILL");
391
+ else yield* TestClock.adjust("10 seconds");
392
+ const result = yield* Fiber.join(opening);
393
+ assert.equal(Exit.isSuccess(result), exits);
394
+ if (Exit.isSuccess(result)) yield* result.value.close;
395
+ assert.equal(querySpy.mock.calls.length, exits ? 2 : 1);
396
+ assert.equal(disposed.mock.calls.length, 1);
397
+ }).pipe(Effect.provide(realQueryRunner)),
398
+);
399
+
400
+it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
401
+ Effect.gen(function* () {
402
+ const firstRegistration = Promise.withResolvers<void>();
403
+ const secondRegistration = Promise.withResolvers<void>();
404
+ const disposed = vi.fn(async () => {});
405
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
406
+ const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
407
+ return {
408
+ initializationResult: async () => ({}),
409
+ setMcpServers: () => {
410
+ started.resolve();
411
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
412
+ },
413
+ [Symbol.asyncDispose]: disposed,
414
+ } as unknown as ClaudeSdk.Query;
415
+ });
416
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
417
+ const runner = yield* ClaudeAgentSdkQueryRunner;
418
+ const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.result, Effect.forkChild);
419
+ yield* Effect.promise(() => firstRegistration.promise);
420
+ yield* TestClock.adjust("90 seconds");
421
+ yield* Effect.promise(() => secondRegistration.promise);
422
+ yield* TestClock.adjust("90 seconds");
423
+ const result = yield* Fiber.join(opening);
424
+
425
+ assert.equal(result._tag, "Failure");
426
+ if (result._tag !== "Failure") return;
427
+ assert.equal(querySpy.mock.calls.length, 2);
428
+ assert.equal(disposed.mock.calls.length, 2);
429
+ assert.equal(
430
+ makeProviderFailure({
431
+ cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
432
+ }).message,
433
+ "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
434
+ );
435
+ }).pipe(Effect.provide(realQueryRunner)),
436
+);
437
+
438
+it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
439
+ Effect.gen(function* () {
440
+ const registrationStarted = Promise.withResolvers<void>();
441
+ const disposed = vi.fn(async () => {});
442
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
443
+ () =>
444
+ ({
445
initializationResult: async () => ({}),
446
setMcpServers: () => {
447
registrationStarted.resolve();
367
- return first
368
- ? new Promise<ClaudeSdk.McpSetServersResult>(() => {})
369
- : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} });
448
+ return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
449
},
371
- close: vi.fn(),
450
[Symbol.asyncDispose]: disposed,
373
- } as unknown as ClaudeSdk.Query;
374
- });
375
- yield* Effect.addFinalizer(() =>
376
- Effect.sync(() => {
377
- querySpy.mockRestore();
378
- stdin.destroy();
379
- stdout.destroy();
380
- }),
381
- );
382
- const runner = yield* ClaudeAgentSdkQueryRunner;
383
- const opening = yield* runner
384
- .open({
385
- ...resumedMcpQueryInput,
386
- options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child },
387
- })
388
- .pipe(Effect.exit, Effect.forkChild);
389
- yield* Effect.promise(() => registrationStarted.promise);
390
- yield* TestClock.adjust("90 seconds");
391
-
392
- assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill");
393
- assert.equal(querySpy.mock.calls.length, 1);
394
- assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]);
395
- if (exits) events.emit("exit", null, "SIGKILL");
396
- else yield* TestClock.adjust("10 seconds");
397
- const result = yield* Fiber.join(opening);
398
- assert.equal(Exit.isSuccess(result), exits);
399
- if (Exit.isSuccess(result)) yield* result.value.close;
400
- assert.equal(querySpy.mock.calls.length, exits ? 2 : 1);
401
- assert.equal(disposed.mock.calls.length, 1);
402
- }).pipe(Effect.provide(realQueryRunner)),
403
- ),
451
+ }) as unknown as ClaudeSdk.Query,
452
+ );
453
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
454
+ const runner = yield* ClaudeAgentSdkQueryRunner;
455
+ const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
456
+ yield* Effect.promise(() => registrationStarted.promise);
457
+ yield* Fiber.interrupt(opening);
458
+
459
+ assert.equal(querySpy.mock.calls.length, 1);
460
+ assert.equal(disposed.mock.calls.length, 1);
461
+ const prompt = querySpy.mock.calls[0]![0].prompt;
462
+ if (typeof prompt === "string") throw new Error("Expected streaming input");
463
+ assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done);
464
+ }).pipe(Effect.provide(realQueryRunner)),
465
);
466
406
-it.effect("stops retrying MCP registration after two timeouts and reports the cause", () =>
407
- Effect.scoped(
408
- Effect.gen(function* () {
409
- const firstRegistration = Promise.withResolvers<void>();
410
- const secondRegistration = Promise.withResolvers<void>();
411
- const disposed = vi.fn(async () => {});
412
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(() => {
413
- const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration;
414
- return {
467
+it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
468
+ Effect.gen(function* () {
469
+ const registrationStarted = Promise.withResolvers<void>();
470
+ const disposed = vi.fn(async () => {});
471
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
472
+ () =>
473
+ ({
474
initializationResult: async () => ({}),
475
setMcpServers: () => {
417
- started.resolve();
476
+ registrationStarted.resolve();
477
return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
478
},
479
[Symbol.asyncDispose]: disposed,
421
- } as unknown as ClaudeSdk.Query;
422
- });
423
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
424
- const runner = yield* ClaudeAgentSdkQueryRunner;
425
- const opening = yield* runner
426
- .open(resumedMcpQueryInput)
427
- .pipe(Effect.result, Effect.forkChild);
428
- yield* Effect.promise(() => firstRegistration.promise);
429
- yield* TestClock.adjust("90 seconds");
430
- yield* Effect.promise(() => secondRegistration.promise);
431
- yield* TestClock.adjust("90 seconds");
432
- const result = yield* Fiber.join(opening);
433
-
434
- assert.equal(result._tag, "Failure");
435
- if (result._tag !== "Failure") return;
436
- assert.equal(querySpy.mock.calls.length, 2);
437
- assert.equal(disposed.mock.calls.length, 2);
438
- assert.equal(
439
- makeProviderFailure({
440
- cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
441
- }).message,
442
- "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.",
443
- );
444
- }).pipe(Effect.provide(realQueryRunner)),
445
- ),
446
-);
447
-
448
-it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () =>
449
- Effect.scoped(
450
- Effect.gen(function* () {
451
- const registrationStarted = Promise.withResolvers<void>();
452
- const disposed = vi.fn(async () => {});
453
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
454
- () =>
455
- ({
456
- initializationResult: async () => ({}),
457
- setMcpServers: () => {
458
- registrationStarted.resolve();
459
- return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
460
- },
461
- [Symbol.asyncDispose]: disposed,
462
- }) as unknown as ClaudeSdk.Query,
463
- );
464
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
465
- const runner = yield* ClaudeAgentSdkQueryRunner;
466
- const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild);
467
- yield* Effect.promise(() => registrationStarted.promise);
468
- yield* Fiber.interrupt(opening);
469
-
470
- assert.equal(querySpy.mock.calls.length, 1);
471
- assert.equal(disposed.mock.calls.length, 1);
472
- const prompt = querySpy.mock.calls[0]![0].prompt;
473
- if (typeof prompt === "string") throw new Error("Expected streaming input");
474
- assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done);
475
- }).pipe(Effect.provide(realQueryRunner)),
476
- ),
477
-);
478
-
479
-it.effect("does not reuse a fresh session ID after MCP registration times out", () =>
480
- Effect.scoped(
481
- Effect.gen(function* () {
482
- const registrationStarted = Promise.withResolvers<void>();
483
- const disposed = vi.fn(async () => {});
484
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
485
- () =>
486
- ({
487
- initializationResult: async () => ({}),
488
- setMcpServers: () => {
489
- registrationStarted.resolve();
490
- return new Promise<ClaudeSdk.McpSetServersResult>(() => {});
491
- },
492
- [Symbol.asyncDispose]: disposed,
493
- }) as unknown as ClaudeSdk.Query,
494
- );
495
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
496
- const runner = yield* ClaudeAgentSdkQueryRunner;
497
- const { resume, ...options } = resumedMcpQueryInput.options;
498
- const opening = yield* runner
499
- .open({
500
- ...resumedMcpQueryInput,
501
- options: { ...options, sessionId: resume },
502
- })
503
- .pipe(Effect.result, Effect.forkChild);
504
- yield* Effect.promise(() => registrationStarted.promise);
505
- yield* TestClock.adjust("90 seconds");
506
- const result = yield* Fiber.join(opening);
507
-
508
- assert.equal(result._tag, "Failure");
509
- assert.equal(querySpy.mock.calls.length, 1);
510
- assert.equal(disposed.mock.calls.length, 1);
511
- }).pipe(Effect.provide(realQueryRunner)),
512
- ),
480
+ }) as unknown as ClaudeSdk.Query,
481
+ );
482
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
483
+ const runner = yield* ClaudeAgentSdkQueryRunner;
484
+ const { resume, ...options } = resumedMcpQueryInput.options;
485
+ const opening = yield* runner
486
+ .open({
487
+ ...resumedMcpQueryInput,
488
+ options: { ...options, sessionId: resume },
489
+ })
490
+ .pipe(Effect.result, Effect.forkChild);
491
+ yield* Effect.promise(() => registrationStarted.promise);
492
+ yield* TestClock.adjust("90 seconds");
493
+ const result = yield* Fiber.join(opening);
494
+
495
+ assert.equal(result._tag, "Failure");
496
+ assert.equal(querySpy.mock.calls.length, 1);
497
+ assert.equal(disposed.mock.calls.length, 1);
498
+ }).pipe(Effect.provide(realQueryRunner)),
499
);
500
501
it.effect.each([
502
["opens after a slow CLI boot", "120 seconds", true],
503
["times out a CLI that never boots", "5 minutes", false],
504
] as const)("%s", ([, bootWait, boots]) =>
519
- Effect.scoped(
520
- Effect.gen(function* () {
521
- const waiting = Promise.withResolvers<void>();
522
- const booted = Promise.withResolvers<void>();
523
- const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
524
- () =>
525
- ({
526
- initializationResult: () => {
527
- waiting.resolve();
528
- return booted.promise;
529
- },
530
- // The CLI answers control requests only after it has booted.
531
- setMcpServers: async () => {
532
- waiting.resolve();
533
- await booted.promise;
534
- return { added: ["t3-code"], removed: [], errors: {} };
535
- },
536
- close: vi.fn(),
537
- [Symbol.asyncDispose]: async () => {},
538
- }) as unknown as ClaudeSdk.Query,
505
+ Effect.gen(function* () {
506
+ const waiting = Promise.withResolvers<void>();
507
+ const booted = Promise.withResolvers<void>();
508
+ const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation(
509
+ () =>
510
+ ({
511
+ initializationResult: () => {
512
+ waiting.resolve();
513
+ return booted.promise;
514
+ },
515
+ // The CLI answers control requests only after it has booted.
516
+ setMcpServers: async () => {
517
+ waiting.resolve();
518
+ await booted.promise;
519
+ return { added: ["t3-code"], removed: [], errors: {} };
520
+ },
521
+ close: vi.fn(),
522
+ [Symbol.asyncDispose]: async () => {},
523
+ }) as unknown as ClaudeSdk.Query,
524
+ );
525
+ yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
526
+ const runner = yield* ClaudeAgentSdkQueryRunner;
527
+ const { resume, ...options } = resumedMcpQueryInput.options;
528
+ const opening = yield* runner
529
+ .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
530
+ .pipe(Effect.result, Effect.forkChild);
531
+ yield* Effect.promise(() => waiting.promise);
532
+ yield* TestClock.adjust(bootWait);
533
+ if (boots) booted.resolve();
534
+ const result = yield* Fiber.join(opening);
535
+
536
+ assert.equal(result._tag, boots ? "Success" : "Failure");
537
+ if (result._tag === "Success") yield* result.success.close;
538
+ else
539
+ assert.equal(
540
+ makeProviderFailure({
541
+ cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
542
+ }).message,
543
+ "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.",
544
);
540
- yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore()));
541
- const runner = yield* ClaudeAgentSdkQueryRunner;
542
- const { resume, ...options } = resumedMcpQueryInput.options;
543
- const opening = yield* runner
544
- .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume } })
545
- .pipe(Effect.result, Effect.forkChild);
546
- yield* Effect.promise(() => waiting.promise);
547
- yield* TestClock.adjust(bootWait);
548
- if (boots) booted.resolve();
549
- const result = yield* Fiber.join(opening);
550
-
551
- assert.equal(result._tag, boots ? "Success" : "Failure");
552
- if (result._tag === "Success") yield* result.success.close;
553
- else
554
- assert.equal(
555
- makeProviderFailure({
556
- cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure },
557
- }).message,
558
- "Claude timed out while starting up. Retry the turn; if it keeps failing, check Claude and the server logs.",
559
- );
560
- }).pipe(Effect.provide(realQueryRunner)),
561
- ),
545
+ }).pipe(Effect.provide(realQueryRunner)),
546
);
547
548
function fakeClaudeCli(script: string): string {
apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts
+24
-26
@@ -102,32 +102,30 @@ describe("tailClaudeTaskOutput", () => {
102
);
103
104
it.effect("reads what was written last when the tool result stops it", () =>
105
- Effect.scoped(
106
- Effect.gen(function* () {
107
- const fileSystem = yield* FileSystem.FileSystem;
108
- const { root, tasks, file } = yield* makeTaskFile;
109
- yield* fileSystem.makeDirectory(tasks, { recursive: true });
110
- yield* fileSystem.writeFileString(file, "one\n");
111
- const chunks: Array<string> = [];
112
- const stop = yield* Deferred.make<void>();
113
- const first = yield* Deferred.make<void>();
114
- const fiber = yield* tailClaudeTaskOutput({
115
- root,
116
- sessionId: SESSION_ID,
117
- taskId: TASK_ID,
118
- stop,
119
- onChunk: (chunk) =>
120
- Effect.sync(() => chunks.push(chunk)).pipe(
121
- Effect.andThen(Deferred.succeed(first, undefined)),
122
- ),
123
- }).pipe(Effect.forkScoped);
124
- yield* Deferred.await(first);
125
- yield* fileSystem.writeFileString(file, "one\ntwo\n");
126
- yield* Deferred.succeed(stop, undefined);
127
- yield* Fiber.join(fiber);
128
- assert.deepEqual(chunks, ["one\n", "two\n"]);
129
- }).pipe(Effect.provide(NodeServices.layer)),
130
- ),
105
+ Effect.gen(function* () {
106
+ const fileSystem = yield* FileSystem.FileSystem;
107
+ const { root, tasks, file } = yield* makeTaskFile;
108
+ yield* fileSystem.makeDirectory(tasks, { recursive: true });
109
+ yield* fileSystem.writeFileString(file, "one\n");
110
+ const chunks: Array<string> = [];
111
+ const stop = yield* Deferred.make<void>();
112
+ const first = yield* Deferred.make<void>();
113
+ const fiber = yield* tailClaudeTaskOutput({
114
+ root,
115
+ sessionId: SESSION_ID,
116
+ taskId: TASK_ID,
117
+ stop,
118
+ onChunk: (chunk) =>
119
+ Effect.sync(() => chunks.push(chunk)).pipe(
120
+ Effect.andThen(Deferred.succeed(first, undefined)),
121
+ ),
122
+ }).pipe(Effect.forkScoped);
123
+ yield* Deferred.await(first);
124
+ yield* fileSystem.writeFileString(file, "one\ntwo\n");
125
+ yield* Deferred.succeed(stop, undefined);
126
+ yield* Fiber.join(fiber);
127
+ assert.deepEqual(chunks, ["one\n", "two\n"]);
128
+ }).pipe(Effect.provide(NodeServices.layer)),
129
);
130
});
131
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+4212
-4309
@@ -1930,7 +1930,7 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1930
);
1931
}).pipe(Effect.provide(CodexReplay.layerReplayWithDriver(driver)));
1932
}
1933
- }).pipe(Effect.scoped),
1933
+ }),
1934
);
1935
1936
it.effect("waits for native start before interrupting an acknowledged queued turn", () =>
@@ -2251,55 +2251,351 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2251
);
2252
2253
it.effect("keeps an asynchronous Codex question actionable after the turn completes", () =>
2254
- Effect.scoped(
2255
- Effect.gen(function* () {
2256
- const nativeThreadId = "async-question-thread";
2257
- const nativeTurnId = "async-question-turn";
2258
- const usage = {
2259
- totalTokens: 15,
2254
+ Effect.gen(function* () {
2255
+ const nativeThreadId = "async-question-thread";
2256
+ const nativeTurnId = "async-question-turn";
2257
+ const usage = {
2258
+ totalTokens: 15,
2259
+ inputTokens: 10,
2260
+ cachedInputTokens: 2,
2261
+ outputTokens: 5,
2262
+ reasoningOutputTokens: 1,
2263
+ };
2264
+ const transcript = makeCodexReplayTranscript({
2265
+ scenario: "async-question-and-billed-usage",
2266
+ entries: [
2267
+ ...codexReplayPreamble({
2268
+ nativeThreadId,
2269
+ nativeTurnId,
2270
+ prompt: "Continue while I decide.",
2271
+ }),
2272
+ {
2273
+ type: "emit_inbound",
2274
+ label: "question",
2275
+ frame: {
2276
+ method: "item/completed",
2277
+ params: {
2278
+ threadId: nativeThreadId,
2279
+ turnId: nativeTurnId,
2280
+ item: {
2281
+ type: "agentMessage",
2282
+ id: "async-question-item",
2283
+ text: "Which branch?",
2284
+ delivery: "async",
2285
+ questions: [{ title: "Which branch?", options: ["main", "dev"] }],
2286
+ },
2287
+ },
2288
+ },
2289
+ },
2290
+ {
2291
+ type: "emit_inbound",
2292
+ label: "usage",
2293
+ frame: {
2294
+ method: "thread/tokenUsage/updated",
2295
+ params: {
2296
+ threadId: nativeThreadId,
2297
+ turnId: nativeTurnId,
2298
+ tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 },
2299
+ },
2300
+ },
2301
+ },
2302
+ {
2303
+ type: "emit_inbound",
2304
+ label: "complete",
2305
+ frame: {
2306
+ method: "turn/completed",
2307
+ params: {
2308
+ threadId: nativeThreadId,
2309
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2310
+ },
2311
+ },
2312
+ },
2313
+ ],
2314
+ });
2315
+ const harness = yield* makeCodexReplayHarness(transcript);
2316
+ yield* harness.runtime.startTurn(
2317
+ makeCodexTestTurnInput({
2318
+ threadId: harness.threadId,
2319
+ providerThread: harness.providerThread,
2320
+ now: yield* DateTime.now,
2321
+ attemptId: RunAttemptId.make("async-question-attempt"),
2322
+ text: "Continue while I decide.",
2323
+ }),
2324
+ );
2325
+ yield* harness.firstTerminal;
2326
+ const requests = harness.events.flatMap((event) =>
2327
+ event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
2328
+ );
2329
+ assert.lengthOf(requests, 1);
2330
+ assert.equal(requests[0]?.status, "pending");
2331
+ assert.deepEqual(requests[0]?.responseCapability, { type: "message" });
2332
+ const questionItem = harness.events.find(
2333
+ (event) =>
2334
+ event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
2335
+ );
2336
+ assert.equal(questionItem?.type, "turn_item.updated");
2337
+ if (
2338
+ questionItem?.type === "turn_item.updated" &&
2339
+ questionItem.turnItem.type === "user_input_request"
2340
+ ) {
2341
+ assert.deepEqual(
2342
+ questionItem.turnItem.questions[0]?.options.map((option) => option.label),
2343
+ ["main", "dev"],
2344
+ );
2345
+ assert.equal(questionItem.turnItem.responseMode, "message");
2346
+ }
2347
+ const questionNode = harness.events.find(
2348
+ (event) => event.type === "node.updated" && event.node.id === requests[0]?.nodeId,
2349
+ );
2350
+ assert.equal(questionNode?.type === "node.updated" && questionNode.node.countsForRun, false);
2351
+ const contextReport = harness.events.find(
2352
+ (event) =>
2353
+ event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined,
2354
+ );
2355
+ assert.equal(contextReport?.type, "provider_turn.updated");
2356
+ if (contextReport?.type === "provider_turn.updated") {
2357
+ assert.equal(
2358
+ contextReport.providerTurn.runAttemptId,
2359
+ RunAttemptId.make("async-question-attempt"),
2360
+ );
2361
+ assert.equal(contextReport.providerTurn.providerThreadId, harness.providerThread.id);
2362
+ assert.equal(contextReport.providerTurn.tokenUsage?.usedTokens, 15);
2363
+ assert.equal(contextReport.providerTurn.tokenUsage?.maxTokens, 200_000);
2364
+ }
2365
+ const completed = harness.events.find(
2366
+ (event) =>
2367
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
2368
+ );
2369
+ assert.equal(completed?.type, "provider_turn.updated");
2370
+ if (completed?.type === "provider_turn.updated") {
2371
+ assert.deepEqual(completed.providerTurn.turnTokenUsage, {
2372
+ usageStatus: "complete",
2373
+ usageScope: "main_agent",
2374
+ hasSubagents: false,
2375
inputTokens: 10,
2376
cachedInputTokens: 2,
2377
outputTokens: 5,
2263
- reasoningOutputTokens: 1,
2264
- };
2265
- const transcript = makeCodexReplayTranscript({
2266
- scenario: "async-question-and-billed-usage",
2267
- entries: [
2268
- ...codexReplayPreamble({
2269
- nativeThreadId,
2270
- nativeTurnId,
2271
- prompt: "Continue while I decide.",
2272
- }),
2273
- {
2274
- type: "emit_inbound",
2275
- label: "question",
2276
- frame: {
2277
- method: "item/completed",
2278
- params: {
2279
- threadId: nativeThreadId,
2280
- turnId: nativeTurnId,
2281
- item: {
2282
- type: "agentMessage",
2283
- id: "async-question-item",
2284
- text: "Which branch?",
2285
- delivery: "async",
2286
- questions: [{ title: "Which branch?", options: ["main", "dev"] }],
2378
+ reasoningTokens: 1,
2379
+ });
2380
+ }
2381
+ assert.isEmpty(assistantMessages(harness.events));
2382
+ }).pipe(
2383
+ Effect.provide(
2384
+ Layer.mergeAll(
2385
+ IdAllocator.layer,
2386
+ McpProviderSessions.layer,
2387
+ NodeServices.layer,
2388
+ NodeCrypto.layer,
2389
+ ),
2390
+ ),
2391
+ ),
2392
+ );
2393
+
2394
+ it.effect("returns a Codex question's answer under its native question id", () =>
2395
+ Effect.gen(function* () {
2396
+ const nativeThreadId = "question-id-thread";
2397
+ const nativeTurnId = "question-id-turn";
2398
+ const transcript = makeCodexReplayTranscript({
2399
+ scenario: "codex-question-native-id",
2400
+ entries: [
2401
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Pick one." }),
2402
+ {
2403
+ type: "emit_inbound",
2404
+ label: "question",
2405
+ frame: {
2406
+ id: 100,
2407
+ method: "item/tool/requestUserInput",
2408
+ params: {
2409
+ threadId: nativeThreadId,
2410
+ turnId: nativeTurnId,
2411
+ itemId: "question-id-item",
2412
+ isBlocking: true,
2413
+ questions: [
2414
+ {
2415
+ id: " choice ",
2416
+ header: "Choice",
2417
+ question: "Which option?",
2418
+ options: [{ label: "A", description: "Option A" }],
2419
},
2288
- },
2420
+ ],
2421
},
2422
},
2291
- {
2292
- type: "emit_inbound",
2293
- label: "usage",
2294
- frame: {
2295
- method: "thread/tokenUsage/updated",
2296
- params: {
2297
- threadId: nativeThreadId,
2298
- turnId: nativeTurnId,
2299
- tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 },
2300
- },
2423
+ },
2424
+ {
2425
+ type: "expect_outbound",
2426
+ label: "answer",
2427
+ frame: { id: 100, result: { answers: { " choice ": { answers: ["A"] } } } },
2428
+ },
2429
+ {
2430
+ type: "emit_inbound",
2431
+ label: "complete",
2432
+ frame: {
2433
+ method: "turn/completed",
2434
+ params: {
2435
+ threadId: nativeThreadId,
2436
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2437
+ },
2438
+ },
2439
+ },
2440
+ ],
2441
+ });
2442
+ const harness = yield* makeCodexReplayHarness(transcript);
2443
+ yield* harness.runtime.startTurn(
2444
+ makeCodexTestTurnInput({
2445
+ threadId: harness.threadId,
2446
+ providerThread: harness.providerThread,
2447
+ now: yield* DateTime.now,
2448
+ attemptId: RunAttemptId.make("question-id-attempt"),
2449
+ text: "Pick one.",
2450
+ }),
2451
+ );
2452
+ const questionItem = () =>
2453
+ harness.events.flatMap((event) =>
2454
+ event.type === "turn_item.updated" && event.turnItem.type === "user_input_request"
2455
+ ? [event.turnItem]
2456
+ : [],
2457
+ )[0];
2458
+ const request = () =>
2459
+ harness.events.flatMap((event) =>
2460
+ event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
2461
+ )[0];
2462
+ yield* harness.until(() => questionItem() !== undefined && request() !== undefined);
2463
+ const publishedId = questionItem()!.questions[0]!.id;
2464
+ yield* harness.runtime.respondToRuntimeRequest({
2465
+ requestId: request()!.id,
2466
+ answers: { [publishedId]: ["A"] },
2467
+ });
2468
+ yield* harness.firstTerminal;
2469
+ }).pipe(
2470
+ Effect.provide(
2471
+ Layer.mergeAll(
2472
+ IdAllocator.layer,
2473
+ McpProviderSessions.layer,
2474
+ NodeServices.layer,
2475
+ NodeCrypto.layer,
2476
+ ),
2477
+ ),
2478
+ ),
2479
+ );
2480
+
2481
+ it.effect("records the model Codex reports on the root provider turn", () =>
2482
+ Effect.gen(function* () {
2483
+ const nativeThreadId = "reported-model-thread";
2484
+ const nativeTurnId = "reported-model-turn";
2485
+ const transcript = makeCodexReplayTranscript({
2486
+ scenario: "codex-reported-model",
2487
+ entries: [
2488
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }),
2489
+ {
2490
+ type: "emit_inbound",
2491
+ label: "rerouted",
2492
+ frame: {
2493
+ method: "model/rerouted",
2494
+ params: {
2495
+ threadId: nativeThreadId,
2496
+ turnId: nativeTurnId,
2497
+ fromModel: "gpt-6-astra",
2498
+ toModel: "gpt-5.6-sol",
2499
+ reason: "highRiskCyberActivity",
2500
+ },
2501
+ },
2502
+ },
2503
+ {
2504
+ type: "emit_inbound",
2505
+ label: "complete",
2506
+ frame: {
2507
+ method: "turn/completed",
2508
+ params: {
2509
+ threadId: nativeThreadId,
2510
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2511
+ },
2512
+ },
2513
+ },
2514
+ ],
2515
+ });
2516
+ const harness = yield* makeCodexReplayHarness(transcript);
2517
+ yield* harness.runtime.startTurn(
2518
+ makeCodexTestTurnInput({
2519
+ threadId: harness.threadId,
2520
+ providerThread: harness.providerThread,
2521
+ now: yield* DateTime.now,
2522
+ attemptId: RunAttemptId.make("reported-model-attempt"),
2523
+ text: "say hi",
2524
+ }),
2525
+ );
2526
+ yield* harness.firstTerminal;
2527
+ const completed = harness.events.find(
2528
+ (event) =>
2529
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
2530
+ );
2531
+ assert.equal(completed?.type, "provider_turn.updated");
2532
+ if (completed?.type !== "provider_turn.updated") return;
2533
+ assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]);
2534
+ assert.equal(completed.providerTurn.model, "gpt-5.6-sol");
2535
+ }).pipe(
2536
+ Effect.provide(
2537
+ Layer.mergeAll(
2538
+ IdAllocator.layer,
2539
+ McpProviderSessions.layer,
2540
+ NodeServices.layer,
2541
+ NodeCrypto.layer,
2542
+ ),
2543
+ ),
2544
+ ),
2545
+ );
2546
+
2547
+ it.effect.each(["before", "during"] as const)(
2548
+ "surfaces a user MCP server that fails to start %s the turn",
2549
+ (timing) =>
2550
+ Effect.gen(function* () {
2551
+ const nativeThreadId = "mcp-startup-failed-thread";
2552
+ const nativeTurnId = "mcp-startup-failed-turn";
2553
+ const startupError =
2554
+ "MCP client for `example_mcp` failed to start: MCP startup failed: handshaking with MCP server failed";
2555
+ const startup: Array<CodexReplay.CodexAppServerReplayEntry> = [
2556
+ {
2557
+ type: "emit_inbound",
2558
+ label: "mcp-starting",
2559
+ frame: {
2560
+ method: "mcpServer/startupStatus/updated",
2561
+ params: {
2562
+ threadId: nativeThreadId,
2563
+ name: "example_mcp",
2564
+ status: "starting",
2565
+ error: null,
2566
+ failureReason: null,
2567
+ },
2568
+ },
2569
+ },
2570
+ {
2571
+ type: "emit_inbound",
2572
+ label: "mcp-failed",
2573
+ frame: {
2574
+ method: "mcpServer/startupStatus/updated",
2575
+ params: {
2576
+ threadId: nativeThreadId,
2577
+ name: "example_mcp",
2578
+ status: "failed",
2579
+ error: startupError,
2580
+ failureReason: null,
2581
},
2582
},
2583
+ },
2584
+ ];
2585
+ const preamble = codexReplayPreamble({
2586
+ nativeThreadId,
2587
+ nativeTurnId,
2588
+ prompt: "use example_mcp",
2589
+ });
2590
+ const turnStart = preamble.findIndex(
2591
+ (entry) => entry.type === "expect_outbound" && entry.label === "turn/start",
2592
+ );
2593
+ const transcript = makeCodexReplayTranscript({
2594
+ scenario: "codex-mcp-startup-failed",
2595
+ entries: [
2596
+ ...(timing === "before"
2597
+ ? [...preamble.slice(0, turnStart), ...startup, ...preamble.slice(turnStart)]
2598
+ : [...preamble, ...startup]),
2599
{
2600
type: "emit_inbound",
2601
label: "complete",
@@ -2319,70 +2615,16 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2615
threadId: harness.threadId,
2616
providerThread: harness.providerThread,
2617
now: yield* DateTime.now,
2322
- attemptId: RunAttemptId.make("async-question-attempt"),
2323
- text: "Continue while I decide.",
2618
+ attemptId: RunAttemptId.make("mcp-startup-failed-attempt"),
2619
+ text: "use example_mcp",
2620
}),
2621
);
2622
yield* harness.firstTerminal;
2327
- const requests = harness.events.flatMap((event) =>
2328
- event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
2329
- );
2330
- assert.lengthOf(requests, 1);
2331
- assert.equal(requests[0]?.status, "pending");
2332
- assert.deepEqual(requests[0]?.responseCapability, { type: "message" });
2333
- const questionItem = harness.events.find(
2334
- (event) =>
2335
- event.type === "turn_item.updated" && event.turnItem.type === "user_input_request",
2336
- );
2337
- assert.equal(questionItem?.type, "turn_item.updated");
2338
- if (
2339
- questionItem?.type === "turn_item.updated" &&
2340
- questionItem.turnItem.type === "user_input_request"
2341
- ) {
2342
- assert.deepEqual(
2343
- questionItem.turnItem.questions[0]?.options.map((option) => option.label),
2344
- ["main", "dev"],
2345
- );
2346
- assert.equal(questionItem.turnItem.responseMode, "message");
2347
- }
2348
- const questionNode = harness.events.find(
2349
- (event) => event.type === "node.updated" && event.node.id === requests[0]?.nodeId,
2350
- );
2351
- assert.equal(
2352
- questionNode?.type === "node.updated" && questionNode.node.countsForRun,
2353
- false,
2354
- );
2355
- const contextReport = harness.events.find(
2356
- (event) =>
2357
- event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined,
2358
- );
2359
- assert.equal(contextReport?.type, "provider_turn.updated");
2360
- if (contextReport?.type === "provider_turn.updated") {
2361
- assert.equal(
2362
- contextReport.providerTurn.runAttemptId,
2363
- RunAttemptId.make("async-question-attempt"),
2364
- );
2365
- assert.equal(contextReport.providerTurn.providerThreadId, harness.providerThread.id);
2366
- assert.equal(contextReport.providerTurn.tokenUsage?.usedTokens, 15);
2367
- assert.equal(contextReport.providerTurn.tokenUsage?.maxTokens, 200_000);
2368
- }
2369
- const completed = harness.events.find(
2370
- (event) =>
2371
- event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
2372
- );
2373
- assert.equal(completed?.type, "provider_turn.updated");
2374
- if (completed?.type === "provider_turn.updated") {
2375
- assert.deepEqual(completed.providerTurn.turnTokenUsage, {
2376
- usageStatus: "complete",
2377
- usageScope: "main_agent",
2378
- hasSubagents: false,
2379
- inputTokens: 10,
2380
- cachedInputTokens: 2,
2381
- outputTokens: 5,
2382
- reasoningTokens: 1,
2383
- });
2384
- }
2385
- assert.isEmpty(assistantMessages(harness.events));
2623
+ const surfaced = harness.events.filter((event) => {
2624
+ const serialized = JSON.stringify(event);
2625
+ return serialized.includes("example_mcp") && serialized.includes("failed to start");
2626
+ });
2627
+ assert.isNotEmpty(surfaced);
2628
}).pipe(
2629
Effect.provide(
2630
Layer.mergeAll(
@@ -2393,618 +2635,582 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2635
),
2636
),
2637
),
2396
- ),
2638
);
2639
2399
- it.effect("returns a Codex question's answer under its native question id", () =>
2400
- Effect.scoped(
2401
- Effect.gen(function* () {
2402
- const nativeThreadId = "question-id-thread";
2403
- const nativeTurnId = "question-id-turn";
2404
- const transcript = makeCodexReplayTranscript({
2405
- scenario: "codex-question-native-id",
2406
- entries: [
2407
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Pick one." }),
2408
- {
2409
- type: "emit_inbound",
2410
- label: "question",
2411
- frame: {
2412
- id: 100,
2413
- method: "item/tool/requestUserInput",
2414
- params: {
2415
- threadId: nativeThreadId,
2416
- turnId: nativeTurnId,
2417
- itemId: "question-id-item",
2418
- isBlocking: true,
2419
- questions: [
2420
- {
2421
- id: " choice ",
2422
- header: "Choice",
2423
- question: "Which option?",
2424
- options: [{ label: "A", description: "Option A" }],
2425
- },
2426
- ],
2427
- },
2428
- },
2429
- },
2430
- {
2431
- type: "expect_outbound",
2432
- label: "answer",
2433
- frame: { id: 100, result: { answers: { " choice ": { answers: ["A"] } } } },
2640
+ it.effect("stops asking for commands the user allowed for the session", () =>
2641
+ Effect.gen(function* () {
2642
+ const nativeThreadId = "session-approval-thread";
2643
+ const turnIds = [
2644
+ "session-approval-turn-1",
2645
+ "session-approval-turn-2",
2646
+ "session-approval-turn-3",
2647
+ ];
2648
+ const turnPolicies = {
2649
+ "approval-required": {
2650
+ approvalPolicy: "untrusted",
2651
+ approvalsReviewer: "user",
2652
+ sandboxPolicy: { type: "readOnly" },
2653
+ },
2654
+ "full-access": {
2655
+ approvalPolicy: "never",
2656
+ approvalsReviewer: "user",
2657
+ sandboxPolicy: { type: "dangerFullAccess" },
2658
+ },
2659
+ } as const;
2660
+ const turnModes = ["approval-required", "full-access", "approval-required"] as const;
2661
+ const turnText = (index: number) => `Review round ${index + 1}.`;
2662
+ const startTurn = (index: number): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
2663
+ {
2664
+ type: "expect_outbound",
2665
+ label: `turn ${index + 1} turn/start`,
2666
+ frame: {
2667
+ id: 3 + index,
2668
+ method: "turn/start",
2669
+ params: {
2670
+ threadId: nativeThreadId,
2671
+ input: [{ type: "text", text: turnText(index) }],
2672
+ cwd: "/workspace",
2673
+ model: "gpt-5.4",
2674
+ ...turnPolicies[turnModes[index]!],
2675
+ summary: "auto",
2676
+ collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
2677
},
2435
- {
2436
- type: "emit_inbound",
2437
- label: "complete",
2438
- frame: {
2439
- method: "turn/completed",
2440
- params: {
2441
- threadId: nativeThreadId,
2442
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2443
- },
2444
- },
2678
+ },
2679
+ },
2680
+ {
2681
+ type: "emit_inbound",
2682
+ label: `turn ${index + 1} turn/start`,
2683
+ frame: {
2684
+ id: 3 + index,
2685
+ result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) },
2686
+ },
2687
+ },
2688
+ turnEvent("turn/started", turnIds[index]!),
2689
+ ];
2690
+ const approval = (input: {
2691
+ readonly id: number;
2692
+ readonly turnId: string;
2693
+ readonly kind: "commandExecution" | "fileChange";
2694
+ readonly itemId: string;
2695
+ readonly decision: string;
2696
+ }): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
2697
+ {
2698
+ type: "emit_inbound",
2699
+ label: `${input.itemId} approval`,
2700
+ frame: {
2701
+ id: input.id,
2702
+ method: `item/${input.kind}/requestApproval`,
2703
+ params: {
2704
+ threadId: nativeThreadId,
2705
+ turnId: input.turnId,
2706
+ itemId: input.itemId,
2707
+ startedAtMs: 1782622441000,
2708
+ ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}),
2709
},
2446
- ],
2447
- });
2448
- const harness = yield* makeCodexReplayHarness(transcript);
2449
- yield* harness.runtime.startTurn(
2450
- makeCodexTestTurnInput({
2451
- threadId: harness.threadId,
2452
- providerThread: harness.providerThread,
2453
- now: yield* DateTime.now,
2454
- attemptId: RunAttemptId.make("question-id-attempt"),
2455
- text: "Pick one.",
2710
+ },
2711
+ },
2712
+ {
2713
+ type: "expect_outbound",
2714
+ label: `${input.itemId} decision`,
2715
+ frame: { id: input.id, result: { decision: input.decision } },
2716
+ },
2717
+ ];
2718
+ const turnEvent = (
2719
+ method: "turn/started" | "turn/completed",
2720
+ turnId: string,
2721
+ ): CodexReplay.CodexAppServerReplayEntry => ({
2722
+ type: "emit_inbound",
2723
+ label: `${turnId} ${method}`,
2724
+ frame: {
2725
+ method,
2726
+ params: {
2727
+ threadId: nativeThreadId,
2728
+ turn: makeCodexReplayTurn({
2729
+ id: turnId,
2730
+ status: method === "turn/started" ? "inProgress" : "completed",
2731
+ }),
2732
+ },
2733
+ },
2734
+ });
2735
+ const [patchRequest, patchDecision] = approval({
2736
+ id: 102,
2737
+ turnId: turnIds[0]!,
2738
+ kind: "fileChange",
2739
+ itemId: "first-patch",
2740
+ decision: "acceptForSession",
2741
+ });
2742
+ const transcript = makeCodexReplayTranscript({
2743
+ scenario: "codex-session-approvals",
2744
+ entries: [
2745
+ ...codexReplayPreamble({
2746
+ nativeThreadId,
2747
+ nativeTurnId: turnIds[0]!,
2748
+ prompt: turnText(0),
2749
+ }).slice(0, -3),
2750
+ ...startTurn(0),
2751
+ ...approval({
2752
+ id: 100,
2753
+ turnId: turnIds[0]!,
2754
+ kind: "commandExecution",
2755
+ itemId: "first-command",
2756
+ decision: "acceptForSession",
2757
}),
2457
- );
2458
- const questionItem = () =>
2758
+ patchRequest!,
2759
+ ...approval({
2760
+ id: 101,
2761
+ turnId: turnIds[0]!,
2762
+ kind: "commandExecution",
2763
+ itemId: "second-command",
2764
+ decision: "acceptForSession",
2765
+ }),
2766
+ turnEvent("turn/completed", turnIds[0]!),
2767
+ ...startTurn(1),
2768
+ patchDecision!,
2769
+ turnEvent("turn/completed", turnIds[1]!),
2770
+ ...startTurn(2),
2771
+ ...approval({
2772
+ id: 103,
2773
+ turnId: turnIds[2]!,
2774
+ kind: "commandExecution",
2775
+ itemId: "third-command",
2776
+ decision: "accept",
2777
+ }),
2778
+ ...approval({
2779
+ id: 104,
2780
+ turnId: turnIds[2]!,
2781
+ kind: "fileChange",
2782
+ itemId: "second-patch",
2783
+ decision: "accept",
2784
+ }),
2785
+ turnEvent("turn/completed", turnIds[2]!),
2786
+ ],
2787
+ });
2788
+ const harness = yield* makeCodexReplayHarness(transcript);
2789
+ const requests = () => [
2790
+ ...new Map(
2791
harness.events.flatMap((event) =>
2460
- event.type === "turn_item.updated" && event.turnItem.type === "user_input_request"
2461
- ? [event.turnItem]
2792
+ event.type === "runtime_request.updated"
2793
+ ? [[event.runtimeRequest.id, event.runtimeRequest] as const]
2794
: [],
2463
- )[0];
2464
- const request = () =>
2465
- harness.events.flatMap((event) =>
2466
- event.type === "runtime_request.updated" ? [event.runtimeRequest] : [],
2467
- )[0];
2468
- yield* harness.until(() => questionItem() !== undefined && request() !== undefined);
2469
- const publishedId = questionItem()!.questions[0]!.id;
2470
- yield* harness.runtime.respondToRuntimeRequest({
2471
- requestId: request()!.id,
2472
- answers: { [publishedId]: ["A"] },
2473
- });
2474
- yield* harness.firstTerminal;
2475
- }).pipe(
2476
- Effect.provide(
2477
- Layer.mergeAll(
2478
- IdAllocator.layer,
2479
- McpProviderSessions.layer,
2480
- NodeServices.layer,
2481
- NodeCrypto.layer,
2795
),
2483
- ),
2484
- ),
2485
- ),
2486
- );
2487
-
2488
- it.effect("records the model Codex reports on the root provider turn", () =>
2489
- Effect.scoped(
2490
- Effect.gen(function* () {
2491
- const nativeThreadId = "reported-model-thread";
2492
- const nativeTurnId = "reported-model-turn";
2493
- const transcript = makeCodexReplayTranscript({
2494
- scenario: "codex-reported-model",
2495
- entries: [
2496
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "say hi" }),
2497
- {
2498
- type: "emit_inbound",
2499
- label: "rerouted",
2500
- frame: {
2501
- method: "model/rerouted",
2502
- params: {
2503
- threadId: nativeThreadId,
2504
- turnId: nativeTurnId,
2505
- fromModel: "gpt-6-astra",
2506
- toModel: "gpt-5.6-sol",
2507
- reason: "highRiskCyberActivity",
2508
- },
2509
- },
2510
- },
2511
- {
2512
- type: "emit_inbound",
2513
- label: "complete",
2514
- frame: {
2515
- method: "turn/completed",
2516
- params: {
2517
- threadId: nativeThreadId,
2518
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2519
- },
2520
- },
2521
- },
2522
- ],
2796
+ ).values(),
2797
+ ];
2798
+ const answer = (
2799
+ count: number,
2800
+ kind: "command" | "file-change",
2801
+ decision: ProviderApprovalDecision,
2802
+ ) =>
2803
+ Effect.gen(function* () {
2804
+ yield* harness.until(() => requests().length === count);
2805
+ const request = requests()[count - 1]!;
2806
+ assert.equal(request.kind, kind);
2807
+ yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision });
2808
});
2524
- const harness = yield* makeCodexReplayHarness(transcript);
2525
- yield* harness.runtime.startTurn(
2526
- makeCodexTestTurnInput({
2527
- threadId: harness.threadId,
2528
- providerThread: harness.providerThread,
2529
- now: yield* DateTime.now,
2530
- attemptId: RunAttemptId.make("reported-model-attempt"),
2531
- text: "say hi",
2532
- }),
2533
- );
2534
- yield* harness.firstTerminal;
2535
- const completed = harness.events.find(
2536
- (event) =>
2537
- event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
2538
- );
2539
- assert.equal(completed?.type, "provider_turn.updated");
2540
- if (completed?.type !== "provider_turn.updated") return;
2541
- assert.deepEqual(completed.providerTurn.turnTokenUsage?.models, ["gpt-5.6-sol"]);
2542
- assert.equal(completed.providerTurn.model, "gpt-5.6-sol");
2543
- }).pipe(
2544
- Effect.provide(
2545
- Layer.mergeAll(
2546
- IdAllocator.layer,
2547
- McpProviderSessions.layer,
2548
- NodeServices.layer,
2549
- NodeCrypto.layer,
2550
- ),
2551
- ),
2552
- ),
2553
- ),
2554
- );
2809
2556
- it.effect.each(["before", "during"] as const)(
2557
- "surfaces a user MCP server that fails to start %s the turn",
2558
- (timing) =>
2559
- Effect.scoped(
2810
+ const runTurn = (index: number) =>
2811
Effect.gen(function* () {
2561
- const nativeThreadId = "mcp-startup-failed-thread";
2562
- const nativeTurnId = "mcp-startup-failed-turn";
2563
- const startupError =
2564
- "MCP client for `example_mcp` failed to start: MCP startup failed: handshaking with MCP server failed";
2565
- const startup: Array<CodexReplay.CodexAppServerReplayEntry> = [
2566
- {
2567
- type: "emit_inbound",
2568
- label: "mcp-starting",
2569
- frame: {
2570
- method: "mcpServer/startupStatus/updated",
2571
- params: {
2572
- threadId: nativeThreadId,
2573
- name: "example_mcp",
2574
- status: "starting",
2575
- error: null,
2576
- failureReason: null,
2577
- },
2578
- },
2579
- },
2580
- {
2581
- type: "emit_inbound",
2582
- label: "mcp-failed",
2583
- frame: {
2584
- method: "mcpServer/startupStatus/updated",
2585
- params: {
2586
- threadId: nativeThreadId,
2587
- name: "example_mcp",
2588
- status: "failed",
2589
- error: startupError,
2590
- failureReason: null,
2591
- },
2592
- },
2593
- },
2594
- ];
2595
- const preamble = codexReplayPreamble({
2596
- nativeThreadId,
2597
- nativeTurnId,
2598
- prompt: "use example_mcp",
2599
- });
2600
- const turnStart = preamble.findIndex(
2601
- (entry) => entry.type === "expect_outbound" && entry.label === "turn/start",
2602
- );
2603
- const transcript = makeCodexReplayTranscript({
2604
- scenario: "codex-mcp-startup-failed",
2605
- entries: [
2606
- ...(timing === "before"
2607
- ? [...preamble.slice(0, turnStart), ...startup, ...preamble.slice(turnStart)]
2608
- : [...preamble, ...startup]),
2609
- {
2610
- type: "emit_inbound",
2611
- label: "complete",
2612
- frame: {
2613
- method: "turn/completed",
2614
- params: {
2615
- threadId: nativeThreadId,
2616
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2617
- },
2618
- },
2619
- },
2620
- ],
2621
- });
2622
- const harness = yield* makeCodexReplayHarness(transcript);
2623
- yield* harness.runtime.startTurn(
2624
- makeCodexTestTurnInput({
2812
+ yield* harness.runtime.startTurn({
2813
+ ...makeCodexTestTurnInput({
2814
threadId: harness.threadId,
2815
providerThread: harness.providerThread,
2816
now: yield* DateTime.now,
2628
- attemptId: RunAttemptId.make("mcp-startup-failed-attempt"),
2629
- text: "use example_mcp",
2817
+ attemptId: RunAttemptId.make(`session-approvals-${index + 1}`),
2818
+ text: turnText(index),
2819
}),
2631
- );
2632
- yield* harness.firstTerminal;
2633
- const surfaced = harness.events.filter((event) => {
2634
- const serialized = JSON.stringify(event);
2635
- return serialized.includes("example_mcp") && serialized.includes("failed to start");
2820
+ runOrdinal: index + 1,
2821
+ providerTurnOrdinal: index + 1,
2822
+ runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! },
2823
});
2637
- assert.isNotEmpty(surfaced);
2638
- }).pipe(
2639
- Effect.provide(
2640
- Layer.mergeAll(
2641
- IdAllocator.layer,
2642
- McpProviderSessions.layer,
2643
- NodeServices.layer,
2644
- NodeCrypto.layer,
2645
- ),
2646
- ),
2824
+ });
2825
+
2826
+ yield* runTurn(0);
2827
+ yield* answer(1, "command", "acceptForSession");
2828
+ yield* harness.until(() => requests().length === 2);
2829
+ yield* harness.awaitTerminal(1);
2830
+ yield* runTurn(1);
2831
+ yield* answer(2, "file-change", "acceptForSession");
2832
+ yield* harness.awaitTerminal(2);
2833
+ yield* runTurn(2);
2834
+ yield* answer(3, "command", "accept");
2835
+ yield* answer(4, "file-change", "accept");
2836
+ yield* harness.awaitTerminal(3);
2837
+ assert.lengthOf(requests(), 4);
2838
+ }).pipe(
2839
+ Effect.provide(
2840
+ Layer.mergeAll(
2841
+ IdAllocator.layer,
2842
+ McpProviderSessions.layer,
2843
+ NodeServices.layer,
2844
+ NodeCrypto.layer,
2845
),
2846
),
2847
+ ),
2848
);
2849
2651
- it.effect("stops asking for commands the user allowed for the session", () =>
2652
- Effect.scoped(
2653
- Effect.gen(function* () {
2654
- const nativeThreadId = "session-approval-thread";
2655
- const turnIds = [
2656
- "session-approval-turn-1",
2657
- "session-approval-turn-2",
2658
- "session-approval-turn-3",
2659
- ];
2660
- const turnPolicies = {
2661
- "approval-required": {
2662
- approvalPolicy: "untrusted",
2663
- approvalsReviewer: "user",
2664
- sandboxPolicy: { type: "readOnly" },
2665
- },
2666
- "full-access": {
2667
- approvalPolicy: "never",
2668
- approvalsReviewer: "user",
2669
- sandboxPolicy: { type: "dangerFullAccess" },
2670
- },
2671
- } as const;
2672
- const turnModes = ["approval-required", "full-access", "approval-required"] as const;
2673
- const turnText = (index: number) => `Review round ${index + 1}.`;
2674
- const startTurn = (index: number): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
2850
+ it.effect("preserves T3 context on the wire and restores it after compaction", () =>
2851
+ Effect.gen(function* () {
2852
+ const nativeThreadId = "context-thread";
2853
+ const nativeTurnId = "context-turn";
2854
+ // An explicit Standard must reach Codex, or Codex falls back to Daybreak.
2855
+ const modelSelection = {
2856
+ ...CODEX_TEST_MODEL_SELECTION,
2857
+ options: [{ id: "cyberAccessProgram", value: "standard" }],
2858
+ };
2859
+ const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
2860
+ nativeThreadId,
2861
+ codexInput: [{ type: "text", text: "work" }],
2862
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
2863
+ modelSelection,
2864
+ hasT3Mcp: true,
2865
+ cyberAccess: { defaultProgram: "daybreakBlue" },
2866
+ });
2867
+ assert.include(
2868
+ params.additionalContext?.t3_code_orchestration_01?.value ?? "",
2869
+ "delegate_task",
2870
+ );
2871
+ const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" });
2872
+ const transcript = makeCodexReplayTranscript({
2873
+ scenario: "restore-context",
2874
+ entries: [
2875
+ ...entries.slice(0, 5),
2876
{
2877
type: "expect_outbound",
2677
- label: `turn ${index + 1} turn/start`,
2878
+ label: "context turn",
2879
+ frame: { id: 3, method: "turn/start", params },
2880
+ },
2881
+ ...entries.slice(6),
2882
+ {
2883
+ type: "emit_inbound",
2884
+ label: "compacted",
2885
frame: {
2679
- id: 3 + index,
2680
- method: "turn/start",
2886
+ method: "item/completed",
2887
params: {
2888
threadId: nativeThreadId,
2683
- input: [{ type: "text", text: turnText(index) }],
2684
- cwd: "/workspace",
2685
- model: "gpt-5.4",
2686
- ...turnPolicies[turnModes[index]!],
2687
- summary: "auto",
2688
- collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
2889
+ turnId: nativeTurnId,
2890
+ item: { type: "contextCompaction", id: "compact-context" },
2891
},
2892
},
2893
},
2894
{
2895
type: "emit_inbound",
2694
- label: `turn ${index + 1} turn/start`,
2896
+ label: "done",
2897
frame: {
2696
- id: 3 + index,
2697
- result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) },
2898
+ method: "turn/completed",
2899
+ params: {
2900
+ threadId: nativeThreadId,
2901
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2902
+ },
2903
},
2904
},
2700
- turnEvent("turn/started", turnIds[index]!),
2701
- ];
2702
- const approval = (input: {
2703
- readonly id: number;
2704
- readonly turnId: string;
2705
- readonly kind: "commandExecution" | "fileChange";
2706
- readonly itemId: string;
2707
- readonly decision: string;
2708
- }): ReadonlyArray<CodexReplay.CodexAppServerReplayEntry> => [
2905
{
2710
- type: "emit_inbound",
2711
- label: `${input.itemId} approval`,
2906
+ type: "expect_outbound",
2907
+ label: "restore context",
2908
frame: {
2713
- id: input.id,
2714
- method: `item/${input.kind}/requestApproval`,
2909
+ id: 4,
2910
+ method: "thread/inject_items",
2911
params: {
2912
threadId: nativeThreadId,
2717
- turnId: input.turnId,
2718
- itemId: input.itemId,
2719
- startedAtMs: 1782622441000,
2720
- ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}),
2913
+ items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({
2914
+ type: "message",
2915
+ role: "developer",
2916
+ content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }],
2917
+ })),
2918
},
2919
},
2920
},
2724
- {
2725
- type: "expect_outbound",
2726
- label: `${input.itemId} decision`,
2727
- frame: { id: input.id, result: { decision: input.decision } },
2728
- },
2729
- ];
2730
- const turnEvent = (
2731
- method: "turn/started" | "turn/completed",
2732
- turnId: string,
2733
- ): CodexReplay.CodexAppServerReplayEntry => ({
2734
- type: "emit_inbound",
2735
- label: `${turnId} ${method}`,
2736
- frame: {
2737
- method,
2738
- params: {
2739
- threadId: nativeThreadId,
2740
- turn: makeCodexReplayTurn({
2741
- id: turnId,
2742
- status: method === "turn/started" ? "inProgress" : "completed",
2743
- }),
2921
+ { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } },
2922
+ ],
2923
+ });
2924
+ // Codex queues items injected mid-turn as pending input and samples again.
2925
+ const wireOrder: Array<string> = [];
2926
+ const restoreRequested = yield* Deferred.make<void>();
2927
+ const harness = yield* makeCodexReplayHarness(
2928
+ transcript,
2929
+ undefined,
2930
+ (method) =>
2931
+ method === "thread/inject_items"
2932
+ ? Effect.sync(() => wireOrder.push(method)).pipe(
2933
+ Effect.andThen(Deferred.succeed(restoreRequested, undefined)),
2934
+ )
2935
+ : Effect.void,
2936
+ undefined,
2937
+ undefined,
2938
+ undefined,
2939
+ undefined,
2940
+ (method) =>
2941
+ Effect.sync(() => {
2942
+ if (method === "item/completed" || method === "turn/completed") wireOrder.push(method);
2943
+ }),
2944
+ Effect.succeed<ReadonlyArray<ServerProviderModel>>([
2945
+ {
2946
+ slug: modelSelection.model,
2947
+ name: modelSelection.model,
2948
+ isCustom: false,
2949
+ capabilities: {
2950
+ optionDescriptors: [
2951
+ {
2952
+ id: "cyberAccessProgram",
2953
+ label: "Cyber Access",
2954
+ type: "select",
2955
+ options: [
2956
+ { id: "standard", label: "Standard" },
2957
+ { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true },
2958
+ ],
2959
+ currentValue: "daybreakBlue",
2960
+ },
2961
+ ],
2962
},
2963
},
2746
- });
2747
- const [patchRequest, patchDecision] = approval({
2748
- id: 102,
2749
- turnId: turnIds[0]!,
2750
- kind: "fileChange",
2751
- itemId: "first-patch",
2752
- decision: "acceptForSession",
2753
- });
2754
- const transcript = makeCodexReplayTranscript({
2755
- scenario: "codex-session-approvals",
2756
- entries: [
2757
- ...codexReplayPreamble({
2758
- nativeThreadId,
2759
- nativeTurnId: turnIds[0]!,
2760
- prompt: turnText(0),
2761
- }).slice(0, -3),
2762
- ...startTurn(0),
2763
- ...approval({
2764
- id: 100,
2765
- turnId: turnIds[0]!,
2766
- kind: "commandExecution",
2767
- itemId: "first-command",
2768
- decision: "acceptForSession",
2769
- }),
2770
- patchRequest!,
2771
- ...approval({
2772
- id: 101,
2773
- turnId: turnIds[0]!,
2774
- kind: "commandExecution",
2775
- itemId: "second-command",
2776
- decision: "acceptForSession",
2777
- }),
2778
- turnEvent("turn/completed", turnIds[0]!),
2779
- ...startTurn(1),
2780
- patchDecision!,
2781
- turnEvent("turn/completed", turnIds[1]!),
2782
- ...startTurn(2),
2783
- ...approval({
2784
- id: 103,
2785
- turnId: turnIds[2]!,
2786
- kind: "commandExecution",
2787
- itemId: "third-command",
2788
- decision: "accept",
2789
- }),
2790
- ...approval({
2791
- id: 104,
2792
- turnId: turnIds[2]!,
2793
- kind: "fileChange",
2794
- itemId: "second-patch",
2795
- decision: "accept",
2796
- }),
2797
- turnEvent("turn/completed", turnIds[2]!),
2798
- ],
2799
- });
2800
- const harness = yield* makeCodexReplayHarness(transcript);
2801
- const requests = () => [
2802
- ...new Map(
2803
- harness.events.flatMap((event) =>
2804
- event.type === "runtime_request.updated"
2805
- ? [[event.runtimeRequest.id, event.runtimeRequest] as const]
2806
- : [],
2807
- ),
2808
- ).values(),
2809
- ];
2810
- const answer = (
2811
- count: number,
2812
- kind: "command" | "file-change",
2813
- decision: ProviderApprovalDecision,
2814
- ) =>
2815
- Effect.gen(function* () {
2816
- yield* harness.until(() => requests().length === count);
2817
- const request = requests()[count - 1]!;
2818
- assert.equal(request.kind, kind);
2819
- yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision });
2820
- });
2821
-
2822
- const runTurn = (index: number) =>
2823
- Effect.gen(function* () {
2824
- yield* harness.runtime.startTurn({
2825
- ...makeCodexTestTurnInput({
2826
- threadId: harness.threadId,
2827
- providerThread: harness.providerThread,
2828
- now: yield* DateTime.now,
2829
- attemptId: RunAttemptId.make(`session-approvals-${index + 1}`),
2830
- text: turnText(index),
2831
- }),
2832
- runOrdinal: index + 1,
2833
- providerTurnOrdinal: index + 1,
2834
- runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! },
2835
- });
2836
- });
2964
+ ]),
2965
+ );
2966
+ yield* (yield* McpProviderSessions.McpProviderSessions).set({
2967
+ environmentId: EnvironmentId.make("test"),
2968
+ threadId: harness.threadId,
2969
+ providerSessionId: "context-session",
2970
+ providerInstanceId: ProviderInstanceId.make("codex"),
2971
+ endpoint: "http://127.0.0.1:43123/mcp",
2972
+ authorizationHeader: "Bearer test",
2973
+ browserToolsAvailable: true,
2974
+ });
2975
+ yield* harness.runtime.startTurn({
2976
+ ...makeCodexTestTurnInput({
2977
+ threadId: harness.threadId,
2978
+ providerThread: harness.providerThread,
2979
+ now: yield* DateTime.now,
2980
+ attemptId: RunAttemptId.make("context-attempt"),
2981
+ text: "work",
2982
+ }),
2983
+ modelSelection,
2984
+ });
2985
+ yield* harness.firstTerminal;
2986
+ yield* Deferred.await(restoreRequested);
2987
+ assert.equal(harness.terminalEvents()[0]?.status, "completed");
2988
+ assert.deepEqual(
2989
+ wireOrder,
2990
+ ["item/completed", "turn/completed", "thread/inject_items"],
2991
+ "restored T3 context while the compacting native turn was still running",
2992
+ );
2993
+ }).pipe(
2994
+ Effect.provide(
2995
+ Layer.mergeAll(
2996
+ IdAllocator.layer,
2997
+ McpProviderSessions.layer,
2998
+ NodeServices.layer,
2999
+ NodeCrypto.layer,
3000
+ ),
3001
+ ),
3002
+ ),
3003
+ );
3004
2838
- yield* runTurn(0);
2839
- yield* answer(1, "command", "acceptForSession");
2840
- yield* harness.until(() => requests().length === 2);
2841
- yield* harness.awaitTerminal(1);
2842
- yield* runTurn(1);
2843
- yield* answer(2, "file-change", "acceptForSession");
2844
- yield* harness.awaitTerminal(2);
2845
- yield* runTurn(2);
2846
- yield* answer(3, "command", "accept");
2847
- yield* answer(4, "file-change", "accept");
2848
- yield* harness.awaitTerminal(3);
2849
- assert.lengthOf(requests(), 4);
2850
- }).pipe(
2851
- Effect.provide(
2852
- Layer.mergeAll(
2853
- IdAllocator.layer,
2854
- McpProviderSessions.layer,
2855
- NodeServices.layer,
2856
- NodeCrypto.layer,
2857
- ),
3005
+ it.effect("compacts Codex with the native RPC and completes the compaction turn", () =>
3006
+ Effect.gen(function* () {
3007
+ const nativeThreadId = "compact-thread";
3008
+ const nativeTurnId = "compact-turn";
3009
+ const item = { type: "contextCompaction", id: "compact-item" };
3010
+ const transcript = makeCodexReplayTranscript({
3011
+ scenario: "native-compaction",
3012
+ entries: [
3013
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "unused" }).slice(0, 5),
3014
+ {
3015
+ type: "expect_outbound",
3016
+ label: "compact",
3017
+ frame: {
3018
+ id: 3,
3019
+ method: "thread/compact/start",
3020
+ params: { threadId: nativeThreadId },
3021
+ },
3022
+ },
3023
+ { type: "emit_inbound", label: "compact", frame: { id: 3, result: {} } },
3024
+ {
3025
+ type: "emit_inbound",
3026
+ label: "start",
3027
+ frame: {
3028
+ method: "turn/started",
3029
+ params: {
3030
+ threadId: nativeThreadId,
3031
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
3032
+ },
3033
+ },
3034
+ },
3035
+ ...(["item/started", "item/completed"] as const).map((method) => ({
3036
+ type: "emit_inbound" as const,
3037
+ label: method,
3038
+ frame: { method, params: { threadId: nativeThreadId, turnId: nativeTurnId, item } },
3039
+ })),
3040
+ {
3041
+ type: "emit_inbound",
3042
+ label: "complete",
3043
+ frame: {
3044
+ method: "turn/completed",
3045
+ params: {
3046
+ threadId: nativeThreadId,
3047
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3048
+ },
3049
+ },
3050
+ },
3051
+ ],
3052
+ });
3053
+ const harness = yield* makeCodexReplayHarness(transcript);
3054
+ assert.isDefined(harness.runtime.compactThread);
3055
+ yield* harness.runtime.compactThread!(
3056
+ makeCodexTestTurnInput({
3057
+ threadId: harness.threadId,
3058
+ providerThread: harness.providerThread,
3059
+ now: yield* DateTime.now,
3060
+ attemptId: RunAttemptId.make("compact-attempt"),
3061
+ text: "/compact",
3062
+ }),
3063
+ );
3064
+ yield* harness.firstTerminal;
3065
+ const items = harness.events.flatMap((event) =>
3066
+ event.type === "turn_item.updated" && event.turnItem.type === "compaction"
3067
+ ? [event.turnItem]
3068
+ : [],
3069
+ );
3070
+ assert.deepEqual(
3071
+ items.map((entry) => entry.status),
3072
+ ["running", "completed"],
3073
+ );
3074
+ assert.equal(items[0]?.id, items[1]?.id);
3075
+ assert.equal(harness.terminalEvents()[0]?.status, "completed");
3076
+ }).pipe(
3077
+ Effect.provide(
3078
+ Layer.mergeAll(
3079
+ IdAllocator.layer,
3080
+ McpProviderSessions.layer,
3081
+ NodeServices.layer,
3082
+ NodeCrypto.layer,
3083
),
3084
),
3085
),
3086
);
3087
2863
- it.effect("preserves T3 context on the wire and restores it after compaction", () =>
2864
- Effect.scoped(
3088
+ it.effect.each(["failed", "interrupted", "Stop"] as const)(
3089
+ "settles unfinished compaction on %s without changing completed compaction",
3090
+ (outcome) =>
3091
Effect.gen(function* () {
2866
- const nativeThreadId = "context-thread";
2867
- const nativeTurnId = "context-turn";
2868
- // An explicit Standard must reach Codex, or Codex falls back to Daybreak.
2869
- const modelSelection = {
2870
- ...CODEX_TEST_MODEL_SELECTION,
2871
- options: [{ id: "cyberAccessProgram", value: "standard" }],
3092
+ const nativeThreadId = "compact-thread";
3093
+ const nativeTurnId = "compact-turn";
3094
+ const error = {
3095
+ message: "Remote compaction stream disconnected",
3096
+ codexErrorInfo: "other",
3097
+ additionalDetails: null,
3098
};
2873
- const params = yield* CodexAdapterV2.buildCodexTurnStartParams({
2874
- nativeThreadId,
2875
- codexInput: [{ type: "text", text: "work" }],
2876
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
2877
- modelSelection,
2878
- hasT3Mcp: true,
2879
- cyberAccess: { defaultProgram: "daybreakBlue" },
2880
- });
2881
- assert.include(
2882
- params.additionalContext?.t3_code_orchestration_01?.value ?? "",
2883
- "delegate_task",
2884
- );
2885
- const entries = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" });
3099
const transcript = makeCodexReplayTranscript({
2887
- scenario: "restore-context",
3100
+ scenario: `automatic-compaction-${outcome}`,
3101
entries: [
2889
- ...entries.slice(0, 5),
2890
- {
2891
- type: "expect_outbound",
2892
- label: "context turn",
2893
- frame: { id: 3, method: "turn/start", params },
2894
- },
2895
- ...entries.slice(6),
2896
- {
2897
- type: "emit_inbound",
2898
- label: "compacted",
3102
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
3103
+ ...(
3104
+ [
3105
+ { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 },
3106
+ { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 },
3107
+ { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 },
3108
+ ] as const
3109
+ ).map(({ method, id, ...timestamps }) => ({
3110
+ type: "emit_inbound" as const,
3111
+ label: `${method}/${id}`,
3112
frame: {
2900
- method: "item/completed",
3113
+ method,
3114
params: {
3115
threadId: nativeThreadId,
3116
turnId: nativeTurnId,
2904
- item: { type: "contextCompaction", id: "compact-context" },
2905
- },
2906
- },
2907
- },
2908
- {
2909
- type: "emit_inbound",
2910
- label: "done",
2911
- frame: {
2912
- method: "turn/completed",
2913
- params: {
2914
- threadId: nativeThreadId,
2915
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
2916
- },
2917
- },
2918
- },
2919
- {
2920
- type: "expect_outbound",
2921
- label: "restore context",
2922
- frame: {
2923
- id: 4,
2924
- method: "thread/inject_items",
2925
- params: {
2926
- threadId: nativeThreadId,
2927
- items: Object.entries(params.additionalContext ?? {}).map(([key, entry]) => ({
2928
- type: "message",
2929
- role: "developer",
2930
- content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }],
2931
- })),
3117
+ item: { type: "contextCompaction", id },
3118
+ ...timestamps,
3119
},
3120
},
2934
- },
2935
- { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } },
2936
- ],
2937
- });
2938
- // Codex queues items injected mid-turn as pending input and samples again.
2939
- const wireOrder: Array<string> = [];
2940
- const restoreRequested = yield* Deferred.make<void>();
2941
- const harness = yield* makeCodexReplayHarness(
2942
- transcript,
2943
- undefined,
2944
- (method) =>
2945
- method === "thread/inject_items"
2946
- ? Effect.sync(() => wireOrder.push(method)).pipe(
2947
- Effect.andThen(Deferred.succeed(restoreRequested, undefined)),
2948
- )
2949
- : Effect.void,
2950
- undefined,
2951
- undefined,
2952
- undefined,
2953
- undefined,
2954
- (method) =>
2955
- Effect.sync(() => {
2956
- if (method === "item/completed" || method === "turn/completed")
2957
- wireOrder.push(method);
2958
- }),
2959
- Effect.succeed<ReadonlyArray<ServerProviderModel>>([
2960
- {
2961
- slug: modelSelection.model,
2962
- name: modelSelection.model,
2963
- isCustom: false,
2964
- capabilities: {
2965
- optionDescriptors: [
3121
+ })),
3122
+ ...(outcome === "Stop"
3123
+ ? [
3124
{
2967
- id: "cyberAccessProgram",
2968
- label: "Cyber Access",
2969
- type: "select",
2970
- options: [
2971
- { id: "standard", label: "Standard" },
2972
- { id: "daybreakBlue", label: "Daybreak Blue", isDefault: true },
2973
- ],
2974
- currentValue: "daybreakBlue",
3125
+ type: "expect_outbound" as const,
3126
+ label: "turn/interrupt",
3127
+ frame: {
3128
+ id: 4,
3129
+ method: "turn/interrupt",
3130
+ params: { threadId: nativeThreadId, turnId: nativeTurnId },
3131
+ },
3132
},
2976
- ],
2977
- },
2978
- },
2979
- ]),
2980
- );
2981
- yield* (yield* McpProviderSessions.McpProviderSessions).set({
2982
- environmentId: EnvironmentId.make("test"),
2983
- threadId: harness.threadId,
2984
- providerSessionId: "context-session",
2985
- providerInstanceId: ProviderInstanceId.make("codex"),
2986
- endpoint: "http://127.0.0.1:43123/mcp",
2987
- authorizationHeader: "Bearer test",
2988
- browserToolsAvailable: true,
3133
+ {
3134
+ type: "emit_inbound" as const,
3135
+ label: "turn/interrupt/failed",
3136
+ frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } },
3137
+ },
3138
+ ]
3139
+ : [
3140
+ {
3141
+ type: "emit_inbound" as const,
3142
+ label: "turn/completed",
3143
+ frame: {
3144
+ method: "turn/completed",
3145
+ params: {
3146
+ threadId: nativeThreadId,
3147
+ turn: {
3148
+ ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }),
3149
+ error: outcome === "failed" ? error : null,
3150
+ },
3151
+ },
3152
+ },
3153
+ },
3154
+ ]),
3155
+ ],
3156
});
2990
- yield* harness.runtime.startTurn({
2991
- ...makeCodexTestTurnInput({
3157
+ const compactionStarted = yield* Deferred.make<ProviderTurnId>();
3158
+ const harness = yield* makeCodexReplayHarness(transcript, (event) =>
3159
+ event.type === "turn_item.updated" &&
3160
+ event.turnItem.nativeItemRef?.nativeId === "unfinished-item" &&
3161
+ event.turnItem.status === "running" &&
3162
+ event.turnItem.providerTurnId !== null
3163
+ ? Deferred.succeed(compactionStarted, event.turnItem.providerTurnId)
3164
+ : Effect.void,
3165
+ );
3166
+ yield* TestClock.setTime(1782622445000);
3167
+ yield* harness.runtime.startTurn(
3168
+ makeCodexTestTurnInput({
3169
threadId: harness.threadId,
3170
providerThread: harness.providerThread,
3171
now: yield* DateTime.now,
2995
- attemptId: RunAttemptId.make("context-attempt"),
2996
- text: "work",
3172
+ attemptId: RunAttemptId.make(`compact-${outcome}-attempt`),
3173
+ text: "Continue.",
3174
}),
2998
- modelSelection,
2999
- });
3175
+ );
3176
+ if (outcome === "Stop") {
3177
+ const providerTurnId = yield* Deferred.await(compactionStarted);
3178
+ const interrupt = yield* harness.runtime
3179
+ .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
3180
+ .pipe(Effect.exit);
3181
+ assert.equal(interrupt._tag, "Failure");
3182
+ }
3183
yield* harness.firstTerminal;
3001
- yield* Deferred.await(restoreRequested);
3002
- assert.equal(harness.terminalEvents()[0]?.status, "completed");
3184
+ const items = harness.events.flatMap((event) =>
3185
+ event.type === "turn_item.updated" && event.turnItem.type === "compaction"
3186
+ ? [event.turnItem]
3187
+ : [],
3188
+ );
3189
+ const completed = items.filter((item) => item.nativeItemRef?.nativeId === "completed-item");
3190
+ const unfinished = items.filter(
3191
+ (item) => item.nativeItemRef?.nativeId === "unfinished-item",
3192
+ );
3193
+ const status = outcome === "failed" ? "failed" : "interrupted";
3194
+ assert.deepEqual(
3195
+ unfinished.map((item) => item.status),
3196
+ ["running", status],
3197
+ );
3198
+ assert.equal(unfinished[0]?.id, unfinished[1]?.id);
3199
+ assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000));
3200
assert.deepEqual(
3004
- wireOrder,
3005
- ["item/completed", "turn/completed", "thread/inject_items"],
3006
- "restored T3 context while the compacting native turn was still running",
3201
+ unfinished[1]?.completedAt,
3202
+ DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000),
3203
);
3204
+ assert.deepEqual(
3205
+ completed.map((item) => item.status),
3206
+ ["running", "completed"],
3207
+ );
3208
+ assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000));
3209
+ assert.deepEqual(completed[1]?.completedAt, DateTime.makeUnsafe(1782622442000));
3210
+ assert.equal(harness.terminalEvents()[0]?.status, status);
3211
+ if (outcome === "failed") {
3212
+ assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message);
3213
+ }
3214
}).pipe(
3215
Effect.provide(
3216
Layer.mergeAll(
@@ -3015,234 +3221,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3221
),
3222
),
3223
),
3018
- ),
3019
- );
3020
-
3021
- it.effect("compacts Codex with the native RPC and completes the compaction turn", () =>
3022
- Effect.scoped(
3023
- Effect.gen(function* () {
3024
- const nativeThreadId = "compact-thread";
3025
- const nativeTurnId = "compact-turn";
3026
- const item = { type: "contextCompaction", id: "compact-item" };
3027
- const transcript = makeCodexReplayTranscript({
3028
- scenario: "native-compaction",
3029
- entries: [
3030
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "unused" }).slice(0, 5),
3031
- {
3032
- type: "expect_outbound",
3033
- label: "compact",
3034
- frame: {
3035
- id: 3,
3036
- method: "thread/compact/start",
3037
- params: { threadId: nativeThreadId },
3038
- },
3039
- },
3040
- { type: "emit_inbound", label: "compact", frame: { id: 3, result: {} } },
3041
- {
3042
- type: "emit_inbound",
3043
- label: "start",
3044
- frame: {
3045
- method: "turn/started",
3046
- params: {
3047
- threadId: nativeThreadId,
3048
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }),
3049
- },
3050
- },
3051
- },
3052
- ...(["item/started", "item/completed"] as const).map((method) => ({
3053
- type: "emit_inbound" as const,
3054
- label: method,
3055
- frame: { method, params: { threadId: nativeThreadId, turnId: nativeTurnId, item } },
3056
- })),
3057
- {
3058
- type: "emit_inbound",
3059
- label: "complete",
3060
- frame: {
3061
- method: "turn/completed",
3062
- params: {
3063
- threadId: nativeThreadId,
3064
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
3065
- },
3066
- },
3067
- },
3068
- ],
3069
- });
3070
- const harness = yield* makeCodexReplayHarness(transcript);
3071
- assert.isDefined(harness.runtime.compactThread);
3072
- yield* harness.runtime.compactThread!(
3073
- makeCodexTestTurnInput({
3074
- threadId: harness.threadId,
3075
- providerThread: harness.providerThread,
3076
- now: yield* DateTime.now,
3077
- attemptId: RunAttemptId.make("compact-attempt"),
3078
- text: "/compact",
3079
- }),
3080
- );
3081
- yield* harness.firstTerminal;
3082
- const items = harness.events.flatMap((event) =>
3083
- event.type === "turn_item.updated" && event.turnItem.type === "compaction"
3084
- ? [event.turnItem]
3085
- : [],
3086
- );
3087
- assert.deepEqual(
3088
- items.map((entry) => entry.status),
3089
- ["running", "completed"],
3090
- );
3091
- assert.equal(items[0]?.id, items[1]?.id);
3092
- assert.equal(harness.terminalEvents()[0]?.status, "completed");
3093
- }).pipe(
3094
- Effect.provide(
3095
- Layer.mergeAll(
3096
- IdAllocator.layer,
3097
- McpProviderSessions.layer,
3098
- NodeServices.layer,
3099
- NodeCrypto.layer,
3100
- ),
3101
- ),
3102
- ),
3103
- ),
3104
- );
3105
-
3106
- it.effect.each(["failed", "interrupted", "Stop"] as const)(
3107
- "settles unfinished compaction on %s without changing completed compaction",
3108
- (outcome) =>
3109
- Effect.scoped(
3110
- Effect.gen(function* () {
3111
- const nativeThreadId = "compact-thread";
3112
- const nativeTurnId = "compact-turn";
3113
- const error = {
3114
- message: "Remote compaction stream disconnected",
3115
- codexErrorInfo: "other",
3116
- additionalDetails: null,
3117
- };
3118
- const transcript = makeCodexReplayTranscript({
3119
- scenario: `automatic-compaction-${outcome}`,
3120
- entries: [
3121
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
3122
- ...(
3123
- [
3124
- { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 },
3125
- { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 },
3126
- { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 },
3127
- ] as const
3128
- ).map(({ method, id, ...timestamps }) => ({
3129
- type: "emit_inbound" as const,
3130
- label: `${method}/${id}`,
3131
- frame: {
3132
- method,
3133
- params: {
3134
- threadId: nativeThreadId,
3135
- turnId: nativeTurnId,
3136
- item: { type: "contextCompaction", id },
3137
- ...timestamps,
3138
- },
3139
- },
3140
- })),
3141
- ...(outcome === "Stop"
3142
- ? [
3143
- {
3144
- type: "expect_outbound" as const,
3145
- label: "turn/interrupt",
3146
- frame: {
3147
- id: 4,
3148
- method: "turn/interrupt",
3149
- params: { threadId: nativeThreadId, turnId: nativeTurnId },
3150
- },
3151
- },
3152
- {
3153
- type: "emit_inbound" as const,
3154
- label: "turn/interrupt/failed",
3155
- frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } },
3156
- },
3157
- ]
3158
- : [
3159
- {
3160
- type: "emit_inbound" as const,
3161
- label: "turn/completed",
3162
- frame: {
3163
- method: "turn/completed",
3164
- params: {
3165
- threadId: nativeThreadId,
3166
- turn: {
3167
- ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }),
3168
- error: outcome === "failed" ? error : null,
3169
- },
3170
- },
3171
- },
3172
- },
3173
- ]),
3174
- ],
3175
- });
3176
- const compactionStarted = yield* Deferred.make<ProviderTurnId>();
3177
- const harness = yield* makeCodexReplayHarness(transcript, (event) =>
3178
- event.type === "turn_item.updated" &&
3179
- event.turnItem.nativeItemRef?.nativeId === "unfinished-item" &&
3180
- event.turnItem.status === "running" &&
3181
- event.turnItem.providerTurnId !== null
3182
- ? Deferred.succeed(compactionStarted, event.turnItem.providerTurnId)
3183
- : Effect.void,
3184
- );
3185
- yield* TestClock.setTime(1782622445000);
3186
- yield* harness.runtime.startTurn(
3187
- makeCodexTestTurnInput({
3188
- threadId: harness.threadId,
3189
- providerThread: harness.providerThread,
3190
- now: yield* DateTime.now,
3191
- attemptId: RunAttemptId.make(`compact-${outcome}-attempt`),
3192
- text: "Continue.",
3193
- }),
3194
- );
3195
- if (outcome === "Stop") {
3196
- const providerTurnId = yield* Deferred.await(compactionStarted);
3197
- const interrupt = yield* harness.runtime
3198
- .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
3199
- .pipe(Effect.exit);
3200
- assert.equal(interrupt._tag, "Failure");
3201
- }
3202
- yield* harness.firstTerminal;
3203
- const items = harness.events.flatMap((event) =>
3204
- event.type === "turn_item.updated" && event.turnItem.type === "compaction"
3205
- ? [event.turnItem]
3206
- : [],
3207
- );
3208
- const completed = items.filter(
3209
- (item) => item.nativeItemRef?.nativeId === "completed-item",
3210
- );
3211
- const unfinished = items.filter(
3212
- (item) => item.nativeItemRef?.nativeId === "unfinished-item",
3213
- );
3214
- const status = outcome === "failed" ? "failed" : "interrupted";
3215
- assert.deepEqual(
3216
- unfinished.map((item) => item.status),
3217
- ["running", status],
3218
- );
3219
- assert.equal(unfinished[0]?.id, unfinished[1]?.id);
3220
- assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000));
3221
- assert.deepEqual(
3222
- unfinished[1]?.completedAt,
3223
- DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000),
3224
- );
3225
- assert.deepEqual(
3226
- completed.map((item) => item.status),
3227
- ["running", "completed"],
3228
- );
3229
- assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000));
3230
- assert.deepEqual(completed[1]?.completedAt, DateTime.makeUnsafe(1782622442000));
3231
- assert.equal(harness.terminalEvents()[0]?.status, status);
3232
- if (outcome === "failed") {
3233
- assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message);
3234
- }
3235
- }).pipe(
3236
- Effect.provide(
3237
- Layer.mergeAll(
3238
- IdAllocator.layer,
3239
- McpProviderSessions.layer,
3240
- NodeServices.layer,
3241
- NodeCrypto.layer,
3242
- ),
3243
- ),
3244
- ),
3245
- ),
3224
);
3225
3226
it.effect.each([
@@ -3361,186 +3339,307 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3339
);
3340
3341
it.effect("resumes a provider thread without requesting or decoding its history", () =>
3364
- Effect.scoped(
3365
- Effect.gen(function* () {
3366
- const scenario = "codex-resume-metadata";
3367
- const nativeThreadId = `native-${scenario}-thread`;
3368
- const preamble = codexReplayPreamble({
3369
- nativeThreadId,
3370
- nativeTurnId: "unused-turn",
3371
- prompt: "unused-prompt",
3372
- }).slice(0, 5);
3373
- const transcript = makeCodexReplayTranscript({
3374
- scenario,
3375
- entries: [
3376
- ...preamble,
3377
- {
3378
- type: "expect_outbound",
3379
- label: "thread/resume",
3380
- frame: {
3381
- id: 3,
3382
- method: "thread/resume",
3383
- params: {
3384
- threadId: nativeThreadId,
3385
- excludeTurns: true,
3386
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3387
- },
3388
- },
3389
- },
3390
- {
3391
- type: "emit_inbound",
3392
- label: "thread/resume",
3393
- frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3394
- },
3395
- {
3396
- type: "expect_outbound",
3397
- label: "thread/resume without an app thread",
3398
- frame: {
3399
- id: 4,
3400
- method: "thread/resume",
3401
- params: {
3402
- threadId: nativeThreadId,
3403
- excludeTurns: true,
3404
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3405
- },
3406
- },
3407
- },
3408
- {
3409
- type: "emit_inbound",
3410
- label: "thread/resume without an app thread",
3411
- frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3412
- },
3413
- {
3414
- type: "expect_outbound",
3415
- label: "thread/resume with an explicit app thread",
3416
- frame: {
3417
- id: 5,
3418
- method: "thread/resume",
3419
- params: {
3420
- threadId: nativeThreadId,
3421
- excludeTurns: true,
3422
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3423
- },
3342
+ Effect.gen(function* () {
3343
+ const scenario = "codex-resume-metadata";
3344
+ const nativeThreadId = `native-${scenario}-thread`;
3345
+ const preamble = codexReplayPreamble({
3346
+ nativeThreadId,
3347
+ nativeTurnId: "unused-turn",
3348
+ prompt: "unused-prompt",
3349
+ }).slice(0, 5);
3350
+ const transcript = makeCodexReplayTranscript({
3351
+ scenario,
3352
+ entries: [
3353
+ ...preamble,
3354
+ {
3355
+ type: "expect_outbound",
3356
+ label: "thread/resume",
3357
+ frame: {
3358
+ id: 3,
3359
+ method: "thread/resume",
3360
+ params: {
3361
+ threadId: nativeThreadId,
3362
+ excludeTurns: true,
3363
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3364
},
3365
},
3426
- {
3427
- type: "emit_inbound",
3428
- label: "thread/resume with an explicit app thread",
3429
- frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3430
- },
3431
- ],
3432
- });
3433
- const resumeThreadEnvs: Array<unknown> = [];
3434
- const harness = yield* makeCodexReplayHarness(
3435
- transcript,
3436
- () => Effect.void,
3437
- (method, params) =>
3438
- Effect.sync(() => {
3439
- if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params));
3440
- }),
3441
- );
3442
- const resumed = yield* harness.runtime.resumeThread({
3443
- providerThread: harness.providerThread,
3444
- modelSelection: CODEX_TEST_MODEL_SELECTION,
3445
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3446
- });
3447
- yield* harness.runtime.resumeThread({
3448
- providerThread: { ...harness.providerThread, appThreadId: null },
3449
- modelSelection: CODEX_TEST_MODEL_SELECTION,
3450
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3451
- });
3452
- const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`);
3453
- yield* harness.runtime.resumeThread({
3454
- threadId: explicitThreadId,
3455
- providerThread: harness.providerThread,
3456
- modelSelection: CODEX_TEST_MODEL_SELECTION,
3457
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3458
- });
3459
-
3460
- assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3461
- assert.equal(resumed.status, "idle");
3462
- assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
3463
- assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]);
3464
- }).pipe(
3465
- Effect.provide(
3466
- Layer.mergeAll(
3467
- IdAllocator.layer,
3468
- McpProviderSessions.layer,
3469
- NodeServices.layer,
3470
- NodeCrypto.layer,
3471
- ),
3472
- ),
3473
- ),
3474
- ),
3475
- );
3476
-
3477
- // regression: #15389 archived native Codex sessions resume via thread/unarchive
3478
- it.effect.each(
3479
- (
3480
- [
3481
- ["recovers archived-session errors", "session saved-thread is archived", 0, ""],
3482
- ["preserves missing-thread errors", "thread not found", 3, "thread not found"],
3483
- [
3484
- "propagates unarchive missing-thread errors",
3485
- "session saved-thread is archived",
3486
- 4,
3487
- "thread not found",
3488
- ],
3489
- [
3490
- "does not retry archived errors twice",
3491
- "session saved-thread is archived",
3492
- 5,
3493
- "session saved-thread is archived",
3494
- ],
3495
- ] as const
3496
- ).map(([name, resumeError, failAt, finalError]) => ({ name, resumeError, failAt, finalError })),
3497
- )("$name", ({ name, resumeError, failAt, finalError }) =>
3498
- Effect.scoped(
3499
- Effect.gen(function* () {
3500
- const nativeThreadId = "saved-thread";
3501
- const params = {
3502
- threadId: nativeThreadId,
3503
- excludeTurns: true,
3504
- cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3505
- model: CODEX_TEST_MODEL_SELECTION.model,
3506
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3507
- };
3508
- const entries: Array<CodexReplay.CodexAppServerReplayEntry> = [
3509
- ...codexReplayPreamble({
3510
- nativeThreadId,
3511
- nativeTurnId: "unused-turn",
3512
- prompt: "unused-prompt",
3513
- }).slice(0, 5),
3366
+ },
3367
+ {
3368
+ type: "emit_inbound",
3369
+ label: "thread/resume",
3370
+ frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3371
+ },
3372
{
3373
type: "expect_outbound",
3516
- label: "resume archived thread",
3517
- frame: { id: 3, method: "thread/resume", params },
3374
+ label: "thread/resume without an app thread",
3375
+ frame: {
3376
+ id: 4,
3377
+ method: "thread/resume",
3378
+ params: {
3379
+ threadId: nativeThreadId,
3380
+ excludeTurns: true,
3381
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3382
+ },
3383
+ },
3384
},
3385
{
3386
type: "emit_inbound",
3521
- label: "resume error",
3522
- frame: { id: 3, error: { code: -32600, message: resumeError } },
3387
+ label: "thread/resume without an app thread",
3388
+ frame: { id: 4, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3389
},
3524
- ];
3525
- if (failAt !== 3) {
3526
- entries.push(
3390
+ {
3391
+ type: "expect_outbound",
3392
+ label: "thread/resume with an explicit app thread",
3393
+ frame: {
3394
+ id: 5,
3395
+ method: "thread/resume",
3396
+ params: {
3397
+ threadId: nativeThreadId,
3398
+ excludeTurns: true,
3399
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3400
+ },
3401
+ },
3402
+ },
3403
+ {
3404
+ type: "emit_inbound",
3405
+ label: "thread/resume with an explicit app thread",
3406
+ frame: { id: 5, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } },
3407
+ },
3408
+ ],
3409
+ });
3410
+ const resumeThreadEnvs: Array<unknown> = [];
3411
+ const harness = yield* makeCodexReplayHarness(
3412
+ transcript,
3413
+ () => Effect.void,
3414
+ (method, params) =>
3415
+ Effect.sync(() => {
3416
+ if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params));
3417
+ }),
3418
+ );
3419
+ const resumed = yield* harness.runtime.resumeThread({
3420
+ providerThread: harness.providerThread,
3421
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
3422
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3423
+ });
3424
+ yield* harness.runtime.resumeThread({
3425
+ providerThread: { ...harness.providerThread, appThreadId: null },
3426
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
3427
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3428
+ });
3429
+ const explicitThreadId = ThreadId.make(`thread-${scenario}-explicit`);
3430
+ yield* harness.runtime.resumeThread({
3431
+ threadId: explicitThreadId,
3432
+ providerThread: harness.providerThread,
3433
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
3434
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3435
+ });
3436
+
3437
+ assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3438
+ assert.equal(resumed.status, "idle");
3439
+ assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
3440
+ assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]);
3441
+ }).pipe(
3442
+ Effect.provide(
3443
+ Layer.mergeAll(
3444
+ IdAllocator.layer,
3445
+ McpProviderSessions.layer,
3446
+ NodeServices.layer,
3447
+ NodeCrypto.layer,
3448
+ ),
3449
+ ),
3450
+ ),
3451
+ );
3452
+
3453
+ // regression: #15389 archived native Codex sessions resume via thread/unarchive
3454
+ it.effect.each(
3455
+ (
3456
+ [
3457
+ ["recovers archived-session errors", "session saved-thread is archived", 0, ""],
3458
+ ["preserves missing-thread errors", "thread not found", 3, "thread not found"],
3459
+ [
3460
+ "propagates unarchive missing-thread errors",
3461
+ "session saved-thread is archived",
3462
+ 4,
3463
+ "thread not found",
3464
+ ],
3465
+ [
3466
+ "does not retry archived errors twice",
3467
+ "session saved-thread is archived",
3468
+ 5,
3469
+ "session saved-thread is archived",
3470
+ ],
3471
+ ] as const
3472
+ ).map(([name, resumeError, failAt, finalError]) => ({ name, resumeError, failAt, finalError })),
3473
+ )("$name", ({ name, resumeError, failAt, finalError }) =>
3474
+ Effect.gen(function* () {
3475
+ const nativeThreadId = "saved-thread";
3476
+ const params = {
3477
+ threadId: nativeThreadId,
3478
+ excludeTurns: true,
3479
+ cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3480
+ model: CODEX_TEST_MODEL_SELECTION.model,
3481
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3482
+ };
3483
+ const entries: Array<CodexReplay.CodexAppServerReplayEntry> = [
3484
+ ...codexReplayPreamble({
3485
+ nativeThreadId,
3486
+ nativeTurnId: "unused-turn",
3487
+ prompt: "unused-prompt",
3488
+ }).slice(0, 5),
3489
+ {
3490
+ type: "expect_outbound",
3491
+ label: "resume archived thread",
3492
+ frame: { id: 3, method: "thread/resume", params },
3493
+ },
3494
+ {
3495
+ type: "emit_inbound",
3496
+ label: "resume error",
3497
+ frame: { id: 3, error: { code: -32600, message: resumeError } },
3498
+ },
3499
+ ];
3500
+ if (failAt !== 3) {
3501
+ entries.push(
3502
+ {
3503
+ type: "expect_outbound",
3504
+ label: "unarchive same thread",
3505
+ frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } },
3506
+ },
3507
+ {
3508
+ type: "emit_inbound",
3509
+ label: "unarchive result",
3510
+ frame:
3511
+ failAt === 4
3512
+ ? { id: 4, error: { code: -32600, message: finalError } }
3513
+ : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } },
3514
+ },
3515
+ );
3516
+ }
3517
+ if (failAt === 0 || failAt === 5) {
3518
+ entries.push(
3519
+ {
3520
+ type: "expect_outbound",
3521
+ label: "retry identical resume",
3522
+ frame: { id: 5, method: "thread/resume", params },
3523
+ },
3524
+ {
3525
+ type: "emit_inbound",
3526
+ label: "retry result",
3527
+ frame:
3528
+ failAt === 5
3529
+ ? { id: 5, error: { code: -32600, message: finalError } }
3530
+ : {
3531
+ id: 5,
3532
+ result: {
3533
+ thread: {
3534
+ id: nativeThreadId,
3535
+ updatedAt: 1782622450,
3536
+ turns: [{ type: "unknown-history-item" }],
3537
+ },
3538
+ },
3539
+ },
3540
+ },
3541
+ );
3542
+ }
3543
+ const harness = yield* makeCodexReplayHarness(
3544
+ makeCodexReplayTranscript({ scenario: name, entries }),
3545
+ );
3546
+ const resume = harness.runtime.resumeThread({
3547
+ providerThread: harness.providerThread,
3548
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
3549
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3550
+ });
3551
+ if (failAt !== 0) {
3552
+ const error = yield* Effect.flip(resume);
3553
+ assert.equal(error._tag, "ProviderAdapterResumeThreadError");
3554
+ assert.nestedPropertyVal(error, "cause.errorMessage", finalError);
3555
+ assert.nestedPropertyVal(
3556
+ error,
3557
+ "cause.method",
3558
+ failAt === 4 ? "thread/unarchive" : "thread/resume",
3559
+ );
3560
+ assert.nestedPropertyVal(error, "cause.requestId", String(failAt));
3561
+ return;
3562
+ }
3563
+ const resumed = yield* resume;
3564
+ assert.equal(resumed.id, harness.providerThread.id);
3565
+ assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3566
+ assert.deepEqual(
3567
+ resumed.nativeConversationHeadRef,
3568
+ harness.providerThread.nativeConversationHeadRef,
3569
+ );
3570
+ assert.equal(resumed.status, "idle");
3571
+ assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
3572
+ }).pipe(
3573
+ Effect.provide(
3574
+ Layer.mergeAll(
3575
+ IdAllocator.layer,
3576
+ McpProviderSessions.layer,
3577
+ NodeServices.layer,
3578
+ NodeCrypto.layer,
3579
+ ),
3580
+ ),
3581
+ ),
3582
+ );
3583
+
3584
+ // regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing
3585
+ it.effect.each([
3586
+ { name: "waits for thread/closed after a closing error", closedFirst: false },
3587
+ { name: "retries at once when the thread already closed", closedFirst: true },
3588
+ ])("$name", ({ name, closedFirst }) =>
3589
+ Effect.gen(function* () {
3590
+ const nativeThreadId = "closing-thread";
3591
+ const params = {
3592
+ threadId: nativeThreadId,
3593
+ excludeTurns: true,
3594
+ cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3595
+ model: CODEX_TEST_MODEL_SELECTION.model,
3596
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3597
+ };
3598
+ const closed: CodexReplay.CodexAppServerReplayEntry = {
3599
+ type: "emit_inbound",
3600
+ label: "thread closed",
3601
+ frame: { method: "thread/closed", params: { threadId: nativeThreadId } },
3602
+ };
3603
+ const closingError: CodexReplay.CodexAppServerReplayEntry = {
3604
+ type: "emit_inbound",
3605
+ label: "resume closing error",
3606
+ frame: {
3607
+ id: 4,
3608
+ error: {
3609
+ code: -32600,
3610
+ message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`,
3611
+ },
3612
+ },
3613
+ };
3614
+ const harness = yield* makeCodexReplayHarness(
3615
+ makeCodexReplayTranscript({
3616
+ scenario: name,
3617
+ entries: [
3618
+ ...codexReplayPreamble({
3619
+ nativeThreadId,
3620
+ nativeTurnId: "unused-turn",
3621
+ prompt: "unused-prompt",
3622
+ }).slice(0, 5),
3623
{
3624
type: "expect_outbound",
3529
- label: "unarchive same thread",
3530
- frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } },
3625
+ label: "unsubscribe",
3626
+ frame: {
3627
+ id: 3,
3628
+ method: "thread/unsubscribe",
3629
+ params: { threadId: nativeThreadId },
3630
+ },
3631
},
3632
{
3633
type: "emit_inbound",
3534
- label: "unarchive result",
3535
- frame:
3536
- failAt === 4
3537
- ? { id: 4, error: { code: -32600, message: finalError } }
3538
- : { id: 4, result: { thread: { turns: [{ type: "unknown-history-item" }] } } },
3634
+ label: "unsubscribe result",
3635
+ frame: { id: 3, result: { status: "unsubscribed" } },
3636
},
3540
- );
3541
- }
3542
- if (failAt === 0 || failAt === 5) {
3543
- entries.push(
3637
+ {
3638
+ type: "expect_outbound",
3639
+ label: "resume closing thread",
3640
+ frame: { id: 4, method: "thread/resume", params },
3641
+ },
3642
+ ...(closedFirst ? [closed, closingError] : [closingError, closed]),
3643
{
3644
type: "expect_outbound",
3645
label: "retry identical resume",
@@ -3549,326 +3648,233 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3648
{
3649
type: "emit_inbound",
3650
label: "retry result",
3552
- frame:
3553
- failAt === 5
3554
- ? { id: 5, error: { code: -32600, message: finalError } }
3555
- : {
3556
- id: 5,
3557
- result: {
3558
- thread: {
3559
- id: nativeThreadId,
3560
- updatedAt: 1782622450,
3561
- turns: [{ type: "unknown-history-item" }],
3562
- },
3563
- },
3564
- },
3651
+ frame: {
3652
+ id: 5,
3653
+ result: {
3654
+ thread: {
3655
+ id: nativeThreadId,
3656
+ updatedAt: 1782622450,
3657
+ turns: [{ type: "unknown-history-item" }],
3658
+ },
3659
+ },
3660
+ },
3661
},
3566
- );
3567
- }
3568
- const harness = yield* makeCodexReplayHarness(
3569
- makeCodexReplayTranscript({ scenario: name, entries }),
3570
- );
3571
- const resume = harness.runtime.resumeThread({
3572
- providerThread: harness.providerThread,
3573
- modelSelection: CODEX_TEST_MODEL_SELECTION,
3574
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3575
- });
3576
- if (failAt !== 0) {
3577
- const error = yield* Effect.flip(resume);
3578
- assert.equal(error._tag, "ProviderAdapterResumeThreadError");
3579
- assert.nestedPropertyVal(error, "cause.errorMessage", finalError);
3580
- assert.nestedPropertyVal(
3581
- error,
3582
- "cause.method",
3583
- failAt === 4 ? "thread/unarchive" : "thread/resume",
3584
- );
3585
- assert.nestedPropertyVal(error, "cause.requestId", String(failAt));
3586
- return;
3587
- }
3588
- const resumed = yield* resume;
3589
- assert.equal(resumed.id, harness.providerThread.id);
3590
- assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3591
- assert.deepEqual(
3592
- resumed.nativeConversationHeadRef,
3593
- harness.providerThread.nativeConversationHeadRef,
3594
- );
3595
- assert.equal(resumed.status, "idle");
3596
- assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000);
3597
- }).pipe(
3598
- Effect.provide(
3599
- Layer.mergeAll(
3600
- IdAllocator.layer,
3601
- McpProviderSessions.layer,
3602
- NodeServices.layer,
3603
- NodeCrypto.layer,
3604
- ),
3662
+ ],
3663
+ }),
3664
+ );
3665
+ yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
3666
+ const resumed = yield* harness.runtime.resumeThread({
3667
+ providerThread: harness.providerThread,
3668
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
3669
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3670
+ });
3671
+ assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3672
+ assert.equal(resumed.status, "idle");
3673
+ }).pipe(
3674
+ Effect.provide(
3675
+ Layer.mergeAll(
3676
+ IdAllocator.layer,
3677
+ McpProviderSessions.layer,
3678
+ NodeServices.layer,
3679
+ NodeCrypto.layer,
3680
),
3681
),
3682
),
3683
);
3684
3610
- // regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing
3685
it.effect.each([
3612
- { name: "waits for thread/closed after a closing error", closedFirst: false },
3613
- { name: "retries at once when the thread already closed", closedFirst: true },
3614
- ])("$name", ({ name, closedFirst }) =>
3615
- Effect.scoped(
3616
- Effect.gen(function* () {
3617
- const nativeThreadId = "closing-thread";
3618
- const params = {
3619
- threadId: nativeThreadId,
3620
- excludeTurns: true,
3621
- cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3622
- model: CODEX_TEST_MODEL_SELECTION.model,
3623
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3624
- };
3625
- const closed: CodexReplay.CodexAppServerReplayEntry = {
3686
+ "recover",
3687
+ "completion-only",
3688
+ "exhaust",
3689
+ "stop",
3690
+ "stop-continued",
3691
+ "stop-starting",
3692
+ "started-first",
3693
+ "completed-first",
3694
+ "new-run",
3695
+ "steer",
3696
+ "start-fails",
3697
+ ] as const)("handles terminal Codex capacity failures when retries %s", (outcome) =>
3698
+ Effect.gen(function* () {
3699
+ const scenario = `capacity-${outcome}`;
3700
+ const nativeThreadId = `native-${scenario}`;
3701
+ const nativeTurnId = (attempt: number) => `${nativeThreadId}-${attempt}`;
3702
+ const prompt = "Continue the task.";
3703
+ const capacityError = {
3704
+ message: "Selected model is at capacity. Please try a different model.",
3705
+ codexErrorInfo: "serverOverloaded",
3706
+ };
3707
+ const failureEntries = (attempt: number): Array<CodexReplay.CodexAppServerReplayEntry> => [
3708
+ {
3709
type: "emit_inbound",
3627
- label: "thread closed",
3628
- frame: { method: "thread/closed", params: { threadId: nativeThreadId } },
3629
- };
3630
- const closingError: CodexReplay.CodexAppServerReplayEntry = {
3710
+ frame: {
3711
+ method: "error",
3712
+ params: {
3713
+ threadId: nativeThreadId,
3714
+ turnId: nativeTurnId(attempt),
3715
+ willRetry: false,
3716
+ error: capacityError,
3717
+ },
3718
+ },
3719
+ },
3720
+ {
3721
type: "emit_inbound",
3632
- label: "resume closing error",
3722
frame: {
3634
- id: 4,
3635
- error: {
3636
- code: -32600,
3637
- message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`,
3723
+ method: "turn/completed",
3724
+ params: {
3725
+ threadId: nativeThreadId,
3726
+ turn: {
3727
+ ...makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "failed" }),
3728
+ error: capacityError,
3729
+ },
3730
},
3731
},
3640
- };
3641
- const harness = yield* makeCodexReplayHarness(
3642
- makeCodexReplayTranscript({
3643
- scenario: name,
3644
- entries: [
3645
- ...codexReplayPreamble({
3646
- nativeThreadId,
3647
- nativeTurnId: "unused-turn",
3648
- prompt: "unused-prompt",
3649
- }).slice(0, 5),
3650
- {
3651
- type: "expect_outbound",
3652
- label: "unsubscribe",
3653
- frame: {
3654
- id: 3,
3655
- method: "thread/unsubscribe",
3656
- params: { threadId: nativeThreadId },
3657
- },
3658
- },
3659
- {
3660
- type: "emit_inbound",
3661
- label: "unsubscribe result",
3662
- frame: { id: 3, result: { status: "unsubscribed" } },
3663
- },
3664
- {
3665
- type: "expect_outbound",
3666
- label: "resume closing thread",
3667
- frame: { id: 4, method: "thread/resume", params },
3668
- },
3669
- ...(closedFirst ? [closed, closingError] : [closingError, closed]),
3670
- {
3671
- type: "expect_outbound",
3672
- label: "retry identical resume",
3673
- frame: { id: 5, method: "thread/resume", params },
3674
- },
3675
- {
3676
- type: "emit_inbound",
3677
- label: "retry result",
3678
- frame: {
3679
- id: 5,
3680
- result: {
3681
- thread: {
3682
- id: nativeThreadId,
3683
- updatedAt: 1782622450,
3684
- turns: [{ type: "unknown-history-item" }],
3685
- },
3686
- },
3687
- },
3688
- },
3689
- ],
3690
- }),
3691
- );
3692
- yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
3693
- const resumed = yield* harness.runtime.resumeThread({
3694
- providerThread: harness.providerThread,
3695
- modelSelection: CODEX_TEST_MODEL_SELECTION,
3696
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3697
- });
3698
- assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3699
- assert.equal(resumed.status, "idle");
3700
- }).pipe(
3701
- Effect.provide(
3702
- Layer.mergeAll(
3703
- IdAllocator.layer,
3704
- McpProviderSessions.layer,
3705
- NodeServices.layer,
3706
- NodeCrypto.layer,
3707
- ),
3708
- ),
3709
- ),
3710
- ),
3711
- );
3712
-
3713
- it.effect.each([
3714
- "recover",
3715
- "completion-only",
3716
- "exhaust",
3717
- "stop",
3718
- "stop-continued",
3719
- "stop-starting",
3720
- "started-first",
3721
- "completed-first",
3722
- "new-run",
3723
- "steer",
3724
- "start-fails",
3725
- ] as const)("handles terminal Codex capacity failures when retries %s", (outcome) =>
3726
- Effect.scoped(
3727
- Effect.gen(function* () {
3728
- const scenario = `capacity-${outcome}`;
3729
- const nativeThreadId = `native-${scenario}`;
3730
- const nativeTurnId = (attempt: number) => `${nativeThreadId}-${attempt}`;
3731
- const prompt = "Continue the task.";
3732
- const capacityError = {
3733
- message: "Selected model is at capacity. Please try a different model.",
3734
- codexErrorInfo: "serverOverloaded",
3735
- };
3736
- const failureEntries = (attempt: number): Array<CodexReplay.CodexAppServerReplayEntry> => [
3737
- {
3738
- type: "emit_inbound",
3739
- frame: {
3740
- method: "error",
3741
- params: {
3742
- threadId: nativeThreadId,
3743
- turnId: nativeTurnId(attempt),
3744
- willRetry: false,
3745
- error: capacityError,
3746
- },
3747
- },
3748
- },
3749
- {
3750
- type: "emit_inbound",
3751
- frame: {
3752
- method: "turn/completed",
3753
- params: {
3754
- threadId: nativeThreadId,
3755
- turn: {
3756
- ...makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "failed" }),
3757
- error: capacityError,
3758
- },
3759
- },
3760
- },
3761
- },
3762
- ];
3763
- const entries = codexReplayPreamble({
3732
+ },
3733
+ ];
3734
+ const entries = codexReplayPreamble({
3735
+ nativeThreadId,
3736
+ nativeTurnId: nativeTurnId(0),
3737
+ prompt,
3738
+ });
3739
+ entries.push(
3740
+ ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)),
3741
+ );
3742
+ if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1));
3743
+ const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1;
3744
+ const steeredText = "Use the smaller change.";
3745
+ for (let attempt = 1; attempt <= retries; attempt++) {
3746
+ const start = codexReplayPreamble({
3747
nativeThreadId,
3765
- nativeTurnId: nativeTurnId(0),
3748
+ nativeTurnId: nativeTurnId(attempt),
3749
prompt,
3767
- });
3768
- entries.push(
3769
- ...(outcome === "completion-only" ? failureEntries(0).slice(1) : failureEntries(0)),
3770
- );
3771
- if (outcome === "completion-only") entries.push(...failureEntries(0).slice(1));
3772
- const retries = outcome === "exhaust" ? 5 : outcome === "stop" ? 0 : 1;
3773
- const steeredText = "Use the smaller change.";
3774
- for (let attempt = 1; attempt <= retries; attempt++) {
3775
- const start = codexReplayPreamble({
3776
- nativeThreadId,
3777
- nativeTurnId: nativeTurnId(attempt),
3778
- prompt,
3779
- }).slice(-3);
3780
- if (
3781
- outcome === "started-first" ||
3782
- outcome === "stop-starting" ||
3783
- outcome === "completed-first" ||
3784
- outcome === "new-run"
3785
- ) {
3786
- start.splice(1, 0, ...start.splice(2, 1));
3787
- }
3788
- for (const entry of start) {
3789
- if (entry.type === "expect_outbound") {
3750
+ }).slice(-3);
3751
+ if (
3752
+ outcome === "started-first" ||
3753
+ outcome === "stop-starting" ||
3754
+ outcome === "completed-first" ||
3755
+ outcome === "new-run"
3756
+ ) {
3757
+ start.splice(1, 0, ...start.splice(2, 1));
3758
+ }
3759
+ for (const entry of start) {
3760
+ if (entry.type === "expect_outbound") {
3761
+ entries.push({
3762
+ ...entry,
3763
+ frame: {
3764
+ id: 3 + attempt,
3765
+ method: "turn/start",
3766
+ params: {
3767
+ threadId: nativeThreadId,
3768
+ input: [],
3769
+ cwd: "/workspace",
3770
+ model: "gpt-5.4",
3771
+ approvalPolicy: "never",
3772
+ approvalsReviewer: "user",
3773
+ sandboxPolicy: { type: "dangerFullAccess" },
3774
+ summary: "auto",
3775
+ collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
3776
+ },
3777
+ },
3778
+ });
3779
+ } else if (entry.type === "emit_inbound" && entry.label === "turn/start") {
3780
+ if (outcome === "completed-first" || outcome === "new-run")
3781
entries.push({
3791
- ...entry,
3782
+ type: "emit_inbound",
3783
frame: {
3793
- id: 3 + attempt,
3794
- method: "turn/start",
3784
+ method: "turn/completed",
3785
params: {
3786
threadId: nativeThreadId,
3797
- input: [],
3798
- cwd: "/workspace",
3799
- model: "gpt-5.4",
3800
- approvalPolicy: "never",
3801
- approvalsReviewer: "user",
3802
- sandboxPolicy: { type: "dangerFullAccess" },
3803
- summary: "auto",
3804
- collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } },
3787
+ turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "completed" }),
3788
},
3789
},
3790
});
3808
- } else if (entry.type === "emit_inbound" && entry.label === "turn/start") {
3809
- if (outcome === "completed-first" || outcome === "new-run")
3810
- entries.push({
3811
- type: "emit_inbound",
3812
- frame: {
3813
- method: "turn/completed",
3814
- params: {
3815
- threadId: nativeThreadId,
3816
- turn: makeCodexReplayTurn({ id: nativeTurnId(attempt), status: "completed" }),
3817
- },
3818
- },
3819
- });
3820
- if (outcome === "new-run") {
3821
- entries.push(
3822
- ...codexReplayPreamble({
3823
- nativeThreadId,
3824
- nativeTurnId: nativeTurnId(2),
3825
- prompt: "Next task.",
3826
- })
3827
- .slice(-3)
3828
- .map((next, index) => (index < 2 ? withReplayRequestId(next, 5) : next)),
3829
- ...failureEntries(2),
3830
- );
3831
- }
3791
+ if (outcome === "new-run") {
3792
entries.push(
3833
- outcome === "start-fails"
3834
- ? {
3835
- type: "emit_inbound",
3836
- frame: {
3837
- id: 3 + attempt,
3838
- error: { code: -32603, message: "Start failed" },
3839
- },
3840
- }
3841
- : withReplayRequestId(entry, 3 + attempt),
3842
- );
3843
- } else if (outcome !== "start-fails") {
3844
- entries.push(
3845
- outcome === "stop-starting" && entry.type === "emit_inbound"
3846
- ? { ...entry, afterMs: 1_000 }
3847
- : entry,
3793
+ ...codexReplayPreamble({
3794
+ nativeThreadId,
3795
+ nativeTurnId: nativeTurnId(2),
3796
+ prompt: "Next task.",
3797
+ })
3798
+ .slice(-3)
3799
+ .map((next, index) => (index < 2 ? withReplayRequestId(next, 5) : next)),
3800
+ ...failureEntries(2),
3801
);
3849
- if (outcome === "stop-starting") {
3850
- entries.push(
3851
- {
3852
- type: "expect_outbound",
3802
+ }
3803
+ entries.push(
3804
+ outcome === "start-fails"
3805
+ ? {
3806
+ type: "emit_inbound",
3807
frame: {
3854
- id: 5,
3855
- method: "turn/interrupt",
3856
- params: { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
3808
+ id: 3 + attempt,
3809
+ error: { code: -32603, message: "Start failed" },
3810
},
3811
+ }
3812
+ : withReplayRequestId(entry, 3 + attempt),
3813
+ );
3814
+ } else if (outcome !== "start-fails") {
3815
+ entries.push(
3816
+ outcome === "stop-starting" && entry.type === "emit_inbound"
3817
+ ? { ...entry, afterMs: 1_000 }
3818
+ : entry,
3819
+ );
3820
+ if (outcome === "stop-starting") {
3821
+ entries.push(
3822
+ {
3823
+ type: "expect_outbound",
3824
+ frame: {
3825
+ id: 5,
3826
+ method: "turn/interrupt",
3827
+ params: { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
3828
},
3859
- { type: "emit_inbound", frame: { id: 5, result: {} } },
3860
- );
3861
- }
3829
+ },
3830
+ { type: "emit_inbound", frame: { id: 5, result: {} } },
3831
+ );
3832
}
3833
}
3864
- if (outcome === "exhaust") entries.push(...failureEntries(attempt));
3865
- if (
3866
- outcome === "recover" ||
3867
- outcome === "completion-only" ||
3868
- outcome === "started-first" ||
3869
- outcome === "stop-starting"
3870
- ) {
3871
- entries.push({
3834
+ }
3835
+ if (outcome === "exhaust") entries.push(...failureEntries(attempt));
3836
+ if (
3837
+ outcome === "recover" ||
3838
+ outcome === "completion-only" ||
3839
+ outcome === "started-first" ||
3840
+ outcome === "stop-starting"
3841
+ ) {
3842
+ entries.push({
3843
+ type: "emit_inbound",
3844
+ frame: {
3845
+ method: "turn/completed",
3846
+ params: {
3847
+ threadId: nativeThreadId,
3848
+ turn: makeCodexReplayTurn({
3849
+ id: nativeTurnId(attempt),
3850
+ status: outcome === "stop-starting" ? "interrupted" : "completed",
3851
+ }),
3852
+ },
3853
+ },
3854
+ });
3855
+ }
3856
+ if (outcome === "stop-continued" || outcome === "steer") {
3857
+ const steering = outcome === "steer";
3858
+ entries.push(
3859
+ {
3860
+ type: "expect_outbound",
3861
+ frame: {
3862
+ id: 5,
3863
+ method: steering ? "turn/steer" : "turn/interrupt",
3864
+ params: steering
3865
+ ? {
3866
+ threadId: nativeThreadId,
3867
+ expectedTurnId: nativeTurnId(attempt),
3868
+ input: [{ type: "text", text: steeredText }],
3869
+ }
3870
+ : { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
3871
+ },
3872
+ },
3873
+ {
3874
+ type: "emit_inbound",
3875
+ frame: { id: 5, result: steering ? { turnId: nativeTurnId(attempt) } : {} },
3876
+ },
3877
+ {
3878
type: "emit_inbound",
3879
frame: {
3880
method: "turn/completed",
@@ -3876,565 +3882,681 @@ describe("CodexAdapterV2 post-settle continuation", () => {
3882
threadId: nativeThreadId,
3883
turn: makeCodexReplayTurn({
3884
id: nativeTurnId(attempt),
3879
- status: outcome === "stop-starting" ? "interrupted" : "completed",
3885
+ status: steering ? "completed" : "interrupted",
3886
}),
3887
},
3888
},
3883
- });
3884
- }
3885
- if (outcome === "stop-continued" || outcome === "steer") {
3886
- const steering = outcome === "steer";
3887
- entries.push(
3888
- {
3889
- type: "expect_outbound",
3890
- frame: {
3891
- id: 5,
3892
- method: steering ? "turn/steer" : "turn/interrupt",
3893
- params: steering
3894
- ? {
3895
- threadId: nativeThreadId,
3896
- expectedTurnId: nativeTurnId(attempt),
3897
- input: [{ type: "text", text: steeredText }],
3898
- }
3899
- : { threadId: nativeThreadId, turnId: nativeTurnId(attempt) },
3900
- },
3901
- },
3902
- {
3903
- type: "emit_inbound",
3904
- frame: { id: 5, result: steering ? { turnId: nativeTurnId(attempt) } : {} },
3905
- },
3906
- {
3907
- type: "emit_inbound",
3908
- frame: {
3909
- method: "turn/completed",
3910
- params: {
3911
- threadId: nativeThreadId,
3912
- turn: makeCodexReplayTurn({
3913
- id: nativeTurnId(attempt),
3914
- status: steering ? "completed" : "interrupted",
3915
- }),
3916
- },
3917
- },
3918
- },
3919
- );
3920
- }
3889
+ },
3890
+ );
3891
}
3922
- const milestones = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3923
- const starts: Array<unknown> = [];
3924
- const retryStarted = yield* Deferred.make<void>();
3925
- const harness = yield* makeCodexReplayHarness(
3926
- makeCodexReplayTranscript({ scenario, entries }),
3927
- (event) =>
3928
- event.type === "turn.terminal" ||
3929
- (event.type === "turn_item.updated" &&
3930
- event.turnItem.type === "error" &&
3931
- event.turnItem.status === "running")
3932
- ? Queue.offer(milestones, event)
3933
- : Effect.void,
3934
- (method, params) =>
3935
- Effect.gen(function* () {
3936
- if (method === "turn/start") {
3937
- starts.push(params);
3938
- if (starts.length === 2) yield* Deferred.succeed(retryStarted, undefined);
3939
- }
3940
- }),
3941
- );
3942
- const turnInput = makeCodexTestTurnInput({
3943
- threadId: harness.threadId,
3944
- providerThread: harness.providerThread,
3945
- now: yield* DateTime.now,
3946
- attemptId: RunAttemptId.make(scenario),
3947
- text: prompt,
3892
+ }
3893
+ const milestones = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
3894
+ const starts: Array<unknown> = [];
3895
+ const retryStarted = yield* Deferred.make<void>();
3896
+ const harness = yield* makeCodexReplayHarness(
3897
+ makeCodexReplayTranscript({ scenario, entries }),
3898
+ (event) =>
3899
+ event.type === "turn.terminal" ||
3900
+ (event.type === "turn_item.updated" &&
3901
+ event.turnItem.type === "error" &&
3902
+ event.turnItem.status === "running")
3903
+ ? Queue.offer(milestones, event)
3904
+ : Effect.void,
3905
+ (method, params) =>
3906
+ Effect.gen(function* () {
3907
+ if (method === "turn/start") {
3908
+ starts.push(params);
3909
+ if (starts.length === 2) yield* Deferred.succeed(retryStarted, undefined);
3910
+ }
3911
+ }),
3912
+ );
3913
+ const turnInput = makeCodexTestTurnInput({
3914
+ threadId: harness.threadId,
3915
+ providerThread: harness.providerThread,
3916
+ now: yield* DateTime.now,
3917
+ attemptId: RunAttemptId.make(scenario),
3918
+ text: prompt,
3919
+ });
3920
+ yield* harness.runtime.startTurn(turnInput);
3921
+ for (let attempt = 1; attempt <= Math.max(retries, 1); attempt++) {
3922
+ const milestone = yield* Queue.take(milestones);
3923
+ assert.equal(milestone.type, "turn_item.updated");
3924
+ if (milestone.type !== "turn_item.updated" || milestone.turnItem.type !== "error") return;
3925
+ const providerTurnId = milestone.turnItem.providerTurnId;
3926
+ assert.isNotNull(providerTurnId);
3927
+ if (providerTurnId === null) return;
3928
+ assert.deepEqual(milestone.turnItem.retry, {
3929
+ attempt,
3930
+ maxAttempts: 5,
3931
+ retryDelayMs: Math.min(2_000 * 2 ** (attempt - 1), 30_000),
3932
});
3949
- yield* harness.runtime.startTurn(turnInput);
3950
- for (let attempt = 1; attempt <= Math.max(retries, 1); attempt++) {
3951
- const milestone = yield* Queue.take(milestones);
3952
- assert.equal(milestone.type, "turn_item.updated");
3953
- if (milestone.type !== "turn_item.updated" || milestone.turnItem.type !== "error") return;
3954
- const providerTurnId = milestone.turnItem.providerTurnId;
3955
- assert.isNotNull(providerTurnId);
3956
- if (providerTurnId === null) return;
3957
- assert.deepEqual(milestone.turnItem.retry, {
3958
- attempt,
3959
- maxAttempts: 5,
3960
- retryDelayMs: Math.min(2_000 * 2 ** (attempt - 1), 30_000),
3933
+ assert.isEmpty(harness.terminalEvents());
3934
+ if (outcome === "stop") {
3935
+ yield* harness.runtime.interruptTurn({
3936
+ providerThread: harness.providerThread,
3937
+ providerTurnId,
3938
});
3962
- assert.isEmpty(harness.terminalEvents());
3963
- if (outcome === "stop") {
3964
- yield* harness.runtime.interruptTurn({
3965
- providerThread: harness.providerThread,
3966
- providerTurnId,
3967
- });
3968
- }
3969
- const steering =
3970
- outcome === "steer"
3971
- ? yield* harness.runtime
3972
- .steerTurn({
3973
- ...turnInput,
3974
- providerTurnId,
3975
- message: { ...turnInput.message, text: steeredText },
3976
- })
3977
- .pipe(Effect.forkScoped)
3978
- : undefined;
3979
- yield* TestClock.adjust(Math.min(2_000 * 2 ** (attempt - 1), 30_000));
3980
- if (outcome === "stop-starting") {
3981
- yield* Deferred.await(retryStarted);
3982
- const stopping = yield* harness.runtime
3983
- .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
3984
- .pipe(Effect.forkScoped);
3985
- yield* TestClock.adjust("1 second");
3986
- yield* Fiber.join(stopping);
3987
- }
3988
- if (steering !== undefined) yield* Fiber.join(steering);
3989
- if (outcome === "stop-continued") {
3990
- yield* harness.until(() =>
3991
- harness.events.some(
3992
- (event) =>
3993
- event.type === "provider_turn.updated" &&
3994
- event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId(1),
3995
- ),
3996
- );
3997
- yield* harness.runtime.interruptTurn({
3998
- providerThread: harness.providerThread,
3999
- providerTurnId,
4000
- });
4001
- }
3939
}
4003
- yield* harness.awaitTerminal(1);
4004
- if (outcome === "new-run") {
4005
- assert.equal((yield* Queue.take(milestones)).type, "turn.terminal");
4006
- yield* harness.runtime.startTurn({
4007
- ...turnInput,
4008
- attemptId: RunAttemptId.make("capacity-next-task"),
4009
- message: { ...turnInput.message, text: "Next task." },
3940
+ const steering =
3941
+ outcome === "steer"
3942
+ ? yield* harness.runtime
3943
+ .steerTurn({
3944
+ ...turnInput,
3945
+ providerTurnId,
3946
+ message: { ...turnInput.message, text: steeredText },
3947
+ })
3948
+ .pipe(Effect.forkScoped)
3949
+ : undefined;
3950
+ yield* TestClock.adjust(Math.min(2_000 * 2 ** (attempt - 1), 30_000));
3951
+ if (outcome === "stop-starting") {
3952
+ yield* Deferred.await(retryStarted);
3953
+ const stopping = yield* harness.runtime
3954
+ .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
3955
+ .pipe(Effect.forkScoped);
3956
+ yield* TestClock.adjust("1 second");
3957
+ yield* Fiber.join(stopping);
3958
+ }
3959
+ if (steering !== undefined) yield* Fiber.join(steering);
3960
+ if (outcome === "stop-continued") {
3961
+ yield* harness.until(() =>
3962
+ harness.events.some(
3963
+ (event) =>
3964
+ event.type === "provider_turn.updated" &&
3965
+ event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId(1),
3966
+ ),
3967
+ );
3968
+ yield* harness.runtime.interruptTurn({
3969
+ providerThread: harness.providerThread,
3970
+ providerTurnId,
3971
});
4011
- const nextRetry = yield* Queue.take(milestones);
4012
- assert.equal(nextRetry.type, "turn_item.updated");
4013
- if (nextRetry.type !== "turn_item.updated" || nextRetry.turnItem.type !== "error") return;
4014
- assert.equal(nextRetry.turnItem.retry?.attempt, 1);
4015
- return;
3972
}
4017
- const terminal = harness.terminalEvents()[0];
4018
- assert.equal(
4019
- terminal?.status,
4020
- outcome === "recover" ||
4021
- outcome === "completion-only" ||
4022
- outcome === "steer" ||
4023
- outcome === "started-first" ||
4024
- outcome === "completed-first"
4025
- ? "completed"
4026
- : outcome === "stop" || outcome === "stop-continued" || outcome === "stop-starting"
4027
- ? "interrupted"
4028
- : "failed",
4029
- );
4030
- assert.lengthOf(starts, 1 + retries);
4031
- assert.lengthOf(harness.terminalEvents(), 1);
4032
- assert.lengthOf(
4033
- harness.events.filter(
4034
- (event) =>
4035
- event.type === "provider_turn.updated" && event.providerTurn.status === "running",
4036
- ),
4037
- outcome === "start-fails" ? 1 : 1 + retries,
4038
- );
4039
- const retryItems = harness.events.flatMap((event) =>
4040
- event.type === "turn_item.updated" && event.turnItem.type === "error"
4041
- ? [event.turnItem]
4042
- : [],
4043
- );
4044
- assert.isTrue(
4045
- ["completed", "failed", "interrupted"].includes(retryItems.at(-1)?.status ?? ""),
4046
- );
4047
- assert.lengthOf(new Set(retryItems.map((item) => item.id)), 1);
3973
+ }
3974
+ yield* harness.awaitTerminal(1);
3975
+ if (outcome === "new-run") {
3976
+ assert.equal((yield* Queue.take(milestones)).type, "turn.terminal");
3977
+ yield* harness.runtime.startTurn({
3978
+ ...turnInput,
3979
+ attemptId: RunAttemptId.make("capacity-next-task"),
3980
+ message: { ...turnInput.message, text: "Next task." },
3981
+ });
3982
+ const nextRetry = yield* Queue.take(milestones);
3983
+ assert.equal(nextRetry.type, "turn_item.updated");
3984
+ if (nextRetry.type !== "turn_item.updated" || nextRetry.turnItem.type !== "error") return;
3985
+ assert.equal(nextRetry.turnItem.retry?.attempt, 1);
3986
+ return;
3987
+ }
3988
+ const terminal = harness.terminalEvents()[0];
3989
+ assert.equal(
3990
+ terminal?.status,
3991
+ outcome === "recover" ||
3992
+ outcome === "completion-only" ||
3993
+ outcome === "steer" ||
3994
+ outcome === "started-first" ||
3995
+ outcome === "completed-first"
3996
+ ? "completed"
3997
+ : outcome === "stop" || outcome === "stop-continued" || outcome === "stop-starting"
3998
+ ? "interrupted"
3999
+ : "failed",
4000
+ );
4001
+ assert.lengthOf(starts, 1 + retries);
4002
+ assert.lengthOf(harness.terminalEvents(), 1);
4003
+ assert.lengthOf(
4004
+ harness.events.filter(
4005
+ (event) =>
4006
+ event.type === "provider_turn.updated" && event.providerTurn.status === "running",
4007
+ ),
4008
+ outcome === "start-fails" ? 1 : 1 + retries,
4009
+ );
4010
+ const retryItems = harness.events.flatMap((event) =>
4011
+ event.type === "turn_item.updated" && event.turnItem.type === "error"
4012
+ ? [event.turnItem]
4013
+ : [],
4014
+ );
4015
+ assert.isTrue(
4016
+ ["completed", "failed", "interrupted"].includes(retryItems.at(-1)?.status ?? ""),
4017
+ );
4018
+ assert.lengthOf(new Set(retryItems.map((item) => item.id)), 1);
4019
4049
- if (outcome === "recover") {
4050
- const fs = yield* FileSystem.FileSystem;
4051
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-capacity-retry-" });
4052
- const localTranscript = yield* decodeReplayTranscriptJson(
4053
- (yield* encodeReplayTranscriptJson(
4054
- makeCodexReplayTranscript({ scenario, entries }),
4055
- )).replaceAll(yield* encodeStringJson("/workspace"), yield* encodeStringJson(cwd)),
4020
+ if (outcome === "recover") {
4021
+ const fs = yield* FileSystem.FileSystem;
4022
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-capacity-retry-" });
4023
+ const localTranscript = yield* decodeReplayTranscriptJson(
4024
+ (yield* encodeReplayTranscriptJson(
4025
+ makeCodexReplayTranscript({ scenario, entries }),
4026
+ )).replaceAll(yield* encodeStringJson("/workspace"), yield* encodeStringJson(cwd)),
4027
+ );
4028
+ const driver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript));
4029
+ yield* Effect.gen(function* () {
4030
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4031
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4032
+ const threadId = ThreadId.make("thread:capacity-retry");
4033
+ yield* orchestrator.dispatch({
4034
+ type: "thread.create",
4035
+ commandId: CommandId.make("create-capacity-retry"),
4036
+ threadId,
4037
+ projectId: ProjectId.make("project:capacity-retry"),
4038
+ title: "Capacity retry",
4039
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
4040
+ runtimeMode: "full-access",
4041
+ interactionMode: "default",
4042
+ branch: null,
4043
+ worktreePath: cwd,
4044
+ createdBy: "user",
4045
+ creationSource: "web",
4046
+ });
4047
+ const retrying = yield* orchestrator.streamDomainEvents.pipe(
4048
+ Stream.filter(
4049
+ (event) =>
4050
+ event.type === "turn-item.updated" &&
4051
+ event.payload.type === "error" &&
4052
+ event.payload.retry != null &&
4053
+ event.payload.status === "running",
4054
+ ),
4055
+ Stream.runHead,
4056
+ Effect.forkChild({ startImmediately: true }),
4057
);
4057
- const driver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript));
4058
- yield* Effect.gen(function* () {
4059
- const orchestrator = yield* Orchestrator.OrchestratorV2;
4060
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4061
- const threadId = ThreadId.make("thread:capacity-retry");
4062
- yield* orchestrator.dispatch({
4063
- type: "thread.create",
4064
- commandId: CommandId.make("create-capacity-retry"),
4065
- threadId,
4066
- projectId: ProjectId.make("project:capacity-retry"),
4067
- title: "Capacity retry",
4068
- modelSelection: CODEX_TEST_MODEL_SELECTION,
4069
- runtimeMode: "full-access",
4070
- interactionMode: "default",
4071
- branch: null,
4072
- worktreePath: cwd,
4073
- createdBy: "user",
4074
- creationSource: "web",
4075
- });
4076
- const retrying = yield* orchestrator.streamDomainEvents.pipe(
4077
- Stream.filter(
4078
- (event) =>
4079
- event.type === "turn-item.updated" &&
4080
- event.payload.type === "error" &&
4081
- event.payload.retry != null &&
4082
- event.payload.status === "running",
4083
- ),
4084
- Stream.runHead,
4085
- Effect.forkChild({ startImmediately: true }),
4086
- );
4087
- yield* orchestrator.dispatch({
4088
- type: "message.dispatch",
4089
- commandId: CommandId.make("start-capacity-retry"),
4090
- threadId,
4091
- messageId: MessageId.make("message:capacity-retry"),
4092
- text: prompt,
4093
- attachments: [],
4094
- createdBy: "user",
4095
- creationSource: "web",
4096
- dispatchMode: { type: "start_immediately" },
4097
- });
4098
- yield* worker.drain();
4099
- yield* Fiber.join(retrying);
4100
- assert.equal(
4101
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
4102
- "running",
4103
- );
4104
- const completed = yield* orchestrator.streamDomainEvents.pipe(
4105
- Stream.filter(
4106
- (event) => event.type === "run.updated" && event.payload.status === "waiting",
4107
- ),
4108
- Stream.runHead,
4109
- Effect.forkChild({ startImmediately: true }),
4110
- );
4111
- yield* TestClock.adjust("2 seconds");
4112
- yield* Fiber.join(completed);
4113
- yield* worker.drain();
4114
- const projection = yield* orchestrator.getThreadProjection(threadId);
4115
- assert.equal(projection.runs.at(-1)?.status, "completed");
4116
- assert.deepEqual(
4117
- projection.providerTurns.map((turn) => turn.status),
4118
- ["failed", "completed"],
4119
- );
4120
- assert.lengthOf(
4121
- projection.messages.filter((message) => message.role === "user"),
4122
- 1,
4123
- );
4124
- assert.isNull((yield* Ref.get(driver.state)).failure);
4125
- }).pipe(
4126
- Effect.provide(
4127
- ProviderReplayHarness.layerWithRegistry(
4128
- { name: "codex-capacity-retry", runtimePolicyOverride: { cwd } },
4129
- CodexAdapterV2Testkit.layer({ transcript: localTranscript, driver }),
4130
- { runEffectWorker: false },
4131
- ),
4058
+ yield* orchestrator.dispatch({
4059
+ type: "message.dispatch",
4060
+ commandId: CommandId.make("start-capacity-retry"),
4061
+ threadId,
4062
+ messageId: MessageId.make("message:capacity-retry"),
4063
+ text: prompt,
4064
+ attachments: [],
4065
+ createdBy: "user",
4066
+ creationSource: "web",
4067
+ dispatchMode: { type: "start_immediately" },
4068
+ });
4069
+ yield* worker.drain();
4070
+ yield* Fiber.join(retrying);
4071
+ assert.equal(
4072
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
4073
+ "running",
4074
+ );
4075
+ const completed = yield* orchestrator.streamDomainEvents.pipe(
4076
+ Stream.filter(
4077
+ (event) => event.type === "run.updated" && event.payload.status === "waiting",
4078
),
4079
+ Stream.runHead,
4080
+ Effect.forkChild({ startImmediately: true }),
4081
);
4134
- }
4135
- }).pipe(
4136
- Effect.provide(
4137
- Layer.mergeAll(
4138
- IdAllocator.layer,
4139
- McpProviderSessions.layer,
4140
- NodeServices.layer,
4141
- NodeCrypto.layer,
4082
+ yield* TestClock.adjust("2 seconds");
4083
+ yield* Fiber.join(completed);
4084
+ yield* worker.drain();
4085
+ const projection = yield* orchestrator.getThreadProjection(threadId);
4086
+ assert.equal(projection.runs.at(-1)?.status, "completed");
4087
+ assert.deepEqual(
4088
+ projection.providerTurns.map((turn) => turn.status),
4089
+ ["failed", "completed"],
4090
+ );
4091
+ assert.lengthOf(
4092
+ projection.messages.filter((message) => message.role === "user"),
4093
+ 1,
4094
+ );
4095
+ assert.isNull((yield* Ref.get(driver.state)).failure);
4096
+ }).pipe(
4097
+ Effect.provide(
4098
+ ProviderReplayHarness.layerWithRegistry(
4099
+ { name: "codex-capacity-retry", runtimePolicyOverride: { cwd } },
4100
+ CodexAdapterV2Testkit.layer({ transcript: localTranscript, driver }),
4101
+ { runEffectWorker: false },
4102
+ ),
4103
),
4104
+ );
4105
+ }
4106
+ }).pipe(
4107
+ Effect.provide(
4108
+ Layer.mergeAll(
4109
+ IdAllocator.layer,
4110
+ McpProviderSessions.layer,
4111
+ NodeServices.layer,
4112
+ NodeCrypto.layer,
4113
),
4114
),
4115
),
4116
);
4117
4118
it.effect("reports a thread another Codex client is writing to as in use", () =>
4149
- Effect.scoped(
4150
- Effect.gen(function* () {
4151
- const nativeThreadId = "thread-open-elsewhere";
4152
- const harness = yield* makeCodexReplayHarness(
4153
- makeCodexReplayTranscript({
4154
- scenario: "codex-resume-active-writer",
4155
- entries: [
4156
- ...codexReplayPreamble({
4157
- nativeThreadId,
4158
- nativeTurnId: "unused-turn",
4159
- prompt: "unused-prompt",
4160
- }).slice(0, 5),
4161
- {
4162
- type: "expect_outbound",
4163
- label: "thread/resume",
4164
- frame: {
4165
- id: 3,
4166
- method: "thread/resume",
4167
- params: {
4168
- threadId: nativeThreadId,
4169
- excludeTurns: true,
4170
- cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
4171
- model: CODEX_TEST_MODEL_SELECTION.model,
4172
- config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4173
- },
4119
+ Effect.gen(function* () {
4120
+ const nativeThreadId = "thread-open-elsewhere";
4121
+ const harness = yield* makeCodexReplayHarness(
4122
+ makeCodexReplayTranscript({
4123
+ scenario: "codex-resume-active-writer",
4124
+ entries: [
4125
+ ...codexReplayPreamble({
4126
+ nativeThreadId,
4127
+ nativeTurnId: "unused-turn",
4128
+ prompt: "unused-prompt",
4129
+ }).slice(0, 5),
4130
+ {
4131
+ type: "expect_outbound",
4132
+ label: "thread/resume",
4133
+ frame: {
4134
+ id: 3,
4135
+ method: "thread/resume",
4136
+ params: {
4137
+ threadId: nativeThreadId,
4138
+ excludeTurns: true,
4139
+ cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
4140
+ model: CODEX_TEST_MODEL_SELECTION.model,
4141
+ config: CodexAdapterV2.CODEX_THREAD_CONFIG,
4142
},
4143
},
4176
- {
4177
- type: "emit_inbound",
4178
- label: "active writer",
4179
- frame: {
4180
- id: 3,
4181
- error: {
4182
- code: -32600,
4183
- message: `thread ${nativeThreadId} already has an active writer`,
4184
- },
4144
+ },
4145
+ {
4146
+ type: "emit_inbound",
4147
+ label: "active writer",
4148
+ frame: {
4149
+ id: 3,
4150
+ error: {
4151
+ code: -32600,
4152
+ message: `thread ${nativeThreadId} already has an active writer`,
4153
},
4154
},
4187
- ],
4188
- }),
4189
- );
4190
-
4191
- const error = yield* Effect.flip(
4192
- harness.runtime.resumeThread({
4193
- providerThread: harness.providerThread,
4194
- modelSelection: CODEX_TEST_MODEL_SELECTION,
4195
- runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4196
- }),
4197
- );
4155
+ },
4156
+ ],
4157
+ }),
4158
+ );
4159
4199
- assert.equal(error._tag, "ProviderAdapterThreadInUseError");
4200
- assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id);
4201
- assert.include(error.message, "open in another Codex client");
4202
- assert.nestedPropertyVal(
4203
- error,
4204
- "cause.errorMessage",
4205
- `thread ${nativeThreadId} already has an active writer`,
4206
- );
4207
- }).pipe(
4208
- Effect.provide(
4209
- Layer.mergeAll(
4210
- IdAllocator.layer,
4211
- McpProviderSessions.layer,
4212
- NodeServices.layer,
4213
- NodeCrypto.layer,
4214
- ),
4160
+ const error = yield* Effect.flip(
4161
+ harness.runtime.resumeThread({
4162
+ providerThread: harness.providerThread,
4163
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
4164
+ runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
4165
+ }),
4166
+ );
4167
+
4168
+ assert.equal(error._tag, "ProviderAdapterThreadInUseError");
4169
+ assert.nestedPropertyVal(error, "providerThreadId", harness.providerThread.id);
4170
+ assert.include(error.message, "open in another Codex client");
4171
+ assert.nestedPropertyVal(
4172
+ error,
4173
+ "cause.errorMessage",
4174
+ `thread ${nativeThreadId} already has an active writer`,
4175
+ );
4176
+ }).pipe(
4177
+ Effect.provide(
4178
+ Layer.mergeAll(
4179
+ IdAllocator.layer,
4180
+ McpProviderSessions.layer,
4181
+ NodeServices.layer,
4182
+ NodeCrypto.layer,
4183
),
4184
),
4185
),
4186
);
4187
4188
it.effect("resolves retryable app-server errors on resumed provider activity", () =>
4221
- Effect.scoped(
4222
- Effect.gen(function* () {
4223
- const scenario = "codex-provider-api-retry";
4224
- const nativeThreadId = `native-${scenario}-thread`;
4225
- const nativeTurnId = `native-${scenario}-turn`;
4226
- const transcript = makeCodexReplayTranscript({
4227
- scenario,
4228
- entries: [
4229
- ...codexReplayPreamble({
4230
- nativeThreadId,
4231
- nativeTurnId,
4232
- prompt: "Open github.com.",
4233
- }),
4234
- {
4235
- type: "emit_inbound",
4236
- label: "error/retry",
4237
- frame: {
4238
- method: "error",
4239
- params: {
4240
- threadId: nativeThreadId,
4241
- turnId: nativeTurnId,
4242
- willRetry: true,
4243
- error: {
4244
- message: "Reconnecting... 2/5",
4245
- additionalDetails: "The response stream disconnected.",
4246
- codexErrorInfo: {
4247
- responseStreamDisconnected: { httpStatusCode: 529 },
4248
- },
4189
+ Effect.gen(function* () {
4190
+ const scenario = "codex-provider-api-retry";
4191
+ const nativeThreadId = `native-${scenario}-thread`;
4192
+ const nativeTurnId = `native-${scenario}-turn`;
4193
+ const transcript = makeCodexReplayTranscript({
4194
+ scenario,
4195
+ entries: [
4196
+ ...codexReplayPreamble({
4197
+ nativeThreadId,
4198
+ nativeTurnId,
4199
+ prompt: "Open github.com.",
4200
+ }),
4201
+ {
4202
+ type: "emit_inbound",
4203
+ label: "error/retry",
4204
+ frame: {
4205
+ method: "error",
4206
+ params: {
4207
+ threadId: nativeThreadId,
4208
+ turnId: nativeTurnId,
4209
+ willRetry: true,
4210
+ error: {
4211
+ message: "Reconnecting... 2/5",
4212
+ additionalDetails: "The response stream disconnected.",
4213
+ codexErrorInfo: {
4214
+ responseStreamDisconnected: { httpStatusCode: 529 },
4215
},
4216
},
4217
},
4218
},
4253
- {
4254
- type: "emit_inbound",
4255
- label: "error/retry/waiting-for-network",
4256
- frame: {
4257
- method: "error",
4258
- params: {
4259
- threadId: nativeThreadId,
4260
- turnId: nativeTurnId,
4261
- willRetry: true,
4262
- error: {
4263
- message: "Reconnecting... waiting for network",
4264
- additionalDetails: "Connection failed: error sending request",
4265
- codexErrorInfo: {
4266
- responseStreamDisconnected: { httpStatusCode: null },
4267
- },
4219
+ },
4220
+ {
4221
+ type: "emit_inbound",
4222
+ label: "error/retry/waiting-for-network",
4223
+ frame: {
4224
+ method: "error",
4225
+ params: {
4226
+ threadId: nativeThreadId,
4227
+ turnId: nativeTurnId,
4228
+ willRetry: true,
4229
+ error: {
4230
+ message: "Reconnecting... waiting for network",
4231
+ additionalDetails: "Connection failed: error sending request",
4232
+ codexErrorInfo: {
4233
+ responseStreamDisconnected: { httpStatusCode: null },
4234
},
4235
},
4236
},
4237
},
4272
- {
4273
- type: "emit_inbound",
4274
- label: "item/started/after-retry",
4275
- frame: {
4276
- method: "item/started",
4277
- params: {
4278
- threadId: nativeThreadId,
4279
- turnId: nativeTurnId,
4280
- startedAtMs: 1782622445000,
4281
- item: {
4282
- type: "commandExecution",
4283
- id: "command-after-provider-retry",
4284
- command: "pwd",
4285
- cwd: "/workspace",
4286
- processId: "42",
4287
- source: "unifiedExecStartup",
4288
- status: "inProgress",
4289
- commandActions: [{ type: "unknown", command: "pwd" }],
4290
- aggregatedOutput: null,
4291
- exitCode: null,
4292
- durationMs: null,
4293
- },
4238
+ },
4239
+ {
4240
+ type: "emit_inbound",
4241
+ label: "item/started/after-retry",
4242
+ frame: {
4243
+ method: "item/started",
4244
+ params: {
4245
+ threadId: nativeThreadId,
4246
+ turnId: nativeTurnId,
4247
+ startedAtMs: 1782622445000,
4248
+ item: {
4249
+ type: "commandExecution",
4250
+ id: "command-after-provider-retry",
4251
+ command: "pwd",
4252
+ cwd: "/workspace",
4253
+ processId: "42",
4254
+ source: "unifiedExecStartup",
4255
+ status: "inProgress",
4256
+ commandActions: [{ type: "unknown", command: "pwd" }],
4257
+ aggregatedOutput: null,
4258
+ exitCode: null,
4259
+ durationMs: null,
4260
},
4261
},
4262
},
4297
- {
4298
- type: "emit_inbound",
4299
- label: "item/completed/after-retry",
4300
- frame: {
4301
- method: "item/completed",
4302
- params: {
4303
- threadId: nativeThreadId,
4304
- turnId: nativeTurnId,
4305
- completedAtMs: 1782622445010,
4306
- item: {
4307
- type: "commandExecution",
4308
- id: "command-after-provider-retry",
4309
- command: "pwd",
4310
- cwd: "/workspace",
4311
- processId: "42",
4312
- source: "unifiedExecStartup",
4313
- status: "completed",
4314
- commandActions: [{ type: "unknown", command: "pwd" }],
4315
- aggregatedOutput: "/workspace\n",
4316
- exitCode: 0,
4317
- durationMs: 10,
4318
- },
4263
+ },
4264
+ {
4265
+ type: "emit_inbound",
4266
+ label: "item/completed/after-retry",
4267
+ frame: {
4268
+ method: "item/completed",
4269
+ params: {
4270
+ threadId: nativeThreadId,
4271
+ turnId: nativeTurnId,
4272
+ completedAtMs: 1782622445010,
4273
+ item: {
4274
+ type: "commandExecution",
4275
+ id: "command-after-provider-retry",
4276
+ command: "pwd",
4277
+ cwd: "/workspace",
4278
+ processId: "42",
4279
+ source: "unifiedExecStartup",
4280
+ status: "completed",
4281
+ commandActions: [{ type: "unknown", command: "pwd" }],
4282
+ aggregatedOutput: "/workspace\n",
4283
+ exitCode: 0,
4284
+ durationMs: 10,
4285
},
4286
},
4287
},
4322
- {
4323
- type: "emit_inbound",
4324
- label: "turn/completed",
4325
- frame: {
4326
- method: "turn/completed",
4327
- params: {
4328
- threadId: nativeThreadId,
4329
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
4330
- },
4288
+ },
4289
+ {
4290
+ type: "emit_inbound",
4291
+ label: "turn/completed",
4292
+ frame: {
4293
+ method: "turn/completed",
4294
+ params: {
4295
+ threadId: nativeThreadId,
4296
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
4297
},
4298
},
4333
- ],
4334
- });
4335
- const harness = yield* makeCodexReplayHarness(transcript);
4336
- const now = yield* DateTime.now;
4337
- yield* harness.runtime.startTurn(
4338
- makeCodexTestTurnInput({
4339
- threadId: harness.threadId,
4340
- providerThread: harness.providerThread,
4341
- now,
4342
- attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"),
4343
- text: "Open github.com.",
4344
- }),
4345
- );
4346
- yield* harness.awaitTerminal(1);
4299
+ },
4300
+ ],
4301
+ });
4302
+ const harness = yield* makeCodexReplayHarness(transcript);
4303
+ const now = yield* DateTime.now;
4304
+ yield* harness.runtime.startTurn(
4305
+ makeCodexTestTurnInput({
4306
+ threadId: harness.threadId,
4307
+ providerThread: harness.providerThread,
4308
+ now,
4309
+ attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"),
4310
+ text: "Open github.com.",
4311
+ }),
4312
+ );
4313
+ yield* harness.awaitTerminal(1);
4314
+
4315
+ const retryItems = harness.events.flatMap((event) =>
4316
+ event.type === "turn_item.updated" &&
4317
+ event.turnItem.type === "error" &&
4318
+ event.turnItem.retry !== undefined
4319
+ ? [event.turnItem]
4320
+ : [],
4321
+ );
4322
+ assert.lengthOf(retryItems, 3);
4323
+ assert.equal(retryItems[0]?.status, "running");
4324
+ assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected");
4325
+ assert.deepEqual(retryItems[0]?.retry, {
4326
+ attempt: 2,
4327
+ maxAttempts: 5,
4328
+ retryDelayMs: null,
4329
+ });
4330
+ assert.deepEqual(retryItems[1]?.retry, {
4331
+ attempt: 3,
4332
+ maxAttempts: null,
4333
+ retryDelayMs: null,
4334
+ });
4335
+ assert.equal(retryItems[2]?.id, retryItems[0]?.id);
4336
+ assert.equal(retryItems[2]?.status, "completed");
4337
+ assert.equal(retryItems[2]?.title, "Provider recovered");
4338
4348
- const retryItems = harness.events.flatMap((event) =>
4339
+ const recoveredIndex = harness.events.findIndex(
4340
+ (event) =>
4341
event.type === "turn_item.updated" &&
4342
event.turnItem.type === "error" &&
4351
- event.turnItem.retry !== undefined
4352
- ? [event.turnItem]
4353
- : [],
4354
- );
4355
- assert.lengthOf(retryItems, 3);
4356
- assert.equal(retryItems[0]?.status, "running");
4357
- assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected");
4358
- assert.deepEqual(retryItems[0]?.retry, {
4359
- attempt: 2,
4360
- maxAttempts: 5,
4361
- retryDelayMs: null,
4362
- });
4363
- assert.deepEqual(retryItems[1]?.retry, {
4364
- attempt: 3,
4365
- maxAttempts: null,
4366
- retryDelayMs: null,
4367
- });
4368
- assert.equal(retryItems[2]?.id, retryItems[0]?.id);
4369
- assert.equal(retryItems[2]?.status, "completed");
4370
- assert.equal(retryItems[2]?.title, "Provider recovered");
4343
+ event.turnItem.status === "completed",
4344
+ );
4345
+ const resumedCommandIndex = harness.events.findIndex(
4346
+ (event) =>
4347
+ event.type === "turn_item.updated" &&
4348
+ event.turnItem.type === "command_execution" &&
4349
+ event.turnItem.input === "pwd",
4350
+ );
4351
+ const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
4352
+ assert.isAtLeast(recoveredIndex, 0);
4353
+ assert.isAbove(resumedCommandIndex, recoveredIndex);
4354
+ assert.isAbove(terminalIndex, resumedCommandIndex);
4355
+ }).pipe(
4356
+ Effect.provide(
4357
+ Layer.mergeAll(
4358
+ IdAllocator.layer,
4359
+ McpProviderSessions.layer,
4360
+ NodeServices.layer,
4361
+ NodeCrypto.layer,
4362
+ ),
4363
+ ),
4364
+ ),
4365
+ );
4366
4372
- const recoveredIndex = harness.events.findIndex(
4373
- (event) =>
4374
- event.type === "turn_item.updated" &&
4375
- event.turnItem.type === "error" &&
4376
- event.turnItem.status === "completed",
4377
- );
4378
- const resumedCommandIndex = harness.events.findIndex(
4379
- (event) =>
4380
- event.type === "turn_item.updated" &&
4381
- event.turnItem.type === "command_execution" &&
4382
- event.turnItem.input === "pwd",
4383
- );
4384
- const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal");
4385
- assert.isAtLeast(recoveredIndex, 0);
4386
- assert.isAbove(resumedCommandIndex, recoveredIndex);
4387
- assert.isAbove(terminalIndex, resumedCommandIndex);
4388
- }).pipe(
4389
- Effect.provide(
4390
- Layer.mergeAll(
4391
- IdAllocator.layer,
4392
- McpProviderSessions.layer,
4393
- NodeServices.layer,
4394
- NodeCrypto.layer,
4395
- ),
4367
+ it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () =>
4368
+ Effect.gen(function* () {
4369
+ const scenario = "codex-provider-retry-stall";
4370
+ const nativeThreadId = `native-${scenario}-thread`;
4371
+ const nativeTurnId = `native-${scenario}-turn`;
4372
+ const transcript = makeCodexReplayTranscript({
4373
+ scenario,
4374
+ entries: [
4375
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
4376
+ {
4377
+ type: "emit_inbound",
4378
+ label: "error/retry",
4379
+ frame: {
4380
+ method: "error",
4381
+ params: {
4382
+ threadId: nativeThreadId,
4383
+ turnId: nativeTurnId,
4384
+ willRetry: true,
4385
+ error: {
4386
+ message: "Reconnecting... 1/5",
4387
+ additionalDetails: "exceeded retry limit, last status: 429 Too Many Requests",
4388
+ codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 429 } },
4389
+ },
4390
+ },
4391
+ },
4392
+ },
4393
+ {
4394
+ type: "expect_outbound",
4395
+ label: "turn/interrupt",
4396
+ frame: {
4397
+ id: 4,
4398
+ method: "turn/interrupt",
4399
+ params: { threadId: nativeThreadId, turnId: nativeTurnId },
4400
+ },
4401
+ },
4402
+ { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } },
4403
+ {
4404
+ type: "emit_inbound",
4405
+ label: "turn/completed",
4406
+ frame: {
4407
+ method: "turn/completed",
4408
+ params: {
4409
+ threadId: nativeThreadId,
4410
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }),
4411
+ },
4412
+ },
4413
+ },
4414
+ ],
4415
+ });
4416
+ const retryShown = yield* Deferred.make<void>();
4417
+ const interruptSent = yield* Deferred.make<void>();
4418
+ const harness = yield* makeCodexReplayHarness(
4419
+ transcript,
4420
+ (event) =>
4421
+ event.type === "turn_item.updated" && event.turnItem.type === "error"
4422
+ ? Deferred.succeed(retryShown, undefined)
4423
+ : Effect.void,
4424
+ (method) =>
4425
+ method === "turn/interrupt" ? Deferred.succeed(interruptSent, undefined) : Effect.void,
4426
+ );
4427
+ yield* harness.runtime.startTurn(
4428
+ makeCodexTestTurnInput({
4429
+ threadId: harness.threadId,
4430
+ providerThread: harness.providerThread,
4431
+ now: yield* DateTime.now,
4432
+ text: "Continue.",
4433
+ attemptId: RunAttemptId.make(`attempt-${scenario}`),
4434
+ }),
4435
+ );
4436
+ yield* Deferred.await(retryShown);
4437
+ yield* TestClock.adjust("9 minutes");
4438
+ assert.isEmpty(harness.terminalEvents());
4439
+ yield* TestClock.adjust("1 minute");
4440
+ yield* harness.firstTerminal;
4441
+ yield* Deferred.await(interruptSent);
4442
+ const terminal = harness.terminalEvents()[0];
4443
+ assert.equal(terminal?.status, "failed");
4444
+ if (terminal?.status !== "failed") return;
4445
+ assert.equal(terminal.failure.class, "usage_limit");
4446
+ assert.equal(terminal.failure.code, "responseStreamDisconnected");
4447
+ assert.equal(
4448
+ terminal.failure.message,
4449
+ "exceeded retry limit, last status: 429 Too Many Requests",
4450
+ );
4451
+ assert.equal(terminal.retry?.attempt, 1);
4452
+ assert.equal(terminal.threadDisposition, "reusable");
4453
+ }).pipe(
4454
+ Effect.provide(
4455
+ Layer.mergeAll(
4456
+ IdAllocator.layer,
4457
+ McpProviderSessions.layer,
4458
+ NodeServices.layer,
4459
+ NodeCrypto.layer,
4460
),
4461
),
4462
),
4463
);
4464
4401
- it.effect("fails a stalled 429 provider retry as a usage limit and stops the Codex turn", () =>
4402
- Effect.scoped(
4465
+ it.effect.each(["completed", "interrupted"] as const)(
4466
+ "retains Codex reasoning parts when the turn is %s",
4467
+ (terminalStatus) =>
4468
Effect.gen(function* () {
4404
- const scenario = "codex-provider-retry-stall";
4469
+ const scenario = `codex-reasoning-${terminalStatus}`;
4470
const nativeThreadId = `native-${scenario}-thread`;
4471
const nativeTurnId = `native-${scenario}-turn`;
4472
+ const prompt = "Explain the check.";
4473
const transcript = makeCodexReplayTranscript({
4474
scenario,
4475
entries: [
4410
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
4411
- {
4412
- type: "emit_inbound",
4413
- label: "error/retry",
4414
- frame: {
4415
- method: "error",
4476
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }),
4477
+ ...[
4478
+ {
4479
+ method: "item/reasoning/summaryTextDelta",
4480
+ params: { itemId: "thought", summaryIndex: 0, delta: "Summary " },
4481
+ },
4482
+ {
4483
+ method: "item/reasoning/summaryTextDelta",
4484
+ params: { itemId: "thought", summaryIndex: 0, delta: "one" },
4485
+ },
4486
+ {
4487
+ method: "item/reasoning/summaryTextDelta",
4488
+ params: { itemId: "thought", summaryIndex: 1, delta: "Summary two" },
4489
+ },
4490
+ {
4491
+ method: "item/reasoning/textDelta",
4492
+ params: { itemId: "thought", contentIndex: 0, delta: "Raw trace" },
4493
+ },
4494
+ {
4495
+ method: "item/completed",
4496
params: {
4417
- threadId: nativeThreadId,
4418
- turnId: nativeTurnId,
4419
- willRetry: true,
4420
- error: {
4421
- message: "Reconnecting... 1/5",
4422
- additionalDetails: "exceeded retry limit, last status: 429 Too Many Requests",
4423
- codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 429 } },
4497
+ item: {
4498
+ type: "commandExecution",
4499
+ id: "after-thought",
4500
+ command: "pwd",
4501
+ cwd: "/workspace",
4502
+ processId: "42",
4503
+ source: "unifiedExecStartup",
4504
+ status: "completed",
4505
+ commandActions: [{ type: "unknown", command: "pwd" }],
4506
+ aggregatedOutput: "/workspace",
4507
+ exitCode: 0,
4508
+ durationMs: 1,
4509
},
4510
},
4511
},
4427
- },
4428
- {
4429
- type: "expect_outbound",
4430
- label: "turn/interrupt",
4512
+ ...(terminalStatus === "completed"
4513
+ ? [
4514
+ {
4515
+ method: "item/completed",
4516
+ params: {
4517
+ item: {
4518
+ type: "reasoning",
4519
+ id: "thought",
4520
+ summary: ["Final summary one", "Summary two"],
4521
+ content: ["Raw trace"],
4522
+ },
4523
+ },
4524
+ },
4525
+ {
4526
+ method: "item/completed",
4527
+ params: {
4528
+ item: {
4529
+ type: "reasoning",
4530
+ id: "completion-only",
4531
+ summary: ["Completion without deltas"],
4532
+ content: [],
4533
+ },
4534
+ },
4535
+ },
4536
+ {
4537
+ method: "item/reasoning/textDelta",
4538
+ params: {
4539
+ itemId: "delta-only",
4540
+ contentIndex: 0,
4541
+ delta: "Retained when completion omits content",
4542
+ },
4543
+ },
4544
+ {
4545
+ method: "item/completed",
4546
+ params: {
4547
+ item: { type: "reasoning", id: "delta-only", summary: [], content: [] },
4548
+ },
4549
+ },
4550
+ ]
4551
+ : []),
4552
+ ].map((event, index) => ({
4553
+ type: "emit_inbound" as const,
4554
+ label: `reasoning-${index}`,
4555
frame: {
4432
- id: 4,
4433
- method: "turn/interrupt",
4434
- params: { threadId: nativeThreadId, turnId: nativeTurnId },
4556
+ method: event.method,
4557
+ params: { threadId: nativeThreadId, turnId: nativeTurnId, ...event.params },
4558
},
4436
- },
4437
- { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } },
4559
+ })),
4560
{
4561
type: "emit_inbound",
4562
label: "turn/completed",
@@ -4442,49 +4564,61 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4564
method: "turn/completed",
4565
params: {
4566
threadId: nativeThreadId,
4445
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }),
4567
+ turn: makeCodexReplayTurn({ id: nativeTurnId, status: terminalStatus }),
4568
},
4569
},
4570
},
4571
],
4572
});
4451
- const retryShown = yield* Deferred.make<void>();
4452
- const interruptSent = yield* Deferred.make<void>();
4453
- const harness = yield* makeCodexReplayHarness(
4454
- transcript,
4455
- (event) =>
4456
- event.type === "turn_item.updated" && event.turnItem.type === "error"
4457
- ? Deferred.succeed(retryShown, undefined)
4458
- : Effect.void,
4459
- (method) =>
4460
- method === "turn/interrupt" ? Deferred.succeed(interruptSent, undefined) : Effect.void,
4461
- );
4573
+ const harness = yield* makeCodexReplayHarness(transcript);
4574
yield* harness.runtime.startTurn(
4575
makeCodexTestTurnInput({
4576
threadId: harness.threadId,
4577
providerThread: harness.providerThread,
4578
now: yield* DateTime.now,
4467
- text: "Continue.",
4579
attemptId: RunAttemptId.make(`attempt-${scenario}`),
4580
+ text: prompt,
4581
}),
4582
);
4471
- yield* Deferred.await(retryShown);
4472
- yield* TestClock.adjust("9 minutes");
4473
- assert.isEmpty(harness.terminalEvents());
4474
- yield* TestClock.adjust("1 minute");
4583
yield* harness.firstTerminal;
4476
- yield* Deferred.await(interruptSent);
4477
- const terminal = harness.terminalEvents()[0];
4478
- assert.equal(terminal?.status, "failed");
4479
- if (terminal?.status !== "failed") return;
4480
- assert.equal(terminal.failure.class, "usage_limit");
4481
- assert.equal(terminal.failure.code, "responseStreamDisconnected");
4482
- assert.equal(
4483
- terminal.failure.message,
4484
- "exceeded retry limit, last status: 429 Too Many Requests",
4584
+ const latest = new Map(
4585
+ harness.events.flatMap((event) =>
4586
+ event.type === "turn_item.updated" && event.turnItem.type === "reasoning"
4587
+ ? [[event.turnItem.id, event.turnItem] as const]
4588
+ : [],
4589
+ ),
4590
);
4486
- assert.equal(terminal.retry?.attempt, 1);
4487
- assert.equal(terminal.threadDisposition, "reusable");
4591
+ assert.deepEqual(
4592
+ [...latest.values()].map((item) => item.text),
4593
+ terminalStatus === "completed"
4594
+ ? [
4595
+ "Final summary one",
4596
+ "Summary two",
4597
+ "Raw trace",
4598
+ "Completion without deltas",
4599
+ "Retained when completion omits content",
4600
+ ]
4601
+ : ["Summary one", "Summary two", "Raw trace"],
4602
+ );
4603
+ assert.isTrue([...latest.values()].every((item) => item.status === terminalStatus));
4604
+ assert.isTrue([...latest.values()].every((item) => item.streaming === false));
4605
+ assert.isTrue(
4606
+ [...latest.values()].every((item) => item.runId !== null && item.providerTurnId !== null),
4607
+ );
4608
+ assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, latest.size);
4609
+ const command = harness.events.find(
4610
+ (event) =>
4611
+ event.type === "turn_item.updated" && event.turnItem.type === "command_execution",
4612
+ );
4613
+ assert.isDefined(command);
4614
+ if (command?.type === "turn_item.updated") {
4615
+ assert.isTrue(
4616
+ [...latest.values()]
4617
+ .slice(0, 3)
4618
+ .every((item) => item.ordinal < command.turnItem.ordinal),
4619
+ );
4620
+ }
4621
+ assert.deepEqual(assistantMessages(harness.events), []);
4622
}).pipe(
4623
Effect.provide(
4624
Layer.mergeAll(
@@ -4495,180 +4629,6 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4629
),
4630
),
4631
),
4498
- ),
4499
- );
4500
-
4501
- it.effect.each(["completed", "interrupted"] as const)(
4502
- "retains Codex reasoning parts when the turn is %s",
4503
- (terminalStatus) =>
4504
- Effect.scoped(
4505
- Effect.gen(function* () {
4506
- const scenario = `codex-reasoning-${terminalStatus}`;
4507
- const nativeThreadId = `native-${scenario}-thread`;
4508
- const nativeTurnId = `native-${scenario}-turn`;
4509
- const prompt = "Explain the check.";
4510
- const transcript = makeCodexReplayTranscript({
4511
- scenario,
4512
- entries: [
4513
- ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }),
4514
- ...[
4515
- {
4516
- method: "item/reasoning/summaryTextDelta",
4517
- params: { itemId: "thought", summaryIndex: 0, delta: "Summary " },
4518
- },
4519
- {
4520
- method: "item/reasoning/summaryTextDelta",
4521
- params: { itemId: "thought", summaryIndex: 0, delta: "one" },
4522
- },
4523
- {
4524
- method: "item/reasoning/summaryTextDelta",
4525
- params: { itemId: "thought", summaryIndex: 1, delta: "Summary two" },
4526
- },
4527
- {
4528
- method: "item/reasoning/textDelta",
4529
- params: { itemId: "thought", contentIndex: 0, delta: "Raw trace" },
4530
- },
4531
- {
4532
- method: "item/completed",
4533
- params: {
4534
- item: {
4535
- type: "commandExecution",
4536
- id: "after-thought",
4537
- command: "pwd",
4538
- cwd: "/workspace",
4539
- processId: "42",
4540
- source: "unifiedExecStartup",
4541
- status: "completed",
4542
- commandActions: [{ type: "unknown", command: "pwd" }],
4543
- aggregatedOutput: "/workspace",
4544
- exitCode: 0,
4545
- durationMs: 1,
4546
- },
4547
- },
4548
- },
4549
- ...(terminalStatus === "completed"
4550
- ? [
4551
- {
4552
- method: "item/completed",
4553
- params: {
4554
- item: {
4555
- type: "reasoning",
4556
- id: "thought",
4557
- summary: ["Final summary one", "Summary two"],
4558
- content: ["Raw trace"],
4559
- },
4560
- },
4561
- },
4562
- {
4563
- method: "item/completed",
4564
- params: {
4565
- item: {
4566
- type: "reasoning",
4567
- id: "completion-only",
4568
- summary: ["Completion without deltas"],
4569
- content: [],
4570
- },
4571
- },
4572
- },
4573
- {
4574
- method: "item/reasoning/textDelta",
4575
- params: {
4576
- itemId: "delta-only",
4577
- contentIndex: 0,
4578
- delta: "Retained when completion omits content",
4579
- },
4580
- },
4581
- {
4582
- method: "item/completed",
4583
- params: {
4584
- item: { type: "reasoning", id: "delta-only", summary: [], content: [] },
4585
- },
4586
- },
4587
- ]
4588
- : []),
4589
- ].map((event, index) => ({
4590
- type: "emit_inbound" as const,
4591
- label: `reasoning-${index}`,
4592
- frame: {
4593
- method: event.method,
4594
- params: { threadId: nativeThreadId, turnId: nativeTurnId, ...event.params },
4595
- },
4596
- })),
4597
- {
4598
- type: "emit_inbound",
4599
- label: "turn/completed",
4600
- frame: {
4601
- method: "turn/completed",
4602
- params: {
4603
- threadId: nativeThreadId,
4604
- turn: makeCodexReplayTurn({ id: nativeTurnId, status: terminalStatus }),
4605
- },
4606
- },
4607
- },
4608
- ],
4609
- });
4610
- const harness = yield* makeCodexReplayHarness(transcript);
4611
- yield* harness.runtime.startTurn(
4612
- makeCodexTestTurnInput({
4613
- threadId: harness.threadId,
4614
- providerThread: harness.providerThread,
4615
- now: yield* DateTime.now,
4616
- attemptId: RunAttemptId.make(`attempt-${scenario}`),
4617
- text: prompt,
4618
- }),
4619
- );
4620
- yield* harness.firstTerminal;
4621
- const latest = new Map(
4622
- harness.events.flatMap((event) =>
4623
- event.type === "turn_item.updated" && event.turnItem.type === "reasoning"
4624
- ? [[event.turnItem.id, event.turnItem] as const]
4625
- : [],
4626
- ),
4627
- );
4628
- assert.deepEqual(
4629
- [...latest.values()].map((item) => item.text),
4630
- terminalStatus === "completed"
4631
- ? [
4632
- "Final summary one",
4633
- "Summary two",
4634
- "Raw trace",
4635
- "Completion without deltas",
4636
- "Retained when completion omits content",
4637
- ]
4638
- : ["Summary one", "Summary two", "Raw trace"],
4639
- );
4640
- assert.isTrue([...latest.values()].every((item) => item.status === terminalStatus));
4641
- assert.isTrue([...latest.values()].every((item) => item.streaming === false));
4642
- assert.isTrue(
4643
- [...latest.values()].every(
4644
- (item) => item.runId !== null && item.providerTurnId !== null,
4645
- ),
4646
- );
4647
- assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, latest.size);
4648
- const command = harness.events.find(
4649
- (event) =>
4650
- event.type === "turn_item.updated" && event.turnItem.type === "command_execution",
4651
- );
4652
- assert.isDefined(command);
4653
- if (command?.type === "turn_item.updated") {
4654
- assert.isTrue(
4655
- [...latest.values()]
4656
- .slice(0, 3)
4657
- .every((item) => item.ordinal < command.turnItem.ordinal),
4658
- );
4659
- }
4660
- assert.deepEqual(assistantMessages(harness.events), []);
4661
- }).pipe(
4662
- Effect.provide(
4663
- Layer.mergeAll(
4664
- IdAllocator.layer,
4665
- McpProviderSessions.layer,
4666
- NodeServices.layer,
4667
- NodeCrypto.layer,
4668
- ),
4669
- ),
4670
- ),
4671
- ),
4632
);
4633
4634
const finalAnswerTranscript = (
@@ -4774,106 +4734,104 @@ describe("CodexAdapterV2 post-settle continuation", () => {
4734
it.effect.each([false, true])(
4735
"preserves a final answer that repeats a preceding partial answer (streamed: %s)",
4736
(streamed) =>
4777
- Effect.scoped(
4778
- Effect.gen(function* () {
4779
- const transcript = finalAnswerTranscript("codex-partial-then-final", [
4780
- {
4781
- id: "status",
4782
- text: "Checking the files",
4783
- phase: "commentary",
4784
- streamed,
4785
- },
4786
- {
4787
- id: "partial",
4788
- text: "CODEX_RECOVERY_OK",
4789
- phase: "partial_answer",
4790
- streamed,
4791
- },
4792
- {
4793
- id: "final",
4794
- text: "CODEX_RECOVERY_OK",
4795
- phase: "final_answer",
4796
- streamed,
4797
- },
4798
- ]);
4799
- const gates = yield* Effect.forEach(["status", "partial", "final"], (id) =>
4800
- Effect.gen(function* () {
4801
- return {
4802
- id,
4803
- ready: yield* Deferred.make<void>(),
4804
- release: yield* Deferred.make<void>(),
4805
- };
4806
- }),
4807
- );
4808
- const harness = yield* makeCodexReplayHarness(
4809
- transcript,
4810
- undefined,
4811
- undefined,
4812
- undefined,
4813
- (entry) => {
4814
- const gate = streamed
4815
- ? gates.find((gate) => entry.label === `item/completed/${gate.id}`)
4816
- : undefined;
4817
- return gate === undefined
4818
- ? Effect.void
4819
- : Deferred.succeed(gate.ready, undefined).pipe(
4820
- Effect.andThen(Deferred.await(gate.release)),
4821
- );
4822
- },
4823
- );
4824
- const now = yield* DateTime.now;
4825
- yield* harness.runtime.startTurn(
4826
- makeCodexTestTurnInput({
4827
- threadId: harness.threadId,
4828
- providerThread: harness.providerThread,
4829
- now,
4830
- attemptId: RunAttemptId.make("attempt-codex-partial-then-final"),
4831
- text: "Reply with the requested recovery marker.",
4832
- }),
4833
- );
4834
- if (streamed) {
4835
- for (const gate of gates) {
4836
- yield* Deferred.await(gate.ready);
4837
- yield* TestClock.adjust("50 millis");
4838
- yield* harness.until(() =>
4839
- harness.events.some(
4840
- (event) =>
4841
- event.type === "turn_item.updated" &&
4842
- event.turnItem.type === "assistant_message" &&
4843
- event.turnItem.nativeItemRef?.nativeId === gate.id &&
4844
- event.turnItem.streaming,
4845
- ),
4846
- );
4847
- yield* Deferred.succeed(gate.release, undefined);
4848
- }
4849
- }
4850
- yield* harness.awaitTerminal(1);
4851
- assert.deepEqual(
4852
- assistantMessages(harness.events).map((event) => event.message.text),
4853
- ["Checking the files", "CODEX_RECOVERY_OK", "CODEX_RECOVERY_OK"],
4854
- );
4855
- const updates = harness.events.flatMap((event) =>
4856
- event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
4857
- ? [event.turnItem]
4858
- : [],
4859
- );
4860
- for (const [text, phase] of [
4861
- ["Checking the files", "commentary"],
4862
- ["CODEX_RECOVERY_OK", "partial_answer"],
4863
- ["CODEX_RECOVERY_OK", "final_answer"],
4864
- ]) {
4865
- const matching = updates.filter((item) => item.text === text && item.phase === phase);
4866
- assert.isTrue(matching.some((item) => !item.streaming));
4867
- if (streamed) assert.isTrue(matching.some((item) => item.streaming));
4737
+ Effect.gen(function* () {
4738
+ const transcript = finalAnswerTranscript("codex-partial-then-final", [
4739
+ {
4740
+ id: "status",
4741
+ text: "Checking the files",
4742
+ phase: "commentary",
4743
+ streamed,
4744
+ },
4745
+ {
4746
+ id: "partial",
4747
+ text: "CODEX_RECOVERY_OK",
4748
+ phase: "partial_answer",
4749
+ streamed,
4750
+ },
4751
+ {
4752
+ id: "final",
4753
+ text: "CODEX_RECOVERY_OK",
4754
+ phase: "final_answer",
4755
+ streamed,
4756
+ },
4757
+ ]);
4758
+ const gates = yield* Effect.forEach(["status", "partial", "final"], (id) =>
4759
+ Effect.gen(function* () {
4760
+ return {
4761
+ id,
4762
+ ready: yield* Deferred.make<void>(),
4763
+ release: yield* Deferred.make<void>(),
4764
+ };
4765
+ }),
4766
+ );
4767
+ const harness = yield* makeCodexReplayHarness(
4768
+ transcript,
4769
+ undefined,
4770
+ undefined,
4771
+ undefined,
4772
+ (entry) => {
4773
+ const gate = streamed
4774
+ ? gates.find((gate) => entry.label === `item/completed/${gate.id}`)
4775
+ : undefined;
4776
+ return gate === undefined
4777
+ ? Effect.void
4778
+ : Deferred.succeed(gate.ready, undefined).pipe(
4779
+ Effect.andThen(Deferred.await(gate.release)),
4780
+ );
4781
+ },
4782
+ );
4783
+ const now = yield* DateTime.now;
4784
+ yield* harness.runtime.startTurn(
4785
+ makeCodexTestTurnInput({
4786
+ threadId: harness.threadId,
4787
+ providerThread: harness.providerThread,
4788
+ now,
4789
+ attemptId: RunAttemptId.make("attempt-codex-partial-then-final"),
4790
+ text: "Reply with the requested recovery marker.",
4791
+ }),
4792
+ );
4793
+ if (streamed) {
4794
+ for (const gate of gates) {
4795
+ yield* Deferred.await(gate.ready);
4796
+ yield* TestClock.adjust("50 millis");
4797
+ yield* harness.until(() =>
4798
+ harness.events.some(
4799
+ (event) =>
4800
+ event.type === "turn_item.updated" &&
4801
+ event.turnItem.type === "assistant_message" &&
4802
+ event.turnItem.nativeItemRef?.nativeId === gate.id &&
4803
+ event.turnItem.streaming,
4804
+ ),
4805
+ );
4806
+ yield* Deferred.succeed(gate.release, undefined);
4807
}
4869
- }).pipe(
4870
- Effect.provide(
4871
- Layer.mergeAll(
4872
- IdAllocator.layer,
4873
- McpProviderSessions.layer,
4874
- NodeServices.layer,
4875
- NodeCrypto.layer,
4876
- ),
4808
+ }
4809
+ yield* harness.awaitTerminal(1);
4810
+ assert.deepEqual(
4811
+ assistantMessages(harness.events).map((event) => event.message.text),
4812
+ ["Checking the files", "CODEX_RECOVERY_OK", "CODEX_RECOVERY_OK"],
4813
+ );
4814
+ const updates = harness.events.flatMap((event) =>
4815
+ event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
4816
+ ? [event.turnItem]
4817
+ : [],
4818
+ );
4819
+ for (const [text, phase] of [
4820
+ ["Checking the files", "commentary"],
4821
+ ["CODEX_RECOVERY_OK", "partial_answer"],
4822
+ ["CODEX_RECOVERY_OK", "final_answer"],
4823
+ ]) {
4824
+ const matching = updates.filter((item) => item.text === text && item.phase === phase);
4825
+ assert.isTrue(matching.some((item) => !item.streaming));
4826
+ if (streamed) assert.isTrue(matching.some((item) => item.streaming));
4827
+ }
4828
+ }).pipe(
4829
+ Effect.provide(
4830
+ Layer.mergeAll(
4831
+ IdAllocator.layer,
4832
+ McpProviderSessions.layer,
4833
+ NodeServices.layer,
4834
+ NodeCrypto.layer,
4835
),
4836
),
4837
),
@@ -5159,38 +5117,36 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5117
);
5118
5119
it.effect("suppresses a trailing empty final answer after a non-empty final answer", () =>
5162
- Effect.scoped(
5163
- Effect.gen(function* () {
5164
- const transcript = finalAnswerTranscript("codex-redundant-empty-final", [
5165
- { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" },
5166
- { id: "answer-empty", text: "" },
5167
- ]);
5168
- const harness = yield* makeCodexReplayHarness(transcript);
5169
- const now = yield* DateTime.now;
5120
+ Effect.gen(function* () {
5121
+ const transcript = finalAnswerTranscript("codex-redundant-empty-final", [
5122
+ { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" },
5123
+ { id: "answer-empty", text: "" },
5124
+ ]);
5125
+ const harness = yield* makeCodexReplayHarness(transcript);
5126
+ const now = yield* DateTime.now;
5127
5171
- yield* harness.runtime.startTurn(
5172
- makeCodexTestTurnInput({
5173
- threadId: harness.threadId,
5174
- providerThread: harness.providerThread,
5175
- now,
5176
- attemptId: RunAttemptId.make("attempt-codex-redundant-empty-final"),
5177
- text: "Reply with the requested recovery marker.",
5178
- }),
5179
- );
5180
- yield* harness.awaitTerminal(1);
5128
+ yield* harness.runtime.startTurn(
5129
+ makeCodexTestTurnInput({
5130
+ threadId: harness.threadId,
5131
+ providerThread: harness.providerThread,
5132
+ now,
5133
+ attemptId: RunAttemptId.make("attempt-codex-redundant-empty-final"),
5134
+ text: "Reply with the requested recovery marker.",
5135
+ }),
5136
+ );
5137
+ yield* harness.awaitTerminal(1);
5138
5182
- assert.deepEqual(
5183
- assistantMessages(harness.events).map((event) => event.message.text),
5184
- ["CODEX_RECOVERY_OK"],
5185
- );
5186
- }).pipe(
5187
- Effect.provide(
5188
- Layer.mergeAll(
5189
- IdAllocator.layer,
5190
- McpProviderSessions.layer,
5191
- NodeServices.layer,
5192
- NodeCrypto.layer,
5193
- ),
5139
+ assert.deepEqual(
5140
+ assistantMessages(harness.events).map((event) => event.message.text),
5141
+ ["CODEX_RECOVERY_OK"],
5142
+ );
5143
+ }).pipe(
5144
+ Effect.provide(
5145
+ Layer.mergeAll(
5146
+ IdAllocator.layer,
5147
+ McpProviderSessions.layer,
5148
+ NodeServices.layer,
5149
+ NodeCrypto.layer,
5150
),
5151
),
5152
),
@@ -5332,52 +5288,50 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5288
);
5289
5290
it.effect("wakes with well-formed text when the cuts split an emoji", () =>
5335
- Effect.scoped(
5336
- Effect.gen(function* () {
5337
- const harness = yield* makeCodexReplayHarness(
5338
- makeCodexReplayTranscript({
5339
- scenario: "codex-bg-wake-surrogate",
5340
- entries: [
5341
- ...backgroundExecTranscript.entries.slice(0, -1),
5342
- {
5343
- type: "emit_inbound",
5344
- label: "item/completed/command-late",
5345
- frame: {
5346
- method: "item/completed",
5347
- params: {
5348
- item: {
5349
- ...backgroundCommandItem("completed"),
5350
- command: `${"c".repeat(199)}🚀`,
5351
- aggregatedOutput: `🚀${"x".repeat(999)}\n`,
5352
- },
5353
- threadId: BG_NATIVE_THREAD,
5354
- turnId: BG_NATIVE_TURN,
5355
- completedAtMs: 1782622465500,
5291
+ Effect.gen(function* () {
5292
+ const harness = yield* makeCodexReplayHarness(
5293
+ makeCodexReplayTranscript({
5294
+ scenario: "codex-bg-wake-surrogate",
5295
+ entries: [
5296
+ ...backgroundExecTranscript.entries.slice(0, -1),
5297
+ {
5298
+ type: "emit_inbound",
5299
+ label: "item/completed/command-late",
5300
+ frame: {
5301
+ method: "item/completed",
5302
+ params: {
5303
+ item: {
5304
+ ...backgroundCommandItem("completed"),
5305
+ command: `${"c".repeat(199)}🚀`,
5306
+ aggregatedOutput: `🚀${"x".repeat(999)}\n`,
5307
},
5308
+ threadId: BG_NATIVE_THREAD,
5309
+ turnId: BG_NATIVE_TURN,
5310
+ completedAtMs: 1782622465500,
5311
},
5312
},
5359
- ],
5360
- }),
5361
- );
5362
- yield* harness.runtime.startTurn(
5363
- makeCodexTestTurnInput({
5364
- threadId: harness.threadId,
5365
- providerThread: harness.providerThread,
5366
- now: yield* DateTime.now,
5367
- attemptId: RunAttemptId.make("attempt-codex-bg-wake-surrogate"),
5368
- text: BG_PROMPT,
5369
- }),
5370
- );
5371
- yield* harness.until(() => harness.continuationRequests.length > 0);
5372
- assert.isTrue(harness.continuationRequests[0]?.detail?.isWellFormed());
5373
- }).pipe(
5374
- Effect.provide(
5375
- Layer.mergeAll(
5376
- IdAllocator.layer,
5377
- McpProviderSessions.layer,
5378
- NodeServices.layer,
5379
- NodeCrypto.layer,
5380
- ),
5313
+ },
5314
+ ],
5315
+ }),
5316
+ );
5317
+ yield* harness.runtime.startTurn(
5318
+ makeCodexTestTurnInput({
5319
+ threadId: harness.threadId,
5320
+ providerThread: harness.providerThread,
5321
+ now: yield* DateTime.now,
5322
+ attemptId: RunAttemptId.make("attempt-codex-bg-wake-surrogate"),
5323
+ text: BG_PROMPT,
5324
+ }),
5325
+ );
5326
+ yield* harness.until(() => harness.continuationRequests.length > 0);
5327
+ assert.isTrue(harness.continuationRequests[0]?.detail?.isWellFormed());
5328
+ }).pipe(
5329
+ Effect.provide(
5330
+ Layer.mergeAll(
5331
+ IdAllocator.layer,
5332
+ McpProviderSessions.layer,
5333
+ NodeServices.layer,
5334
+ NodeCrypto.layer,
5335
),
5336
),
5337
),
@@ -5612,67 +5566,65 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5566
(terminated) => {
5567
const stillRunning = terminated === "still_running";
5568
const transcript = makeBackgroundStopTranscript(terminated);
5615
- return Effect.scoped(
5616
- Effect.gen(function* () {
5617
- const stopped = yield* Deferred.make<void>();
5618
- const harness = yield* makeCodexReplayHarness(transcript, (event) =>
5619
- event.type === "turn_item.updated" &&
5620
- event.turnItem.type === "command_execution" &&
5621
- event.turnItem.status === "interrupted"
5622
- ? Deferred.succeed(stopped, undefined)
5623
- : Effect.void,
5624
- );
5625
- const now = yield* DateTime.now;
5626
- yield* harness.runtime.startTurn(
5627
- makeCodexTestTurnInput({
5628
- threadId: harness.threadId,
5569
+ return Effect.gen(function* () {
5570
+ const stopped = yield* Deferred.make<void>();
5571
+ const harness = yield* makeCodexReplayHarness(transcript, (event) =>
5572
+ event.type === "turn_item.updated" &&
5573
+ event.turnItem.type === "command_execution" &&
5574
+ event.turnItem.status === "interrupted"
5575
+ ? Deferred.succeed(stopped, undefined)
5576
+ : Effect.void,
5577
+ );
5578
+ const now = yield* DateTime.now;
5579
+ yield* harness.runtime.startTurn(
5580
+ makeCodexTestTurnInput({
5581
+ threadId: harness.threadId,
5582
+ providerThread: harness.providerThread,
5583
+ now,
5584
+ attemptId: RunAttemptId.make("attempt-codex-bg-stop"),
5585
+ text: BG_PROMPT,
5586
+ }),
5587
+ );
5588
+ yield* harness.firstTerminal;
5589
+ const terminal = harness.terminalEvents()[0]!;
5590
+ assert.equal(terminal.status, "completed");
5591
+ assert.isTrue(yield* harness.hasPendingBackgroundWork);
5592
+ assert.isFalse(
5593
+ yield* harness.runtime.hasPendingBackgroundWorkForThread!({
5594
+ ...harness.providerThread,
5595
+ id: ProviderThreadId.make("unrelated-provider-thread"),
5596
+ }),
5597
+ );
5598
+ if (stillRunning) {
5599
+ const failed = yield* harness.runtime
5600
+ .interruptTurn({
5601
providerThread: harness.providerThread,
5630
- now,
5631
- attemptId: RunAttemptId.make("attempt-codex-bg-stop"),
5632
- text: BG_PROMPT,
5633
- }),
5634
- );
5635
- yield* harness.firstTerminal;
5636
- const terminal = harness.terminalEvents()[0]!;
5637
- assert.equal(terminal.status, "completed");
5602
+ providerTurnId: terminal.providerTurnId,
5603
+ requestRuntimeRestart: true,
5604
+ })
5605
+ .pipe(Effect.exit);
5606
+ assert.equal(failed._tag, "Failure");
5607
assert.isTrue(yield* harness.hasPendingBackgroundWork);
5639
- assert.isFalse(
5640
- yield* harness.runtime.hasPendingBackgroundWorkForThread!({
5641
- ...harness.providerThread,
5642
- id: ProviderThreadId.make("unrelated-provider-thread"),
5643
- }),
5644
- );
5645
- if (stillRunning) {
5646
- const failed = yield* harness.runtime
5647
- .interruptTurn({
5648
- providerThread: harness.providerThread,
5649
- providerTurnId: terminal.providerTurnId,
5650
- requestRuntimeRestart: true,
5651
- })
5652
- .pipe(Effect.exit);
5653
- assert.equal(failed._tag, "Failure");
5654
- assert.isTrue(yield* harness.hasPendingBackgroundWork);
5655
- }
5656
- yield* harness.runtime.interruptTurn({
5657
- providerThread: harness.providerThread,
5658
- providerTurnId: stillRunning
5659
- ? ProviderTurnId.make("later-completed-turn")
5660
- : terminal.providerTurnId,
5661
- requestRuntimeRestart: true,
5662
- });
5663
- yield* Deferred.await(stopped);
5664
- assert.isFalse(yield* harness.hasPendingBackgroundWork);
5665
- assert.lengthOf(harness.terminalEvents(), 1);
5666
- assert.equal(harness.terminalEvents()[0]?.status, "completed");
5667
- assert.lengthOf(harness.continuationRequests, 0);
5668
- }).pipe(
5669
- Effect.provide(
5670
- Layer.mergeAll(
5671
- IdAllocator.layer,
5672
- McpProviderSessions.layer,
5673
- NodeServices.layer,
5674
- NodeCrypto.layer,
5675
- ),
5608
+ }
5609
+ yield* harness.runtime.interruptTurn({
5610
+ providerThread: harness.providerThread,
5611
+ providerTurnId: stillRunning
5612
+ ? ProviderTurnId.make("later-completed-turn")
5613
+ : terminal.providerTurnId,
5614
+ requestRuntimeRestart: true,
5615
+ });
5616
+ yield* Deferred.await(stopped);
5617
+ assert.isFalse(yield* harness.hasPendingBackgroundWork);
5618
+ assert.lengthOf(harness.terminalEvents(), 1);
5619
+ assert.equal(harness.terminalEvents()[0]?.status, "completed");
5620
+ assert.lengthOf(harness.continuationRequests, 0);
5621
+ }).pipe(
5622
+ Effect.provide(
5623
+ Layer.mergeAll(
5624
+ IdAllocator.layer,
5625
+ McpProviderSessions.layer,
5626
+ NodeServices.layer,
5627
+ NodeCrypto.layer,
5628
),
5629
),
5630
);
@@ -5680,246 +5632,242 @@ describe("CodexAdapterV2 post-settle continuation", () => {
5632
);
5633
it.effect("stops a completed run's background command without a client-supplied run", () => {
5634
const transcript = makeBackgroundStopTranscript(true);
5683
- return Effect.scoped(
5684
- Effect.gen(function* () {
5685
- const fs = yield* FileSystem.FileSystem;
5686
- const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" });
5687
- const localTranscript = yield* decodeReplayTranscriptJson(
5688
- (yield* encodeReplayTranscriptJson(transcript)).replaceAll(
5689
- yield* encodeStringJson("/workspace"),
5690
- yield* encodeStringJson(cwd),
5635
+ return Effect.gen(function* () {
5636
+ const fs = yield* FileSystem.FileSystem;
5637
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bg-stop-workspace-" });
5638
+ const localTranscript = yield* decodeReplayTranscriptJson(
5639
+ (yield* encodeReplayTranscriptJson(transcript)).replaceAll(
5640
+ yield* encodeStringJson("/workspace"),
5641
+ yield* encodeStringJson(cwd),
5642
+ ),
5643
+ );
5644
+ const replayDriver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript));
5645
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5646
+ assert.equal(
5647
+ Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))),
5648
+ 0,
5649
+ );
5650
+ assert.equal(
5651
+ Number(
5652
+ yield* spawner.exitCode(
5653
+ ChildProcess.make(
5654
+ "git",
5655
+ [
5656
+ "-c",
5657
+ "user.name=Test",
5658
+ "-c",
5659
+ "user.email=test@example.com",
5660
+ "commit",
5661
+ "--allow-empty",
5662
+ "--quiet",
5663
+ "-m",
5664
+ "Initial commit",
5665
+ ],
5666
+ { cwd },
5667
+ ),
5668
),
5669
+ ),
5670
+ 0,
5671
+ );
5672
+ yield* Effect.gen(function* () {
5673
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
5674
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
5675
+ const threadId = ThreadId.make("thread:background-stop");
5676
+ yield* orchestrator.dispatch({
5677
+ type: "thread.create",
5678
+ commandId: CommandId.make("create-background-stop"),
5679
+ threadId,
5680
+ projectId: ProjectId.make("project:background-stop"),
5681
+ title: "Background stop",
5682
+ modelSelection: CODEX_TEST_MODEL_SELECTION,
5683
+ runtimeMode: "full-access",
5684
+ interactionMode: "default",
5685
+ branch: null,
5686
+ worktreePath: cwd,
5687
+ createdBy: "user",
5688
+ creationSource: "web",
5689
+ });
5690
+ const waiting = yield* orchestrator.streamDomainEvents.pipe(
5691
+ Stream.filter(
5692
+ (event) => event.type === "run.updated" && event.payload.status === "waiting",
5693
+ ),
5694
+ Stream.runHead,
5695
+ Effect.forkChild({ startImmediately: true }),
5696
);
5693
- const replayDriver = yield* CodexReplay.makeReplayDriver(withConfigReads(localTranscript));
5694
- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
5695
- assert.equal(
5696
- Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))),
5697
- 0,
5698
- );
5697
+ yield* orchestrator.dispatch({
5698
+ type: "message.dispatch",
5699
+ commandId: CommandId.make("start-background-stop"),
5700
+ threadId,
5701
+ messageId: MessageId.make("message:background-stop"),
5702
+ text: BG_PROMPT,
5703
+ attachments: [],
5704
+ createdBy: "user",
5705
+ creationSource: "web",
5706
+ dispatchMode: { type: "start_immediately" },
5707
+ });
5708
+ yield* worker.drain();
5709
+ assert.isNull((yield* Ref.get(replayDriver.state)).failure);
5710
+ yield* Fiber.join(waiting);
5711
+ yield* worker.drain();
5712
+ const projection = yield* orchestrator.getThreadProjection(threadId);
5713
+ const run = projection.runs.at(-1)!;
5714
+ assert.equal(run.status, "completed");
5715
assert.equal(
5700
- Number(
5701
- yield* spawner.exitCode(
5702
- ChildProcess.make(
5703
- "git",
5704
- [
5705
- "-c",
5706
- "user.name=Test",
5707
- "-c",
5708
- "user.email=test@example.com",
5709
- "commit",
5710
- "--allow-empty",
5711
- "--quiet",
5712
- "-m",
5713
- "Initial commit",
5714
- ],
5715
- { cwd },
5716
- ),
5717
- ),
5718
- ),
5719
- 0,
5716
+ (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length,
5717
+ 1,
5718
);
5721
- yield* Effect.gen(function* () {
5722
- const orchestrator = yield* Orchestrator.OrchestratorV2;
5723
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
5724
- const threadId = ThreadId.make("thread:background-stop");
5725
- yield* orchestrator.dispatch({
5726
- type: "thread.create",
5727
- commandId: CommandId.make("create-background-stop"),
5728
- threadId,
5729
- projectId: ProjectId.make("project:background-stop"),
5730
- title: "Background stop",
5731
- modelSelection: CODEX_TEST_MODEL_SELECTION,
5732
- runtimeMode: "full-access",
5733
- interactionMode: "default",
5734
- branch: null,
5735
- worktreePath: cwd,
5736
- createdBy: "user",
5737
- creationSource: "web",
5738
- });
5739
- const waiting = yield* orchestrator.streamDomainEvents.pipe(
5740
- Stream.filter(
5741
- (event) => event.type === "run.updated" && event.payload.status === "waiting",
5742
- ),
5743
- Stream.runHead,
5744
- Effect.forkChild({ startImmediately: true }),
5745
- );
5746
- yield* orchestrator.dispatch({
5747
- type: "message.dispatch",
5748
- commandId: CommandId.make("start-background-stop"),
5749
- threadId,
5750
- messageId: MessageId.make("message:background-stop"),
5751
- text: BG_PROMPT,
5752
- attachments: [],
5753
- createdBy: "user",
5754
- creationSource: "web",
5755
- dispatchMode: { type: "start_immediately" },
5756
- });
5757
- yield* worker.drain();
5758
- assert.isNull((yield* Ref.get(replayDriver.state)).failure);
5759
- yield* Fiber.join(waiting);
5760
- yield* worker.drain();
5761
- const projection = yield* orchestrator.getThreadProjection(threadId);
5762
- const run = projection.runs.at(-1)!;
5763
- assert.equal(run.status, "completed");
5764
- assert.equal(
5765
- (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks?.length,
5766
- 1,
5767
- );
5768
- const stopped = yield* orchestrator.streamDomainEvents.pipe(
5769
- Stream.filter(
5770
- (event) =>
5771
- event.type === "turn-item.updated" &&
5772
- event.payload.type === "command_execution" &&
5773
- event.payload.status === "interrupted",
5774
- ),
5775
- Stream.runHead,
5776
- Effect.forkChild({ startImmediately: true }),
5777
- );
5778
- yield* orchestrator.dispatch({
5779
- type: "thread.stop",
5780
- commandId: CommandId.make("stop-background-command"),
5781
- threadId,
5782
- });
5783
- yield* worker.drain();
5784
- yield* Fiber.join(stopped);
5785
- assert.equal(
5786
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
5787
- "completed",
5788
- );
5789
- assert.deepEqual(
5790
- (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks,
5791
- [],
5792
- );
5793
- }).pipe(
5794
- Effect.provide(
5795
- ProviderReplayHarness.layerWithRegistry(
5796
- { name: "codex-background-stop", runtimePolicyOverride: { cwd } },
5797
- CodexAdapterV2Testkit.layer({
5798
- transcript: localTranscript,
5799
- driver: replayDriver,
5800
- }),
5801
- { runEffectWorker: false },
5802
- ),
5719
+ const stopped = yield* orchestrator.streamDomainEvents.pipe(
5720
+ Stream.filter(
5721
+ (event) =>
5722
+ event.type === "turn-item.updated" &&
5723
+ event.payload.type === "command_execution" &&
5724
+ event.payload.status === "interrupted",
5725
),
5726
+ Stream.runHead,
5727
+ Effect.forkChild({ startImmediately: true }),
5728
);
5805
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
5806
- );
5729
+ yield* orchestrator.dispatch({
5730
+ type: "thread.stop",
5731
+ commandId: CommandId.make("stop-background-command"),
5732
+ threadId,
5733
+ });
5734
+ yield* worker.drain();
5735
+ yield* Fiber.join(stopped);
5736
+ assert.equal(
This file is too large to show in full.
apps/server/src/orchestration-v2/Adapters/FxAdapterV2.test.ts
+4
-4
@@ -287,7 +287,7 @@ describe("FxAdapterV2", () => {
287
],
288
}),
289
{ discard: true },
290
- ).pipe(Effect.provide(testLayer), Effect.scoped),
290
+ ).pipe(Effect.provide(testLayer)),
291
);
292
293
it.effect("puts a loaded session that ran a named model back on fx's default for Default", () =>
@@ -309,7 +309,7 @@ describe("FxAdapterV2", () => {
309
// Written on load even though fx reports ask.
310
...setConfig("mode", "ask", fxConfig({ model: FX_DEFAULT_MODEL, modes: FX_0_0_13_MODES })),
311
],
312
- }).pipe(Effect.provide(testLayer), Effect.scoped),
312
+ }).pipe(Effect.provide(testLayer)),
313
);
314
315
// `fx status` names the gateway default, but this loaded session runs on
@@ -334,7 +334,7 @@ describe("FxAdapterV2", () => {
334
fxConfig({ model: CODEX_MODEL, models: [CODEX_MODEL], modes: FX_0_0_13_MODES }),
335
),
336
],
337
- }).pipe(Effect.provide(testLayer), Effect.scoped),
337
+ }).pipe(Effect.provide(testLayer)),
338
);
339
340
// fx 0.0.13's gateway takes any model id (src/acp/server.zig
@@ -367,6 +367,6 @@ describe("FxAdapterV2", () => {
367
outbound("session/prompt"),
368
answer("session/prompt", { stopReason: "end_turn" }),
369
],
370
- }).pipe(Effect.provide(testLayer), Effect.scoped),
370
+ }).pipe(Effect.provide(testLayer)),
371
);
372
});
apps/server/src/orchestration-v2/Adapters/KiroAdapterV2.test.ts
+12
-12
@@ -509,7 +509,7 @@ describe("KiroAdapterV2", () => {
509
ProviderCompactionUnsupportedError,
510
);
511
}),
512
- }).pipe(Effect.provide(testLayer), Effect.scoped),
512
+ }).pipe(Effect.provide(testLayer)),
513
);
514
515
it.effect("switches back to Kiro's default model after a named one", () =>
@@ -557,7 +557,7 @@ describe("KiroAdapterV2", () => {
557
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
558
}
559
}),
560
- }).pipe(Effect.provide(testLayer), Effect.scoped),
560
+ }).pipe(Effect.provide(testLayer)),
561
);
562
563
it.effect("sets the thread's effort once the model write advertises it, and after a switch", () =>
@@ -638,7 +638,7 @@ describe("KiroAdapterV2", () => {
638
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
639
}
640
}),
641
- }).pipe(Effect.provide(testLayer), Effect.scoped),
641
+ }).pipe(Effect.provide(testLayer)),
642
);
643
644
it.effect("waits for Kiro to advertise the model before setting its effort", () =>
@@ -688,7 +688,7 @@ describe("KiroAdapterV2", () => {
688
yield* startTurnOn(1, "claude-opus-5.5", reasoning("high"));
689
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
690
}),
691
- }).pipe(Effect.provide(testLayer), Effect.scoped),
691
+ }).pipe(Effect.provide(testLayer)),
692
);
693
694
it.effect("never sends an effort level the model does not offer", () =>
@@ -744,7 +744,7 @@ describe("KiroAdapterV2", () => {
744
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
745
}
746
}),
747
- }).pipe(Effect.provide(testLayer), Effect.scoped),
747
+ }).pipe(Effect.provide(testLayer)),
748
);
749
750
it.effect("answers a stale 'this session' approval with Kiro's allow_once", () =>
@@ -805,7 +805,7 @@ describe("KiroAdapterV2", () => {
805
yield* respond(yield* Deferred.await(pending), "acceptForSession");
806
assert.equal(terminalStatus(yield* Fiber.join(turn)), "completed");
807
}),
808
- }).pipe(Effect.provide(testLayer), Effect.scoped),
808
+ }).pipe(Effect.provide(testLayer)),
809
);
810
811
it.effect("sends a model Kiro does not list, and fails with Kiro's own message", () =>
@@ -855,7 +855,7 @@ describe("KiroAdapterV2", () => {
855
}
856
assert.include(terminal.failure.message, "'claude-opus-9' is not available");
857
}),
858
- }).pipe(Effect.provide(testLayer), Effect.scoped),
858
+ }).pipe(Effect.provide(testLayer)),
859
);
860
});
861
@@ -921,7 +921,7 @@ describe("KiroAdapterV2 agents", () => {
921
yield* startTurnOn(2, "claude-opus-5.5", agent("spec"));
922
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
923
}),
924
- }).pipe(Effect.provide(testLayer), Effect.scoped),
924
+ }).pipe(Effect.provide(testLayer)),
925
);
926
927
it.effect("puts Kiro default back after an agent switch moved the session off it", () =>
@@ -957,7 +957,7 @@ describe("KiroAdapterV2 agents", () => {
957
yield* startTurn;
958
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
959
}),
960
- }).pipe(Effect.provide(testLayer), Effect.scoped),
960
+ }).pipe(Effect.provide(testLayer)),
961
);
962
963
it.effect("keeps the session's agent when the thread's agent no longer exists", () =>
@@ -984,7 +984,7 @@ describe("KiroAdapterV2 agents", () => {
984
yield* startTurn;
985
assert.equal(terminalStatus(yield* collectTurn(events)), "completed");
986
}),
987
- }).pipe(Effect.provide(testLayer), Effect.scoped),
987
+ }).pipe(Effect.provide(testLayer)),
988
);
989
});
990
@@ -1348,7 +1348,7 @@ describe("KiroAdapterV2 MCP tools", () => {
1348
);
1349
}),
1350
});
1351
- }).pipe(Effect.provide(testLayer), Effect.scoped),
1351
+ }).pipe(Effect.provide(testLayer)),
1352
);
1353
});
1354
@@ -1403,7 +1403,7 @@ describe("KiroAdapterV2 unknown model", () => {
1403
assert.equal(terminal.failure.code, "-32000");
1404
}),
1405
});
1406
- }).pipe(Effect.provide(testLayer), Effect.scoped),
1406
+ }).pipe(Effect.provide(testLayer)),
1407
);
1408
});
1409
apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+101
-101
@@ -501,7 +501,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
501
}),
502
);
503
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
504
- }).pipe(Effect.scoped),
504
+ }),
505
);
506
507
it.effect("never sends a saved variant the catalog model does not list", () =>
@@ -516,7 +516,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
516
turnInput(thread, { ...bigPickle, options: [{ id: "variant", value: "medium" }] }),
517
);
518
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
519
- }).pipe(Effect.scoped),
519
+ }),
520
);
521
522
it.effect("renames the session before the first turn after the thread was renamed", () =>
@@ -545,7 +545,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
545
attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
546
});
547
assert.equal((yield* Fiber.join(second))?.status, "completed");
548
- }).pipe(Effect.scoped),
548
+ }),
549
);
550
551
it.effect("ends a turn on the provider thread it started on", () =>
@@ -562,7 +562,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
562
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
563
yield* runtime.startTurn(turnInput(forkedRow));
564
assert.equal((yield* Fiber.join(terminal))?.providerThreadId, forkedRow.id);
565
- }).pipe(Effect.scoped),
565
+ }),
566
);
567
568
// regression: #18315 OpenCode Go quota stops were not shown as usage limits
@@ -590,7 +590,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
590
message: "Provider rejected the request",
591
retryable: null,
592
});
593
- }).pipe(Effect.scoped),
593
+ }),
594
);
595
596
// OpenCode types an empty balance as provider.quota too, but answers it with
@@ -671,7 +671,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
671
message: error.message,
672
retryable: null,
673
});
674
- }).pipe(Effect.scoped),
674
+ }),
675
);
676
677
// regression: #29289 Claude weekly limits through claude-agent lost their usage-limit reset
@@ -700,7 +700,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
700
retryable: null,
701
resetAt: "2026-11-02T20:00:00.000Z",
702
});
703
- }).pipe(Effect.scoped),
703
+ }),
704
);
705
706
it.effect("ends the turn when its terminal event is one this build cannot decode", () =>
@@ -713,7 +713,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
713
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
714
yield* runtime.startTurn(turnInput(thread));
715
assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
716
- }).pipe(Effect.scoped),
716
+ }),
717
);
718
719
it.effect("keeps a turn running through a start event this build cannot decode", () =>
@@ -767,7 +767,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
767
event.turnItem.text === "DONE",
768
),
769
);
770
- }).pipe(Effect.scoped),
770
+ }),
771
);
772
773
it.effect("stops running turns on an external server when the session closes", () =>
@@ -843,7 +843,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
843
yield* Fiber.join(started);
844
assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
845
assert.lengthOf(prompts, 0);
846
- }).pipe(Effect.scoped),
846
+ }),
847
);
848
849
const childCreated = (child: string) => ({
@@ -1065,7 +1065,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1065
output: stop === "burst" ? "x".repeat(262127) + "FINAL DIAGNOSTIC\n" : "retained\n",
1066
});
1067
assert.isFalse(items.some((i) => i.type === "subagent"));
1068
- }).pipe(Effect.scoped),
1068
+ }),
1069
);
1070
1071
it.effect.each([
@@ -1234,7 +1234,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1234
output: "retained",
1235
});
1236
}
1237
- }).pipe(Effect.scoped),
1237
+ }),
1238
);
1239
1240
it.effect.each(["remove", "lookup", "output", "timeout"] as const)(
@@ -1366,7 +1366,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1366
if (failure === "remove")
1367
yield* runtime.stopTask!({ providerThread: thread, taskId: ids[0]! });
1368
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1369
- }).pipe(Effect.scoped),
1369
+ }),
1370
);
1371
1372
it.effect("keeps background subagents running when a turn is interrupted to restart it", () =>
@@ -1386,7 +1386,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1386
});
1387
assert.equal((yield* watch.terminal)?.status, "interrupted");
1388
assert.isTrue(yield* runtime.hasPendingBackgroundWork!);
1389
- }).pipe(Effect.scoped),
1389
+ }),
1390
);
1391
1392
it.effect("stops background subagents on a user Stop", () =>
@@ -1409,7 +1409,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1409
});
1410
assert.equal((yield* watch.terminal)?.status, "interrupted");
1411
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
1412
- }).pipe(Effect.scoped),
1412
+ }),
1413
);
1414
1415
it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
@@ -1457,7 +1457,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1457
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
1458
["completed", "completed"],
1459
);
1460
- }).pipe(Effect.scoped),
1460
+ }),
1461
);
1462
1463
it.effect(
@@ -1538,7 +1538,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1538
assert.isAbove(timeline.indexOf(false), timeline.indexOf("completed"));
1539
assert.strictEqual(timeline.at(-1), false);
1540
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1541
- }).pipe(Effect.scoped),
1541
+ }),
1542
);
1543
1544
const returnedRunning = (id: string): ProviderReplayEntry => ({
@@ -1768,7 +1768,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1768
);
1769
assert.deepEqual(watch.state.roster, []);
1770
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1771
- }).pipe(Effect.scoped),
1771
+ }),
1772
);
1773
1774
// regression: #21979 a failed background subagent pinned its thread as busy
@@ -1810,7 +1810,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1810
);
1811
assert.deepEqual(watch.state.roster, []);
1812
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
1813
- }).pipe(Effect.scoped),
1813
+ }),
1814
);
1815
1816
it.effect("settles every call that joined a running subagent with its one report", () =>
@@ -1834,7 +1834,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1834
Sleep: { status: "completed", result: "CHILD_OK" },
1835
Again: { status: "completed", result: "CHILD_OK" },
1836
});
1837
- }).pipe(Effect.scoped),
1837
+ }),
1838
);
1839
1840
it.effect("keeps a call to a finished subagent for its own run's report", () =>
@@ -1858,7 +1858,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
1858
});
1859
yield* watch.until(() => watch.calls.get("Again")?.status === "completed");
1860
assert.deepEqual(watch.calls.get("Again"), { status: "completed", result: "SECOND_OK" });
1861
- }).pipe(Effect.scoped),
1861
+ }),
1862
);
1863
1864
const MIDDLE = "ses_middle0000000000000000000";
@@ -2048,7 +2048,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2048
yield* watch.until(() => watch.rootVariant === "none");
2049
assert.isFalse(yield* runtime.hasPendingBackgroundWork!);
2050
assert.strictEqual(watch.pendingSnapshots.get(MIDDLE), false);
2051
- }).pipe(Effect.scoped),
2051
+ }),
2052
);
2053
2054
it.effect("clears the caller's pending work when a called session's held wake runs", () =>
@@ -2130,7 +2130,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2130
yield* watch.until(() => watch.variants.get(OTHER) === "none");
2131
assert.isFalse(watch.pendingSnapshots.get(OTHER));
2132
assert.isFalse(watch.pendingSnapshots.get(SESSION));
2133
- }).pipe(Effect.scoped),
2133
+ }),
2134
);
2135
2136
it.effect("stops a foreground subagent's background subagent after the turn ended", () =>
@@ -2167,7 +2167,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2167
yield* Deferred.await(offered);
2168
assert.equal(watch.deep.at(-1), "interrupted");
2169
assert.deepEqual([...watch.middleTurns.keys()], [`${MIDDLE}:turn:1`]);
2170
- }).pipe(Effect.scoped),
2170
+ }),
2171
);
2172
2173
it.effect("stops the turn a foreground subagent runs to answer its background subagent", () =>
@@ -2199,7 +2199,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2199
});
2200
yield* watch.until(() => watch.middleTurns.get(`${MIDDLE}:turn:2`) === "interrupted");
2201
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
2202
- }).pipe(Effect.scoped),
2202
+ }),
2203
);
2204
2205
const stopTimedOut: ReadonlyArray<ProviderReplayEntry> = [
@@ -2592,7 +2592,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2592
.pipe(Effect.flip);
2593
assert.equal(failed._tag, "ProviderAdapterInterruptError");
2594
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2595
- }).pipe(Effect.scoped),
2595
+ }),
2596
);
2597
2598
it.effect("gives a resumed session T3's rules when it was made with others", () =>
@@ -2619,7 +2619,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2619
modelSelection: bigPickle,
2620
runtimePolicy: policy(),
2621
});
2622
- }).pipe(Effect.scoped),
2622
+ }),
2623
);
2624
2625
it.effect("moves the session when the thread's worktree changed", () =>
@@ -2639,7 +2639,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2639
modelSelection: bigPickle,
2640
runtimePolicy: { ...policy(), cwd: "/work/opencode2-feature" },
2641
});
2642
- }).pipe(Effect.scoped),
2642
+ }),
2643
);
2644
2645
it.effect("breaks the thread and forgets it when the session was deleted outside T3", () =>
@@ -2663,7 +2663,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2663
const again = yield* runtime.startTurn(turnInput(thread)).pipe(Effect.flip);
2664
assert.equal(again._tag, "ProviderAdapterProtocolError");
2665
assert.include(again.message, "not registered");
2666
- }).pipe(Effect.scoped),
2666
+ }),
2667
);
2668
2669
it.effect("stops the requests a session still waits on when a restarted T3 loads it", () =>
@@ -2704,7 +2704,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2704
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
2705
yield* runtime.startTurn(turnInput(thread));
2706
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2707
- }).pipe(Effect.scoped),
2707
+ }),
2708
);
2709
2710
it.effect("ends the turn when an answer to its request cannot be delivered", () =>
@@ -2743,7 +2743,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2743
ended?.status === "failed" ? ended.failure.message : undefined,
2744
"OpenCode is waiting on a request T3 Code couldn't answer.",
2745
);
2746
- }).pipe(Effect.scoped),
2746
+ }),
2747
);
2748
2749
it.effect("counts an answer to a request OpenCode already dropped as delivered", () =>
@@ -2776,7 +2776,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2776
const request = yield* Fiber.join(requested);
2777
yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
2778
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2779
- }).pipe(Effect.scoped),
2779
+ }),
2780
);
2781
2782
it.effect("declines a form T3 cannot show with the reason, instead of leaving it open", () =>
@@ -2814,7 +2814,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2814
ended?.status === "failed" ? ended.failure.message : "",
2815
"asked for a link to open",
2816
);
2817
- }).pipe(Effect.scoped),
2817
+ }),
2818
);
2819
2820
it.effect("asks a subagent's permission request on the parent thread's turn", () =>
@@ -2860,7 +2860,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2860
assert.equal(request?.nativeRequestRef?.nativeId, shellAsk.data.id);
2861
yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
2862
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2863
- }).pipe(Effect.scoped),
2863
+ }),
2864
);
2865
2866
it.effect("keeps 'allow this session' in the session's rules, not OpenCode's saved grants", () =>
@@ -2898,7 +2898,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2898
decision: "acceptForSession",
2899
});
2900
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
2901
- }).pipe(Effect.scoped),
2901
+ }),
2902
);
2903
2904
it.effect("reads the agents again while a fresh server still lists none", () =>
@@ -2926,7 +2926,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
2926
.pipe(Effect.forkScoped);
2927
yield* TestClock.adjust("250 millis");
2928
assert.equal((yield* Fiber.join(created)).nativeThreadRef?.nativeId, SESSION);
2929
- }).pipe(Effect.scoped),
2929
+ }),
2930
);
2931
const reconnected = (
2932
active: Record<string, unknown>,
@@ -3079,7 +3079,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3079
e.turnItem.text === "Steer processed",
3080
),
3081
);
3082
- }).pipe(Effect.scoped),
3082
+ }),
3083
);
3084
3085
it.effect("does not end a turn from an earlier turn's history when its prompt is not there", () =>
@@ -3125,7 +3125,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3125
"An earlier turn's answer.",
3126
);
3127
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "interrupted" });
3128
- }).pipe(Effect.scoped),
3128
+ }),
3129
);
3130
3131
it.effect("ends a turn that finished while the stream was down with the server's outcome", () =>
@@ -3170,7 +3170,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3170
settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined;
3171
assert.deepInclude(usage, { usageStatus: "partial", inputTokens: 100, outputTokens: 10 });
3172
assert.notProperty(usage, "models");
3173
- }).pipe(Effect.scoped),
3173
+ }),
3174
);
3175
3176
it.effect("finishes a workspace command whose stream dropped before its inbox event", () =>
@@ -3233,7 +3233,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3233
);
3234
assert.include(texts, "HELLO WORLD");
3235
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3236
- }).pipe(Effect.scoped),
3236
+ }),
3237
);
3238
3239
it.effect("sends a $skill that appears once OpenCode finishes scanning the directory", () =>
@@ -3269,7 +3269,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3269
assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] });
3270
assert.isTrue(Exit.isSuccess(started));
3271
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3272
- }).pipe(Effect.scoped),
3272
+ }),
3273
);
3274
3275
it.effect("keeps owned work through a stalled reconciliation without releasing its server", () =>
@@ -3308,7 +3308,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3308
yield* Deferred.succeed(resume, undefined);
3309
yield* Fiber.join(ended);
3310
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3311
- }).pipe(Effect.scoped),
3311
+ }),
3312
);
3313
3314
it.effect("reconciles a session deleted after the active snapshot", () =>
@@ -3401,7 +3401,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3401
ended.map((event) => event.providerThreadId),
3402
[thread.id, other.id],
3403
);
3404
- }).pipe(Effect.scoped),
3404
+ }),
3405
);
3406
3407
it.effect.each([503, 429])(
@@ -3445,7 +3445,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3445
yield* Queue.take(attempts);
3446
yield* Deferred.succeed(allowRecovery, undefined);
3447
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3448
- }).pipe(Effect.scoped),
3448
+ }),
3449
);
3450
3451
it.effect(
@@ -3479,7 +3479,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3479
});
3480
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3481
assert.deepInclude(prompts[0], { skills: [{ id: "greet" }] });
3482
- }).pipe(Effect.scoped),
3482
+ }),
3483
);
3484
3485
it.effect.each([
@@ -3520,7 +3520,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3520
}
3521
yield* Queue.take(attempts);
3522
assert.equal((yield* Fiber.join(terminal))?.status, "failed");
3523
- }).pipe(Effect.scoped),
3523
+ }),
3524
);
3525
3526
it.effect.each(["lists", "stream"] as const)(
@@ -3606,7 +3606,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3606
answers: { q0: "Red" },
3607
});
3608
assert.equal(yield* Deferred.await(ended), "completed");
3609
- }).pipe(Effect.scoped),
3609
+ }),
3610
);
3611
3612
it.effect(
@@ -3655,7 +3655,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3655
yield* Deferred.await(cancelled);
3656
assert.equal((yield* Fiber.join(terminal))?.status, "interrupted");
3657
assert.equal(runtime.providerSession.status, "ready");
3658
- }).pipe(Effect.scoped),
3658
+ }),
3659
);
3660
3661
it.effect("releases a recovering session on shutdown without waiting for its HTTP read", () =>
@@ -3689,7 +3689,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3689
yield* Scope.close(sessionScope, Exit.void);
3690
yield* Deferred.await(cancelled);
3691
assert.equal(borrowers.current, 0);
3692
- }).pipe(Effect.scoped),
3692
+ }),
3693
);
3694
3695
it.effect("honors a confirmed Stop during recovery and ignores its late backfill", () =>
@@ -3758,7 +3758,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3758
event.type === "turn_item.updated" && event.turnItem.type === "assistant_message",
3759
),
3760
);
3761
- }).pipe(Effect.scoped),
3761
+ }),
3762
);
3763
3764
it.effect("keeps a background child's requests when its parent stops during reconciliation", () =>
@@ -3837,7 +3837,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3837
requestId: requests.get(form.id)!.id,
3838
answers: { q0: "Red" },
3839
});
3840
- }).pipe(Effect.scoped),
3840
+ }),
3841
);
3842
3843
it.effect("keeps a turn still running after a reconnect open for its next events", () =>
@@ -3872,7 +3872,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3872
"Arrived on the new stream.",
3873
]);
3874
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3875
- }).pipe(Effect.scoped),
3875
+ }),
3876
);
3877
3878
it.effect("continues a reply still streaming at reconnect from the text already shown", () =>
@@ -3915,7 +3915,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3915
"Sent before the stream dropped and after it came back.",
3916
"Sent before the stream dropped and after it came back.",
3917
]);
3918
- }).pipe(Effect.scoped),
3918
+ }),
3919
);
3920
3921
it.effect("shows a permission asked while the stream was down, and answers it", () =>
@@ -3943,7 +3943,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3943
assert.equal(request?.nativeRequestRef?.nativeId, shellAsk.data.id);
3944
yield* runtime.respondToRuntimeRequest({ requestId: request!.id, decision: "accept" });
3945
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
3946
- }).pipe(Effect.scoped),
3946
+ }),
3947
);
3948
3949
it.effect("settles a request OpenCode no longer lists after the stream came back", () =>
@@ -3971,7 +3971,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
3971
);
3972
assert.deepEqual(statuses, ["pending", "cancelled"]);
3973
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
3974
- }).pipe(Effect.scoped),
3974
+ }),
3975
);
3976
3977
it.effect.each(["delegate_task", "html_preview", "mcp__acme__edit_document"])(
@@ -4034,7 +4034,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4034
toolOutputImages(last?.type === "dynamic_tool" ? last.output : null),
4035
toolName !== "delegate_task" ? [{ mimeType: "image/png", data: "iVBORw0KGgo=" }] : [],
4036
);
4037
- }).pipe(Effect.scoped),
4037
+ }),
4038
);
4039
4040
it.effect.each(["completed", "error", "cancelled"] as const)(
@@ -4143,7 +4143,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4143
);
4144
assert.isTrue(rosters.some((tasks) => tasks.some((task) => task.taskId === "image_test")));
4145
assert.deepEqual(rosters.at(-1), []);
4146
- }).pipe(Effect.scoped),
4146
+ }),
4147
);
4148
4149
it.effect.each(["history", "list", "late-preview"] as const)(
@@ -4283,7 +4283,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4283
e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_gap"),
4284
),
4285
);
4286
- }).pipe(Effect.scoped),
4286
+ }),
4287
);
4288
4289
it.effect("settles a recovered image outcome when preview I/O is interrupted", () =>
@@ -4457,7 +4457,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4457
e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_lost"),
4458
),
4459
);
4460
- }).pipe(Effect.scoped),
4460
+ }),
4461
);
4462
4463
it.effect("projects successful native todo updates into one checklist", () =>
@@ -4582,7 +4582,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4582
items.find((item) => item.nativeItemRef?.nativeId === "call-malformed"),
4583
{ type: "dynamic_tool", status: "completed" },
4584
);
4585
- }).pipe(Effect.scoped),
4585
+ }),
4586
);
4587
4588
it.effect("recovers native todo updates missed during reconnect", () =>
@@ -4625,7 +4625,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4625
[["Saved during disconnect", "running"]],
4626
);
4627
assert.include(turnItems(collected), "todo_list:completed");
4628
- }).pipe(Effect.scoped),
4628
+ }),
4629
);
4630
4631
it.effect("stores a shell command that exits non-zero as failed", () =>
@@ -4675,7 +4675,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4675
.findLast((node) => node.id === item?.nodeId)?.status,
4676
"failed",
4677
);
4678
- }).pipe(Effect.scoped),
4678
+ }),
4679
);
4680
4681
it.effect("re-registers T3 MCP each turn and drops its instructions when adding fails", () =>
@@ -4740,7 +4740,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4740
yield* Fiber.join(started);
4741
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
4742
}
4743
- }).pipe(Effect.scoped),
4743
+ }),
4744
);
4745
4746
it.effect("registers a long thread id's MCP server under a name OpenCode accepts", () =>
@@ -4805,7 +4805,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
4805
yield* Fiber.join(started);
4806
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
4807
yield* runtime.unloadThread!({ providerThread: thread });
4808
- }).pipe(Effect.scoped),
4808
+ }),
4809
);
4810
4811
// regression: #16142 OpenCode 2 threads were missing T3 Code's MCP tools
@@ -5133,7 +5133,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5133
snapshot.providerThread.nativeConversationHeadRef?.nativeId,
5134
history.data[0]!.id,
5135
);
5136
- }).pipe(Effect.scoped),
5136
+ }),
5137
);
5138
5139
it.effect("ends a turn before re-reading a model list that never answers", () =>
@@ -5161,7 +5161,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5161
yield* runtime.startTurn(turnInput(thread));
5162
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
5163
for (let i = 0; i < 20; i++) yield* Effect.yieldNow;
5164
- }).pipe(Effect.scoped),
5164
+ }),
5165
);
5166
5167
it.effect("leaves models unknown when a step ends without a seen start", () =>
@@ -5195,7 +5195,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5195
settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined;
5196
assert.deepInclude(usage, { usageStatus: "complete", inputTokens: 20, outputTokens: 2 });
5197
assert.notProperty(usage, "models");
5198
- }).pipe(Effect.scoped),
5198
+ }),
5199
);
5200
5201
it.effect("reports cache writes as cache creation, not only as input", () =>
@@ -5231,7 +5231,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5231
outputTokens: 40,
5232
},
5233
);
5234
- }).pipe(Effect.scoped),
5234
+ }),
5235
);
5236
5237
const ASSISTANT = "msg_0eb735d5b001oAFVeY5jz3WD4Z";
@@ -5335,7 +5335,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5335
],
5336
);
5337
assert.deepInclude(seen.at(-1), { type: "turn.terminal", status: ended, failure: null });
5338
- }).pipe(Effect.scoped),
5338
+ }),
5339
);
5340
5341
// regression: #15672 OpenCode 2 provider retries ran silently instead of showing
@@ -5405,7 +5405,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5405
),
5406
);
5407
}
5408
- }).pipe(Effect.scoped),
5408
+ }),
5409
);
5410
5411
it.effect("replaces a provider retry with the error that failed the turn", () =>
@@ -5488,7 +5488,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5488
retry: lastRetry,
5489
retryStartedAt: startedAt,
5490
});
5491
- }).pipe(Effect.scoped),
5491
+ }),
5492
);
5493
5494
it.effect("reports each directory's own limit for a model its project config changed", () =>
@@ -5547,7 +5547,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5547
turn?.type === "provider_turn.updated" ? turn.providerTurn.tokenUsage?.maxTokens : null,
5548
48000,
5549
);
5550
- }).pipe(Effect.scoped),
5550
+ }),
5551
);
5552
5553
it.effect("rejects unreadable rollback history before cutting the native session", () =>
@@ -5597,7 +5597,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5597
.pipe(Effect.flip);
5598
assert.equal(failure._tag, "ProviderAdapterRollbackThreadError");
5599
assert.include(Cause.pretty(Cause.fail(failure)), '["recent"]');
5600
- }).pipe(Effect.scoped),
5600
+ }),
5601
);
5602
5603
it.effect("clears a staged revert whose commit failed, before the next prompt too", () =>
@@ -5665,7 +5665,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5665
assert.isTrue(Exit.isFailure(rollback));
5666
yield* runtime.startTurn(turnInput(thread));
5667
assert.equal((yield* terminalOf(runtime))?.status, "completed");
5668
- }).pipe(Effect.scoped),
5668
+ }),
5669
);
5670
5671
it.effect("offers no follow-up for the execution a cleared revert starts", () =>
@@ -5732,7 +5732,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5732
assert.isTrue(Exit.isFailure(rollback));
5733
assert.lengthOf(offers, 0);
5734
assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread));
5735
- }).pipe(Effect.scoped),
5735
+ }),
5736
);
5737
5738
it.effect("prompts under ids no other session on the server can hold", () =>
@@ -5889,7 +5889,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
5889
),
5890
["running", "ready"],
5891
);
5892
- }).pipe(Effect.scoped),
5892
+ }),
5893
);
5894
5895
it.effect.each([
@@ -6048,7 +6048,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6048
attemptId: RunAttemptId.make("attempt:opencode2-adapter:3"),
6049
});
6050
yield* Deferred.await(thirdEnded);
6051
- }).pipe(Effect.scoped),
6051
+ }),
6052
);
6053
6054
it.effect("drops the turns a rollback cut from the snapshot it returns", () =>
@@ -6117,7 +6117,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6117
snapshot.providerTurns.map((turn) => turn.id),
6118
[first!.id],
6119
);
6120
- }).pipe(Effect.scoped),
6120
+ }),
6121
);
6122
6123
it.effect("starts a turn sent during a rollback only once the cut is made", () =>
@@ -6168,7 +6168,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6168
yield* runtime.startTurn({ ...turnInput(thread), providerTurnOrdinal: 1 });
6169
yield* Fiber.join(rollback);
6170
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
6171
- }).pipe(Effect.scoped),
6171
+ }),
6172
);
6173
6174
it.effect.each([
@@ -6252,7 +6252,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6252
[kept.id],
6253
);
6254
}
6255
- }).pipe(Effect.scoped),
6255
+ }),
6256
);
6257
6258
it.effect("refuses to fork a session while OpenCode runs a follow-up on it", () =>
@@ -6274,7 +6274,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6274
})
6275
.pipe(Effect.flip);
6276
assert.equal(refused._tag, "ProviderAdapterProtocolError");
6277
- }).pipe(Effect.scoped),
6277
+ }),
6278
);
6279
6280
// regression: #24549 a Stop whose interrupted event never arrives blocked the next fork
@@ -6320,7 +6320,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6320
const [first, second] = yield* Fiber.join(ended);
6321
assert.equal(first?.status, "interrupted");
6322
assert.equal(second?.failure?.message, "second turn failed");
6323
- }).pipe(Effect.scoped),
6323
+ }),
6324
);
6325
6326
it.effect("refuses to fork a stopped session OpenCode still runs", () =>
@@ -6346,7 +6346,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6346
})
6347
.pipe(Effect.flip);
6348
assert.equal(refused._tag, "ProviderAdapterProtocolError");
6349
- }).pipe(Effect.scoped),
6349
+ }),
6350
);
6351
6352
it.effect("moves a fork into its target thread's worktree before the first prompt", () =>
@@ -6375,7 +6375,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6375
runtimePolicy: { ...policy(), cwd: target },
6376
});
6377
assert.equal(forked.nativeThreadRef?.nativeId, FORK);
6378
- }).pipe(Effect.scoped),
6378
+ }),
6379
);
6380
6381
const continued = (after: ReadonlyArray<ProviderReplayEntry>, external?: string) =>
@@ -6499,7 +6499,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6499
sourceProviderTurns: [first, second],
6500
});
6501
assert.equal(forked.nativeThreadRef?.nativeId, FORK);
6502
- }).pipe(Effect.scoped),
6502
+ }),
6503
);
6504
6505
it.effect(
@@ -6552,7 +6552,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6552
snapshot.providerTurns.map((turn) => turn.id),
6553
[first.id],
6554
);
6555
- }).pipe(Effect.scoped),
6555
+ }),
6556
);
6557
6558
it.effect("keeps a subagent a stopped background reply started off the next turn", () =>
@@ -6739,7 +6739,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6739
),
6740
[],
6741
);
6742
- }).pipe(Effect.scoped),
6742
+ }),
6743
);
6744
6745
// regression: #14752 continuations replayed background replies that were not theirs
@@ -6828,7 +6828,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
6828
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
6829
["completed", "completed"],
6830
);
6831
- }).pipe(Effect.scoped),
6831
+ }),
6832
);
6833
6834
it.effect("replays only its own background reply into a continuation turn", () =>
@@ -7064,7 +7064,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7064
snapshot.providerTurns.map((turn) => turn.id),
7065
[first!.id],
7066
);
7067
- }).pipe(Effect.scoped),
7067
+ }),
7068
);
7069
7070
it.effect(
@@ -7186,7 +7186,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7186
snapshot.providerTurns.map((turn) => turn.id),
7187
[first!.id],
7188
);
7189
- }).pipe(Effect.scoped),
7189
+ }),
7190
);
7191
7192
it.effect("shows a second prompt another client sent while its continuation was pending", () =>
@@ -7269,7 +7269,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7269
],
7270
["user: first?", "user: second?", "assistant: Both!"],
7271
);
7272
- }).pipe(Effect.scoped),
7272
+ }),
7273
);
7274
7275
it.effect("shows a question asked while OpenCode wakes for a background reply", () =>
@@ -7377,7 +7377,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7377
yield* Deferred.await(ended);
7378
const last = collected.findLast((event) => event.type === "turn.terminal");
7379
assert.equal(last?.type === "turn.terminal" ? last.status : undefined, "completed");
7380
- }).pipe(Effect.scoped),
7380
+ }),
7381
);
7382
7383
it.effect("ends a follow-up turn a steer joined exactly once", () =>
@@ -7523,7 +7523,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7523
),
7524
);
7525
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
7526
- }).pipe(Effect.scoped),
7526
+ }),
7527
);
7528
7529
// regression: #35872
@@ -7547,7 +7547,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7547
const input = turnInput(thread);
7548
yield* runtime.startTurn({ ...input, message: { ...input.message, text: "/goal clear" } });
7549
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
7550
- }).pipe(Effect.scoped),
7550
+ }),
7551
);
7552
7553
it.effect("reads an existing OpenCode 2.2.5 goal when resuming a session", () =>
@@ -7582,7 +7582,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7582
checks: 2,
7583
lastCheck: "Checked proof.txt",
7584
});
7585
- }).pipe(Effect.scoped),
7585
+ }),
7586
);
7587
7588
it.effect.each([
@@ -7671,7 +7671,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7671
),
7672
);
7673
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
7674
- }).pipe(Effect.scoped),
7674
+ }),
7675
);
7676
7677
it.effect("does not replace a newer goal event with an older goal RPC response", () =>
@@ -7716,7 +7716,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7716
: undefined,
7717
"paused",
7718
);
7719
- }).pipe(Effect.scoped),
7719
+ }),
7720
);
7721
7722
it.effect.each(["unreadable", "stalled"] as const)(
@@ -7760,7 +7760,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7760
}
7761
const collected = yield* Fiber.join(events);
7762
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
7763
- }).pipe(Effect.scoped),
7763
+ }),
7764
);
7765
7766
it.effect.each([
@@ -7826,7 +7826,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7826
),
7827
);
7828
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
7829
- }).pipe(Effect.scoped),
7829
+ }),
7830
);
7831
7832
it.effect.each(["show", "pause", "clear"] as const)(
@@ -7896,7 +7896,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7896
e.turnItem.text === "Replacement still tracked",
7897
),
7898
);
7899
- }).pipe(Effect.scoped),
7899
+ }),
7900
);
7901
7902
it.effect.each(["show", "pause", "clear"] as const)(
@@ -7937,7 +7937,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
7937
goal?.status ?? null,
7938
);
7939
assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });
7940
- }).pipe(Effect.scoped),
7940
+ }),
7941
);
7942
});
7943
apps/server/src/orchestration-v2/BackgroundWorkStop.integration.test.ts
+865
-875
@@ -51,981 +51,971 @@ const stopEarlierBackgroundWork = ({
51
readonly workflowMember?: boolean;
52
readonly stalledRun?: "missing-session-terminal" | "returned-interrupt" | "superseded-attempt";
53
}) =>
54
- Effect.scoped(
55
- Effect.gen(function* () {
56
- const cwd = yield* checkpointWorkspace("background-work-stop");
57
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
58
- const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
59
- const interrupts: ProviderAdapter.ProviderAdapterV2InterruptInput[] = [];
60
- const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
61
- instanceId,
62
- driver,
63
- getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
64
- planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
65
- openSession: (input) =>
66
- Effect.gen(function* () {
67
- const now = yield* DateTime.now;
68
- return {
69
- instanceId,
54
+ Effect.gen(function* () {
55
+ const cwd = yield* checkpointWorkspace("background-work-stop");
56
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
57
+ const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
58
+ const interrupts: ProviderAdapter.ProviderAdapterV2InterruptInput[] = [];
59
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
60
+ instanceId,
61
+ driver,
62
+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
63
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
64
+ openSession: (input) =>
65
+ Effect.gen(function* () {
66
+ const now = yield* DateTime.now;
67
+ return {
68
+ instanceId,
69
+ driver,
70
+ providerSessionId: input.providerSessionId,
71
+ providerSession: {
72
+ id: input.providerSessionId,
73
driver,
71
- providerSessionId: input.providerSessionId,
72
- providerSession: {
73
- id: input.providerSessionId,
74
+ providerInstanceId: instanceId,
75
+ status: "ready",
76
+ cwd,
77
+ model: modelSelection.model,
78
+ capabilities: CodexProviderCapabilitiesV2,
79
+ createdAt: now,
80
+ updatedAt: now,
81
+ lastError: null,
82
+ },
83
+ events: Stream.fromQueue(events),
84
+ ...(failedStart
85
+ ? {
86
+ hasPendingBackgroundWorkForThread: (providerThread) =>
87
+ Effect.gen(function* () {
88
+ if (
89
+ !interrupts.some((input) => input.providerThread.id === providerThread.id)
90
+ ) {
91
+ return false;
92
+ }
93
+ if (backgroundWorkAfterStop === "unknown") {
94
+ return yield* Effect.die("Background work probe failed");
95
+ }
96
+ return backgroundWorkAfterStop === "running";
97
+ }),
98
+ }
99
+ : {}),
100
+ ensureThread: ({ threadId }) =>
101
+ Effect.succeed({
102
+ id: ProviderThreadId.make(`provider-thread:codex:${threadId}`),
103
driver,
104
providerInstanceId: instanceId,
76
- status: "ready",
77
- cwd,
78
- model: modelSelection.model,
79
- capabilities: CodexProviderCapabilitiesV2,
105
+ providerSessionId: input.providerSessionId,
106
+ appThreadId: threadId,
107
+ ownerNodeId: null,
108
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
109
+ nativeConversationHeadRef: null,
110
+ status: "idle",
111
+ firstRunOrdinal: null,
112
+ lastRunOrdinal: null,
113
+ handoffIds: [],
114
+ forkedFrom: null,
115
createdAt: now,
116
updatedAt: now,
82
- lastError: null,
83
- },
84
- events: Stream.fromQueue(events),
85
- ...(failedStart
86
- ? {
87
- hasPendingBackgroundWorkForThread: (providerThread) =>
88
- Effect.gen(function* () {
89
- if (
90
- !interrupts.some((input) => input.providerThread.id === providerThread.id)
91
- ) {
92
- return false;
93
- }
94
- if (backgroundWorkAfterStop === "unknown") {
95
- return yield* Effect.die("Background work probe failed");
96
- }
97
- return backgroundWorkAfterStop === "running";
98
- }),
99
- }
100
- : {}),
101
- ensureThread: ({ threadId }) =>
102
- Effect.succeed({
103
- id: ProviderThreadId.make(`provider-thread:codex:${threadId}`),
117
+ }),
118
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
119
+ startTurn: (turn) =>
120
+ Effect.gen(function* () {
121
+ started.push(turn);
122
+ yield* Queue.offer(events, {
123
+ type: "provider_turn.updated",
124
driver,
105
- providerInstanceId: instanceId,
106
- providerSessionId: input.providerSessionId,
107
- appThreadId: threadId,
108
- ownerNodeId: null,
109
- nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
110
- nativeConversationHeadRef: null,
111
- status: "idle",
112
- firstRunOrdinal: null,
113
- lastRunOrdinal: null,
114
- handoffIds: [],
115
- forkedFrom: null,
116
- createdAt: now,
117
- updatedAt: now,
118
- }),
119
- resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
120
- startTurn: (turn) =>
121
- Effect.gen(function* () {
122
- started.push(turn);
123
- yield* Queue.offer(events, {
124
- type: "provider_turn.updated",
125
- driver,
126
- providerTurn: {
127
- id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
128
- providerThreadId: turn.providerThread.id,
129
- nodeId: turn.rootNodeId,
130
- runAttemptId: turn.attemptId,
131
- nativeTurnRef: {
132
- driver,
133
- nativeId: `native:${turn.attemptId}`,
134
- strength: "strong",
135
- },
136
- ordinal: turn.providerTurnOrdinal,
137
- status: "running",
138
- startedAt: now,
139
- completedAt: null,
125
+ providerTurn: {
126
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
127
+ providerThreadId: turn.providerThread.id,
128
+ nodeId: turn.rootNodeId,
129
+ runAttemptId: turn.attemptId,
130
+ nativeTurnRef: {
131
+ driver,
132
+ nativeId: `native:${turn.attemptId}`,
133
+ strength: "strong",
134
},
141
- });
142
- }),
143
- steerTurn: () => Effect.die("unused"),
144
- interruptTurn: (interrupt) =>
145
- Effect.sync(() => {
146
- interrupts.push(interrupt);
147
- }),
148
- respondToRuntimeRequest: () => Effect.die("unused"),
149
- readThreadSnapshot: () => Effect.die("unused"),
150
- rollbackThread: () => Effect.die("unused"),
151
- forkThread: () => Effect.die("unused"),
152
- };
153
- }),
154
- };
155
- yield* Effect.gen(function* () {
156
- const orchestrator = yield* Orchestrator.OrchestratorV2;
157
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
158
- const sink = yield* EventSink.EventSinkV2;
159
- const threadId = ThreadId.make("thread:background-work-stop");
160
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
161
- orchestrator.streamDomainEvents.pipe(
162
- Stream.filter(predicate),
163
- Stream.take(1),
164
- Stream.runDrain,
165
- Effect.forkScoped,
166
- );
167
- yield* orchestrator.dispatch({
168
- type: "thread.create",
169
- commandId: CommandId.make("create"),
170
- threadId,
171
- projectId: ProjectId.make("project:background-work-stop"),
172
- title: "Background work stop",
173
- modelSelection,
174
- runtimeMode: "full-access",
175
- interactionMode: "default",
176
- branch: null,
177
- worktreePath: cwd,
178
- createdBy: "user",
179
- creationSource: "web",
180
- });
181
- const running = yield* watch(
182
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
135
+ ordinal: turn.providerTurnOrdinal,
136
+ status: "running",
137
+ startedAt: now,
138
+ completedAt: null,
139
+ },
140
+ });
141
+ }),
142
+ steerTurn: () => Effect.die("unused"),
143
+ interruptTurn: (interrupt) =>
144
+ Effect.sync(() => {
145
+ interrupts.push(interrupt);
146
+ }),
147
+ respondToRuntimeRequest: () => Effect.die("unused"),
148
+ readThreadSnapshot: () => Effect.die("unused"),
149
+ rollbackThread: () => Effect.die("unused"),
150
+ forkThread: () => Effect.die("unused"),
151
+ };
152
+ }),
153
+ };
154
+ yield* Effect.gen(function* () {
155
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
156
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
157
+ const sink = yield* EventSink.EventSinkV2;
158
+ const threadId = ThreadId.make("thread:background-work-stop");
159
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
160
+ orchestrator.streamDomainEvents.pipe(
161
+ Stream.filter(predicate),
162
+ Stream.take(1),
163
+ Stream.runDrain,
164
+ Effect.forkScoped,
165
);
166
+ yield* orchestrator.dispatch({
167
+ type: "thread.create",
168
+ commandId: CommandId.make("create"),
169
+ threadId,
170
+ projectId: ProjectId.make("project:background-work-stop"),
171
+ title: "Background work stop",
172
+ modelSelection,
173
+ runtimeMode: "full-access",
174
+ interactionMode: "default",
175
+ branch: null,
176
+ worktreePath: cwd,
177
+ createdBy: "user",
178
+ creationSource: "web",
179
+ });
180
+ const running = yield* watch(
181
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
182
+ );
183
+ yield* orchestrator.dispatch({
184
+ type: "message.dispatch",
185
+ commandId: CommandId.make("start-dev-server"),
186
+ threadId,
187
+ messageId: MessageId.make("message:start-dev-server"),
188
+ text: "Start the dev server",
189
+ attachments: [],
190
+ dispatchMode: { type: "start_immediately" },
191
+ createdBy: "user",
192
+ creationSource: "web",
193
+ });
194
+ yield* worker.drain();
195
+ yield* Fiber.join(running);
196
+ if (wakeAfterStop) {
197
+ const send = (id: string, provider = false) =>
198
+ orchestrator.dispatch({
199
+ type: "message.dispatch",
200
+ commandId: CommandId.make(id),
201
+ threadId,
202
+ messageId: MessageId.make(`message:${id}`),
203
+ text: id,
204
+ attachments: [],
205
+ dispatchMode: { type: "queue_after_active" },
206
+ createdBy: provider ? "agent" : "user",
207
+ creationSource: provider ? "provider" : "web",
208
+ });
209
+ yield* send("follow-up");
210
yield* orchestrator.dispatch({
185
- type: "message.dispatch",
186
- commandId: CommandId.make("start-dev-server"),
211
+ type: "thread.stop",
212
+ commandId: CommandId.make("stop"),
213
threadId,
188
- messageId: MessageId.make("message:start-dev-server"),
189
- text: "Start the dev server",
190
- attachments: [],
191
- dispatchMode: { type: "start_immediately" },
192
- createdBy: "user",
193
- creationSource: "web",
214
});
215
+ // Stop is committed, but its provider interrupt has not run yet.
216
+ yield* send("Background task completed.", true);
217
+ const [stopped, followUp, wake] = (yield* orchestrator.getThreadProjection(threadId)).runs;
218
+ assert.equal(stopped?.status, "running");
219
+ assert.isTrue(followUp?.queueHeld);
220
+ assert.isTrue(wake?.queueHeld);
221
+
222
yield* worker.drain();
196
- yield* Fiber.join(running);
197
- if (wakeAfterStop) {
198
- const send = (id: string, provider = false) =>
199
- orchestrator.dispatch({
200
- type: "message.dispatch",
201
- commandId: CommandId.make(id),
202
- threadId,
203
- messageId: MessageId.make(`message:${id}`),
204
- text: id,
205
- attachments: [],
206
- dispatchMode: { type: "queue_after_active" },
207
- createdBy: provider ? "agent" : "user",
208
- creationSource: provider ? "provider" : "web",
209
- });
210
- yield* send("follow-up");
211
- yield* orchestrator.dispatch({
212
- type: "thread.stop",
213
- commandId: CommandId.make("stop"),
223
+ yield* orchestrator.resumeQueuedRuns;
224
+ yield* worker.drain();
225
+ const after = yield* orchestrator.getThreadProjection(threadId);
226
+ assert.deepEqual(
227
+ after.runs.map((run) => run.status),
228
+ ["interrupted", "queued", "queued"],
229
+ );
230
+ assert.isTrue(after.runs.find((run) => run.id === followUp?.id)?.queueHeld);
231
+ assert.isTrue(after.runs.find((run) => run.id === wake?.id)?.queueHeld);
232
+ assert.lengthOf(started, 1);
233
+ return;
234
+ }
235
+ const first = started[0]!;
236
+ const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
237
+ const devServerId = TurnItemId.make("turn-item:dev-server");
238
+ const now = yield* DateTime.now;
239
+ yield* sink.write({
240
+ events: [
241
+ {
242
+ id: EventId.make("dev-server"),
243
+ type: "turn-item.updated",
244
threadId,
215
- });
216
- // Stop is committed, but its provider interrupt has not run yet.
217
- yield* send("Background task completed.", true);
218
- const [stopped, followUp, wake] = (yield* orchestrator.getThreadProjection(threadId))
219
- .runs;
220
- assert.equal(stopped?.status, "running");
221
- assert.isTrue(followUp?.queueHeld);
222
- assert.isTrue(wake?.queueHeld);
223
-
224
- yield* worker.drain();
225
- yield* orchestrator.resumeQueuedRuns;
226
- yield* worker.drain();
227
- const after = yield* orchestrator.getThreadProjection(threadId);
228
- assert.deepEqual(
229
- after.runs.map((run) => run.status),
230
- ["interrupted", "queued", "queued"],
245
+ runId: first.runId,
246
+ occurredAt: now,
247
+ payload: {
248
+ id: devServerId,
249
+ threadId,
250
+ runId: first.runId,
251
+ nodeId: first.rootNodeId,
252
+ providerThreadId: codexTurn.providerThreadId,
253
+ providerTurnId: codexTurn.id,
254
+ nativeItemRef: null,
255
+ parentItemId: null,
256
+ ordinal: 100,
257
+ status: "running",
258
+ title: null,
259
+ startedAt: now,
260
+ completedAt: null,
261
+ updatedAt: now,
262
+ type: "command_execution",
263
+ input: "vp run dev --share",
264
+ },
265
+ },
266
+ ],
267
+ });
268
+ if (stalledRun !== undefined) {
269
+ const before = yield* orchestrator.getThreadProjection(threadId);
270
+ const run = before.runs[0]!;
271
+ const node = before.nodes.find((candidate) => candidate.id === run.rootNodeId)!;
272
+ const attempt = before.attempts[0]!;
273
+ if (stalledRun === "missing-session-terminal") {
274
+ const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
275
+ const failed = yield* watch(
276
+ (event) => event.type === "run.updated" && event.payload.status === "failed",
277
);
232
- assert.isTrue(after.runs.find((run) => run.id === followUp?.id)?.queueHeld);
233
- assert.isTrue(after.runs.find((run) => run.id === wake?.id)?.queueHeld);
234
- assert.lengthOf(started, 1);
235
- return;
278
+ yield* sessions.release({
279
+ providerSessionId: first.providerThread.providerSessionId!,
280
+ reason: "runtime_error",
281
+ });
282
+ yield* Fiber.join(failed);
283
+ yield* sink.write({
284
+ events: [
285
+ {
286
+ id: EventId.make("stale-run"),
287
+ type: "run.updated",
288
+ threadId,
289
+ occurredAt: now,
290
+ payload: run,
291
+ },
292
+ {
293
+ id: EventId.make("stale-node"),
294
+ type: "node.updated",
295
+ threadId,
296
+ occurredAt: now,
297
+ payload: node,
298
+ },
299
+ {
300
+ id: EventId.make("stale-attempt"),
301
+ type: "run-attempt.updated",
302
+ threadId,
303
+ occurredAt: now,
304
+ payload: attempt,
305
+ },
306
+ ],
307
+ });
308
+ }
309
+ const messageId = MessageId.make("partial-output");
310
+ const item = before.turnItems.find((candidate) => candidate.id === devServerId)!;
311
+ assert.ok(item.type === "command_execution");
312
+ const terminalProviderTurn = stalledRun.endsWith("-terminal");
313
+ if (terminalProviderTurn) {
314
+ yield* sink.write({
315
+ events: [
316
+ {
317
+ id: EventId.make("terminal-provider-turn"),
318
+ type: "provider-turn.updated",
319
+ threadId,
320
+ occurredAt: now,
321
+ payload: { ...codexTurn, status: "completed", completedAt: now },
322
+ },
323
+ ...(stalledRun === "missing-session-terminal"
324
+ ? [
325
+ {
326
+ id: EventId.make("completed-dev-server"),
327
+ type: "turn-item.updated" as const,
328
+ threadId,
329
+ occurredAt: now,
330
+ payload: { ...item, status: "completed" as const, completedAt: now },
331
+ },
332
+ ]
333
+ : []),
334
+ ],
335
+ });
336
}
237
- const first = started[0]!;
238
- const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
239
- const devServerId = TurnItemId.make("turn-item:dev-server");
240
- const now = yield* DateTime.now;
337
yield* sink.write({
338
events: [
339
{
244
- id: EventId.make("dev-server"),
245
- type: "turn-item.updated",
340
+ id: EventId.make("partial-message"),
341
+ type: "message.updated",
342
threadId,
247
- runId: first.runId,
343
+ runId: run.id,
344
occurredAt: now,
345
payload: {
250
- id: devServerId,
346
+ id: messageId,
347
threadId,
252
- runId: first.runId,
253
- nodeId: first.rootNodeId,
348
+ runId: run.id,
349
+ nodeId: node.id,
350
+ role: "assistant",
351
+ text: "Partial output",
352
+ attachments: [],
353
+ streaming: true,
354
+ createdBy: "agent",
355
+ creationSource: "provider",
356
+ createdAt: now,
357
+ updatedAt: now,
358
+ },
359
+ },
360
+ {
361
+ id: EventId.make("partial-item"),
362
+ type: "turn-item.updated",
363
+ threadId,
364
+ runId: run.id,
365
+ occurredAt: now,
366
+ payload: {
367
+ ...item,
368
providerThreadId: codexTurn.providerThreadId,
369
providerTurnId: codexTurn.id,
256
- nativeItemRef: null,
257
- parentItemId: null,
258
- ordinal: 100,
259
- status: "running",
260
- title: null,
261
- startedAt: now,
262
- completedAt: null,
263
- updatedAt: now,
264
- type: "command_execution",
265
- input: "vp run dev --share",
370
+ id: TurnItemId.make("partial-output"),
371
+ type: "assistant_message",
372
+ messageId,
373
+ text: "Partial output",
374
+ streaming: true,
375
},
376
},
377
],
378
});
270
- if (stalledRun !== undefined) {
271
- const before = yield* orchestrator.getThreadProjection(threadId);
272
- const run = before.runs[0]!;
273
- const node = before.nodes.find((candidate) => candidate.id === run.rootNodeId)!;
274
- const attempt = before.attempts[0]!;
275
- if (stalledRun === "missing-session-terminal") {
276
- const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
277
- const failed = yield* watch(
278
- (event) => event.type === "run.updated" && event.payload.status === "failed",
279
- );
280
- yield* sessions.release({
281
- providerSessionId: first.providerThread.providerSessionId!,
282
- reason: "runtime_error",
283
- });
284
- yield* Fiber.join(failed);
285
- yield* sink.write({
286
- events: [
287
- {
288
- id: EventId.make("stale-run"),
289
- type: "run.updated",
290
- threadId,
291
- occurredAt: now,
292
- payload: run,
293
- },
294
- {
295
- id: EventId.make("stale-node"),
296
- type: "node.updated",
297
- threadId,
298
- occurredAt: now,
299
- payload: node,
300
- },
301
- {
302
- id: EventId.make("stale-attempt"),
303
- type: "run-attempt.updated",
304
- threadId,
305
- occurredAt: now,
306
- payload: attempt,
307
- },
308
- ],
309
- });
310
- }
311
- const messageId = MessageId.make("partial-output");
312
- const item = before.turnItems.find((candidate) => candidate.id === devServerId)!;
313
- assert.ok(item.type === "command_execution");
314
- const terminalProviderTurn = stalledRun.endsWith("-terminal");
315
- if (terminalProviderTurn) {
316
- yield* sink.write({
317
- events: [
318
- {
319
- id: EventId.make("terminal-provider-turn"),
320
- type: "provider-turn.updated",
321
- threadId,
322
- occurredAt: now,
323
- payload: { ...codexTurn, status: "completed", completedAt: now },
324
- },
325
- ...(stalledRun === "missing-session-terminal"
326
- ? [
327
- {
328
- id: EventId.make("completed-dev-server"),
329
- type: "turn-item.updated" as const,
330
- threadId,
331
- occurredAt: now,
332
- payload: { ...item, status: "completed" as const, completedAt: now },
333
- },
334
- ]
335
- : []),
336
- ],
337
- });
338
- }
379
+ if (stalledRun === "superseded-attempt") {
380
yield* sink.write({
381
events: [
382
{
342
- id: EventId.make("partial-message"),
343
- type: "message.updated",
383
+ id: EventId.make("new-attempt"),
384
+ type: "run.updated",
385
threadId,
345
- runId: run.id,
386
occurredAt: now,
347
- payload: {
348
- id: messageId,
349
- threadId,
350
- runId: run.id,
351
- nodeId: node.id,
352
- role: "assistant",
353
- text: "Partial output",
354
- attachments: [],
355
- streaming: true,
356
- createdBy: "agent",
357
- creationSource: "provider",
358
- createdAt: now,
359
- updatedAt: now,
360
- },
387
+ payload: { ...run, activeAttemptId: RunAttemptId.make("new-attempt") },
388
},
362
- {
363
- id: EventId.make("partial-item"),
364
- type: "turn-item.updated",
389
+ ],
390
+ });
391
+ }
392
+ yield* orchestrator.dispatch(
393
+ stalledRun === "superseded-attempt"
394
+ ? {
395
+ type: "thread.background-work.settle",
396
+ commandId: CommandId.make("late-settle"),
397
threadId,
366
- runId: run.id,
398
+ providerThreadId: codexTurn.providerThreadId,
399
+ providerTurnId: codexTurn.id,
400
+ }
401
+ : {
402
+ type: "thread.stop",
403
+ commandId: CommandId.make("stop-stalled-run"),
404
+ threadId,
405
+ },
406
+ );
407
+ yield* worker.drain();
408
+ const after = yield* orchestrator.getThreadProjection(threadId);
409
+ const interrupted = stalledRun !== "superseded-attempt";
410
+ assert.equal(after.runs[0]?.status, interrupted ? "interrupted" : "running");
411
+ assert.equal(after.attempts[0]?.status, interrupted ? "interrupted" : "running");
412
+ assert.equal(
413
+ after.providerTurns[0]?.status,
414
+ terminalProviderTurn ? "completed" : interrupted ? "interrupted" : "running",
415
+ );
416
+ assert.equal(
417
+ after.nodes.find((candidate) => candidate.id === node.id)?.status,
418
+ interrupted ? "interrupted" : "running",
419
+ );
420
+ const output = after.messages.find((message) => message.id === messageId)!;
421
+ assert.equal(output.streaming, !interrupted);
422
+ assert.equal(output.text, "Partial output");
423
+ assert.equal(
424
+ after.turnItems.find((candidate) => candidate.id === devServerId)?.status,
425
+ stalledRun === "missing-session-terminal"
426
+ ? "completed"
427
+ : interrupted
428
+ ? "interrupted"
429
+ : "running",
430
+ );
431
+ assert.equal(
432
+ after.turnItems.find((candidate) => candidate.type === "assistant_message")?.status,
433
+ interrupted ? "interrupted" : "running",
434
+ );
435
+ assert.equal(
436
+ after.turnItems.filter((candidate) => candidate.type === "run_interrupt_result").length,
437
+ interrupted ? 1 : 0,
438
+ );
439
+ assert.isEmpty(after.runs.filter((candidate) => candidate.status === "waiting"));
440
+ return;
441
+ }
442
+ const settled = yield* watch(
443
+ (event) =>
444
+ event.type === "run.updated" &&
445
+ event.payload.id === first.runId &&
446
+ event.payload.status === "waiting",
447
+ );
448
+ yield* Queue.offer(events, {
449
+ type: "provider_turn.updated",
450
+ driver,
451
+ providerTurn: { ...codexTurn, status: "completed", completedAt: now },
452
+ });
453
+ yield* Queue.offer(events, {
454
+ type: "turn.terminal",
455
+ driver,
456
+ providerThreadId: codexTurn.providerThreadId,
457
+ providerTurnId: codexTurn.id,
458
+ runOrdinal: first.runOrdinal,
459
+ status: "completed",
460
+ failure: null,
461
+ threadDisposition: "reusable",
462
+ });
463
+ yield* Fiber.join(settled);
464
+ yield* worker.drain();
465
+
466
+ const codexProviderThread = (yield* orchestrator.getThreadProjection(threadId))
467
+ .providerThreads[0]!;
468
+ const backgroundTasks = [
469
+ { taskId: "sleep", description: "Wait before the recheck", kind: "command" as const },
470
+ ];
471
+ const otherBackgroundTasks = [{ ...backgroundTasks[0]!, taskId: "other-sleep" }];
472
+ const subagentThread = (name: string) =>
473
+ Effect.gen(function* () {
474
+ const subagentThreadId = ThreadId.make(`thread:${name}`);
475
+ const rootId = NodeId.make(`node:${name}-root`);
476
+ yield* orchestrator.dispatch({
477
+ type: "thread.create",
478
+ commandId: CommandId.make(`create-${name}`),
479
+ threadId: subagentThreadId,
480
+ projectId: ProjectId.make("project:background-work-stop"),
481
+ title: name,
482
+ modelSelection,
483
+ runtimeMode: "full-access",
484
+ interactionMode: "default",
485
+ branch: null,
486
+ worktreePath: cwd,
487
+ createdBy: "agent",
488
+ creationSource: "provider",
489
+ });
490
+ yield* sink.write({
491
+ events: [
492
+ {
493
+ id: EventId.make(`${name}-root`),
494
+ type: "node.updated",
495
+ threadId: subagentThreadId,
496
occurredAt: now,
497
payload: {
369
- ...item,
370
- providerThreadId: codexTurn.providerThreadId,
371
- providerTurnId: codexTurn.id,
372
- id: TurnItemId.make("partial-output"),
373
- type: "assistant_message",
374
- messageId,
375
- text: "Partial output",
376
- streaming: true,
498
+ id: rootId,
499
+ threadId: subagentThreadId,
500
+ runId: null,
501
+ parentNodeId: null,
502
+ rootNodeId: rootId,
503
+ kind: "root_turn",
504
+ status: "running",
505
+ countsForRun: false,
506
+ providerThreadId: null,
507
+ providerTurnId: null,
508
+ nativeItemRef: null,
509
+ runtimeRequestId: null,
510
+ checkpointScopeId: null,
511
+ startedAt: now,
512
+ completedAt: null,
513
},
514
},
515
],
516
});
381
- if (stalledRun === "superseded-attempt") {
382
- yield* sink.write({
383
- events: [
384
- {
385
- id: EventId.make("new-attempt"),
386
- type: "run.updated",
387
- threadId,
388
- occurredAt: now,
389
- payload: { ...run, activeAttemptId: RunAttemptId.make("new-attempt") },
390
- },
391
- ],
392
- });
393
- }
394
- yield* orchestrator.dispatch(
395
- stalledRun === "superseded-attempt"
396
- ? {
397
- type: "thread.background-work.settle",
398
- commandId: CommandId.make("late-settle"),
399
- threadId,
400
- providerThreadId: codexTurn.providerThreadId,
401
- providerTurnId: codexTurn.id,
402
- }
403
- : {
404
- type: "thread.stop",
405
- commandId: CommandId.make("stop-stalled-run"),
406
- threadId,
407
- },
408
- );
409
- yield* worker.drain();
410
- const after = yield* orchestrator.getThreadProjection(threadId);
411
- const interrupted = stalledRun !== "superseded-attempt";
412
- assert.equal(after.runs[0]?.status, interrupted ? "interrupted" : "running");
413
- assert.equal(after.attempts[0]?.status, interrupted ? "interrupted" : "running");
414
- assert.equal(
415
- after.providerTurns[0]?.status,
416
- terminalProviderTurn ? "completed" : interrupted ? "interrupted" : "running",
417
- );
418
- assert.equal(
419
- after.nodes.find((candidate) => candidate.id === node.id)?.status,
420
- interrupted ? "interrupted" : "running",
421
- );
422
- const output = after.messages.find((message) => message.id === messageId)!;
423
- assert.equal(output.streaming, !interrupted);
424
- assert.equal(output.text, "Partial output");
425
- assert.equal(
426
- after.turnItems.find((candidate) => candidate.id === devServerId)?.status,
427
- stalledRun === "missing-session-terminal"
428
- ? "completed"
429
- : interrupted
430
- ? "interrupted"
431
- : "running",
432
- );
433
- assert.equal(
434
- after.turnItems.find((candidate) => candidate.type === "assistant_message")?.status,
435
- interrupted ? "interrupted" : "running",
436
- );
437
- assert.equal(
438
- after.turnItems.filter((candidate) => candidate.type === "run_interrupt_result").length,
439
- interrupted ? 1 : 0,
440
- );
441
- assert.isEmpty(after.runs.filter((candidate) => candidate.status === "waiting"));
442
- return;
443
- }
444
- const settled = yield* watch(
445
- (event) =>
446
- event.type === "run.updated" &&
447
- event.payload.id === first.runId &&
448
- event.payload.status === "waiting",
449
- );
450
- yield* Queue.offer(events, {
451
- type: "provider_turn.updated",
452
- driver,
453
- providerTurn: { ...codexTurn, status: "completed", completedAt: now },
454
- });
455
- yield* Queue.offer(events, {
456
- type: "turn.terminal",
457
- driver,
458
- providerThreadId: codexTurn.providerThreadId,
459
- providerTurnId: codexTurn.id,
460
- runOrdinal: first.runOrdinal,
461
- status: "completed",
462
- failure: null,
463
- threadDisposition: "reusable",
517
+ return { threadId: subagentThreadId, rootId };
518
});
465
- yield* Fiber.join(settled);
466
- yield* worker.drain();
467
-
468
- const codexProviderThread = (yield* orchestrator.getThreadProjection(threadId))
469
- .providerThreads[0]!;
470
- const backgroundTasks = [
471
- { taskId: "sleep", description: "Wait before the recheck", kind: "command" as const },
472
- ];
473
- const otherBackgroundTasks = [{ ...backgroundTasks[0]!, taskId: "other-sleep" }];
474
- const subagentThread = (name: string) =>
475
- Effect.gen(function* () {
476
- const subagentThreadId = ThreadId.make(`thread:${name}`);
477
- const rootId = NodeId.make(`node:${name}-root`);
478
- yield* orchestrator.dispatch({
479
- type: "thread.create",
480
- commandId: CommandId.make(`create-${name}`),
481
- threadId: subagentThreadId,
482
- projectId: ProjectId.make("project:background-work-stop"),
483
- title: name,
484
- modelSelection,
485
- runtimeMode: "full-access",
486
- interactionMode: "default",
487
- branch: null,
488
- worktreePath: cwd,
489
- createdBy: "agent",
490
- creationSource: "provider",
491
- });
492
- yield* sink.write({
493
- events: [
519
+ const { threadId: reviewerThreadId, rootId: reviewerRootId } =
520
+ yield* subagentThread("reviewer");
521
+ const tester = yield* subagentThread("tester");
522
+ const nestedSubagentId = NodeId.make("subagent:nested");
523
+ const nestedItemId = TurnItemId.make("turn-item:nested-subagent");
524
+ const nested = {
525
+ threadId: reviewerThreadId,
526
+ runId: null,
527
+ origin: "provider_native",
528
+ driver,
529
+ providerInstanceId: instanceId,
530
+ providerThreadId: null,
531
+ childThreadId: tester.threadId,
532
+ prompt: "Check the tests",
533
+ title: null,
534
+ status: "running",
535
+ result: null,
536
+ startedAt: now,
537
+ completedAt: null,
538
+ updatedAt: now,
539
+ } as const;
540
+ yield* sink.write({
541
+ events: [
542
+ ...(workflowMember
543
+ ? []
544
+ : [
545
{
495
- id: EventId.make(`${name}-root`),
496
- type: "node.updated",
497
- threadId: subagentThreadId,
546
+ id: EventId.make("nested-subagent-item"),
547
+ type: "turn-item.updated",
548
+ threadId: reviewerThreadId,
549
occurredAt: now,
550
payload: {
500
- id: rootId,
501
- threadId: subagentThreadId,
502
- runId: null,
503
- parentNodeId: null,
504
- rootNodeId: rootId,
505
- kind: "root_turn",
506
- status: "running",
507
- countsForRun: false,
508
- providerThreadId: null,
551
+ ...nested,
552
+ id: nestedItemId,
553
+ nodeId: nestedSubagentId,
554
providerTurnId: null,
555
nativeItemRef: null,
511
- runtimeRequestId: null,
512
- checkpointScopeId: null,
513
- startedAt: now,
514
- completedAt: null,
556
+ parentItemId: null,
557
+ ordinal: 1,
558
+ type: "subagent",
559
+ subagentId: nestedSubagentId,
560
},
516
- },
517
- ],
518
- });
519
- return { threadId: subagentThreadId, rootId };
520
- });
521
- const { threadId: reviewerThreadId, rootId: reviewerRootId } =
522
- yield* subagentThread("reviewer");
523
- const tester = yield* subagentThread("tester");
524
- const nestedSubagentId = NodeId.make("subagent:nested");
525
- const nestedItemId = TurnItemId.make("turn-item:nested-subagent");
526
- const nested = {
527
- threadId: reviewerThreadId,
528
- runId: null,
529
- origin: "provider_native",
530
- driver,
531
- providerInstanceId: instanceId,
532
- providerThreadId: null,
533
- childThreadId: tester.threadId,
534
- prompt: "Check the tests",
535
- title: null,
536
- status: "running",
537
- result: null,
538
- startedAt: now,
539
- completedAt: null,
540
- updatedAt: now,
541
- } as const;
561
+ } as const,
562
+ ]),
563
+ {
564
+ id: EventId.make("nested-subagent"),
565
+ type: "subagent.updated",
566
+ threadId: reviewerThreadId,
567
+ occurredAt: now,
568
+ payload: {
569
+ ...nested,
570
+ id: nestedSubagentId,
571
+ parentNodeId: reviewerRootId,
572
+ createdBy: "agent",
573
+ nativeTaskRef: workflowMember
574
+ ? { driver, nativeId: "workflow:member", strength: "strong" }
575
+ : null,
576
+ model: null,
577
+ },
578
+ },
579
+ ],
580
+ });
581
+ if (workflowMember) {
582
+ const memberRoot = (yield* orchestrator.getThreadProjection(tester.threadId)).nodes[0]!;
583
yield* sink.write({
584
events: [
544
- ...(workflowMember
545
- ? []
546
- : [
547
- {
548
- id: EventId.make("nested-subagent-item"),
549
- type: "turn-item.updated",
550
- threadId: reviewerThreadId,
551
- occurredAt: now,
552
- payload: {
553
- ...nested,
554
- id: nestedItemId,
555
- nodeId: nestedSubagentId,
556
- providerTurnId: null,
557
- nativeItemRef: null,
558
- parentItemId: null,
559
- ordinal: 1,
560
- type: "subagent",
561
- subagentId: nestedSubagentId,
562
- },
563
- } as const,
564
- ]),
585
{
566
- id: EventId.make("nested-subagent"),
567
- type: "subagent.updated",
586
+ id: EventId.make("workflow-member-node"),
587
+ type: "node.updated",
588
threadId: reviewerThreadId,
589
occurredAt: now,
590
payload: {
571
- ...nested,
591
+ ...memberRoot,
592
id: nestedSubagentId,
593
+ threadId: reviewerThreadId,
594
parentNodeId: reviewerRootId,
574
- createdBy: "agent",
575
- nativeTaskRef: workflowMember
576
- ? { driver, nativeId: "workflow:member", strength: "strong" }
577
- : null,
578
- model: null,
595
+ rootNodeId: reviewerRootId,
596
+ kind: "subagent",
597
},
598
},
599
],
600
});
583
- if (workflowMember) {
584
- const memberRoot = (yield* orchestrator.getThreadProjection(tester.threadId)).nodes[0]!;
585
- yield* sink.write({
586
- events: [
587
- {
588
- id: EventId.make("workflow-member-node"),
589
- type: "node.updated",
590
- threadId: reviewerThreadId,
591
- occurredAt: now,
592
- payload: {
593
- ...memberRoot,
594
- id: nestedSubagentId,
595
- threadId: reviewerThreadId,
596
- parentNodeId: reviewerRootId,
597
- rootNodeId: reviewerRootId,
598
- kind: "subagent",
599
- },
600
- },
601
- ],
601
+ }
602
+ const settledRun = (input: {
603
+ readonly ordinal: number;
604
+ readonly providerThreadId: ProviderThreadId;
605
+ readonly runningItem?: {
606
+ readonly id: TurnItemId;
607
+ readonly kind: "command" | "subagent";
608
+ };
609
+ }) => {
610
+ const runId = RunId.make(`run:${input.ordinal}`);
611
+ const attemptId = RunAttemptId.make(`attempt:${input.ordinal}`);
612
+ const nodeId = NodeId.make(`node:${input.ordinal}`);
613
+ const providerTurnId = ProviderTurnId.make(`provider-turn:${input.ordinal}`);
614
+ const events: Array<OrchestrationV2DomainEvent> = [
615
+ {
616
+ id: EventId.make(`run:${input.ordinal}`),
617
+ type: "run.created",
618
+ threadId,
619
+ occurredAt: now,
620
+ payload: {
621
+ id: runId,
622
+ threadId,
623
+ ordinal: input.ordinal,
624
+ providerInstanceId: instanceId,
625
+ modelSelection,
626
+ providerThreadId: input.providerThreadId,
627
+ userMessageId: MessageId.make(`message:${input.ordinal}`),
628
+ rootNodeId: nodeId,
629
+ activeAttemptId: attemptId,
630
+ status: "completed",
631
+ requestedAt: now,
632
+ startedAt: now,
633
+ completedAt: now,
634
+ checkpointId: null,
635
+ contextHandoffId: null,
636
+ },
637
+ },
638
+ {
639
+ id: EventId.make(`node:${input.ordinal}`),
640
+ type: "node.updated",
641
+ threadId,
642
+ runId,
643
+ occurredAt: now,
644
+ payload: {
645
+ id: nodeId,
646
+ threadId,
647
+ runId,
648
+ parentNodeId: null,
649
+ rootNodeId: nodeId,
650
+ kind: "root_turn",
651
+ status: "completed",
652
+ countsForRun: true,
653
+ providerThreadId: input.providerThreadId,
654
+ providerTurnId,
655
+ nativeItemRef: null,
656
+ runtimeRequestId: null,
657
+ checkpointScopeId: null,
658
+ startedAt: now,
659
+ completedAt: now,
660
+ },
661
+ },
662
+ {
663
+ id: EventId.make(`attempt:${input.ordinal}`),
664
+ type: "run-attempt.created",
665
+ threadId,
666
+ occurredAt: now,
667
+ payload: {
668
+ id: attemptId,
669
+ runId,
670
+ attemptOrdinal: 1,
671
+ rootNodeId: nodeId,
672
+ providerInstanceId: instanceId,
673
+ providerThreadId: input.providerThreadId,
674
+ providerTurnId,
675
+ reason: "initial",
676
+ status: "completed",
677
+ startedAt: now,
678
+ completedAt: now,
679
+ },
680
+ },
681
+ {
682
+ id: EventId.make(`provider-turn:${input.ordinal}`),
683
+ type: "provider-turn.updated",
684
+ threadId,
685
+ occurredAt: now,
686
+ payload: {
687
+ id: providerTurnId,
688
+ providerThreadId: input.providerThreadId,
689
+ nodeId,
690
+ runAttemptId: attemptId,
691
+ nativeTurnRef: null,
692
+ ordinal: input.ordinal,
693
+ status: "completed",
694
+ startedAt: now,
695
+ completedAt: now,
696
+ },
697
+ },
698
+ ];
699
+ const item = input.runningItem;
700
+ if (item !== undefined) {
701
+ const base = {
702
+ id: item.id,
703
+ threadId,
704
+ runId,
705
+ nodeId,
706
+ providerThreadId: input.providerThreadId,
707
+ providerTurnId,
708
+ nativeItemRef: null,
709
+ parentItemId: null,
710
+ ordinal: input.ordinal * 100,
711
+ status: "running",
712
+ title: null,
713
+ startedAt: now,
714
+ completedAt: null,
715
+ updatedAt: now,
716
+ } as const;
717
+ events.push({
718
+ id: EventId.make(`item:${input.ordinal}`),
719
+ type: "turn-item.updated",
720
+ threadId,
721
+ runId,
722
+ occurredAt: now,
723
+ payload:
724
+ item.kind === "command"
725
+ ? { ...base, type: "command_execution", input: "vp run test --watch" }
726
+ : {
727
+ ...base,
728
+ providerThreadId: ProviderThreadId.make("provider-thread:codex-subagent"),
729
+ type: "subagent",
730
+ subagentId: NodeId.make(`subagent:${input.ordinal}`),
731
+ origin: "provider_native",
732
+ driver,
733
+ providerInstanceId: instanceId,
734
+ childThreadId: reviewerThreadId,
735
+ prompt: "Review the change",
736
+ result: null,
737
+ },
738
});
603
- }
604
- const settledRun = (input: {
605
- readonly ordinal: number;
606
- readonly providerThreadId: ProviderThreadId;
607
- readonly runningItem?: {
608
- readonly id: TurnItemId;
609
- readonly kind: "command" | "subagent";
610
- };
611
- }) => {
612
- const runId = RunId.make(`run:${input.ordinal}`);
613
- const attemptId = RunAttemptId.make(`attempt:${input.ordinal}`);
614
- const nodeId = NodeId.make(`node:${input.ordinal}`);
615
- const providerTurnId = ProviderTurnId.make(`provider-turn:${input.ordinal}`);
616
- const events: Array<OrchestrationV2DomainEvent> = [
617
- {
618
- id: EventId.make(`run:${input.ordinal}`),
619
- type: "run.created",
739
+ if (item.kind === "subagent") {
740
+ events.push({
741
+ id: EventId.make(`subagent:${input.ordinal}`),
742
+ type: "subagent.updated",
743
threadId,
744
+ runId,
745
occurredAt: now,
746
payload: {
623
- id: runId,
624
- threadId,
625
- ordinal: input.ordinal,
747
+ ...base,
748
+ id: NodeId.make(`subagent:${input.ordinal}`),
749
+ parentNodeId: nodeId,
750
+ origin: "provider_native",
751
+ createdBy: "agent",
752
+ driver,
753
providerInstanceId: instanceId,
627
- modelSelection,
628
- providerThreadId: input.providerThreadId,
629
- userMessageId: MessageId.make(`message:${input.ordinal}`),
630
- rootNodeId: nodeId,
631
- activeAttemptId: attemptId,
632
- status: "completed",
633
- requestedAt: now,
634
- startedAt: now,
635
- completedAt: now,
636
- checkpointId: null,
637
- contextHandoffId: null,
754
+ providerThreadId: null,
755
+ childThreadId: reviewerThreadId,
756
+ nativeTaskRef: null,
757
+ prompt: "Review the change",
758
+ model: null,
759
+ result: null,
760
},
761
+ });
762
+ }
763
+ }
764
+ return { runId, providerTurnId, events };
765
+ };
766
+
767
+ const watcherId = TurnItemId.make("turn-item:watcher");
768
+ const otherProviderThreadId = ProviderThreadId.make("provider-thread:other");
769
+ const watcherRun = settledRun({
770
+ ordinal: 2,
771
+ providerThreadId: olderStart ? otherProviderThreadId : codexProviderThread.id,
772
+ ...(olderStart ? {} : { runningItem: { id: watcherId, kind: "command" as const } }),
773
+ });
774
+ const reviewerId = TurnItemId.make("turn-item:reviewer");
775
+ const reviewerRun = settledRun({
776
+ ordinal: 3,
777
+ providerThreadId: codexProviderThread.id,
778
+ runningItem: { id: reviewerId, kind: "subagent" },
779
+ });
780
+ const latestRun = settledRun({ ordinal: 4, providerThreadId: otherProviderThreadId });
781
+ yield* sink.write({
782
+ events: [
783
+ ...watcherRun.events,
784
+ ...reviewerRun.events,
785
+ {
786
+ id: EventId.make("provider-thread:other"),
787
+ type: "provider-thread.updated",
788
+ threadId,
789
+ occurredAt: now,
790
+ payload: {
791
+ ...codexProviderThread,
792
+ id: otherProviderThreadId,
793
+ firstRunOrdinal: 4,
794
+ lastRunOrdinal: 4,
795
+ ...(failedStart ? { pendingBackgroundTasks: otherBackgroundTasks } : {}),
796
},
797
+ },
798
+ ...latestRun.events,
799
+ ],
800
+ });
801
+
802
+ const failedRun = settledRun({ ordinal: 5, providerThreadId: codexProviderThread.id });
803
+ if (failedStart) {
804
+ yield* sink.write({
805
+ events: [
806
{
641
- id: EventId.make(`node:${input.ordinal}`),
642
- type: "node.updated",
807
+ id: EventId.make("failed-start-roster"),
808
+ type: "provider-thread.updated",
809
threadId,
644
- runId,
810
occurredAt: now,
811
payload: {
647
- id: nodeId,
648
- threadId,
649
- runId,
650
- parentNodeId: null,
651
- rootNodeId: nodeId,
652
- kind: "root_turn",
653
- status: "completed",
654
- countsForRun: true,
655
- providerThreadId: input.providerThreadId,
656
- providerTurnId,
657
- nativeItemRef: null,
658
- runtimeRequestId: null,
659
- checkpointScopeId: null,
660
- startedAt: now,
661
- completedAt: now,
812
+ ...codexProviderThread,
813
+ lastRunOrdinal: 5,
814
+ pendingBackgroundTasks: backgroundTasks,
815
},
816
},
817
+ ...failedRun.events.flatMap((event): Array<OrchestrationV2DomainEvent> => {
818
+ switch (event.type) {
819
+ case "provider-turn.updated":
820
+ return [];
821
+ case "run.created":
822
+ return [{ ...event, payload: { ...event.payload, status: "failed" } }];
823
+ case "node.updated":
824
+ return [
825
+ {
826
+ ...event,
827
+ payload: { ...event.payload, status: "failed", providerTurnId: null },
828
+ },
829
+ ];
830
+ case "run-attempt.created":
831
+ return [
832
+ {
833
+ ...event,
834
+ payload: { ...event.payload, status: "failed", providerTurnId: null },
835
+ },
836
+ ];
837
+ default:
838
+ return [event];
839
+ }
840
+ }),
841
+ ],
842
+ });
843
+ // The older turn reports an empty roster, but the refused run owns the row now.
844
+ const clear = yield* sink.writeIfProviderThreadOwner({
845
+ providerThreadId: codexProviderThread.id,
846
+ runId: reviewerRun.runId,
847
+ activeAttemptId: RunAttemptId.make("attempt:3"),
848
+ expectedLastRunOrdinal: 3,
849
+ events: [
850
{
665
- id: EventId.make(`attempt:${input.ordinal}`),
666
- type: "run-attempt.created",
851
+ id: EventId.make("dropped-roster-clear"),
852
+ type: "provider-thread.updated",
853
threadId,
854
occurredAt: now,
669
- payload: {
670
- id: attemptId,
671
- runId,
672
- attemptOrdinal: 1,
673
- rootNodeId: nodeId,
674
- providerInstanceId: instanceId,
675
- providerThreadId: input.providerThreadId,
676
- providerTurnId,
677
- reason: "initial",
678
- status: "completed",
679
- startedAt: now,
680
- completedAt: now,
681
- },
855
+ payload: { ...codexProviderThread, pendingBackgroundTasks: [] },
856
},
857
+ ],
858
+ });
859
+ assert.isFalse(clear.committed);
860
+ const beforeStop = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
861
+ (thread) => thread.id === codexProviderThread.id,
862
+ )!;
863
+ assert.equal(beforeStop.lastRunOrdinal, 5);
864
+ assert.deepEqual(beforeStop.pendingBackgroundTasks, backgroundTasks);
865
+ }
866
+
867
+ if (stopWithQueue !== undefined) {
868
+ const owner = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
869
+ (run) => run.id === latestRun.runId,
870
+ )!;
871
+ yield* sink.write({
872
+ events: [
873
{
684
- id: EventId.make(`provider-turn:${input.ordinal}`),
685
- type: "provider-turn.updated",
874
+ id: EventId.make("latest-run-waiting"),
875
+ type: "run.updated",
876
threadId,
877
+ runId: owner.id,
878
occurredAt: now,
688
- payload: {
689
- id: providerTurnId,
690
- providerThreadId: input.providerThreadId,
691
- nodeId,
692
- runAttemptId: attemptId,
693
- nativeTurnRef: null,
694
- ordinal: input.ordinal,
695
- status: "completed",
696
- startedAt: now,
697
- completedAt: now,
698
- },
879
+ payload: { ...owner, status: "waiting", completedAt: null },
880
},
700
- ];
701
- const item = input.runningItem;
702
- if (item !== undefined) {
703
- const base = {
704
- id: item.id,
881
+ ],
882
+ });
883
+ yield* orchestrator.dispatch({
884
+ type: "message.dispatch",
885
+ commandId: CommandId.make("queue-follow-up"),
886
+ threadId,
887
+ messageId: MessageId.make("message:queue-follow-up"),
888
+ text: "Follow up after the background work",
889
+ attachments: [],
890
+ dispatchMode: { type: "queue_after_active" },
891
+ createdBy: "user",
892
+ creationSource: "web",
893
+ });
894
+ const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
895
+ assert.equal(queued.status, "queued");
896
+ yield* sink.write({
897
+ events: [
898
+ {
899
+ id: EventId.make("queue-held"),
900
+ type: "run.updated",
901
threadId,
706
- runId,
707
- nodeId,
708
- providerThreadId: input.providerThreadId,
709
- providerTurnId,
710
- nativeItemRef: null,
711
- parentItemId: null,
712
- ordinal: input.ordinal * 100,
713
- status: "running",
714
- title: null,
715
- startedAt: now,
716
- completedAt: null,
717
- updatedAt: now,
718
- } as const;
719
- events.push({
720
- id: EventId.make(`item:${input.ordinal}`),
721
- type: "turn-item.updated",
902
+ runId: queued.id,
903
+ occurredAt: now,
904
+ payload: { ...queued, queueHeld: true },
905
+ },
906
+ {
907
+ id: EventId.make("latest-run-settled"),
908
+ type: "run.updated",
909
threadId,
723
- runId,
910
+ runId: owner.id,
911
occurredAt: now,
725
- payload:
726
- item.kind === "command"
727
- ? { ...base, type: "command_execution", input: "vp run test --watch" }
728
- : {
729
- ...base,
730
- providerThreadId: ProviderThreadId.make("provider-thread:codex-subagent"),
731
- type: "subagent",
732
- subagentId: NodeId.make(`subagent:${input.ordinal}`),
733
- origin: "provider_native",
734
- driver,
735
- providerInstanceId: instanceId,
736
- childThreadId: reviewerThreadId,
737
- prompt: "Review the change",
738
- result: null,
739
- },
740
- });
741
- if (item.kind === "subagent") {
742
- events.push({
743
- id: EventId.make(`subagent:${input.ordinal}`),
744
- type: "subagent.updated",
745
- threadId,
746
- runId,
747
- occurredAt: now,
748
- payload: {
749
- ...base,
750
- id: NodeId.make(`subagent:${input.ordinal}`),
751
- parentNodeId: nodeId,
752
- origin: "provider_native",
753
- createdBy: "agent",
754
- driver,
755
- providerInstanceId: instanceId,
756
- providerThreadId: null,
757
- childThreadId: reviewerThreadId,
758
- nativeTaskRef: null,
759
- prompt: "Review the change",
760
- model: null,
761
- result: null,
762
- },
763
- });
764
- }
765
- }
766
- return { runId, providerTurnId, events };
767
- };
768
-
769
- const watcherId = TurnItemId.make("turn-item:watcher");
770
- const otherProviderThreadId = ProviderThreadId.make("provider-thread:other");
771
- const watcherRun = settledRun({
772
- ordinal: 2,
773
- providerThreadId: olderStart ? otherProviderThreadId : codexProviderThread.id,
774
- ...(olderStart ? {} : { runningItem: { id: watcherId, kind: "command" as const } }),
775
- });
776
- const reviewerId = TurnItemId.make("turn-item:reviewer");
777
- const reviewerRun = settledRun({
778
- ordinal: 3,
779
- providerThreadId: codexProviderThread.id,
780
- runningItem: { id: reviewerId, kind: "subagent" },
912
+ payload: owner,
913
+ },
914
+ ],
915
});
782
- const latestRun = settledRun({ ordinal: 4, providerThreadId: otherProviderThreadId });
916
+ }
917
+
918
+ if (olderStart) {
919
+ const older = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
920
+ (run) => run.id === watcherRun.runId,
921
+ )!;
922
yield* sink.write({
923
events: [
785
- ...watcherRun.events,
786
- ...reviewerRun.events,
924
{
788
- id: EventId.make("provider-thread:other"),
789
- type: "provider-thread.updated",
925
+ id: EventId.make("older-run-starting"),
926
+ type: "run.updated",
927
threadId,
928
+ runId: older.id,
929
occurredAt: now,
792
- payload: {
793
- ...codexProviderThread,
794
- id: otherProviderThreadId,
795
- firstRunOrdinal: 4,
796
- lastRunOrdinal: 4,
797
- ...(failedStart ? { pendingBackgroundTasks: otherBackgroundTasks } : {}),
798
- },
930
+ payload: { ...older, status: "starting", startedAt: null, completedAt: null },
931
},
800
- ...latestRun.events,
932
],
933
});
934
+ }
935
804
- const failedRun = settledRun({ ordinal: 5, providerThreadId: codexProviderThread.id });
805
- if (failedStart) {
806
- yield* sink.write({
807
- events: [
808
- {
809
- id: EventId.make("failed-start-roster"),
810
- type: "provider-thread.updated",
811
- threadId,
812
- occurredAt: now,
813
- payload: {
814
- ...codexProviderThread,
815
- lastRunOrdinal: 5,
816
- pendingBackgroundTasks: backgroundTasks,
817
- },
818
- },
819
- ...failedRun.events.flatMap((event): Array<OrchestrationV2DomainEvent> => {
820
- switch (event.type) {
821
- case "provider-turn.updated":
822
- return [];
823
- case "run.created":
824
- return [{ ...event, payload: { ...event.payload, status: "failed" } }];
825
- case "node.updated":
826
- return [
827
- {
828
- ...event,
829
- payload: { ...event.payload, status: "failed", providerTurnId: null },
830
- },
831
- ];
832
- case "run-attempt.created":
833
- return [
834
- {
835
- ...event,
836
- payload: { ...event.payload, status: "failed", providerTurnId: null },
837
- },
838
- ];
839
- default:
840
- return [event];
841
- }
842
- }),
843
- ],
844
- });
845
- // The older turn reports an empty roster, but the refused run owns the row now.
846
- const clear = yield* sink.writeIfProviderThreadOwner({
847
- providerThreadId: codexProviderThread.id,
848
- runId: reviewerRun.runId,
849
- activeAttemptId: RunAttemptId.make("attempt:3"),
850
- expectedLastRunOrdinal: 3,
851
- events: [
852
- {
853
- id: EventId.make("dropped-roster-clear"),
854
- type: "provider-thread.updated",
855
- threadId,
856
- occurredAt: now,
857
- payload: { ...codexProviderThread, pendingBackgroundTasks: [] },
858
- },
859
- ],
860
- });
861
- assert.isFalse(clear.committed);
862
- const beforeStop = (yield* orchestrator.getThreadProjection(
863
- threadId,
864
- )).providerThreads.find((thread) => thread.id === codexProviderThread.id)!;
865
- assert.equal(beforeStop.lastRunOrdinal, 5);
866
- assert.deepEqual(beforeStop.pendingBackgroundTasks, backgroundTasks);
867
- }
868
-
869
- if (stopWithQueue !== undefined) {
870
- const owner = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
871
- (run) => run.id === latestRun.runId,
872
- )!;
873
- yield* sink.write({
874
- events: [
875
- {
876
- id: EventId.make("latest-run-waiting"),
877
- type: "run.updated",
878
- threadId,
879
- runId: owner.id,
880
- occurredAt: now,
881
- payload: { ...owner, status: "waiting", completedAt: null },
882
- },
883
- ],
884
- });
885
- yield* orchestrator.dispatch({
886
- type: "message.dispatch",
887
- commandId: CommandId.make("queue-follow-up"),
888
- threadId,
889
- messageId: MessageId.make("message:queue-follow-up"),
890
- text: "Follow up after the background work",
891
- attachments: [],
892
- dispatchMode: { type: "queue_after_active" },
893
- createdBy: "user",
894
- creationSource: "web",
895
- });
896
- const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
897
- assert.equal(queued.status, "queued");
898
- yield* sink.write({
899
- events: [
900
- {
901
- id: EventId.make("queue-held"),
902
- type: "run.updated",
903
- threadId,
904
- runId: queued.id,
905
- occurredAt: now,
906
- payload: { ...queued, queueHeld: true },
907
- },
908
- {
909
- id: EventId.make("latest-run-settled"),
910
- type: "run.updated",
911
- threadId,
912
- runId: owner.id,
913
- occurredAt: now,
914
- payload: owner,
915
- },
916
- ],
917
- });
918
- }
919
-
920
- if (olderStart) {
921
- const older = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
922
- (run) => run.id === watcherRun.runId,
923
- )!;
924
- yield* sink.write({
925
- events: [
926
- {
927
- id: EventId.make("older-run-starting"),
928
- type: "run.updated",
929
- threadId,
930
- runId: older.id,
931
- occurredAt: now,
932
- payload: { ...older, status: "starting", startedAt: null, completedAt: null },
933
- },
934
- ],
935
- });
936
- }
936
+ yield* orchestrator.dispatch(
937
+ stopWithQueue === "thread.stop"
938
+ ? {
939
+ type: "thread.stop",
940
+ commandId: CommandId.make("stop-background-work"),
941
+ threadId,
942
+ }
943
+ : {
944
+ type: "run.interrupt",
945
+ commandId: CommandId.make("stop-background-work"),
946
+ threadId,
947
+ runId: olderStart
948
+ ? watcherRun.runId
949
+ : failedStart
950
+ ? failedRun.runId
951
+ : latestRun.runId,
952
+ ...(stopWithQueue === undefined ? {} : { holdQueue: true }),
953
+ },
954
+ );
955
+ yield* worker.drain();
956
938
- yield* orchestrator.dispatch(
939
- stopWithQueue === "thread.stop"
940
- ? {
941
- type: "thread.stop",
942
- commandId: CommandId.make("stop-background-work"),
943
- threadId,
944
- }
945
- : {
946
- type: "run.interrupt",
947
- commandId: CommandId.make("stop-background-work"),
948
- threadId,
949
- runId: olderStart
950
- ? watcherRun.runId
951
- : failedStart
952
- ? failedRun.runId
953
- : latestRun.runId,
954
- ...(stopWithQueue === undefined ? {} : { holdQueue: true }),
955
- },
957
+ assert.sameDeepMembers(
958
+ interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]),
959
+ [
960
+ ...(olderStart || failedStart ? [] : [[otherProviderThreadId, latestRun.providerTurnId]]),
961
+ [codexProviderThread.id, reviewerRun.providerTurnId],
962
+ ],
963
+ );
964
+ const after = yield* orchestrator.getThreadProjection(threadId);
965
+ if (olderStart) {
966
+ assert.equal(after.runs.find((run) => run.id === watcherRun.runId)?.status, "interrupted");
967
+ }
968
+ if (stopWithQueue !== undefined) {
969
+ assert.equal(after.runs.at(-1)?.status, "queued");
970
+ assert.equal(after.runs.at(-1)?.queueHeld, true);
971
+ assert.lengthOf(started, 1);
972
+ }
973
+ assert.deepEqual(
974
+ [devServerId, ...(olderStart ? [] : [watcherId]), reviewerId].map(
975
+ (id) => after.turnItems.find((item) => item.id === id)?.status,
976
+ ),
977
+ olderStart ? ["interrupted", "interrupted"] : ["interrupted", "interrupted", "interrupted"],
978
+ );
979
+ assert.equal(after.subagents[0]?.status, "interrupted");
980
+ const reviewerThread = yield* orchestrator.getThreadProjection(reviewerThreadId);
981
+ assert.equal(reviewerThread.nodes[0]?.status, "interrupted");
982
+ assert.equal(reviewerThread.subagents[0]?.status, "interrupted");
983
+ if (workflowMember) {
984
+ assert.isUndefined(reviewerThread.turnItems.find((item) => item.id === nestedItemId));
985
+ assert.equal(
986
+ reviewerThread.nodes.find((node) => node.id === nestedSubagentId)?.status,
987
+ "interrupted",
988
);
957
- yield* worker.drain();
958
-
959
- assert.sameDeepMembers(
960
- interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]),
961
- [
962
- ...(olderStart || failedStart
963
- ? []
964
- : [[otherProviderThreadId, latestRun.providerTurnId]]),
965
- [codexProviderThread.id, reviewerRun.providerTurnId],
966
- ],
989
+ } else {
990
+ assert.equal(
991
+ reviewerThread.turnItems.find((item) => item.id === nestedItemId)?.status,
992
+ "interrupted",
993
);
968
- const after = yield* orchestrator.getThreadProjection(threadId);
969
- if (olderStart) {
970
- assert.equal(
971
- after.runs.find((run) => run.id === watcherRun.runId)?.status,
972
- "interrupted",
973
- );
974
- }
975
- if (stopWithQueue !== undefined) {
976
- assert.equal(after.runs.at(-1)?.status, "queued");
977
- assert.equal(after.runs.at(-1)?.queueHeld, true);
978
- assert.lengthOf(started, 1);
979
- }
994
+ }
995
+ const testerThread = yield* orchestrator.getThreadProjection(tester.threadId);
996
+ assert.equal(testerThread.nodes[0]?.status, "interrupted");
997
+ if (failedStart) {
998
assert.deepEqual(
981
- [devServerId, ...(olderStart ? [] : [watcherId]), reviewerId].map(
982
- (id) => after.turnItems.find((item) => item.id === id)?.status,
983
- ),
984
- olderStart
985
- ? ["interrupted", "interrupted"]
986
- : ["interrupted", "interrupted", "interrupted"],
999
+ after.providerThreads.find((candidate) => candidate.id === codexProviderThread.id)
1000
+ ?.pendingBackgroundTasks,
1001
+ backgroundWorkAfterStop === undefined ? [] : backgroundTasks,
1002
);
988
- assert.equal(after.subagents[0]?.status, "interrupted");
989
- const reviewerThread = yield* orchestrator.getThreadProjection(reviewerThreadId);
990
- assert.equal(reviewerThread.nodes[0]?.status, "interrupted");
991
- assert.equal(reviewerThread.subagents[0]?.status, "interrupted");
992
- if (workflowMember) {
993
- assert.isUndefined(reviewerThread.turnItems.find((item) => item.id === nestedItemId));
994
- assert.equal(
995
- reviewerThread.nodes.find((node) => node.id === nestedSubagentId)?.status,
996
- "interrupted",
997
- );
998
- } else {
999
- assert.equal(
1000
- reviewerThread.turnItems.find((item) => item.id === nestedItemId)?.status,
1001
- "interrupted",
1002
- );
1003
- }
1004
- const testerThread = yield* orchestrator.getThreadProjection(tester.threadId);
1005
- assert.equal(testerThread.nodes[0]?.status, "interrupted");
1006
- if (failedStart) {
1007
- assert.deepEqual(
1008
- after.providerThreads.find((candidate) => candidate.id === codexProviderThread.id)
1009
- ?.pendingBackgroundTasks,
1010
- backgroundWorkAfterStop === undefined ? [] : backgroundTasks,
1011
- );
1012
- assert.deepEqual(
1013
- after.providerThreads.find((candidate) => candidate.id === otherProviderThreadId)
1014
- ?.pendingBackgroundTasks,
1015
- otherBackgroundTasks,
1016
- );
1017
- }
1018
- }).pipe(
1019
- Effect.provide(
1020
- ProviderReplayHarness.layerWithRegistry(
1021
- { name: "background-work-stop" },
1022
- ProviderAdapterRegistry.layerSingle(adapter),
1023
- { runEffectWorker: false },
1024
- ),
1003
+ assert.deepEqual(
1004
+ after.providerThreads.find((candidate) => candidate.id === otherProviderThreadId)
1005
+ ?.pendingBackgroundTasks,
1006
+ otherBackgroundTasks,
1007
+ );
1008
+ }
1009
+ }).pipe(
1010
+ Effect.provide(
1011
+ ProviderReplayHarness.layerWithRegistry(
1012
+ { name: "background-work-stop" },
1013
+ ProviderAdapterRegistry.layerSingle(adapter),
1014
+ { runEffectWorker: false },
1015
),
1026
- );
1027
- }),
1028
- );
1016
+ ),
1017
+ );
1018
+ });
1019
1020
it.effect("Stop reaches background work an earlier provider thread still runs", () =>
1021
stopEarlierBackgroundWork({}),
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+603
-622
@@ -136,374 +136,13 @@ const deliveries = [
136
it.effect.each(deliveries)(
137
"delivers %s with Claude's native pending-tool cancellation behavior",
138
(delivery) =>
139
- Effect.scoped(
140
- Effect.gen(function* () {
141
- const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
142
- const sdkMessages = yield* Queue.unbounded<SDKMessage>();
143
- const offers: SDKUserMessage[] = [];
144
- const nativeQueue: SDKUserMessage[] = [];
145
- // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber.
146
- const batchAbort = new AbortController();
147
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
148
- instanceId: modelSelection.instanceId,
149
- settings,
150
- environment: {},
151
- attachmentsDir: cwd,
152
- fileSystem: yield* FileSystem.FileSystem,
153
- path: yield* Path.Path,
154
- random: yield* SecureRandom.SecureRandom,
155
- idAllocator: yield* IdAllocator.IdAllocatorV2,
156
- queryRunner: {
157
- allocateSessionId: Effect.succeed(sessionId),
158
- open: () =>
159
- Effect.succeed({
160
- messages: Stream.fromQueue(sdkMessages),
161
- offer: (message) =>
162
- Effect.sync(() => {
163
- offers.push(message);
164
- nativeQueue.push(message);
165
- // Claude Code 2.1.289 aborts on now-priority commands even while Bash blocks reads.
166
- if (nativeQueue.some((command) => command.priority === "now")) {
167
- batchAbort.abort({ kind: "interrupt" });
168
- }
169
- }),
170
- setModel: () => Effect.void,
171
- applyFlagSettings: () => Effect.void,
172
- setPermissionMode: () => Effect.void,
173
- backgroundTasks: () => Effect.succeed(false),
174
- mcpServerStatus: Effect.succeed([]),
175
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
176
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
177
- listPermissionRules: Effect.die("unexpected permission rules read"),
178
- stopTask: () => Effect.void,
179
- interrupt: Effect.die("automatic delivery must never interrupt"),
180
- close: Effect.void,
181
- }),
182
- forkSession: () => Effect.die("unused"),
183
- subagentLaunchToolUseId: () => Effect.succeed(null),
184
- subagentModel: () => Effect.succeed(null),
185
- assertComplete: Effect.void,
186
- },
187
- });
188
- yield* Effect.gen(function* () {
189
- const orchestrator = yield* Orchestrator.OrchestratorV2;
190
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
191
- const threadId = ThreadId.make("thread:automatic-delivery");
192
- const projectId = ProjectId.make("project:automatic-delivery");
193
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
194
- orchestrator.streamDomainEvents.pipe(
195
- Stream.filter(predicate),
196
- Stream.take(1),
197
- Stream.runDrain,
198
- Effect.forkScoped,
199
- );
200
- yield* orchestrator.dispatch({
201
- type: "thread.create",
202
- commandId: CommandId.make("create"),
203
- threadId,
204
- projectId,
205
- title: "Automatic delivery",
206
- modelSelection,
207
- runtimeMode: "full-access",
208
- interactionMode: "default",
209
- branch: null,
210
- worktreePath: cwd,
211
- createdBy: "user",
212
- creationSource: "web",
213
- });
214
- const running = yield* watch(
215
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
216
- );
217
- yield* orchestrator.dispatch({
218
- type: "message.dispatch",
219
- commandId: CommandId.make("first"),
220
- threadId,
221
- messageId: MessageId.make("first"),
222
- text: "Build and check all four tasks.",
223
- attachments: [],
224
- dispatchMode: { type: "start_immediately" },
225
- createdBy: "user",
226
- creationSource: "web",
227
- });
228
- yield* worker.drain();
229
- yield* Fiber.join(running);
230
- const pending = yield* watch(
231
- (event) =>
232
- event.type === "turn-item.updated" &&
233
- event.payload.nativeItemRef?.nativeId === "status-4",
234
- );
235
- yield* Queue.offer(sdkMessages, batch);
236
- yield* Fiber.join(pending);
237
- const before = yield* orchestrator.getThreadProjection(threadId);
238
- assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
239
- const parent = before.runs[0]!;
240
- if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
241
- const messageId = MessageId.make("automatic-notice");
242
- if (delivery === "child completion") {
243
- const taskId = NodeId.make("completed-child");
244
- const now = yield* DateTime.now;
245
- const sink = yield* EventSink.EventSinkV2;
246
- yield* sink.write({
247
- events: [
248
- {
249
- id: EventId.make("cohort"),
250
- type: "run.updated",
251
- threadId,
252
- runId: parent.id,
253
- occurredAt: now,
254
- payload: {
255
- ...parent,
256
- delegatedCompletion: {
257
- disposition: "open",
258
- nextGeneration: 2,
259
- delivery: { generation: 1, messageId, taskIds: [taskId] },
260
- },
261
- },
262
- },
263
- {
264
- id: EventId.make("child"),
265
- type: "subagent.updated",
266
- threadId,
267
- runId: parent.id,
268
- nodeId: taskId,
269
- occurredAt: now,
270
- payload: {
271
- id: taskId,
272
- threadId,
273
- runId: parent.id,
274
- parentNodeId: parent.rootNodeId,
275
- origin: "app_owned",
276
- createdBy: "agent",
277
- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
278
- providerInstanceId: modelSelection.instanceId,
279
- providerThreadId: null,
280
- childThreadId: null,
281
- nativeTaskRef: null,
282
- prompt: "Background work",
283
- title: "Child",
284
- model: null,
285
- completionWake: "always",
286
- completionDelivery: { state: "claimed", observedByRunId: null },
287
- status: "completed",
288
- result: "done",
289
- startedAt: now,
290
- completedAt: now,
291
- updatedAt: now,
292
- },
293
- },
294
- ],
295
- });
296
- const command = {
297
- type: "message.dispatch" as const,
298
- commandId: CommandId.make("completion"),
299
- threadId,
300
- messageId,
301
- text: "Child completed",
302
- attachments: [],
303
- dispatchMode: { type: "queue_after_active" as const },
304
- createdBy: "agent" as const,
305
- creationSource: "server" as const,
306
- delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
307
- };
308
- yield* orchestrator.dispatch(command);
309
- yield* orchestrator.dispatch(command);
310
- yield* orchestrator.recoverDelegatedTasks;
311
- } else if (delivery === "scheduled message") {
312
- yield* Effect.gen(function* () {
313
- const service = yield* ScheduledTaskService.ScheduledTaskService;
314
- const { task } = yield* service.upsert(
315
- yield* decodeScheduledTask({
316
- title: "Status check",
317
- prompt: "Check the four tasks.",
318
- enabled: true,
319
- schedule: { type: "interval", everyMs: 60_000 },
320
- projectId,
321
- threadId,
322
- workspaceStrategy: { type: "root" },
323
- modelSelection,
324
- runtimeMode: "full-access",
325
- interactionMode: "default",
326
- }),
327
- );
328
- const ran = yield* service.runNow({ id: task.id });
329
- assert.equal(ran.task.lastRunStatus, "succeeded");
330
- }).pipe(
331
- Effect.provide(
332
- ScheduledTaskService.layer.pipe(
333
- Layer.provide(ThreadManagementService.layer),
334
- Layer.provide(ServerSettings.layerTest()),
335
- Layer.provide(
336
- Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
337
- ensureTranscript: () =>
338
- Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
339
- }),
340
- ),
341
- Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
342
- Layer.provide(ManagedPolicy.layerTest()),
343
- Layer.provide(
344
- Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
345
- namedProjectsRoot: "/projects",
346
- isScratchProject: () => Effect.succeed(false),
347
- }),
348
- ),
349
- Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
350
- Layer.provide(
351
- CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
352
- ),
353
- Layer.provide(
354
- Layer.mergeAll(
355
- NodeCrypto.layer,
356
- Scheduler.layer,
357
- SqlitePersistence.layerMemory,
358
- ),
359
- ),
360
- ),
361
- ),
362
- );
363
- } else if (delivery === "user steering") {
364
- yield* orchestrator.dispatch({
365
- type: "message.dispatch",
366
- commandId: CommandId.make("steer"),
367
- threadId,
368
- messageId,
369
- text: "Change direction now.",
370
- attachments: [],
371
- dispatchMode: { type: "steer_active", targetRunId: parent.id },
372
- createdBy: "user",
373
- creationSource: "web",
374
- });
375
- } else {
376
- yield* orchestrator.dispatch({
377
- type: "message.dispatch",
378
- commandId: CommandId.make("queue"),
379
- threadId,
380
- messageId,
381
- text: "Change direction now.",
382
- attachments: [],
383
- dispatchMode: { type: "queue_after_active" },
384
- createdBy: "user",
385
- creationSource: "web",
386
- });
387
- const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
388
- yield* orchestrator.dispatch({
389
- type: "queued-message.promote-to-steer",
390
- commandId: CommandId.make("promote"),
391
- threadId,
392
- queuedRunId: queuedRun.id,
393
- targetRunId: parent.id,
394
- });
395
- const promoted = yield* orchestrator.getThreadProjection(threadId);
396
- assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
397
- assert.equal(
398
- promoted.messages.find((message) => message.id === messageId)?.runId,
399
- parent.id,
400
- );
401
- const steer = promoted.turnItems.find(
402
- (item) => item.type === "user_message" && item.messageId === messageId,
403
- );
404
- assert.ok(steer?.type === "user_message");
405
- assert.equal(steer.inputIntent, "promoted_queued_to_steer");
406
- }
407
- yield* worker.drain();
408
- const explicitSteer =
409
- delivery === "user steering" || delivery === "promoted queued message";
410
- assert.equal(batchAbort.signal.aborted, explicitSteer);
411
- assert.equal(offers.length, explicitSteer ? 2 : 1);
412
- const finished = yield* watch(
413
- (event) =>
414
- event.type === "run.updated" &&
415
- event.payload.id === parent.id &&
416
- event.payload.status === "waiting",
417
- );
418
- yield* Queue.offer(sdkMessages, toolResult("build", false));
419
- for (const id of statusIds)
420
- yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
421
- if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
422
- yield* Queue.offer(sdkMessages, result("completed", false));
423
- yield* Fiber.join(finished);
424
- yield* worker.drain();
425
- yield* orchestrator.resumeQueuedRuns;
426
- yield* worker.drain();
427
- if (!explicitSteer) {
428
- const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
429
- const noticeFinished = yield* watch(
430
- (event) =>
431
- event.type === "run.updated" &&
432
- event.payload.id === queued.id &&
433
- event.payload.status === "waiting",
434
- );
435
- const delivered =
436
- delivery === "child completion"
437
- ? yield* watch(
438
- (event) =>
439
- event.type === "subagent.updated" &&
440
- event.payload.completionDelivery?.state === "delivered",
441
- )
442
- : null;
443
- yield* Queue.offer(sdkMessages, result("notice-completed", false));
444
- yield* Fiber.join(noticeFinished);
445
- yield* worker.drain();
446
- if (delivered !== null) yield* Fiber.join(delivered);
447
- }
448
- const after = yield* orchestrator.getThreadProjection(threadId);
449
- const reads = after.turnItems.filter((item) =>
450
- statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
451
- );
452
- assert.equal(reads.length, 4);
453
- for (const read of reads) {
454
- assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
455
- assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
456
- assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
457
- }
458
- assert.equal(offers.length, 2);
459
- assert.equal(
460
- offers.filter((offer) => offer.priority === "now").length,
461
- explicitSteer ? 1 : 0,
462
- );
463
- if (!explicitSteer) {
464
- assert.equal(after.runs.length, 2);
465
- if (delivery === "child completion") {
466
- assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
467
- assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
468
- } else {
469
- assert.equal(
470
- after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
471
- 1,
472
- );
473
- }
474
- }
475
- yield* orchestrator.recoverDelegatedTasks;
476
- yield* orchestrator.resumeQueuedRuns;
477
- yield* worker.drain();
478
- assert.equal(offers.length, 2);
479
- }).pipe(
480
- Effect.provide(
481
- ProviderReplayHarness.layerWithRegistry(
482
- { name: "claude-automatic-delivery" },
483
- ProviderAdapterRegistry.layerSingle(adapter),
484
- { runEffectWorker: false },
485
- ),
486
- ),
487
- );
488
- }).pipe(
489
- Effect.provide(
490
- Layer.mergeAll(
491
- IdAllocator.layer,
492
- McpProviderSessions.layer,
493
- NodeServices.layer,
494
- NodeCrypto.layer,
495
- ),
496
- ),
497
- ),
498
- ),
499
-);
500
-
501
-it.effect("applies an effort change to the running Claude query without waiting for a turn", () =>
502
- Effect.scoped(
139
Effect.gen(function* () {
504
- const cwd = yield* checkpointWorkspace("claude-live-effort");
140
+ const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
141
const sdkMessages = yield* Queue.unbounded<SDKMessage>();
506
- const flagSettings: unknown[] = [];
142
+ const offers: SDKUserMessage[] = [];
143
+ const nativeQueue: SDKUserMessage[] = [];
144
+ // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber.
145
+ const batchAbort = new AbortController();
146
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
147
instanceId: modelSelection.instanceId,
148
settings,
@@ -518,12 +157,17 @@ it.effect("applies an effort change to the running Claude query without waiting
157
open: () =>
158
Effect.succeed({
159
messages: Stream.fromQueue(sdkMessages),
521
- offer: () => Effect.void,
522
- setModel: () => Effect.void,
523
- applyFlagSettings: (flags) =>
160
+ offer: (message) =>
161
Effect.sync(() => {
525
- flagSettings.push(flags);
162
+ offers.push(message);
163
+ nativeQueue.push(message);
164
+ // Claude Code 2.1.289 aborts on now-priority commands even while Bash blocks reads.
165
+ if (nativeQueue.some((command) => command.priority === "now")) {
166
+ batchAbort.abort({ kind: "interrupt" });
167
+ }
168
}),
169
+ setModel: () => Effect.void,
170
+ applyFlagSettings: () => Effect.void,
171
setPermissionMode: () => Effect.void,
172
backgroundTasks: () => Effect.succeed(false),
173
mcpServerStatus: Effect.succeed([]),
@@ -531,7 +175,7 @@ it.effect("applies an effort change to the running Claude query without waiting
175
callMcpTool: () => Effect.die("unexpected MCP tool call"),
176
listPermissionRules: Effect.die("unexpected permission rules read"),
177
stopTask: () => Effect.void,
534
- interrupt: Effect.die("an effort change must not interrupt the turn"),
178
+ interrupt: Effect.die("automatic delivery must never interrupt"),
179
close: Effect.void,
180
}),
181
forkSession: () => Effect.die("unused"),
@@ -543,23 +187,22 @@ it.effect("applies an effort change to the running Claude query without waiting
187
yield* Effect.gen(function* () {
188
const orchestrator = yield* Orchestrator.OrchestratorV2;
189
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
546
- const threadId = ThreadId.make("thread:live-effort");
547
- const high = { ...modelSelection, options: [{ id: "effort", value: "high" }] };
548
- const running = yield* orchestrator.streamDomainEvents.pipe(
549
- Stream.filter(
550
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
551
- ),
552
- Stream.take(1),
553
- Stream.runDrain,
554
- Effect.forkScoped,
555
- );
190
+ const threadId = ThreadId.make("thread:automatic-delivery");
191
+ const projectId = ProjectId.make("project:automatic-delivery");
192
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
193
+ orchestrator.streamDomainEvents.pipe(
194
+ Stream.filter(predicate),
195
+ Stream.take(1),
196
+ Stream.runDrain,
197
+ Effect.forkScoped,
198
+ );
199
yield* orchestrator.dispatch({
200
type: "thread.create",
201
commandId: CommandId.make("create"),
202
threadId,
560
- projectId: ProjectId.make("project:live-effort"),
561
- title: "Live effort",
562
- modelSelection: high,
203
+ projectId,
204
+ title: "Automatic delivery",
205
+ modelSelection,
206
runtimeMode: "full-access",
207
interactionMode: "default",
208
branch: null,
@@ -567,12 +210,15 @@ it.effect("applies an effort change to the running Claude query without waiting
210
createdBy: "user",
211
creationSource: "web",
212
});
213
+ const running = yield* watch(
214
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
215
+ );
216
yield* orchestrator.dispatch({
217
type: "message.dispatch",
218
commandId: CommandId.make("first"),
219
threadId,
220
messageId: MessageId.make("first"),
575
- text: "Keep working.",
221
+ text: "Build and check all four tasks.",
222
attachments: [],
223
dispatchMode: { type: "start_immediately" },
224
createdBy: "user",
@@ -580,23 +226,255 @@ it.effect("applies an effort change to the running Claude query without waiting
226
});
227
yield* worker.drain();
228
yield* Fiber.join(running);
583
- assert.deepEqual(flagSettings, []);
584
-
585
- yield* orchestrator.dispatch({
586
- type: "thread.model-selection.set",
587
- commandId: CommandId.make("medium"),
588
- threadId,
589
- modelSelection: { ...modelSelection, options: [{ id: "effort", value: "medium" }] },
590
- });
229
+ const pending = yield* watch(
230
+ (event) =>
231
+ event.type === "turn-item.updated" &&
232
+ event.payload.nativeItemRef?.nativeId === "status-4",
233
+ );
234
+ yield* Queue.offer(sdkMessages, batch);
235
+ yield* Fiber.join(pending);
236
+ const before = yield* orchestrator.getThreadProjection(threadId);
237
+ assert.equal(before.turnItems.filter((item) => item.status === "running").length, 5);
238
+ const parent = before.runs[0]!;
239
+ if (parent.rootNodeId === null) return yield* Effect.die("parent has no root node");
240
+ const messageId = MessageId.make("automatic-notice");
241
+ if (delivery === "child completion") {
242
+ const taskId = NodeId.make("completed-child");
243
+ const now = yield* DateTime.now;
244
+ const sink = yield* EventSink.EventSinkV2;
245
+ yield* sink.write({
246
+ events: [
247
+ {
248
+ id: EventId.make("cohort"),
249
+ type: "run.updated",
250
+ threadId,
251
+ runId: parent.id,
252
+ occurredAt: now,
253
+ payload: {
254
+ ...parent,
255
+ delegatedCompletion: {
256
+ disposition: "open",
257
+ nextGeneration: 2,
258
+ delivery: { generation: 1, messageId, taskIds: [taskId] },
259
+ },
260
+ },
261
+ },
262
+ {
263
+ id: EventId.make("child"),
264
+ type: "subagent.updated",
265
+ threadId,
266
+ runId: parent.id,
267
+ nodeId: taskId,
268
+ occurredAt: now,
269
+ payload: {
270
+ id: taskId,
271
+ threadId,
272
+ runId: parent.id,
273
+ parentNodeId: parent.rootNodeId,
274
+ origin: "app_owned",
275
+ createdBy: "agent",
276
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
277
+ providerInstanceId: modelSelection.instanceId,
278
+ providerThreadId: null,
279
+ childThreadId: null,
280
+ nativeTaskRef: null,
281
+ prompt: "Background work",
282
+ title: "Child",
283
+ model: null,
284
+ completionWake: "always",
285
+ completionDelivery: { state: "claimed", observedByRunId: null },
286
+ status: "completed",
287
+ result: "done",
288
+ startedAt: now,
289
+ completedAt: now,
290
+ updatedAt: now,
291
+ },
292
+ },
293
+ ],
294
+ });
295
+ const command = {
296
+ type: "message.dispatch" as const,
297
+ commandId: CommandId.make("completion"),
298
+ threadId,
299
+ messageId,
300
+ text: "Child completed",
301
+ attachments: [],
302
+ dispatchMode: { type: "queue_after_active" as const },
303
+ createdBy: "agent" as const,
304
+ creationSource: "server" as const,
305
+ delegatedCompletion: { parentRunId: parent.id, generation: 1, taskIds: [taskId] },
306
+ };
307
+ yield* orchestrator.dispatch(command);
308
+ yield* orchestrator.dispatch(command);
309
+ yield* orchestrator.recoverDelegatedTasks;
310
+ } else if (delivery === "scheduled message") {
311
+ yield* Effect.gen(function* () {
312
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
313
+ const { task } = yield* service.upsert(
314
+ yield* decodeScheduledTask({
315
+ title: "Status check",
316
+ prompt: "Check the four tasks.",
317
+ enabled: true,
318
+ schedule: { type: "interval", everyMs: 60_000 },
319
+ projectId,
320
+ threadId,
321
+ workspaceStrategy: { type: "root" },
322
+ modelSelection,
323
+ runtimeMode: "full-access",
324
+ interactionMode: "default",
325
+ }),
326
+ );
327
+ const ran = yield* service.runNow({ id: task.id });
328
+ assert.equal(ran.task.lastRunStatus, "succeeded");
329
+ }).pipe(
330
+ Effect.provide(
331
+ ScheduledTaskService.layer.pipe(
332
+ Layer.provide(ThreadManagementService.layer),
333
+ Layer.provide(ServerSettings.layerTest()),
334
+ Layer.provide(
335
+ Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
336
+ ensureTranscript: () =>
337
+ Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
338
+ }),
339
+ ),
340
+ Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
341
+ Layer.provide(ManagedPolicy.layerTest()),
342
+ Layer.provide(
343
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
344
+ namedProjectsRoot: "/projects",
345
+ isScratchProject: () => Effect.succeed(false),
346
+ }),
347
+ ),
348
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
349
+ Layer.provide(
350
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
351
+ ),
352
+ Layer.provide(
353
+ Layer.mergeAll(NodeCrypto.layer, Scheduler.layer, SqlitePersistence.layerMemory),
354
+ ),
355
+ ),
356
+ ),
357
+ );
358
+ } else if (delivery === "user steering") {
359
+ yield* orchestrator.dispatch({
360
+ type: "message.dispatch",
361
+ commandId: CommandId.make("steer"),
362
+ threadId,
363
+ messageId,
364
+ text: "Change direction now.",
365
+ attachments: [],
366
+ dispatchMode: { type: "steer_active", targetRunId: parent.id },
367
+ createdBy: "user",
368
+ creationSource: "web",
369
+ });
370
+ } else {
371
+ yield* orchestrator.dispatch({
372
+ type: "message.dispatch",
373
+ commandId: CommandId.make("queue"),
374
+ threadId,
375
+ messageId,
376
+ text: "Change direction now.",
377
+ attachments: [],
378
+ dispatchMode: { type: "queue_after_active" },
379
+ createdBy: "user",
380
+ creationSource: "web",
381
+ });
382
+ const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
383
+ yield* orchestrator.dispatch({
384
+ type: "queued-message.promote-to-steer",
385
+ commandId: CommandId.make("promote"),
386
+ threadId,
387
+ queuedRunId: queuedRun.id,
388
+ targetRunId: parent.id,
389
+ });
390
+ const promoted = yield* orchestrator.getThreadProjection(threadId);
391
+ assert.equal(promoted.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled");
392
+ assert.equal(
393
+ promoted.messages.find((message) => message.id === messageId)?.runId,
394
+ parent.id,
395
+ );
396
+ const steer = promoted.turnItems.find(
397
+ (item) => item.type === "user_message" && item.messageId === messageId,
398
+ );
399
+ assert.ok(steer?.type === "user_message");
400
+ assert.equal(steer.inputIntent, "promoted_queued_to_steer");
401
+ }
402
yield* worker.drain();
592
-
593
- assert.deepEqual(flagSettings, [
594
- { effortLevel: "medium", fastMode: null, ultracode: null },
595
- ]);
403
+ const explicitSteer =
404
+ delivery === "user steering" || delivery === "promoted queued message";
405
+ assert.equal(batchAbort.signal.aborted, explicitSteer);
406
+ assert.equal(offers.length, explicitSteer ? 2 : 1);
407
+ const finished = yield* watch(
408
+ (event) =>
409
+ event.type === "run.updated" &&
410
+ event.payload.id === parent.id &&
411
+ event.payload.status === "waiting",
412
+ );
413
+ yield* Queue.offer(sdkMessages, toolResult("build", false));
414
+ for (const id of statusIds)
415
+ yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
416
+ if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
417
+ yield* Queue.offer(sdkMessages, result("completed", false));
418
+ yield* Fiber.join(finished);
419
+ yield* worker.drain();
420
+ yield* orchestrator.resumeQueuedRuns;
421
+ yield* worker.drain();
422
+ if (!explicitSteer) {
423
+ const queued = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!;
424
+ const noticeFinished = yield* watch(
425
+ (event) =>
426
+ event.type === "run.updated" &&
427
+ event.payload.id === queued.id &&
428
+ event.payload.status === "waiting",
429
+ );
430
+ const delivered =
431
+ delivery === "child completion"
432
+ ? yield* watch(
433
+ (event) =>
434
+ event.type === "subagent.updated" &&
435
+ event.payload.completionDelivery?.state === "delivered",
436
+ )
437
+ : null;
438
+ yield* Queue.offer(sdkMessages, result("notice-completed", false));
439
+ yield* Fiber.join(noticeFinished);
440
+ yield* worker.drain();
441
+ if (delivered !== null) yield* Fiber.join(delivered);
442
+ }
443
+ const after = yield* orchestrator.getThreadProjection(threadId);
444
+ const reads = after.turnItems.filter((item) =>
445
+ statusIds.includes(item.nativeItemRef?.nativeId ?? ""),
446
+ );
447
+ assert.equal(reads.length, 4);
448
+ for (const read of reads) {
449
+ assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
450
+ assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
451
+ assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
452
+ }
453
+ assert.equal(offers.length, 2);
454
+ assert.equal(
455
+ offers.filter((offer) => offer.priority === "now").length,
456
+ explicitSteer ? 1 : 0,
457
+ );
458
+ if (!explicitSteer) {
459
+ assert.equal(after.runs.length, 2);
460
+ if (delivery === "child completion") {
461
+ assert.equal(after.messages.filter((message) => message.id === messageId).length, 1);
462
+ assert.equal(after.subagents[0]?.completionDelivery?.state, "delivered");
463
+ } else {
464
+ assert.equal(
465
+ after.messages.filter((message) => message.scheduledTaskId !== undefined).length,
466
+ 1,
467
+ );
468
+ }
469
+ }
470
+ yield* orchestrator.recoverDelegatedTasks;
471
+ yield* orchestrator.resumeQueuedRuns;
472
+ yield* worker.drain();
473
+ assert.equal(offers.length, 2);
474
}).pipe(
475
Effect.provide(
476
ProviderReplayHarness.layerWithRegistry(
599
- { name: "claude-live-effort" },
477
+ { name: "claude-automatic-delivery" },
478
ProviderAdapterRegistry.layerSingle(adapter),
479
{ runEffectWorker: false },
480
),
@@ -612,6 +490,118 @@ it.effect("applies an effort change to the running Claude query without waiting
490
),
491
),
492
),
493
+);
494
+
495
+it.effect("applies an effort change to the running Claude query without waiting for a turn", () =>
496
+ Effect.gen(function* () {
497
+ const cwd = yield* checkpointWorkspace("claude-live-effort");
498
+ const sdkMessages = yield* Queue.unbounded<SDKMessage>();
499
+ const flagSettings: unknown[] = [];
500
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
501
+ instanceId: modelSelection.instanceId,
502
+ settings,
503
+ environment: {},
504
+ attachmentsDir: cwd,
505
+ fileSystem: yield* FileSystem.FileSystem,
506
+ path: yield* Path.Path,
507
+ random: yield* SecureRandom.SecureRandom,
508
+ idAllocator: yield* IdAllocator.IdAllocatorV2,
509
+ queryRunner: {
510
+ allocateSessionId: Effect.succeed(sessionId),
511
+ open: () =>
512
+ Effect.succeed({
513
+ messages: Stream.fromQueue(sdkMessages),
514
+ offer: () => Effect.void,
515
+ setModel: () => Effect.void,
516
+ applyFlagSettings: (flags) =>
517
+ Effect.sync(() => {
518
+ flagSettings.push(flags);
519
+ }),
520
+ setPermissionMode: () => Effect.void,
521
+ backgroundTasks: () => Effect.succeed(false),
522
+ mcpServerStatus: Effect.succeed([]),
523
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
524
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
525
+ listPermissionRules: Effect.die("unexpected permission rules read"),
526
+ stopTask: () => Effect.void,
527
+ interrupt: Effect.die("an effort change must not interrupt the turn"),
528
+ close: Effect.void,
529
+ }),
530
+ forkSession: () => Effect.die("unused"),
531
+ subagentLaunchToolUseId: () => Effect.succeed(null),
532
+ subagentModel: () => Effect.succeed(null),
533
+ assertComplete: Effect.void,
534
+ },
535
+ });
536
+ yield* Effect.gen(function* () {
537
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
538
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
539
+ const threadId = ThreadId.make("thread:live-effort");
540
+ const high = { ...modelSelection, options: [{ id: "effort", value: "high" }] };
541
+ const running = yield* orchestrator.streamDomainEvents.pipe(
542
+ Stream.filter(
543
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
544
+ ),
545
+ Stream.take(1),
546
+ Stream.runDrain,
547
+ Effect.forkScoped,
548
+ );
549
+ yield* orchestrator.dispatch({
550
+ type: "thread.create",
551
+ commandId: CommandId.make("create"),
552
+ threadId,
553
+ projectId: ProjectId.make("project:live-effort"),
554
+ title: "Live effort",
555
+ modelSelection: high,
556
+ runtimeMode: "full-access",
557
+ interactionMode: "default",
558
+ branch: null,
559
+ worktreePath: cwd,
560
+ createdBy: "user",
561
+ creationSource: "web",
562
+ });
563
+ yield* orchestrator.dispatch({
564
+ type: "message.dispatch",
565
+ commandId: CommandId.make("first"),
566
+ threadId,
567
+ messageId: MessageId.make("first"),
568
+ text: "Keep working.",
569
+ attachments: [],
570
+ dispatchMode: { type: "start_immediately" },
571
+ createdBy: "user",
572
+ creationSource: "web",
573
+ });
574
+ yield* worker.drain();
575
+ yield* Fiber.join(running);
576
+ assert.deepEqual(flagSettings, []);
577
+
578
+ yield* orchestrator.dispatch({
579
+ type: "thread.model-selection.set",
580
+ commandId: CommandId.make("medium"),
581
+ threadId,
582
+ modelSelection: { ...modelSelection, options: [{ id: "effort", value: "medium" }] },
583
+ });
584
+ yield* worker.drain();
585
+
586
+ assert.deepEqual(flagSettings, [{ effortLevel: "medium", fastMode: null, ultracode: null }]);
587
+ }).pipe(
588
+ Effect.provide(
589
+ ProviderReplayHarness.layerWithRegistry(
590
+ { name: "claude-live-effort" },
591
+ ProviderAdapterRegistry.layerSingle(adapter),
592
+ { runEffectWorker: false },
593
+ ),
594
+ ),
595
+ );
596
+ }).pipe(
597
+ Effect.provide(
598
+ Layer.mergeAll(
599
+ IdAllocator.layer,
600
+ McpProviderSessions.layer,
601
+ NodeServices.layer,
602
+ NodeCrypto.layer,
603
+ ),
604
+ ),
605
),
606
);
607
@@ -660,246 +650,237 @@ const wakeAssistant = (uuid: string) =>
650
});
651
652
it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () =>
663
- Effect.scoped(
664
- Effect.gen(function* () {
665
- const cwd = yield* checkpointWorkspace("claude-cancelled-continuation");
666
- const sdkMessages = yield* Queue.unbounded<SDKMessage>();
667
- const processed = new WeakMap<SDKMessage, Deferred.Deferred<void>>();
668
- const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) {
669
- const done = yield* Deferred.make<void>();
670
- processed.set(message, done);
671
- yield* Queue.offer(sdkMessages, message);
672
- yield* Deferred.await(done);
673
- });
674
- const fileSystem = yield* FileSystem.FileSystem;
675
- const path = yield* Path.Path;
676
- const random = yield* SecureRandom.SecureRandom;
677
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
678
- const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
679
- const services =
680
- yield* Effect.context<
681
- Effect.Services<ReturnType<typeof ClaudeAdapterV2.makeClaudeAdapterV2>>
682
- >();
683
- const registry = ProviderAdapterRegistry.layerFromAdaptersEffect(
684
- Effect.gen(function* () {
685
- const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
686
- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
687
- instanceId: modelSelection.instanceId,
688
- settings,
689
- environment: {},
690
- attachmentsDir: cwd,
691
- fileSystem,
692
- path,
693
- random,
694
- idAllocator,
695
- continuationRequests: {
696
- offer: (request) =>
697
- Effect.sync(() => continuations.push(request)).pipe(
698
- Effect.andThen(requests.offer(request)),
699
- ),
700
- },
701
- queryRunner: {
702
- allocateSessionId: Effect.succeed(sessionId),
703
- open: () =>
704
- Effect.succeed({
705
- // Resolve each frame's Deferred once the adapter pulls the next one.
706
- messages: Stream.fromQueue(sdkMessages).pipe(
707
- Stream.flatMap((message) =>
708
- Stream.make(message).pipe(
709
- Stream.concat(
710
- Stream.fromEffect(
711
- Effect.suspend(() => {
712
- const done = processed.get(message);
713
- return done === undefined
714
- ? Effect.void
715
- : Deferred.succeed(done, undefined);
716
- }),
717
- ).pipe(Stream.drain),
718
- ),
653
+ Effect.gen(function* () {
654
+ const cwd = yield* checkpointWorkspace("claude-cancelled-continuation");
655
+ const sdkMessages = yield* Queue.unbounded<SDKMessage>();
656
+ const processed = new WeakMap<SDKMessage, Deferred.Deferred<void>>();
657
+ const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) {
658
+ const done = yield* Deferred.make<void>();
659
+ processed.set(message, done);
660
+ yield* Queue.offer(sdkMessages, message);
661
+ yield* Deferred.await(done);
662
+ });
663
+ const fileSystem = yield* FileSystem.FileSystem;
664
+ const path = yield* Path.Path;
665
+ const random = yield* SecureRandom.SecureRandom;
666
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
667
+ const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
668
+ const services =
669
+ yield* Effect.context<
670
+ Effect.Services<ReturnType<typeof ClaudeAdapterV2.makeClaudeAdapterV2>>
671
+ >();
672
+ const registry = ProviderAdapterRegistry.layerFromAdaptersEffect(
673
+ Effect.gen(function* () {
674
+ const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
675
+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
676
+ instanceId: modelSelection.instanceId,
677
+ settings,
678
+ environment: {},
679
+ attachmentsDir: cwd,
680
+ fileSystem,
681
+ path,
682
+ random,
683
+ idAllocator,
684
+ continuationRequests: {
685
+ offer: (request) =>
686
+ Effect.sync(() => continuations.push(request)).pipe(
687
+ Effect.andThen(requests.offer(request)),
688
+ ),
689
+ },
690
+ queryRunner: {
691
+ allocateSessionId: Effect.succeed(sessionId),
692
+ open: () =>
693
+ Effect.succeed({
694
+ // Resolve each frame's Deferred once the adapter pulls the next one.
695
+ messages: Stream.fromQueue(sdkMessages).pipe(
696
+ Stream.flatMap((message) =>
697
+ Stream.make(message).pipe(
698
+ Stream.concat(
699
+ Stream.fromEffect(
700
+ Effect.suspend(() => {
701
+ const done = processed.get(message);
702
+ return done === undefined
703
+ ? Effect.void
704
+ : Deferred.succeed(done, undefined);
705
+ }),
706
+ ).pipe(Stream.drain),
707
),
708
),
709
),
722
- offer: () => Effect.void,
723
- setModel: () => Effect.void,
724
- applyFlagSettings: () => Effect.void,
725
- setPermissionMode: () => Effect.void,
726
- backgroundTasks: () => Effect.succeed(false),
727
- mcpServerStatus: Effect.succeed([]),
728
- readMcpResource: () => Effect.die("unexpected MCP resource read"),
729
- callMcpTool: () => Effect.die("unexpected MCP tool call"),
730
- listPermissionRules: Effect.die("unexpected permission rules read"),
731
- stopTask: () => Effect.void,
732
- interrupt: Effect.void,
733
- close: Effect.void,
734
- }),
735
- forkSession: () => Effect.die("unused"),
736
- subagentLaunchToolUseId: () => Effect.succeed(null),
737
- subagentModel: () => Effect.succeed(null),
738
- assertComplete: Effect.void,
739
- },
740
- }).pipe(Effect.provideContext(services));
741
- return [adapter];
742
- }),
743
- );
744
- yield* Effect.gen(function* () {
745
- const orchestrator = yield* Orchestrator.OrchestratorV2;
746
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
747
- const threadId = ThreadId.make("thread:cancelled-continuation");
748
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
749
- orchestrator.streamDomainEvents.pipe(
750
- Stream.filter(predicate),
751
- Stream.take(1),
752
- Stream.runDrain,
753
- Effect.forkScoped,
754
- );
755
- const runUpdated = (messageId: string, status: string) =>
756
- watch(
757
- (event) =>
758
- event.type === "run.updated" &&
759
- event.payload.userMessageId === messageId &&
760
- event.payload.status === status,
761
- );
762
- // A user turn that leaves a background task running when it ends.
763
- const userTurnWithBackgroundTask = Effect.fnUntraced(function* (
764
- id: string,
765
- taskId: string,
766
- ) {
767
- const running = yield* runUpdated(id, "running");
768
- yield* orchestrator.dispatch({
769
- type: "message.dispatch",
770
- commandId: CommandId.make(id),
771
- threadId,
772
- messageId: MessageId.make(id),
773
- text: "Run the build in the background.",
774
- attachments: [],
775
- dispatchMode: { type: "start_immediately" },
776
- createdBy: "user",
777
- creationSource: "web",
778
- });
779
- yield* worker.drain();
780
- yield* Fiber.join(running);
781
- const waiting = yield* runUpdated(id, "waiting");
782
- yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
783
- yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
784
- yield* Fiber.join(waiting);
785
- });
786
- yield* orchestrator.dispatch({
787
- type: "thread.create",
788
- commandId: CommandId.make("create"),
789
- threadId,
790
- projectId: ProjectId.make("project:cancelled-continuation"),
791
- title: "Cancelled continuation",
792
- modelSelection,
793
- runtimeMode: "full-access",
794
- interactionMode: "default",
795
- branch: null,
796
- worktreePath: cwd,
797
- createdBy: "user",
798
- creationSource: "web",
799
- });
800
-
801
- // The first run is still finalizing when its background task wakes Claude.
802
- yield* userTurnWithBackgroundTask("first", "build-1");
803
- const queued = yield* watch(
804
- (event) => event.type === "run.created" && event.payload.status === "queued",
710
+ ),
711
+ offer: () => Effect.void,
712
+ setModel: () => Effect.void,
713
+ applyFlagSettings: () => Effect.void,
714
+ setPermissionMode: () => Effect.void,
715
+ backgroundTasks: () => Effect.succeed(false),
716
+ mcpServerStatus: Effect.succeed([]),
717
+ readMcpResource: () => Effect.die("unexpected MCP resource read"),
718
+ callMcpTool: () => Effect.die("unexpected MCP tool call"),
719
+ listPermissionRules: Effect.die("unexpected permission rules read"),
720
+ stopTask: () => Effect.void,
721
+ interrupt: Effect.void,
722
+ close: Effect.void,
723
+ }),
724
+ forkSession: () => Effect.die("unused"),
725
+ subagentLaunchToolUseId: () => Effect.succeed(null),
726
+ subagentModel: () => Effect.succeed(null),
727
+ assertComplete: Effect.void,
728
+ },
729
+ }).pipe(Effect.provideContext(services));
730
+ return [adapter];
731
+ }),
732
+ );
733
+ yield* Effect.gen(function* () {
734
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
735
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
736
+ const threadId = ThreadId.make("thread:cancelled-continuation");
737
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
738
+ orchestrator.streamDomainEvents.pipe(
739
+ Stream.filter(predicate),
740
+ Stream.take(1),
741
+ Stream.runDrain,
742
+ Effect.forkScoped,
743
);
806
- yield* offerAndWait(backgroundTaskNotification("build-1"));
807
- yield* offerAndWait(wakeAssistant("wake-1"));
808
- yield* Fiber.join(queued);
809
- assert.lengthOf(continuations, 1);
810
- const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
811
- (run) => run.status === "queued",
744
+ const runUpdated = (messageId: string, status: string) =>
745
+ watch(
746
+ (event) =>
747
+ event.type === "run.updated" &&
748
+ event.payload.userMessageId === messageId &&
749
+ event.payload.status === status,
750
);
813
- assert.ok(continuationRun !== undefined);
751
+ // A user turn that leaves a background task running when it ends.
752
+ const userTurnWithBackgroundTask = Effect.fnUntraced(function* (id: string, taskId: string) {
753
+ const running = yield* runUpdated(id, "running");
754
yield* orchestrator.dispatch({
815
- type: "queued-run.cancel",
816
- commandId: CommandId.make("cancel"),
755
+ type: "message.dispatch",
756
+ commandId: CommandId.make(id),
757
threadId,
818
- runId: continuationRun.id,
758
+ messageId: MessageId.make(id),
759
+ text: "Run the build in the background.",
760
+ attachments: [],
761
+ dispatchMode: { type: "start_immediately" },
762
+ createdBy: "user",
763
+ creationSource: "web",
764
});
820
- yield* offerAndWait(result("wake-1-result", false));
765
yield* worker.drain();
822
- yield* orchestrator.resumeQueuedRuns;
823
- yield* worker.drain();
824
- const idle = yield* orchestrator.getThreadProjection(threadId);
825
- assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled");
826
- assert.isFalse(idle.runs.some((run) => run.status === "queued"));
766
+ yield* Fiber.join(running);
767
+ const waiting = yield* runUpdated(id, "waiting");
768
+ yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId));
769
+ yield* Queue.offer(sdkMessages, result(`result-${id}`, false));
770
+ yield* Fiber.join(waiting);
771
+ });
772
+ yield* orchestrator.dispatch({
773
+ type: "thread.create",
774
+ commandId: CommandId.make("create"),
775
+ threadId,
776
+ projectId: ProjectId.make("project:cancelled-continuation"),
777
+ title: "Cancelled continuation",
778
+ modelSelection,
779
+ runtimeMode: "full-access",
780
+ interactionMode: "default",
781
+ branch: null,
782
+ worktreePath: cwd,
783
+ createdBy: "user",
784
+ creationSource: "web",
785
+ });
786
828
- yield* userTurnWithBackgroundTask("second", "build-2");
829
- yield* worker.drain();
830
- // The second user run has completed, so this continuation starts without queueing.
831
- const isContinuationRun = (
832
- event: OrchestrationV2DomainEvent,
833
- type: string,
834
- status: string,
835
- ) =>
836
- (event.type === "run.created" || event.type === "run.updated") &&
837
- event.type === type &&
838
- event.payload.status === status &&
839
- event.payload.userMessageId !== MessageId.make("first") &&
840
- event.payload.userMessageId !== MessageId.make("second");
841
- const secondCreated = yield* watch((event) =>
842
- isContinuationRun(event, "run.created", "starting"),
843
- );
844
- const secondRunning = yield* watch((event) =>
845
- isContinuationRun(event, "run.updated", "running"),
846
- );
847
- yield* offerAndWait(backgroundTaskNotification("build-2"));
848
- yield* offerAndWait(wakeAssistant("wake-2"));
849
- assert.lengthOf(
850
- continuations,
851
- 2,
852
- "the wake after a cancelled queued continuation must offer a new continuation",
853
- );
854
- yield* Fiber.join(secondCreated);
855
- yield* worker.drain();
856
- yield* Fiber.join(secondRunning);
857
- const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
858
- (run) => run.status === "running",
859
- );
860
- assert.ok(secondContinuation !== undefined);
861
- const secondWaiting = yield* watch(
862
- (event) =>
863
- event.type === "run.updated" &&
864
- event.payload.id === secondContinuation.id &&
865
- event.payload.status === "waiting",
866
- );
867
- yield* offerAndWait(result("wake-2-result", false));
868
- yield* Fiber.join(secondWaiting);
869
- yield* worker.drain();
870
- const settled = yield* orchestrator.getThreadProjection(threadId);
871
- assert.equal(
872
- settled.runs.find((run) => run.id === secondContinuation.id)?.status,
873
- "completed",
874
- );
875
- assert.deepEqual(
876
- settled.turnItems.flatMap((item) =>
877
- item.runId === secondContinuation.id && item.type === "assistant_message"
878
- ? [item.text]
879
- : [],
880
- ),
881
- ["Background build finished (wake-2)."],
882
- "the continuation must carry only its own wake's output",
883
- );
884
- assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations");
885
- }).pipe(
886
- Effect.provide(
887
- ProviderReplayHarness.layerWithRegistry(
888
- { name: "claude-cancelled-continuation" },
889
- registry,
890
- { runEffectWorker: false, runContinuationWorker: true },
891
- ),
787
+ // The first run is still finalizing when its background task wakes Claude.
788
+ yield* userTurnWithBackgroundTask("first", "build-1");
789
+ const queued = yield* watch(
790
+ (event) => event.type === "run.created" && event.payload.status === "queued",
791
+ );
792
+ yield* offerAndWait(backgroundTaskNotification("build-1"));
793
+ yield* offerAndWait(wakeAssistant("wake-1"));
794
+ yield* Fiber.join(queued);
795
+ assert.lengthOf(continuations, 1);
796
+ const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
797
+ (run) => run.status === "queued",
798
+ );
799
+ assert.ok(continuationRun !== undefined);
800
+ yield* orchestrator.dispatch({
801
+ type: "queued-run.cancel",
802
+ commandId: CommandId.make("cancel"),
803
+ threadId,
804
+ runId: continuationRun.id,
805
+ });
806
+ yield* offerAndWait(result("wake-1-result", false));
807
+ yield* worker.drain();
808
+ yield* orchestrator.resumeQueuedRuns;
809
+ yield* worker.drain();
810
+ const idle = yield* orchestrator.getThreadProjection(threadId);
811
+ assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled");
812
+ assert.isFalse(idle.runs.some((run) => run.status === "queued"));
813
+
814
+ yield* userTurnWithBackgroundTask("second", "build-2");
815
+ yield* worker.drain();
816
+ // The second user run has completed, so this continuation starts without queueing.
817
+ const isContinuationRun = (event: OrchestrationV2DomainEvent, type: string, status: string) =>
818
+ (event.type === "run.created" || event.type === "run.updated") &&
819
+ event.type === type &&
820
+ event.payload.status === status &&
821
+ event.payload.userMessageId !== MessageId.make("first") &&
822
+ event.payload.userMessageId !== MessageId.make("second");
823
+ const secondCreated = yield* watch((event) =>
824
+ isContinuationRun(event, "run.created", "starting"),
825
+ );
826
+ const secondRunning = yield* watch((event) =>
827
+ isContinuationRun(event, "run.updated", "running"),
828
+ );
829
+ yield* offerAndWait(backgroundTaskNotification("build-2"));
830
+ yield* offerAndWait(wakeAssistant("wake-2"));
831
+ assert.lengthOf(
832
+ continuations,
833
+ 2,
834
+ "the wake after a cancelled queued continuation must offer a new continuation",
835
+ );
836
+ yield* Fiber.join(secondCreated);
837
+ yield* worker.drain();
838
+ yield* Fiber.join(secondRunning);
839
+ const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
840
+ (run) => run.status === "running",
841
+ );
842
+ assert.ok(secondContinuation !== undefined);
843
+ const secondWaiting = yield* watch(
844
+ (event) =>
845
+ event.type === "run.updated" &&
846
+ event.payload.id === secondContinuation.id &&
847
+ event.payload.status === "waiting",
848
+ );
849
+ yield* offerAndWait(result("wake-2-result", false));
850
+ yield* Fiber.join(secondWaiting);
851
+ yield* worker.drain();
852
+ const settled = yield* orchestrator.getThreadProjection(threadId);
853
+ assert.equal(
854
+ settled.runs.find((run) => run.id === secondContinuation.id)?.status,
855
+ "completed",
856
+ );
857
+ assert.deepEqual(
858
+ settled.turnItems.flatMap((item) =>
859
+ item.runId === secondContinuation.id && item.type === "assistant_message"
860
+ ? [item.text]
861
+ : [],
862
),
863
+ ["Background build finished (wake-2)."],
864
+ "the continuation must carry only its own wake's output",
865
);
866
+ assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations");
867
}).pipe(
868
Effect.provide(
896
- Layer.mergeAll(
897
- IdAllocator.layer,
898
- McpProviderSessions.layer,
899
- NodeServices.layer,
900
- NodeCrypto.layer,
869
+ ProviderReplayHarness.layerWithRegistry(
870
+ { name: "claude-cancelled-continuation" },
871
+ registry,
872
+ { runEffectWorker: false, runContinuationWorker: true },
873
),
874
),
875
+ );
876
+ }).pipe(
877
+ Effect.provide(
878
+ Layer.mergeAll(
879
+ IdAllocator.layer,
880
+ McpProviderSessions.layer,
881
+ NodeServices.layer,
882
+ NodeCrypto.layer,
883
+ ),
884
),
885
),
886
);
apps/server/src/orchestration-v2/CommandOutputHub.test.ts
+139
-153
@@ -175,54 +175,52 @@ layer("CommandOutputHub", (it) => {
175
it.effect(
176
"a late subscriber gets the running tail, then live appends, then the final output",
177
() =>
178
- Effect.scoped(
179
- Effect.gen(function* () {
180
- const hub = yield* CommandOutputHub.CommandOutputHub;
181
- const threadId = yield* seedThread;
182
- yield* writeCommandItem(threadId, { status: "running" });
183
- yield* hub.append({
184
- threadId,
185
- itemId: ITEM_ID,
186
- chunk: "\u001b[32mbuilding\u001b[0m\n10%",
187
- });
188
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });
178
+ Effect.gen(function* () {
179
+ const hub = yield* CommandOutputHub.CommandOutputHub;
180
+ const threadId = yield* seedThread;
181
+ yield* writeCommandItem(threadId, { status: "running" });
182
+ yield* hub.append({
183
+ threadId,
184
+ itemId: ITEM_ID,
185
+ chunk: "\u001b[32mbuilding\u001b[0m\n10%",
186
+ });
187
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r55%\u001b[3" });
188
190
- const frames = yield* subscribeFrames(threadId);
191
- const first = yield* takeFrame(frames);
192
- assert.equal(first.kind, "replace");
193
- assert.isTrue(first.running);
194
- let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);
195
- assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");
189
+ const frames = yield* subscribeFrames(threadId);
190
+ const first = yield* takeFrame(frames);
191
+ assert.equal(first.kind, "replace");
192
+ assert.isTrue(first.running);
193
+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, first);
194
+ assert.equal(client.text, "\u001b[0;32mbuilding\u001b[0m\n55%");
195
197
- yield* TestClock.adjust("1 second");
198
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });
199
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });
200
- const append = yield* takeFrame(frames);
201
- assert.equal(append.kind, "append");
202
- client = applyFrame(client, append);
203
- assert.equal(
204
- client.text,
205
- normalizeTerminalOutput(
206
- "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",
207
- ).text,
208
- );
196
+ yield* TestClock.adjust("1 second");
197
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "1m" });
198
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\r100%\u001b[0m\ndone\n" });
199
+ const append = yield* takeFrame(frames);
200
+ assert.equal(append.kind, "append");
201
+ client = applyFrame(client, append);
202
+ assert.equal(
203
+ client.text,
204
+ normalizeTerminalOutput(
205
+ "\u001b[32mbuilding\u001b[0m\n10%\r55%\u001b[31m\r100%\u001b[0m\ndone\n",
206
+ ).text,
207
+ );
208
210
- yield* TestClock.adjust("1 second");
211
- yield* writeCommandItem(threadId, {
212
- status: "completed",
213
- exitCode: 0,
214
- output: "building\n100%\ndone\n",
215
- });
216
- const final = yield* takeFrame(frames);
217
- assert.deepEqual(final, {
218
- kind: "replace",
219
- text: "building\n100%\ndone\n",
220
- truncated: false,
221
- running: false,
222
- });
223
- assert.equal(yield* Queue.take(frames), "ended");
224
- }),
225
- ),
209
+ yield* TestClock.adjust("1 second");
210
+ yield* writeCommandItem(threadId, {
211
+ status: "completed",
212
+ exitCode: 0,
213
+ output: "building\n100%\ndone\n",
214
+ });
215
+ const final = yield* takeFrame(frames);
216
+ assert.deepEqual(final, {
217
+ kind: "replace",
218
+ text: "building\n100%\ndone\n",
219
+ truncated: false,
220
+ running: false,
221
+ });
222
+ assert.equal(yield* Queue.take(frames), "ended");
223
+ }),
224
);
225
226
it.effect("a row that is not a known command fails instead of waiting forever", () =>
@@ -238,128 +236,116 @@ layer("CommandOutputHub", (it) => {
236
);
237
238
it.effect("a viewer whose command was evicted for newer ones is resynced, not appended to", () =>
241
- Effect.scoped(
242
- Effect.gen(function* () {
243
- const hub = yield* CommandOutputHub.CommandOutputHub;
244
- const threadId = yield* seedThread;
245
- yield* writeCommandItem(threadId, { status: "running" });
246
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
247
- const frames = yield* subscribeFrames(threadId);
248
- let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
249
- assert.equal(client.text, "abc");
250
- for (let index = 0; index < 64; index += 1) {
251
- yield* hub.append({
252
- threadId,
253
- itemId: TurnItemId.make(`turn-item:other-${index}`),
254
- chunk: "x",
255
- });
256
- }
257
- yield* TestClock.adjust("1 second");
258
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
259
- const next = yield* takeFrame(frames);
260
- assert.equal(next.kind, "replace");
261
- client = applyFrame(client, next);
262
- assert.equal(client.text, "X");
263
- }),
264
- ),
239
+ Effect.gen(function* () {
240
+ const hub = yield* CommandOutputHub.CommandOutputHub;
241
+ const threadId = yield* seedThread;
242
+ yield* writeCommandItem(threadId, { status: "running" });
243
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "abc" });
244
+ const frames = yield* subscribeFrames(threadId);
245
+ let client = applyFrame(EMPTY_TERMINAL_OUTPUT, yield* takeFrame(frames));
246
+ assert.equal(client.text, "abc");
247
+ for (let index = 0; index < 64; index += 1) {
248
+ yield* hub.append({
249
+ threadId,
250
+ itemId: TurnItemId.make(`turn-item:other-${index}`),
251
+ chunk: "x",
252
+ });
253
+ }
254
+ yield* TestClock.adjust("1 second");
255
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "\rX" });
256
+ const next = yield* takeFrame(frames);
257
+ assert.equal(next.kind, "replace");
258
+ client = applyFrame(client, next);
259
+ assert.equal(client.text, "X");
260
+ }),
261
);
262
263
it.effect("a finished command sends only its bounded final output", () =>
268
- Effect.scoped(
269
- Effect.gen(function* () {
270
- const threadId = yield* seedThread;
271
- const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");
272
- yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });
273
- const frames = yield* subscribeFrames(threadId);
274
- const final = yield* takeFrame(frames);
275
- assert.equal(final.kind, "replace");
276
- assert.isFalse(final.running);
277
- assert.isTrue(final.truncated);
278
- assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
279
- assert.isTrue(final.text.endsWith("line 399999"));
280
- assert.equal(yield* Queue.take(frames), "ended");
281
- }),
282
- ),
264
+ Effect.gen(function* () {
265
+ const threadId = yield* seedThread;
266
+ const huge = Array.from({ length: 400_000 }, (_, index) => `line ${index}`).join("\n");
267
+ yield* writeCommandItem(threadId, { status: "failed", exitCode: 1, output: huge });
268
+ const frames = yield* subscribeFrames(threadId);
269
+ const final = yield* takeFrame(frames);
270
+ assert.equal(final.kind, "replace");
271
+ assert.isFalse(final.running);
272
+ assert.isTrue(final.truncated);
273
+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
274
+ assert.isTrue(final.text.endsWith("line 399999"));
275
+ assert.equal(yield* Queue.take(frames), "ended");
276
+ }),
277
);
278
279
it.effect("a finished command whose output is one huge line still shows its tail", () =>
286
- Effect.scoped(
287
- Effect.gen(function* () {
288
- const threadId = yield* seedThread;
289
- const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);
290
- yield* writeCommandItem(threadId, {
291
- status: "completed",
292
- exitCode: 0,
293
- output: `${line}\n`,
294
- });
295
- const frames = yield* subscribeFrames(threadId);
296
- const final = yield* takeFrame(frames);
297
- assert.equal(final.kind, "replace");
298
- assert.isTrue(final.truncated);
299
- assert.isTrue(final.text.includes("xxxx"));
300
- assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
301
- }),
302
- ),
280
+ Effect.gen(function* () {
281
+ const threadId = yield* seedThread;
282
+ const line = "x".repeat(TERMINAL_OUTPUT_TAIL_CHARS * 8);
283
+ yield* writeCommandItem(threadId, {
284
+ status: "completed",
285
+ exitCode: 0,
286
+ output: `${line}\n`,
287
+ });
288
+ const frames = yield* subscribeFrames(threadId);
289
+ const final = yield* takeFrame(frames);
290
+ assert.equal(final.kind, "replace");
291
+ assert.isTrue(final.truncated);
292
+ assert.isTrue(final.text.includes("xxxx"));
293
+ assert.isAtMost(final.text.length, TERMINAL_OUTPUT_TAIL_CHARS);
294
+ }),
295
);
296
297
it.effect("an old Claude row's raw Bash result shows as its stdout and stderr", () =>
306
- Effect.scoped(
307
- Effect.gen(function* () {
308
- const threadId = yield* seedThread;
309
- yield* writeCommandItem(threadId, {
310
- status: "completed",
311
- exitCode: 0,
312
- output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
313
- });
314
- const frames = yield* subscribeFrames(threadId);
315
- const final = yield* takeFrame(frames);
316
- assert.equal(final.text, "built\n1 warning");
317
- }),
318
- ),
298
+ Effect.gen(function* () {
299
+ const threadId = yield* seedThread;
300
+ yield* writeCommandItem(threadId, {
301
+ status: "completed",
302
+ exitCode: 0,
303
+ output: '{"stdout":"built","stderr":"1 warning","interrupted":false}',
304
+ });
305
+ const frames = yield* subscribeFrames(threadId);
306
+ const final = yield* takeFrame(frames);
307
+ assert.equal(final.text, "built\n1 warning");
308
+ }),
309
);
310
311
it.effect("providers that only report output in item snapshots still stream", () =>
322
- Effect.scoped(
323
- Effect.gen(function* () {
324
- const threadId = yield* seedThread;
325
- yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
326
- const frames = yield* subscribeFrames(threadId);
327
- assert.equal((yield* takeFrame(frames)).text, "step 1\n");
328
- yield* TestClock.adjust("1 second");
329
- yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
330
- const update = yield* takeFrame(frames);
331
- assert.deepEqual(update, {
332
- kind: "replace",
333
- text: "step 1\nstep 2\n",
334
- truncated: false,
335
- running: true,
336
- });
337
- }),
338
- ),
312
+ Effect.gen(function* () {
313
+ const threadId = yield* seedThread;
314
+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\n" });
315
+ const frames = yield* subscribeFrames(threadId);
316
+ assert.equal((yield* takeFrame(frames)).text, "step 1\n");
317
+ yield* TestClock.adjust("1 second");
318
+ yield* writeCommandItem(threadId, { status: "running", output: "step 1\nstep 2\n" });
319
+ const update = yield* takeFrame(frames);
320
+ assert.deepEqual(update, {
321
+ kind: "replace",
322
+ text: "step 1\nstep 2\n",
323
+ truncated: false,
324
+ running: true,
325
+ });
326
+ }),
327
);
328
329
it.effect("an interrupted command ends the stream with the output it printed", () =>
342
- Effect.scoped(
343
- Effect.gen(function* () {
344
- const hub = yield* CommandOutputHub.CommandOutputHub;
345
- const threadId = yield* seedThread;
346
- yield* writeCommandItem(threadId, { status: "running" });
347
- yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
348
- const frames = yield* subscribeFrames(threadId);
349
- yield* takeFrame(frames);
350
- yield* TestClock.adjust("1 second");
351
- // Some providers omit stopped-command output; the live tail is released before the settled item persists.
352
- yield* hub.finish({ threadId, itemId: ITEM_ID });
353
- yield* writeCommandItem(threadId, { status: "interrupted" });
354
- const final = yield* takeFrame(frames);
355
- assert.deepEqual(final, {
356
- kind: "replace",
357
- text: "waiting for server\n",
358
- truncated: false,
359
- running: false,
360
- });
361
- assert.equal(yield* Queue.take(frames), "ended");
362
- }),
363
- ),
330
+ Effect.gen(function* () {
331
+ const hub = yield* CommandOutputHub.CommandOutputHub;
332
+ const threadId = yield* seedThread;
333
+ yield* writeCommandItem(threadId, { status: "running" });
334
+ yield* hub.append({ threadId, itemId: ITEM_ID, chunk: "waiting for server\n" });
335
+ const frames = yield* subscribeFrames(threadId);
336
+ yield* takeFrame(frames);
337
+ yield* TestClock.adjust("1 second");
338
+ // Some providers omit stopped-command output; the live tail is released before the settled item persists.
339
+ yield* hub.finish({ threadId, itemId: ITEM_ID });
340
+ yield* writeCommandItem(threadId, { status: "interrupted" });
341
+ const final = yield* takeFrame(frames);
342
+ assert.deepEqual(final, {
343
+ kind: "replace",
344
+ text: "waiting for server\n",
345
+ truncated: false,
346
+ running: false,
347
+ });
348
+ assert.equal(yield* Queue.take(frames), "ended");
349
+ }),
350
);
351
});
apps/server/src/orchestration-v2/FoundationPersistence.test.ts
+268
-280
@@ -416,7 +416,7 @@ it.effect(
416
yield* store.read({ afterSequence: highWater }).pipe(Stream.runCollect),
417
published,
418
);
419
- }).pipe(Effect.provide(Layer.fresh(layerTest)), Effect.scoped),
419
+ }).pipe(Effect.provide(Layer.fresh(layerTest))),
420
);
421
422
it.effect.each(
@@ -718,313 +718,301 @@ it.effect.each([false, true])("groups shutdown commits with rollback=%s", (fail)
718
719
it.layer(layerTest)("orchestration V2 foundation persistence", (it) => {
720
it.effect("projects oversized tool bodies once before replay and live RPC retention", () =>
721
- Effect.scoped(
721
+ Effect.gen(function* () {
722
+ const sink = yield* EventSink.EventSinkV2;
723
+ const store = yield* EventStore.EventStoreV2;
724
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
725
+ const now = yield* DateTime.now;
726
+ const thread = makeThread(ThreadId.make("thread:large-stream-body"), now);
727
+ const output = {
728
+ content: [{ type: "text", text: "first line\n" + "x".repeat(9 * 1024 * 1024) }],
729
+ };
730
+ const tool: OrchestrationV2TurnItem = {
731
+ id: TurnItemId.make("tool:large-stream-body"),
732
+ type: "dynamic_tool",
733
+ threadId: thread.id,
734
+ runId: null,
735
+ nodeId: null,
736
+ providerThreadId: null,
737
+ providerTurnId: null,
738
+ nativeItemRef: null,
739
+ parentItemId: null,
740
+ ordinal: 1,
741
+ status: "running",
742
+ title: "Large tool",
743
+ toolName: "mcp__large_tool",
744
+ input: { query: "details" },
745
+ output,
746
+ startedAt: now,
747
+ completedAt: null,
748
+ updatedAt: now,
749
+ };
750
+ const [created] = yield* sink.write({
751
+ events: [
752
+ threadCreatedEvent({ id: "event:large-stream-body:created", thread, now }),
753
+ {
754
+ id: EventId.make("event:large-stream-body:replay"),
755
+ type: "turn-item.updated",
756
+ threadId: thread.id,
757
+ occurredAt: now,
758
+ payload: tool,
759
+ },
760
+ ],
761
+ });
762
+ const subscribe = () =>
763
+ Stream.toPull(
764
+ sink.stream({
765
+ threadId: thread.id,
766
+ afterSequence: created!.sequence,
767
+ bounded: true,
768
+ }),
769
+ );
770
+ const pull = yield* subscribe();
771
+ const other = yield* subscribe();
772
+ const replay = yield* pull;
773
+ assert.lengthOf(replay, 1);
774
+ assert.lengthOf(yield* other, 1);
775
+ assert.equal(replay[0]!.event.type, "turn-item.updated");
776
+ assert.isBelow(Buffer.byteLength(yield* encodeJson(replay)), 4_000);
777
+ const stringify = yield* Effect.acquireRelease(
778
+ Effect.sync(() => vi.spyOn(JSON, "stringify")),
779
+ (spy) => Effect.sync(() => spy.mockRestore()),
780
+ );
781
+ const [completed] = yield* sink.write({
782
+ events: [
783
+ {
784
+ id: EventId.make("event:large-stream-body:live"),
785
+ type: "turn-item.updated",
786
+ threadId: thread.id,
787
+ occurredAt: now,
788
+ payload: { ...tool, status: "completed", completedAt: now },
789
+ },
790
+ ],
791
+ });
792
+ const live = yield* pull;
793
+ const otherLive = yield* other;
794
+ assert.deepEqual(
795
+ live.map((stored) => stored.sequence),
796
+ [completed!.sequence],
797
+ );
798
+ // Both subscribers get one shared projection, so the live budget sizes it once.
799
+ assert.strictEqual(otherLive[0], live[0]);
800
+ assert.lengthOf(
801
+ stringify.mock.calls.filter(([value]) => value === live[0] || value === otherLive[0]),
802
+ 1,
803
+ );
804
+ assert.isBelow(Buffer.byteLength(yield* encodeJson(live)), 4_000);
805
+ for (const stored of [...replay, ...live]) {
806
+ assert.equal(stored.event.type, "turn-item.updated");
807
+ if (stored.event.type !== "turn-item.updated") return;
808
+ assert.equal(stored.event.payload.type, "dynamic_tool");
809
+ if (stored.event.payload.type !== "dynamic_tool") return;
810
+ assert.notProperty(stored.event.payload, "output");
811
+ }
812
+ const persisted = yield* store.read({ threadId: thread.id }).pipe(Stream.runCollect);
813
+ const fullEvent = persisted.find((stored) => stored.sequence === completed!.sequence)!.event;
814
+ assert.equal(fullEvent.type, "turn-item.updated");
815
+ if (fullEvent.type !== "turn-item.updated") return;
816
+ assert.equal(fullEvent.payload.type, "dynamic_tool");
817
+ if (fullEvent.payload.type !== "dynamic_tool") return;
818
+ assert.deepEqual(fullEvent.payload.output, output);
819
+ const detail = (yield* projections.getThreadProjection(thread.id)).turnItems.find(
820
+ (item) => item.id === tool.id,
821
+ )!;
822
+ assert.equal(detail.type, "dynamic_tool");
823
+ if (detail.type === "dynamic_tool") assert.deepEqual(detail.output, output);
824
+ }),
825
+ );
826
+
827
+ it.effect.each(["high-water", "replay"] as const)(
828
+ "bounds live events while the V2 %s query is blocked",
829
+ (phase) =>
830
Effect.gen(function* () {
831
const sink = yield* EventSink.EventSinkV2;
724
- const store = yield* EventStore.EventStoreV2;
725
- const projections = yield* ProjectionStore.ProjectionStoreV2;
832
const now = yield* DateTime.now;
727
- const thread = makeThread(ThreadId.make("thread:large-stream-body"), now);
728
- const output = {
729
- content: [{ type: "text", text: "first line\n" + "x".repeat(9 * 1024 * 1024) }],
730
- };
731
- const tool: OrchestrationV2TurnItem = {
732
- id: TurnItemId.make("tool:large-stream-body"),
733
- type: "dynamic_tool",
734
- threadId: thread.id,
735
- runId: null,
736
- nodeId: null,
737
- providerThreadId: null,
738
- providerTurnId: null,
739
- nativeItemRef: null,
740
- parentItemId: null,
741
- ordinal: 1,
742
- status: "running",
743
- title: "Large tool",
744
- toolName: "mcp__large_tool",
745
- input: { query: "details" },
746
- output,
747
- startedAt: now,
748
- completedAt: null,
749
- updatedAt: now,
750
- };
833
+ const thread = makeThread(ThreadId.make(`thread:blocked-${phase}`), now);
834
const [created] = yield* sink.write({
752
- events: [
753
- threadCreatedEvent({ id: "event:large-stream-body:created", thread, now }),
754
- {
755
- id: EventId.make("event:large-stream-body:replay"),
756
- type: "turn-item.updated",
757
- threadId: thread.id,
758
- occurredAt: now,
759
- payload: tool,
760
- },
761
- ],
835
+ events: [threadCreatedEvent({ id: `event:blocked-${phase}:created`, thread, now })],
836
});
763
- const subscribe = () =>
764
- Stream.toPull(
765
- sink.stream({
766
- threadId: thread.id,
767
- afterSequence: created!.sequence,
768
- bounded: true,
769
- }),
837
+ const readStarted = yield* Deferred.make<void>();
838
+ const readClosed = yield* Deferred.make<void>();
839
+ const blockRead: Statement.Transformer = (statement) => {
840
+ const [query] = statement.compile();
841
+ if (
842
+ query.includes("FROM orchestration_events") &&
843
+ query.includes("MAX(sequence)") === (phase === "high-water")
844
+ ) {
845
+ return Deferred.succeed(readStarted, undefined).pipe(
846
+ Effect.andThen(Effect.never),
847
+ Effect.ensuring(Deferred.succeed(readClosed, undefined)),
848
+ Effect.as(statement),
849
+ );
850
+ }
851
+ return Effect.succeed(statement);
852
+ };
853
+ const reader = yield* sink
854
+ .stream({ threadId: thread.id, afterSequence: created!.sequence, bounded: true })
855
+ .pipe(
856
+ Stream.provideService(Statement.CurrentTransformer, blockRead),
857
+ Stream.runDrain,
858
+ Effect.result,
859
+ Effect.forkScoped,
860
);
771
- const pull = yield* subscribe();
772
- const other = yield* subscribe();
773
- const replay = yield* pull;
774
- assert.lengthOf(replay, 1);
775
- assert.lengthOf(yield* other, 1);
776
- assert.equal(replay[0]!.event.type, "turn-item.updated");
777
- assert.isBelow(Buffer.byteLength(yield* encodeJson(replay)), 4_000);
778
- const stringify = yield* Effect.acquireRelease(
779
- Effect.sync(() => vi.spyOn(JSON, "stringify")),
780
- (spy) => Effect.sync(() => spy.mockRestore()),
781
- );
782
- const [completed] = yield* sink.write({
783
- events: [
784
- {
785
- id: EventId.make("event:large-stream-body:live"),
786
- type: "turn-item.updated",
787
- threadId: thread.id,
788
- occurredAt: now,
789
- payload: { ...tool, status: "completed", completedAt: now },
790
- },
791
- ],
861
+ yield* Deferred.await(readStarted);
862
+ yield* sink.write({
863
+ events: Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
864
+ id: EventId.make(`event:blocked-${phase}:${index}`),
865
+ type: "thread.metadata-updated" as const,
866
+ threadId: thread.id,
867
+ occurredAt: now,
868
+ payload: { ...thread, title: `Updated ${index}` },
869
+ })),
870
});
793
- const live = yield* pull;
794
- const otherLive = yield* other;
795
- assert.deepEqual(
796
- live.map((stored) => stored.sequence),
797
- [completed!.sequence],
798
- );
799
- // Both subscribers get one shared projection, so the live budget sizes it once.
800
- assert.strictEqual(otherLive[0], live[0]);
801
- assert.lengthOf(
802
- stringify.mock.calls.filter(([value]) => value === live[0] || value === otherLive[0]),
803
- 1,
804
- );
805
- assert.isBelow(Buffer.byteLength(yield* encodeJson(live)), 4_000);
806
- for (const stored of [...replay, ...live]) {
807
- assert.equal(stored.event.type, "turn-item.updated");
808
- if (stored.event.type !== "turn-item.updated") return;
809
- assert.equal(stored.event.payload.type, "dynamic_tool");
810
- if (stored.event.payload.type !== "dynamic_tool") return;
811
- assert.notProperty(stored.event.payload, "output");
871
+ yield* Deferred.await(readClosed);
872
+ const result = yield* Fiber.join(reader);
873
+ assert.equal(result._tag, "Failure");
874
+ if (result._tag === "Failure") {
875
+ assert.equal(result.failure._tag, "EventSinkStreamError");
876
+ assert.isTrue(isLiveStreamBufferError(result.failure.cause));
877
}
813
- const persisted = yield* store.read({ threadId: thread.id }).pipe(Stream.runCollect);
814
- const fullEvent = persisted.find(
815
- (stored) => stored.sequence === completed!.sequence,
816
- )!.event;
817
- assert.equal(fullEvent.type, "turn-item.updated");
818
- if (fullEvent.type !== "turn-item.updated") return;
819
- assert.equal(fullEvent.payload.type, "dynamic_tool");
820
- if (fullEvent.payload.type !== "dynamic_tool") return;
821
- assert.deepEqual(fullEvent.payload.output, output);
822
- const detail = (yield* projections.getThreadProjection(thread.id)).turnItems.find(
823
- (item) => item.id === tool.id,
824
- )!;
825
- assert.equal(detail.type, "dynamic_tool");
826
- if (detail.type === "dynamic_tool") assert.deepEqual(detail.output, output);
878
}),
828
- ),
829
- );
830
-
831
- it.effect.each(["high-water", "replay"] as const)(
832
- "bounds live events while the V2 %s query is blocked",
833
- (phase) =>
834
- Effect.scoped(
835
- Effect.gen(function* () {
836
- const sink = yield* EventSink.EventSinkV2;
837
- const now = yield* DateTime.now;
838
- const thread = makeThread(ThreadId.make(`thread:blocked-${phase}`), now);
839
- const [created] = yield* sink.write({
840
- events: [threadCreatedEvent({ id: `event:blocked-${phase}:created`, thread, now })],
841
- });
842
- const readStarted = yield* Deferred.make<void>();
843
- const readClosed = yield* Deferred.make<void>();
844
- const blockRead: Statement.Transformer = (statement) => {
845
- const [query] = statement.compile();
846
- if (
847
- query.includes("FROM orchestration_events") &&
848
- query.includes("MAX(sequence)") === (phase === "high-water")
849
- ) {
850
- return Deferred.succeed(readStarted, undefined).pipe(
851
- Effect.andThen(Effect.never),
852
- Effect.ensuring(Deferred.succeed(readClosed, undefined)),
853
- Effect.as(statement),
854
- );
855
- }
856
- return Effect.succeed(statement);
857
- };
858
- const reader = yield* sink
859
- .stream({ threadId: thread.id, afterSequence: created!.sequence, bounded: true })
860
- .pipe(
861
- Stream.provideService(Statement.CurrentTransformer, blockRead),
862
- Stream.runDrain,
863
- Effect.result,
864
- Effect.forkScoped,
865
- );
866
- yield* Deferred.await(readStarted);
867
- yield* sink.write({
868
- events: Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
869
- id: EventId.make(`event:blocked-${phase}:${index}`),
870
- type: "thread.metadata-updated" as const,
871
- threadId: thread.id,
872
- occurredAt: now,
873
- payload: { ...thread, title: `Updated ${index}` },
874
- })),
875
- });
876
- yield* Deferred.await(readClosed);
877
- const result = yield* Fiber.join(reader);
878
- assert.equal(result._tag, "Failure");
879
- if (result._tag === "Failure") {
880
- assert.equal(result.failure._tag, "EventSinkStreamError");
881
- assert.isTrue(isLiveStreamBufferError(result.failure.cause));
882
- }
883
- }),
884
- ),
879
);
880
881
it.effect(
882
"keeps internal streams subscribed while replay is blocked beyond the RPC buffer cap",
883
() =>
890
- Effect.scoped(
891
- Effect.gen(function* () {
892
- const sink = yield* EventSink.EventSinkV2;
893
- const now = yield* DateTime.now;
894
- const thread = makeThread(ThreadId.make("thread:internal-stream-burst"), now);
895
- const [created] = yield* sink.write({
896
- events: [
897
- threadCreatedEvent({ id: "event:internal-stream-burst:created", thread, now }),
898
- ],
899
- });
900
- const readStarted = yield* Deferred.make<void>();
901
- const releaseRead = yield* Deferred.make<void>();
902
- const blockHighWater: Statement.Transformer = (statement) => {
903
- const [query] = statement.compile();
904
- return query.includes("MAX(sequence)") && query.includes("FROM orchestration_events")
905
- ? Deferred.succeed(readStarted, undefined).pipe(
906
- Effect.andThen(Deferred.await(releaseRead)),
907
- Effect.as(statement),
908
- )
909
- : Effect.succeed(statement);
910
- };
911
- const eventCount = LIVE_STREAM_MAX_ITEMS + 1;
912
- const reader = yield* sink
913
- .stream({ threadId: thread.id, afterSequence: created!.sequence })
914
- .pipe(
915
- Stream.provideService(Statement.CurrentTransformer, blockHighWater),
916
- Stream.take(eventCount),
917
- Stream.runCollect,
918
- Effect.forkScoped,
919
- );
920
- yield* Deferred.await(readStarted);
921
- const written = yield* sink.write({
922
- events: Array.from({ length: eventCount }, (_, index) => ({
923
- id: EventId.make(`event:internal-stream-burst:${index}`),
924
- type: "thread.metadata-updated" as const,
925
- threadId: thread.id,
926
- occurredAt: now,
927
- payload: { ...thread, title: `Updated ${index}` },
928
- })),
929
- });
930
- yield* Deferred.succeed(releaseRead, undefined);
931
- assert.deepEqual(
932
- (yield* Fiber.join(reader)).map((event) => event.sequence),
933
- written.map((event) => event.sequence),
934
- );
935
- }),
936
- ),
937
- );
938
-
939
- it.effect("filters worker replay and live queues without losing matching events", () =>
940
- Effect.scoped(
884
Effect.gen(function* () {
885
const sink = yield* EventSink.EventSinkV2;
943
- const sql = yield* SqlClient.SqlClient;
886
const now = yield* DateTime.now;
945
- const thread = makeThread(ThreadId.make("thread:filtered-worker"), now);
946
- const other = makeThread(ThreadId.make("thread:filtered-worker-other"), now);
947
- const run: OrchestrationV2Run = {
948
- id: RunId.make("run:filtered-worker"),
949
- threadId: thread.id,
950
- ordinal: 1,
951
- providerInstanceId,
952
- modelSelection,
953
- providerThreadId: null,
954
- userMessageId: MessageId.make("message:filtered-worker"),
955
- rootNodeId: null,
956
- activeAttemptId: null,
957
- status: "completed",
958
- queuePosition: null,
959
- requestedAt: now,
960
- startedAt: now,
961
- completedAt: now,
962
- checkpointId: null,
963
- contextHandoffId: null,
964
- };
965
- const runEvent = (id: string, payload: OrchestrationV2Run): OrchestrationV2DomainEvent => ({
966
- id: EventId.make(id),
967
- type: "run.updated",
968
- threadId: payload.threadId,
969
- runId: payload.id,
970
- occurredAt: now,
971
- payload,
887
+ const thread = makeThread(ThreadId.make("thread:internal-stream-burst"), now);
888
+ const [created] = yield* sink.write({
889
+ events: [threadCreatedEvent({ id: "event:internal-stream-burst:created", thread, now })],
890
});
973
- const history = yield* sink.write({
974
- events: [
975
- threadCreatedEvent({ id: "event:filtered-worker:created", thread, now }),
976
- threadCreatedEvent({ id: "event:filtered-worker:other", thread: other, now }),
977
- runEvent("event:filtered-worker:history", run),
978
- runEvent("event:filtered-worker:other-history", {
979
- ...run,
980
- id: RunId.make("run:filtered-worker-other"),
981
- threadId: other.id,
982
- }),
983
- ],
891
+ const readStarted = yield* Deferred.make<void>();
892
+ const releaseRead = yield* Deferred.make<void>();
893
+ const blockHighWater: Statement.Transformer = (statement) => {
894
+ const [query] = statement.compile();
895
+ return query.includes("MAX(sequence)") && query.includes("FROM orchestration_events")
896
+ ? Deferred.succeed(readStarted, undefined).pipe(
897
+ Effect.andThen(Deferred.await(releaseRead)),
898
+ Effect.as(statement),
899
+ )
900
+ : Effect.succeed(statement);
901
+ };
902
+ const eventCount = LIVE_STREAM_MAX_ITEMS + 1;
903
+ const reader = yield* sink
904
+ .stream({ threadId: thread.id, afterSequence: created!.sequence })
905
+ .pipe(
906
+ Stream.provideService(Statement.CurrentTransformer, blockHighWater),
907
+ Stream.take(eventCount),
908
+ Stream.runCollect,
909
+ Effect.forkScoped,
910
+ );
911
+ yield* Deferred.await(readStarted);
912
+ const written = yield* sink.write({
913
+ events: Array.from({ length: eventCount }, (_, index) => ({
914
+ id: EventId.make(`event:internal-stream-burst:${index}`),
915
+ type: "thread.metadata-updated" as const,
916
+ threadId: thread.id,
917
+ occurredAt: now,
918
+ payload: { ...thread, title: `Updated ${index}` },
919
+ })),
920
});
985
- const original = yield* sql<{ readonly payload_json: string }>`
921
+ yield* Deferred.succeed(releaseRead, undefined);
922
+ assert.deepEqual(
923
+ (yield* Fiber.join(reader)).map((event) => event.sequence),
924
+ written.map((event) => event.sequence),
925
+ );
926
+ }),
927
+ );
928
+
929
+ it.effect("filters worker replay and live queues without losing matching events", () =>
930
+ Effect.gen(function* () {
931
+ const sink = yield* EventSink.EventSinkV2;
932
+ const sql = yield* SqlClient.SqlClient;
933
+ const now = yield* DateTime.now;
934
+ const thread = makeThread(ThreadId.make("thread:filtered-worker"), now);
935
+ const other = makeThread(ThreadId.make("thread:filtered-worker-other"), now);
936
+ const run: OrchestrationV2Run = {
937
+ id: RunId.make("run:filtered-worker"),
938
+ threadId: thread.id,
939
+ ordinal: 1,
940
+ providerInstanceId,
941
+ modelSelection,
942
+ providerThreadId: null,
943
+ userMessageId: MessageId.make("message:filtered-worker"),
944
+ rootNodeId: null,
945
+ activeAttemptId: null,
946
+ status: "completed",
947
+ queuePosition: null,
948
+ requestedAt: now,
949
+ startedAt: now,
950
+ completedAt: now,
951
+ checkpointId: null,
952
+ contextHandoffId: null,
953
+ };
954
+ const runEvent = (id: string, payload: OrchestrationV2Run): OrchestrationV2DomainEvent => ({
955
+ id: EventId.make(id),
956
+ type: "run.updated",
957
+ threadId: payload.threadId,
958
+ runId: payload.id,
959
+ occurredAt: now,
960
+ payload,
961
+ });
962
+ const history = yield* sink.write({
963
+ events: [
964
+ threadCreatedEvent({ id: "event:filtered-worker:created", thread, now }),
965
+ threadCreatedEvent({ id: "event:filtered-worker:other", thread: other, now }),
966
+ runEvent("event:filtered-worker:history", run),
967
+ runEvent("event:filtered-worker:other-history", {
968
+ ...run,
969
+ id: RunId.make("run:filtered-worker-other"),
970
+ threadId: other.id,
971
+ }),
972
+ ],
973
+ });
974
+ const original = yield* sql<{ readonly payload_json: string }>`
975
SELECT payload_json FROM orchestration_events
976
WHERE sequence = ${history[0]!.sequence}
977
`;
989
- yield* Effect.acquireRelease(
990
- sql`
978
+ yield* Effect.acquireRelease(
979
+ sql`
980
UPDATE orchestration_events SET payload_json = 'unreadable unrelated payload'
981
WHERE sequence = ${history[0]!.sequence}
982
`,
994
- () =>
995
- sql`
983
+ () =>
984
+ sql`
985
UPDATE orchestration_events SET payload_json = ${original[0]!.payload_json}
986
WHERE sequence = ${history[0]!.sequence}
987
`.pipe(Effect.orDie),
999
- );
1000
- const pull = yield* Stream.toPull(
1001
- sink.stream({ threadId: thread.id, eventType: "run.updated" }),
1002
- );
1003
- assert.deepEqual(
1004
- (yield* pull).map((stored) => stored.sequence),
1005
- [history[2]!.sequence],
1006
- );
1007
- yield* sink.write({
1008
- events: Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
1009
- id: EventId.make(`event:filtered-worker:output:${index}`),
1010
- type: "thread.metadata-updated" as const,
1011
- threadId: thread.id,
1012
- occurredAt: now,
1013
- payload: { ...thread, title: `Output ${index}` },
1014
- })),
1015
- });
1016
- const live = yield* sink.write({
1017
- events: [
1018
- runEvent("event:filtered-worker:live:1", { ...run, status: "interrupted" }),
1019
- runEvent("event:filtered-worker:live:2", { ...run, status: "failed" }),
1020
- ],
1021
- });
1022
- assert.deepEqual(
1023
- (yield* pull).map((stored) => stored.sequence),
1024
- live.map((stored) => stored.sequence),
1025
- );
1026
- }),
1027
- ),
988
+ );
989
+ const pull = yield* Stream.toPull(
990
+ sink.stream({ threadId: thread.id, eventType: "run.updated" }),
991
+ );
992
+ assert.deepEqual(
993
+ (yield* pull).map((stored) => stored.sequence),
994
+ [history[2]!.sequence],
995
+ );
996
+ yield* sink.write({
997
+ events: Array.from({ length: LIVE_STREAM_MAX_ITEMS + 1 }, (_, index) => ({
998
+ id: EventId.make(`event:filtered-worker:output:${index}`),
999
+ type: "thread.metadata-updated" as const,
1000
+ threadId: thread.id,
1001
+ occurredAt: now,
1002
+ payload: { ...thread, title: `Output ${index}` },
1003
+ })),
1004
+ });
1005
+ const live = yield* sink.write({
1006
+ events: [
1007
+ runEvent("event:filtered-worker:live:1", { ...run, status: "interrupted" }),
1008
+ runEvent("event:filtered-worker:live:2", { ...run, status: "failed" }),
1009
+ ],
1010
+ });
1011
+ assert.deepEqual(
1012
+ (yield* pull).map((stored) => stored.sequence),
1013
+ live.map((stored) => stored.sequence),
1014
+ );
1015
+ }),
1016
);
1017
1018
it.effect("paginates catch-up beyond the event-store read limit", () =>
apps/server/src/orchestration-v2/IdleCompaction.test.ts
+164
-168
@@ -214,147 +214,30 @@ describe("IdleCompactionService", () => {
214
projectDisabled: false,
215
...scenario,
216
} as const;
217
- return Effect.scoped(
218
- Effect.gen(function* () {
219
- yield* TestClock.setTime(NOW_MS);
220
- const selectedInstance = ProviderInstanceId.make(
221
- "instance" in test ? test.instance : "claudeAgent",
222
- );
223
- const driver = ProviderDriverKind.make("driver" in test ? test.driver : "claudeAgent");
224
- const base = records({ cacheExpiresInMs: 2 * MINUTE_MS });
225
- const data: OrchestrationV2ThreadProjection = {
226
- ...base,
227
- thread: {
228
- ...base.thread,
229
- providerInstanceId: selectedInstance,
230
- modelSelection: { ...base.thread.modelSelection, instanceId: selectedInstance },
231
- },
232
- runs: base.runs.map((run) => ({
233
- ...run,
234
- providerInstanceId: selectedInstance,
235
- modelSelection: { ...run.modelSelection, instanceId: selectedInstance },
236
- })),
237
- providerThreads: base.providerThreads.map((thread) => ({
238
- ...thread,
239
- driver,
240
- providerInstanceId: selectedInstance,
241
- })),
242
- attempts: [],
243
- nodes: [],
244
- subagents: [],
245
- providerSessions: [],
246
- plans: [],
247
- checkpointScopes: [],
248
- checkpoints: [],
249
- contextHandoffs: [],
250
- visibleTurnItems: [],
251
- updatedAt: at(),
252
- };
253
- let historyReads = 0;
254
- let dispatches = 0;
255
- const done = yield* Deferred.make<void>();
256
- const tracer = Tracer.make({
257
- span(options) {
258
- const span = new Tracer.NativeSpan(options);
259
- const end = span.end.bind(span);
260
- span.end = (...args) => {
261
- end(...args);
262
- if (span.name === "IdleCompactionService.compactWhenDue")
263
- Deferred.doneUnsafe(done, Effect.void);
264
- };
265
- return span;
266
- },
267
- });
268
- const dependencies = Layer.mergeAll(
269
- Layer.mock(Orchestrator.OrchestratorV2)({
270
- streamDomainEvents: Stream.make({
271
- id: EventId.make("idle-completed"),
272
- type: "run.updated",
273
- threadId,
274
- runId,
275
- occurredAt: at(),
276
- payload: data.runs[0]!,
277
- }),
278
- dispatch: () =>
279
- Effect.sync(() => {
280
- dispatches++;
281
- return { sequence: 1, storedEvents: [] };
282
- }),
283
- }),
284
- Layer.mock(ProjectionStore.ProjectionStoreV2)({
285
- getThread: () => Effect.succeed(data.thread),
286
- getThreadRecords: () =>
287
- Effect.sync(() => {
288
- historyReads++;
289
- return data;
290
- }),
291
- }),
292
- Layer.mock(ServerSettings.ServerSettingsService)({
293
- getSettings: Effect.succeed({
294
- ...DEFAULT_SERVER_SETTINGS,
295
- idleCompaction: test.mode,
296
- providerInstances:
297
- "unconfigured" in test
298
- ? {}
299
- : {
300
- [selectedInstance]: {
301
- driver,
302
- enabled: test.enabled,
303
- config: { idleCompaction: test.override },
304
- },
305
- },
306
- projectSettingsOverrides: test.projectDisabled
307
- ? {
308
- [data.thread.projectId]: {
309
- providerInstances: { [selectedInstance]: { enabled: false } },
310
- },
311
- }
312
- : {},
313
- }),
314
- }),
315
- );
316
- yield* Effect.gen(function* () {
317
- const service = yield* IdleCompactionService.make;
318
- yield* service.start();
319
- yield* Deferred.await(done);
320
- }).pipe(Effect.provide(dependencies), Effect.withTracer(tracer));
321
- expect(historyReads).toBe(test.reads);
322
- expect(dispatches).toBe(test.reads);
323
- }),
324
- );
325
- },
326
- );
327
-
328
- it.effect("keeps the latest run's compaction when an earlier run reports completed again", () =>
329
- Effect.scoped(
330
- Effect.gen(function* () {
217
+ return Effect.gen(function* () {
218
yield* TestClock.setTime(NOW_MS);
332
- const base = records({ cacheExpiresInMs: 10 * MINUTE_MS });
333
- const laterRunId = RunId.make("run-2");
334
- const laterMessageId = MessageId.make("message-2");
335
- const earlierRun = base.runs[0]!;
336
- const laterRun = {
337
- ...earlierRun,
338
- id: laterRunId,
339
- ordinal: 2,
340
- userMessageId: laterMessageId,
341
- };
342
- const cancelledRun = {
343
- ...earlierRun,
344
- id: RunId.make("run-3"),
345
- ordinal: 3,
346
- userMessageId: MessageId.make("message-3"),
347
- status: "cancelled" as const,
348
- startedAt: null,
349
- };
219
+ const selectedInstance = ProviderInstanceId.make(
220
+ "instance" in test ? test.instance : "claudeAgent",
221
+ );
222
+ const driver = ProviderDriverKind.make("driver" in test ? test.driver : "claudeAgent");
223
+ const base = records({ cacheExpiresInMs: 2 * MINUTE_MS });
224
const data: OrchestrationV2ThreadProjection = {
225
...base,
352
- runs: [earlierRun, laterRun, cancelledRun],
353
- messages: [
354
- ...base.messages,
355
- { ...base.messages[0]!, id: laterMessageId, runId: laterRunId, text: "Keep going" },
356
- ],
357
- providerThreads: [{ ...base.providerThreads[0]!, lastRunOrdinal: 2 }],
226
+ thread: {
227
+ ...base.thread,
228
+ providerInstanceId: selectedInstance,
229
+ modelSelection: { ...base.thread.modelSelection, instanceId: selectedInstance },
230
+ },
231
+ runs: base.runs.map((run) => ({
232
+ ...run,
233
+ providerInstanceId: selectedInstance,
234
+ modelSelection: { ...run.modelSelection, instanceId: selectedInstance },
235
+ })),
236
+ providerThreads: base.providerThreads.map((thread) => ({
237
+ ...thread,
238
+ driver,
239
+ providerInstanceId: selectedInstance,
240
+ })),
241
attempts: [],
242
nodes: [],
243
subagents: [],
@@ -366,55 +249,168 @@ describe("IdleCompactionService", () => {
249
visibleTurnItems: [],
250
updatedAt: at(),
251
};
369
- const completed = (run: typeof earlierRun) => ({
370
- id: EventId.make(`completed-${run.id}`),
371
- type: "run.updated" as const,
372
- threadId,
373
- runId: run.id,
374
- occurredAt: at(),
375
- payload: run,
252
+ let historyReads = 0;
253
+ let dispatches = 0;
254
+ const done = yield* Deferred.make<void>();
255
+ const tracer = Tracer.make({
256
+ span(options) {
257
+ const span = new Tracer.NativeSpan(options);
258
+ const end = span.end.bind(span);
259
+ span.end = (...args) => {
260
+ end(...args);
261
+ if (span.name === "IdleCompactionService.compactWhenDue")
262
+ Deferred.doneUnsafe(done, Effect.void);
263
+ };
264
+ return span;
265
+ },
266
});
377
- const dispatched: Array<string> = [];
378
- const streamDone = yield* Deferred.make<void>();
267
const dependencies = Layer.mergeAll(
268
Layer.mock(Orchestrator.OrchestratorV2)({
381
- // A delegated completion on the earlier run lands after the later run completed.
382
- streamDomainEvents: Stream.make(completed(laterRun), completed(earlierRun)).pipe(
383
- Stream.ensuring(Deferred.succeed(streamDone, undefined)),
384
- ),
385
- dispatch: (command) =>
269
+ streamDomainEvents: Stream.make({
270
+ id: EventId.make("idle-completed"),
271
+ type: "run.updated",
272
+ threadId,
273
+ runId,
274
+ occurredAt: at(),
275
+ payload: data.runs[0]!,
276
+ }),
277
+ dispatch: () =>
278
Effect.sync(() => {
387
- dispatched.push(command.commandId);
279
+ dispatches++;
280
return { sequence: 1, storedEvents: [] };
281
}),
282
}),
283
Layer.mock(ProjectionStore.ProjectionStoreV2)({
284
getThread: () => Effect.succeed(data.thread),
393
- getThreadRecords: (_threadId, _keys, options) =>
394
- Effect.succeed({
395
- ...data,
396
- messages: data.messages.filter(
397
- (message) =>
398
- options?.messageRunIds === undefined ||
399
- (message.runId !== null && options.messageRunIds.includes(message.runId)),
400
- ),
285
+ getThreadRecords: () =>
286
+ Effect.sync(() => {
287
+ historyReads++;
288
+ return data;
289
}),
290
}),
291
Layer.mock(ServerSettings.ServerSettingsService)({
292
getSettings: Effect.succeed({
293
...DEFAULT_SERVER_SETTINGS,
406
- idleCompaction: "beforeCacheExpires",
294
+ idleCompaction: test.mode,
295
+ providerInstances:
296
+ "unconfigured" in test
297
+ ? {}
298
+ : {
299
+ [selectedInstance]: {
300
+ driver,
301
+ enabled: test.enabled,
302
+ config: { idleCompaction: test.override },
303
+ },
304
+ },
305
+ projectSettingsOverrides: test.projectDisabled
306
+ ? {
307
+ [data.thread.projectId]: {
308
+ providerInstances: { [selectedInstance]: { enabled: false } },
309
+ },
310
+ }
311
+ : {},
312
}),
313
}),
314
);
315
yield* Effect.gen(function* () {
316
const service = yield* IdleCompactionService.make;
317
yield* service.start();
413
- yield* Deferred.await(streamDone);
414
- yield* TestClock.adjust(9 * MINUTE_MS);
415
- }).pipe(Effect.provide(dependencies));
416
- expect(dispatched).toEqual(["server:idle-compact:idle-thread:run-2"]);
417
- }),
418
- ),
318
+ yield* Deferred.await(done);
319
+ }).pipe(Effect.provide(dependencies), Effect.withTracer(tracer));
320
+ expect(historyReads).toBe(test.reads);
321
+ expect(dispatches).toBe(test.reads);
322
+ });
323
+ },
324
+ );
325
+
326
+ it.effect("keeps the latest run's compaction when an earlier run reports completed again", () =>
327
+ Effect.gen(function* () {
328
+ yield* TestClock.setTime(NOW_MS);
329
+ const base = records({ cacheExpiresInMs: 10 * MINUTE_MS });
330
+ const laterRunId = RunId.make("run-2");
331
+ const laterMessageId = MessageId.make("message-2");
332
+ const earlierRun = base.runs[0]!;
333
+ const laterRun = {
334
+ ...earlierRun,
335
+ id: laterRunId,
336
+ ordinal: 2,
337
+ userMessageId: laterMessageId,
338
+ };
339
+ const cancelledRun = {
340
+ ...earlierRun,
341
+ id: RunId.make("run-3"),
342
+ ordinal: 3,
343
+ userMessageId: MessageId.make("message-3"),
344
+ status: "cancelled" as const,
345
+ startedAt: null,
346
+ };
347
+ const data: OrchestrationV2ThreadProjection = {
348
+ ...base,
349
+ runs: [earlierRun, laterRun, cancelledRun],
350
+ messages: [
351
+ ...base.messages,
352
+ { ...base.messages[0]!, id: laterMessageId, runId: laterRunId, text: "Keep going" },
353
+ ],
354
+ providerThreads: [{ ...base.providerThreads[0]!, lastRunOrdinal: 2 }],
355
+ attempts: [],
356
+ nodes: [],
357
+ subagents: [],
358
+ providerSessions: [],
359
+ plans: [],
360
+ checkpointScopes: [],
361
+ checkpoints: [],
362
+ contextHandoffs: [],
363
+ visibleTurnItems: [],
364
+ updatedAt: at(),
365
+ };
366
+ const completed = (run: typeof earlierRun) => ({
367
+ id: EventId.make(`completed-${run.id}`),
368
+ type: "run.updated" as const,
369
+ threadId,
370
+ runId: run.id,
371
+ occurredAt: at(),
372
+ payload: run,
373
+ });
374
+ const dispatched: Array<string> = [];
375
+ const streamDone = yield* Deferred.make<void>();
376
+ const dependencies = Layer.mergeAll(
377
+ Layer.mock(Orchestrator.OrchestratorV2)({
378
+ // A delegated completion on the earlier run lands after the later run completed.
379
+ streamDomainEvents: Stream.make(completed(laterRun), completed(earlierRun)).pipe(
380
+ Stream.ensuring(Deferred.succeed(streamDone, undefined)),
381
+ ),
382
+ dispatch: (command) =>
383
+ Effect.sync(() => {
384
+ dispatched.push(command.commandId);
385
+ return { sequence: 1, storedEvents: [] };
386
+ }),
387
+ }),
388
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
389
+ getThread: () => Effect.succeed(data.thread),
390
+ getThreadRecords: (_threadId, _keys, options) =>
391
+ Effect.succeed({
392
+ ...data,
393
+ messages: data.messages.filter(
394
+ (message) =>
395
+ options?.messageRunIds === undefined ||
396
+ (message.runId !== null && options.messageRunIds.includes(message.runId)),
397
+ ),
398
+ }),
399
+ }),
400
+ Layer.mock(ServerSettings.ServerSettingsService)({
401
+ getSettings: Effect.succeed({
402
+ ...DEFAULT_SERVER_SETTINGS,
403
+ idleCompaction: "beforeCacheExpires",
404
+ }),
405
+ }),
406
+ );
407
+ yield* Effect.gen(function* () {
408
+ const service = yield* IdleCompactionService.make;
409
+ yield* service.start();
410
+ yield* Deferred.await(streamDone);
411
+ yield* TestClock.adjust(9 * MINUTE_MS);
412
+ }).pipe(Effect.provide(dependencies));
413
+ expect(dispatched).toEqual(["server:idle-compact:idle-thread:run-2"]);
414
+ }),
415
);
416
});
apps/server/src/orchestration-v2/LiveStreamBudget.test.ts
+187
-199
@@ -16,38 +16,36 @@ import {
16
17
describe("LiveStreamBudget", () => {
18
it.effect("closes the source without releasing a batch still waiting for an ACK", () =>
19
- Effect.scoped(
20
- Effect.gen(function* () {
21
- const budget = yield* makeLiveStreamBudget({ maxItems: 3 });
22
- const queue = yield* Queue.unbounded<RetainedLiveItem<{ text: string }>>();
23
- const sourceClosed = yield* Deferred.make<void>();
24
- const first = yield* budget.retain({ text: "first" });
25
- const second = yield* budget.retain({ text: "second" });
26
- const third = yield* budget.retain({ text: "third" });
27
- yield* Queue.offerAll(queue, [first, second, third]);
28
- yield* Effect.scoped(
29
- Effect.gen(function* () {
30
- const pull = yield* Stream.toPull(
31
- budget.deliver(
32
- Stream.fromQueue(queue).pipe(
33
- Stream.rechunk(1),
34
- Stream.ensuring(Deferred.succeed(sourceClosed, undefined)),
35
- ),
19
+ Effect.gen(function* () {
20
+ const budget = yield* makeLiveStreamBudget({ maxItems: 3 });
21
+ const queue = yield* Queue.unbounded<RetainedLiveItem<{ text: string }>>();
22
+ const sourceClosed = yield* Deferred.make<void>();
23
+ const first = yield* budget.retain({ text: "first" });
24
+ const second = yield* budget.retain({ text: "second" });
25
+ const third = yield* budget.retain({ text: "third" });
26
+ yield* Queue.offerAll(queue, [first, second, third]);
27
+ yield* Effect.scoped(
28
+ Effect.gen(function* () {
29
+ const pull = yield* Stream.toPull(
30
+ budget.deliver(
31
+ Stream.fromQueue(queue).pipe(
32
+ Stream.rechunk(1),
33
+ Stream.ensuring(Deferred.succeed(sourceClosed, undefined)),
34
),
37
- );
38
- expect(yield* pull).toEqual([{ text: "first" }]);
39
- expect(yield* Queue.size(queue)).toBe(0);
40
- expect((yield* budget.usage).retainedItems).toBe(3);
41
- const overflow = yield* budget.retain({ text: "fourth" }).pipe(Effect.result);
42
- expect(overflow._tag).toBe("Failure");
43
- yield* Deferred.await(sourceClosed);
44
- yield* budget.closed;
45
- expect((yield* budget.usage).retainedItems).toBe(1);
46
- }),
47
- );
48
- expect(yield* budget.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
49
- }),
50
- ),
35
+ ),
36
+ );
37
+ expect(yield* pull).toEqual([{ text: "first" }]);
38
+ expect(yield* Queue.size(queue)).toBe(0);
39
+ expect((yield* budget.usage).retainedItems).toBe(3);
40
+ const overflow = yield* budget.retain({ text: "fourth" }).pipe(Effect.result);
41
+ expect(overflow._tag).toBe("Failure");
42
+ yield* Deferred.await(sourceClosed);
43
+ yield* budget.closed;
44
+ expect((yield* budget.usage).retainedItems).toBe(1);
45
+ }),
46
+ );
47
+ expect(yield* budget.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
48
+ }),
49
);
50
});
51
@@ -57,32 +55,30 @@ describe("bufferLatestLiveStream", () => {
55
it.effect.each(["items", "bytes"] as const)(
56
"counts an unacknowledged state against the %s limit when its replacement arrives",
57
(limit) =>
60
- Effect.scoped(
61
- Effect.gen(function* () {
62
- const releaseUpdate = yield* Deferred.make<void>();
63
- const closed = yield* Deferred.make<void>();
64
- const first = { sequence: 1, text: "é".repeat(20) };
65
- const next = { ...first, sequence: 2 };
66
- const pull = yield* Stream.toPull(
67
- bufferLatestLiveStream(
68
- Stream.concat(
69
- Stream.succeed(first),
70
- Stream.fromEffect(Deferred.await(releaseUpdate)).pipe(Stream.map(() => next)),
71
- ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
72
- () => "same-thread",
73
- limit === "items"
74
- ? { maxItems: 1 }
75
- : { maxSerializedBytes: Buffer.byteLength(JSON.stringify(first)) },
76
- ),
77
- );
78
- expect(yield* pull).toEqual([first]);
79
- yield* Deferred.succeed(releaseUpdate, undefined);
80
- yield* Deferred.await(closed);
81
- const result = yield* pull.pipe(Effect.result);
82
- expect(result._tag).toBe("Failure");
83
- if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
84
- }),
85
- ),
58
+ Effect.gen(function* () {
59
+ const releaseUpdate = yield* Deferred.make<void>();
60
+ const closed = yield* Deferred.make<void>();
61
+ const first = { sequence: 1, text: "é".repeat(20) };
62
+ const next = { ...first, sequence: 2 };
63
+ const pull = yield* Stream.toPull(
64
+ bufferLatestLiveStream(
65
+ Stream.concat(
66
+ Stream.succeed(first),
67
+ Stream.fromEffect(Deferred.await(releaseUpdate)).pipe(Stream.map(() => next)),
68
+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
69
+ () => "same-thread",
70
+ limit === "items"
71
+ ? { maxItems: 1 }
72
+ : { maxSerializedBytes: Buffer.byteLength(JSON.stringify(first)) },
73
+ ),
74
+ );
75
+ expect(yield* pull).toEqual([first]);
76
+ yield* Deferred.succeed(releaseUpdate, undefined);
77
+ yield* Deferred.await(closed);
78
+ const result = yield* pull.pipe(Effect.result);
79
+ expect(result._tag).toBe("Failure");
80
+ if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
81
+ }),
82
);
83
});
84
@@ -90,167 +86,159 @@ describe("replayAndBufferProjectedLiveEvents", () => {
86
it.effect.each(["items", "bytes"] as const)(
87
"replays the undelivered tail after a %s overflow without losing or duplicating events",
88
(limit) =>
93
- Effect.scoped(
94
- Effect.gen(function* () {
95
- const pubsub = yield* PubSub.unbounded<Event>();
96
- const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
97
- const events = [
98
- { sequence: 1, text: "one" },
99
- { sequence: 2, text: "two" },
100
- { sequence: 3, text: "three" },
101
- ];
102
- const limits = limit === "items" ? { maxItems: 1 } : { maxSerializedBytes: 40 };
103
- const pull = yield* Stream.toPull(
104
- replayAndBufferProjectedLiveEvents(
105
- {
106
- project: (event: Event) => event,
107
- subscribe: PubSub.subscribe(pubsub).pipe(
108
- Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
109
- ),
110
- latestSequence: Effect.succeed(1),
111
- replay: () => Stream.succeed(events[0]!),
112
- },
113
- limits,
114
- ),
115
- );
116
- const received = [...(yield* pull)];
117
- // Hold the ACK while more durable events arrive.
118
- yield* PubSub.publishAll(pubsub, events.slice(1));
119
- yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
120
- const overflow = yield* pull.pipe(Effect.result);
121
- expect(overflow._tag).toBe("Failure");
122
- if (overflow._tag === "Failure")
123
- expect(overflow.failure._tag).toBe("LiveStreamBufferError");
124
-
125
- const afterSequence = received.at(-1)!.sequence;
126
- const resumed = yield* replayAndBufferProjectedLiveEvents(
89
+ Effect.gen(function* () {
90
+ const pubsub = yield* PubSub.unbounded<Event>();
91
+ const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
92
+ const events = [
93
+ { sequence: 1, text: "one" },
94
+ { sequence: 2, text: "two" },
95
+ { sequence: 3, text: "three" },
96
+ ];
97
+ const limits = limit === "items" ? { maxItems: 1 } : { maxSerializedBytes: 40 };
98
+ const pull = yield* Stream.toPull(
99
+ replayAndBufferProjectedLiveEvents(
100
{
101
project: (event: Event) => event,
129
- subscribe: PubSub.subscribe(pubsub),
130
- afterSequence,
131
- latestSequence: Effect.succeed(3),
132
- replay: (throughSequence) =>
133
- Stream.fromIterable(
134
- events.filter(
135
- (event) => event.sequence > afterSequence && event.sequence <= throughSequence,
136
- ),
137
- ),
102
+ subscribe: PubSub.subscribe(pubsub).pipe(
103
+ Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
104
+ ),
105
+ latestSequence: Effect.succeed(1),
106
+ replay: () => Stream.succeed(events[0]!),
107
},
108
limits,
140
- ).pipe(Stream.take(2), Stream.runCollect);
141
- expect([...received, ...resumed]).toEqual(events);
142
- expect(yield* PubSub.size(pubsub)).toBe(0);
143
- }),
144
- ),
109
+ ),
110
+ );
111
+ const received = [...(yield* pull)];
112
+ // Hold the ACK while more durable events arrive.
113
+ yield* PubSub.publishAll(pubsub, events.slice(1));
114
+ yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
115
+ const overflow = yield* pull.pipe(Effect.result);
116
+ expect(overflow._tag).toBe("Failure");
117
+ if (overflow._tag === "Failure")
118
+ expect(overflow.failure._tag).toBe("LiveStreamBufferError");
119
+
120
+ const afterSequence = received.at(-1)!.sequence;
121
+ const resumed = yield* replayAndBufferProjectedLiveEvents(
122
+ {
123
+ project: (event: Event) => event,
124
+ subscribe: PubSub.subscribe(pubsub),
125
+ afterSequence,
126
+ latestSequence: Effect.succeed(3),
127
+ replay: (throughSequence) =>
128
+ Stream.fromIterable(
129
+ events.filter(
130
+ (event) => event.sequence > afterSequence && event.sequence <= throughSequence,
131
+ ),
132
+ ),
133
+ },
134
+ limits,
135
+ ).pipe(Stream.take(2), Stream.runCollect);
136
+ expect([...received, ...resumed]).toEqual(events);
137
+ expect(yield* PubSub.size(pubsub)).toBe(0);
138
+ }),
139
);
140
141
it.effect.each(["high-water", "replay"] as const)(
142
"unsubscribes and cancels a blocked %s read on live overflow",
143
(phase) =>
150
- Effect.scoped(
151
- Effect.gen(function* () {
152
- const pubsub = yield* PubSub.unbounded<Event>();
153
- const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
154
- const readStarted = yield* Deferred.make<void>();
155
- const readClosed = yield* Deferred.make<void>();
156
- const blockedRead = Deferred.succeed(readStarted, undefined).pipe(
157
- Effect.andThen(Effect.never),
158
- Effect.ensuring(Deferred.succeed(readClosed, undefined)),
159
- );
160
- const pull = yield* Stream.toPull(
161
- replayAndBufferProjectedLiveEvents(
162
- {
163
- project: (event: Event) => event,
164
- subscribe: PubSub.subscribe(pubsub).pipe(
165
- Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
166
- ),
167
- latestSequence:
168
- phase === "high-water" ? blockedRead.pipe(Effect.as(0)) : Effect.succeed(0),
169
- replay: () => (phase === "replay" ? Stream.fromEffect(blockedRead) : Stream.empty),
170
- },
171
- { maxItems: 2 },
172
- ),
173
- );
174
- const reader = yield* pull.pipe(Effect.result, Effect.forkScoped);
175
- yield* Deferred.await(readStarted);
176
- yield* PubSub.publishAll(pubsub, [
177
- { sequence: 1, text: "one" },
178
- { sequence: 2, text: "two" },
179
- { sequence: 3, text: "overflow" },
180
- ]);
181
- yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
182
- yield* Deferred.await(readClosed);
183
- const result = yield* Fiber.join(reader);
184
- expect(result._tag).toBe("Failure");
185
- if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
186
- expect(yield* PubSub.size(pubsub)).toBe(0);
187
- yield* PubSub.publish(pubsub, { sequence: 4, text: "after overflow" });
188
- expect(yield* PubSub.size(pubsub)).toBe(0);
189
- }),
190
- ),
144
+ Effect.gen(function* () {
145
+ const pubsub = yield* PubSub.unbounded<Event>();
146
+ const subscribed = yield* Deferred.make<PubSub.Subscription<Event>>();
147
+ const readStarted = yield* Deferred.make<void>();
148
+ const readClosed = yield* Deferred.make<void>();
149
+ const blockedRead = Deferred.succeed(readStarted, undefined).pipe(
150
+ Effect.andThen(Effect.never),
151
+ Effect.ensuring(Deferred.succeed(readClosed, undefined)),
152
+ );
153
+ const pull = yield* Stream.toPull(
154
+ replayAndBufferProjectedLiveEvents(
155
+ {
156
+ project: (event: Event) => event,
157
+ subscribe: PubSub.subscribe(pubsub).pipe(
158
+ Effect.tap((subscription) => Deferred.succeed(subscribed, subscription)),
159
+ ),
160
+ latestSequence:
161
+ phase === "high-water" ? blockedRead.pipe(Effect.as(0)) : Effect.succeed(0),
162
+ replay: () => (phase === "replay" ? Stream.fromEffect(blockedRead) : Stream.empty),
163
+ },
164
+ { maxItems: 2 },
165
+ ),
166
+ );
167
+ const reader = yield* pull.pipe(Effect.result, Effect.forkScoped);
168
+ yield* Deferred.await(readStarted);
169
+ yield* PubSub.publishAll(pubsub, [
170
+ { sequence: 1, text: "one" },
171
+ { sequence: 2, text: "two" },
172
+ { sequence: 3, text: "overflow" },
173
+ ]);
174
+ yield* (yield* Deferred.await(subscribed)).shutdownHook.await;
175
+ yield* Deferred.await(readClosed);
176
+ const result = yield* Fiber.join(reader);
177
+ expect(result._tag).toBe("Failure");
178
+ if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
179
+ expect(yield* PubSub.size(pubsub)).toBe(0);
180
+ yield* PubSub.publish(pubsub, { sequence: 4, text: "after overflow" });
181
+ expect(yield* PubSub.size(pubsub)).toBe(0);
182
+ }),
183
);
184
185
it.effect("lets a fast reader replay a database page larger than both buffer limits", () =>
194
- Effect.scoped(
186
+ Effect.gen(function* () {
187
+ const pubsub = yield* PubSub.unbounded<Event>();
188
+ const events = Array.from({ length: 20 }, (_, index) => ({
189
+ sequence: index + 1,
190
+ text: "historical event",
191
+ }));
192
+ const replayed = yield* replayAndBufferProjectedLiveEvents(
193
+ {
194
+ project: (event: Event) => event,
195
+ subscribe: PubSub.subscribe(pubsub),
196
+ latestSequence: Effect.succeed(20),
197
+ replay: () => Stream.fromIterable(events),
198
+ },
199
+ { maxItems: 2, maxSerializedBytes: 100 },
200
+ ).pipe(Stream.take(20), Stream.runCollect);
201
+ expect(replayed).toEqual(events);
202
+ expect(yield* PubSub.size(pubsub)).toBe(0);
203
+ }),
204
+ );
205
+
206
+ it.effect(
207
+ "filters unrelated events before buffering and deduplicates the replay/live overlap",
208
+ () =>
209
Effect.gen(function* () {
210
const pubsub = yield* PubSub.unbounded<Event>();
197
- const events = Array.from({ length: 20 }, (_, index) => ({
198
- sequence: index + 1,
199
- text: "historical event",
200
- }));
201
- const replayed = yield* replayAndBufferProjectedLiveEvents(
211
+ const highWaterStarted = yield* Deferred.make<void>();
212
+ const highWater = yield* Deferred.make<number>();
213
+ const first = { sequence: 1, text: "first", threadId: "selected" };
214
+ const unrelatedReplay = { sequence: 0, text: "unrelated replay", threadId: "other" };
215
+ const overlap = { sequence: 2, text: "overlap", threadId: "selected" };
216
+ const last = { sequence: 10, text: "last", threadId: "selected" };
217
+ const reader = yield* replayAndBufferProjectedLiveEvents(
218
{
219
project: (event: Event) => event,
220
subscribe: PubSub.subscribe(pubsub),
205
- latestSequence: Effect.succeed(20),
206
- replay: () => Stream.fromIterable(events),
221
+ latestSequence: Deferred.succeed(highWaterStarted, undefined).pipe(
222
+ Effect.andThen(Deferred.await(highWater)),
223
+ ),
224
+ replay: () => Stream.make(unrelatedReplay, first, overlap),
225
+ filter: (event) => event.threadId === "selected",
226
},
208
- { maxItems: 2, maxSerializedBytes: 100 },
209
- ).pipe(Stream.take(20), Stream.runCollect);
210
- expect(replayed).toEqual(events);
227
+ { maxItems: 4 },
228
+ ).pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped);
229
+ yield* Deferred.await(highWaterStarted);
230
+ yield* PubSub.publishAll(pubsub, [
231
+ overlap,
232
+ ...Array.from({ length: 6 }, (_, index) => ({
233
+ sequence: index + 3,
234
+ text: "unrelated",
235
+ threadId: "other",
236
+ })),
237
+ last,
238
+ ]);
239
+ yield* Deferred.succeed(highWater, 2);
240
+ expect(yield* Fiber.join(reader)).toEqual([first, overlap, last]);
241
expect(yield* PubSub.size(pubsub)).toBe(0);
242
}),
213
- ),
214
- );
215
-
216
- it.effect(
217
- "filters unrelated events before buffering and deduplicates the replay/live overlap",
218
- () =>
219
- Effect.scoped(
220
- Effect.gen(function* () {
221
- const pubsub = yield* PubSub.unbounded<Event>();
222
- const highWaterStarted = yield* Deferred.make<void>();
223
- const highWater = yield* Deferred.make<number>();
224
- const first = { sequence: 1, text: "first", threadId: "selected" };
225
- const unrelatedReplay = { sequence: 0, text: "unrelated replay", threadId: "other" };
226
- const overlap = { sequence: 2, text: "overlap", threadId: "selected" };
227
- const last = { sequence: 10, text: "last", threadId: "selected" };
228
- const reader = yield* replayAndBufferProjectedLiveEvents(
229
- {
230
- project: (event: Event) => event,
231
- subscribe: PubSub.subscribe(pubsub),
232
- latestSequence: Deferred.succeed(highWaterStarted, undefined).pipe(
233
- Effect.andThen(Deferred.await(highWater)),
234
- ),
235
- replay: () => Stream.make(unrelatedReplay, first, overlap),
236
- filter: (event) => event.threadId === "selected",
237
- },
238
- { maxItems: 4 },
239
- ).pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped);
240
- yield* Deferred.await(highWaterStarted);
241
- yield* PubSub.publishAll(pubsub, [
242
- overlap,
243
- ...Array.from({ length: 6 }, (_, index) => ({
244
- sequence: index + 3,
245
- text: "unrelated",
246
- threadId: "other",
247
- })),
248
- last,
249
- ]);
250
- yield* Deferred.succeed(highWater, 2);
251
- expect(yield* Fiber.join(reader)).toEqual([first, overlap, last]);
252
- expect(yield* PubSub.size(pubsub)).toBe(0);
253
- }),
254
- ),
243
);
244
});
apps/server/src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts
+3
-3
@@ -346,7 +346,7 @@ describe("OpenCode 2 through the orchestrator", () => {
346
);
347
348
assert.lengthOf(projection.providerThreads, 1);
349
- }).pipe(Effect.scoped),
349
+ }),
350
);
351
352
it.effect("rewrites the session's rules when the thread's mode changes between turns", () =>
@@ -397,7 +397,7 @@ describe("OpenCode 2 through the orchestrator", () => {
397
["completed", "completed", "completed"],
398
);
399
assert.lengthOf(projection.providerThreads, 1);
400
- }).pipe(Effect.scoped),
400
+ }),
401
);
402
403
it.effect("denies edits outside the plan directory in plan mode and lifts it after", () =>
@@ -439,7 +439,7 @@ describe("OpenCode 2 through the orchestrator", () => {
439
projection.runs.map((run) => run.status),
440
["completed", "completed"],
441
);
442
- }).pipe(Effect.scoped),
442
+ }),
443
);
444
445
it.effect("forks from an earlier turn before the next turn's user message", () =>
apps/server/src/orchestration-v2/ProviderCommitBatch.test.ts
+12
-12
@@ -81,7 +81,7 @@ it.effect("publishes preceding snapshots before a control", () =>
81
assert.deepEqual(yield* Queue.take(recorder.output), [event(2)]);
82
assert.deepEqual(yield* Queue.take(recorder.output), [control]);
83
yield* Fiber.join(consumer);
84
- }).pipe(Effect.scoped),
84
+ }),
85
);
86
87
it.effect("publishes isolated snapshots without advancing the clock", () =>
@@ -104,7 +104,7 @@ it.effect("publishes isolated snapshots without advancing the clock", () =>
104
assert.equal(published._tag, "Some");
105
if (published._tag === "Some") assert.deepEqual(published.value, [raw]);
106
}
107
- }).pipe(Effect.scoped),
107
+ }),
108
);
109
110
it.effect("bounds transactions by count and bytes, including the final partial group", () =>
@@ -148,7 +148,7 @@ it.effect("bounds transactions by count and bytes, including the final partial g
148
);
149
assert.deepEqual(batches.flat(), events);
150
}
151
- }).pipe(Effect.scoped),
151
+ }),
152
);
153
154
it.effect("keeps updates immediate and ordered when batching is disabled", () =>
@@ -164,7 +164,7 @@ it.effect("keeps updates immediate and ordered when batching is disabled", () =>
164
Effect.succeed(false),
165
);
166
assert.deepEqual(seen, [event(1), control, event(2)]);
167
- }).pipe(Effect.scoped),
167
+ }),
168
);
169
170
it.effect.each([
@@ -226,7 +226,7 @@ it.effect.each([
226
);
227
for (const input of inputs) yield* Queue.offer(input, control);
228
yield* Effect.forEach(consumers, Fiber.join);
229
- }).pipe(Effect.scoped),
229
+ }),
230
);
231
232
it.effect("does not hold the shared worker while one consumer checks background work", () =>
@@ -251,7 +251,7 @@ it.effect("does not hold the shared worker while one consumer checks background
251
);
252
yield* Deferred.succeed(release, undefined);
253
yield* Fiber.join(consumer);
254
- }).pipe(Effect.scoped),
254
+ }),
255
);
256
257
it.effect.each(["job", "commit"] as const)(
@@ -296,7 +296,7 @@ it.effect.each(["job", "commit"] as const)(
296
yield* coordinator.barrier(Effect.fail("original error")).pipe(Effect.exit),
297
Exit.fail("original error"),
298
);
299
- }).pipe(Effect.scoped),
299
+ }),
300
);
301
302
it.effect("keeps a transaction failure when rolling back one failed snapshot", () =>
@@ -315,7 +315,7 @@ it.effect("keeps a transaction failure when rolling back one failed snapshot", (
315
.pipe(Effect.exit);
316
assert.isTrue(Exit.isFailure(exit));
317
if (Exit.isFailure(exit)) assert.strictEqual(Cause.squash(exit.cause), transactionError);
318
- }).pipe(Effect.scoped),
318
+ }),
319
);
320
321
it.effect(
@@ -353,7 +353,7 @@ it.effect(
353
assert.isTrue(yield* Deferred.isDone(committed));
354
yield* Fiber.join(command);
355
yield* Fiber.join(consumer);
356
- }).pipe(Effect.scoped),
356
+ }),
357
);
358
359
it.effect.each([false, true])(
@@ -401,7 +401,7 @@ it.effect.each([false, true])(
401
[event(-1)],
402
Array.from({ length: cancel ? 9 : 10 }, (_, index) => event(index + (cancel ? 1 : 0))),
403
]);
404
- }).pipe(Effect.scoped),
404
+ }),
405
);
406
407
it.effect.each(["failure", "stop"] as const)(
@@ -430,7 +430,7 @@ it.effect.each(["failure", "stop"] as const)(
430
yield* coordinator.barrier(Effect.succeed("still available")),
431
"still available",
432
);
433
- }).pipe(Effect.scoped),
433
+ }),
434
);
435
436
it.effect("does not force a separate commit for every consumer that ends", () =>
@@ -458,7 +458,7 @@ it.effect("does not force a separate commit for every consumer that ends", () =>
458
(yield* Queue.takeAll(coordinator.output)).map((batch) => batch.length),
459
[10],
460
);
461
- }).pipe(Effect.scoped),
461
+ }),
462
);
463
464
it.effect("settles calls made after the coordinator's scope closes", () =>
apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts
+247
-251
@@ -231,99 +231,97 @@ function threadCreatedEvent(
231
const layer = it.layer(layerTest);
232
233
it.effect("refreshes the failing instance snapshot after a committed usage_limit terminal", () =>
234
- Effect.scoped(
235
- Effect.gen(function* () {
236
- const refreshed = yield* Deferred.make<void>();
237
- const adapter = yield* ProviderAdapter.ProviderAdapterV2.pipe(
238
- Effect.provide(
239
- Layer.mock(ProviderAdapter.ProviderAdapterV2)({
240
- instanceId: ProviderInstanceId.make("cursor-work"),
241
- driver: ProviderDriverKind.make("cursor"),
242
- }),
243
- ),
244
- );
245
- const instance: ProviderInstance = {
246
- instanceId: ProviderInstanceId.make("cursor-work"),
234
+ Effect.gen(function* () {
235
+ const refreshed = yield* Deferred.make<void>();
236
+ const adapter = yield* ProviderAdapter.ProviderAdapterV2.pipe(
237
+ Effect.provide(
238
+ Layer.mock(ProviderAdapter.ProviderAdapterV2)({
239
+ instanceId: ProviderInstanceId.make("cursor-work"),
240
+ driver: ProviderDriverKind.make("cursor"),
241
+ }),
242
+ ),
243
+ );
244
+ const instance: ProviderInstance = {
245
+ instanceId: ProviderInstanceId.make("cursor-work"),
246
+ driverKind: ProviderDriverKind.make("cursor"),
247
+ continuationIdentity: {
248
driverKind: ProviderDriverKind.make("cursor"),
248
- continuationIdentity: {
249
- driverKind: ProviderDriverKind.make("cursor"),
250
- continuationKey: "work",
251
- },
252
- enabled: true,
253
- displayName: undefined,
254
- orchestrationAdapter: adapter,
255
- textGeneration: {
256
- generateBranchName: () => Effect.die("unused"),
257
- generateCommitMessage: () => Effect.die("unused"),
258
- generatePrContent: () => Effect.die("unused"),
259
- generateThreadTitle: () => Effect.die("unused"),
260
- generateReviewGuide: () => Effect.die("unused"),
261
- generateTranscriptionPostProcessing: () => Effect.die("unused"),
262
- },
263
- snapshot: {
264
- refreshUsage: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid),
265
- getSnapshot: Effect.die("unused"),
266
- refresh: Effect.die("unused"),
267
- resolveMaintenance: () => Effect.die("unused"),
268
- applyUsageLimits: () => Effect.die("unused"),
269
- streamChanges: Stream.empty,
270
- },
271
- };
272
- const lookups: ProviderInstanceId[] = [];
273
- const instances = Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
274
- getInstance: (id) =>
275
- Effect.sync(() => {
276
- lookups.push(id);
277
- return id === instance.instanceId ? instance : undefined;
278
- }),
279
- });
280
- yield* Effect.gen(function* () {
281
- const now = yield* DateTime.now;
282
- const eventSink = yield* EventSink.EventSinkV2;
283
- const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
284
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
285
- const threadEvent = yield* threadCreatedEvent(now);
286
- yield* eventSink.write({ events: [threadEvent] });
287
- const input = {
288
- providerSessionId: yield* idAllocator.allocate.providerSession({
289
- providerInstanceId: instance.instanceId,
290
- threadId: threadEvent.threadId,
291
- }),
249
+ continuationKey: "work",
250
+ },
251
+ enabled: true,
252
+ displayName: undefined,
253
+ orchestrationAdapter: adapter,
254
+ textGeneration: {
255
+ generateBranchName: () => Effect.die("unused"),
256
+ generateCommitMessage: () => Effect.die("unused"),
257
+ generatePrContent: () => Effect.die("unused"),
258
+ generateThreadTitle: () => Effect.die("unused"),
259
+ generateReviewGuide: () => Effect.die("unused"),
260
+ generateTranscriptionPostProcessing: () => Effect.die("unused"),
261
+ },
262
+ snapshot: {
263
+ refreshUsage: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid),
264
+ getSnapshot: Effect.die("unused"),
265
+ refresh: Effect.die("unused"),
266
+ resolveMaintenance: () => Effect.die("unused"),
267
+ applyUsageLimits: () => Effect.die("unused"),
268
+ streamChanges: Stream.empty,
269
+ },
270
+ };
271
+ const lookups: ProviderInstanceId[] = [];
272
+ const instances = Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
273
+ getInstance: (id) =>
274
+ Effect.sync(() => {
275
+ lookups.push(id);
276
+ return id === instance.instanceId ? instance : undefined;
277
+ }),
278
+ });
279
+ yield* Effect.gen(function* () {
280
+ const now = yield* DateTime.now;
281
+ const eventSink = yield* EventSink.EventSinkV2;
282
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
283
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
284
+ const threadEvent = yield* threadCreatedEvent(now);
285
+ yield* eventSink.write({ events: [threadEvent] });
286
+ const input = {
287
+ providerSessionId: yield* idAllocator.allocate.providerSession({
288
providerInstanceId: instance.instanceId,
289
threadId: threadEvent.threadId,
294
- };
295
- for (const failureClass of ["validation_error", "usage_limit"] as const) {
296
- const stored = yield* ingestor.ingestNormalized({
297
- ...input,
298
- event: {
299
- type: "turn.terminal",
290
+ }),
291
+ providerInstanceId: instance.instanceId,
292
+ threadId: threadEvent.threadId,
293
+ };
294
+ for (const failureClass of ["validation_error", "usage_limit"] as const) {
295
+ const stored = yield* ingestor.ingestNormalized({
296
+ ...input,
297
+ event: {
298
+ type: "turn.terminal",
299
+ driver: instance.driverKind,
300
+ providerThreadId: idAllocator.derive.providerThread({
301
driver: instance.driverKind,
301
- providerThreadId: idAllocator.derive.providerThread({
302
- driver: instance.driverKind,
303
- nativeThreadId: "limited",
304
- }),
305
- providerTurnId: idAllocator.derive.providerTurn({
306
- driver: instance.driverKind,
307
- nativeTurnId: failureClass,
308
- }),
309
- runOrdinal: 1,
310
- failureItemOrdinal: 1,
311
- status: "failed",
312
- failure: makeProviderFailure({
313
- class: failureClass,
314
- message: "Provider rejected turn.",
315
- }),
316
- threadDisposition: "reusable",
317
- },
318
- });
319
- assert.equal(stored.length, 1);
320
- if (failureClass === "validation_error") assert.deepEqual(lookups, []);
321
- }
322
- assert.deepEqual(lookups, [instance.instanceId]);
323
- yield* Deferred.await(refreshed);
324
- }).pipe(Effect.provide(makeLayerTest(layerTestEventSink, instances)));
325
- }),
326
- ),
302
+ nativeThreadId: "limited",
303
+ }),
304
+ providerTurnId: idAllocator.derive.providerTurn({
305
+ driver: instance.driverKind,
306
+ nativeTurnId: failureClass,
307
+ }),
308
+ runOrdinal: 1,
309
+ failureItemOrdinal: 1,
310
+ status: "failed",
311
+ failure: makeProviderFailure({
312
+ class: failureClass,
313
+ message: "Provider rejected turn.",
314
+ }),
315
+ threadDisposition: "reusable",
316
+ },
317
+ });
318
+ assert.equal(stored.length, 1);
319
+ if (failureClass === "validation_error") assert.deepEqual(lookups, []);
320
+ }
321
+ assert.deepEqual(lookups, [instance.instanceId]);
322
+ yield* Deferred.await(refreshed);
323
+ }).pipe(Effect.provide(makeLayerTest(layerTestEventSink, instances)));
324
+ }),
325
);
326
327
it.effect("records accepted billed turn usage once without billing the context window", () => {
@@ -1306,173 +1304,171 @@ layer("ProviderEventIngestorV2", (it) => {
1304
it.effect(
1305
"preserves an answer committed after terminal normalization reads a pending question",
1306
() =>
1309
- Effect.scoped(
1310
- Effect.gen(function* () {
1311
- const eventSink = yield* EventSink.EventSinkV2;
1312
- const eventStore = yield* EventStore.EventStoreV2;
1313
- const projections = yield* ProjectionStore.ProjectionStoreV2;
1314
- const idAllocator = yield* IdAllocator.IdAllocatorV2;
1315
- const now = yield* DateTime.now;
1316
- const threadEvent = yield* threadCreatedEvent(now);
1317
- const threadId = threadEvent.threadId;
1318
- const providerSessionId = yield* idAllocator.allocate.providerSession({
1319
- providerInstanceId: modelSelection.instanceId,
1307
+ Effect.gen(function* () {
1308
+ const eventSink = yield* EventSink.EventSinkV2;
1309
+ const eventStore = yield* EventStore.EventStoreV2;
1310
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
1311
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
1312
+ const now = yield* DateTime.now;
1313
+ const threadEvent = yield* threadCreatedEvent(now);
1314
+ const threadId = threadEvent.threadId;
1315
+ const providerSessionId = yield* idAllocator.allocate.providerSession({
1316
+ providerInstanceId: modelSelection.instanceId,
1317
+ threadId,
1318
+ });
1319
+ const providerThreadId = idAllocator.derive.providerThread({
1320
+ driver: CODEX_DRIVER,
1321
+ nativeThreadId: `${threadId}:race`,
1322
+ });
1323
+ const providerTurnId = idAllocator.derive.providerTurn({
1324
+ driver: CODEX_DRIVER,
1325
+ nativeTurnId: `${threadId}:race`,
1326
+ });
1327
+ const nodeId = NodeId.make(`${threadId}:question`);
1328
+ const request: OrchestrationV2RuntimeRequest = {
1329
+ id: RuntimeRequestId.make(`${threadId}:question`),
1330
+ nodeId,
1331
+ providerTurnId,
1332
+ nativeRequestRef: null,
1333
+ kind: "user_input",
1334
+ status: "pending",
1335
+ responseCapability: { type: "live", providerSessionId },
1336
+ createdAt: now,
1337
+ resolvedAt: null,
1338
+ };
1339
+ const node: OrchestrationV2ExecutionNode = {
1340
+ id: nodeId,
1341
+ threadId,
1342
+ runId: null,
1343
+ parentNodeId: null,
1344
+ rootNodeId: nodeId,
1345
+ kind: "user_input_request",
1346
+ status: "waiting",
1347
+ countsForRun: false,
1348
+ providerThreadId,
1349
+ providerTurnId,
1350
+ nativeItemRef: null,
1351
+ runtimeRequestId: request.id,
1352
+ checkpointScopeId: null,
1353
+ startedAt: now,
1354
+ completedAt: null,
1355
+ };
1356
+ const item: OrchestrationV2TurnItem = {
1357
+ id: TurnItemId.make(`${threadId}:question`),
1358
+ threadId,
1359
+ runId: null,
1360
+ nodeId,
1361
+ providerThreadId,
1362
+ providerTurnId,
1363
+ nativeItemRef: null,
1364
+ parentItemId: null,
1365
+ ordinal: 1,
1366
+ status: "waiting",
1367
+ title: "Which option?",
1368
+ startedAt: now,
1369
+ completedAt: null,
1370
+ updatedAt: now,
1371
+ type: "user_input_request",
1372
+ requestId: request.id,
1373
+ questions: [],
1374
+ };
1375
+ const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
1376
+ for (const payload of [
1377
+ { type: "runtime-request.updated" as const, payload: request },
1378
+ { type: "node.updated" as const, payload: node },
1379
+ { type: "turn-item.updated" as const, payload: item },
1380
+ ])
1381
+ seedEvents.push({
1382
+ id: yield* idAllocator.allocate.event({ threadId }),
1383
threadId,
1384
+ occurredAt: now,
1385
+ ...payload,
1386
});
1322
- const providerThreadId = idAllocator.derive.providerThread({
1323
- driver: CODEX_DRIVER,
1324
- nativeThreadId: `${threadId}:race`,
1325
- });
1326
- const providerTurnId = idAllocator.derive.providerTurn({
1327
- driver: CODEX_DRIVER,
1328
- nativeTurnId: `${threadId}:race`,
1329
- });
1330
- const nodeId = NodeId.make(`${threadId}:question`);
1331
- const request: OrchestrationV2RuntimeRequest = {
1332
- id: RuntimeRequestId.make(`${threadId}:question`),
1333
- nodeId,
1334
- providerTurnId,
1335
- nativeRequestRef: null,
1336
- kind: "user_input",
1337
- status: "pending",
1338
- responseCapability: { type: "live", providerSessionId },
1339
- createdAt: now,
1340
- resolvedAt: null,
1341
- };
1342
- const node: OrchestrationV2ExecutionNode = {
1343
- id: nodeId,
1344
- threadId,
1345
- runId: null,
1346
- parentNodeId: null,
1347
- rootNodeId: nodeId,
1348
- kind: "user_input_request",
1349
- status: "waiting",
1350
- countsForRun: false,
1351
- providerThreadId,
1352
- providerTurnId,
1353
- nativeItemRef: null,
1354
- runtimeRequestId: request.id,
1355
- checkpointScopeId: null,
1356
- startedAt: now,
1357
- completedAt: null,
1358
- };
1359
- const item: OrchestrationV2TurnItem = {
1360
- id: TurnItemId.make(`${threadId}:question`),
1387
+ yield* eventSink.write({ events: seedEvents });
1388
+ const normalized = yield* Deferred.make<void>();
1389
+ const releaseTerminalWrite = yield* Deferred.make<void>();
1390
+ const gatedSink = EventSink.EventSinkV2.of({
1391
+ ...eventSink,
1392
+ write: (input) =>
1393
+ Deferred.succeed(normalized, undefined).pipe(
1394
+ Effect.andThen(Deferred.await(releaseTerminalWrite)),
1395
+ Effect.andThen(eventSink.write(input)),
1396
+ ),
1397
+ });
1398
+ const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1399
+ Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1400
+ Effect.provideService(EventSink.EventSinkV2, gatedSink),
1401
+ );
1402
+ const terminal = yield* ingestor
1403
+ .ingestNormalized({
1404
+ providerSessionId,
1405
+ providerInstanceId: modelSelection.instanceId,
1406
threadId,
1362
- runId: null,
1363
- nodeId,
1364
- providerThreadId,
1365
- providerTurnId,
1366
- nativeItemRef: null,
1367
- parentItemId: null,
1368
- ordinal: 1,
1369
- status: "waiting",
1370
- title: "Which option?",
1371
- startedAt: now,
1372
- completedAt: null,
1373
- updatedAt: now,
1374
- type: "user_input_request",
1375
- requestId: request.id,
1376
- questions: [],
1377
- };
1378
- const seedEvents: Array<OrchestrationV2DomainEvent> = [threadEvent];
1379
- for (const payload of [
1380
- { type: "runtime-request.updated" as const, payload: request },
1381
- { type: "node.updated" as const, payload: node },
1382
- { type: "turn-item.updated" as const, payload: item },
1383
- ])
1384
- seedEvents.push({
1385
- id: yield* idAllocator.allocate.event({ threadId }),
1386
- threadId,
1387
- occurredAt: now,
1388
- ...payload,
1389
- });
1390
- yield* eventSink.write({ events: seedEvents });
1391
- const normalized = yield* Deferred.make<void>();
1392
- const releaseTerminalWrite = yield* Deferred.make<void>();
1393
- const gatedSink = EventSink.EventSinkV2.of({
1394
- ...eventSink,
1395
- write: (input) =>
1396
- Deferred.succeed(normalized, undefined).pipe(
1397
- Effect.andThen(Deferred.await(releaseTerminalWrite)),
1398
- Effect.andThen(eventSink.write(input)),
1399
- ),
1400
- });
1401
- const ingestor = yield* ProviderEventIngestor.ProviderEventIngestorV2.pipe(
1402
- Effect.provide(Layer.fresh(ProviderEventIngestor.layer)),
1403
- Effect.provideService(EventSink.EventSinkV2, gatedSink),
1404
- );
1405
- const terminal = yield* ingestor
1406
- .ingestNormalized({
1407
- providerSessionId,
1408
- providerInstanceId: modelSelection.instanceId,
1409
- threadId,
1410
- event: {
1411
- type: "provider_turn.updated",
1412
- driver: CODEX_DRIVER,
1413
- providerTurn: {
1414
- id: providerTurnId,
1415
- providerThreadId,
1416
- nodeId,
1417
- runAttemptId: null,
1418
- nativeTurnRef: null,
1419
- ordinal: 1,
1420
- status: "completed",
1421
- startedAt: now,
1422
- completedAt: now,
1423
- },
1407
+ event: {
1408
+ type: "provider_turn.updated",
1409
+ driver: CODEX_DRIVER,
1410
+ providerTurn: {
1411
+ id: providerTurnId,
1412
+ providerThreadId,
1413
+ nodeId,
1414
+ runAttemptId: null,
1415
+ nativeTurnRef: null,
1416
+ ordinal: 1,
1417
+ status: "completed",
1418
+ startedAt: now,
1419
+ completedAt: now,
1420
},
1425
- })
1426
- .pipe(Effect.forkScoped);
1427
- yield* Deferred.await(normalized);
1428
- const answers = { decision: "Use the existing workspace" };
1429
- const responseEvents: Array<OrchestrationV2DomainEvent> = [];
1430
- for (const payload of [
1431
- {
1432
- type: "runtime-request.updated" as const,
1433
- payload: { ...request, status: "resolved" as const, answers, resolvedAt: now },
1434
- },
1435
- {
1436
- type: "node.updated" as const,
1437
- payload: { ...node, status: "completed" as const, completedAt: now },
1438
- },
1439
- {
1440
- type: "turn-item.updated" as const,
1441
- payload: { ...item, status: "completed" as const, completedAt: now },
1421
},
1443
- ])
1444
- responseEvents.push({
1445
- id: yield* idAllocator.allocate.event({ threadId }),
1446
- threadId,
1447
- occurredAt: now,
1448
- ...payload,
1449
- });
1450
- yield* eventSink.write({ events: responseEvents });
1451
- yield* Deferred.succeed(releaseTerminalWrite, undefined);
1452
- const committedTerminal = yield* Fiber.join(terminal);
1453
- assert.deepEqual(
1454
- committedTerminal.map((stored) => stored.event.type),
1455
- ["provider-turn.updated"],
1456
- );
1457
- const projection = yield* projections.getThreadProjection(threadId);
1458
- const answered = projection.runtimeRequests.find((entry) => entry.id === request.id)!;
1459
- assert.equal(answered.status, "resolved");
1460
- assert.deepEqual(answered.answers, answers);
1461
- assert.equal(projection.nodes.find((entry) => entry.id === nodeId)!.status, "completed");
1462
- assert.equal(
1463
- projection.turnItems.find((entry) => entry.id === item.id)!.status,
1464
- "completed",
1465
- );
1466
- const history = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
1467
- assert.isFalse(
1468
- history.some(
1469
- (stored) =>
1470
- stored.event.type === "runtime-request.updated" &&
1471
- stored.event.payload.status === "cancelled",
1472
- ),
1473
- );
1474
- }),
1475
- ),
1422
+ })
1423
+ .pipe(Effect.forkScoped);
1424
+ yield* Deferred.await(normalized);
1425
+ const answers = { decision: "Use the existing workspace" };
1426
+ const responseEvents: Array<OrchestrationV2DomainEvent> = [];
1427
+ for (const payload of [
1428
+ {
1429
+ type: "runtime-request.updated" as const,
1430
+ payload: { ...request, status: "resolved" as const, answers, resolvedAt: now },
1431
+ },
1432
+ {
1433
+ type: "node.updated" as const,
1434
+ payload: { ...node, status: "completed" as const, completedAt: now },
1435
+ },
1436
+ {
1437
+ type: "turn-item.updated" as const,
1438
+ payload: { ...item, status: "completed" as const, completedAt: now },
1439
+ },
1440
+ ])
1441
+ responseEvents.push({
1442
+ id: yield* idAllocator.allocate.event({ threadId }),
1443
+ threadId,
1444
+ occurredAt: now,
1445
+ ...payload,
1446
+ });
1447
+ yield* eventSink.write({ events: responseEvents });
1448
+ yield* Deferred.succeed(releaseTerminalWrite, undefined);
1449
+ const committedTerminal = yield* Fiber.join(terminal);
1450
+ assert.deepEqual(
1451
+ committedTerminal.map((stored) => stored.event.type),
1452
+ ["provider-turn.updated"],
1453
+ );
1454
+ const projection = yield* projections.getThreadProjection(threadId);
1455
+ const answered = projection.runtimeRequests.find((entry) => entry.id === request.id)!;
1456
+ assert.equal(answered.status, "resolved");
1457
+ assert.deepEqual(answered.answers, answers);
1458
+ assert.equal(projection.nodes.find((entry) => entry.id === nodeId)!.status, "completed");
1459
+ assert.equal(
1460
+ projection.turnItems.find((entry) => entry.id === item.id)!.status,
1461
+ "completed",
1462
+ );
1463
+ const history = yield* eventStore.read({ threadId }).pipe(Stream.runCollect);
1464
+ assert.isFalse(
1465
+ history.some(
1466
+ (stored) =>
1467
+ stored.event.type === "runtime-request.updated" &&
1468
+ stored.event.payload.status === "cancelled",
1469
+ ),
1470
+ );
1471
+ }),
1472
);
1473
1474
it.effect("persists a failed provider terminal as one expected error item", () =>
apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+1204
-1285
@@ -555,566 +555,530 @@ describe("PullRequestSyncReactor", () => {
555
);
556
557
it.effect("retries a failed stack read after the summary becomes terminal", () =>
558
- Effect.scoped(
559
- Effect.gen(function* () {
560
- yield* TestClock.setTime(Date.parse(NOW));
561
- let attempts = 0;
562
- const nativeStack: PullRequestStack = {
563
- id: "stack",
564
- number: 7,
565
- url: "https://github.com/owner/repository/stacks/7",
566
- base: "main",
567
- layers: [{ number: 7, headBranch: "feature", state: "merged" }],
568
- };
569
- const fixture = yield* makeHarness({
570
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
571
- summary: (input) =>
572
- Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
573
- stack: () =>
574
- ++attempts === 1
575
- ? Effect.fail(
576
- new PullRequestOperationError({
577
- operation: "stack",
578
- detail: "temporary failure",
579
- }),
580
- )
581
- : Effect.succeed(nativeStack),
558
+ Effect.gen(function* () {
559
+ yield* TestClock.setTime(Date.parse(NOW));
560
+ let attempts = 0;
561
+ const nativeStack: PullRequestStack = {
562
+ id: "stack",
563
+ number: 7,
564
+ url: "https://github.com/owner/repository/stacks/7",
565
+ base: "main",
566
+ layers: [{ number: 7, headBranch: "feature", state: "merged" }],
567
+ };
568
+ const fixture = yield* makeHarness({
569
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7)] })]),
570
+ summary: (input) => Effect.succeed(makeSummary(input, { state: "merged", mergedAt: NOW })),
571
+ stack: () =>
572
+ ++attempts === 1
573
+ ? Effect.fail(
574
+ new PullRequestOperationError({
575
+ operation: "stack",
576
+ detail: "temporary failure",
577
+ }),
578
+ )
579
+ : Effect.succeed(nativeStack),
580
+ });
581
+ yield* Effect.gen(function* () {
582
+ const reactor = yield* startAndSweep(fixture);
583
+ const commands = yield* Ref.get(fixture.syncCommands);
584
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
585
+ yield* sweepAgain(fixture, reactor);
586
+ assert.strictEqual(attempts, 2);
587
+ assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
588
+ kind: "native",
589
+ ...nativeStack,
590
});
583
- yield* Effect.gen(function* () {
584
- const reactor = yield* startAndSweep(fixture);
585
- const commands = yield* Ref.get(fixture.syncCommands);
586
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
587
- yield* sweepAgain(fixture, reactor);
588
- assert.strictEqual(attempts, 2);
589
- assert.deepStrictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.stack, {
590
- kind: "native",
591
- ...nativeStack,
592
- });
593
- }).pipe(Effect.provide(fixture.layer));
594
- }),
595
- ),
591
+ }).pipe(Effect.provide(fixture.layer));
592
+ }),
593
);
594
595
it.effect("explicit refresh reads a changed stack even when its PR summary is unchanged", () =>
599
- Effect.scoped(
600
- Effect.gen(function* () {
601
- yield* TestClock.setTime(Date.parse(NOW));
602
- const fixture = yield* makeHarness({
603
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
596
+ Effect.gen(function* () {
597
+ yield* TestClock.setTime(Date.parse(NOW));
598
+ const fixture = yield* makeHarness({
599
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(7, {})] })]),
600
+ });
601
+ yield* Effect.gen(function* () {
602
+ const reactor = yield* startAndSweep(fixture);
603
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
604
+ yield* reactor.requestSync({
605
+ host: "github.com",
606
+ repository: "owner/repository",
607
+ number: 7,
608
});
605
- yield* Effect.gen(function* () {
606
- const reactor = yield* startAndSweep(fixture);
607
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 0);
608
- yield* reactor.requestSync({
609
- host: "github.com",
610
- repository: "owner/repository",
611
- number: 7,
612
- });
613
- yield* Queue.take(fixture.snapshotReads);
614
- yield* reactor.drain;
615
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
616
- }).pipe(Effect.provide(fixture.layer));
617
- }),
618
- ),
609
+ yield* Queue.take(fixture.snapshotReads);
610
+ yield* reactor.drain;
611
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
612
+ }).pipe(Effect.provide(fixture.layer));
613
+ }),
614
);
615
it.effect("snapshots an unsynced link once and writes it to the thread", () =>
621
- Effect.scoped(
622
- Effect.gen(function* () {
623
- yield* TestClock.setTime(Date.parse(NOW));
624
- const fixture = yield* makeHarness({
625
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
626
- summary: (input) =>
627
- Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
628
- });
616
+ Effect.gen(function* () {
617
+ yield* TestClock.setTime(Date.parse(NOW));
618
+ const fixture = yield* makeHarness({
619
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
620
+ summary: (input) => Effect.succeed(makeSummary(input, { title: "Ship it", isDraft: true })),
621
+ });
622
630
- yield* Effect.gen(function* () {
631
- yield* startAndSweep(fixture);
623
+ yield* Effect.gen(function* () {
624
+ yield* startAndSweep(fixture);
625
633
- assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
626
+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), [
627
+ {
628
+ projectId: PROJECT_ID,
629
+ host: "github.com",
630
+ repository: "owner/repository",
631
+ number: 42,
632
+ },
633
+ ]);
634
+ assert.deepStrictEqual(
635
+ (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
636
+ [
637
{
635
- projectId: PROJECT_ID,
638
+ type: "thread.pull-request-link.sync",
639
+ threadId: ThreadId.make("one"),
640
host: "github.com",
641
repository: "owner/repository",
642
number: 42,
639
- },
640
- ]);
641
- assert.deepStrictEqual(
642
- (yield* Ref.get(fixture.syncCommands)).map(({ commandId: _, ...rest }) => rest),
643
- [
644
- {
645
- type: "thread.pull-request-link.sync",
646
- threadId: ThreadId.make("one"),
647
- host: "github.com",
648
- repository: "owner/repository",
649
- number: 42,
650
- snapshot: {
651
- state: "open",
652
- title: "Ship it",
653
- headBranch: "feature",
654
- baseBranch: "main",
655
- isDraft: true,
656
- updatedAt: "2026-08-27T00:00:00.000Z",
657
- syncedAt: NOW,
658
- closedAt: null,
659
- mergedAt: null,
660
- },
661
- stack: null,
643
+ snapshot: {
644
+ state: "open",
645
+ title: "Ship it",
646
+ headBranch: "feature",
647
+ baseBranch: "main",
648
+ isDraft: true,
649
+ updatedAt: "2026-08-27T00:00:00.000Z",
650
+ syncedAt: NOW,
651
+ closedAt: null,
652
+ mergedAt: null,
653
},
663
- ],
664
- );
665
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
666
- assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
667
- }).pipe(Effect.provide(fixture.layer));
668
- }),
669
- ),
654
+ stack: null,
655
+ },
656
+ ],
657
+ );
658
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
659
+ assert.strictEqual(yield* Ref.get(fixture.shellSnapshotReads), 0);
660
+ }).pipe(Effect.provide(fixture.layer));
661
+ }),
662
);
663
664
it.effect("asks the host once for a pull request shared by two threads in one project", () =>
673
- Effect.scoped(
665
+ Effect.gen(function* () {
666
+ yield* TestClock.setTime(Date.parse(NOW));
667
+ const fixture = yield* makeHarness({
668
+ snapshot: makeSnapshot([
669
+ makeThread("one", { pullRequests: [makeLink(42)] }),
670
+ makeThread("two", {
671
+ pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
672
+ }),
673
+ ]),
674
+ });
675
+
676
+ yield* Effect.gen(function* () {
677
+ yield* startAndSweep(fixture);
678
+
679
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
680
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
681
+ const commands = yield* Ref.get(fixture.syncCommands);
682
+ assert.deepStrictEqual(
683
+ commands
684
+ .map((command) => [command.threadId, command.repository] as const)
685
+ .sort((left, right) => left[0].localeCompare(right[0])),
686
+ [
687
+ [ThreadId.make("one"), "owner/repository"],
688
+ [ThreadId.make("two"), "Owner/Repository"],
689
+ ],
690
+ );
691
+ }).pipe(Effect.provide(fixture.layer));
692
+ }),
693
+ );
694
+
695
+ it.effect.each(["summary", "stack"] as const)(
696
+ "isolates a failed project %s refresh and retries it after the other project succeeds",
697
+ (operation) =>
698
Effect.gen(function* () {
699
yield* TestClock.setTime(Date.parse(NOW));
700
+ const otherProject = ProjectId.make("other-project");
701
+ const link = makeLink(42, { state: "merged", mergedAt: NOW });
702
+ let failing = true;
703
+ const failure = new PullRequestOperationError({ operation, detail: "checkout missing" });
704
const fixture = yield* makeHarness({
705
snapshot: makeSnapshot([
678
- makeThread("one", { pullRequests: [makeLink(42)] }),
679
- makeThread("two", {
680
- pullRequests: [makeLink(42, null, { repository: "Owner/Repository" })],
681
- }),
706
+ makeThread("failing", { pullRequests: [link] }),
707
+ makeThread("healthy", { projectId: otherProject, pullRequests: [link] }),
708
+ makeThread("same-project", { projectId: otherProject, pullRequests: [link] }),
709
]),
710
+ summary: (input) =>
711
+ failing && input.projectId === PROJECT_ID && operation === "summary"
712
+ ? Effect.fail(failure)
713
+ : Effect.succeed(
714
+ makeSummary(input, {
715
+ state: "merged",
716
+ mergedAt: NOW,
717
+ title: input.projectId,
718
+ }),
719
+ ),
720
+ stack: (input) =>
721
+ failing && input.projectId === PROJECT_ID && operation === "stack"
722
+ ? Effect.fail(failure)
723
+ : Effect.succeed({
724
+ id: input.projectId,
725
+ number: 42,
726
+ url: "https://github.com/owner/repository/stacks/42",
727
+ base: "main",
728
+ layers: [{ number: 42, headBranch: "feature", state: "merged" }],
729
+ }),
730
});
684
-
731
yield* Effect.gen(function* () {
686
- yield* startAndSweep(fixture);
687
-
688
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
689
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
732
+ const reactor = yield* startAndSweep(fixture);
733
+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
734
+ yield* reactor.requestSync(link);
735
+ yield* Queue.take(fixture.snapshotReads);
736
+ yield* reactor.drain;
737
const commands = yield* Ref.get(fixture.syncCommands);
691
- assert.deepStrictEqual(
692
- commands
693
- .map((command) => [command.threadId, command.repository] as const)
694
- .sort((left, right) => left[0].localeCompare(right[0])),
738
+ assert.sameDeepMembers(
739
+ commands.map((command) => [
740
+ command.threadId,
741
+ command.snapshot.title,
742
+ command.stack?.id,
743
+ ]),
744
[
696
- [ThreadId.make("one"), "owner/repository"],
697
- [ThreadId.make("two"), "Owner/Repository"],
745
+ ["healthy", otherProject, otherProject],
746
+ ["same-project", otherProject, otherProject],
747
],
748
);
749
+ assert.sameMembers(
750
+ (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId),
751
+ [PROJECT_ID, otherProject],
752
+ );
753
+ assert.sameMembers(
754
+ (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
755
+ operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject],
756
+ );
757
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
758
+ failing = false;
759
+ yield* sweepAgain(fixture, reactor);
760
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
761
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId, PROJECT_ID);
762
+ const retried = (yield* Ref.get(fixture.syncCommands)).at(-1);
763
+ assert.strictEqual(retried?.threadId, ThreadId.make("failing"));
764
+ assert.strictEqual(retried?.snapshot.title, PROJECT_ID);
765
+ assert.strictEqual(retried?.stack?.id, PROJECT_ID);
766
}).pipe(Effect.provide(fixture.layer));
767
}),
702
- ),
703
- );
704
-
705
- it.effect.each(["summary", "stack"] as const)(
706
- "isolates a failed project %s refresh and retries it after the other project succeeds",
707
- (operation) =>
708
- Effect.scoped(
709
- Effect.gen(function* () {
710
- yield* TestClock.setTime(Date.parse(NOW));
711
- const otherProject = ProjectId.make("other-project");
712
- const link = makeLink(42, { state: "merged", mergedAt: NOW });
713
- let failing = true;
714
- const failure = new PullRequestOperationError({ operation, detail: "checkout missing" });
715
- const fixture = yield* makeHarness({
716
- snapshot: makeSnapshot([
717
- makeThread("failing", { pullRequests: [link] }),
718
- makeThread("healthy", { projectId: otherProject, pullRequests: [link] }),
719
- makeThread("same-project", { projectId: otherProject, pullRequests: [link] }),
720
- ]),
721
- summary: (input) =>
722
- failing && input.projectId === PROJECT_ID && operation === "summary"
723
- ? Effect.fail(failure)
724
- : Effect.succeed(
725
- makeSummary(input, {
726
- state: "merged",
727
- mergedAt: NOW,
728
- title: input.projectId,
729
- }),
730
- ),
731
- stack: (input) =>
732
- failing && input.projectId === PROJECT_ID && operation === "stack"
733
- ? Effect.fail(failure)
734
- : Effect.succeed({
735
- id: input.projectId,
736
- number: 42,
737
- url: "https://github.com/owner/repository/stacks/42",
738
- base: "main",
739
- layers: [{ number: 42, headBranch: "feature", state: "merged" }],
740
- }),
741
- });
742
- yield* Effect.gen(function* () {
743
- const reactor = yield* startAndSweep(fixture);
744
- assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
745
- yield* reactor.requestSync(link);
746
- yield* Queue.take(fixture.snapshotReads);
747
- yield* reactor.drain;
748
- const commands = yield* Ref.get(fixture.syncCommands);
749
- assert.sameDeepMembers(
750
- commands.map((command) => [
751
- command.threadId,
752
- command.snapshot.title,
753
- command.stack?.id,
754
- ]),
755
- [
756
- ["healthy", otherProject, otherProject],
757
- ["same-project", otherProject, otherProject],
758
- ],
759
- );
760
- assert.sameMembers(
761
- (yield* Ref.get(fixture.summaryCalls)).map((call) => call.projectId),
762
- [PROJECT_ID, otherProject],
763
- );
764
- assert.sameMembers(
765
- (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
766
- operation === "stack" ? [PROJECT_ID, otherProject] : [otherProject],
767
- );
768
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
769
- failing = false;
770
- yield* sweepAgain(fixture, reactor);
771
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
772
- assert.strictEqual(
773
- (yield* Ref.get(fixture.summaryCalls)).at(-1)?.projectId,
774
- PROJECT_ID,
775
- );
776
- const retried = (yield* Ref.get(fixture.syncCommands)).at(-1);
777
- assert.strictEqual(retried?.threadId, ThreadId.make("failing"));
778
- assert.strictEqual(retried?.snapshot.title, PROJECT_ID);
779
- assert.strictEqual(retried?.stack?.id, PROJECT_ID);
780
- }).pipe(Effect.provide(fixture.layer));
781
- }),
782
- ),
768
);
769
770
it.effect("recovers the HTTP port when syncing an older Forgejo link", () =>
786
- Effect.scoped(
787
- Effect.gen(function* () {
788
- const fixture = yield* makeHarness({
789
- snapshot: makeSnapshot([
790
- makeThread("one", {
791
- pullRequests: [
792
- makeLink(42, null, {
793
- host: "forge.example",
794
- url: "http://forge.example:3000/owner/repository/pulls/42",
795
- }),
796
- ],
797
- }),
798
- ]),
799
- summary: (input) => Effect.succeed(makeSummary(input)),
800
- });
801
- yield* Effect.gen(function* () {
802
- yield* startAndSweep(fixture);
803
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
804
- assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
805
- }).pipe(Effect.provide(fixture.layer));
806
- }),
807
- ),
771
+ Effect.gen(function* () {
772
+ const fixture = yield* makeHarness({
773
+ snapshot: makeSnapshot([
774
+ makeThread("one", {
775
+ pullRequests: [
776
+ makeLink(42, null, {
777
+ host: "forge.example",
778
+ url: "http://forge.example:3000/owner/repository/pulls/42",
779
+ }),
780
+ ],
781
+ }),
782
+ ]),
783
+ summary: (input) => Effect.succeed(makeSummary(input)),
784
+ });
785
+ yield* Effect.gen(function* () {
786
+ yield* startAndSweep(fixture);
787
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls))[0]?.host, "forge.example:3000");
788
+ assert.strictEqual((yield* Ref.get(fixture.syncCommands))[0]?.host, "forge.example:3000");
789
+ }).pipe(Effect.provide(fixture.layer));
790
+ }),
791
);
792
793
it.effect("dispatches nothing when the host snapshot is unchanged", () =>
811
- Effect.scoped(
812
- Effect.gen(function* () {
813
- yield* TestClock.setTime(Date.parse(NOW));
814
- const fixture = yield* makeHarness({
815
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
816
- summary: (input) => Effect.succeed(makeSummary(input, { updatedAt: NOW })),
817
- });
794
+ Effect.gen(function* () {
795
+ yield* TestClock.setTime(Date.parse(NOW));
796
+ const fixture = yield* makeHarness({
797
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(42)] })]),
798
+ summary: (input) => Effect.succeed(makeSummary(input, { updatedAt: NOW })),
799
+ });
800
819
- yield* Effect.gen(function* () {
820
- const reactor = yield* startAndSweep(fixture);
821
- const firstSweep = yield* Ref.get(fixture.syncCommands);
822
- assert.strictEqual(firstSweep.length, 1);
823
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
801
+ yield* Effect.gen(function* () {
802
+ const reactor = yield* startAndSweep(fixture);
803
+ const firstSweep = yield* Ref.get(fixture.syncCommands);
804
+ assert.strictEqual(firstSweep.length, 1);
805
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
806
825
- yield* sweepAgain(fixture, reactor);
807
+ yield* sweepAgain(fixture, reactor);
808
827
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
828
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
829
- assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
830
- }).pipe(Effect.provide(fixture.layer));
831
- }),
832
- ),
809
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
810
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
811
+ assert.strictEqual((yield* Ref.get(fixture.syncCommands)).length, 1);
812
+ }).pipe(Effect.provide(fixture.layer));
813
+ }),
814
);
815
816
it.effect("keeps the known mergeability while the host recomputes it", () =>
836
- Effect.scoped(
837
- Effect.gen(function* () {
838
- yield* TestClock.setTime(Date.parse(NOW));
839
- const answers = yield* Ref.make<ReadonlyArray<"unknown" | "mergeable">>([
840
- "unknown",
841
- "mergeable",
842
- ]);
843
- const fixture = yield* makeHarness({
844
- snapshot: makeSnapshot([
845
- makeThread("one", {
846
- pullRequests: [makeLink(42, { mergeability: "conflicting" })],
847
- }),
817
+ Effect.gen(function* () {
818
+ yield* TestClock.setTime(Date.parse(NOW));
819
+ const answers = yield* Ref.make<ReadonlyArray<"unknown" | "mergeable">>([
820
+ "unknown",
821
+ "mergeable",
822
+ ]);
823
+ const fixture = yield* makeHarness({
824
+ snapshot: makeSnapshot([
825
+ makeThread("one", {
826
+ pullRequests: [makeLink(42, { mergeability: "conflicting" })],
827
+ }),
828
+ ]),
829
+ summary: (input) =>
830
+ Ref.modify(answers, ([next = "mergeable", ...rest]) => [
831
+ makeSummary(input, { mergeability: next }),
832
+ rest,
833
]),
849
- summary: (input) =>
850
- Ref.modify(answers, ([next = "mergeable", ...rest]) => [
851
- makeSummary(input, { mergeability: next }),
852
- rest,
853
- ]),
854
- });
855
-
856
- yield* Effect.gen(function* () {
857
- const reactor = yield* startAndSweep(fixture);
858
- assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
859
-
860
- // An unchanged old PR uses main's five-minute quiet polling cadence.
861
- yield* TestClock.adjust("5 minutes");
862
- yield* Queue.take(fixture.snapshotReads);
863
- yield* reactor.drain;
864
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
834
+ });
835
866
- const commands = yield* Ref.get(fixture.syncCommands);
867
- assert.deepStrictEqual(
868
- commands.map((command) => command.snapshot.mergeability),
869
- ["mergeable"],
870
- );
871
- }).pipe(Effect.provide(fixture.layer));
872
- }),
873
- ),
836
+ yield* Effect.gen(function* () {
837
+ const reactor = yield* startAndSweep(fixture);
838
+ assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
839
+
840
+ // An unchanged old PR uses main's five-minute quiet polling cadence.
841
+ yield* TestClock.adjust("5 minutes");
842
+ yield* Queue.take(fixture.snapshotReads);
843
+ yield* reactor.drain;
844
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
845
+
846
+ const commands = yield* Ref.get(fixture.syncCommands);
847
+ assert.deepStrictEqual(
848
+ commands.map((command) => command.snapshot.mergeability),
849
+ ["mergeable"],
850
+ );
851
+ }).pipe(Effect.provide(fixture.layer));
852
+ }),
853
);
854
855
it.effect.each([
856
{ provider: "github" as const, updatedAt: "2026-08-28T00:00:00.000Z" },
857
{ provider: "forgejo" as const, updatedAt: "2026-08-27T00:00:00.000Z" },
858
])("persists unknown mergeability for $provider at $updatedAt", ({ provider, updatedAt }) =>
880
- Effect.scoped(
881
- Effect.gen(function* () {
882
- yield* TestClock.setTime(Date.parse(NOW));
883
- const fixture = yield* makeHarness({
884
- snapshot: makeSnapshot([
885
- makeThread("one", {
886
- pullRequests: [makeLink(42, { mergeability: "mergeable" })],
859
+ Effect.gen(function* () {
860
+ yield* TestClock.setTime(Date.parse(NOW));
861
+ const fixture = yield* makeHarness({
862
+ snapshot: makeSnapshot([
863
+ makeThread("one", {
864
+ pullRequests: [makeLink(42, { mergeability: "mergeable" })],
865
+ }),
866
+ ]),
867
+ summary: (input) =>
868
+ Effect.succeed(
869
+ makeSummary(input, {
870
+ provider: SourceControlProviderKind.make(provider),
871
+ updatedAt,
872
+ mergeability: "unknown",
873
}),
888
- ]),
889
- summary: (input) =>
890
- Effect.succeed(
891
- makeSummary(input, {
892
- provider: SourceControlProviderKind.make(provider),
893
- updatedAt,
894
- mergeability: "unknown",
895
- }),
896
- ),
897
- });
898
- yield* Effect.gen(function* () {
899
- yield* startAndSweep(fixture);
900
- const commands = yield* Ref.get(fixture.syncCommands);
901
- assert.deepStrictEqual(
902
- commands.map((command) => command.snapshot.mergeability),
903
- ["unknown"],
904
- );
905
- }).pipe(Effect.provide(fixture.layer));
906
- }),
907
- ),
874
+ ),
875
+ });
876
+ yield* Effect.gen(function* () {
877
+ yield* startAndSweep(fixture);
878
+ const commands = yield* Ref.get(fixture.syncCommands);
879
+ assert.deepStrictEqual(
880
+ commands.map((command) => command.snapshot.mergeability),
881
+ ["unknown"],
882
+ );
883
+ }).pipe(Effect.provide(fixture.layer));
884
+ }),
885
);
886
887
it.effect("refreshes closed links through each project after reopening elsewhere", () =>
911
- Effect.scoped(
912
- Effect.gen(function* () {
913
- yield* TestClock.setTime(Date.parse(NOW));
914
- const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);
915
- const fixture = yield* makeHarness({
916
- snapshot: makeSnapshot([
917
- makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
918
- makeThread("second", {
919
- projectId: ProjectId.make("second-project"),
920
- pullRequests: [makeLink(42, { state: "closed" })],
921
- }),
922
- ]),
923
- invalidate: ({ reference }) =>
924
- reference !== undefined
925
- ? Ref.update(invalidated, (projects) => [...projects, reference.projectId])
926
- : Effect.void,
927
- summary: (input) =>
928
- Ref.get(invalidated).pipe(
929
- Effect.map((projects) =>
930
- makeSummary(input, {
931
- state: projects.includes(input.projectId) ? "open" : "closed",
932
- }),
933
- ),
888
+ Effect.gen(function* () {
889
+ yield* TestClock.setTime(Date.parse(NOW));
890
+ const invalidated = yield* Ref.make<ReadonlyArray<ProjectId>>([]);
891
+ const fixture = yield* makeHarness({
892
+ snapshot: makeSnapshot([
893
+ makeThread("first", { pullRequests: [makeLink(42, { state: "closed" })] }),
894
+ makeThread("second", {
895
+ projectId: ProjectId.make("second-project"),
896
+ pullRequests: [makeLink(42, { state: "closed" })],
897
+ }),
898
+ ]),
899
+ invalidate: ({ reference }) =>
900
+ reference !== undefined
901
+ ? Ref.update(invalidated, (projects) => [...projects, reference.projectId])
902
+ : Effect.void,
903
+ summary: (input) =>
904
+ Ref.get(invalidated).pipe(
905
+ Effect.map((projects) =>
906
+ makeSummary(input, {
907
+ state: projects.includes(input.projectId) ? "open" : "closed",
908
+ }),
909
),
910
+ ),
911
+ });
912
+ yield* Effect.gen(function* () {
913
+ const reactor = yield* startAndSweep(fixture);
914
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
915
+ yield* reactor.requestSync({
916
+ host: "github.com",
917
+ repository: "owner/repository",
918
+ number: 42,
919
});
936
- yield* Effect.gen(function* () {
937
- const reactor = yield* startAndSweep(fixture);
938
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
939
- yield* reactor.requestSync({
940
- host: "github.com",
941
- repository: "owner/repository",
942
- number: 42,
943
- });
944
- yield* Queue.take(fixture.snapshotReads);
945
- yield* reactor.drain;
946
- assert.sameMembers(
947
- [...(yield* Ref.get(invalidated))],
948
- [PROJECT_ID, ProjectId.make("second-project")],
949
- );
950
- assert.sameMembers(
951
- (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
952
- [PROJECT_ID, ProjectId.make("second-project")],
953
- );
954
- const commands = yield* Ref.get(fixture.syncCommands);
955
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
956
- const snapshot = yield* Ref.get(fixture.snapshots);
957
- assert.deepStrictEqual(
958
- snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
959
- ["open", "open"],
960
- );
961
- }).pipe(Effect.provide(fixture.layer));
962
- }),
963
- ),
920
+ yield* Queue.take(fixture.snapshotReads);
921
+ yield* reactor.drain;
922
+ assert.sameMembers(
923
+ [...(yield* Ref.get(invalidated))],
924
+ [PROJECT_ID, ProjectId.make("second-project")],
925
+ );
926
+ assert.sameMembers(
927
+ (yield* Ref.get(fixture.stackCalls)).map((call) => call.projectId),
928
+ [PROJECT_ID, ProjectId.make("second-project")],
929
+ );
930
+ const commands = yield* Ref.get(fixture.syncCommands);
931
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
932
+ const snapshot = yield* Ref.get(fixture.snapshots);
933
+ assert.deepStrictEqual(
934
+ snapshot.threads.map((thread) => thread.pullRequests[0]?.snapshot?.state),
935
+ ["open", "open"],
936
+ );
937
+ }).pipe(Effect.provide(fixture.layer));
938
+ }),
939
);
940
941
it.effect("stops asking the host once a pull request is merged", () =>
967
- Effect.scoped(
968
- Effect.gen(function* () {
969
- yield* TestClock.setTime(Date.parse(NOW));
970
- const fixture = yield* makeHarness({
971
- snapshot: makeSnapshot([
972
- makeThread("merged", {
973
- pullRequests: [
974
- makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
975
- ],
976
- }),
977
- ]),
978
- });
942
+ Effect.gen(function* () {
943
+ yield* TestClock.setTime(Date.parse(NOW));
944
+ const fixture = yield* makeHarness({
945
+ snapshot: makeSnapshot([
946
+ makeThread("merged", {
947
+ pullRequests: [makeLink(1, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" })],
948
+ }),
949
+ ]),
950
+ });
951
980
- yield* Effect.gen(function* () {
981
- const reactor = yield* startAndSweep(fixture);
982
- yield* sweepAgain(fixture, reactor);
952
+ yield* Effect.gen(function* () {
953
+ const reactor = yield* startAndSweep(fixture);
954
+ yield* sweepAgain(fixture, reactor);
955
984
- assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
985
- assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
956
+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
957
+ assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
958
987
- yield* reactor.requestSync({
988
- host: "github.com",
989
- repository: "owner/repository",
990
- number: 1,
991
- });
992
- yield* Queue.take(fixture.snapshotReads);
993
- yield* reactor.drain;
959
+ yield* reactor.requestSync({
960
+ host: "github.com",
961
+ repository: "owner/repository",
962
+ number: 1,
963
+ });
964
+ yield* Queue.take(fixture.snapshotReads);
965
+ yield* reactor.drain;
966
995
- assert.deepStrictEqual(
996
- (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
997
- [1],
998
- );
999
- }).pipe(Effect.provide(fixture.layer));
1000
- }),
1001
- ),
967
+ assert.deepStrictEqual(
968
+ (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
969
+ [1],
970
+ );
971
+ }).pipe(Effect.provide(fixture.layer));
972
+ }),
973
);
974
975
it.effect("stops reading a pull request a day after it closed, until a refresh asks", () =>
1005
- Effect.scoped(
1006
- Effect.gen(function* () {
1007
- yield* TestClock.setTime(Date.parse(NOW));
1008
- const closed = (closedAt: string | null) => ({ state: "closed" as const, closedAt });
1009
- const fixture = yield* makeHarness({
1010
- snapshot: makeSnapshot([
1011
- makeThread("closed", {
1012
- pullRequests: [
1013
- makeLink(1, closed("2026-08-20T00:00:00.000Z")),
1014
- makeLink(2, closed("2026-08-26T00:00:00.000Z")),
1015
- makeLink(3, closed("2026-08-28T11:00:00.000Z")),
1016
- makeLink(4, closed(null)),
1017
- ],
1018
- }),
1019
- ]),
1020
- summary: (input) =>
1021
- Effect.succeed(makeSummary(input, { state: "closed", closedAt: NOW })),
1022
- });
1023
- const reads = Ref.get(fixture.summaryCalls).pipe(
1024
- Effect.map((calls) => calls.map((call) => call.number).toSorted()),
1025
- );
1026
-
1027
- yield* Effect.gen(function* () {
1028
- const reactor = yield* startAndSweep(fixture);
1029
- // Closed within the day, or with no close time, keeps the fifteen-minute cadence.
1030
- assert.deepStrictEqual(yield* reads, [3, 4]);
1031
- for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1032
- assert.deepStrictEqual(yield* reads, [3, 3, 4, 4]);
976
+ Effect.gen(function* () {
977
+ yield* TestClock.setTime(Date.parse(NOW));
978
+ const closed = (closedAt: string | null) => ({ state: "closed" as const, closedAt });
979
+ const fixture = yield* makeHarness({
980
+ snapshot: makeSnapshot([
981
+ makeThread("closed", {
982
+ pullRequests: [
983
+ makeLink(1, closed("2026-08-20T00:00:00.000Z")),
984
+ makeLink(2, closed("2026-08-26T00:00:00.000Z")),
985
+ makeLink(3, closed("2026-08-28T11:00:00.000Z")),
986
+ makeLink(4, closed(null)),
987
+ ],
988
+ }),
989
+ ]),
990
+ summary: (input) => Effect.succeed(makeSummary(input, { state: "closed", closedAt: NOW })),
991
+ });
992
+ const reads = Ref.get(fixture.summaryCalls).pipe(
993
+ Effect.map((calls) => calls.map((call) => call.number).toSorted()),
994
+ );
995
1034
- yield* reactor.requestSync({
1035
- host: "github.com",
1036
- repository: "owner/repository",
1037
- number: 1,
1038
- });
1039
- yield* Queue.take(fixture.snapshotReads);
1040
- yield* reactor.drain;
1041
- assert.deepStrictEqual(yield* reads, [1, 3, 3, 4, 4]);
1042
- }).pipe(Effect.provide(fixture.layer));
1043
- }),
1044
- ),
996
+ yield* Effect.gen(function* () {
997
+ const reactor = yield* startAndSweep(fixture);
998
+ // Closed within the day, or with no close time, keeps the fifteen-minute cadence.
999
+ assert.deepStrictEqual(yield* reads, [3, 4]);
1000
+ for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1001
+ assert.deepStrictEqual(yield* reads, [3, 3, 4, 4]);
1002
+
1003
+ yield* reactor.requestSync({
1004
+ host: "github.com",
1005
+ repository: "owner/repository",
1006
+ number: 1,
1007
+ });
1008
+ yield* Queue.take(fixture.snapshotReads);
1009
+ yield* reactor.drain;
1010
+ assert.deepStrictEqual(yield* reads, [1, 3, 3, 4, 4]);
1011
+ }).pipe(Effect.provide(fixture.layer));
1012
+ }),
1013
);
1014
1015
it.effect("re-reads a merged pull request until the host supplies its merge time", () =>
1048
- Effect.scoped(
1049
- Effect.gen(function* () {
1050
- yield* TestClock.setTime(Date.parse(NOW));
1051
- const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1052
- const fixture = yield* makeHarness({
1053
- snapshot: makeSnapshot([
1054
- makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
1055
- ]),
1056
- invalidate: ({ reference }) =>
1057
- Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1058
- summary: (input) =>
1059
- Effect.succeed(
1060
- makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
1061
- ),
1062
- });
1063
-
1064
- yield* Effect.gen(function* () {
1065
- const reactor = yield* startAndSweep(fixture);
1066
- const firstSweep = yield* Ref.get(fixture.syncCommands);
1067
- assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
1068
- assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
1069
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
1016
+ Effect.gen(function* () {
1017
+ yield* TestClock.setTime(Date.parse(NOW));
1018
+ const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1019
+ const fixture = yield* makeHarness({
1020
+ snapshot: makeSnapshot([
1021
+ makeThread("merged", { pullRequests: [makeLink(1, { state: "merged" })] }),
1022
+ ]),
1023
+ invalidate: ({ reference }) =>
1024
+ Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1025
+ summary: (input) =>
1026
+ Effect.succeed(
1027
+ makeSummary(input, { state: "merged", mergedAt: "2026-08-27T00:00:00.000Z" }),
1028
+ ),
1029
+ });
1030
1071
- for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1072
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
1073
- }).pipe(Effect.provide(fixture.layer));
1074
- }),
1075
- ),
1031
+ yield* Effect.gen(function* () {
1032
+ const reactor = yield* startAndSweep(fixture);
1033
+ const firstSweep = yield* Ref.get(fixture.syncCommands);
1034
+ assert.deepStrictEqual(yield* Ref.get(invalidated), [1]);
1035
+ assert.strictEqual(firstSweep.at(-1)?.snapshot.mergedAt, "2026-08-27T00:00:00.000Z");
1036
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, firstSweep));
1037
+
1038
+ for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1039
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 1);
1040
+ }).pipe(Effect.provide(fixture.layer));
1041
+ }),
1042
);
1043
1044
it.effect("syncs a pull request a reader saw merge without waiting for the sweep", () =>
1079
- Effect.scoped(
1080
- Effect.gen(function* () {
1081
- yield* TestClock.setTime(Date.parse(NOW));
1082
- const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1083
- const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1084
- const fixture = yield* makeHarness({
1085
- snapshot: makeSnapshot([
1086
- makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1087
- ]),
1088
- summary: (input) =>
1089
- Ref.get(state).pipe(
1090
- Effect.map((current) =>
1091
- makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1092
- ),
1045
+ Effect.gen(function* () {
1046
+ yield* TestClock.setTime(Date.parse(NOW));
1047
+ const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1048
+ const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1049
+ const fixture = yield* makeHarness({
1050
+ snapshot: makeSnapshot([
1051
+ makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1052
+ ]),
1053
+ summary: (input) =>
1054
+ Ref.get(state).pipe(
1055
+ Effect.map((current) =>
1056
+ makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1057
),
1094
- invalidate: ({ reference }) =>
1095
- Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1096
- });
1058
+ ),
1059
+ invalidate: ({ reference }) =>
1060
+ Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1061
+ });
1062
1098
- yield* Effect.gen(function* () {
1099
- const reactor = yield* startAndSweep(fixture);
1100
- yield* Ref.set(state, "merged");
1063
+ yield* Effect.gen(function* () {
1064
+ const reactor = yield* startAndSweep(fixture);
1065
+ yield* Ref.set(state, "merged");
1066
1102
- yield* Queue.offer(fixture.stateChanges, {
1103
- host: "github.com",
1104
- repository: "owner/repository",
1105
- number: 7,
1106
- });
1107
- yield* Queue.take(fixture.snapshotReads);
1108
- yield* reactor.drain;
1067
+ yield* Queue.offer(fixture.stateChanges, {
1068
+ host: "github.com",
1069
+ repository: "owner/repository",
1070
+ number: 7,
1071
+ });
1072
+ yield* Queue.take(fixture.snapshotReads);
1073
+ yield* reactor.drain;
1074
1110
- assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1111
- assert.deepStrictEqual(
1112
- (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
1113
- ["merged"],
1114
- );
1115
- }).pipe(Effect.provide(fixture.layer));
1116
- }),
1117
- ),
1075
+ assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1076
+ assert.deepStrictEqual(
1077
+ (yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.state),
1078
+ ["merged"],
1079
+ );
1080
+ }).pipe(Effect.provide(fixture.layer));
1081
+ }),
1082
);
1083
1084
it.effect.each([true, false])(
@@ -1155,826 +1119,837 @@ describe("PullRequestSyncReactor", () => {
1119
);
1120
1121
it.effect("preserves a refresh requested while an older host read is in flight", () =>
1158
- Effect.scoped(
1159
- Effect.gen(function* () {
1160
- yield* TestClock.setTime(Date.parse(NOW));
1161
- const reading = yield* Deferred.make<void>();
1162
- const release = yield* Deferred.make<void>();
1163
- let calls = 0;
1164
- const fixture = yield* makeHarness({
1165
- snapshot: makeSnapshot([]),
1166
- summary: (input) =>
1167
- Effect.gen(function* () {
1168
- calls += 1;
1169
- if (calls === 1) {
1170
- yield* Deferred.succeed(reading, undefined);
1171
- yield* Deferred.await(release);
1172
- }
1173
- return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
1174
- }),
1175
- });
1176
- yield* Effect.gen(function* () {
1177
- const reactor = yield* startAndSweep(fixture);
1178
- yield* Ref.set(
1179
- fixture.snapshots,
1180
- makeSnapshot([
1181
- makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
1182
- ]),
1183
- );
1184
- const key = { host: "github.com", repository: "owner/repository", number: 2 };
1185
- yield* reactor.requestSync(key);
1186
- yield* Deferred.await(reading);
1187
- yield* reactor.requestSync(key);
1188
- yield* Deferred.succeed(release, undefined);
1189
- yield* reactor.drain;
1190
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1191
- assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
1192
- }).pipe(Effect.provide(fixture.layer));
1193
- }),
1194
- ),
1122
+ Effect.gen(function* () {
1123
+ yield* TestClock.setTime(Date.parse(NOW));
1124
+ const reading = yield* Deferred.make<void>();
1125
+ const release = yield* Deferred.make<void>();
1126
+ let calls = 0;
1127
+ const fixture = yield* makeHarness({
1128
+ snapshot: makeSnapshot([]),
1129
+ summary: (input) =>
1130
+ Effect.gen(function* () {
1131
+ calls += 1;
1132
+ if (calls === 1) {
1133
+ yield* Deferred.succeed(reading, undefined);
1134
+ yield* Deferred.await(release);
1135
+ }
1136
+ return makeSummary(input, { state: calls === 1 ? "closed" : "open" });
1137
+ }),
1138
+ });
1139
+ yield* Effect.gen(function* () {
1140
+ const reactor = yield* startAndSweep(fixture);
1141
+ yield* Ref.set(
1142
+ fixture.snapshots,
1143
+ makeSnapshot([
1144
+ makeThread("closed", { pullRequests: [makeLink(2, { state: "closed" })] }),
1145
+ ]),
1146
+ );
1147
+ const key = { host: "github.com", repository: "owner/repository", number: 2 };
1148
+ yield* reactor.requestSync(key);
1149
+ yield* Deferred.await(reading);
1150
+ yield* reactor.requestSync(key);
1151
+ yield* Deferred.succeed(release, undefined);
1152
+ yield* reactor.drain;
1153
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1154
+ assert.strictEqual((yield* Ref.get(fixture.syncCommands)).at(-1)?.snapshot.state, "open");
1155
+ }).pipe(Effect.provide(fixture.layer));
1156
+ }),
1157
);
1158
1159
it.effect("reads a burst of requested links in one sweep", () =>
1198
- Effect.scoped(
1199
- Effect.gen(function* () {
1200
- yield* TestClock.setTime(Date.parse(NOW));
1201
- const reading = yield* Deferred.make<void>();
1202
- const release = yield* Deferred.make<void>();
1203
- const fixture = yield* makeHarness({
1204
- snapshot: makeSnapshot([]),
1205
- summary: (input) =>
1206
- Effect.gen(function* () {
1207
- if (input.number === 1) {
1208
- yield* Deferred.succeed(reading, undefined);
1209
- yield* Deferred.await(release);
1210
- }
1211
- return makeSummary(input);
1212
- }),
1213
- });
1214
- yield* Effect.gen(function* () {
1215
- const reactor = yield* startAndSweep(fixture);
1216
- yield* Ref.set(
1217
- fixture.snapshots,
1218
- makeSnapshot(
1219
- [1, 2, 3, 4].map((number) =>
1220
- makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
1221
- ),
1160
+ Effect.gen(function* () {
1161
+ yield* TestClock.setTime(Date.parse(NOW));
1162
+ const reading = yield* Deferred.make<void>();
1163
+ const release = yield* Deferred.make<void>();
1164
+ const fixture = yield* makeHarness({
1165
+ snapshot: makeSnapshot([]),
1166
+ summary: (input) =>
1167
+ Effect.gen(function* () {
1168
+ if (input.number === 1) {
1169
+ yield* Deferred.succeed(reading, undefined);
1170
+ yield* Deferred.await(release);
1171
+ }
1172
+ return makeSummary(input);
1173
+ }),
1174
+ });
1175
+ yield* Effect.gen(function* () {
1176
+ const reactor = yield* startAndSweep(fixture);
1177
+ yield* Ref.set(
1178
+ fixture.snapshots,
1179
+ makeSnapshot(
1180
+ [1, 2, 3, 4].map((number) =>
1181
+ makeThread(`thread-${number}`, { pullRequests: [makeLink(number)] }),
1182
),
1223
- );
1224
- const request = (number: number) =>
1225
- reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
1226
- yield* request(1);
1227
- yield* Deferred.await(reading);
1228
- yield* Effect.forEach([2, 3, 4], request, { discard: true });
1229
- yield* Deferred.succeed(release, undefined);
1230
- yield* reactor.drain;
1231
- assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
1232
- assert.deepStrictEqual(
1233
- (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
1234
- [1, 2, 3, 4],
1235
- );
1236
- }).pipe(Effect.provide(fixture.layer));
1237
- }),
1238
- ),
1183
+ ),
1184
+ );
1185
+ const request = (number: number) =>
1186
+ reactor.requestSync({ host: "github.com", repository: "owner/repository", number });
1187
+ yield* request(1);
1188
+ yield* Deferred.await(reading);
1189
+ yield* Effect.forEach([2, 3, 4], request, { discard: true });
1190
+ yield* Deferred.succeed(release, undefined);
1191
+ yield* reactor.drain;
1192
+ assert.strictEqual(yield* Queue.size(fixture.snapshotReads), 2);
1193
+ assert.deepStrictEqual(
1194
+ (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number).toSorted(),
1195
+ [1, 2, 3, 4],
1196
+ );
1197
+ }).pipe(Effect.provide(fixture.layer));
1198
+ }),
1199
);
1200
1201
it.effect("reads hosts that batch all at once and other hosts at the old sweep width", () =>
1242
- Effect.scoped(
1243
- Effect.gen(function* () {
1244
- yield* TestClock.setTime(Date.parse(NOW));
1245
- const numbers = Array.from({ length: 60 }, (_, index) => index + 1);
1246
- const hostOf = (number: number) => (number <= 30 ? "github.com" : "gitlab.example.com");
1247
- const batches = (input: PullRequestRef) => input.host === "github.com";
1248
- const batched = yield* Ref.make(0);
1249
- const unbatched = yield* Ref.make(0);
1250
- const started = yield* Queue.unbounded<void>();
1251
- const release = yield* Deferred.make<void>();
1252
- const fixture = yield* makeHarness({
1253
- snapshot: makeSnapshot(
1254
- numbers.map((number) =>
1255
- makeThread(`thread-${number}`, {
1256
- pullRequests: [makeLink(number, null, { host: hostOf(number) })],
1257
- }),
1258
- ),
1202
+ Effect.gen(function* () {
1203
+ yield* TestClock.setTime(Date.parse(NOW));
1204
+ const numbers = Array.from({ length: 60 }, (_, index) => index + 1);
1205
+ const hostOf = (number: number) => (number <= 30 ? "github.com" : "gitlab.example.com");
1206
+ const batches = (input: PullRequestRef) => input.host === "github.com";
1207
+ const batched = yield* Ref.make(0);
1208
+ const unbatched = yield* Ref.make(0);
1209
+ const started = yield* Queue.unbounded<void>();
1210
+ const release = yield* Deferred.make<void>();
1211
+ const fixture = yield* makeHarness({
1212
+ snapshot: makeSnapshot(
1213
+ numbers.map((number) =>
1214
+ makeThread(`thread-${number}`, {
1215
+ pullRequests: [makeLink(number, null, { host: hostOf(number) })],
1216
+ }),
1217
),
1260
- batchesReads: batches,
1261
- summary: (input) => {
1262
- const inFlight = batches(input) ? batched : unbatched;
1263
- return Ref.update(inFlight, (count) => count + 1).pipe(
1264
- Effect.andThen(Queue.offer(started, undefined)),
1265
- Effect.andThen(Deferred.await(release)),
1266
- Effect.andThen(Ref.update(inFlight, (count) => count - 1)),
1267
- Effect.as(makeSummary(input)),
1268
- );
1269
- },
1270
- });
1271
- yield* Effect.gen(function* () {
1272
- const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
1273
- yield* reactor.start();
1274
- yield* Deferred.succeed(fixture.activation, undefined);
1275
- yield* Queue.takeN(started, 55);
1276
- assert.strictEqual(yield* Ref.get(batched), 30);
1277
- assert.strictEqual(yield* Ref.get(unbatched), 25);
1278
- yield* Deferred.succeed(release, undefined);
1279
- yield* reactor.drain;
1280
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, numbers.length);
1281
- }).pipe(Effect.provide(fixture.layer));
1282
- }),
1283
- ),
1218
+ ),
1219
+ batchesReads: batches,
1220
+ summary: (input) => {
1221
+ const inFlight = batches(input) ? batched : unbatched;
1222
+ return Ref.update(inFlight, (count) => count + 1).pipe(
1223
+ Effect.andThen(Queue.offer(started, undefined)),
1224
+ Effect.andThen(Deferred.await(release)),
1225
+ Effect.andThen(Ref.update(inFlight, (count) => count - 1)),
1226
+ Effect.as(makeSummary(input)),
1227
+ );
1228
+ },
1229
+ });
1230
+ yield* Effect.gen(function* () {
1231
+ const reactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
1232
+ yield* reactor.start();
1233
+ yield* Deferred.succeed(fixture.activation, undefined);
1234
+ yield* Queue.takeN(started, 55);
1235
+ assert.strictEqual(yield* Ref.get(batched), 30);
1236
+ assert.strictEqual(yield* Ref.get(unbatched), 25);
1237
+ yield* Deferred.succeed(release, undefined);
1238
+ yield* reactor.drain;
1239
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, numbers.length);
1240
+ }).pipe(Effect.provide(fixture.layer));
1241
+ }),
1242
);
1243
1244
it.effect("reads a member a sibling flags while the sweep is full", () =>
1287
- Effect.scoped(
1288
- Effect.gen(function* () {
1289
- yield* TestClock.setTime(Date.parse(NOW));
1290
- const stackOf = (layers: ReadonlyArray<number>) => ({
1291
- id: "9",
1292
- number: 9,
1293
- url: "https://github.com/owner/repository/stack/9",
1294
- base: "main",
1295
- layers: layers.map(stackLayer),
1296
- });
1297
- // #50 is merged and not due until #1's stack read shows it a different layer list.
1298
- const merged = makeLink(
1299
- 50,
1300
- { state: "merged", mergedAt: NOW },
1301
- { stack: { kind: "native", ...stackOf([50]) } },
1302
- );
1303
- const started = yield* Ref.make(0);
1304
- const full = yield* Deferred.make<void>();
1305
- const synced1 = yield* Deferred.make<void>();
1306
- const fixture = yield* makeHarness({
1307
- snapshot: makeSnapshot([
1308
- // Another host takes 24 of the 25 shared slots and #1 the last one.
1309
- ...Array.from({ length: 24 }, (_, index) =>
1310
- makeThread(`thread-${index + 2}`, {
1311
- pullRequests: [makeLink(index + 2, null, { host: "gitlab.example.com" })],
1312
- }),
1245
+ Effect.gen(function* () {
1246
+ yield* TestClock.setTime(Date.parse(NOW));
1247
+ const stackOf = (layers: ReadonlyArray<number>) => ({
1248
+ id: "9",
1249
+ number: 9,
1250
+ url: "https://github.com/owner/repository/stack/9",
1251
+ base: "main",
1252
+ layers: layers.map(stackLayer),
1253
+ });
1254
+ // #50 is merged and not due until #1's stack read shows it a different layer list.
1255
+ const merged = makeLink(
1256
+ 50,
1257
+ { state: "merged", mergedAt: NOW },
1258
+ { stack: { kind: "native", ...stackOf([50]) } },
1259
+ );
1260
+ const started = yield* Ref.make(0);
1261
+ const full = yield* Deferred.make<void>();
1262
+ const synced1 = yield* Deferred.make<void>();
1263
+ const fixture = yield* makeHarness({
1264
+ snapshot: makeSnapshot([
1265
+ // Another host takes 24 of the 25 shared slots and #1 the last one.
1266
+ ...Array.from({ length: 24 }, (_, index) =>
1267
+ makeThread(`thread-${index + 2}`, {
1268
+ pullRequests: [makeLink(index + 2, null, { host: "gitlab.example.com" })],
1269
+ }),
1270
+ ),
1271
+ makeThread("thread-1", { pullRequests: [makeLink(1)] }),
1272
+ makeThread("thread-50", { pullRequests: [merged] }),
1273
+ ]),
1274
+ batchesReads: () => false,
1275
+ // #1 reads once all 25 slots are taken; the other 24 hold theirs until #1 has synced.
1276
+ summary: (input) =>
1277
+ Ref.updateAndGet(started, (count) => count + 1).pipe(
1278
+ // Forked, so #1 resumes only after the sweep has handed out its next slot.
1279
+ Effect.tap((count) =>
1280
+ count === 25 ? Effect.forkChild(Deferred.succeed(full, undefined)) : Effect.void,
1281
),
1314
- makeThread("thread-1", { pullRequests: [makeLink(1)] }),
1315
- makeThread("thread-50", { pullRequests: [merged] }),
1316
- ]),
1317
- batchesReads: () => false,
1318
- // #1 reads once all 25 slots are taken; the other 24 hold theirs until #1 has synced.
1319
- summary: (input) =>
1320
- Ref.updateAndGet(started, (count) => count + 1).pipe(
1321
- // Forked, so #1 resumes only after the sweep has handed out its next slot.
1322
- Effect.tap((count) =>
1323
- count === 25 ? Effect.forkChild(Deferred.succeed(full, undefined)) : Effect.void,
1324
- ),
1325
- Effect.andThen(
1326
- input.number === 50
1327
- ? Effect.void
1328
- : Deferred.await(input.number === 1 ? full : synced1),
1329
- ),
1330
- Effect.as(makeSummary(input)),
1282
+ Effect.andThen(
1283
+ input.number === 50
1284
+ ? Effect.void
1285
+ : Deferred.await(input.number === 1 ? full : synced1),
1286
),
1332
- stack: (input) => Effect.succeed(input.number === 1 ? stackOf([1, 50]) : null),
1333
- onSync: (command) =>
1334
- command.number === 1 ? Deferred.succeed(synced1, undefined) : Effect.void,
1335
- });
1336
- yield* Effect.gen(function* () {
1337
- yield* startAndSweep(fixture);
1338
- const read = (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number);
1339
- assert.include(read, 50);
1340
- }).pipe(Effect.provide(fixture.layer));
1341
- }),
1342
- ),
1287
+ Effect.as(makeSummary(input)),
1288
+ ),
1289
+ stack: (input) => Effect.succeed(input.number === 1 ? stackOf([1, 50]) : null),
1290
+ onSync: (command) =>
1291
+ command.number === 1 ? Deferred.succeed(synced1, undefined) : Effect.void,
1292
+ });
1293
+ yield* Effect.gen(function* () {
1294
+ yield* startAndSweep(fixture);
1295
+ const read = (yield* Ref.get(fixture.summaryCalls)).map((ref) => ref.number);
1296
+ assert.include(read, 50);
1297
+ }).pipe(Effect.provide(fixture.layer));
1298
+ }),
1299
);
1300
1301
it.effect("skips the stack read for a pull request the summary places in no stack", () =>
1346
- Effect.scoped(
1347
- Effect.gen(function* () {
1348
- yield* TestClock.setTime(Date.parse(NOW));
1349
- const fixture = yield* makeHarness({
1350
- snapshot: makeSnapshot([
1351
- makeThread("unstacked", { pullRequests: [makeLink(1)] }),
1352
- makeThread("stacked", { pullRequests: [makeLink(2)] }),
1353
- makeThread("unknown", { pullRequests: [makeLink(3)] }),
1354
- ]),
1355
- summary: (input) =>
1356
- Effect.succeed(
1357
- makeSummary(
1358
- input,
1359
- input.number === 1
1360
- ? { stack: null }
1361
- : input.number === 2
1362
- ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
1363
- : {},
1364
- ),
1302
+ Effect.gen(function* () {
1303
+ yield* TestClock.setTime(Date.parse(NOW));
1304
+ const fixture = yield* makeHarness({
1305
+ snapshot: makeSnapshot([
1306
+ makeThread("unstacked", { pullRequests: [makeLink(1)] }),
1307
+ makeThread("stacked", { pullRequests: [makeLink(2)] }),
1308
+ makeThread("unknown", { pullRequests: [makeLink(3)] }),
1309
+ ]),
1310
+ summary: (input) =>
1311
+ Effect.succeed(
1312
+ makeSummary(
1313
+ input,
1314
+ input.number === 1
1315
+ ? { stack: null }
1316
+ : input.number === 2
1317
+ ? { stack: { number: 9, position: 1, size: 2, base: "main" } }
1318
+ : {},
1319
),
1366
- });
1367
- yield* Effect.gen(function* () {
1368
- yield* startAndSweep(fixture);
1369
- assert.deepStrictEqual(
1370
- (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1371
- [2, 3],
1372
- );
1373
- assert.deepStrictEqual(
1374
- (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1375
- [1, 2, 3],
1376
- );
1377
- }).pipe(Effect.provide(fixture.layer));
1378
- }),
1379
- ),
1320
+ ),
1321
+ });
1322
+ yield* Effect.gen(function* () {
1323
+ yield* startAndSweep(fixture);
1324
+ assert.deepStrictEqual(
1325
+ (yield* Ref.get(fixture.stackCalls)).map((ref) => ref.number).toSorted(),
1326
+ [2, 3],
1327
+ );
1328
+ assert.deepStrictEqual(
1329
+ (yield* Ref.get(fixture.syncCommands)).map((command) => command.number).toSorted(),
1330
+ [1, 2, 3],
1331
+ );
1332
+ }).pipe(Effect.provide(fixture.layer));
1333
+ }),
1334
);
1335
1336
it.effect("reads a settled thread's links once when it settles, then until unsettled", () =>
1383
- Effect.scoped(
1384
- Effect.gen(function* () {
1385
- yield* TestClock.setTime(Date.parse(NOW));
1386
- const fixture = yield* makeHarness({
1387
- snapshot: makeSnapshot([
1388
- makeThread("settled", {
1389
- settledOverride: "settled",
1390
- settledAt: "2026-08-21T00:00:00.000Z",
1391
- pullRequests: [
1392
- makeLink(5, { state: "open" }),
1393
- makeLink(6, { state: "closed" }),
1394
- makeLink(7),
1395
- ],
1396
- }),
1397
- ]),
1398
- });
1399
-
1400
- yield* Effect.gen(function* () {
1401
- const reactor = yield* startAndSweep(fixture);
1402
- assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1403
-
1404
- const threadId = ThreadId.make("settled");
1405
- const at = DateTime.makeUnsafe(NOW);
1406
- yield* Queue.offer(fixture.domainEvents, {
1407
- type: "thread.settled",
1408
- id: EventId.make("event:settled"),
1409
- threadId,
1410
- occurredAt: at,
1411
- payload: {
1412
- createdBy: "user",
1413
- creationSource: "web",
1414
- id: threadId,
1415
- projectId: PROJECT_ID,
1416
- title: "settled",
1417
- providerInstanceId: ProviderInstanceId.make("codex"),
1418
- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1419
- runtimeMode: "full-access",
1420
- interactionMode: "default",
1421
- branch: null,
1422
- worktreePath: null,
1423
- activeProviderThreadId: null,
1424
- lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1425
- forkedFrom: null,
1426
- createdAt: at,
1427
- updatedAt: at,
1428
- archivedAt: null,
1429
- settledOverride: "settled",
1430
- settledAt: at,
1431
- lastVisitedAt: null,
1432
- deletedAt: null,
1433
- },
1434
- });
1435
- yield* Queue.take(fixture.snapshotReads);
1436
- yield* Queue.take(fixture.snapshotReads);
1437
- yield* reactor.drain;
1438
- assert.deepStrictEqual(
1439
- (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(),
1440
- [5, 6],
1441
- );
1442
- for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1443
- assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1337
+ Effect.gen(function* () {
1338
+ yield* TestClock.setTime(Date.parse(NOW));
1339
+ const fixture = yield* makeHarness({
1340
+ snapshot: makeSnapshot([
1341
+ makeThread("settled", {
1342
+ settledOverride: "settled",
1343
+ settledAt: "2026-08-21T00:00:00.000Z",
1344
+ pullRequests: [
1345
+ makeLink(5, { state: "open" }),
1346
+ makeLink(6, { state: "closed" }),
1347
+ makeLink(7),
1348
+ ],
1349
+ }),
1350
+ ]),
1351
+ });
1352
1445
- yield* Ref.update(fixture.snapshots, (snapshot) => ({
1446
- ...snapshot,
1447
- threads: snapshot.threads.map((thread) => ({
1448
- ...thread,
1449
- settledOverride: null,
1450
- settledAt: null,
1451
- })),
1452
- }));
1453
- yield* sweepAgain(fixture, reactor);
1454
- assert.deepStrictEqual(
1455
- (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1456
- [5, 6, 7],
1457
- );
1458
- }).pipe(Effect.provide(fixture.layer));
1459
- }),
1460
- ),
1353
+ yield* Effect.gen(function* () {
1354
+ const reactor = yield* startAndSweep(fixture);
1355
+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1356
+
1357
+ const threadId = ThreadId.make("settled");
1358
+ const at = DateTime.makeUnsafe(NOW);
1359
+ yield* Queue.offer(fixture.domainEvents, {
1360
+ type: "thread.settled",
1361
+ id: EventId.make("event:settled"),
1362
+ threadId,
1363
+ occurredAt: at,
1364
+ payload: {
1365
+ createdBy: "user",
1366
+ creationSource: "web",
1367
+ id: threadId,
1368
+ projectId: PROJECT_ID,
1369
+ title: "settled",
1370
+ providerInstanceId: ProviderInstanceId.make("codex"),
1371
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
1372
+ runtimeMode: "full-access",
1373
+ interactionMode: "default",
1374
+ branch: null,
1375
+ worktreePath: null,
1376
+ activeProviderThreadId: null,
1377
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
1378
+ forkedFrom: null,
1379
+ createdAt: at,
1380
+ updatedAt: at,
1381
+ archivedAt: null,
1382
+ settledOverride: "settled",
1383
+ settledAt: at,
1384
+ lastVisitedAt: null,
1385
+ deletedAt: null,
1386
+ },
1387
+ });
1388
+ yield* Queue.take(fixture.snapshotReads);
1389
+ yield* Queue.take(fixture.snapshotReads);
1390
+ yield* reactor.drain;
1391
+ assert.deepStrictEqual(
1392
+ (yield* Ref.getAndSet(fixture.summaryCalls, [])).map((call) => call.number).toSorted(),
1393
+ [5, 6],
1394
+ );
1395
+ for (let index = 0; index < 15; index += 1) yield* sweepAgain(fixture, reactor);
1396
+ assert.deepStrictEqual(yield* Ref.get(fixture.summaryCalls), []);
1397
+
1398
+ yield* Ref.update(fixture.snapshots, (snapshot) => ({
1399
+ ...snapshot,
1400
+ threads: snapshot.threads.map((thread) => ({
1401
+ ...thread,
1402
+ settledOverride: null,
1403
+ settledAt: null,
1404
+ })),
1405
+ }));
1406
+ yield* sweepAgain(fixture, reactor);
1407
+ assert.deepStrictEqual(
1408
+ (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number).toSorted(),
1409
+ [5, 6, 7],
1410
+ );
1411
+ }).pipe(Effect.provide(fixture.layer));
1412
+ }),
1413
);
1414
1415
it.effect("auto-links missing native stack layers on active threads only", () =>
1464
- Effect.scoped(
1465
- Effect.gen(function* () {
1466
- yield* TestClock.setTime(Date.parse(NOW));
1467
- const stack: PullRequestStack = {
1468
- id: "stack-1",
1469
- number: 42,
1470
- url: "https://github.com/owner/repository/stack/1",
1471
- base: "main",
1472
- layers: [
1473
- { number: 41, headBranch: "layer-1", state: "merged" },
1474
- { number: 42, headBranch: "layer-2", state: "open" },
1475
- { number: 43, headBranch: "layer-3", state: "open" },
1476
- ],
1477
- };
1478
- const fixture = yield* makeHarness({
1479
- snapshot: makeSnapshot([
1480
- makeThread("one", {
1481
- pullRequests: [
1482
- makeLink(42),
1483
- makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1484
- ],
1485
- }),
1486
- makeThread("settled", {
1487
- settledOverride: "settled",
1488
- settledAt: "2026-08-21T00:00:00.000Z",
1489
- pullRequests: [makeLink(42)],
1490
- }),
1491
- ]),
1492
- stack: () => Effect.succeed(stack),
1493
- });
1416
+ Effect.gen(function* () {
1417
+ yield* TestClock.setTime(Date.parse(NOW));
1418
+ const stack: PullRequestStack = {
1419
+ id: "stack-1",
1420
+ number: 42,
1421
+ url: "https://github.com/owner/repository/stack/1",
1422
+ base: "main",
1423
+ layers: [
1424
+ { number: 41, headBranch: "layer-1", state: "merged" },
1425
+ { number: 42, headBranch: "layer-2", state: "open" },
1426
+ { number: 43, headBranch: "layer-3", state: "open" },
1427
+ ],
1428
+ };
1429
+ const fixture = yield* makeHarness({
1430
+ snapshot: makeSnapshot([
1431
+ makeThread("one", {
1432
+ pullRequests: [
1433
+ makeLink(42),
1434
+ makeLink(41, { state: "merged" }, { source: "stack-dismissed" }),
1435
+ ],
1436
+ }),
1437
+ makeThread("settled", {
1438
+ settledOverride: "settled",
1439
+ settledAt: "2026-08-21T00:00:00.000Z",
1440
+ pullRequests: [makeLink(42)],
1441
+ }),
1442
+ ]),
1443
+ stack: () => Effect.succeed(stack),
1444
+ });
1445
1495
- yield* Effect.gen(function* () {
1496
- yield* startAndSweep(fixture);
1446
+ yield* Effect.gen(function* () {
1447
+ yield* startAndSweep(fixture);
1448
1498
- const syncCommands = yield* Ref.get(fixture.syncCommands);
1499
- assert.deepStrictEqual(
1500
- syncCommands.map((command) => [command.threadId, command.stack] as const),
1501
- [
1502
- [ThreadId.make("one"), { kind: "native", ...stack }],
1503
- [ThreadId.make("settled"), { kind: "native", ...stack }],
1504
- ],
1505
- );
1506
- assert.deepStrictEqual(
1507
- (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1508
- [
1509
- {
1510
- type: "thread.pull-request.link",
1511
- threadId: ThreadId.make("one"),
1512
- host: "github.com",
1513
- repository: "owner/repository",
1514
- number: 43,
1515
- url: "https://github.com/owner/repository/pull/43",
1516
- source: "stack",
1517
- },
1518
- ],
1519
- );
1520
- }).pipe(Effect.provide(fixture.layer));
1521
- }),
1522
- ),
1449
+ const syncCommands = yield* Ref.get(fixture.syncCommands);
1450
+ assert.deepStrictEqual(
1451
+ syncCommands.map((command) => [command.threadId, command.stack] as const),
1452
+ [
1453
+ [ThreadId.make("one"), { kind: "native", ...stack }],
1454
+ [ThreadId.make("settled"), { kind: "native", ...stack }],
1455
+ ],
1456
+ );
1457
+ assert.deepStrictEqual(
1458
+ (yield* Ref.get(fixture.linkCommands)).map(({ commandId: _, ...rest }) => rest),
1459
+ [
1460
+ {
1461
+ type: "thread.pull-request.link",
1462
+ threadId: ThreadId.make("one"),
1463
+ host: "github.com",
1464
+ repository: "owner/repository",
1465
+ number: 43,
1466
+ url: "https://github.com/owner/repository/pull/43",
1467
+ source: "stack",
1468
+ },
1469
+ ],
1470
+ );
1471
+ }).pipe(Effect.provide(fixture.layer));
1472
+ }),
1473
);
1474
1475
it.effect("re-reads every member's layers once a new layer joins the stack", () =>
1526
- Effect.scoped(
1527
- Effect.gen(function* () {
1528
- yield* TestClock.setTime(Date.parse(NOW));
1529
- const stack = makeGrowingStack();
1530
- const fixture = yield* makeHarness({
1531
- snapshot: makeSnapshot([
1532
- makeThread("one", { pullRequests: [makeLink(18), makeLink(20)] }),
1533
- ]),
1534
- stack: stack.read,
1535
- });
1536
- const sweepAndApply = (reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"]) =>
1537
- sweepAgain(fixture, reactor).pipe(Effect.andThen(applyRecordedSyncs(fixture)));
1538
-
1539
- yield* Effect.gen(function* () {
1540
- const reactor = yield* startAndSweep(fixture);
1541
- yield* applyRecordedSyncs(fixture);
1542
- assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1543
- [18, [18, 20]],
1544
- [20, [18, 20]],
1545
- ]);
1546
- const readsBeforeGrowth = (yield* Ref.get(fixture.stackCalls)).length;
1547
-
1548
- // #83 is pushed on top and linked; only its own link starts without a snapshot.
1549
- stack.grow();
1550
- yield* linkPullRequest83(fixture);
1551
- yield* sweepAndApply(reactor);
1552
- yield* sweepAndApply(reactor);
1553
-
1554
- assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1555
- [18, [18, 20, 83]],
1556
- [20, [18, 20, 83]],
1557
- [83, [18, 20, 83]],
1558
- ]);
1559
- const readsAfterGrowth = (yield* Ref.get(fixture.stackCalls)).slice(readsBeforeGrowth);
1560
- assert.deepStrictEqual(
1561
- readsAfterGrowth.map((ref) => ref.number).toSorted(),
1562
- [18, 20, 83],
1563
- );
1476
+ Effect.gen(function* () {
1477
+ yield* TestClock.setTime(Date.parse(NOW));
1478
+ const stack = makeGrowingStack();
1479
+ const fixture = yield* makeHarness({
1480
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18), makeLink(20)] })]),
1481
+ stack: stack.read,
1482
+ });
1483
+ const sweepAndApply = (reactor: PullRequestSyncReactor.PullRequestSyncReactor["Service"]) =>
1484
+ sweepAgain(fixture, reactor).pipe(Effect.andThen(applyRecordedSyncs(fixture)));
1485
1565
- // Every member agrees now, so a further sweep reads no stack.
1566
- yield* sweepAndApply(reactor);
1567
- assert.strictEqual(
1568
- (yield* Ref.get(fixture.stackCalls)).length,
1569
- readsBeforeGrowth + readsAfterGrowth.length,
1570
- );
1571
- }).pipe(Effect.provide(fixture.layer));
1572
- }),
1573
- ),
1486
+ yield* Effect.gen(function* () {
1487
+ const reactor = yield* startAndSweep(fixture);
1488
+ yield* applyRecordedSyncs(fixture);
1489
+ assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1490
+ [18, [18, 20]],
1491
+ [20, [18, 20]],
1492
+ ]);
1493
+ const readsBeforeGrowth = (yield* Ref.get(fixture.stackCalls)).length;
1494
+
1495
+ // #83 is pushed on top and linked; only its own link starts without a snapshot.
1496
+ stack.grow();
1497
+ yield* linkPullRequest83(fixture);
1498
+ yield* sweepAndApply(reactor);
1499
+ yield* sweepAndApply(reactor);
1500
+
1501
+ assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1502
+ [18, [18, 20, 83]],
1503
+ [20, [18, 20, 83]],
1504
+ [83, [18, 20, 83]],
1505
+ ]);
1506
+ const readsAfterGrowth = (yield* Ref.get(fixture.stackCalls)).slice(readsBeforeGrowth);
1507
+ assert.deepStrictEqual(readsAfterGrowth.map((ref) => ref.number).toSorted(), [18, 20, 83]);
1508
+
1509
+ // Every member agrees now, so a further sweep reads no stack.
1510
+ yield* sweepAndApply(reactor);
1511
+ assert.strictEqual(
1512
+ (yield* Ref.get(fixture.stackCalls)).length,
1513
+ readsBeforeGrowth + readsAfterGrowth.length,
1514
+ );
1515
+ }).pipe(Effect.provide(fixture.layer));
1516
+ }),
1517
);
1518
1519
it.effect("reads past the cache when a sibling flags a member during its summary read", () =>
1577
- Effect.scoped(
1578
- Effect.gen(function* () {
1579
- yield* TestClock.setTime(Date.parse(NOW));
1580
- const stack = makeGrowingStack();
1581
- const synced83 = yield* Deferred.make<void>();
1582
- let holdSummary = false;
1583
- const fixture = yield* makeHarness({
1584
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18)] })]),
1585
- invalidate: stack.invalidate,
1586
- stack: stack.cachedRead,
1587
- // #18's summary stays in flight until #83 has read its stack, flagged #18 and synced.
1588
- summary: (input) =>
1589
- (holdSummary && input.number === 18 ? Deferred.await(synced83) : Effect.void).pipe(
1590
- Effect.as(makeSummary(input, { updatedAt: NOW })),
1591
- ),
1592
- onSync: (command) =>
1593
- command.number === 83 ? Deferred.succeed(synced83, undefined) : Effect.void,
1594
- });
1595
-
1596
- yield* Effect.gen(function* () {
1597
- const reactor = yield* startAndSweep(fixture);
1598
- yield* applyRecordedSyncs(fixture);
1599
-
1600
- // 30 s later a state change refreshes #18, which caches its two-layer read until 90 s.
1601
- yield* TestClock.adjust("30 seconds");
1602
- yield* requestAndApply(fixture, reactor, 18);
1603
-
1604
- // #83 is pushed on top and linked as the scheduled sweep at 60 s starts, so that sweep
1605
- // reads #83 for the first time while #18's summary is still in flight.
1606
- stack.grow();
1607
- yield* linkPullRequest83(fixture);
1608
- holdSummary = true;
1609
- const invalidatedBefore = stack.invalidated.length;
1610
- yield* TestClock.adjust("30 seconds");
1611
- yield* Queue.take(fixture.snapshotReads);
1612
- yield* reactor.drain;
1613
- yield* applyRecordedSyncs(fixture);
1614
-
1615
- assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1616
- [18, [18, 20, 83]],
1617
- [83, [18, 20, 83]],
1618
- ]);
1619
- assert.deepStrictEqual(stack.invalidated.slice(invalidatedBefore), [18]);
1620
- }).pipe(Effect.provide(fixture.layer));
1621
- }),
1622
- ),
1520
+ Effect.gen(function* () {
1521
+ yield* TestClock.setTime(Date.parse(NOW));
1522
+ const stack = makeGrowingStack();
1523
+ const synced83 = yield* Deferred.make<void>();
1524
+ let holdSummary = false;
1525
+ const fixture = yield* makeHarness({
1526
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(18)] })]),
1527
+ invalidate: stack.invalidate,
1528
+ stack: stack.cachedRead,
1529
+ // #18's summary stays in flight until #83 has read its stack, flagged #18 and synced.
1530
+ summary: (input) =>
1531
+ (holdSummary && input.number === 18 ? Deferred.await(synced83) : Effect.void).pipe(
1532
+ Effect.as(makeSummary(input, { updatedAt: NOW })),
1533
+ ),
1534
+ onSync: (command) =>
1535
+ command.number === 83 ? Deferred.succeed(synced83, undefined) : Effect.void,
1536
+ });
1537
+
1538
+ yield* Effect.gen(function* () {
1539
+ const reactor = yield* startAndSweep(fixture);
1540
+ yield* applyRecordedSyncs(fixture);
1541
+
1542
+ // 30 s later a state change refreshes #18, which caches its two-layer read until 90 s.
1543
+ yield* TestClock.adjust("30 seconds");
1544
+ yield* requestAndApply(fixture, reactor, 18);
1545
+
1546
+ // #83 is pushed on top and linked as the scheduled sweep at 60 s starts, so that sweep
1547
+ // reads #83 for the first time while #18's summary is still in flight.
1548
+ stack.grow();
1549
+ yield* linkPullRequest83(fixture);
1550
+ holdSummary = true;
1551
+ const invalidatedBefore = stack.invalidated.length;
1552
+ yield* TestClock.adjust("30 seconds");
1553
+ yield* Queue.take(fixture.snapshotReads);
1554
+ yield* reactor.drain;
1555
+ yield* applyRecordedSyncs(fixture);
1556
+
1557
+ assert.deepStrictEqual(yield* storedStackLayers(fixture), [
1558
+ [18, [18, 20, 83]],
1559
+ [83, [18, 20, 83]],
1560
+ ]);
1561
+ assert.deepStrictEqual(stack.invalidated.slice(invalidatedBefore), [18]);
1562
+ }).pipe(Effect.provide(fixture.layer));
1563
+ }),
1564
);
1565
1566
it.effect("leaves stacks in other repositories alone when their ids match", () =>
1626
- Effect.scoped(
1627
- Effect.gen(function* () {
1628
- yield* TestClock.setTime(Date.parse(NOW));
1629
- // Without a host id the GitHub decoder falls back to the stack number, so two
1630
- // repositories can both report stack "3".
1631
- const otherLink = makeLink(7, null, {
1632
- repository: "owner/other",
1633
- url: "https://github.com/owner/other/pull/7",
1634
- });
1635
- const fixture = yield* makeHarness({
1636
- snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(1), otherLink] })]),
1637
- stack: (input) =>
1638
- Effect.succeed({
1639
- id: "3",
1640
- number: 3,
1641
- url: `https://github.com/${input.repository}/stack/3`,
1642
- base: "main",
1643
- layers: [
1644
- { number: input.number, headBranch: "layer-1", state: "open" },
1645
- { number: input.number + 1, headBranch: "layer-2", state: "open" },
1646
- ],
1647
- }),
1648
- });
1567
+ Effect.gen(function* () {
1568
+ yield* TestClock.setTime(Date.parse(NOW));
1569
+ // Without a host id the GitHub decoder falls back to the stack number, so two
1570
+ // repositories can both report stack "3".
1571
+ const otherLink = makeLink(7, null, {
1572
+ repository: "owner/other",
1573
+ url: "https://github.com/owner/other/pull/7",
1574
+ });
1575
+ const fixture = yield* makeHarness({
1576
+ snapshot: makeSnapshot([makeThread("one", { pullRequests: [makeLink(1), otherLink] })]),
1577
+ stack: (input) =>
1578
+ Effect.succeed({
1579
+ id: "3",
1580
+ number: 3,
1581
+ url: `https://github.com/${input.repository}/stack/3`,
1582
+ base: "main",
1583
+ layers: [
1584
+ { number: input.number, headBranch: "layer-1", state: "open" },
1585
+ { number: input.number + 1, headBranch: "layer-2", state: "open" },
1586
+ ],
1587
+ }),
1588
+ });
1589
1650
- yield* Effect.gen(function* () {
1651
- const reactor = yield* startAndSweep(fixture);
1652
- yield* applyRecordedSyncs(fixture);
1653
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1590
+ yield* Effect.gen(function* () {
1591
+ const reactor = yield* startAndSweep(fixture);
1592
+ yield* applyRecordedSyncs(fixture);
1593
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1594
1655
- yield* sweepAgain(fixture, reactor);
1656
- yield* sweepAgain(fixture, reactor);
1657
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1658
- }).pipe(Effect.provide(fixture.layer));
1659
- }),
1660
- ),
1595
+ yield* sweepAgain(fixture, reactor);
1596
+ yield* sweepAgain(fixture, reactor);
1597
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 2);
1598
+ }).pipe(Effect.provide(fixture.layer));
1599
+ }),
1600
);
1601
1602
it.effect("keeps existing snapshots and continues when the host fails", () =>
1664
- Effect.scoped(
1665
- Effect.gen(function* () {
1666
- yield* TestClock.setTime(Date.parse(NOW));
1667
- const fixture = yield* makeHarness({
1668
- snapshot: makeSnapshot([
1669
- makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1670
- makeThread("fine", { pullRequests: [makeLink(8)] }),
1671
- ]),
1672
- summary: (input) =>
1673
- input.number === 7
1674
- ? Effect.fail(
1675
- new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1676
- )
1677
- : Effect.succeed(makeSummary(input)),
1678
- });
1603
+ Effect.gen(function* () {
1604
+ yield* TestClock.setTime(Date.parse(NOW));
1605
+ const fixture = yield* makeHarness({
1606
+ snapshot: makeSnapshot([
1607
+ makeThread("failing", { pullRequests: [makeLink(7, { state: "open" })] }),
1608
+ makeThread("fine", { pullRequests: [makeLink(8)] }),
1609
+ ]),
1610
+ summary: (input) =>
1611
+ input.number === 7
1612
+ ? Effect.fail(
1613
+ new PullRequestOperationError({ operation: "summary", detail: "host down" }),
1614
+ )
1615
+ : Effect.succeed(makeSummary(input)),
1616
+ });
1617
1680
- yield* Effect.gen(function* () {
1681
- yield* startAndSweep(fixture);
1618
+ yield* Effect.gen(function* () {
1619
+ yield* startAndSweep(fixture);
1620
1683
- assert.deepStrictEqual(
1684
- (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1685
- [8],
1686
- );
1687
- }).pipe(Effect.provide(fixture.layer));
1688
- }),
1689
- ),
1621
+ assert.deepStrictEqual(
1622
+ (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1623
+ [8],
1624
+ );
1625
+ }).pipe(Effect.provide(fixture.layer));
1626
+ }),
1627
);
1628
1629
it.effect(
1630
"retries missing links every fifteen minutes and resumes normal reads after recovery",
1631
() =>
1695
- Effect.scoped(
1696
- Effect.gen(function* () {
1697
- yield* TestClock.setTime(Date.parse(NOW));
1698
- const found = yield* Ref.make(false);
1699
- const fixture = yield* makeHarness({
1700
- snapshot: makeSnapshot([
1701
- makeThread("missing", { pullRequests: [makeLink(9), makeLink(10, {})] }),
1702
- ]),
1703
- summary: (input) =>
1704
- Ref.get(found).pipe(
1705
- Effect.flatMap((available) =>
1706
- available ? Effect.succeed(makeSummary(input)) : missingSummary,
1707
- ),
1708
- ),
1709
- });
1710
- yield* Effect.gen(function* () {
1711
- const reactor = yield* startAndSweep(fixture);
1712
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1713
- for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
1714
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1715
- yield* sweepAgain(fixture, reactor);
1716
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1717
- assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
1718
-
1719
- yield* Ref.set(found, true);
1720
- for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
1721
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1722
- yield* sweepAgain(fixture, reactor);
1723
- const commands = yield* Ref.get(fixture.syncCommands);
1724
- assert.deepStrictEqual(
1725
- commands.map((command) => command.number),
1726
- [9],
1727
- );
1728
- yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
1729
- // Recovered quiet open pull requests return to the five-minute cadence.
1730
- for (let index = 0; index < 5; index += 1) yield* sweepAgain(fixture, reactor);
1731
- assert.deepStrictEqual(
1732
- (yield* Ref.get(fixture.summaryCalls))
1733
- .map((call) => call.number)
1734
- .toSorted((left, right) => left - right),
1735
- [9, 9, 9, 9, 10, 10, 10, 10],
1736
- );
1737
- }).pipe(Effect.provide(fixture.layer));
1738
- }),
1739
- ),
1740
- );
1741
-
1742
- it.effect(
1743
- "holds missing links through sibling and link updates but honors a reader refresh",
1744
- () =>
1745
- Effect.scoped(
1746
- Effect.gen(function* () {
1747
- yield* TestClock.setTime(Date.parse(NOW));
1748
- const fixture = yield* makeHarness({
1749
- snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(9)] })]),
1750
- summary: (input) =>
1751
- input.number === 9 ? missingSummary : Effect.succeed(makeSummary(input)),
1752
- });
1753
- const missingReads = Ref.get(fixture.summaryCalls).pipe(
1754
- Effect.map((calls) => calls.filter((call) => call.number === 9).length),
1755
- );
1756
- yield* Effect.gen(function* () {
1757
- const reactor = yield* startAndSweep(fixture);
1758
- const linked = makeThread("missing", { pullRequests: [makeLink(9), makeLink(8)] });
1759
- yield* Ref.set(fixture.snapshots, makeSnapshot([linked]));
1760
- yield* Queue.offer(fixture.domainEvents, {
1761
- type: "thread.pull-request-synced",
1762
- id: EventId.make("sibling-synced"),
1763
- threadId: linked.id,
1764
- occurredAt: DateTime.makeUnsafe(NOW),
1765
- payload: { ...v2PullRequestThread(linked), lastVisitedAt: null },
1766
- });
1767
- yield* Queue.take(fixture.snapshotReads);
1768
- yield* reactor.drain;
1769
- const afterSiblingSync = yield* missingReads;
1770
- assert.deepStrictEqual(
1771
- (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1772
- [8],
1773
- );
1774
-
1775
- yield* Queue.offer(fixture.domainEvents, {
1776
- type: "thread.pull-request-link-updated",
1777
- id: EventId.make("missing-link-updated"),
1778
- threadId: linked.id,
1779
- occurredAt: DateTime.makeUnsafe(NOW),
1780
- payload: makeLink(9),
1781
- });
1782
- // Let the event consumer finish even when it correctly queues no sweep.
1783
- yield* TestClock.adjust(0);
1784
- yield* reactor.drain;
1785
- const afterLinkUpdate = yield* missingReads;
1786
-
1787
- yield* Queue.offer(fixture.stateChanges, makeLink(9));
1788
- yield* TestClock.adjust(0);
1789
- yield* reactor.drain;
1790
- const afterReaderRefresh = yield* missingReads;
1791
- yield* sweepAgain(fixture, reactor);
1792
- assert.deepStrictEqual(
1793
- {
1794
- afterSiblingSync,
1795
- afterLinkUpdate,
1796
- afterReaderRefresh,
1797
- afterSweep: yield* missingReads,
1798
- },
1799
- { afterSiblingSync: 1, afterLinkUpdate: 1, afterReaderRefresh: 2, afterSweep: 2 },
1800
- );
1801
- }).pipe(Effect.provide(fixture.layer));
1802
- }),
1803
- ),
1804
- );
1805
-
1806
- it.effect("a pending stack retry respects the missing summary backoff", () =>
1807
- Effect.scoped(
1632
Effect.gen(function* () {
1633
yield* TestClock.setTime(Date.parse(NOW));
1810
- const found = yield* Ref.make(true);
1634
+ const found = yield* Ref.make(false);
1635
const fixture = yield* makeHarness({
1812
- snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(4)] })]),
1636
+ snapshot: makeSnapshot([
1637
+ makeThread("missing", { pullRequests: [makeLink(9), makeLink(10, {})] }),
1638
+ ]),
1639
summary: (input) =>
1640
Ref.get(found).pipe(
1641
Effect.flatMap((available) =>
1642
available ? Effect.succeed(makeSummary(input)) : missingSummary,
1643
),
1644
),
1819
- stack: () =>
1820
- Effect.fail(new PullRequestOperationError({ operation: "stack", detail: "host down" })),
1645
});
1646
yield* Effect.gen(function* () {
1647
const reactor = yield* startAndSweep(fixture);
1824
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
1825
- yield* Ref.set(found, false);
1826
- yield* sweepAgain(fixture, reactor);
1648
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1649
for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
1650
assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1651
yield* sweepAgain(fixture, reactor);
1831
- assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
1832
- assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
1652
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1653
+ assert.deepStrictEqual(yield* Ref.get(fixture.syncCommands), []);
1654
+
1655
+ yield* Ref.set(found, true);
1656
+ for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
1657
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 4);
1658
+ yield* sweepAgain(fixture, reactor);
1659
+ const commands = yield* Ref.get(fixture.syncCommands);
1660
+ assert.deepStrictEqual(
1661
+ commands.map((command) => command.number),
1662
+ [9],
1663
+ );
1664
+ yield* Ref.update(fixture.snapshots, (snapshot) => applySync(snapshot, commands));
1665
+ // Recovered quiet open pull requests return to the five-minute cadence.
1666
+ for (let index = 0; index < 5; index += 1) yield* sweepAgain(fixture, reactor);
1667
+ assert.deepStrictEqual(
1668
+ (yield* Ref.get(fixture.summaryCalls))
1669
+ .map((call) => call.number)
1670
+ .toSorted((left, right) => left - right),
1671
+ [9, 9, 9, 9, 10, 10, 10, 10],
1672
+ );
1673
}).pipe(Effect.provide(fixture.layer));
1674
}),
1835
- ),
1675
);
1676
1838
- it.effect.each([
1839
- "gh pr merge 7 --squash 2>&1 | tail -3",
1840
- "cafe pr merge 7 --squash",
1841
- "az repos pr update --id 7 --status completed",
1842
- ])("reads open links fresh only for a thread that ran `%s`", (mergeCommand) =>
1843
- Effect.scoped(
1677
+ it.effect(
1678
+ "holds missing links through sibling and link updates but honors a reader refresh",
1679
+ () =>
1680
Effect.gen(function* () {
1681
yield* TestClock.setTime(Date.parse(NOW));
1846
- const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1847
- const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1682
const fixture = yield* makeHarness({
1849
- snapshot: makeSnapshot([
1850
- makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1851
- makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1852
- ]),
1683
+ snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(9)] })]),
1684
summary: (input) =>
1854
- Ref.get(state).pipe(
1855
- Effect.map((current) =>
1856
- makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1857
- ),
1858
- ),
1859
- invalidate: ({ reference }) =>
1860
- Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1685
+ input.number === 9 ? missingSummary : Effect.succeed(makeSummary(input)),
1686
});
1862
-
1687
+ const missingReads = Ref.get(fixture.summaryCalls).pipe(
1688
+ Effect.map((calls) => calls.filter((call) => call.number === 9).length),
1689
+ );
1690
yield* Effect.gen(function* () {
1691
const reactor = yield* startAndSweep(fixture);
1865
- yield* Ref.set(state, "merged");
1866
- yield* Ref.set(fixture.summaryCalls, []);
1867
-
1868
- yield* Queue.offerAll(fixture.domainEvents, [
1869
- commandRan(ThreadId.make("other"), "gh pr view 9"),
1870
- runUpdated(ThreadId.make("other"), "completed"),
1871
- commandRan(ThreadId.make("agent"), mergeCommand),
1872
- runUpdated(ThreadId.make("agent"), "completed"),
1873
- ]);
1874
- yield* Queue.take(fixture.snapshotReads);
1692
+ const linked = makeThread("missing", { pullRequests: [makeLink(9), makeLink(8)] });
1693
+ yield* Ref.set(fixture.snapshots, makeSnapshot([linked]));
1694
+ yield* Queue.offer(fixture.domainEvents, {
1695
+ type: "thread.pull-request-synced",
1696
+ id: EventId.make("sibling-synced"),
1697
+ threadId: linked.id,
1698
+ occurredAt: DateTime.makeUnsafe(NOW),
1699
+ payload: { ...v2PullRequestThread(linked), lastVisitedAt: null },
1700
+ });
1701
yield* Queue.take(fixture.snapshotReads);
1702
yield* reactor.drain;
1877
-
1878
- assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1703
+ const afterSiblingSync = yield* missingReads;
1704
assert.deepStrictEqual(
1880
- (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1881
- [7],
1705
+ (yield* Ref.get(fixture.syncCommands)).map((command) => command.number),
1706
+ [8],
1707
);
1708
+
1709
+ yield* Queue.offer(fixture.domainEvents, {
1710
+ type: "thread.pull-request-link-updated",
1711
+ id: EventId.make("missing-link-updated"),
1712
+ threadId: linked.id,
1713
+ occurredAt: DateTime.makeUnsafe(NOW),
1714
+ payload: makeLink(9),
1715
+ });
1716
+ // Let the event consumer finish even when it correctly queues no sweep.
1717
+ yield* TestClock.adjust(0);
1718
+ yield* reactor.drain;
1719
+ const afterLinkUpdate = yield* missingReads;
1720
+
1721
+ yield* Queue.offer(fixture.stateChanges, makeLink(9));
1722
+ yield* TestClock.adjust(0);
1723
+ yield* reactor.drain;
1724
+ const afterReaderRefresh = yield* missingReads;
1725
+ yield* sweepAgain(fixture, reactor);
1726
assert.deepStrictEqual(
1884
- (yield* Ref.get(fixture.syncCommands)).map((command) => [
1885
- command.number,
1886
- command.snapshot.state,
1887
- ]),
1888
- [[7, "merged"]],
1727
+ {
1728
+ afterSiblingSync,
1729
+ afterLinkUpdate,
1730
+ afterReaderRefresh,
1731
+ afterSweep: yield* missingReads,
1732
+ },
1733
+ { afterSiblingSync: 1, afterLinkUpdate: 1, afterReaderRefresh: 2, afterSweep: 2 },
1734
);
1735
}).pipe(Effect.provide(fixture.layer));
1736
}),
1892
- ),
1737
);
1738
1895
- it.effect("reopens a watch's checks when its thread's agent pushes", () =>
1896
- Effect.scoped(
1897
- Effect.gen(function* () {
1898
- yield* TestClock.setTime(Date.parse(NOW));
1899
- const watch = {
1900
- startedAt: NOW,
1901
- headSha: "aaaaaaaaaa",
1902
- failedChecks: [],
1903
- passed: true,
1904
- passedChecks: ["test"],
1905
- remarksThrough: NOW,
1906
- remarkIds: [],
1907
- conflicting: false,
1908
- wakes: 0,
1909
- };
1910
- const fixture = yield* makeHarness({
1911
- snapshot: makeSnapshot([
1912
- makeThread("agent", {
1913
- pullRequests: [
1914
- makeLink(7, { state: "open" }, { watch: { ...watch, checksPending: false } }),
1915
- ],
1916
- }),
1917
- makeThread("unread", {
1918
- pullRequests: [makeLink(8, { state: "open" }, { watch })],
1919
- }),
1739
+ it.effect("a pending stack retry respects the missing summary backoff", () =>
1740
+ Effect.gen(function* () {
1741
+ yield* TestClock.setTime(Date.parse(NOW));
1742
+ const found = yield* Ref.make(true);
1743
+ const fixture = yield* makeHarness({
1744
+ snapshot: makeSnapshot([makeThread("missing", { pullRequests: [makeLink(4)] })]),
1745
+ summary: (input) =>
1746
+ Ref.get(found).pipe(
1747
+ Effect.flatMap((available) =>
1748
+ available ? Effect.succeed(makeSummary(input)) : missingSummary,
1749
+ ),
1750
+ ),
1751
+ stack: () =>
1752
+ Effect.fail(new PullRequestOperationError({ operation: "stack", detail: "host down" })),
1753
+ });
1754
+ yield* Effect.gen(function* () {
1755
+ const reactor = yield* startAndSweep(fixture);
1756
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
1757
+ yield* Ref.set(found, false);
1758
+ yield* sweepAgain(fixture, reactor);
1759
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1760
+ for (let index = 0; index < 14; index += 1) yield* sweepAgain(fixture, reactor);
1761
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 2);
1762
+ yield* sweepAgain(fixture, reactor);
1763
+ assert.strictEqual((yield* Ref.get(fixture.summaryCalls)).length, 3);
1764
+ assert.strictEqual((yield* Ref.get(fixture.stackCalls)).length, 1);
1765
+ }).pipe(Effect.provide(fixture.layer));
1766
+ }),
1767
+ );
1768
+
1769
+ it.effect.each([
1770
+ "gh pr merge 7 --squash 2>&1 | tail -3",
1771
+ "cafe pr merge 7 --squash",
1772
+ "az repos pr update --id 7 --status completed",
1773
+ ])("reads open links fresh only for a thread that ran `%s`", (mergeCommand) =>
1774
+ Effect.gen(function* () {
1775
+ yield* TestClock.setTime(Date.parse(NOW));
1776
+ const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1777
+ const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
1778
+ const fixture = yield* makeHarness({
1779
+ snapshot: makeSnapshot([
1780
+ makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1781
+ makeThread("other", { pullRequests: [makeLink(9, { state: "open" })] }),
1782
+ ]),
1783
+ summary: (input) =>
1784
+ Ref.get(state).pipe(
1785
+ Effect.map((current) =>
1786
+ makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1787
+ ),
1788
+ ),
1789
+ invalidate: ({ reference }) =>
1790
+ Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
1791
+ });
1792
+
1793
+ yield* Effect.gen(function* () {
1794
+ const reactor = yield* startAndSweep(fixture);
1795
+ yield* Ref.set(state, "merged");
1796
+ yield* Ref.set(fixture.summaryCalls, []);
1797
+
1798
+ yield* Queue.offerAll(fixture.domainEvents, [
1799
+ commandRan(ThreadId.make("other"), "gh pr view 9"),
1800
+ runUpdated(ThreadId.make("other"), "completed"),
1801
+ commandRan(ThreadId.make("agent"), mergeCommand),
1802
+ runUpdated(ThreadId.make("agent"), "completed"),
1803
+ ]);
1804
+ yield* Queue.take(fixture.snapshotReads);
1805
+ yield* Queue.take(fixture.snapshotReads);
1806
+ yield* reactor.drain;
1807
+
1808
+ assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
1809
+ assert.deepStrictEqual(
1810
+ (yield* Ref.get(fixture.summaryCalls)).map((call) => call.number),
1811
+ [7],
1812
+ );
1813
+ assert.deepStrictEqual(
1814
+ (yield* Ref.get(fixture.syncCommands)).map((command) => [
1815
+ command.number,
1816
+ command.snapshot.state,
1817
]),
1921
- });
1818
+ [[7, "merged"]],
1819
+ );
1820
+ }).pipe(Effect.provide(fixture.layer));
1821
+ }),
1822
+ );
1823
1923
- yield* Effect.gen(function* () {
1924
- yield* startAndSweep(fixture);
1925
- const agent = ThreadId.make("agent");
1926
- yield* Queue.offerAll(fixture.domainEvents, [
1927
- commandRan(agent, "git status && echo 'then git push'", undefined, "status"),
1928
- // A watch that has not read its checks yet has no answer to forget.
1929
- commandRan(ThreadId.make("unread"), "git push", undefined, "unread-push"),
1930
- commandRan(agent, "cd app && git -C . push --force-with-lease", undefined, "push"),
1931
- commandRan(agent, '/bin/zsh -lc "gh stack submit --auto"', undefined, "stack"),
1932
- ]);
1933
- for (const item of ["push", "stack"]) {
1934
- const command = yield* Queue.take(fixture.reopenCommands);
1935
- assert.deepStrictEqual(
1936
- [command.threadId, command.commandId],
1937
- [agent, `server:pr-push-checks:agent:item:agent:${item}`],
1938
- );
1939
- }
1940
- }).pipe(Effect.provide(fixture.layer));
1941
- }),
1942
- ),
1824
+ it.effect("reopens a watch's checks when its thread's agent pushes", () =>
1825
+ Effect.gen(function* () {
1826
+ yield* TestClock.setTime(Date.parse(NOW));
1827
+ const watch = {
1828
+ startedAt: NOW,
1829
+ headSha: "aaaaaaaaaa",
1830
+ failedChecks: [],
1831
+ passed: true,
1832
+ passedChecks: ["test"],
1833
+ remarksThrough: NOW,
1834
+ remarkIds: [],
1835
+ conflicting: false,
1836
+ wakes: 0,
1837
+ };
1838
+ const fixture = yield* makeHarness({
1839
+ snapshot: makeSnapshot([
1840
+ makeThread("agent", {
1841
+ pullRequests: [
1842
+ makeLink(7, { state: "open" }, { watch: { ...watch, checksPending: false } }),
1843
+ ],
1844
+ }),
1845
+ makeThread("unread", {
1846
+ pullRequests: [makeLink(8, { state: "open" }, { watch })],
1847
+ }),
1848
+ ]),
1849
+ });
1850
+
1851
+ yield* Effect.gen(function* () {
1852
+ yield* startAndSweep(fixture);
1853
+ const agent = ThreadId.make("agent");
1854
+ yield* Queue.offerAll(fixture.domainEvents, [
1855
+ commandRan(agent, "git status && echo 'then git push'", undefined, "status"),
1856
+ // A watch that has not read its checks yet has no answer to forget.
1857
+ commandRan(ThreadId.make("unread"), "git push", undefined, "unread-push"),
1858
+ commandRan(agent, "cd app && git -C . push --force-with-lease", undefined, "push"),
1859
+ commandRan(agent, '/bin/zsh -lc "gh stack submit --auto"', undefined, "stack"),
1860
+ ]);
1861
+ for (const item of ["push", "stack"]) {
1862
+ const command = yield* Queue.take(fixture.reopenCommands);
1863
+ assert.deepStrictEqual(
1864
+ [command.threadId, command.commandId],
1865
+ [agent, `server:pr-push-checks:agent:item:agent:${item}`],
1866
+ );
1867
+ }
1868
+ }).pipe(Effect.provide(fixture.layer));
1869
+ }),
1870
);
1871
1872
it.effect("reads open links again when the run ends, after `merge --auto` left them open", () =>
1946
- Effect.scoped(
1873
+ Effect.gen(function* () {
1874
+ yield* TestClock.setTime(Date.parse(NOW));
1875
+ const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1876
+ const fixture = yield* makeHarness({
1877
+ snapshot: makeSnapshot([
1878
+ makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1879
+ ]),
1880
+ summary: (input) =>
1881
+ Ref.get(state).pipe(
1882
+ Effect.map((current) =>
1883
+ makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1884
+ ),
1885
+ ),
1886
+ });
1887
+
1888
+ yield* Effect.gen(function* () {
1889
+ const reactor = yield* startAndSweep(fixture);
1890
+ yield* Queue.offer(
1891
+ fixture.domainEvents,
1892
+ commandRan(ThreadId.make("agent"), "gh pr merge 7 --auto"),
1893
+ );
1894
+ yield* Queue.take(fixture.snapshotReads);
1895
+ yield* Queue.take(fixture.snapshotReads);
1896
+ yield* reactor.drain;
1897
+ yield* Ref.set(state, "merged");
1898
+ yield* Ref.set(fixture.syncCommands, []);
1899
+
1900
+ yield* Queue.offer(fixture.domainEvents, runUpdated(ThreadId.make("agent"), "completed"));
1901
+ yield* Queue.take(fixture.snapshotReads);
1902
+ yield* Queue.take(fixture.snapshotReads);
1903
+ yield* reactor.drain;
1904
+
1905
+ assert.deepStrictEqual(
1906
+ (yield* Ref.get(fixture.syncCommands)).map((command) => [
1907
+ command.number,
1908
+ command.snapshot.state,
1909
+ ]),
1910
+ [[7, "merged"]],
1911
+ );
1912
+ }).pipe(Effect.provide(fixture.layer));
1913
+ }),
1914
+ );
1915
+
1916
+ it.effect.each(["open", "closed"] as const)(
1917
+ "reads %s links fresh as soon as a merge command ends, before its run ends",
1918
+ (initialState) =>
1919
Effect.gen(function* () {
1920
yield* TestClock.setTime(Date.parse(NOW));
1949
- const state = yield* Ref.make<PullRequestSummary["state"]>("open");
1921
+ const state = yield* Ref.make<PullRequestSummary["state"]>(initialState);
1922
+ const initialSnapshot = {
1923
+ state: initialState,
1924
+ closedAt: initialState === "closed" ? "2026-08-20T00:00:00.000Z" : null,
1925
+ };
1926
const fixture = yield* makeHarness({
1927
snapshot: makeSnapshot([
1952
- makeThread("agent", { pullRequests: [makeLink(7, { state: "open" })] }),
1928
+ makeThread("agent", { pullRequests: [makeLink(7, initialSnapshot)] }),
1929
]),
1930
summary: (input) =>
1931
Ref.get(state).pipe(
1932
Effect.map((current) =>
1957
- makeSummary(input, current === "merged" ? { state: current, mergedAt: NOW } : {}),
1933
+ makeSummary(
1934
+ input,
1935
+ current === "merged" ? { state: current, mergedAt: NOW } : initialSnapshot,
1936
+ ),
1937
),
1938
),
1939
});
1940
1941
yield* Effect.gen(function* () {
1942
const reactor = yield* startAndSweep(fixture);
1943
+ yield* Ref.set(state, "merged");
1944
+ yield* Ref.set(fixture.summaryCalls, []);
1945
+
1946
yield* Queue.offer(
1947
fixture.domainEvents,
1966
- commandRan(ThreadId.make("agent"), "gh pr merge 7 --auto"),
1948
+ commandRan(ThreadId.make("agent"), "gh pr merge 7"),
1949
);
1950
yield* Queue.take(fixture.snapshotReads);
1951
yield* Queue.take(fixture.snapshotReads);
1952
yield* reactor.drain;
1971
- yield* Ref.set(state, "merged");
1972
- yield* Ref.set(fixture.syncCommands, []);
1973
-
1974
- yield* Queue.offer(fixture.domainEvents, runUpdated(ThreadId.make("agent"), "completed"));
1975
- yield* Queue.take(fixture.snapshotReads);
1976
- yield* Queue.take(fixture.snapshotReads);
1977
- yield* reactor.drain;
1953
1954
assert.deepStrictEqual(
1955
(yield* Ref.get(fixture.syncCommands)).map((command) => [
@@ -1985,58 +1960,6 @@ describe("PullRequestSyncReactor", () => {
1960
);
1961
}).pipe(Effect.provide(fixture.layer));
1962
}),
1988
- ),
1989
- );
1990
-
1991
- it.effect.each(["open", "closed"] as const)(
1992
- "reads %s links fresh as soon as a merge command ends, before its run ends",
1993
- (initialState) =>
1994
- Effect.scoped(
1995
- Effect.gen(function* () {
1996
- yield* TestClock.setTime(Date.parse(NOW));
1997
- const state = yield* Ref.make<PullRequestSummary["state"]>(initialState);
1998
- const initialSnapshot = {
1999
- state: initialState,
2000
- closedAt: initialState === "closed" ? "2026-08-20T00:00:00.000Z" : null,
2001
- };
2002
- const fixture = yield* makeHarness({
2003
- snapshot: makeSnapshot([
2004
- makeThread("agent", { pullRequests: [makeLink(7, initialSnapshot)] }),
2005
- ]),
2006
- summary: (input) =>
2007
- Ref.get(state).pipe(
2008
- Effect.map((current) =>
2009
- makeSummary(
2010
- input,
2011
- current === "merged" ? { state: current, mergedAt: NOW } : initialSnapshot,
2012
- ),
2013
- ),
2014
- ),
2015
- });
2016
-
2017
- yield* Effect.gen(function* () {
2018
- const reactor = yield* startAndSweep(fixture);
2019
- yield* Ref.set(state, "merged");
2020
- yield* Ref.set(fixture.summaryCalls, []);
2021
-
2022
- yield* Queue.offer(
2023
- fixture.domainEvents,
2024
- commandRan(ThreadId.make("agent"), "gh pr merge 7"),
2025
- );
2026
- yield* Queue.take(fixture.snapshotReads);
2027
- yield* Queue.take(fixture.snapshotReads);
2028
- yield* reactor.drain;
2029
-
2030
- assert.deepStrictEqual(
2031
- (yield* Ref.get(fixture.syncCommands)).map((command) => [
2032
- command.number,
2033
- command.snapshot.state,
2034
- ]),
2035
- [[7, "merged"]],
2036
- );
2037
- }).pipe(Effect.provide(fixture.layer));
2038
- }),
2039
- ),
1963
);
1964
1965
it.effect.each([
@@ -2167,54 +2090,50 @@ describe("PullRequestSyncReactor", () => {
2090
linked: [],
2091
},
2092
])("links what the command created: $name", ({ input, output, linked }) =>
2170
- Effect.scoped(
2171
- Effect.gen(function* () {
2172
- yield* TestClock.setTime(Date.parse(NOW));
2173
- const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
2093
+ Effect.gen(function* () {
2094
+ yield* TestClock.setTime(Date.parse(NOW));
2095
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
2096
2175
- yield* Effect.gen(function* () {
2176
- const reactor = yield* startAndSweep(fixture);
2177
- const child = ThreadId.make("delegated-child");
2178
- const links = yield* linksFrom(fixture, reactor, [commandRan(child, input, output)]);
2097
+ yield* Effect.gen(function* () {
2098
+ const reactor = yield* startAndSweep(fixture);
2099
+ const child = ThreadId.make("delegated-child");
2100
+ const links = yield* linksFrom(fixture, reactor, [commandRan(child, input, output)]);
2101
2180
- assert.deepStrictEqual(
2181
- links.map((command) => [command.threadId, command.number, command.source]),
2182
- linked.map((number) => [child, number, "created"]),
2183
- );
2184
- }).pipe(Effect.provide(fixture.layer));
2185
- }),
2186
- ),
2102
+ assert.deepStrictEqual(
2103
+ links.map((command) => [command.threadId, command.number, command.source]),
2104
+ linked.map((number) => [child, number, "created"]),
2105
+ );
2106
+ }).pipe(Effect.provide(fixture.layer));
2107
+ }),
2108
);
2109
2110
it.effect("links a created pull request once its command settles, with one command id", () =>
2190
- Effect.scoped(
2191
- Effect.gen(function* () {
2192
- yield* TestClock.setTime(Date.parse(NOW));
2193
- const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
2111
+ Effect.gen(function* () {
2112
+ yield* TestClock.setTime(Date.parse(NOW));
2113
+ const fixture = yield* makeHarness({ snapshot: mergingSnapshot() });
2114
2195
- yield* Effect.gen(function* () {
2196
- const reactor = yield* startAndSweep(fixture);
2197
- const settled = commandRan(
2198
- ThreadId.make("agent"),
2199
- "gh pr create --fill",
2200
- "https://github.com/owner/repository/pull/124",
2201
- );
2202
- assert.strictEqual(settled.type, "turn-item.updated");
2203
- if (settled.type !== "turn-item.updated") return;
2115
+ yield* Effect.gen(function* () {
2116
+ const reactor = yield* startAndSweep(fixture);
2117
+ const settled = commandRan(
2118
+ ThreadId.make("agent"),
2119
+ "gh pr create --fill",
2120
+ "https://github.com/owner/repository/pull/124",
2121
+ );
2122
+ assert.strictEqual(settled.type, "turn-item.updated");
2123
+ if (settled.type !== "turn-item.updated") return;
2124
2205
- const links = yield* linksFrom(fixture, reactor, [
2206
- { ...settled, payload: { ...settled.payload, status: "running" } },
2207
- settled,
2208
- settled,
2209
- ]);
2125
+ const links = yield* linksFrom(fixture, reactor, [
2126
+ { ...settled, payload: { ...settled.payload, status: "running" } },
2127
+ settled,
2128
+ settled,
2129
+ ]);
2130
2211
- assert.deepStrictEqual(
2212
- links.map((command) => command.number),
2213
- [124, 124],
2214
- );
2215
- assert.strictEqual(links[0]!.commandId, links[1]!.commandId);
2216
- }).pipe(Effect.provide(fixture.layer));
2217
- }),
2218
- ),
2131
+ assert.deepStrictEqual(
2132
+ links.map((command) => command.number),
2133
+ [124, 124],
2134
+ );
2135
+ assert.strictEqual(links[0]!.commandId, links[1]!.commandId);
2136
+ }).pipe(Effect.provide(fixture.layer));
2137
+ }),
2138
);
2139
});
apps/server/src/orchestration-v2/RunExecutionService.test.ts
+1
-1
@@ -2050,7 +2050,7 @@ it.effect(
2050
},
2051
).pipe(Effect.forkScoped);
2052
assert.isFalse(yield* Deferred.await(active));
2053
- }).pipe(Effect.scoped),
2053
+ }),
2054
);
2055
2056
it.effect("keeps ingesting a failed root's background item when its work continues", () =>
apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts
+640
-652
@@ -285,728 +285,716 @@ function makeRestartAdapter(
285
}
286
287
it.live("retries a failed selection restart session open before completing", () =>
288
- Effect.scoped(
289
- Effect.gen(function* () {
290
- const cwd = yield* checkpointWorkspace("selection-restart-lifecycle");
291
- const threadId = ThreadId.make("thread:selection-restart-lifecycle");
292
- const state = yield* Ref.make<RestartAdapterState>({
293
- activeTurn: null,
294
- opened: [],
295
- started: [],
296
- closedSessionCount: 0,
297
- failedReplacementOpen: false,
298
- });
299
- const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
288
+ Effect.gen(function* () {
289
+ const cwd = yield* checkpointWorkspace("selection-restart-lifecycle");
290
+ const threadId = ThreadId.make("thread:selection-restart-lifecycle");
291
+ const state = yield* Ref.make<RestartAdapterState>({
292
+ activeTurn: null,
293
+ opened: [],
294
+ started: [],
295
+ closedSessionCount: 0,
296
+ failedReplacementOpen: false,
297
+ });
298
+ const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
299
301
- const result = yield* Effect.gen(function* () {
302
- const orchestrator = yield* Orchestrator.OrchestratorV2;
303
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
304
- const eventSink = yield* EventSink.EventSinkV2;
300
+ const result = yield* Effect.gen(function* () {
301
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
302
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
303
+ const eventSink = yield* EventSink.EventSinkV2;
304
306
- yield* orchestrator.dispatch({
307
- type: "thread.create",
308
- createdBy: "user",
309
- creationSource: "web",
310
- commandId: CommandId.make("command:selection-restart:create"),
305
+ yield* orchestrator.dispatch({
306
+ type: "thread.create",
307
+ createdBy: "user",
308
+ creationSource: "web",
309
+ commandId: CommandId.make("command:selection-restart:create"),
310
+ threadId,
311
+ projectId: ProjectId.make("project:selection-restart"),
312
+ title: "Selection restart",
313
+ modelSelection: initialSelection,
314
+ runtimeMode: "full-access",
315
+ interactionMode: "default",
316
+ branch: null,
317
+ worktreePath: cwd,
318
+ });
319
+ const running = yield* eventSink
320
+ .stream({
321
threadId,
312
- projectId: ProjectId.make("project:selection-restart"),
313
- title: "Selection restart",
314
- modelSelection: initialSelection,
315
- runtimeMode: "full-access",
316
- interactionMode: "default",
317
- branch: null,
318
- worktreePath: cwd,
319
- });
320
- const running = yield* eventSink
321
- .stream({
322
- threadId,
323
- afterSequence: yield* eventSink.latestSequence({ threadId }),
324
- })
325
- .pipe(
326
- Stream.map((stored) => stored.event),
327
- Stream.filter(
328
- (event) =>
329
- event.type === "provider-turn.updated" && event.payload.status === "running",
330
- ),
331
- Stream.take(1),
332
- Stream.runDrain,
333
- Effect.forkScoped,
334
- );
335
- yield* orchestrator.dispatch({
336
- type: "message.dispatch",
337
- createdBy: "user",
338
- creationSource: "web",
339
- commandId: CommandId.make("command:selection-restart:first"),
322
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
323
+ })
324
+ .pipe(
325
+ Stream.map((stored) => stored.event),
326
+ Stream.filter(
327
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
328
+ ),
329
+ Stream.take(1),
330
+ Stream.runDrain,
331
+ Effect.forkScoped,
332
+ );
333
+ yield* orchestrator.dispatch({
334
+ type: "message.dispatch",
335
+ createdBy: "user",
336
+ creationSource: "web",
337
+ commandId: CommandId.make("command:selection-restart:first"),
338
+ threadId,
339
+ messageId: MessageId.make("message:selection-restart:first"),
340
+ text: "first",
341
+ attachments: [],
342
+ modelSelection: initialSelection,
343
+ dispatchMode: { type: "start_immediately" },
344
+ });
345
+ yield* Fiber.join(running);
346
+ yield* worker.drain();
347
+ const activeProjection = yield* orchestrator.getThreadProjection(threadId);
348
+ assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running"));
349
+ const activeRunId = activeProjection.runs[0]?.id;
350
+ if (activeRunId === undefined) {
351
+ return yield* Effect.die("active restart test run is missing");
352
+ }
353
+
354
+ const completed = yield* eventSink
355
+ .stream({
356
threadId,
341
- messageId: MessageId.make("message:selection-restart:first"),
342
- text: "first",
343
- attachments: [],
344
- modelSelection: initialSelection,
345
- dispatchMode: { type: "start_immediately" },
346
- });
347
- yield* Fiber.join(running);
348
- yield* worker.drain();
349
- const activeProjection = yield* orchestrator.getThreadProjection(threadId);
350
- assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running"));
351
- const activeRunId = activeProjection.runs[0]?.id;
352
- if (activeRunId === undefined) {
353
- return yield* Effect.die("active restart test run is missing");
354
- }
357
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
358
+ })
359
+ .pipe(
360
+ Stream.map((stored) => stored.event),
361
+ Stream.filter(
362
+ (event) => event.type === "run.updated" && event.payload.status === "completed",
363
+ ),
364
+ Stream.take(1),
365
+ Stream.runDrain,
366
+ Effect.forkScoped,
367
+ );
368
+ yield* orchestrator.dispatch({
369
+ type: "message.dispatch",
370
+ createdBy: "user",
371
+ creationSource: "web",
372
+ commandId: CommandId.make("command:selection-restart:second"),
373
+ threadId,
374
+ messageId: MessageId.make("message:selection-restart:second"),
375
+ text: "second",
376
+ attachments: [],
377
+ modelSelection: replacementSelection,
378
+ dispatchMode: { type: "restart_active", targetRunId: activeRunId },
379
+ });
380
+ yield* Fiber.join(completed);
381
+ yield* worker.drain();
382
+ return {
383
+ projection: yield* orchestrator.getThreadProjection(threadId),
384
+ captured: yield* Ref.get(state),
385
+ };
386
+ }).pipe(
387
+ Effect.provide(
388
+ ProviderReplayHarness.layerWithRegistry(
389
+ { name: "selection-restart-lifecycle" },
390
+ layerRegistry,
391
+ ),
392
+ ),
393
+ );
394
+ const { projection, captured } = result;
395
356
- const completed = yield* eventSink
357
- .stream({
358
- threadId,
359
- afterSequence: yield* eventSink.latestSequence({ threadId }),
360
- })
361
- .pipe(
362
- Stream.map((stored) => stored.event),
363
- Stream.filter(
364
- (event) => event.type === "run.updated" && event.payload.status === "completed",
365
- ),
366
- Stream.take(1),
367
- Stream.runDrain,
368
- Effect.forkScoped,
369
- );
370
- yield* orchestrator.dispatch({
371
- type: "message.dispatch",
372
- createdBy: "user",
373
- creationSource: "web",
374
- commandId: CommandId.make("command:selection-restart:second"),
396
+ assert.lengthOf(projection.runs, 1);
397
+ assert.lengthOf(projection.attempts, 2);
398
+ assert.deepEqual(
399
+ projection.attempts.map((attempt) => attempt.status),
400
+ ["superseded", "completed"],
401
+ );
402
+ assert.deepEqual(
403
+ projection.providerTurns.map((turn) => turn.status),
404
+ ["interrupted", "completed"],
405
+ );
406
+ assert.isFalse(
407
+ projection.turnItems.some(
408
+ (item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
409
+ ),
410
+ "selection restart supersede must not project hard-Stop interrupt items",
411
+ );
412
+ assert.equal(projection.runs.at(-1)?.modelSelection.model, replacementSelection.model);
413
+ assert.deepEqual(modelSwitches(projection), [
414
+ { from: initialSelection, to: replacementSelection },
415
+ ]);
416
+ assert.equal(projection.runs.at(-1)?.status, "completed");
417
+ assert.isTrue(captured.failedReplacementOpen);
418
+ assert.equal(captured.closedSessionCount, 0);
419
+ assert.deepEqual(
420
+ captured.opened.map((open) => [open.model, open.cwd]),
421
+ [
422
+ [initialSelection.model, cwd],
423
+ [replacementSelection.model, cwd],
424
+ [replacementSelection.model, cwd],
425
+ ],
426
+ );
427
+ assert.deepEqual(
428
+ captured.started.map((turn) => [turn.model, turn.cwd]),
429
+ [
430
+ [initialSelection.model, cwd],
431
+ [replacementSelection.model, cwd],
432
+ ],
433
+ );
434
+ assert.notEqual(
435
+ projection.providerSessions[0]?.id,
436
+ projection.providerThreads[0]?.providerSessionId,
437
+ );
438
+ assert.equal(
439
+ projection.providerThreads[0]?.providerSessionId,
440
+ projection.providerSessions.find((session) => session.model === replacementSelection.model)
441
+ ?.id,
442
+ );
443
+ }),
444
+);
445
+
446
+it.live("a workspace handoff during a run does not leave the run interrupted", () =>
447
+ Effect.gen(function* () {
448
+ const cwd = yield* checkpointWorkspace("workspace-handoff-lifecycle");
449
+ const handoffCwd = yield* checkpointWorkspace("workspace-handoff-lifecycle-target");
450
+ const threadId = ThreadId.make("thread:workspace-handoff-lifecycle");
451
+ const state = yield* Ref.make<RestartAdapterState>({
452
+ activeTurn: null,
453
+ opened: [],
454
+ started: [],
455
+ closedSessionCount: 0,
456
+ failedReplacementOpen: false,
457
+ });
458
+ const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
459
+
460
+ const projection = yield* Effect.gen(function* () {
461
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
462
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
463
+ const eventSink = yield* EventSink.EventSinkV2;
464
+
465
+ yield* orchestrator.dispatch({
466
+ type: "thread.create",
467
+ createdBy: "user",
468
+ creationSource: "web",
469
+ commandId: CommandId.make("command:workspace-handoff:create"),
470
+ threadId,
471
+ projectId: ProjectId.make("project:workspace-handoff"),
472
+ title: "Workspace handoff",
473
+ modelSelection: initialSelection,
474
+ runtimeMode: "full-access",
475
+ interactionMode: "default",
476
+ branch: null,
477
+ worktreePath: cwd,
478
+ });
479
+ const running = yield* eventSink
480
+ .stream({
481
threadId,
376
- messageId: MessageId.make("message:selection-restart:second"),
377
- text: "second",
378
- attachments: [],
379
- modelSelection: replacementSelection,
380
- dispatchMode: { type: "restart_active", targetRunId: activeRunId },
381
- });
382
- yield* Fiber.join(completed);
383
- yield* worker.drain();
384
- return {
385
- projection: yield* orchestrator.getThreadProjection(threadId),
386
- captured: yield* Ref.get(state),
387
- };
388
- }).pipe(
389
- Effect.provide(
390
- ProviderReplayHarness.layerWithRegistry(
391
- { name: "selection-restart-lifecycle" },
392
- layerRegistry,
482
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
483
+ })
484
+ .pipe(
485
+ Stream.map((stored) => stored.event),
486
+ Stream.filter(
487
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
488
+ ),
489
+ Stream.take(1),
490
+ Stream.runDrain,
491
+ Effect.forkScoped,
492
+ );
493
+ yield* orchestrator.dispatch({
494
+ type: "message.dispatch",
495
+ createdBy: "user",
496
+ creationSource: "web",
497
+ commandId: CommandId.make("command:workspace-handoff:first"),
498
+ threadId,
499
+ messageId: MessageId.make("message:workspace-handoff:first"),
500
+ text: "move to a worktree",
501
+ attachments: [],
502
+ modelSelection: initialSelection,
503
+ dispatchMode: { type: "start_immediately" },
504
+ });
505
+ yield* Fiber.join(running);
506
+ yield* worker.drain();
507
+
508
+ const settled = yield* eventSink
509
+ .stream({
510
+ threadId,
511
+ afterSequence: yield* eventSink.latestSequence({ threadId }),
512
+ })
513
+ .pipe(
514
+ Stream.map((stored) => stored.event),
515
+ Stream.filter(
516
+ (event) =>
517
+ event.type === "run.updated" &&
518
+ event.payload.status !== "running" &&
519
+ event.payload.status !== "queued" &&
520
+ event.payload.status !== "starting",
521
),
522
+ Stream.take(1),
523
+ Stream.runDrain,
524
+ Effect.forkScoped,
525
+ );
526
+ // What t3_worktree_handoff dispatches while the calling turn is still running.
527
+ yield* orchestrator.dispatch({
528
+ type: "thread.metadata.update",
529
+ commandId: CommandId.make("command:workspace-handoff:rebind"),
530
+ threadId,
531
+ branch: "repro-handoff",
532
+ worktreePath: handoffCwd,
533
+ });
534
+ yield* Fiber.join(settled);
535
+ yield* worker.drain();
536
+ return yield* orchestrator.getThreadProjection(threadId);
537
+ }).pipe(
538
+ Effect.provide(
539
+ ProviderReplayHarness.layerWithRegistry(
540
+ { name: "workspace-handoff-lifecycle" },
541
+ layerRegistry,
542
),
395
- );
396
- const { projection, captured } = result;
543
+ ),
544
+ );
545
398
- assert.lengthOf(projection.runs, 1);
399
- assert.lengthOf(projection.attempts, 2);
400
- assert.deepEqual(
401
- projection.attempts.map((attempt) => attempt.status),
402
- ["superseded", "completed"],
403
- );
404
- assert.deepEqual(
405
- projection.providerTurns.map((turn) => turn.status),
406
- ["interrupted", "completed"],
407
- );
408
- assert.isFalse(
409
- projection.turnItems.some(
410
- (item) => item.type === "run_interrupt_request" || item.type === "run_interrupt_result",
546
+ assert.equal(projection.thread.worktreePath, handoffCwd);
547
+ assert.equal(projection.runs[0]?.status, "completed");
548
+ assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
549
+ assert.isFalse(
550
+ projection.turnItems.some((item) => item.type === "run_interrupt_result"),
551
+ "an intentional workspace handoff must not project an interrupt result",
552
+ );
553
+ }),
554
+);
555
+
556
+it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
557
+ Effect.gen(function* () {
558
+ const cwd = yield* checkpointWorkspace("selection-restart-stop");
559
+ const threadId = ThreadId.make("thread:selection-restart-stop");
560
+ const state = yield* Ref.make<RestartAdapterState>({
561
+ activeTurn: null,
562
+ opened: [],
563
+ started: [],
564
+ closedSessionCount: 0,
565
+ failedReplacementOpen: false,
566
+ });
567
+ const base = makeRestartAdapter(state);
568
+ // A wedged provider ignores the restart's soft cancel; only Stop ends its turn.
569
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
570
+ ...base,
571
+ openSession: (input) =>
572
+ base.openSession(input).pipe(
573
+ Effect.map((session) => ({
574
+ ...session,
575
+ interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
576
+ interrupt.requestRuntimeRestart === true
577
+ ? session.interruptTurn(interrupt)
578
+ : Effect.never,
579
+ })),
580
),
412
- "selection restart supersede must not project hard-Stop interrupt items",
413
- );
414
- assert.equal(projection.runs.at(-1)?.modelSelection.model, replacementSelection.model);
415
- assert.deepEqual(modelSwitches(projection), [
416
- { from: initialSelection, to: replacementSelection },
417
- ]);
418
- assert.equal(projection.runs.at(-1)?.status, "completed");
419
- assert.isTrue(captured.failedReplacementOpen);
420
- assert.equal(captured.closedSessionCount, 0);
421
- assert.deepEqual(
422
- captured.opened.map((open) => [open.model, open.cwd]),
423
- [
424
- [initialSelection.model, cwd],
425
- [replacementSelection.model, cwd],
426
- [replacementSelection.model, cwd],
427
- ],
428
- );
429
- assert.deepEqual(
430
- captured.started.map((turn) => [turn.model, turn.cwd]),
431
- [
432
- [initialSelection.model, cwd],
433
- [replacementSelection.model, cwd],
434
- ],
435
- );
436
- assert.notEqual(
437
- projection.providerSessions[0]?.id,
438
- projection.providerThreads[0]?.providerSessionId,
439
- );
440
- assert.equal(
441
- projection.providerThreads[0]?.providerSessionId,
442
- projection.providerSessions.find((session) => session.model === replacementSelection.model)
443
- ?.id,
581
+ };
582
+
583
+ const result = yield* Effect.gen(function* () {
584
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
585
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
586
+ const running = yield* orchestrator.streamDomainEvents.pipe(
587
+ Stream.filter(
588
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
589
+ ),
590
+ Stream.take(1),
591
+ Stream.runDrain,
592
+ Effect.forkScoped({ startImmediately: true }),
593
);
445
- }),
446
- ),
594
+ yield* orchestrator.dispatch({
595
+ type: "thread.create",
596
+ createdBy: "user",
597
+ creationSource: "web",
598
+ commandId: CommandId.make("command:selection-restart-stop:create"),
599
+ threadId,
600
+ projectId: ProjectId.make("project:selection-restart-stop"),
601
+ title: "Stop during restart",
602
+ modelSelection: initialSelection,
603
+ runtimeMode: "full-access",
604
+ interactionMode: "default",
605
+ branch: null,
606
+ worktreePath: cwd,
607
+ });
608
+ yield* orchestrator.dispatch({
609
+ type: "message.dispatch",
610
+ createdBy: "user",
611
+ creationSource: "web",
612
+ commandId: CommandId.make("command:selection-restart-stop:first"),
613
+ threadId,
614
+ messageId: MessageId.make("message:selection-restart-stop:first"),
615
+ text: "first",
616
+ attachments: [],
617
+ modelSelection: initialSelection,
618
+ dispatchMode: { type: "start_immediately" },
619
+ });
620
+ yield* worker.drain();
621
+ yield* Fiber.join(running);
622
+ const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id;
623
+
624
+ yield* orchestrator.dispatch({
625
+ type: "message.dispatch",
626
+ createdBy: "user",
627
+ creationSource: "web",
628
+ commandId: CommandId.make("command:selection-restart-stop:steer"),
629
+ threadId,
630
+ messageId: MessageId.make("message:selection-restart-stop:steer"),
631
+ text: "Are you still going?",
632
+ attachments: [],
633
+ modelSelection: initialSelection,
634
+ dispatchMode: { type: "restart_active", targetRunId: runId },
635
+ });
636
+ yield* orchestrator.dispatch({
637
+ type: "run.interrupt",
638
+ commandId: CommandId.make("command:selection-restart-stop:stop"),
639
+ threadId,
640
+ runId,
641
+ });
642
+ yield* worker.drain();
643
+ return {
644
+ projection: yield* orchestrator.getThreadProjection(threadId),
645
+ captured: yield* Ref.get(state),
646
+ };
647
+ }).pipe(
648
+ Effect.provide(
649
+ ProviderReplayHarness.layerWithRegistry(
650
+ { name: "selection-restart-stop" },
651
+ ProviderAdapterRegistry.layerSingle(adapter),
652
+ ),
653
+ ),
654
+ );
655
+
656
+ assert.isNull(result.captured.activeTurn);
657
+ assert.lengthOf(result.captured.started, 1);
658
+ assert.equal(result.projection.runs[0]?.status, "interrupted");
659
+ assert.deepEqual(
660
+ result.projection.providerTurns.map((turn) => turn.status),
661
+ ["interrupted"],
662
+ );
663
+ }),
664
);
665
449
-it.live("a workspace handoff during a run does not leave the run interrupted", () =>
450
- Effect.scoped(
666
+it.live(
667
+ "restarts the live session on a model change when a newer stopped session record exists",
668
+ () =>
669
Effect.gen(function* () {
452
- const cwd = yield* checkpointWorkspace("workspace-handoff-lifecycle");
453
- const handoffCwd = yield* checkpointWorkspace("workspace-handoff-lifecycle-target");
454
- const threadId = ThreadId.make("thread:workspace-handoff-lifecycle");
670
+ const name = "selection-restart-dead-stopped";
671
+ const cwd = yield* checkpointWorkspace(name);
672
+ const threadId = ThreadId.make(`thread:${name}`);
673
const state = yield* Ref.make<RestartAdapterState>({
674
activeTurn: null,
675
opened: [],
676
started: [],
677
closedSessionCount: 0,
460
- failedReplacementOpen: false,
678
+ failedReplacementOpen: true,
679
});
462
- const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state));
680
+ const layerRegistry = ProviderAdapterRegistry.layerSingle(
681
+ makeRestartAdapter(state, exclusiveCapabilities),
682
+ );
683
464
- const projection = yield* Effect.gen(function* () {
684
+ const result = yield* Effect.gen(function* () {
685
const orchestrator = yield* Orchestrator.OrchestratorV2;
686
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
687
const eventSink = yield* EventSink.EventSinkV2;
468
-
688
+ const dispatch = (step: string, modelSelection: ModelSelection) =>
689
+ Effect.gen(function* () {
690
+ const terminal = yield* orchestrator.streamDomainEvents.pipe(
691
+ Stream.filter(
692
+ (event) => event.type === "run.updated" && event.payload.status === "completed",
693
+ ),
694
+ Stream.take(1),
695
+ Stream.runDrain,
696
+ Effect.forkScoped,
697
+ );
698
+ yield* orchestrator.dispatch({
699
+ type: "message.dispatch",
700
+ createdBy: "user",
701
+ creationSource: "web",
702
+ commandId: CommandId.make(`${name}:${step}`),
703
+ threadId,
704
+ messageId: MessageId.make(`${name}:${step}`),
705
+ text: step,
706
+ attachments: [],
707
+ modelSelection,
708
+ dispatchMode: { type: "start_immediately" },
709
+ });
710
+ yield* worker.drain();
711
+ yield* Fiber.join(terminal);
712
+ yield* worker.drain();
713
+ return yield* orchestrator.getThreadProjection(threadId);
714
+ });
715
yield* orchestrator.dispatch({
716
type: "thread.create",
717
createdBy: "user",
718
creationSource: "web",
473
- commandId: CommandId.make("command:workspace-handoff:create"),
719
+ commandId: CommandId.make(`${name}:create`),
720
threadId,
475
- projectId: ProjectId.make("project:workspace-handoff"),
476
- title: "Workspace handoff",
477
- modelSelection: initialSelection,
721
+ projectId: ProjectId.make(`project:${name}`),
722
+ title: name,
723
+ modelSelection: seedSelection,
724
runtimeMode: "full-access",
725
interactionMode: "default",
726
branch: null,
727
worktreePath: cwd,
728
});
483
- const running = yield* eventSink
484
- .stream({
485
- threadId,
486
- afterSequence: yield* eventSink.latestSequence({ threadId }),
487
- })
488
- .pipe(
489
- Stream.map((stored) => stored.event),
490
- Stream.filter(
491
- (event) =>
492
- event.type === "provider-turn.updated" && event.payload.status === "running",
493
- ),
494
- Stream.take(1),
495
- Stream.runDrain,
496
- Effect.forkScoped,
497
- );
498
- yield* orchestrator.dispatch({
499
- type: "message.dispatch",
500
- createdBy: "user",
501
- creationSource: "web",
502
- commandId: CommandId.make("command:workspace-handoff:first"),
503
- threadId,
504
- messageId: MessageId.make("message:workspace-handoff:first"),
505
- text: "move to a worktree",
506
- attachments: [],
507
- modelSelection: initialSelection,
508
- dispatchMode: { type: "start_immediately" },
729
+ const first = yield* dispatch("first", seedSelection);
730
+ const liveSession = first.providerSessions.find(
731
+ (session) => session.status !== "stopped" && session.status !== "error",
732
+ );
733
+ assert.isDefined(liveSession);
734
+
735
+ const deadAt = yield* DateTime.now;
736
+ const deadSession: OrchestrationV2ProviderSession = {
737
+ id: ProviderSessionId.make(`session:${name}:dead`),
738
+ driver,
739
+ providerInstanceId,
740
+ status: "ready",
741
+ cwd,
742
+ model: seedSelection.model,
743
+ capabilities: exclusiveCapabilities,
744
+ createdAt: deadAt,
745
+ updatedAt: deadAt,
746
+ lastError: null,
747
+ };
748
+ yield* eventSink.write({
749
+ events: [
750
+ {
751
+ id: EventId.make(`event:${name}:dead-attached`),
752
+ type: "provider-session.attached",
753
+ threadId,
754
+ driver,
755
+ providerInstanceId,
756
+ occurredAt: deadAt,
757
+ payload: deadSession,
758
+ },
759
+ {
760
+ id: EventId.make(`event:${name}:dead-updated`),
761
+ type: "provider-session.updated",
762
+ threadId,
763
+ driver,
764
+ providerInstanceId,
765
+ occurredAt: deadAt,
766
+ payload: {
767
+ ...deadSession,
768
+ status: "stopped",
769
+ updatedAt: deadAt,
770
+ lastError: null,
771
+ },
772
+ },
773
+ ],
774
});
510
- yield* Fiber.join(running);
511
- yield* worker.drain();
775
513
- const settled = yield* eventSink
514
- .stream({
515
- threadId,
516
- afterSequence: yield* eventSink.latestSequence({ threadId }),
517
- })
518
- .pipe(
519
- Stream.map((stored) => stored.event),
520
- Stream.filter(
521
- (event) =>
522
- event.type === "run.updated" &&
523
- event.payload.status !== "running" &&
524
- event.payload.status !== "queued" &&
525
- event.payload.status !== "starting",
526
- ),
527
- Stream.take(1),
528
- Stream.runDrain,
529
- Effect.forkScoped,
530
- );
531
- // What t3_worktree_handoff dispatches while the calling turn is still running.
776
+ const switchCommandId = CommandId.make(`${name}:switch`);
777
yield* orchestrator.dispatch({
533
- type: "thread.metadata.update",
534
- commandId: CommandId.make("command:workspace-handoff:rebind"),
778
+ type: "thread.model-selection.set",
779
+ commandId: switchCommandId,
780
threadId,
536
- branch: "repro-handoff",
537
- worktreePath: handoffCwd,
781
+ modelSelection: replacementSelection,
782
});
539
- yield* Fiber.join(settled);
783
yield* worker.drain();
541
- return yield* orchestrator.getThreadProjection(threadId);
542
- }).pipe(
543
- Effect.provide(
544
- ProviderReplayHarness.layerWithRegistry(
545
- { name: "workspace-handoff-lifecycle" },
546
- layerRegistry,
547
- ),
548
- ),
549
- );
784
+ const storedSwitchEvents = yield* eventSink
785
+ .readByCommandId({ commandId: switchCommandId })
786
+ .pipe(Stream.runCollect);
787
+ const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
788
+ stored.event.type === "provider-session.detached"
789
+ ? [stored.event.payload.providerSessionId]
790
+ : [],
791
+ );
792
+
793
+ const second = yield* dispatch("second", replacementSelection);
794
+ return {
795
+ projection: second,
796
+ captured: yield* Ref.get(state),
797
+ liveSessionId: liveSession.id,
798
+ detachedSessionIds,
799
+ };
800
+ }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
801
551
- assert.equal(projection.thread.worktreePath, handoffCwd);
552
- assert.equal(projection.runs[0]?.status, "completed");
553
- assert.isNotNull(projection.runs[0]?.checkpointId ?? null);
554
- assert.isFalse(
555
- projection.turnItems.some((item) => item.type === "run_interrupt_result"),
556
- "an intentional workspace handoff must not project an interrupt result",
802
+ const { projection, captured } = result;
803
+ assert.lengthOf(projection.runs, 2);
804
+ assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
805
+ assert.deepEqual(modelSwitches(projection), [
806
+ { from: seedSelection, to: replacementSelection },
807
+ ]);
808
+ assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
809
+ assert.equal(captured.closedSessionCount, 1);
810
+ assert.deepEqual(
811
+ captured.opened.map((open) => open.model),
812
+ [seedSelection.model, replacementSelection.model],
813
+ );
814
+ assert.deepEqual(
815
+ captured.started.map((turn) => turn.model),
816
+ [seedSelection.model, replacementSelection.model],
817
);
818
+ const servingSession = projection.providerSessions.find(
819
+ (session) =>
820
+ session.id ===
821
+ projection.providerThreads.find(
822
+ (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
823
+ )?.providerSessionId,
824
+ );
825
+ assert.equal(servingSession?.model, replacementSelection.model);
826
}),
559
- ),
827
);
828
562
-it.live("Stop during a restart interrupts the turn the restart could not stop", () =>
563
- Effect.scoped(
829
+it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
830
+ "preserves native history only for compatible account switches (%s)",
831
+ (mode) =>
832
Effect.gen(function* () {
565
- const cwd = yield* checkpointWorkspace("selection-restart-stop");
566
- const threadId = ThreadId.make("thread:selection-restart-stop");
833
+ const name = `shared-home-${mode}`;
834
+ const cwd = yield* checkpointWorkspace(name);
835
+ const threadId = ThreadId.make(`thread:${name}`);
836
+ const targetId = ProviderInstanceId.make("codex-shadow-account");
837
const state = yield* Ref.make<RestartAdapterState>({
838
activeTurn: null,
839
opened: [],
840
started: [],
841
closedSessionCount: 0,
572
- failedReplacementOpen: false,
842
+ failedReplacementOpen: true,
843
});
574
- const base = makeRestartAdapter(state);
575
- // A wedged provider ignores the restart's soft cancel; only Stop ends its turn.
576
- const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
577
- ...base,
578
- openSession: (input) =>
579
- base.openSession(input).pipe(
580
- Effect.map((session) => ({
581
- ...session,
582
- interruptTurn: (interrupt: ProviderAdapter.ProviderAdapterV2InterruptInput) =>
583
- interrupt.requestRuntimeRestart === true
584
- ? session.interruptTurn(interrupt)
585
- : Effect.never,
586
- })),
587
- ),
588
- };
589
-
590
- const result = yield* Effect.gen(function* () {
844
+ const resumes: Array<{
845
+ instanceId: ProviderInstanceId;
846
+ nativeId: string | null | undefined;
847
+ }> = [];
848
+ const messages: string[] = [];
849
+ const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
850
+ const adapters = [providerInstanceId, targetId].map((instanceId) => {
851
+ const base = makeRestartAdapter(state, capabilities, instanceId);
852
+ return {
853
+ ...base,
854
+ openSession: (input) =>
855
+ base.openSession(input).pipe(
856
+ Effect.map((session) => ({
857
+ ...session,
858
+ resumeThread: (input) =>
859
+ Effect.gen(function* () {
860
+ resumes.push({
861
+ instanceId,
862
+ nativeId: input.providerThread.nativeThreadRef?.nativeId,
863
+ });
864
+ return yield* session.resumeThread(input);
865
+ }),
866
+ startTurn: (input) =>
867
+ Effect.gen(function* () {
868
+ messages.push(input.message.text);
869
+ yield* session.startTurn(input);
870
+ }),
871
+ })),
872
+ ),
873
+ } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
874
+ });
875
+ const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
876
+ get: (instanceId) =>
877
+ Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
878
+ list: () => Effect.succeed([providerInstanceId, targetId]),
879
+ getMetadata: (instanceId) =>
880
+ Effect.succeed({
881
+ driver,
882
+ continuationKey:
883
+ mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
884
+ enabled: true,
885
+ capabilities,
886
+ }),
887
+ });
888
+ yield* Effect.gen(function* () {
889
const orchestrator = yield* Orchestrator.OrchestratorV2;
890
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
593
- const running = yield* orchestrator.streamDomainEvents.pipe(
594
- Stream.filter(
595
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
596
- ),
597
- Stream.take(1),
598
- Stream.runDrain,
599
- Effect.forkScoped({ startImmediately: true }),
600
- );
891
+ const selection = {
892
+ ...initialSelection,
893
+ model: mode === "active" ? initialSelection.model : "complete",
894
+ };
895
yield* orchestrator.dispatch({
896
type: "thread.create",
603
- createdBy: "user",
604
- creationSource: "web",
605
- commandId: CommandId.make("command:selection-restart-stop:create"),
897
+ commandId: CommandId.make(`${name}:create`),
898
threadId,
607
- projectId: ProjectId.make("project:selection-restart-stop"),
608
- title: "Stop during restart",
609
- modelSelection: initialSelection,
899
+ projectId: ProjectId.make(`project:${name}`),
900
+ title: name,
901
+ modelSelection: selection,
902
runtimeMode: "full-access",
903
interactionMode: "default",
904
branch: null,
905
worktreePath: cwd,
614
- });
615
- yield* orchestrator.dispatch({
616
- type: "message.dispatch",
906
createdBy: "user",
907
creationSource: "web",
619
- commandId: CommandId.make("command:selection-restart-stop:first"),
620
- threadId,
621
- messageId: MessageId.make("message:selection-restart-stop:first"),
622
- text: "first",
623
- attachments: [],
624
- modelSelection: initialSelection,
625
- dispatchMode: { type: "start_immediately" },
626
- });
627
- yield* worker.drain();
628
- yield* Fiber.join(running);
629
- const runId = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!.id;
630
-
631
- yield* orchestrator.dispatch({
632
- type: "message.dispatch",
633
- createdBy: "user",
634
- creationSource: "web",
635
- commandId: CommandId.make("command:selection-restart-stop:steer"),
636
- threadId,
637
- messageId: MessageId.make("message:selection-restart-stop:steer"),
638
- text: "Are you still going?",
639
- attachments: [],
640
- modelSelection: initialSelection,
641
- dispatchMode: { type: "restart_active", targetRunId: runId },
642
- });
643
- yield* orchestrator.dispatch({
644
- type: "run.interrupt",
645
- commandId: CommandId.make("command:selection-restart-stop:stop"),
646
- threadId,
647
- runId,
648
- });
649
- yield* worker.drain();
650
- return {
651
- projection: yield* orchestrator.getThreadProjection(threadId),
652
- captured: yield* Ref.get(state),
653
- };
654
- }).pipe(
655
- Effect.provide(
656
- ProviderReplayHarness.layerWithRegistry(
657
- { name: "selection-restart-stop" },
658
- ProviderAdapterRegistry.layerSingle(adapter),
659
- ),
660
- ),
661
- );
662
-
663
- assert.isNull(result.captured.activeTurn);
664
- assert.lengthOf(result.captured.started, 1);
665
- assert.equal(result.projection.runs[0]?.status, "interrupted");
666
- assert.deepEqual(
667
- result.projection.providerTurns.map((turn) => turn.status),
668
- ["interrupted"],
669
- );
670
- }),
671
- ),
672
-);
673
-
674
-it.live(
675
- "restarts the live session on a model change when a newer stopped session record exists",
676
- () =>
677
- Effect.scoped(
678
- Effect.gen(function* () {
679
- const name = "selection-restart-dead-stopped";
680
- const cwd = yield* checkpointWorkspace(name);
681
- const threadId = ThreadId.make(`thread:${name}`);
682
- const state = yield* Ref.make<RestartAdapterState>({
683
- activeTurn: null,
684
- opened: [],
685
- started: [],
686
- closedSessionCount: 0,
687
- failedReplacementOpen: true,
908
});
689
- const layerRegistry = ProviderAdapterRegistry.layerSingle(
690
- makeRestartAdapter(state, exclusiveCapabilities),
691
- );
692
-
693
- const result = yield* Effect.gen(function* () {
694
- const orchestrator = yield* Orchestrator.OrchestratorV2;
695
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
696
- const eventSink = yield* EventSink.EventSinkV2;
697
- const dispatch = (step: string, modelSelection: ModelSelection) =>
698
- Effect.gen(function* () {
699
- const terminal = yield* orchestrator.streamDomainEvents.pipe(
700
- Stream.filter(
701
- (event) => event.type === "run.updated" && event.payload.status === "completed",
702
- ),
703
- Stream.take(1),
704
- Stream.runDrain,
705
- Effect.forkScoped,
706
- );
707
- yield* orchestrator.dispatch({
708
- type: "message.dispatch",
709
- createdBy: "user",
710
- creationSource: "web",
711
- commandId: CommandId.make(`${name}:${step}`),
712
- threadId,
713
- messageId: MessageId.make(`${name}:${step}`),
714
- text: step,
715
- attachments: [],
716
- modelSelection,
717
- dispatchMode: { type: "start_immediately" },
718
- });
719
- yield* worker.drain();
720
- yield* Fiber.join(terminal);
721
- yield* worker.drain();
722
- return yield* orchestrator.getThreadProjection(threadId);
909
+ const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
910
+ Effect.gen(function* () {
911
+ const terminal = yield* orchestrator.streamDomainEvents.pipe(
912
+ Stream.filter((event) =>
913
+ mode === "active" && step === "first"
914
+ ? event.type === "provider-turn.updated" && event.payload.status === "running"
915
+ : event.type === "run.updated" && event.payload.status === "completed",
916
+ ),
917
+ Stream.take(1),
918
+ Stream.runDrain,
919
+ Effect.forkScoped,
920
+ );
921
+ yield* orchestrator.dispatch({
922
+ type: "message.dispatch",
923
+ commandId: CommandId.make(`${name}:${step}`),
924
+ threadId,
925
+ messageId: MessageId.make(`${name}:${step}`),
926
+ text: step,
927
+ attachments: [],
928
+ modelSelection,
929
+ dispatchMode:
930
+ targetRunId === undefined
931
+ ? { type: "start_immediately" }
932
+ : { type: "restart_active", targetRunId },
933
+ createdBy: "user",
934
+ creationSource: "web",
935
});
724
- yield* orchestrator.dispatch({
725
- type: "thread.create",
726
- createdBy: "user",
727
- creationSource: "web",
728
- commandId: CommandId.make(`${name}:create`),
729
- threadId,
730
- projectId: ProjectId.make(`project:${name}`),
731
- title: name,
732
- modelSelection: seedSelection,
733
- runtimeMode: "full-access",
734
- interactionMode: "default",
735
- branch: null,
736
- worktreePath: cwd,
737
- });
738
- const first = yield* dispatch("first", seedSelection);
739
- const liveSession = first.providerSessions.find(
740
- (session) => session.status !== "stopped" && session.status !== "error",
741
- );
742
- assert.isDefined(liveSession);
743
-
744
- const deadAt = yield* DateTime.now;
745
- const deadSession: OrchestrationV2ProviderSession = {
746
- id: ProviderSessionId.make(`session:${name}:dead`),
747
- driver,
748
- providerInstanceId,
749
- status: "ready",
750
- cwd,
751
- model: seedSelection.model,
752
- capabilities: exclusiveCapabilities,
753
- createdAt: deadAt,
754
- updatedAt: deadAt,
755
- lastError: null,
756
- };
757
- yield* eventSink.write({
758
- events: [
759
- {
760
- id: EventId.make(`event:${name}:dead-attached`),
761
- type: "provider-session.attached",
762
- threadId,
763
- driver,
764
- providerInstanceId,
765
- occurredAt: deadAt,
766
- payload: deadSession,
767
- },
768
- {
769
- id: EventId.make(`event:${name}:dead-updated`),
770
- type: "provider-session.updated",
771
- threadId,
772
- driver,
773
- providerInstanceId,
774
- occurredAt: deadAt,
775
- payload: {
776
- ...deadSession,
777
- status: "stopped",
778
- updatedAt: deadAt,
779
- lastError: null,
780
- },
781
- },
782
- ],
936
+ yield* worker.drain();
937
+ yield* Fiber.join(terminal);
938
+ yield* worker.drain();
939
+ return yield* orchestrator.getThreadProjection(threadId);
940
});
784
-
785
- const switchCommandId = CommandId.make(`${name}:switch`);
941
+ const first = yield* dispatch("first", selection);
942
+ const originalThread = first.providerThreads.find(
943
+ (thread) => thread.id === first.thread.activeProviderThreadId,
944
+ )!;
945
+ const targetSelection = { instanceId: targetId, model: "complete" };
946
+ if (mode === "selection-command") {
947
yield* orchestrator.dispatch({
787
- type: "thread.model-selection.set",
788
- commandId: switchCommandId,
948
+ type: "provider.switch",
949
+ commandId: CommandId.make(`${name}:switch`),
950
threadId,
790
- modelSelection: replacementSelection,
951
+ modelSelection: targetSelection,
952
});
953
yield* worker.drain();
793
- const storedSwitchEvents = yield* eventSink
794
- .readByCommandId({ commandId: switchCommandId })
795
- .pipe(Stream.runCollect);
796
- const detachedSessionIds = [...storedSwitchEvents].flatMap((stored) =>
797
- stored.event.type === "provider-session.detached"
798
- ? [stored.event.payload.providerSessionId]
799
- : [],
800
- );
801
-
802
- const second = yield* dispatch("second", replacementSelection);
803
- return {
804
- projection: second,
805
- captured: yield* Ref.get(state),
806
- liveSessionId: liveSession.id,
807
- detachedSessionIds,
808
- };
809
- }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
810
-
811
- const { projection, captured } = result;
812
- assert.lengthOf(projection.runs, 2);
813
- assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model);
814
- assert.deepEqual(modelSwitches(projection), [
815
- { from: seedSelection, to: replacementSelection },
816
- ]);
817
- assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]);
818
- assert.equal(captured.closedSessionCount, 1);
819
- assert.deepEqual(
820
- captured.opened.map((open) => open.model),
821
- [seedSelection.model, replacementSelection.model],
822
- );
823
- assert.deepEqual(
824
- captured.started.map((turn) => turn.model),
825
- [seedSelection.model, replacementSelection.model],
826
- );
827
- const servingSession = projection.providerSessions.find(
828
- (session) =>
829
- session.id ===
830
- projection.providerThreads.find(
831
- (providerThread) => providerThread.id === projection.thread.activeProviderThreadId,
832
- )?.providerSessionId,
954
+ }
955
+ const second = yield* dispatch(
956
+ "second",
957
+ targetSelection,
958
+ mode === "active" ? first.runs[0]!.id : undefined,
959
);
834
- assert.equal(servingSession?.model, replacementSelection.model);
835
- }),
836
- ),
837
-);
838
-
839
-it.live.each(["active", "idle", "selection-command", "pooled", "separate-home"] as const)(
840
- "preserves native history only for compatible account switches (%s)",
841
- (mode) =>
842
- Effect.scoped(
843
- Effect.gen(function* () {
844
- const name = `shared-home-${mode}`;
845
- const cwd = yield* checkpointWorkspace(name);
846
- const threadId = ThreadId.make(`thread:${name}`);
847
- const targetId = ProviderInstanceId.make("codex-shadow-account");
848
- const state = yield* Ref.make<RestartAdapterState>({
849
- activeTurn: null,
850
- opened: [],
851
- started: [],
852
- closedSessionCount: 0,
853
- failedReplacementOpen: true,
854
- });
855
- const resumes: Array<{
856
- instanceId: ProviderInstanceId;
857
- nativeId: string | null | undefined;
858
- }> = [];
859
- const messages: string[] = [];
860
- const capabilities = mode === "pooled" ? pooledCapabilities : exclusiveCapabilities;
861
- const adapters = [providerInstanceId, targetId].map((instanceId) => {
862
- const base = makeRestartAdapter(state, capabilities, instanceId);
863
- return {
864
- ...base,
865
- openSession: (input) =>
866
- base.openSession(input).pipe(
867
- Effect.map((session) => ({
868
- ...session,
869
- resumeThread: (input) =>
870
- Effect.gen(function* () {
871
- resumes.push({
872
- instanceId,
873
- nativeId: input.providerThread.nativeThreadRef?.nativeId,
874
- });
875
- return yield* session.resumeThread(input);
876
- }),
877
- startTurn: (input) =>
878
- Effect.gen(function* () {
879
- messages.push(input.message.text);
880
- yield* session.startTurn(input);
881
- }),
882
- })),
883
- ),
884
- } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
885
- });
886
- const layerRegistry = Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, {
887
- get: (instanceId) =>
888
- Effect.succeed(adapters.find((adapter) => adapter.instanceId === instanceId)!),
889
- list: () => Effect.succeed([providerInstanceId, targetId]),
890
- getMetadata: (instanceId) =>
891
- Effect.succeed({
892
- driver,
893
- continuationKey:
894
- mode === "separate-home" ? `codex:home:/${instanceId}` : "codex:home:/shared",
895
- enabled: true,
896
- capabilities,
897
- }),
898
- });
899
- yield* Effect.gen(function* () {
900
- const orchestrator = yield* Orchestrator.OrchestratorV2;
901
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
902
- const selection = {
903
- ...initialSelection,
904
- model: mode === "active" ? initialSelection.model : "complete",
905
- };
906
- yield* orchestrator.dispatch({
907
- type: "thread.create",
908
- commandId: CommandId.make(`${name}:create`),
909
- threadId,
910
- projectId: ProjectId.make(`project:${name}`),
911
- title: name,
912
- modelSelection: selection,
913
- runtimeMode: "full-access",
914
- interactionMode: "default",
915
- branch: null,
916
- worktreePath: cwd,
917
- createdBy: "user",
918
- creationSource: "web",
919
- });
920
- const dispatch = (step: string, modelSelection: ModelSelection, targetRunId?: RunId) =>
921
- Effect.gen(function* () {
922
- const terminal = yield* orchestrator.streamDomainEvents.pipe(
923
- Stream.filter((event) =>
924
- mode === "active" && step === "first"
925
- ? event.type === "provider-turn.updated" && event.payload.status === "running"
926
- : event.type === "run.updated" && event.payload.status === "completed",
927
- ),
928
- Stream.take(1),
929
- Stream.runDrain,
930
- Effect.forkScoped,
931
- );
932
- yield* orchestrator.dispatch({
933
- type: "message.dispatch",
934
- commandId: CommandId.make(`${name}:${step}`),
935
- threadId,
936
- messageId: MessageId.make(`${name}:${step}`),
937
- text: step,
938
- attachments: [],
939
- modelSelection,
940
- dispatchMode:
941
- targetRunId === undefined
942
- ? { type: "start_immediately" }
943
- : { type: "restart_active", targetRunId },
944
- createdBy: "user",
945
- creationSource: "web",
946
- });
947
- yield* worker.drain();
948
- yield* Fiber.join(terminal);
949
- yield* worker.drain();
950
- return yield* orchestrator.getThreadProjection(threadId);
951
- });
952
- const first = yield* dispatch("first", selection);
953
- const originalThread = first.providerThreads.find(
954
- (thread) => thread.id === first.thread.activeProviderThreadId,
955
- )!;
956
- const targetSelection = { instanceId: targetId, model: "complete" };
957
- if (mode === "selection-command") {
958
- yield* orchestrator.dispatch({
959
- type: "provider.switch",
960
- commandId: CommandId.make(`${name}:switch`),
961
- threadId,
962
- modelSelection: targetSelection,
963
- });
964
- yield* worker.drain();
965
- }
966
- const second = yield* dispatch(
967
- "second",
968
- targetSelection,
969
- mode === "active" ? first.runs[0]!.id : undefined,
960
+ const targetThread = second.providerThreads.find(
961
+ (thread) => thread.id === second.thread.activeProviderThreadId,
962
+ )!;
963
+ if (mode === "separate-home") {
964
+ assert.notEqual(targetThread.id, originalThread.id);
965
+ assert.lengthOf(second.contextHandoffs, 1);
966
+ assert.lengthOf(second.contextTransfers, 1);
967
+ assert.isEmpty(resumes);
968
+ assert.notEqual(messages[1], "second");
969
+ return;
970
+ }
971
+ assert.equal(targetThread.id, originalThread.id);
972
+ assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
973
+ assert.equal(targetThread.providerInstanceId, targetId);
974
+ assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
975
+ assert.isEmpty(second.contextHandoffs);
976
+ assert.isEmpty(second.contextTransfers);
977
+ assert.deepEqual(resumes, [
978
+ { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
979
+ ]);
980
+ assert.deepEqual(messages, ["first", "second"]);
981
+ assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
982
+ if (mode === "pooled") {
983
+ assert.isFalse(
984
+ second.providerSessions.some(
985
+ (session) => session.id === originalThread.providerSessionId,
986
+ ),
987
);
971
- const targetThread = second.providerThreads.find(
972
- (thread) => thread.id === second.thread.activeProviderThreadId,
973
- )!;
974
- if (mode === "separate-home") {
975
- assert.notEqual(targetThread.id, originalThread.id);
976
- assert.lengthOf(second.contextHandoffs, 1);
977
- assert.lengthOf(second.contextTransfers, 1);
978
- assert.isEmpty(resumes);
979
- assert.notEqual(messages[1], "second");
980
- return;
981
- }
982
- assert.equal(targetThread.id, originalThread.id);
983
- assert.deepEqual(targetThread.nativeThreadRef, originalThread.nativeThreadRef);
984
- assert.equal(targetThread.providerInstanceId, targetId);
985
- assert.notEqual(targetThread.providerSessionId, originalThread.providerSessionId);
986
- assert.isEmpty(second.contextHandoffs);
987
- assert.isEmpty(second.contextTransfers);
988
- assert.deepEqual(resumes, [
989
- { instanceId: targetId, nativeId: originalThread.nativeThreadRef?.nativeId },
990
- ]);
991
- assert.deepEqual(messages, ["first", "second"]);
992
- assert.equal((yield* Ref.get(state)).closedSessionCount, mode === "pooled" ? 0 : 1);
993
- if (mode === "pooled") {
994
- assert.isFalse(
995
- second.providerSessions.some(
996
- (session) => session.id === originalThread.providerSessionId,
997
- ),
998
- );
999
- }
1000
- const third = yield* dispatch("third", { ...selection, model: "complete" });
1001
- const returnedThread = third.providerThreads.find(
1002
- (thread) => thread.id === third.thread.activeProviderThreadId,
1003
- )!;
1004
- assert.equal(returnedThread.id, originalThread.id);
1005
- assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
1006
- assert.equal(returnedThread.providerInstanceId, providerInstanceId);
1007
- assert.isEmpty(third.contextHandoffs);
1008
- assert.deepEqual(messages, ["first", "second", "third"]);
1009
- }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
1010
- }),
1011
- ),
988
+ }
989
+ const third = yield* dispatch("third", { ...selection, model: "complete" });
990
+ const returnedThread = third.providerThreads.find(
991
+ (thread) => thread.id === third.thread.activeProviderThreadId,
992
+ )!;
993
+ assert.equal(returnedThread.id, originalThread.id);
994
+ assert.deepEqual(returnedThread.nativeThreadRef, originalThread.nativeThreadRef);
995
+ assert.equal(returnedThread.providerInstanceId, providerInstanceId);
996
+ assert.isEmpty(third.contextHandoffs);
997
+ assert.deepEqual(messages, ["first", "second", "third"]);
998
+ }).pipe(Effect.provide(ProviderReplayHarness.layerWithRegistry({ name }, layerRegistry)));
999
+ }),
1000
);
apps/server/src/orchestration-v2/ShellStream.test.ts
+137
-144
@@ -89,61 +89,59 @@ describe("subagent shell events", () => {
89
});
90
91
it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
92
- Effect.scoped(
93
- Effect.gen(function* () {
94
- const input = yield* Queue.unbounded<
95
- Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
96
- Cause.Done
97
- >();
98
- const drained = yield* Deferred.make<void>();
99
- const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
100
- const project = {
101
- id: ProjectId.make("same"),
102
- title: "Before",
103
- workspaceRoot: "/workspace/same",
104
- repositoryIdentity: null,
105
- defaultModelSelection: null,
106
- scripts: [],
107
- createdAt: "2026-09-01T00:00:00Z",
108
- updatedAt: "2026-09-01T00:00:00Z",
109
- };
110
- const initial = {
111
- kind: "thread.updated" as const,
112
- sequence: 1,
113
- location: "active" as const,
114
- thread: shell,
115
- };
116
- const updates = [
117
- { kind: "project.updated", sequence: 2, project },
118
- { ...initial, sequence: 3 },
119
- { ...initial, sequence: 4, location: "archive" },
120
- { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
121
- {
122
- kind: "project.updated",
123
- sequence: 6,
124
- project: { ...project, id: ProjectId.make("other") },
125
- },
126
- { kind: "project.removed", sequence: 7, projectId: project.id },
127
- { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
128
- { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
129
- { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
130
- { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
131
- ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
132
- const pull = yield* Stream.toPull(
133
- bufferShellLiveStream(
134
- Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
135
- { maxItems: 6, maxSerializedBytes: 1_500 },
136
- ),
137
- );
138
- yield* Queue.offer(input, initial);
139
- expect(yield* pull).toEqual([initial]);
140
- yield* Queue.offerAll(input, updates);
141
- yield* Queue.end(input);
142
- // Finish producing the burst while the first batch is still awaiting its ACK.
143
- yield* Deferred.await(drained);
144
- expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
145
- }),
146
- ),
92
+ Effect.gen(function* () {
93
+ const input = yield* Queue.unbounded<
94
+ Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
95
+ Cause.Done
96
+ >();
97
+ const drained = yield* Deferred.make<void>();
98
+ const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
99
+ const project = {
100
+ id: ProjectId.make("same"),
101
+ title: "Before",
102
+ workspaceRoot: "/workspace/same",
103
+ repositoryIdentity: null,
104
+ defaultModelSelection: null,
105
+ scripts: [],
106
+ createdAt: "2026-09-01T00:00:00Z",
107
+ updatedAt: "2026-09-01T00:00:00Z",
108
+ };
109
+ const initial = {
110
+ kind: "thread.updated" as const,
111
+ sequence: 1,
112
+ location: "active" as const,
113
+ thread: shell,
114
+ };
115
+ const updates = [
116
+ { kind: "project.updated", sequence: 2, project },
117
+ { ...initial, sequence: 3 },
118
+ { ...initial, sequence: 4, location: "archive" },
119
+ { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
120
+ {
121
+ kind: "project.updated",
122
+ sequence: 6,
123
+ project: { ...project, id: ProjectId.make("other") },
124
+ },
125
+ { kind: "project.removed", sequence: 7, projectId: project.id },
126
+ { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
127
+ { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
128
+ { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
129
+ { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
130
+ ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
131
+ const pull = yield* Stream.toPull(
132
+ bufferShellLiveStream(
133
+ Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
134
+ { maxItems: 6, maxSerializedBytes: 1_500 },
135
+ ),
136
+ );
137
+ yield* Queue.offer(input, initial);
138
+ expect(yield* pull).toEqual([initial]);
139
+ yield* Queue.offerAll(input, updates);
140
+ yield* Queue.end(input);
141
+ // Finish producing the burst while the first batch is still awaiting its ACK.
142
+ yield* Deferred.await(drained);
143
+ expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
144
+ }),
145
);
146
147
function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
@@ -365,101 +363,96 @@ describe("shellStreamItemsFromInitialSnapshot", () => {
363
364
describe("composeShellStreamWithEnrichment", () => {
365
it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () =>
368
- Effect.scoped(
369
- Effect.gen(function* () {
370
- // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
371
- const changes = yield* Effect.acquireRelease(
372
- PubSub.sliding<{ readonly workspaceRoot: string }>(256),
373
- PubSub.shutdown,
374
- );
375
- const subscription = yield* PubSub.subscribe(changes);
376
- const pull = yield* Stream.toPull(
377
- composeShellStreamWithEnrichment({
378
- initial: Stream.empty,
379
- tail: Stream.empty,
380
- enrichment: Stream.fromSubscription(subscription).pipe(
381
- Stream.groupedWithin(64, Duration.millis(25)),
382
- Stream.map((changes) =>
383
- shellStreamItemFromEnrichmentRefresh({
384
- snapshot: emptyShellSnapshot,
385
- changes,
386
- }),
387
- ),
366
+ Effect.gen(function* () {
367
+ // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
368
+ const changes = yield* Effect.acquireRelease(
369
+ PubSub.sliding<{ readonly workspaceRoot: string }>(256),
370
+ PubSub.shutdown,
371
+ );
372
+ const subscription = yield* PubSub.subscribe(changes);
373
+ const pull = yield* Stream.toPull(
374
+ composeShellStreamWithEnrichment({
375
+ initial: Stream.empty,
376
+ tail: Stream.empty,
377
+ enrichment: Stream.fromSubscription(subscription).pipe(
378
+ Stream.groupedWithin(64, Duration.millis(25)),
379
+ Stream.map((changes) =>
380
+ shellStreamItemFromEnrichmentRefresh({
381
+ snapshot: emptyShellSnapshot,
382
+ changes,
383
+ }),
384
),
389
- }),
390
- );
385
+ ),
386
+ }),
387
+ );
388
392
- const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
393
- yield* PubSub.publishAll(
394
- changes,
395
- firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
396
- );
397
- expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
398
-
399
- // The next completion can be batched before the client acknowledges the first.
400
- yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
401
- yield* Effect.yieldNow;
402
- yield* TestClock.adjust(Duration.millis(25));
403
- const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
404
- yield* PubSub.publishAll(
405
- changes,
406
- laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
407
- );
389
+ const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
390
+ yield* PubSub.publishAll(
391
+ changes,
392
+ firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
393
+ );
394
+ expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
395
+
396
+ // The next completion can be batched before the client acknowledges the first.
397
+ yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
398
+ yield* Effect.yieldNow;
399
+ yield* TestClock.adjust(Duration.millis(25));
400
+ const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
401
+ yield* PubSub.publishAll(
402
+ changes,
403
+ laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
404
+ );
405
409
- const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
410
- Stream.takeUntil(
411
- (item) =>
412
- item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
413
- ),
414
- Stream.runCollect,
415
- );
416
- expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
417
- "/workspace/pending",
418
- ...laterRoots,
419
- ]);
420
- }),
421
- ),
406
+ const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
407
+ Stream.takeUntil(
408
+ (item) => item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
409
+ ),
410
+ Stream.runCollect,
411
+ );
412
+ expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
413
+ "/workspace/pending",
414
+ ...laterRoots,
415
+ ]);
416
+ }),
417
);
418
419
it.effect("keeps a merged shell batch charged while the client withholds its ACK", () =>
425
- Effect.scoped(
426
- Effect.gen(function* () {
427
- const update = yield* Deferred.make<void>();
428
- const closed = yield* Deferred.make<void>();
429
- const initial = {
430
- kind: "thread.removed" as const,
431
- sequence: 1,
432
- location: "active" as const,
433
- threadId: ThreadId.make("thread-a"),
434
- };
435
- const pull = yield* Stream.toPull(
436
- composeShellStreamWithEnrichment({
437
- initial: Stream.empty,
438
- tail: bufferShellLiveStream(
439
- Stream.concat(
440
- Stream.succeed(initial),
441
- Stream.fromEffect(Deferred.await(update)).pipe(
442
- Stream.map(() => ({ ...initial, sequence: 2 })),
443
- ),
444
- ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
445
- { maxItems: 1 },
446
- ),
447
- enrichment: Stream.empty,
448
- }),
449
- );
450
- expect(yield* pull).toEqual([initial]);
451
- // Let the merge producer run while the client still withholds its ACK.
452
- yield* Effect.yieldNow;
453
- yield* Deferred.succeed(update, undefined);
454
- yield* Deferred.await(closed);
455
- const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
456
- Stream.runDrain,
457
- Effect.result,
458
- );
459
- expect(result._tag).toBe("Failure");
460
- if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
461
- }),
462
- ),
420
+ Effect.gen(function* () {
421
+ const update = yield* Deferred.make<void>();
422
+ const closed = yield* Deferred.make<void>();
423
+ const initial = {
424
+ kind: "thread.removed" as const,
425
+ sequence: 1,
426
+ location: "active" as const,
427
+ threadId: ThreadId.make("thread-a"),
428
+ };
429
+ const pull = yield* Stream.toPull(
430
+ composeShellStreamWithEnrichment({
431
+ initial: Stream.empty,
432
+ tail: bufferShellLiveStream(
433
+ Stream.concat(
434
+ Stream.succeed(initial),
435
+ Stream.fromEffect(Deferred.await(update)).pipe(
436
+ Stream.map(() => ({ ...initial, sequence: 2 })),
437
+ ),
438
+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
439
+ { maxItems: 1 },
440
+ ),
441
+ enrichment: Stream.empty,
442
+ }),
443
+ );
444
+ expect(yield* pull).toEqual([initial]);
445
+ // Let the merge producer run while the client still withholds its ACK.
446
+ yield* Effect.yieldNow;
447
+ yield* Deferred.succeed(update, undefined);
448
+ yield* Deferred.await(closed);
449
+ const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
450
+ Stream.runDrain,
451
+ Effect.result,
452
+ );
453
+ expect(result._tag).toBe("Failure");
454
+ if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
455
+ }),
456
);
457
458
it.effect(
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+2185
-2259
@@ -62,378 +62,231 @@ it.effect.each(
62
kind === "question" ? "delegated task question" : kind ? "mailbox notification" : "steering",
63
})),
64
)("delivers $label when completion wins $timing", ({ mailbox, question, timing }) =>
65
- Effect.scoped(
66
- Effect.gen(function* () {
67
- const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
68
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
69
- const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
70
- const steerEntered = yield* Deferred.make<void>();
71
- const rejectSteer = yield* Deferred.make<void>();
72
- let steerCalls = 0;
73
- const capabilities = {
74
- ...CodexProviderCapabilitiesV2,
75
- turns: {
76
- ...CodexProviderCapabilitiesV2.turns,
77
- supportsActiveSteering: timing !== "without native steering",
78
- activeSteeringInterruptsTools: timing === "with interrupting native steering",
79
- },
80
- };
81
- const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
82
- instanceId,
83
- driver,
84
- getCapabilities: () => Effect.succeed(capabilities),
85
- planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
86
- openSession: (input) =>
87
- Effect.gen(function* () {
88
- const now = yield* DateTime.now;
89
- return {
90
- instanceId,
65
+ Effect.gen(function* () {
66
+ const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
67
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
68
+ const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
69
+ const steerEntered = yield* Deferred.make<void>();
70
+ const rejectSteer = yield* Deferred.make<void>();
71
+ let steerCalls = 0;
72
+ const capabilities = {
73
+ ...CodexProviderCapabilitiesV2,
74
+ turns: {
75
+ ...CodexProviderCapabilitiesV2.turns,
76
+ supportsActiveSteering: timing !== "without native steering",
77
+ activeSteeringInterruptsTools: timing === "with interrupting native steering",
78
+ },
79
+ };
80
+ const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
81
+ instanceId,
82
+ driver,
83
+ getCapabilities: () => Effect.succeed(capabilities),
84
+ planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
85
+ openSession: (input) =>
86
+ Effect.gen(function* () {
87
+ const now = yield* DateTime.now;
88
+ return {
89
+ instanceId,
90
+ driver,
91
+ providerSessionId: input.providerSessionId,
92
+ providerSession: {
93
+ id: input.providerSessionId,
94
driver,
92
- providerSessionId: input.providerSessionId,
93
- providerSession: {
94
- id: input.providerSessionId,
95
+ providerInstanceId: instanceId,
96
+ status: "ready",
97
+ cwd,
98
+ model: modelSelection.model,
99
+ capabilities,
100
+ createdAt: now,
101
+ updatedAt: now,
102
+ lastError: null,
103
+ },
104
+ events: Stream.fromQueue(events),
105
+ ensureThread: ({ threadId }) =>
106
+ Effect.succeed({
107
+ id: ProviderThreadId.make(`provider-thread:${threadId}`),
108
driver,
109
providerInstanceId: instanceId,
97
- status: "ready",
98
- cwd,
99
- model: modelSelection.model,
100
- capabilities,
110
+ providerSessionId: input.providerSessionId,
111
+ appThreadId: threadId,
112
+ ownerNodeId: null,
113
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
114
+ nativeConversationHeadRef: null,
115
+ status: "idle",
116
+ firstRunOrdinal: null,
117
+ lastRunOrdinal: null,
118
+ handoffIds: [],
119
+ forkedFrom: null,
120
createdAt: now,
121
updatedAt: now,
103
- lastError: null,
104
- },
105
- events: Stream.fromQueue(events),
106
- ensureThread: ({ threadId }) =>
107
- Effect.succeed({
108
- id: ProviderThreadId.make(`provider-thread:${threadId}`),
122
+ }),
123
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
124
+ startTurn: (turn) =>
125
+ Effect.gen(function* () {
126
+ started.push(turn);
127
+ yield* Queue.offer(events, {
128
+ type: "provider_turn.updated",
129
driver,
110
- providerInstanceId: instanceId,
111
- providerSessionId: input.providerSessionId,
112
- appThreadId: threadId,
113
- ownerNodeId: null,
114
- nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
115
- nativeConversationHeadRef: null,
116
- status: "idle",
117
- firstRunOrdinal: null,
118
- lastRunOrdinal: null,
119
- handoffIds: [],
120
- forkedFrom: null,
121
- createdAt: now,
122
- updatedAt: now,
123
- }),
124
- resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
125
- startTurn: (turn) =>
126
- Effect.gen(function* () {
127
- started.push(turn);
128
- yield* Queue.offer(events, {
129
- type: "provider_turn.updated",
130
- driver,
131
- providerTurn: {
132
- id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
133
- providerThreadId: turn.providerThread.id,
134
- nodeId: turn.rootNodeId,
135
- runAttemptId: turn.attemptId,
136
- nativeTurnRef: {
137
- driver,
138
- nativeId: `native:${turn.attemptId}`,
139
- strength: "strong",
140
- },
141
- ordinal: turn.providerTurnOrdinal,
142
- status: "running",
143
- startedAt: now,
144
- completedAt: null,
145
- },
146
- });
147
- }),
148
- steerTurn: (turn) =>
149
- Effect.gen(function* () {
150
- steerCalls += 1;
151
- if (timing === "after delivery" || timing === "during continuation") return;
152
- yield* Deferred.succeed(steerEntered, undefined);
153
- yield* Deferred.await(rejectSteer);
154
- return yield* new ProviderAdapter.ProviderAdapterSteerRunError({
155
- driver,
130
+ providerTurn: {
131
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
132
providerThreadId: turn.providerThread.id,
157
- providerTurnId: turn.providerTurnId,
158
- cause: "turn already completed",
159
- });
160
- }),
161
- interruptTurn: () => Effect.void,
162
- respondToRuntimeRequest: () => Effect.void,
163
- readThreadSnapshot: () => Effect.die("unused"),
164
- rollbackThread: () => Effect.die("unused"),
165
- forkThread: () => Effect.die("unused"),
166
- };
167
- }),
168
- };
169
- yield* Effect.gen(function* () {
170
- const orchestrator = yield* Orchestrator.OrchestratorV2;
171
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
172
- const threadId = ThreadId.make("thread:steering-completion");
173
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
174
- orchestrator.streamDomainEvents.pipe(
175
- Stream.filter(predicate),
176
- Stream.take(1),
177
- Stream.runDrain,
178
- Effect.forkScoped,
179
- );
180
- yield* orchestrator.dispatch({
181
- type: "thread.create",
182
- commandId: CommandId.make("create"),
183
- threadId,
184
- projectId: ProjectId.make("project:steering-completion"),
185
- title: "Steering race",
186
- modelSelection,
187
- runtimeMode: "full-access",
188
- interactionMode: "default",
189
- branch: null,
190
- worktreePath: cwd,
191
- createdBy: "user",
192
- creationSource: "web",
193
- });
194
- yield* orchestrator.dispatch({
195
- type: "message.dispatch",
196
- commandId: CommandId.make("first"),
197
- threadId,
198
- messageId: MessageId.make("message:first"),
199
- text: "first",
200
- attachments: [],
201
- dispatchMode: { type: "start_immediately" },
202
- createdBy: "user",
203
- creationSource: "web",
204
- });
205
- const running = yield* watch(
206
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
207
- );
208
- yield* worker.drain();
209
- yield* Fiber.join(running);
210
- const first = started[0]!;
211
- const messageId = MessageId.make("message:steering");
212
- const taskId = NodeId.make("task:mailbox");
213
- if (mailbox) {
214
- const sink = yield* EventSink.EventSinkV2;
215
- const current = yield* orchestrator.getThreadProjection(threadId);
216
- const parentRun = current.runs.find((run) => run.id === first.runId)!;
217
- const now = yield* DateTime.now;
218
- yield* sink.write({
219
- events: [
220
- {
221
- id: EventId.make("mailbox:cohort"),
222
- type: "run.updated",
223
- threadId,
224
- runId: first.runId,
225
- occurredAt: now,
226
- payload: {
227
- ...parentRun,
228
- delegatedCompletion: {
229
- disposition: "open",
230
- nextGeneration: 2,
231
- delivery: { generation: 1, messageId, taskIds: [taskId] },
133
+ nodeId: turn.rootNodeId,
134
+ runAttemptId: turn.attemptId,
135
+ nativeTurnRef: {
136
+ driver,
137
+ nativeId: `native:${turn.attemptId}`,
138
+ strength: "strong",
139
+ },
140
+ ordinal: turn.providerTurnOrdinal,
141
+ status: "running",
142
+ startedAt: now,
143
+ completedAt: null,
144
},
233
- },
234
- },
235
- {
236
- id: EventId.make("mailbox:task"),
237
- type: "subagent.updated",
238
- threadId,
239
- runId: first.runId,
240
- nodeId: taskId,
241
- occurredAt: now,
242
- payload: {
243
- id: taskId,
244
- threadId,
245
- runId: first.runId,
246
- parentNodeId: first.rootNodeId,
247
- origin: "app_owned",
248
- createdBy: "agent",
145
+ });
146
+ }),
147
+ steerTurn: (turn) =>
148
+ Effect.gen(function* () {
149
+ steerCalls += 1;
150
+ if (timing === "after delivery" || timing === "during continuation") return;
151
+ yield* Deferred.succeed(steerEntered, undefined);
152
+ yield* Deferred.await(rejectSteer);
153
+ return yield* new ProviderAdapter.ProviderAdapterSteerRunError({
154
driver,
250
- providerInstanceId: instanceId,
251
- providerThreadId: null,
252
- childThreadId: null,
253
- nativeTaskRef: null,
254
- prompt: "Do background work",
255
- title: "Background test",
256
- model: null,
257
- completionWake: timing === "settled only" ? "settled_only" : "always",
258
- completionDelivery: { state: "claimed", observedByRunId: null },
259
- status: "completed",
260
- result: "done",
261
- startedAt: now,
262
- completedAt: now,
263
- updatedAt: now,
155
+ providerThreadId: turn.providerThread.id,
156
+ providerTurnId: turn.providerTurnId,
157
+ cause: "turn already completed",
158
+ });
159
+ }),
160
+ interruptTurn: () => Effect.void,
161
+ respondToRuntimeRequest: () => Effect.void,
162
+ readThreadSnapshot: () => Effect.die("unused"),
163
+ rollbackThread: () => Effect.die("unused"),
164
+ forkThread: () => Effect.die("unused"),
165
+ };
166
+ }),
167
+ };
168
+ yield* Effect.gen(function* () {
169
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
170
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
171
+ const threadId = ThreadId.make("thread:steering-completion");
172
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
173
+ orchestrator.streamDomainEvents.pipe(
174
+ Stream.filter(predicate),
175
+ Stream.take(1),
176
+ Stream.runDrain,
177
+ Effect.forkScoped,
178
+ );
179
+ yield* orchestrator.dispatch({
180
+ type: "thread.create",
181
+ commandId: CommandId.make("create"),
182
+ threadId,
183
+ projectId: ProjectId.make("project:steering-completion"),
184
+ title: "Steering race",
185
+ modelSelection,
186
+ runtimeMode: "full-access",
187
+ interactionMode: "default",
188
+ branch: null,
189
+ worktreePath: cwd,
190
+ createdBy: "user",
191
+ creationSource: "web",
192
+ });
193
+ yield* orchestrator.dispatch({
194
+ type: "message.dispatch",
195
+ commandId: CommandId.make("first"),
196
+ threadId,
197
+ messageId: MessageId.make("message:first"),
198
+ text: "first",
199
+ attachments: [],
200
+ dispatchMode: { type: "start_immediately" },
201
+ createdBy: "user",
202
+ creationSource: "web",
203
+ });
204
+ const running = yield* watch(
205
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
206
+ );
207
+ yield* worker.drain();
208
+ yield* Fiber.join(running);
209
+ const first = started[0]!;
210
+ const messageId = MessageId.make("message:steering");
211
+ const taskId = NodeId.make("task:mailbox");
212
+ if (mailbox) {
213
+ const sink = yield* EventSink.EventSinkV2;
214
+ const current = yield* orchestrator.getThreadProjection(threadId);
215
+ const parentRun = current.runs.find((run) => run.id === first.runId)!;
216
+ const now = yield* DateTime.now;
217
+ yield* sink.write({
218
+ events: [
219
+ {
220
+ id: EventId.make("mailbox:cohort"),
221
+ type: "run.updated",
222
+ threadId,
223
+ runId: first.runId,
224
+ occurredAt: now,
225
+ payload: {
226
+ ...parentRun,
227
+ delegatedCompletion: {
228
+ disposition: "open",
229
+ nextGeneration: 2,
230
+ delivery: { generation: 1, messageId, taskIds: [taskId] },
231
},
232
},
266
- ],
267
- });
268
- }
269
- if (question) {
270
- const { thread } = yield* orchestrator.getThreadProjection(threadId);
271
- yield* (yield* EventSink.EventSinkV2).write({
272
- events: [
273
- {
274
- id: EventId.make("event:composer-selection"),
275
- type: "thread.model-selection-updated",
233
+ },
234
+ {
235
+ id: EventId.make("mailbox:task"),
236
+ type: "subagent.updated",
237
+ threadId,
238
+ runId: first.runId,
239
+ nodeId: taskId,
240
+ occurredAt: now,
241
+ payload: {
242
+ id: taskId,
243
threadId,
244
+ runId: first.runId,
245
+ parentNodeId: first.rootNodeId,
246
+ origin: "app_owned",
247
+ createdBy: "agent",
248
+ driver,
249
providerInstanceId: instanceId,
278
- occurredAt: yield* DateTime.now,
279
- payload: { ...thread, modelSelection: composerSelection },
250
+ providerThreadId: null,
251
+ childThreadId: null,
252
+ nativeTaskRef: null,
253
+ prompt: "Do background work",
254
+ title: "Background test",
255
+ model: null,
256
+ completionWake: timing === "settled only" ? "settled_only" : "always",
257
+ completionDelivery: { state: "claimed", observedByRunId: null },
258
+ status: "completed",
259
+ result: "done",
260
+ startedAt: now,
261
+ completedAt: now,
262
+ updatedAt: now,
263
},
281
- ],
282
- });
283
- }
284
- const dispatchSteer = orchestrator.dispatch({
285
- type: "message.dispatch",
286
- commandId: CommandId.make("steer"),
287
- threadId,
288
- messageId,
289
- text: "fix the popover",
290
- attachments: [
291
- {
292
- type: "image",
293
- id: "steering-screenshot",
294
- name: "image.png",
295
- mimeType: "image/png",
296
- sizeBytes: 10,
264
},
265
],
299
- dispatchMode:
300
- mailbox || question
301
- ? { type: "queue_after_active" }
302
- : { type: "steer_active", targetRunId: first.runId },
303
- createdBy: mailbox || question ? "agent" : "user",
304
- creationSource: mailbox || question ? "server" : "web",
305
- ...(question
306
- ? {
307
- notification: {
308
- source: { kind: "delegated_task", taskIds: [taskId] },
309
- outcome: "updated",
310
- summary: "Delegated task has a question",
311
- },
312
- }
313
- : {}),
314
- ...(mailbox
315
- ? {
316
- delegatedCompletion: {
317
- parentRunId: first.runId,
318
- generation: 1,
319
- taskIds: [taskId],
320
- },
321
- }
322
- : {}),
323
- });
324
- if (timing !== "before dispatch") yield* dispatchSteer;
325
- if (timing === "during continuation") {
326
- const projection = yield* orchestrator.getThreadProjection(threadId);
327
- const turn = projection.providerTurns[0]!;
328
- const failed = yield* watch(
329
- (event) => event.type === "provider-turn.updated" && event.payload.status === "failed",
330
- );
331
- yield* Queue.offer(events, {
332
- type: "provider_turn.updated",
333
- driver,
334
- providerTurn: { ...turn, status: "failed", completedAt: yield* DateTime.now },
335
- });
336
- yield* Fiber.join(failed);
337
- yield* worker.drain();
338
- assert.equal(steerCalls, 1);
339
- assert.lengthOf(started, 1);
340
- const continued = yield* orchestrator.getThreadProjection(threadId);
341
- assert.equal(continued.runs[0]?.status, "running");
342
- assert.equal(
343
- continued.messages.find((message) => message.id === messageId)?.runId,
344
- first.runId,
345
- );
346
- return;
347
- }
348
- if (timing === "after delivery") yield* worker.drain();
349
- const delivery =
350
- timing === "during delivery" ? yield* worker.runOnce().pipe(Effect.forkScoped) : null;
351
- if (delivery !== null) yield* Deferred.await(steerEntered);
352
- const completed = yield* watch(
353
- (event) =>
354
- event.type === "run.updated" &&
355
- event.payload.id === first.runId &&
356
- event.payload.status === "waiting",
357
- );
358
- const projection = yield* orchestrator.getThreadProjection(threadId);
359
- const turn = projection.providerTurns[0]!;
360
- yield* Queue.offer(events, {
361
- type: "provider_turn.updated",
362
- driver,
363
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
364
- });
365
- yield* Queue.offer(events, {
366
- type: "turn.terminal",
367
- driver,
368
- providerThreadId: turn.providerThreadId,
369
- providerTurnId: turn.id,
370
- runOrdinal: first.runOrdinal,
371
- status: "completed",
372
- failure: null,
373
- threadDisposition: "reusable",
266
});
375
- yield* Fiber.join(completed);
376
- if (delivery !== null) {
377
- yield* Deferred.succeed(rejectSteer, undefined);
378
- yield* Fiber.join(delivery);
379
- }
380
- if (delivery !== null && !question) {
381
- const requeued = yield* orchestrator.getThreadProjection(threadId);
382
- assert.isTrue(requeued.runs.some((run) => run.status === "queued"));
383
- assert.isFalse(
384
- requeued.visibleTurnItems.some(
385
- ({ item }) => item.type === "user_message" && item.messageId === messageId,
386
- ),
387
- "a steer that fell back to the queue must not appear delivered",
388
- );
389
- const item = requeued.turnItems.find(
390
- (item) => item.type === "user_message" && item.messageId === messageId,
391
- );
392
- assert.equal(item?.status, "pending");
393
- assert.isNull(item?.startedAt);
394
- assert.isNull(item?.completedAt);
395
- }
396
- if (timing === "before dispatch") yield* dispatchSteer;
397
- yield* worker.drain();
398
- yield* orchestrator.resumeQueuedRuns;
399
- yield* worker.drain();
400
- if (timing === "after delivery") {
401
- assert.equal(steerCalls, 1);
402
- assert.equal(started.length, 1);
403
- if (mailbox) {
404
- const delivered = yield* orchestrator.getThreadProjection(threadId);
405
- assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
406
- assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
407
- assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
408
- assert.equal(
409
- delivered.turnItems.filter((item) => item.type === "notification").length,
410
- 1,
411
- );
412
- yield* orchestrator.dispatch({
413
- type: "notification.delivery.accept",
414
- commandId: CommandId.make("duplicate-acceptance"),
267
+ }
268
+ if (question) {
269
+ const { thread } = yield* orchestrator.getThreadProjection(threadId);
270
+ yield* (yield* EventSink.EventSinkV2).write({
271
+ events: [
272
+ {
273
+ id: EventId.make("event:composer-selection"),
274
+ type: "thread.model-selection-updated",
275
threadId,
416
- messageId,
417
- });
418
- yield* worker.drain();
419
- assert.equal(steerCalls, 1);
420
- yield* orchestrator.dispatch({
421
- type: "delegated_task.completion-delivery.acknowledge",
422
- commandId: CommandId.make("read-result"),
423
- parentThreadId: threadId,
424
- taskId,
425
- observedByRunId: first.runId,
426
- });
427
- const acknowledged = yield* orchestrator.getThreadProjection(threadId);
428
- assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
429
- }
430
- return;
431
- }
432
- assert.equal(started.length, 2);
433
- assert.equal(started[1]?.message.messageId, messageId);
434
- if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
435
- else assert.equal(started[1]?.message.text, "fix the popover");
436
- assert.deepEqual(started[1]?.message.attachments, [
276
+ providerInstanceId: instanceId,
277
+ occurredAt: yield* DateTime.now,
278
+ payload: { ...thread, modelSelection: composerSelection },
279
+ },
280
+ ],
281
+ });
282
+ }
283
+ const dispatchSteer = orchestrator.dispatch({
284
+ type: "message.dispatch",
285
+ commandId: CommandId.make("steer"),
286
+ threadId,
287
+ messageId,
288
+ text: "fix the popover",
289
+ attachments: [
290
{
291
type: "image",
292
id: "steering-screenshot",
@@ -441,55 +294,200 @@ it.effect.each(
294
mimeType: "image/png",
295
sizeBytes: 10,
296
},
444
- ]);
445
- assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
446
- const final = yield* orchestrator.getThreadProjection(threadId);
447
- if (question) {
448
- assert.deepEqual(final.thread.modelSelection, composerSelection);
449
- assert.deepEqual(started[1]?.modelSelection, composerSelection);
450
- }
451
- if (!mailbox && !question) {
297
+ ],
298
+ dispatchMode:
299
+ mailbox || question
300
+ ? { type: "queue_after_active" }
301
+ : { type: "steer_active", targetRunId: first.runId },
302
+ createdBy: mailbox || question ? "agent" : "user",
303
+ creationSource: mailbox || question ? "server" : "web",
304
+ ...(question
305
+ ? {
306
+ notification: {
307
+ source: { kind: "delegated_task", taskIds: [taskId] },
308
+ outcome: "updated",
309
+ summary: "Delegated task has a question",
310
+ },
311
+ }
312
+ : {}),
313
+ ...(mailbox
314
+ ? {
315
+ delegatedCompletion: {
316
+ parentRunId: first.runId,
317
+ generation: 1,
318
+ taskIds: [taskId],
319
+ },
320
+ }
321
+ : {}),
322
+ });
323
+ if (timing !== "before dispatch") yield* dispatchSteer;
324
+ if (timing === "during continuation") {
325
+ const projection = yield* orchestrator.getThreadProjection(threadId);
326
+ const turn = projection.providerTurns[0]!;
327
+ const failed = yield* watch(
328
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "failed",
329
+ );
330
+ yield* Queue.offer(events, {
331
+ type: "provider_turn.updated",
332
+ driver,
333
+ providerTurn: { ...turn, status: "failed", completedAt: yield* DateTime.now },
334
+ });
335
+ yield* Fiber.join(failed);
336
+ yield* worker.drain();
337
+ assert.equal(steerCalls, 1);
338
+ assert.lengthOf(started, 1);
339
+ const continued = yield* orchestrator.getThreadProjection(threadId);
340
+ assert.equal(continued.runs[0]?.status, "running");
341
+ assert.equal(
342
+ continued.messages.find((message) => message.id === messageId)?.runId,
343
+ first.runId,
344
+ );
345
+ return;
346
+ }
347
+ if (timing === "after delivery") yield* worker.drain();
348
+ const delivery =
349
+ timing === "during delivery" ? yield* worker.runOnce().pipe(Effect.forkScoped) : null;
350
+ if (delivery !== null) yield* Deferred.await(steerEntered);
351
+ const completed = yield* watch(
352
+ (event) =>
353
+ event.type === "run.updated" &&
354
+ event.payload.id === first.runId &&
355
+ event.payload.status === "waiting",
356
+ );
357
+ const projection = yield* orchestrator.getThreadProjection(threadId);
358
+ const turn = projection.providerTurns[0]!;
359
+ yield* Queue.offer(events, {
360
+ type: "provider_turn.updated",
361
+ driver,
362
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
363
+ });
364
+ yield* Queue.offer(events, {
365
+ type: "turn.terminal",
366
+ driver,
367
+ providerThreadId: turn.providerThreadId,
368
+ providerTurnId: turn.id,
369
+ runOrdinal: first.runOrdinal,
370
+ status: "completed",
371
+ failure: null,
372
+ threadDisposition: "reusable",
373
+ });
374
+ yield* Fiber.join(completed);
375
+ if (delivery !== null) {
376
+ yield* Deferred.succeed(rejectSteer, undefined);
377
+ yield* Fiber.join(delivery);
378
+ }
379
+ if (delivery !== null && !question) {
380
+ const requeued = yield* orchestrator.getThreadProjection(threadId);
381
+ assert.isTrue(requeued.runs.some((run) => run.status === "queued"));
382
+ assert.isFalse(
383
+ requeued.visibleTurnItems.some(
384
+ ({ item }) => item.type === "user_message" && item.messageId === messageId,
385
+ ),
386
+ "a steer that fell back to the queue must not appear delivered",
387
+ );
388
+ const item = requeued.turnItems.find(
389
+ (item) => item.type === "user_message" && item.messageId === messageId,
390
+ );
391
+ assert.equal(item?.status, "pending");
392
+ assert.isNull(item?.startedAt);
393
+ assert.isNull(item?.completedAt);
394
+ }
395
+ if (timing === "before dispatch") yield* dispatchSteer;
396
+ yield* worker.drain();
397
+ yield* orchestrator.resumeQueuedRuns;
398
+ yield* worker.drain();
399
+ if (timing === "after delivery") {
400
+ assert.equal(steerCalls, 1);
401
+ assert.equal(started.length, 1);
402
+ if (mailbox) {
403
+ const delivered = yield* orchestrator.getThreadProjection(threadId);
404
+ assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
405
+ assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
406
+ assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
407
assert.equal(
453
- final.turnItems.find(
454
- (item) => item.type === "user_message" && item.messageId === messageId,
455
- )?.status,
456
- "completed",
408
+ delivered.turnItems.filter((item) => item.type === "notification").length,
409
+ 1,
410
);
411
+ yield* orchestrator.dispatch({
412
+ type: "notification.delivery.accept",
413
+ commandId: CommandId.make("duplicate-acceptance"),
414
+ threadId,
415
+ messageId,
416
+ });
417
+ yield* worker.drain();
418
+ assert.equal(steerCalls, 1);
419
+ yield* orchestrator.dispatch({
420
+ type: "delegated_task.completion-delivery.acknowledge",
421
+ commandId: CommandId.make("read-result"),
422
+ parentThreadId: threadId,
423
+ taskId,
424
+ observedByRunId: first.runId,
425
+ });
426
+ const acknowledged = yield* orchestrator.getThreadProjection(threadId);
427
+ assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
428
}
459
- assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
429
+ return;
430
+ }
431
+ assert.equal(started.length, 2);
432
+ assert.equal(started[1]?.message.messageId, messageId);
433
+ if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
434
+ else assert.equal(started[1]?.message.text, "fix the popover");
435
+ assert.deepEqual(started[1]?.message.attachments, [
436
+ {
437
+ type: "image",
438
+ id: "steering-screenshot",
439
+ name: "image.png",
440
+ mimeType: "image/png",
441
+ sizeBytes: 10,
442
+ },
443
+ ]);
444
+ assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
445
+ const final = yield* orchestrator.getThreadProjection(threadId);
446
+ if (question) {
447
+ assert.deepEqual(final.thread.modelSelection, composerSelection);
448
+ assert.deepEqual(started[1]?.modelSelection, composerSelection);
449
+ }
450
+ if (!mailbox && !question) {
451
assert.equal(
461
- final.messages.find((message) => message.id === messageId)?.runId,
462
- started[1]?.runId,
452
+ final.turnItems.find(
453
+ (item) => item.type === "user_message" && item.messageId === messageId,
454
+ )?.status,
455
+ "completed",
456
);
457
+ }
458
+ assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
459
+ assert.equal(
460
+ final.messages.find((message) => message.id === messageId)?.runId,
461
+ started[1]?.runId,
462
+ );
463
+ assert.equal(
464
+ final.turnItems.filter((item) =>
465
+ mailbox || question
466
+ ? item.type === "notification"
467
+ : item.type === "user_message" && item.messageId === messageId,
468
+ ).length,
469
+ 1,
470
+ );
471
+ if (!mailbox && !question) {
472
assert.equal(
465
- final.turnItems.filter((item) =>
466
- mailbox || question
467
- ? item.type === "notification"
468
- : item.type === "user_message" && item.messageId === messageId,
473
+ final.visibleTurnItems.filter(
474
+ ({ item }) => item.type === "user_message" && item.messageId === messageId,
475
).length,
476
1,
477
);
472
- if (!mailbox && !question) {
473
- assert.equal(
474
- final.visibleTurnItems.filter(
475
- ({ item }) => item.type === "user_message" && item.messageId === messageId,
476
- ).length,
477
- 1,
478
- );
479
- }
480
- yield* worker.drain();
481
- assert.equal(started.length, 2);
482
- }).pipe(
483
- Effect.provide(
484
- ProviderReplayHarness.layerWithRegistry(
485
- { name: `steering-completion-${timing}` },
486
- ProviderAdapterRegistry.layerSingle(adapter),
487
- { runEffectWorker: false },
488
- ),
478
+ }
479
+ yield* worker.drain();
480
+ assert.equal(started.length, 2);
481
+ }).pipe(
482
+ Effect.provide(
483
+ ProviderReplayHarness.layerWithRegistry(
484
+ { name: `steering-completion-${timing}` },
485
+ ProviderAdapterRegistry.layerSingle(adapter),
486
+ { runEffectWorker: false },
487
),
490
- );
491
- }),
492
- ),
488
+ ),
489
+ );
490
+ }),
491
);
492
493
const runSelection = {
@@ -689,183 +687,179 @@ it.effect.each([
687
] as const)(
688
"a $notice notice steers into the running turn: $steers (goal $goal)",
689
({ notice, goal, steers }) =>
692
- Effect.scoped(
693
- Effect.gen(function* () {
694
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
695
- `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`,
696
- );
697
- yield* Effect.gen(function* () {
698
- const orchestrator = yield* Orchestrator.OrchestratorV2;
699
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
700
- const threadId = yield* startFirstTurn;
701
- const { thread } = yield* orchestrator.getThreadProjection(threadId);
702
- yield* (yield* EventSink.EventSinkV2).write({
703
- events: [
704
- {
705
- id: EventId.make("event:composer-selection"),
706
- type: "thread.model-selection-updated",
707
- threadId,
708
- providerInstanceId: instanceId,
709
- occurredAt: yield* DateTime.now,
710
- payload: { ...thread, modelSelection: composerSelection },
711
- },
712
- ],
713
- });
714
- if (goal !== null) {
715
- const providerThread = (yield* orchestrator.getThreadProjection(threadId))
716
- .providerThreads[0]!;
717
- yield* (yield* EventSink.EventSinkV2).write({
718
- events: [
719
- {
720
- id: EventId.make("event:goal-active"),
721
- type: "provider-thread.updated",
722
- threadId,
723
- occurredAt: yield* DateTime.now,
724
- payload: { ...providerThread, goal: { objective: "Ship it", status: goal } },
725
- },
726
- ],
727
- });
728
- }
729
- const messageId = MessageId.make("message:notice");
730
- const notification =
731
- notice === "delegated task question"
732
- ? {
733
- source: {
734
- kind: "delegated_task" as const,
735
- taskIds: [NodeId.make("task:question")],
736
- childThreadId: ThreadId.make("thread:question-child"),
737
- },
738
- outcome: "updated" as const,
739
- summary: "Delegated task has a question",
740
- }
741
- : {
742
- source: { kind: "command" as const },
743
- outcome: "completed" as const,
744
- summary: "Background command finished",
745
- };
746
- yield* orchestrator.dispatch({
747
- type: "message.dispatch",
748
- commandId: CommandId.make("notice-wake"),
749
- threadId,
750
- messageId,
751
- text: `${notification.summary}\nexit 0: built 12 files`,
752
- notification,
753
- attachments: [],
754
- dispatchMode: { type: "queue_after_active" },
755
- createdBy: "agent",
756
- creationSource: "server",
757
- });
758
- yield* worker.drain();
759
- const after = yield* orchestrator.getThreadProjection(threadId);
760
- assert.deepEqual(
761
- steered,
762
- steers ? [`${notification.summary}\nexit 0: built 12 files`] : [],
763
- );
764
- assert.lengthOf(started, 1);
765
- assert.equal(
766
- after.runs.some((run) => run.status === "queued"),
767
- !steers,
768
- );
769
- const message = after.messages.find((candidate) => candidate.id === messageId);
770
- assert.deepEqual(message?.notification, notification);
771
- if (steers) assert.equal(message?.runId, started[0]?.runId);
772
- assert.deepEqual(after.thread.modelSelection, composerSelection);
773
- }).pipe(Effect.provide(layer));
774
- }),
775
- ),
776
-);
777
-
778
-it.effect("sends a selected held message once and preserves the remaining queue order", () =>
779
- Effect.scoped(
690
Effect.gen(function* () {
781
- const { started, steered, layer, startFirstTurn } =
782
- yield* nextTurnSelectionHarness("send-held-message");
691
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
692
+ `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`,
693
+ );
694
yield* Effect.gen(function* () {
695
const orchestrator = yield* Orchestrator.OrchestratorV2;
696
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
697
const threadId = yield* startFirstTurn;
787
- yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
788
- orchestrator.dispatch({
789
- type: "message.dispatch",
790
- commandId: CommandId.make(text),
791
- threadId,
792
- messageId: MessageId.make(`message:${text}`),
793
- text,
794
- attachments: [],
795
- modelSelection: runSelection,
796
- dispatchMode: { type: "queue_after_active" },
797
- createdBy: "user",
798
- creationSource: "web",
799
- }),
800
- );
801
- const before = yield* orchestrator.getThreadProjection(threadId);
802
- const selected = before.runs.find(
803
- (run) => run.userMessageId === MessageId.make("message:selected"),
804
- )!;
805
- const sink = yield* EventSink.EventSinkV2;
806
- const now = yield* DateTime.now;
807
- // Restart recovery cancels the active run and holds every queued message.
808
- yield* sink.write({
698
+ const { thread } = yield* orchestrator.getThreadProjection(threadId);
699
+ yield* (yield* EventSink.EventSinkV2).write({
700
events: [
810
- ...before.runs.map((run) => ({
811
- id: EventId.make(`restart:${run.id}`),
812
- type: "run.updated" as const,
813
- threadId,
814
- runId: run.id,
815
- occurredAt: now,
816
- payload:
817
- run.status === "queued"
818
- ? { ...run, queueHeld: true }
819
- : { ...run, status: "cancelled" as const, completedAt: now },
820
- })),
821
- ...before.providerTurns.map((turn) => ({
822
- id: EventId.make(`restart:${turn.id}`),
823
- type: "provider-turn.updated" as const,
701
+ {
702
+ id: EventId.make("event:composer-selection"),
703
+ type: "thread.model-selection-updated",
704
threadId,
825
- occurredAt: now,
826
- payload: { ...turn, status: "cancelled" as const, completedAt: now },
827
- })),
705
+ providerInstanceId: instanceId,
706
+ occurredAt: yield* DateTime.now,
707
+ payload: { ...thread, modelSelection: composerSelection },
708
+ },
709
],
710
});
830
- const command = {
831
- type: "queued-run.start" as const,
832
- commandId: CommandId.make("send-selected"),
711
+ if (goal !== null) {
712
+ const providerThread = (yield* orchestrator.getThreadProjection(threadId))
713
+ .providerThreads[0]!;
714
+ yield* (yield* EventSink.EventSinkV2).write({
715
+ events: [
716
+ {
717
+ id: EventId.make("event:goal-active"),
718
+ type: "provider-thread.updated",
719
+ threadId,
720
+ occurredAt: yield* DateTime.now,
721
+ payload: { ...providerThread, goal: { objective: "Ship it", status: goal } },
722
+ },
723
+ ],
724
+ });
725
+ }
726
+ const messageId = MessageId.make("message:notice");
727
+ const notification =
728
+ notice === "delegated task question"
729
+ ? {
730
+ source: {
731
+ kind: "delegated_task" as const,
732
+ taskIds: [NodeId.make("task:question")],
733
+ childThreadId: ThreadId.make("thread:question-child"),
734
+ },
735
+ outcome: "updated" as const,
736
+ summary: "Delegated task has a question",
737
+ }
738
+ : {
739
+ source: { kind: "command" as const },
740
+ outcome: "completed" as const,
741
+ summary: "Background command finished",
742
+ };
743
+ yield* orchestrator.dispatch({
744
+ type: "message.dispatch",
745
+ commandId: CommandId.make("notice-wake"),
746
threadId,
834
- runId: selected.id,
835
- };
836
- yield* orchestrator.dispatch(command);
837
- yield* worker.drain();
838
- yield* orchestrator.dispatch(command);
747
+ messageId,
748
+ text: `${notification.summary}\nexit 0: built 12 files`,
749
+ notification,
750
+ attachments: [],
751
+ dispatchMode: { type: "queue_after_active" },
752
+ createdBy: "agent",
753
+ creationSource: "server",
754
+ });
755
yield* worker.drain();
756
const after = yield* orchestrator.getThreadProjection(threadId);
841
- assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
757
assert.deepEqual(
843
- started.map((input) => input.message.text),
844
- ["first", "selected"],
845
- );
846
- assert.equal(started[1]?.runId, selected.id);
847
- assert.equal(started[1]?.message.messageId, selected.userMessageId);
848
- assert.deepEqual(started[1]?.modelSelection, runSelection);
849
- assert.deepEqual(steered, []);
850
- assert.lengthOf(
851
- after.messages.filter((message) => message.id === selected.userMessageId),
852
- 1,
758
+ steered,
759
+ steers ? [`${notification.summary}\nexit 0: built 12 files`] : [],
760
);
854
- assert.deepEqual(
855
- after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
856
- [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
761
+ assert.lengthOf(started, 1);
762
+ assert.equal(
763
+ after.runs.some((run) => run.status === "queued"),
764
+ !steers,
765
);
858
- assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
859
- const duplicate = yield* orchestrator
860
- .dispatch({
861
- ...command,
862
- commandId: CommandId.make("send-selected-again"),
863
- })
864
- .pipe(Effect.flip);
865
- assert.equal(duplicate._tag, "OrchestratorDispatchError");
766
+ const message = after.messages.find((candidate) => candidate.id === messageId);
767
+ assert.deepEqual(message?.notification, notification);
768
+ if (steers) assert.equal(message?.runId, started[0]?.runId);
769
+ assert.deepEqual(after.thread.modelSelection, composerSelection);
770
}).pipe(Effect.provide(layer));
771
}),
868
- ),
772
+);
773
+
774
+it.effect("sends a selected held message once and preserves the remaining queue order", () =>
775
+ Effect.gen(function* () {
776
+ const { started, steered, layer, startFirstTurn } =
777
+ yield* nextTurnSelectionHarness("send-held-message");
778
+ yield* Effect.gen(function* () {
779
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
780
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
781
+ const threadId = yield* startFirstTurn;
782
+ yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
783
+ orchestrator.dispatch({
784
+ type: "message.dispatch",
785
+ commandId: CommandId.make(text),
786
+ threadId,
787
+ messageId: MessageId.make(`message:${text}`),
788
+ text,
789
+ attachments: [],
790
+ modelSelection: runSelection,
791
+ dispatchMode: { type: "queue_after_active" },
792
+ createdBy: "user",
793
+ creationSource: "web",
794
+ }),
795
+ );
796
+ const before = yield* orchestrator.getThreadProjection(threadId);
797
+ const selected = before.runs.find(
798
+ (run) => run.userMessageId === MessageId.make("message:selected"),
799
+ )!;
800
+ const sink = yield* EventSink.EventSinkV2;
801
+ const now = yield* DateTime.now;
802
+ // Restart recovery cancels the active run and holds every queued message.
803
+ yield* sink.write({
804
+ events: [
805
+ ...before.runs.map((run) => ({
806
+ id: EventId.make(`restart:${run.id}`),
807
+ type: "run.updated" as const,
808
+ threadId,
809
+ runId: run.id,
810
+ occurredAt: now,
811
+ payload:
812
+ run.status === "queued"
813
+ ? { ...run, queueHeld: true }
814
+ : { ...run, status: "cancelled" as const, completedAt: now },
815
+ })),
816
+ ...before.providerTurns.map((turn) => ({
817
+ id: EventId.make(`restart:${turn.id}`),
818
+ type: "provider-turn.updated" as const,
819
+ threadId,
820
+ occurredAt: now,
821
+ payload: { ...turn, status: "cancelled" as const, completedAt: now },
822
+ })),
823
+ ],
824
+ });
825
+ const command = {
826
+ type: "queued-run.start" as const,
827
+ commandId: CommandId.make("send-selected"),
828
+ threadId,
829
+ runId: selected.id,
830
+ };
831
+ yield* orchestrator.dispatch(command);
832
+ yield* worker.drain();
833
+ yield* orchestrator.dispatch(command);
834
+ yield* worker.drain();
835
+ const after = yield* orchestrator.getThreadProjection(threadId);
836
+ assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
837
+ assert.deepEqual(
838
+ started.map((input) => input.message.text),
839
+ ["first", "selected"],
840
+ );
841
+ assert.equal(started[1]?.runId, selected.id);
842
+ assert.equal(started[1]?.message.messageId, selected.userMessageId);
843
+ assert.deepEqual(started[1]?.modelSelection, runSelection);
844
+ assert.deepEqual(steered, []);
845
+ assert.lengthOf(
846
+ after.messages.filter((message) => message.id === selected.userMessageId),
847
+ 1,
848
+ );
849
+ assert.deepEqual(
850
+ after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
851
+ [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
852
+ );
853
+ assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
854
+ const duplicate = yield* orchestrator
855
+ .dispatch({
856
+ ...command,
857
+ commandId: CommandId.make("send-selected-again"),
858
+ })
859
+ .pipe(Effect.flip);
860
+ assert.equal(duplicate._tag, "OrchestratorDispatchError");
861
+ }).pipe(Effect.provide(layer));
862
+ }),
863
);
864
865
it.effect.each(
@@ -873,712 +867,586 @@ it.effect.each(
867
[false, true].map((direct) => ({ status, direct })),
868
),
869
)("delivers a deferred steer for a $status run (direct: $direct)", ({ status, direct }) =>
876
- Effect.scoped(
877
- Effect.gen(function* () {
878
- const restarting = status === "starting" && !direct;
879
- const { started, steered, layer, startFirstTurn, events } = yield* nextTurnSelectionHarness(
880
- `deferred-steer-${status}-${direct}`,
881
- restarting,
882
- !restarting,
883
- );
884
- yield* Effect.gen(function* () {
885
- const orchestrator = yield* Orchestrator.OrchestratorV2;
886
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
887
- const threadId = yield* startFirstTurn;
888
- const before = yield* orchestrator.getThreadProjection(threadId);
889
- const run = before.runs[0]!;
890
- const turn = before.providerTurns[0]!;
891
- const now = yield* DateTime.now;
892
- yield* (yield* EventSink.EventSinkV2).write({
893
- events: [
894
- {
895
- id: EventId.make("setup-run"),
896
- type: "run.updated",
897
- threadId,
898
- occurredAt: now,
899
- payload: { ...run, status },
900
- },
901
- {
902
- id: EventId.make("setup-turn"),
903
- type: "provider-turn.updated",
904
- threadId,
905
- occurredAt: now,
906
- payload: { ...turn, status: "pending" },
907
- },
908
- ],
909
- });
910
- if (status === "preparing" && !direct) {
911
- yield* orchestrator.dispatch({
912
- type: "message.dispatch",
913
- commandId: CommandId.make("edited-steer"),
914
- threadId,
915
- messageId: MessageId.make("message:edited-steer"),
916
- text: "edit this steer",
917
- attachments: [],
918
- deliveryIntent: "steer",
919
- dispatchMode: { type: "queue_after_active" },
920
- createdBy: "user",
921
- creationSource: "web",
922
- });
923
- const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
924
- (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"),
925
- )!;
926
- yield* orchestrator.dispatch({
927
- type: "queued-run.edit",
928
- commandId: CommandId.make("edit-steer-to-compact"),
870
+ Effect.gen(function* () {
871
+ const restarting = status === "starting" && !direct;
872
+ const { started, steered, layer, startFirstTurn, events } = yield* nextTurnSelectionHarness(
873
+ `deferred-steer-${status}-${direct}`,
874
+ restarting,
875
+ !restarting,
876
+ );
877
+ yield* Effect.gen(function* () {
878
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
879
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
880
+ const threadId = yield* startFirstTurn;
881
+ const before = yield* orchestrator.getThreadProjection(threadId);
882
+ const run = before.runs[0]!;
883
+ const turn = before.providerTurns[0]!;
884
+ const now = yield* DateTime.now;
885
+ yield* (yield* EventSink.EventSinkV2).write({
886
+ events: [
887
+ {
888
+ id: EventId.make("setup-run"),
889
+ type: "run.updated",
890
threadId,
930
- runId: edited.id,
931
- text: "/compact",
932
- });
933
- }
934
- if (direct) {
935
- yield* orchestrator.dispatch({
936
- type: "message.dispatch",
937
- commandId: CommandId.make("earlier-queue"),
891
+ occurredAt: now,
892
+ payload: { ...run, status },
893
+ },
894
+ {
895
+ id: EventId.make("setup-turn"),
896
+ type: "provider-turn.updated",
897
threadId,
939
- messageId: MessageId.make("message:earlier-queue"),
940
- text: "earlier queued selection",
941
- modelSelection: composerSelection,
942
- attachments: [],
943
- dispatchMode: { type: "queue_after_active" },
944
- createdBy: "user",
945
- creationSource: "web",
946
- });
947
- }
898
+ occurredAt: now,
899
+ payload: { ...turn, status: "pending" },
900
+ },
901
+ ],
902
+ });
903
+ if (status === "preparing" && !direct) {
904
yield* orchestrator.dispatch({
905
type: "message.dispatch",
950
- commandId: CommandId.make("queue"),
906
+ commandId: CommandId.make("edited-steer"),
907
threadId,
952
- messageId: MessageId.make("message:steer-after-setup"),
953
- text: "steer after setup",
908
+ messageId: MessageId.make("message:edited-steer"),
909
+ text: "edit this steer",
910
attachments: [],
911
+ deliveryIntent: "steer",
912
dispatchMode: { type: "queue_after_active" },
956
- ...(direct ? { deliveryIntent: "steer" as const } : {}),
913
createdBy: "user",
914
creationSource: "web",
915
});
960
- const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
961
- (candidate) => candidate.userMessageId === MessageId.make("message:steer-after-setup"),
916
+ const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
917
+ (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"),
918
)!;
963
- assert.deepEqual(queued.modelSelection, runSelection);
964
- for (const text of ["/compact", "/logout"]) {
965
- yield* orchestrator.dispatch({
966
- type: "message.dispatch",
967
- commandId: CommandId.make(`queue-${text}`),
919
+ yield* orchestrator.dispatch({
920
+ type: "queued-run.edit",
921
+ commandId: CommandId.make("edit-steer-to-compact"),
922
+ threadId,
923
+ runId: edited.id,
924
+ text: "/compact",
925
+ });
926
+ }
927
+ if (direct) {
928
+ yield* orchestrator.dispatch({
929
+ type: "message.dispatch",
930
+ commandId: CommandId.make("earlier-queue"),
931
+ threadId,
932
+ messageId: MessageId.make("message:earlier-queue"),
933
+ text: "earlier queued selection",
934
+ modelSelection: composerSelection,
935
+ attachments: [],
936
+ dispatchMode: { type: "queue_after_active" },
937
+ createdBy: "user",
938
+ creationSource: "web",
939
+ });
940
+ }
941
+ yield* orchestrator.dispatch({
942
+ type: "message.dispatch",
943
+ commandId: CommandId.make("queue"),
944
+ threadId,
945
+ messageId: MessageId.make("message:steer-after-setup"),
946
+ text: "steer after setup",
947
+ attachments: [],
948
+ dispatchMode: { type: "queue_after_active" },
949
+ ...(direct ? { deliveryIntent: "steer" as const } : {}),
950
+ createdBy: "user",
951
+ creationSource: "web",
952
+ });
953
+ const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
954
+ (candidate) => candidate.userMessageId === MessageId.make("message:steer-after-setup"),
955
+ )!;
956
+ assert.deepEqual(queued.modelSelection, runSelection);
957
+ for (const text of ["/compact", "/logout"]) {
958
+ yield* orchestrator.dispatch({
959
+ type: "message.dispatch",
960
+ commandId: CommandId.make(`queue-${text}`),
961
+ threadId,
962
+ messageId: MessageId.make(`message:${text}`),
963
+ text,
964
+ attachments: [],
965
+ dispatchMode: { type: "queue_after_active" },
966
+ createdBy: "user",
967
+ creationSource: "web",
968
+ });
969
+ const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
970
+ (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`),
971
+ )!;
972
+ const error = yield* orchestrator
973
+ .dispatch({
974
+ type: "queued-message.promote-to-steer",
975
+ commandId: CommandId.make(`promote-${text}`),
976
threadId,
969
- messageId: MessageId.make(`message:${text}`),
970
- text,
971
- attachments: [],
972
- dispatchMode: { type: "queue_after_active" },
973
- createdBy: "user",
974
- creationSource: "web",
975
- });
976
- const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
977
- (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`),
978
- )!;
979
- const error = yield* orchestrator
980
- .dispatch({
981
- type: "queued-message.promote-to-steer",
982
- commandId: CommandId.make(`promote-${text}`),
983
- threadId,
984
- queuedRunId: maintenance.id,
985
- targetRunId: run.id,
986
- })
987
- .pipe(Effect.flip);
988
- assert.equal(error._tag, "OrchestratorDispatchError");
989
- }
990
- const command = {
991
- type: "queued-message.promote-to-steer" as const,
992
- commandId: CommandId.make("promote"),
977
+ queuedRunId: maintenance.id,
978
+ targetRunId: run.id,
979
+ })
980
+ .pipe(Effect.flip);
981
+ assert.equal(error._tag, "OrchestratorDispatchError");
982
+ }
983
+ const command = {
984
+ type: "queued-message.promote-to-steer" as const,
985
+ commandId: CommandId.make("promote"),
986
+ threadId,
987
+ queuedRunId: queued.id,
988
+ targetRunId: run.id,
989
+ };
990
+ if (!direct) {
991
+ yield* orchestrator.dispatch(command);
992
+ yield* orchestrator.dispatch(command);
993
+ }
994
+ let secondQueuedId: typeof queued.id | undefined;
995
+ if (restarting) {
996
+ yield* orchestrator.dispatch({
997
+ type: "message.dispatch",
998
+ commandId: CommandId.make("second"),
999
threadId,
994
- queuedRunId: queued.id,
995
- targetRunId: run.id,
996
- };
997
- if (!direct) {
998
- yield* orchestrator.dispatch(command);
999
- yield* orchestrator.dispatch(command);
1000
- }
1001
- let secondQueuedId: typeof queued.id | undefined;
1002
- if (restarting) {
1003
- yield* orchestrator.dispatch({
1004
- type: "message.dispatch",
1005
- commandId: CommandId.make("second"),
1000
+ messageId: MessageId.make("message:second"),
1001
+ text: "second steer",
1002
+ attachments: [],
1003
+ dispatchMode: { type: "queue_after_active" },
1004
+ createdBy: "user",
1005
+ creationSource: "web",
1006
+ });
1007
+ secondQueuedId = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1008
+ (candidate) => candidate.userMessageId === MessageId.make("message:second"),
1009
+ )!.id;
1010
+ yield* orchestrator.dispatch({
1011
+ ...command,
1012
+ commandId: CommandId.make("promote-second"),
1013
+ queuedRunId: secondQueuedId,
1014
+ });
1015
+ }
1016
+ const secondReDeferred = yield* orchestrator.streamDomainEvents.pipe(
1017
+ Stream.filter(
1018
+ (event) =>
1019
+ event.type === "run.updated" &&
1020
+ event.payload.id === secondQueuedId &&
1021
+ event.payload.status === "queued",
1022
+ ),
1023
+ Stream.take(1),
1024
+ Stream.runDrain,
1025
+ Effect.forkScoped,
1026
+ );
1027
+ const secondPromoted = yield* orchestrator.streamDomainEvents.pipe(
1028
+ Stream.filter(
1029
+ (event) =>
1030
+ event.type === "run.updated" &&
1031
+ event.payload.id === secondQueuedId &&
1032
+ event.payload.status === "cancelled",
1033
+ ),
1034
+ Stream.take(1),
1035
+ Stream.runDrain,
1036
+ Effect.forkScoped,
1037
+ );
1038
+ yield* worker.drain();
1039
+ assert.deepEqual(steered, []);
1040
+ const promoted = yield* orchestrator.streamDomainEvents.pipe(
1041
+ Stream.filter(
1042
+ (event) =>
1043
+ event.type === "run.updated" &&
1044
+ event.payload.id === queued.id &&
1045
+ event.payload.status === "cancelled",
1046
+ ),
1047
+ Stream.take(1),
1048
+ Stream.runDrain,
1049
+ Effect.forkScoped,
1050
+ );
1051
+ yield* (yield* EventSink.EventSinkV2).write({
1052
+ events: [
1053
+ {
1054
+ id: EventId.make("ready-run"),
1055
+ type: "run.updated",
1056
threadId,
1007
- messageId: MessageId.make("message:second"),
1008
- text: "second steer",
1009
- attachments: [],
1010
- dispatchMode: { type: "queue_after_active" },
1011
- createdBy: "user",
1012
- creationSource: "web",
1013
- });
1014
- secondQueuedId = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1015
- (candidate) => candidate.userMessageId === MessageId.make("message:second"),
1016
- )!.id;
1017
- yield* orchestrator.dispatch({
1018
- ...command,
1019
- commandId: CommandId.make("promote-second"),
1020
- queuedRunId: secondQueuedId,
1021
- });
1022
- }
1023
- const secondReDeferred = yield* orchestrator.streamDomainEvents.pipe(
1024
- Stream.filter(
1025
- (event) =>
1026
- event.type === "run.updated" &&
1027
- event.payload.id === secondQueuedId &&
1028
- event.payload.status === "queued",
1029
- ),
1030
- Stream.take(1),
1031
- Stream.runDrain,
1032
- Effect.forkScoped,
1033
- );
1034
- const secondPromoted = yield* orchestrator.streamDomainEvents.pipe(
1035
- Stream.filter(
1036
- (event) =>
1037
- event.type === "run.updated" &&
1038
- event.payload.id === secondQueuedId &&
1039
- event.payload.status === "cancelled",
1040
- ),
1041
- Stream.take(1),
1042
- Stream.runDrain,
1043
- Effect.forkScoped,
1044
- );
1057
+ occurredAt: now,
1058
+ payload: run,
1059
+ },
1060
+ ],
1061
+ });
1062
+ yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn });
1063
+ yield* Fiber.join(promoted);
1064
+ if (restarting) yield* Fiber.join(secondReDeferred);
1065
+ yield* worker.drain();
1066
+ if (restarting) {
1067
+ yield* Fiber.join(secondPromoted);
1068
yield* worker.drain();
1046
- assert.deepEqual(steered, []);
1047
- const promoted = yield* orchestrator.streamDomainEvents.pipe(
1048
- Stream.filter(
1049
- (event) =>
1050
- event.type === "run.updated" &&
1051
- event.payload.id === queued.id &&
1052
- event.payload.status === "cancelled",
1053
- ),
1054
- Stream.take(1),
1055
- Stream.runDrain,
1056
- Effect.forkScoped,
1057
- );
1058
- yield* (yield* EventSink.EventSinkV2).write({
1059
- events: [
1060
- {
1061
- id: EventId.make("ready-run"),
1062
- type: "run.updated",
1063
- threadId,
1064
- occurredAt: now,
1065
- payload: run,
1066
- },
1067
- ],
1068
- });
1069
- yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn });
1070
- yield* Fiber.join(promoted);
1071
- if (restarting) yield* Fiber.join(secondReDeferred);
1072
- yield* worker.drain();
1073
- if (restarting) {
1074
- yield* Fiber.join(secondPromoted);
1075
- yield* worker.drain();
1076
- assert.deepEqual(
1077
- started.map((turn) => turn.message.text),
1078
- ["first", "steer after setup", "second steer"],
1079
- );
1080
- } else {
1081
- assert.deepEqual(steered, ["steer after setup"]);
1082
- assert.lengthOf(started, 1);
1083
- }
1084
- const after = yield* orchestrator.getThreadProjection(threadId);
1085
- assert.equal(
1086
- after.messages.find((message) => message.id === queued.userMessageId)?.runId,
1087
- run.id,
1088
- );
1089
- assert.equal(after.runs.find((candidate) => candidate.id === run.id)?.status, "running");
1090
- }).pipe(Effect.provide(layer));
1091
- }),
1092
- ),
1093
-);
1094
-
1095
-it.effect("force sends multiple queued messages and can force send a requeued message again", () =>
1096
- Effect.scoped(
1097
- Effect.gen(function* () {
1098
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1099
- "multiple-promoted-messages",
1100
- );
1101
- yield* Effect.gen(function* () {
1102
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1103
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1104
- const threadId = yield* startFirstTurn;
1105
- const queue = (text: string, commandId: string) =>
1106
- orchestrator.dispatch({
1107
- type: "message.dispatch",
1108
- commandId: CommandId.make(commandId),
1109
- threadId,
1110
- messageId: MessageId.make(`message:${text}`),
1111
- text,
1112
- attachments: [],
1113
- dispatchMode: { type: "queue_after_active" },
1114
- createdBy: "user",
1115
- creationSource: "web",
1116
- });
1117
- for (const text of ["one", "two", "remaining"]) yield* queue(text, `queue-${text}`);
1118
- const promote = Effect.fn("test.promote")(function* (text: string, commandId: string) {
1119
- const projection = yield* orchestrator.getThreadProjection(threadId);
1120
- const queued = projection.runs.find(
1121
- (run) =>
1122
- run.status === "queued" && run.userMessageId === MessageId.make(`message:${text}`),
1123
- )!;
1124
- yield* orchestrator.dispatch({
1125
- type: "queued-message.promote-to-steer",
1126
- commandId: CommandId.make(commandId),
1127
- threadId,
1128
- queuedRunId: queued.id,
1129
- targetRunId: started[0]!.runId,
1130
- });
1131
- });
1132
- yield* promote("one", "promote-one");
1133
- yield* promote("two", "promote-two");
1134
- yield* worker.drain();
1135
- assert.deepEqual(steered, ["one", "two"]);
1136
-
1137
- // The completion-race fallback redispatches the same message into the queue.
1138
- yield* queue("one", "requeue-one");
1139
- const requeued = yield* orchestrator.getThreadProjection(threadId);
1140
- assert.equal(
1141
- requeued.turnItems.find(
1142
- (item) => item.type === "user_message" && item.messageId === "message:one",
1143
- )?.status,
1144
- "pending",
1145
- );
1146
- yield* promote("one", "promote-one-again");
1147
- yield* worker.drain();
1148
- assert.deepEqual(steered, ["one", "two", "one"]);
1149
- assert.lengthOf(started, 1);
1150
- const final = yield* orchestrator.getThreadProjection(threadId);
1069
assert.deepEqual(
1152
- final.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
1153
- [MessageId.make("message:remaining")],
1070
+ started.map((turn) => turn.message.text),
1071
+ ["first", "steer after setup", "second steer"],
1072
);
1155
- for (const text of ["one", "two"]) {
1156
- const items = final.turnItems.filter(
1157
- (item) => item.type === "user_message" && item.messageId === `message:${text}`,
1158
- );
1159
- assert.lengthOf(items, 1);
1160
- assert.equal(items[0]?.status, "completed");
1161
- }
1162
- }).pipe(Effect.provide(layer));
1163
- }),
1164
- ),
1073
+ } else {
1074
+ assert.deepEqual(steered, ["steer after setup"]);
1075
+ assert.lengthOf(started, 1);
1076
+ }
1077
+ const after = yield* orchestrator.getThreadProjection(threadId);
1078
+ assert.equal(
1079
+ after.messages.find((message) => message.id === queued.userMessageId)?.runId,
1080
+ run.id,
1081
+ );
1082
+ assert.equal(after.runs.find((candidate) => candidate.id === run.id)?.status, "running");
1083
+ }).pipe(Effect.provide(layer));
1084
+ }),
1085
);
1086
1167
-it.effect("keeps a message queued when send now races with a running turn", () =>
1168
- Effect.scoped(
1169
- Effect.gen(function* () {
1170
- const { started, layer, startFirstTurn } =
1171
- yield* nextTurnSelectionHarness("send-queued-race");
1172
- yield* Effect.gen(function* () {
1173
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1174
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1175
- const threadId = yield* startFirstTurn;
1176
- yield* orchestrator.dispatch({
1087
+it.effect("force sends multiple queued messages and can force send a requeued message again", () =>
1088
+ Effect.gen(function* () {
1089
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1090
+ "multiple-promoted-messages",
1091
+ );
1092
+ yield* Effect.gen(function* () {
1093
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1094
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1095
+ const threadId = yield* startFirstTurn;
1096
+ const queue = (text: string, commandId: string) =>
1097
+ orchestrator.dispatch({
1098
type: "message.dispatch",
1178
- commandId: CommandId.make("queue"),
1099
+ commandId: CommandId.make(commandId),
1100
threadId,
1180
- messageId: MessageId.make("message:queued"),
1181
- text: "queued",
1101
+ messageId: MessageId.make(`message:${text}`),
1102
+ text,
1103
attachments: [],
1104
dispatchMode: { type: "queue_after_active" },
1105
createdBy: "user",
1106
creationSource: "web",
1107
});
1187
- const before = yield* orchestrator.getThreadProjection(threadId);
1188
- const queued = before.runs.find((run) => run.status === "queued")!;
1189
- const error = yield* orchestrator
1190
- .dispatch({
1191
- type: "queued-run.start",
1192
- commandId: CommandId.make("send-now"),
1193
- threadId,
1194
- runId: queued.id,
1195
- })
1196
- .pipe(Effect.flip);
1197
- yield* worker.drain();
1198
- assert.equal(error._tag, "OrchestratorDispatchError");
1199
- assert.equal(started.length, 1);
1200
- const after = yield* orchestrator.getThreadProjection(threadId);
1201
- assert.deepEqual(after.runs, before.runs);
1202
- }).pipe(Effect.provide(layer));
1203
- }),
1204
- ),
1108
+ for (const text of ["one", "two", "remaining"]) yield* queue(text, `queue-${text}`);
1109
+ const promote = Effect.fn("test.promote")(function* (text: string, commandId: string) {
1110
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1111
+ const queued = projection.runs.find(
1112
+ (run) =>
1113
+ run.status === "queued" && run.userMessageId === MessageId.make(`message:${text}`),
1114
+ )!;
1115
+ yield* orchestrator.dispatch({
1116
+ type: "queued-message.promote-to-steer",
1117
+ commandId: CommandId.make(commandId),
1118
+ threadId,
1119
+ queuedRunId: queued.id,
1120
+ targetRunId: started[0]!.runId,
1121
+ });
1122
+ });
1123
+ yield* promote("one", "promote-one");
1124
+ yield* promote("two", "promote-two");
1125
+ yield* worker.drain();
1126
+ assert.deepEqual(steered, ["one", "two"]);
1127
+
1128
+ // The completion-race fallback redispatches the same message into the queue.
1129
+ yield* queue("one", "requeue-one");
1130
+ const requeued = yield* orchestrator.getThreadProjection(threadId);
1131
+ assert.equal(
1132
+ requeued.turnItems.find(
1133
+ (item) => item.type === "user_message" && item.messageId === "message:one",
1134
+ )?.status,
1135
+ "pending",
1136
+ );
1137
+ yield* promote("one", "promote-one-again");
1138
+ yield* worker.drain();
1139
+ assert.deepEqual(steered, ["one", "two", "one"]);
1140
+ assert.lengthOf(started, 1);
1141
+ const final = yield* orchestrator.getThreadProjection(threadId);
1142
+ assert.deepEqual(
1143
+ final.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
1144
+ [MessageId.make("message:remaining")],
1145
+ );
1146
+ for (const text of ["one", "two"]) {
1147
+ const items = final.turnItems.filter(
1148
+ (item) => item.type === "user_message" && item.messageId === `message:${text}`,
1149
+ );
1150
+ assert.lengthOf(items, 1);
1151
+ assert.equal(items[0]?.status, "completed");
1152
+ }
1153
+ }).pipe(Effect.provide(layer));
1154
+ }),
1155
+);
1156
+
1157
+it.effect("keeps a message queued when send now races with a running turn", () =>
1158
+ Effect.gen(function* () {
1159
+ const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness("send-queued-race");
1160
+ yield* Effect.gen(function* () {
1161
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1162
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1163
+ const threadId = yield* startFirstTurn;
1164
+ yield* orchestrator.dispatch({
1165
+ type: "message.dispatch",
1166
+ commandId: CommandId.make("queue"),
1167
+ threadId,
1168
+ messageId: MessageId.make("message:queued"),
1169
+ text: "queued",
1170
+ attachments: [],
1171
+ dispatchMode: { type: "queue_after_active" },
1172
+ createdBy: "user",
1173
+ creationSource: "web",
1174
+ });
1175
+ const before = yield* orchestrator.getThreadProjection(threadId);
1176
+ const queued = before.runs.find((run) => run.status === "queued")!;
1177
+ const error = yield* orchestrator
1178
+ .dispatch({
1179
+ type: "queued-run.start",
1180
+ commandId: CommandId.make("send-now"),
1181
+ threadId,
1182
+ runId: queued.id,
1183
+ })
1184
+ .pipe(Effect.flip);
1185
+ yield* worker.drain();
1186
+ assert.equal(error._tag, "OrchestratorDispatchError");
1187
+ assert.equal(started.length, 1);
1188
+ const after = yield* orchestrator.getThreadProjection(threadId);
1189
+ assert.deepEqual(after.runs, before.runs);
1190
+ }).pipe(Effect.provide(layer));
1191
+ }),
1192
);
1193
1194
// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
1195
it.effect(
1196
"steers a changed turn-scoped selection into a running turn the provider could restart",
1197
() =>
1211
- Effect.scoped(
1212
- Effect.gen(function* () {
1213
- const { started, steered, steeredSelections, layer, startFirstTurn } =
1214
- yield* nextTurnSelectionHarness("steering-selection-change", true);
1215
- yield* Effect.gen(function* () {
1216
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1217
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1218
- const threadId = yield* startFirstTurn;
1219
- const steer = (id: string, selection: ModelSelection) =>
1220
- orchestrator
1221
- .dispatch({
1222
- type: "message.dispatch",
1223
- commandId: CommandId.make(id),
1224
- threadId,
1225
- messageId: MessageId.make(`message:${id}`),
1226
- text: id,
1227
- attachments: [],
1228
- modelSelection: selection,
1229
- dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
1230
- createdBy: "user",
1231
- creationSource: "web",
1232
- })
1233
- .pipe(Effect.andThen(worker.drain()));
1234
-
1235
- yield* steer("steer-changed", composerSelection);
1236
- const changed = yield* orchestrator.getThreadProjection(threadId);
1237
- assert.deepEqual(steered, ["steer-changed"]);
1238
- assert.equal(started.length, 1);
1239
- assert.lengthOf(changed.attempts, 1);
1240
- assert.equal(changed.runs[0]?.status, "running");
1241
- assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
1242
- assert.deepEqual(changed.thread.modelSelection, composerSelection);
1243
-
1244
- yield* steer("steer-reverted", runSelection);
1245
- const reverted = yield* orchestrator.getThreadProjection(threadId);
1246
- assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
1247
- assert.lengthOf(reverted.attempts, 1);
1248
- assert.deepEqual(reverted.thread.modelSelection, runSelection);
1249
-
1250
- const otherSelection = {
1251
- instanceId: ProviderInstanceId.make("codex-work"),
1252
- model: "other",
1253
- };
1254
- const sink = yield* EventSink.EventSinkV2;
1255
- yield* sink.write({
1256
- events: [
1257
- {
1258
- id: EventId.make("switched-away"),
1259
- type: "thread.provider-switched",
1260
- threadId,
1261
- providerInstanceId: otherSelection.instanceId,
1262
- occurredAt: yield* DateTime.now,
1263
- payload: {
1264
- ...reverted.thread,
1265
- providerInstanceId: otherSelection.instanceId,
1266
- modelSelection: otherSelection,
1267
- },
1268
- },
1269
- ],
1270
- });
1271
- yield* steer("steer-back", runSelection);
1272
- const back = yield* orchestrator.getThreadProjection(threadId);
1273
- assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
1274
- // The adapter gets each steer's selection so it can switch the live turn, and back.
1275
- assert.deepEqual(steeredSelections, [composerSelection, runSelection, runSelection]);
1276
- assert.equal(back.thread.providerInstanceId, instanceId);
1277
- assert.deepEqual(back.thread.modelSelection, runSelection);
1278
- }).pipe(Effect.provide(layer));
1279
- }),
1280
- ),
1281
-);
1282
-
1283
-it.effect("restarts the turn for an image when native steering takes text only", () =>
1284
- Effect.scoped(
1198
Effect.gen(function* () {
1286
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1287
- "steering-text-only-attachment",
1288
- true,
1289
- true,
1290
- Effect.void,
1291
- false,
1292
- );
1199
+ const { started, steered, steeredSelections, layer, startFirstTurn } =
1200
+ yield* nextTurnSelectionHarness("steering-selection-change", true);
1201
yield* Effect.gen(function* () {
1202
const orchestrator = yield* Orchestrator.OrchestratorV2;
1203
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1204
const threadId = yield* startFirstTurn;
1297
- yield* orchestrator.dispatch({
1298
- type: "message.dispatch",
1299
- commandId: CommandId.make("steer-image"),
1300
- threadId,
1301
- messageId: MessageId.make("message:steer-image"),
1302
- text: "look at this",
1303
- attachments: [
1205
+ const steer = (id: string, selection: ModelSelection) =>
1206
+ orchestrator
1207
+ .dispatch({
1208
+ type: "message.dispatch",
1209
+ commandId: CommandId.make(id),
1210
+ threadId,
1211
+ messageId: MessageId.make(`message:${id}`),
1212
+ text: id,
1213
+ attachments: [],
1214
+ modelSelection: selection,
1215
+ dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
1216
+ createdBy: "user",
1217
+ creationSource: "web",
1218
+ })
1219
+ .pipe(Effect.andThen(worker.drain()));
1220
+
1221
+ yield* steer("steer-changed", composerSelection);
1222
+ const changed = yield* orchestrator.getThreadProjection(threadId);
1223
+ assert.deepEqual(steered, ["steer-changed"]);
1224
+ assert.equal(started.length, 1);
1225
+ assert.lengthOf(changed.attempts, 1);
1226
+ assert.equal(changed.runs[0]?.status, "running");
1227
+ assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
1228
+ assert.deepEqual(changed.thread.modelSelection, composerSelection);
1229
+
1230
+ yield* steer("steer-reverted", runSelection);
1231
+ const reverted = yield* orchestrator.getThreadProjection(threadId);
1232
+ assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
1233
+ assert.lengthOf(reverted.attempts, 1);
1234
+ assert.deepEqual(reverted.thread.modelSelection, runSelection);
1235
+
1236
+ const otherSelection = {
1237
+ instanceId: ProviderInstanceId.make("codex-work"),
1238
+ model: "other",
1239
+ };
1240
+ const sink = yield* EventSink.EventSinkV2;
1241
+ yield* sink.write({
1242
+ events: [
1243
{
1305
- type: "image",
1306
- id: ChatAttachmentId.make("steer-image"),
1307
- name: "screenshot.png",
1308
- mimeType: "image/png",
1309
- sizeBytes: 4,
1244
+ id: EventId.make("switched-away"),
1245
+ type: "thread.provider-switched",
1246
+ threadId,
1247
+ providerInstanceId: otherSelection.instanceId,
1248
+ occurredAt: yield* DateTime.now,
1249
+ payload: {
1250
+ ...reverted.thread,
1251
+ providerInstanceId: otherSelection.instanceId,
1252
+ modelSelection: otherSelection,
1253
+ },
1254
},
1255
],
1312
- modelSelection: runSelection,
1313
- dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
1314
- createdBy: "user",
1315
- creationSource: "web",
1256
});
1317
- yield* worker.drain();
1318
- assert.deepEqual(steered, []);
1319
- assert.deepEqual(
1320
- started.map((turn) => [turn.message.text, turn.message.attachments.length]),
1321
- [
1322
- ["first", 0],
1323
- ["look at this", 1],
1324
- ],
1325
- );
1257
+ yield* steer("steer-back", runSelection);
1258
+ const back = yield* orchestrator.getThreadProjection(threadId);
1259
+ assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
1260
+ // The adapter gets each steer's selection so it can switch the live turn, and back.
1261
+ assert.deepEqual(steeredSelections, [composerSelection, runSelection, runSelection]);
1262
+ assert.equal(back.thread.providerInstanceId, instanceId);
1263
+ assert.deepEqual(back.thread.modelSelection, runSelection);
1264
}).pipe(Effect.provide(layer));
1265
}),
1328
- ),
1266
+);
1267
+
1268
+it.effect("restarts the turn for an image when native steering takes text only", () =>
1269
+ Effect.gen(function* () {
1270
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1271
+ "steering-text-only-attachment",
1272
+ true,
1273
+ true,
1274
+ Effect.void,
1275
+ false,
1276
+ );
1277
+ yield* Effect.gen(function* () {
1278
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1279
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1280
+ const threadId = yield* startFirstTurn;
1281
+ yield* orchestrator.dispatch({
1282
+ type: "message.dispatch",
1283
+ commandId: CommandId.make("steer-image"),
1284
+ threadId,
1285
+ messageId: MessageId.make("message:steer-image"),
1286
+ text: "look at this",
1287
+ attachments: [
1288
+ {
1289
+ type: "image",
1290
+ id: ChatAttachmentId.make("steer-image"),
1291
+ name: "screenshot.png",
1292
+ mimeType: "image/png",
1293
+ sizeBytes: 4,
1294
+ },
1295
+ ],
1296
+ modelSelection: runSelection,
1297
+ dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
1298
+ createdBy: "user",
1299
+ creationSource: "web",
1300
+ });
1301
+ yield* worker.drain();
1302
+ assert.deepEqual(steered, []);
1303
+ assert.deepEqual(
1304
+ started.map((turn) => [turn.message.text, turn.message.attachments.length]),
1305
+ [
1306
+ ["first", 0],
1307
+ ["look at this", 1],
1308
+ ],
1309
+ );
1310
+ }).pipe(Effect.provide(layer));
1311
+ }),
1312
);
1313
1314
it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>
1332
- Effect.scoped(
1333
- Effect.gen(function* () {
1334
- const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1335
- "steering-selection-follow-up",
1315
+ Effect.gen(function* () {
1316
+ const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1317
+ "steering-selection-follow-up",
1318
+ );
1319
+ yield* Effect.gen(function* () {
1320
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1321
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1322
+ const threadId = yield* startFirstTurn;
1323
+ const first = started[0]!;
1324
+ yield* orchestrator.dispatch({
1325
+ type: "message.dispatch",
1326
+ commandId: CommandId.make("steer"),
1327
+ threadId,
1328
+ messageId: MessageId.make("message:steer"),
1329
+ text: "late steer",
1330
+ attachments: [],
1331
+ modelSelection: composerSelection,
1332
+ dispatchMode: { type: "steer_active", targetRunId: first.runId },
1333
+ createdBy: "user",
1334
+ creationSource: "web",
1335
+ });
1336
+ const settled = yield* orchestrator.streamDomainEvents.pipe(
1337
+ Stream.filter(
1338
+ (event) =>
1339
+ event.type === "run.updated" &&
1340
+ event.payload.id === first.runId &&
1341
+ event.payload.status === "waiting",
1342
+ ),
1343
+ Stream.take(1),
1344
+ Stream.runDrain,
1345
+ Effect.forkScoped,
1346
);
1337
- yield* Effect.gen(function* () {
1338
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1339
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1340
- const threadId = yield* startFirstTurn;
1341
- const first = started[0]!;
1342
- yield* orchestrator.dispatch({
1343
- type: "message.dispatch",
1344
- commandId: CommandId.make("steer"),
1345
- threadId,
1346
- messageId: MessageId.make("message:steer"),
1347
- text: "late steer",
1348
- attachments: [],
1349
- modelSelection: composerSelection,
1350
- dispatchMode: { type: "steer_active", targetRunId: first.runId },
1351
- createdBy: "user",
1352
- creationSource: "web",
1353
- });
1354
- const settled = yield* orchestrator.streamDomainEvents.pipe(
1355
- Stream.filter(
1356
- (event) =>
1357
- event.type === "run.updated" &&
1358
- event.payload.id === first.runId &&
1359
- event.payload.status === "waiting",
1360
- ),
1361
- Stream.take(1),
1362
- Stream.runDrain,
1363
- Effect.forkScoped,
1364
- );
1365
- const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
1366
- yield* Queue.offer(events, {
1367
- type: "provider_turn.updated",
1368
- driver,
1369
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1370
- });
1371
- yield* Queue.offer(events, {
1372
- type: "turn.terminal",
1373
- driver,
1374
- providerThreadId: turn.providerThreadId,
1375
- providerTurnId: turn.id,
1376
- runOrdinal: first.runOrdinal,
1377
- status: "completed",
1378
- failure: null,
1379
- threadDisposition: "reusable",
1380
- });
1381
- yield* Fiber.join(settled);
1382
- yield* worker.drain();
1383
- yield* orchestrator.resumeQueuedRuns;
1384
- yield* worker.drain();
1347
+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
1348
+ yield* Queue.offer(events, {
1349
+ type: "provider_turn.updated",
1350
+ driver,
1351
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1352
+ });
1353
+ yield* Queue.offer(events, {
1354
+ type: "turn.terminal",
1355
+ driver,
1356
+ providerThreadId: turn.providerThreadId,
1357
+ providerTurnId: turn.id,
1358
+ runOrdinal: first.runOrdinal,
1359
+ status: "completed",
1360
+ failure: null,
1361
+ threadDisposition: "reusable",
1362
+ });
1363
+ yield* Fiber.join(settled);
1364
+ yield* worker.drain();
1365
+ yield* orchestrator.resumeQueuedRuns;
1366
+ yield* worker.drain();
1367
1386
- const projection = yield* orchestrator.getThreadProjection(threadId);
1387
- assert.deepEqual(steered, []);
1388
- assert.equal(started.length, 2);
1389
- assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
1390
- assert.deepEqual(started[1]?.modelSelection, composerSelection);
1391
- assert.deepEqual(projection.thread.modelSelection, composerSelection);
1392
- }).pipe(Effect.provide(layer));
1393
- }),
1394
- ),
1368
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1369
+ assert.deepEqual(steered, []);
1370
+ assert.equal(started.length, 2);
1371
+ assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
1372
+ assert.deepEqual(started[1]?.modelSelection, composerSelection);
1373
+ assert.deepEqual(projection.thread.modelSelection, composerSelection);
1374
+ }).pipe(Effect.provide(layer));
1375
+ }),
1376
);
1377
1378
it.effect.each(["complete", "stop-before-decline", "stop-after-decline", "queued-model"] as const)(
1379
"persists a declined steer without blocking the worker: %s",
1380
(timing) =>
1400
- Effect.scoped(
1401
- Effect.gen(function* () {
1402
- let beforeDecline: Effect.Effect<void> = Effect.void;
1403
- const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1404
- `steering-declined-${timing}`,
1405
- false,
1406
- true,
1407
- Effect.void,
1408
- true,
1409
- undefined,
1410
- (turn) =>
1411
- Effect.suspend(() => beforeDecline).pipe(
1412
- Effect.andThen(
1413
- Effect.fail(
1414
- new ProviderAdapter.ProviderAdapterSteerDeclinedError({
1415
- driver,
1416
- providerThreadId: turn.providerThread.id,
1417
- providerTurnId: turn.providerTurnId,
1418
- }),
1419
- ),
1420
- ),
1421
- ),
1422
- );
1423
- yield* Effect.gen(function* () {
1424
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1425
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1426
- const threadId = yield* startFirstTurn;
1427
- const first = started[0]!;
1428
- const stop = orchestrator
1429
- .dispatch({
1430
- type: "run.interrupt",
1431
- commandId: CommandId.make("stop"),
1432
- threadId,
1433
- runId: first.runId,
1434
- holdQueue: true,
1435
- })
1436
- .pipe(Effect.asVoid, Effect.orDie);
1437
- if (timing === "stop-before-decline") beforeDecline = stop;
1438
- const steerSelection = { ...runSelection, model: "steer-model" };
1439
- if (timing === "queued-model") {
1440
- yield* orchestrator.dispatch({
1441
- type: "message.dispatch",
1442
- commandId: CommandId.make("queued-model"),
1443
- threadId,
1444
- messageId: MessageId.make("message:queued-model"),
1445
- text: "already queued",
1446
- attachments: [],
1447
- modelSelection: composerSelection,
1448
- dispatchMode: { type: "queue_after_active" },
1449
- createdBy: "user",
1450
- creationSource: "web",
1451
- });
1452
- beforeDecline = Effect.forEach(["queued-later", "steer-later", "queued-last"], (id) =>
1453
- orchestrator.dispatch({
1454
- type: "message.dispatch",
1455
- commandId: CommandId.make(id),
1456
- threadId,
1457
- messageId: MessageId.make(`message:${id}`),
1458
- text: id,
1459
- attachments: [],
1460
- dispatchMode:
1461
- id === "steer-later"
1462
- ? { type: "steer_active", targetRunId: first.runId }
1463
- : { type: "queue_after_active" },
1464
- createdBy: "user",
1465
- creationSource: "web",
1466
- }),
1467
- ).pipe(Effect.asVoid, Effect.orDie);
1468
- }
1469
- const messageId = MessageId.make("message:declined");
1470
- yield* orchestrator.dispatch({
1471
- type: "message.dispatch",
1472
- commandId: CommandId.make("steer"),
1473
- threadId,
1474
- messageId,
1475
- text: "follow up",
1476
- attachments: [],
1477
- ...(timing === "queued-model" ? { modelSelection: steerSelection } : {}),
1478
- dispatchMode: { type: "steer_active", targetRunId: first.runId },
1479
- createdBy: "user",
1480
- creationSource: "web",
1481
- });
1482
- yield* worker.drain();
1483
- const pending = yield* orchestrator.getThreadProjection(threadId);
1484
- const queued = pending.runs.find(
1485
- (run) => run.userMessageId === messageId && run.id !== first.runId,
1486
- );
1487
- const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId(
1488
- CommandId.make("steer"),
1489
- );
1490
- assert.deepEqual(
1491
- effects.map((effect) => [effect.request.type, effect.status]),
1492
- [["provider-turn.steer", "succeeded"]],
1493
- );
1494
- assert.equal(started.length, 1);
1495
- if (timing === "stop-before-decline") {
1496
- assert.isUndefined(queued);
1497
- return;
1498
- }
1499
- assert.equal(queued?.status, "queued");
1500
- assert.equal(queued?.userMessageId, messageId);
1501
- if (timing === "queued-model") {
1502
- assert.deepEqual(queued?.modelSelection, steerSelection);
1503
- assert.deepEqual(
1504
- pending.runs
1505
- .filter((run) => run.status === "queued")
1506
- .toSorted(
1507
- (left, right) =>
1508
- (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal),
1509
- )
1510
- .map((run) => run.userMessageId),
1511
- [
1512
- MessageId.make("message:queued-model"),
1513
- messageId,
1514
- MessageId.make("message:queued-later"),
1515
- MessageId.make("message:steer-later"),
1516
- MessageId.make("message:queued-last"),
1517
- ],
1518
- );
1519
- return;
1520
- }
1521
- if (timing === "stop-after-decline") {
1522
- yield* stop;
1523
- yield* worker.drain();
1524
- yield* orchestrator.resumeQueuedRuns;
1525
- yield* worker.drain();
1526
- const held = yield* orchestrator.getThreadProjection(threadId);
1527
- assert.equal(held.runs.find((run) => run.id === queued?.id)?.queueHeld, true);
1528
- assert.equal(started.length, 1);
1529
- return;
1530
- }
1531
- const settled = yield* orchestrator.streamDomainEvents.pipe(
1532
- Stream.filter(
1533
- (event) =>
1534
- event.type === "run.updated" &&
1535
- event.payload.id === first.runId &&
1536
- event.payload.status === "waiting",
1537
- ),
1538
- Stream.take(1),
1539
- Stream.runDrain,
1540
- Effect.forkScoped,
1541
- );
1542
- const turn = pending.providerTurns[0]!;
1543
- yield* Queue.offer(events, {
1544
- type: "provider_turn.updated",
1545
- driver,
1546
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1547
- });
1548
- yield* Queue.offer(events, {
1549
- type: "turn.terminal",
1550
- driver,
1551
- providerThreadId: turn.providerThreadId,
1552
- providerTurnId: turn.id,
1553
- runOrdinal: first.runOrdinal,
1554
- status: "completed",
1555
- failure: null,
1556
- threadDisposition: "reusable",
1557
- });
1558
- yield* Fiber.join(settled);
1559
- yield* worker.drain();
1560
- yield* orchestrator.resumeQueuedRuns;
1561
- yield* worker.drain();
1562
- assert.equal(started.length, 2);
1563
- assert.equal(started[1]?.message.messageId, messageId);
1564
- assert.equal(started[1]?.runId, queued?.id);
1565
- }).pipe(Effect.provide(layer));
1566
- }),
1567
- ),
1568
-);
1569
-
1570
-// regression: #26695 cancelling a Copilot prompt to steer it kills its background agents
1571
-it.effect("queues a steer until the turn ends when the provider cannot steer it", () =>
1572
- Effect.scoped(
1381
Effect.gen(function* () {
1574
- const { events, started, steered, interrupted, layer, startFirstTurn } =
1575
- yield* nextTurnSelectionHarness("steering-unsupported", false, false);
1382
+ let beforeDecline: Effect.Effect<void> = Effect.void;
1383
+ const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
1384
+ `steering-declined-${timing}`,
1385
+ false,
1386
+ true,
1387
+ Effect.void,
1388
+ true,
1389
+ undefined,
1390
+ (turn) =>
1391
+ Effect.suspend(() => beforeDecline).pipe(
1392
+ Effect.andThen(
1393
+ Effect.fail(
1394
+ new ProviderAdapter.ProviderAdapterSteerDeclinedError({
1395
+ driver,
1396
+ providerThreadId: turn.providerThread.id,
1397
+ providerTurnId: turn.providerTurnId,
1398
+ }),
1399
+ ),
1400
+ ),
1401
+ ),
1402
+ );
1403
yield* Effect.gen(function* () {
1404
const orchestrator = yield* Orchestrator.OrchestratorV2;
1405
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1406
const threadId = yield* startFirstTurn;
1407
const first = started[0]!;
1581
- const messageId = MessageId.make("message:steer");
1408
+ const stop = orchestrator
1409
+ .dispatch({
1410
+ type: "run.interrupt",
1411
+ commandId: CommandId.make("stop"),
1412
+ threadId,
1413
+ runId: first.runId,
1414
+ holdQueue: true,
1415
+ })
1416
+ .pipe(Effect.asVoid, Effect.orDie);
1417
+ if (timing === "stop-before-decline") beforeDecline = stop;
1418
+ const steerSelection = { ...runSelection, model: "steer-model" };
1419
+ if (timing === "queued-model") {
1420
+ yield* orchestrator.dispatch({
1421
+ type: "message.dispatch",
1422
+ commandId: CommandId.make("queued-model"),
1423
+ threadId,
1424
+ messageId: MessageId.make("message:queued-model"),
1425
+ text: "already queued",
1426
+ attachments: [],
1427
+ modelSelection: composerSelection,
1428
+ dispatchMode: { type: "queue_after_active" },
1429
+ createdBy: "user",
1430
+ creationSource: "web",
1431
+ });
1432
+ beforeDecline = Effect.forEach(["queued-later", "steer-later", "queued-last"], (id) =>
1433
+ orchestrator.dispatch({
1434
+ type: "message.dispatch",
1435
+ commandId: CommandId.make(id),
1436
+ threadId,
1437
+ messageId: MessageId.make(`message:${id}`),
1438
+ text: id,
1439
+ attachments: [],
1440
+ dispatchMode:
1441
+ id === "steer-later"
1442
+ ? { type: "steer_active", targetRunId: first.runId }
1443
+ : { type: "queue_after_active" },
1444
+ createdBy: "user",
1445
+ creationSource: "web",
1446
+ }),
1447
+ ).pipe(Effect.asVoid, Effect.orDie);
1448
+ }
1449
+ const messageId = MessageId.make("message:declined");
1450
yield* orchestrator.dispatch({
1451
type: "message.dispatch",
1452
commandId: CommandId.make("steer"),
@@ -1586,22 +1454,60 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it"
1454
messageId,
1455
text: "follow up",
1456
attachments: [],
1589
- modelSelection: runSelection,
1590
- dispatchMode: { type: "start_immediately" },
1591
- deliveryIntent: "steer",
1457
+ ...(timing === "queued-model" ? { modelSelection: steerSelection } : {}),
1458
+ dispatchMode: { type: "steer_active", targetRunId: first.runId },
1459
createdBy: "user",
1460
creationSource: "web",
1461
});
1462
yield* worker.drain();
1596
-
1597
- const held = yield* orchestrator.getThreadProjection(threadId);
1598
- assert.deepEqual(steered, []);
1599
- assert.deepEqual(interrupted, []);
1463
+ const pending = yield* orchestrator.getThreadProjection(threadId);
1464
+ const queued = pending.runs.find(
1465
+ (run) => run.userMessageId === messageId && run.id !== first.runId,
1466
+ );
1467
+ const effects = yield* (yield* EffectOutbox.EffectOutboxV2).listByCommandId(
1468
+ CommandId.make("steer"),
1469
+ );
1470
+ assert.deepEqual(
1471
+ effects.map((effect) => [effect.request.type, effect.status]),
1472
+ [["provider-turn.steer", "succeeded"]],
1473
+ );
1474
assert.equal(started.length, 1);
1601
- assert.equal(held.runs.find((run) => run.id === first.runId)?.status, "running");
1602
- const queued = held.runs.find((run) => run.userMessageId === messageId);
1475
+ if (timing === "stop-before-decline") {
1476
+ assert.isUndefined(queued);
1477
+ return;
1478
+ }
1479
assert.equal(queued?.status, "queued");
1604
-
1480
+ assert.equal(queued?.userMessageId, messageId);
1481
+ if (timing === "queued-model") {
1482
+ assert.deepEqual(queued?.modelSelection, steerSelection);
1483
+ assert.deepEqual(
1484
+ pending.runs
1485
+ .filter((run) => run.status === "queued")
1486
+ .toSorted(
1487
+ (left, right) =>
1488
+ (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal),
1489
+ )
1490
+ .map((run) => run.userMessageId),
1491
+ [
1492
+ MessageId.make("message:queued-model"),
1493
+ messageId,
1494
+ MessageId.make("message:queued-later"),
1495
+ MessageId.make("message:steer-later"),
1496
+ MessageId.make("message:queued-last"),
1497
+ ],
1498
+ );
1499
+ return;
1500
+ }
1501
+ if (timing === "stop-after-decline") {
1502
+ yield* stop;
1503
+ yield* worker.drain();
1504
+ yield* orchestrator.resumeQueuedRuns;
1505
+ yield* worker.drain();
1506
+ const held = yield* orchestrator.getThreadProjection(threadId);
1507
+ assert.equal(held.runs.find((run) => run.id === queued?.id)?.queueHeld, true);
1508
+ assert.equal(started.length, 1);
1509
+ return;
1510
+ }
1511
const settled = yield* orchestrator.streamDomainEvents.pipe(
1512
Stream.filter(
1513
(event) =>
@@ -1613,7 +1519,7 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it"
1519
Stream.runDrain,
1520
Effect.forkScoped,
1521
);
1616
- const turn = held.providerTurns[0]!;
1522
+ const turn = pending.providerTurns[0]!;
1523
yield* Queue.offer(events, {
1524
type: "provider_turn.updated",
1525
driver,
@@ -1633,14 +1539,85 @@ it.effect("queues a steer until the turn ends when the provider cannot steer it"
1539
yield* worker.drain();
1540
yield* orchestrator.resumeQueuedRuns;
1541
yield* worker.drain();
1636
-
1637
- assert.deepEqual(interrupted, []);
1542
assert.equal(started.length, 2);
1543
+ assert.equal(started[1]?.message.messageId, messageId);
1544
assert.equal(started[1]?.runId, queued?.id);
1640
- assert.equal(started[1]?.message.text, "follow up");
1545
}).pipe(Effect.provide(layer));
1546
}),
1643
- ),
1547
+);
1548
+
1549
+// regression: #26695 cancelling a Copilot prompt to steer it kills its background agents
1550
+it.effect("queues a steer until the turn ends when the provider cannot steer it", () =>
1551
+ Effect.gen(function* () {
1552
+ const { events, started, steered, interrupted, layer, startFirstTurn } =
1553
+ yield* nextTurnSelectionHarness("steering-unsupported", false, false);
1554
+ yield* Effect.gen(function* () {
1555
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1556
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1557
+ const threadId = yield* startFirstTurn;
1558
+ const first = started[0]!;
1559
+ const messageId = MessageId.make("message:steer");
1560
+ yield* orchestrator.dispatch({
1561
+ type: "message.dispatch",
1562
+ commandId: CommandId.make("steer"),
1563
+ threadId,
1564
+ messageId,
1565
+ text: "follow up",
1566
+ attachments: [],
1567
+ modelSelection: runSelection,
1568
+ dispatchMode: { type: "start_immediately" },
1569
+ deliveryIntent: "steer",
1570
+ createdBy: "user",
1571
+ creationSource: "web",
1572
+ });
1573
+ yield* worker.drain();
1574
+
1575
+ const held = yield* orchestrator.getThreadProjection(threadId);
1576
+ assert.deepEqual(steered, []);
1577
+ assert.deepEqual(interrupted, []);
1578
+ assert.equal(started.length, 1);
1579
+ assert.equal(held.runs.find((run) => run.id === first.runId)?.status, "running");
1580
+ const queued = held.runs.find((run) => run.userMessageId === messageId);
1581
+ assert.equal(queued?.status, "queued");
1582
+
1583
+ const settled = yield* orchestrator.streamDomainEvents.pipe(
1584
+ Stream.filter(
1585
+ (event) =>
1586
+ event.type === "run.updated" &&
1587
+ event.payload.id === first.runId &&
1588
+ event.payload.status === "waiting",
1589
+ ),
1590
+ Stream.take(1),
1591
+ Stream.runDrain,
1592
+ Effect.forkScoped,
1593
+ );
1594
+ const turn = held.providerTurns[0]!;
1595
+ yield* Queue.offer(events, {
1596
+ type: "provider_turn.updated",
1597
+ driver,
1598
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1599
+ });
1600
+ yield* Queue.offer(events, {
1601
+ type: "turn.terminal",
1602
+ driver,
1603
+ providerThreadId: turn.providerThreadId,
1604
+ providerTurnId: turn.id,
1605
+ runOrdinal: first.runOrdinal,
1606
+ status: "completed",
1607
+ failure: null,
1608
+ threadDisposition: "reusable",
1609
+ });
1610
+ yield* Fiber.join(settled);
1611
+ yield* worker.drain();
1612
+ yield* orchestrator.resumeQueuedRuns;
1613
+ yield* worker.drain();
1614
+
1615
+ assert.deepEqual(interrupted, []);
1616
+ assert.equal(started.length, 2);
1617
+ assert.equal(started[1]?.runId, queued?.id);
1618
+ assert.equal(started[1]?.message.text, "follow up");
1619
+ }).pipe(Effect.provide(layer));
1620
+ }),
1621
);
1622
1623
// regression: #33454 a steer that restarts a completion wake run left its cohort claimed forever
@@ -1891,485 +1868,463 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* (
1868
});
1869
1870
it.effect("wakes the parent for a sibling result after a steer restarts the completion wake", () =>
1894
- Effect.scoped(
1871
+ Effect.gen(function* () {
1872
+ const harness = yield* nextTurnSelectionHarness("steered-completion-wake", true, false);
1873
+ yield* Effect.gen(function* () {
1874
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1875
+ const {
1876
+ threadId,
1877
+ origin,
1878
+ wake,
1879
+ steered,
1880
+ firstTaskId,
1881
+ siblingTaskId,
1882
+ watchRun,
1883
+ finishTurn,
1884
+ completeTask,
1885
+ } = yield* restartCompletionWake(harness, false);
1886
+
1887
+ // A follow-up queued behind the wake starts once the terminal-run listener has settled it.
1888
+ const followUp = MessageId.make("message:follow-up");
1889
+ yield* orchestrator.dispatch({
1890
+ type: "message.dispatch",
1891
+ commandId: CommandId.make("command:follow-up"),
1892
+ threadId,
1893
+ messageId: followUp,
1894
+ text: "follow up",
1895
+ attachments: [],
1896
+ modelSelection: runSelection,
1897
+ dispatchMode: { type: "queue_after_active" },
1898
+ createdBy: "user",
1899
+ creationSource: "web",
1900
+ });
1901
+ const followUpRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1902
+ (run) => run.userMessageId === followUp,
1903
+ )!;
1904
+ const followUpStarted = yield* watchRun(followUpRun.id, "starting");
1905
+ yield* finishTurn(steered);
1906
+ yield* Fiber.join(followUpStarted);
1907
+ assert.equal(
1908
+ (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1909
+ (run) => run.id === wake.runId,
1910
+ )?.status,
1911
+ "completed",
1912
+ );
1913
+
1914
+ yield* completeTask(siblingTaskId);
1915
+ const final = yield* orchestrator.getThreadProjection(threadId);
1916
+ const tasks = new Map(
1917
+ final.subagents.map((task) => [task.id, task.completionDelivery?.state]),
1918
+ );
1919
+ assert.deepInclude(
1920
+ final.runs.find((run) => run.id === origin.runId)?.delegatedCompletion?.delivery ?? {},
1921
+ { generation: 2, taskIds: [siblingTaskId] },
1922
+ "the sibling finished after the steered wake but no new completion wake was reserved",
1923
+ );
1924
+ assert.equal(tasks.get(siblingTaskId), "claimed");
1925
+ assert.equal(
1926
+ tasks.get(firstTaskId),
1927
+ "delivered",
1928
+ "the steered wake run's own task stays claimed after that run completed",
1929
+ );
1930
+ }).pipe(Effect.provide(harness.layer));
1931
+ }),
1932
+);
1933
+
1934
+it.effect.each([false, true])(
1935
+ "settles a steered completion wake whose parent run is before the last compaction (restart by intent: %s)",
1936
+ (intentNamesTarget) =>
1937
Effect.gen(function* () {
1896
- const harness = yield* nextTurnSelectionHarness("steered-completion-wake", true, false);
1938
+ const harness = yield* nextTurnSelectionHarness(
1939
+ `steered-wake-after-compaction-${intentNamesTarget}`,
1940
+ true,
1941
+ false,
1942
+ );
1943
yield* Effect.gen(function* () {
1944
const orchestrator = yield* Orchestrator.OrchestratorV2;
1899
- const {
1900
- threadId,
1901
- origin,
1902
- wake,
1903
- steered,
1904
- firstTaskId,
1905
- siblingTaskId,
1906
- watchRun,
1907
- finishTurn,
1908
- completeTask,
1909
- } = yield* restartCompletionWake(harness, false);
1910
-
1911
- // A follow-up queued behind the wake starts once the terminal-run listener has settled it.
1912
- const followUp = MessageId.make("message:follow-up");
1913
- yield* orchestrator.dispatch({
1914
- type: "message.dispatch",
1915
- commandId: CommandId.make("command:follow-up"),
1916
- threadId,
1917
- messageId: followUp,
1918
- text: "follow up",
1919
- attachments: [],
1920
- modelSelection: runSelection,
1921
- dispatchMode: { type: "queue_after_active" },
1922
- createdBy: "user",
1923
- creationSource: "web",
1924
- });
1925
- const followUpRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1926
- (run) => run.userMessageId === followUp,
1927
- )!;
1928
- const followUpStarted = yield* watchRun(followUpRun.id, "starting");
1929
- yield* finishTurn(steered);
1930
- yield* Fiber.join(followUpStarted);
1931
- assert.equal(
1932
- (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1933
- (run) => run.id === wake.runId,
1934
- )?.status,
1935
- "completed",
1936
- );
1937
-
1938
- yield* completeTask(siblingTaskId);
1939
- const final = yield* orchestrator.getThreadProjection(threadId);
1940
- const tasks = new Map(
1941
- final.subagents.map((task) => [task.id, task.completionDelivery?.state]),
1942
- );
1943
- assert.deepInclude(
1944
- final.runs.find((run) => run.id === origin.runId)?.delegatedCompletion?.delivery ?? {},
1945
- { generation: 2, taskIds: [siblingTaskId] },
1946
- "the sibling finished after the steered wake but no new completion wake was reserved",
1945
+ const { threadId, steered, firstTaskId, finishTurn } = yield* restartCompletionWake(
1946
+ harness,
1947
+ false,
1948
+ true,
1949
+ intentNamesTarget,
1950
);
1948
- assert.equal(tasks.get(siblingTaskId), "claimed");
1951
+ yield* finishTurn(steered);
1952
+ const tasks = (yield* orchestrator.getThreadProjection(threadId)).subagents;
1953
assert.equal(
1950
- tasks.get(firstTaskId),
1954
+ tasks.find((task) => task.id === firstTaskId)?.completionDelivery?.state,
1955
"delivered",
1952
- "the steered wake run's own task stays claimed after that run completed",
1956
);
1957
}).pipe(Effect.provide(harness.layer));
1958
}),
1956
- ),
1957
-);
1958
-
1959
-it.effect.each([false, true])(
1960
- "settles a steered completion wake whose parent run is before the last compaction (restart by intent: %s)",
1961
- (intentNamesTarget) =>
1962
- Effect.scoped(
1963
- Effect.gen(function* () {
1964
- const harness = yield* nextTurnSelectionHarness(
1965
- `steered-wake-after-compaction-${intentNamesTarget}`,
1966
- true,
1967
- false,
1968
- );
1969
- yield* Effect.gen(function* () {
1970
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1971
- const { threadId, steered, firstTaskId, finishTurn } = yield* restartCompletionWake(
1972
- harness,
1973
- false,
1974
- true,
1975
- intentNamesTarget,
1976
- );
1977
- yield* finishTurn(steered);
1978
- const tasks = (yield* orchestrator.getThreadProjection(threadId)).subagents;
1979
- assert.equal(
1980
- tasks.find((task) => task.id === firstTaskId)?.completionDelivery?.state,
1981
- "delivered",
1982
- );
1983
- }).pipe(Effect.provide(harness.layer));
1984
- }),
1985
- ),
1959
);
1960
1961
it.effect(
1962
"offers the next completion wake when a steer restarts a wake a sibling finished behind",
1963
() =>
1991
- Effect.scoped(
1992
- Effect.gen(function* () {
1993
- const harness = yield* nextTurnSelectionHarness(
1994
- "steered-completion-wake-behind",
1964
+ Effect.gen(function* () {
1965
+ const harness = yield* nextTurnSelectionHarness(
1966
+ "steered-completion-wake-behind",
1967
+ true,
1968
+ false,
1969
+ );
1970
+ const offers: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
1971
+ const requests = Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
1972
+ offer: (request) => Effect.sync(() => void offers.push(request)),
1973
+ take: Effect.never,
1974
+ });
1975
+ yield* Effect.gen(function* () {
1976
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1977
+ const { threadId, origin, firstTaskId, siblingTaskId } = yield* restartCompletionWake(
1978
+ harness,
1979
true,
1996
- false,
1980
);
1998
- const offers: ProviderContinuationRequests.ProviderContinuationRequest[] = [];
1999
- const requests = Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
2000
- offer: (request) => Effect.sync(() => void offers.push(request)),
2001
- take: Effect.never,
1981
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1982
+ const delivery = projection.runs.find((run) => run.id === origin.runId)?.delegatedCompletion
1983
+ ?.delivery;
1984
+ assert.deepInclude(delivery ?? {}, { generation: 2, taskIds: [siblingTaskId] });
1985
+ const tasks = new Map(
1986
+ projection.subagents.map((task) => [task.id, task.completionDelivery?.state]),
1987
+ );
1988
+ assert.equal(tasks.get(firstTaskId), "delivered");
1989
+ assert.equal(tasks.get(siblingTaskId), "claimed");
1990
+ assert.deepEqual(offers.at(-1)?.delegatedCompletion, {
1991
+ parentRunId: origin.runId,
1992
+ generation: 2,
1993
+ messageId: delivery!.messageId,
1994
});
2003
- yield* Effect.gen(function* () {
2004
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2005
- const { threadId, origin, firstTaskId, siblingTaskId } = yield* restartCompletionWake(
2006
- harness,
2007
- true,
2008
- );
2009
- const projection = yield* orchestrator.getThreadProjection(threadId);
2010
- const delivery = projection.runs.find((run) => run.id === origin.runId)
2011
- ?.delegatedCompletion?.delivery;
2012
- assert.deepInclude(delivery ?? {}, { generation: 2, taskIds: [siblingTaskId] });
2013
- const tasks = new Map(
2014
- projection.subagents.map((task) => [task.id, task.completionDelivery?.state]),
2015
- );
2016
- assert.equal(tasks.get(firstTaskId), "delivered");
2017
- assert.equal(tasks.get(siblingTaskId), "claimed");
2018
- assert.deepEqual(offers.at(-1)?.delegatedCompletion, {
2019
- parentRunId: origin.runId,
2020
- generation: 2,
2021
- messageId: delivery!.messageId,
2022
- });
2023
- }).pipe(Effect.provide(harness.layer.pipe(Layer.provide(requests))));
2024
- }),
2025
- ),
1995
+ }).pipe(Effect.provide(harness.layer.pipe(Layer.provide(requests))));
1996
+ }),
1997
);
1998
1999
// Codex flushes held drafts after the final answer; reserve their pre-steer position before turn end.
2000
it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
2030
- Effect.scoped(
2031
- Effect.gen(function* () {
2032
- const { events, started, layer, startFirstTurn } =
2033
- yield* nextTurnSelectionHarness("steering-held-draft");
2034
- yield* Effect.gen(function* () {
2035
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2036
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2037
- const threadId = yield* startFirstTurn;
2038
- const first = started[0]!;
2039
- const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2040
- const now = yield* DateTime.now;
2041
- const assistantItem = (id: string, text: string, streaming: boolean) =>
2042
- ({
2043
- type: "turn_item.updated",
2044
- driver,
2045
- turnItem: {
2046
- id: TurnItemId.make(id),
2047
- threadId,
2048
- runId: first.runId,
2049
- nodeId: first.rootNodeId,
2050
- providerThreadId: turn.providerThreadId,
2051
- providerTurnId: turn.id,
2052
- nativeItemRef: null,
2053
- parentItemId: null,
2054
- ordinal: 0,
2055
- status: streaming ? "running" : "completed",
2056
- title: null,
2057
- startedAt: now,
2058
- completedAt: streaming ? null : now,
2059
- updatedAt: now,
2060
- type: "assistant_message",
2061
- messageId: MessageId.make(`message:${id}`),
2062
- text,
2063
- streaming,
2064
- },
2065
- }) satisfies ProviderAdapter.ProviderAdapterV2Event;
2066
- const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
2067
- orchestrator.streamDomainEvents.pipe(
2068
- Stream.filter(predicate),
2069
- Stream.take(1),
2070
- Stream.runDrain,
2071
- Effect.forkScoped,
2072
- );
2073
-
2074
- yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
2075
- const commentaryWritten = yield* watch(
2076
- (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
2001
+ Effect.gen(function* () {
2002
+ const { events, started, layer, startFirstTurn } =
2003
+ yield* nextTurnSelectionHarness("steering-held-draft");
2004
+ yield* Effect.gen(function* () {
2005
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2006
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2007
+ const threadId = yield* startFirstTurn;
2008
+ const first = started[0]!;
2009
+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2010
+ const now = yield* DateTime.now;
2011
+ const assistantItem = (id: string, text: string, streaming: boolean) =>
2012
+ ({
2013
+ type: "turn_item.updated",
2014
+ driver,
2015
+ turnItem: {
2016
+ id: TurnItemId.make(id),
2017
+ threadId,
2018
+ runId: first.runId,
2019
+ nodeId: first.rootNodeId,
2020
+ providerThreadId: turn.providerThreadId,
2021
+ providerTurnId: turn.id,
2022
+ nativeItemRef: null,
2023
+ parentItemId: null,
2024
+ ordinal: 0,
2025
+ status: streaming ? "running" : "completed",
2026
+ title: null,
2027
+ startedAt: now,
2028
+ completedAt: streaming ? null : now,
2029
+ updatedAt: now,
2030
+ type: "assistant_message",
2031
+ messageId: MessageId.make(`message:${id}`),
2032
+ text,
2033
+ streaming,
2034
+ },
2035
+ }) satisfies ProviderAdapter.ProviderAdapterV2Event;
2036
+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
2037
+ orchestrator.streamDomainEvents.pipe(
2038
+ Stream.filter(predicate),
2039
+ Stream.take(1),
2040
+ Stream.runDrain,
2041
+ Effect.forkScoped,
2042
);
2078
- yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
2079
- yield* Fiber.join(commentaryWritten);
2043
2081
- yield* orchestrator.dispatch({
2082
- type: "message.dispatch",
2083
- commandId: CommandId.make("steer"),
2084
- threadId,
2085
- messageId: MessageId.make("message:steer"),
2086
- text: "fix the popover",
2087
- attachments: [],
2088
- dispatchMode: { type: "steer_active", targetRunId: first.runId },
2089
- createdBy: "user",
2090
- creationSource: "web",
2091
- });
2092
- yield* worker.drain();
2044
+ yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
2045
+ const commentaryWritten = yield* watch(
2046
+ (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
2047
+ );
2048
+ yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
2049
+ yield* Fiber.join(commentaryWritten);
2050
2094
- const settled = yield* watch(
2095
- (event) =>
2096
- event.type === "run.updated" &&
2097
- event.payload.id === first.runId &&
2098
- event.payload.status === "waiting",
2099
- );
2100
- yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
2101
- yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
2102
- yield* Queue.offer(events, {
2103
- type: "provider_turn.updated",
2104
- driver,
2105
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
2106
- });
2107
- yield* Queue.offer(events, {
2108
- type: "turn.terminal",
2109
- driver,
2110
- providerThreadId: turn.providerThreadId,
2111
- providerTurnId: turn.id,
2112
- runOrdinal: first.runOrdinal,
2113
- status: "completed",
2114
- failure: null,
2115
- threadDisposition: "reusable",
2116
- });
2117
- yield* Fiber.join(settled);
2118
- yield* worker.drain();
2051
+ yield* orchestrator.dispatch({
2052
+ type: "message.dispatch",
2053
+ commandId: CommandId.make("steer"),
2054
+ threadId,
2055
+ messageId: MessageId.make("message:steer"),
2056
+ text: "fix the popover",
2057
+ attachments: [],
2058
+ dispatchMode: { type: "steer_active", targetRunId: first.runId },
2059
+ createdBy: "user",
2060
+ creationSource: "web",
2061
+ });
2062
+ yield* worker.drain();
2063
+
2064
+ const settled = yield* watch(
2065
+ (event) =>
2066
+ event.type === "run.updated" &&
2067
+ event.payload.id === first.runId &&
2068
+ event.payload.status === "waiting",
2069
+ );
2070
+ yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
2071
+ yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
2072
+ yield* Queue.offer(events, {
2073
+ type: "provider_turn.updated",
2074
+ driver,
2075
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
2076
+ });
2077
+ yield* Queue.offer(events, {
2078
+ type: "turn.terminal",
2079
+ driver,
2080
+ providerThreadId: turn.providerThreadId,
2081
+ providerTurnId: turn.id,
2082
+ runOrdinal: first.runOrdinal,
2083
+ status: "completed",
2084
+ failure: null,
2085
+ threadDisposition: "reusable",
2086
+ });
2087
+ yield* Fiber.join(settled);
2088
+ yield* worker.drain();
2089
2120
- const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
2121
- .toSorted((left, right) => left.ordinal - right.ordinal)
2122
- .flatMap((item) =>
2123
- item.type === "user_message"
2124
- ? [String(item.messageId)]
2125
- : item.type === "assistant_message"
2126
- ? [String(item.id)]
2127
- : [],
2128
- );
2129
- assert.deepEqual(items, [
2130
- "message:first",
2131
- "draft",
2132
- "commentary",
2133
- "message:steer",
2134
- "answer",
2135
- ]);
2136
- }).pipe(Effect.provide(layer));
2137
- }),
2138
- ),
2090
+ const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
2091
+ .toSorted((left, right) => left.ordinal - right.ordinal)
2092
+ .flatMap((item) =>
2093
+ item.type === "user_message"
2094
+ ? [String(item.messageId)]
2095
+ : item.type === "assistant_message"
2096
+ ? [String(item.id)]
2097
+ : [],
2098
+ );
2099
+ assert.deepEqual(items, ["message:first", "draft", "commentary", "message:steer", "answer"]);
2100
+ }).pipe(Effect.provide(layer));
2101
+ }),
2102
);
2103
2104
it.effect("steers a promoted queued message with the selection it was queued with", () =>
2142
- Effect.scoped(
2143
- Effect.gen(function* () {
2144
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2145
- "promote-queued-selection",
2146
- );
2147
- yield* Effect.gen(function* () {
2148
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2149
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2150
- const threadId = yield* startFirstTurn;
2151
- yield* orchestrator.dispatch({
2152
- type: "message.dispatch",
2153
- commandId: CommandId.make("queued"),
2154
- threadId,
2155
- messageId: MessageId.make("message:queued"),
2156
- text: "queued",
2157
- attachments: [],
2158
- modelSelection: composerSelection,
2159
- dispatchMode: { type: "queue_after_active" },
2160
- createdBy: "user",
2161
- creationSource: "web",
2162
- });
2163
- const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2164
- (run) => run.status === "queued",
2165
- )!;
2166
- yield* orchestrator.dispatch({
2167
- type: "queued-message.promote-to-steer",
2168
- commandId: CommandId.make("promote"),
2169
- threadId,
2170
- queuedRunId: queuedRun.id,
2171
- targetRunId: started[0]!.runId,
2172
- });
2173
- yield* worker.drain();
2105
+ Effect.gen(function* () {
2106
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2107
+ "promote-queued-selection",
2108
+ );
2109
+ yield* Effect.gen(function* () {
2110
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2111
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2112
+ const threadId = yield* startFirstTurn;
2113
+ yield* orchestrator.dispatch({
2114
+ type: "message.dispatch",
2115
+ commandId: CommandId.make("queued"),
2116
+ threadId,
2117
+ messageId: MessageId.make("message:queued"),
2118
+ text: "queued",
2119
+ attachments: [],
2120
+ modelSelection: composerSelection,
2121
+ dispatchMode: { type: "queue_after_active" },
2122
+ createdBy: "user",
2123
+ creationSource: "web",
2124
+ });
2125
+ const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2126
+ (run) => run.status === "queued",
2127
+ )!;
2128
+ yield* orchestrator.dispatch({
2129
+ type: "queued-message.promote-to-steer",
2130
+ commandId: CommandId.make("promote"),
2131
+ threadId,
2132
+ queuedRunId: queuedRun.id,
2133
+ targetRunId: started[0]!.runId,
2134
+ });
2135
+ yield* worker.drain();
2136
2175
- const projection = yield* orchestrator.getThreadProjection(threadId);
2176
- assert.deepEqual(steered, ["queued"]);
2177
- assert.deepEqual(projection.thread.modelSelection, composerSelection);
2178
- }).pipe(Effect.provide(layer));
2179
- }),
2180
- ),
2137
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2138
+ assert.deepEqual(steered, ["queued"]);
2139
+ assert.deepEqual(projection.thread.modelSelection, composerSelection);
2140
+ }).pipe(Effect.provide(layer));
2141
+ }),
2142
);
2143
2144
it.effect("marks the model switch on a promoted message that restarts the turn", () =>
2184
- Effect.scoped(
2185
- Effect.gen(function* () {
2186
- const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2187
- "promote-restart-switch",
2188
- true,
2189
- false,
2145
+ Effect.gen(function* () {
2146
+ const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2147
+ "promote-restart-switch",
2148
+ true,
2149
+ false,
2150
+ );
2151
+ const otherSelection = { ...runSelection, model: "other-model" };
2152
+ yield* Effect.gen(function* () {
2153
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2154
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2155
+ const threadId = yield* startFirstTurn;
2156
+ yield* orchestrator.dispatch({
2157
+ type: "message.dispatch",
2158
+ commandId: CommandId.make("queued"),
2159
+ threadId,
2160
+ messageId: MessageId.make("message:queued"),
2161
+ text: "queued",
2162
+ attachments: [],
2163
+ modelSelection: otherSelection,
2164
+ dispatchMode: { type: "queue_after_active" },
2165
+ createdBy: "user",
2166
+ creationSource: "web",
2167
+ });
2168
+ const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2169
+ (run) => run.status === "queued",
2170
+ )!;
2171
+ yield* orchestrator.dispatch({
2172
+ type: "queued-message.promote-to-steer",
2173
+ commandId: CommandId.make("promote"),
2174
+ threadId,
2175
+ queuedRunId: queuedRun.id,
2176
+ targetRunId: started[0]!.runId,
2177
+ });
2178
+ yield* worker.drain();
2179
+
2180
+ const promoted = (yield* orchestrator.getThreadProjection(threadId)).turnItems.find(
2181
+ (item) => item.type === "user_message" && item.messageId === "message:queued",
2182
);
2191
- const otherSelection = { ...runSelection, model: "other-model" };
2192
- yield* Effect.gen(function* () {
2193
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2194
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2195
- const threadId = yield* startFirstTurn;
2196
- yield* orchestrator.dispatch({
2197
- type: "message.dispatch",
2198
- commandId: CommandId.make("queued"),
2199
- threadId,
2200
- messageId: MessageId.make("message:queued"),
2201
- text: "queued",
2202
- attachments: [],
2203
- modelSelection: otherSelection,
2204
- dispatchMode: { type: "queue_after_active" },
2205
- createdBy: "user",
2206
- creationSource: "web",
2207
- });
2208
- const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2209
- (run) => run.status === "queued",
2210
- )!;
2211
- yield* orchestrator.dispatch({
2183
+ assert.deepEqual(promoted?.type === "user_message" ? promoted.modelSwitch : undefined, {
2184
+ from: runSelection,
2185
+ to: otherSelection,
2186
+ });
2187
+ }).pipe(Effect.provide(layer));
2188
+ }),
2189
+);
2190
+
2191
+it.effect("keeps a queued message queued when promoted into a run that Stop reached", () =>
2192
+ Effect.gen(function* () {
2193
+ const { started, steered, layer, startFirstTurn } =
2194
+ yield* nextTurnSelectionHarness("steering-after-stop");
2195
+ yield* Effect.gen(function* () {
2196
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2197
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2198
+ const threadId = yield* startFirstTurn;
2199
+ const first = started[0]!;
2200
+ yield* orchestrator.dispatch({
2201
+ type: "message.dispatch",
2202
+ commandId: CommandId.make("queued"),
2203
+ threadId,
2204
+ messageId: MessageId.make("message:queued"),
2205
+ text: "queued",
2206
+ attachments: [],
2207
+ modelSelection: runSelection,
2208
+ dispatchMode: { type: "queue_after_active" },
2209
+ createdBy: "user",
2210
+ creationSource: "web",
2211
+ });
2212
+ const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2213
+ (run) => run.status === "queued",
2214
+ )!;
2215
+ // The worker has not delivered the interrupt yet, so the run still reads as running.
2216
+ yield* orchestrator.dispatch({
2217
+ type: "run.interrupt",
2218
+ commandId: CommandId.make("stop"),
2219
+ threadId,
2220
+ runId: first.runId,
2221
+ holdQueue: true,
2222
+ });
2223
+
2224
+ const promoteError = yield* orchestrator
2225
+ .dispatch({
2226
type: "queued-message.promote-to-steer",
2227
commandId: CommandId.make("promote"),
2228
threadId,
2229
queuedRunId: queuedRun.id,
2216
- targetRunId: started[0]!.runId,
2217
- });
2218
- yield* worker.drain();
2230
+ targetRunId: first.runId,
2231
+ })
2232
+ .pipe(Effect.flip);
2233
+ yield* worker.drain();
2234
2220
- const promoted = (yield* orchestrator.getThreadProjection(threadId)).turnItems.find(
2221
- (item) => item.type === "user_message" && item.messageId === "message:queued",
2222
- );
2223
- assert.deepEqual(promoted?.type === "user_message" ? promoted.modelSwitch : undefined, {
2224
- from: runSelection,
2225
- to: otherSelection,
2226
- });
2227
- }).pipe(Effect.provide(layer));
2228
- }),
2229
- ),
2235
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2236
+ assert.equal(promoteError._tag, "OrchestratorDispatchError");
2237
+ assert.deepEqual(steered, []);
2238
+ const queued = projection.runs.find((run) => run.id === queuedRun.id);
2239
+ assert.equal(queued?.status, "queued");
2240
+ assert.isTrue(queued?.queueHeld);
2241
+ }).pipe(Effect.provide(layer));
2242
+ }),
2243
);
2244
2232
-it.effect("keeps a queued message queued when promoted into a run that Stop reached", () =>
2233
- Effect.scoped(
2245
+// regression: #32891 a restart that Stop already reached is lost
2246
+it.effect.each([false, true])(
2247
+ "refuses a steer after Stop (provider turn ready: %s)",
2248
+ (providerTurnReady) =>
2249
Effect.gen(function* () {
2250
const { started, steered, layer, startFirstTurn } =
2236
- yield* nextTurnSelectionHarness("steering-after-stop");
2251
+ yield* nextTurnSelectionHarness("restart-after-stop");
2252
yield* Effect.gen(function* () {
2253
const orchestrator = yield* Orchestrator.OrchestratorV2;
2254
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2255
const threadId = yield* startFirstTurn;
2256
const first = started[0]!;
2242
- yield* orchestrator.dispatch({
2243
- type: "message.dispatch",
2244
- commandId: CommandId.make("queued"),
2245
- threadId,
2246
- messageId: MessageId.make("message:queued"),
2247
- text: "queued",
2248
- attachments: [],
2249
- modelSelection: runSelection,
2250
- dispatchMode: { type: "queue_after_active" },
2251
- createdBy: "user",
2252
- creationSource: "web",
2253
- });
2254
- const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2255
- (run) => run.status === "queued",
2256
- )!;
2257
// The worker has not delivered the interrupt yet, so the run still reads as running.
2258
yield* orchestrator.dispatch({
2259
type: "run.interrupt",
2260
commandId: CommandId.make("stop"),
2261
threadId,
2262
runId: first.runId,
2263
- holdQueue: true,
2263
});
2265
-
2266
- const promoteError = yield* orchestrator
2267
- .dispatch({
2268
- type: "queued-message.promote-to-steer",
2269
- commandId: CommandId.make("promote"),
2270
- threadId,
2271
- queuedRunId: queuedRun.id,
2272
- targetRunId: first.runId,
2273
- })
2274
- .pipe(Effect.flip);
2275
- yield* worker.drain();
2276
-
2277
- const projection = yield* orchestrator.getThreadProjection(threadId);
2278
- assert.equal(promoteError._tag, "OrchestratorDispatchError");
2279
- assert.deepEqual(steered, []);
2280
- const queued = projection.runs.find((run) => run.id === queuedRun.id);
2281
- assert.equal(queued?.status, "queued");
2282
- assert.isTrue(queued?.queueHeld);
2283
- }).pipe(Effect.provide(layer));
2284
- }),
2285
- ),
2286
-);
2287
-
2288
-// regression: #32891 a restart that Stop already reached is lost
2289
-it.effect.each([false, true])(
2290
- "refuses a steer after Stop (provider turn ready: %s)",
2291
- (providerTurnReady) =>
2292
- Effect.scoped(
2293
- Effect.gen(function* () {
2294
- const { started, steered, layer, startFirstTurn } =
2295
- yield* nextTurnSelectionHarness("restart-after-stop");
2296
- yield* Effect.gen(function* () {
2297
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2298
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2299
- const threadId = yield* startFirstTurn;
2300
- const first = started[0]!;
2301
- // The worker has not delivered the interrupt yet, so the run still reads as running.
2302
- yield* orchestrator.dispatch({
2303
- type: "run.interrupt",
2304
- commandId: CommandId.make("stop"),
2305
- threadId,
2306
- runId: first.runId,
2264
+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2265
+ if (!providerTurnReady) {
2266
+ yield* (yield* EventSink.EventSinkV2).write({
2267
+ events: [
2268
+ {
2269
+ id: EventId.make("turn-not-ready"),
2270
+ type: "provider-turn.updated",
2271
+ threadId,
2272
+ occurredAt: yield* DateTime.now,
2273
+ payload: { ...turn, status: "pending" },
2274
+ },
2275
+ ],
2276
});
2308
- const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2309
- if (!providerTurnReady) {
2310
- yield* (yield* EventSink.EventSinkV2).write({
2311
- events: [
2312
- {
2313
- id: EventId.make("turn-not-ready"),
2314
- type: "provider-turn.updated",
2315
- threadId,
2316
- occurredAt: yield* DateTime.now,
2317
- payload: { ...turn, status: "pending" },
2318
- },
2319
- ],
2320
- });
2321
- }
2322
- const steerError = yield* orchestrator
2323
- .dispatch({
2324
- type: "message.dispatch",
2325
- commandId: CommandId.make("steer"),
2326
- threadId,
2327
- messageId: MessageId.make("message:steer"),
2328
- text: "steer",
2329
- attachments: [],
2330
- modelSelection: runSelection,
2331
- dispatchMode: { type: "steer_active", targetRunId: first.runId },
2332
- createdBy: "user",
2333
- creationSource: "web",
2334
- })
2335
- .pipe(Effect.flip);
2336
- assert.equal(steerError._tag, "OrchestratorDispatchError");
2337
- assert.include(String(steerError.cause), "is stopping and cannot be steered");
2338
- if (!providerTurnReady) {
2339
- yield* (yield* EventSink.EventSinkV2).write({
2340
- events: [
2341
- {
2342
- id: EventId.make("restore-ready-turn"),
2343
- type: "provider-turn.updated",
2344
- threadId,
2345
- occurredAt: yield* DateTime.now,
2346
- payload: turn,
2347
- },
2348
- ],
2349
- });
2350
- }
2351
- yield* orchestrator.dispatch({
2277
+ }
2278
+ const steerError = yield* orchestrator
2279
+ .dispatch({
2280
type: "message.dispatch",
2353
- commandId: CommandId.make("restart"),
2281
+ commandId: CommandId.make("steer"),
2282
threadId,
2355
- messageId: MessageId.make("message:restart"),
2356
- text: "restart",
2283
+ messageId: MessageId.make("message:steer"),
2284
+ text: "steer",
2285
attachments: [],
2286
modelSelection: runSelection,
2359
- dispatchMode: { type: "restart_active", targetRunId: first.runId },
2287
+ dispatchMode: { type: "steer_active", targetRunId: first.runId },
2288
createdBy: "user",
2289
creationSource: "web",
2290
+ })
2291
+ .pipe(Effect.flip);
2292
+ assert.equal(steerError._tag, "OrchestratorDispatchError");
2293
+ assert.include(String(steerError.cause), "is stopping and cannot be steered");
2294
+ if (!providerTurnReady) {
2295
+ yield* (yield* EventSink.EventSinkV2).write({
2296
+ events: [
2297
+ {
2298
+ id: EventId.make("restore-ready-turn"),
2299
+ type: "provider-turn.updated",
2300
+ threadId,
2301
+ occurredAt: yield* DateTime.now,
2302
+ payload: turn,
2303
+ },
2304
+ ],
2305
});
2363
- yield* worker.drain();
2306
+ }
2307
+ yield* orchestrator.dispatch({
2308
+ type: "message.dispatch",
2309
+ commandId: CommandId.make("restart"),
2310
+ threadId,
2311
+ messageId: MessageId.make("message:restart"),
2312
+ text: "restart",
2313
+ attachments: [],
2314
+ modelSelection: runSelection,
2315
+ dispatchMode: { type: "restart_active", targetRunId: first.runId },
2316
+ createdBy: "user",
2317
+ creationSource: "web",
2318
+ });
2319
+ yield* worker.drain();
2320
2365
- assert.deepEqual(steered, []);
2366
- assert.deepEqual(
2367
- started.map((turn) => turn.message.text),
2368
- ["first", "restart"],
2369
- );
2370
- }).pipe(Effect.provide(layer));
2371
- }),
2372
- ),
2321
+ assert.deepEqual(steered, []);
2322
+ assert.deepEqual(
2323
+ started.map((turn) => turn.message.text),
2324
+ ["first", "restart"],
2325
+ );
2326
+ }).pipe(Effect.provide(layer));
2327
+ }),
2328
);
2329
2330
// regression: #32891 a restart that arrives after the turn ended is lost
@@ -2377,112 +2332,14 @@ it.effect.each([
2332
{ status: "completed", settled: true },
2333
{ status: "completed", settled: false },
2334
{ status: "interrupted", settled: true },
2380
- { status: "interrupted", settled: false },
2381
- { status: "cancelled", settled: false },
2382
-] as const)(
2383
- "starts a restart that missed the turn ($status, run settled: $settled) as a new turn",
2384
- ({ status, settled: runSettled }) =>
2385
- Effect.scoped(
2386
- Effect.gen(function* () {
2387
- const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2388
- `restart-after-${status}-${runSettled ? "settled" : "unsettled"}`,
2389
- );
2390
- yield* Effect.gen(function* () {
2391
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2392
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2393
- const threadId = yield* startFirstTurn;
2394
- const first = started[0]!;
2395
- const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2396
- const turnEnded = yield* orchestrator.streamDomainEvents.pipe(
2397
- Stream.filter(
2398
- (event) =>
2399
- event.type === "provider-turn.updated" &&
2400
- event.payload.id === turn.id &&
2401
- event.payload.status === status,
2402
- ),
2403
- Stream.take(1),
2404
- Stream.runDrain,
2405
- Effect.forkScoped,
2406
- );
2407
- yield* Queue.offer(events, {
2408
- type: "provider_turn.updated",
2409
- driver,
2410
- providerTurn: { ...turn, status, completedAt: yield* DateTime.now },
2411
- });
2412
- yield* Fiber.join(turnEnded);
2413
- const settleRun = Effect.gen(function* () {
2414
- const settled = yield* orchestrator.streamDomainEvents.pipe(
2415
- Stream.filter(
2416
- (event) =>
2417
- event.type === "run.updated" &&
2418
- event.payload.id === first.runId &&
2419
- event.payload.status !== "running",
2420
- ),
2421
- Stream.take(1),
2422
- Stream.runDrain,
2423
- Effect.forkScoped,
2424
- );
2425
- yield* Queue.offer(events, {
2426
- type: "turn.terminal",
2427
- driver,
2428
- providerThreadId: turn.providerThreadId,
2429
- providerTurnId: turn.id,
2430
- runOrdinal: first.runOrdinal,
2431
- status,
2432
- failure: null,
2433
- threadDisposition: "reusable",
2434
- });
2435
- yield* Fiber.join(settled);
2436
- yield* worker.drain();
2437
- });
2438
- if (runSettled) yield* settleRun;
2439
-
2440
- yield* orchestrator.dispatch({
2441
- type: "message.dispatch",
2442
- commandId: CommandId.make("restart"),
2443
- threadId,
2444
- messageId: MessageId.make("message:restart"),
2445
- text: "restart",
2446
- attachments: [],
2447
- modelSelection: runSelection,
2448
- dispatchMode: { type: "restart_active", targetRunId: first.runId },
2449
- createdBy: "user",
2450
- creationSource: "web",
2451
- });
2452
- yield* worker.drain();
2453
- if (!runSettled) {
2454
- const restartLeftQueue = yield* orchestrator.streamDomainEvents.pipe(
2455
- Stream.filter(
2456
- (event) =>
2457
- event.type === "run.updated" &&
2458
- event.payload.userMessageId === "message:restart" &&
2459
- event.payload.status !== "queued",
2460
- ),
2461
- Stream.take(1),
2462
- Stream.runDrain,
2463
- Effect.forkScoped,
2464
- );
2465
- yield* settleRun;
2466
- yield* Fiber.join(restartLeftQueue);
2467
- yield* worker.drain();
2468
- }
2469
-
2470
- assert.deepEqual(steered, []);
2471
- assert.deepEqual(
2472
- started.map((turn) => turn.message.text),
2473
- ["first", "restart"],
2474
- );
2475
- }).pipe(Effect.provide(layer));
2476
- }),
2477
- ),
2478
-);
2479
-
2480
-// regression: #32891 a restart into a failed provider turn is lost
2481
-it.effect("queues a restart sent into a provider turn that failed before its run settled", () =>
2482
- Effect.scoped(
2335
+ { status: "interrupted", settled: false },
2336
+ { status: "cancelled", settled: false },
2337
+] as const)(
2338
+ "starts a restart that missed the turn ($status, run settled: $settled) as a new turn",
2339
+ ({ status, settled: runSettled }) =>
2340
Effect.gen(function* () {
2341
const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2485
- "restart-after-failed-unsettled",
2342
+ `restart-after-${status}-${runSettled ? "settled" : "unsettled"}`,
2343
);
2344
yield* Effect.gen(function* () {
2345
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -2490,12 +2347,12 @@ it.effect("queues a restart sent into a provider turn that failed before its run
2347
const threadId = yield* startFirstTurn;
2348
const first = started[0]!;
2349
const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2493
- const turnFailed = yield* orchestrator.streamDomainEvents.pipe(
2350
+ const turnEnded = yield* orchestrator.streamDomainEvents.pipe(
2351
Stream.filter(
2352
(event) =>
2353
event.type === "provider-turn.updated" &&
2354
event.payload.id === turn.id &&
2498
- event.payload.status === "failed",
2355
+ event.payload.status === status,
2356
),
2357
Stream.take(1),
2358
Stream.runDrain,
@@ -2504,9 +2361,35 @@ it.effect("queues a restart sent into a provider turn that failed before its run
2361
yield* Queue.offer(events, {
2362
type: "provider_turn.updated",
2363
driver,
2507
- providerTurn: { ...turn, status: "failed", completedAt: yield* DateTime.now },
2364
+ providerTurn: { ...turn, status, completedAt: yield* DateTime.now },
2365
+ });
2366
+ yield* Fiber.join(turnEnded);
2367
+ const settleRun = Effect.gen(function* () {
2368
+ const settled = yield* orchestrator.streamDomainEvents.pipe(
2369
+ Stream.filter(
2370
+ (event) =>
2371
+ event.type === "run.updated" &&
2372
+ event.payload.id === first.runId &&
2373
+ event.payload.status !== "running",
2374
+ ),
2375
+ Stream.take(1),
2376
+ Stream.runDrain,
2377
+ Effect.forkScoped,
2378
+ );
2379
+ yield* Queue.offer(events, {
2380
+ type: "turn.terminal",
2381
+ driver,
2382
+ providerThreadId: turn.providerThreadId,
2383
+ providerTurnId: turn.id,
2384
+ runOrdinal: first.runOrdinal,
2385
+ status,
2386
+ failure: null,
2387
+ threadDisposition: "reusable",
2388
+ });
2389
+ yield* Fiber.join(settled);
2390
+ yield* worker.drain();
2391
});
2509
- yield* Fiber.join(turnFailed);
2392
+ if (runSettled) yield* settleRun;
2393
2394
yield* orchestrator.dispatch({
2395
type: "message.dispatch",
@@ -2521,84 +2404,150 @@ it.effect("queues a restart sent into a provider turn that failed before its run
2404
creationSource: "web",
2405
});
2406
yield* worker.drain();
2407
+ if (!runSettled) {
2408
+ const restartLeftQueue = yield* orchestrator.streamDomainEvents.pipe(
2409
+ Stream.filter(
2410
+ (event) =>
2411
+ event.type === "run.updated" &&
2412
+ event.payload.userMessageId === "message:restart" &&
2413
+ event.payload.status !== "queued",
2414
+ ),
2415
+ Stream.take(1),
2416
+ Stream.runDrain,
2417
+ Effect.forkScoped,
2418
+ );
2419
+ yield* settleRun;
2420
+ yield* Fiber.join(restartLeftQueue);
2421
+ yield* worker.drain();
2422
+ }
2423
2424
assert.deepEqual(steered, []);
2526
- const projection = yield* orchestrator.getThreadProjection(threadId);
2527
- assert.equal(
2528
- projection.runs.find((run) => run.userMessageId === "message:restart")?.status,
2529
- "queued",
2425
+ assert.deepEqual(
2426
+ started.map((turn) => turn.message.text),
2427
+ ["first", "restart"],
2428
);
2429
}).pipe(Effect.provide(layer));
2430
}),
2533
- ),
2431
);
2432
2536
-it.effect("queues a plain send behind the stopped queue and releases its hold", () =>
2537
- Effect.scoped(
2538
- Effect.gen(function* () {
2539
- const interruptReached = yield* Deferred.make<void>();
2540
- const releaseInterrupt = yield* Deferred.make<void>();
2541
- const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2542
- "plain-send-after-stop",
2543
- false,
2544
- true,
2545
- Deferred.succeed(interruptReached, undefined).pipe(
2546
- Effect.andThen(Deferred.await(releaseInterrupt)),
2433
+// regression: #32891 a restart into a failed provider turn is lost
2434
+it.effect("queues a restart sent into a provider turn that failed before its run settled", () =>
2435
+ Effect.gen(function* () {
2436
+ const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2437
+ "restart-after-failed-unsettled",
2438
+ );
2439
+ yield* Effect.gen(function* () {
2440
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2441
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2442
+ const threadId = yield* startFirstTurn;
2443
+ const first = started[0]!;
2444
+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2445
+ const turnFailed = yield* orchestrator.streamDomainEvents.pipe(
2446
+ Stream.filter(
2447
+ (event) =>
2448
+ event.type === "provider-turn.updated" &&
2449
+ event.payload.id === turn.id &&
2450
+ event.payload.status === "failed",
2451
),
2452
+ Stream.take(1),
2453
+ Stream.runDrain,
2454
+ Effect.forkScoped,
2455
);
2549
- yield* Effect.gen(function* () {
2550
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2551
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2552
- const threadId = yield* startFirstTurn;
2553
- const send = (id: string, delivery: "queue" | "auto") =>
2554
- orchestrator.dispatch({
2555
- type: "message.dispatch",
2556
- commandId: CommandId.make(id),
2557
- threadId,
2558
- messageId: MessageId.make(`message:${id}`),
2559
- text: id,
2560
- attachments: [],
2561
- modelSelection: runSelection,
2562
- ...(delivery === "queue"
2563
- ? { dispatchMode: { type: "queue_after_active" } }
2564
- : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
2565
- createdBy: "user",
2566
- creationSource: "web",
2567
- });
2568
- yield* send("queued", "queue");
2569
- yield* orchestrator.dispatch({
2570
- type: "run.interrupt",
2571
- commandId: CommandId.make("stop"),
2456
+ yield* Queue.offer(events, {
2457
+ type: "provider_turn.updated",
2458
+ driver,
2459
+ providerTurn: { ...turn, status: "failed", completedAt: yield* DateTime.now },
2460
+ });
2461
+ yield* Fiber.join(turnFailed);
2462
+
2463
+ yield* orchestrator.dispatch({
2464
+ type: "message.dispatch",
2465
+ commandId: CommandId.make("restart"),
2466
+ threadId,
2467
+ messageId: MessageId.make("message:restart"),
2468
+ text: "restart",
2469
+ attachments: [],
2470
+ modelSelection: runSelection,
2471
+ dispatchMode: { type: "restart_active", targetRunId: first.runId },
2472
+ createdBy: "user",
2473
+ creationSource: "web",
2474
+ });
2475
+ yield* worker.drain();
2476
+
2477
+ assert.deepEqual(steered, []);
2478
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2479
+ assert.equal(
2480
+ projection.runs.find((run) => run.userMessageId === "message:restart")?.status,
2481
+ "queued",
2482
+ );
2483
+ }).pipe(Effect.provide(layer));
2484
+ }),
2485
+);
2486
+
2487
+it.effect("queues a plain send behind the stopped queue and releases its hold", () =>
2488
+ Effect.gen(function* () {
2489
+ const interruptReached = yield* Deferred.make<void>();
2490
+ const releaseInterrupt = yield* Deferred.make<void>();
2491
+ const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
2492
+ "plain-send-after-stop",
2493
+ false,
2494
+ true,
2495
+ Deferred.succeed(interruptReached, undefined).pipe(
2496
+ Effect.andThen(Deferred.await(releaseInterrupt)),
2497
+ ),
2498
+ );
2499
+ yield* Effect.gen(function* () {
2500
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2501
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2502
+ const threadId = yield* startFirstTurn;
2503
+ const send = (id: string, delivery: "queue" | "auto") =>
2504
+ orchestrator.dispatch({
2505
+ type: "message.dispatch",
2506
+ commandId: CommandId.make(id),
2507
threadId,
2573
- runId: started[0]!.runId,
2574
- holdQueue: true,
2508
+ messageId: MessageId.make(`message:${id}`),
2509
+ text: id,
2510
+ attachments: [],
2511
+ modelSelection: runSelection,
2512
+ ...(delivery === "queue"
2513
+ ? { dispatchMode: { type: "queue_after_active" } }
2514
+ : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
2515
+ createdBy: "user",
2516
+ creationSource: "web",
2517
});
2576
- // The provider has not stopped yet, so a plain send still resolves to a steer.
2577
- yield* send("sent", "auto");
2578
- // Once the stop settles, the run-update reactor promotes the queue on
2579
- // its own fiber, so read the queue while the provider is still stopping.
2580
- const draining = yield* worker.drain().pipe(Effect.forkScoped);
2581
- yield* Deferred.await(interruptReached);
2582
-
2583
- const projection = yield* orchestrator.getThreadProjection(threadId);
2584
- assert.equal(started.length, 1);
2585
- const queued = projection.runs
2586
- .filter((run) => run.status === "queued")
2587
- .sort((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0));
2588
- assert.deepEqual(
2589
- queued.map(
2590
- (run) => projection.messages.find((message) => message.id === run.userMessageId)?.text,
2591
- ),
2592
- ["queued", "sent"],
2593
- );
2594
- // The user sent it, so the queue they stopped runs again once the provider stops.
2595
- assert.isFalse(queued.some((run) => run.queueHeld === true));
2596
- yield* Deferred.succeed(releaseInterrupt, undefined);
2597
- yield* Fiber.join(draining);
2598
- assert.deepEqual(steered, []);
2599
- }).pipe(Effect.provide(layer));
2600
- }),
2601
- ),
2518
+ yield* send("queued", "queue");
2519
+ yield* orchestrator.dispatch({
2520
+ type: "run.interrupt",
2521
+ commandId: CommandId.make("stop"),
2522
+ threadId,
2523
+ runId: started[0]!.runId,
2524
+ holdQueue: true,
2525
+ });
2526
+ // The provider has not stopped yet, so a plain send still resolves to a steer.
2527
+ yield* send("sent", "auto");
2528
+ // Once the stop settles, the run-update reactor promotes the queue on
2529
+ // its own fiber, so read the queue while the provider is still stopping.
2530
+ const draining = yield* worker.drain().pipe(Effect.forkScoped);
2531
+ yield* Deferred.await(interruptReached);
2532
+
2533
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2534
+ assert.equal(started.length, 1);
2535
+ const queued = projection.runs
2536
+ .filter((run) => run.status === "queued")
2537
+ .sort((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0));
2538
+ assert.deepEqual(
2539
+ queued.map(
2540
+ (run) => projection.messages.find((message) => message.id === run.userMessageId)?.text,
2541
+ ),
2542
+ ["queued", "sent"],
2543
+ );
2544
+ // The user sent it, so the queue they stopped runs again once the provider stops.
2545
+ assert.isFalse(queued.some((run) => run.queueHeld === true));
2546
+ yield* Deferred.succeed(releaseInterrupt, undefined);
2547
+ yield* Fiber.join(draining);
2548
+ assert.deepEqual(steered, []);
2549
+ }).pipe(Effect.provide(layer));
2550
+ }),
2551
);
2552
2553
const goalHarness = Effect.fn("goalHarness")(function* (name: string, nativeGoals?: boolean) {
@@ -2652,507 +2601,294 @@ const goalHarness = Effect.fn("goalHarness")(function* (name: string, nativeGoal
2601
it.effect.each([undefined, false, true])(
2602
"goal dispatch stops the active turn only with native support: %s",
2603
(nativeGoals) =>
2655
- Effect.scoped(
2656
- Effect.gen(function* () {
2657
- const { steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2658
- "goal-steer",
2659
- nativeGoals,
2660
- );
2661
- yield* Effect.gen(function* () {
2662
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2663
- const threadId = yield* startFirstTurn;
2664
- yield* send("queued", "queued", "queue");
2665
- const sending = send("goal", "/goal all tests pass", "auto");
2666
- if (nativeGoals === false) {
2667
- yield* Effect.flip(sending);
2668
- } else yield* sending;
2669
- yield* worker.drain();
2670
-
2671
- assert.deepEqual(steered, []);
2672
- assert.deepEqual(yield* read(threadId), {
2673
- queue: ["queued"],
2674
- started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"],
2675
- stopRequested: nativeGoals !== false,
2676
- });
2677
- }).pipe(Effect.provide(layer));
2678
- }),
2679
- ),
2680
-);
2681
-
2682
-it.effect("starts a goal that names no model on the thread's model ahead of a queued pick", () =>
2683
- Effect.scoped(
2684
- Effect.gen(function* () {
2685
- const { started, layer, startFirstTurn, read } = yield* goalHarness("goal-ahead-of-pick");
2686
- yield* Effect.gen(function* () {
2687
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2688
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2689
- const threadId = yield* startFirstTurn;
2690
- for (const [id, text, modelSelection] of [
2691
- ["picked", "picked", composerSelection],
2692
- ["goal", "/goal all tests pass", undefined],
2693
- ] as const) {
2694
- yield* orchestrator.dispatch({
2695
- type: "message.dispatch",
2696
- commandId: CommandId.make(id),
2697
- threadId,
2698
- messageId: MessageId.make(`message:${id}`),
2699
- text,
2700
- attachments: [],
2701
- ...(modelSelection === undefined ? {} : { modelSelection }),
2702
- dispatchMode:
2703
- id === "picked" ? { type: "queue_after_active" } : { type: "start_immediately" },
2704
- ...(id === "picked" ? {} : { deliveryIntent: "auto" as const }),
2705
- createdBy: "user",
2706
- creationSource: "web",
2707
- });
2708
- }
2709
- yield* worker.drain();
2710
-
2711
- assert.deepEqual(yield* read(threadId), {
2712
- queue: ["picked"],
2713
- started: ["first", "/goal all tests pass"],
2714
- stopRequested: true,
2715
- });
2716
- assert.deepEqual(started[1]?.modelSelection, runSelection);
2717
- }).pipe(Effect.provide(layer));
2718
- }),
2719
- ),
2720
-);
2721
-
2722
-it.effect("restarts by stopping the running turn when the provider cannot interrupt-restart", () =>
2723
- Effect.scoped(
2604
Effect.gen(function* () {
2725
- const { started, steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2726
- "restart-without-interrupt-restart",
2605
+ const { steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2606
+ "goal-steer",
2607
+ nativeGoals,
2608
);
2609
yield* Effect.gen(function* () {
2729
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2610
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2611
const threadId = yield* startFirstTurn;
2612
yield* send("queued", "queued", "queue");
2733
- yield* orchestrator.dispatch({
2734
- type: "message.dispatch",
2735
- commandId: CommandId.make("restart"),
2736
- threadId,
2737
- messageId: MessageId.make("message:restart"),
2738
- text: "do this instead",
2739
- attachments: [],
2740
- modelSelection: runSelection,
2741
- dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId },
2742
- createdBy: "agent",
2743
- creationSource: "server",
2744
- });
2613
+ const sending = send("goal", "/goal all tests pass", "auto");
2614
+ if (nativeGoals === false) {
2615
+ yield* Effect.flip(sending);
2616
+ } else yield* sending;
2617
yield* worker.drain();
2618
2619
assert.deepEqual(steered, []);
2620
assert.deepEqual(yield* read(threadId), {
2621
queue: ["queued"],
2750
- started: ["first", "do this instead"],
2751
- stopRequested: true,
2622
+ started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"],
2623
+ stopRequested: nativeGoals !== false,
2624
});
2625
}).pipe(Effect.provide(layer));
2626
}),
2755
- ),
2627
);
2628
2758
-it.effect("starts a restart that stops the running turn ahead of an older held queue", () =>
2759
- Effect.scoped(
2760
- Effect.gen(function* () {
2761
- const { started, layer, startFirstTurn, send, read } =
2762
- yield* goalHarness("restart-past-held-queue");
2763
- yield* Effect.gen(function* () {
2764
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2765
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2766
- const threadId = yield* startFirstTurn;
2767
- yield* send("queued", "queued", "queue");
2768
- yield* orchestrator.dispatch({
2769
- type: "thread.stop",
2770
- commandId: CommandId.make("stop"),
2771
- threadId,
2772
- });
2773
- yield* worker.drain();
2774
- const secondRunning = yield* orchestrator.streamDomainEvents.pipe(
2775
- Stream.filter(
2776
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
2777
- ),
2778
- Stream.take(1),
2779
- Stream.runDrain,
2780
- Effect.forkScoped,
2781
- );
2782
- yield* orchestrator.dispatch({
2783
- type: "message.dispatch",
2784
- commandId: CommandId.make("second"),
2785
- threadId,
2786
- messageId: MessageId.make("message:second"),
2787
- text: "second",
2788
- attachments: [],
2789
- dispatchMode: { type: "start_immediately" },
2790
- createdBy: "agent",
2791
- creationSource: "mcp",
2792
- });
2793
- yield* worker.drain();
2794
- yield* Fiber.join(secondRunning);
2629
+it.effect("starts a goal that names no model on the thread's model ahead of a queued pick", () =>
2630
+ Effect.gen(function* () {
2631
+ const { started, layer, startFirstTurn, read } = yield* goalHarness("goal-ahead-of-pick");
2632
+ yield* Effect.gen(function* () {
2633
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2634
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2635
+ const threadId = yield* startFirstTurn;
2636
+ for (const [id, text, modelSelection] of [
2637
+ ["picked", "picked", composerSelection],
2638
+ ["goal", "/goal all tests pass", undefined],
2639
+ ] as const) {
2640
yield* orchestrator.dispatch({
2641
type: "message.dispatch",
2797
- commandId: CommandId.make("restart"),
2642
+ commandId: CommandId.make(id),
2643
threadId,
2799
- messageId: MessageId.make("message:restart"),
2800
- text: "do this instead",
2644
+ messageId: MessageId.make(`message:${id}`),
2645
+ text,
2646
attachments: [],
2802
- dispatchMode: { type: "restart_active", targetRunId: started[1]!.runId },
2803
- createdBy: "agent",
2804
- creationSource: "mcp",
2647
+ ...(modelSelection === undefined ? {} : { modelSelection }),
2648
+ dispatchMode:
2649
+ id === "picked" ? { type: "queue_after_active" } : { type: "start_immediately" },
2650
+ ...(id === "picked" ? {} : { deliveryIntent: "auto" as const }),
2651
+ createdBy: "user",
2652
+ creationSource: "web",
2653
});
2806
- yield* worker.drain();
2654
+ }
2655
+ yield* worker.drain();
2656
2808
- const { queue, started: startedTexts } = yield* read(threadId);
2809
- assert.deepEqual(
2810
- { queue, started: startedTexts },
2811
- { queue: ["queued"], started: ["first", "second", "do this instead"] },
2812
- );
2813
- }).pipe(Effect.provide(layer));
2814
- }),
2815
- ),
2657
+ assert.deepEqual(yield* read(threadId), {
2658
+ queue: ["picked"],
2659
+ started: ["first", "/goal all tests pass"],
2660
+ stopRequested: true,
2661
+ });
2662
+ assert.deepEqual(started[1]?.modelSelection, runSelection);
2663
+ }).pipe(Effect.provide(layer));
2664
+ }),
2665
);
2666
2818
-it.effect("reports a restart that stops the running turn as restarted", () =>
2819
- Effect.scoped(
2820
- Effect.gen(function* () {
2821
- const { started, layer, startFirstTurn } = yield* goalHarness("restart-send-delivery");
2822
- yield* Effect.gen(function* () {
2823
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2824
- const threadManagement = yield* ThreadManagementService.ThreadManagementService;
2825
- const threadId = yield* startFirstTurn;
2826
- const input = {
2827
- projectId: ProjectId.make("project:restart-send-delivery"),
2828
- commandId: CommandId.make("restart"),
2829
- threadId,
2830
- messageId: MessageId.make("message:restart"),
2831
- text: "do this instead",
2832
- attachments: [],
2833
- mode: "restart",
2834
- createdBy: "agent",
2835
- creationSource: "mcp",
2836
- } as const;
2837
- const sent = yield* threadManagement.sendToThread(input);
2838
- // Stop holds the replacement before it starts; a replay must still report the restart.
2839
- yield* orchestrator.dispatch({
2840
- type: "thread.stop",
2841
- commandId: CommandId.make("stop-after-restart"),
2842
- threadId,
2843
- });
2844
- const replayed = yield* threadManagement.sendToThread(input);
2667
+it.effect("restarts by stopping the running turn when the provider cannot interrupt-restart", () =>
2668
+ Effect.gen(function* () {
2669
+ const { started, steered, layer, startFirstTurn, send, read } = yield* goalHarness(
2670
+ "restart-without-interrupt-restart",
2671
+ );
2672
+ yield* Effect.gen(function* () {
2673
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2674
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2675
+ const threadId = yield* startFirstTurn;
2676
+ yield* send("queued", "queued", "queue");
2677
+ yield* orchestrator.dispatch({
2678
+ type: "message.dispatch",
2679
+ commandId: CommandId.make("restart"),
2680
+ threadId,
2681
+ messageId: MessageId.make("message:restart"),
2682
+ text: "do this instead",
2683
+ attachments: [],
2684
+ modelSelection: runSelection,
2685
+ dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId },
2686
+ createdBy: "agent",
2687
+ creationSource: "server",
2688
+ });
2689
+ yield* worker.drain();
2690
2846
- assert.equal(started.length, 1);
2847
- assert.deepEqual([sent.delivery, replayed.delivery], ["restarted", "restarted"]);
2848
- }).pipe(
2849
- Effect.provide(
2850
- ThreadManagementService.layer.pipe(
2851
- Layer.provideMerge(layer),
2852
- Layer.provide(ServerSettings.layerTest()),
2853
- Layer.provide(
2854
- CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
2855
- ),
2691
+ assert.deepEqual(steered, []);
2692
+ assert.deepEqual(yield* read(threadId), {
2693
+ queue: ["queued"],
2694
+ started: ["first", "do this instead"],
2695
+ stopRequested: true,
2696
+ });
2697
+ }).pipe(Effect.provide(layer));
2698
+ }),
2699
+);
2700
+
2701
+it.effect("starts a restart that stops the running turn ahead of an older held queue", () =>
2702
+ Effect.gen(function* () {
2703
+ const { started, layer, startFirstTurn, send, read } =
2704
+ yield* goalHarness("restart-past-held-queue");
2705
+ yield* Effect.gen(function* () {
2706
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2707
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2708
+ const threadId = yield* startFirstTurn;
2709
+ yield* send("queued", "queued", "queue");
2710
+ yield* orchestrator.dispatch({
2711
+ type: "thread.stop",
2712
+ commandId: CommandId.make("stop"),
2713
+ threadId,
2714
+ });
2715
+ yield* worker.drain();
2716
+ const secondRunning = yield* orchestrator.streamDomainEvents.pipe(
2717
+ Stream.filter(
2718
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
2719
+ ),
2720
+ Stream.take(1),
2721
+ Stream.runDrain,
2722
+ Effect.forkScoped,
2723
+ );
2724
+ yield* orchestrator.dispatch({
2725
+ type: "message.dispatch",
2726
+ commandId: CommandId.make("second"),
2727
+ threadId,
2728
+ messageId: MessageId.make("message:second"),
2729
+ text: "second",
2730
+ attachments: [],
2731
+ dispatchMode: { type: "start_immediately" },
2732
+ createdBy: "agent",
2733
+ creationSource: "mcp",
2734
+ });
2735
+ yield* worker.drain();
2736
+ yield* Fiber.join(secondRunning);
2737
+ yield* orchestrator.dispatch({
2738
+ type: "message.dispatch",
2739
+ commandId: CommandId.make("restart"),
2740
+ threadId,
2741
+ messageId: MessageId.make("message:restart"),
2742
+ text: "do this instead",
2743
+ attachments: [],
2744
+ dispatchMode: { type: "restart_active", targetRunId: started[1]!.runId },
2745
+ createdBy: "agent",
2746
+ creationSource: "mcp",
2747
+ });
2748
+ yield* worker.drain();
2749
+
2750
+ const { queue, started: startedTexts } = yield* read(threadId);
2751
+ assert.deepEqual(
2752
+ { queue, started: startedTexts },
2753
+ { queue: ["queued"], started: ["first", "second", "do this instead"] },
2754
+ );
2755
+ }).pipe(Effect.provide(layer));
2756
+ }),
2757
+);
2758
+
2759
+it.effect("reports a restart that stops the running turn as restarted", () =>
2760
+ Effect.gen(function* () {
2761
+ const { started, layer, startFirstTurn } = yield* goalHarness("restart-send-delivery");
2762
+ yield* Effect.gen(function* () {
2763
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2764
+ const threadManagement = yield* ThreadManagementService.ThreadManagementService;
2765
+ const threadId = yield* startFirstTurn;
2766
+ const input = {
2767
+ projectId: ProjectId.make("project:restart-send-delivery"),
2768
+ commandId: CommandId.make("restart"),
2769
+ threadId,
2770
+ messageId: MessageId.make("message:restart"),
2771
+ text: "do this instead",
2772
+ attachments: [],
2773
+ mode: "restart",
2774
+ createdBy: "agent",
2775
+ creationSource: "mcp",
2776
+ } as const;
2777
+ const sent = yield* threadManagement.sendToThread(input);
2778
+ // Stop holds the replacement before it starts; a replay must still report the restart.
2779
+ yield* orchestrator.dispatch({
2780
+ type: "thread.stop",
2781
+ commandId: CommandId.make("stop-after-restart"),
2782
+ threadId,
2783
+ });
2784
+ const replayed = yield* threadManagement.sendToThread(input);
2785
+
2786
+ assert.equal(started.length, 1);
2787
+ assert.deepEqual([sent.delivery, replayed.delivery], ["restarted", "restarted"]);
2788
+ }).pipe(
2789
+ Effect.provide(
2790
+ ThreadManagementService.layer.pipe(
2791
+ Layer.provideMerge(layer),
2792
+ Layer.provide(ServerSettings.layerTest()),
2793
+ Layer.provide(
2794
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
2795
),
2796
),
2858
- );
2859
- }),
2860
- ),
2797
+ ),
2798
+ );
2799
+ }),
2800
);
2801
2802
it.effect("queues a goal clear without stopping work when no goal drives it", () =>
2864
- Effect.scoped(
2865
- Effect.gen(function* () {
2866
- const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-clear");
2867
- yield* Effect.gen(function* () {
2868
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2869
- const threadId = yield* startFirstTurn;
2870
- yield* send("queued", "queued", "queue");
2871
- yield* send("clear", "/goal clear", "auto");
2872
- yield* worker.drain();
2803
+ Effect.gen(function* () {
2804
+ const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-clear");
2805
+ yield* Effect.gen(function* () {
2806
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2807
+ const threadId = yield* startFirstTurn;
2808
+ yield* send("queued", "queued", "queue");
2809
+ yield* send("clear", "/goal clear", "auto");
2810
+ yield* worker.drain();
2811
2874
- assert.deepEqual(steered, []);
2875
- assert.deepEqual(yield* read(threadId), {
2876
- queue: ["queued", "/goal clear"],
2877
- started: ["first"],
2878
- stopRequested: false,
2879
- });
2880
- }).pipe(Effect.provide(layer));
2881
- }),
2882
- ),
2812
+ assert.deepEqual(steered, []);
2813
+ assert.deepEqual(yield* read(threadId), {
2814
+ queue: ["queued", "/goal clear"],
2815
+ started: ["first"],
2816
+ stopRequested: false,
2817
+ });
2818
+ }).pipe(Effect.provide(layer));
2819
+ }),
2820
);
2821
2822
it.effect("promotes a queued goal by stopping the running turn", () =>
2886
- Effect.scoped(
2887
- Effect.gen(function* () {
2888
- const { started, steered, layer, startFirstTurn, send, read } =
2889
- yield* goalHarness("goal-promote");
2890
- yield* Effect.gen(function* () {
2891
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2892
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2893
- const threadId = yield* startFirstTurn;
2894
- yield* send("queued", "queued", "queue");
2895
- yield* send("goal", "/goal ship it", "queue");
2896
- const goalRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2897
- (run) => run.userMessageId === MessageId.make("message:goal"),
2898
- )!;
2899
- yield* orchestrator.dispatch({
2900
- type: "queued-message.promote-to-steer",
2901
- commandId: CommandId.make("promote"),
2902
- threadId,
2903
- queuedRunId: goalRun.id,
2904
- targetRunId: started[0]!.runId,
2905
- });
2906
- yield* worker.drain();
2823
+ Effect.gen(function* () {
2824
+ const { started, steered, layer, startFirstTurn, send, read } =
2825
+ yield* goalHarness("goal-promote");
2826
+ yield* Effect.gen(function* () {
2827
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2828
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2829
+ const threadId = yield* startFirstTurn;
2830
+ yield* send("queued", "queued", "queue");
2831
+ yield* send("goal", "/goal ship it", "queue");
2832
+ const goalRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2833
+ (run) => run.userMessageId === MessageId.make("message:goal"),
2834
+ )!;
2835
+ yield* orchestrator.dispatch({
2836
+ type: "queued-message.promote-to-steer",
2837
+ commandId: CommandId.make("promote"),
2838
+ threadId,
2839
+ queuedRunId: goalRun.id,
2840
+ targetRunId: started[0]!.runId,
2841
+ });
2842
+ yield* worker.drain();
2843
2908
- assert.deepEqual(steered, []);
2909
- assert.deepEqual(yield* read(threadId), {
2910
- queue: ["queued"],
2911
- started: ["first", "/goal ship it"],
2912
- stopRequested: true,
2913
- });
2914
- }).pipe(Effect.provide(layer));
2915
- }),
2916
- ),
2844
+ assert.deepEqual(steered, []);
2845
+ assert.deepEqual(yield* read(threadId), {
2846
+ queue: ["queued"],
2847
+ started: ["first", "/goal ship it"],
2848
+ stopRequested: true,
2849
+ });
2850
+ }).pipe(Effect.provide(layer));
2851
+ }),
2852
);
2853
2854
// A fresh message skips compaction as its own turn, which steering a running turn would not.
2855
it.effect.each(["next", "/goal ship it", "fresh next"])(
2856
"promoting %s into a compaction stops it and sends it next",
2857
(promoted) =>
2923
- Effect.scoped(
2924
- Effect.gen(function* () {
2925
- const { events, layer, send, read, started, steered, startFirstTurn } = yield* goalHarness(
2926
- `compaction-promote-${promoted.length}`,
2927
- );
2928
- yield* Effect.gen(function* () {
2929
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2930
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2931
- const threadId = yield* startFirstTurn;
2932
- yield* send("compact", "/compact", "queue");
2933
- yield* send("queued", "queued", "queue");
2934
- yield* send("next", promoted, "queue", promoted.startsWith("fresh"));
2935
- const settled = yield* orchestrator.streamDomainEvents.pipe(
2936
- Stream.filter(
2937
- (event) =>
2938
- event.type === "run.updated" &&
2939
- event.payload.id === started[0]!.runId &&
2940
- event.payload.status === "waiting",
2941
- ),
2942
- Stream.take(1),
2943
- Stream.runDrain,
2944
- Effect.forkScoped,
2945
- );
2946
- const compacting = yield* orchestrator.streamDomainEvents.pipe(
2947
- Stream.filter(
2948
- (event) =>
2949
- event.type === "provider-turn.updated" &&
2950
- event.payload.status === "running" &&
2951
- event.payload.runAttemptId !== started[0]!.attemptId,
2952
- ),
2953
- Stream.take(1),
2954
- Stream.runDrain,
2955
- Effect.forkScoped,
2956
- );
2957
- const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2958
- yield* Queue.offer(events, {
2959
- type: "provider_turn.updated",
2960
- driver,
2961
- providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
2962
- });
2963
- yield* Queue.offer(events, {
2964
- type: "turn.terminal",
2965
- driver,
2966
- providerThreadId: turn.providerThreadId,
2967
- providerTurnId: turn.id,
2968
- runOrdinal: started[0]!.runOrdinal,
2969
- status: "completed",
2970
- failure: null,
2971
- threadDisposition: "reusable",
2972
- });
2973
- yield* Fiber.join(settled);
2974
- yield* worker.drain();
2975
- yield* orchestrator.resumeQueuedRuns;
2976
- yield* worker.drain();
2977
- yield* Fiber.join(compacting);
2978
- const compactRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2979
- (run) => run.userMessageId === MessageId.make("message:compact"),
2980
- )!;
2981
- const nextRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2982
- (run) => run.userMessageId === MessageId.make("message:next"),
2983
- )!;
2984
- yield* orchestrator.dispatch({
2985
- type: "queued-message.promote-to-steer",
2986
- commandId: CommandId.make("promote"),
2987
- threadId,
2988
- queuedRunId: nextRun.id,
2989
- targetRunId: compactRun.id,
2990
- });
2991
- yield* worker.drain();
2992
-
2993
- const projection = yield* orchestrator.getThreadProjection(threadId);
2994
- assert.deepEqual(steered, []);
2995
- assert.isTrue(
2996
- projection.turnItems.some(
2997
- (item) => item.type === "run_interrupt_request" && item.runId === compactRun.id,
2998
- ),
2999
- );
3000
- assert.deepEqual((yield* read(threadId)).queue, ["queued"]);
3001
- assert.deepEqual(
3002
- started.map((turn) => turn.message.text),
3003
- ["first", "/compact", promoted],
3004
- );
3005
- }).pipe(Effect.provide(layer));
3006
- }),
3007
- ),
3008
-);
3009
-
3010
-it.effect("stops a turn that is still starting when a goal is sent into it", () =>
3011
- Effect.scoped(
2858
Effect.gen(function* () {
3013
- const { cwd, layer, send, started } = yield* goalHarness("goal-during-start");
2859
+ const { events, layer, send, read, started, steered, startFirstTurn } = yield* goalHarness(
2860
+ `compaction-promote-${promoted.length}`,
2861
+ );
2862
yield* Effect.gen(function* () {
2863
const orchestrator = yield* Orchestrator.OrchestratorV2;
2864
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3017
- const threadId = ThreadId.make("thread:goal-during-start");
3018
- yield* orchestrator.dispatch({
3019
- type: "thread.create",
3020
- commandId: CommandId.make("create"),
3021
- threadId,
3022
- projectId: ProjectId.make("project:goal-during-start"),
3023
- title: "Goal during start",
3024
- modelSelection: runSelection,
3025
- runtimeMode: "full-access",
3026
- interactionMode: "default",
3027
- branch: null,
3028
- worktreePath: cwd,
3029
- createdBy: "user",
3030
- creationSource: "web",
3031
- });
3032
- // The stopped run's end starts the queue, which then needs one more drain.
3033
- const goalStarting = yield* orchestrator.streamDomainEvents.pipe(
2865
+ const threadId = yield* startFirstTurn;
2866
+ yield* send("compact", "/compact", "queue");
2867
+ yield* send("queued", "queued", "queue");
2868
+ yield* send("next", promoted, "queue", promoted.startsWith("fresh"));
2869
+ const settled = yield* orchestrator.streamDomainEvents.pipe(
2870
Stream.filter(
3035
- (event) => event.type === "run.updated" && event.payload.status === "starting",
2871
+ (event) =>
2872
+ event.type === "run.updated" &&
2873
+ event.payload.id === started[0]!.runId &&
2874
+ event.payload.status === "waiting",
2875
),
2876
Stream.take(1),
2877
Stream.runDrain,
3039
- Effect.forkScoped({ startImmediately: true }),
3040
- );
3041
- yield* send("first", "first", "auto");
3042
- yield* send("goal", "/goal all tests pass", "auto");
3043
- yield* worker.drain();
3044
- yield* Fiber.join(goalStarting);
3045
- yield* worker.drain();
3046
-
3047
- const projection = yield* orchestrator.getThreadProjection(threadId);
3048
- const statusOf = (text: string) =>
3049
- projection.runs.find(
3050
- (run) =>
3051
- projection.messages.find((message) => message.id === run.userMessageId)?.text ===
3052
- text,
3053
- )?.status;
3054
- assert.equal(statusOf("first"), "interrupted");
3055
- assert.deepEqual(
3056
- started.map((turn) => turn.message.text),
3057
- ["/goal all tests pass"],
2878
+ Effect.forkScoped,
2879
);
3059
- }).pipe(Effect.provide(layer));
3060
- }),
3061
- ),
3062
-);
3063
-
3064
-it.effect("stops the running turn when a goal clear ends the goal driving it", () =>
3065
- Effect.scoped(
3066
- Effect.gen(function* () {
3067
- const { events, layer, startFirstTurn, send, read, steered } =
3068
- yield* goalHarness("goal-clear-active");
3069
- yield* Effect.gen(function* () {
3070
- const orchestrator = yield* Orchestrator.OrchestratorV2;
3071
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3072
- const threadId = yield* startFirstTurn;
3073
- const providerThread = (yield* orchestrator.getThreadProjection(threadId))
3074
- .providerThreads[0]!;
3075
- const goalSeen = yield* orchestrator.streamDomainEvents.pipe(
2880
+ const compacting = yield* orchestrator.streamDomainEvents.pipe(
2881
Stream.filter(
2882
(event) =>
3078
- event.type === "provider-thread.updated" && event.payload.goal?.status === "active",
2883
+ event.type === "provider-turn.updated" &&
2884
+ event.payload.status === "running" &&
2885
+ event.payload.runAttemptId !== started[0]!.attemptId,
2886
),
2887
Stream.take(1),
2888
Stream.runDrain,
3082
- Effect.forkScoped({ startImmediately: true }),
3083
- );
3084
- yield* Queue.offer(events, {
3085
- type: "provider_thread.updated",
3086
- driver,
3087
- providerThread: {
3088
- ...providerThread,
3089
- goal: { objective: "all tests pass", status: "active" },
3090
- },
3091
- });
3092
- yield* Fiber.join(goalSeen);
3093
- yield* send("clear", "/goal clear", "auto");
3094
- yield* worker.drain();
3095
-
3096
- assert.deepEqual(steered, []);
3097
- assert.deepEqual(yield* read(threadId), {
3098
- queue: [],
3099
- started: ["first", "/goal clear"],
3100
- stopRequested: true,
3101
- });
3102
- }).pipe(Effect.provide(layer));
3103
- }),
3104
- ),
3105
-);
3106
-
3107
-it.effect("a side chat that opens with /goal gets its context on the next question", () =>
3108
- Effect.scoped(
3109
- Effect.gen(function* () {
3110
- const { events, layer, started, startFirstTurn } = yield* goalHarness("side-chat-goal");
3111
- yield* Effect.gen(function* () {
3112
- const orchestrator = yield* Orchestrator.OrchestratorV2;
3113
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3114
- const parentId = yield* startFirstTurn;
3115
- const sideChatId = ThreadId.make("thread:side-chat-goal-child");
3116
- yield* orchestrator.dispatch({
3117
- type: "thread.fork",
3118
- commandId: CommandId.make("side-chat"),
3119
- sourceThreadId: parentId,
3120
- targetThreadId: sideChatId,
3121
- sourcePoint: { type: "latest_stable" },
3122
- sideChat: true,
3123
- createdBy: "user",
3124
- creationSource: "web",
3125
- });
3126
- const ask = (id: string, text: string) =>
3127
- orchestrator.dispatch({
3128
- type: "message.dispatch",
3129
- commandId: CommandId.make(id),
3130
- threadId: sideChatId,
3131
- messageId: MessageId.make(`message:${id}`),
3132
- text,
3133
- attachments: [],
3134
- modelSelection: runSelection,
3135
- dispatchMode: { type: "start_immediately" },
3136
- createdBy: "user",
3137
- creationSource: "web",
3138
- });
3139
- const sideChatEvent = (matches: (event: OrchestrationV2DomainEvent) => boolean) =>
3140
- orchestrator.streamDomainEvents.pipe(
3141
- Stream.filter((event) => event.threadId === sideChatId && matches(event)),
3142
- Stream.take(1),
3143
- Stream.runDrain,
3144
- Effect.forkScoped({ startImmediately: true }),
3145
- );
3146
- const running = yield* sideChatEvent(
3147
- (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
3148
- );
3149
- const settled = yield* sideChatEvent(
3150
- (event) => event.type === "run.updated" && event.payload.status === "waiting",
2889
+ Effect.forkScoped,
2890
);
3152
- yield* ask("goal", "/goal clear");
3153
- yield* worker.drain();
3154
- yield* Fiber.join(running);
3155
- const turn = (yield* orchestrator.getThreadProjection(sideChatId)).providerTurns[0]!;
2891
+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
2892
yield* Queue.offer(events, {
2893
type: "provider_turn.updated",
2894
driver,
@@ -3163,22 +2899,212 @@ it.effect("a side chat that opens with /goal gets its context on the next questi
2899
driver,
2900
providerThreadId: turn.providerThreadId,
2901
providerTurnId: turn.id,
3166
- runOrdinal: started[1]!.runOrdinal,
2902
+ runOrdinal: started[0]!.runOrdinal,
2903
status: "completed",
2904
failure: null,
2905
threadDisposition: "reusable",
2906
});
2907
yield* Fiber.join(settled);
2908
yield* worker.drain();
3173
- yield* ask("question", "What is the main thread doing?");
2909
+ yield* orchestrator.resumeQueuedRuns;
2910
+ yield* worker.drain();
2911
+ yield* Fiber.join(compacting);
2912
+ const compactRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2913
+ (run) => run.userMessageId === MessageId.make("message:compact"),
2914
+ )!;
2915
+ const nextRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
2916
+ (run) => run.userMessageId === MessageId.make("message:next"),
2917
+ )!;
2918
+ yield* orchestrator.dispatch({
2919
+ type: "queued-message.promote-to-steer",
2920
+ commandId: CommandId.make("promote"),
2921
+ threadId,
2922
+ queuedRunId: nextRun.id,
2923
+ targetRunId: compactRun.id,
2924
+ });
2925
yield* worker.drain();
2926
3176
- const [first, goal, question] = started.map((turn) => turn.message.text);
3177
- assert.deepEqual([first, goal], ["first", "/goal clear"]);
3178
- assert.include(question, "You are in a side chat beside the main thread.");
3179
- assert.include(question, "- User: first");
3180
- assert.isTrue(question?.endsWith("What is the main thread doing?"));
2927
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2928
+ assert.deepEqual(steered, []);
2929
+ assert.isTrue(
2930
+ projection.turnItems.some(
2931
+ (item) => item.type === "run_interrupt_request" && item.runId === compactRun.id,
2932
+ ),
2933
+ );
2934
+ assert.deepEqual((yield* read(threadId)).queue, ["queued"]);
2935
+ assert.deepEqual(
2936
+ started.map((turn) => turn.message.text),
2937
+ ["first", "/compact", promoted],
2938
+ );
2939
}).pipe(Effect.provide(layer));
2940
}),
3183
- ),
2941
+);
2942
+
2943
+it.effect("stops a turn that is still starting when a goal is sent into it", () =>
2944
+ Effect.gen(function* () {
2945
+ const { cwd, layer, send, started } = yield* goalHarness("goal-during-start");
2946
+ yield* Effect.gen(function* () {
2947
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2948
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2949
+ const threadId = ThreadId.make("thread:goal-during-start");
2950
+ yield* orchestrator.dispatch({
2951
+ type: "thread.create",
2952
+ commandId: CommandId.make("create"),
2953
+ threadId,
2954
+ projectId: ProjectId.make("project:goal-during-start"),
2955
+ title: "Goal during start",
2956
+ modelSelection: runSelection,
2957
+ runtimeMode: "full-access",
2958
+ interactionMode: "default",
2959
+ branch: null,
2960
+ worktreePath: cwd,
2961
+ createdBy: "user",
2962
+ creationSource: "web",
2963
+ });
2964
+ // The stopped run's end starts the queue, which then needs one more drain.
2965
+ const goalStarting = yield* orchestrator.streamDomainEvents.pipe(
2966
+ Stream.filter(
2967
+ (event) => event.type === "run.updated" && event.payload.status === "starting",
2968
+ ),
2969
+ Stream.take(1),
2970
+ Stream.runDrain,
2971
+ Effect.forkScoped({ startImmediately: true }),
2972
+ );
2973
+ yield* send("first", "first", "auto");
2974
+ yield* send("goal", "/goal all tests pass", "auto");
2975
+ yield* worker.drain();
2976
+ yield* Fiber.join(goalStarting);
2977
+ yield* worker.drain();
2978
+
2979
+ const projection = yield* orchestrator.getThreadProjection(threadId);
2980
+ const statusOf = (text: string) =>
2981
+ projection.runs.find(
2982
+ (run) =>
2983
+ projection.messages.find((message) => message.id === run.userMessageId)?.text === text,
2984
+ )?.status;
2985
+ assert.equal(statusOf("first"), "interrupted");
2986
+ assert.deepEqual(
2987
+ started.map((turn) => turn.message.text),
2988
+ ["/goal all tests pass"],
2989
+ );
2990
+ }).pipe(Effect.provide(layer));
2991
+ }),
2992
+);
2993
+
2994
+it.effect("stops the running turn when a goal clear ends the goal driving it", () =>
2995
+ Effect.gen(function* () {
2996
+ const { events, layer, startFirstTurn, send, read, steered } =
2997
+ yield* goalHarness("goal-clear-active");
2998
+ yield* Effect.gen(function* () {
2999
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
3000
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3001
+ const threadId = yield* startFirstTurn;
3002
+ const providerThread = (yield* orchestrator.getThreadProjection(threadId))
3003
+ .providerThreads[0]!;
3004
+ const goalSeen = yield* orchestrator.streamDomainEvents.pipe(
3005
+ Stream.filter(
3006
+ (event) =>
3007
+ event.type === "provider-thread.updated" && event.payload.goal?.status === "active",
3008
+ ),
3009
+ Stream.take(1),
3010
+ Stream.runDrain,
3011
+ Effect.forkScoped({ startImmediately: true }),
3012
+ );
3013
+ yield* Queue.offer(events, {
3014
+ type: "provider_thread.updated",
3015
+ driver,
3016
+ providerThread: {
3017
+ ...providerThread,
3018
+ goal: { objective: "all tests pass", status: "active" },
3019
+ },
3020
+ });
3021
+ yield* Fiber.join(goalSeen);
3022
+ yield* send("clear", "/goal clear", "auto");
3023
+ yield* worker.drain();
3024
+
3025
+ assert.deepEqual(steered, []);
3026
+ assert.deepEqual(yield* read(threadId), {
3027
+ queue: [],
3028
+ started: ["first", "/goal clear"],
3029
+ stopRequested: true,
3030
+ });
3031
+ }).pipe(Effect.provide(layer));
3032
+ }),
3033
+);
3034
+
3035
+it.effect("a side chat that opens with /goal gets its context on the next question", () =>
3036
+ Effect.gen(function* () {
3037
+ const { events, layer, started, startFirstTurn } = yield* goalHarness("side-chat-goal");
3038
+ yield* Effect.gen(function* () {
3039
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
3040
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3041
+ const parentId = yield* startFirstTurn;
3042
+ const sideChatId = ThreadId.make("thread:side-chat-goal-child");
3043
+ yield* orchestrator.dispatch({
3044
+ type: "thread.fork",
3045
+ commandId: CommandId.make("side-chat"),
3046
+ sourceThreadId: parentId,
3047
+ targetThreadId: sideChatId,
3048
+ sourcePoint: { type: "latest_stable" },
3049
+ sideChat: true,
3050
+ createdBy: "user",
3051
+ creationSource: "web",
3052
+ });
3053
+ const ask = (id: string, text: string) =>
3054
+ orchestrator.dispatch({
3055
+ type: "message.dispatch",
3056
+ commandId: CommandId.make(id),
3057
+ threadId: sideChatId,
3058
+ messageId: MessageId.make(`message:${id}`),
3059
+ text,
3060
+ attachments: [],
3061
+ modelSelection: runSelection,
3062
+ dispatchMode: { type: "start_immediately" },
3063
+ createdBy: "user",
3064
+ creationSource: "web",
3065
+ });
3066
+ const sideChatEvent = (matches: (event: OrchestrationV2DomainEvent) => boolean) =>
3067
+ orchestrator.streamDomainEvents.pipe(
3068
+ Stream.filter((event) => event.threadId === sideChatId && matches(event)),
3069
+ Stream.take(1),
3070
+ Stream.runDrain,
3071
+ Effect.forkScoped({ startImmediately: true }),
3072
+ );
3073
+ const running = yield* sideChatEvent(
3074
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
3075
+ );
3076
+ const settled = yield* sideChatEvent(
3077
+ (event) => event.type === "run.updated" && event.payload.status === "waiting",
3078
+ );
3079
+ yield* ask("goal", "/goal clear");
3080
+ yield* worker.drain();
3081
+ yield* Fiber.join(running);
3082
+ const turn = (yield* orchestrator.getThreadProjection(sideChatId)).providerTurns[0]!;
3083
+ yield* Queue.offer(events, {
3084
+ type: "provider_turn.updated",
3085
+ driver,
3086
+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
3087
+ });
3088
+ yield* Queue.offer(events, {
3089
+ type: "turn.terminal",
3090
+ driver,
3091
+ providerThreadId: turn.providerThreadId,
3092
+ providerTurnId: turn.id,
3093
+ runOrdinal: started[1]!.runOrdinal,
3094
+ status: "completed",
3095
+ failure: null,
3096
+ threadDisposition: "reusable",
3097
+ });
3098
+ yield* Fiber.join(settled);
3099
+ yield* worker.drain();
3100
+ yield* ask("question", "What is the main thread doing?");
3101
+ yield* worker.drain();
3102
+
3103
+ const [first, goal, question] = started.map((turn) => turn.message.text);
3104
+ assert.deepEqual([first, goal], ["first", "/goal clear"]);
3105
+ assert.include(question, "You are in a side chat beside the main thread.");
3106
+ assert.include(question, "- User: first");
3107
+ assert.isTrue(question?.endsWith("What is the main thread doing?"));
3108
+ }).pipe(Effect.provide(layer));
3109
+ }),
3110
);
apps/server/src/orchestration-v2/ThreadLiveEventCoalescer.test.ts
+124
-142
@@ -159,57 +159,51 @@ describe("ThreadLiveEventCoalescer", () => {
159
it.effect.each(["items", "bytes"] as const)(
160
"replaces superseded tool output before charging the %s budget",
161
(limit) =>
162
- Effect.scoped(
163
- Effect.gen(function* () {
164
- const updates = Array.from({ length: 1_100 }, (_, index) => makeToolActivity(index + 1));
165
- const latest = updates.at(-1)!;
166
- const coalescer = yield* makeThreadLiveEventCoalescer(
167
- limit === "items"
168
- ? { maxItems: 1 }
169
- : { maxSerializedBytes: Buffer.byteLength(encodeEvent(latest)) },
170
- );
171
- yield* coalescer.offerAll(updates);
172
- expect(yield* coalescer.usage).toEqual({
173
- retainedItems: 1,
174
- retainedSerializedBytes: Buffer.byteLength(encodeEvent(latest)),
175
- });
176
- yield* coalescer.end;
177
- expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([latest]);
178
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
179
- }),
180
- ),
181
- );
182
-
183
- it.effect("handles a tool output burst larger than the default 8 MiB buffer", () =>
184
- Effect.scoped(
162
Effect.gen(function* () {
186
- const coalescer = yield* makeThreadLiveEventCoalescer();
187
- const updates = Array.from({ length: 150 }, (_, index) =>
188
- makeToolActivity(index + 1, { output: "x".repeat(64 * 1024) }),
163
+ const updates = Array.from({ length: 1_100 }, (_, index) => makeToolActivity(index + 1));
164
+ const latest = updates.at(-1)!;
165
+ const coalescer = yield* makeThreadLiveEventCoalescer(
166
+ limit === "items"
167
+ ? { maxItems: 1 }
168
+ : { maxSerializedBytes: Buffer.byteLength(encodeEvent(latest)) },
169
);
170
yield* coalescer.offerAll(updates);
171
+ expect(yield* coalescer.usage).toEqual({
172
+ retainedItems: 1,
173
+ retainedSerializedBytes: Buffer.byteLength(encodeEvent(latest)),
174
+ });
175
yield* coalescer.end;
192
- expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([updates.at(-1)]);
176
+ expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([latest]);
177
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
178
}),
194
- ),
179
+ );
180
+
181
+ it.effect("handles a tool output burst larger than the default 8 MiB buffer", () =>
182
+ Effect.gen(function* () {
183
+ const coalescer = yield* makeThreadLiveEventCoalescer();
184
+ const updates = Array.from({ length: 150 }, (_, index) =>
185
+ makeToolActivity(index + 1, { output: "x".repeat(64 * 1024) }),
186
+ );
187
+ yield* coalescer.offerAll(updates);
188
+ yield* coalescer.end;
189
+ expect(yield* coalescer.stream.pipe(Stream.runCollect)).toEqual([updates.at(-1)]);
190
+ }),
191
);
192
193
it.effect("still fails when a single replacement exceeds the byte budget", () =>
198
- Effect.scoped(
199
- Effect.gen(function* () {
200
- const first = makeToolActivity(1);
201
- const coalescer = yield* makeThreadLiveEventCoalescer({
202
- maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
203
- });
204
- yield* coalescer.offer(first);
205
- const overflow = yield* coalescer
206
- .offer(makeToolActivity(2, { output: "x".repeat(2_000) }))
207
- .pipe(Effect.result);
208
- expect(overflow._tag).toBe("Failure");
209
- yield* coalescer.closed;
210
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
211
- }),
212
- ),
194
+ Effect.gen(function* () {
195
+ const first = makeToolActivity(1);
196
+ const coalescer = yield* makeThreadLiveEventCoalescer({
197
+ maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
198
+ });
199
+ yield* coalescer.offer(first);
200
+ const overflow = yield* coalescer
201
+ .offer(makeToolActivity(2, { output: "x".repeat(2_000) }))
202
+ .pipe(Effect.result);
203
+ expect(overflow._tag).toBe("Failure");
204
+ yield* coalescer.closed;
205
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
206
+ }),
207
);
208
209
it("preserves tool-call identity switches as insertion-order boundaries", () => {
@@ -413,119 +407,107 @@ describe("ThreadLiveEventCoalescer", () => {
407
);
408
409
it.effect("flushes text at synchronization and completion boundaries", () =>
416
- Effect.scoped(
417
- Effect.gen(function* () {
418
- const coalescer = yield* makeThreadLiveEventCoalescer();
419
- const events = [
420
- makeStreamingMessage(1),
421
- makeTextItem(2, { type: "reasoning" }),
422
- makeStreamingMessage(3),
423
- makeTextItem(4, { type: "reasoning" }),
424
- { kind: "synchronized" } as const,
425
- makeStreamingMessage(5),
426
- makeTextItem(6, { type: "reasoning" }),
427
- makeStreamingMessage(7, { streaming: false, text: "Final answer" }),
428
- makeTextItem(8, {
429
- type: "reasoning",
430
- streaming: false,
431
- status: "completed",
432
- text: "Final answer",
433
- }),
434
- makeStreamingMessage(9),
435
- makeTextItem(10, { type: "reasoning" }),
436
- ];
437
- yield* coalescer.offerAll(events);
438
- yield* coalescer.end;
439
- expect(yield* Stream.runCollect(coalescer.stream)).toEqual(events.slice(2));
440
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
441
- }),
442
- ),
410
+ Effect.gen(function* () {
411
+ const coalescer = yield* makeThreadLiveEventCoalescer();
412
+ const events = [
413
+ makeStreamingMessage(1),
414
+ makeTextItem(2, { type: "reasoning" }),
415
+ makeStreamingMessage(3),
416
+ makeTextItem(4, { type: "reasoning" }),
417
+ { kind: "synchronized" } as const,
418
+ makeStreamingMessage(5),
419
+ makeTextItem(6, { type: "reasoning" }),
420
+ makeStreamingMessage(7, { streaming: false, text: "Final answer" }),
421
+ makeTextItem(8, {
422
+ type: "reasoning",
423
+ streaming: false,
424
+ status: "completed",
425
+ text: "Final answer",
426
+ }),
427
+ makeStreamingMessage(9),
428
+ makeTextItem(10, { type: "reasoning" }),
429
+ ];
430
+ yield* coalescer.offerAll(events);
431
+ yield* coalescer.end;
432
+ expect(yield* Stream.runCollect(coalescer.stream)).toEqual(events.slice(2));
433
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
434
+ }),
435
);
436
437
it.effect(
438
"flushes growing text on the fixed window and charges only unacknowledged survivors",
439
() =>
448
- Effect.scoped(
449
- Effect.gen(function* () {
450
- const coalescer = yield* makeThreadLiveEventCoalescer();
451
- const first = [makeStreamingMessage(1, { text: "é" }), makeTextItem(2, { text: "é" })];
452
- const latest = [makeStreamingMessage(3, { text: "éé" }), makeTextItem(4, { text: "éé" })];
453
- const serializedBytes = (events: ReadonlyArray<ThreadEvent>) =>
454
- events.reduce((sum, event) => sum + Buffer.byteLength(encodeEvent(event)), 0);
455
- yield* coalescer.offerAll(first);
456
- yield* TestClock.adjust("40 millis");
457
- yield* coalescer.offerAll(latest);
458
- expect(yield* coalescer.usage).toEqual({
459
- retainedItems: 2,
460
- retainedSerializedBytes: serializedBytes(latest),
461
- });
462
- yield* TestClock.adjust("10 millis");
463
- const expectedUsage = {
464
- retainedItems: 2,
465
- retainedSerializedBytes: serializedBytes(latest),
466
- };
467
- expect(yield* coalescer.usage).toEqual(expectedUsage);
468
- const pull = yield* Stream.toPull(coalescer.stream);
469
- expect(yield* pull).toEqual(latest);
470
- expect(yield* coalescer.usage).toEqual(expectedUsage);
471
-
472
- const next = [makeStreamingMessage(5), makeTextItem(6)];
473
- yield* coalescer.offerAll(next);
474
- yield* TestClock.adjust("50 millis");
475
- expect(yield* pull).toEqual(next);
476
- yield* coalescer.end;
477
- yield* pull.pipe(Effect.result);
478
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
479
- }),
480
- ),
481
- );
482
-
483
- it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
484
- Effect.scoped(
440
Effect.gen(function* () {
441
const coalescer = yield* makeThreadLiveEventCoalescer();
487
- yield* Effect.scoped(coalescer.offer(makeToolActivity(1)));
442
+ const first = [makeStreamingMessage(1, { text: "é" }), makeTextItem(2, { text: "é" })];
443
+ const latest = [makeStreamingMessage(3, { text: "éé" }), makeTextItem(4, { text: "éé" })];
444
+ const serializedBytes = (events: ReadonlyArray<ThreadEvent>) =>
445
+ events.reduce((sum, event) => sum + Buffer.byteLength(encodeEvent(event)), 0);
446
+ yield* coalescer.offerAll(first);
447
+ yield* TestClock.adjust("40 millis");
448
+ yield* coalescer.offerAll(latest);
449
+ expect(yield* coalescer.usage).toEqual({
450
+ retainedItems: 2,
451
+ retainedSerializedBytes: serializedBytes(latest),
452
+ });
453
+ yield* TestClock.adjust("10 millis");
454
+ const expectedUsage = {
455
+ retainedItems: 2,
456
+ retainedSerializedBytes: serializedBytes(latest),
457
+ };
458
+ expect(yield* coalescer.usage).toEqual(expectedUsage);
459
+ const pull = yield* Stream.toPull(coalescer.stream);
460
+ expect(yield* pull).toEqual(latest);
461
+ expect(yield* coalescer.usage).toEqual(expectedUsage);
462
+
463
+ const next = [makeStreamingMessage(5), makeTextItem(6)];
464
+ yield* coalescer.offerAll(next);
465
yield* TestClock.adjust("50 millis");
489
- const items = yield* coalescer.stream.pipe(Stream.take(1), Stream.runCollect);
490
- expect(items.map((item) => (item.kind === "event" ? item.sequence : item.kind))).toEqual([
491
- 1,
492
- ]);
466
+ expect(yield* pull).toEqual(next);
467
+ yield* coalescer.end;
468
+ yield* pull.pipe(Effect.result);
469
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
470
}),
494
- ),
471
+ );
472
+
473
+ it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
474
+ Effect.gen(function* () {
475
+ const coalescer = yield* makeThreadLiveEventCoalescer();
476
+ yield* Effect.scoped(coalescer.offer(makeToolActivity(1)));
477
+ yield* TestClock.adjust("50 millis");
478
+ const items = yield* coalescer.stream.pipe(Stream.take(1), Stream.runCollect);
479
+ expect(items.map((item) => (item.kind === "event" ? item.sequence : item.kind))).toEqual([1]);
480
+ }),
481
);
482
483
it.effect("keeps an unacknowledged batch charged and clears later events on overflow", () =>
498
- Effect.scoped(
499
- Effect.gen(function* () {
500
- const coalescer = yield* makeThreadLiveEventCoalescer({ maxItems: 3 });
501
- const first = makeMessage(1, "é".repeat(1_024));
502
- yield* coalescer.offer(first);
484
+ Effect.gen(function* () {
485
+ const coalescer = yield* makeThreadLiveEventCoalescer({ maxItems: 3 });
486
+ const first = makeMessage(1, "é".repeat(1_024));
487
+ yield* coalescer.offer(first);
488
504
- yield* Effect.scoped(
505
- Effect.gen(function* () {
506
- const pull = yield* Stream.toPull(coalescer.stream);
507
- const batch = yield* pull;
508
- expect(batch.map((item) => (item.kind === "event" ? item.sequence : null))).toEqual([
509
- 1,
510
- ]);
511
- yield* coalescer.offer(makeMessage(2));
512
- yield* coalescer.offer(makeToolActivity(3));
513
- expect((yield* coalescer.usage).retainedItems).toBe(3);
489
+ yield* Effect.scoped(
490
+ Effect.gen(function* () {
491
+ const pull = yield* Stream.toPull(coalescer.stream);
492
+ const batch = yield* pull;
493
+ expect(batch.map((item) => (item.kind === "event" ? item.sequence : null))).toEqual([1]);
494
+ yield* coalescer.offer(makeMessage(2));
495
+ yield* coalescer.offer(makeToolActivity(3));
496
+ expect((yield* coalescer.usage).retainedItems).toBe(3);
497
515
- const overflow = yield* coalescer
516
- .offer(makeToolActivity(4, { kind: "tool.completed" }))
517
- .pipe(Effect.result);
518
- expect(overflow._tag).toBe("Failure");
519
- yield* coalescer.closed;
520
- expect(yield* coalescer.usage).toEqual({
521
- retainedItems: 1,
522
- retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
523
- });
524
- }),
525
- );
526
- expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
527
- }),
528
- ),
498
+ const overflow = yield* coalescer
499
+ .offer(makeToolActivity(4, { kind: "tool.completed" }))
500
+ .pipe(Effect.result);
501
+ expect(overflow._tag).toBe("Failure");
502
+ yield* coalescer.closed;
503
+ expect(yield* coalescer.usage).toEqual({
504
+ retainedItems: 1,
505
+ retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
506
+ });
507
+ }),
508
+ );
509
+ expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
510
+ }),
511
);
512
});
513
apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts
+735
-751
@@ -89,229 +89,225 @@ describe("ThreadPullRequestServiceV2 reads", () => {
89
};
90
91
it.effect("does not sweep branch pull requests while no client is connected", () =>
92
- Effect.scoped(
93
- Effect.gen(function* () {
94
- // Polling active branches without a connected client wastes GitHub requests.
95
- const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
96
- const project: OrchestrationProjectShell = {
97
- id: thread.projectId,
98
- title: "Project",
99
- workspaceRoot: "/workspace/project",
100
- defaultModelSelection: null,
101
- scripts: [],
102
- createdAt: "2026-08-01T00:00:00.000Z",
103
- updatedAt: "2026-08-01T00:00:00.000Z",
104
- };
105
- const activation = yield* Deferred.make<void>();
106
- const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
107
- const turnLookup = yield* Deferred.make<void>();
108
- const lookups: Array<{ readonly refresh: boolean }> = [];
109
- const dependencies = Layer.mergeAll(
110
- Layer.mock(Orchestrator.OrchestratorV2)({
111
- streamDomainEvents: Stream.fromQueue(domainEvents),
112
- getPullRequestSnapshot: () =>
113
- Effect.succeed({
114
- schemaVersion: 2,
115
- snapshotSequence: 1,
116
- threads: [thread],
117
- archivedThreads: [],
118
- }),
119
- }),
120
- Layer.mock(ProjectStore.ProjectStoreV2)({
121
- listShells: () => Effect.succeed([project]),
122
- getShell: () => Effect.succeedSome(project),
123
- }),
124
- Layer.mock(GitManager.GitManager)({
125
- branchPullRequest: (_input, options) =>
126
- Effect.gen(function* () {
127
- const refresh = options?.refresh ?? false;
128
- lookups.push({ refresh });
129
- if (refresh) yield* Deferred.succeed(turnLookup, undefined);
130
- return null;
131
- }),
132
- }),
133
- Layer.mock(PullRequestService.PullRequestService)({}),
134
- Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
135
- resolve: () =>
136
- Effect.succeed({
137
- canonicalKey: "github.com/acme/project",
138
- locator: {
139
- source: "git-remote" as const,
140
- remoteName: "origin",
141
- remoteUrl: "git@github.com:acme/project.git",
142
- },
143
- provider: SourceControlProviderKind.make("github"),
144
- owner: "acme",
145
- name: "project",
146
- }),
147
- }),
148
- // No client holds an activity lease.
149
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({
150
- shouldRunScopeWork: () => Effect.succeed(false),
151
- shouldRunOpportunisticWork: Effect.succeed(false),
152
- }),
153
- Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
154
- Layer.succeed(
155
- SecureRandom.SecureRandom,
156
- SecureRandom.make((size) => new Uint8Array(size).fill(1)),
157
- ),
158
- FileSystem.layerNoop({}),
159
- Path.layer,
160
- );
161
- yield* Effect.gen(function* () {
162
- const service = yield* ThreadPullRequestService.make;
163
- yield* service.start();
164
- yield* Deferred.succeed(activation, undefined);
92
+ Effect.gen(function* () {
93
+ // Polling active branches without a connected client wastes GitHub requests.
94
+ const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
95
+ const project: OrchestrationProjectShell = {
96
+ id: thread.projectId,
97
+ title: "Project",
98
+ workspaceRoot: "/workspace/project",
99
+ defaultModelSelection: null,
100
+ scripts: [],
101
+ createdAt: "2026-08-01T00:00:00.000Z",
102
+ updatedAt: "2026-08-01T00:00:00.000Z",
103
+ };
104
+ const activation = yield* Deferred.make<void>();
105
+ const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
106
+ const turnLookup = yield* Deferred.make<void>();
107
+ const lookups: Array<{ readonly refresh: boolean }> = [];
108
+ const dependencies = Layer.mergeAll(
109
+ Layer.mock(Orchestrator.OrchestratorV2)({
110
+ streamDomainEvents: Stream.fromQueue(domainEvents),
111
+ getPullRequestSnapshot: () =>
112
+ Effect.succeed({
113
+ schemaVersion: 2,
114
+ snapshotSequence: 1,
115
+ threads: [thread],
116
+ archivedThreads: [],
117
+ }),
118
+ }),
119
+ Layer.mock(ProjectStore.ProjectStoreV2)({
120
+ listShells: () => Effect.succeed([project]),
121
+ getShell: () => Effect.succeedSome(project),
122
+ }),
123
+ Layer.mock(GitManager.GitManager)({
124
+ branchPullRequest: (_input, options) =>
125
+ Effect.gen(function* () {
126
+ const refresh = options?.refresh ?? false;
127
+ lookups.push({ refresh });
128
+ if (refresh) yield* Deferred.succeed(turnLookup, undefined);
129
+ return null;
130
+ }),
131
+ }),
132
+ Layer.mock(PullRequestService.PullRequestService)({}),
133
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
134
+ resolve: () =>
135
+ Effect.succeed({
136
+ canonicalKey: "github.com/acme/project",
137
+ locator: {
138
+ source: "git-remote" as const,
139
+ remoteName: "origin",
140
+ remoteUrl: "git@github.com:acme/project.git",
141
+ },
142
+ provider: SourceControlProviderKind.make("github"),
143
+ owner: "acme",
144
+ name: "project",
145
+ }),
146
+ }),
147
+ // No client holds an activity lease.
148
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
149
+ shouldRunScopeWork: () => Effect.succeed(false),
150
+ shouldRunOpportunisticWork: Effect.succeed(false),
151
+ }),
152
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
153
+ Layer.succeed(
154
+ SecureRandom.SecureRandom,
155
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
156
+ ),
157
+ FileSystem.layerNoop({}),
158
+ Path.layer,
159
+ );
160
+ yield* Effect.gen(function* () {
161
+ const service = yield* ThreadPullRequestService.make;
162
+ yield* service.start();
163
+ yield* Deferred.succeed(activation, undefined);
164
166
- // A finished turn still discovers the pull request for its branch.
167
- yield* Queue.offer(domainEvents, {
168
- type: "checkpoint.captured",
169
- threadId: thread.id,
170
- } as OrchestrationV2DomainEvent);
171
- yield* Deferred.await(turnLookup);
172
- yield* service.drain;
173
- const lookupsBeforeIdle = lookups.length;
165
+ // A finished turn still discovers the pull request for its branch.
166
+ yield* Queue.offer(domainEvents, {
167
+ type: "checkpoint.captured",
168
+ threadId: thread.id,
169
+ } as OrchestrationV2DomainEvent);
170
+ yield* Deferred.await(turnLookup);
171
+ yield* service.drain;
172
+ const lookupsBeforeIdle = lookups.length;
173
175
- yield* TestClock.adjust("10 minutes");
176
- yield* service.drain;
174
+ yield* TestClock.adjust("10 minutes");
175
+ yield* service.drain;
176
178
- expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
179
- }).pipe(Effect.provide(dependencies));
180
- }),
181
- ),
177
+ expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
178
+ }).pipe(Effect.provide(dependencies));
179
+ }),
180
);
181
182
it.effect("looks up a finished turn's branch once for all its turn-end events", () =>
185
- Effect.scoped(
186
- Effect.gen(function* () {
187
- const thread = { ...threadShell("turn-end-thread"), branch: "t3/turn-end" };
188
- const otherThread = {
189
- ...threadShell("other-turn-end-thread"),
190
- branch: "t3/other-turn-end",
191
- };
192
- const project: OrchestrationProjectShell = {
193
- id: thread.projectId,
194
- title: "Project",
195
- workspaceRoot: "/workspace/project",
196
- defaultModelSelection: null,
197
- scripts: [],
198
- createdAt: "2026-08-01T00:00:00.000Z",
199
- updatedAt: "2026-08-01T00:00:00.000Z",
200
- };
201
- // A turn end commits its checkpoints and the run's end together. The queued
202
- // non-refresh request ahead of them must still become a refresh when they join it.
203
- const turnEnd = [
204
- { type: "thread.metadata-updated", threadId: thread.id },
205
- { type: "checkpoint.captured", threadId: thread.id },
206
- { type: "checkpoint.captured", threadId: thread.id },
207
- { type: "run.updated", threadId: thread.id, payload: { status: "completed" } },
208
- { type: "checkpoint.captured", threadId: otherThread.id },
209
- { type: "run.updated", threadId: otherThread.id, payload: { status: "completed" } },
210
- ] as Array<OrchestrationV2DomainEvent>;
211
- // Arrives during the thread's own lookup, which may already have read the old host state.
212
- const duringLookup = [
213
- { type: "checkpoint.captured", threadId: thread.id },
214
- { type: "thread.metadata-updated", threadId: thread.id },
215
- ] as Array<OrchestrationV2DomainEvent>;
216
- const activation = yield* Deferred.make<void>();
217
- const sweepStarted = yield* Deferred.make<void>();
218
- const turnEndQueued = yield* Deferred.make<void>();
219
- const lookupStarted = yield* Deferred.make<void>();
220
- const followUpQueued = yield* Deferred.make<void>();
221
- const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
222
- const dependencies = Layer.mergeAll(
223
- Layer.mock(Orchestrator.OrchestratorV2)({
224
- // The batch arrives while the worker is busy with the startup sweep.
225
- streamDomainEvents: Stream.fromEffect(Deferred.await(sweepStarted)).pipe(
226
- Stream.drain,
227
- Stream.concat(Stream.fromIterable(turnEnd)),
228
- Stream.concat(
229
- Stream.fromEffect(Deferred.succeed(turnEndQueued, undefined)).pipe(Stream.drain),
230
- ),
231
- Stream.concat(Stream.fromEffect(Deferred.await(lookupStarted)).pipe(Stream.drain)),
232
- Stream.concat(Stream.fromIterable(duringLookup)),
233
- Stream.concat(
234
- Stream.fromEffect(Deferred.succeed(followUpQueued, undefined)).pipe(Stream.drain),
235
- ),
236
- Stream.concat(Stream.never),
183
+ Effect.gen(function* () {
184
+ const thread = { ...threadShell("turn-end-thread"), branch: "t3/turn-end" };
185
+ const otherThread = {
186
+ ...threadShell("other-turn-end-thread"),
187
+ branch: "t3/other-turn-end",
188
+ };
189
+ const project: OrchestrationProjectShell = {
190
+ id: thread.projectId,
191
+ title: "Project",
192
+ workspaceRoot: "/workspace/project",
193
+ defaultModelSelection: null,
194
+ scripts: [],
195
+ createdAt: "2026-08-01T00:00:00.000Z",
196
+ updatedAt: "2026-08-01T00:00:00.000Z",
197
+ };
198
+ // A turn end commits its checkpoints and the run's end together. The queued
199
+ // non-refresh request ahead of them must still become a refresh when they join it.
200
+ const turnEnd = [
201
+ { type: "thread.metadata-updated", threadId: thread.id },
202
+ { type: "checkpoint.captured", threadId: thread.id },
203
+ { type: "checkpoint.captured", threadId: thread.id },
204
+ { type: "run.updated", threadId: thread.id, payload: { status: "completed" } },
205
+ { type: "checkpoint.captured", threadId: otherThread.id },
206
+ { type: "run.updated", threadId: otherThread.id, payload: { status: "completed" } },
207
+ ] as Array<OrchestrationV2DomainEvent>;
208
+ // Arrives during the thread's own lookup, which may already have read the old host state.
209
+ const duringLookup = [
210
+ { type: "checkpoint.captured", threadId: thread.id },
211
+ { type: "thread.metadata-updated", threadId: thread.id },
212
+ ] as Array<OrchestrationV2DomainEvent>;
213
+ const activation = yield* Deferred.make<void>();
214
+ const sweepStarted = yield* Deferred.make<void>();
215
+ const turnEndQueued = yield* Deferred.make<void>();
216
+ const lookupStarted = yield* Deferred.make<void>();
217
+ const followUpQueued = yield* Deferred.make<void>();
218
+ const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
219
+ const dependencies = Layer.mergeAll(
220
+ Layer.mock(Orchestrator.OrchestratorV2)({
221
+ // The batch arrives while the worker is busy with the startup sweep.
222
+ streamDomainEvents: Stream.fromEffect(Deferred.await(sweepStarted)).pipe(
223
+ Stream.drain,
224
+ Stream.concat(Stream.fromIterable(turnEnd)),
225
+ Stream.concat(
226
+ Stream.fromEffect(Deferred.succeed(turnEndQueued, undefined)).pipe(Stream.drain),
227
),
238
- getPullRequestSnapshot: ({ threadId }) =>
239
- Effect.succeed({
240
- schemaVersion: 2,
241
- snapshotSequence: 1,
242
- threads: [thread, otherThread].filter(
243
- (candidate) => threadId === undefined || candidate.id === threadId,
244
- ),
245
- archivedThreads: [],
246
- }),
247
- }),
248
- Layer.mock(ProjectStore.ProjectStoreV2)({
249
- listShells: () => Effect.succeed([project]),
250
- getShell: () => Effect.succeedSome(project),
251
- }),
252
- Layer.mock(GitManager.GitManager)({
253
- branchPullRequest: (input, options) =>
254
- Effect.gen(function* () {
255
- lookups.push({ branch: input.branch, refresh: options?.refresh ?? false });
256
- if (!(yield* Deferred.isDone(turnEndQueued))) {
257
- yield* Deferred.succeed(sweepStarted, undefined);
258
- yield* Deferred.await(turnEndQueued);
259
- } else if (
260
- input.branch === thread.branch &&
261
- !(yield* Deferred.isDone(followUpQueued))
262
- ) {
263
- yield* Deferred.succeed(lookupStarted, undefined);
264
- yield* Deferred.await(followUpQueued);
265
- }
266
- return null;
267
- }),
268
- }),
269
- Layer.mock(PullRequestService.PullRequestService)({}),
270
- Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
271
- resolve: () =>
272
- Effect.succeed({
273
- canonicalKey: "github.com/acme/project",
274
- locator: {
275
- source: "git-remote" as const,
276
- remoteName: "origin",
277
- remoteUrl: "git@github.com:acme/project.git",
278
- },
279
- provider: SourceControlProviderKind.make("github"),
280
- owner: "acme",
281
- name: "project",
282
- }),
283
- }),
284
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({
285
- shouldRunScopeWork: () => Effect.succeed(false),
286
- shouldRunOpportunisticWork: Effect.succeed(false),
287
- }),
288
- Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
289
- Layer.succeed(
290
- SecureRandom.SecureRandom,
291
- SecureRandom.make((size) => new Uint8Array(size).fill(1)),
228
+ Stream.concat(Stream.fromEffect(Deferred.await(lookupStarted)).pipe(Stream.drain)),
229
+ Stream.concat(Stream.fromIterable(duringLookup)),
230
+ Stream.concat(
231
+ Stream.fromEffect(Deferred.succeed(followUpQueued, undefined)).pipe(Stream.drain),
232
+ ),
233
+ Stream.concat(Stream.never),
234
),
293
- FileSystem.layerNoop({}),
294
- Path.layer,
295
- );
296
- yield* Effect.gen(function* () {
297
- const service = yield* ThreadPullRequestService.make;
298
- yield* service.start();
299
- yield* Deferred.succeed(activation, undefined);
300
- yield* Deferred.await(followUpQueued);
301
- yield* service.drain;
302
- }).pipe(Effect.provide(dependencies));
235
+ getPullRequestSnapshot: ({ threadId }) =>
236
+ Effect.succeed({
237
+ schemaVersion: 2,
238
+ snapshotSequence: 1,
239
+ threads: [thread, otherThread].filter(
240
+ (candidate) => threadId === undefined || candidate.id === threadId,
241
+ ),
242
+ archivedThreads: [],
243
+ }),
244
+ }),
245
+ Layer.mock(ProjectStore.ProjectStoreV2)({
246
+ listShells: () => Effect.succeed([project]),
247
+ getShell: () => Effect.succeedSome(project),
248
+ }),
249
+ Layer.mock(GitManager.GitManager)({
250
+ branchPullRequest: (input, options) =>
251
+ Effect.gen(function* () {
252
+ lookups.push({ branch: input.branch, refresh: options?.refresh ?? false });
253
+ if (!(yield* Deferred.isDone(turnEndQueued))) {
254
+ yield* Deferred.succeed(sweepStarted, undefined);
255
+ yield* Deferred.await(turnEndQueued);
256
+ } else if (
257
+ input.branch === thread.branch &&
258
+ !(yield* Deferred.isDone(followUpQueued))
259
+ ) {
260
+ yield* Deferred.succeed(lookupStarted, undefined);
261
+ yield* Deferred.await(followUpQueued);
262
+ }
263
+ return null;
264
+ }),
265
+ }),
266
+ Layer.mock(PullRequestService.PullRequestService)({}),
267
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
268
+ resolve: () =>
269
+ Effect.succeed({
270
+ canonicalKey: "github.com/acme/project",
271
+ locator: {
272
+ source: "git-remote" as const,
273
+ remoteName: "origin",
274
+ remoteUrl: "git@github.com:acme/project.git",
275
+ },
276
+ provider: SourceControlProviderKind.make("github"),
277
+ owner: "acme",
278
+ name: "project",
279
+ }),
280
+ }),
281
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
282
+ shouldRunScopeWork: () => Effect.succeed(false),
283
+ shouldRunOpportunisticWork: Effect.succeed(false),
284
+ }),
285
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
286
+ Layer.succeed(
287
+ SecureRandom.SecureRandom,
288
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
289
+ ),
290
+ FileSystem.layerNoop({}),
291
+ Path.layer,
292
+ );
293
+ yield* Effect.gen(function* () {
294
+ const service = yield* ThreadPullRequestService.make;
295
+ yield* service.start();
296
+ yield* Deferred.succeed(activation, undefined);
297
+ yield* Deferred.await(followUpQueued);
298
+ yield* service.drain;
299
+ }).pipe(Effect.provide(dependencies));
300
304
- // The startup sweep, one refresh lookup per thread for its turn-end batch, then one
305
- // follow-up refresh for the events that arrived during the thread's lookup.
306
- expect(lookups).toEqual([
307
- { branch: thread.branch, refresh: false },
308
- { branch: otherThread.branch, refresh: false },
309
- { branch: thread.branch, refresh: true },
310
- { branch: otherThread.branch, refresh: true },
311
- { branch: thread.branch, refresh: true },
312
- ]);
313
- }),
314
- ),
301
+ // The startup sweep, one refresh lookup per thread for its turn-end batch, then one
302
+ // follow-up refresh for the events that arrived during the thread's lookup.
303
+ expect(lookups).toEqual([
304
+ { branch: thread.branch, refresh: false },
305
+ { branch: otherThread.branch, refresh: false },
306
+ { branch: thread.branch, refresh: true },
307
+ { branch: otherThread.branch, refresh: true },
308
+ { branch: thread.branch, refresh: true },
309
+ ]);
310
+ }),
311
);
312
313
it.effect.each([
@@ -343,120 +339,16 @@ describe("ThreadPullRequestServiceV2 reads", () => {
339
] as const)(
340
"looks up a branch whose worktree is $worktree in $cwd",
341
({ existingPaths, unreadablePaths, cwd }) =>
346
- Effect.scoped(
347
- Effect.gen(function* () {
348
- const thread = {
349
- ...threadShell("worktree-thread"),
350
- settledOverride: "settled" as const,
351
- settledAt: NOW,
352
- branch: "feature/worktree",
353
- worktreePath: "/workspace/worktree",
354
- };
355
- const project: OrchestrationProjectShell = {
356
- id: thread.projectId,
357
- title: "Project",
358
- workspaceRoot: "/workspace/project",
359
- defaultModelSelection: null,
360
- scripts: [],
361
- createdAt: "2026-08-01T00:00:00.000Z",
362
- updatedAt: "2026-08-01T00:00:00.000Z",
363
- };
364
- const activation = yield* Deferred.make<void>();
365
- const sweepStarted = yield* Deferred.make<void>();
366
- const lookupCwds: Array<string> = [];
367
- const dependencies = Layer.mergeAll(
368
- Layer.mock(Orchestrator.OrchestratorV2)({
369
- streamDomainEvents: Stream.never,
370
- getPullRequestSnapshot: () =>
371
- Deferred.succeed(sweepStarted, undefined).pipe(
372
- Effect.as({
373
- schemaVersion: 2,
374
- snapshotSequence: 1,
375
- threads: [thread],
376
- archivedThreads: [],
377
- }),
378
- ),
379
- }),
380
- Layer.mock(ProjectStore.ProjectStoreV2)({
381
- listShells: () => Effect.succeed([project]),
382
- getShell: () => Effect.succeedSome(project),
383
- }),
384
- Layer.mock(GitManager.GitManager)({
385
- branchPullRequest: (input) =>
386
- Effect.sync(() => {
387
- lookupCwds.push(input.cwd);
388
- return null;
389
- }),
390
- }),
391
- Layer.mock(PullRequestService.PullRequestService)({}),
392
- Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
393
- resolve: () =>
394
- Effect.succeed({
395
- canonicalKey: "github.com/acme/project",
396
- locator: {
397
- source: "git-remote" as const,
398
- remoteName: "origin",
399
- remoteUrl: "git@github.com:acme/project.git",
400
- },
401
- provider: SourceControlProviderKind.make("github"),
402
- owner: "acme",
403
- name: "project",
404
- }),
405
- }),
406
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
407
- Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
408
- Layer.succeed(
409
- SecureRandom.SecureRandom,
410
- SecureRandom.make((size) => new Uint8Array(size).fill(1)),
411
- ),
412
- FileSystem.layerNoop({
413
- exists: (path) =>
414
- unreadablePaths.some((entry) => entry === path)
415
- ? Effect.fail(
416
- PlatformError.systemError({
417
- _tag: "PermissionDenied",
418
- module: "FileSystem",
419
- method: "exists",
420
- pathOrDescriptor: path,
421
- }),
422
- )
423
- : Effect.succeed(existingPaths.some((entry) => entry === path)),
424
- }),
425
- Path.layer,
426
- );
427
- yield* Effect.gen(function* () {
428
- const service = yield* ThreadPullRequestService.make;
429
- yield* service.start();
430
- yield* Deferred.succeed(activation, undefined);
431
- yield* Deferred.await(sweepStarted);
432
- yield* service.drain;
433
- }).pipe(Effect.provide(dependencies));
434
-
435
- expect(lookupCwds).toEqual([cwd]);
436
- }),
437
- ),
438
- );
439
-
440
- it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
441
- Effect.scoped(
342
Effect.gen(function* () {
443
- const parent = {
444
- ...threadShell("parent-thread"),
445
- branch: "feature/parent",
446
- worktreePath: "/workspace/parent",
447
- };
448
- const child: OrchestrationV2ThreadShell = {
449
- ...threadShell("child-thread"),
450
- branch: "t3/reply-ok",
451
- worktreePath: "/workspace/child",
452
- lineage: {
453
- rootThreadId: parent.id,
454
- parentThreadId: parent.id,
455
- relationshipToParent: "subagent",
456
- },
343
+ const thread = {
344
+ ...threadShell("worktree-thread"),
345
+ settledOverride: "settled" as const,
346
+ settledAt: NOW,
347
+ branch: "feature/worktree",
348
+ worktreePath: "/workspace/worktree",
349
};
350
const project: OrchestrationProjectShell = {
459
- id: parent.projectId,
351
+ id: thread.projectId,
352
title: "Project",
353
workspaceRoot: "/workspace/project",
354
defaultModelSelection: null,
@@ -465,37 +357,29 @@ describe("ThreadPullRequestServiceV2 reads", () => {
357
updatedAt: "2026-08-01T00:00:00.000Z",
358
};
359
const activation = yield* Deferred.make<void>();
468
- const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
469
- const sweeps = yield* Queue.unbounded<void>();
470
- const childLookup = yield* Deferred.make<void>();
471
- const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
360
+ const sweepStarted = yield* Deferred.make<void>();
361
+ const lookupCwds: Array<string> = [];
362
const dependencies = Layer.mergeAll(
363
Layer.mock(Orchestrator.OrchestratorV2)({
474
- streamDomainEvents: Stream.fromQueue(domainEvents),
475
- getPullRequestSnapshot: ({ threadId }) =>
476
- threadId !== undefined
477
- ? Effect.succeed({ snapshotSequence: 1, threads: [child] })
478
- : Queue.offer(sweeps, undefined).pipe(
479
- Effect.as({
480
- schemaVersion: 2,
481
- snapshotSequence: 1,
482
- threads: [parent, child],
483
- archivedThreads: [],
484
- }),
485
- ),
364
+ streamDomainEvents: Stream.never,
365
+ getPullRequestSnapshot: () =>
366
+ Deferred.succeed(sweepStarted, undefined).pipe(
367
+ Effect.as({
368
+ schemaVersion: 2,
369
+ snapshotSequence: 1,
370
+ threads: [thread],
371
+ archivedThreads: [],
372
+ }),
373
+ ),
374
}),
375
Layer.mock(ProjectStore.ProjectStoreV2)({
376
listShells: () => Effect.succeed([project]),
377
getShell: () => Effect.succeedSome(project),
378
}),
379
Layer.mock(GitManager.GitManager)({
492
- branchPullRequest: (input, options) =>
493
- Effect.gen(function* () {
494
- const refresh = options?.refresh ?? false;
495
- lookups.push({ branch: input.branch, refresh });
496
- if (input.branch === child.branch && refresh) {
497
- yield* Deferred.succeed(childLookup, undefined);
498
- }
380
+ branchPullRequest: (input) =>
381
+ Effect.sync(() => {
382
+ lookupCwds.push(input.cwd);
383
return null;
384
}),
385
}),
@@ -514,341 +398,193 @@ describe("ThreadPullRequestServiceV2 reads", () => {
398
name: "project",
399
}),
400
}),
517
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({
518
- shouldRunScopeWork: () => Effect.succeed(true),
519
- shouldRunOpportunisticWork: Effect.succeed(true),
520
- }),
401
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
402
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
403
Layer.succeed(
404
SecureRandom.SecureRandom,
405
SecureRandom.make((size) => new Uint8Array(size).fill(1)),
406
),
526
- FileSystem.layerNoop({}),
407
+ FileSystem.layerNoop({
408
+ exists: (path) =>
409
+ unreadablePaths.some((entry) => entry === path)
410
+ ? Effect.fail(
411
+ PlatformError.systemError({
412
+ _tag: "PermissionDenied",
413
+ module: "FileSystem",
414
+ method: "exists",
415
+ pathOrDescriptor: path,
416
+ }),
417
+ )
418
+ : Effect.succeed(existingPaths.some((entry) => entry === path)),
419
+ }),
420
Path.layer,
421
);
422
yield* Effect.gen(function* () {
423
const service = yield* ThreadPullRequestService.make;
424
yield* service.start();
425
yield* Deferred.succeed(activation, undefined);
533
-
534
- // Startup backfill sweep, then one periodic sweep.
535
- yield* Queue.take(sweeps);
536
- yield* service.drain;
537
- yield* TestClock.adjust("1 minute");
538
- yield* Queue.take(sweeps);
539
- yield* service.drain;
540
- const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
541
-
542
- // The child's own turn still discovers its pull request.
543
- yield* Queue.offer(domainEvents, {
544
- type: "checkpoint.captured",
545
- threadId: child.id,
546
- } as OrchestrationV2DomainEvent);
547
- yield* Deferred.await(childLookup);
426
+ yield* Deferred.await(sweepStarted);
427
yield* service.drain;
549
-
550
- expect(sweepLookups).toEqual([parent.branch, parent.branch]);
551
- expect(lookups.slice(sweepLookups.length)).toEqual([
552
- { branch: child.branch, refresh: true },
553
- ]);
428
}).pipe(Effect.provide(dependencies));
429
+
430
+ expect(lookupCwds).toEqual([cwd]);
431
}),
556
- ),
432
);
433
559
- it.effect.each([
560
- { state: "open", checkedOut: false },
561
- { state: "merged", checkedOut: false },
562
- { state: "closed", checkedOut: false },
563
- { state: "merged", checkedOut: true },
564
- ] as const)(
565
- "associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
566
- ({ state, checkedOut }) =>
567
- Effect.scoped(
568
- Effect.gen(function* () {
569
- const reference = {
570
- projectId: ProjectId.make("project-1"),
571
- repository: "acme/project",
572
- number: 42,
573
- url: "https://github.com/acme/project/pull/42",
574
- };
575
- const terminalAt = "2026-09-19T00:00:00.000Z";
576
- const detected = {
577
- number: 42,
578
- url: reference.url,
579
- title: "Previous staging work",
580
- baseRef: "main",
581
- headRef: "staging",
582
- state,
583
- updatedAt: terminalAt,
584
- closedAt: state === "closed" ? terminalAt : null,
585
- mergedAt: state === "merged" ? terminalAt : null,
586
- repositoryKey: "github.com/acme/project",
587
- };
588
- const threads = [
589
- { ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
590
- { ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
591
- threadShell("new"),
592
- { ...threadShell("saved"), branchPullRequest: reference },
593
- { ...threadShell("explicit"), linkedPullRequest: reference },
594
- ].map((thread) => ({ ...thread, branch: "staging" }));
595
- const project: OrchestrationProjectShell = {
596
- id: reference.projectId,
597
- title: "Project",
598
- workspaceRoot: "/workspace/project",
599
- defaultModelSelection: null,
600
- scripts: [],
601
- createdAt: "2026-08-01T00:00:00.000Z",
602
- updatedAt: "2026-08-01T00:00:00.000Z",
603
- };
604
- const activation = yield* Deferred.make<void>();
605
- const sweepStarted = yield* Deferred.make<void>();
606
- const commands: Array<OrchestrationV2ServerCommand> = [];
607
- const dependencies = Layer.mergeAll(
608
- Layer.mock(Orchestrator.OrchestratorV2)({
609
- streamDomainEvents: Stream.never,
610
- getPullRequestSnapshot: () =>
611
- Deferred.succeed(sweepStarted, undefined).pipe(
612
- Effect.as({ snapshotSequence: 1, threads }),
434
+ it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
435
+ Effect.gen(function* () {
436
+ const parent = {
437
+ ...threadShell("parent-thread"),
438
+ branch: "feature/parent",
439
+ worktreePath: "/workspace/parent",
440
+ };
441
+ const child: OrchestrationV2ThreadShell = {
442
+ ...threadShell("child-thread"),
443
+ branch: "t3/reply-ok",
444
+ worktreePath: "/workspace/child",
445
+ lineage: {
446
+ rootThreadId: parent.id,
447
+ parentThreadId: parent.id,
448
+ relationshipToParent: "subagent",
449
+ },
450
+ };
451
+ const project: OrchestrationProjectShell = {
452
+ id: parent.projectId,
453
+ title: "Project",
454
+ workspaceRoot: "/workspace/project",
455
+ defaultModelSelection: null,
456
+ scripts: [],
457
+ createdAt: "2026-08-01T00:00:00.000Z",
458
+ updatedAt: "2026-08-01T00:00:00.000Z",
459
+ };
460
+ const activation = yield* Deferred.make<void>();
461
+ const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
462
+ const sweeps = yield* Queue.unbounded<void>();
463
+ const childLookup = yield* Deferred.make<void>();
464
+ const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
465
+ const dependencies = Layer.mergeAll(
466
+ Layer.mock(Orchestrator.OrchestratorV2)({
467
+ streamDomainEvents: Stream.fromQueue(domainEvents),
468
+ getPullRequestSnapshot: ({ threadId }) =>
469
+ threadId !== undefined
470
+ ? Effect.succeed({ snapshotSequence: 1, threads: [child] })
471
+ : Queue.offer(sweeps, undefined).pipe(
472
+ Effect.as({
473
+ schemaVersion: 2,
474
+ snapshotSequence: 1,
475
+ threads: [parent, child],
476
+ archivedThreads: [],
477
+ }),
478
),
614
- dispatch: (command) =>
615
- Effect.sync(() => {
616
- commands.push(command);
617
- return { sequence: 2, storedEvents: [] };
618
- }),
619
- }),
620
- Layer.mock(ProjectStore.ProjectStoreV2)({
621
- listShells: () => Effect.succeed([project]),
622
- getShell: () => Effect.succeedSome(project),
623
- }),
624
- Layer.mock(GitManager.GitManager)({
625
- branchPullRequest: () => Effect.succeed(detected),
626
- checkedOutPullRequest: () => Effect.succeed(checkedOut),
627
- }),
628
- Layer.mock(PullRequestService.PullRequestService)({
629
- summary: () =>
630
- Effect.succeed({
631
- ...detected,
632
- ...reference,
633
- provider: SourceControlProviderKind.make("github"),
634
- baseBranch: detected.baseRef,
635
- headBranch: detected.headRef,
636
- }),
637
- }),
638
- Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
639
- resolve: () =>
640
- Effect.succeed({
641
- canonicalKey: "github.com/acme/project",
642
- locator: {
643
- source: "git-remote" as const,
644
- remoteName: "origin",
645
- remoteUrl: "git@github.com:acme/project.git",
646
- },
647
- provider: SourceControlProviderKind.make("github"),
648
- owner: "acme",
649
- name: "project",
650
- }),
479
+ }),
480
+ Layer.mock(ProjectStore.ProjectStoreV2)({
481
+ listShells: () => Effect.succeed([project]),
482
+ getShell: () => Effect.succeedSome(project),
483
+ }),
484
+ Layer.mock(GitManager.GitManager)({
485
+ branchPullRequest: (input, options) =>
486
+ Effect.gen(function* () {
487
+ const refresh = options?.refresh ?? false;
488
+ lookups.push({ branch: input.branch, refresh });
489
+ if (input.branch === child.branch && refresh) {
490
+ yield* Deferred.succeed(childLookup, undefined);
491
+ }
492
+ return null;
493
}),
652
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
653
- Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
654
- Layer.succeed(
655
- SecureRandom.SecureRandom,
656
- SecureRandom.make((size) => new Uint8Array(size).fill(1)),
657
- ),
658
- FileSystem.layerNoop({}),
659
- Path.layer,
660
- );
661
- yield* Effect.gen(function* () {
662
- const service = yield* ThreadPullRequestService.make;
663
- yield* service.start();
664
- yield* Deferred.succeed(activation, undefined);
665
- yield* Deferred.await(sweepStarted);
666
- yield* service.drain;
667
- }).pipe(Effect.provide(dependencies));
668
-
669
- expect(
670
- commands.map((command) => {
671
- if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
672
- expect(command).not.toHaveProperty("linkedPullRequest");
673
- return [command.threadId, command.branchPullRequest];
494
+ }),
495
+ Layer.mock(PullRequestService.PullRequestService)({}),
496
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
497
+ resolve: () =>
498
+ Effect.succeed({
499
+ canonicalKey: "github.com/acme/project",
500
+ locator: {
501
+ source: "git-remote" as const,
502
+ remoteName: "origin",
503
+ remoteUrl: "git@github.com:acme/project.git",
504
+ },
505
+ provider: SourceControlProviderKind.make("github"),
506
+ owner: "acme",
507
+ name: "project",
508
}),
675
- ).toEqual(
676
- (state === "open" || checkedOut
677
- ? ["older", "same-time", "new", "explicit"]
678
- : ["older", "same-time"]
679
- ).map((id) => [id, reference]),
680
- );
509
}),
682
- ),
683
- );
510
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
511
+ shouldRunScopeWork: () => Effect.succeed(true),
512
+ shouldRunOpportunisticWork: Effect.succeed(true),
513
+ }),
514
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
515
+ Layer.succeed(
516
+ SecureRandom.SecureRandom,
517
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
518
+ ),
519
+ FileSystem.layerNoop({}),
520
+ Path.layer,
521
+ );
522
+ yield* Effect.gen(function* () {
523
+ const service = yield* ThreadPullRequestService.make;
524
+ yield* service.start();
525
+ yield* Deferred.succeed(activation, undefined);
526
685
- it.effect.each([
686
- { state: "closed", sameBranch: false },
687
- { state: "merged", sameBranch: false },
688
- { state: "closed", sameBranch: true },
689
- { state: "merged", sameBranch: true },
690
- ] as const)(
691
- "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
692
- ({ state, sameBranch }) =>
693
- Effect.scoped(
694
- Effect.gen(function* () {
695
- const savedReference = {
696
- projectId: ProjectId.make("project-1"),
697
- repository: "acme/project",
698
- number: 42,
699
- url: "https://github.com/acme/project/pull/42",
700
- };
701
- const thread = {
702
- ...threadShell("branch-pr-thread"),
703
- branch: "main",
704
- branchPullRequest: savedReference,
705
- linkedPullRequest: savedReference,
706
- };
707
- const project: OrchestrationProjectShell = {
708
- id: thread.projectId,
709
- title: "Project",
710
- workspaceRoot: "/workspace/project",
711
- defaultModelSelection: null,
712
- scripts: [],
713
- createdAt: "2026-08-01T00:00:00.000Z",
714
- updatedAt: "2026-08-01T00:00:00.000Z",
715
- };
716
- const activation = yield* Deferred.make<void>();
717
- const sweepStarted = yield* Deferred.make<void>();
718
- const commands: Array<OrchestrationV2ServerCommand> = [];
719
- let snapshotThread: unknown;
720
- const dependencies = Layer.mergeAll(
721
- Layer.mock(Orchestrator.OrchestratorV2)({
722
- streamDomainEvents: Stream.never,
723
- getPullRequestSnapshot: (options) =>
724
- Effect.gen(function* () {
725
- const store = yield* ProjectionStore.ProjectionStoreV2;
726
- yield* store.apply({
727
- id: EventId.make(`event:${thread.id}:created`),
728
- type: "thread.created",
729
- threadId: thread.id,
730
- occurredAt: NOW,
731
- payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
732
- });
733
- const sql = yield* SqlClient.SqlClient;
734
- yield* sql`INSERT INTO orchestration_events (
735
- sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
736
- occurred_at, actor_kind, payload_json, metadata_json, application_event_version
737
- ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
738
- '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
739
- for (const table of [
740
- "orchestration_v2_projection_turn_items",
741
- "orchestration_v2_projection_messages",
742
- "orchestration_v2_projection_provider_threads",
743
- "orchestration_v2_projection_runs",
744
- ])
745
- yield* sql.unsafe(`DROP TABLE ${table}`);
746
- const snapshot = yield* store.getPullRequestSnapshot(options);
747
- snapshotThread = snapshot.threads[0];
748
- yield* Deferred.succeed(sweepStarted, undefined);
749
- return snapshot;
750
- }).pipe(
751
- Effect.provide(
752
- ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
753
- ),
754
- Effect.orDie,
755
- ),
756
- dispatch: (command) =>
757
- Effect.sync(() => {
758
- commands.push(command);
759
- return { sequence: 2, storedEvents: [] };
760
- }),
761
- }),
762
- Layer.mock(ProjectStore.ProjectStoreV2)({
763
- listShells: () => Effect.succeed([project]),
764
- getShell: () => Effect.succeedSome(project),
765
- }),
766
- Layer.mock(GitManager.GitManager)({
767
- branchPullRequest: () => Effect.succeed(null),
768
- }),
769
- Layer.mock(PullRequestService.PullRequestService)({
770
- summary: () =>
771
- Effect.succeed({
772
- ...savedReference,
773
- provider: SourceControlProviderKind.make("github"),
774
- title: "Previous branch work",
775
- state,
776
- headBranch: sameBranch ? thread.branch : "feature/previous-work",
777
- baseBranch: "release",
778
- updatedAt: "2026-09-19T00:00:00.000Z",
779
- }),
780
- }),
781
- Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
782
- resolve: () =>
783
- Effect.succeed({
784
- canonicalKey: "github.com/acme/project",
785
- locator: {
786
- source: "git-remote" as const,
787
- remoteName: "origin",
788
- remoteUrl: "git@github.com:acme/project.git",
789
- },
790
- provider: SourceControlProviderKind.make("github"),
791
- owner: "acme",
792
- name: "project",
793
- }),
794
- }),
795
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
796
- Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
797
- Layer.succeed(
798
- SecureRandom.SecureRandom,
799
- SecureRandom.make((size) => new Uint8Array(size).fill(1)),
800
- ),
801
- FileSystem.layerNoop({}),
802
- Path.layer,
803
- );
804
- yield* Effect.gen(function* () {
805
- const service = yield* ThreadPullRequestService.make;
806
- yield* service.start();
807
- yield* Deferred.succeed(activation, undefined);
808
- yield* Deferred.await(sweepStarted);
809
- yield* service.drain;
810
- }).pipe(Effect.provide(dependencies));
527
+ // Startup backfill sweep, then one periodic sweep.
528
+ yield* Queue.take(sweeps);
529
+ yield* service.drain;
530
+ yield* TestClock.adjust("1 minute");
531
+ yield* Queue.take(sweeps);
532
+ yield* service.drain;
533
+ const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
534
812
- expect(snapshotThread).toHaveProperty("createdAt", NOW);
813
- if (sameBranch) {
814
- expect(commands).toEqual([]);
815
- } else {
816
- expect(commands).toHaveLength(1);
817
- expect(commands[0]).toMatchObject({
818
- type: "thread.pull-request.sync",
819
- threadId: thread.id,
820
- snapshotSequence: 7,
821
- expected: {
822
- workspaceRoot: project.workspaceRoot,
823
- branch: thread.branch,
824
- worktreePath: thread.worktreePath,
825
- linkedPullRequest: savedReference,
826
- branchPullRequest: savedReference,
827
- },
828
- branchPullRequest: null,
829
- });
830
- expect(commands[0]).not.toHaveProperty("linkedPullRequest");
831
- }
832
- }),
833
- ),
535
+ // The child's own turn still discovers its pull request.
536
+ yield* Queue.offer(domainEvents, {
537
+ type: "checkpoint.captured",
538
+ threadId: child.id,
539
+ } as OrchestrationV2DomainEvent);
540
+ yield* Deferred.await(childLookup);
541
+ yield* service.drain;
542
+
543
+ expect(sweepLookups).toEqual([parent.branch, parent.branch]);
544
+ expect(lookups.slice(sweepLookups.length)).toEqual([
545
+ { branch: child.branch, refresh: true },
546
+ ]);
547
+ }).pipe(Effect.provide(dependencies));
548
+ }),
549
);
550
836
- it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
837
- Effect.scoped(
551
+ it.effect.each([
552
+ { state: "open", checkedOut: false },
553
+ { state: "merged", checkedOut: false },
554
+ { state: "closed", checkedOut: false },
555
+ { state: "merged", checkedOut: true },
556
+ ] as const)(
557
+ "associates a $state branch PR (checkedOut=$checkedOut) only with threads that predate its completion or saved it",
558
+ ({ state, checkedOut }) =>
559
Effect.gen(function* () {
839
- const savedReference = {
560
+ const reference = {
561
projectId: ProjectId.make("project-1"),
562
repository: "acme/project",
563
number: 42,
564
url: "https://github.com/acme/project/pull/42",
565
};
845
- const thread = {
846
- ...threadShell("merged-branch-thread"),
847
- branch: "feature/merged",
848
- branchPullRequest: savedReference,
566
+ const terminalAt = "2026-09-19T00:00:00.000Z";
567
+ const detected = {
568
+ number: 42,
569
+ url: reference.url,
570
+ title: "Previous staging work",
571
+ baseRef: "main",
572
+ headRef: "staging",
573
+ state,
574
+ updatedAt: terminalAt,
575
+ closedAt: state === "closed" ? terminalAt : null,
576
+ mergedAt: state === "merged" ? terminalAt : null,
577
+ repositoryKey: "github.com/acme/project",
578
};
579
+ const threads = [
580
+ { ...threadShell("older"), createdAt: DateTime.makeUnsafe("2026-09-18T00:00:00Z") },
581
+ { ...threadShell("same-time"), createdAt: DateTime.makeUnsafe(terminalAt) },
582
+ threadShell("new"),
583
+ { ...threadShell("saved"), branchPullRequest: reference },
584
+ { ...threadShell("explicit"), linkedPullRequest: reference },
585
+ ].map((thread) => ({ ...thread, branch: "staging" }));
586
const project: OrchestrationProjectShell = {
851
- id: thread.projectId,
587
+ id: reference.projectId,
588
title: "Project",
589
workspaceRoot: "/workspace/project",
590
defaultModelSelection: null,
@@ -857,21 +593,14 @@ describe("ThreadPullRequestServiceV2 reads", () => {
593
updatedAt: "2026-08-01T00:00:00.000Z",
594
};
595
const activation = yield* Deferred.make<void>();
860
- const sweeps = yield* Queue.unbounded<void>();
596
+ const sweepStarted = yield* Deferred.make<void>();
597
const commands: Array<OrchestrationV2ServerCommand> = [];
862
- const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
863
- [];
598
const dependencies = Layer.mergeAll(
599
Layer.mock(Orchestrator.OrchestratorV2)({
600
streamDomainEvents: Stream.never,
601
getPullRequestSnapshot: () =>
868
- Queue.offer(sweeps, undefined).pipe(
869
- Effect.as({
870
- schemaVersion: 2,
871
- snapshotSequence: 1,
872
- threads: [thread],
873
- archivedThreads: [],
874
- }),
602
+ Deferred.succeed(sweepStarted, undefined).pipe(
603
+ Effect.as({ snapshotSequence: 1, threads }),
604
),
605
dispatch: (command) =>
606
Effect.sync(() => {
@@ -884,24 +613,19 @@ describe("ThreadPullRequestServiceV2 reads", () => {
613
getShell: () => Effect.succeedSome(project),
614
}),
615
Layer.mock(GitManager.GitManager)({
887
- branchPullRequest: (_input, options) =>
888
- Effect.sync(() => {
889
- lookups.push(options);
890
- return {
891
- number: 42,
892
- title: "Merged work",
893
- url: savedReference.url,
894
- baseRef: "main",
895
- headRef: thread.branch,
896
- state: "merged" as const,
897
- repositoryKey: "github.com/acme/project",
898
- updatedAt: "2026-09-19T00:00:00.000Z",
899
- closedAt: null,
900
- mergedAt: "2026-09-19T00:00:00.000Z",
901
- };
616
+ branchPullRequest: () => Effect.succeed(detected),
617
+ checkedOutPullRequest: () => Effect.succeed(checkedOut),
618
+ }),
619
+ Layer.mock(PullRequestService.PullRequestService)({
620
+ summary: () =>
621
+ Effect.succeed({
622
+ ...detected,
623
+ ...reference,
624
+ provider: SourceControlProviderKind.make("github"),
625
+ baseBranch: detected.baseRef,
626
+ headBranch: detected.headRef,
627
}),
628
}),
904
- Layer.mock(PullRequestService.PullRequestService)({}),
629
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
630
resolve: () =>
631
Effect.succeed({
@@ -916,10 +640,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
640
name: "project",
641
}),
642
}),
919
- // A connected client keeps the periodic sweep running.
920
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({
921
- shouldRunOpportunisticWork: Effect.succeed(true),
922
- }),
643
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
644
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
645
Layer.succeed(
646
SecureRandom.SecureRandom,
@@ -932,47 +653,33 @@ describe("ThreadPullRequestServiceV2 reads", () => {
653
const service = yield* ThreadPullRequestService.make;
654
yield* service.start();
655
yield* Deferred.succeed(activation, undefined);
935
- yield* Queue.take(sweeps);
936
- yield* service.drain;
937
- yield* TestClock.adjust("1 minute");
938
- yield* Queue.take(sweeps);
656
+ yield* Deferred.await(sweepStarted);
657
yield* service.drain;
658
}).pipe(Effect.provide(dependencies));
659
942
- expect(commands).toEqual([]);
943
- expect(lookups).toHaveLength(2);
944
- // GitManager rereads git state on request, and by default whenever its
945
- // remembered answer is merged or closed.
660
expect(
947
- lookups.filter(
948
- (options) =>
949
- options?.refresh === true ||
950
- options?.freshGitState === true ||
951
- options?.confirmTerminal !== false,
952
- ),
953
- ).toEqual([]);
661
+ commands.map((command) => {
662
+ if (command.type !== "thread.pull-request.sync") throw new Error(command.type);
663
+ expect(command).not.toHaveProperty("linkedPullRequest");
664
+ return [command.threadId, command.branchPullRequest];
665
+ }),
666
+ ).toEqual(
667
+ (state === "open" || checkedOut
668
+ ? ["older", "same-time", "new", "explicit"]
669
+ : ["older", "same-time"]
670
+ ).map((id) => [id, reference]),
671
+ );
672
}),
955
- ),
673
);
674
958
- const mergedPullRequest43 = {
959
- number: 43,
960
- title: "Replacement work",
961
- url: "https://github.com/acme/project/pull/43",
962
- baseRef: "main",
963
- headRef: "feature/replaced",
964
- state: "merged" as const,
965
- repositoryKey: "github.com/acme/project",
966
- updatedAt: "2026-09-19T00:00:00.000Z",
967
- closedAt: null,
968
- mergedAt: "2026-09-19T00:00:00.000Z",
969
- };
970
-
675
it.effect.each([
972
- { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
973
- { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
974
- ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
975
- Effect.scoped(
676
+ { state: "closed", sameBranch: false },
677
+ { state: "merged", sameBranch: false },
678
+ { state: "closed", sameBranch: true },
679
+ { state: "merged", sameBranch: true },
680
+ ] as const)(
681
+ "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
682
+ ({ state, sameBranch }) =>
683
Effect.gen(function* () {
684
const savedReference = {
685
projectId: ProjectId.make("project-1"),
@@ -981,10 +688,10 @@ describe("ThreadPullRequestServiceV2 reads", () => {
688
url: "https://github.com/acme/project/pull/42",
689
};
690
const thread = {
984
- ...threadShell("replaced-branch-thread"),
985
- createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
986
- branch: mergedPullRequest43.headRef,
691
+ ...threadShell("branch-pr-thread"),
692
+ branch: "main",
693
branchPullRequest: savedReference,
694
+ linkedPullRequest: savedReference,
695
};
696
const project: OrchestrationProjectShell = {
697
id: thread.projectId,
@@ -996,19 +703,44 @@ describe("ThreadPullRequestServiceV2 reads", () => {
703
updatedAt: "2026-08-01T00:00:00.000Z",
704
};
705
const activation = yield* Deferred.make<void>();
999
- const sweeps = yield* Queue.unbounded<void>();
706
+ const sweepStarted = yield* Deferred.make<void>();
707
const commands: Array<OrchestrationV2ServerCommand> = [];
708
+ let snapshotThread: unknown;
709
const dependencies = Layer.mergeAll(
710
Layer.mock(Orchestrator.OrchestratorV2)({
711
streamDomainEvents: Stream.never,
1004
- getPullRequestSnapshot: () =>
1005
- Queue.offer(sweeps, undefined).pipe(
1006
- Effect.as({
1007
- schemaVersion: 2,
1008
- snapshotSequence: 1,
1009
- threads: [thread],
1010
- archivedThreads: [],
1011
- }),
712
+ getPullRequestSnapshot: (options) =>
713
+ Effect.gen(function* () {
714
+ const store = yield* ProjectionStore.ProjectionStoreV2;
715
+ yield* store.apply({
716
+ id: EventId.make(`event:${thread.id}:created`),
717
+ type: "thread.created",
718
+ threadId: thread.id,
719
+ occurredAt: NOW,
720
+ payload: { ...thread, lastVisitedAt: thread.lastVisitedAt ?? null },
721
+ });
722
+ const sql = yield* SqlClient.SqlClient;
723
+ yield* sql`INSERT INTO orchestration_events (
724
+ sequence, event_id, aggregate_kind, stream_id, stream_version, event_type,
725
+ occurred_at, actor_kind, payload_json, metadata_json, application_event_version
726
+ ) VALUES (7, 'pr-discovery', 'thread', ${thread.id}, 1, 'thread.created',
727
+ '2026-09-20T00:00:00.000Z', 'system', '{}', '{}', 2)`;
728
+ for (const table of [
729
+ "orchestration_v2_projection_turn_items",
730
+ "orchestration_v2_projection_messages",
731
+ "orchestration_v2_projection_provider_threads",
732
+ "orchestration_v2_projection_runs",
733
+ ])
734
+ yield* sql.unsafe(`DROP TABLE ${table}`);
735
+ const snapshot = yield* store.getPullRequestSnapshot(options);
736
+ snapshotThread = snapshot.threads[0];
737
+ yield* Deferred.succeed(sweepStarted, undefined);
738
+ return snapshot;
739
+ }).pipe(
740
+ Effect.provide(
741
+ ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMemory)),
742
+ ),
743
+ Effect.orDie,
744
),
745
dispatch: (command) =>
746
Effect.sync(() => {
@@ -1020,12 +752,21 @@ describe("ThreadPullRequestServiceV2 reads", () => {
752
listShells: () => Effect.succeed([project]),
753
getShell: () => Effect.succeedSome(project),
754
}),
1023
- // Only the fresh read disagrees with the remembered detection.
755
Layer.mock(GitManager.GitManager)({
1025
- branchPullRequest: (_input, options) =>
1026
- Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
756
+ branchPullRequest: () => Effect.succeed(null),
757
+ }),
758
+ Layer.mock(PullRequestService.PullRequestService)({
759
+ summary: () =>
760
+ Effect.succeed({
761
+ ...savedReference,
762
+ provider: SourceControlProviderKind.make("github"),
763
+ title: "Previous branch work",
764
+ state,
765
+ headBranch: sameBranch ? thread.branch : "feature/previous-work",
766
+ baseBranch: "release",
767
+ updatedAt: "2026-09-19T00:00:00.000Z",
768
+ }),
769
}),
1028
- Layer.mock(PullRequestService.PullRequestService)({}),
770
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
771
resolve: () =>
772
Effect.succeed({
@@ -1040,9 +781,7 @@ describe("ThreadPullRequestServiceV2 reads", () => {
781
name: "project",
782
}),
783
}),
1043
- Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1044
- shouldRunOpportunisticWork: Effect.succeed(true),
1045
- }),
784
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
785
Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
786
Layer.succeed(
787
SecureRandom.SecureRandom,
@@ -1055,27 +794,272 @@ describe("ThreadPullRequestServiceV2 reads", () => {
794
const service = yield* ThreadPullRequestService.make;
795
yield* service.start();
796
yield* Deferred.succeed(activation, undefined);
1058
- yield* Queue.take(sweeps);
797
+ yield* Deferred.await(sweepStarted);
798
yield* service.drain;
799
}).pipe(Effect.provide(dependencies));
800
1062
- expect(
1063
- commands.map((command) =>
1064
- command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1065
- ),
1066
- ).toEqual(
1067
- writes
1068
- ? [
1069
- {
1070
- projectId: project.id,
1071
- repository: "acme/project",
1072
- number: 43,
1073
- url: mergedPullRequest43.url,
1074
- },
1075
- ]
1076
- : [],
1077
- );
801
+ expect(snapshotThread).toHaveProperty("createdAt", NOW);
802
+ if (sameBranch) {
803
+ expect(commands).toEqual([]);
804
+ } else {
805
+ expect(commands).toHaveLength(1);
806
+ expect(commands[0]).toMatchObject({
807
+ type: "thread.pull-request.sync",
808
+ threadId: thread.id,
809
+ snapshotSequence: 7,
810
+ expected: {
811
+ workspaceRoot: project.workspaceRoot,
812
+ branch: thread.branch,
813
+ worktreePath: thread.worktreePath,
814
+ linkedPullRequest: savedReference,
815
+ branchPullRequest: savedReference,
816
+ },
817
+ branchPullRequest: null,
818
+ });
819
+ expect(commands[0]).not.toHaveProperty("linkedPullRequest");
820
+ }
821
}),
1079
- ),
822
+ );
823
+
824
+ it.effect("a saved merged branch PR rereads no git state on each sweep", () =>
825
+ Effect.gen(function* () {
826
+ const savedReference = {
827
+ projectId: ProjectId.make("project-1"),
828
+ repository: "acme/project",
829
+ number: 42,
830
+ url: "https://github.com/acme/project/pull/42",
831
+ };
832
+ const thread = {
833
+ ...threadShell("merged-branch-thread"),
834
+ branch: "feature/merged",
835
+ branchPullRequest: savedReference,
836
+ };
837
+ const project: OrchestrationProjectShell = {
838
+ id: thread.projectId,
839
+ title: "Project",
840
+ workspaceRoot: "/workspace/project",
841
+ defaultModelSelection: null,
842
+ scripts: [],
843
+ createdAt: "2026-08-01T00:00:00.000Z",
844
+ updatedAt: "2026-08-01T00:00:00.000Z",
845
+ };
846
+ const activation = yield* Deferred.make<void>();
847
+ const sweeps = yield* Queue.unbounded<void>();
848
+ const commands: Array<OrchestrationV2ServerCommand> = [];
849
+ const lookups: Array<Parameters<GitManager.GitManager["Service"]["branchPullRequest"]>[1]> =
850
+ [];
851
+ const dependencies = Layer.mergeAll(
852
+ Layer.mock(Orchestrator.OrchestratorV2)({
853
+ streamDomainEvents: Stream.never,
854
+ getPullRequestSnapshot: () =>
855
+ Queue.offer(sweeps, undefined).pipe(
856
+ Effect.as({
857
+ schemaVersion: 2,
858
+ snapshotSequence: 1,
859
+ threads: [thread],
860
+ archivedThreads: [],
861
+ }),
862
+ ),
863
+ dispatch: (command) =>
864
+ Effect.sync(() => {
865
+ commands.push(command);
866
+ return { sequence: 2, storedEvents: [] };
867
+ }),
868
+ }),
869
+ Layer.mock(ProjectStore.ProjectStoreV2)({
870
+ listShells: () => Effect.succeed([project]),
871
+ getShell: () => Effect.succeedSome(project),
872
+ }),
873
+ Layer.mock(GitManager.GitManager)({
874
+ branchPullRequest: (_input, options) =>
875
+ Effect.sync(() => {
876
+ lookups.push(options);
877
+ return {
878
+ number: 42,
879
+ title: "Merged work",
880
+ url: savedReference.url,
881
+ baseRef: "main",
882
+ headRef: thread.branch,
883
+ state: "merged" as const,
884
+ repositoryKey: "github.com/acme/project",
885
+ updatedAt: "2026-09-19T00:00:00.000Z",
886
+ closedAt: null,
887
+ mergedAt: "2026-09-19T00:00:00.000Z",
888
+ };
889
+ }),
890
+ }),
891
+ Layer.mock(PullRequestService.PullRequestService)({}),
892
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
893
+ resolve: () =>
894
+ Effect.succeed({
895
+ canonicalKey: "github.com/acme/project",
896
+ locator: {
897
+ source: "git-remote" as const,
898
+ remoteName: "origin",
899
+ remoteUrl: "git@github.com:acme/project.git",
900
+ },
901
+ provider: SourceControlProviderKind.make("github"),
902
+ owner: "acme",
903
+ name: "project",
904
+ }),
905
+ }),
906
+ // A connected client keeps the periodic sweep running.
907
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
908
+ shouldRunOpportunisticWork: Effect.succeed(true),
909
+ }),
910
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
911
+ Layer.succeed(
912
+ SecureRandom.SecureRandom,
913
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
914
+ ),
915
+ FileSystem.layerNoop({}),
916
+ Path.layer,
917
+ );
918
+ yield* Effect.gen(function* () {
919
+ const service = yield* ThreadPullRequestService.make;
920
+ yield* service.start();
921
+ yield* Deferred.succeed(activation, undefined);
922
+ yield* Queue.take(sweeps);
923
+ yield* service.drain;
924
+ yield* TestClock.adjust("1 minute");
925
+ yield* Queue.take(sweeps);
926
+ yield* service.drain;
927
+ }).pipe(Effect.provide(dependencies));
928
+
929
+ expect(commands).toEqual([]);
930
+ expect(lookups).toHaveLength(2);
931
+ // GitManager rereads git state on request, and by default whenever its
932
+ // remembered answer is merged or closed.
933
+ expect(
934
+ lookups.filter(
935
+ (options) =>
936
+ options?.refresh === true ||
937
+ options?.freshGitState === true ||
938
+ options?.confirmTerminal !== false,
939
+ ),
940
+ ).toEqual([]);
941
+ }),
942
+ );
943
+
944
+ const mergedPullRequest43 = {
945
+ number: 43,
946
+ title: "Replacement work",
947
+ url: "https://github.com/acme/project/pull/43",
948
+ baseRef: "main",
949
+ headRef: "feature/replaced",
950
+ state: "merged" as const,
951
+ repositoryKey: "github.com/acme/project",
952
+ updatedAt: "2026-09-19T00:00:00.000Z",
953
+ closedAt: null,
954
+ mergedAt: "2026-09-19T00:00:00.000Z",
955
+ };
956
+
957
+ it.effect.each([
958
+ { name: "reopened", fresh: { ...mergedPullRequest43, state: "open" as const }, writes: false },
959
+ { name: "the same merged PR", fresh: mergedPullRequest43, writes: true },
960
+ ])("saves a remembered merged PR only when fresh git state finds $name", ({ fresh, writes }) =>
961
+ Effect.gen(function* () {
962
+ const savedReference = {
963
+ projectId: ProjectId.make("project-1"),
964
+ repository: "acme/project",
965
+ number: 42,
966
+ url: "https://github.com/acme/project/pull/42",
967
+ };
968
+ const thread = {
969
+ ...threadShell("replaced-branch-thread"),
970
+ createdAt: DateTime.makeUnsafe("2026-09-01T00:00:00.000Z"),
971
+ branch: mergedPullRequest43.headRef,
972
+ branchPullRequest: savedReference,
973
+ };
974
+ const project: OrchestrationProjectShell = {
975
+ id: thread.projectId,
976
+ title: "Project",
977
+ workspaceRoot: "/workspace/project",
978
+ defaultModelSelection: null,
979
+ scripts: [],
980
+ createdAt: "2026-08-01T00:00:00.000Z",
981
+ updatedAt: "2026-08-01T00:00:00.000Z",
982
+ };
983
+ const activation = yield* Deferred.make<void>();
984
+ const sweeps = yield* Queue.unbounded<void>();
985
+ const commands: Array<OrchestrationV2ServerCommand> = [];
986
+ const dependencies = Layer.mergeAll(
987
+ Layer.mock(Orchestrator.OrchestratorV2)({
988
+ streamDomainEvents: Stream.never,
989
+ getPullRequestSnapshot: () =>
990
+ Queue.offer(sweeps, undefined).pipe(
991
+ Effect.as({
992
+ schemaVersion: 2,
993
+ snapshotSequence: 1,
994
+ threads: [thread],
995
+ archivedThreads: [],
996
+ }),
997
+ ),
998
+ dispatch: (command) =>
999
+ Effect.sync(() => {
1000
+ commands.push(command);
1001
+ return { sequence: 2, storedEvents: [] };
1002
+ }),
1003
+ }),
1004
+ Layer.mock(ProjectStore.ProjectStoreV2)({
1005
+ listShells: () => Effect.succeed([project]),
1006
+ getShell: () => Effect.succeedSome(project),
1007
+ }),
1008
+ // Only the fresh read disagrees with the remembered detection.
1009
+ Layer.mock(GitManager.GitManager)({
1010
+ branchPullRequest: (_input, options) =>
1011
+ Effect.succeed(options?.freshGitState === true ? fresh : mergedPullRequest43),
1012
+ }),
1013
+ Layer.mock(PullRequestService.PullRequestService)({}),
1014
+ Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
1015
+ resolve: () =>
1016
+ Effect.succeed({
1017
+ canonicalKey: "github.com/acme/project",
1018
+ locator: {
1019
+ source: "git-remote" as const,
1020
+ remoteName: "origin",
1021
+ remoteUrl: "git@github.com:acme/project.git",
1022
+ },
1023
+ provider: SourceControlProviderKind.make("github"),
1024
+ owner: "acme",
1025
+ name: "project",
1026
+ }),
1027
+ }),
1028
+ Layer.mock(BackgroundPolicy.BackgroundPolicy)({
1029
+ shouldRunOpportunisticWork: Effect.succeed(true),
1030
+ }),
1031
+ Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
1032
+ Layer.succeed(
1033
+ SecureRandom.SecureRandom,
1034
+ SecureRandom.make((size) => new Uint8Array(size).fill(1)),
1035
+ ),
1036
+ FileSystem.layerNoop({}),
1037
+ Path.layer,
1038
+ );
1039
+ yield* Effect.gen(function* () {
1040
+ const service = yield* ThreadPullRequestService.make;
1041
+ yield* service.start();
1042
+ yield* Deferred.succeed(activation, undefined);
1043
+ yield* Queue.take(sweeps);
1044
+ yield* service.drain;
1045
+ }).pipe(Effect.provide(dependencies));
1046
+
1047
+ expect(
1048
+ commands.map((command) =>
1049
+ command.type === "thread.pull-request.sync" ? command.branchPullRequest : command.type,
1050
+ ),
1051
+ ).toEqual(
1052
+ writes
1053
+ ? [
1054
+ {
1055
+ projectId: project.id,
1056
+ repository: "acme/project",
1057
+ number: 43,
1058
+ url: mergedPullRequest43.url,
1059
+ },
1060
+ ]
1061
+ : [],
1062
+ );
1063
+ }),
1064
);
1065
});
apps/server/src/orchestration-v2/ThreadSettlementService.test.ts
+1035
-1094
@@ -843,1042 +843,868 @@ const settledEvent = (thread: OrchestrationV2AppThread): OrchestrationV2DomainEv
843
844
describe("ThreadSettlementServiceV2 worker", () => {
845
it.effect("skips settings and PR decisions for recent branchless threads", () =>
846
- Effect.scoped(
847
- Effect.gen(function* () {
848
- yield* TestClock.setTime(Date.parse(NOW));
849
- const threads = Array.from({ length: 32 }, (_, index) =>
850
- makeThread(`recent-${index}`, {
851
- updatedAt: DateTime.makeUnsafe(NOW),
852
- latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS),
853
- }),
846
+ Effect.gen(function* () {
847
+ yield* TestClock.setTime(Date.parse(NOW));
848
+ const threads = Array.from({ length: 32 }, (_, index) =>
849
+ makeThread(`recent-${index}`, {
850
+ updatedAt: DateTime.makeUnsafe(NOW),
851
+ latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS),
852
+ }),
853
+ );
854
+ const fixture = yield* makeHarness({
855
+ snapshot: makeSnapshot(threads),
856
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
857
+ });
858
+ yield* Effect.gen(function* () {
859
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
860
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
861
+ assert.deepEqual(yield* Ref.get(fixture.commands), []);
862
+ assert.deepEqual(yield* Ref.get(fixture.branchCalls), []);
863
+ assert.equal(yield* Ref.get(fixture.settingsReadCount), 2);
864
+ yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
865
+ yield* Queue.take(fixture.snapshotReads);
866
+ yield* service.drain;
867
+ assert.deepEqual(
868
+ new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
869
+ new Set(threads.map((thread) => thread.id)),
870
);
855
- const fixture = yield* makeHarness({
856
- snapshot: makeSnapshot(threads),
857
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
858
- });
859
- yield* Effect.gen(function* () {
860
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
861
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
862
- assert.deepEqual(yield* Ref.get(fixture.commands), []);
863
- assert.deepEqual(yield* Ref.get(fixture.branchCalls), []);
864
- assert.equal(yield* Ref.get(fixture.settingsReadCount), 2);
865
- yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 });
866
- yield* Queue.take(fixture.snapshotReads);
867
- yield* service.drain;
868
- assert.deepEqual(
869
- new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)),
870
- new Set(threads.map((thread) => thread.id)),
871
- );
872
- }).pipe(Effect.provide(fixture.layer));
873
- }),
874
- ),
871
+ }).pipe(Effect.provide(fixture.layer));
872
+ }),
873
);
874
it.effect("settles a merged pull request stored only in the thread links", () =>
877
- Effect.scoped(
875
+ Effect.gen(function* () {
876
+ yield* TestClock.setTime(Date.parse(NOW));
877
+ const thread = makeThread("merged-link", {
878
+ pullRequests: [
879
+ {
880
+ host: "example.test",
881
+ repository: "owner/repository",
882
+ number: 42,
883
+ url: "https://example.test/owner/repository/pull/42",
884
+ source: "manual",
885
+ linkedAt: "2026-08-20T00:00:00.000Z",
886
+ snapshot: {
887
+ state: "merged",
888
+ title: "Pull request",
889
+ headBranch: "feature",
890
+ baseBranch: "main",
891
+ isDraft: false,
892
+ updatedAt: NOW,
893
+ syncedAt: NOW,
894
+ mergedAt: NOW,
895
+ },
896
+ stack: null,
897
+ },
898
+ ],
899
+ });
900
+ const fixture = yield* makeHarness({
901
+ snapshot: makeSnapshot([thread]),
902
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
903
+ });
904
+
905
+ yield* Effect.gen(function* () {
906
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
907
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
908
+ expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
909
+ thread.id,
910
+ ]);
911
+ }).pipe(Effect.provide(fixture.layer));
912
+ }),
913
+ );
914
+
915
+ it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
916
+ Effect.gen(function* () {
917
+ yield* TestClock.setTime(Date.parse(NOW));
918
+ const thread = makeThread("open-link", {
919
+ pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
920
+ });
921
+ const fixture = yield* makeHarness({
922
+ snapshot: makeSnapshot([thread]),
923
+ settings: {
924
+ ...DEFAULT_SERVER_SETTINGS,
925
+ sidebarAutoSettleAfterDays: 3,
926
+ sidebarAutoSettleKeepPullRequests: false,
927
+ },
928
+ });
929
+ yield* Effect.gen(function* () {
930
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
931
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
932
+ expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
933
+ thread.id,
934
+ ]);
935
+ }).pipe(Effect.provide(fixture.layer));
936
+ }),
937
+ );
938
+
939
+ it.effect("settles only the project opted in while environment settlement is disabled", () =>
940
+ Effect.gen(function* () {
941
+ yield* TestClock.setTime(Date.parse(NOW));
942
+ const thread = makeThread("project-opt-in", {
943
+ latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
944
+ });
945
+ const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
946
+ const fixture = yield* makeHarness({
947
+ snapshot: makeSnapshot([thread, other]),
948
+ settings: {
949
+ ...DEFAULT_SERVER_SETTINGS,
950
+ sidebarAutoSettleAfterDays: null,
951
+ sidebarAutoSettleOnMerge: false,
952
+ projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
953
+ },
954
+ });
955
+ yield* Effect.gen(function* () {
956
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
957
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
958
+ const commands = yield* Ref.get(fixture.commands);
959
+ expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
960
+ }).pipe(Effect.provide(fixture.layer));
961
+ }),
962
+ );
963
+
964
+ it.effect("stops settling the rest of a sweep once auto-settlement is turned off", () =>
965
+ Effect.gen(function* () {
966
+ yield* TestClock.setTime(Date.parse(NOW));
967
+ // Sweeps settle 8 threads at a time, so the ninth starts after a dispatch turned it off.
968
+ const threads = Array.from({ length: 9 }, (_, index) => makeThread(`idle-${index}`));
969
+ let disable: Effect.Effect<unknown> = Effect.void;
970
+ const fixture = yield* makeHarness({
971
+ snapshot: makeSnapshot(threads),
972
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
973
+ onDispatch: () => disable,
974
+ });
975
+ disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
976
+ yield* Effect.gen(function* () {
977
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
978
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
979
+ const settled = (yield* Ref.get(fixture.commands)).map((command) => command.threadId);
980
+ expect(settled).not.toContain(threads[8]!.id);
981
+ }).pipe(Effect.provide(fixture.layer));
982
+ }),
983
+ );
984
+
985
+ it.effect(
986
+ "drains idle subagents of a settled parent and retries busy children without PR lookups",
987
+ () =>
988
Effect.gen(function* () {
989
yield* TestClock.setTime(Date.parse(NOW));
880
- const thread = makeThread("merged-link", {
881
- pullRequests: [
882
- {
883
- host: "example.test",
884
- repository: "owner/repository",
885
- number: 42,
886
- url: "https://example.test/owner/repository/pull/42",
887
- source: "manual",
888
- linkedAt: "2026-08-20T00:00:00.000Z",
889
- snapshot: {
890
- state: "merged",
891
- title: "Pull request",
892
- headBranch: "feature",
893
- baseBranch: "main",
894
- isDraft: false,
895
- updatedAt: NOW,
896
- syncedAt: NOW,
897
- mergedAt: NOW,
898
- },
899
- stack: null,
900
- },
901
- ],
990
+ const store = yield* ProjectionStore.ProjectionStoreV2;
991
+ const parent = appThread("subagent-parent", "settled");
992
+ const child = (id: string, overrides: Partial<OrchestrationV2AppThread> = {}) => ({
993
+ ...appThread(id, null),
994
+ branch: "feature",
995
+ lineage: {
996
+ rootThreadId: parent.id,
997
+ parentThreadId: parent.id,
998
+ relationshipToParent: "subagent" as const,
999
+ },
1000
+ ...overrides,
1001
+ });
1002
+ const empty = child("empty");
1003
+ const recent = child("recent");
1004
+ const busy = child("busy");
1005
+ const marker = appThread("marker", "settled");
1006
+ for (const thread of [
1007
+ parent,
1008
+ empty,
1009
+ recent,
1010
+ busy,
1011
+ marker,
1012
+ child("pinned", { pinnedAt: DateTime.makeUnsafe(NOW) }),
1013
+ child("opted-out", { autoSettleDisabledAt: DateTime.makeUnsafe(NOW) }),
1014
+ ]) {
1015
+ yield* store.apply({
1016
+ type: "thread.created",
1017
+ id: EventId.make(`created:${thread.id}`),
1018
+ threadId: thread.id,
1019
+ occurredAt: thread.createdAt,
1020
+ payload: thread,
1021
+ });
1022
+ }
1023
+ const run = (threadId: ThreadId, status: "running" | "completed"): OrchestrationV2Run => ({
1024
+ id: RunId.make(`run:${threadId}`),
1025
+ threadId,
1026
+ ordinal: 1,
1027
+ providerInstanceId: parent.providerInstanceId,
1028
+ modelSelection: parent.modelSelection,
1029
+ providerThreadId: null,
1030
+ userMessageId: MessageId.make(`message:${threadId}`),
1031
+ rootNodeId: null,
1032
+ activeAttemptId: null,
1033
+ status,
1034
+ requestedAt: DateTime.makeUnsafe(NOW),
1035
+ startedAt: DateTime.makeUnsafe(NOW),
1036
+ completedAt: status === "completed" ? DateTime.makeUnsafe(NOW) : null,
1037
+ checkpointId: null,
1038
+ contextHandoffId: null,
1039
});
1040
+ for (const payload of [run(recent.id, "completed"), run(busy.id, "running")]) {
1041
+ yield* store.apply({
1042
+ type: "run.created",
1043
+ id: EventId.make(`created:${payload.id}`),
1044
+ threadId: payload.threadId,
1045
+ occurredAt: DateTime.makeUnsafe(NOW),
1046
+ payload,
1047
+ });
1048
+ }
1049
const fixture = yield* makeHarness({
904
- snapshot: makeSnapshot([thread]),
905
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1050
+ snapshot: makeSnapshot([]),
1051
+ projections: store,
1052
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1053
+ onDispatch: (command) =>
1054
+ store.getThread(command.threadId).pipe(
1055
+ Effect.flatMap((thread) =>
1056
+ store.apply(
1057
+ settledEvent({
1058
+ ...thread,
1059
+ settledOverride: "settled",
1060
+ settledAt: DateTime.makeUnsafe(NOW),
1061
+ }),
1062
+ ),
1063
+ ),
1064
+ Effect.orDie,
1065
+ ),
1066
});
907
-
1067
yield* Effect.gen(function* () {
1068
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1069
yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1070
+ const commands = yield* Ref.get(fixture.commands);
1071
+ expect(commands.map((command) => command.threadId).toSorted()).toEqual([
1072
+ empty.id,
1073
+ recent.id,
1074
+ ]);
1075
+ for (const command of commands) {
1076
+ expect(command.snapshotAt).toEqual(DateTime.makeUnsafe(NOW));
1077
+ expect(command.settledAt).toBeUndefined();
1078
+ }
1079
+ const finished: OrchestrationV2DomainEvent = {
1080
+ type: "run.updated",
1081
+ id: EventId.make("busy:completed"),
1082
+ threadId: busy.id,
1083
+ occurredAt: DateTime.makeUnsafe(NOW),
1084
+ payload: run(busy.id, "completed"),
1085
+ };
1086
+ yield* store.apply(finished);
1087
+ yield* fixture.publishEvent(finished);
1088
+ // Cleanup of the following event marks delivery of the run event before draining.
1089
+ yield* fixture.publishEvent(settledEvent(marker));
1090
+ expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1091
+ yield* service.drain;
1092
expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
912
- thread.id,
1093
+ empty.id,
1094
+ recent.id,
1095
+ busy.id,
1096
]);
1097
+ expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1098
+ expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1099
}).pipe(Effect.provide(fixture.layer));
915
- }),
916
- ),
1100
+ }).pipe(Effect.provide(projectionStoreSql)),
1101
);
1102
919
- it.effect("settles an idle thread with an open persisted link on the inactivity sweep", () =>
920
- Effect.scoped(
1103
+ it.effect(
1104
+ "manual parent settlement drains hidden children with automatic settlement disabled",
1105
+ () =>
1106
Effect.gen(function* () {
1107
yield* TestClock.setTime(Date.parse(NOW));
923
- const thread = makeThread("open-link", {
924
- pullRequests: [persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z"))],
925
- });
926
- const fixture = yield* makeHarness({
927
- snapshot: makeSnapshot([thread]),
928
- settings: {
929
- ...DEFAULT_SERVER_SETTINGS,
930
- sidebarAutoSettleAfterDays: 3,
931
- sidebarAutoSettleKeepPullRequests: false,
1108
+ const store = yield* ProjectionStore.ProjectionStoreV2;
1109
+ const parent = appThread("manual-parent", null);
1110
+ const child = {
1111
+ ...appThread("manual-child", null),
1112
+ branch: "feature",
1113
+ lineage: {
1114
+ rootThreadId: parent.id,
1115
+ parentThreadId: parent.id,
1116
+ relationshipToParent: "subagent" as const,
1117
},
1118
+ };
1119
+ const marker = appThread("marker", "settled");
1120
+ for (const thread of [parent, child, marker]) {
1121
+ yield* store.apply({
1122
+ type: "thread.created",
1123
+ id: EventId.make(`created:${thread.id}`),
1124
+ threadId: thread.id,
1125
+ occurredAt: thread.createdAt,
1126
+ payload: thread,
1127
+ });
1128
+ }
1129
+ const fixture = yield* makeHarness({
1130
+ snapshot: makeSnapshot([]),
1131
+ projections: store,
1132
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1133
+ onDispatch: (command) =>
1134
+ store.getThread(command.threadId).pipe(
1135
+ Effect.flatMap((thread) =>
1136
+ store.apply(
1137
+ settledEvent({
1138
+ ...thread,
1139
+ settledOverride: "settled",
1140
+ settledAt: DateTime.makeUnsafe(NOW),
1141
+ }),
1142
+ ),
1143
+ ),
1144
+ Effect.orDie,
1145
+ ),
1146
});
1147
yield* Effect.gen(function* () {
1148
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1149
yield* startHarness(service, fixture.activation, fixture.snapshotReads);
937
- expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
938
- thread.id,
1150
+ expect(yield* Ref.get(fixture.commands)).toEqual([]);
1151
+ expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1152
+ // Avoid a settings-change sweep: the parent event must trigger the child dispatch.
1153
+ yield* Ref.set(fixture.settings, {
1154
+ ...DEFAULT_SERVER_SETTINGS,
1155
+ sidebarAutoSettleAfterDays: null,
1156
+ sidebarAutoSettleOnMerge: false,
1157
+ });
1158
+ const event = settledEvent({
1159
+ ...parent,
1160
+ settledOverride: "settled",
1161
+ settledAt: DateTime.makeUnsafe(NOW),
1162
+ });
1163
+ yield* store.apply(event);
1164
+ yield* fixture.publishEvent(event);
1165
+ yield* fixture.publishEvent(settledEvent(marker));
1166
+ expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: parent.id });
1167
+ expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1168
+ yield* service.drain;
1169
+ expect(yield* Ref.get(fixture.commands)).toEqual([
1170
+ expect.objectContaining({
1171
+ type: "thread.auto-settle",
1172
+ threadId: child.id,
1173
+ snapshotAt: child.updatedAt,
1174
+ }),
1175
]);
1176
+ expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1177
+ expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1178
}).pipe(Effect.provide(fixture.layer));
941
- }),
942
- ),
1179
+ }).pipe(Effect.provide(projectionStoreSql)),
1180
);
1181
945
- it.effect("settles only the project opted in while environment settlement is disabled", () =>
946
- Effect.scoped(
1182
+ it.effect(
1183
+ "coalesces bulk cleanup wakes and still drains children discovered during a sweep",
1184
+ () =>
1185
Effect.gen(function* () {
1186
yield* TestClock.setTime(Date.parse(NOW));
949
- const thread = makeThread("project-opt-in", {
950
- latestRunCompletedAt: DateTime.makeUnsafe("2026-08-25T00:00:00.000Z"),
951
- });
952
- const other = makeThread("environment-off", { projectId: ProjectId.make("other-project") });
1187
+ const store = yield* ProjectionStore.ProjectionStoreV2;
1188
+ const sweepStarted = yield* Deferred.make<void>();
1189
+ const releaseSweep = yield* Deferred.make<void>();
1190
+ const childSettled = yield* Deferred.make<void>();
1191
+ const parent = appThread("bulk-parent", null);
1192
+ const child = {
1193
+ ...appThread("bulk-child", null),
1194
+ lineage: {
1195
+ parentThreadId: parent.id,
1196
+ rootThreadId: parent.id,
1197
+ relationshipToParent: "subagent" as const,
1198
+ },
1199
+ };
1200
+ const marker = appThread("bulk-marker", "settled");
1201
+ const parents = [
1202
+ parent,
1203
+ ...Array.from({ length: 233 }, (_, i) => appThread(`bulk-parent-${i}`, null)),
1204
+ ];
1205
+ for (const thread of [...parents, child, marker]) {
1206
+ yield* store.apply({
1207
+ type: "thread.created",
1208
+ id: EventId.make(`created:${thread.id}`),
1209
+ threadId: thread.id,
1210
+ occurredAt: thread.createdAt,
1211
+ payload: thread,
1212
+ });
1213
+ }
1214
+ let blockNextSweep = false;
1215
const fixture = yield* makeHarness({
954
- snapshot: makeSnapshot([thread, other]),
1216
+ snapshot: makeSnapshot([]),
1217
settings: {
1218
...DEFAULT_SERVER_SETTINGS,
1219
sidebarAutoSettleAfterDays: null,
1220
sidebarAutoSettleOnMerge: false,
959
- projectSettingsOverrides: { [PROJECT_ID]: { sidebarAutoSettleAfterDays: 2 } },
1221
},
1222
+ projections: {
1223
+ ...store,
1224
+ getSettlementCandidates: (threadId) =>
1225
+ Effect.gen(function* () {
1226
+ const candidates = yield* store.getSettlementCandidates(threadId);
1227
+ if (blockNextSweep) {
1228
+ blockNextSweep = false;
1229
+ yield* Deferred.succeed(sweepStarted, undefined);
1230
+ yield* Deferred.await(releaseSweep);
1231
+ }
1232
+ return candidates;
1233
+ }),
1234
+ },
1235
+ onDispatch: (command): Effect.Effect<void> =>
1236
+ Effect.gen(function* () {
1237
+ const thread = yield* store.getThread(command.threadId);
1238
+ const event = settledEvent({
1239
+ ...thread,
1240
+ settledOverride: "settled",
1241
+ settledAt: DateTime.makeUnsafe(NOW),
1242
+ });
1243
+ yield* store.apply(event);
1244
+ yield* fixture.publishEvent(event);
1245
+ yield* Deferred.succeed(childSettled, undefined);
1246
+ }).pipe(Effect.orDie),
1247
});
1248
yield* Effect.gen(function* () {
1249
const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1250
yield* startHarness(service, fixture.activation, fixture.snapshotReads);
965
- const commands = yield* Ref.get(fixture.commands);
966
- expect(commands.map((command) => command.threadId)).toEqual([thread.id]);
967
- }).pipe(Effect.provide(fixture.layer));
968
- }),
969
- ),
970
- );
971
-
972
- it.effect("stops settling the rest of a sweep once auto-settlement is turned off", () =>
973
- Effect.scoped(
974
- Effect.gen(function* () {
975
- yield* TestClock.setTime(Date.parse(NOW));
976
- // Sweeps settle 8 threads at a time, so the ninth starts after a dispatch turned it off.
977
- const threads = Array.from({ length: 9 }, (_, index) => makeThread(`idle-${index}`));
978
- let disable: Effect.Effect<unknown> = Effect.void;
979
- const fixture = yield* makeHarness({
980
- snapshot: makeSnapshot(threads),
981
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 },
982
- onDispatch: () => disable,
983
- });
984
- disable = fixture.updateSettings({ sidebarAutoSettleAfterDays: null });
985
- yield* Effect.gen(function* () {
986
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
987
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
988
- const settled = (yield* Ref.get(fixture.commands)).map((command) => command.threadId);
989
- expect(settled).not.toContain(threads[8]!.id);
990
- }).pipe(Effect.provide(fixture.layer));
991
- }),
992
- ),
993
- );
1251
+ yield* Ref.set(fixture.candidateReads, []);
1252
+ blockNextSweep = true;
1253
+ yield* fixture.publishEvent(settledEvent(marker));
1254
+ yield* Deferred.await(sweepStarted);
1255
995
- it.effect(
996
- "drains idle subagents of a settled parent and retries busy children without PR lookups",
997
- () =>
998
- Effect.scoped(
999
- Effect.gen(function* () {
1000
- yield* TestClock.setTime(Date.parse(NOW));
1001
- const store = yield* ProjectionStore.ProjectionStoreV2;
1002
- const parent = appThread("subagent-parent", "settled");
1003
- const child = (id: string, overrides: Partial<OrchestrationV2AppThread> = {}) => ({
1004
- ...appThread(id, null),
1005
- branch: "feature",
1006
- lineage: {
1007
- rootThreadId: parent.id,
1008
- parentThreadId: parent.id,
1009
- relationshipToParent: "subagent" as const,
1010
- },
1011
- ...overrides,
1012
- });
1013
- const empty = child("empty");
1014
- const recent = child("recent");
1015
- const busy = child("busy");
1016
- const marker = appThread("marker", "settled");
1017
- for (const thread of [
1018
- parent,
1019
- empty,
1020
- recent,
1021
- busy,
1022
- marker,
1023
- child("pinned", { pinnedAt: DateTime.makeUnsafe(NOW) }),
1024
- child("opted-out", { autoSettleDisabledAt: DateTime.makeUnsafe(NOW) }),
1025
- ]) {
1026
- yield* store.apply({
1027
- type: "thread.created",
1028
- id: EventId.make(`created:${thread.id}`),
1256
+ for (const [i, thread] of parents.entries()) {
1257
+ const type = (["thread.settled", "thread.archived", "thread.deleted"] as const)[i % 3]!;
1258
+ const event: OrchestrationV2DomainEvent = {
1259
+ type,
1260
+ id: EventId.make(`bulk:${thread.id}`),
1261
threadId: thread.id,
1030
- occurredAt: thread.createdAt,
1031
- payload: thread,
1032
- });
1033
- }
1034
- const run = (
1035
- threadId: ThreadId,
1036
- status: "running" | "completed",
1037
- ): OrchestrationV2Run => ({
1038
- id: RunId.make(`run:${threadId}`),
1039
- threadId,
1040
- ordinal: 1,
1041
- providerInstanceId: parent.providerInstanceId,
1042
- modelSelection: parent.modelSelection,
1043
- providerThreadId: null,
1044
- userMessageId: MessageId.make(`message:${threadId}`),
1045
- rootNodeId: null,
1046
- activeAttemptId: null,
1047
- status,
1048
- requestedAt: DateTime.makeUnsafe(NOW),
1049
- startedAt: DateTime.makeUnsafe(NOW),
1050
- completedAt: status === "completed" ? DateTime.makeUnsafe(NOW) : null,
1051
- checkpointId: null,
1052
- contextHandoffId: null,
1053
- });
1054
- for (const payload of [run(recent.id, "completed"), run(busy.id, "running")]) {
1055
- yield* store.apply({
1056
- type: "run.created",
1057
- id: EventId.make(`created:${payload.id}`),
1058
- threadId: payload.threadId,
1262
occurredAt: DateTime.makeUnsafe(NOW),
1060
- payload,
1061
- });
1062
- }
1063
- const fixture = yield* makeHarness({
1064
- snapshot: makeSnapshot([]),
1065
- projections: store,
1066
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1067
- onDispatch: (command) =>
1068
- store.getThread(command.threadId).pipe(
1069
- Effect.flatMap((thread) =>
1070
- store.apply(
1071
- settledEvent({
1072
- ...thread,
1073
- settledOverride: "settled",
1074
- settledAt: DateTime.makeUnsafe(NOW),
1075
- }),
1076
- ),
1077
- ),
1078
- Effect.orDie,
1079
- ),
1080
- });
1081
- yield* Effect.gen(function* () {
1082
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1083
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1084
- const commands = yield* Ref.get(fixture.commands);
1085
- expect(commands.map((command) => command.threadId).toSorted()).toEqual([
1086
- empty.id,
1087
- recent.id,
1088
- ]);
1089
- for (const command of commands) {
1090
- expect(command.snapshotAt).toEqual(DateTime.makeUnsafe(NOW));
1091
- expect(command.settledAt).toBeUndefined();
1092
- }
1093
- const finished: OrchestrationV2DomainEvent = {
1094
- type: "run.updated",
1095
- id: EventId.make("busy:completed"),
1096
- threadId: busy.id,
1097
- occurredAt: DateTime.makeUnsafe(NOW),
1098
- payload: run(busy.id, "completed"),
1263
+ payload: {
1264
+ ...thread,
1265
+ ...(type === "thread.settled"
1266
+ ? { settledOverride: "settled" as const, settledAt: DateTime.makeUnsafe(NOW) }
1267
+ : type === "thread.archived"
1268
+ ? { archivedAt: DateTime.makeUnsafe(NOW) }
1269
+ : { deletedAt: DateTime.makeUnsafe(NOW) }),
1270
+ },
1271
};
1100
- yield* store.apply(finished);
1101
- yield* fixture.publishEvent(finished);
1102
- // Cleanup of the following event marks delivery of the run event before draining.
1103
- yield* fixture.publishEvent(settledEvent(marker));
1104
- expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1105
- yield* service.drain;
1106
- expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1107
- empty.id,
1108
- recent.id,
1109
- busy.id,
1110
- ]);
1111
- expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1112
- expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1113
- }).pipe(Effect.provide(fixture.layer));
1114
- }).pipe(Effect.provide(projectionStoreSql)),
1115
- ),
1116
- );
1117
-
1118
- it.effect(
1119
- "manual parent settlement drains hidden children with automatic settlement disabled",
1120
- () =>
1121
- Effect.scoped(
1122
- Effect.gen(function* () {
1123
- yield* TestClock.setTime(Date.parse(NOW));
1124
- const store = yield* ProjectionStore.ProjectionStoreV2;
1125
- const parent = appThread("manual-parent", null);
1126
- const child = {
1127
- ...appThread("manual-child", null),
1128
- branch: "feature",
1129
- lineage: {
1130
- rootThreadId: parent.id,
1131
- parentThreadId: parent.id,
1132
- relationshipToParent: "subagent" as const,
1133
- },
1134
- };
1135
- const marker = appThread("marker", "settled");
1136
- for (const thread of [parent, child, marker]) {
1137
- yield* store.apply({
1138
- type: "thread.created",
1139
- id: EventId.make(`created:${thread.id}`),
1140
- threadId: thread.id,
1141
- occurredAt: thread.createdAt,
1142
- payload: thread,
1143
- });
1144
- }
1145
- const fixture = yield* makeHarness({
1146
- snapshot: makeSnapshot([]),
1147
- projections: store,
1148
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 2 },
1149
- onDispatch: (command) =>
1150
- store.getThread(command.threadId).pipe(
1151
- Effect.flatMap((thread) =>
1152
- store.apply(
1153
- settledEvent({
1154
- ...thread,
1155
- settledOverride: "settled",
1156
- settledAt: DateTime.makeUnsafe(NOW),
1157
- }),
1158
- ),
1159
- ),
1160
- Effect.orDie,
1161
- ),
1162
- });
1163
- yield* Effect.gen(function* () {
1164
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1165
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1166
- expect(yield* Ref.get(fixture.commands)).toEqual([]);
1167
- expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1168
- // Avoid a settings-change sweep: the parent event must trigger the child dispatch.
1169
- yield* Ref.set(fixture.settings, {
1170
- ...DEFAULT_SERVER_SETTINGS,
1171
- sidebarAutoSettleAfterDays: null,
1172
- sidebarAutoSettleOnMerge: false,
1173
- });
1174
- const event = settledEvent({
1175
- ...parent,
1176
- settledOverride: "settled",
1177
- settledAt: DateTime.makeUnsafe(NOW),
1178
- });
1272
yield* store.apply(event);
1273
yield* fixture.publishEvent(event);
1181
- yield* fixture.publishEvent(settledEvent(marker));
1182
- expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: parent.id });
1183
- expect(yield* Queue.take(fixture.closedIdle)).toEqual({ threadId: marker.id });
1184
- yield* service.drain;
1185
- expect(yield* Ref.get(fixture.commands)).toEqual([
1186
- expect.objectContaining({
1187
- type: "thread.auto-settle",
1188
- threadId: child.id,
1189
- snapshotAt: child.updatedAt,
1190
- }),
1191
- ]);
1192
- expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1193
- expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1194
- }).pipe(Effect.provide(fixture.layer));
1195
- }).pipe(Effect.provide(projectionStoreSql)),
1196
- ),
1197
- );
1198
-
1199
- it.effect(
1200
- "coalesces bulk cleanup wakes and still drains children discovered during a sweep",
1201
- () =>
1202
- Effect.scoped(
1203
- Effect.gen(function* () {
1204
- yield* TestClock.setTime(Date.parse(NOW));
1205
- const store = yield* ProjectionStore.ProjectionStoreV2;
1206
- const sweepStarted = yield* Deferred.make<void>();
1207
- const releaseSweep = yield* Deferred.make<void>();
1208
- const childSettled = yield* Deferred.make<void>();
1209
- const parent = appThread("bulk-parent", null);
1210
- const child = {
1211
- ...appThread("bulk-child", null),
1212
- lineage: {
1213
- parentThreadId: parent.id,
1214
- rootThreadId: parent.id,
1215
- relationshipToParent: "subagent" as const,
1216
- },
1217
- };
1218
- const marker = appThread("bulk-marker", "settled");
1219
- const parents = [
1220
- parent,
1221
- ...Array.from({ length: 233 }, (_, i) => appThread(`bulk-parent-${i}`, null)),
1222
- ];
1223
- for (const thread of [...parents, child, marker]) {
1224
- yield* store.apply({
1225
- type: "thread.created",
1226
- id: EventId.make(`created:${thread.id}`),
1227
- threadId: thread.id,
1228
- occurredAt: thread.createdAt,
1229
- payload: thread,
1230
- });
1274
}
1232
- let blockNextSweep = false;
1233
- const fixture = yield* makeHarness({
1234
- snapshot: makeSnapshot([]),
1235
- settings: {
1236
- ...DEFAULT_SERVER_SETTINGS,
1237
- sidebarAutoSettleAfterDays: null,
1238
- sidebarAutoSettleOnMerge: false,
1239
- },
1240
- projections: {
1241
- ...store,
1242
- getSettlementCandidates: (threadId) =>
1243
- Effect.gen(function* () {
1244
- const candidates = yield* store.getSettlementCandidates(threadId);
1245
- if (blockNextSweep) {
1246
- blockNextSweep = false;
1247
- yield* Deferred.succeed(sweepStarted, undefined);
1248
- yield* Deferred.await(releaseSweep);
1249
- }
1250
- return candidates;
1251
- }),
1252
- },
1253
- onDispatch: (command): Effect.Effect<void> =>
1254
- Effect.gen(function* () {
1255
- const thread = yield* store.getThread(command.threadId);
1256
- const event = settledEvent({
1257
- ...thread,
1258
- settledOverride: "settled",
1259
- settledAt: DateTime.makeUnsafe(NOW),
1260
- });
1261
- yield* store.apply(event);
1262
- yield* fixture.publishEvent(event);
1263
- yield* Deferred.succeed(childSettled, undefined);
1264
- }).pipe(Effect.orDie),
1265
- });
1266
- yield* Effect.gen(function* () {
1267
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1268
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1269
- yield* Ref.set(fixture.candidateReads, []);
1270
- blockNextSweep = true;
1271
- yield* fixture.publishEvent(settledEvent(marker));
1272
- yield* Deferred.await(sweepStarted);
1273
-
1274
- for (const [i, thread] of parents.entries()) {
1275
- const type = (["thread.settled", "thread.archived", "thread.deleted"] as const)[
1276
- i % 3
1277
- ]!;
1278
- const event: OrchestrationV2DomainEvent = {
1279
- type,
1280
- id: EventId.make(`bulk:${thread.id}`),
1281
- threadId: thread.id,
1282
- occurredAt: DateTime.makeUnsafe(NOW),
1283
- payload: {
1284
- ...thread,
1285
- ...(type === "thread.settled"
1286
- ? { settledOverride: "settled" as const, settledAt: DateTime.makeUnsafe(NOW) }
1287
- : type === "thread.archived"
1288
- ? { archivedAt: DateTime.makeUnsafe(NOW) }
1289
- : { deletedAt: DateTime.makeUnsafe(NOW) }),
1290
- },
1291
- };
1292
- yield* store.apply(event);
1293
- yield* fixture.publishEvent(event);
1294
- }
1295
- const markDelivery = (id: string) =>
1296
- fixture
1297
- .publishEvent({
1298
- type: "thread.created",
1299
- id: EventId.make(id),
1300
- threadId: marker.id,
1301
- occurredAt: marker.createdAt,
1302
- payload: marker,
1303
- })
1304
- .pipe(
1305
- // The next event is observed only after the previous handler has finished enqueueing.
1306
- Effect.andThen(
1307
- Queue.take(fixture.observedEvents).pipe(
1308
- Effect.repeat({ until: (seen) => seen === id }),
1309
- ),
1275
+ const markDelivery = (id: string) =>
1276
+ fixture
1277
+ .publishEvent({
1278
+ type: "thread.created",
1279
+ id: EventId.make(id),
1280
+ threadId: marker.id,
1281
+ occurredAt: marker.createdAt,
1282
+ payload: marker,
1283
+ })
1284
+ .pipe(
1285
+ // The next event is observed only after the previous handler has finished enqueueing.
1286
+ Effect.andThen(
1287
+ Queue.take(fixture.observedEvents).pipe(
1288
+ Effect.repeat({ until: (seen) => seen === id }),
1289
),
1311
- );
1312
- yield* markDelivery("bulk-delivered");
1313
- yield* Deferred.succeed(releaseSweep, undefined);
1314
- yield* Deferred.await(childSettled);
1315
- yield* markDelivery("child-delivered");
1316
- yield* service.drain;
1317
-
1318
- expect(yield* Ref.get(fixture.candidateReads)).toEqual([
1319
- undefined,
1320
- undefined,
1321
- undefined,
1322
- ]);
1323
- expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1324
- child.id,
1325
- ]);
1326
- expect((yield* store.getThread(child.id)).settledOverride).toBe("settled");
1327
- expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1328
- expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1329
- }).pipe(Effect.provide(fixture.layer));
1330
- }).pipe(Effect.provide(projectionStoreSql)),
1331
- ),
1290
+ ),
1291
+ );
1292
+ yield* markDelivery("bulk-delivered");
1293
+ yield* Deferred.succeed(releaseSweep, undefined);
1294
+ yield* Deferred.await(childSettled);
1295
+ yield* markDelivery("child-delivered");
1296
+ yield* service.drain;
1297
+
1298
+ expect(yield* Ref.get(fixture.candidateReads)).toEqual([undefined, undefined, undefined]);
1299
+ expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1300
+ child.id,
1301
+ ]);
1302
+ expect((yield* store.getThread(child.id)).settledOverride).toBe("settled");
1303
+ expect(yield* Ref.get(fixture.branchCalls)).toEqual([]);
1304
+ expect(yield* Ref.get(fixture.summaryCalls)).toEqual([]);
1305
+ }).pipe(Effect.provide(fixture.layer));
1306
+ }).pipe(Effect.provide(projectionStoreSql)),
1307
);
1308
1309
it.effect("looks up a branch in its worktree only while the worktree has .git", () =>
1335
- Effect.scoped(
1336
- Effect.gen(function* () {
1337
- yield* TestClock.setTime(Date.parse(NOW));
1338
- const fixture = yield* makeHarness({
1339
- snapshot: makeSnapshot([
1340
- makeThread("linked-worktree", {
1341
- branch: "linked",
1342
- worktreePath: "/worktrees/linked",
1343
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1344
- }),
1345
- // A folder that outlived its .git makes git fail with not_a_repository.
1346
- makeThread("emptied-worktree", {
1347
- branch: "emptied",
1348
- worktreePath: "/worktrees/emptied",
1349
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1350
- }),
1351
- ]),
1352
- existingWorktreePaths: [
1353
- "/worktrees/linked",
1354
- "/worktrees/linked/.git",
1355
- "/worktrees/emptied",
1356
- ],
1310
+ Effect.gen(function* () {
1311
+ yield* TestClock.setTime(Date.parse(NOW));
1312
+ const fixture = yield* makeHarness({
1313
+ snapshot: makeSnapshot([
1314
+ makeThread("linked-worktree", {
1315
+ branch: "linked",
1316
+ worktreePath: "/worktrees/linked",
1317
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1318
+ }),
1319
+ // A folder that outlived its .git makes git fail with not_a_repository.
1320
+ makeThread("emptied-worktree", {
1321
+ branch: "emptied",
1322
+ worktreePath: "/worktrees/emptied",
1323
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1324
+ }),
1325
+ ]),
1326
+ existingWorktreePaths: [
1327
+ "/worktrees/linked",
1328
+ "/worktrees/linked/.git",
1329
+ "/worktrees/emptied",
1330
+ ],
1331
+ });
1332
+
1333
+ yield* Effect.gen(function* () {
1334
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1335
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1336
+ const cwdByBranch = Object.fromEntries(
1337
+ (yield* Ref.get(fixture.branchCalls)).map((call) => [call.branch, call.cwd]),
1338
+ );
1339
+ expect(cwdByBranch).toEqual({
1340
+ linked: "/worktrees/linked",
1341
+ emptied: "/workspace/project",
1342
});
1358
-
1359
- yield* Effect.gen(function* () {
1360
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1361
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1362
- const cwdByBranch = Object.fromEntries(
1363
- (yield* Ref.get(fixture.branchCalls)).map((call) => [call.branch, call.cwd]),
1364
- );
1365
- expect(cwdByBranch).toEqual({
1366
- linked: "/worktrees/linked",
1367
- emptied: "/workspace/project",
1368
- });
1369
- }).pipe(Effect.provide(fixture.layer));
1370
- }),
1371
- ),
1343
+ }).pipe(Effect.provide(fixture.layer));
1344
+ }),
1345
);
1346
1347
it.effect("does not settle a thread whose worktree cannot be checked", () =>
1375
- Effect.scoped(
1376
- Effect.gen(function* () {
1377
- yield* TestClock.setTime(Date.parse(NOW));
1378
- const fixture = yield* makeHarness({
1379
- snapshot: makeSnapshot(
1380
- [
1381
- makeThread("unreadable-worktree", {
1382
- branch: "unreadable",
1383
- worktreePath: "/worktrees/unreadable",
1384
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1385
- }),
1386
- // A merged linked pull request still needs the branch recheck before settling.
1387
- makeThread("unreadable-linked-worktree", {
1388
- branch: "feature",
1389
- worktreePath: "/worktrees/unreadable-linked",
1390
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1391
- linkedPullRequest: {
1392
- projectId: PROJECT_ID,
1393
- repository: "owner/repository",
1394
- number: 41,
1395
- url: "https://example.test/owner/repository/pull/41",
1396
- },
1397
- }),
1398
- makeThread("readable-worktree", {
1399
- branch: "readable",
1400
- worktreePath: "/worktrees/readable",
1401
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1402
- }),
1403
- ],
1404
- [
1405
- {
1406
- ...makeProject(),
1407
- repositoryIdentity: {
1408
- canonicalKey: "example.test/owner/repository",
1409
- locator: {
1410
- source: "git-remote",
1411
- remoteName: "origin",
1412
- remoteUrl: "https://example.test/owner/repository.git",
1413
- },
1414
- provider: SourceControlProviderKind.make("github"),
1415
- owner: "owner",
1416
- name: "repository",
1417
- },
1418
- },
1419
- ],
1420
- ),
1421
- existingWorktreePaths: ["/worktrees/readable", "/worktrees/readable/.git"],
1422
- unreadablePaths: ["/worktrees/unreadable/.git", "/worktrees/unreadable-linked/.git"],
1423
- pullRequestSummary: (input) =>
1424
- Effect.succeed({
1425
- ...makePullRequestSummary({ ...input, state: "merged" }),
1426
- mergedAt: NOW,
1348
+ Effect.gen(function* () {
1349
+ yield* TestClock.setTime(Date.parse(NOW));
1350
+ const fixture = yield* makeHarness({
1351
+ snapshot: makeSnapshot(
1352
+ [
1353
+ makeThread("unreadable-worktree", {
1354
+ branch: "unreadable",
1355
+ worktreePath: "/worktrees/unreadable",
1356
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1357
}),
1428
- branchPullRequest: (input) =>
1429
- input.cwd.startsWith("/worktrees/unreadable")
1430
- ? Effect.die(new Error("git: permission denied"))
1431
- : Effect.succeed(makeBranchPullRequest("merged")),
1432
- });
1433
-
1434
- yield* Effect.gen(function* () {
1435
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1436
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1437
- expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1438
- ThreadId.make("readable-worktree"),
1439
- ]);
1440
- }).pipe(Effect.provide(fixture.layer));
1441
- }),
1442
- ),
1443
- );
1444
-
1445
- it.effect("reevaluates immediately after a pull request merge", () =>
1446
- Effect.scoped(
1447
- Effect.gen(function* () {
1448
- yield* TestClock.setTime(Date.parse(NOW));
1449
- const periodicLookupStarted = yield* Deferred.make<void>();
1450
- const releasePeriodicLookup = yield* Deferred.make<void>();
1451
- const mergedThreadSettled = yield* Deferred.make<void>();
1452
- const branchLookupCount = yield* Ref.make(0);
1453
- const fixture = yield* makeHarness({
1454
- snapshot: makeSnapshot([
1455
- makeThread("merged-in-app", {
1358
+ // A merged linked pull request still needs the branch recheck before settling.
1359
+ makeThread("unreadable-linked-worktree", {
1360
+ branch: "feature",
1361
+ worktreePath: "/worktrees/unreadable-linked",
1362
latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1363
linkedPullRequest: {
1364
projectId: PROJECT_ID,
1459
- repository: "Owner/Repository",
1460
- number: 42,
1461
- url: "https://example.test/owner/repository/pull/42",
1365
+ repository: "owner/repository",
1366
+ number: 41,
1367
+ url: "https://example.test/owner/repository/pull/41",
1368
},
1369
}),
1464
- makeThread("slow-periodic-lookup", {
1465
- branch: "another-feature",
1370
+ makeThread("readable-worktree", {
1371
+ branch: "readable",
1372
+ worktreePath: "/worktrees/readable",
1373
latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1374
}),
1468
- ]),
1469
- branchPullRequest: () =>
1470
- Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1471
- Effect.flatMap((count) =>
1472
- count === 1
1473
- ? Effect.succeed(makeBranchPullRequest("open"))
1474
- : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1475
- Effect.andThen(Deferred.await(releasePeriodicLookup)),
1476
- Effect.as(makeBranchPullRequest("open")),
1477
- ),
1478
- ),
1479
- ),
1480
- onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1481
- });
1482
-
1483
- yield* Effect.gen(function* () {
1484
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1485
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1486
- yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1487
- yield* Deferred.await(periodicLookupStarted);
1488
-
1489
- yield* fixture.publishMerge;
1490
- yield* Deferred.await(mergedThreadSettled);
1491
-
1492
- assert.deepStrictEqual(
1493
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1494
- [ThreadId.make("merged-in-app")],
1495
- );
1496
- yield* Deferred.succeed(releasePeriodicLookup, undefined);
1497
- yield* reactor.drain;
1498
- }).pipe(Effect.provide(fixture.layer));
1499
- }),
1500
- ),
1375
+ ],
1376
+ [
1377
+ {
1378
+ ...makeProject(),
1379
+ repositoryIdentity: {
1380
+ canonicalKey: "example.test/owner/repository",
1381
+ locator: {
1382
+ source: "git-remote",
1383
+ remoteName: "origin",
1384
+ remoteUrl: "https://example.test/owner/repository.git",
1385
+ },
1386
+ provider: SourceControlProviderKind.make("github"),
1387
+ owner: "owner",
1388
+ name: "repository",
1389
+ },
1390
+ },
1391
+ ],
1392
+ ),
1393
+ existingWorktreePaths: ["/worktrees/readable", "/worktrees/readable/.git"],
1394
+ unreadablePaths: ["/worktrees/unreadable/.git", "/worktrees/unreadable-linked/.git"],
1395
+ pullRequestSummary: (input) =>
1396
+ Effect.succeed({
1397
+ ...makePullRequestSummary({ ...input, state: "merged" }),
1398
+ mergedAt: NOW,
1399
+ }),
1400
+ branchPullRequest: (input) =>
1401
+ input.cwd.startsWith("/worktrees/unreadable")
1402
+ ? Effect.die(new Error("git: permission denied"))
1403
+ : Effect.succeed(makeBranchPullRequest("merged")),
1404
+ });
1405
+
1406
+ yield* Effect.gen(function* () {
1407
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1408
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1409
+ expect((yield* Ref.get(fixture.commands)).map((command) => command.threadId)).toEqual([
1410
+ ThreadId.make("readable-worktree"),
1411
+ ]);
1412
+ }).pipe(Effect.provide(fixture.layer));
1413
+ }),
1414
);
1415
1503
- it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
1504
- Effect.scoped(
1505
- Effect.gen(function* () {
1506
- yield* TestClock.setTime(Date.parse(NOW));
1507
- const periodicLookupStarted = yield* Deferred.make<void>();
1508
- const releasePeriodicLookup = yield* Deferred.make<void>();
1509
- const settled = yield* Deferred.make<void>();
1510
- const branchLookupCount = yield* Ref.make(0);
1511
- const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
1512
- ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
1513
- snapshot: {
1514
- state: "merged",
1515
- title: "Pull request",
1516
- headBranch: "feature",
1517
- baseBranch: "main",
1518
- isDraft: false,
1519
- updatedAt: NOW,
1520
- syncedAt: NOW,
1521
- mergedAt: NOW,
1522
- },
1523
- };
1524
- const waiting = makeThread("waiting-on-subagent", {
1525
- pullRequests: [mergedLink],
1526
- pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1527
- });
1528
- const slow = makeThread("slow-periodic-lookup", {
1529
- branch: "another-feature",
1530
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1531
- });
1532
- const fixture = yield* makeHarness({
1533
- snapshot: makeSnapshot([waiting, slow]),
1534
- branchPullRequest: () =>
1535
- Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1536
- Effect.flatMap((count) =>
1537
- count === 1
1538
- ? Effect.succeed(makeBranchPullRequest("open"))
1539
- : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1540
- Effect.andThen(Deferred.await(releasePeriodicLookup)),
1541
- Effect.as(makeBranchPullRequest("open")),
1542
- ),
1543
- ),
1416
+ it.effect("reevaluates immediately after a pull request merge", () =>
1417
+ Effect.gen(function* () {
1418
+ yield* TestClock.setTime(Date.parse(NOW));
1419
+ const periodicLookupStarted = yield* Deferred.make<void>();
1420
+ const releasePeriodicLookup = yield* Deferred.make<void>();
1421
+ const mergedThreadSettled = yield* Deferred.make<void>();
1422
+ const branchLookupCount = yield* Ref.make(0);
1423
+ const fixture = yield* makeHarness({
1424
+ snapshot: makeSnapshot([
1425
+ makeThread("merged-in-app", {
1426
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1427
+ linkedPullRequest: {
1428
+ projectId: PROJECT_ID,
1429
+ repository: "Owner/Repository",
1430
+ number: 42,
1431
+ url: "https://example.test/owner/repository/pull/42",
1432
+ },
1433
+ }),
1434
+ makeThread("slow-periodic-lookup", {
1435
+ branch: "another-feature",
1436
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1437
+ }),
1438
+ ]),
1439
+ branchPullRequest: () =>
1440
+ Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1441
+ Effect.flatMap((count) =>
1442
+ count === 1
1443
+ ? Effect.succeed(makeBranchPullRequest("open"))
1444
+ : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1445
+ Effect.andThen(Deferred.await(releasePeriodicLookup)),
1446
+ Effect.as(makeBranchPullRequest("open")),
1447
+ ),
1448
),
1545
- onDispatch: () => Deferred.succeed(settled, undefined),
1546
- });
1449
+ ),
1450
+ onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1451
+ });
1452
1548
- yield* Effect.gen(function* () {
1549
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1550
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1551
- assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1552
- yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1553
- yield* Deferred.await(periodicLookupStarted);
1453
+ yield* Effect.gen(function* () {
1454
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1455
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1456
+ yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1457
+ yield* Deferred.await(periodicLookupStarted);
1458
1555
- yield* Ref.set(
1556
- fixture.snapshots,
1557
- makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
1558
- );
1559
- yield* fixture.publishEvent({
1560
- type: "run.background-work-cancelled",
1561
- id: EventId.make("event:background-ended"),
1562
- threadId: waiting.id,
1563
- occurredAt: DateTime.makeUnsafe(NOW),
1564
- payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
1565
- });
1566
- yield* Deferred.await(settled);
1459
+ yield* fixture.publishMerge;
1460
+ yield* Deferred.await(mergedThreadSettled);
1461
1568
- assert.deepStrictEqual(
1569
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1570
- [waiting.id],
1571
- );
1572
- yield* Deferred.succeed(releasePeriodicLookup, undefined);
1573
- yield* reactor.drain;
1574
- }).pipe(Effect.provide(fixture.layer));
1575
- }),
1576
- ),
1462
+ assert.deepStrictEqual(
1463
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1464
+ [ThreadId.make("merged-in-app")],
1465
+ );
1466
+ yield* Deferred.succeed(releasePeriodicLookup, undefined);
1467
+ yield* reactor.drain;
1468
+ }).pipe(Effect.provide(fixture.layer));
1469
+ }),
1470
);
1471
1579
- it.effect("settles a stopped thread while another thread's lookup is slow", () =>
1580
- Effect.scoped(
1581
- Effect.gen(function* () {
1582
- yield* TestClock.setTime(Date.parse(NOW));
1583
- const slowLookupStarted = yield* Deferred.make<void>();
1584
- const releaseSlowLookup = yield* Deferred.make<void>();
1585
- const settled = yield* Deferred.make<void>();
1586
- const branchLookupCount = yield* Ref.make(0);
1587
- const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
1588
- const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
1589
- const merged = makeThread("merged", {
1590
- latestUserMessageAt: recent,
1591
- pullRequests: [
1592
- {
1593
- ...persistedLink("open", recent),
1594
- snapshot: {
1595
- state: "merged",
1596
- title: "Pull request",
1597
- headBranch: "feature",
1598
- baseBranch: "main",
1599
- isDraft: false,
1600
- updatedAt: NOW,
1601
- syncedAt: NOW,
1602
- mergedAt: NOW,
1603
- },
1604
- },
1605
- ],
1606
- pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1607
- });
1608
- const fixture = yield* makeHarness({
1609
- snapshot: makeSnapshot([slow, merged]),
1610
- branchPullRequest: () =>
1611
- Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1612
- Effect.flatMap((count) =>
1613
- count === 1
1614
- ? Effect.succeed(makeBranchPullRequest("open"))
1615
- : Deferred.succeed(slowLookupStarted, undefined).pipe(
1616
- Effect.andThen(Deferred.await(releaseSlowLookup)),
1617
- Effect.as(makeBranchPullRequest("open")),
1618
- ),
1619
- ),
1472
+ it.effect("settles a merged thread when its background work ends, during a slow full sweep", () =>
1473
+ Effect.gen(function* () {
1474
+ yield* TestClock.setTime(Date.parse(NOW));
1475
+ const periodicLookupStarted = yield* Deferred.make<void>();
1476
+ const releasePeriodicLookup = yield* Deferred.make<void>();
1477
+ const settled = yield* Deferred.make<void>();
1478
+ const branchLookupCount = yield* Ref.make(0);
1479
+ const mergedLink: NonNullable<SettlementShell["pullRequests"]>[number] = {
1480
+ ...persistedLink("open", DateTime.makeUnsafe("2026-08-20T00:00:00.000Z")),
1481
+ snapshot: {
1482
+ state: "merged",
1483
+ title: "Pull request",
1484
+ headBranch: "feature",
1485
+ baseBranch: "main",
1486
+ isDraft: false,
1487
+ updatedAt: NOW,
1488
+ syncedAt: NOW,
1489
+ mergedAt: NOW,
1490
+ },
1491
+ };
1492
+ const waiting = makeThread("waiting-on-subagent", {
1493
+ pullRequests: [mergedLink],
1494
+ pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1495
+ });
1496
+ const slow = makeThread("slow-periodic-lookup", {
1497
+ branch: "another-feature",
1498
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1499
+ });
1500
+ const fixture = yield* makeHarness({
1501
+ snapshot: makeSnapshot([waiting, slow]),
1502
+ branchPullRequest: () =>
1503
+ Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1504
+ Effect.flatMap((count) =>
1505
+ count === 1
1506
+ ? Effect.succeed(makeBranchPullRequest("open"))
1507
+ : Deferred.succeed(periodicLookupStarted, undefined).pipe(
1508
+ Effect.andThen(Deferred.await(releasePeriodicLookup)),
1509
+ Effect.as(makeBranchPullRequest("open")),
1510
+ ),
1511
),
1621
- onDispatch: () => Deferred.succeed(settled, undefined),
1622
- });
1623
- const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1512
+ ),
1513
+ onDispatch: () => Deferred.succeed(settled, undefined),
1514
+ });
1515
+
1516
+ yield* Effect.gen(function* () {
1517
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1518
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1519
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1520
+ yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 4 });
1521
+ yield* Deferred.await(periodicLookupStarted);
1522
+
1523
+ yield* Ref.set(
1524
+ fixture.snapshots,
1525
+ makeSnapshot([{ ...waiting, pendingBackgroundTasks: [] }, slow]),
1526
+ );
1527
+ yield* fixture.publishEvent({
1528
type: "run.background-work-cancelled",
1625
- id: EventId.make(`event:background-ended:${threadId}`),
1626
- threadId,
1529
+ id: EventId.make("event:background-ended"),
1530
+ threadId: waiting.id,
1531
occurredAt: DateTime.makeUnsafe(NOW),
1628
- payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1532
+ payload: { runId: RunId.make("run:waiting"), restartCancelledBackgroundWork: [] },
1533
});
1534
+ yield* Deferred.await(settled);
1535
1631
- yield* Effect.gen(function* () {
1632
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1633
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1536
+ assert.deepStrictEqual(
1537
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1538
+ [waiting.id],
1539
+ );
1540
+ yield* Deferred.succeed(releasePeriodicLookup, undefined);
1541
+ yield* reactor.drain;
1542
+ }).pipe(Effect.provide(fixture.layer));
1543
+ }),
1544
+ );
1545
+
1546
+ it.effect("settles a stopped thread while another thread's lookup is slow", () =>
1547
+ Effect.gen(function* () {
1548
+ yield* TestClock.setTime(Date.parse(NOW));
1549
+ const slowLookupStarted = yield* Deferred.make<void>();
1550
+ const releaseSlowLookup = yield* Deferred.make<void>();
1551
+ const settled = yield* Deferred.make<void>();
1552
+ const branchLookupCount = yield* Ref.make(0);
1553
+ const recent = DateTime.makeUnsafe("2026-08-27T00:00:00.000Z");
1554
+ const slow = makeThread("slow-lookup", { branch: "feature", latestUserMessageAt: recent });
1555
+ const merged = makeThread("merged", {
1556
+ latestUserMessageAt: recent,
1557
+ pullRequests: [
1558
+ {
1559
+ ...persistedLink("open", recent),
1560
+ snapshot: {
1561
+ state: "merged",
1562
+ title: "Pull request",
1563
+ headBranch: "feature",
1564
+ baseBranch: "main",
1565
+ isDraft: false,
1566
+ updatedAt: NOW,
1567
+ syncedAt: NOW,
1568
+ mergedAt: NOW,
1569
+ },
1570
+ },
1571
+ ],
1572
+ pendingBackgroundTasks: [{ taskId: "child", kind: "subagent", description: "Review" }],
1573
+ });
1574
+ const fixture = yield* makeHarness({
1575
+ snapshot: makeSnapshot([slow, merged]),
1576
+ branchPullRequest: () =>
1577
+ Ref.updateAndGet(branchLookupCount, (count) => count + 1).pipe(
1578
+ Effect.flatMap((count) =>
1579
+ count === 1
1580
+ ? Effect.succeed(makeBranchPullRequest("open"))
1581
+ : Deferred.succeed(slowLookupStarted, undefined).pipe(
1582
+ Effect.andThen(Deferred.await(releaseSlowLookup)),
1583
+ Effect.as(makeBranchPullRequest("open")),
1584
+ ),
1585
+ ),
1586
+ ),
1587
+ onDispatch: () => Deferred.succeed(settled, undefined),
1588
+ });
1589
+ const backgroundEnded = (threadId: ThreadId): OrchestrationV2DomainEvent => ({
1590
+ type: "run.background-work-cancelled",
1591
+ id: EventId.make(`event:background-ended:${threadId}`),
1592
+ threadId,
1593
+ occurredAt: DateTime.makeUnsafe(NOW),
1594
+ payload: { runId: RunId.make(`run:${threadId}`), restartCancelledBackgroundWork: [] },
1595
+ });
1596
+
1597
+ yield* Effect.gen(function* () {
1598
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1599
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1600
+ yield* fixture.publishEvent(backgroundEnded(slow.id));
1601
+ yield* Deferred.await(slowLookupStarted);
1602
+ // More events for the slow thread coalesce into one more pass, not more sweeps.
1603
+ for (let index = 0; index < 9; index++) {
1604
yield* fixture.publishEvent(backgroundEnded(slow.id));
1635
- yield* Deferred.await(slowLookupStarted);
1636
- // More events for the slow thread coalesce into one more pass, not more sweeps.
1637
- for (let index = 0; index < 9; index++) {
1638
- yield* fixture.publishEvent(backgroundEnded(slow.id));
1639
- }
1605
+ }
1606
1641
- yield* Ref.set(
1642
- fixture.snapshots,
1643
- makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1644
- );
1645
- yield* fixture.publishEvent(backgroundEnded(merged.id));
1646
- yield* Deferred.await(settled);
1607
+ yield* Ref.set(
1608
+ fixture.snapshots,
1609
+ makeSnapshot([slow, { ...merged, pendingBackgroundTasks: [] }]),
1610
+ );
1611
+ yield* fixture.publishEvent(backgroundEnded(merged.id));
1612
+ yield* Deferred.await(settled);
1613
1648
- assert.deepStrictEqual(
1649
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1650
- [merged.id],
1651
- );
1652
- yield* Deferred.succeed(releaseSlowLookup, undefined);
1653
- yield* reactor.drain;
1654
- // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1655
- assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1656
- }).pipe(Effect.provide(fixture.layer));
1657
- }),
1658
- ),
1614
+ assert.deepStrictEqual(
1615
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1616
+ [merged.id],
1617
+ );
1618
+ yield* Deferred.succeed(releaseSlowLookup, undefined);
1619
+ yield* reactor.drain;
1620
+ // The startup sweep, the first per-thread sweep, and one coalesced rerun.
1621
+ assert.strictEqual(yield* Ref.get(branchLookupCount), 3);
1622
+ }).pipe(Effect.provide(fixture.layer));
1623
+ }),
1624
);
1625
1626
it.effect("settles an unlinked branch thread its agent merged from a shell, past the cache", () =>
1662
- Effect.scoped(
1663
- Effect.gen(function* () {
1664
- yield* TestClock.setTime(Date.parse(NOW));
1665
- const settled = yield* Deferred.make<void>();
1666
- const thread = makeThread("shell-merged", {
1667
- branch: "saved-feature",
1668
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1669
- });
1670
- const fixture = yield* makeHarness({
1671
- snapshot: makeSnapshot([thread]),
1672
- // The host already merged it; only a fresh read sees that past the cached open lookup.
1673
- branchPullRequest: (_input, lookupOptions) =>
1674
- Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1675
- onDispatch: () => Deferred.succeed(settled, undefined),
1676
- });
1677
- const at = DateTime.makeUnsafe(NOW);
1678
- const runId = RunId.make("run:shell-merged");
1679
- const runEnded: OrchestrationV2DomainEvent = {
1680
- type: "run.background-work-cancelled",
1681
- id: EventId.make("event:shell-merged:run-ended"),
1627
+ Effect.gen(function* () {
1628
+ yield* TestClock.setTime(Date.parse(NOW));
1629
+ const settled = yield* Deferred.make<void>();
1630
+ const thread = makeThread("shell-merged", {
1631
+ branch: "saved-feature",
1632
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1633
+ });
1634
+ const fixture = yield* makeHarness({
1635
+ snapshot: makeSnapshot([thread]),
1636
+ // The host already merged it; only a fresh read sees that past the cached open lookup.
1637
+ branchPullRequest: (_input, lookupOptions) =>
1638
+ Effect.succeed(makeBranchPullRequest(lookupOptions?.refresh ? "merged" : "open")),
1639
+ onDispatch: () => Deferred.succeed(settled, undefined),
1640
+ });
1641
+ const at = DateTime.makeUnsafe(NOW);
1642
+ const runId = RunId.make("run:shell-merged");
1643
+ const runEnded: OrchestrationV2DomainEvent = {
1644
+ type: "run.background-work-cancelled",
1645
+ id: EventId.make("event:shell-merged:run-ended"),
1646
+ threadId: thread.id,
1647
+ occurredAt: at,
1648
+ payload: { runId, restartCancelledBackgroundWork: [] },
1649
+ };
1650
+
1651
+ yield* Effect.gen(function* () {
1652
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1653
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1654
+ yield* fixture.publishEvent(runEnded);
1655
+ yield* Queue.take(fixture.snapshotReads);
1656
+ yield* reactor.drain;
1657
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1658
+
1659
+ yield* fixture.publishEvent({
1660
+ type: "turn-item.updated",
1661
+ id: EventId.make("event:shell-merged:command"),
1662
threadId: thread.id,
1663
+ runId,
1664
occurredAt: at,
1684
- payload: { runId, restartCancelledBackgroundWork: [] },
1685
- };
1686
-
1687
- yield* Effect.gen(function* () {
1688
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1689
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1690
- yield* fixture.publishEvent(runEnded);
1691
- yield* Queue.take(fixture.snapshotReads);
1692
- yield* reactor.drain;
1693
- assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1694
-
1695
- yield* fixture.publishEvent({
1696
- type: "turn-item.updated",
1697
- id: EventId.make("event:shell-merged:command"),
1665
+ payload: {
1666
+ id: TurnItemId.make("item:shell-merged:command"),
1667
threadId: thread.id,
1668
runId,
1700
- occurredAt: at,
1701
- payload: {
1702
- id: TurnItemId.make("item:shell-merged:command"),
1703
- threadId: thread.id,
1704
- runId,
1705
- nodeId: null,
1706
- providerThreadId: null,
1707
- providerTurnId: null,
1708
- nativeItemRef: null,
1709
- parentItemId: null,
1710
- ordinal: 1,
1711
- status: "completed",
1712
- title: null,
1713
- startedAt: at,
1714
- completedAt: at,
1715
- updatedAt: at,
1716
- type: "command_execution",
1717
- input: "gh pr merge 42 --squash",
1718
- },
1719
- });
1720
- yield* Deferred.await(settled);
1721
- assert.deepStrictEqual(
1722
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1723
- [thread.id],
1724
- );
1725
- }).pipe(Effect.provide(fixture.layer));
1726
- }),
1727
- ),
1669
+ nodeId: null,
1670
+ providerThreadId: null,
1671
+ providerTurnId: null,
1672
+ nativeItemRef: null,
1673
+ parentItemId: null,
1674
+ ordinal: 1,
1675
+ status: "completed",
1676
+ title: null,
1677
+ startedAt: at,
1678
+ completedAt: at,
1679
+ updatedAt: at,
1680
+ type: "command_execution",
1681
+ input: "gh pr merge 42 --squash",
1682
+ },
1683
+ });
1684
+ yield* Deferred.await(settled);
1685
+ assert.deepStrictEqual(
1686
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1687
+ [thread.id],
1688
+ );
1689
+ }).pipe(Effect.provide(fixture.layer));
1690
+ }),
1691
);
1692
1693
it.effect(
1694
"settles branch threads on a pull request merge without waiting for the next sweep",
1695
() =>
1733
- Effect.scoped(
1734
- Effect.gen(function* () {
1735
- yield* TestClock.setTime(Date.parse(NOW));
1736
- const state = yield* Ref.make<"open" | "merged">("open");
1737
- const mergedThreadSettled = yield* Deferred.make<void>();
1738
- const fixture = yield* makeHarness({
1739
- snapshot: makeSnapshot([
1740
- makeThread("branch-thread", {
1741
- branch: "saved-feature",
1742
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1743
- }),
1744
- ]),
1745
- branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1746
- onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1747
- });
1748
-
1749
- yield* Effect.gen(function* () {
1750
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1751
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1752
- assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1753
- assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1754
-
1755
- yield* Ref.set(state, "merged");
1756
- yield* fixture.publishMerge;
1757
- yield* Deferred.await(mergedThreadSettled);
1758
-
1759
- assert.deepStrictEqual(
1760
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1761
- [ThreadId.make("branch-thread")],
1762
- );
1763
- assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1764
- yield* reactor.drain;
1765
- }).pipe(Effect.provide(fixture.layer));
1766
- }),
1767
- ),
1768
- );
1769
-
1770
- it.effect("a merged branch PR that cannot settle its thread rereads no git state", () =>
1771
- Effect.scoped(
1772
- Effect.gen(function* () {
1773
- yield* TestClock.setTime(Date.parse(NOW));
1774
- const freshReads = yield* Ref.make(0);
1775
- const fixture = yield* makeHarness({
1776
- snapshot: makeSnapshot([
1777
- makeThread("worked-after-merge", {
1778
- branch: "merged-feature",
1779
- latestUserAuthoredMessageAt: DateTime.makeUnsafe("2026-08-28T06:00:00.000Z"),
1780
- }),
1781
- ]),
1782
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1783
- branchPullRequest: (_input, lookupOptions) =>
1784
- Ref.update(
1785
- freshReads,
1786
- (count) => count + (readsFreshGitState(lookupOptions) ? 1 : 0),
1787
- ).pipe(
1788
- Effect.as({
1789
- ...makeBranchPullRequest("merged"),
1790
- mergedAt: "2026-08-27T00:00:00.000Z",
1791
- }),
1792
- ),
1793
- });
1794
-
1795
- yield* Effect.gen(function* () {
1796
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1797
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1798
- yield* TestClock.adjust("1 minute");
1799
- yield* Queue.take(fixture.snapshotReads);
1800
- yield* reactor.drain;
1801
-
1802
- assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
1803
- assert.strictEqual(yield* Ref.get(freshReads), 0);
1804
- assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1805
- }).pipe(Effect.provide(fixture.layer));
1806
- }),
1807
- ),
1808
- );
1809
-
1810
- it.effect("a remembered merged branch PR settles only after fresh git state agrees", () =>
1811
- Effect.scoped(
1812
- Effect.gen(function* () {
1813
- yield* TestClock.setTime(Date.parse(NOW));
1814
- const freshState = yield* Ref.make<"open" | "merged">("open");
1815
- const fixture = yield* makeHarness({
1816
- snapshot: makeSnapshot([makeThread("merged-branch", { branch: "merged-feature" })]),
1817
- settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1818
- branchPullRequest: (_input, lookupOptions) =>
1819
- readsFreshGitState(lookupOptions)
1820
- ? Ref.get(freshState).pipe(Effect.map(makeBranchPullRequest))
1821
- : Effect.succeed(makeBranchPullRequest("merged")),
1822
- });
1823
-
1824
- yield* Effect.gen(function* () {
1825
- const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1826
- yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1827
- assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1828
-
1829
- yield* Ref.set(freshState, "merged");
1830
- yield* TestClock.adjust("1 minute");
1831
- yield* Queue.take(fixture.snapshotReads);
1832
- yield* reactor.drain;
1833
-
1834
- assert.deepStrictEqual(
1835
- (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1836
- [ThreadId.make("merged-branch")],
1837
- );
1838
- }).pipe(Effect.provide(fixture.layer));
1839
- }),
1840
- ),
1841
- );
1842
-
1843
- it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1844
- Effect.scoped(
1696
Effect.gen(function* () {
1697
yield* TestClock.setTime(Date.parse(NOW));
1698
+ const state = yield* Ref.make<"open" | "merged">("open");
1699
const mergedThreadSettled = yield* Deferred.make<void>();
1848
- const mergeLookupStarted = yield* Deferred.make<void>();
1849
- const releaseMergeLookup = yield* Deferred.make<void>();
1850
- const lookupCount = yield* Ref.make(0);
1700
const fixture = yield* makeHarness({
1701
snapshot: makeSnapshot([
1853
- makeThread("merged-in-app", {
1854
- latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1855
- linkedPullRequest: {
1856
- projectId: PROJECT_ID,
1857
- repository: "owner/repository",
1858
- number: 42,
1859
- url: "https://example.test/owner/repository/pull/42",
1860
- },
1861
- }),
1862
- makeThread("unrelated-linked", {
1702
+ makeThread("branch-thread", {
1703
+ branch: "saved-feature",
1704
latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1864
- linkedPullRequest: {
1865
- projectId: PROJECT_ID,
1866
- repository: "owner/repository",
1867
- number: 99,
1868
- url: "https://example.test/owner/repository/pull/99",
1869
- },
1705
}),
1706
]),
1872
- pullRequestSummary: (input) =>
1873
- Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1874
- Effect.tap((count) =>
1875
- count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1876
- ),
1877
- Effect.tap((count) =>
1878
- count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void,
1879
- ),
1880
- Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1881
- ),
1707
+ branchPullRequest: () => Ref.get(state).pipe(Effect.map(makeBranchPullRequest)),
1708
onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1709
});
1710
@@ -1886,192 +1712,307 @@ describe("ThreadSettlementServiceV2 worker", () => {
1712
const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1713
yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1714
assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1715
+ assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), []);
1716
1717
+ yield* Ref.set(state, "merged");
1718
yield* fixture.publishMerge;
1891
- yield* Deferred.await(mergeLookupStarted);
1719
yield* Deferred.await(mergedThreadSettled);
1893
- yield* Deferred.succeed(releaseMergeLookup, undefined);
1894
- yield* reactor.drain;
1720
1721
assert.deepStrictEqual(
1722
(yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1898
- [ThreadId.make("merged-in-app")],
1899
- );
1900
- assert.deepStrictEqual(
1901
- (yield* Ref.get(fixture.summaryCalls))
1902
- .map((call) => call.number)
1903
- .toSorted((left, right) => left - right),
1904
- [42, 99, 99],
1723
+ [ThreadId.make("branch-thread")],
1724
);
1725
+ assert.deepStrictEqual(yield* Ref.get(fixture.invalidatedCwds), ["/workspace/project"]);
1726
+ yield* reactor.drain;
1727
}).pipe(Effect.provide(fixture.layer));
1728
}),
1908
- ),
1729
+ );
1730
+
1731
+ it.effect("a merged branch PR that cannot settle its thread rereads no git state", () =>
1732
+ Effect.gen(function* () {
1733
+ yield* TestClock.setTime(Date.parse(NOW));
1734
+ const freshReads = yield* Ref.make(0);
1735
+ const fixture = yield* makeHarness({
1736
+ snapshot: makeSnapshot([
1737
+ makeThread("worked-after-merge", {
1738
+ branch: "merged-feature",
1739
+ latestUserAuthoredMessageAt: DateTime.makeUnsafe("2026-08-28T06:00:00.000Z"),
1740
+ }),
1741
+ ]),
1742
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1743
+ branchPullRequest: (_input, lookupOptions) =>
1744
+ Ref.update(
1745
+ freshReads,
1746
+ (count) => count + (readsFreshGitState(lookupOptions) ? 1 : 0),
1747
+ ).pipe(
1748
+ Effect.as({
1749
+ ...makeBranchPullRequest("merged"),
1750
+ mergedAt: "2026-08-27T00:00:00.000Z",
1751
+ }),
1752
+ ),
1753
+ });
1754
+
1755
+ yield* Effect.gen(function* () {
1756
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1757
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1758
+ yield* TestClock.adjust("1 minute");
1759
+ yield* Queue.take(fixture.snapshotReads);
1760
+ yield* reactor.drain;
1761
+
1762
+ assert.strictEqual((yield* Ref.get(fixture.branchCalls)).length, 2);
1763
+ assert.strictEqual(yield* Ref.get(freshReads), 0);
1764
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1765
+ }).pipe(Effect.provide(fixture.layer));
1766
+ }),
1767
+ );
1768
+
1769
+ it.effect("a remembered merged branch PR settles only after fresh git state agrees", () =>
1770
+ Effect.gen(function* () {
1771
+ yield* TestClock.setTime(Date.parse(NOW));
1772
+ const freshState = yield* Ref.make<"open" | "merged">("open");
1773
+ const fixture = yield* makeHarness({
1774
+ snapshot: makeSnapshot([makeThread("merged-branch", { branch: "merged-feature" })]),
1775
+ settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: null },
1776
+ branchPullRequest: (_input, lookupOptions) =>
1777
+ readsFreshGitState(lookupOptions)
1778
+ ? Ref.get(freshState).pipe(Effect.map(makeBranchPullRequest))
1779
+ : Effect.succeed(makeBranchPullRequest("merged")),
1780
+ });
1781
+
1782
+ yield* Effect.gen(function* () {
1783
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1784
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1785
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1786
+
1787
+ yield* Ref.set(freshState, "merged");
1788
+ yield* TestClock.adjust("1 minute");
1789
+ yield* Queue.take(fixture.snapshotReads);
1790
+ yield* reactor.drain;
1791
+
1792
+ assert.deepStrictEqual(
1793
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1794
+ [ThreadId.make("merged-branch")],
1795
+ );
1796
+ }).pipe(Effect.provide(fixture.layer));
1797
+ }),
1798
+ );
1799
+
1800
+ it.effect("a merge does not settle threads linked to an unrelated pull request", () =>
1801
+ Effect.gen(function* () {
1802
+ yield* TestClock.setTime(Date.parse(NOW));
1803
+ const mergedThreadSettled = yield* Deferred.make<void>();
1804
+ const mergeLookupStarted = yield* Deferred.make<void>();
1805
+ const releaseMergeLookup = yield* Deferred.make<void>();
1806
+ const lookupCount = yield* Ref.make(0);
1807
+ const fixture = yield* makeHarness({
1808
+ snapshot: makeSnapshot([
1809
+ makeThread("merged-in-app", {
1810
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1811
+ linkedPullRequest: {
1812
+ projectId: PROJECT_ID,
1813
+ repository: "owner/repository",
1814
+ number: 42,
1815
+ url: "https://example.test/owner/repository/pull/42",
1816
+ },
1817
+ }),
1818
+ makeThread("unrelated-linked", {
1819
+ latestUserMessageAt: DateTime.makeUnsafe("2026-08-27T00:00:00.000Z"),
1820
+ linkedPullRequest: {
1821
+ projectId: PROJECT_ID,
1822
+ repository: "owner/repository",
1823
+ number: 99,
1824
+ url: "https://example.test/owner/repository/pull/99",
1825
+ },
1826
+ }),
1827
+ ]),
1828
+ pullRequestSummary: (input) =>
1829
+ Ref.updateAndGet(lookupCount, (count) => count + 1).pipe(
1830
+ Effect.tap((count) =>
1831
+ count === 3 ? Deferred.succeed(mergeLookupStarted, undefined) : Effect.void,
1832
+ ),
1833
+ Effect.tap((count) => (count === 3 ? Deferred.await(releaseMergeLookup) : Effect.void)),
1834
+ Effect.map(() => makePullRequestSummary({ ...input, state: "open" })),
1835
+ ),
1836
+ onDispatch: () => Deferred.succeed(mergedThreadSettled, undefined),
1837
+ });
1838
+
1839
+ yield* Effect.gen(function* () {
1840
+ const reactor = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1841
+ yield* startHarness(reactor, fixture.activation, fixture.snapshotReads);
1842
+ assert.deepStrictEqual(yield* Ref.get(fixture.commands), []);
1843
+
1844
+ yield* fixture.publishMerge;
1845
+ yield* Deferred.await(mergeLookupStarted);
1846
+ yield* Deferred.await(mergedThreadSettled);
1847
+ yield* Deferred.succeed(releaseMergeLookup, undefined);
1848
+ yield* reactor.drain;
1849
+
1850
+ assert.deepStrictEqual(
1851
+ (yield* Ref.get(fixture.commands)).map((command) => command.threadId),
1852
+ [ThreadId.make("merged-in-app")],
1853
+ );
1854
+ assert.deepStrictEqual(
1855
+ (yield* Ref.get(fixture.summaryCalls))
1856
+ .map((call) => call.number)
1857
+ .toSorted((left, right) => left - right),
1858
+ [42, 99, 99],
1859
+ );
1860
+ }).pipe(Effect.provide(fixture.layer));
1861
+ }),
1862
);
1863
});
1864
1865
describe("ThreadSettlementServiceV2 terminals", () => {
1866
it.effect("keeps the terminals of a thread re-engaged before the event ran", () =>
1914
- Effect.scoped(
1915
- Effect.gen(function* () {
1916
- const settled = appThread("reengaged-thread", "settled");
1917
- const reengaged = appThread("reengaged-thread", "active");
1918
- const marker = appThread("marker-thread", "settled");
1919
- const fixture = yield* makeHarness({
1920
- snapshot: makeSnapshot([]),
1921
- currentThreads: [reengaged, marker],
1922
- });
1923
-
1924
- yield* Effect.gen(function* () {
1925
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1926
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1927
- yield* fixture.publishEvent(settledEvent(settled));
1928
- yield* fixture.publishEvent(settledEvent(marker));
1929
- assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1930
- }).pipe(Effect.provide(fixture.layer));
1931
- }),
1932
- ),
1867
+ Effect.gen(function* () {
1868
+ const settled = appThread("reengaged-thread", "settled");
1869
+ const reengaged = appThread("reengaged-thread", "active");
1870
+ const marker = appThread("marker-thread", "settled");
1871
+ const fixture = yield* makeHarness({
1872
+ snapshot: makeSnapshot([]),
1873
+ currentThreads: [reengaged, marker],
1874
+ });
1875
+
1876
+ yield* Effect.gen(function* () {
1877
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1878
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1879
+ yield* fixture.publishEvent(settledEvent(settled));
1880
+ yield* fixture.publishEvent(settledEvent(marker));
1881
+ assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: marker.id });
1882
+ }).pipe(Effect.provide(fixture.layer));
1883
+ }),
1884
);
1885
1886
it.effect("runs the settle script in the thread's own worktree", () =>
1936
- Effect.scoped(
1937
- Effect.gen(function* () {
1938
- const shared = appThread("shared-checkout-thread", "settled");
1939
- const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1940
- const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1941
- const fixture = yield* makeHarness({
1942
- snapshot: makeSnapshot([]),
1943
- currentThreads: [shared, missing, worktree],
1944
- existingWorktreePaths: ["/worktrees/thread"],
1945
- });
1946
-
1947
- yield* Effect.gen(function* () {
1948
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1949
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1950
- yield* fixture.publishEvent(settledEvent(shared));
1951
- yield* fixture.publishEvent(settledEvent(missing));
1952
- yield* fixture.publishEvent(settledEvent(worktree));
1953
- const run = yield* Queue.take(fixture.scriptRuns);
1954
- assert.strictEqual(run.threadId, worktree.id);
1955
- assert.strictEqual(run.worktreePath, "/worktrees/thread");
1956
- assert.strictEqual(run.trigger, "settle");
1957
- }).pipe(Effect.provide(fixture.layer));
1958
- }),
1959
- ),
1887
+ Effect.gen(function* () {
1888
+ const shared = appThread("shared-checkout-thread", "settled");
1889
+ const missing = appThread("removed-worktree-thread", "settled", "/worktrees/removed");
1890
+ const worktree = appThread("worktree-thread", "settled", "/worktrees/thread");
1891
+ const fixture = yield* makeHarness({
1892
+ snapshot: makeSnapshot([]),
1893
+ currentThreads: [shared, missing, worktree],
1894
+ existingWorktreePaths: ["/worktrees/thread"],
1895
+ });
1896
+
1897
+ yield* Effect.gen(function* () {
1898
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1899
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1900
+ yield* fixture.publishEvent(settledEvent(shared));
1901
+ yield* fixture.publishEvent(settledEvent(missing));
1902
+ yield* fixture.publishEvent(settledEvent(worktree));
1903
+ const run = yield* Queue.take(fixture.scriptRuns);
1904
+ assert.strictEqual(run.threadId, worktree.id);
1905
+ assert.strictEqual(run.worktreePath, "/worktrees/thread");
1906
+ assert.strictEqual(run.trigger, "settle");
1907
+ }).pipe(Effect.provide(fixture.layer));
1908
+ }),
1909
);
1910
1911
it.effect("skips the settle script for a thread re-engaged while its shells close", () =>
1963
- Effect.scoped(
1964
- Effect.gen(function* () {
1965
- const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1966
- const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1967
- const currentThreads = [settled, marker];
1968
- const fixture = yield* makeHarness({
1969
- snapshot: makeSnapshot([]),
1970
- currentThreads,
1971
- existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1972
- onCloseIdle: () =>
1973
- Effect.sync(() => {
1974
- currentThreads[0] = { ...settled, settledOverride: "active" };
1975
- }),
1976
- });
1977
-
1978
- yield* Effect.gen(function* () {
1979
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1980
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1981
- yield* fixture.publishEvent(settledEvent(settled));
1982
- yield* fixture.publishEvent(settledEvent(marker));
1983
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1984
- }).pipe(Effect.provide(fixture.layer));
1985
- }),
1986
- ),
1912
+ Effect.gen(function* () {
1913
+ const settled = appThread("reengaging-thread", "settled", "/worktrees/reengaging");
1914
+ const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1915
+ const currentThreads = [settled, marker];
1916
+ const fixture = yield* makeHarness({
1917
+ snapshot: makeSnapshot([]),
1918
+ currentThreads,
1919
+ existingWorktreePaths: ["/worktrees/reengaging", "/worktrees/marker"],
1920
+ onCloseIdle: () =>
1921
+ Effect.sync(() => {
1922
+ currentThreads[0] = { ...settled, settledOverride: "active" };
1923
+ }),
1924
+ });
1925
+
1926
+ yield* Effect.gen(function* () {
1927
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1928
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1929
+ yield* fixture.publishEvent(settledEvent(settled));
1930
+ yield* fixture.publishEvent(settledEvent(marker));
1931
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1932
+ }).pipe(Effect.provide(fixture.layer));
1933
+ }),
1934
);
1935
1936
it.effect("skips the settle script for a subagent in its parent's worktree", () =>
1990
- Effect.scoped(
1991
- Effect.gen(function* () {
1992
- const parent = appThread("subagent-parent", "settled", "/worktrees/parent");
1993
- const subagent = (id: string, worktreePath: string) => ({
1994
- ...appThread(id, "settled", worktreePath),
1995
- lineage: {
1996
- parentThreadId: parent.id,
1997
- relationshipToParent: "subagent" as const,
1998
- rootThreadId: parent.id,
1999
- },
2000
- });
2001
- const shared = subagent("subagent-shared", "/worktrees/parent");
2002
- const own = subagent("subagent-own", "/worktrees/own");
2003
- const fixture = yield* makeHarness({
2004
- snapshot: makeSnapshot([]),
2005
- currentThreads: [parent, shared, own],
2006
- existingWorktreePaths: ["/worktrees/parent", "/worktrees/own"],
2007
- });
2008
-
2009
- yield* Effect.gen(function* () {
2010
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2011
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2012
- // Events run in order, so the first run belongs to the second event
2013
- // only if the shared-worktree child was skipped. Both still close.
2014
- yield* fixture.publishEvent(settledEvent(shared));
2015
- yield* fixture.publishEvent(settledEvent(own));
2016
- assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: shared.id });
2017
- assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: own.id });
2018
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, own.id);
2019
- }).pipe(Effect.provide(fixture.layer));
2020
- }),
2021
- ),
1937
+ Effect.gen(function* () {
1938
+ const parent = appThread("subagent-parent", "settled", "/worktrees/parent");
1939
+ const subagent = (id: string, worktreePath: string) => ({
1940
+ ...appThread(id, "settled", worktreePath),
1941
+ lineage: {
1942
+ parentThreadId: parent.id,
1943
+ relationshipToParent: "subagent" as const,
1944
+ rootThreadId: parent.id,
1945
+ },
1946
+ });
1947
+ const shared = subagent("subagent-shared", "/worktrees/parent");
1948
+ const own = subagent("subagent-own", "/worktrees/own");
1949
+ const fixture = yield* makeHarness({
1950
+ snapshot: makeSnapshot([]),
1951
+ currentThreads: [parent, shared, own],
1952
+ existingWorktreePaths: ["/worktrees/parent", "/worktrees/own"],
1953
+ });
1954
+
1955
+ yield* Effect.gen(function* () {
1956
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1957
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1958
+ // Events run in order, so the first run belongs to the second event
1959
+ // only if the shared-worktree child was skipped. Both still close.
1960
+ yield* fixture.publishEvent(settledEvent(shared));
1961
+ yield* fixture.publishEvent(settledEvent(own));
1962
+ assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: shared.id });
1963
+ assert.deepStrictEqual(yield* Queue.take(fixture.closedIdle), { threadId: own.id });
1964
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, own.id);
1965
+ }).pipe(Effect.provide(fixture.layer));
1966
+ }),
1967
);
1968
1969
it.effect("runs the settle script once when a settlement is re-emitted", () =>
2025
- Effect.scoped(
2026
- Effect.gen(function* () {
2027
- const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
2028
- const marker = appThread("marker-thread", "settled", "/worktrees/marker");
2029
- const fixture = yield* makeHarness({
2030
- snapshot: makeSnapshot([]),
2031
- currentThreads: [repeated, marker],
2032
- existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
2033
- });
2034
-
2035
- yield* Effect.gen(function* () {
2036
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2037
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2038
- yield* fixture.publishEvent(settledEvent(repeated));
2039
- yield* fixture.publishEvent(settledEvent(repeated));
2040
- yield* fixture.publishEvent(settledEvent(marker));
2041
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
2042
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
2043
- }).pipe(Effect.provide(fixture.layer));
2044
- }),
2045
- ),
1970
+ Effect.gen(function* () {
1971
+ const repeated = appThread("repeated-thread", "settled", "/worktrees/repeated");
1972
+ const marker = appThread("marker-thread", "settled", "/worktrees/marker");
1973
+ const fixture = yield* makeHarness({
1974
+ snapshot: makeSnapshot([]),
1975
+ currentThreads: [repeated, marker],
1976
+ existingWorktreePaths: ["/worktrees/repeated", "/worktrees/marker"],
1977
+ });
1978
+
1979
+ yield* Effect.gen(function* () {
1980
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
1981
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
1982
+ yield* fixture.publishEvent(settledEvent(repeated));
1983
+ yield* fixture.publishEvent(settledEvent(repeated));
1984
+ yield* fixture.publishEvent(settledEvent(marker));
1985
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, repeated.id);
1986
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, marker.id);
1987
+ }).pipe(Effect.provide(fixture.layer));
1988
+ }),
1989
);
1990
1991
it.effect("retries the settle script on a re-emitted settlement after a failed start", () =>
2049
- Effect.scoped(
2050
- Effect.gen(function* () {
2051
- const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
2052
- const starts = yield* Ref.make(0);
2053
- const fixture = yield* makeHarness({
2054
- snapshot: makeSnapshot([]),
2055
- currentThreads: [thread],
2056
- existingWorktreePaths: ["/worktrees/failed-start"],
2057
- onScriptRun: () =>
2058
- Ref.updateAndGet(starts, (count) => count + 1).pipe(
2059
- Effect.flatMap((count) =>
2060
- count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
2061
- ),
1992
+ Effect.gen(function* () {
1993
+ const thread = appThread("failed-start-thread", "settled", "/worktrees/failed-start");
1994
+ const starts = yield* Ref.make(0);
1995
+ const fixture = yield* makeHarness({
1996
+ snapshot: makeSnapshot([]),
1997
+ currentThreads: [thread],
1998
+ existingWorktreePaths: ["/worktrees/failed-start"],
1999
+ onScriptRun: () =>
2000
+ Ref.updateAndGet(starts, (count) => count + 1).pipe(
2001
+ Effect.flatMap((count) =>
2002
+ count === 1 ? Effect.die(new Error("terminal failed to open")) : Effect.void,
2003
),
2063
- });
2064
-
2065
- yield* Effect.gen(function* () {
2066
- const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2067
- yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2068
- yield* fixture.publishEvent(settledEvent(thread));
2069
- yield* fixture.publishEvent(settledEvent(thread));
2070
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2071
- assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2072
- }).pipe(Effect.provide(fixture.layer));
2073
- }),
2074
- ),
2004
+ ),
2005
+ });
2006
+
2007
+ yield* Effect.gen(function* () {
2008
+ const service = yield* ThreadSettlementService.ThreadSettlementServiceV2;
2009
+ yield* startHarness(service, fixture.activation, fixture.snapshotReads);
2010
+ yield* fixture.publishEvent(settledEvent(thread));
2011
+ yield* fixture.publishEvent(settledEvent(thread));
2012
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2013
+ assert.strictEqual((yield* Queue.take(fixture.scriptRuns)).threadId, thread.id);
2014
+ }).pipe(Effect.provide(fixture.layer));
2015
+ }),
2016
);
2017
});
2018
apps/server/src/orchestration-v2/ThreadStop.test.ts
+230
-233
@@ -1847,252 +1847,249 @@ it.effect.each([
1847
])(
1848
"Force stop keeps only the session of a queued follow-up that $followUp",
1849
({ startedBeforeRelease, switchesInstance = false, freshContext = false }) =>
1850
- Effect.scoped(
1851
- Effect.gen(function* () {
1852
- const cwd = yield* checkpointWorkspace("thread-stop-force-stop-follow-up");
1853
- const driver = adapter.driver;
1854
- const otherInstanceId = ProviderInstanceId.make("codex-other");
1855
- const eventQueues = new Map<
1856
- ProviderSessionId,
1857
- Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>
1858
- >();
1859
- const started: Array<ProviderAdapter.ProviderAdapterV2TurnInput> = [];
1860
- const interrupted: Array<ProviderAdapter.ProviderAdapterV2InterruptInput> = [];
1861
- let opened = 0;
1862
- // Fresh context on a one-thread-per-session provider puts the follow-up on its own session.
1863
- // The session itself reports shared threads so fresh-context cleanup leaves the stopped
1864
- // run's session to Force stop, as pending background work would.
1865
- const adapterCapabilities = freshContext
1866
- ? {
1867
- ...CodexProviderCapabilitiesV2,
1868
- sessions: {
1869
- ...CodexProviderCapabilitiesV2.sessions,
1870
- supportsMultipleProviderThreadsPerSession: false,
1871
- },
1872
- }
1873
- : CodexProviderCapabilitiesV2;
1874
- const liveAdapter = (
1875
- instanceId: ProviderInstanceId,
1876
- ): ProviderAdapter.ProviderAdapterV2["Service"] => ({
1877
- ...adapter,
1878
- instanceId,
1879
- getCapabilities: () => Effect.succeed(adapterCapabilities),
1880
- openSession: (input) =>
1881
- Effect.gen(function* () {
1882
- opened += 1;
1883
- const now = yield* DateTime.now;
1884
- const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1885
- eventQueues.set(input.providerSessionId, events);
1886
- return {
1887
- instanceId,
1850
+ Effect.gen(function* () {
1851
+ const cwd = yield* checkpointWorkspace("thread-stop-force-stop-follow-up");
1852
+ const driver = adapter.driver;
1853
+ const otherInstanceId = ProviderInstanceId.make("codex-other");
1854
+ const eventQueues = new Map<
1855
+ ProviderSessionId,
1856
+ Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>
1857
+ >();
1858
+ const started: Array<ProviderAdapter.ProviderAdapterV2TurnInput> = [];
1859
+ const interrupted: Array<ProviderAdapter.ProviderAdapterV2InterruptInput> = [];
1860
+ let opened = 0;
1861
+ // Fresh context on a one-thread-per-session provider puts the follow-up on its own session.
1862
+ // The session itself reports shared threads so fresh-context cleanup leaves the stopped
1863
+ // run's session to Force stop, as pending background work would.
1864
+ const adapterCapabilities = freshContext
1865
+ ? {
1866
+ ...CodexProviderCapabilitiesV2,
1867
+ sessions: {
1868
+ ...CodexProviderCapabilitiesV2.sessions,
1869
+ supportsMultipleProviderThreadsPerSession: false,
1870
+ },
1871
+ }
1872
+ : CodexProviderCapabilitiesV2;
1873
+ const liveAdapter = (
1874
+ instanceId: ProviderInstanceId,
1875
+ ): ProviderAdapter.ProviderAdapterV2["Service"] => ({
1876
+ ...adapter,
1877
+ instanceId,
1878
+ getCapabilities: () => Effect.succeed(adapterCapabilities),
1879
+ openSession: (input) =>
1880
+ Effect.gen(function* () {
1881
+ opened += 1;
1882
+ const now = yield* DateTime.now;
1883
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
1884
+ eventQueues.set(input.providerSessionId, events);
1885
+ return {
1886
+ instanceId,
1887
+ driver,
1888
+ providerSessionId: input.providerSessionId,
1889
+ providerSession: {
1890
+ id: input.providerSessionId,
1891
driver,
1889
- providerSessionId: input.providerSessionId,
1890
- providerSession: {
1891
- id: input.providerSessionId,
1892
+ providerInstanceId: instanceId,
1893
+ status: "ready",
1894
+ cwd,
1895
+ model: modelSelection.model,
1896
+ capabilities: CodexProviderCapabilitiesV2,
1897
+ createdAt: now,
1898
+ updatedAt: now,
1899
+ lastError: null,
1900
+ },
1901
+ events: Stream.fromQueue(events),
1902
+ ensureThread: ({ threadId }) =>
1903
+ Effect.succeed({
1904
+ id: ProviderThreadId.make(
1905
+ `provider-thread:${input.providerSessionId}:${threadId}`,
1906
+ ),
1907
driver,
1908
providerInstanceId: instanceId,
1894
- status: "ready",
1895
- cwd,
1896
- model: modelSelection.model,
1897
- capabilities: CodexProviderCapabilitiesV2,
1909
+ providerSessionId: input.providerSessionId,
1910
+ appThreadId: threadId,
1911
+ ownerNodeId: null,
1912
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
1913
+ nativeConversationHeadRef: null,
1914
+ status: "idle",
1915
+ firstRunOrdinal: null,
1916
+ lastRunOrdinal: null,
1917
+ handoffIds: [],
1918
+ forkedFrom: null,
1919
createdAt: now,
1920
updatedAt: now,
1900
- lastError: null,
1901
- },
1902
- events: Stream.fromQueue(events),
1903
- ensureThread: ({ threadId }) =>
1904
- Effect.succeed({
1905
- id: ProviderThreadId.make(
1906
- `provider-thread:${input.providerSessionId}:${threadId}`,
1907
- ),
1921
+ }),
1922
+ resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
1923
+ startTurn: (turn) =>
1924
+ Effect.gen(function* () {
1925
+ started.push(turn);
1926
+ yield* Queue.offer(events, {
1927
+ type: "provider_turn.updated",
1928
driver,
1909
- providerInstanceId: instanceId,
1910
- providerSessionId: input.providerSessionId,
1911
- appThreadId: threadId,
1912
- ownerNodeId: null,
1913
- nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
1914
- nativeConversationHeadRef: null,
1915
- status: "idle",
1916
- firstRunOrdinal: null,
1917
- lastRunOrdinal: null,
1918
- handoffIds: [],
1919
- forkedFrom: null,
1920
- createdAt: now,
1921
- updatedAt: now,
1922
- }),
1923
- resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
1924
- startTurn: (turn) =>
1925
- Effect.gen(function* () {
1926
- started.push(turn);
1927
- yield* Queue.offer(events, {
1928
- type: "provider_turn.updated",
1929
- driver,
1930
- providerTurn: {
1931
- id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
1932
- providerThreadId: turn.providerThread.id,
1933
- nodeId: turn.rootNodeId,
1934
- runAttemptId: turn.attemptId,
1935
- nativeTurnRef: {
1936
- driver,
1937
- nativeId: `native:${turn.attemptId}`,
1938
- strength: "strong",
1939
- },
1940
- ordinal: turn.providerTurnOrdinal,
1941
- status: "running",
1942
- startedAt: now,
1943
- completedAt: null,
1929
+ providerTurn: {
1930
+ id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
1931
+ providerThreadId: turn.providerThread.id,
1932
+ nodeId: turn.rootNodeId,
1933
+ runAttemptId: turn.attemptId,
1934
+ nativeTurnRef: {
1935
+ driver,
1936
+ nativeId: `native:${turn.attemptId}`,
1937
+ strength: "strong",
1938
},
1945
- });
1946
- }),
1947
- steerTurn: () => Effect.die("unused"),
1948
- interruptTurn: (interrupt) => Effect.sync(() => interrupted.push(interrupt)),
1949
- respondToRuntimeRequest: () => Effect.die("unused"),
1950
- readThreadSnapshot: () => Effect.die("unused"),
1951
- rollbackThread: () => Effect.die("unused"),
1952
- forkThread: () => Effect.die("unused"),
1953
- };
1954
- }),
1955
- });
1956
- // The settlement promotes the follow-up; optionally its turn starts before Force stop releases.
1957
- const layerSessionsStartingFollowUpFirst = Layer.effect(
1958
- ProviderSessionManager.ProviderSessionManagerV2,
1959
- Effect.gen(function* () {
1960
- const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
1961
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1962
- return ProviderSessionManager.ProviderSessionManagerV2.of({
1963
- ...sessions,
1964
- releaseUnlessBusy: (input) =>
1965
- (startedBeforeRelease ? worker.drain().pipe(Effect.orDie) : Effect.void).pipe(
1966
- Effect.andThen(sessions.releaseUnlessBusy(input)),
1967
- ),
1968
- });
1939
+ ordinal: turn.providerTurnOrdinal,
1940
+ status: "running",
1941
+ startedAt: now,
1942
+ completedAt: null,
1943
+ },
1944
+ });
1945
+ }),
1946
+ steerTurn: () => Effect.die("unused"),
1947
+ interruptTurn: (interrupt) => Effect.sync(() => interrupted.push(interrupt)),
1948
+ respondToRuntimeRequest: () => Effect.die("unused"),
1949
+ readThreadSnapshot: () => Effect.die("unused"),
1950
+ rollbackThread: () => Effect.die("unused"),
1951
+ forkThread: () => Effect.die("unused"),
1952
+ };
1953
}),
1970
- );
1971
- const layerLive = ThreadManagementService.layer.pipe(
1972
- Layer.provide(layerSessionsStartingFollowUpFirst),
1973
- Layer.provideMerge(
1974
- Layer.mergeAll(
1975
- layerDatabase,
1976
- ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
1977
- EventStore.layer.pipe(Layer.provide(layerDatabase)),
1978
- EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
1979
- ProviderReplayHarness.layerWithRegistry(
1980
- { name: "thread-stop-force-stop-follow-up" },
1981
- ProviderAdapterRegistry.layerFromAdapters([
1982
- liveAdapter(instanceId),
1983
- liveAdapter(otherInstanceId),
1984
- ]),
1985
- { databaseLayer: layerDatabase, runEffectWorker: false },
1954
+ });
1955
+ // The settlement promotes the follow-up; optionally its turn starts before Force stop releases.
1956
+ const layerSessionsStartingFollowUpFirst = Layer.effect(
1957
+ ProviderSessionManager.ProviderSessionManagerV2,
1958
+ Effect.gen(function* () {
1959
+ const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
1960
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1961
+ return ProviderSessionManager.ProviderSessionManagerV2.of({
1962
+ ...sessions,
1963
+ releaseUnlessBusy: (input) =>
1964
+ (startedBeforeRelease ? worker.drain().pipe(Effect.orDie) : Effect.void).pipe(
1965
+ Effect.andThen(sessions.releaseUnlessBusy(input)),
1966
),
1967
+ });
1968
+ }),
1969
+ );
1970
+ const layerLive = ThreadManagementService.layer.pipe(
1971
+ Layer.provide(layerSessionsStartingFollowUpFirst),
1972
+ Layer.provideMerge(
1973
+ Layer.mergeAll(
1974
+ layerDatabase,
1975
+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
1976
+ EventStore.layer.pipe(Layer.provide(layerDatabase)),
1977
+ EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
1978
+ ProviderReplayHarness.layerWithRegistry(
1979
+ { name: "thread-stop-force-stop-follow-up" },
1980
+ ProviderAdapterRegistry.layerFromAdapters([
1981
+ liveAdapter(instanceId),
1982
+ liveAdapter(otherInstanceId),
1983
+ ]),
1984
+ { databaseLayer: layerDatabase, runEffectWorker: false },
1985
),
1986
),
1989
- Layer.provideMerge(ServerSettings.layerTest()),
1990
- Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
1991
- );
1987
+ ),
1988
+ Layer.provideMerge(ServerSettings.layerTest()),
1989
+ Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
1990
+ );
1991
1993
- yield* Effect.gen(function* () {
1994
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1995
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1996
- const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
1997
- const threads = yield* ThreadManagementService.ThreadManagementService;
1998
- const threadId = ThreadId.make("thread:force-stop-follow-up");
1999
- const runningTurn = orchestrator.streamDomainEvents.pipe(
2000
- Stream.filter(
2001
- (event) =>
2002
- event.type === "provider-turn.updated" && event.payload.status === "running",
2003
- ),
2004
- Stream.take(1),
2005
- Stream.runDrain,
2006
- Effect.forkScoped,
2007
- );
2008
- yield* orchestrator.dispatch({
2009
- type: "thread.create",
2010
- commandId: CommandId.make("create:force-stop-follow-up"),
2011
- threadId,
2012
- projectId: ProjectId.make("project:thread-stop"),
2013
- title: "Force stop follow-up",
2014
- modelSelection,
2015
- runtimeMode: "full-access",
2016
- interactionMode: "default",
2017
- branch: null,
2018
- worktreePath: cwd,
2019
- createdBy: "user",
2020
- creationSource: "web",
2021
- });
2022
- const firstRunning = yield* runningTurn;
2023
- yield* send(threadId, "first", "start_immediately");
2024
- yield* worker.drain();
2025
- yield* Fiber.join(firstRunning);
2026
- yield* orchestrator.dispatch({
2027
- type: "message.dispatch",
2028
- commandId: CommandId.make("send:force-stop-follow-up"),
2029
- threadId,
2030
- messageId: MessageId.make("message:force-stop-follow-up"),
2031
- text: "follow-up",
2032
- attachments: [],
2033
- dispatchMode: { type: "queue_after_active" },
2034
- ...(switchesInstance
2035
- ? { modelSelection: { ...modelSelection, instanceId: otherInstanceId } }
2036
- : {}),
2037
- ...(freshContext ? { freshContext } : {}),
2038
- createdBy: "user",
2039
- creationSource: "web",
2040
- });
1992
+ yield* Effect.gen(function* () {
1993
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1994
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1995
+ const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
1996
+ const threads = yield* ThreadManagementService.ThreadManagementService;
1997
+ const threadId = ThreadId.make("thread:force-stop-follow-up");
1998
+ const runningTurn = orchestrator.streamDomainEvents.pipe(
1999
+ Stream.filter(
2000
+ (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
2001
+ ),
2002
+ Stream.take(1),
2003
+ Stream.runDrain,
2004
+ Effect.forkScoped,
2005
+ );
2006
+ yield* orchestrator.dispatch({
2007
+ type: "thread.create",
2008
+ commandId: CommandId.make("create:force-stop-follow-up"),
2009
+ threadId,
2010
+ projectId: ProjectId.make("project:thread-stop"),
2011
+ title: "Force stop follow-up",
2012
+ modelSelection,
2013
+ runtimeMode: "full-access",
2014
+ interactionMode: "default",
2015
+ branch: null,
2016
+ worktreePath: cwd,
2017
+ createdBy: "user",
2018
+ creationSource: "web",
2019
+ });
2020
+ const firstRunning = yield* runningTurn;
2021
+ yield* send(threadId, "first", "start_immediately");
2022
+ yield* worker.drain();
2023
+ yield* Fiber.join(firstRunning);
2024
+ yield* orchestrator.dispatch({
2025
+ type: "message.dispatch",
2026
+ commandId: CommandId.make("send:force-stop-follow-up"),
2027
+ threadId,
2028
+ messageId: MessageId.make("message:force-stop-follow-up"),
2029
+ text: "follow-up",
2030
+ attachments: [],
2031
+ dispatchMode: { type: "queue_after_active" },
2032
+ ...(switchesInstance
2033
+ ? { modelSelection: { ...modelSelection, instanceId: otherInstanceId } }
2034
+ : {}),
2035
+ ...(freshContext ? { freshContext } : {}),
2036
+ createdBy: "user",
2037
+ creationSource: "web",
2038
+ });
2039
2042
- const result = yield* threads.forceStopThread({ threadId });
2043
- yield* worker.drain();
2040
+ const result = yield* threads.forceStopThread({ threadId });
2041
+ yield* worker.drain();
2042
2045
- assert.deepEqual(
2046
- started.map((turn) => turn.runOrdinal),
2047
- [1, 2],
2048
- "the queued follow-up did not start its turn",
2049
- );
2050
- assert.equal(
2051
- opened,
2052
- switchesInstance || freshContext ? 2 : 1,
2053
- "Force stop tore down the session the follow-up was promoted onto",
2054
- );
2055
- const [stopped, followUp] = [started[0]!, started[1]!];
2056
- const providerSessionId = followUp.providerThread.providerSessionId!;
2057
- assert.equal(
2058
- yield* sessions.isLive(stopped.providerThread.providerSessionId!),
2059
- !switchesInstance && !freshContext,
2060
- "Force stop kept the stopped run's session for a follow-up on another session",
2061
- );
2062
- assert.isFalse(
2063
- interrupted.some((interrupt) =>
2064
- String(interrupt.providerTurnId).includes(followUp.attemptId),
2065
- ),
2066
- "Force stop of the first run interrupted the follow-up's turn",
2067
- );
2068
- assert.isTrue(
2069
- yield* sessions.isLive(providerSessionId),
2070
- "Force stop of the first run released the session the follow-up's turn is running on",
2071
- );
2072
- assert.deepEqual(
2073
- result,
2074
- { outcome: "released", sharedWithThreadIds: [] },
2075
- "Force stop detached the thread the follow-up runs on as if its session were shared",
2076
- );
2043
+ assert.deepEqual(
2044
+ started.map((turn) => turn.runOrdinal),
2045
+ [1, 2],
2046
+ "the queued follow-up did not start its turn",
2047
+ );
2048
+ assert.equal(
2049
+ opened,
2050
+ switchesInstance || freshContext ? 2 : 1,
2051
+ "Force stop tore down the session the follow-up was promoted onto",
2052
+ );
2053
+ const [stopped, followUp] = [started[0]!, started[1]!];
2054
+ const providerSessionId = followUp.providerThread.providerSessionId!;
2055
+ assert.equal(
2056
+ yield* sessions.isLive(stopped.providerThread.providerSessionId!),
2057
+ !switchesInstance && !freshContext,
2058
+ "Force stop kept the stopped run's session for a follow-up on another session",
2059
+ );
2060
+ assert.isFalse(
2061
+ interrupted.some((interrupt) =>
2062
+ String(interrupt.providerTurnId).includes(followUp.attemptId),
2063
+ ),
2064
+ "Force stop of the first run interrupted the follow-up's turn",
2065
+ );
2066
+ assert.isTrue(
2067
+ yield* sessions.isLive(providerSessionId),
2068
+ "Force stop of the first run released the session the follow-up's turn is running on",
2069
+ );
2070
+ assert.deepEqual(
2071
+ result,
2072
+ { outcome: "released", sharedWithThreadIds: [] },
2073
+ "Force stop detached the thread the follow-up runs on as if its session were shared",
2074
+ );
2075
2078
- // The first run's provider never confirms the stop; the follow-up's turn ends normally.
2079
- yield* Queue.offer(eventQueues.get(providerSessionId)!, {
2080
- type: "turn.terminal",
2081
- driver,
2082
- providerThreadId: followUp.providerThread.id,
2083
- providerTurnId: ProviderTurnId.make(`provider-turn:${followUp.attemptId}`),
2084
- runOrdinal: followUp.runOrdinal,
2085
- status: "completed",
2086
- failure: null,
2087
- threadDisposition: "reusable",
2088
- });
2089
- yield* worker.drain();
2090
- yield* TestClock.adjust("31 minutes");
2091
- assert.isFalse(
2092
- yield* sessions.isLive(providerSessionId),
2093
- "the stopped run's unconfirmed turn kept the session from going idle",
2094
- );
2095
- }).pipe(Effect.provide(layerLive));
2096
- }),
2097
- ),
2076
+ // The first run's provider never confirms the stop; the follow-up's turn ends normally.
2077
+ yield* Queue.offer(eventQueues.get(providerSessionId)!, {
2078
+ type: "turn.terminal",
2079
+ driver,
2080
+ providerThreadId: followUp.providerThread.id,
2081
+ providerTurnId: ProviderTurnId.make(`provider-turn:${followUp.attemptId}`),
2082
+ runOrdinal: followUp.runOrdinal,
2083
+ status: "completed",
2084
+ failure: null,
2085
+ threadDisposition: "reusable",
2086
+ });
2087
+ yield* worker.drain();
2088
+ yield* TestClock.adjust("31 minutes");
2089
+ assert.isFalse(
2090
+ yield* sessions.isLive(providerSessionId),
2091
+ "the stopped run's unconfirmed turn kept the session from going idle",
2092
+ );
2093
+ }).pipe(Effect.provide(layerLive));
2094
+ }),
2095
);
apps/server/src/orchestration-v2/WorktreeBranchSync.test.ts
-1
@@ -105,7 +105,6 @@ it.effect.each([false, true])(
105
}),
106
),
107
),
108
- Effect.scoped,
108
);
109
},
110
);
apps/server/src/orchestration-v2/legacy/LegacyV1Cutover.integration.test.ts
+322
-334
@@ -734,164 +734,159 @@ describe("orchestration v2 legacy v1 cutover", () => {
734
it.live(
735
"migrates an untouched v1 database copy through shell import, lazy transcripts, continuation and restart",
736
() =>
737
- Effect.scoped(
738
- Effect.gen(function* () {
739
- const fs = yield* FileSystem.FileSystem;
740
- const path = yield* Path.Path;
741
- const workspace = yield* checkpointWorkspace("legacy-v1-cutover");
742
- const stateDir = yield* fs.makeTempDirectory({ prefix: "t3-v1-cutover-state-" });
743
- const fixturePath = path.join(stateDir, "v1-source.sqlite");
744
- const copyPath = path.join(stateDir, "userdata", "state.sqlite");
745
- yield* fs.makeDirectory(path.join(stateDir, "userdata"), { recursive: true });
737
+ Effect.gen(function* () {
738
+ const fs = yield* FileSystem.FileSystem;
739
+ const path = yield* Path.Path;
740
+ const workspace = yield* checkpointWorkspace("legacy-v1-cutover");
741
+ const stateDir = yield* fs.makeTempDirectory({ prefix: "t3-v1-cutover-state-" });
742
+ const fixturePath = path.join(stateDir, "v1-source.sqlite");
743
+ const copyPath = path.join(stateDir, "userdata", "state.sqlite");
744
+ yield* fs.makeDirectory(path.join(stateDir, "userdata"), { recursive: true });
745
747
- const v1Snapshot = yield* seedV1Database(fixturePath, workspace);
748
- const fixtureHashBefore = yield* sha256File(fixturePath);
749
- yield* fs.copyFile(fixturePath, copyPath);
746
+ const v1Snapshot = yield* seedV1Database(fixturePath, workspace);
747
+ const fixtureHashBefore = yield* sha256File(fixturePath);
748
+ yield* fs.copyFile(fixturePath, copyPath);
749
751
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
752
- const longThreadId = ThreadId.make(LONG_THREAD);
750
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
751
+ const longThreadId = ThreadId.make(LONG_THREAD);
752
754
- const boot1Logs: CapturedLog[] = [];
755
- const firstBoot = yield* Effect.scoped(
756
- Effect.gen(function* () {
757
- const sql = yield* SqlClient.SqlClient;
758
- const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
759
- const maintenance = yield* ProjectionReplay.ProjectionReplay;
760
- const projections = yield* ProjectionStore.ProjectionStoreV2;
753
+ const boot1Logs: CapturedLog[] = [];
754
+ const firstBoot = yield* Effect.scoped(
755
+ Effect.gen(function* () {
756
+ const sql = yield* SqlClient.SqlClient;
757
+ const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
758
+ const maintenance = yield* ProjectionReplay.ProjectionReplay;
759
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
760
762
- assert.equal(yield* importer.pendingThreadCount, ALL_THREADS.length);
763
- const shellImport = yield* importer.reconcileShells;
764
- assert.deepStrictEqual(shellImport, {
765
- importedThreadCount: ALL_THREADS.length,
766
- importedMessageCount: 14,
767
- });
761
+ assert.equal(yield* importer.pendingThreadCount, ALL_THREADS.length);
762
+ const shellImport = yield* importer.reconcileShells;
763
+ assert.deepStrictEqual(shellImport, {
764
+ importedThreadCount: ALL_THREADS.length,
765
+ importedMessageCount: 14,
766
+ });
767
769
- assert.deepStrictEqual(yield* importer.reconcileShells, {
770
- importedThreadCount: 0,
771
- importedMessageCount: 0,
772
- });
773
- assert.isTrue((yield* maintenance.rebuild).valid);
768
+ assert.deepStrictEqual(yield* importer.reconcileShells, {
769
+ importedThreadCount: 0,
770
+ importedMessageCount: 0,
771
+ });
772
+ assert.isTrue((yield* maintenance.rebuild).valid);
773
775
- const shellSnapshot = yield* projections.getShellSnapshot();
776
- const visibleShellIds = [
777
- ...shellSnapshot.threads.map((thread) => thread.id),
778
- ...shellSnapshot.archivedThreads.map((thread) => thread.id),
779
- ];
780
- assert.notInclude(visibleShellIds, ThreadId.make(DELETED_THREAD));
781
- assert.include(
782
- shellSnapshot.archivedThreads.map((thread) => thread.id),
783
- ThreadId.make(ARCHIVED_THREAD),
784
- );
785
- const pinnedShell = shellSnapshot.threads.find(
786
- (thread) => thread.id === PINNED_THREAD,
787
- );
788
- assert.equal(pinnedShell?.pinOrderKey, "a0");
774
+ const shellSnapshot = yield* projections.getShellSnapshot();
775
+ const visibleShellIds = [
776
+ ...shellSnapshot.threads.map((thread) => thread.id),
777
+ ...shellSnapshot.archivedThreads.map((thread) => thread.id),
778
+ ];
779
+ assert.notInclude(visibleShellIds, ThreadId.make(DELETED_THREAD));
780
+ assert.include(
781
+ shellSnapshot.archivedThreads.map((thread) => thread.id),
782
+ ThreadId.make(ARCHIVED_THREAD),
783
+ );
784
+ const pinnedShell = shellSnapshot.threads.find((thread) => thread.id === PINNED_THREAD);
785
+ assert.equal(pinnedShell?.pinOrderKey, "a0");
786
790
- const activeShell = yield* projections.getThreadProjection(
791
- ThreadId.make(ACTIVE_THREAD),
792
- );
793
- assert.equal(activeShell.thread.historyOrigin, "v1_import");
794
- assert.isNull(activeShell.thread.activeProviderThreadId);
795
- assert.deepStrictEqual(
796
- activeShell.messages.map((message) => message.id),
797
- ["message:cutover:active:3", "message:cutover:active:4"],
798
- );
799
- assert.isEmpty(activeShell.providerThreads);
787
+ const activeShell = yield* projections.getThreadProjection(
788
+ ThreadId.make(ACTIVE_THREAD),
789
+ );
790
+ assert.equal(activeShell.thread.historyOrigin, "v1_import");
791
+ assert.isNull(activeShell.thread.activeProviderThreadId);
792
+ assert.deepStrictEqual(
793
+ activeShell.messages.map((message) => message.id),
794
+ ["message:cutover:active:3", "message:cutover:active:4"],
795
+ );
796
+ assert.isEmpty(activeShell.providerThreads);
797
801
- assert.isEmpty(
802
- activeShell.turnItems.filter(
803
- (item) => item.type !== "user_message" && item.type !== "assistant_message",
804
- ),
805
- );
798
+ assert.isEmpty(
799
+ activeShell.turnItems.filter(
800
+ (item) => item.type !== "user_message" && item.type !== "assistant_message",
801
+ ),
802
+ );
803
807
- const deletedShell = yield* projections.getThreadProjection(
808
- ThreadId.make(DELETED_THREAD),
809
- );
810
- assert.isNotNull(deletedShell.thread.deletedAt);
811
- assert.equal(
812
- deletedShell.thread.deletedAt?.toString(),
813
- DateTime.makeUnsafe("2026-01-09T00:00:00.000Z").toString(),
814
- );
804
+ const deletedShell = yield* projections.getThreadProjection(
805
+ ThreadId.make(DELETED_THREAD),
806
+ );
807
+ assert.isNotNull(deletedShell.thread.deletedAt);
808
+ assert.equal(
809
+ deletedShell.thread.deletedAt?.toString(),
810
+ DateTime.makeUnsafe("2026-01-09T00:00:00.000Z").toString(),
811
+ );
812
816
- for (const threadId of [
817
- ACTIVE_THREAD,
818
- ARCHIVED_THREAD,
819
- PINNED_THREAD,
820
- DELETED_THREAD,
821
- INTERRUPTED_THREAD,
822
- LONG_THREAD,
823
- ]) {
824
- yield* importer.ensureTranscript(ThreadId.make(threadId));
825
- }
826
- assert.deepStrictEqual(
827
- yield* importer.ensureTranscript(ThreadId.make(ACTIVE_THREAD)),
828
- { importedThreadCount: 0, importedMessageCount: 0 },
829
- );
813
+ for (const threadId of [
814
+ ACTIVE_THREAD,
815
+ ARCHIVED_THREAD,
816
+ PINNED_THREAD,
817
+ DELETED_THREAD,
818
+ INTERRUPTED_THREAD,
819
+ LONG_THREAD,
820
+ ]) {
821
+ yield* importer.ensureTranscript(ThreadId.make(threadId));
822
+ }
823
+ assert.deepStrictEqual(yield* importer.ensureTranscript(ThreadId.make(ACTIVE_THREAD)), {
824
+ importedThreadCount: 0,
825
+ importedMessageCount: 0,
826
+ });
827
831
- const active = yield* projections.getThreadProjection(ThreadId.make(ACTIVE_THREAD));
832
- assert.deepStrictEqual(
833
- active.messages.map((message) => message.id),
834
- [
835
- "message:cutover:active:1",
836
- "message:cutover:active:2",
837
- "message:cutover:active:3",
838
- "message:cutover:active:4",
839
- ],
840
- );
841
- assert.deepStrictEqual(messageOrdinals(active), [
842
- ["message:cutover:active:1", 1, "completed"],
843
- ["message:cutover:active:2", 2, "completed"],
844
- ["message:cutover:active:3", 3, "completed"],
845
- ["message:cutover:active:4", 4, "completed"],
846
- ]);
847
- assert.deepStrictEqual(
848
- active.messages.find((message) => message.id === "message:cutover:active:2")
849
- ?.attachments,
850
- [
851
- {
852
- type: "image",
853
- id: "att-1",
854
- name: "shot.png",
855
- mimeType: "image/png",
856
- sizeBytes: 1234,
857
- },
858
- ],
859
- );
860
- assert.equal(active.thread.linkedPullRequest?.number, 9100);
861
- assert.deepStrictEqual(
862
- active.thread.pullRequests?.map((pullRequest) => pullRequest.number),
863
- [9100],
864
- );
828
+ const active = yield* projections.getThreadProjection(ThreadId.make(ACTIVE_THREAD));
829
+ assert.deepStrictEqual(
830
+ active.messages.map((message) => message.id),
831
+ [
832
+ "message:cutover:active:1",
833
+ "message:cutover:active:2",
834
+ "message:cutover:active:3",
835
+ "message:cutover:active:4",
836
+ ],
837
+ );
838
+ assert.deepStrictEqual(messageOrdinals(active), [
839
+ ["message:cutover:active:1", 1, "completed"],
840
+ ["message:cutover:active:2", 2, "completed"],
841
+ ["message:cutover:active:3", 3, "completed"],
842
+ ["message:cutover:active:4", 4, "completed"],
843
+ ]);
844
+ assert.deepStrictEqual(
845
+ active.messages.find((message) => message.id === "message:cutover:active:2")
846
+ ?.attachments,
847
+ [
848
+ {
849
+ type: "image",
850
+ id: "att-1",
851
+ name: "shot.png",
852
+ mimeType: "image/png",
853
+ sizeBytes: 1234,
854
+ },
855
+ ],
856
+ );
857
+ assert.equal(active.thread.linkedPullRequest?.number, 9100);
858
+ assert.deepStrictEqual(
859
+ active.thread.pullRequests?.map((pullRequest) => pullRequest.number),
860
+ [9100],
861
+ );
862
866
- const archived = yield* projections.getThreadProjection(
867
- ThreadId.make(ARCHIVED_THREAD),
868
- );
869
- assert.isNotNull(archived.thread.archivedAt);
870
- const pinned = yield* projections.getThreadProjection(ThreadId.make(PINNED_THREAD));
871
- assert.isNotNull(pinned.thread.pinnedAt);
872
- assert.equal(pinned.thread.pinOrderKey, "a0");
873
- const snoozed = yield* projections.getThreadProjection(ThreadId.make(SNOOZED_THREAD));
874
- assert.equal(
875
- snoozed.thread.snoozedUntil?.toString(),
876
- DateTime.makeUnsafe("2026-02-01T00:00:00.000Z").toString(),
877
- );
863
+ const archived = yield* projections.getThreadProjection(ThreadId.make(ARCHIVED_THREAD));
864
+ assert.isNotNull(archived.thread.archivedAt);
865
+ const pinned = yield* projections.getThreadProjection(ThreadId.make(PINNED_THREAD));
866
+ assert.isNotNull(pinned.thread.pinnedAt);
867
+ assert.equal(pinned.thread.pinOrderKey, "a0");
868
+ const snoozed = yield* projections.getThreadProjection(ThreadId.make(SNOOZED_THREAD));
869
+ assert.equal(
870
+ snoozed.thread.snoozedUntil?.toString(),
871
+ DateTime.makeUnsafe("2026-02-01T00:00:00.000Z").toString(),
872
+ );
873
879
- assert.deepStrictEqual(
880
- snoozed.messages.map((message) => message.id),
881
- ["message:cutover:snoozed:1", "message:cutover:snoozed:3"],
882
- );
883
- const snoozedImportRow = yield* sql<{
884
- readonly transcript_imported_at: string | null;
885
- }>`
874
+ assert.deepStrictEqual(
875
+ snoozed.messages.map((message) => message.id),
876
+ ["message:cutover:snoozed:1", "message:cutover:snoozed:3"],
877
+ );
878
+ const snoozedImportRow = yield* sql<{
879
+ readonly transcript_imported_at: string | null;
880
+ }>`
881
SELECT transcript_imported_at
882
FROM orchestration_v2_legacy_imports
883
WHERE thread_id = ${SNOOZED_THREAD}
884
`;
890
- assert.isNull(snoozedImportRow[0]?.transcript_imported_at);
885
+ assert.isNull(snoozedImportRow[0]?.transcript_imported_at);
886
892
- // A failed hydration leaves the legacy rows and pending marker
893
- // available for retry in a fresh runtime after restart.
894
- yield* sql`
887
+ // A failed hydration leaves the legacy rows and pending marker
888
+ // available for retry in a fresh runtime after restart.
889
+ yield* sql`
890
CREATE TRIGGER fail_snoozed_hydration
891
BEFORE INSERT ON orchestration_events
892
WHEN NEW.event_id = 'migration:v1:message:message:cutover:snoozed:2'
@@ -899,253 +894,246 @@ describe("orchestration v2 legacy v1 cutover", () => {
894
SELECT RAISE(ABORT, 'injected cutover hydration failure');
895
END
896
`;
902
- const hydrationError = yield* importer
903
- .ensureTranscript(ThreadId.make(SNOOZED_THREAD))
904
- .pipe(Effect.flip);
905
- assert.equal(hydrationError._tag, "LegacyV1ThreadImportError");
906
- assert.equal(yield* importer.pendingThreadCount, 1);
897
+ const hydrationError = yield* importer
898
+ .ensureTranscript(ThreadId.make(SNOOZED_THREAD))
899
+ .pipe(Effect.flip);
900
+ assert.equal(hydrationError._tag, "LegacyV1ThreadImportError");
901
+ assert.equal(yield* importer.pendingThreadCount, 1);
902
908
- const interrupted = yield* projections.getThreadProjection(
909
- ThreadId.make(INTERRUPTED_THREAD),
910
- );
911
- assert.deepStrictEqual(messageOrdinals(interrupted), [
912
- ["message:cutover:interrupted:1", 1, "completed"],
913
- ["message:cutover:interrupted:2", 2, "interrupted"],
914
- ]);
903
+ const interrupted = yield* projections.getThreadProjection(
904
+ ThreadId.make(INTERRUPTED_THREAD),
905
+ );
906
+ assert.deepStrictEqual(messageOrdinals(interrupted), [
907
+ ["message:cutover:interrupted:1", 1, "completed"],
908
+ ["message:cutover:interrupted:2", 2, "interrupted"],
909
+ ]);
910
916
- const continued = yield* dispatchMessageAwaitingRun({
917
- threadId: longThreadId,
918
- messageId: "message:cutover:long:continuation",
919
- commandId: "command:cutover:continue",
920
- text: CONTINUATION_PROMPT,
921
- });
911
+ const continued = yield* dispatchMessageAwaitingRun({
912
+ threadId: longThreadId,
913
+ messageId: "message:cutover:long:continuation",
914
+ commandId: "command:cutover:continue",
915
+ text: CONTINUATION_PROMPT,
916
+ });
917
923
- const runs = continued.runs.filter((run) => run.ordinal >= 1);
924
- assert.equal(runs.at(-1)?.status, "completed");
925
- assert.equal(continued.providerThreads.length, 1);
926
- assert.isNotNull(continued.providerThreads[0]?.nativeThreadRef);
927
- assert.equal(continued.contextHandoffs.length, 1);
928
- const handoff = continued.contextHandoffs[0]!;
929
- assert.equal(handoff.strategy, "manual_context");
930
- assert.isAtMost(handoff.summaryText.length, 32_000);
931
- assert.include(handoff.summaryText, LATEST_MARKER);
932
- assert.notInclude(handoff.summaryText, EARLIEST_MARKER);
933
- const turns = yield* Ref.get(capturedTurns);
934
- assert.equal(turns.length, 1);
935
- assert.include(turns[0]!.text, "Context handoff (manual_context):");
936
- assert.include(turns[0]!.text, `User message:\n${CONTINUATION_PROMPT}`);
918
+ const runs = continued.runs.filter((run) => run.ordinal >= 1);
919
+ assert.equal(runs.at(-1)?.status, "completed");
920
+ assert.equal(continued.providerThreads.length, 1);
921
+ assert.isNotNull(continued.providerThreads[0]?.nativeThreadRef);
922
+ assert.equal(continued.contextHandoffs.length, 1);
923
+ const handoff = continued.contextHandoffs[0]!;
924
+ assert.equal(handoff.strategy, "manual_context");
925
+ assert.isAtMost(handoff.summaryText.length, 32_000);
926
+ assert.include(handoff.summaryText, LATEST_MARKER);
927
+ assert.notInclude(handoff.summaryText, EARLIEST_MARKER);
928
+ const turns = yield* Ref.get(capturedTurns);
929
+ assert.equal(turns.length, 1);
930
+ assert.include(turns[0]!.text, "Context handoff (manual_context):");
931
+ assert.include(turns[0]!.text, `User message:\n${CONTINUATION_PROMPT}`);
932
938
- const continuedAgain = yield* dispatchMessageAwaitingRun({
939
- threadId: longThreadId,
940
- messageId: "message:cutover:long:continuation:2",
941
- commandId: "command:cutover:continue:again",
942
- text: "One more.",
943
- });
944
- assert.equal(continuedAgain.contextHandoffs.length, 1);
945
- assert.equal((yield* Ref.get(capturedTurns)).length, 2);
933
+ const continuedAgain = yield* dispatchMessageAwaitingRun({
934
+ threadId: longThreadId,
935
+ messageId: "message:cutover:long:continuation:2",
936
+ commandId: "command:cutover:continue:again",
937
+ text: "One more.",
938
+ });
939
+ assert.equal(continuedAgain.contextHandoffs.length, 1);
940
+ assert.equal((yield* Ref.get(capturedTurns)).length, 2);
941
947
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
948
- yield* worker.drain();
942
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
943
+ yield* worker.drain();
944
950
- const migrationEventCount = yield* sql<{ readonly count: number }>`
945
+ const migrationEventCount = yield* sql<{ readonly count: number }>`
946
SELECT COUNT(*) AS count
947
FROM orchestration_events
948
WHERE application_event_version = 2
949
AND event_id LIKE 'migration:v1:%'
950
`;
956
- const importRows = yield* sql<{
957
- readonly thread_id: string;
958
- readonly transcript_imported_at: string | null;
959
- }>`
951
+ const importRows = yield* sql<{
952
+ readonly thread_id: string;
953
+ readonly transcript_imported_at: string | null;
954
+ }>`
955
SELECT thread_id, transcript_imported_at
956
FROM orchestration_v2_legacy_imports
957
ORDER BY thread_id
958
`;
964
- const legacyProjects = yield* sql<Record<string, unknown>>`
959
+ const legacyProjects = yield* sql<Record<string, unknown>>`
960
SELECT * FROM projection_projects ORDER BY project_id
961
`;
967
- const legacyThreads = yield* sql<Record<string, unknown>>`
962
+ const legacyThreads = yield* sql<Record<string, unknown>>`
963
SELECT * FROM projection_threads ORDER BY thread_id
964
`;
970
- const legacyMessages = yield* sql<Record<string, unknown>>`
965
+ const legacyMessages = yield* sql<Record<string, unknown>>`
966
SELECT * FROM projection_thread_messages ORDER BY message_id
967
`;
973
- const recordedMigration41 = yield* sql<{ readonly name: string }>`
968
+ const recordedMigration41 = yield* sql<{ readonly name: string }>`
969
SELECT name FROM effect_sql_migrations WHERE migration_id = 41
970
`;
976
- const authSessionColumns = yield* sql<{ readonly name: string }>`
971
+ const authSessionColumns = yield* sql<{ readonly name: string }>`
972
PRAGMA table_info(auth_sessions)
973
`;
979
- return {
980
- migrationEventCount: migrationEventCount[0]?.count ?? 0,
981
- importRows,
982
- legacyProjects,
983
- legacyThreads,
984
- legacyMessages,
985
- longProjection: continuedAgain,
986
- migration41Name: recordedMigration41[0]?.name ?? null,
987
- authSessionColumnNames: authSessionColumns.map((column) => column.name),
988
- };
989
- }).pipe(
990
- Effect.provide(
991
- layerBoot({
992
- name: "legacy-v1-cutover-first",
993
- dbPath: copyPath,
994
- workspace,
995
- capturedTurns,
996
- }),
997
- ),
998
- Effect.provideService(
999
- Logger.CurrentLoggers,
1000
- new Set([makeCapturingLogger(boot1Logs)]),
1001
- ),
974
+ return {
975
+ migrationEventCount: migrationEventCount[0]?.count ?? 0,
976
+ importRows,
977
+ legacyProjects,
978
+ legacyThreads,
979
+ legacyMessages,
980
+ longProjection: continuedAgain,
981
+ migration41Name: recordedMigration41[0]?.name ?? null,
982
+ authSessionColumnNames: authSessionColumns.map((column) => column.name),
983
+ };
984
+ }).pipe(
985
+ Effect.provide(
986
+ layerBoot({
987
+ name: "legacy-v1-cutover-first",
988
+ dbPath: copyPath,
989
+ workspace,
990
+ capturedTurns,
991
+ }),
992
),
1003
- );
993
+ Effect.provideService(Logger.CurrentLoggers, new Set([makeCapturingLogger(boot1Logs)])),
994
+ ),
995
+ );
996
1005
- const divergenceLog = boot1Logs.find((log) =>
1006
- String(log.message).includes("migration history diverges"),
1007
- );
1008
- assert.deepStrictEqual(divergenceLog?.annotations.divergent, [
1009
- "41:ThreadSummaryTimeline (this build: AuthSessionClientConnection)",
1010
- ]);
1011
- assert.equal(firstBoot.migration41Name, "ThreadSummaryTimeline");
997
+ const divergenceLog = boot1Logs.find((log) =>
998
+ String(log.message).includes("migration history diverges"),
999
+ );
1000
+ assert.deepStrictEqual(divergenceLog?.annotations.divergent, [
1001
+ "41:ThreadSummaryTimeline (this build: AuthSessionClientConnection)",
1002
+ ]);
1003
+ assert.equal(firstBoot.migration41Name, "ThreadSummaryTimeline");
1004
1013
- assert.notInclude(firstBoot.authSessionColumnNames, "client_surface");
1014
- assert.notInclude(firstBoot.authSessionColumnNames, "client_app_version");
1005
+ assert.notInclude(firstBoot.authSessionColumnNames, "client_surface");
1006
+ assert.notInclude(firstBoot.authSessionColumnNames, "client_app_version");
1007
1016
- // Full row contents of the legacy recovery tables survive migration
1017
- // and continuation unchanged, not just their counts.
1018
- assert.deepStrictEqual(
1019
- restrictToSnapshotColumns(firstBoot.legacyProjects, v1Snapshot.projects),
1020
- v1Snapshot.projects.rows,
1021
- );
1022
- assert.deepStrictEqual(
1023
- restrictToSnapshotColumns(firstBoot.legacyThreads, v1Snapshot.threads),
1024
- v1Snapshot.threads.rows,
1025
- );
1026
- assert.deepStrictEqual(
1027
- restrictToSnapshotColumns(firstBoot.legacyMessages, v1Snapshot.messages),
1028
- v1Snapshot.messages.rows,
1029
- );
1008
+ // Full row contents of the legacy recovery tables survive migration
1009
+ // and continuation unchanged, not just their counts.
1010
+ assert.deepStrictEqual(
1011
+ restrictToSnapshotColumns(firstBoot.legacyProjects, v1Snapshot.projects),
1012
+ v1Snapshot.projects.rows,
1013
+ );
1014
+ assert.deepStrictEqual(
1015
+ restrictToSnapshotColumns(firstBoot.legacyThreads, v1Snapshot.threads),
1016
+ v1Snapshot.threads.rows,
1017
+ );
1018
+ assert.deepStrictEqual(
1019
+ restrictToSnapshotColumns(firstBoot.legacyMessages, v1Snapshot.messages),
1020
+ v1Snapshot.messages.rows,
1021
+ );
1022
1031
- assert.equal(firstBoot.importRows.length, ALL_THREADS.length);
1032
- const unhydratedRows = firstBoot.importRows.filter(
1033
- (row) => row.transcript_imported_at === null,
1034
- );
1035
- assert.deepStrictEqual(
1036
- unhydratedRows.map((row) => row.thread_id),
1037
- [SNOOZED_THREAD],
1038
- );
1023
+ assert.equal(firstBoot.importRows.length, ALL_THREADS.length);
1024
+ const unhydratedRows = firstBoot.importRows.filter(
1025
+ (row) => row.transcript_imported_at === null,
1026
+ );
1027
+ assert.deepStrictEqual(
1028
+ unhydratedRows.map((row) => row.thread_id),
1029
+ [SNOOZED_THREAD],
1030
+ );
1031
1040
- const boot2Logs: CapturedLog[] = [];
1041
- yield* Effect.scoped(
1042
- Effect.gen(function* () {
1043
- const sql = yield* SqlClient.SqlClient;
1044
- const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
1045
- const projections = yield* ProjectionStore.ProjectionStoreV2;
1032
+ const boot2Logs: CapturedLog[] = [];
1033
+ yield* Effect.scoped(
1034
+ Effect.gen(function* () {
1035
+ const sql = yield* SqlClient.SqlClient;
1036
+ const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
1037
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
1038
1047
- assert.equal(yield* importer.pendingThreadCount, 1);
1048
- assert.deepStrictEqual(yield* importer.reconcileShells, {
1039
+ assert.equal(yield* importer.pendingThreadCount, 1);
1040
+ assert.deepStrictEqual(yield* importer.reconcileShells, {
1041
+ importedThreadCount: 0,
1042
+ importedMessageCount: 0,
1043
+ });
1044
+ yield* sql`DROP TRIGGER fail_snoozed_hydration`;
1045
+ assert.deepStrictEqual(
1046
+ yield* importer.ensureTranscript(ThreadId.make(SNOOZED_THREAD)),
1047
+ { importedThreadCount: 1, importedMessageCount: 1 },
1048
+ );
1049
+ const snoozed = yield* projections.getThreadProjection(ThreadId.make(SNOOZED_THREAD));
1050
+ assert.deepStrictEqual(
1051
+ snoozed.messages.map((message) => message.id),
1052
+ [
1053
+ "message:cutover:snoozed:1",
1054
+ "message:cutover:snoozed:2",
1055
+ "message:cutover:snoozed:3",
1056
+ ],
1057
+ );
1058
+ assert.equal(yield* importer.pendingThreadCount, 0);
1059
+ for (const threadId of ALL_THREADS) {
1060
+ assert.deepStrictEqual(yield* importer.ensureTranscript(ThreadId.make(threadId)), {
1061
importedThreadCount: 0,
1062
importedMessageCount: 0,
1063
});
1052
- yield* sql`DROP TRIGGER fail_snoozed_hydration`;
1053
- assert.deepStrictEqual(
1054
- yield* importer.ensureTranscript(ThreadId.make(SNOOZED_THREAD)),
1055
- { importedThreadCount: 1, importedMessageCount: 1 },
1056
- );
1057
- const snoozed = yield* projections.getThreadProjection(ThreadId.make(SNOOZED_THREAD));
1058
- assert.deepStrictEqual(
1059
- snoozed.messages.map((message) => message.id),
1060
- [
1061
- "message:cutover:snoozed:1",
1062
- "message:cutover:snoozed:2",
1063
- "message:cutover:snoozed:3",
1064
- ],
1065
- );
1066
- assert.equal(yield* importer.pendingThreadCount, 0);
1067
- for (const threadId of ALL_THREADS) {
1068
- assert.deepStrictEqual(yield* importer.ensureTranscript(ThreadId.make(threadId)), {
1069
- importedThreadCount: 0,
1070
- importedMessageCount: 0,
1071
- });
1072
- }
1073
- const migrationEventCount = yield* sql<{ readonly count: number }>`
1064
+ }
1065
+ const migrationEventCount = yield* sql<{ readonly count: number }>`
1066
SELECT COUNT(*) AS count
1067
FROM orchestration_events
1068
WHERE application_event_version = 2
1069
AND event_id LIKE 'migration:v1:%'
1070
`;
1071
1080
- assert.equal(migrationEventCount[0]?.count, firstBoot.migrationEventCount + 2);
1072
+ assert.equal(migrationEventCount[0]?.count, firstBoot.migrationEventCount + 2);
1073
1082
- const restarted = yield* projections.getThreadProjection(longThreadId);
1083
- assert.equal(restarted.thread.historyOrigin, "v1_import");
1084
- assert.equal(restarted.contextHandoffs.length, 1);
1085
- assert.isNotNull(restarted.thread.activeProviderThreadId);
1086
- assert.deepStrictEqual(
1087
- restarted.runs.map((run) => run.status),
1088
- firstBoot.longProjection.runs.map((run) => run.status),
1089
- );
1074
+ const restarted = yield* projections.getThreadProjection(longThreadId);
1075
+ assert.equal(restarted.thread.historyOrigin, "v1_import");
1076
+ assert.equal(restarted.contextHandoffs.length, 1);
1077
+ assert.isNotNull(restarted.thread.activeProviderThreadId);
1078
+ assert.deepStrictEqual(
1079
+ restarted.runs.map((run) => run.status),
1080
+ firstBoot.longProjection.runs.map((run) => run.status),
1081
+ );
1082
1091
- assert.deepStrictEqual(
1092
- restrictToSnapshotColumns(
1093
- yield* sql<Record<string, unknown>>`
1083
+ assert.deepStrictEqual(
1084
+ restrictToSnapshotColumns(
1085
+ yield* sql<Record<string, unknown>>`
1086
SELECT * FROM projection_projects ORDER BY project_id
1087
`,
1096
- v1Snapshot.projects,
1097
- ),
1098
- v1Snapshot.projects.rows,
1099
- );
1100
- assert.deepStrictEqual(
1101
- restrictToSnapshotColumns(
1102
- yield* sql<Record<string, unknown>>`
1088
+ v1Snapshot.projects,
1089
+ ),
1090
+ v1Snapshot.projects.rows,
1091
+ );
1092
+ assert.deepStrictEqual(
1093
+ restrictToSnapshotColumns(
1094
+ yield* sql<Record<string, unknown>>`
1095
SELECT * FROM projection_threads ORDER BY thread_id
1096
`,
1105
- v1Snapshot.threads,
1106
- ),
1107
- v1Snapshot.threads.rows,
1108
- );
1109
- assert.deepStrictEqual(
1110
- restrictToSnapshotColumns(
1111
- yield* sql<Record<string, unknown>>`
1097
+ v1Snapshot.threads,
1098
+ ),
1099
+ v1Snapshot.threads.rows,
1100
+ );
1101
+ assert.deepStrictEqual(
1102
+ restrictToSnapshotColumns(
1103
+ yield* sql<Record<string, unknown>>`
1104
SELECT * FROM projection_thread_messages ORDER BY message_id
1105
`,
1114
- v1Snapshot.messages,
1115
- ),
1116
- v1Snapshot.messages.rows,
1117
- );
1118
- const quickCheck = yield* sql<{ readonly quick_check: string }>`
1106
+ v1Snapshot.messages,
1107
+ ),
1108
+ v1Snapshot.messages.rows,
1109
+ );
1110
+ const quickCheck = yield* sql<{ readonly quick_check: string }>`
1111
PRAGMA quick_check
1112
`;
1121
- assert.deepStrictEqual(
1122
- quickCheck.map((row) => row.quick_check),
1123
- ["ok"],
1124
- );
1125
- }).pipe(
1126
- Effect.provide(
1127
- layerBoot({
1128
- name: "legacy-v1-cutover-restart",
1129
- dbPath: copyPath,
1130
- workspace,
1131
- capturedTurns,
1132
- }),
1133
- ),
1134
- Effect.provideService(
1135
- Logger.CurrentLoggers,
1136
- new Set([makeCapturingLogger(boot2Logs)]),
1137
- ),
1113
+ assert.deepStrictEqual(
1114
+ quickCheck.map((row) => row.quick_check),
1115
+ ["ok"],
1116
+ );
1117
+ }).pipe(
1118
+ Effect.provide(
1119
+ layerBoot({
1120
+ name: "legacy-v1-cutover-restart",
1121
+ dbPath: copyPath,
1122
+ workspace,
1123
+ capturedTurns,
1124
+ }),
1125
),
1139
- );
1126
+ Effect.provideService(Logger.CurrentLoggers, new Set([makeCapturingLogger(boot2Logs)])),
1127
+ ),
1128
+ );
1129
1141
- assert.isTrue(
1142
- boot2Logs.some((log) => String(log.message).includes("migration history diverges")),
1143
- );
1130
+ assert.isTrue(
1131
+ boot2Logs.some((log) => String(log.message).includes("migration history diverges")),
1132
+ );
1133
1145
- // The seeded source file is the untouched recovery copy: migration
1146
- // only ever ran against the file copied out of it.
1147
- assert.equal(yield* sha256File(fixturePath), fixtureHashBefore);
1148
- }).pipe(Effect.provide(NodeServices.layer)),
1149
- ),
1134
+ // The seeded source file is the untouched recovery copy: migration
1135
+ // only ever ran against the file copied out of it.
1136
+ assert.equal(yield* sha256File(fixturePath), fixtureHashBefore);
1137
+ }).pipe(Effect.provide(NodeServices.layer)),
1138
);
1139
});
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+109
-111
@@ -4778,122 +4778,120 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
4778
it.effect(
4779
"reads a watched pull request when the host reports a change, and wakes once per change",
4780
() =>
4781
- Effect.scoped(
4782
- Effect.gen(function* () {
4783
- const orchestrator = yield* Orchestrator.OrchestratorV2;
4784
- const threadId = ThreadId.make("runtime-pull-request-watch-host-event");
4785
- const projectId = ProjectId.make("pr-watch-host-event-project");
4786
- yield* seedProject({
4787
- projectId,
4788
- title: "Watch host events",
4789
- workspaceRoot: "/workspace/watch-host-event",
4790
- defaultModelSelection: null,
4791
- createdAt: "2026-10-01T00:00:00.000Z",
4792
- });
4793
- yield* orchestrator.dispatch({
4794
- type: "thread.create",
4795
- createdBy: "user",
4796
- creationSource: "web",
4797
- commandId: CommandId.make("pr-watch-host-event-create"),
4798
- threadId,
4799
- projectId,
4800
- title: "Watch host events",
4801
- modelSelection,
4802
- runtimeMode: "full-access",
4803
- interactionMode: "default",
4804
- branch: null,
4805
- worktreePath: null,
4806
- });
4807
- const key = { host: "github.com", repository: "pingdotgg/t3code", number: 15 };
4808
- yield* orchestrator.dispatch({
4809
- type: "thread.pull-request.watch",
4810
- commandId: CommandId.make("pr-watch-host-event-start"),
4811
- threadId,
4812
- ...key,
4813
- watching: true,
4814
- link: { url: "https://github.com/pingdotgg/t3code/pull/15", source: "agent" },
4815
- });
4781
+ Effect.gen(function* () {
4782
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
4783
+ const threadId = ThreadId.make("runtime-pull-request-watch-host-event");
4784
+ const projectId = ProjectId.make("pr-watch-host-event-project");
4785
+ yield* seedProject({
4786
+ projectId,
4787
+ title: "Watch host events",
4788
+ workspaceRoot: "/workspace/watch-host-event",
4789
+ defaultModelSelection: null,
4790
+ createdAt: "2026-10-01T00:00:00.000Z",
4791
+ });
4792
+ yield* orchestrator.dispatch({
4793
+ type: "thread.create",
4794
+ createdBy: "user",
4795
+ creationSource: "web",
4796
+ commandId: CommandId.make("pr-watch-host-event-create"),
4797
+ threadId,
4798
+ projectId,
4799
+ title: "Watch host events",
4800
+ modelSelection,
4801
+ runtimeMode: "full-access",
4802
+ interactionMode: "default",
4803
+ branch: null,
4804
+ worktreePath: null,
4805
+ });
4806
+ const key = { host: "github.com", repository: "pingdotgg/t3code", number: 15 };
4807
+ yield* orchestrator.dispatch({
4808
+ type: "thread.pull-request.watch",
4809
+ commandId: CommandId.make("pr-watch-host-event-start"),
4810
+ threadId,
4811
+ ...key,
4812
+ watching: true,
4813
+ link: { url: "https://github.com/pingdotgg/t3code/pull/15", source: "agent" },
4814
+ });
4815
4817
- let checks: PullRequestDetail["checks"] = [
4818
- { name: "lint", status: "pending", description: null, url: null, required: true },
4819
- ];
4820
- let fingerprints = 0;
4821
- const events = yield* Queue.unbounded<void>();
4822
- const following = yield* Deferred.make<void>();
4823
- const detailReads = yield* Queue.unbounded<void>();
4824
- const host = Layer.mergeAll(
4825
- NodeServices.layer,
4826
- NodeCrypto.layer,
4827
- Layer.mock(PullRequestService.PullRequestService)({
4828
- detail: () =>
4829
- Queue.offer(detailReads, undefined).pipe(
4830
- Effect.as({
4831
- ...watchedPullRequestDetail({
4832
- projectId,
4833
- number: 15,
4834
- at: "2026-10-02T12:00:00.000Z",
4835
- }),
4836
- headSha: "aaaaaaaaaa",
4837
- checks,
4816
+ let checks: PullRequestDetail["checks"] = [
4817
+ { name: "lint", status: "pending", description: null, url: null, required: true },
4818
+ ];
4819
+ let fingerprints = 0;
4820
+ const events = yield* Queue.unbounded<void>();
4821
+ const following = yield* Deferred.make<void>();
4822
+ const detailReads = yield* Queue.unbounded<void>();
4823
+ const host = Layer.mergeAll(
4824
+ NodeServices.layer,
4825
+ NodeCrypto.layer,
4826
+ Layer.mock(PullRequestService.PullRequestService)({
4827
+ detail: () =>
4828
+ Queue.offer(detailReads, undefined).pipe(
4829
+ Effect.as({
4830
+ ...watchedPullRequestDetail({
4831
+ projectId,
4832
+ number: 15,
4833
+ at: "2026-10-02T12:00:00.000Z",
4834
}),
4839
- ),
4840
- activity: () =>
4841
- Effect.succeed({
4842
- comments: [],
4843
- commentCount: 0,
4844
- commentsTruncated: false,
4845
- reviewThreads: [],
4846
- commits: [],
4835
+ headSha: "aaaaaaaaaa",
4836
+ checks,
4837
}),
4848
- // A fresh fingerprint every time, so every pass reads the detail.
4849
- watchFingerprint: () =>
4850
- Effect.sync(() => ({ status: String(++fingerprints), remarks: "" })),
4851
- invalidate: () => Effect.void,
4852
- changes: () =>
4853
- Stream.fromEffectDrain(Deferred.succeed(following, undefined)).pipe(
4854
- Stream.concat(Stream.fromQueue(events)),
4855
- ),
4856
- }),
4857
- );
4858
- const wakes = Effect.map(
4859
- orchestrator.getThreadRecords(threadId, ["messages"]),
4860
- ({ messages }) =>
4861
- messages.filter(
4862
- (message) => message.notification !== undefined && message.notification !== null,
4838
),
4864
- );
4865
- const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4866
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4867
- yield* reactor.start();
4868
- // The feed starts after the first sweep has read the pull request.
4869
- yield* Deferred.await(following);
4870
- yield* Queue.take(detailReads);
4871
-
4872
- checks = [
4873
- { name: "lint", status: "failure", description: null, url: null, required: true },
4874
- ];
4875
- yield* Queue.offer(events, undefined);
4876
- // The clock never moves, so no sweep can be the one that reads the failure.
4877
- yield* Queue.take(detailReads);
4878
- // Nothing new: this read must compare against the watch the last one recorded.
4879
- yield* Queue.offer(events, undefined);
4880
- yield* Queue.take(detailReads);
4881
- // A sweep waits for the change read in flight.
4882
- yield* reactor.sweep;
4883
- yield* worker.drain();
4884
- const woken = yield* wakes;
4885
- assert.lengthOf(woken, 1);
4886
- assert.include(woken[0]!.notification?.summary ?? "", "failed");
4839
+ activity: () =>
4840
+ Effect.succeed({
4841
+ comments: [],
4842
+ commentCount: 0,
4843
+ commentsTruncated: false,
4844
+ reviewThreads: [],
4845
+ commits: [],
4846
+ }),
4847
+ // A fresh fingerprint every time, so every pass reads the detail.
4848
+ watchFingerprint: () =>
4849
+ Effect.sync(() => ({ status: String(++fingerprints), remarks: "" })),
4850
+ invalidate: () => Effect.void,
4851
+ changes: () =>
4852
+ Stream.fromEffectDrain(Deferred.succeed(following, undefined)).pipe(
4853
+ Stream.concat(Stream.fromQueue(events)),
4854
+ ),
4855
+ }),
4856
+ );
4857
+ const wakes = Effect.map(
4858
+ orchestrator.getThreadRecords(threadId, ["messages"]),
4859
+ ({ messages }) =>
4860
+ messages.filter(
4861
+ (message) => message.notification !== undefined && message.notification !== null,
4862
+ ),
4863
+ );
4864
+ const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4865
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
4866
+ yield* reactor.start();
4867
+ // The feed starts after the first sweep has read the pull request.
4868
+ yield* Deferred.await(following);
4869
+ yield* Queue.take(detailReads);
4870
4888
- yield* orchestrator.dispatch({
4889
- type: "thread.pull-request.watch",
4890
- commandId: CommandId.make("pr-watch-host-event-end"),
4891
- threadId,
4892
- ...key,
4893
- watching: false,
4894
- });
4895
- }),
4896
- ),
4871
+ checks = [
4872
+ { name: "lint", status: "failure", description: null, url: null, required: true },
4873
+ ];
4874
+ yield* Queue.offer(events, undefined);
4875
+ // The clock never moves, so no sweep can be the one that reads the failure.
4876
+ yield* Queue.take(detailReads);
4877
+ // Nothing new: this read must compare against the watch the last one recorded.
4878
+ yield* Queue.offer(events, undefined);
4879
+ yield* Queue.take(detailReads);
4880
+ // A sweep waits for the change read in flight.
4881
+ yield* reactor.sweep;
4882
+ yield* worker.drain();
4883
+ const woken = yield* wakes;
4884
+ assert.lengthOf(woken, 1);
4885
+ assert.include(woken[0]!.notification?.summary ?? "", "failed");
4886
+
4887
+ yield* orchestrator.dispatch({
4888
+ type: "thread.pull-request.watch",
4889
+ commandId: CommandId.make("pr-watch-host-event-end"),
4890
+ threadId,
4891
+ ...key,
4892
+ watching: false,
4893
+ });
4894
+ }),
4895
);
4896
4897
it.effect("wakes for checks that complete after the no-checks notice on the same head", () =>
apps/server/src/orchestration-v2/testkit/OpenCode2PendingSnapshots.evidence.test.ts
+1
-4
@@ -151,9 +151,6 @@ const runRow = (row: Row) =>
151
152
describe("OpenCode 2 pending-work snapshots (#19228 evidence)", () => {
153
it.effect.each(ROWS.map((row) => [`${row.id} ${row.fixture}`, row] as const))("%s", ([, row]) =>
154
- runRow(row).pipe(
155
- Effect.map((failures) => assert.deepEqual(failures, [])),
156
- Effect.scoped,
157
- ),
154
+ runRow(row).pipe(Effect.map((failures) => assert.deepEqual(failures, []))),
155
);
156
});
apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
+294
-304
@@ -275,351 +275,341 @@ describe("orchestrator replay recovery", () => {
275
it.effect(
276
"resumes a provider-native Codex thread after recreating the orchestrator runtime",
277
() =>
278
- Effect.scoped(
279
- Effect.gen(function* () {
280
- // Use a throwaway checkpoint workspace; cold full-repo capture exceeds CI wait budgets.
281
- const workspace = yield* checkpointWorkspace("provider_thread_resume");
282
- const transcript = yield* readCodexTranscript(workspace);
283
- const fs = yield* FileSystem.FileSystem;
284
- const path = yield* Path.Path;
285
- const tempDir = yield* Effect.acquireRelease(
286
- fs.makeTempDirectory({
287
- prefix: "t3-orchestration-v2-recovery-",
288
- }),
289
- (directory) =>
290
- fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
291
- );
292
- yield* fs.makeDirectory(tempDir, { recursive: true });
293
- const dbPath = path.join(tempDir, "state.sqlite");
294
- const driver = yield* CodexReplay.makeReplayDriver(transcript);
295
- const materialized = yield* materializeFixtureInput({
296
- scenario: "provider_thread_resume",
297
- fixtureInput: {
298
- steps: [
299
- { type: "message", text: PROVIDER_THREAD_RESUME_FIRST_PROMPT },
300
- { type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT },
301
- ],
302
- },
303
- driver: ProviderDriverKind.make("codex"),
304
- modelSelection: CODEX_MODEL_SELECTION,
305
- });
306
- const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
307
- splitAfterFirstIdle(materialized);
308
-
309
- const harness = {
310
- ...CodexOrchestratorReplayHarness,
311
- makeProviderAdapterRegistryLayer: () =>
312
- CodexAdapterV2Testkit.layer({ transcript, driver }),
313
- };
314
- const options = {
315
- databaseLayer: SqlitePersistence.layerFromPath(dbPath).pipe(
316
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
317
- ),
318
- };
319
-
320
- yield* runOrchestratorV2ProviderReplayScenario(
321
- {
322
- name: "provider_thread_resume/codex:first-runtime",
323
- transcript,
324
- commands: phase1Commands,
325
- steps: phase1Steps,
326
- projectionThreadIds: materialized.projectionThreadIds,
327
- runtimePolicyOverride: { cwd: workspace },
328
- },
329
- harness,
330
- options,
331
- );
332
-
333
- const result = yield* runOrchestratorV2ProviderReplayScenario(
334
- {
335
- name: "provider_thread_resume/codex:second-runtime",
336
- transcript,
337
- commands: phase2Commands,
338
- steps: phase2Steps,
339
- projectionThreadIds: materialized.projectionThreadIds,
340
- runtimePolicyOverride: { cwd: workspace },
341
- },
342
- harness,
343
- { ...options, recoverOnStartup: true },
344
- );
345
-
346
- assertBaseProjection({
347
- result,
348
- transcript,
349
- runCount: 2,
350
- runStatuses: ["completed", "completed"],
351
- });
352
- const projection = projectionFor(result, transcript.scenario);
353
- assertSemanticProjectionIntegrity(projection);
354
- assertRunOrdinals(projection, [1, 2]);
355
- assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
356
- assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
357
- assertUserMessagesInclude(projection, [
358
- PROVIDER_THREAD_RESUME_FIRST_PROMPT,
359
- PROVIDER_THREAD_RESUME_SECOND_PROMPT,
360
- ]);
361
- assertAssistantTextIncludes(projection, FIRST_FINAL);
362
- assertAssistantTextIncludes(projection, SECOND_FINAL);
363
- assert.lengthOf(projection.providerThreads, 1);
364
- }).pipe(
365
- provideDeterministicTestRuntime,
366
- Effect.provide(
367
- Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
368
- ),
369
- ),
370
- ),
371
- );
372
-
373
- it.effect(
374
- "resumes a provider-native Cursor thread after recreating the orchestrator runtime",
375
- () =>
376
- Effect.scoped(
377
- Effect.gen(function* () {
378
- const transcript = yield* readCursorTranscript();
379
- const runner = makeCursorAgentSdkReplayRunner(transcript);
380
- yield* runCursorRecovery({ transcript, runner });
381
- yield* runner.assertComplete;
382
- }).pipe(
383
- provideDeterministicTestRuntime,
384
- Effect.provide(
385
- Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
386
- ),
387
- ),
388
- ),
389
- );
390
- it.effect("keeps a Claude subagent resumed after a server restart in its own thread", () =>
391
- Effect.scoped(
278
Effect.gen(function* () {
393
- const transcript = yield* readClaudeSubagentResumeTranscript();
394
- const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
395
- const workspace = yield* checkpointWorkspace(transcript.scenario);
279
+ // Use a throwaway checkpoint workspace; cold full-repo capture exceeds CI wait budgets.
280
+ const workspace = yield* checkpointWorkspace("provider_thread_resume");
281
+ const transcript = yield* readCodexTranscript(workspace);
282
const fs = yield* FileSystem.FileSystem;
283
const path = yield* Path.Path;
284
const tempDir = yield* Effect.acquireRelease(
399
- fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
285
+ fs.makeTempDirectory({
286
+ prefix: "t3-orchestration-v2-recovery-",
287
+ }),
288
(directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
289
);
290
+ yield* fs.makeDirectory(tempDir, { recursive: true });
291
+ const dbPath = path.join(tempDir, "state.sqlite");
292
+ const driver = yield* CodexReplay.makeReplayDriver(transcript);
293
const materialized = yield* materializeFixtureInput({
403
- scenario: transcript.scenario,
294
+ scenario: "provider_thread_resume",
295
fixtureInput: {
296
steps: [
406
- { type: "message", text: launchPrompt },
407
- { type: "message", text: resumePrompt },
297
+ { type: "message", text: PROVIDER_THREAD_RESUME_FIRST_PROMPT },
298
+ { type: "message", text: PROVIDER_THREAD_RESUME_SECOND_PROMPT },
299
],
300
},
410
- driver: ProviderDriverKind.make("claudeAgent"),
411
- modelSelection: CLAUDE_MODEL_SELECTION,
301
+ driver: ProviderDriverKind.make("codex"),
302
+ modelSelection: CODEX_MODEL_SELECTION,
303
});
304
const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
305
splitAfterFirstIdle(materialized);
415
- const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
306
+
307
+ const harness = {
308
+ ...CodexOrchestratorReplayHarness,
309
+ makeProviderAdapterRegistryLayer: () =>
310
+ CodexAdapterV2Testkit.layer({ transcript, driver }),
311
+ };
312
const options = {
417
- databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
313
+ databaseLayer: SqlitePersistence.layerFromPath(dbPath).pipe(
314
Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
315
),
316
};
317
422
- yield* Effect.scoped(
423
- runOrchestratorV2ProviderReplayScenario(
424
- {
425
- name: `${transcript.scenario}:first-runtime`,
426
- transcript,
427
- commands: phase1Commands,
428
- steps: phase1Steps,
429
- projectionThreadIds: materialized.projectionThreadIds,
430
- runtimePolicyOverride: { cwd: workspace },
431
- },
432
- harness,
433
- options,
434
- ),
318
+ yield* runOrchestratorV2ProviderReplayScenario(
319
+ {
320
+ name: "provider_thread_resume/codex:first-runtime",
321
+ transcript,
322
+ commands: phase1Commands,
323
+ steps: phase1Steps,
324
+ projectionThreadIds: materialized.projectionThreadIds,
325
+ runtimePolicyOverride: { cwd: workspace },
326
+ },
327
+ harness,
328
+ options,
329
);
436
- const result = yield* Effect.scoped(
437
- runOrchestratorV2ProviderReplayScenario(
438
- {
439
- name: `${transcript.scenario}:second-runtime`,
440
- transcript,
441
- commands: phase2Commands,
442
- steps: phase2Steps,
443
- projectionThreadIds: materialized.projectionThreadIds,
444
- runtimePolicyOverride: { cwd: workspace },
445
- },
446
- harness,
447
- { ...options, recoverOnStartup: true },
448
- ),
330
+
331
+ const result = yield* runOrchestratorV2ProviderReplayScenario(
332
+ {
333
+ name: "provider_thread_resume/codex:second-runtime",
334
+ transcript,
335
+ commands: phase2Commands,
336
+ steps: phase2Steps,
337
+ projectionThreadIds: materialized.projectionThreadIds,
338
+ runtimePolicyOverride: { cwd: workspace },
339
+ },
340
+ harness,
341
+ { ...options, recoverOnStartup: true },
342
);
450
- yield* assertComplete;
343
344
+ assertBaseProjection({
345
+ result,
346
+ transcript,
347
+ runCount: 2,
348
+ runStatuses: ["completed", "completed"],
349
+ });
350
const projection = projectionFor(result, transcript.scenario);
351
assertSemanticProjectionIntegrity(projection);
454
- assert.lengthOf(projection.subagents, 1);
455
- const subagent = projection.subagents[0];
456
- assert.equal(subagent?.status, "completed");
457
- const childThreads = [...result.projections.values()].filter(
458
- (candidate) => candidate.thread.lineage.parentThreadId === projection.thread.id,
459
- );
460
- assert.lengthOf(childThreads, 1);
461
- const child = childThreads[0];
462
- assert.equal(child?.thread.id, subagent?.childThreadId);
463
- assert.deepEqual(child?.thread.modelSelection, {
464
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
465
- model: "claude-sonnet-5",
466
- });
352
+ assertRunOrdinals(projection, [1, 2]);
353
+ assertConversationMessageRoles(projection, ["user", "assistant", "user", "assistant"]);
354
+ assertTurnItemTypes(projection, ["user_message", "assistant_message"]);
355
+ assertUserMessagesInclude(projection, [
356
+ PROVIDER_THREAD_RESUME_FIRST_PROMPT,
357
+ PROVIDER_THREAD_RESUME_SECOND_PROMPT,
358
+ ]);
359
+ assertAssistantTextIncludes(projection, FIRST_FINAL);
360
+ assertAssistantTextIncludes(projection, SECOND_FINAL);
361
+ assert.lengthOf(projection.providerThreads, 1);
362
+ }).pipe(
363
+ provideDeterministicTestRuntime,
364
+ Effect.provide(
365
+ Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
366
+ ),
367
+ ),
368
+ );
369
468
- const conversation = (child?.turnItems ?? [])
469
- .toSorted((left, right) => left.ordinal - right.ordinal)
470
- .flatMap((item) =>
471
- item.type === "user_message" || item.type === "assistant_message"
472
- ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
473
- : [],
474
- );
475
- const launchTask = conversation[0];
476
- assert.deepEqual(
477
- conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
478
- ["user", "assistant", "user", "assistant"],
479
- );
480
- assert.include(launchTask, "Your job is just the file");
481
- assert.include(conversation[1], "is 1 line long");
482
- assert.include(conversation[2], "Look again at");
483
- assert.include(conversation[3], "Bug/edge case found and fixed");
484
- const childCommands = (child?.turnItems ?? []).filter(
485
- (item) => item.type === "command_execution",
486
- );
487
- assert.lengthOf(childCommands, 3);
488
- assert.isFalse(
489
- projection.turnItems.some(
490
- (item) =>
491
- item.type === "assistant_message" && item.text.includes("Bug/edge case found"),
492
- ),
493
- "the resumed subagent's reply leaked into the parent thread",
494
- );
370
+ it.effect(
371
+ "resumes a provider-native Cursor thread after recreating the orchestrator runtime",
372
+ () =>
373
+ Effect.gen(function* () {
374
+ const transcript = yield* readCursorTranscript();
375
+ const runner = makeCursorAgentSdkReplayRunner(transcript);
376
+ yield* runCursorRecovery({ transcript, runner });
377
+ yield* runner.assertComplete;
378
}).pipe(
379
provideDeterministicTestRuntime,
380
Effect.provide(
381
Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
382
),
383
),
384
+ );
385
+ it.effect("keeps a Claude subagent resumed after a server restart in its own thread", () =>
386
+ Effect.gen(function* () {
387
+ const transcript = yield* readClaudeSubagentResumeTranscript();
388
+ const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
389
+ const workspace = yield* checkpointWorkspace(transcript.scenario);
390
+ const fs = yield* FileSystem.FileSystem;
391
+ const path = yield* Path.Path;
392
+ const tempDir = yield* Effect.acquireRelease(
393
+ fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
394
+ (directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
395
+ );
396
+ const materialized = yield* materializeFixtureInput({
397
+ scenario: transcript.scenario,
398
+ fixtureInput: {
399
+ steps: [
400
+ { type: "message", text: launchPrompt },
401
+ { type: "message", text: resumePrompt },
402
+ ],
403
+ },
404
+ driver: ProviderDriverKind.make("claudeAgent"),
405
+ modelSelection: CLAUDE_MODEL_SELECTION,
406
+ });
407
+ const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
408
+ splitAfterFirstIdle(materialized);
409
+ const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
410
+ const options = {
411
+ databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
412
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
413
+ ),
414
+ };
415
+
416
+ yield* Effect.scoped(
417
+ runOrchestratorV2ProviderReplayScenario(
418
+ {
419
+ name: `${transcript.scenario}:first-runtime`,
420
+ transcript,
421
+ commands: phase1Commands,
422
+ steps: phase1Steps,
423
+ projectionThreadIds: materialized.projectionThreadIds,
424
+ runtimePolicyOverride: { cwd: workspace },
425
+ },
426
+ harness,
427
+ options,
428
+ ),
429
+ );
430
+ const result = yield* Effect.scoped(
431
+ runOrchestratorV2ProviderReplayScenario(
432
+ {
433
+ name: `${transcript.scenario}:second-runtime`,
434
+ transcript,
435
+ commands: phase2Commands,
436
+ steps: phase2Steps,
437
+ projectionThreadIds: materialized.projectionThreadIds,
438
+ runtimePolicyOverride: { cwd: workspace },
439
+ },
440
+ harness,
441
+ { ...options, recoverOnStartup: true },
442
+ ),
443
+ );
444
+ yield* assertComplete;
445
+
446
+ const projection = projectionFor(result, transcript.scenario);
447
+ assertSemanticProjectionIntegrity(projection);
448
+ assert.lengthOf(projection.subagents, 1);
449
+ const subagent = projection.subagents[0];
450
+ assert.equal(subagent?.status, "completed");
451
+ const childThreads = [...result.projections.values()].filter(
452
+ (candidate) => candidate.thread.lineage.parentThreadId === projection.thread.id,
453
+ );
454
+ assert.lengthOf(childThreads, 1);
455
+ const child = childThreads[0];
456
+ assert.equal(child?.thread.id, subagent?.childThreadId);
457
+ assert.deepEqual(child?.thread.modelSelection, {
458
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
459
+ model: "claude-sonnet-5",
460
+ });
461
+
462
+ const conversation = (child?.turnItems ?? [])
463
+ .toSorted((left, right) => left.ordinal - right.ordinal)
464
+ .flatMap((item) =>
465
+ item.type === "user_message" || item.type === "assistant_message"
466
+ ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
467
+ : [],
468
+ );
469
+ const launchTask = conversation[0];
470
+ assert.deepEqual(
471
+ conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
472
+ ["user", "assistant", "user", "assistant"],
473
+ );
474
+ assert.include(launchTask, "Your job is just the file");
475
+ assert.include(conversation[1], "is 1 line long");
476
+ assert.include(conversation[2], "Look again at");
477
+ assert.include(conversation[3], "Bug/edge case found and fixed");
478
+ const childCommands = (child?.turnItems ?? []).filter(
479
+ (item) => item.type === "command_execution",
480
+ );
481
+ assert.lengthOf(childCommands, 3);
482
+ assert.isFalse(
483
+ projection.turnItems.some(
484
+ (item) => item.type === "assistant_message" && item.text.includes("Bug/edge case found"),
485
+ ),
486
+ "the resumed subagent's reply leaked into the parent thread",
487
+ );
488
+ }).pipe(
489
+ provideDeterministicTestRuntime,
490
+ Effect.provide(
491
+ Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
492
+ ),
493
),
494
);
495
it.effect("reopens the thread of a Claude subagent the restart cancelled when resumed", () =>
504
- Effect.scoped(
505
- Effect.gen(function* () {
506
- const transcript = yield* readClaudeCancelledSubagentResumeTranscript();
507
- const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
508
- const workspace = yield* checkpointWorkspace(transcript.scenario);
509
- const fs = yield* FileSystem.FileSystem;
510
- const path = yield* Path.Path;
511
- const tempDir = yield* Effect.acquireRelease(
512
- fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
513
- (directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
496
+ Effect.gen(function* () {
497
+ const transcript = yield* readClaudeCancelledSubagentResumeTranscript();
498
+ const [launchPrompt, resumePrompt] = yield* decodePromptPair(transcript.metadata?.prompts);
499
+ const workspace = yield* checkpointWorkspace(transcript.scenario);
500
+ const fs = yield* FileSystem.FileSystem;
501
+ const path = yield* Path.Path;
502
+ const tempDir = yield* Effect.acquireRelease(
503
+ fs.makeTempDirectory({ prefix: "t3-orchestration-v2-claude-recovery-" }),
504
+ (directory) => fs.remove(directory, { recursive: true, force: true }).pipe(Effect.orDie),
505
+ );
506
+ const materialized = yield* materializeFixtureInput({
507
+ scenario: transcript.scenario,
508
+ fixtureInput: {
509
+ steps: [
510
+ { type: "message", text: launchPrompt },
511
+ { type: "message", text: resumePrompt },
512
+ ],
513
+ },
514
+ driver: ProviderDriverKind.make("claudeAgent"),
515
+ modelSelection: CLAUDE_MODEL_SELECTION,
516
+ });
517
+ const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
518
+ splitAfterFirstIdle(materialized);
519
+ const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
520
+ const options = {
521
+ databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
522
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
523
+ ),
524
+ };
525
+ const childThreadOf = (result: OrchestratorV2ScenarioResult, parentThreadId: ThreadId) =>
526
+ [...result.projections.values()].find(
527
+ (candidate) => candidate.thread.lineage.parentThreadId === parentThreadId,
528
);
515
- const materialized = yield* materializeFixtureInput({
516
- scenario: transcript.scenario,
517
- fixtureInput: {
518
- steps: [
519
- { type: "message", text: launchPrompt },
520
- { type: "message", text: resumePrompt },
521
- ],
522
- },
523
- driver: ProviderDriverKind.make("claudeAgent"),
524
- modelSelection: CLAUDE_MODEL_SELECTION,
525
- });
526
- const { phase1Commands, phase1Steps, phase2Commands, phase2Steps } =
527
- splitAfterFirstIdle(materialized);
528
- const { harness, assertComplete } = makeClaudeRestartReplayHarness(transcript);
529
- const options = {
530
- databaseLayer: SqlitePersistence.layerFromPath(path.join(tempDir, "state.sqlite")).pipe(
531
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
532
- ),
533
- };
534
- const childThreadOf = (result: OrchestratorV2ScenarioResult, parentThreadId: ThreadId) =>
535
- [...result.projections.values()].find(
536
- (candidate) => candidate.thread.lineage.parentThreadId === parentThreadId,
537
- );
538
- const childRootStatus = (child: OrchestrationV2ThreadProjection | undefined) =>
539
- child?.nodes.find((node) => node.kind === "root_turn" && node.runId === null)?.status;
529
+ const childRootStatus = (child: OrchestrationV2ThreadProjection | undefined) =>
530
+ child?.nodes.find((node) => node.kind === "root_turn" && node.runId === null)?.status;
531
541
- const snapshotPath = path.join(tempDir, "restart-state.sqlite");
542
- const beforeScenario = {
543
- name: `${transcript.scenario}:cancelled-first-runtime`,
544
- transcript,
545
- commands: phase1Commands,
546
- steps: phase1Steps,
547
- projectionThreadIds: materialized.projectionThreadIds,
548
- runtimePolicyOverride: { cwd: workspace },
549
- };
550
- const before = yield* Effect.scoped(
551
- Effect.gen(function* () {
552
- const result = yield* runOrchestratorV2Scenario(beforeScenario);
553
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
554
- yield* worker.drain();
555
- // Preserve the orphan before scoped teardown settles its provider work.
556
- const sql = yield* SqlClient.SqlClient;
557
- yield* sql`VACUUM INTO ${snapshotPath}`;
558
- return result;
559
- }).pipe(
560
- Effect.provide(
561
- Layer.merge(
562
- layerProviderReplay(beforeScenario, harness, options),
563
- options.databaseLayer,
564
- ),
532
+ const snapshotPath = path.join(tempDir, "restart-state.sqlite");
533
+ const beforeScenario = {
534
+ name: `${transcript.scenario}:cancelled-first-runtime`,
535
+ transcript,
536
+ commands: phase1Commands,
537
+ steps: phase1Steps,
538
+ projectionThreadIds: materialized.projectionThreadIds,
539
+ runtimePolicyOverride: { cwd: workspace },
540
+ };
541
+ const before = yield* Effect.scoped(
542
+ Effect.gen(function* () {
543
+ const result = yield* runOrchestratorV2Scenario(beforeScenario);
544
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
545
+ yield* worker.drain();
546
+ // Preserve the orphan before scoped teardown settles its provider work.
547
+ const sql = yield* SqlClient.SqlClient;
548
+ yield* sql`VACUUM INTO ${snapshotPath}`;
549
+ return result;
550
+ }).pipe(
551
+ Effect.provide(
552
+ Layer.merge(
553
+ layerProviderReplay(beforeScenario, harness, options),
554
+ options.databaseLayer,
555
),
556
),
567
- );
568
- const settled = projectionFor(before, transcript.scenario);
569
- assert.equal(settled.subagents[0]?.status, "running");
570
- assert.equal(childRootStatus(childThreadOf(before, settled.thread.id)), "running");
557
+ ),
558
+ );
559
+ const settled = projectionFor(before, transcript.scenario);
560
+ assert.equal(settled.subagents[0]?.status, "running");
561
+ assert.equal(childRootStatus(childThreadOf(before, settled.thread.id)), "running");
562
572
- const result = yield* Effect.scoped(
573
- runOrchestratorV2ProviderReplayScenario(
574
- {
575
- name: `${transcript.scenario}:cancelled-second-runtime`,
576
- transcript,
577
- commands: phase2Commands,
578
- steps: phase2Steps,
579
- projectionThreadIds: materialized.projectionThreadIds,
580
- runtimePolicyOverride: { cwd: workspace },
581
- },
582
- harness,
583
- {
584
- databaseLayer: SqlitePersistence.layerFromPath(snapshotPath).pipe(
585
- Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
586
- ),
587
- recoverOnStartup: true,
588
- continueThreadsAfterServerUpdate: false,
589
- },
590
- ),
591
- );
592
- yield* assertComplete;
563
+ const result = yield* Effect.scoped(
564
+ runOrchestratorV2ProviderReplayScenario(
565
+ {
566
+ name: `${transcript.scenario}:cancelled-second-runtime`,
567
+ transcript,
568
+ commands: phase2Commands,
569
+ steps: phase2Steps,
570
+ projectionThreadIds: materialized.projectionThreadIds,
571
+ runtimePolicyOverride: { cwd: workspace },
572
+ },
573
+ harness,
574
+ {
575
+ databaseLayer: SqlitePersistence.layerFromPath(snapshotPath).pipe(
576
+ Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
577
+ ),
578
+ recoverOnStartup: true,
579
+ continueThreadsAfterServerUpdate: false,
580
+ },
581
+ ),
582
+ );
583
+ yield* assertComplete;
584
594
- const projection = projectionFor(result, transcript.scenario);
595
- assertSemanticProjectionIntegrity(projection);
596
- assert.equal(projection.subagents[0]?.status, "completed");
597
- const child = childThreadOf(result, projection.thread.id);
598
- assert.equal(child?.thread.id, projection.subagents[0]?.childThreadId);
599
- assert.equal(childRootStatus(child), "completed");
600
- const conversation = (child?.turnItems ?? [])
601
- .toSorted((left, right) => left.ordinal - right.ordinal)
602
- .flatMap((item) =>
603
- item.type === "user_message" || item.type === "assistant_message"
604
- ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
605
- : [],
606
- );
607
- assert.deepEqual(
608
- conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
609
- ["user", "user", "assistant"],
610
- );
611
- assert.include(conversation[0], "Your job is just the file");
612
- assert.include(conversation[1], "Look again at");
613
- assert.include(conversation[2], "Bug/edge case found and fixed");
614
- assert.lengthOf(
615
- (child?.turnItems ?? []).filter((item) => item.type === "command_execution"),
616
- 2,
585
+ const projection = projectionFor(result, transcript.scenario);
586
+ assertSemanticProjectionIntegrity(projection);
587
+ assert.equal(projection.subagents[0]?.status, "completed");
588
+ const child = childThreadOf(result, projection.thread.id);
589
+ assert.equal(child?.thread.id, projection.subagents[0]?.childThreadId);
590
+ assert.equal(childRootStatus(child), "completed");
591
+ const conversation = (child?.turnItems ?? [])
592
+ .toSorted((left, right) => left.ordinal - right.ordinal)
593
+ .flatMap((item) =>
594
+ item.type === "user_message" || item.type === "assistant_message"
595
+ ? [`${item.type === "user_message" ? "user" : "assistant"}:${item.text}`]
596
+ : [],
597
);
618
- }).pipe(
619
- provideDeterministicTestRuntime,
620
- Effect.provide(
621
- Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
622
- ),
598
+ assert.deepEqual(
599
+ conversation.map((entry) => entry.slice(0, entry.indexOf(":"))),
600
+ ["user", "user", "assistant"],
601
+ );
602
+ assert.include(conversation[0], "Your job is just the file");
603
+ assert.include(conversation[1], "Look again at");
604
+ assert.include(conversation[2], "Bug/edge case found and fixed");
605
+ assert.lengthOf(
606
+ (child?.turnItems ?? []).filter((item) => item.type === "command_execution"),
607
+ 2,
608
+ );
609
+ }).pipe(
610
+ provideDeterministicTestRuntime,
611
+ Effect.provide(
612
+ Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
613
),
614
),
615
);
apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
+23
-27
@@ -268,34 +268,30 @@ describe("restart-cancelled background work", () => {
268
it.effect.each([false, true])(
269
"keeps the thread settled and tells the next user turn once when continuation is %s",
270
(continueThreadsAfterServerUpdate) =>
271
- Effect.scoped(
272
- Effect.gen(function* () {
273
- const projection = yield* runRestart({
274
- resumedPrompts: [
275
- `${NOTE}\n\nUser message:\n${FIRST_AFTER_RESTART}`,
276
- SECOND_AFTER_RESTART,
277
- ],
278
- userMessagesAfterRestart: [FIRST_AFTER_RESTART, SECOND_AFTER_RESTART],
279
- continueThreadsAfterServerUpdate,
280
- });
281
- assert.deepEqual(
282
- projection.runs.map((run) => run.status),
283
- ["completed", "completed", "completed"],
284
- );
285
- assert.isFalse(
286
- projection.runs.some((run) => run.restartContinuationOfRunId !== undefined),
287
- );
288
-
289
- assert.deepEqual(userTexts(projection), [
290
- CLAUDE_BACKGROUND_SUBAGENT_AFTER_ROOT_PROMPT,
291
- FIRST_AFTER_RESTART,
271
+ Effect.gen(function* () {
272
+ const projection = yield* runRestart({
273
+ resumedPrompts: [
274
+ `${NOTE}\n\nUser message:\n${FIRST_AFTER_RESTART}`,
275
SECOND_AFTER_RESTART,
293
- ]);
294
- }).pipe(
295
- provideDeterministicTestRuntime,
296
- Effect.provide(
297
- Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
298
- ),
276
+ ],
277
+ userMessagesAfterRestart: [FIRST_AFTER_RESTART, SECOND_AFTER_RESTART],
278
+ continueThreadsAfterServerUpdate,
279
+ });
280
+ assert.deepEqual(
281
+ projection.runs.map((run) => run.status),
282
+ ["completed", "completed", "completed"],
283
+ );
284
+ assert.isFalse(projection.runs.some((run) => run.restartContinuationOfRunId !== undefined));
285
+
286
+ assert.deepEqual(userTexts(projection), [
287
+ CLAUDE_BACKGROUND_SUBAGENT_AFTER_ROOT_PROMPT,
288
+ FIRST_AFTER_RESTART,
289
+ SECOND_AFTER_RESTART,
290
+ ]);
291
+ }).pipe(
292
+ provideDeterministicTestRuntime,
293
+ Effect.provide(
294
+ Layer.merge(IdAllocator.layer, Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
295
),
296
),
297
);
apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+2967
-3018
@@ -515,38 +515,594 @@ describe("orchestration v2 provider switching", () => {
515
"prior-images-legacy-replacement-native",
516
"delivery-write-failure",
517
] as const)("preserves handoffs through %s", (scenario) =>
518
- Effect.scoped(
518
+ Effect.gen(function* () {
519
+ const cwd = yield* checkpointWorkspace(`handoff-${scenario}`);
520
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
521
+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
522
+ const reasoningScenario = scenario.includes("reasoning-change");
523
+ const turnUsageScenario = reasoningScenario || scenario.includes("turn-usage");
524
+ const modelScenario =
525
+ scenario.includes("model") || scenario.includes("option-change") || reasoningScenario;
526
+ const failStartOnce = yield* Ref.make(false);
527
+ const failResumeOnce = yield* Ref.make(false);
528
+ const generation = yield* Ref.make(0);
529
+ const pendingBackgroundWork = yield* Ref.make(false);
530
+ const priorImages = scenario.includes("prior-images");
531
+ const exhaustedTarget = scenario.includes("exhausted-target");
532
+ const replaceNative = scenario.includes("replacement");
533
+ const capacityScenario = modelScenario || scenario.includes("reported-capacity");
534
+ const returning =
535
+ scenario === "large-current-input" ||
536
+ scenario.includes("-change-") ||
537
+ priorImages ||
538
+ exhaustedTarget;
539
+ const targetSelection: ModelSelection = !modelScenario
540
+ ? CLAUDE_MODEL_SELECTION
541
+ : {
542
+ ...CLAUDE_MODEL_SELECTION,
543
+ ...(reasoningScenario
544
+ ? { options: [{ id: "reasoningEffort", value: "low" }] }
545
+ : scenario.includes("option-change")
546
+ ? { options: [{ id: "contextWindow", value: "1m" }] }
547
+ : { model: `${CLAUDE_MODEL_SELECTION.model}-large` }),
548
+ };
549
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
550
+ makeTestAdapter({
551
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
552
+ driver: CODEX_DRIVER,
553
+ capabilities: CodexProviderCapabilitiesV2,
554
+ modelSelection: CODEX_MODEL_SELECTION,
555
+ responseByRunOrdinal: { 1: "Original partial work" },
556
+ capturedTurns,
557
+ }),
558
+ makeTestAdapter({
559
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
560
+ driver: CLAUDE_DRIVER,
561
+ capabilities: ClaudeProviderCapabilitiesV2,
562
+ modelSelection: CLAUDE_MODEL_SELECTION,
563
+ responseByRunOrdinal: scenario.includes("target-estimate")
564
+ ? { 2: "x".repeat(64_000) }
565
+ : {},
566
+ capturedTurns,
567
+ ...(scenario.includes("retry") || scenario.includes("unsent") ? { failStartOnce } : {}),
568
+ ...(replaceNative ? { failResumeOnce, nativeThreadGeneration: generation } : {}),
569
+ ...(exhaustedTarget ? { nativeThreadGeneration: generation } : {}),
570
+ ...(scenario.includes("target-background") || scenario.includes("target-subagent")
571
+ ? {
572
+ pendingBackgroundWork,
573
+ subagentOnlyBackgroundWork: scenario.includes("target-subagent"),
574
+ }
575
+ : {}),
576
+ ...(scenario.includes("reported-capacity")
577
+ ? { initialContextUsage: { usedTokens: 999_999, maxTokens: 1_000_000 } }
578
+ : {}),
579
+ ...(turnUsageScenario
580
+ ? {
581
+ canReuseContextUsage: canReuseCodexContextUsage,
582
+ tokenUsageByRunOrdinal: {
583
+ 2: {
584
+ usedTokens: replaceNative ? 30_000 : 37_321,
585
+ maxTokens: replaceNative
586
+ ? scenario.includes("small")
587
+ ? 32_000
588
+ : 64_000
589
+ : 258_400,
590
+ },
591
+ },
592
+ }
593
+ : modelScenario
594
+ ? {
595
+ getModelContextWindow: (selection: ModelSelection) =>
596
+ selection.model.endsWith("-large") ||
597
+ selection.options?.some(
598
+ (option) => option.id === "contextWindow" && option.value === "1m",
599
+ )
600
+ ? 1_000_000
601
+ : 32_000,
602
+ }
603
+ : scenario === "large-current-input" || priorImages || exhaustedTarget
604
+ ? {
605
+ getModelContextWindow: () =>
606
+ scenario.includes("target-tight") ? 25_121 : 32_000,
607
+ }
608
+ : {}),
609
+ ...(scenario.endsWith("-native") || scenario === "large-current-input"
610
+ ? { injectedHistory }
611
+ : {}),
612
+ }),
613
+ ]);
614
+ yield* Effect.gen(function* () {
615
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
616
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
617
+ const eventSink = yield* EventSink.EventSinkV2;
618
+ const screenshot: ChatAttachment = {
619
+ type: "image",
620
+ id: "screenshot",
621
+ name: "screenshot.png",
622
+ mimeType: "image/png",
623
+ sizeBytes: 100_000,
624
+ };
625
+ const screenshots = Array.from(
626
+ {
627
+ length:
628
+ scenario.includes("eight") || capacityScenario
629
+ ? 8
630
+ : scenario.includes("pair")
631
+ ? 2
632
+ : 1,
633
+ },
634
+ (_, index) => ({ ...screenshot, id: `screenshot-${index}` }),
635
+ );
636
+ const targetOrdinal = returning ? 4 : 2;
637
+ const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
638
+ orchestrator.dispatch({
639
+ type: "message.dispatch",
640
+ commandId: CommandId.make(`regression:${ordinal}`),
641
+ threadId,
642
+ messageId: MessageId.make(`regression:${ordinal}`),
643
+ createdBy: "user",
644
+ creationSource: "web",
645
+ text,
646
+ attachments:
647
+ turnUsageScenario && ordinal === 2
648
+ ? Array.from({ length: 8 }, (_, index) => ({
649
+ ...screenshot,
650
+ id: `prior-${index}`,
651
+ }))
652
+ : turnUsageScenario && ordinal >= targetOrdinal
653
+ ? [screenshot, { ...screenshot, id: "current-2" }]
654
+ : scenario.startsWith("screenshot") &&
655
+ ordinal >= targetOrdinal &&
656
+ (!exhaustedTarget || ordinal === targetOrdinal)
657
+ ? screenshots
658
+ : priorImages && ordinal === (scenario.startsWith("imported") ? 1 : 2)
659
+ ? [screenshot]
660
+ : [],
661
+ modelSelection: selection,
662
+ dispatchMode: { type: "start_immediately" },
663
+ });
664
+ const wait = (ordinal: number) =>
665
+ orchestrator.streamStoredEvents.pipe(
666
+ Stream.filter(
667
+ ({ event }) =>
668
+ event.type === "run.updated" &&
669
+ event.payload.ordinal === ordinal &&
670
+ (event.payload.status === "completed" || event.payload.status === "failed"),
671
+ ),
672
+ Stream.runHead,
673
+ Effect.andThen(worker.drain()),
674
+ );
675
+ yield* orchestrator.dispatch({
676
+ type: "thread.create",
677
+ commandId: CommandId.make("regression:create"),
678
+ threadId,
679
+ projectId,
680
+ createdBy: "user",
681
+ creationSource: "web",
682
+ title: "Handoff regression",
683
+ modelSelection: CODEX_MODEL_SELECTION,
684
+ runtimeMode: "full-access",
685
+ interactionMode: "default",
686
+ branch: null,
687
+ worktreePath: null,
688
+ });
689
+ yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
690
+ yield* wait(1);
691
+ const write = eventSink.write;
692
+ const spy =
693
+ scenario === "delivery-write-failure"
694
+ ? vi.spyOn(eventSink, "write").mockImplementation((input) =>
695
+ input.events.some(
696
+ (event) =>
697
+ event.type === "context-handoff.updated" &&
698
+ event.payload.delivery?.status === "inline",
699
+ )
700
+ ? Effect.fail(
701
+ new EventSink.EventSinkWriteError({
702
+ eventCount: input.events.length,
703
+ cause: "bookkeeping unavailable",
704
+ }),
705
+ )
706
+ : write(input),
707
+ )
708
+ : undefined;
709
+ yield* Effect.addFinalizer(() => Effect.sync(() => spy?.mockRestore()));
710
+ const current = scenario.startsWith("compact")
711
+ ? "/compact"
712
+ : scenario.includes("target-oversized")
713
+ ? "x".repeat(40_000)
714
+ : capacityScenario && !turnUsageScenario
715
+ ? "x".repeat(70_000)
716
+ : scenario === "large-current-input"
717
+ ? "x".repeat(9_000)
718
+ : "Continue work";
719
+ if (returning) {
720
+ if (scenario.includes("unsent")) yield* Ref.set(failStartOnce, true);
721
+ yield* dispatch(
722
+ 2,
723
+ turnUsageScenario
724
+ ? "x".repeat(27_460)
725
+ : scenario.includes("target-estimate")
726
+ ? "x".repeat(12_000)
727
+ : "Establish target",
728
+ CLAUDE_MODEL_SELECTION,
729
+ );
730
+ yield* wait(2);
731
+ if (exhaustedTarget) {
732
+ assert.equal(
733
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
734
+ "completed",
735
+ );
736
+ }
737
+ if (exhaustedTarget && !scenario.includes("target-estimate")) {
738
+ const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
739
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
740
+ )!;
741
+ yield* eventSink.write({
742
+ events: [
743
+ {
744
+ id: EventId.make("exhausted-target-usage"),
745
+ type: "provider-thread.updated",
746
+ threadId,
747
+ occurredAt: yield* DateTime.now,
748
+ payload: { ...target, contextUsage: { usedTokens: 30_000, maxTokens: 32_000 } },
749
+ },
750
+ ],
751
+ });
752
+ }
753
+ if (modelScenario && !turnUsageScenario) {
754
+ const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
755
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
756
+ )!;
757
+ yield* eventSink.write({
758
+ events: [
759
+ {
760
+ id: EventId.make("old-model-usage"),
761
+ type: "provider-thread.updated",
762
+ threadId,
763
+ occurredAt: yield* DateTime.now,
764
+ payload: {
765
+ ...target,
766
+ contextUsage: {
767
+ usedTokens: 30_000,
768
+ maxTokens: 32_000,
769
+ autoCompactThreshold: 31_000,
770
+ },
771
+ },
772
+ },
773
+ ],
774
+ });
775
+ }
776
+ if (scenario.includes("legacy-replacement")) {
777
+ const existing = yield* orchestrator.getThreadProjection(threadId);
778
+ yield* eventSink.write({
779
+ events: existing.attempts.map(
780
+ ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
781
+ id: EventId.make(`legacy-attempt:${index}`),
782
+ type: "run-attempt.updated" as const,
783
+ threadId,
784
+ occurredAt: existing.thread.createdAt,
785
+ payload: legacy,
786
+ }),
787
+ ),
788
+ });
789
+ }
790
+ if (scenario.includes("telemetry")) {
791
+ const target = (yield* orchestrator.getThreadProjection(threadId)).providerThreads.find(
792
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
793
+ )!;
794
+ yield* eventSink.write({
795
+ events: [
796
+ {
797
+ id: EventId.make("compacted-context-usage"),
798
+ type: "provider-thread.updated",
799
+ threadId,
800
+ occurredAt: yield* DateTime.now,
801
+ payload: { ...target, contextUsage: { usedTokens: 100, maxTokens: 32_000 } },
802
+ },
803
+ ],
804
+ });
805
+ }
806
+ yield* dispatch(
807
+ 3,
808
+ priorImages && !replaceNative
809
+ ? "New source constraint " + "q".repeat(9_000)
810
+ : "New source constraint",
811
+ CODEX_MODEL_SELECTION,
812
+ );
813
+ yield* wait(3);
814
+ }
815
+ if (replaceNative) {
816
+ // Switching back to Codex already released Claude's session.
817
+ yield* Ref.set(failResumeOnce, true);
818
+ }
819
+ if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true);
820
+ if (scenario.includes("target-background") || scenario.includes("target-subagent"))
821
+ yield* Ref.set(pendingBackgroundWork, true);
822
+ yield* dispatch(targetOrdinal, current, targetSelection);
823
+ yield* wait(targetOrdinal);
824
+ if (scenario.includes("retry")) {
825
+ const failed = yield* orchestrator.getThreadProjection(threadId);
826
+ assert.equal(failed.runs.at(-1)?.status, "failed");
827
+ const failedUsage = failed.providerThreads.find(
828
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
829
+ )!.contextUsage;
830
+ if (reasoningScenario || scenario.includes("turn-usage")) {
831
+ assert.deepEqual(failedUsage, { usedTokens: 37_321, maxTokens: 258_400 });
832
+ } else {
833
+ assert.deepEqual(failedUsage, { usedTokens: 30_000, maxTokens: 1_000_000 });
834
+ }
835
+ if (reasoningScenario) {
836
+ const target = failed.providerThreads.find(
837
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
838
+ )!;
839
+ yield* orchestrator.dispatch({
840
+ type: "provider-session.detach",
841
+ commandId: CommandId.make("detach-before-reasoning-retry"),
842
+ threadId,
843
+ providerSessionId: target.providerSessionId!,
844
+ });
845
+ yield* worker.drain();
846
+ }
847
+ yield* dispatch(targetOrdinal + 1, current, targetSelection);
848
+ yield* wait(targetOrdinal + 1);
849
+ }
850
+ if (reasoningScenario && replaceNative) {
851
+ const replaced = yield* orchestrator.getThreadProjection(threadId);
852
+ assert.equal(
853
+ replaced.runs.at(-1)?.status,
854
+ scenario.includes("small") ? "failed" : "completed",
855
+ );
856
+ const target = replaced.providerThreads.find(
857
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
858
+ )!;
859
+ assert.isNull(target.contextUsage);
860
+ assert.equal(yield* Ref.get(generation), 2);
861
+ assert.equal(
862
+ (yield* Ref.get(capturedTurns)).at(-1)!.driver,
863
+ scenario.includes("small") ? CODEX_DRIVER : CLAUDE_DRIVER,
864
+ );
865
+ return;
866
+ }
867
+ if (replaceNative) {
868
+ if (scenario.includes("legacy-replacement")) {
869
+ const recovered = yield* orchestrator.getThreadProjection(threadId);
870
+ const handoff = recovered.contextHandoffs.at(-1)!;
871
+ const { history: _history, ...legacyHandoff } = handoff;
872
+ yield* eventSink.write({
873
+ events: [
874
+ {
875
+ id: EventId.make("legacy-replacement-handoff"),
876
+ type: "context-handoff.updated",
877
+ threadId,
878
+ occurredAt: yield* DateTime.now,
879
+ payload: {
880
+ ...legacyHandoff,
881
+ delivery: {
882
+ nativeThreadId: handoff.delivery!.nativeThreadId,
883
+ status: handoff.delivery!.status,
884
+ itemIds: [],
885
+ },
886
+ },
887
+ },
888
+ ],
889
+ });
890
+ }
891
+ yield* dispatch(
892
+ targetOrdinal + 1,
893
+ "Continue after native replacement",
894
+ CLAUDE_MODEL_SELECTION,
895
+ );
896
+ yield* wait(targetOrdinal + 1);
897
+ yield* dispatch(
898
+ targetOrdinal + 2,
899
+ "Another source constraint " + "q".repeat(9_000),
900
+ CODEX_MODEL_SELECTION,
901
+ );
902
+ yield* wait(targetOrdinal + 2);
903
+ yield* dispatch(targetOrdinal + 3, current, CLAUDE_MODEL_SELECTION);
904
+ yield* wait(targetOrdinal + 3);
905
+ }
906
+ const projection = yield* orchestrator.getThreadProjection(threadId);
907
+ if (
908
+ scenario.includes("target-oversized") ||
909
+ scenario.includes("target-tight") ||
910
+ scenario.includes("target-background") ||
911
+ scenario.includes("target-subagent")
912
+ ) {
913
+ assert.equal(projection.runs.at(-1)?.status, "failed");
914
+ assert.equal(yield* Ref.get(generation), 1);
915
+ assert.equal(projection.messages.at(-1)!.text, current);
916
+ assert.deepEqual(projection.messages.at(-1)!.attachments, screenshots);
917
+ if (scenario.includes("target-background") || scenario.includes("target-subagent")) {
918
+ assert.isTrue(yield* Ref.get(pendingBackgroundWork));
919
+ const failure = projection.turnItems.findLast((item) => item.type === "error");
920
+ assert.equal(
921
+ failure?.type === "error" ? failure.failure.message : null,
922
+ "The target provider still has background work running. Wait for it to finish or stop it before retrying the handoff.",
923
+ );
924
+ }
925
+ return;
926
+ }
927
+ assert.equal(projection.runs.at(-1)?.status, "completed");
928
+ if (exhaustedTarget) {
929
+ assert.equal(yield* Ref.get(generation), 2);
930
+ const turns = (yield* Ref.get(capturedTurns)).filter(
931
+ (turn) => turn.driver === CLAUDE_DRIVER,
932
+ );
933
+ assert.notEqual(turns[0]!.nativeThreadId, turns[1]!.nativeThreadId);
934
+ const latestRun = projection.runs.at(-1)!;
935
+ assert.equal(
936
+ projection.attempts.find((attempt) => attempt.id === latestRun.activeAttemptId)!
937
+ .nativeThreadId,
938
+ turns[1]!.nativeThreadId,
939
+ );
940
+ const context = scenario.endsWith("-native")
941
+ ? yield* encodeJson(yield* Ref.get(injectedHistory))
942
+ : turns[1]!.text;
943
+ assert.include(context, "Original request with constraints");
944
+ assert.include(context, "Original partial work");
945
+ assert.include(context, "New source constraint");
946
+ assert.include(turns[1]!.text, current);
947
+ assert.deepEqual(turns[1]!.attachments, screenshots);
948
+ const historyBeforeFollowup = yield* Ref.get(injectedHistory);
949
+ yield* dispatch(5, "Continue after automatic recovery", CLAUDE_MODEL_SELECTION);
950
+ yield* wait(5);
951
+ assert.equal(
952
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
953
+ "completed",
954
+ );
955
+ assert.equal(yield* Ref.get(generation), 2);
956
+ assert.equal(
957
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
958
+ "Continue after automatic recovery",
959
+ );
960
+ assert.deepEqual(yield* Ref.get(injectedHistory), historyBeforeFollowup);
961
+ if (scenario.includes("target-estimate")) {
962
+ yield* dispatch(6, "Another source turn", CODEX_MODEL_SELECTION);
963
+ yield* wait(6);
964
+ yield* dispatch(7, "Return after recovery", CLAUDE_MODEL_SELECTION);
965
+ yield* wait(7);
966
+ assert.equal(
967
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
968
+ "completed",
969
+ );
970
+ assert.equal(yield* Ref.get(generation), 2);
971
+ }
972
+ return;
973
+ }
974
+ if (priorImages) {
975
+ const handoff = projection.contextHandoffs.at(-1)!;
976
+ const context = scenario.endsWith("-native")
977
+ ? yield* encodeJson(yield* Ref.get(injectedHistory))
978
+ : (yield* Ref.get(capturedTurns)).at(-1)!.text;
979
+ const shouldFit =
980
+ turnUsageScenario ||
981
+ scenario.startsWith("imported") ||
982
+ scenario.includes("telemetry") ||
983
+ scenario.includes("unsent") ||
984
+ replaceNative;
985
+ const sourceText =
986
+ `${replaceNative ? "Another" : "New"} source constraint ` + "q".repeat(9_000);
987
+ const sourceItem = projection.turnItems.find(
988
+ (item) => item.type === "user_message" && item.text === sourceText,
989
+ )!;
990
+ assert.isDefined(sourceItem);
991
+ if (shouldFit) {
992
+ assert.include(context, sourceText);
993
+ assert.include(
994
+ projection.contextHandoffs
995
+ .filter(
996
+ (record) =>
997
+ record.targetRunId ===
998
+ (scenario.includes("retry")
999
+ ? projection.runs.find((run) => run.ordinal === targetOrdinal)!.id
1000
+ : projection.runs.at(-1)!.id),
1001
+ )
1002
+ .flatMap((record) => record.delivery?.itemIds ?? []),
1003
+ sourceItem.id,
1004
+ );
1005
+ } else {
1006
+ assert.notInclude(context, "q".repeat(9_000));
1007
+ assert.isAbove(handoff.delivery!.omittedItemIds!.length, 0);
1008
+ }
1009
+ const latestRun = projection.runs.at(-1)!;
1010
+ const latestAttempt = projection.attempts.find(
1011
+ (attempt) => attempt.id === latestRun.activeAttemptId,
1012
+ )!;
1013
+ const target = projection.providerThreads.find(
1014
+ (thread) => thread.id === latestAttempt.providerThreadId,
1015
+ )!;
1016
+ assert.equal(latestAttempt.nativeThreadId, target.nativeThreadRef!.nativeId);
1017
+ if (turnUsageScenario) {
1018
+ if (replaceNative) assert.isNull(target.contextUsage);
1019
+ else assert.deepEqual(target.contextUsage, { usedTokens: 37_321, maxTokens: 258_400 });
1020
+ assert.lengthOf((yield* Ref.get(capturedTurns)).at(-1)!.attachments, 2);
1021
+ }
1022
+ if (replaceNative) assert.equal(yield* Ref.get(generation), 2);
1023
+ return;
1024
+ }
1025
+ const handoff = projection.contextHandoffs.at(-1)!;
1026
+ if (scenario.startsWith("screenshot")) {
1027
+ assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
1028
+ }
1029
+ if (scenario === "compact-legacy") {
1030
+ const { history: _history, ...legacyHandoff } = handoff;
1031
+ yield* eventSink.write({
1032
+ events: [
1033
+ {
1034
+ id: EventId.make("legacy-handoff-shape"),
1035
+ type: "context-handoff.updated",
1036
+ threadId,
1037
+ runId: handoff.targetRunId,
1038
+ occurredAt: yield* DateTime.now,
1039
+ payload: legacyHandoff,
1040
+ },
1041
+ ],
1042
+ });
1043
+ assert.isUndefined(handoff.delivery);
1044
+ yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
1045
+ yield* wait(3);
1046
+ assert.include(
1047
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
1048
+ "Original request with constraints",
1049
+ );
1050
+ assert.equal(
1051
+ (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.at(-1)?.delivery
1052
+ ?.status,
1053
+ "inline",
1054
+ );
1055
+ } else if (
1056
+ scenario === "delivery-write-failure" ||
1057
+ (scenario.startsWith("screenshot") && scenario.endsWith("fallback"))
1058
+ ) {
1059
+ assert.equal(
1060
+ handoff.delivery?.status,
1061
+ scenario.startsWith("screenshot") ? "inline" : "pending",
1062
+ );
1063
+ assert.include(
1064
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
1065
+ "Original request with constraints",
1066
+ );
1067
+ } else {
1068
+ assert.equal(handoff.delivery?.status, "injected");
1069
+ assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, current);
1070
+ assert.include(
1071
+ yield* encodeJson(yield* Ref.get(injectedHistory)),
1072
+ "Original request with constraints",
1073
+ );
1074
+ }
1075
+ }).pipe(
1076
+ Effect.provide(
1077
+ ProviderReplayHarness.layerWithRegistry(
1078
+ {
1079
+ name: `handoff-${scenario}`,
1080
+ runtimePolicyOverride: {
1081
+ cwd,
1082
+ approvalPolicy: "never",
1083
+ sandboxPolicy: { type: "readOnly" },
1084
+ },
1085
+ },
1086
+ layerRegistry,
1087
+ ),
1088
+ ),
1089
+ );
1090
+ }),
1091
+ );
1092
+ it.live.each([
1093
+ "turn-start",
1094
+ "injection",
1095
+ "large-missed-request",
1096
+ "exhausted-target-retry",
1097
+ ] as const)(
1098
+ "recovers %s failure without duplicating history in the same native thread",
1099
+ (failure) =>
1100
Effect.gen(function* () {
520
- const cwd = yield* checkpointWorkspace(`handoff-${scenario}`);
1101
+ const cwd = yield* checkpointWorkspace(`handoff-retry-${failure}`);
1102
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1103
const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
523
- const reasoningScenario = scenario.includes("reasoning-change");
524
- const turnUsageScenario = reasoningScenario || scenario.includes("turn-usage");
525
- const modelScenario =
526
- scenario.includes("model") || scenario.includes("option-change") || reasoningScenario;
527
- const failStartOnce = yield* Ref.make(false);
528
- const failResumeOnce = yield* Ref.make(false);
1104
+ const failOnce = yield* Ref.make(true);
1105
const generation = yield* Ref.make(0);
530
- const pendingBackgroundWork = yield* Ref.make(false);
531
- const priorImages = scenario.includes("prior-images");
532
- const exhaustedTarget = scenario.includes("exhausted-target");
533
- const replaceNative = scenario.includes("replacement");
534
- const capacityScenario = modelScenario || scenario.includes("reported-capacity");
535
- const returning =
536
- scenario === "large-current-input" ||
537
- scenario.includes("-change-") ||
538
- priorImages ||
539
- exhaustedTarget;
540
- const targetSelection: ModelSelection = !modelScenario
541
- ? CLAUDE_MODEL_SELECTION
542
- : {
543
- ...CLAUDE_MODEL_SELECTION,
544
- ...(reasoningScenario
545
- ? { options: [{ id: "reasoningEffort", value: "low" }] }
546
- : scenario.includes("option-change")
547
- ? { options: [{ id: "contextWindow", value: "1m" }] }
548
- : { model: `${CLAUDE_MODEL_SELECTION.model}-large` }),
549
- };
1106
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1107
makeTestAdapter({
1108
instanceId: CODEX_MODEL_SELECTION.instanceId,
@@ -561,108 +1117,33 @@ describe("orchestration v2 provider switching", () => {
1117
driver: CLAUDE_DRIVER,
1118
capabilities: ClaudeProviderCapabilitiesV2,
1119
modelSelection: CLAUDE_MODEL_SELECTION,
564
- responseByRunOrdinal: scenario.includes("target-estimate")
565
- ? { 2: "x".repeat(64_000) }
566
- : {},
1120
+ responseByRunOrdinal: {},
1121
capturedTurns,
568
- ...(scenario.includes("retry") || scenario.includes("unsent") ? { failStartOnce } : {}),
569
- ...(replaceNative ? { failResumeOnce, nativeThreadGeneration: generation } : {}),
570
- ...(exhaustedTarget ? { nativeThreadGeneration: generation } : {}),
571
- ...(scenario.includes("target-background") || scenario.includes("target-subagent")
572
- ? {
573
- pendingBackgroundWork,
574
- subagentOnlyBackgroundWork: scenario.includes("target-subagent"),
575
- }
576
- : {}),
577
- ...(scenario.includes("reported-capacity")
578
- ? { initialContextUsage: { usedTokens: 999_999, maxTokens: 1_000_000 } }
579
- : {}),
580
- ...(turnUsageScenario
581
- ? {
582
- canReuseContextUsage: canReuseCodexContextUsage,
583
- tokenUsageByRunOrdinal: {
584
- 2: {
585
- usedTokens: replaceNative ? 30_000 : 37_321,
586
- maxTokens: replaceNative
587
- ? scenario.includes("small")
588
- ? 32_000
589
- : 64_000
590
- : 258_400,
591
- },
592
- },
593
- }
594
- : modelScenario
595
- ? {
596
- getModelContextWindow: (selection: ModelSelection) =>
597
- selection.model.endsWith("-large") ||
598
- selection.options?.some(
599
- (option) => option.id === "contextWindow" && option.value === "1m",
600
- )
601
- ? 1_000_000
602
- : 32_000,
603
- }
604
- : scenario === "large-current-input" || priorImages || exhaustedTarget
605
- ? {
606
- getModelContextWindow: () =>
607
- scenario.includes("target-tight") ? 25_121 : 32_000,
608
- }
609
- : {}),
610
- ...(scenario.endsWith("-native") || scenario === "large-current-input"
611
- ? { injectedHistory }
612
- : {}),
1122
+ injectedHistory,
1123
+ nativeThreadGeneration: generation,
1124
+ getModelContextWindow: () => 32_000,
1125
+ ...(failure !== "injection"
1126
+ ? { failStartOnce: failOnce }
1127
+ : { failInjectionOnce: failOnce }),
1128
}),
1129
]);
1130
yield* Effect.gen(function* () {
1131
const orchestrator = yield* Orchestrator.OrchestratorV2;
1132
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
618
- const eventSink = yield* EventSink.EventSinkV2;
619
- const screenshot: ChatAttachment = {
620
- type: "image",
621
- id: "screenshot",
622
- name: "screenshot.png",
623
- mimeType: "image/png",
624
- sizeBytes: 100_000,
625
- };
626
- const screenshots = Array.from(
627
- {
628
- length:
629
- scenario.includes("eight") || capacityScenario
630
- ? 8
631
- : scenario.includes("pair")
632
- ? 2
633
- : 1,
634
- },
635
- (_, index) => ({ ...screenshot, id: `screenshot-${index}` }),
636
- );
637
- const targetOrdinal = returning ? 4 : 2;
1133
const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
1134
orchestrator.dispatch({
1135
type: "message.dispatch",
641
- commandId: CommandId.make(`regression:${ordinal}`),
1136
+ commandId: CommandId.make(`retry:${ordinal}`),
1137
threadId,
643
- messageId: MessageId.make(`regression:${ordinal}`),
1138
+ messageId: MessageId.make(`retry:${ordinal}`),
1139
createdBy: "user",
1140
creationSource: "web",
1141
text,
647
- attachments:
648
- turnUsageScenario && ordinal === 2
649
- ? Array.from({ length: 8 }, (_, index) => ({
650
- ...screenshot,
651
- id: `prior-${index}`,
652
- }))
653
- : turnUsageScenario && ordinal >= targetOrdinal
654
- ? [screenshot, { ...screenshot, id: "current-2" }]
655
- : scenario.startsWith("screenshot") &&
656
- ordinal >= targetOrdinal &&
657
- (!exhaustedTarget || ordinal === targetOrdinal)
658
- ? screenshots
659
- : priorImages && ordinal === (scenario.startsWith("imported") ? 1 : 2)
660
- ? [screenshot]
661
- : [],
1142
+ attachments: [],
1143
modelSelection: selection,
1144
dispatchMode: { type: "start_immediately" },
1145
});
665
- const wait = (ordinal: number) =>
1146
+ const wait = (ordinal: number, status: "failed" | "completed") =>
1147
orchestrator.streamStoredEvents.pipe(
1148
Stream.filter(
1149
({ event }) =>
@@ -672,15 +1153,23 @@ describe("orchestration v2 provider switching", () => {
1153
),
1154
Stream.runHead,
1155
Effect.andThen(worker.drain()),
1156
+ Effect.andThen(
1157
+ Effect.gen(function* () {
1158
+ assert.equal(
1159
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1160
+ status,
1161
+ );
1162
+ }),
1163
+ ),
1164
);
1165
yield* orchestrator.dispatch({
1166
type: "thread.create",
678
- commandId: CommandId.make("regression:create"),
1167
+ commandId: CommandId.make("retry:create"),
1168
threadId,
1169
projectId,
1170
createdBy: "user",
1171
creationSource: "web",
683
- title: "Handoff regression",
1172
+ title: "Handoff retry",
1173
modelSelection: CODEX_MODEL_SELECTION,
1174
runtimeMode: "full-access",
1175
interactionMode: "default",
@@ -688,403 +1177,87 @@ describe("orchestration v2 provider switching", () => {
1177
worktreePath: null,
1178
});
1179
yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
691
- yield* wait(1);
692
- const write = eventSink.write;
693
- const spy =
694
- scenario === "delivery-write-failure"
695
- ? vi.spyOn(eventSink, "write").mockImplementation((input) =>
696
- input.events.some(
697
- (event) =>
698
- event.type === "context-handoff.updated" &&
699
- event.payload.delivery?.status === "inline",
700
- )
701
- ? Effect.fail(
702
- new EventSink.EventSinkWriteError({
703
- eventCount: input.events.length,
704
- cause: "bookkeeping unavailable",
705
- }),
706
- )
707
- : write(input),
708
- )
709
- : undefined;
710
- yield* Effect.addFinalizer(() => Effect.sync(() => spy?.mockRestore()));
711
- const current = scenario.startsWith("compact")
712
- ? "/compact"
713
- : scenario.includes("target-oversized")
714
- ? "x".repeat(40_000)
715
- : capacityScenario && !turnUsageScenario
716
- ? "x".repeat(70_000)
717
- : scenario === "large-current-input"
718
- ? "x".repeat(9_000)
719
- : "Continue work";
720
- if (returning) {
721
- if (scenario.includes("unsent")) yield* Ref.set(failStartOnce, true);
722
- yield* dispatch(
723
- 2,
724
- turnUsageScenario
725
- ? "x".repeat(27_460)
726
- : scenario.includes("target-estimate")
727
- ? "x".repeat(12_000)
728
- : "Establish target",
729
- CLAUDE_MODEL_SELECTION,
1180
+ yield* wait(1, "completed");
1181
+ yield* dispatch(
1182
+ 2,
1183
+ failure === "large-missed-request" ? "x".repeat(7_000) : "First target request",
1184
+ CLAUDE_MODEL_SELECTION,
1185
+ );
1186
+ yield* wait(2, "failed");
1187
+ const failed = yield* orchestrator.getThreadProjection(threadId);
1188
+ const failedHandoff = failed.contextHandoffs.at(-1)!;
1189
+ assert.equal(
1190
+ failedHandoff.delivery?.status,
1191
+ failure !== "injection" ? "injected" : "pending",
1192
+ );
1193
+ const historyBeforeRetry = (yield* Ref.get(injectedHistory)).length;
1194
+ if (failure === "exhausted-target-retry") {
1195
+ const target = failed.providerThreads.find(
1196
+ (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
1197
+ )!;
1198
+ yield* (yield* EventSink.EventSinkV2).write({
1199
+ events: [
1200
+ {
1201
+ id: EventId.make("exhausted-retry-usage"),
1202
+ type: "provider-thread.updated",
1203
+ threadId,
1204
+ occurredAt: yield* DateTime.now,
1205
+ payload: { ...target, contextUsage: { usedTokens: 30_000, maxTokens: 32_000 } },
1206
+ },
1207
+ ],
1208
+ });
1209
+ }
1210
+ const retryText =
1211
+ failure === "large-missed-request" ? "y".repeat(10_000) : "Retry target request";
1212
+ yield* dispatch(3, retryText, CLAUDE_MODEL_SELECTION);
1213
+ yield* wait(3, "completed");
1214
+ const retried = yield* orchestrator.getThreadProjection(threadId);
1215
+ const lastTurn = (yield* Ref.get(capturedTurns)).at(-1)!;
1216
+ assert.equal(lastTurn.text, retryText);
1217
+ if (failure !== "injection" && failure !== "exhausted-target-retry") {
1218
+ const delta = yield* encodeJson(
1219
+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
1220
);
731
- yield* wait(2);
732
- if (exhaustedTarget) {
733
- assert.equal(
734
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
735
- "completed",
736
- );
737
- }
738
- if (exhaustedTarget && !scenario.includes("target-estimate")) {
739
- const target = (yield* orchestrator.getThreadProjection(
740
- threadId,
741
- )).providerThreads.find(
742
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
1221
+ if (failure === "large-missed-request") {
1222
+ assert.include(delta, "omitted 1 items");
1223
+ const missedRequest = retried.turnItems.find(
1224
+ (item) => item.type === "user_message" && item.text === "x".repeat(7_000),
1225
)!;
744
- yield* eventSink.write({
745
- events: [
746
- {
747
- id: EventId.make("exhausted-target-usage"),
748
- type: "provider-thread.updated",
749
- threadId,
750
- occurredAt: yield* DateTime.now,
751
- payload: { ...target, contextUsage: { usedTokens: 30_000, maxTokens: 32_000 } },
752
- },
753
- ],
754
- });
755
- }
756
- if (modelScenario && !turnUsageScenario) {
757
- const target = (yield* orchestrator.getThreadProjection(
758
- threadId,
759
- )).providerThreads.find(
760
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
761
- )!;
762
- yield* eventSink.write({
763
- events: [
764
- {
765
- id: EventId.make("old-model-usage"),
766
- type: "provider-thread.updated",
767
- threadId,
768
- occurredAt: yield* DateTime.now,
769
- payload: {
770
- ...target,
771
- contextUsage: {
772
- usedTokens: 30_000,
773
- maxTokens: 32_000,
774
- autoCompactThreshold: 31_000,
775
- },
776
- },
777
- },
778
- ],
779
- });
780
- }
781
- if (scenario.includes("legacy-replacement")) {
782
- const existing = yield* orchestrator.getThreadProjection(threadId);
783
- yield* eventSink.write({
784
- events: existing.attempts.map(
785
- ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
786
- id: EventId.make(`legacy-attempt:${index}`),
787
- type: "run-attempt.updated" as const,
788
- threadId,
789
- occurredAt: existing.thread.createdAt,
790
- payload: legacy,
791
- }),
792
- ),
793
- });
794
- }
795
- if (scenario.includes("telemetry")) {
796
- const target = (yield* orchestrator.getThreadProjection(
797
- threadId,
798
- )).providerThreads.find(
799
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
800
- )!;
801
- yield* eventSink.write({
802
- events: [
803
- {
804
- id: EventId.make("compacted-context-usage"),
805
- type: "provider-thread.updated",
806
- threadId,
807
- occurredAt: yield* DateTime.now,
808
- payload: { ...target, contextUsage: { usedTokens: 100, maxTokens: 32_000 } },
809
- },
810
- ],
811
- });
812
- }
813
- yield* dispatch(
814
- 3,
815
- priorImages && !replaceNative
816
- ? "New source constraint " + "q".repeat(9_000)
817
- : "New source constraint",
818
- CODEX_MODEL_SELECTION,
819
- );
820
- yield* wait(3);
821
- }
822
- if (replaceNative) {
823
- // Switching back to Codex already released Claude's session.
824
- yield* Ref.set(failResumeOnce, true);
825
- }
826
- if (scenario.includes("retry")) yield* Ref.set(failStartOnce, true);
827
- if (scenario.includes("target-background") || scenario.includes("target-subagent"))
828
- yield* Ref.set(pendingBackgroundWork, true);
829
- yield* dispatch(targetOrdinal, current, targetSelection);
830
- yield* wait(targetOrdinal);
831
- if (scenario.includes("retry")) {
832
- const failed = yield* orchestrator.getThreadProjection(threadId);
833
- assert.equal(failed.runs.at(-1)?.status, "failed");
834
- const failedUsage = failed.providerThreads.find(
835
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
836
- )!.contextUsage;
837
- if (reasoningScenario || scenario.includes("turn-usage")) {
838
- assert.deepEqual(failedUsage, { usedTokens: 37_321, maxTokens: 258_400 });
839
- } else {
840
- assert.deepEqual(failedUsage, { usedTokens: 30_000, maxTokens: 1_000_000 });
841
- }
842
- if (reasoningScenario) {
843
- const target = failed.providerThreads.find(
844
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
845
- )!;
846
- yield* orchestrator.dispatch({
847
- type: "provider-session.detach",
848
- commandId: CommandId.make("detach-before-reasoning-retry"),
849
- threadId,
850
- providerSessionId: target.providerSessionId!,
851
- });
852
- yield* worker.drain();
853
- }
854
- yield* dispatch(targetOrdinal + 1, current, targetSelection);
855
- yield* wait(targetOrdinal + 1);
856
- }
857
- if (reasoningScenario && replaceNative) {
858
- const replaced = yield* orchestrator.getThreadProjection(threadId);
859
- assert.equal(
860
- replaced.runs.at(-1)?.status,
861
- scenario.includes("small") ? "failed" : "completed",
862
- );
863
- const target = replaced.providerThreads.find(
864
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
865
- )!;
866
- assert.isNull(target.contextUsage);
867
- assert.equal(yield* Ref.get(generation), 2);
868
- assert.equal(
869
- (yield* Ref.get(capturedTurns)).at(-1)!.driver,
870
- scenario.includes("small") ? CODEX_DRIVER : CLAUDE_DRIVER,
871
- );
872
- return;
873
- }
874
- if (replaceNative) {
875
- if (scenario.includes("legacy-replacement")) {
876
- const recovered = yield* orchestrator.getThreadProjection(threadId);
877
- const handoff = recovered.contextHandoffs.at(-1)!;
878
- const { history: _history, ...legacyHandoff } = handoff;
879
- yield* eventSink.write({
880
- events: [
881
- {
882
- id: EventId.make("legacy-replacement-handoff"),
883
- type: "context-handoff.updated",
884
- threadId,
885
- occurredAt: yield* DateTime.now,
886
- payload: {
887
- ...legacyHandoff,
888
- delivery: {
889
- nativeThreadId: handoff.delivery!.nativeThreadId,
890
- status: handoff.delivery!.status,
891
- itemIds: [],
892
- },
893
- },
894
- },
895
- ],
896
- });
897
- }
898
- yield* dispatch(
899
- targetOrdinal + 1,
900
- "Continue after native replacement",
901
- CLAUDE_MODEL_SELECTION,
902
- );
903
- yield* wait(targetOrdinal + 1);
904
- yield* dispatch(
905
- targetOrdinal + 2,
906
- "Another source constraint " + "q".repeat(9_000),
907
- CODEX_MODEL_SELECTION,
908
- );
909
- yield* wait(targetOrdinal + 2);
910
- yield* dispatch(targetOrdinal + 3, current, CLAUDE_MODEL_SELECTION);
911
- yield* wait(targetOrdinal + 3);
912
- }
913
- const projection = yield* orchestrator.getThreadProjection(threadId);
914
- if (
915
- scenario.includes("target-oversized") ||
916
- scenario.includes("target-tight") ||
917
- scenario.includes("target-background") ||
918
- scenario.includes("target-subagent")
919
- ) {
920
- assert.equal(projection.runs.at(-1)?.status, "failed");
921
- assert.equal(yield* Ref.get(generation), 1);
922
- assert.equal(projection.messages.at(-1)!.text, current);
923
- assert.deepEqual(projection.messages.at(-1)!.attachments, screenshots);
924
- if (scenario.includes("target-background") || scenario.includes("target-subagent")) {
925
- assert.isTrue(yield* Ref.get(pendingBackgroundWork));
926
- const failure = projection.turnItems.findLast((item) => item.type === "error");
927
- assert.equal(
928
- failure?.type === "error" ? failure.failure.message : null,
929
- "The target provider still has background work running. Wait for it to finish or stop it before retrying the handoff.",
930
- );
931
- }
932
- return;
933
- }
934
- assert.equal(projection.runs.at(-1)?.status, "completed");
935
- if (exhaustedTarget) {
936
- assert.equal(yield* Ref.get(generation), 2);
937
- const turns = (yield* Ref.get(capturedTurns)).filter(
938
- (turn) => turn.driver === CLAUDE_DRIVER,
939
- );
940
- assert.notEqual(turns[0]!.nativeThreadId, turns[1]!.nativeThreadId);
941
- const latestRun = projection.runs.at(-1)!;
942
- assert.equal(
943
- projection.attempts.find((attempt) => attempt.id === latestRun.activeAttemptId)!
944
- .nativeThreadId,
945
- turns[1]!.nativeThreadId,
946
- );
947
- const context = scenario.endsWith("-native")
948
- ? yield* encodeJson(yield* Ref.get(injectedHistory))
949
- : turns[1]!.text;
950
- assert.include(context, "Original request with constraints");
951
- assert.include(context, "Original partial work");
952
- assert.include(context, "New source constraint");
953
- assert.include(turns[1]!.text, current);
954
- assert.deepEqual(turns[1]!.attachments, screenshots);
955
- const historyBeforeFollowup = yield* Ref.get(injectedHistory);
956
- yield* dispatch(5, "Continue after automatic recovery", CLAUDE_MODEL_SELECTION);
957
- yield* wait(5);
958
- assert.equal(
959
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
960
- "completed",
961
- );
962
- assert.equal(yield* Ref.get(generation), 2);
963
- assert.equal(
964
- (yield* Ref.get(capturedTurns)).at(-1)!.text,
965
- "Continue after automatic recovery",
966
- );
967
- assert.deepEqual(yield* Ref.get(injectedHistory), historyBeforeFollowup);
968
- if (scenario.includes("target-estimate")) {
969
- yield* dispatch(6, "Another source turn", CODEX_MODEL_SELECTION);
970
- yield* wait(6);
971
- yield* dispatch(7, "Return after recovery", CLAUDE_MODEL_SELECTION);
972
- yield* wait(7);
973
- assert.equal(
974
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
975
- "completed",
976
- );
977
- assert.equal(yield* Ref.get(generation), 2);
978
- }
979
- return;
980
- }
981
- if (priorImages) {
982
- const handoff = projection.contextHandoffs.at(-1)!;
983
- const context = scenario.endsWith("-native")
984
- ? yield* encodeJson(yield* Ref.get(injectedHistory))
985
- : (yield* Ref.get(capturedTurns)).at(-1)!.text;
986
- const shouldFit =
987
- turnUsageScenario ||
988
- scenario.startsWith("imported") ||
989
- scenario.includes("telemetry") ||
990
- scenario.includes("unsent") ||
991
- replaceNative;
992
- const sourceText =
993
- `${replaceNative ? "Another" : "New"} source constraint ` + "q".repeat(9_000);
994
- const sourceItem = projection.turnItems.find(
995
- (item) => item.type === "user_message" && item.text === sourceText,
996
- )!;
997
- assert.isDefined(sourceItem);
998
- if (shouldFit) {
999
- assert.include(context, sourceText);
1000
- assert.include(
1001
- projection.contextHandoffs
1002
- .filter(
1003
- (record) =>
1004
- record.targetRunId ===
1005
- (scenario.includes("retry")
1006
- ? projection.runs.find((run) => run.ordinal === targetOrdinal)!.id
1007
- : projection.runs.at(-1)!.id),
1008
- )
1009
- .flatMap((record) => record.delivery?.itemIds ?? []),
1010
- sourceItem.id,
1011
- );
1012
- } else {
1013
- assert.notInclude(context, "q".repeat(9_000));
1014
- assert.isAbove(handoff.delivery!.omittedItemIds!.length, 0);
1015
- }
1016
- const latestRun = projection.runs.at(-1)!;
1017
- const latestAttempt = projection.attempts.find(
1018
- (attempt) => attempt.id === latestRun.activeAttemptId,
1019
- )!;
1020
- const target = projection.providerThreads.find(
1021
- (thread) => thread.id === latestAttempt.providerThreadId,
1022
- )!;
1023
- assert.equal(latestAttempt.nativeThreadId, target.nativeThreadRef!.nativeId);
1024
- if (turnUsageScenario) {
1025
- if (replaceNative) assert.isNull(target.contextUsage);
1026
- else
1027
- assert.deepEqual(target.contextUsage, { usedTokens: 37_321, maxTokens: 258_400 });
1028
- assert.lengthOf((yield* Ref.get(capturedTurns)).at(-1)!.attachments, 2);
1029
- }
1030
- if (replaceNative) assert.equal(yield* Ref.get(generation), 2);
1031
- return;
1032
- }
1033
- const handoff = projection.contextHandoffs.at(-1)!;
1034
- if (scenario.startsWith("screenshot")) {
1035
- assert.deepEqual((yield* Ref.get(capturedTurns)).at(-1)!.attachments, screenshots);
1036
- }
1037
- if (scenario === "compact-legacy") {
1038
- const { history: _history, ...legacyHandoff } = handoff;
1039
- yield* eventSink.write({
1040
- events: [
1041
- {
1042
- id: EventId.make("legacy-handoff-shape"),
1043
- type: "context-handoff.updated",
1044
- threadId,
1045
- runId: handoff.targetRunId,
1046
- occurredAt: yield* DateTime.now,
1047
- payload: legacyHandoff,
1048
- },
1049
- ],
1050
- });
1051
- assert.isUndefined(handoff.delivery);
1052
- yield* dispatch(3, "Continue after compact", CLAUDE_MODEL_SELECTION);
1053
- yield* wait(3);
1054
- assert.include(
1055
- (yield* Ref.get(capturedTurns)).at(-1)!.text,
1056
- "Original request with constraints",
1057
- );
1058
- assert.equal(
1059
- (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.at(-1)?.delivery
1060
- ?.status,
1061
- "inline",
1062
- );
1063
- } else if (
1064
- scenario === "delivery-write-failure" ||
1065
- (scenario.startsWith("screenshot") && scenario.endsWith("fallback"))
1066
- ) {
1067
- assert.equal(
1068
- handoff.delivery?.status,
1069
- scenario.startsWith("screenshot") ? "inline" : "pending",
1070
- );
1071
- assert.include(
1072
- (yield* Ref.get(capturedTurns)).at(-1)!.text,
1073
- "Original request with constraints",
1074
- );
1075
- } else {
1076
- assert.equal(handoff.delivery?.status, "injected");
1077
- assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, current);
1078
- assert.include(
1079
- yield* encodeJson(yield* Ref.get(injectedHistory)),
1080
- "Original request with constraints",
1226
+ const delivery = retried.contextHandoffs.at(-1)!.delivery!;
1227
+ assert.include(delivery.omittedItemIds ?? [], missedRequest.id);
1228
+ assert.notInclude(delivery.itemIds, missedRequest.id);
1229
+ } else assert.include(delta, "First target request");
1230
+ assert.notInclude(delta, "Original request with constraints");
1231
+ assert.notInclude(delta, "Original partial work");
1232
+ assert.equal(yield* Ref.get(generation), 1);
1233
+ } else {
1234
+ assert.equal(yield* Ref.get(generation), 2);
1235
+ assert.notEqual(
1236
+ retried.contextHandoffs.at(-1)?.delivery?.nativeThreadId,
1237
+ failedHandoff.delivery?.nativeThreadId,
1238
);
1239
+ const newHistory = yield* encodeJson(
1240
+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
1241
+ );
1242
+ assert.include(newHistory, "Original request with constraints");
1243
+ assert.include(newHistory, "Original partial work");
1244
+ assert.notInclude(newHistory, "Retry target request");
1245
}
1246
+ const beforeFollowup = yield* Ref.get(injectedHistory);
1247
+ const followup = "z".repeat(6_000);
1248
+ yield* dispatch(4, followup, CLAUDE_MODEL_SELECTION);
1249
+ yield* wait(4, "completed");
1250
+ assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, followup);
1251
+ assert.deepEqual(yield* Ref.get(injectedHistory), beforeFollowup);
1252
+ assert.equal(
1253
+ (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.length,
1254
+ retried.contextHandoffs.length,
1255
+ );
1256
}).pipe(
1257
Effect.provide(
1258
ProviderReplayHarness.layerWithRegistry(
1259
{
1087
- name: `handoff-${scenario}`,
1260
+ name: `handoff-retry-${failure}`,
1261
runtimePolicyOverride: {
1262
cwd,
1263
approvalPolicy: "never",
@@ -1096,238 +1269,143 @@ describe("orchestration v2 provider switching", () => {
1269
),
1270
);
1271
}),
1099
- ),
1272
);
1101
- it.live.each([
1102
- "turn-start",
1103
- "injection",
1104
- "large-missed-request",
1105
- "exhausted-target-retry",
1106
- ] as const)(
1107
- "recovers %s failure without duplicating history in the same native thread",
1108
- (failure) =>
1109
- Effect.scoped(
1110
- Effect.gen(function* () {
1111
- const cwd = yield* checkpointWorkspace(`handoff-retry-${failure}`);
1112
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1113
- const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1114
- const failOnce = yield* Ref.make(true);
1115
- const generation = yield* Ref.make(0);
1116
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1117
- makeTestAdapter({
1118
- instanceId: CODEX_MODEL_SELECTION.instanceId,
1119
- driver: CODEX_DRIVER,
1120
- capabilities: CodexProviderCapabilitiesV2,
1121
- modelSelection: CODEX_MODEL_SELECTION,
1122
- responseByRunOrdinal: { 1: "Original partial work" },
1123
- capturedTurns,
1124
- }),
1125
- makeTestAdapter({
1126
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1127
- driver: CLAUDE_DRIVER,
1128
- capabilities: ClaudeProviderCapabilitiesV2,
1129
- modelSelection: CLAUDE_MODEL_SELECTION,
1130
- responseByRunOrdinal: {},
1131
- capturedTurns,
1132
- injectedHistory,
1133
- nativeThreadGeneration: generation,
1134
- getModelContextWindow: () => 32_000,
1135
- ...(failure !== "injection"
1136
- ? { failStartOnce: failOnce }
1137
- : { failInjectionOnce: failOnce }),
1138
- }),
1139
- ]);
1140
- yield* Effect.gen(function* () {
1141
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1142
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1143
- const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
1144
- orchestrator.dispatch({
1145
- type: "message.dispatch",
1146
- commandId: CommandId.make(`retry:${ordinal}`),
1147
- threadId,
1148
- messageId: MessageId.make(`retry:${ordinal}`),
1149
- createdBy: "user",
1150
- creationSource: "web",
1151
- text,
1152
- attachments: [],
1153
- modelSelection: selection,
1154
- dispatchMode: { type: "start_immediately" },
1155
- });
1156
- const wait = (ordinal: number, status: "failed" | "completed") =>
1157
- orchestrator.streamStoredEvents.pipe(
1158
- Stream.filter(
1159
- ({ event }) =>
1160
- event.type === "run.updated" &&
1161
- event.payload.ordinal === ordinal &&
1162
- (event.payload.status === "completed" || event.payload.status === "failed"),
1163
- ),
1164
- Stream.runHead,
1165
- Effect.andThen(worker.drain()),
1166
- Effect.andThen(
1167
- Effect.gen(function* () {
1168
- assert.equal(
1169
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1170
- status,
1171
- );
1172
- }),
1173
- ),
1174
- );
1175
- yield* orchestrator.dispatch({
1176
- type: "thread.create",
1177
- commandId: CommandId.make("retry:create"),
1178
- threadId,
1179
- projectId,
1180
- createdBy: "user",
1181
- creationSource: "web",
1182
- title: "Handoff retry",
1183
- modelSelection: CODEX_MODEL_SELECTION,
1184
- runtimeMode: "full-access",
1185
- interactionMode: "default",
1186
- branch: null,
1187
- worktreePath: null,
1188
- });
1189
- yield* dispatch(1, "Original request with constraints", CODEX_MODEL_SELECTION);
1190
- yield* wait(1, "completed");
1191
- yield* dispatch(
1192
- 2,
1193
- failure === "large-missed-request" ? "x".repeat(7_000) : "First target request",
1194
- CLAUDE_MODEL_SELECTION,
1195
- );
1196
- yield* wait(2, "failed");
1197
- const failed = yield* orchestrator.getThreadProjection(threadId);
1198
- const failedHandoff = failed.contextHandoffs.at(-1)!;
1199
- assert.equal(
1200
- failedHandoff.delivery?.status,
1201
- failure !== "injection" ? "injected" : "pending",
1202
- );
1203
- const historyBeforeRetry = (yield* Ref.get(injectedHistory)).length;
1204
- if (failure === "exhausted-target-retry") {
1205
- const target = failed.providerThreads.find(
1206
- (thread) => thread.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
1207
- )!;
1208
- yield* (yield* EventSink.EventSinkV2).write({
1209
- events: [
1210
- {
1211
- id: EventId.make("exhausted-retry-usage"),
1212
- type: "provider-thread.updated",
1213
- threadId,
1214
- occurredAt: yield* DateTime.now,
1215
- payload: { ...target, contextUsage: { usedTokens: 30_000, maxTokens: 32_000 } },
1216
- },
1217
- ],
1218
- });
1219
- }
1220
- const retryText =
1221
- failure === "large-missed-request" ? "y".repeat(10_000) : "Retry target request";
1222
- yield* dispatch(3, retryText, CLAUDE_MODEL_SELECTION);
1223
- yield* wait(3, "completed");
1224
- const retried = yield* orchestrator.getThreadProjection(threadId);
1225
- const lastTurn = (yield* Ref.get(capturedTurns)).at(-1)!;
1226
- assert.equal(lastTurn.text, retryText);
1227
- if (failure !== "injection" && failure !== "exhausted-target-retry") {
1228
- const delta = yield* encodeJson(
1229
- (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
1230
- );
1231
- if (failure === "large-missed-request") {
1232
- assert.include(delta, "omitted 1 items");
1233
- const missedRequest = retried.turnItems.find(
1234
- (item) => item.type === "user_message" && item.text === "x".repeat(7_000),
1235
- )!;
1236
- const delivery = retried.contextHandoffs.at(-1)!.delivery!;
1237
- assert.include(delivery.omittedItemIds ?? [], missedRequest.id);
1238
- assert.notInclude(delivery.itemIds, missedRequest.id);
1239
- } else assert.include(delta, "First target request");
1240
- assert.notInclude(delta, "Original request with constraints");
1241
- assert.notInclude(delta, "Original partial work");
1242
- assert.equal(yield* Ref.get(generation), 1);
1243
- } else {
1244
- assert.equal(yield* Ref.get(generation), 2);
1245
- assert.notEqual(
1246
- retried.contextHandoffs.at(-1)?.delivery?.nativeThreadId,
1247
- failedHandoff.delivery?.nativeThreadId,
1248
- );
1249
- const newHistory = yield* encodeJson(
1250
- (yield* Ref.get(injectedHistory)).slice(historyBeforeRetry),
1251
- );
1252
- assert.include(newHistory, "Original request with constraints");
1253
- assert.include(newHistory, "Original partial work");
1254
- assert.notInclude(newHistory, "Retry target request");
1255
- }
1256
- const beforeFollowup = yield* Ref.get(injectedHistory);
1257
- const followup = "z".repeat(6_000);
1258
- yield* dispatch(4, followup, CLAUDE_MODEL_SELECTION);
1259
- yield* wait(4, "completed");
1260
- assert.equal((yield* Ref.get(capturedTurns)).at(-1)!.text, followup);
1261
- assert.deepEqual(yield* Ref.get(injectedHistory), beforeFollowup);
1262
- assert.equal(
1263
- (yield* orchestrator.getThreadProjection(threadId)).contextHandoffs.length,
1264
- retried.contextHandoffs.length,
1265
- );
1266
- }).pipe(
1267
- Effect.provide(
1268
- ProviderReplayHarness.layerWithRegistry(
1269
- {
1270
- name: `handoff-retry-${failure}`,
1271
- runtimePolicyOverride: {
1272
- cwd,
1273
- approvalPolicy: "never",
1274
- sandboxPolicy: { type: "readOnly" },
1275
- },
1276
- },
1277
- layerRegistry,
1278
- ),
1273
+
1274
+ it.live("keeps a native session whose stored prose is far below an unreported window", () =>
1275
+ Effect.gen(function* () {
1276
+ const cwd = yield* checkpointWorkspace("handoff-estimate-headroom");
1277
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1278
+ const generation = yield* Ref.make(0);
1279
+ // About 112 KB of ordinary English is about 25k tokens: a quarter of a 128k window.
1280
+ const prose = "The quick brown fox jumps over the lazy dog. ".repeat(2_500);
1281
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1282
+ makeTestAdapter({
1283
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
1284
+ driver: CODEX_DRIVER,
1285
+ capabilities: CodexProviderCapabilitiesV2,
1286
+ modelSelection: CODEX_MODEL_SELECTION,
1287
+ responseByRunOrdinal: { 2: "Source work" },
1288
+ capturedTurns,
1289
+ }),
1290
+ // No window and no usage, like an ACP registry agent that sends no usage_update.
1291
+ makeTestAdapter({
1292
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1293
+ driver: CLAUDE_DRIVER,
1294
+ capabilities: ClaudeProviderCapabilitiesV2,
1295
+ modelSelection: CLAUDE_MODEL_SELECTION,
1296
+ responseByRunOrdinal: { 1: prose },
1297
+ capturedTurns,
1298
+ nativeThreadGeneration: generation,
1299
+ }),
1300
+ ]);
1301
+ yield* Effect.gen(function* () {
1302
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1303
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1304
+ const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
1305
+ orchestrator.dispatch({
1306
+ type: "message.dispatch",
1307
+ commandId: CommandId.make(`headroom:${ordinal}`),
1308
+ threadId,
1309
+ messageId: MessageId.make(`headroom:${ordinal}`),
1310
+ createdBy: "user",
1311
+ creationSource: "web",
1312
+ text,
1313
+ attachments: [],
1314
+ modelSelection: selection,
1315
+ dispatchMode: { type: "start_immediately" },
1316
+ });
1317
+ const wait = (ordinal: number) =>
1318
+ orchestrator.streamStoredEvents.pipe(
1319
+ Stream.filter(
1320
+ ({ event }) =>
1321
+ event.type === "run.updated" &&
1322
+ event.payload.ordinal === ordinal &&
1323
+ (event.payload.status === "completed" || event.payload.status === "failed"),
1324
),
1325
+ Stream.runHead,
1326
+ Effect.andThen(worker.drain()),
1327
);
1281
- }),
1282
- ),
1328
+ yield* orchestrator.dispatch({
1329
+ type: "thread.create",
1330
+ commandId: CommandId.make("headroom:create"),
1331
+ threadId,
1332
+ projectId,
1333
+ createdBy: "user",
1334
+ creationSource: "web",
1335
+ title: "Handoff estimate headroom",
1336
+ modelSelection: CLAUDE_MODEL_SELECTION,
1337
+ runtimeMode: "full-access",
1338
+ interactionMode: "default",
1339
+ branch: null,
1340
+ worktreePath: null,
1341
+ });
1342
+ yield* dispatch(1, "Write the long report", CLAUDE_MODEL_SELECTION);
1343
+ yield* wait(1);
1344
+ yield* dispatch(2, "Continue elsewhere", CODEX_MODEL_SELECTION);
1345
+ yield* wait(2);
1346
+ yield* dispatch(3, "Back to the first provider", CLAUDE_MODEL_SELECTION);
1347
+ yield* wait(3);
1348
+ assert.equal(
1349
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1350
+ "completed",
1351
+ );
1352
+ // A second generation means T3 discarded the native session as full.
1353
+ assert.equal(yield* Ref.get(generation), 1);
1354
+ }).pipe(
1355
+ Effect.provide(
1356
+ ProviderReplayHarness.layerWithRegistry(
1357
+ {
1358
+ name: "handoff-estimate-headroom",
1359
+ runtimePolicyOverride: {
1360
+ cwd,
1361
+ approvalPolicy: "never",
1362
+ sandboxPolicy: { type: "readOnly" },
1363
+ },
1364
+ },
1365
+ layerRegistry,
1366
+ ),
1367
+ ),
1368
+ );
1369
+ }),
1370
);
1371
1285
- it.live("keeps a native session whose stored prose is far below an unreported window", () =>
1286
- Effect.scoped(
1372
+ it.live.each(["native", "legacy"] as const)(
1373
+ "starts a replacement native thread as new after the resume fallback with %s attempts",
1374
+ (attempts) =>
1375
Effect.gen(function* () {
1288
- const cwd = yield* checkpointWorkspace("handoff-estimate-headroom");
1376
+ const cwd = yield* checkpointWorkspace("resume-fallback-native-turns");
1377
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1378
+ const failResumeOnce = yield* Ref.make(false);
1379
const generation = yield* Ref.make(0);
1291
- // About 112 KB of ordinary English is about 25k tokens: a quarter of a 128k window.
1292
- const prose = "The quick brown fox jumps over the lazy dog. ".repeat(2_500);
1380
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1294
- makeTestAdapter({
1295
- instanceId: CODEX_MODEL_SELECTION.instanceId,
1296
- driver: CODEX_DRIVER,
1297
- capabilities: CodexProviderCapabilitiesV2,
1298
- modelSelection: CODEX_MODEL_SELECTION,
1299
- responseByRunOrdinal: { 2: "Source work" },
1300
- capturedTurns,
1301
- }),
1302
- // No window and no usage, like an ACP registry agent that sends no usage_update.
1381
makeTestAdapter({
1382
instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1383
driver: CLAUDE_DRIVER,
1384
capabilities: ClaudeProviderCapabilitiesV2,
1385
modelSelection: CLAUDE_MODEL_SELECTION,
1308
- responseByRunOrdinal: { 1: prose },
1386
+ responseByRunOrdinal: {},
1387
capturedTurns,
1388
+ failResumeOnce,
1389
nativeThreadGeneration: generation,
1390
}),
1391
]);
1392
yield* Effect.gen(function* () {
1393
const orchestrator = yield* Orchestrator.OrchestratorV2;
1394
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1316
- const dispatch = (ordinal: number, text: string, selection: ModelSelection) =>
1317
- orchestrator.dispatch({
1395
+ const runToCompletion = Effect.fn("runToCompletion")(function* (ordinal: number) {
1396
+ yield* orchestrator.dispatch({
1397
type: "message.dispatch",
1319
- commandId: CommandId.make(`headroom:${ordinal}`),
1398
+ commandId: CommandId.make(`resume-fallback:${ordinal}`),
1399
threadId,
1321
- messageId: MessageId.make(`headroom:${ordinal}`),
1400
+ messageId: MessageId.make(`resume-fallback:${ordinal}`),
1401
createdBy: "user",
1402
creationSource: "web",
1324
- text,
1403
+ text: `Request ${ordinal}`,
1404
attachments: [],
1326
- modelSelection: selection,
1405
+ modelSelection: CLAUDE_MODEL_SELECTION,
1406
dispatchMode: { type: "start_immediately" },
1407
});
1329
- const wait = (ordinal: number) =>
1330
- orchestrator.streamStoredEvents.pipe(
1408
+ yield* orchestrator.streamStoredEvents.pipe(
1409
Stream.filter(
1410
({ event }) =>
1411
event.type === "run.updated" &&
@@ -1335,39 +1413,86 @@ describe("orchestration v2 provider switching", () => {
1413
(event.payload.status === "completed" || event.payload.status === "failed"),
1414
),
1415
Stream.runHead,
1338
- Effect.andThen(worker.drain()),
1416
);
1417
+ yield* worker.drain();
1418
+ assert.equal(
1419
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1420
+ "completed",
1421
+ );
1422
+ });
1423
yield* orchestrator.dispatch({
1424
type: "thread.create",
1342
- commandId: CommandId.make("headroom:create"),
1425
+ commandId: CommandId.make("resume-fallback:create"),
1426
threadId,
1427
projectId,
1428
createdBy: "user",
1429
creationSource: "web",
1347
- title: "Handoff estimate headroom",
1430
+ title: "Resume fallback",
1431
modelSelection: CLAUDE_MODEL_SELECTION,
1432
runtimeMode: "full-access",
1433
interactionMode: "default",
1434
branch: null,
1435
worktreePath: null,
1436
});
1354
- yield* dispatch(1, "Write the long report", CLAUDE_MODEL_SELECTION);
1355
- yield* wait(1);
1356
- yield* dispatch(2, "Continue elsewhere", CODEX_MODEL_SELECTION);
1357
- yield* wait(2);
1358
- yield* dispatch(3, "Back to the first provider", CLAUDE_MODEL_SELECTION);
1359
- yield* wait(3);
1360
- assert.equal(
1361
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1362
- "completed",
1437
+ yield* runToCompletion(1);
1438
+ const providerThread = (yield* orchestrator.getThreadProjection(
1439
+ threadId,
1440
+ )).providerThreads.at(0);
1441
+ if (providerThread === undefined || providerThread.providerSessionId === null) {
1442
+ return yield* Effect.die("Expected a provider session after the first turn.");
1443
+ }
1444
+ yield* orchestrator.dispatch({
1445
+ type: "provider-session.detach",
1446
+ commandId: CommandId.make("resume-fallback:detach"),
1447
+ threadId,
1448
+ providerSessionId: providerThread.providerSessionId,
1449
+ });
1450
+ yield* worker.drain();
1451
+ if (attempts === "legacy") {
1452
+ const existing = yield* orchestrator.getThreadProjection(threadId);
1453
+ yield* (yield* EventSink.EventSinkV2).write({
1454
+ events: existing.attempts.map(
1455
+ ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
1456
+ id: EventId.make(`resume-fallback-legacy-attempt:${index}`),
1457
+ type: "run-attempt.updated" as const,
1458
+ threadId,
1459
+ occurredAt: existing.thread.createdAt,
1460
+ payload: legacy,
1461
+ }),
1462
+ ),
1463
+ });
1464
+ }
1465
+ yield* Ref.set(failResumeOnce, true);
1466
+ yield* runToCompletion(2);
1467
+ yield* runToCompletion(3);
1468
+
1469
+ const turns = yield* Ref.get(capturedTurns);
1470
+ assert.equal(turns.length, 3);
1471
+ assert.equal(yield* Ref.get(generation), 2);
1472
+ assert.notEqual(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId);
1473
+ assert.isAbove(turns[1]?.providerTurnOrdinal ?? 0, 1);
1474
+ assert.isFalse(turns[1]?.nativeThreadHasTurns);
1475
+ assert.equal(turns[2]?.nativeThreadId, turns[1]?.nativeThreadId);
1476
+ assert.isTrue(turns[2]?.nativeThreadHasTurns);
1477
+
1478
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1479
+ const run2 = projection.runs[1]!;
1480
+ const handoff = projection.contextHandoffs.find(
1481
+ (candidate) => candidate.targetRunId === run2.id,
1482
+ );
1483
+ assert.deepEqual(
1484
+ projection.turnItems
1485
+ .filter((item) => item.runId === run2.id)
1486
+ .toSorted((left, right) => left.ordinal - right.ordinal)
1487
+ .slice(0, 2)
1488
+ .map((item) => (item.type === "handoff" ? item.contextHandoffId : item.type)),
1489
+ [handoff?.id, "user_message"],
1490
);
1364
- // A second generation means T3 discarded the native session as full.
1365
- assert.equal(yield* Ref.get(generation), 1);
1491
}).pipe(
1492
Effect.provide(
1493
ProviderReplayHarness.layerWithRegistry(
1494
{
1370
- name: "handoff-estimate-headroom",
1495
+ name: "resume-fallback-native-turns",
1496
runtimePolicyOverride: {
1497
cwd,
1498
approvalPolicy: "never",
@@ -1379,272 +1504,130 @@ describe("orchestration v2 provider switching", () => {
1504
),
1505
);
1506
}),
1382
- ),
1507
);
1508
1385
- it.live.each(["native", "legacy"] as const)(
1386
- "starts a replacement native thread as new after the resume fallback with %s attempts",
1387
- (attempts) =>
1388
- Effect.scoped(
1389
- Effect.gen(function* () {
1390
- const cwd = yield* checkpointWorkspace("resume-fallback-native-turns");
1391
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1392
- const failResumeOnce = yield* Ref.make(false);
1393
- const generation = yield* Ref.make(0);
1394
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1395
- makeTestAdapter({
1396
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1397
- driver: CLAUDE_DRIVER,
1398
- capabilities: ClaudeProviderCapabilitiesV2,
1399
- modelSelection: CLAUDE_MODEL_SELECTION,
1400
- responseByRunOrdinal: {},
1401
- capturedTurns,
1402
- failResumeOnce,
1403
- nativeThreadGeneration: generation,
1404
- }),
1405
- ]);
1406
- yield* Effect.gen(function* () {
1407
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1408
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1409
- const runToCompletion = Effect.fn("runToCompletion")(function* (ordinal: number) {
1509
+ it.live.each(["an older handoff", "a missed request"] as const)(
1510
+ "keeps the latest turn when a resume fallback also delivers %s",
1511
+ (older) =>
1512
+ Effect.gen(function* () {
1513
+ // A run that fails before its provider turn starts is retried as a missed request.
1514
+ const missed = older === "a missed request";
1515
+ const name = `resume-fallback-handoff-order${missed ? "-missed" : ""}`;
1516
+ const cwd = yield* checkpointWorkspace(name);
1517
+ const failStartOnce = yield* Ref.make(false);
1518
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1519
+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1520
+ const oldResult = `old result ${"o".repeat(2_500)}`;
1521
+ const latestResult = `latest result ${"l".repeat(2_500)}`;
1522
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1523
+ makeTestAdapter({
1524
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1525
+ driver: CLAUDE_DRIVER,
1526
+ capabilities: ClaudeProviderCapabilitiesV2,
1527
+ modelSelection: CLAUDE_MODEL_SELECTION,
1528
+ responseByRunOrdinal: { 1: oldResult, 3: latestResult },
1529
+ capturedTurns,
1530
+ injectedHistory,
1531
+ failResume: true,
1532
+ ...(missed ? { failStartOnce } : { failedRunOrdinals: new Set([2]) }),
1533
+ nativeThreadGeneration: yield* Ref.make(0),
1534
+ }),
1535
+ ]);
1536
+ yield* Effect.gen(function* () {
1537
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1538
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1539
+ const runAfterDetach = Effect.fn("runAfterDetach")(function* (
1540
+ ordinal: number,
1541
+ text: string,
1542
+ ) {
1543
+ const providerSessionId = (yield* orchestrator.getThreadProjection(threadId))
1544
+ .providerThreads[0]?.providerSessionId;
1545
+ if (providerSessionId != null) {
1546
yield* orchestrator.dispatch({
1411
- type: "message.dispatch",
1412
- commandId: CommandId.make(`resume-fallback:${ordinal}`),
1547
+ type: "provider-session.detach",
1548
+ commandId: CommandId.make(`handoff-order:detach:${ordinal}`),
1549
threadId,
1414
- messageId: MessageId.make(`resume-fallback:${ordinal}`),
1415
- createdBy: "user",
1416
- creationSource: "web",
1417
- text: `Request ${ordinal}`,
1418
- attachments: [],
1419
- modelSelection: CLAUDE_MODEL_SELECTION,
1420
- dispatchMode: { type: "start_immediately" },
1550
+ providerSessionId,
1551
});
1422
- yield* orchestrator.streamStoredEvents.pipe(
1423
- Stream.filter(
1424
- ({ event }) =>
1425
- event.type === "run.updated" &&
1426
- event.payload.ordinal === ordinal &&
1427
- (event.payload.status === "completed" || event.payload.status === "failed"),
1428
- ),
1429
- Stream.runHead,
1430
- );
1552
yield* worker.drain();
1432
- assert.equal(
1433
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1434
- "completed",
1435
- );
1436
- });
1553
+ }
1554
yield* orchestrator.dispatch({
1438
- type: "thread.create",
1439
- commandId: CommandId.make("resume-fallback:create"),
1555
+ type: "message.dispatch",
1556
+ commandId: CommandId.make(`handoff-order:${ordinal}`),
1557
threadId,
1441
- projectId,
1558
+ messageId: MessageId.make(`handoff-order:${ordinal}`),
1559
createdBy: "user",
1560
creationSource: "web",
1444
- title: "Resume fallback",
1561
+ text,
1562
+ attachments: [],
1563
modelSelection: CLAUDE_MODEL_SELECTION,
1446
- runtimeMode: "full-access",
1447
- interactionMode: "default",
1448
- branch: null,
1449
- worktreePath: null,
1450
- });
1451
- yield* runToCompletion(1);
1452
- const providerThread = (yield* orchestrator.getThreadProjection(
1453
- threadId,
1454
- )).providerThreads.at(0);
1455
- if (providerThread === undefined || providerThread.providerSessionId === null) {
1456
- return yield* Effect.die("Expected a provider session after the first turn.");
1457
- }
1458
- yield* orchestrator.dispatch({
1459
- type: "provider-session.detach",
1460
- commandId: CommandId.make("resume-fallback:detach"),
1461
- threadId,
1462
- providerSessionId: providerThread.providerSessionId,
1564
+ dispatchMode: { type: "start_immediately" },
1565
});
1566
+ yield* orchestrator.streamStoredEvents.pipe(
1567
+ Stream.filter(
1568
+ ({ event }) =>
1569
+ event.type === "run.updated" &&
1570
+ event.payload.ordinal === ordinal &&
1571
+ (event.payload.status === "completed" || event.payload.status === "failed"),
1572
+ ),
1573
+ Stream.runHead,
1574
+ );
1575
yield* worker.drain();
1465
- if (attempts === "legacy") {
1466
- const existing = yield* orchestrator.getThreadProjection(threadId);
1467
- yield* (yield* EventSink.EventSinkV2).write({
1468
- events: existing.attempts.map(
1469
- ({ nativeThreadId: _nativeThreadId, ...legacy }, index) => ({
1470
- id: EventId.make(`resume-fallback-legacy-attempt:${index}`),
1471
- type: "run-attempt.updated" as const,
1472
- threadId,
1473
- occurredAt: existing.thread.createdAt,
1474
- payload: legacy,
1475
- }),
1476
- ),
1477
- });
1478
- }
1479
- yield* Ref.set(failResumeOnce, true);
1480
- yield* runToCompletion(2);
1481
- yield* runToCompletion(3);
1482
-
1483
- const turns = yield* Ref.get(capturedTurns);
1484
- assert.equal(turns.length, 3);
1485
- assert.equal(yield* Ref.get(generation), 2);
1486
- assert.notEqual(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId);
1487
- assert.isAbove(turns[1]?.providerTurnOrdinal ?? 0, 1);
1488
- assert.isFalse(turns[1]?.nativeThreadHasTurns);
1489
- assert.equal(turns[2]?.nativeThreadId, turns[1]?.nativeThreadId);
1490
- assert.isTrue(turns[2]?.nativeThreadHasTurns);
1576
+ });
1577
+ yield* orchestrator.dispatch({
1578
+ type: "thread.create",
1579
+ commandId: CommandId.make("handoff-order:create"),
1580
+ threadId,
1581
+ projectId,
1582
+ createdBy: "user",
1583
+ creationSource: "web",
1584
+ title: "Resume fallback handoff order",
1585
+ modelSelection: CLAUDE_MODEL_SELECTION,
1586
+ runtimeMode: "full-access",
1587
+ interactionMode: "default",
1588
+ branch: null,
1589
+ worktreePath: null,
1590
+ });
1591
+ yield* runAfterDetach(1, `Original brief ${"b".repeat(9_000)}`);
1592
+ yield* Ref.set(failStartOnce, missed);
1593
+ yield* runAfterDetach(2, missed ? `Request 2 ${"r".repeat(6_000)}` : "Request 2");
1594
+ yield* runAfterDetach(3, "Request 3");
1595
+ const historyBeforeRun4 = (yield* Ref.get(injectedHistory)).length;
1596
+ yield* runAfterDetach(4, "Request 4");
1597
1492
- const projection = yield* orchestrator.getThreadProjection(threadId);
1493
- const run2 = projection.runs[1]!;
1494
- const handoff = projection.contextHandoffs.find(
1495
- (candidate) => candidate.targetRunId === run2.id,
1496
- );
1497
- assert.deepEqual(
1498
- projection.turnItems
1499
- .filter((item) => item.runId === run2.id)
1500
- .toSorted((left, right) => left.ordinal - right.ordinal)
1501
- .slice(0, 2)
1502
- .map((item) => (item.type === "handoff" ? item.contextHandoffId : item.type)),
1503
- [handoff?.id, "user_message"],
1504
- );
1505
- }).pipe(
1506
- Effect.provide(
1507
- ProviderReplayHarness.layerWithRegistry(
1508
- {
1509
- name: "resume-fallback-native-turns",
1510
- runtimePolicyOverride: {
1511
- cwd,
1512
- approvalPolicy: "never",
1513
- sandboxPolicy: { type: "readOnly" },
1514
- },
1515
- },
1516
- layerRegistry,
1517
- ),
1518
- ),
1598
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1599
+ assert.deepEqual(
1600
+ projection.runs.map((run) => run.status),
1601
+ ["completed", "failed", "completed", "completed"],
1602
);
1520
- }),
1521
- ),
1522
- );
1523
-
1524
- it.live.each(["an older handoff", "a missed request"] as const)(
1525
- "keeps the latest turn when a resume fallback also delivers %s",
1526
- (older) =>
1527
- Effect.scoped(
1528
- Effect.gen(function* () {
1529
- // A run that fails before its provider turn starts is retried as a missed request.
1530
- const missed = older === "a missed request";
1531
- const name = `resume-fallback-handoff-order${missed ? "-missed" : ""}`;
1532
- const cwd = yield* checkpointWorkspace(name);
1533
- const failStartOnce = yield* Ref.make(false);
1534
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1535
- const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1536
- const oldResult = `old result ${"o".repeat(2_500)}`;
1537
- const latestResult = `latest result ${"l".repeat(2_500)}`;
1538
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1539
- makeTestAdapter({
1540
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1541
- driver: CLAUDE_DRIVER,
1542
- capabilities: ClaudeProviderCapabilitiesV2,
1543
- modelSelection: CLAUDE_MODEL_SELECTION,
1544
- responseByRunOrdinal: { 1: oldResult, 3: latestResult },
1545
- capturedTurns,
1546
- injectedHistory,
1547
- failResume: true,
1548
- ...(missed ? { failStartOnce } : { failedRunOrdinals: new Set([2]) }),
1549
- nativeThreadGeneration: yield* Ref.make(0),
1550
- }),
1551
- ]);
1552
- yield* Effect.gen(function* () {
1553
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1554
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1555
- const runAfterDetach = Effect.fn("runAfterDetach")(function* (
1556
- ordinal: number,
1557
- text: string,
1558
- ) {
1559
- const providerSessionId = (yield* orchestrator.getThreadProjection(threadId))
1560
- .providerThreads[0]?.providerSessionId;
1561
- if (providerSessionId != null) {
1562
- yield* orchestrator.dispatch({
1563
- type: "provider-session.detach",
1564
- commandId: CommandId.make(`handoff-order:detach:${ordinal}`),
1565
- threadId,
1566
- providerSessionId,
1567
- });
1568
- yield* worker.drain();
1569
- }
1570
- yield* orchestrator.dispatch({
1571
- type: "message.dispatch",
1572
- commandId: CommandId.make(`handoff-order:${ordinal}`),
1573
- threadId,
1574
- messageId: MessageId.make(`handoff-order:${ordinal}`),
1575
- createdBy: "user",
1576
- creationSource: "web",
1577
- text,
1578
- attachments: [],
1579
- modelSelection: CLAUDE_MODEL_SELECTION,
1580
- dispatchMode: { type: "start_immediately" },
1581
- });
1582
- yield* orchestrator.streamStoredEvents.pipe(
1583
- Stream.filter(
1584
- ({ event }) =>
1585
- event.type === "run.updated" &&
1586
- event.payload.ordinal === ordinal &&
1587
- (event.payload.status === "completed" || event.payload.status === "failed"),
1588
- ),
1589
- Stream.runHead,
1590
- );
1591
- yield* worker.drain();
1592
- });
1593
- yield* orchestrator.dispatch({
1594
- type: "thread.create",
1595
- commandId: CommandId.make("handoff-order:create"),
1596
- threadId,
1597
- projectId,
1598
- createdBy: "user",
1599
- creationSource: "web",
1600
- title: "Resume fallback handoff order",
1601
- modelSelection: CLAUDE_MODEL_SELECTION,
1602
- runtimeMode: "full-access",
1603
- interactionMode: "default",
1604
- branch: null,
1605
- worktreePath: null,
1606
- });
1607
- yield* runAfterDetach(1, `Original brief ${"b".repeat(9_000)}`);
1608
- yield* Ref.set(failStartOnce, missed);
1609
- yield* runAfterDetach(2, missed ? `Request 2 ${"r".repeat(6_000)}` : "Request 2");
1610
- yield* runAfterDetach(3, "Request 3");
1611
- const historyBeforeRun4 = (yield* Ref.get(injectedHistory)).length;
1612
- yield* runAfterDetach(4, "Request 4");
1613
-
1614
- const projection = yield* orchestrator.getThreadProjection(threadId);
1615
- assert.deepEqual(
1616
- projection.runs.map((run) => run.status),
1617
- ["completed", "failed", "completed", "completed"],
1618
- );
1619
- const run4NativeThreadId = (yield* Ref.get(capturedTurns)).at(-1)?.nativeThreadId;
1620
- assert.equal(
1621
- projection.contextHandoffs.find(
1622
- (handoff) => handoff.targetRunId === projection.runs[1]?.id,
1623
- )?.delivery?.nativeThreadId,
1624
- run4NativeThreadId,
1625
- );
1626
- const run4History = yield* encodeJson(
1627
- (yield* Ref.get(injectedHistory)).slice(historyBeforeRun4),
1628
- );
1629
- assert.include(run4History, "Original brief");
1630
- assert.include(run4History, latestResult);
1631
- }).pipe(
1632
- Effect.provide(
1633
- ProviderReplayHarness.layerWithRegistry(
1634
- {
1635
- name,
1636
- runtimePolicyOverride: {
1637
- cwd,
1638
- approvalPolicy: "never",
1639
- sandboxPolicy: { type: "readOnly" },
1640
- },
1603
+ const run4NativeThreadId = (yield* Ref.get(capturedTurns)).at(-1)?.nativeThreadId;
1604
+ assert.equal(
1605
+ projection.contextHandoffs.find(
1606
+ (handoff) => handoff.targetRunId === projection.runs[1]?.id,
1607
+ )?.delivery?.nativeThreadId,
1608
+ run4NativeThreadId,
1609
+ );
1610
+ const run4History = yield* encodeJson(
1611
+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRun4),
1612
+ );
1613
+ assert.include(run4History, "Original brief");
1614
+ assert.include(run4History, latestResult);
1615
+ }).pipe(
1616
+ Effect.provide(
1617
+ ProviderReplayHarness.layerWithRegistry(
1618
+ {
1619
+ name,
1620
+ runtimePolicyOverride: {
1621
+ cwd,
1622
+ approvalPolicy: "never",
1623
+ sandboxPolicy: { type: "readOnly" },
1624
},
1642
- layerRegistry,
1643
- ),
1625
+ },
1626
+ layerRegistry,
1627
),
1645
- );
1646
- }),
1647
- ),
1628
+ ),
1629
+ );
1630
+ }),
1631
);
1632
1633
it.live.each([
@@ -1666,96 +1649,94 @@ describe("orchestration v2 provider switching", () => {
1649
}),
1650
],
1651
] as const)("keeps the native session after turns refused for %s", ([, refusalCause]) =>
1669
- Effect.scoped(
1670
- Effect.gen(function* () {
1671
- const cwd = yield* checkpointWorkspace("refused-start-keeps-native");
1672
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1673
- const refuseStarts = yield* Ref.make(0);
1674
- const generation = yield* Ref.make(0);
1675
- const registry = ProviderAdapterRegistry.layerFromAdapters([
1676
- makeTestAdapter({
1677
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1678
- driver: CLAUDE_DRIVER,
1679
- capabilities: ClaudeProviderCapabilitiesV2,
1680
- modelSelection: CLAUDE_MODEL_SELECTION,
1681
- responseByRunOrdinal: {},
1682
- capturedTurns,
1683
- refuseStarts,
1684
- refusalCause,
1685
- nativeThreadGeneration: generation,
1686
- }),
1687
- ]);
1688
- yield* Effect.gen(function* () {
1689
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1690
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1691
- const run = Effect.fn("run")(function* (ordinal: number) {
1692
- yield* orchestrator.dispatch({
1693
- type: "message.dispatch",
1694
- commandId: CommandId.make(`refused-start:${ordinal}`),
1695
- threadId,
1696
- messageId: MessageId.make(`refused-start:${ordinal}`),
1697
- createdBy: "user",
1698
- creationSource: "web",
1699
- text: `Request ${ordinal}`,
1700
- attachments: [],
1701
- modelSelection: CLAUDE_MODEL_SELECTION,
1702
- dispatchMode: { type: "start_immediately" },
1703
- });
1704
- yield* orchestrator.streamStoredEvents.pipe(
1705
- Stream.filter(
1706
- ({ event }) =>
1707
- event.type === "run.updated" &&
1708
- event.payload.ordinal === ordinal &&
1709
- (event.payload.status === "completed" || event.payload.status === "failed"),
1710
- ),
1711
- Stream.runHead,
1712
- );
1713
- yield* worker.drain();
1714
- return (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status;
1715
- });
1652
+ Effect.gen(function* () {
1653
+ const cwd = yield* checkpointWorkspace("refused-start-keeps-native");
1654
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1655
+ const refuseStarts = yield* Ref.make(0);
1656
+ const generation = yield* Ref.make(0);
1657
+ const registry = ProviderAdapterRegistry.layerFromAdapters([
1658
+ makeTestAdapter({
1659
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1660
+ driver: CLAUDE_DRIVER,
1661
+ capabilities: ClaudeProviderCapabilitiesV2,
1662
+ modelSelection: CLAUDE_MODEL_SELECTION,
1663
+ responseByRunOrdinal: {},
1664
+ capturedTurns,
1665
+ refuseStarts,
1666
+ refusalCause,
1667
+ nativeThreadGeneration: generation,
1668
+ }),
1669
+ ]);
1670
+ yield* Effect.gen(function* () {
1671
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1672
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1673
+ const run = Effect.fn("run")(function* (ordinal: number) {
1674
yield* orchestrator.dispatch({
1717
- type: "thread.create",
1718
- commandId: CommandId.make("refused-start:create"),
1675
+ type: "message.dispatch",
1676
+ commandId: CommandId.make(`refused-start:${ordinal}`),
1677
threadId,
1720
- projectId,
1678
+ messageId: MessageId.make(`refused-start:${ordinal}`),
1679
createdBy: "user",
1680
creationSource: "web",
1723
- title: "Refused start",
1681
+ text: `Request ${ordinal}`,
1682
+ attachments: [],
1683
modelSelection: CLAUDE_MODEL_SELECTION,
1725
- runtimeMode: "full-access",
1726
- interactionMode: "default",
1727
- branch: null,
1728
- worktreePath: null,
1684
+ dispatchMode: { type: "start_immediately" },
1685
});
1730
- assert.equal(yield* run(1), "completed");
1731
- yield* Ref.set(refuseStarts, 2);
1732
- assert.equal(yield* run(2), "failed");
1733
- assert.equal(yield* run(3), "failed");
1734
- assert.equal(yield* run(4), "completed");
1686
+ yield* orchestrator.streamStoredEvents.pipe(
1687
+ Stream.filter(
1688
+ ({ event }) =>
1689
+ event.type === "run.updated" &&
1690
+ event.payload.ordinal === ordinal &&
1691
+ (event.payload.status === "completed" || event.payload.status === "failed"),
1692
+ ),
1693
+ Stream.runHead,
1694
+ );
1695
+ yield* worker.drain();
1696
+ return (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status;
1697
+ });
1698
+ yield* orchestrator.dispatch({
1699
+ type: "thread.create",
1700
+ commandId: CommandId.make("refused-start:create"),
1701
+ threadId,
1702
+ projectId,
1703
+ createdBy: "user",
1704
+ creationSource: "web",
1705
+ title: "Refused start",
1706
+ modelSelection: CLAUDE_MODEL_SELECTION,
1707
+ runtimeMode: "full-access",
1708
+ interactionMode: "default",
1709
+ branch: null,
1710
+ worktreePath: null,
1711
+ });
1712
+ assert.equal(yield* run(1), "completed");
1713
+ yield* Ref.set(refuseStarts, 2);
1714
+ assert.equal(yield* run(2), "failed");
1715
+ assert.equal(yield* run(3), "failed");
1716
+ assert.equal(yield* run(4), "completed");
1717
1736
- const turns = yield* Ref.get(capturedTurns);
1737
- assert.equal(turns.length, 2);
1738
- assert.equal(yield* Ref.get(generation), 1);
1739
- assert.equal(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId);
1740
- assert.include(turns[1]?.text, "Request 2");
1741
- assert.include(turns[1]?.text, "Request 3");
1742
- }).pipe(
1743
- Effect.provide(
1744
- ProviderReplayHarness.layerWithRegistry(
1745
- {
1746
- name: "refused-start-keeps-native",
1747
- runtimePolicyOverride: {
1748
- cwd,
1749
- approvalPolicy: "never",
1750
- sandboxPolicy: { type: "readOnly" },
1751
- },
1718
+ const turns = yield* Ref.get(capturedTurns);
1719
+ assert.equal(turns.length, 2);
1720
+ assert.equal(yield* Ref.get(generation), 1);
1721
+ assert.equal(turns[1]?.nativeThreadId, turns[0]?.nativeThreadId);
1722
+ assert.include(turns[1]?.text, "Request 2");
1723
+ assert.include(turns[1]?.text, "Request 3");
1724
+ }).pipe(
1725
+ Effect.provide(
1726
+ ProviderReplayHarness.layerWithRegistry(
1727
+ {
1728
+ name: "refused-start-keeps-native",
1729
+ runtimePolicyOverride: {
1730
+ cwd,
1731
+ approvalPolicy: "never",
1732
+ sandboxPolicy: { type: "readOnly" },
1733
},
1753
- registry,
1754
- ),
1734
+ },
1735
+ registry,
1736
),
1756
- );
1757
- }),
1758
- ),
1737
+ ),
1738
+ );
1739
+ }),
1740
);
1741
1742
it.live.each(
@@ -1776,591 +1757,391 @@ describe("orchestration v2 provider switching", () => {
1757
] as const,
1758
),
1759
)("hands off %s", ([, { status, queued, returning, native }]) =>
1779
- Effect.scoped(
1780
- Effect.gen(function* () {
1781
- const cwd = yield* checkpointWorkspace(`handoff-${status}-${queued}-${returning}`);
1782
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1783
- const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1784
- const started = yield* Deferred.make<void>();
1785
- const release = yield* Deferred.make<void>();
1786
- const sourceOrdinal = returning ? 2 : 1;
1787
- const sourceSelection = returning ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION;
1788
- const targetSelection = returning ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION;
1789
- const originalPrompt = "Keep the release marker violet and preserve the existing API.";
1790
- const partialResponse = "I checked the API and found the release configuration.";
1791
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(
1792
- (
1793
- [
1794
- [CODEX_MODEL_SELECTION, CODEX_DRIVER, CodexProviderCapabilitiesV2],
1795
- [CLAUDE_MODEL_SELECTION, CLAUDE_DRIVER, ClaudeProviderCapabilitiesV2],
1796
- ] as const
1797
- ).map(([modelSelection, driver, capabilities]) =>
1798
- makeTestAdapter({
1799
- instanceId: modelSelection.instanceId,
1800
- driver,
1801
- capabilities,
1802
- modelSelection,
1803
- responseByRunOrdinal: { [sourceOrdinal]: partialResponse },
1804
- capturedTurns,
1805
- ...(native && modelSelection.instanceId === targetSelection.instanceId
1806
- ? { injectedHistory }
1807
- : {}),
1808
- ...(modelSelection.instanceId === sourceSelection.instanceId
1809
- ? {
1810
- failedRunOrdinals: new Set(status === "failed" ? [sourceOrdinal] : []),
1811
- interruptedRunOrdinals: new Set(
1812
- status === "interrupted" ? [sourceOrdinal] : [],
1813
- ),
1814
- cancelledRunOrdinals: new Set(status === "cancelled" ? [sourceOrdinal] : []),
1815
- holdRunOrdinal: sourceOrdinal,
1816
- holdFirstTurn: started,
1817
- releaseFirstTurn: release,
1818
- }
1819
- : {}),
1820
- }),
1821
- ),
1822
- );
1823
- yield* Effect.gen(function* () {
1824
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1825
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1826
- const waitForRun = (
1827
- ordinal: number,
1828
- expectedStatus: "completed" | "failed" | "interrupted" | "cancelled",
1829
- ) =>
1830
- orchestrator.streamStoredEvents.pipe(
1831
- Stream.filter(
1832
- ({ event }) =>
1833
- event.type === "run.updated" &&
1834
- event.threadId === threadId &&
1835
- event.payload.ordinal === ordinal &&
1836
- event.payload.status === expectedStatus,
1837
- ),
1838
- Stream.runHead,
1839
- Effect.andThen(worker.drain()),
1840
- );
1841
- const dispatch = (
1842
- key: string,
1843
- text: string,
1844
- modelSelection: ModelSelection,
1845
- queue = false,
1846
- ) =>
1847
- orchestrator.dispatch({
1848
- type: "message.dispatch",
1849
- commandId: CommandId.make(`command:handoff:${key}`),
1850
- threadId,
1851
- messageId: MessageId.make(`message:handoff:${key}`),
1852
- createdBy: "user",
1853
- creationSource: "web",
1854
- text,
1855
- attachments: [],
1856
- modelSelection,
1857
- dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" },
1858
- });
1859
- yield* orchestrator.dispatch({
1860
- type: "thread.create",
1861
- commandId: CommandId.make("command:handoff:create"),
1760
+ Effect.gen(function* () {
1761
+ const cwd = yield* checkpointWorkspace(`handoff-${status}-${queued}-${returning}`);
1762
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1763
+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);
1764
+ const started = yield* Deferred.make<void>();
1765
+ const release = yield* Deferred.make<void>();
1766
+ const sourceOrdinal = returning ? 2 : 1;
1767
+ const sourceSelection = returning ? CLAUDE_MODEL_SELECTION : CODEX_MODEL_SELECTION;
1768
+ const targetSelection = returning ? CODEX_MODEL_SELECTION : CLAUDE_MODEL_SELECTION;
1769
+ const originalPrompt = "Keep the release marker violet and preserve the existing API.";
1770
+ const partialResponse = "I checked the API and found the release configuration.";
1771
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters(
1772
+ (
1773
+ [
1774
+ [CODEX_MODEL_SELECTION, CODEX_DRIVER, CodexProviderCapabilitiesV2],
1775
+ [CLAUDE_MODEL_SELECTION, CLAUDE_DRIVER, ClaudeProviderCapabilitiesV2],
1776
+ ] as const
1777
+ ).map(([modelSelection, driver, capabilities]) =>
1778
+ makeTestAdapter({
1779
+ instanceId: modelSelection.instanceId,
1780
+ driver,
1781
+ capabilities,
1782
+ modelSelection,
1783
+ responseByRunOrdinal: { [sourceOrdinal]: partialResponse },
1784
+ capturedTurns,
1785
+ ...(native && modelSelection.instanceId === targetSelection.instanceId
1786
+ ? { injectedHistory }
1787
+ : {}),
1788
+ ...(modelSelection.instanceId === sourceSelection.instanceId
1789
+ ? {
1790
+ failedRunOrdinals: new Set(status === "failed" ? [sourceOrdinal] : []),
1791
+ interruptedRunOrdinals: new Set(status === "interrupted" ? [sourceOrdinal] : []),
1792
+ cancelledRunOrdinals: new Set(status === "cancelled" ? [sourceOrdinal] : []),
1793
+ holdRunOrdinal: sourceOrdinal,
1794
+ holdFirstTurn: started,
1795
+ releaseFirstTurn: release,
1796
+ }
1797
+ : {}),
1798
+ }),
1799
+ ),
1800
+ );
1801
+ yield* Effect.gen(function* () {
1802
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1803
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1804
+ const waitForRun = (
1805
+ ordinal: number,
1806
+ expectedStatus: "completed" | "failed" | "interrupted" | "cancelled",
1807
+ ) =>
1808
+ orchestrator.streamStoredEvents.pipe(
1809
+ Stream.filter(
1810
+ ({ event }) =>
1811
+ event.type === "run.updated" &&
1812
+ event.threadId === threadId &&
1813
+ event.payload.ordinal === ordinal &&
1814
+ event.payload.status === expectedStatus,
1815
+ ),
1816
+ Stream.runHead,
1817
+ Effect.andThen(worker.drain()),
1818
+ );
1819
+ const dispatch = (
1820
+ key: string,
1821
+ text: string,
1822
+ modelSelection: ModelSelection,
1823
+ queue = false,
1824
+ ) =>
1825
+ orchestrator.dispatch({
1826
+ type: "message.dispatch",
1827
+ commandId: CommandId.make(`command:handoff:${key}`),
1828
threadId,
1863
- projectId,
1829
+ messageId: MessageId.make(`message:handoff:${key}`),
1830
createdBy: "user",
1831
creationSource: "web",
1866
- title: "Interrupted provider handoff",
1867
- modelSelection: CODEX_MODEL_SELECTION,
1868
- runtimeMode: "full-access",
1869
- interactionMode: "default",
1870
- branch: null,
1871
- worktreePath: null,
1832
+ text,
1833
+ attachments: [],
1834
+ modelSelection,
1835
+ dispatchMode: { type: queue ? "queue_after_active" : "start_immediately" },
1836
});
1873
- if (returning) {
1874
- yield* dispatch("initial", "Earlier successful request.", CODEX_MODEL_SELECTION);
1875
- yield* waitForRun(1, "completed");
1876
- }
1877
- yield* dispatch("source", originalPrompt, sourceSelection);
1878
- yield* Deferred.await(started);
1879
- if (queued) {
1880
- yield* dispatch("target", "Continue", targetSelection, true);
1881
- assert.equal(
1882
- (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1883
- "queued",
1884
- );
1885
- }
1886
- yield* Deferred.succeed(release, undefined);
1887
- yield* waitForRun(sourceOrdinal, status);
1888
- if (!queued) {
1889
- yield* dispatch("target", "Continue", targetSelection);
1890
- }
1891
- yield* waitForRun(sourceOrdinal + 1, "completed");
1892
- const projection = yield* orchestrator.getThreadProjection(threadId);
1893
- const targetRun = projection.runs.at(-1)!;
1894
- const handoff = projection.contextHandoffs.find(
1895
- (candidate) => candidate.id === targetRun.contextHandoffId,
1896
- );
1897
- assert.isDefined(handoff);
1837
+ yield* orchestrator.dispatch({
1838
+ type: "thread.create",
1839
+ commandId: CommandId.make("command:handoff:create"),
1840
+ threadId,
1841
+ projectId,
1842
+ createdBy: "user",
1843
+ creationSource: "web",
1844
+ title: "Interrupted provider handoff",
1845
+ modelSelection: CODEX_MODEL_SELECTION,
1846
+ runtimeMode: "full-access",
1847
+ interactionMode: "default",
1848
+ branch: null,
1849
+ worktreePath: null,
1850
+ });
1851
+ if (returning) {
1852
+ yield* dispatch("initial", "Earlier successful request.", CODEX_MODEL_SELECTION);
1853
+ yield* waitForRun(1, "completed");
1854
+ }
1855
+ yield* dispatch("source", originalPrompt, sourceSelection);
1856
+ yield* Deferred.await(started);
1857
+ if (queued) {
1858
+ yield* dispatch("target", "Continue", targetSelection, true);
1859
assert.equal(
1899
- handoff?.strategy,
1900
- returning ? "delta_since_target_last_seen" : "full_thread_summary",
1860
+ (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
1861
+ "queued",
1862
);
1902
- assert.deepEqual(handoff?.coveredRunOrdinals, {
1903
- from: sourceOrdinal,
1904
- to: sourceOrdinal,
1905
- });
1906
- const delivered = (yield* Ref.get(capturedTurns)).at(-1)!;
1907
- const history = yield* Ref.get(injectedHistory);
1908
- const deliveredHistory = native ? yield* encodeJson(history) : delivered.text;
1909
- assert.include(deliveredHistory, originalPrompt);
1910
- assert.include(deliveredHistory, partialResponse);
1911
- assert.include(deliveredHistory, `run-status=${status}`);
1912
- if (native) {
1913
- assert.equal(delivered.text, "Continue");
1914
- assert.notInclude(deliveredHistory, '"text":"Continue"');
1915
- assert.include(deliveredHistory, '"role":"assistant"');
1916
- assert.include(deliveredHistory, '"role":"user"');
1917
- assert.equal(handoff?.delivery?.status, "injected");
1918
- } else {
1919
- assert.include(delivered.text, "User message:\nContinue");
1920
- assert.equal(handoff?.delivery?.status, "inline");
1921
- }
1922
- assert.notInclude(deliveredHistory, "Earlier successful request.");
1923
- yield* dispatch("back", "Finish the remaining work", sourceSelection);
1924
- yield* waitForRun(sourceOrdinal + 2, "completed");
1925
- const back = (yield* Ref.get(capturedTurns)).at(-1)!;
1926
- assert.notInclude(back.text, originalPrompt);
1927
- assert.notInclude(back.text, partialResponse);
1928
- }).pipe(
1929
- Effect.provide(
1930
- ProviderReplayHarness.layerWithRegistry(
1931
- {
1932
- name: `handoff-${status}-${queued}-${returning}`,
1933
- runtimePolicyOverride: {
1934
- cwd,
1935
- approvalPolicy: "never",
1936
- sandboxPolicy: {
1937
- type: "readOnly",
1938
- access: { type: "fullAccess" },
1939
- networkAccess: false,
1940
- },
1863
+ }
1864
+ yield* Deferred.succeed(release, undefined);
1865
+ yield* waitForRun(sourceOrdinal, status);
1866
+ if (!queued) {
1867
+ yield* dispatch("target", "Continue", targetSelection);
1868
+ }
1869
+ yield* waitForRun(sourceOrdinal + 1, "completed");
1870
+ const projection = yield* orchestrator.getThreadProjection(threadId);
1871
+ const targetRun = projection.runs.at(-1)!;
1872
+ const handoff = projection.contextHandoffs.find(
1873
+ (candidate) => candidate.id === targetRun.contextHandoffId,
1874
+ );
1875
+ assert.isDefined(handoff);
1876
+ assert.equal(
1877
+ handoff?.strategy,
1878
+ returning ? "delta_since_target_last_seen" : "full_thread_summary",
1879
+ );
1880
+ assert.deepEqual(handoff?.coveredRunOrdinals, {
1881
+ from: sourceOrdinal,
1882
+ to: sourceOrdinal,
1883
+ });
1884
+ const delivered = (yield* Ref.get(capturedTurns)).at(-1)!;
1885
+ const history = yield* Ref.get(injectedHistory);
1886
+ const deliveredHistory = native ? yield* encodeJson(history) : delivered.text;
1887
+ assert.include(deliveredHistory, originalPrompt);
1888
+ assert.include(deliveredHistory, partialResponse);
1889
+ assert.include(deliveredHistory, `run-status=${status}`);
1890
+ if (native) {
1891
+ assert.equal(delivered.text, "Continue");
1892
+ assert.notInclude(deliveredHistory, '"text":"Continue"');
1893
+ assert.include(deliveredHistory, '"role":"assistant"');
1894
+ assert.include(deliveredHistory, '"role":"user"');
1895
+ assert.equal(handoff?.delivery?.status, "injected");
1896
+ } else {
1897
+ assert.include(delivered.text, "User message:\nContinue");
1898
+ assert.equal(handoff?.delivery?.status, "inline");
1899
+ }
1900
+ assert.notInclude(deliveredHistory, "Earlier successful request.");
1901
+ yield* dispatch("back", "Finish the remaining work", sourceSelection);
1902
+ yield* waitForRun(sourceOrdinal + 2, "completed");
1903
+ const back = (yield* Ref.get(capturedTurns)).at(-1)!;
1904
+ assert.notInclude(back.text, originalPrompt);
1905
+ assert.notInclude(back.text, partialResponse);
1906
+ }).pipe(
1907
+ Effect.provide(
1908
+ ProviderReplayHarness.layerWithRegistry(
1909
+ {
1910
+ name: `handoff-${status}-${queued}-${returning}`,
1911
+ runtimePolicyOverride: {
1912
+ cwd,
1913
+ approvalPolicy: "never",
1914
+ sandboxPolicy: {
1915
+ type: "readOnly",
1916
+ access: { type: "fullAccess" },
1917
+ networkAccess: false,
1918
},
1919
},
1943
- layerRegistry,
1944
- ),
1920
+ },
1921
+ layerRegistry,
1922
),
1946
- );
1947
- }),
1948
- ),
1923
+ ),
1924
+ );
1925
+ }),
1926
);
1927
1928
// regression: #15993 t3_worktree_handoff releases the Claude session that runs it. Nothing
1929
// was left to report how the call ended, so it stayed running and the thread stayed Waiting.
1930
it.live("interrupts the handoff tool call that releases its own session", () =>
1954
- Effect.scoped(
1955
- Effect.gen(function* () {
1956
- const key = "handoff-cuts-off-tool-call";
1957
- const worktreePath = yield* checkpointWorkspace(key);
1958
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1959
- const started = yield* Deferred.make<void>();
1960
- const toolCallId = TurnItemId.make(`turn-item:${key}`);
1961
- const scenarioThreadId = ThreadId.make(`thread:${key}`);
1962
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1963
- makeTestAdapter({
1964
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1965
- driver: CLAUDE_DRIVER,
1966
- capabilities: ClaudeProviderCapabilitiesV2,
1967
- modelSelection: CLAUDE_MODEL_SELECTION,
1968
- responseByRunOrdinal: {},
1969
- capturedTurns,
1970
- holdFirstTurn: started,
1971
- heldRunningToolCall: {
1972
- id: toolCallId,
1973
- toolName: "mcp__t3-code__t3_worktree_handoff",
1974
- },
1975
- backgroundTasksEndWithProcess: true,
1976
- }),
1977
- makeTestAdapter({
1978
- instanceId: CODEX_MODEL_SELECTION.instanceId,
1979
- driver: CODEX_DRIVER,
1980
- capabilities: CodexProviderCapabilitiesV2,
1981
- modelSelection: CODEX_MODEL_SELECTION,
1982
- responseByRunOrdinal: {},
1983
- capturedTurns,
1984
- }),
1985
- ]);
1986
- yield* Effect.gen(function* () {
1987
- const orchestrator = yield* Orchestrator.OrchestratorV2;
1988
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1989
- const awaitEvent = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
1990
- orchestrator.streamDomainEvents.pipe(
1991
- Stream.filter(predicate),
1992
- Stream.take(1),
1993
- Stream.runDrain,
1994
- Effect.forkScoped,
1995
- );
1996
- yield* orchestrator.dispatch({
1997
- type: "thread.create",
1998
- createdBy: "user",
1999
- creationSource: "web",
2000
- commandId: CommandId.make(`command:${key}:create`),
2001
- threadId: scenarioThreadId,
2002
- projectId: ProjectId.make(`project:${key}`),
2003
- title: "Tool call releases its session",
2004
- modelSelection: CLAUDE_MODEL_SELECTION,
2005
- runtimeMode: "full-access",
2006
- interactionMode: "default",
2007
- branch: null,
2008
- worktreePath: null,
2009
- });
2010
- const toolCallRunning = yield* awaitEvent(
2011
- (event) =>
2012
- event.type === "turn-item.updated" &&
2013
- event.payload.id === toolCallId &&
2014
- event.payload.status === "running",
1931
+ Effect.gen(function* () {
1932
+ const key = "handoff-cuts-off-tool-call";
1933
+ const worktreePath = yield* checkpointWorkspace(key);
1934
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
1935
+ const started = yield* Deferred.make<void>();
1936
+ const toolCallId = TurnItemId.make(`turn-item:${key}`);
1937
+ const scenarioThreadId = ThreadId.make(`thread:${key}`);
1938
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
1939
+ makeTestAdapter({
1940
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
1941
+ driver: CLAUDE_DRIVER,
1942
+ capabilities: ClaudeProviderCapabilitiesV2,
1943
+ modelSelection: CLAUDE_MODEL_SELECTION,
1944
+ responseByRunOrdinal: {},
1945
+ capturedTurns,
1946
+ holdFirstTurn: started,
1947
+ heldRunningToolCall: {
1948
+ id: toolCallId,
1949
+ toolName: "mcp__t3-code__t3_worktree_handoff",
1950
+ },
1951
+ backgroundTasksEndWithProcess: true,
1952
+ }),
1953
+ makeTestAdapter({
1954
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
1955
+ driver: CODEX_DRIVER,
1956
+ capabilities: CodexProviderCapabilitiesV2,
1957
+ modelSelection: CODEX_MODEL_SELECTION,
1958
+ responseByRunOrdinal: {},
1959
+ capturedTurns,
1960
+ }),
1961
+ ]);
1962
+ yield* Effect.gen(function* () {
1963
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
1964
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1965
+ const awaitEvent = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
1966
+ orchestrator.streamDomainEvents.pipe(
1967
+ Stream.filter(predicate),
1968
+ Stream.take(1),
1969
+ Stream.runDrain,
1970
+ Effect.forkScoped,
1971
);
2016
- yield* orchestrator.dispatch({
2017
- type: "message.dispatch",
2018
- createdBy: "user",
2019
- creationSource: "web",
2020
- commandId: CommandId.make(`command:${key}:message`),
2021
- threadId: scenarioThreadId,
2022
- messageId: MessageId.make(`message:${key}`),
2023
- text: "Release this session",
2024
- attachments: [],
2025
- modelSelection: CLAUDE_MODEL_SELECTION,
2026
- dispatchMode: { type: "start_immediately" },
2027
- });
2028
- yield* Deferred.await(started);
2029
- yield* Fiber.join(toolCallRunning);
1972
+ yield* orchestrator.dispatch({
1973
+ type: "thread.create",
1974
+ createdBy: "user",
1975
+ creationSource: "web",
1976
+ commandId: CommandId.make(`command:${key}:create`),
1977
+ threadId: scenarioThreadId,
1978
+ projectId: ProjectId.make(`project:${key}`),
1979
+ title: "Tool call releases its session",
1980
+ modelSelection: CLAUDE_MODEL_SELECTION,
1981
+ runtimeMode: "full-access",
1982
+ interactionMode: "default",
1983
+ branch: null,
1984
+ worktreePath: null,
1985
+ });
1986
+ const toolCallRunning = yield* awaitEvent(
1987
+ (event) =>
1988
+ event.type === "turn-item.updated" &&
1989
+ event.payload.id === toolCallId &&
1990
+ event.payload.status === "running",
1991
+ );
1992
+ yield* orchestrator.dispatch({
1993
+ type: "message.dispatch",
1994
+ createdBy: "user",
1995
+ creationSource: "web",
1996
+ commandId: CommandId.make(`command:${key}:message`),
1997
+ threadId: scenarioThreadId,
1998
+ messageId: MessageId.make(`message:${key}`),
1999
+ text: "Release this session",
2000
+ attachments: [],
2001
+ modelSelection: CLAUDE_MODEL_SELECTION,
2002
+ dispatchMode: { type: "start_immediately" },
2003
+ });
2004
+ yield* Deferred.await(started);
2005
+ yield* Fiber.join(toolCallRunning);
2006
2031
- const runFailed = yield* awaitEvent(
2032
- (event) => event.type === "run.updated" && event.payload.status === "failed",
2033
- );
2034
- yield* orchestrator.dispatch({
2035
- type: "thread.metadata.update",
2036
- commandId: CommandId.make(`command:${key}:release`),
2037
- threadId: scenarioThreadId,
2038
- branch: `t3/${key}`,
2039
- worktreePath,
2040
- expectedWorktreePath: null,
2041
- });
2042
- yield* worker.drain();
2043
- yield* Fiber.join(runFailed);
2007
+ const runFailed = yield* awaitEvent(
2008
+ (event) => event.type === "run.updated" && event.payload.status === "failed",
2009
+ );
2010
+ yield* orchestrator.dispatch({
2011
+ type: "thread.metadata.update",
2012
+ commandId: CommandId.make(`command:${key}:release`),
2013
+ threadId: scenarioThreadId,
2014
+ branch: `t3/${key}`,
2015
+ worktreePath,
2016
+ expectedWorktreePath: null,
2017
+ });
2018
+ yield* worker.drain();
2019
+ yield* Fiber.join(runFailed);
2020
2045
- const projection = yield* orchestrator.getThreadProjection(scenarioThreadId);
2046
- const toolCall = projection.turnItems.find((item) => item.id === toolCallId);
2047
- assert.equal(toolCall?.status, "interrupted");
2048
- assert.isNotNull(toolCall?.completedAt);
2049
- assert.deepEqual(
2050
- derivePendingBackgroundWork({
2051
- latestRun: projection.runs.at(-1),
2052
- providerThreads: projection.providerThreads,
2053
- turnItems: projection.turnItems,
2054
- activeProviderThreadId: projection.thread.activeProviderThreadId,
2055
- runs: projection.runs,
2056
- }),
2057
- [],
2058
- );
2059
- }).pipe(
2060
- Effect.provide(ProviderReplayHarness.layerWithRegistry({ name: key }, layerRegistry)),
2021
+ const projection = yield* orchestrator.getThreadProjection(scenarioThreadId);
2022
+ const toolCall = projection.turnItems.find((item) => item.id === toolCallId);
2023
+ assert.equal(toolCall?.status, "interrupted");
2024
+ assert.isNotNull(toolCall?.completedAt);
2025
+ assert.deepEqual(
2026
+ derivePendingBackgroundWork({
2027
+ latestRun: projection.runs.at(-1),
2028
+ providerThreads: projection.providerThreads,
2029
+ turnItems: projection.turnItems,
2030
+ activeProviderThreadId: projection.thread.activeProviderThreadId,
2031
+ runs: projection.runs,
2032
+ }),
2033
+ [],
2034
);
2062
- }),
2063
- ),
2035
+ }).pipe(
2036
+ Effect.provide(ProviderReplayHarness.layerWithRegistry({ name: key }, layerRegistry)),
2037
+ );
2038
+ }),
2039
);
2040
2041
it.live("checks the queued provider's capability while the current provider stays running", () =>
2067
- Effect.scoped(
2068
- Effect.gen(function* () {
2069
- for (const scenario of [
2070
- { activeSupportsQueue: false, selectedSupportsQueue: true },
2071
- { activeSupportsQueue: true, selectedSupportsQueue: false },
2072
- ]) {
2073
- const key = `active-${scenario.activeSupportsQueue}-selected-${scenario.selectedSupportsQueue}`;
2074
- const cwd = yield* checkpointWorkspace(`queued-capability-${key}`);
2075
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2076
- const started = yield* Deferred.make<void>();
2077
- const scenarioThreadId = ThreadId.make(`thread:queued-capability:${key}`);
2078
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2079
- makeTestAdapter({
2080
- instanceId: CODEX_MODEL_SELECTION.instanceId,
2081
- driver: CODEX_DRIVER,
2082
- capabilities: {
2083
- ...CodexProviderCapabilitiesV2,
2084
- turns: {
2085
- ...CodexProviderCapabilitiesV2.turns,
2086
- supportsQueuedMessages: scenario.activeSupportsQueue,
2087
- },
2088
- },
2089
- modelSelection: CODEX_MODEL_SELECTION,
2090
- responseByRunOrdinal: {},
2091
- capturedTurns,
2092
- holdFirstTurn: started,
2093
- }),
2094
- makeTestAdapter({
2095
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2096
- driver: CLAUDE_DRIVER,
2097
- capabilities: {
2098
- ...ClaudeProviderCapabilitiesV2,
2099
- turns: {
2100
- ...ClaudeProviderCapabilitiesV2.turns,
2101
- supportsQueuedMessages: scenario.selectedSupportsQueue,
2102
- },
2103
- },
2104
- modelSelection: CLAUDE_MODEL_SELECTION,
2105
- responseByRunOrdinal: {},
2106
- capturedTurns,
2107
- }),
2108
- ]);
2109
- yield* Effect.gen(function* () {
2110
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2111
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2112
- yield* orchestrator.dispatch({
2113
- type: "thread.create",
2114
- createdBy: "user",
2115
- creationSource: "web",
2116
- commandId: CommandId.make(`command:queued-capability:create:${key}`),
2117
- threadId: scenarioThreadId,
2118
- projectId: ProjectId.make(`project:queued-capability:${key}`),
2119
- title: "Queued capability",
2120
- modelSelection: CODEX_MODEL_SELECTION,
2121
- runtimeMode: "full-access",
2122
- interactionMode: "default",
2123
- branch: null,
2124
- worktreePath: cwd,
2125
- });
2126
- yield* orchestrator.dispatch({
2127
- type: "message.dispatch",
2128
- createdBy: "user",
2129
- creationSource: "web",
2130
- commandId: CommandId.make(`command:queued-capability:first:${key}`),
2131
- threadId: scenarioThreadId,
2132
- messageId: MessageId.make(`message:queued-capability:first:${key}`),
2133
- text: "Current Codex turn",
2134
- attachments: [],
2135
- modelSelection: CODEX_MODEL_SELECTION,
2136
- dispatchMode: { type: "start_immediately" },
2137
- });
2138
- yield* Deferred.await(started);
2139
- yield* worker.drain();
2140
- const queue = orchestrator.dispatch({
2141
- type: "message.dispatch",
2142
- createdBy: "user",
2143
- creationSource: "web",
2144
- commandId: CommandId.make(`command:queued-capability:claude:${key}`),
2145
- threadId: scenarioThreadId,
2146
- messageId: MessageId.make(`message:queued-capability:claude:${key}`),
2147
- text: "Queued Claude turn",
2148
- attachments: [],
2149
- modelSelection: CLAUDE_MODEL_SELECTION,
2150
- dispatchMode: { type: "queue_after_active" },
2151
- });
2152
- if (scenario.selectedSupportsQueue) {
2153
- yield* queue;
2154
- } else {
2155
- const error = yield* queue.pipe(Effect.flip);
2156
- assert.instanceOf(error, Orchestrator.OrchestratorDispatchError);
2157
- assert.instanceOf(error.cause, CommandPolicyCapabilityUnsupportedError);
2158
- assert.equal(error.cause.capability, "queued_messages");
2159
- }
2160
- const projection = yield* orchestrator.getThreadProjection(scenarioThreadId);
2161
- assert.deepEqual(
2162
- projection.runs.map((run) => run.status),
2163
- scenario.selectedSupportsQueue ? ["running", "queued"] : ["running"],
2164
- );
2165
- assert.deepEqual(projection.thread.modelSelection, CODEX_MODEL_SELECTION);
2166
- }).pipe(
2167
- Effect.provide(
2168
- ProviderReplayHarness.layerWithRegistry(
2169
- {
2170
- name: `queued-capability-${key}`,
2171
- runtimePolicyOverride: {
2172
- cwd,
2173
- approvalPolicy: "never",
2174
- sandboxPolicy: {
2175
- type: "readOnly",
2176
- access: { type: "fullAccess" },
2177
- networkAccess: false,
2178
- },
2179
- },
2180
- },
2181
- layerRegistry,
2182
- ),
2183
- ),
2184
- );
2185
- }
2186
- }),
2187
- ),
2188
- );
2189
-
2190
- it.live("hands completed Grok steering context to earlier queued Codex and later Claude", () =>
2191
- Effect.scoped(
2192
- Effect.gen(function* () {
2193
- const cwd = yield* checkpointWorkspace("queued-steer-provider-switch");
2042
+ Effect.gen(function* () {
2043
+ for (const scenario of [
2044
+ { activeSupportsQueue: false, selectedSupportsQueue: true },
2045
+ { activeSupportsQueue: true, selectedSupportsQueue: false },
2046
+ ]) {
2047
+ const key = `active-${scenario.activeSupportsQueue}-selected-${scenario.selectedSupportsQueue}`;
2048
+ const cwd = yield* checkpointWorkspace(`queued-capability-${key}`);
2049
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2050
const started = yield* Deferred.make<void>();
2051
+ const scenarioThreadId = ThreadId.make(`thread:queued-capability:${key}`);
2052
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2053
makeTestAdapter({
2054
instanceId: CODEX_MODEL_SELECTION.instanceId,
2055
driver: CODEX_DRIVER,
2200
- capabilities: CodexProviderCapabilitiesV2,
2056
+ capabilities: {
2057
+ ...CodexProviderCapabilitiesV2,
2058
+ turns: {
2059
+ ...CodexProviderCapabilitiesV2.turns,
2060
+ supportsQueuedMessages: scenario.activeSupportsQueue,
2061
+ },
2062
+ },
2063
modelSelection: CODEX_MODEL_SELECTION,
2202
- responseByRunOrdinal: { 2: "Codex queued response" },
2064
+ responseByRunOrdinal: {},
2065
capturedTurns,
2066
holdFirstTurn: started,
2067
}),
2068
makeTestAdapter({
2069
instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2070
driver: CLAUDE_DRIVER,
2209
- capabilities: ClaudeProviderCapabilitiesV2,
2071
+ capabilities: {
2072
+ ...ClaudeProviderCapabilitiesV2,
2073
+ turns: {
2074
+ ...ClaudeProviderCapabilitiesV2.turns,
2075
+ supportsQueuedMessages: scenario.selectedSupportsQueue,
2076
+ },
2077
+ },
2078
modelSelection: CLAUDE_MODEL_SELECTION,
2211
- responseByRunOrdinal: { 3: "Claude queued response" },
2212
- capturedTurns,
2213
- }),
2214
- makeTestAdapter({
2215
- instanceId: GROK_MODEL_SELECTION.instanceId,
2216
- driver: GROK_DRIVER,
2217
- capabilities: AcpProviderCapabilitiesV2,
2218
- modelSelection: GROK_MODEL_SELECTION,
2219
- responseByRunOrdinal: { 1: "Grok steered response" },
2079
+ responseByRunOrdinal: {},
2080
capturedTurns,
2081
}),
2082
]);
2223
- const queuedThreadId = ThreadId.make("thread:queued-steer-provider-switch");
2224
- const projection = yield* Effect.gen(function* () {
2083
+ yield* Effect.gen(function* () {
2084
const orchestrator = yield* Orchestrator.OrchestratorV2;
2085
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2227
- const eventSink = yield* EventSink.EventSinkV2;
2228
- const dispatch = (
2229
- key: string,
2230
- modelSelection: ModelSelection,
2231
- dispatchMode: Extract<
2232
- OrchestrationV2Command,
2233
- { readonly type: "message.dispatch" }
2234
- >["dispatchMode"],
2235
- ) =>
2236
- orchestrator.dispatch({
2237
- type: "message.dispatch",
2238
- createdBy: "user",
2239
- creationSource: "web",
2240
- commandId: CommandId.make(`command:queued-steer-provider-switch:${key}`),
2241
- threadId: queuedThreadId,
2242
- messageId: MessageId.make(`message:queued-steer-provider-switch:${key}`),
2243
- text: `Prompt ${key}`,
2244
- attachments: [],
2245
- modelSelection,
2246
- dispatchMode,
2247
- });
2086
yield* orchestrator.dispatch({
2087
type: "thread.create",
2088
createdBy: "user",
2089
creationSource: "web",
2252
- commandId: CommandId.make("command:queued-steer-provider-switch:create"),
2253
- threadId: queuedThreadId,
2254
- projectId: ProjectId.make("project:queued-steer-provider-switch"),
2255
- title: "Queued steer provider switch",
2090
+ commandId: CommandId.make(`command:queued-capability:create:${key}`),
2091
+ threadId: scenarioThreadId,
2092
+ projectId: ProjectId.make(`project:queued-capability:${key}`),
2093
+ title: "Queued capability",
2094
modelSelection: CODEX_MODEL_SELECTION,
2095
runtimeMode: "full-access",
2096
interactionMode: "default",
2097
branch: null,
2098
worktreePath: cwd,
2099
});
2262
- yield* dispatch("first", CODEX_MODEL_SELECTION, { type: "start_immediately" });
2100
+ yield* orchestrator.dispatch({
2101
+ type: "message.dispatch",
2102
+ createdBy: "user",
2103
+ creationSource: "web",
2104
+ commandId: CommandId.make(`command:queued-capability:first:${key}`),
2105
+ threadId: scenarioThreadId,
2106
+ messageId: MessageId.make(`message:queued-capability:first:${key}`),
2107
+ text: "Current Codex turn",
2108
+ attachments: [],
2109
+ modelSelection: CODEX_MODEL_SELECTION,
2110
+ dispatchMode: { type: "start_immediately" },
2111
+ });
2112
yield* Deferred.await(started);
2113
yield* worker.drain();
2265
- yield* dispatch("codex-queued", CODEX_MODEL_SELECTION, { type: "queue_after_active" });
2266
- yield* dispatch("claude-queued", CLAUDE_MODEL_SELECTION, { type: "queue_after_active" });
2267
- const beforeSteer = yield* orchestrator.getThreadProjection(queuedThreadId);
2268
- assert.deepEqual(
2269
- beforeSteer.runs.map((run) => run.status),
2270
- ["running", "queued", "queued"],
2271
- );
2272
- assert.equal(beforeSteer.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2273
- assert.lengthOf(beforeSteer.contextHandoffs, 0);
2274
- const now = yield* DateTime.now;
2275
- yield* eventSink.write({
2276
- events: [
2277
- {
2278
- id: EventId.make("event:queued-steer-provider-switch:first-turn-running"),
2279
- type: "provider-turn.updated",
2280
- threadId: queuedThreadId,
2281
- runId: beforeSteer.runs[0]!.id,
2282
- nodeId: beforeSteer.runs[0]!.rootNodeId!,
2283
- driver: CODEX_DRIVER,
2284
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2285
- occurredAt: now,
2286
- payload: {
2287
- id: ProviderTurnId.make("provider-turn:queued-steer-provider-switch:first"),
2288
- providerThreadId: beforeSteer.runs[0]!.providerThreadId!,
2289
- nodeId: beforeSteer.runs[0]!.rootNodeId!,
2290
- runAttemptId: beforeSteer.runs[0]!.activeAttemptId!,
2291
- nativeTurnRef: null,
2292
- ordinal: 1,
2293
- status: "running",
2294
- startedAt: now,
2295
- completedAt: null,
2296
- },
2297
- },
2298
- ],
2114
+ const queue = orchestrator.dispatch({
2115
+ type: "message.dispatch",
2116
+ createdBy: "user",
2117
+ creationSource: "web",
2118
+ commandId: CommandId.make(`command:queued-capability:claude:${key}`),
2119
+ threadId: scenarioThreadId,
2120
+ messageId: MessageId.make(`message:queued-capability:claude:${key}`),
2121
+ text: "Queued Claude turn",
2122
+ attachments: [],
2123
+ modelSelection: CLAUDE_MODEL_SELECTION,
2124
+ dispatchMode: { type: "queue_after_active" },
2125
});
2300
- const queuedClaudeCompleted = yield* orchestrator.streamStoredEvents.pipe(
2301
- Stream.filter(
2302
- (event) =>
2303
- event.event.type === "run.updated" &&
2304
- event.event.runId === beforeSteer.runs[2]?.id &&
2305
- event.event.payload.status === "completed",
2306
- ),
2307
- Stream.runHead,
2308
- Effect.forkScoped,
2126
+ if (scenario.selectedSupportsQueue) {
2127
+ yield* queue;
2128
+ } else {
2129
+ const error = yield* queue.pipe(Effect.flip);
2130
+ assert.instanceOf(error, Orchestrator.OrchestratorDispatchError);
2131
+ assert.instanceOf(error.cause, CommandPolicyCapabilityUnsupportedError);
2132
+ assert.equal(error.cause.capability, "queued_messages");
2133
+ }
2134
+ const projection = yield* orchestrator.getThreadProjection(scenarioThreadId);
2135
+ assert.deepEqual(
2136
+ projection.runs.map((run) => run.status),
2137
+ scenario.selectedSupportsQueue ? ["running", "queued"] : ["running"],
2138
);
2310
- yield* dispatch("grok-steer", GROK_MODEL_SELECTION, {
2311
- type: "steer_active",
2312
- targetRunId: beforeSteer.runs[0]!.id,
2313
- });
2314
- const afterSteer = yield* orchestrator.getThreadProjection(queuedThreadId);
2315
- assert.deepEqual(afterSteer.thread.modelSelection, GROK_MODEL_SELECTION);
2316
- const interruptedTurn = afterSteer.providerTurns.find(
2317
- (turn) => turn.runAttemptId === beforeSteer.runs[0]?.activeAttemptId,
2318
- )!;
2319
- const interruptedAttempt = afterSteer.attempts.find(
2320
- (attempt) => attempt.id === beforeSteer.runs[0]?.activeAttemptId,
2321
- )!;
2322
- const interruptedAt = yield* DateTime.now;
2323
- yield* eventSink.write({
2324
- events: [
2325
- {
2326
- id: EventId.make("event:queued-steer-provider-switch:first-turn-interrupted"),
2327
- type: "provider-turn.updated",
2328
- threadId: queuedThreadId,
2329
- runId: beforeSteer.runs[0]!.id,
2330
- nodeId: beforeSteer.runs[0]!.rootNodeId!,
2331
- driver: CODEX_DRIVER,
2332
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2333
- occurredAt: interruptedAt,
2334
- payload: {
2335
- ...interruptedTurn,
2336
- status: "interrupted",
2337
- completedAt: interruptedAt,
2338
- },
2339
- },
2340
- {
2341
- id: EventId.make("event:queued-steer-provider-switch:first-attempt-interrupted"),
2342
- type: "run-attempt.updated",
2343
- threadId: queuedThreadId,
2344
- runId: beforeSteer.runs[0]!.id,
2345
- nodeId: beforeSteer.runs[0]!.rootNodeId!,
2346
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2347
- occurredAt: interruptedAt,
2348
- payload: {
2349
- ...interruptedAttempt,
2350
- status: "interrupted",
2351
- completedAt: interruptedAt,
2352
- },
2353
- },
2354
- ],
2355
- });
2356
- yield* worker.drain();
2357
- yield* Fiber.join(queuedClaudeCompleted);
2358
- return yield* orchestrator.getThreadProjection(queuedThreadId);
2139
+ assert.deepEqual(projection.thread.modelSelection, CODEX_MODEL_SELECTION);
2140
}).pipe(
2141
Effect.provide(
2142
ProviderReplayHarness.layerWithRegistry(
2143
{
2363
- name: "queued-steer-provider-switch",
2144
+ name: `queued-capability-${key}`,
2145
runtimePolicyOverride: {
2146
cwd,
2147
approvalPolicy: "never",
@@ -2375,183 +2156,579 @@ describe("orchestration v2 provider switching", () => {
2156
),
2157
),
2158
);
2159
+ }
2160
+ }),
2161
+ );
2162
+
2163
+ it.live("hands completed Grok steering context to earlier queued Codex and later Claude", () =>
2164
+ Effect.gen(function* () {
2165
+ const cwd = yield* checkpointWorkspace("queued-steer-provider-switch");
2166
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2167
+ const started = yield* Deferred.make<void>();
2168
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2169
+ makeTestAdapter({
2170
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
2171
+ driver: CODEX_DRIVER,
2172
+ capabilities: CodexProviderCapabilitiesV2,
2173
+ modelSelection: CODEX_MODEL_SELECTION,
2174
+ responseByRunOrdinal: { 2: "Codex queued response" },
2175
+ capturedTurns,
2176
+ holdFirstTurn: started,
2177
+ }),
2178
+ makeTestAdapter({
2179
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2180
+ driver: CLAUDE_DRIVER,
2181
+ capabilities: ClaudeProviderCapabilitiesV2,
2182
+ modelSelection: CLAUDE_MODEL_SELECTION,
2183
+ responseByRunOrdinal: { 3: "Claude queued response" },
2184
+ capturedTurns,
2185
+ }),
2186
+ makeTestAdapter({
2187
+ instanceId: GROK_MODEL_SELECTION.instanceId,
2188
+ driver: GROK_DRIVER,
2189
+ capabilities: AcpProviderCapabilitiesV2,
2190
+ modelSelection: GROK_MODEL_SELECTION,
2191
+ responseByRunOrdinal: { 1: "Grok steered response" },
2192
+ capturedTurns,
2193
+ }),
2194
+ ]);
2195
+ const queuedThreadId = ThreadId.make("thread:queued-steer-provider-switch");
2196
+ const projection = yield* Effect.gen(function* () {
2197
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2198
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2199
+ const eventSink = yield* EventSink.EventSinkV2;
2200
+ const dispatch = (
2201
+ key: string,
2202
+ modelSelection: ModelSelection,
2203
+ dispatchMode: Extract<
2204
+ OrchestrationV2Command,
2205
+ { readonly type: "message.dispatch" }
2206
+ >["dispatchMode"],
2207
+ ) =>
2208
+ orchestrator.dispatch({
2209
+ type: "message.dispatch",
2210
+ createdBy: "user",
2211
+ creationSource: "web",
2212
+ commandId: CommandId.make(`command:queued-steer-provider-switch:${key}`),
2213
+ threadId: queuedThreadId,
2214
+ messageId: MessageId.make(`message:queued-steer-provider-switch:${key}`),
2215
+ text: `Prompt ${key}`,
2216
+ attachments: [],
2217
+ modelSelection,
2218
+ dispatchMode,
2219
+ });
2220
+ yield* orchestrator.dispatch({
2221
+ type: "thread.create",
2222
+ createdBy: "user",
2223
+ creationSource: "web",
2224
+ commandId: CommandId.make("command:queued-steer-provider-switch:create"),
2225
+ threadId: queuedThreadId,
2226
+ projectId: ProjectId.make("project:queued-steer-provider-switch"),
2227
+ title: "Queued steer provider switch",
2228
+ modelSelection: CODEX_MODEL_SELECTION,
2229
+ runtimeMode: "full-access",
2230
+ interactionMode: "default",
2231
+ branch: null,
2232
+ worktreePath: cwd,
2233
+ });
2234
+ yield* dispatch("first", CODEX_MODEL_SELECTION, { type: "start_immediately" });
2235
+ yield* Deferred.await(started);
2236
+ yield* worker.drain();
2237
+ yield* dispatch("codex-queued", CODEX_MODEL_SELECTION, { type: "queue_after_active" });
2238
+ yield* dispatch("claude-queued", CLAUDE_MODEL_SELECTION, { type: "queue_after_active" });
2239
+ const beforeSteer = yield* orchestrator.getThreadProjection(queuedThreadId);
2240
assert.deepEqual(
2379
- projection.runs.map((run) => [run.providerInstanceId, run.status]),
2380
- [
2381
- [GROK_MODEL_SELECTION.instanceId, "completed"],
2382
- [CODEX_MODEL_SELECTION.instanceId, "completed"],
2383
- [CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2384
- ],
2385
- );
2386
- const turns = yield* Ref.get(capturedTurns);
2387
- assert.deepEqual(
2388
- turns.map((turn) => turn.driver),
2389
- [CODEX_DRIVER, GROK_DRIVER, CODEX_DRIVER, CLAUDE_DRIVER],
2241
+ beforeSteer.runs.map((run) => run.status),
2242
+ ["running", "queued", "queued"],
2243
);
2391
- assert.include(turns[2]?.text ?? "", "Grok steered response");
2392
- assert.include(turns[3]?.text ?? "", "Grok steered response");
2393
- assert.include(turns[3]?.text ?? "", "Codex queued response");
2394
- assert.deepEqual(
2395
- projection.contextHandoffs.map((handoff) => handoff.targetRunId),
2396
- [projection.runs[0]?.id, projection.runs[1]?.id, projection.runs[2]?.id],
2244
+ assert.equal(beforeSteer.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2245
+ assert.lengthOf(beforeSteer.contextHandoffs, 0);
2246
+ const now = yield* DateTime.now;
2247
+ yield* eventSink.write({
2248
+ events: [
2249
+ {
2250
+ id: EventId.make("event:queued-steer-provider-switch:first-turn-running"),
2251
+ type: "provider-turn.updated",
2252
+ threadId: queuedThreadId,
2253
+ runId: beforeSteer.runs[0]!.id,
2254
+ nodeId: beforeSteer.runs[0]!.rootNodeId!,
2255
+ driver: CODEX_DRIVER,
2256
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2257
+ occurredAt: now,
2258
+ payload: {
2259
+ id: ProviderTurnId.make("provider-turn:queued-steer-provider-switch:first"),
2260
+ providerThreadId: beforeSteer.runs[0]!.providerThreadId!,
2261
+ nodeId: beforeSteer.runs[0]!.rootNodeId!,
2262
+ runAttemptId: beforeSteer.runs[0]!.activeAttemptId!,
2263
+ nativeTurnRef: null,
2264
+ ordinal: 1,
2265
+ status: "running",
2266
+ startedAt: now,
2267
+ completedAt: null,
2268
+ },
2269
+ },
2270
+ ],
2271
+ });
2272
+ const queuedClaudeCompleted = yield* orchestrator.streamStoredEvents.pipe(
2273
+ Stream.filter(
2274
+ (event) =>
2275
+ event.event.type === "run.updated" &&
2276
+ event.event.runId === beforeSteer.runs[2]?.id &&
2277
+ event.event.payload.status === "completed",
2278
+ ),
2279
+ Stream.runHead,
2280
+ Effect.forkScoped,
2281
);
2398
- }),
2399
- ),
2282
+ yield* dispatch("grok-steer", GROK_MODEL_SELECTION, {
2283
+ type: "steer_active",
2284
+ targetRunId: beforeSteer.runs[0]!.id,
2285
+ });
2286
+ const afterSteer = yield* orchestrator.getThreadProjection(queuedThreadId);
2287
+ assert.deepEqual(afterSteer.thread.modelSelection, GROK_MODEL_SELECTION);
2288
+ const interruptedTurn = afterSteer.providerTurns.find(
2289
+ (turn) => turn.runAttemptId === beforeSteer.runs[0]?.activeAttemptId,
2290
+ )!;
2291
+ const interruptedAttempt = afterSteer.attempts.find(
2292
+ (attempt) => attempt.id === beforeSteer.runs[0]?.activeAttemptId,
2293
+ )!;
2294
+ const interruptedAt = yield* DateTime.now;
2295
+ yield* eventSink.write({
2296
+ events: [
2297
+ {
2298
+ id: EventId.make("event:queued-steer-provider-switch:first-turn-interrupted"),
2299
+ type: "provider-turn.updated",
2300
+ threadId: queuedThreadId,
2301
+ runId: beforeSteer.runs[0]!.id,
2302
+ nodeId: beforeSteer.runs[0]!.rootNodeId!,
2303
+ driver: CODEX_DRIVER,
2304
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2305
+ occurredAt: interruptedAt,
2306
+ payload: {
2307
+ ...interruptedTurn,
2308
+ status: "interrupted",
2309
+ completedAt: interruptedAt,
2310
+ },
2311
+ },
2312
+ {
2313
+ id: EventId.make("event:queued-steer-provider-switch:first-attempt-interrupted"),
2314
+ type: "run-attempt.updated",
2315
+ threadId: queuedThreadId,
2316
+ runId: beforeSteer.runs[0]!.id,
2317
+ nodeId: beforeSteer.runs[0]!.rootNodeId!,
2318
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2319
+ occurredAt: interruptedAt,
2320
+ payload: {
2321
+ ...interruptedAttempt,
2322
+ status: "interrupted",
2323
+ completedAt: interruptedAt,
2324
+ },
2325
+ },
2326
+ ],
2327
+ });
2328
+ yield* worker.drain();
2329
+ yield* Fiber.join(queuedClaudeCompleted);
2330
+ return yield* orchestrator.getThreadProjection(queuedThreadId);
2331
+ }).pipe(
2332
+ Effect.provide(
2333
+ ProviderReplayHarness.layerWithRegistry(
2334
+ {
2335
+ name: "queued-steer-provider-switch",
2336
+ runtimePolicyOverride: {
2337
+ cwd,
2338
+ approvalPolicy: "never",
2339
+ sandboxPolicy: {
2340
+ type: "readOnly",
2341
+ access: { type: "fullAccess" },
2342
+ networkAccess: false,
2343
+ },
2344
+ },
2345
+ },
2346
+ layerRegistry,
2347
+ ),
2348
+ ),
2349
+ );
2350
+ assert.deepEqual(
2351
+ projection.runs.map((run) => [run.providerInstanceId, run.status]),
2352
+ [
2353
+ [GROK_MODEL_SELECTION.instanceId, "completed"],
2354
+ [CODEX_MODEL_SELECTION.instanceId, "completed"],
2355
+ [CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2356
+ ],
2357
+ );
2358
+ const turns = yield* Ref.get(capturedTurns);
2359
+ assert.deepEqual(
2360
+ turns.map((turn) => turn.driver),
2361
+ [CODEX_DRIVER, GROK_DRIVER, CODEX_DRIVER, CLAUDE_DRIVER],
2362
+ );
2363
+ assert.include(turns[2]?.text ?? "", "Grok steered response");
2364
+ assert.include(turns[3]?.text ?? "", "Grok steered response");
2365
+ assert.include(turns[3]?.text ?? "", "Codex queued response");
2366
+ assert.deepEqual(
2367
+ projection.contextHandoffs.map((handoff) => handoff.targetRunId),
2368
+ [projection.runs[0]?.id, projection.runs[1]?.id, projection.runs[2]?.id],
2369
+ );
2370
+ }),
2371
);
2372
2373
it.live("resumes a queued account switch without requiring a portable handoff", () =>
2403
- Effect.scoped(
2404
- Effect.gen(function* () {
2405
- const cwd = yield* checkpointWorkspace("queued-account-switch");
2406
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2407
- const started = yield* Deferred.make<void>();
2408
- const alternateSelection: ModelSelection = {
2409
- ...CODEX_MODEL_SELECTION,
2410
- instanceId: ProviderInstanceId.make("codex-alternate"),
2411
- };
2412
- const alternateCapabilities = {
2413
- ...CodexProviderCapabilitiesV2,
2414
- canConsumeHandoffSummaries: false,
2415
- };
2416
- const adapters = [
2417
- makeTestAdapter({
2418
- instanceId: CODEX_MODEL_SELECTION.instanceId,
2419
- driver: CODEX_DRIVER,
2420
- capabilities: CodexProviderCapabilitiesV2,
2421
- modelSelection: CODEX_MODEL_SELECTION,
2422
- responseByRunOrdinal: {},
2423
- capturedTurns,
2424
- holdFirstTurn: started,
2425
- }),
2426
- makeTestAdapter({
2427
- instanceId: alternateSelection.instanceId,
2428
- driver: CODEX_DRIVER,
2429
- capabilities: alternateCapabilities,
2430
- modelSelection: alternateSelection,
2431
- responseByRunOrdinal: { 2: "Alternate account complete" },
2432
- capturedTurns,
2433
- }),
2434
- ];
2435
- const layerRegistry = Layer.succeed(
2436
- ProviderAdapterRegistry.ProviderAdapterRegistryV2,
2437
- ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
2438
- get: (instanceId) => {
2439
- const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2440
- return adapter === undefined
2441
- ? Effect.fail(
2442
- new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
2443
- )
2444
- : Effect.succeed(adapter);
2445
- },
2446
- list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
2447
- getMetadata: (instanceId) => {
2448
- const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2449
- return adapter === undefined
2450
- ? Effect.fail(
2451
- new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
2452
- )
2453
- : Effect.succeed({
2454
- driver: CODEX_DRIVER,
2455
- continuationKey: "codex:shared-native-account-history",
2456
- enabled: true,
2457
- capabilities:
2458
- instanceId === alternateSelection.instanceId
2459
- ? alternateCapabilities
2460
- : CodexProviderCapabilitiesV2,
2461
- });
2374
+ Effect.gen(function* () {
2375
+ const cwd = yield* checkpointWorkspace("queued-account-switch");
2376
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2377
+ const started = yield* Deferred.make<void>();
2378
+ const alternateSelection: ModelSelection = {
2379
+ ...CODEX_MODEL_SELECTION,
2380
+ instanceId: ProviderInstanceId.make("codex-alternate"),
2381
+ };
2382
+ const alternateCapabilities = {
2383
+ ...CodexProviderCapabilitiesV2,
2384
+ canConsumeHandoffSummaries: false,
2385
+ };
2386
+ const adapters = [
2387
+ makeTestAdapter({
2388
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
2389
+ driver: CODEX_DRIVER,
2390
+ capabilities: CodexProviderCapabilitiesV2,
2391
+ modelSelection: CODEX_MODEL_SELECTION,
2392
+ responseByRunOrdinal: {},
2393
+ capturedTurns,
2394
+ holdFirstTurn: started,
2395
+ }),
2396
+ makeTestAdapter({
2397
+ instanceId: alternateSelection.instanceId,
2398
+ driver: CODEX_DRIVER,
2399
+ capabilities: alternateCapabilities,
2400
+ modelSelection: alternateSelection,
2401
+ responseByRunOrdinal: { 2: "Alternate account complete" },
2402
+ capturedTurns,
2403
+ }),
2404
+ ];
2405
+ const layerRegistry = Layer.succeed(
2406
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2,
2407
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
2408
+ get: (instanceId) => {
2409
+ const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2410
+ return adapter === undefined
2411
+ ? Effect.fail(
2412
+ new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
2413
+ )
2414
+ : Effect.succeed(adapter);
2415
+ },
2416
+ list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
2417
+ getMetadata: (instanceId) => {
2418
+ const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2419
+ return adapter === undefined
2420
+ ? Effect.fail(
2421
+ new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
2422
+ )
2423
+ : Effect.succeed({
2424
+ driver: CODEX_DRIVER,
2425
+ continuationKey: "codex:shared-native-account-history",
2426
+ enabled: true,
2427
+ capabilities:
2428
+ instanceId === alternateSelection.instanceId
2429
+ ? alternateCapabilities
2430
+ : CodexProviderCapabilitiesV2,
2431
+ });
2432
+ },
2433
+ }),
2434
+ );
2435
+ const queuedThreadId = ThreadId.make("thread:queued-account-switch");
2436
+ const projection = yield* Effect.gen(function* () {
2437
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2438
+ const eventSink = yield* EventSink.EventSinkV2;
2439
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2440
+ yield* orchestrator.dispatch({
2441
+ type: "thread.create",
2442
+ createdBy: "user",
2443
+ creationSource: "web",
2444
+ commandId: CommandId.make("command:queued-account-switch:create"),
2445
+ threadId: queuedThreadId,
2446
+ projectId: ProjectId.make("project:queued-account-switch"),
2447
+ title: "Queued account switch",
2448
+ modelSelection: CODEX_MODEL_SELECTION,
2449
+ runtimeMode: "full-access",
2450
+ interactionMode: "default",
2451
+ branch: null,
2452
+ worktreePath: cwd,
2453
+ });
2454
+ yield* orchestrator.dispatch({
2455
+ type: "message.dispatch",
2456
+ createdBy: "user",
2457
+ creationSource: "web",
2458
+ commandId: CommandId.make("command:queued-account-switch:first"),
2459
+ threadId: queuedThreadId,
2460
+ messageId: MessageId.make("message:queued-account-switch:first"),
2461
+ text: "First account turn",
2462
+ attachments: [],
2463
+ modelSelection: CODEX_MODEL_SELECTION,
2464
+ dispatchMode: { type: "start_immediately" },
2465
+ });
2466
+ yield* Deferred.await(started);
2467
+ yield* orchestrator.dispatch({
2468
+ type: "message.dispatch",
2469
+ createdBy: "user",
2470
+ creationSource: "web",
2471
+ commandId: CommandId.make("command:queued-account-switch:second"),
2472
+ threadId: queuedThreadId,
2473
+ messageId: MessageId.make("message:queued-account-switch:second"),
2474
+ text: "Alternate account turn",
2475
+ attachments: [],
2476
+ modelSelection: alternateSelection,
2477
+ dispatchMode: { type: "queue_after_active" },
2478
+ });
2479
+ const queued = yield* orchestrator.getThreadProjection(queuedThreadId);
2480
+ assert.deepEqual(
2481
+ queued.runs.map((run) => run.status),
2482
+ ["running", "queued"],
2483
+ );
2484
+ assert.equal(queued.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2485
+ const sourceNativeRef = queued.providerThreads.find(
2486
+ (providerThread) => providerThread.id === queued.runs[0]?.providerThreadId,
2487
+ )?.nativeThreadRef;
2488
+ assert.isNotNull(sourceNativeRef);
2489
+ const now = yield* DateTime.now;
2490
+ yield* eventSink.write({
2491
+ events: [
2492
+ {
2493
+ id: EventId.make("event:queued-account-switch:first-complete"),
2494
+ type: "run.updated",
2495
+ threadId: queuedThreadId,
2496
+ runId: queued.runs[0]!.id,
2497
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2498
+ occurredAt: now,
2499
+ payload: { ...queued.runs[0]!, status: "completed", completedAt: now },
2500
},
2463
- }),
2501
+ ],
2502
+ });
2503
+ yield* orchestrator.resumeQueuedRuns;
2504
+ yield* orchestrator.streamStoredEvents.pipe(
2505
+ Stream.filter(
2506
+ (event) =>
2507
+ event.event.type === "run.updated" &&
2508
+ event.event.runId === queued.runs[1]?.id &&
2509
+ event.event.payload.status === "completed",
2510
+ ),
2511
+ Stream.runHead,
2512
);
2465
- const queuedThreadId = ThreadId.make("thread:queued-account-switch");
2466
- const projection = yield* Effect.gen(function* () {
2467
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2468
- const eventSink = yield* EventSink.EventSinkV2;
2469
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2470
- yield* orchestrator.dispatch({
2471
- type: "thread.create",
2472
- createdBy: "user",
2473
- creationSource: "web",
2474
- commandId: CommandId.make("command:queued-account-switch:create"),
2475
- threadId: queuedThreadId,
2476
- projectId: ProjectId.make("project:queued-account-switch"),
2477
- title: "Queued account switch",
2478
- modelSelection: CODEX_MODEL_SELECTION,
2479
- runtimeMode: "full-access",
2480
- interactionMode: "default",
2481
- branch: null,
2482
- worktreePath: cwd,
2483
- });
2484
- yield* orchestrator.dispatch({
2485
- type: "message.dispatch",
2486
- createdBy: "user",
2487
- creationSource: "web",
2488
- commandId: CommandId.make("command:queued-account-switch:first"),
2489
- threadId: queuedThreadId,
2490
- messageId: MessageId.make("message:queued-account-switch:first"),
2491
- text: "First account turn",
2492
- attachments: [],
2493
- modelSelection: CODEX_MODEL_SELECTION,
2494
- dispatchMode: { type: "start_immediately" },
2495
- });
2496
- yield* Deferred.await(started);
2497
- yield* orchestrator.dispatch({
2513
+ yield* worker.drain();
2514
+ const delivered = yield* orchestrator.getThreadProjection(queuedThreadId);
2515
+ const targetNativeRef = delivered.providerThreads.find(
2516
+ (providerThread) => providerThread.id === delivered.runs[1]?.providerThreadId,
2517
+ )?.nativeThreadRef;
2518
+ assert.deepEqual(targetNativeRef, sourceNativeRef);
2519
+ return delivered;
2520
+ }).pipe(
2521
+ Effect.provide(
2522
+ ProviderReplayHarness.layerWithRegistry(
2523
+ {
2524
+ name: "queued-account-switch",
2525
+ runtimePolicyOverride: {
2526
+ cwd,
2527
+ approvalPolicy: "never",
2528
+ sandboxPolicy: {
2529
+ type: "readOnly",
2530
+ access: { type: "fullAccess" },
2531
+ networkAccess: false,
2532
+ },
2533
+ },
2534
+ },
2535
+ layerRegistry,
2536
+ ),
2537
+ ),
2538
+ );
2539
+ assert.deepEqual(
2540
+ projection.runs.map((run) => [run.providerInstanceId, run.status]),
2541
+ [
2542
+ [CODEX_MODEL_SELECTION.instanceId, "completed"],
2543
+ [alternateSelection.instanceId, "completed"],
2544
+ ],
2545
+ );
2546
+ assert.lengthOf(projection.contextHandoffs, 0);
2547
+ assert.deepEqual(
2548
+ (yield* Ref.get(capturedTurns)).map((turn) => turn.text),
2549
+ ["First account turn", "Alternate account turn"],
2550
+ );
2551
+ }),
2552
+ );
2553
+
2554
+ it.live("finishes earlier queued Codex turns before handing context to queued Claude", () =>
2555
+ Effect.gen(function* () {
2556
+ const cwd = yield* checkpointWorkspace("queued-provider-switch");
2557
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2558
+ const started = yield* Deferred.make<void>();
2559
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2560
+ makeTestAdapter({
2561
+ instanceId: ProviderInstanceId.make("codex"),
2562
+ driver: CODEX_DRIVER,
2563
+ capabilities: CodexProviderCapabilitiesV2,
2564
+ modelSelection: CODEX_MODEL_SELECTION,
2565
+ responseByRunOrdinal: {
2566
+ 1: "Codex current turn complete",
2567
+ 2: "Codex first queued turn complete",
2568
+ 3: "Codex second queued turn complete",
2569
+ },
2570
+ capturedTurns,
2571
+ holdFirstTurn: started,
2572
+ }),
2573
+ makeTestAdapter({
2574
+ instanceId: ProviderInstanceId.make("claudeAgent"),
2575
+ driver: CLAUDE_DRIVER,
2576
+ capabilities: ClaudeProviderCapabilitiesV2,
2577
+ modelSelection: CLAUDE_MODEL_SELECTION,
2578
+ responseByRunOrdinal: { 4: "Claude turn complete" },
2579
+ capturedTurns,
2580
+ }),
2581
+ ]);
2582
+ const queuedThreadId = ThreadId.make("thread:queued-provider-switch");
2583
+ const layerDatabase = SqlitePersistence.layerMemory;
2584
+ const layerOutboxProvided = EffectOutbox.layer.pipe(Layer.provide(layerDatabase));
2585
+ const projection = yield* Effect.gen(function* () {
2586
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2587
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2588
+ const eventSink = yield* EventSink.EventSinkV2;
2589
+ const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
2590
+ const dispatch = (ordinal: number, modelSelection: ModelSelection) =>
2591
+ orchestrator.dispatch({
2592
type: "message.dispatch",
2593
createdBy: "user",
2594
creationSource: "web",
2501
- commandId: CommandId.make("command:queued-account-switch:second"),
2595
+ commandId: CommandId.make(`command:queued-provider-switch:${ordinal}`),
2596
threadId: queuedThreadId,
2503
- messageId: MessageId.make("message:queued-account-switch:second"),
2504
- text: "Alternate account turn",
2597
+ messageId: MessageId.make(`message:queued-provider-switch:${ordinal}`),
2598
+ text: `Prompt ${ordinal}`,
2599
attachments: [],
2506
- modelSelection: alternateSelection,
2507
- dispatchMode: { type: "queue_after_active" },
2600
+ modelSelection,
2601
+ dispatchMode: {
2602
+ type: ordinal === 1 ? "start_immediately" : "queue_after_active",
2603
+ },
2604
});
2509
- const queued = yield* orchestrator.getThreadProjection(queuedThreadId);
2510
- assert.deepEqual(
2511
- queued.runs.map((run) => run.status),
2512
- ["running", "queued"],
2513
- );
2514
- assert.equal(queued.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2515
- const sourceNativeRef = queued.providerThreads.find(
2516
- (providerThread) => providerThread.id === queued.runs[0]?.providerThreadId,
2517
- )?.nativeThreadRef;
2518
- assert.isNotNull(sourceNativeRef);
2519
- const now = yield* DateTime.now;
2520
- yield* eventSink.write({
2521
- events: [
2522
- {
2523
- id: EventId.make("event:queued-account-switch:first-complete"),
2524
- type: "run.updated",
2605
+ yield* orchestrator.dispatch({
2606
+ type: "thread.create",
2607
+ createdBy: "user",
2608
+ creationSource: "web",
2609
+ commandId: CommandId.make("command:queued-provider-switch:create"),
2610
+ threadId: queuedThreadId,
2611
+ projectId: ProjectId.make("project:queued-provider-switch"),
2612
+ title: "Queued provider switch",
2613
+ modelSelection: CODEX_MODEL_SELECTION,
2614
+ runtimeMode: "full-access",
2615
+ interactionMode: "default",
2616
+ branch: null,
2617
+ worktreePath: cwd,
2618
+ });
2619
+ yield* dispatch(1, CODEX_MODEL_SELECTION);
2620
+ yield* Deferred.await(started);
2621
+ yield* dispatch(2, CODEX_MODEL_SELECTION);
2622
+ yield* dispatch(3, CODEX_MODEL_SELECTION);
2623
+ yield* dispatch(4, CLAUDE_MODEL_SELECTION);
2624
+ const queued = yield* orchestrator.getThreadProjection(queuedThreadId);
2625
+ assert.deepEqual(
2626
+ queued.runs.map((run) => run.status),
2627
+ ["running", "queued", "queued", "queued"],
2628
+ );
2629
+ assert.equal(queued.thread.activeProviderThreadId, queued.runs[0]?.providerThreadId);
2630
+ assert.equal(queued.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2631
+ assert.lengthOf(queued.contextHandoffs, 0);
2632
+ const activeSession = queued.providerSessions.find(
2633
+ (session) => session.providerInstanceId === CODEX_MODEL_SELECTION.instanceId,
2634
+ );
2635
+ assert.isDefined(activeSession);
2636
+ const now = yield* DateTime.now;
2637
+ yield* eventSink.write({
2638
+ events: [
2639
+ ...(["stopped", "error"] as const).map((status) => ({
2640
+ id: EventId.make(`event:queued-provider-switch:dead-session:${status}`),
2641
+ type: "provider-session.updated" as const,
2642
+ threadId: queuedThreadId,
2643
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2644
+ occurredAt: now,
2645
+ payload: {
2646
+ ...activeSession!,
2647
+ id: ProviderSessionId.make(`provider-session:queued-provider-switch:${status}`),
2648
+ status,
2649
+ },
2650
+ })),
2651
+ {
2652
+ id: EventId.make("event:queued-provider-switch:first-response"),
2653
+ type: "turn-item.updated",
2654
+ threadId: queuedThreadId,
2655
+ runId: queued.runs[0]!.id,
2656
+ nodeId: queued.runs[0]!.rootNodeId!,
2657
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2658
+ occurredAt: now,
2659
+ payload: {
2660
+ id: TurnItemId.make("turn-item:queued-provider-switch:first-response"),
2661
threadId: queuedThreadId,
2662
runId: queued.runs[0]!.id,
2527
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2528
- occurredAt: now,
2529
- payload: { ...queued.runs[0]!, status: "completed", completedAt: now },
2663
+ nodeId: queued.runs[0]!.rootNodeId!,
2664
+ providerThreadId: queued.runs[0]!.providerThreadId,
2665
+ providerTurnId: null,
2666
+ nativeItemRef: null,
2667
+ parentItemId: null,
2668
+ ordinal: 101,
2669
+ status: "completed",
2670
+ title: null,
2671
+ startedAt: now,
2672
+ completedAt: now,
2673
+ updatedAt: now,
2674
+ type: "assistant_message",
2675
+ messageId: MessageId.make("message:queued-provider-switch:first-response"),
2676
+ text: "Codex current turn complete",
2677
+ streaming: false,
2678
},
2531
- ],
2532
- });
2533
- yield* orchestrator.resumeQueuedRuns;
2534
- yield* orchestrator.streamStoredEvents.pipe(
2535
- Stream.filter(
2536
- (event) =>
2537
- event.event.type === "run.updated" &&
2538
- event.event.runId === queued.runs[1]?.id &&
2539
- event.event.payload.status === "completed",
2540
- ),
2541
- Stream.runHead,
2542
- );
2543
- yield* worker.drain();
2544
- const delivered = yield* orchestrator.getThreadProjection(queuedThreadId);
2545
- const targetNativeRef = delivered.providerThreads.find(
2546
- (providerThread) => providerThread.id === delivered.runs[1]?.providerThreadId,
2547
- )?.nativeThreadRef;
2548
- assert.deepEqual(targetNativeRef, sourceNativeRef);
2549
- return delivered;
2550
- }).pipe(
2551
- Effect.provide(
2679
+ },
2680
+ {
2681
+ id: EventId.make("event:queued-provider-switch:first-complete"),
2682
+ type: "run.updated",
2683
+ threadId: queuedThreadId,
2684
+ runId: queued.runs[0]!.id,
2685
+ providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2686
+ occurredAt: now,
2687
+ payload: { ...queued.runs[0]!, status: "completed", completedAt: now },
2688
+ },
2689
+ ],
2690
+ });
2691
+ yield* orchestrator.resumeQueuedRuns;
2692
+ yield* orchestrator.streamStoredEvents.pipe(
2693
+ Stream.filter(
2694
+ (event) =>
2695
+ event.event.type === "run.updated" &&
2696
+ event.event.runId === queued.runs[3]?.id &&
2697
+ event.event.payload.status === "completed",
2698
+ ),
2699
+ Stream.runHead,
2700
+ );
2701
+ yield* worker.drain();
2702
+ const detachEvents = yield* eventSink.stream({ threadId: queuedThreadId }).pipe(
2703
+ Stream.filter((stored) => stored.event.type === "provider-session.detached"),
2704
+ Stream.take(1),
2705
+ Stream.runCollect,
2706
+ );
2707
+ assert.equal(
2708
+ detachEvents[0]?.event.type === "provider-session.detached"
2709
+ ? detachEvents[0].event.payload.providerSessionId
2710
+ : null,
2711
+ activeSession?.id,
2712
+ );
2713
+ const startCommandId = CommandId.make(`command:system:start-queued:${queued.runs[3]!.id}`);
2714
+ const detachEffects = (yield* effectOutbox.listByCommandId(startCommandId)).filter(
2715
+ (effect) => effect.request.type === "provider-session.detach",
2716
+ );
2717
+ assert.deepEqual(
2718
+ detachEffects.map((effect) =>
2719
+ effect.request.type === "provider-session.detach"
2720
+ ? effect.request.providerSessionId
2721
+ : null,
2722
+ ),
2723
+ [activeSession?.id],
2724
+ );
2725
+ return yield* orchestrator.getThreadProjection(queuedThreadId);
2726
+ }).pipe(
2727
+ Effect.provide(
2728
+ Layer.merge(
2729
ProviderReplayHarness.layerWithRegistry(
2730
{
2554
- name: "queued-account-switch",
2731
+ name: "queued-provider-switch",
2732
runtimePolicyOverride: {
2733
cwd,
2734
approvalPolicy: "never",
@@ -2563,264 +2740,52 @@ describe("orchestration v2 provider switching", () => {
2740
},
2741
},
2742
layerRegistry,
2743
+ { databaseLayer: layerDatabase },
2744
),
2745
+ layerOutboxProvided,
2746
),
2568
- );
2569
- assert.deepEqual(
2570
- projection.runs.map((run) => [run.providerInstanceId, run.status]),
2571
- [
2572
- [CODEX_MODEL_SELECTION.instanceId, "completed"],
2573
- [alternateSelection.instanceId, "completed"],
2574
- ],
2575
- );
2576
- assert.lengthOf(projection.contextHandoffs, 0);
2577
- assert.deepEqual(
2578
- (yield* Ref.get(capturedTurns)).map((turn) => turn.text),
2579
- ["First account turn", "Alternate account turn"],
2580
- );
2581
- }),
2582
- ),
2583
- );
2584
-
2585
- it.live("finishes earlier queued Codex turns before handing context to queued Claude", () =>
2586
- Effect.scoped(
2587
- Effect.gen(function* () {
2588
- const cwd = yield* checkpointWorkspace("queued-provider-switch");
2589
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2590
- const started = yield* Deferred.make<void>();
2591
- const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
2592
- makeTestAdapter({
2593
- instanceId: ProviderInstanceId.make("codex"),
2594
- driver: CODEX_DRIVER,
2595
- capabilities: CodexProviderCapabilitiesV2,
2596
- modelSelection: CODEX_MODEL_SELECTION,
2597
- responseByRunOrdinal: {
2598
- 1: "Codex current turn complete",
2599
- 2: "Codex first queued turn complete",
2600
- 3: "Codex second queued turn complete",
2601
- },
2602
- capturedTurns,
2603
- holdFirstTurn: started,
2604
- }),
2605
- makeTestAdapter({
2606
- instanceId: ProviderInstanceId.make("claudeAgent"),
2607
- driver: CLAUDE_DRIVER,
2608
- capabilities: ClaudeProviderCapabilitiesV2,
2609
- modelSelection: CLAUDE_MODEL_SELECTION,
2610
- responseByRunOrdinal: { 4: "Claude turn complete" },
2611
- capturedTurns,
2612
- }),
2613
- ]);
2614
- const queuedThreadId = ThreadId.make("thread:queued-provider-switch");
2615
- const layerDatabase = SqlitePersistence.layerMemory;
2616
- const layerOutboxProvided = EffectOutbox.layer.pipe(Layer.provide(layerDatabase));
2617
- const projection = yield* Effect.gen(function* () {
2618
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2619
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2620
- const eventSink = yield* EventSink.EventSinkV2;
2621
- const effectOutbox = yield* EffectOutbox.EffectOutboxV2;
2622
- const dispatch = (ordinal: number, modelSelection: ModelSelection) =>
2623
- orchestrator.dispatch({
2624
- type: "message.dispatch",
2625
- createdBy: "user",
2626
- creationSource: "web",
2627
- commandId: CommandId.make(`command:queued-provider-switch:${ordinal}`),
2628
- threadId: queuedThreadId,
2629
- messageId: MessageId.make(`message:queued-provider-switch:${ordinal}`),
2630
- text: `Prompt ${ordinal}`,
2631
- attachments: [],
2632
- modelSelection,
2633
- dispatchMode: {
2634
- type: ordinal === 1 ? "start_immediately" : "queue_after_active",
2635
- },
2636
- });
2637
- yield* orchestrator.dispatch({
2638
- type: "thread.create",
2639
- createdBy: "user",
2640
- creationSource: "web",
2641
- commandId: CommandId.make("command:queued-provider-switch:create"),
2642
- threadId: queuedThreadId,
2643
- projectId: ProjectId.make("project:queued-provider-switch"),
2644
- title: "Queued provider switch",
2645
- modelSelection: CODEX_MODEL_SELECTION,
2646
- runtimeMode: "full-access",
2647
- interactionMode: "default",
2648
- branch: null,
2649
- worktreePath: cwd,
2650
- });
2651
- yield* dispatch(1, CODEX_MODEL_SELECTION);
2652
- yield* Deferred.await(started);
2653
- yield* dispatch(2, CODEX_MODEL_SELECTION);
2654
- yield* dispatch(3, CODEX_MODEL_SELECTION);
2655
- yield* dispatch(4, CLAUDE_MODEL_SELECTION);
2656
- const queued = yield* orchestrator.getThreadProjection(queuedThreadId);
2657
- assert.deepEqual(
2658
- queued.runs.map((run) => run.status),
2659
- ["running", "queued", "queued", "queued"],
2660
- );
2661
- assert.equal(queued.thread.activeProviderThreadId, queued.runs[0]?.providerThreadId);
2662
- assert.equal(queued.thread.providerInstanceId, CODEX_MODEL_SELECTION.instanceId);
2663
- assert.lengthOf(queued.contextHandoffs, 0);
2664
- const activeSession = queued.providerSessions.find(
2665
- (session) => session.providerInstanceId === CODEX_MODEL_SELECTION.instanceId,
2666
- );
2667
- assert.isDefined(activeSession);
2668
- const now = yield* DateTime.now;
2669
- yield* eventSink.write({
2670
- events: [
2671
- ...(["stopped", "error"] as const).map((status) => ({
2672
- id: EventId.make(`event:queued-provider-switch:dead-session:${status}`),
2673
- type: "provider-session.updated" as const,
2674
- threadId: queuedThreadId,
2675
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2676
- occurredAt: now,
2677
- payload: {
2678
- ...activeSession!,
2679
- id: ProviderSessionId.make(`provider-session:queued-provider-switch:${status}`),
2680
- status,
2681
- },
2682
- })),
2683
- {
2684
- id: EventId.make("event:queued-provider-switch:first-response"),
2685
- type: "turn-item.updated",
2686
- threadId: queuedThreadId,
2687
- runId: queued.runs[0]!.id,
2688
- nodeId: queued.runs[0]!.rootNodeId!,
2689
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2690
- occurredAt: now,
2691
- payload: {
2692
- id: TurnItemId.make("turn-item:queued-provider-switch:first-response"),
2693
- threadId: queuedThreadId,
2694
- runId: queued.runs[0]!.id,
2695
- nodeId: queued.runs[0]!.rootNodeId!,
2696
- providerThreadId: queued.runs[0]!.providerThreadId,
2697
- providerTurnId: null,
2698
- nativeItemRef: null,
2699
- parentItemId: null,
2700
- ordinal: 101,
2701
- status: "completed",
2702
- title: null,
2703
- startedAt: now,
2704
- completedAt: now,
2705
- updatedAt: now,
2706
- type: "assistant_message",
2707
- messageId: MessageId.make("message:queued-provider-switch:first-response"),
2708
- text: "Codex current turn complete",
2709
- streaming: false,
2710
- },
2711
- },
2712
- {
2713
- id: EventId.make("event:queued-provider-switch:first-complete"),
2714
- type: "run.updated",
2715
- threadId: queuedThreadId,
2716
- runId: queued.runs[0]!.id,
2717
- providerInstanceId: CODEX_MODEL_SELECTION.instanceId,
2718
- occurredAt: now,
2719
- payload: { ...queued.runs[0]!, status: "completed", completedAt: now },
2720
- },
2721
- ],
2722
- });
2723
- yield* orchestrator.resumeQueuedRuns;
2724
- yield* orchestrator.streamStoredEvents.pipe(
2725
- Stream.filter(
2726
- (event) =>
2727
- event.event.type === "run.updated" &&
2728
- event.event.runId === queued.runs[3]?.id &&
2729
- event.event.payload.status === "completed",
2730
- ),
2731
- Stream.runHead,
2732
- );
2733
- yield* worker.drain();
2734
- const detachEvents = yield* eventSink.stream({ threadId: queuedThreadId }).pipe(
2735
- Stream.filter((stored) => stored.event.type === "provider-session.detached"),
2736
- Stream.take(1),
2737
- Stream.runCollect,
2738
- );
2739
- assert.equal(
2740
- detachEvents[0]?.event.type === "provider-session.detached"
2741
- ? detachEvents[0].event.payload.providerSessionId
2742
- : null,
2743
- activeSession?.id,
2744
- );
2745
- const startCommandId = CommandId.make(
2746
- `command:system:start-queued:${queued.runs[3]!.id}`,
2747
- );
2748
- const detachEffects = (yield* effectOutbox.listByCommandId(startCommandId)).filter(
2749
- (effect) => effect.request.type === "provider-session.detach",
2750
- );
2751
- assert.deepEqual(
2752
- detachEffects.map((effect) =>
2753
- effect.request.type === "provider-session.detach"
2754
- ? effect.request.providerSessionId
2755
- : null,
2756
- ),
2757
- [activeSession?.id],
2758
- );
2759
- return yield* orchestrator.getThreadProjection(queuedThreadId);
2760
- }).pipe(
2761
- Effect.provide(
2762
- Layer.merge(
2763
- ProviderReplayHarness.layerWithRegistry(
2764
- {
2765
- name: "queued-provider-switch",
2766
- runtimePolicyOverride: {
2767
- cwd,
2768
- approvalPolicy: "never",
2769
- sandboxPolicy: {
2770
- type: "readOnly",
2771
- access: { type: "fullAccess" },
2772
- networkAccess: false,
2773
- },
2774
- },
2775
- },
2776
- layerRegistry,
2777
- { databaseLayer: layerDatabase },
2778
- ),
2779
- layerOutboxProvided,
2780
- ),
2781
- ),
2782
- );
2783
- const turns = yield* Ref.get(capturedTurns);
2784
- assert.deepEqual(
2785
- projection.runs.map((run) => [run.providerInstanceId, run.status]),
2786
- [
2787
- ["codex", "completed"],
2788
- ["codex", "completed"],
2789
- ["codex", "completed"],
2790
- ["claudeAgent", "completed"],
2791
- ],
2792
- );
2793
- assert.deepEqual(
2794
- turns.map((turn) => [turn.driver, turn.text.includes("Prompt 4")]),
2795
- [
2796
- ["codex", false],
2797
- ["codex", false],
2798
- ["codex", false],
2799
- ["claudeAgent", true],
2800
- ],
2801
- );
2802
- assert.lengthOf(projection.contextHandoffs, 1);
2803
- assert.equal(projection.contextHandoffs[0]?.targetRunId, projection.runs[3]?.id);
2804
- const handoffItem = projection.turnItems.find(
2805
- (item) => item.type === "handoff" && item.runId === projection.runs[3]?.id,
2806
- );
2807
- assert.equal(
2808
- handoffItem?.type === "handoff" ? handoffItem.contextHandoffId : null,
2809
- projection.contextHandoffs[0]?.id,
2810
- );
2811
- const queuedUserItem = projection.turnItems.find(
2812
- (item) => item.type === "user_message" && item.runId === projection.runs[3]?.id,
2813
- );
2814
- assert.isBelow(handoffItem?.ordinal ?? Infinity, queuedUserItem?.ordinal ?? -Infinity);
2815
- assert.include(
2816
- handoffItem?.type === "handoff" ? handoffItem.summary : "",
2817
- "Codex second queued turn complete",
2818
- );
2819
- assert.include(turns[3]?.text ?? "", "Codex current turn complete");
2820
- assert.include(turns[3]?.text ?? "", "Codex first queued turn complete");
2821
- assert.include(turns[3]?.text ?? "", "Codex second queued turn complete");
2822
- }),
2823
- ),
2747
+ ),
2748
+ );
2749
+ const turns = yield* Ref.get(capturedTurns);
2750
+ assert.deepEqual(
2751
+ projection.runs.map((run) => [run.providerInstanceId, run.status]),
2752
+ [
2753
+ ["codex", "completed"],
2754
+ ["codex", "completed"],
2755
+ ["codex", "completed"],
2756
+ ["claudeAgent", "completed"],
2757
+ ],
2758
+ );
2759
+ assert.deepEqual(
2760
+ turns.map((turn) => [turn.driver, turn.text.includes("Prompt 4")]),
2761
+ [
2762
+ ["codex", false],
2763
+ ["codex", false],
2764
+ ["codex", false],
2765
+ ["claudeAgent", true],
2766
+ ],
2767
+ );
2768
+ assert.lengthOf(projection.contextHandoffs, 1);
2769
+ assert.equal(projection.contextHandoffs[0]?.targetRunId, projection.runs[3]?.id);
2770
+ const handoffItem = projection.turnItems.find(
2771
+ (item) => item.type === "handoff" && item.runId === projection.runs[3]?.id,
2772
+ );
2773
+ assert.equal(
2774
+ handoffItem?.type === "handoff" ? handoffItem.contextHandoffId : null,
2775
+ projection.contextHandoffs[0]?.id,
2776
+ );
2777
+ const queuedUserItem = projection.turnItems.find(
2778
+ (item) => item.type === "user_message" && item.runId === projection.runs[3]?.id,
2779
+ );
2780
+ assert.isBelow(handoffItem?.ordinal ?? Infinity, queuedUserItem?.ordinal ?? -Infinity);
2781
+ assert.include(
2782
+ handoffItem?.type === "handoff" ? handoffItem.summary : "",
2783
+ "Codex second queued turn complete",
2784
+ );
2785
+ assert.include(turns[3]?.text ?? "", "Codex current turn complete");
2786
+ assert.include(turns[3]?.text ?? "", "Codex first queued turn complete");
2787
+ assert.include(turns[3]?.text ?? "", "Codex second queued turn complete");
2788
+ }),
2789
);
2790
2791
// regression: #20343 sending to an instance with separate history must release the old session
@@ -2842,315 +2807,507 @@ describe("orchestration v2 provider switching", () => {
2807
{ background: true, queued: true, sharedHistory: true },
2808
],
2809
] as const)("%s", ([, { background, queued, sharedHistory }]) =>
2845
- Effect.scoped(
2846
- Effect.gen(function* () {
2847
- const cwd = yield* checkpointWorkspace("handoff-releases-session");
2848
- const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2849
- const backgroundWork = yield* Ref.make(background);
2850
- const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
2851
- const firstStarted = yield* Deferred.make<void>();
2852
- const releaseFirst = yield* Deferred.make<void>();
2853
- const secondSelection: ModelSelection = {
2854
- ...CLAUDE_MODEL_SELECTION,
2855
- instanceId: ProviderInstanceId.make("claude-second-account"),
2856
- };
2857
- const adapters = [
2858
- makeTestAdapter({
2859
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2860
- driver: CLAUDE_DRIVER,
2861
- capabilities: ClaudeProviderCapabilitiesV2,
2862
- modelSelection: CLAUDE_MODEL_SELECTION,
2863
- responseByRunOrdinal: { 1: "First account complete" },
2864
- capturedTurns,
2865
- backgroundWork,
2866
- closedSessions,
2867
- ...(queued ? { holdFirstTurn: firstStarted, releaseFirstTurn: releaseFirst } : {}),
2868
- }),
2869
- makeTestAdapter({
2870
- instanceId: secondSelection.instanceId,
2871
- driver: CLAUDE_DRIVER,
2872
- capabilities: ClaudeProviderCapabilitiesV2,
2873
- modelSelection: secondSelection,
2874
- responseByRunOrdinal: { 2: "Second account complete" },
2875
- capturedTurns,
2876
- }),
2877
- ];
2878
- // Without a shared continuation key, each Claude instance owns its own native history.
2879
- const layerRegistry = sharedHistory
2880
- ? Layer.succeed(
2881
- ProviderAdapterRegistry.ProviderAdapterRegistryV2,
2882
- ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
2883
- get: (instanceId) => {
2884
- const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2885
- return adapter === undefined
2886
- ? Effect.fail(
2887
- new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({
2888
- instanceId,
2889
- }),
2890
- )
2891
- : Effect.succeed(adapter);
2892
- },
2893
- list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
2894
- getMetadata: () =>
2895
- Effect.succeed({
2896
- driver: CLAUDE_DRIVER,
2897
- continuationKey: "claude:shared-native-account-history",
2898
- enabled: true,
2899
- capabilities: ClaudeProviderCapabilitiesV2,
2900
- }),
2901
- }),
2902
- )
2903
- : ProviderAdapterRegistry.layerFromAdapters(adapters);
2904
- const handoffThreadId = ThreadId.make("thread:handoff-releases-session");
2905
- yield* Effect.gen(function* () {
2906
- const orchestrator = yield* Orchestrator.OrchestratorV2;
2907
- const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2908
- const send = (ordinal: number, modelSelection: ModelSelection, attempt = "") =>
2909
- orchestrator.dispatch({
2910
- type: "message.dispatch",
2911
- createdBy: "user",
2912
- creationSource: "web",
2913
- commandId: CommandId.make(`command:handoff-releases-session:${ordinal}${attempt}`),
2914
- threadId: handoffThreadId,
2915
- messageId: MessageId.make(`message:handoff-releases-session:${ordinal}${attempt}`),
2916
- text: `Prompt ${ordinal}`,
2917
- attachments: [],
2918
- modelSelection,
2919
- dispatchMode: { type: queued ? "queue_after_active" : "start_immediately" },
2920
- });
2921
- yield* orchestrator.dispatch({
2922
- type: "thread.create",
2810
+ Effect.gen(function* () {
2811
+ const cwd = yield* checkpointWorkspace("handoff-releases-session");
2812
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
2813
+ const backgroundWork = yield* Ref.make(background);
2814
+ const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
2815
+ const firstStarted = yield* Deferred.make<void>();
2816
+ const releaseFirst = yield* Deferred.make<void>();
2817
+ const secondSelection: ModelSelection = {
2818
+ ...CLAUDE_MODEL_SELECTION,
2819
+ instanceId: ProviderInstanceId.make("claude-second-account"),
2820
+ };
2821
+ const adapters = [
2822
+ makeTestAdapter({
2823
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
2824
+ driver: CLAUDE_DRIVER,
2825
+ capabilities: ClaudeProviderCapabilitiesV2,
2826
+ modelSelection: CLAUDE_MODEL_SELECTION,
2827
+ responseByRunOrdinal: { 1: "First account complete" },
2828
+ capturedTurns,
2829
+ backgroundWork,
2830
+ closedSessions,
2831
+ ...(queued ? { holdFirstTurn: firstStarted, releaseFirstTurn: releaseFirst } : {}),
2832
+ }),
2833
+ makeTestAdapter({
2834
+ instanceId: secondSelection.instanceId,
2835
+ driver: CLAUDE_DRIVER,
2836
+ capabilities: ClaudeProviderCapabilitiesV2,
2837
+ modelSelection: secondSelection,
2838
+ responseByRunOrdinal: { 2: "Second account complete" },
2839
+ capturedTurns,
2840
+ }),
2841
+ ];
2842
+ // Without a shared continuation key, each Claude instance owns its own native history.
2843
+ const layerRegistry = sharedHistory
2844
+ ? Layer.succeed(
2845
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2,
2846
+ ProviderAdapterRegistry.ProviderAdapterRegistryV2.of({
2847
+ get: (instanceId) => {
2848
+ const adapter = adapters.find((candidate) => candidate.instanceId === instanceId);
2849
+ return adapter === undefined
2850
+ ? Effect.fail(
2851
+ new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({
2852
+ instanceId,
2853
+ }),
2854
+ )
2855
+ : Effect.succeed(adapter);
2856
+ },
2857
+ list: () => Effect.succeed(adapters.map((adapter) => adapter.instanceId)),
2858
+ getMetadata: () =>
2859
+ Effect.succeed({
2860
+ driver: CLAUDE_DRIVER,
2861
+ continuationKey: "claude:shared-native-account-history",
2862
+ enabled: true,
2863
+ capabilities: ClaudeProviderCapabilitiesV2,
2864
+ }),
2865
+ }),
2866
+ )
2867
+ : ProviderAdapterRegistry.layerFromAdapters(adapters);
2868
+ const handoffThreadId = ThreadId.make("thread:handoff-releases-session");
2869
+ yield* Effect.gen(function* () {
2870
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
2871
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
2872
+ const send = (ordinal: number, modelSelection: ModelSelection, attempt = "") =>
2873
+ orchestrator.dispatch({
2874
+ type: "message.dispatch",
2875
createdBy: "user",
2876
creationSource: "web",
2925
- commandId: CommandId.make("command:handoff-releases-session:create"),
2877
+ commandId: CommandId.make(`command:handoff-releases-session:${ordinal}${attempt}`),
2878
threadId: handoffThreadId,
2927
- projectId: ProjectId.make("project:handoff-releases-session"),
2928
- title: "Handoff releases session",
2929
- modelSelection: CLAUDE_MODEL_SELECTION,
2930
- runtimeMode: "full-access",
2931
- interactionMode: "default",
2932
- branch: null,
2933
- worktreePath: cwd,
2879
+ messageId: MessageId.make(`message:handoff-releases-session:${ordinal}${attempt}`),
2880
+ text: `Prompt ${ordinal}`,
2881
+ attachments: [],
2882
+ modelSelection,
2883
+ dispatchMode: { type: queued ? "queue_after_active" : "start_immediately" },
2884
});
2935
- yield* send(1, CLAUDE_MODEL_SELECTION);
2885
+ yield* orchestrator.dispatch({
2886
+ type: "thread.create",
2887
+ createdBy: "user",
2888
+ creationSource: "web",
2889
+ commandId: CommandId.make("command:handoff-releases-session:create"),
2890
+ threadId: handoffThreadId,
2891
+ projectId: ProjectId.make("project:handoff-releases-session"),
2892
+ title: "Handoff releases session",
2893
+ modelSelection: CLAUDE_MODEL_SELECTION,
2894
+ runtimeMode: "full-access",
2895
+ interactionMode: "default",
2896
+ branch: null,
2897
+ worktreePath: cwd,
2898
+ });
2899
+ yield* send(1, CLAUDE_MODEL_SELECTION);
2900
2937
- if (queued) {
2938
- yield* Deferred.await(firstStarted);
2939
- yield* send(2, secondSelection);
2940
- const queuedRunId = (yield* orchestrator.getThreadProjection(handoffThreadId)).runs[1]
2941
- ?.id;
2942
- assert.isDefined(queuedRunId);
2943
- yield* Deferred.succeed(releaseFirst, undefined);
2944
- yield* orchestrator.streamStoredEvents.pipe(
2945
- Stream.filter(
2946
- ({ event }) =>
2947
- event.type === "run.updated" &&
2948
- event.runId === queuedRunId &&
2949
- (event.payload.queueHeld === true || event.payload.status === "completed"),
2950
- ),
2951
- Stream.runHead,
2952
- );
2953
- yield* worker.drain();
2954
- const afterQueue = yield* orchestrator.getThreadProjection(handoffThreadId);
2955
- const firstSession = afterQueue.providerSessions.find(
2956
- (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
2957
- );
2958
- // Detaching would end the background agents, so the busy session must stay up.
2959
- assert.deepEqual(yield* Ref.get(closedSessions), []);
2960
- assert.equal(firstSession?.status, "ready");
2961
- if (!sharedHistory) {
2962
- assert.deepEqual(
2963
- afterQueue.runs.map((run) => [run.providerInstanceId, run.status]),
2964
- [
2965
- [CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2966
- [secondSelection.instanceId, "completed"],
2967
- ],
2968
- );
2969
- return;
2970
- }
2971
- // Resuming the native thread beside the busy session would fork its history.
2972
- assert.deepEqual(
2973
- afterQueue.runs.map((run) => [run.status, run.queueHeld === true]),
2974
- [
2975
- ["completed", false],
2976
- ["queued", true],
2977
- ],
2978
- );
2979
- assert.lengthOf(yield* Ref.get(capturedTurns), 1);
2980
- yield* Ref.set(backgroundWork, false);
2981
- yield* orchestrator.dispatch({
2982
- type: "queue.resume",
2983
- commandId: CommandId.make("command:handoff-releases-session:resume"),
2984
- threadId: handoffThreadId,
2985
- });
2986
- yield* worker.drain();
2987
- const resumed = yield* waitForIdle(handoffThreadId);
2901
+ if (queued) {
2902
+ yield* Deferred.await(firstStarted);
2903
+ yield* send(2, secondSelection);
2904
+ const queuedRunId = (yield* orchestrator.getThreadProjection(handoffThreadId)).runs[1]
2905
+ ?.id;
2906
+ assert.isDefined(queuedRunId);
2907
+ yield* Deferred.succeed(releaseFirst, undefined);
2908
+ yield* orchestrator.streamStoredEvents.pipe(
2909
+ Stream.filter(
2910
+ ({ event }) =>
2911
+ event.type === "run.updated" &&
2912
+ event.runId === queuedRunId &&
2913
+ (event.payload.queueHeld === true || event.payload.status === "completed"),
2914
+ ),
2915
+ Stream.runHead,
2916
+ );
2917
+ yield* worker.drain();
2918
+ const afterQueue = yield* orchestrator.getThreadProjection(handoffThreadId);
2919
+ const firstSession = afterQueue.providerSessions.find(
2920
+ (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
2921
+ );
2922
+ // Detaching would end the background agents, so the busy session must stay up.
2923
+ assert.deepEqual(yield* Ref.get(closedSessions), []);
2924
+ assert.equal(firstSession?.status, "ready");
2925
+ if (!sharedHistory) {
2926
assert.deepEqual(
2989
- resumed.runs.map((run) => [run.providerInstanceId, run.status]),
2927
+ afterQueue.runs.map((run) => [run.providerInstanceId, run.status]),
2928
[
2929
[CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2930
[secondSelection.instanceId, "completed"],
2931
],
2932
);
2995
- assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]);
2933
return;
2934
}
2998
-
2999
- yield* worker.drain();
3000
- const afterFirst = yield* waitForIdle(handoffThreadId);
3001
- const firstSession = afterFirst.providerSessions.find(
3002
- (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
2935
+ // Resuming the native thread beside the busy session would fork its history.
2936
+ assert.deepEqual(
2937
+ afterQueue.runs.map((run) => [run.status, run.queueHeld === true]),
2938
+ [
2939
+ ["completed", false],
2940
+ ["queued", true],
2941
+ ],
2942
);
3004
- assert.equal(firstSession?.status, "ready");
3005
-
3006
- if (background) {
3007
- // Native subagents live only in the adapter's roster, so the projection's
3008
- // pendingBackgroundTasks stays empty while the probe still reports work.
3009
- assert.deepEqual(afterFirst.providerThreads[0]?.pendingBackgroundTasks ?? [], []);
3010
- const refused = yield* send(2, secondSelection, ":refused").pipe(Effect.flip);
3011
- assert.include(String(refused.cause), "still running background agents or commands");
3012
- const unchanged = yield* orchestrator.getThreadProjection(handoffThreadId);
3013
- assert.lengthOf(unchanged.runs, 1);
3014
- assert.deepEqual(yield* Ref.get(closedSessions), []);
3015
- assert.equal(unchanged.thread.providerInstanceId, CLAUDE_MODEL_SELECTION.instanceId);
3016
- assert.deepEqual(
3017
- unchanged.providerSessions.map((session) => [session.id, session.status]),
3018
- [[firstSession!.id, "ready"]],
3019
- );
3020
- yield* Ref.set(backgroundWork, false);
3021
- }
3022
-
3023
- yield* send(2, secondSelection);
3024
- yield* worker.drain();
3025
- const afterSecond = yield* waitForIdle(handoffThreadId);
2943
+ assert.lengthOf(yield* Ref.get(capturedTurns), 1);
2944
+ yield* Ref.set(backgroundWork, false);
2945
+ yield* orchestrator.dispatch({
2946
+ type: "queue.resume",
2947
+ commandId: CommandId.make("command:handoff-releases-session:resume"),
2948
+ threadId: handoffThreadId,
2949
+ });
2950
yield* worker.drain();
3027
- const projection = yield* orchestrator.getThreadProjection(handoffThreadId);
3028
-
2951
+ const resumed = yield* waitForIdle(handoffThreadId);
2952
assert.deepEqual(
3030
- projection.runs.map((run) => [run.providerInstanceId, run.status]),
2953
+ resumed.runs.map((run) => [run.providerInstanceId, run.status]),
2954
[
2955
[CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2956
[secondSelection.instanceId, "completed"],
2957
],
2958
);
3036
- assert.lengthOf(afterSecond.contextHandoffs, 1);
2959
+ assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]);
2960
+ return;
2961
+ }
2962
+
2963
+ yield* worker.drain();
2964
+ const afterFirst = yield* waitForIdle(handoffThreadId);
2965
+ const firstSession = afterFirst.providerSessions.find(
2966
+ (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
2967
+ );
2968
+ assert.equal(firstSession?.status, "ready");
2969
+
2970
+ if (background) {
2971
+ // Native subagents live only in the adapter's roster, so the projection's
2972
+ // pendingBackgroundTasks stays empty while the probe still reports work.
2973
+ assert.deepEqual(afterFirst.providerThreads[0]?.pendingBackgroundTasks ?? [], []);
2974
+ const refused = yield* send(2, secondSelection, ":refused").pipe(Effect.flip);
2975
+ assert.include(String(refused.cause), "still running background agents or commands");
2976
+ const unchanged = yield* orchestrator.getThreadProjection(handoffThreadId);
2977
+ assert.lengthOf(unchanged.runs, 1);
2978
+ assert.deepEqual(yield* Ref.get(closedSessions), []);
2979
+ assert.equal(unchanged.thread.providerInstanceId, CLAUDE_MODEL_SELECTION.instanceId);
2980
assert.deepEqual(
3038
- projection.providerSessions.map((session) => session.providerInstanceId),
3039
- [secondSelection.instanceId],
2981
+ unchanged.providerSessions.map((session) => [session.id, session.status]),
2982
+ [[firstSession!.id, "ready"]],
2983
);
3041
- // The detached event alone hides the session; the runtime must also close.
3042
- assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]);
3043
- }).pipe(
3044
- Effect.provide(
3045
- ProviderReplayHarness.layerWithRegistry(
3046
- {
3047
- name: "handoff-releases-session",
3048
- runtimePolicyOverride: {
3049
- cwd,
3050
- approvalPolicy: "never",
3051
- sandboxPolicy: {
3052
- type: "readOnly",
3053
- access: { type: "fullAccess" },
3054
- networkAccess: false,
2984
+ yield* Ref.set(backgroundWork, false);
2985
+ }
2986
+
2987
+ yield* send(2, secondSelection);
2988
+ yield* worker.drain();
2989
+ const afterSecond = yield* waitForIdle(handoffThreadId);
2990
+ yield* worker.drain();
2991
+ const projection = yield* orchestrator.getThreadProjection(handoffThreadId);
2992
+
2993
+ assert.deepEqual(
2994
+ projection.runs.map((run) => [run.providerInstanceId, run.status]),
2995
+ [
2996
+ [CLAUDE_MODEL_SELECTION.instanceId, "completed"],
2997
+ [secondSelection.instanceId, "completed"],
2998
+ ],
2999
+ );
3000
+ assert.lengthOf(afterSecond.contextHandoffs, 1);
3001
+ assert.deepEqual(
3002
+ projection.providerSessions.map((session) => session.providerInstanceId),
3003
+ [secondSelection.instanceId],
3004
+ );
3005
+ // The detached event alone hides the session; the runtime must also close.
3006
+ assert.deepEqual(yield* Ref.get(closedSessions), [firstSession!.id]);
3007
+ }).pipe(
3008
+ Effect.provide(
3009
+ ProviderReplayHarness.layerWithRegistry(
3010
+ {
3011
+ name: "handoff-releases-session",
3012
+ runtimePolicyOverride: {
3013
+ cwd,
3014
+ approvalPolicy: "never",
3015
+ sandboxPolicy: {
3016
+ type: "readOnly",
3017
+ access: { type: "fullAccess" },
3018
+ networkAccess: false,
3019
+ },
3020
+ },
3021
+ },
3022
+ layerRegistry,
3023
+ ),
3024
+ ),
3025
+ );
3026
+ }),
3027
+ );
3028
+
3029
+ // regression: #16000 thread setting changes must not end a Claude session's background work
3030
+ it.live.each([
3031
+ ["runtime mode", "runtime-mode"],
3032
+ ["worktree", "worktree"],
3033
+ ["provider instance", "instance"],
3034
+ ] as const)("keeps background work alive when the %s changes on an idle thread", ([, change]) =>
3035
+ Effect.gen(function* () {
3036
+ const cwd = yield* checkpointWorkspace(`settings-background-${change}`);
3037
+ const nextCwd = yield* checkpointWorkspace(`settings-background-${change}-next`);
3038
+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
3039
+ const backgroundWork = yield* Ref.make(false);
3040
+ const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
3041
+ const secondSelection: ModelSelection = {
3042
+ ...CLAUDE_MODEL_SELECTION,
3043
+ instanceId: ProviderInstanceId.make("claude-second-account"),
3044
+ };
3045
+ const threadId = ThreadId.make(`thread:settings-background-${change}`);
3046
+ yield* Effect.gen(function* () {
3047
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
3048
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3049
+ yield* orchestrator.dispatch({
3050
+ type: "thread.create",
3051
+ createdBy: "user",
3052
+ creationSource: "web",
3053
+ commandId: CommandId.make(`command:settings-background-${change}:create`),
3054
+ threadId,
3055
+ projectId: ProjectId.make(`project:settings-background-${change}`),
3056
+ title: "Settings change with background work",
3057
+ modelSelection: CLAUDE_MODEL_SELECTION,
3058
+ runtimeMode: "full-access",
3059
+ interactionMode: "default",
3060
+ branch: null,
3061
+ worktreePath: cwd,
3062
+ });
3063
+ yield* orchestrator.dispatch({
3064
+ type: "message.dispatch",
3065
+ createdBy: "user",
3066
+ creationSource: "web",
3067
+ commandId: CommandId.make(`command:settings-background-${change}:send`),
3068
+ threadId,
3069
+ messageId: MessageId.make(`message:settings-background-${change}:send`),
3070
+ text: "Start background work",
3071
+ attachments: [],
3072
+ modelSelection: CLAUDE_MODEL_SELECTION,
3073
+ dispatchMode: { type: "start_immediately" },
3074
+ });
3075
+ yield* worker.drain();
3076
+ const afterFirst = yield* waitForIdle(threadId);
3077
+ const session = afterFirst.providerSessions[0];
3078
+ assert.equal(session?.status, "ready");
3079
+ // The turn ended but a background subagent keeps running in the CLI process.
3080
+ yield* Ref.set(backgroundWork, true);
3081
+
3082
+ const commandId = CommandId.make(`command:settings-background-${change}:change`);
3083
+ yield* orchestrator
3084
+ .dispatch(
3085
+ change === "runtime-mode"
3086
+ ? {
3087
+ type: "thread.runtime-mode.set",
3088
+ commandId,
3089
+ threadId,
3090
+ runtimeMode: "auto-accept-edits",
3091
+ }
3092
+ : change === "worktree"
3093
+ ? { type: "thread.metadata.update", commandId, threadId, worktreePath: nextCwd }
3094
+ : {
3095
+ type: "thread.model-selection.set",
3096
+ commandId,
3097
+ threadId,
3098
+ modelSelection: secondSelection,
3099
},
3100
+ )
3101
+ .pipe(Effect.ignore);
3102
+ yield* worker.drain();
3103
+
3104
+ const projection = yield* orchestrator.getThreadProjection(threadId);
3105
+ // Refusing or deferring are both fine; closing the busy process is not.
3106
+ assert.deepEqual(yield* Ref.get(closedSessions), []);
3107
+ assert.deepEqual(
3108
+ projection.providerSessions.map((candidate) => [candidate.id, candidate.status]),
3109
+ [[session!.id, "ready"]],
3110
+ );
3111
+ }).pipe(
3112
+ Effect.provide(
3113
+ ProviderReplayHarness.layerWithRegistry(
3114
+ {
3115
+ name: `settings-background-${change}`,
3116
+ runtimePolicyOverride: {
3117
+ cwd,
3118
+ approvalPolicy: "never",
3119
+ sandboxPolicy: {
3120
+ type: "readOnly",
3121
+ access: { type: "fullAccess" },
3122
+ networkAccess: false,
3123
},
3124
},
3058
- layerRegistry,
3059
- ),
3125
+ },
3126
+ ProviderAdapterRegistry.layerFromAdapters([
3127
+ makeTestAdapter({
3128
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
3129
+ driver: CLAUDE_DRIVER,
3130
+ capabilities: ClaudeProviderCapabilitiesV2,
3131
+ modelSelection: CLAUDE_MODEL_SELECTION,
3132
+ responseByRunOrdinal: { 1: "Background work started" },
3133
+ capturedTurns,
3134
+ backgroundWork,
3135
+ closedSessions,
3136
+ }),
3137
+ makeTestAdapter({
3138
+ instanceId: secondSelection.instanceId,
3139
+ driver: CLAUDE_DRIVER,
3140
+ capabilities: ClaudeProviderCapabilitiesV2,
3141
+ modelSelection: secondSelection,
3142
+ responseByRunOrdinal: {},
3143
+ capturedTurns,
3144
+ }),
3145
+ ]),
3146
),
3061
- );
3062
- }),
3063
- ),
3147
+ ),
3148
+ );
3149
+ }),
3150
);
3151
3066
- // regression: #16000 thread setting changes must not end a Claude session's background work
3067
- it.live.each([
3068
- ["runtime mode", "runtime-mode"],
3069
- ["worktree", "worktree"],
3070
- ["provider instance", "instance"],
3071
- ] as const)("keeps background work alive when the %s changes on an idle thread", ([, change]) =>
3072
- Effect.scoped(
3152
+ it.live.each(["immediately", "behind a running turn"] as const)(
3153
+ "starts a fresh provider session %s and never hands earlier runs to a later provider",
3154
+ (variant) =>
3155
Effect.gen(function* () {
3074
- const cwd = yield* checkpointWorkspace(`settings-background-${change}`);
3075
- const nextCwd = yield* checkpointWorkspace(`settings-background-${change}-next`);
3156
+ const queued = variant !== "immediately";
3157
+ const key = queued ? "queued" : "immediate";
3158
+ const cwd = yield* checkpointWorkspace(`fresh-context-${key}`);
3159
const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);
3077
- const backgroundWork = yield* Ref.make(false);
3160
const closedSessions = yield* Ref.make<ReadonlyArray<string>>([]);
3079
- const secondSelection: ModelSelection = {
3080
- ...CLAUDE_MODEL_SELECTION,
3081
- instanceId: ProviderInstanceId.make("claude-second-account"),
3082
- };
3083
- const threadId = ThreadId.make(`thread:settings-background-${change}`);
3161
+ // A queued start has nobody to refuse, so a busy session must stay up.
3162
+ const backgroundWork = yield* Ref.make(queued);
3163
+ const started = yield* Deferred.make<void>();
3164
+ const release = yield* Deferred.make<void>();
3165
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
3166
+ makeTestAdapter({
3167
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
3168
+ driver: CLAUDE_DRIVER,
3169
+ capabilities: ClaudeProviderCapabilitiesV2,
3170
+ modelSelection: CLAUDE_MODEL_SELECTION,
3171
+ responseByRunOrdinal: {},
3172
+ capturedTurns,
3173
+ closedSessions,
3174
+ backgroundWork,
3175
+ nativeThreadGeneration: yield* Ref.make(0),
3176
+ ...(queued
3177
+ ? { holdFirstTurn: started, releaseFirstTurn: release, holdRunOrdinal: 2 }
3178
+ : {}),
3179
+ }),
3180
+ makeTestAdapter({
3181
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
3182
+ driver: CODEX_DRIVER,
3183
+ capabilities: CodexProviderCapabilitiesV2,
3184
+ modelSelection: CODEX_MODEL_SELECTION,
3185
+ responseByRunOrdinal: {},
3186
+ capturedTurns,
3187
+ }),
3188
+ ]);
3189
+ const freshThreadId = ThreadId.make(`thread:fresh-context:${key}`);
3190
yield* Effect.gen(function* () {
3191
const orchestrator = yield* Orchestrator.OrchestratorV2;
3192
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
3193
+ const send = (
3194
+ name: string,
3195
+ modelSelection: ModelSelection,
3196
+ options: { readonly freshContext?: boolean } = {},
3197
+ ) =>
3198
+ orchestrator.dispatch({
3199
+ type: "message.dispatch",
3200
+ createdBy: "user",
3201
+ creationSource: "web",
3202
+ commandId: CommandId.make(`command:fresh-context:${key}:${name}`),
3203
+ threadId: freshThreadId,
3204
+ messageId: MessageId.make(`message:fresh-context:${key}:${name}`),
3205
+ text: `Prompt ${name}`,
3206
+ attachments: [],
3207
+ modelSelection,
3208
+ ...options,
3209
+ // A fresh send must never steer the running turn.
3210
+ deliveryIntent: "auto",
3211
+ dispatchMode: { type: "start_immediately" },
3212
+ });
3213
yield* orchestrator.dispatch({
3214
type: "thread.create",
3215
createdBy: "user",
3216
creationSource: "web",
3091
- commandId: CommandId.make(`command:settings-background-${change}:create`),
3092
- threadId,
3093
- projectId: ProjectId.make(`project:settings-background-${change}`),
3094
- title: "Settings change with background work",
3217
+ commandId: CommandId.make(`command:fresh-context:${key}:create`),
3218
+ threadId: freshThreadId,
3219
+ projectId: ProjectId.make(`project:fresh-context:${key}`),
3220
+ title: "Fresh context",
3221
modelSelection: CLAUDE_MODEL_SELECTION,
3222
runtimeMode: "full-access",
3223
interactionMode: "default",
3224
branch: null,
3225
worktreePath: cwd,
3226
});
3101
- yield* orchestrator.dispatch({
3102
- type: "message.dispatch",
3103
- createdBy: "user",
3104
- creationSource: "web",
3105
- commandId: CommandId.make(`command:settings-background-${change}:send`),
3106
- threadId,
3107
- messageId: MessageId.make(`message:settings-background-${change}:send`),
3108
- text: "Start background work",
3109
- attachments: [],
3110
- modelSelection: CLAUDE_MODEL_SELECTION,
3111
- dispatchMode: { type: "start_immediately" },
3112
- });
3227
+ // Codex keeps a native thread from before the fresh run that must not resume.
3228
+ yield* send("zero", CODEX_MODEL_SELECTION);
3229
yield* worker.drain();
3114
- const afterFirst = yield* waitForIdle(threadId);
3115
- const session = afterFirst.providerSessions[0];
3116
- assert.equal(session?.status, "ready");
3117
- // The turn ended but a background subagent keeps running in the CLI process.
3118
- yield* Ref.set(backgroundWork, true);
3119
-
3120
- const commandId = CommandId.make(`command:settings-background-${change}:change`);
3121
- yield* orchestrator
3122
- .dispatch(
3123
- change === "runtime-mode"
3124
- ? {
3125
- type: "thread.runtime-mode.set",
3126
- commandId,
3127
- threadId,
3128
- runtimeMode: "auto-accept-edits",
3129
- }
3130
- : change === "worktree"
3131
- ? { type: "thread.metadata.update", commandId, threadId, worktreePath: nextCwd }
3132
- : {
3133
- type: "thread.model-selection.set",
3134
- commandId,
3135
- threadId,
3136
- modelSelection: secondSelection,
3137
- },
3138
- )
3139
- .pipe(Effect.ignore);
3230
+ yield* waitForIdle(freshThreadId);
3231
+ yield* send("alpha", CLAUDE_MODEL_SELECTION);
3232
+ if (queued) {
3233
+ yield* Deferred.await(started);
3234
+ yield* worker.drain();
3235
+ } else {
3236
+ yield* worker.drain();
3237
+ yield* waitForIdle(freshThreadId);
3238
+ }
3239
+ const firstSession = (yield* orchestrator.getThreadProjection(
3240
+ freshThreadId,
3241
+ )).providerSessions.find(
3242
+ (session) => session.providerInstanceId === CLAUDE_MODEL_SELECTION.instanceId,
3243
+ )!;
3244
+ yield* send("beta", CLAUDE_MODEL_SELECTION, { freshContext: true });
3245
+ if (queued) {
3246
+ // Queued before the fresh run started, so it is bound to the old conversation.
3247
+ yield* send("gamma", CLAUDE_MODEL_SELECTION);
3248
+ const waiting = yield* orchestrator.getThreadProjection(freshThreadId);
3249
+ assert.deepEqual(
3250
+ waiting.runs.map((run) => run.status),
3251
+ ["completed", "running", "queued", "queued"],
3252
+ );
3253
+ // Steering would send it into the conversation it is meant to leave.
3254
+ const promoted = yield* orchestrator
3255
+ .dispatch({
3256
+ type: "queued-message.promote-to-steer",
3257
+ commandId: CommandId.make(`command:fresh-context:${key}:promote`),
3258
+ threadId: freshThreadId,
3259
+ queuedRunId: waiting.runs.find((run) => run.freshContext === true)!.id,
3260
+ targetRunId: waiting.runs.find((run) => run.status === "running")!.id,
3261
+ })
3262
+ .pipe(Effect.flip);
3263
+ assert.instanceOf(promoted, Orchestrator.OrchestratorDispatchError);
3264
+ assert.include(String(promoted.cause), "fresh session");
3265
+ yield* Deferred.succeed(release, undefined);
3266
+ }
3267
yield* worker.drain();
3268
+ yield* waitForIdle(freshThreadId);
3269
+ // Claude hosts one native thread per session, so an idle old one is closed.
3270
+ assert.deepEqual(yield* Ref.get(closedSessions), queued ? [] : [firstSession.id]);
3271
+ yield* Ref.set(backgroundWork, false);
3272
+ yield* send("delta", CODEX_MODEL_SELECTION);
3273
+ yield* worker.drain();
3274
+ yield* waitForIdle(freshThreadId);
3275
+ yield* worker.drain();
3276
+ const projection = yield* orchestrator.getThreadProjection(freshThreadId);
3277
+ const turns = yield* Ref.get(capturedTurns);
3278
+ const turnFor = (name: string) =>
3279
+ turns.find((turn) => turn.text.endsWith(`Prompt ${name}`))!;
3280
3142
- const projection = yield* orchestrator.getThreadProjection(threadId);
3143
- // Refusing or deferring are both fine; closing the busy process is not.
3144
- assert.deepEqual(yield* Ref.get(closedSessions), []);
3145
- assert.deepEqual(
3146
- projection.providerSessions.map((candidate) => [candidate.id, candidate.status]),
3147
- [[session!.id, "ready"]],
3281
+ const freshRun = projection.runs.find(
3282
+ (run) => run.userMessageId === `message:fresh-context:${key}:beta`,
3283
+ )!;
3284
+ assert.isTrue(freshRun.freshContext);
3285
+ assert.equal(freshRun.contextHandoffId, null);
3286
+ assert.isTrue(
3287
+ projection.turnItems.some(
3288
+ (item) =>
3289
+ item.type === "user_message" &&
3290
+ item.messageId === freshRun.userMessageId &&
3291
+ item.freshContext === true,
3292
+ ),
3293
);
3294
+ assert.notEqual(turnFor("beta").providerThreadId, turnFor("alpha").providerThreadId);
3295
+ assert.notEqual(turnFor("beta").nativeThreadId, turnFor("alpha").nativeThreadId);
3296
+ assert.equal(turnFor("beta").text, "Prompt beta");
3297
+ if (queued) {
3298
+ assert.equal(turnFor("gamma").providerThreadId, turnFor("beta").providerThreadId);
3299
+ }
3300
+ const codexTurn = turnFor("delta");
3301
+ assert.notEqual(codexTurn.providerThreadId, turnFor("zero").providerThreadId);
3302
+ assert.include(codexTurn.text, "Prompt beta");
3303
+ assert.notInclude(codexTurn.text, "Prompt alpha");
3304
+ assert.notInclude(codexTurn.text, "Prompt zero");
3305
+ assert.equal(projection.contextHandoffs.at(-1)!.coveredRunOrdinals.from, 3);
3306
}).pipe(
3307
Effect.provide(
3308
ProviderReplayHarness.layerWithRegistry(
3309
{
3153
- name: `settings-background-${change}`,
3310
+ name: `fresh-context-${key}`,
3311
runtimePolicyOverride: {
3312
cwd,
3313
approvalPolicy: "never",
@@ -3161,312 +3318,21 @@ describe("orchestration v2 provider switching", () => {
3318
},
3319
},
3320
},
3164
- ProviderAdapterRegistry.layerFromAdapters([
3165
- makeTestAdapter({
3166
- instanceId: CLAUDE_MODEL_SELECTION.instanceId,
3167
- driver: CLAUDE_DRIVER,
3168
- capabilities: ClaudeProviderCapabilitiesV2,
3169
- modelSelection: CLAUDE_MODEL_SELECTION,
3170
- responseByRunOrdinal: { 1: "Background work started" },
3171
- capturedTurns,
3172
- backgroundWork,
3173
- closedSessions,
3174
- }),
3175
- makeTestAdapter({
3176
- instanceId: secondSelection.instanceId,
3177
- driver: CLAUDE_DRIVER,
This file is too large to show in full.
apps/server/src/orchestration-v2/workflowAgentTranscript.test.ts
+1
-1
@@ -60,6 +60,6 @@ it.layer(NodeServices.layer)("readWorkflowAgentTranscript", (it) => {
60
assert.equal(NodeFS.statSync(file).ino, replaced.cursor.identity?.ino);
61
const shrunk = yield* read(replaced.cursor);
62
assert.deepEqual(uuids(shrunk.lines), ["d"], "a shrunk file reads from 0");
63
- }).pipe(Effect.scoped),
63
+ }),
64
);
65
});
apps/server/src/peer/PeerLinks.test.ts
+29
-31
@@ -123,16 +123,15 @@ const serveApart = (descriptor: ExecutionEnvironmentDescriptor) =>
123
);
124
125
it.effect("routes peer reads to readers and sees uncommitted link updates", () =>
126
- Effect.scoped(
127
- Effect.gen(function* () {
128
- const context = yield* layerLinkingEnvironment(
129
- laptop,
130
- ServerSecretStore.layer,
131
- layerReaderDatabase,
132
- ).pipe(Layer.build);
133
- const links = Context.get(context, PeerLinks.PeerLinks);
134
- const sql = Context.get(context, SqlClient.SqlClient);
135
- yield* sql`
126
+ Effect.gen(function* () {
127
+ const context = yield* layerLinkingEnvironment(
128
+ laptop,
129
+ ServerSecretStore.layer,
130
+ layerReaderDatabase,
131
+ ).pipe(Layer.build);
132
+ const links = Context.get(context, PeerLinks.PeerLinks);
133
+ const sql = Context.get(context, SqlClient.SqlClient);
134
+ yield* sql`
135
INSERT INTO peer_environment_links (
136
environment_id, secret_name, label, urls_json, access, linked_at, expires_at, fenced
137
) VALUES (
@@ -140,27 +139,26 @@ it.effect("routes peer reads to readers and sees uncommitted link updates", () =
139
'2026-01-01T00:00:00.000Z', '2026-01-02T00:00:00.000Z', 1
140
)
141
`;
143
- const { queries, trace } = traceSqlRouting();
144
- yield* links.list.pipe(trace);
145
- expect(Option.getOrThrow(yield* links.get(box.environmentId).pipe(trace)).label).toBe("Box");
146
- const reads = queries.filter(({ query }) =>
147
- query.includes("SELECT * FROM peer_environment_links"),
148
- );
149
- expect(reads).toHaveLength(2);
150
- expect(reads.map((row) => row.connection)).toEqual(["reader", "reader"]);
151
- yield* sql.withTransaction(
152
- Effect.gen(function* () {
153
- yield* sql`UPDATE peer_environment_links SET label = 'Uncommitted box'`;
154
- expect(Option.getOrThrow(yield* links.get(box.environmentId)).label).toBe(
155
- "Uncommitted box",
156
- );
157
- expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
158
- }),
159
- );
160
- expect(yield* links.unlink(box.environmentId)).toBe(true);
161
- expect(yield* links.list).toEqual([]);
162
- }),
163
- ),
142
+ const { queries, trace } = traceSqlRouting();
143
+ yield* links.list.pipe(trace);
144
+ expect(Option.getOrThrow(yield* links.get(box.environmentId).pipe(trace)).label).toBe("Box");
145
+ const reads = queries.filter(({ query }) =>
146
+ query.includes("SELECT * FROM peer_environment_links"),
147
+ );
148
+ expect(reads).toHaveLength(2);
149
+ expect(reads.map((row) => row.connection)).toEqual(["reader", "reader"]);
150
+ yield* sql.withTransaction(
151
+ Effect.gen(function* () {
152
+ yield* sql`UPDATE peer_environment_links SET label = 'Uncommitted box'`;
153
+ expect(Option.getOrThrow(yield* links.get(box.environmentId)).label).toBe(
154
+ "Uncommitted box",
155
+ );
156
+ expect((yield* links.list)[0]?.label).toBe("Uncommitted box");
157
+ }),
158
+ );
159
+ expect(yield* links.unlink(box.environmentId)).toBe(true);
160
+ expect(yield* links.list).toEqual([]);
161
+ }),
162
);
163
164
it.effect("links with a pairing code, and the peer holds its agents to the limits they carry", () =>
apps/server/src/peer/PeerMcpClient.test.ts
+2
-2
@@ -339,7 +339,7 @@ it.effect("renews a missing peer session once and reuses its replacement", () =>
339
"renewed",
340
"renewed",
341
]);
342
- }).pipe(Effect.scoped),
342
+ }),
343
);
344
345
it.effect("bounds the session handshake, not a tool call that waits longer", () =>
@@ -381,5 +381,5 @@ it.effect("bounds the session handshake, not a tool call that waits longer", ()
381
yield* TestClock.adjust(Duration.minutes(1));
382
yield* Deferred.succeed(answer, undefined);
383
expect(yield* Fiber.join(waiting)).toEqual({ modes: "approval-required/plan" });
384
- }).pipe(Effect.scoped),
384
+ }),
385
);
apps/server/src/persistence/DatabaseMaintenance.test.ts
+5
-5
@@ -28,7 +28,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
28
yield* fs.writeFileString(dbPath, "not a database");
29
const failure = yield* Effect.flip(maintenance.inspect(dbPath));
30
assert.equal(failure._tag, "DatabaseInspectError");
31
- }).pipe(Effect.scoped),
31
+ }),
32
);
33
34
it.effect("reports and deletes only the database from before 0.1.0", () =>
@@ -98,7 +98,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
98
assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
99
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
100
assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
101
- }).pipe(Effect.scoped),
101
+ }),
102
);
103
104
it.effect("runs a repair requested from Settings once and keeps its failure for Settings", () =>
@@ -153,7 +153,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
153
yield* fs.readFileString(broken.failure),
154
new DatabaseMaintenance.DatabaseCompactError({ path: brokenPath, cause: null }).message,
155
);
156
- }).pipe(Effect.scoped),
156
+ }),
157
);
158
159
it.effect("refuses a repair whose copies would not fit on disk", () =>
@@ -169,7 +169,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
169
const shortfall = yield* DatabaseMaintenance.reclaimSpaceShortfall(dbPath, huge);
170
assert.isAtLeast(shortfall?.neededBytes ?? 0, huge);
171
assert.isBelow(shortfall?.freeBytes ?? Infinity, huge);
172
- }).pipe(Effect.scoped),
172
+ }),
173
);
174
175
it.effect("compacts an existing database offline only once its server has stopped", () =>
@@ -260,7 +260,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
260
[{ messageId: "message-1" }],
261
);
262
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
263
- }).pipe(Effect.scoped),
263
+ }),
264
);
265
},
266
);
apps/server/src/persistence/OrchestrationEventStore.test.ts
+59
-61
@@ -38,69 +38,67 @@ const layer = it.layer(layerTest);
38
39
layer("OrchestrationEventStore", (it) => {
40
it.effect("retains only shell metadata from oversized replay and live application events", () =>
41
- Effect.scoped(
42
- Effect.gen(function* () {
43
- const store = yield* OrchestrationEventStore.OrchestrationEventStore;
44
- const afterSequence = yield* store.latestApplicationSequence;
45
- const now = yield* DateTime.now;
46
- const threadId = ThreadId.make("thread:large-shell-body");
47
- const input = "x".repeat(9 * 1024 * 1024);
48
- const event: OrchestrationV2DomainEvent = {
49
- id: EventId.make("event:large-shell-body:replay"),
50
- type: "turn-item.updated",
41
+ Effect.gen(function* () {
42
+ const store = yield* OrchestrationEventStore.OrchestrationEventStore;
43
+ const afterSequence = yield* store.latestApplicationSequence;
44
+ const now = yield* DateTime.now;
45
+ const threadId = ThreadId.make("thread:large-shell-body");
46
+ const input = "x".repeat(9 * 1024 * 1024);
47
+ const event: OrchestrationV2DomainEvent = {
48
+ id: EventId.make("event:large-shell-body:replay"),
49
+ type: "turn-item.updated",
50
+ threadId,
51
+ occurredAt: now,
52
+ payload: {
53
+ id: TurnItemId.make("tool:large-shell-body"),
54
+ type: "command_execution",
55
threadId,
52
- occurredAt: now,
53
- payload: {
54
- id: TurnItemId.make("tool:large-shell-body"),
55
- type: "command_execution",
56
- threadId,
57
- runId: null,
58
- nodeId: null,
59
- providerThreadId: null,
60
- providerTurnId: null,
61
- nativeItemRef: null,
62
- parentItemId: null,
63
- ordinal: 1,
64
- status: "running",
65
- title: "Large command",
66
- input,
67
- startedAt: now,
68
- completedAt: null,
69
- updatedAt: now,
56
+ runId: null,
57
+ nodeId: null,
58
+ providerThreadId: null,
59
+ providerTurnId: null,
60
+ nativeItemRef: null,
61
+ parentItemId: null,
62
+ ordinal: 1,
63
+ status: "running",
64
+ title: "Large command",
65
+ input,
66
+ startedAt: now,
67
+ completedAt: null,
68
+ updatedAt: now,
69
+ },
70
+ };
71
+ const [replayed] = yield* store.appendAgentEvents({ events: [event] });
72
+ const pull = yield* Stream.toPull(
73
+ store.streamProjectedApplicationEvents({
74
+ afterSequence,
75
+ project: toShellApplicationEvent,
76
+ }),
77
+ );
78
+ assert.deepEqual(yield* pull, [{ sequence: replayed!.sequence, event: { threadId } }]);
79
+ const [live] = yield* store.appendAgentEvents({
80
+ events: [
81
+ {
82
+ ...event,
83
+ id: EventId.make("event:large-shell-body:live"),
84
+ payload: { ...event.payload, status: "completed", completedAt: now },
85
},
71
- };
72
- const [replayed] = yield* store.appendAgentEvents({ events: [event] });
73
- const pull = yield* Stream.toPull(
74
- store.streamProjectedApplicationEvents({
75
- afterSequence,
76
- project: toShellApplicationEvent,
77
- }),
78
- );
79
- assert.deepEqual(yield* pull, [{ sequence: replayed!.sequence, event: { threadId } }]);
80
- const [live] = yield* store.appendAgentEvents({
81
- events: [
82
- {
83
- ...event,
84
- id: EventId.make("event:large-shell-body:live"),
85
- payload: { ...event.payload, status: "completed", completedAt: now },
86
- },
87
- ],
88
- });
89
- yield* store.publishCommitted([live!]);
90
- assert.deepEqual(yield* pull, [{ sequence: live!.sequence, event: { threadId } }]);
91
- const durable = yield* store
92
- .readAgentEvents({ threadId, afterSequence })
93
- .pipe(Stream.runCollect);
94
- assert.lengthOf(durable, 2);
95
- for (const stored of durable) {
96
- assert.equal(stored.event.type, "turn-item.updated");
97
- if (stored.event.type !== "turn-item.updated") return;
98
- assert.equal(stored.event.payload.type, "command_execution");
99
- if (stored.event.payload.type !== "command_execution") return;
100
- assert.equal(stored.event.payload.input, input);
101
- }
102
- }),
103
- ),
86
+ ],
87
+ });
88
+ yield* store.publishCommitted([live!]);
89
+ assert.deepEqual(yield* pull, [{ sequence: live!.sequence, event: { threadId } }]);
90
+ const durable = yield* store
91
+ .readAgentEvents({ threadId, afterSequence })
92
+ .pipe(Stream.runCollect);
93
+ assert.lengthOf(durable, 2);
94
+ for (const stored of durable) {
95
+ assert.equal(stored.event.type, "turn-item.updated");
96
+ if (stored.event.type !== "turn-item.updated") return;
97
+ assert.equal(stored.event.payload.type, "command_execution");
98
+ if (stored.event.payload.type !== "command_execution") return;
99
+ assert.equal(stored.event.payload.input, input);
100
+ }
101
+ }),
102
);
103
104
it.effect("stores an unchanged subagent prompt once and replays it on every update", () =>
apps/server/src/preview/ServerBrowserStream.test.ts
+5
-5
@@ -149,7 +149,7 @@ it.effect.each([
149
},
150
]);
151
expect(auth.requests).toEqual([resource]);
152
- }).pipe(Effect.scoped),
152
+ }),
153
);
154
155
it.effect("sends replies ahead of stale frames and only the newest frame after an ack", () =>
@@ -221,7 +221,7 @@ it.effect("sends replies ahead of stale frames and only the newest frame after a
221
yield* Effect.promise(() => next.promise);
222
expect(received).toEqual([1, "probe", 4]);
223
expect(released).toEqual([2, 3, 1]);
224
- }).pipe(Effect.scoped),
224
+ }),
225
);
226
227
it.effect.each([
@@ -264,7 +264,7 @@ it.effect.each([
264
);
265
expect(response.status).toBe(testCase.status);
266
expect(attachments).toBe(0);
267
- }).pipe(Effect.scoped),
267
+ }),
268
);
269
270
it.effect("serves a tab's download only to an authorized session", () =>
@@ -369,7 +369,7 @@ it.effect("passes uploaded files to the page's open picker and needs operate sco
369
{ chooserId: "chooser-1", files: [{ name: "notes.txt", text: "hello" }] },
370
]);
371
expect((yield* upload([AuthPreviewOperateScope], "stale")).status).toBe(409);
372
- }).pipe(Effect.scoped),
372
+ }),
373
);
374
375
const decodeHostSetup = Schema.decodeUnknownEffect(Schema.fromJsonString(PreviewStreamHostSetup));
@@ -430,5 +430,5 @@ it.effect.each([
430
need,
431
command: "sudo t3 browser setup",
432
});
433
- }).pipe(Effect.scoped),
433
+ }),
434
);
apps/server/src/provider/AcpRegistryProbe.test.ts
-1
@@ -410,7 +410,6 @@ describe("ACP Registry probe", () => {
410
}).pipe(
411
Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog),
412
Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
413
- Effect.scoped,
413
);
414
});
415
apps/server/src/provider/AntigravityProvider.test.ts
+446
-488
@@ -291,561 +291,519 @@ describe("Antigravity model catalog", () => {
291
292
it.layer(layerTest)("Antigravity provider snapshots", (it) => {
293
it.effect("does not probe or run helper safety checks while disabled", () =>
294
- Effect.scoped(
295
- Effect.gen(function* () {
296
- const harness = yield* makeHarness({ enabled: false });
297
- const snapshot = yield* harness.provider.snapshot.refresh;
298
- expect(snapshot).toMatchObject({
299
- enabled: false,
294
+ Effect.gen(function* () {
295
+ const harness = yield* makeHarness({ enabled: false });
296
+ const snapshot = yield* harness.provider.snapshot.refresh;
297
+ expect(snapshot).toMatchObject({
298
+ enabled: false,
299
+ installed: false,
300
+ status: "disabled",
301
+ auth: { status: "unknown" },
302
+ models: [],
303
+ setup: { canAuthenticate: true, canInstall: true },
304
+ showInteractionModeToggle: false,
305
+ supportsConversationRollback: false,
306
+ supportsTextGeneration: false,
307
+ });
308
+ expect(yield* Ref.get(harness.probeCalls)).toBe(0);
309
+ expect(yield* Ref.get(harness.safetyCalls)).toBe(0);
310
+ }),
311
+ );
312
+
313
+ it.effect("treats initialize as installation proof, not account or model discovery", () =>
314
+ Effect.gen(function* () {
315
+ for (const auth of [
316
+ undefined,
317
+ { type: "oauth-personal", label: "Google account" },
318
+ { type: "oauth-business", label: "Gemini Enterprise" },
319
+ { type: "gemini-api-key", label: "Gemini API key" },
320
+ { type: "agent-platform", label: "Agent Platform" },
321
+ ]) {
322
+ const harness = yield* makeHarness(auth ? { auth } : {});
323
+ expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
324
installed: false,
301
- status: "disabled",
325
+ status: "warning",
326
auth: { status: "unknown" },
327
models: [],
304
- setup: { canAuthenticate: true, canInstall: true },
305
- showInteractionModeToggle: false,
306
- supportsConversationRollback: false,
307
- supportsTextGeneration: false,
328
});
309
- expect(yield* Ref.get(harness.probeCalls)).toBe(0);
310
- expect(yield* Ref.get(harness.safetyCalls)).toBe(0);
311
- }),
312
- ),
313
- );
314
-
315
- it.effect("treats initialize as installation proof, not account or model discovery", () =>
316
- Effect.scoped(
317
- Effect.gen(function* () {
318
- for (const auth of [
319
- undefined,
320
- { type: "oauth-personal", label: "Google account" },
321
- { type: "oauth-business", label: "Gemini Enterprise" },
322
- { type: "gemini-api-key", label: "Gemini API key" },
323
- { type: "agent-platform", label: "Agent Platform" },
324
- ]) {
325
- const harness = yield* makeHarness(auth ? { auth } : {});
326
- expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
327
- installed: false,
328
- status: "warning",
329
- auth: { status: "unknown" },
330
- models: [],
331
- });
332
- yield* harness.initialize;
333
- const snapshot = yield* harness.provider.snapshot.getSnapshot;
334
- expect(snapshot).toMatchObject({
335
- installed: true,
336
- status: "warning",
337
- version: "agy_acp_server_20260818_01_RC01",
338
- auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) },
339
- message:
340
- auth?.type === "gemini-api-key" || auth?.type === "agent-platform"
341
- ? `Antigravity is installed. Connect with ${auth.label} to load models.`
342
- : "Antigravity is installed. Google account access is not checked yet.",
343
- models: [],
344
- });
345
- expect(yield* Ref.get(harness.probeCalls)).toBe(1);
346
- }
347
- }),
348
- ),
329
+ yield* harness.initialize;
330
+ const snapshot = yield* harness.provider.snapshot.getSnapshot;
331
+ expect(snapshot).toMatchObject({
332
+ installed: true,
333
+ status: "warning",
334
+ version: "agy_acp_server_20260818_01_RC01",
335
+ auth: { status: "unknown", ...(auth ? { type: auth.type } : {}) },
336
+ message:
337
+ auth?.type === "gemini-api-key" || auth?.type === "agent-platform"
338
+ ? `Antigravity is installed. Connect with ${auth.label} to load models.`
339
+ : "Antigravity is installed. Google account access is not checked yet.",
340
+ models: [],
341
+ });
342
+ expect(yield* Ref.get(harness.probeCalls)).toBe(1);
343
+ }
344
+ }),
345
);
346
347
it.effect("does not offer Auto, so Auto threads fall back to Supervised", () =>
352
- Effect.scoped(
353
- Effect.gen(function* () {
354
- const harness = yield* makeHarness();
355
- yield* harness.initialize;
356
- // Antigravity has no automatic review; the shared ACP policy would approve every request.
357
- expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([
358
- "approval-required",
359
- "auto-accept-edits",
360
- "full-access",
361
- ]);
362
- }),
363
- ),
348
+ Effect.gen(function* () {
349
+ const harness = yield* makeHarness();
350
+ yield* harness.initialize;
351
+ // Antigravity has no automatic review; the shared ACP policy would approve every request.
352
+ expect((yield* harness.provider.snapshot.getSnapshot).supportedRuntimeModes).toEqual([
353
+ "approval-required",
354
+ "auto-accept-edits",
355
+ "full-access",
356
+ ]);
357
+ }),
358
);
359
360
it.effect("publishes session metadata and native commands without another health probe", () =>
367
- Effect.scoped(
368
- Effect.gen(function* () {
369
- const harness = yield* makeHarness();
370
- yield* harness.initialize;
371
- const nextReady = yield* Stream.toPull(
372
- harness.provider.snapshot.streamChanges.pipe(
373
- Stream.filter(
374
- (snapshot) =>
375
- snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0,
376
- ),
361
+ Effect.gen(function* () {
362
+ const harness = yield* makeHarness();
363
+ yield* harness.initialize;
364
+ const nextReady = yield* Stream.toPull(
365
+ harness.provider.snapshot.streamChanges.pipe(
366
+ Stream.filter(
367
+ (snapshot) =>
368
+ snapshot.auth.status === "authenticated" && snapshot.slashCommands.length > 0,
369
),
378
- );
379
- yield* harness.provider.onSessionStarted(started, "/workspace");
380
- yield* harness.provider.onAvailableCommands(commands, "/workspace");
381
- const [snapshot] = yield* nextReady;
382
- expect(snapshot).toMatchObject({
383
- status: "ready",
384
- auth: { status: "authenticated", type: "oauth-personal" },
385
- supportsTextGeneration: true,
386
- });
387
- expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
388
- expect(snapshot.slashCommands).toEqual(expectedCommands);
389
- expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual(
390
- expectedCommands,
391
- );
392
- expect(yield* Ref.get(harness.probeCalls)).toBe(1);
393
- }),
394
- ),
370
+ ),
371
+ );
372
+ yield* harness.provider.onSessionStarted(started, "/workspace");
373
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
374
+ const [snapshot] = yield* nextReady;
375
+ expect(snapshot).toMatchObject({
376
+ status: "ready",
377
+ auth: { status: "authenticated", type: "oauth-personal" },
378
+ supportsTextGeneration: true,
379
+ });
380
+ expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
381
+ expect(snapshot.slashCommands).toEqual(expectedCommands);
382
+ expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual(
383
+ expectedCommands,
384
+ );
385
+ expect(yield* Ref.get(harness.probeCalls)).toBe(1);
386
+ }),
387
);
388
389
it.effect("clears all account metadata on sign-out and authentication failure", () =>
398
- Effect.scoped(
399
- Effect.gen(function* () {
400
- const auth = { type: "gemini-api-key", label: "Gemini API key" };
401
- const harness = yield* makeHarness({ auth });
402
- yield* harness.initialize;
403
- for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) {
404
- yield* harness.provider.onSessionStarted(started, "/workspace");
405
- yield* harness.provider.onAvailableCommands(commands, "/workspace");
406
- yield* clear;
407
- expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
408
- installed: true,
409
- status: "warning",
410
- auth: { status: "unauthenticated", type: auth.type, label: auth.label },
411
- message: "Connect with Gemini API key to use Antigravity and load models.",
412
- models: [],
413
- slashCommands: [],
414
- skills: [],
415
- workspaceSnapshots: [],
416
- supportsTextGeneration: false,
417
- });
418
- yield* harness.provider.onAvailableCommands(commands, "/workspace");
419
- yield* harness.provider.onConfigOptionsUpdated([modelConfig]);
420
- expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]);
421
- expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]);
422
- }
423
- const refreshed = yield* harness.provider.snapshot.refresh;
424
- expect(refreshed.auth).toEqual({
425
- status: "unauthenticated",
426
- type: auth.type,
427
- label: auth.label,
428
- });
429
- expect(refreshed.message).toBe(
430
- "Connect with Gemini API key to use Antigravity and load models.",
431
- );
432
- expect(refreshed.supportsTextGeneration).toBe(false);
433
- }),
434
- ),
435
- );
436
-
437
- it.effect("replaces live model choices and accepts an empty catalog", () =>
438
- Effect.scoped(
439
- Effect.gen(function* () {
440
- const harness = yield* makeHarness();
441
- yield* harness.initialize;
390
+ Effect.gen(function* () {
391
+ const auth = { type: "gemini-api-key", label: "Gemini API key" };
392
+ const harness = yield* makeHarness({ auth });
393
+ yield* harness.initialize;
394
+ for (const clear of [harness.provider.onSignedOut, harness.provider.onAuthRequired]) {
395
yield* harness.provider.onSessionStarted(started, "/workspace");
396
yield* harness.provider.onAvailableCommands(commands, "/workspace");
444
- const before = yield* harness.provider.snapshot.getSnapshot;
445
- const configOptions = [
446
- {
447
- ...modelConfig,
448
- currentValue: "gemini-3.8-flash-high",
449
- options: modelOptions.slice(0, 3),
450
- },
451
- ];
452
- const nextSnapshot = yield* Stream.toPull(
453
- harness.provider.snapshot.streamChanges.pipe(
454
- Stream.filter((snapshot) => snapshot.models.length === 3),
455
- ),
456
- );
457
- yield* harness.provider.onConfigOptionsUpdated(configOptions);
458
- expect((yield* nextSnapshot)[0]).toMatchObject({
459
- models: buildAntigravityModelsFromSession({ configOptions }),
460
- auth: before.auth,
461
- workspaceSnapshots: before.workspaceSnapshots,
462
- slashCommands: expectedCommands,
397
+ yield* clear;
398
+ expect(yield* harness.provider.snapshot.getSnapshot).toMatchObject({
399
+ installed: true,
400
+ status: "warning",
401
+ auth: { status: "unauthenticated", type: auth.type, label: auth.label },
402
+ message: "Connect with Gemini API key to use Antigravity and load models.",
403
+ models: [],
404
+ slashCommands: [],
405
+ skills: [],
406
+ workspaceSnapshots: [],
407
+ supportsTextGeneration: false,
408
});
464
- yield* harness.provider.onConfigOptionsUpdated([]);
409
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
410
+ yield* harness.provider.onConfigOptionsUpdated([modelConfig]);
411
+ expect((yield* harness.provider.snapshotForCwd("/workspace")).slashCommands).toEqual([]);
412
expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]);
466
- }),
467
- ),
413
+ }
414
+ const refreshed = yield* harness.provider.snapshot.refresh;
415
+ expect(refreshed.auth).toEqual({
416
+ status: "unauthenticated",
417
+ type: auth.type,
418
+ label: auth.label,
419
+ });
420
+ expect(refreshed.message).toBe(
421
+ "Connect with Gemini API key to use Antigravity and load models.",
422
+ );
423
+ expect(refreshed.supportsTextGeneration).toBe(false);
424
+ }),
425
+ );
426
+
427
+ it.effect("replaces live model choices and accepts an empty catalog", () =>
428
+ Effect.gen(function* () {
429
+ const harness = yield* makeHarness();
430
+ yield* harness.initialize;
431
+ yield* harness.provider.onSessionStarted(started, "/workspace");
432
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
433
+ const before = yield* harness.provider.snapshot.getSnapshot;
434
+ const configOptions = [
435
+ {
436
+ ...modelConfig,
437
+ currentValue: "gemini-3.8-flash-high",
438
+ options: modelOptions.slice(0, 3),
439
+ },
440
+ ];
441
+ const nextSnapshot = yield* Stream.toPull(
442
+ harness.provider.snapshot.streamChanges.pipe(
443
+ Stream.filter((snapshot) => snapshot.models.length === 3),
444
+ ),
445
+ );
446
+ yield* harness.provider.onConfigOptionsUpdated(configOptions);
447
+ expect((yield* nextSnapshot)[0]).toMatchObject({
448
+ models: buildAntigravityModelsFromSession({ configOptions }),
449
+ auth: before.auth,
450
+ workspaceSnapshots: before.workspaceSnapshots,
451
+ slashCommands: expectedCommands,
452
+ });
453
+ yield* harness.provider.onConfigOptionsUpdated([]);
454
+ expect((yield* harness.provider.snapshot.getSnapshot).models).toEqual([]);
455
+ }),
456
);
457
458
it.effect("does not guess a version before a custom launcher's first handshake", () =>
471
- Effect.scoped(
472
- Effect.gen(function* () {
473
- const harness = yield* makeHarness();
474
- yield* Deferred.succeed(harness.initialProbe, {
475
- ...initializeResult,
476
- agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
477
- });
478
- yield* harness.initialUpdate;
479
- expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull();
480
- }),
481
- ),
459
+ Effect.gen(function* () {
460
+ const harness = yield* makeHarness();
461
+ yield* Deferred.succeed(harness.initialProbe, {
462
+ ...initializeResult,
463
+ agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
464
+ });
465
+ yield* harness.initialUpdate;
466
+ expect((yield* harness.provider.snapshot.getSnapshot).version).toBeNull();
467
+ }),
468
);
469
470
it.effect("does not replace a handshake version with an unknown custom-launcher probe", () =>
485
- Effect.scoped(
486
- Effect.gen(function* () {
487
- const harness = yield* makeHarness();
488
- yield* harness.initialize;
489
- yield* harness.provider.onSessionStarted({
490
- ...started,
491
- initializeResult: {
492
- ...initializeResult,
493
- agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" },
494
- },
495
- });
496
- yield* Ref.set(
497
- harness.probe,
498
- Effect.succeed({
499
- ...initializeResult,
500
- agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
501
- }),
502
- );
503
- expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0");
504
- }),
505
- ),
471
+ Effect.gen(function* () {
472
+ const harness = yield* makeHarness();
473
+ yield* harness.initialize;
474
+ yield* harness.provider.onSessionStarted({
475
+ ...started,
476
+ initializeResult: {
477
+ ...initializeResult,
478
+ agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" },
479
+ },
480
+ });
481
+ yield* Ref.set(
482
+ harness.probe,
483
+ Effect.succeed({
484
+ ...initializeResult,
485
+ agentInfo: { ...initializeResult.agentInfo, version: "unknown" },
486
+ }),
487
+ );
488
+ expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0");
489
+ }),
490
);
491
492
it.effect("replaces one account's catalog instead of combining accounts", () =>
509
- Effect.scoped(
510
- Effect.gen(function* () {
511
- const harness = yield* makeHarness();
512
- yield* harness.initialize;
513
- yield* harness.provider.onSessionStarted(started);
514
- yield* harness.provider.onSignedOut;
515
- yield* harness.provider.onSessionStarted({
516
- ...started,
517
- sessionSetupResult: {
518
- sessionId: "new-account-session",
519
- configOptions: [
520
- { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] },
521
- ],
522
- },
523
- });
524
- expect(
525
- (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug),
526
- ).toEqual(["gemini-pro-agent"]);
527
- }),
528
- ),
493
+ Effect.gen(function* () {
494
+ const harness = yield* makeHarness();
495
+ yield* harness.initialize;
496
+ yield* harness.provider.onSessionStarted(started);
497
+ yield* harness.provider.onSignedOut;
498
+ yield* harness.provider.onSessionStarted({
499
+ ...started,
500
+ sessionSetupResult: {
501
+ sessionId: "new-account-session",
502
+ configOptions: [
503
+ { ...modelConfig, currentValue: "gemini-pro-agent", options: [modelOptions[9]!] },
504
+ ],
505
+ },
506
+ });
507
+ expect(
508
+ (yield* harness.provider.snapshot.getSnapshot).models.map((model) => model.slug),
509
+ ).toEqual(["gemini-pro-agent"]);
510
+ }),
511
);
512
513
it.effect("retains known account metadata when a local health check fails", () =>
532
- Effect.scoped(
533
- Effect.gen(function* () {
534
- const harness = yield* makeHarness();
535
- yield* harness.initialize;
514
+ Effect.gen(function* () {
515
+ const harness = yield* makeHarness();
516
+ yield* harness.initialize;
517
+ yield* harness.provider.onSessionStarted(started, "/workspace");
518
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
519
+ yield* Ref.set(
520
+ harness.probe,
521
+ Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")),
522
+ );
523
+ const snapshot = yield* harness.provider.snapshot.refresh;
524
+ expect(snapshot).toMatchObject({
525
+ installed: true,
526
+ status: "error",
527
+ auth: { status: "authenticated" },
528
+ });
529
+ expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
530
+ expect(snapshot.slashCommands).toEqual(expectedCommands);
531
+ expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace");
532
+ }),
533
+ );
534
+
535
+ it.effect("distinguishes missing executables from a failed installed executable", () =>
536
+ Effect.gen(function* () {
537
+ const harness = yield* makeHarness();
538
+ yield* harness.initialize;
539
+ const failures = [
540
+ {
541
+ error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }),
542
+ installed: false,
543
+ },
544
+ {
545
+ error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }),
546
+ installed: true,
547
+ },
548
+ {
549
+ error: new ProviderSetupError({
550
+ instanceId,
551
+ operation: "resolve",
552
+ detail: "Antigravity is not installed.",
553
+ }),
554
+ installed: false,
555
+ },
556
+ ];
557
+ for (const { error, installed } of failures) {
558
yield* harness.provider.onSessionStarted(started, "/workspace");
559
yield* harness.provider.onAvailableCommands(commands, "/workspace");
538
- yield* Ref.set(
539
- harness.probe,
540
- Effect.fail(EffectAcpErrors.AcpRequestError.internalError("probe failed")),
541
- );
560
+ yield* Ref.set(harness.probe, Effect.fail(error));
561
const snapshot = yield* harness.provider.snapshot.refresh;
562
expect(snapshot).toMatchObject({
544
- installed: true,
563
+ installed,
564
status: "error",
565
auth: { status: "authenticated" },
566
});
548
- expect(snapshot.models).toEqual(buildAntigravityModelsFromSession(sessionSetupResult));
549
- expect(snapshot.slashCommands).toEqual(expectedCommands);
550
- expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace");
551
- }),
552
- ),
553
- );
554
-
555
- it.effect("distinguishes missing executables from a failed installed executable", () =>
556
- Effect.scoped(
557
- Effect.gen(function* () {
558
- const harness = yield* makeHarness();
559
- yield* harness.initialize;
560
- const failures = [
561
- {
562
- error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "ENOENT" } }),
563
- installed: false,
564
- },
565
- {
566
- error: new EffectAcpErrors.AcpSpawnError({ cause: { code: "EACCES" } }),
567
- installed: true,
568
- },
569
- {
570
- error: new ProviderSetupError({
571
- instanceId,
572
- operation: "resolve",
573
- detail: "Antigravity is not installed.",
574
- }),
575
- installed: false,
576
- },
577
- ];
578
- for (const { error, installed } of failures) {
579
- yield* harness.provider.onSessionStarted(started, "/workspace");
580
- yield* harness.provider.onAvailableCommands(commands, "/workspace");
581
- yield* Ref.set(harness.probe, Effect.fail(error));
582
- const snapshot = yield* harness.provider.snapshot.refresh;
583
- expect(snapshot).toMatchObject({
584
- installed,
585
- status: "error",
586
- auth: { status: "authenticated" },
587
- });
588
- expect(snapshot.models).toHaveLength(installed ? 11 : 0);
589
- expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0);
590
- expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0);
591
- expect(snapshot.supportsTextGeneration).toBe(installed);
592
- }
593
- }),
594
- ),
567
+ expect(snapshot.models).toHaveLength(installed ? 11 : 0);
568
+ expect(snapshot.slashCommands).toHaveLength(installed ? 2 : 0);
569
+ expect(snapshot.workspaceSnapshots).toHaveLength(installed ? 1 : 0);
570
+ expect(snapshot.supportsTextGeneration).toBe(installed);
571
+ }
572
+ }),
573
);
574
575
it.effect("does not let an old health result restore a signed-out account", () =>
598
- Effect.scoped(
599
- Effect.gen(function* () {
600
- const harness = yield* makeHarness();
601
- yield* harness.initialize;
602
- yield* harness.provider.onSessionStarted(started);
603
- const releaseProbe = yield* Deferred.make<EffectAcpSchema.InitializeResponse>();
604
- const probeEntered = yield* Deferred.make<void>();
605
- yield* Ref.set(
606
- harness.probe,
607
- Deferred.succeed(probeEntered, undefined).pipe(
608
- Effect.andThen(Deferred.await(releaseProbe)),
609
- ),
610
- );
611
- const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
612
- yield* Deferred.await(probeEntered);
613
- yield* harness.provider.onSignedOut;
614
- yield* Deferred.succeed(releaseProbe, initializeResult);
615
- const snapshot = yield* Fiber.join(refresh);
616
- expect(snapshot).toMatchObject({
617
- auth: { status: "unauthenticated" },
618
- models: [],
619
- supportsTextGeneration: false,
620
- });
621
- }),
622
- ),
576
+ Effect.gen(function* () {
577
+ const harness = yield* makeHarness();
578
+ yield* harness.initialize;
579
+ yield* harness.provider.onSessionStarted(started);
580
+ const releaseProbe = yield* Deferred.make<EffectAcpSchema.InitializeResponse>();
581
+ const probeEntered = yield* Deferred.make<void>();
582
+ yield* Ref.set(
583
+ harness.probe,
584
+ Deferred.succeed(probeEntered, undefined).pipe(
585
+ Effect.andThen(Deferred.await(releaseProbe)),
586
+ ),
587
+ );
588
+ const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
589
+ yield* Deferred.await(probeEntered);
590
+ yield* harness.provider.onSignedOut;
591
+ yield* Deferred.succeed(releaseProbe, initializeResult);
592
+ const snapshot = yield* Fiber.join(refresh);
593
+ expect(snapshot).toMatchObject({
594
+ auth: { status: "unauthenticated" },
595
+ models: [],
596
+ supportsTextGeneration: false,
597
+ });
598
+ }),
599
);
600
601
it.effect("exposes helper support only when the supplied safety check allows it", () =>
626
- Effect.scoped(
627
- Effect.gen(function* () {
628
- const harness = yield* makeHarness({ safe: false });
629
- yield* harness.initialize;
630
- yield* harness.provider.onSessionStarted(started);
631
- expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false);
632
- yield* Ref.set(harness.safety, Effect.succeed(true));
633
- yield* harness.provider.snapshot.refresh;
634
- expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true);
635
- }),
636
- ),
602
+ Effect.gen(function* () {
603
+ const harness = yield* makeHarness({ safe: false });
604
+ yield* harness.initialize;
605
+ yield* harness.provider.onSessionStarted(started);
606
+ expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(false);
607
+ yield* Ref.set(harness.safety, Effect.succeed(true));
608
+ yield* harness.provider.snapshot.refresh;
609
+ expect((yield* harness.provider.snapshot.getSnapshot).supportsTextGeneration).toBe(true);
610
+ }),
611
);
612
613
it.effect("keeps discovered workspace skills through session and command updates", () =>
640
- Effect.scoped(
641
- Effect.gen(function* () {
642
- const harness = yield* makeHarness();
643
- yield* harness.initialize;
644
- const skills = [
645
- {
646
- name: "deploy",
647
- description: "Ship it",
648
- path: "/workspace/.agent/skills/deploy",
649
- enabled: true,
650
- },
651
- ];
652
- const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills);
653
- expect(discovered.skills).toEqual(skills);
654
- yield* harness.provider.onSessionStarted(started, "/workspace");
655
- yield* harness.provider.onAvailableCommands(commands, "/workspace");
656
- const after = yield* harness.provider.snapshot.getSnapshot;
657
- expect(
658
- after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills,
659
- ).toEqual(skills);
660
- expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills);
661
-
662
- const rescanned = [
663
- ...skills,
664
- { name: "review", path: "/workspace/.agent/skills/review", enabled: true },
665
- ];
666
- yield* harness.provider.snapshotForCwd("/workspace", rescanned);
667
- yield* harness.provider.onSessionStarted(started, "/workspace");
668
- expect(
669
- (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find(
670
- (entry) => entry.cwd === "/workspace",
671
- )?.skills,
672
- ).toEqual(rescanned);
673
- }),
674
- ),
614
+ Effect.gen(function* () {
615
+ const harness = yield* makeHarness();
616
+ yield* harness.initialize;
617
+ const skills = [
618
+ {
619
+ name: "deploy",
620
+ description: "Ship it",
621
+ path: "/workspace/.agent/skills/deploy",
622
+ enabled: true,
623
+ },
624
+ ];
625
+ const discovered = yield* harness.provider.snapshotForCwd("/workspace", skills);
626
+ expect(discovered.skills).toEqual(skills);
627
+ yield* harness.provider.onSessionStarted(started, "/workspace");
628
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
629
+ const after = yield* harness.provider.snapshot.getSnapshot;
630
+ expect(after.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace")?.skills).toEqual(
631
+ skills,
632
+ );
633
+ expect((yield* harness.provider.snapshotForCwd("/workspace")).skills).toEqual(skills);
634
+
635
+ const rescanned = [
636
+ ...skills,
637
+ { name: "review", path: "/workspace/.agent/skills/review", enabled: true },
638
+ ];
639
+ yield* harness.provider.snapshotForCwd("/workspace", rescanned);
640
+ yield* harness.provider.onSessionStarted(started, "/workspace");
641
+ expect(
642
+ (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find(
643
+ (entry) => entry.cwd === "/workspace",
644
+ )?.skills,
645
+ ).toEqual(rescanned);
646
+ }),
647
);
648
649
it.effect("bounds workspace metadata without starting sessions for workspace lookup", () =>
678
- Effect.scoped(
679
- Effect.gen(function* () {
680
- const harness = yield* makeHarness();
681
- yield* harness.initialize;
682
- yield* harness.provider.onSessionStarted(started);
683
- for (let index = 0; index < 35; index++) {
684
- yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`);
685
- }
686
- const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34");
687
- expect(snapshot.workspaceSnapshots).toHaveLength(32);
688
- expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3");
689
- expect(snapshot.slashCommands).toEqual(expectedCommands);
690
- expect(yield* Ref.get(harness.probeCalls)).toBe(1);
691
- }),
692
- ),
650
+ Effect.gen(function* () {
651
+ const harness = yield* makeHarness();
652
+ yield* harness.initialize;
653
+ yield* harness.provider.onSessionStarted(started);
654
+ for (let index = 0; index < 35; index++) {
655
+ yield* harness.provider.onAvailableCommands(commands, `/workspace-${index}`);
656
+ }
657
+ const snapshot = yield* harness.provider.snapshotForCwd("/workspace-34");
658
+ expect(snapshot.workspaceSnapshots).toHaveLength(32);
659
+ expect(snapshot.workspaceSnapshots?.[0]?.cwd).toBe("/workspace-3");
660
+ expect(snapshot.slashCommands).toEqual(expectedCommands);
661
+ expect(yield* Ref.get(harness.probeCalls)).toBe(1);
662
+ }),
663
);
664
665
it.effect(
666
"publishes limits, retains a successful read on failure, and clears them on sign-out",
667
() =>
698
- Effect.scoped(
699
- Effect.gen(function* () {
700
- const limits: ServerProviderUsageLimits = {
701
- checkedAt: "2026-10-09T12:00:00.000Z",
702
- windows: [
703
- {
704
- id: "3p-weekly",
705
- kind: "weekly",
706
- label: "Claude & GPT (shared) · Weekly",
707
- usedPercent: 75,
708
- },
709
- ],
710
- };
711
- const usage = yield* Ref.make(limits);
712
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });
713
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
714
- yield* harness.initialize;
715
- expect((yield* published)?.usageLimits).toEqual(limits);
716
- // The second health check is the one the failed background read triggers.
717
- const checks = yield* Ref.make(0);
718
- const failedReadApplied = yield* Deferred.make<void>();
719
- yield* Ref.set(
720
- harness.probe,
721
- Ref.updateAndGet(checks, (count) => count + 1).pipe(
722
- Effect.tap((count) =>
723
- count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,
724
- ),
725
- Effect.as(initializeResult),
726
- ),
727
- );
728
- yield* Ref.set(usage, {
729
- checkedAt: "2026-10-09T12:01:00.000Z",
730
- windows: [],
731
- unavailable: { reason: "probeFailed" },
732
- });
733
- yield* harness.provider.snapshot.refresh;
734
- yield* Deferred.await(failedReadApplied);
735
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
736
- yield* harness.provider.onSignedOut;
737
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
738
- yield* Ref.set(usage, {
739
- checkedAt: "2026-10-09T12:02:00.000Z",
740
- windows: [],
741
- unavailable: { reason: "unsupported" },
742
- });
743
- const unsupported = yield* harness.nextPublish(
744
- (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
745
- );
746
- yield* harness.provider.snapshot.refresh;
747
- expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);
748
- }),
749
- ),
750
- );
751
-
752
- it.effect("a quota read finishing after sign-out cannot restore account limits", () =>
753
- Effect.scoped(
668
Effect.gen(function* () {
755
- const readStarted = yield* Deferred.make<void>();
756
- const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
757
- const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
758
- Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }),
759
- );
760
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
669
+ const limits: ServerProviderUsageLimits = {
670
+ checkedAt: "2026-10-09T12:00:00.000Z",
671
+ windows: [
672
+ {
673
+ id: "3p-weekly",
674
+ kind: "weekly",
675
+ label: "Claude & GPT (shared) · Weekly",
676
+ usedPercent: 75,
677
+ },
678
+ ],
679
+ };
680
+ const usage = yield* Ref.make(limits);
681
+ const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });
682
+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
683
yield* harness.initialize;
762
- yield* Ref.set(harness.probe, Effect.succeed(initializeResult));
684
+ expect((yield* published)?.usageLimits).toEqual(limits);
685
+ // The second health check is the one the failed background read triggers.
686
+ const checks = yield* Ref.make(0);
687
+ const failedReadApplied = yield* Deferred.make<void>();
688
yield* Ref.set(
764
- usage,
765
- Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))),
689
+ harness.probe,
690
+ Ref.updateAndGet(checks, (count) => count + 1).pipe(
691
+ Effect.tap((count) =>
692
+ count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,
693
+ ),
694
+ Effect.as(initializeResult),
695
+ ),
696
);
767
- const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
768
- yield* Deferred.await(readStarted);
769
- yield* harness.provider.onSignedOut;
770
- yield* Deferred.succeed(readResult, {
697
+ yield* Ref.set(usage, {
698
checkedAt: "2026-10-09T12:01:00.000Z",
772
- windows: [
773
- { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },
774
- ],
699
+ windows: [],
700
+ unavailable: { reason: "probeFailed" },
701
});
776
- yield* Fiber.join(refresh);
702
+ yield* harness.provider.snapshot.refresh;
703
+ yield* Deferred.await(failedReadApplied);
704
+ expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
705
+ yield* harness.provider.onSignedOut;
706
expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
707
+ yield* Ref.set(usage, {
708
+ checkedAt: "2026-10-09T12:02:00.000Z",
709
+ windows: [],
710
+ unavailable: { reason: "unsupported" },
711
+ });
712
+ const unsupported = yield* harness.nextPublish(
713
+ (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
714
+ );
715
+ yield* harness.provider.snapshot.refresh;
716
+ expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);
717
}),
779
- ),
718
+ );
719
+
720
+ it.effect("a quota read finishing after sign-out cannot restore account limits", () =>
721
+ Effect.gen(function* () {
722
+ const readStarted = yield* Deferred.make<void>();
723
+ const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
724
+ const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
725
+ Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }),
726
+ );
727
+ const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
728
+ yield* harness.initialize;
729
+ yield* Ref.set(harness.probe, Effect.succeed(initializeResult));
730
+ yield* Ref.set(
731
+ usage,
732
+ Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))),
733
+ );
734
+ const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
735
+ yield* Deferred.await(readStarted);
736
+ yield* harness.provider.onSignedOut;
737
+ yield* Deferred.succeed(readResult, {
738
+ checkedAt: "2026-10-09T12:01:00.000Z",
739
+ windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }],
740
+ });
741
+ yield* Fiber.join(refresh);
742
+ expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
743
+ }),
744
);
745
746
it.effect("reports ready and starts sessions while one shared quota read is pending", () =>
783
- Effect.scoped(
784
- Effect.gen(function* () {
785
- const reads = yield* Ref.make(0);
786
- const readStarted = yield* Deferred.make<void>();
787
- const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
788
- const harness = yield* makeHarness({
789
- probeUsage: Ref.update(reads, (count) => count + 1).pipe(
790
- Effect.andThen(Deferred.succeed(readStarted, undefined)),
791
- Effect.andThen(Deferred.await(readResult)),
792
- ),
793
- });
794
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
795
- yield* harness.initialize;
796
- yield* Deferred.await(readStarted);
797
- yield* harness.provider.onSessionStarted(started, "/workspace");
798
- yield* harness.provider.onSessionStarted(started, "/other");
799
- const ready = yield* harness.provider.snapshot.getSnapshot;
800
- expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });
801
- expect(ready.usageLimits).toBeUndefined();
802
- expect(yield* Ref.get(reads)).toBe(1);
803
- const limits = {
804
- checkedAt: "2026-10-09T12:00:00.000Z",
805
- windows: [
806
- { id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 },
807
- ],
808
- } satisfies ServerProviderUsageLimits;
809
- yield* Deferred.succeed(readResult, limits);
810
- expect((yield* published)?.usageLimits).toEqual(limits);
811
- }),
812
- ),
747
+ Effect.gen(function* () {
748
+ const reads = yield* Ref.make(0);
749
+ const readStarted = yield* Deferred.make<void>();
750
+ const readResult = yield* Deferred.make<ServerProviderUsageLimits>();
751
+ const harness = yield* makeHarness({
752
+ probeUsage: Ref.update(reads, (count) => count + 1).pipe(
753
+ Effect.andThen(Deferred.succeed(readStarted, undefined)),
754
+ Effect.andThen(Deferred.await(readResult)),
755
+ ),
756
+ });
757
+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
758
+ yield* harness.initialize;
759
+ yield* Deferred.await(readStarted);
760
+ yield* harness.provider.onSessionStarted(started, "/workspace");
761
+ yield* harness.provider.onSessionStarted(started, "/other");
762
+ const ready = yield* harness.provider.snapshot.getSnapshot;
763
+ expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });
764
+ expect(ready.usageLimits).toBeUndefined();
765
+ expect(yield* Ref.get(reads)).toBe(1);
766
+ const limits = {
767
+ checkedAt: "2026-10-09T12:00:00.000Z",
768
+ windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }],
769
+ } satisfies ServerProviderUsageLimits;
770
+ yield* Deferred.succeed(readResult, limits);
771
+ expect((yield* published)?.usageLimits).toEqual(limits);
772
+ }),
773
);
774
775
it.effect("a quota read for the previous account is dropped after a new sign-in", () =>
816
- Effect.scoped(
817
- Effect.gen(function* () {
818
- const oldReadStarted = yield* Deferred.make<void>();
819
- const newLimits = {
820
- checkedAt: "2026-10-09T12:01:00.000Z",
821
- windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],
822
- } satisfies ServerProviderUsageLimits;
823
- const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
824
- Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),
825
- );
826
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
827
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
828
- yield* harness.initialize;
829
- yield* Deferred.await(oldReadStarted);
830
- yield* Ref.set(usage, Effect.succeed(newLimits));
831
- yield* harness.provider.onSignedIn;
832
- yield* harness.provider.onSessionStarted(started);
833
- expect((yield* published)?.usageLimits).toEqual(newLimits);
834
- // Switching again must not republish the previous account's limits, even if the read fails.
835
- const failed = {
836
- checkedAt: "2026-10-09T12:02:00.000Z",
837
- windows: [],
838
- unavailable: { reason: "probeFailed" },
839
- } satisfies ServerProviderUsageLimits;
840
- yield* Ref.set(usage, Effect.succeed(failed));
841
- const republished = yield* harness.nextPublish(
842
- (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
843
- );
844
- yield* harness.provider.onSignedIn;
845
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
846
- yield* harness.provider.onSessionStarted(started);
847
- expect((yield* republished)?.usageLimits).toEqual(failed);
848
- }),
849
- ),
776
+ Effect.gen(function* () {
777
+ const oldReadStarted = yield* Deferred.make<void>();
778
+ const newLimits = {
779
+ checkedAt: "2026-10-09T12:01:00.000Z",
780
+ windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],
781
+ } satisfies ServerProviderUsageLimits;
782
+ const usage = yield* Ref.make<Effect.Effect<ServerProviderUsageLimits>>(
783
+ Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),
784
+ );
785
+ const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
786
+ const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
787
+ yield* harness.initialize;
788
+ yield* Deferred.await(oldReadStarted);
789
+ yield* Ref.set(usage, Effect.succeed(newLimits));
790
+ yield* harness.provider.onSignedIn;
791
+ yield* harness.provider.onSessionStarted(started);
792
+ expect((yield* published)?.usageLimits).toEqual(newLimits);
793
+ // Switching again must not republish the previous account's limits, even if the read fails.
794
+ const failed = {
795
+ checkedAt: "2026-10-09T12:02:00.000Z",
796
+ windows: [],
797
+ unavailable: { reason: "probeFailed" },
798
+ } satisfies ServerProviderUsageLimits;
799
+ yield* Ref.set(usage, Effect.succeed(failed));
800
+ const republished = yield* harness.nextPublish(
801
+ (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
802
+ );
803
+ yield* harness.provider.onSignedIn;
804
+ expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
805
+ yield* harness.provider.onSessionStarted(started);
806
+ expect((yield* republished)?.usageLimits).toEqual(failed);
807
+ }),
808
);
809
});
apps/server/src/provider/CodexThreadRevert.test.ts
-2
@@ -68,7 +68,6 @@ it.effect("finds the revert boundary across pages of newest-first turns", () =>
68
],
69
}),
70
),
71
- Effect.scoped,
71
),
72
);
73
@@ -87,6 +86,5 @@ it.effect("rejects repeated cursors instead of looping or reverting incomplete h
86
entries: [...page(1, null, 3, ["newest"], "again"), ...page(2, "again", 2, [], "again")],
87
}),
88
),
90
- Effect.scoped,
89
),
90
);
apps/server/src/provider/Drivers/AntigravityDriver.test.ts
+6
-6
@@ -444,7 +444,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
444
.map((request) => request.params?.value),
445
).toEqual(["default"]);
446
}
447
- }).pipe(Effect.scoped),
447
+ }),
448
);
449
450
it.effect.skipIf(windowsHost)(
@@ -464,7 +464,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
464
expect(h.acquisitions).toHaveLength(2);
465
expect(h.releases).toEqual([h.first.version, h.signedOut.version]);
466
yield* h.assertClosed;
467
- }).pipe(Effect.scoped),
467
+ }),
468
);
469
470
it.effect.skipIf(windowsHost)("keeps the previous catalog when executable resolution fails", () =>
@@ -481,7 +481,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
481
expect(h.acquisitions).toHaveLength(2);
482
expect(h.releases).toEqual([h.first.version]);
483
yield* h.assertClosed;
484
- }).pipe(Effect.scoped),
484
+ }),
485
);
486
487
it.effect.skipIf(windowsHost)(
@@ -502,7 +502,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
502
expect(after.models).toEqual(before.models);
503
expect(after.auth).toEqual(before.auth);
504
yield* h.assertClosed;
505
- }).pipe(Effect.scoped),
505
+ }),
506
);
507
508
it.effect.skipIf(windowsHost)(
@@ -539,7 +539,7 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
539
expect(after.auth).toEqual(before.auth);
540
expect(JSON.stringify(after)).not.toContain("sk-secret-123");
541
yield* h.assertClosed;
542
- }).pipe(Effect.scoped),
542
+ }),
543
);
544
545
it.effect.skipIf(windowsHost)(
@@ -577,6 +577,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
577
);
578
expect(yield* fs.exists(directories.runtimeTemp)).toBe(false);
579
expect(yield* fs.exists(legacyRoot)).toBe(false);
580
- }).pipe(Effect.scoped),
580
+ }),
581
);
582
});
apps/server/src/provider/Drivers/ClaudeMaintenance.test.ts
+5
-5
@@ -239,7 +239,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
239
);
240
yield* enrich;
241
expect(requests).toHaveLength(1);
242
- }).pipe(Effect.scoped),
242
+ }),
243
);
244
245
it.effect.each([
@@ -297,7 +297,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
297
);
298
yield* check;
299
expect(requests).toHaveLength(3);
300
- }).pipe(Effect.scoped),
300
+ }),
301
);
302
303
it.effect.each([
@@ -317,7 +317,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
317
),
318
);
319
expect((yield* resolve()).update?.lockKey).toBe(row.lockKey);
320
- }).pipe(Effect.scoped),
320
+ }),
321
);
322
323
it.effect("automatic refresh rereads the native channel while preserving both caches", () =>
@@ -403,7 +403,7 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
403
]);
404
expect(f.installationReads()).toBe(1);
405
}
406
- }).pipe(Effect.scoped),
406
+ }),
407
);
408
409
it.effect("bounds stalled feed bodies and skips disabled update checks", () =>
@@ -433,6 +433,6 @@ it.layer(NodeServices.layer)("ClaudeMaintenance", (it) => {
433
yield* TestClock.adjust("4 seconds");
434
expect((yield* Fiber.join(pending)).versionAdvisory?.status).toBe("unknown");
435
expect(requests).toBe(1);
436
- }).pipe(Effect.scoped),
436
+ }),
437
);
438
});
apps/server/src/provider/Drivers/CodexDriver.test.ts
+9
-24
@@ -374,10 +374,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
374
lockKey: "codex-native",
375
env: { CODEX_HOME: sharedHome },
376
});
377
- }).pipe(
378
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
379
- Effect.scoped,
380
- ),
377
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
378
);
379
380
it.effect.skipIf(windowsHost)(
@@ -431,10 +428,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
428
env: { CODEX_HOME: installHome },
429
});
430
}
434
- }).pipe(
435
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
436
- Effect.scoped,
437
- ),
431
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
432
);
433
434
it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () =>
@@ -478,7 +472,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
472
CODEX_HOME: fixture.home,
473
});
474
}
481
- }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
475
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
476
);
477
478
// regression: #23937 `codex update` installs the native channel's release, which can lag npm.
@@ -556,10 +550,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
550
maintenanceCapabilities: capabilities,
551
}).status,
552
).not.toBe("behind_latest");
559
- }).pipe(
560
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
561
- Effect.scoped,
562
- ),
553
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
554
);
555
556
it.effect("uses each instance's environment CODEX_HOME for continuation", () =>
@@ -577,7 +568,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
568
});
569
expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`);
570
}
580
- }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
571
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
572
);
573
574
it.effect.skipIf(windowsHost)(
@@ -606,10 +597,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
597
expect(yield* fs.readLink(NodePath.join(shadowHome, "sessions"))).toBe(
598
NodePath.join(codexHome, "sessions"),
599
);
609
- }).pipe(
610
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
611
- Effect.scoped,
612
- ),
600
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
601
);
602
603
for (const fixture of [
@@ -685,10 +673,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
673
} else {
674
expect(update).toBeNull();
675
}
688
- }).pipe(
689
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
690
- Effect.scoped,
691
- ),
676
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
677
);
678
}
679
@@ -837,7 +822,7 @@ it.layer(layerTest)("CodexDriver", (it) => {
822
} else {
823
expect(capabilities.update).toBeNull();
824
}
840
- }).pipe(Effect.scoped),
825
+ }),
826
{ skip: windowsHost },
827
);
828
@@ -888,6 +873,6 @@ it.layer(layerTest)("CodexDriver", (it) => {
873
yield* TestClock.adjust("250 millis");
874
875
yield* Queue.take(probes);
891
- }).pipe(Effect.scoped),
876
+ }),
877
);
878
});
apps/server/src/provider/GrokProvider.test.ts
+2
-2
@@ -639,7 +639,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount"
639
),
640
);
641
expect(limits.windows[0]?.usedPercent).toBe(37);
642
- }).pipe(Effect.scoped),
642
+ }),
643
);
644
645
it.effect(
@@ -749,7 +749,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("readGrokAccount"
749
message: "Grok could not read usage limits.",
750
});
751
}
752
- }).pipe(Effect.scoped),
752
+ }),
753
);
754
755
it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () =>
apps/server/src/provider/ProviderAuthService.test.ts
+3
-3
@@ -743,7 +743,7 @@ it.effect("queued logout prompts resolve the current controller after provider r
743
assert.isTrue(yield* Fiber.join(queued));
744
assert.isTrue(replacementLoggedOut);
745
assert.strictEqual(harness.actions.filter((action) => action === "native-logout").length, 1);
746
- }).pipe(Effect.scoped),
746
+ }),
747
);
748
749
it.effect.each(["start", "logout", "prompt"] as const)(
@@ -814,7 +814,7 @@ it.effect.each(["start", "logout", "prompt"] as const)(
814
const blocked = yield* Effect.flip(harness.service.logout({ instanceId }));
815
assert.include(blocked.detail, "shared sign-in");
816
assert.equal(replacementMutations, 0);
817
- }).pipe(Effect.scoped),
817
+ }),
818
);
819
820
it.effect.each(["selection", "drain"] as const)(
@@ -855,5 +855,5 @@ it.effect.each(["selection", "drain"] as const)(
855
assert.notInclude(harness.actions, "stop:peer-persisted");
856
assert.isFalse(harness.sessions.has(ThreadId.make("target-draining")));
857
assert.include(harness.actions, "native-logout");
858
- }).pipe(Effect.scoped),
858
+ }),
859
);
apps/server/src/provider/ProviderInstanceRegistry.test.ts
+8
-8
@@ -990,7 +990,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
990
{ name: "BASE_URL", value: "https://example.test", sensitive: false },
991
],
992
]);
993
- }).pipe(Effect.scoped);
993
+ });
994
});
995
996
// An empty secret must not let a driver fall back to a credential the server inherited.
@@ -1013,7 +1013,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1013
yield* mutator.reconcile({ ...fixture.configMap });
1014
expect(fixture.reads).toHaveLength(readsAtStartup);
1015
expect(yield* registry.listUnavailable).toHaveLength(1);
1016
- }).pipe(Effect.scoped);
1016
+ });
1017
});
1018
1019
it.effect("does not read the secrets of an instance its config decodes as disabled", () => {
@@ -1025,7 +1025,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1025
expect(fixture.reads).toEqual([]);
1026
expect(fixture.invalidated).toEqual([]);
1027
expect(fixture.created).toHaveLength(1);
1028
- }).pipe(Effect.scoped);
1028
+ });
1029
});
1030
1031
it.effect("re-reads secrets on reload and rebuilds only when they changed", () => {
@@ -1048,7 +1048,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1048
"sk-live",
1049
"sk-rotated",
1050
]);
1051
- }).pipe(Effect.scoped);
1051
+ });
1052
});
1053
1054
it.effect("reads a config field typed SettingsSecretValue and rebuilds when it rotates", () => {
@@ -1068,7 +1068,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1068
{ apiKey: "gw-live", model: "m" },
1069
{ apiKey: "gw-rotated", model: "m" },
1070
]);
1071
- }).pipe(Effect.scoped);
1071
+ });
1072
});
1073
1074
it.effect.each([
@@ -1084,7 +1084,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1084
return Effect.gen(function* () {
1085
yield* fixture.make;
1086
expect(fixture.configs).toEqual([expect.objectContaining({ [field]: "provider-live" })]);
1087
- }).pipe(Effect.scoped);
1087
+ });
1088
});
1089
1090
it.effect("keeps a working instance live when a reload cannot read its secret", () => {
@@ -1098,7 +1098,7 @@ describe("ProviderInstanceRegistry secret environment", () => {
1098
expect(yield* registry.getInstance(instanceId)).toBeDefined();
1099
expect(yield* registry.listUnavailable).toEqual([]);
1100
expect(fixture.created).toHaveLength(1);
1101
- }).pipe(Effect.scoped);
1101
+ });
1102
});
1103
1104
it.effect("starts without waiting for secrets to be read", () => {
@@ -1115,6 +1115,6 @@ describe("ProviderInstanceRegistry secret environment", () => {
1115
yield* PubSub.take(changes);
1116
expect(yield* registry.getInstance(instanceId)).toBeDefined();
1117
expect(yield* registry.listUnavailable).toEqual([]);
1118
- }).pipe(Effect.scoped);
1118
+ });
1119
});
1120
});
apps/server/src/provider/acp/AntigravitySessionFiles.test.ts
+1
-1
@@ -31,7 +31,7 @@ it.layer(NodeServices.layer)("retireAntigravityRuntimeTempDirs", (it) => {
31
32
yield* removeRetired;
33
expect((yield* fs.readDirectory(parent)).toSorted()).toEqual(["other-instance"]);
34
- }).pipe(Effect.scoped),
34
+ }),
35
);
36
37
it.effect(
apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts
+2
-2
@@ -158,7 +158,7 @@ describe("watchAntigravityPromptOutcome", () => {
158
code: "QUOTA_EXHAUSTED",
159
retryable: true,
160
});
161
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
161
+ }).pipe(Effect.provide(NodeServices.layer)),
162
);
163
164
it.effect("reads only this session's own unlinked log, and keeps a typed refusal", () =>
@@ -206,6 +206,6 @@ describe("watchAntigravityPromptOutcome", () => {
206
code: "QUOTA_EXHAUSTED",
207
retryable: true,
208
});
209
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
209
+ }).pipe(Effect.provide(NodeServices.layer)),
210
);
211
});
apps/server/src/provider/providerCompatibility.test.ts
+1
-1
@@ -325,5 +325,5 @@ it.effect("a remote policy refresh preserves a newer health result on the regist
325
),
326
),
327
);
328
- }).pipe(Effect.scoped),
328
+ }),
329
);
apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts
+179
-189
@@ -390,208 +390,198 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic
390
expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"],
391
},
392
])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) =>
393
- Effect.scoped(
394
- Effect.gen(function* () {
395
- const run = yield* startSingleBranchRun({
396
- repositoryName: "refused-head",
397
- reportedHead,
398
- refuseCommitFetch: false,
399
- prepare: (repositories, workspace) =>
400
- git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
401
- Effect.andThen(
402
- shadow === "none"
403
- ? Effect.void
404
- : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
405
- ),
406
- Effect.asVoid,
393
+ Effect.gen(function* () {
394
+ const run = yield* startSingleBranchRun({
395
+ repositoryName: "refused-head",
396
+ reportedHead,
397
+ refuseCommitFetch: false,
398
+ prepare: (repositories, workspace) =>
399
+ git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe(
400
+ Effect.andThen(
401
+ shadow === "none"
402
+ ? Effect.void
403
+ : git(workspace, [shadow, repositories.headSha.slice(0, 12), "HEAD"]),
404
),
408
- });
409
- const result = yield* run.settled;
410
- assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
411
- assert.strictEqual(result.run?._tag, "Failed");
412
- const detail = result.run?._tag === "Failed" ? result.run.detail : "";
413
- for (const part of expected) assert.include(detail, part);
414
- // Only the host's own head ref is tried.
415
- assert.notInclude(detail, "refs/merge-requests/");
416
- assert.deepStrictEqual(run.observed, []);
417
- assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
418
- const fs = yield* FileSystem.FileSystem;
419
- assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
420
- }),
421
- ),
405
+ Effect.asVoid,
406
+ ),
407
+ });
408
+ const result = yield* run.settled;
409
+ assert.isFalse(yield* Deferred.isDone(run.stored), "a guide was written");
410
+ assert.strictEqual(result.run?._tag, "Failed");
411
+ const detail = result.run?._tag === "Failed" ? result.run.detail : "";
412
+ for (const part of expected) assert.include(detail, part);
413
+ // Only the host's own head ref is tried.
414
+ assert.notInclude(detail, "refs/merge-requests/");
415
+ assert.deepStrictEqual(run.observed, []);
416
+ assert.isFalse(run.fetchedRefs.some((ref) => ref.startsWith("-")));
417
+ const fs = yield* FileSystem.FileSystem;
418
+ assert.isFalse(yield* fs.exists(`${run.repositories.root}/injected`));
419
+ }),
420
);
421
422
it.effect("measures only the PR change using the renamed verified remote's fetch URL", () =>
425
- Effect.scoped(
426
- Effect.gen(function* () {
427
- const repositories = yield* makeRepositories;
428
- const fork = `${repositories.root}/fork`;
429
- yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
430
- yield* git(fork, ["branch", "stack-base", "main~1"]);
431
- // The cached identity still names origin, which now belongs to the stale fork.
432
- yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
433
- yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
434
- yield* git(repositories.workspace, [
435
- "config",
436
- `url.${repositories.remote}.insteadOf`,
437
- "review-upstream:",
438
- ]);
439
- yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
440
- const changed = yield* Deferred.make<string>();
441
- const driver = yield* GitVcsDriver.GitVcsDriver;
442
- const stored = yield* Deferred.make<void>();
443
- const context = yield* Layer.build(
444
- makeLayer({
445
- ...repositories,
446
- stored,
447
- generate: (input) =>
448
- git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
449
- Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
450
- Effect.orDie,
451
- Effect.flatMap((names) => Deferred.succeed(changed, names)),
452
- Effect.as({ stops: [] }),
453
- ),
454
- }),
455
- );
456
- const service = Context.get(
457
- context,
458
- PullRequestReviewGuideService.PullRequestReviewGuideService,
459
- );
460
- yield* service.generate(reference);
461
- assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
462
- yield* Deferred.await(stored);
463
- const result = yield* service.get(reference);
464
- assert.strictEqual(result.guide?.headSha, repositories.headSha);
465
- assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
466
- }),
467
- ),
423
+ Effect.gen(function* () {
424
+ const repositories = yield* makeRepositories;
425
+ const fork = `${repositories.root}/fork`;
426
+ yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
427
+ yield* git(fork, ["branch", "stack-base", "main~1"]);
428
+ // The cached identity still names origin, which now belongs to the stale fork.
429
+ yield* git(repositories.workspace, ["remote", "rename", "origin", "upstream"]);
430
+ yield* git(repositories.workspace, ["remote", "add", "origin", fork]);
431
+ yield* git(repositories.workspace, [
432
+ "config",
433
+ `url.${repositories.remote}.insteadOf`,
434
+ "review-upstream:",
435
+ ]);
436
+ yield* git(repositories.workspace, ["remote", "set-url", "upstream", "review-upstream:"]);
437
+ const changed = yield* Deferred.make<string>();
438
+ const driver = yield* GitVcsDriver.GitVcsDriver;
439
+ const stored = yield* Deferred.make<void>();
440
+ const context = yield* Layer.build(
441
+ makeLayer({
442
+ ...repositories,
443
+ stored,
444
+ generate: (input) =>
445
+ git(input.cwd, ["diff", "--name-only", `${input.baseCommit}...HEAD`]).pipe(
446
+ Effect.provideService(GitVcsDriver.GitVcsDriver, driver),
447
+ Effect.orDie,
448
+ Effect.flatMap((names) => Deferred.succeed(changed, names)),
449
+ Effect.as({ stops: [] }),
450
+ ),
451
+ }),
452
+ );
453
+ const service = Context.get(
454
+ context,
455
+ PullRequestReviewGuideService.PullRequestReviewGuideService,
456
+ );
457
+ yield* service.generate(reference);
458
+ assert.strictEqual(yield* Deferred.await(changed), "feature.txt");
459
+ yield* Deferred.await(stored);
460
+ const result = yield* service.get(reference);
461
+ assert.strictEqual(result.guide?.headSha, repositories.headSha);
462
+ assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]);
463
+ }),
464
);
465
466
it.effect("keeps excerpts despite the checkout's diff driver and a failing hook", () =>
471
- Effect.scoped(
472
- Effect.gen(function* () {
473
- const repositories = yield* makeRepositories;
474
- const fs = yield* FileSystem.FileSystem;
475
- yield* fs.writeFileString(
476
- `${repositories.workspace}/.git/info/attributes`,
477
- "feature.txt diff=blank\n",
478
- );
479
- yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]);
480
- const hook = `${repositories.workspace}/.git/hooks/post-checkout`;
481
- yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n");
482
- yield* fs.chmod(hook, 0o755);
483
- const stored = yield* Deferred.make<void>();
484
- const context = yield* Layer.build(
485
- makeLayer({
486
- ...repositories,
487
- stored,
488
- generate: () =>
489
- Effect.succeed({
490
- stops: [
491
- {
492
- title: "The feature",
493
- summary: "The change.",
494
- attention: null,
495
- excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }],
496
- files: [],
497
- notes: [],
498
- questions: [],
499
- },
500
- ],
501
- }),
502
- }),
503
- );
504
- const service = Context.get(
505
- context,
506
- PullRequestReviewGuideService.PullRequestReviewGuideService,
507
- );
508
- const runs = yield* watchRuns;
509
- yield* runs.generate(service, reference);
510
- const result = yield* runs.settled(service, reference);
511
- assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run));
512
- assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [
513
- { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" },
514
- ]);
515
- }),
516
- ),
467
+ Effect.gen(function* () {
468
+ const repositories = yield* makeRepositories;
469
+ const fs = yield* FileSystem.FileSystem;
470
+ yield* fs.writeFileString(
471
+ `${repositories.workspace}/.git/info/attributes`,
472
+ "feature.txt diff=blank\n",
473
+ );
474
+ yield* git(repositories.workspace, ["config", "diff.blank.textconv", "true"]);
475
+ const hook = `${repositories.workspace}/.git/hooks/post-checkout`;
476
+ yield* fs.writeFileString(hook, "#!/bin/sh\nexit 1\n");
477
+ yield* fs.chmod(hook, 0o755);
478
+ const stored = yield* Deferred.make<void>();
479
+ const context = yield* Layer.build(
480
+ makeLayer({
481
+ ...repositories,
482
+ stored,
483
+ generate: () =>
484
+ Effect.succeed({
485
+ stops: [
486
+ {
487
+ title: "The feature",
488
+ summary: "The change.",
489
+ attention: null,
490
+ excerpts: [{ path: "feature.txt", side: "new", start: 1, end: 3, caption: "" }],
491
+ files: [],
492
+ notes: [],
493
+ questions: [],
494
+ },
495
+ ],
496
+ }),
497
+ }),
498
+ );
499
+ const service = Context.get(
500
+ context,
501
+ PullRequestReviewGuideService.PullRequestReviewGuideService,
502
+ );
503
+ const runs = yield* watchRuns;
504
+ yield* runs.generate(service, reference);
505
+ const result = yield* runs.settled(service, reference);
506
+ assert.notStrictEqual(result.run?._tag, "Failed", JSON.stringify(result.run));
507
+ assert.deepStrictEqual(result.guide?.stops[0]?.excerpts, [
508
+ { path: "feature.txt", side: "new", start: 1, end: 3, caption: "" },
509
+ ]);
510
+ }),
511
);
512
513
it.effect("refuses generation when the verified remote disappeared despite a usable origin", () =>
520
- Effect.scoped(
521
- Effect.gen(function* () {
522
- const repositories = yield* makeRepositories;
523
- const fork = `${repositories.root}/fork`;
524
- yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
525
- yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
526
- yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
527
- const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
528
- const stored = yield* Deferred.make<void>();
529
- const generated = yield* Ref.make(false);
530
- const driver = yield* GitVcsDriver.GitVcsDriver;
531
- const context = yield* Layer.build(
532
- makeLayer({
533
- ...repositories,
534
- stored,
535
- generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
536
- }).pipe(
537
- Layer.provide(
538
- Layer.succeed(GitVcsDriver.GitVcsDriver, {
539
- ...driver,
540
- execute: (call) =>
541
- Effect.withFiber((fiber) =>
542
- Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
543
- ),
544
- }),
545
- ),
514
+ Effect.gen(function* () {
515
+ const repositories = yield* makeRepositories;
516
+ const fork = `${repositories.root}/fork`;
517
+ yield* git(repositories.root, ["clone", "--quiet", repositories.remote, fork]);
518
+ yield* git(fork, ["branch", "stack-base", repositories.lowerSha]);
519
+ yield* git(repositories.workspace, ["remote", "set-url", "origin", fork]);
520
+ const started = yield* Deferred.make<Fiber.Fiber<unknown, unknown>>();
521
+ const stored = yield* Deferred.make<void>();
522
+ const generated = yield* Ref.make(false);
523
+ const driver = yield* GitVcsDriver.GitVcsDriver;
524
+ const context = yield* Layer.build(
525
+ makeLayer({
526
+ ...repositories,
527
+ stored,
528
+ generate: () => Ref.set(generated, true).pipe(Effect.as({ stops: [] })),
529
+ }).pipe(
530
+ Layer.provide(
531
+ Layer.succeed(GitVcsDriver.GitVcsDriver, {
532
+ ...driver,
533
+ execute: (call) =>
534
+ Effect.withFiber((fiber) =>
535
+ Deferred.succeed(started, fiber).pipe(Effect.andThen(driver.execute(call))),
536
+ ),
537
+ }),
538
),
547
- );
548
- const service = Context.get(
549
- context,
550
- PullRequestReviewGuideService.PullRequestReviewGuideService,
551
- );
552
- const before = yield* service.get(reference);
553
- yield* service.generate(reference);
554
- // Join the background run so its failure is visible without polling service state.
555
- yield* Fiber.await(yield* Deferred.await(started));
556
- const result = yield* service.get(reference);
557
- assert.strictEqual(result.run?._tag, "Failed");
558
- assert.include(
559
- result.run?._tag === "Failed" ? result.run.detail : "",
560
- "no longer has a remote for the pull request's repository",
561
- );
562
- assert.deepStrictEqual(result.guide, before.guide);
563
- assert.isFalse(yield* Deferred.isDone(stored));
564
- assert.isFalse(yield* Ref.get(generated));
565
- }),
566
- ),
539
+ ),
540
+ );
541
+ const service = Context.get(
542
+ context,
543
+ PullRequestReviewGuideService.PullRequestReviewGuideService,
544
+ );
545
+ const before = yield* service.get(reference);
546
+ yield* service.generate(reference);
547
+ // Join the background run so its failure is visible without polling service state.
548
+ yield* Fiber.await(yield* Deferred.await(started));
549
+ const result = yield* service.get(reference);
550
+ assert.strictEqual(result.run?._tag, "Failed");
551
+ assert.include(
552
+ result.run?._tag === "Failed" ? result.run.detail : "",
553
+ "no longer has a remote for the pull request's repository",
554
+ );
555
+ assert.deepStrictEqual(result.guide, before.guide);
556
+ assert.isFalse(yield* Deferred.isDone(stored));
557
+ assert.isFalse(yield* Ref.get(generated));
558
+ }),
559
);
560
561
it.effect("refuses a pull request from a repository the project is not a checkout of", () =>
570
- Effect.scoped(
571
- Effect.gen(function* () {
572
- const repositories = yield* makeRepositories;
573
- const stored = yield* Deferred.make<void>();
574
- const context = yield* Layer.build(
575
- makeLayer({
576
- ...repositories,
577
- stored,
578
- identity: {
579
- ...ACME_APP,
580
- canonicalKey: "github.com/acme/other",
581
- displayName: "acme/other",
582
- name: "other",
583
- },
584
- generate: () =>
585
- Effect.die("a guide must not be written from another repository's checkout"),
586
- }),
587
- );
588
- const service = Context.get(
589
- context,
590
- PullRequestReviewGuideService.PullRequestReviewGuideService,
591
- );
592
- const result = yield* Effect.flip(service.generate(reference));
593
- assert.include(result.message, "in another repository");
594
- }),
595
- ),
562
+ Effect.gen(function* () {
563
+ const repositories = yield* makeRepositories;
564
+ const stored = yield* Deferred.make<void>();
565
+ const context = yield* Layer.build(
566
+ makeLayer({
567
+ ...repositories,
568
+ stored,
569
+ identity: {
570
+ ...ACME_APP,
571
+ canonicalKey: "github.com/acme/other",
572
+ displayName: "acme/other",
573
+ name: "other",
574
+ },
575
+ generate: () =>
576
+ Effect.die("a guide must not be written from another repository's checkout"),
577
+ }),
578
+ );
579
+ const service = Context.get(
580
+ context,
581
+ PullRequestReviewGuideService.PullRequestReviewGuideService,
582
+ );
583
+ const result = yield* Effect.flip(service.generate(reference));
584
+ assert.include(result.message, "in another repository");
585
+ }),
586
);
587
});
apps/server/src/pullRequest/PullRequestService.test.ts
+190
-208
@@ -1429,174 +1429,160 @@ it.effect(
1429
);
1430
1431
it.effect("publishes a merge for immediate settlement only after host confirmation", () =>
1432
- Effect.scoped(
1433
- Effect.gen(function* () {
1434
- const mergedAt = "2026-09-03T02:00:00.000Z";
1435
- let state: "open" | "merged" = "open";
1436
- let confirmationFails = false;
1437
- const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1438
- const service = yield* makeService({
1439
- projects: [
1440
- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1441
- ],
1442
- providers: [
1443
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1444
- getChangeRequestSummary: () =>
1445
- confirmationFails
1446
- ? Effect.fail(
1447
- new PullRequestProviderError({
1448
- provider: SourceControlProviderKind.make("github"),
1449
- operation: "getChangeRequestSummary",
1450
- reason: "failed",
1451
- detail: "HTTP 504",
1452
- }),
1453
- )
1454
- : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }),
1455
- }),
1456
- ],
1457
- });
1458
- const merges = yield* service.subscribeMerges;
1459
- const observedMerge = yield* Stream.runHead(merges).pipe(
1460
- Effect.forkChild({ startImmediately: true }),
1461
- );
1432
+ Effect.gen(function* () {
1433
+ const mergedAt = "2026-09-03T02:00:00.000Z";
1434
+ let state: "open" | "merged" = "open";
1435
+ let confirmationFails = false;
1436
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1437
+ const service = yield* makeService({
1438
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1439
+ providers: [
1440
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1441
+ getChangeRequestSummary: () =>
1442
+ confirmationFails
1443
+ ? Effect.fail(
1444
+ new PullRequestProviderError({
1445
+ provider: SourceControlProviderKind.make("github"),
1446
+ operation: "getChangeRequestSummary",
1447
+ reason: "failed",
1448
+ detail: "HTTP 504",
1449
+ }),
1450
+ )
1451
+ : Effect.succeed({ ...changeRequest(1, mergedAt), state, mergedAt }),
1452
+ }),
1453
+ ],
1454
+ });
1455
+ const merges = yield* service.subscribeMerges;
1456
+ const observedMerge = yield* Stream.runHead(merges).pipe(
1457
+ Effect.forkChild({ startImmediately: true }),
1458
+ );
1459
1463
- assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1464
- const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes));
1465
- confirmationFails = true;
1466
- yield* service.runAction({ ...reference, action: "merge" });
1467
- assert.isAbove(
1468
- Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)),
1469
- queuedRefresh,
1470
- );
1471
- confirmationFails = false;
1472
- state = "merged";
1473
- // The event carries the host's merge time, not the moment the confirmation ran.
1474
- yield* TestClock.setTime(Date.parse(mergedAt) + 60_000);
1475
- yield* service.runAction({
1476
- ...reference,
1477
- repository: " ACME/WEB ",
1478
- action: "merge",
1479
- mergeMethod: "merge",
1480
- });
1460
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1461
+ const queuedRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes));
1462
+ confirmationFails = true;
1463
+ yield* service.runAction({ ...reference, action: "merge" });
1464
+ assert.isAbove(
1465
+ Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)),
1466
+ queuedRefresh,
1467
+ );
1468
+ confirmationFails = false;
1469
+ state = "merged";
1470
+ // The event carries the host's merge time, not the moment the confirmation ran.
1471
+ yield* TestClock.setTime(Date.parse(mergedAt) + 60_000);
1472
+ yield* service.runAction({
1473
+ ...reference,
1474
+ repository: " ACME/WEB ",
1475
+ action: "merge",
1476
+ mergeMethod: "merge",
1477
+ });
1478
1482
- assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
1483
- ...reference,
1484
- mergedAt,
1485
- });
1486
- }),
1487
- ),
1479
+ assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
1480
+ ...reference,
1481
+ mergedAt,
1482
+ });
1483
+ }),
1484
);
1485
1486
it.effect("returns the host's merged reply as a summary and trusts it without another read", () =>
1491
- Effect.scoped(
1492
- Effect.gen(function* () {
1493
- const mergedAt = "2026-09-03T02:00:00.000Z";
1494
- const merged = {
1495
- number: 1,
1496
- title: "Change request 1",
1497
- url: "https://host/pull/1",
1498
- headBranch: "feat/1",
1499
- baseBranch: "main",
1500
- state: "merged" as const,
1501
- isDraft: false,
1502
- updatedAt: mergedAt,
1503
- mergedAt,
1504
- headSha: "abc123",
1505
- autoMergeEnabled: false,
1506
- };
1507
- let summaryReads = 0;
1508
- const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1509
- const service = yield* makeService({
1510
- projects: [
1511
- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1512
- ],
1513
- providers: [
1514
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1515
- runAction: () => Effect.succeed(merged),
1516
- getChangeRequestSummary: () =>
1517
- Effect.sync(() => {
1518
- summaryReads++;
1519
- return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt };
1520
- }),
1521
- }),
1522
- ],
1523
- });
1524
- const merges = yield* service.subscribeMerges;
1525
- const observedMerge = yield* Stream.runHead(merges).pipe(
1526
- Effect.forkChild({ startImmediately: true }),
1527
- );
1528
- const observedAt = Date.parse("2026-09-03T02:00:01.000Z");
1529
- yield* TestClock.setTime(observedAt);
1530
-
1531
- // Clients that did not ask decode the success as void, so they must get nothing back.
1532
- assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1533
- const result = yield* service.runAction({
1534
- ...reference,
1535
- action: "merge",
1536
- replyWithSummary: true,
1537
- });
1487
+ Effect.gen(function* () {
1488
+ const mergedAt = "2026-09-03T02:00:00.000Z";
1489
+ const merged = {
1490
+ number: 1,
1491
+ title: "Change request 1",
1492
+ url: "https://host/pull/1",
1493
+ headBranch: "feat/1",
1494
+ baseBranch: "main",
1495
+ state: "merged" as const,
1496
+ isDraft: false,
1497
+ updatedAt: mergedAt,
1498
+ mergedAt,
1499
+ headSha: "abc123",
1500
+ autoMergeEnabled: false,
1501
+ };
1502
+ let summaryReads = 0;
1503
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1504
+ const service = yield* makeService({
1505
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1506
+ providers: [
1507
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1508
+ runAction: () => Effect.succeed(merged),
1509
+ getChangeRequestSummary: () =>
1510
+ Effect.sync(() => {
1511
+ summaryReads++;
1512
+ return { ...changeRequest(1, mergedAt), state: "merged" as const, mergedAt };
1513
+ }),
1514
+ }),
1515
+ ],
1516
+ });
1517
+ const merges = yield* service.subscribeMerges;
1518
+ const observedMerge = yield* Stream.runHead(merges).pipe(
1519
+ Effect.forkChild({ startImmediately: true }),
1520
+ );
1521
+ const observedAt = Date.parse("2026-09-03T02:00:01.000Z");
1522
+ yield* TestClock.setTime(observedAt);
1523
1539
- assert.deepStrictEqual(result, {
1540
- ...merged,
1541
- provider: SourceControlProviderKind.make("github"),
1542
- projectId: reference.projectId,
1543
- repository: reference.repository,
1544
- observedAt,
1545
- });
1546
- assert.strictEqual(summaryReads, 0);
1547
- assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
1548
- ...reference,
1549
- mergedAt,
1550
- });
1551
- }),
1552
- ),
1524
+ // Clients that did not ask decode the success as void, so they must get nothing back.
1525
+ assert.isUndefined(yield* service.runAction({ ...reference, action: "merge" }));
1526
+ const result = yield* service.runAction({
1527
+ ...reference,
1528
+ action: "merge",
1529
+ replyWithSummary: true,
1530
+ });
1531
+
1532
+ assert.deepStrictEqual(result, {
1533
+ ...merged,
1534
+ provider: SourceControlProviderKind.make("github"),
1535
+ projectId: reference.projectId,
1536
+ repository: reference.repository,
1537
+ observedAt,
1538
+ });
1539
+ assert.strictEqual(summaryReads, 0);
1540
+ assert.deepStrictEqual(Option.getOrThrow(yield* Fiber.join(observedMerge)), {
1541
+ ...reference,
1542
+ mergedAt,
1543
+ });
1544
+ }),
1545
);
1546
1547
it.effect("refreshes every reader before a queued merge confirmation finishes", () =>
1556
- Effect.scoped(
1557
- Effect.gen(function* () {
1558
- const confirmationStarted = yield* Deferred.make<void>();
1559
- const confirm = yield* Deferred.make<void>();
1560
- const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1561
- const service = yield* makeService({
1562
- projects: [
1563
- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
1564
- ],
1565
- providers: [
1566
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1567
- getChangeRequestSummary: () =>
1568
- Effect.gen(function* () {
1569
- yield* Deferred.succeed(confirmationStarted, undefined);
1570
- yield* Deferred.await(confirm);
1571
- return changeRequest(1, "2026-09-16T00:00:00.000Z");
1572
- }),
1573
- }),
1574
- ],
1575
- });
1576
- const merges = yield* service.subscribeMerges;
1577
- const observedMerge = yield* Stream.runHead(merges).pipe(
1578
- Effect.forkChild({ startImmediately: true }),
1579
- );
1580
- const readers = yield* Effect.forEach([0, 1], () =>
1581
- Stream.runHead(service.subscribeRefreshes).pipe(
1582
- Effect.forkChild({ startImmediately: true }),
1583
- ),
1584
- );
1585
- const action = yield* service
1586
- .runAction({ ...reference, action: "merge" })
1587
- .pipe(Effect.forkChild({ startImmediately: true }));
1588
- yield* Deferred.await(confirmationStarted);
1589
- const revisions = yield* Effect.forEach(readers, (reader) =>
1590
- Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)),
1591
- );
1592
- assert.isAbove(revisions[0]!, 0);
1593
- assert.strictEqual(revisions[0], revisions[1]);
1594
- assert.isUndefined(action.pollUnsafe());
1595
- yield* Deferred.succeed(confirm, undefined);
1596
- yield* Fiber.join(action);
1597
- assert.isUndefined(observedMerge.pollUnsafe());
1598
- }),
1599
- ),
1548
+ Effect.gen(function* () {
1549
+ const confirmationStarted = yield* Deferred.make<void>();
1550
+ const confirm = yield* Deferred.make<void>();
1551
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
1552
+ const service = yield* makeService({
1553
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
1554
+ providers: [
1555
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
1556
+ getChangeRequestSummary: () =>
1557
+ Effect.gen(function* () {
1558
+ yield* Deferred.succeed(confirmationStarted, undefined);
1559
+ yield* Deferred.await(confirm);
1560
+ return changeRequest(1, "2026-09-16T00:00:00.000Z");
1561
+ }),
1562
+ }),
1563
+ ],
1564
+ });
1565
+ const merges = yield* service.subscribeMerges;
1566
+ const observedMerge = yield* Stream.runHead(merges).pipe(
1567
+ Effect.forkChild({ startImmediately: true }),
1568
+ );
1569
+ const readers = yield* Effect.forEach([0, 1], () =>
1570
+ Stream.runHead(service.subscribeRefreshes).pipe(Effect.forkChild({ startImmediately: true })),
1571
+ );
1572
+ const action = yield* service
1573
+ .runAction({ ...reference, action: "merge" })
1574
+ .pipe(Effect.forkChild({ startImmediately: true }));
1575
+ yield* Deferred.await(confirmationStarted);
1576
+ const revisions = yield* Effect.forEach(readers, (reader) =>
1577
+ Fiber.join(reader).pipe(Effect.map(Option.getOrThrow)),
1578
+ );
1579
+ assert.isAbove(revisions[0]!, 0);
1580
+ assert.strictEqual(revisions[0], revisions[1]);
1581
+ assert.isUndefined(action.pollUnsafe());
1582
+ yield* Deferred.succeed(confirm, undefined);
1583
+ yield* Fiber.join(action);
1584
+ assert.isUndefined(observedMerge.pollUnsafe());
1585
+ }),
1586
);
1587
1588
it.effect("runs branch deletion only when the host and viewer support it, never for a stack", () =>
@@ -2864,56 +2850,52 @@ it.effect("a read during a refresh cannot keep the provider's old change request
2850
);
2851
2852
it.effect("close and reopen notify subscribed readers after invalidating their cached state", () =>
2867
- Effect.scoped(
2868
- Effect.gen(function* () {
2869
- let hostCalls = 0;
2870
- let state: "open" | "closed" = "open";
2871
- const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
2872
- const service = yield* makeService({
2873
- projects: [
2874
- project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }),
2875
- ],
2876
- providers: [
2877
- fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2878
- getChangeRequestSummary: () =>
2879
- Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }),
2880
- runAction: (input) =>
2881
- Effect.sync(() => {
2882
- state = input.action === "close" ? "closed" : "open";
2883
- }),
2884
- listChangeRequests: () => {
2885
- hostCalls += 1;
2886
- return Effect.succeed({ items: [], truncated: false, continues: false });
2887
- },
2888
- }),
2889
- ],
2890
- });
2891
-
2892
- yield* service.refreshAfterTurn(reference.projectId);
2893
- yield* service.list({ state: "open" });
2894
- assert.strictEqual((yield* service.summary(reference)).state, "open");
2895
- for (const action of ["close", "reopen"] as const) {
2896
- const refreshed = yield* service.subscribeRefreshes.pipe(
2897
- Stream.drop(1),
2898
- Stream.take(1),
2899
- Stream.mapEffect(() =>
2900
- Effect.gen(function* () {
2901
- yield* service.list({ state: "open" });
2902
- return yield* service.summary(reference);
2853
+ Effect.gen(function* () {
2854
+ let hostCalls = 0;
2855
+ let state: "open" | "closed" = "open";
2856
+ const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
2857
+ const service = yield* makeService({
2858
+ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2859
+ providers: [
2860
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
2861
+ getChangeRequestSummary: () =>
2862
+ Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }),
2863
+ runAction: (input) =>
2864
+ Effect.sync(() => {
2865
+ state = input.action === "close" ? "closed" : "open";
2866
}),
2904
- ),
2905
- Stream.runHead,
2906
- Effect.forkChild({ startImmediately: true }),
2907
- );
2908
- yield* service.runAction({ ...reference, action });
2909
- assert.strictEqual(
2910
- Option.getOrThrow(yield* Fiber.join(refreshed)).state,
2911
- action === "close" ? "closed" : "open",
2912
- );
2913
- }
2914
- assert.strictEqual(hostCalls, 3);
2915
- }),
2916
- ),
2867
+ listChangeRequests: () => {
2868
+ hostCalls += 1;
2869
+ return Effect.succeed({ items: [], truncated: false, continues: false });
2870
+ },
2871
+ }),
2872
+ ],
2873
+ });
2874
+
2875
+ yield* service.refreshAfterTurn(reference.projectId);
2876
+ yield* service.list({ state: "open" });
2877
+ assert.strictEqual((yield* service.summary(reference)).state, "open");
2878
+ for (const action of ["close", "reopen"] as const) {
2879
+ const refreshed = yield* service.subscribeRefreshes.pipe(
2880
+ Stream.drop(1),
2881
+ Stream.take(1),
2882
+ Stream.mapEffect(() =>
2883
+ Effect.gen(function* () {
2884
+ yield* service.list({ state: "open" });
2885
+ return yield* service.summary(reference);
2886
+ }),
2887
+ ),
2888
+ Stream.runHead,
2889
+ Effect.forkChild({ startImmediately: true }),
2890
+ );
2891
+ yield* service.runAction({ ...reference, action });
2892
+ assert.strictEqual(
2893
+ Option.getOrThrow(yield* Fiber.join(refreshed)).state,
2894
+ action === "close" ? "closed" : "open",
2895
+ );
2896
+ }
2897
+ assert.strictEqual(hostCalls, 3);
2898
+ }),
2899
);
2900
2901
it.effect("reads a host's repositories in one search, and files the rows back under each", () =>
apps/server/src/relay/AgentAwarenessRelay.test.ts
+5
-5
@@ -434,7 +434,7 @@ describe("AgentAwarenessRelay", () => {
434
assert.equal(publications.length, 1);
435
assert.isTrue(publications[0]?.url.includes(`/threads/${THREAD_ID}/`) ?? false);
436
assert.equal(publications[0]?.state?.phase, "waiting_for_input");
437
- }).pipe(Effect.scoped),
437
+ }),
438
);
439
440
it.effect(
@@ -528,7 +528,7 @@ describe("AgentAwarenessRelay", () => {
528
yield* relay.drain;
529
assert.equal(publications.length, 2);
530
assert.equal(publications[1]?.state?.phase, "completed");
531
- }).pipe(Effect.scoped),
531
+ }),
532
);
533
534
it.effect("republishes a completed parent for its waiting child after a relink", () =>
@@ -554,7 +554,7 @@ describe("AgentAwarenessRelay", () => {
554
yield* relay.drain;
555
assert.equal(publications.length, 2);
556
assert.equal(publications[1]?.state?.phase, "waiting_for_approval");
557
- }).pipe(Effect.scoped),
557
+ }),
558
);
559
560
it.effect("keeps a child's alert time when the parent's own request comes and goes", () =>
@@ -722,7 +722,7 @@ describe("AgentAwarenessRelay", () => {
722
yield* relay.drain;
723
assert.equal(publications.length, 3);
724
assert.equal(publications[2]?.state, null);
725
- }).pipe(Effect.scoped),
725
+ }),
726
);
727
728
it.effect("holds a completion through a continuation gap, then publishes it once", () =>
@@ -1170,5 +1170,5 @@ it.effect("catches up after startup without polling after success", () =>
1170
assert.equal(catchUp.activitySnapshotReads, 3);
1171
assert.equal(publications.length, 2);
1172
assert.equal(publications[1]?.state?.threadId, THREAD_ID);
1173
- }).pipe(Effect.scoped),
1173
+ }),
1174
);
apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts
+110
-114
@@ -272,131 +272,127 @@ describe("ResourceTelemetry", () => {
272
);
273
274
it.effect("rejects buffered snapshots from an earlier sidecar generation", () =>
275
- Effect.scoped(
276
- Effect.gen(function* () {
277
- const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
278
- const stale = nativeSnapshot({
279
- sequence: 100,
280
- sampledAtUnixMs: startedAt + 1_000,
281
- childCpuTimeMs: 100,
282
- childWriteBytes: 1_000,
283
- });
284
- const current = nativeSnapshot({
285
- sequence: 1,
286
- sampledAtUnixMs: startedAt + 2_000,
287
- childCpuTimeMs: 200,
288
- childWriteBytes: 2_000,
289
- });
290
- const nativeSnapshots =
291
- yield* PubSub.unbounded<NativeTelemetryClient.NativeTelemetrySnapshot>();
292
- const layerNative = NativeTelemetryClient.layerTest({
293
- snapshots: Stream.fromPubSub(nativeSnapshots),
294
- sampleNow: Effect.never,
295
- health: Effect.succeed({
296
- status: "healthy",
297
- hello: Option.none(),
298
- lastSampleAt: Option.none(),
299
- lastError: Option.none(),
300
- restartCount: 1,
301
- sampleIntervalMs: 1_000,
302
- }),
303
- });
304
- const layerTelemetry = ResourceTelemetry.layer.pipe(
305
- Layer.provide(
306
- Layer.mergeAll(
307
- layerNative,
308
- DesktopTelemetryReceiver.layerTest(),
309
- ResourceAttribution.layer,
310
- ),
275
+ Effect.gen(function* () {
276
+ const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
277
+ const stale = nativeSnapshot({
278
+ sequence: 100,
279
+ sampledAtUnixMs: startedAt + 1_000,
280
+ childCpuTimeMs: 100,
281
+ childWriteBytes: 1_000,
282
+ });
283
+ const current = nativeSnapshot({
284
+ sequence: 1,
285
+ sampledAtUnixMs: startedAt + 2_000,
286
+ childCpuTimeMs: 200,
287
+ childWriteBytes: 2_000,
288
+ });
289
+ const nativeSnapshots =
290
+ yield* PubSub.unbounded<NativeTelemetryClient.NativeTelemetrySnapshot>();
291
+ const layerNative = NativeTelemetryClient.layerTest({
292
+ snapshots: Stream.fromPubSub(nativeSnapshots),
293
+ sampleNow: Effect.never,
294
+ health: Effect.succeed({
295
+ status: "healthy",
296
+ hello: Option.none(),
297
+ lastSampleAt: Option.none(),
298
+ lastError: Option.none(),
299
+ restartCount: 1,
300
+ sampleIntervalMs: 1_000,
301
+ }),
302
+ });
303
+ const layerTelemetry = ResourceTelemetry.layer.pipe(
304
+ Layer.provide(
305
+ Layer.mergeAll(
306
+ layerNative,
307
+ DesktopTelemetryReceiver.layerTest(),
308
+ ResourceAttribution.layer,
309
),
312
- );
310
+ ),
311
+ );
312
314
- yield* Effect.gen(function* () {
315
- const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
316
- const subscription = yield* telemetry.subscribe;
317
- const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild);
313
+ yield* Effect.gen(function* () {
314
+ const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
315
+ const subscription = yield* telemetry.subscribe;
316
+ const nextSnapshot = yield* Stream.runHead(subscription.changes).pipe(Effect.forkChild);
317
319
- yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0));
320
- yield* Effect.yieldNow;
321
- expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0);
318
+ yield* PubSub.publish(nativeSnapshots, nativeGeneration(stale, 0));
319
+ yield* Effect.yieldNow;
320
+ expect((yield* telemetry.latest).health.scannedProcessCount).toBe(0);
321
323
- yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1));
324
- const received = yield* Fiber.join(nextSnapshot);
322
+ yield* PubSub.publish(nativeSnapshots, nativeGeneration(current, 1));
323
+ const received = yield* Fiber.join(nextSnapshot);
324
326
- expect(Option.isSome(received)).toBe(true);
327
- expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe(
328
- current.sampledAtUnixMs,
329
- );
330
- }).pipe(Effect.provide(layerTelemetry));
331
- }),
332
- ),
325
+ expect(Option.isSome(received)).toBe(true);
326
+ expect(DateTime.toEpochMillis(Option.getOrThrow(received).readAt)).toBe(
327
+ current.sampledAtUnixMs,
328
+ );
329
+ }).pipe(Effect.provide(layerTelemetry));
330
+ }),
331
);
332
333
it.effect("atomically subscribes while a desktop update is being rebuilt", () =>
336
- Effect.scoped(
337
- Effect.gen(function* () {
338
- const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
339
- const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000);
340
- const desktopChanges = yield* PubSub.unbounded<DesktopHostTelemetrySnapshot>();
341
- const rebuildStarted = yield* Deferred.make<void>();
342
- const finishRebuild = yield* Deferred.make<void>();
343
- const attributionReads = yield* Ref.make(0);
344
- const layerAttribution = Layer.succeed(
345
- ResourceAttribution.ResourceAttribution,
346
- ResourceAttribution.ResourceAttribution.of({
347
- record: () => Effect.void,
348
- snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe(
349
- Effect.flatMap((count) =>
350
- count === 1
351
- ? Effect.void
352
- : Deferred.succeed(rebuildStarted, undefined).pipe(
353
- Effect.andThen(Deferred.await(finishRebuild)),
354
- ),
355
- ),
356
- Effect.andThen(
357
- Effect.succeed({
358
- readAt: DateTime.makeUnsafe(startedAt),
359
- entries: [],
360
- }),
361
- ),
334
+ Effect.gen(function* () {
335
+ const startedAt = DateTime.toEpochMillis(yield* DateTime.now);
336
+ const nextDesktopSnapshot = desktopSnapshot(startedAt + 1_000);
337
+ const desktopChanges = yield* PubSub.unbounded<DesktopHostTelemetrySnapshot>();
338
+ const rebuildStarted = yield* Deferred.make<void>();
339
+ const finishRebuild = yield* Deferred.make<void>();
340
+ const attributionReads = yield* Ref.make(0);
341
+ const layerAttribution = Layer.succeed(
342
+ ResourceAttribution.ResourceAttribution,
343
+ ResourceAttribution.ResourceAttribution.of({
344
+ record: () => Effect.void,
345
+ snapshot: Ref.updateAndGet(attributionReads, (count) => count + 1).pipe(
346
+ Effect.flatMap((count) =>
347
+ count === 1
348
+ ? Effect.void
349
+ : Deferred.succeed(rebuildStarted, undefined).pipe(
350
+ Effect.andThen(Deferred.await(finishRebuild)),
351
+ ),
352
),
363
- }),
364
- );
365
- const layerNative = NativeTelemetryClient.layerTest({
366
- sampleNow: Effect.never,
367
- health: Effect.succeed({
368
- status: "healthy",
369
- hello: Option.none(),
370
- lastSampleAt: Option.none(),
371
- lastError: Option.none(),
372
- restartCount: 0,
373
- sampleIntervalMs: 1_000,
374
- }),
375
- });
376
- const layerDesktop = DesktopTelemetryReceiver.layerTest({
377
- changes: Stream.fromPubSub(desktopChanges),
378
- });
379
- const layerTelemetry = ResourceTelemetry.layer.pipe(
380
- Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)),
381
- );
353
+ Effect.andThen(
354
+ Effect.succeed({
355
+ readAt: DateTime.makeUnsafe(startedAt),
356
+ entries: [],
357
+ }),
358
+ ),
359
+ ),
360
+ }),
361
+ );
362
+ const layerNative = NativeTelemetryClient.layerTest({
363
+ sampleNow: Effect.never,
364
+ health: Effect.succeed({
365
+ status: "healthy",
366
+ hello: Option.none(),
367
+ lastSampleAt: Option.none(),
368
+ lastError: Option.none(),
369
+ restartCount: 0,
370
+ sampleIntervalMs: 1_000,
371
+ }),
372
+ });
373
+ const layerDesktop = DesktopTelemetryReceiver.layerTest({
374
+ changes: Stream.fromPubSub(desktopChanges),
375
+ });
376
+ const layerTelemetry = ResourceTelemetry.layer.pipe(
377
+ Layer.provide(Layer.mergeAll(layerNative, layerDesktop, layerAttribution)),
378
+ );
379
383
- yield* Effect.gen(function* () {
384
- const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
385
- yield* Effect.yieldNow;
386
- yield* PubSub.publish(desktopChanges, nextDesktopSnapshot);
387
- yield* Deferred.await(rebuildStarted);
380
+ yield* Effect.gen(function* () {
381
+ const telemetry = yield* ResourceTelemetry.ResourceTelemetry;
382
+ yield* Effect.yieldNow;
383
+ yield* PubSub.publish(desktopChanges, nextDesktopSnapshot);
384
+ yield* Deferred.await(rebuildStarted);
385
389
- const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild);
390
- yield* Effect.yieldNow;
391
- yield* Deferred.succeed(finishRebuild, undefined);
392
- const subscription = yield* Fiber.join(subscriptionFiber);
386
+ const subscriptionFiber = yield* telemetry.subscribe.pipe(Effect.forkChild);
387
+ yield* Effect.yieldNow;
388
+ yield* Deferred.succeed(finishRebuild, undefined);
389
+ const subscription = yield* Fiber.join(subscriptionFiber);
390
394
- expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe(
395
- nextDesktopSnapshot.sampledAtUnixMs,
396
- );
397
- expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power);
398
- }).pipe(Effect.provide(layerTelemetry));
399
- }),
400
- ),
391
+ expect(DateTime.toEpochMillis(subscription.latest.readAt)).toBe(
392
+ nextDesktopSnapshot.sampledAtUnixMs,
393
+ );
394
+ expect(subscription.latest.power).toEqual(nextDesktopSnapshot.power);
395
+ }).pipe(Effect.provide(layerTelemetry));
396
+ }),
397
);
398
});
apps/server/src/secrets/SecretCheck.test.ts
+5
-5
@@ -228,7 +228,7 @@ it.layer(layerTest)("SecretCheck", (it) => {
228
]);
229
assert.deepStrictEqual(server.refreshed, [dependent]);
230
assert.deepStrictEqual(yield* server.registry.listUnavailable, []);
231
- }).pipe(Effect.scoped),
231
+ }),
232
);
233
234
it.effect("an unreadable secret fails naming its provider and leaves instances alone", () =>
@@ -250,7 +250,7 @@ it.layer(layerTest)("SecretCheck", (it) => {
250
(yield* server.registry.listUnavailable).map((entry) => entry.instanceId),
251
[dependent],
252
);
253
- }).pipe(Effect.scoped),
253
+ }),
254
);
255
256
it.effect("a failed check keeps the value the server already holds", () =>
@@ -267,7 +267,7 @@ it.layer(layerTest)("SecretCheck", (it) => {
267
268
assert.deepStrictEqual(yield* server.resolver.read([locked]), ["locked-key"]);
269
assert.deepStrictEqual(server.reads.slice(readsBefore), [locked.reference]);
270
- }).pipe(Effect.scoped),
270
+ }),
271
);
272
273
it.effect("a check applies to an instance whose other secret failed a later refresh", () =>
@@ -289,7 +289,7 @@ it.layer(layerTest)("SecretCheck", (it) => {
289
secrets: ["wanted-new", "locked-key"],
290
});
291
assert.deepStrictEqual(yield* server.registry.listUnavailable, []);
292
- }).pipe(Effect.scoped),
292
+ }),
293
);
294
295
it.effect("a check applies the value it read when a refresh re-reads that secret first", () =>
@@ -358,6 +358,6 @@ it.layer(layerTest)("SecretCheck", (it) => {
358
assert.deepStrictEqual(server.createdConfigs.at(-1), {
359
keys: { a: "wanted-new", b: "locked-key" },
360
});
361
- }).pipe(Effect.scoped),
361
+ }),
362
);
363
});
apps/server/src/serverRuntimeStartup.autoPull.test.ts
+154
-158
@@ -37,166 +37,162 @@ import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
37
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
38
39
it.effect("parks automatic pull until activation without delaying command readiness", () =>
40
- Effect.scoped(
41
- Effect.gen(function* () {
42
- const activation = yield* Deferred.make<void>();
43
- const prepared = yield* Deferred.make<void>();
44
- const commitTrial = yield* Deferred.make<void>();
45
- const statusCalled = yield* Deferred.make<string>();
46
- const statusInterrupted = yield* Deferred.make<void>();
47
- const cwd = "/auto-pull-project";
48
- const updatedAt = "2026-01-01T00:00:00.000Z";
49
- const snapshot = {
50
- projects: [
51
- {
52
- id: ProjectId.make("auto-pull-project"),
53
- title: "Auto pull project",
54
- workspaceRoot: cwd,
55
- repositoryIdentity: null,
56
- defaultModelSelection: null,
57
- scripts: [],
58
- createdAt: updatedAt,
59
- updatedAt,
60
- deletedAt: null,
61
- },
62
- ],
63
- updatedAt,
64
- };
65
- const recovery = {
66
- terminalizedRuns: 0,
67
- stoppedSessions: 0,
68
- closedRequests: 0,
69
- retiredEffects: 0,
70
- requeuedEffects: 0,
71
- };
72
- const importSummary = { importedThreadCount: 0, importedMessageCount: 0 };
73
- const dependencies: Layer.Layer<
74
- Layer.Services<ReturnType<typeof ServerRuntimeStartup.layerWithOptions>>
75
- > = Layer.mergeAll(
76
- Layer.mock(ServerConfig.ServerConfig)({
77
- ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe(
78
- Effect.provide(Path.layer),
79
- )),
80
- baseDir: cwd,
81
- logLevel: "Error",
82
- traceMinLevel: "Info",
83
- traceTimingEnabled: false,
84
- traceBatchWindowMs: 200,
85
- traceMaxBytes: 1024,
86
- traceMaxFiles: 1,
87
- otlpTracesUrl: undefined,
88
- otlpMetricsUrl: undefined,
89
- otlpLogsUrl: undefined,
90
- otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
91
- otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
92
- otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
93
- otelEnvironment: OtelEnvironment.none,
94
- staticDir: undefined,
95
- devAllowedOrigins: [],
96
- desktopBootstrapToken: undefined,
97
- logWebSocketEvents: false,
98
- tailscaleServeEnabled: false,
99
- tailscaleServePort: 443,
100
- mode: "desktop",
101
- cwd,
102
- host: "localhost",
103
- port: 3773,
104
- devUrl: undefined,
105
- noBrowser: true,
106
- startupPresentation: "browser",
107
- autoBootstrapProjectFromCwd: false,
40
+ Effect.gen(function* () {
41
+ const activation = yield* Deferred.make<void>();
42
+ const prepared = yield* Deferred.make<void>();
43
+ const commitTrial = yield* Deferred.make<void>();
44
+ const statusCalled = yield* Deferred.make<string>();
45
+ const statusInterrupted = yield* Deferred.make<void>();
46
+ const cwd = "/auto-pull-project";
47
+ const updatedAt = "2026-01-01T00:00:00.000Z";
48
+ const snapshot = {
49
+ projects: [
50
+ {
51
+ id: ProjectId.make("auto-pull-project"),
52
+ title: "Auto pull project",
53
+ workspaceRoot: cwd,
54
+ repositoryIdentity: null,
55
+ defaultModelSelection: null,
56
+ scripts: [],
57
+ createdAt: updatedAt,
58
+ updatedAt,
59
+ deletedAt: null,
60
+ },
61
+ ],
62
+ updatedAt,
63
+ };
64
+ const recovery = {
65
+ terminalizedRuns: 0,
66
+ stoppedSessions: 0,
67
+ closedRequests: 0,
68
+ retiredEffects: 0,
69
+ requeuedEffects: 0,
70
+ };
71
+ const importSummary = { importedThreadCount: 0, importedMessageCount: 0 };
72
+ const dependencies: Layer.Layer<
73
+ Layer.Services<ReturnType<typeof ServerRuntimeStartup.layerWithOptions>>
74
+ > = Layer.mergeAll(
75
+ Layer.mock(ServerConfig.ServerConfig)({
76
+ ...(yield* ServerConfig.deriveServerPaths(cwd, undefined).pipe(Effect.provide(Path.layer))),
77
+ baseDir: cwd,
78
+ logLevel: "Error",
79
+ traceMinLevel: "Info",
80
+ traceTimingEnabled: false,
81
+ traceBatchWindowMs: 200,
82
+ traceMaxBytes: 1024,
83
+ traceMaxFiles: 1,
84
+ otlpTracesUrl: undefined,
85
+ otlpMetricsUrl: undefined,
86
+ otlpLogsUrl: undefined,
87
+ otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
88
+ otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
89
+ otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
90
+ otelEnvironment: OtelEnvironment.none,
91
+ staticDir: undefined,
92
+ devAllowedOrigins: [],
93
+ desktopBootstrapToken: undefined,
94
+ logWebSocketEvents: false,
95
+ tailscaleServeEnabled: false,
96
+ tailscaleServePort: 443,
97
+ mode: "desktop",
98
+ cwd,
99
+ host: "localhost",
100
+ port: 3773,
101
+ devUrl: undefined,
102
+ noBrowser: true,
103
+ startupPresentation: "browser",
104
+ autoBootstrapProjectFromCwd: false,
105
+ }),
106
+ Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
107
+ Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
108
+ pendingThreadCount: Effect.succeed(0),
109
+ reconcileShells: Effect.succeed(importSummary),
110
+ importPendingTranscripts: Effect.succeed(importSummary),
111
+ }),
112
+ Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
113
+ recover: Effect.succeed(recovery),
114
+ prepareForShutdown: Effect.void,
115
+ reconcile: () => Effect.succeed(recovery),
116
+ }),
117
+ Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
118
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
119
+ Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
120
+ Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }),
121
+ Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
122
+ publish: (event) => Effect.succeed({ ...event, sequence: 1 }),
123
+ }),
124
+ Layer.mock(ServerSettings.ServerSettingsService)({
125
+ start: Effect.void,
126
+ getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }),
127
+ }),
128
+ Layer.mock(ServerEnvironment.ServerEnvironment)({
129
+ getDescriptor: Effect.succeed({
130
+ environmentId: EnvironmentId.make("auto-pull-environment"),
131
+ label: "Test environment",
132
+ platform: { os: "darwin", arch: "arm64" },
133
+ serverVersion: "0.0.0-test",
134
+ capabilities: { repositoryIdentity: true },
135
}),
109
- Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
110
- Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
111
- pendingThreadCount: Effect.succeed(0),
112
- reconcileShells: Effect.succeed(importSummary),
113
- importPendingTranscripts: Effect.succeed(importSummary),
114
- }),
115
- Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
116
- recover: Effect.succeed(recovery),
117
- prepareForShutdown: Effect.void,
118
- reconcile: () => Effect.succeed(recovery),
119
- }),
120
- Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
121
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
122
- Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
123
- Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }),
124
- Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
125
- publish: (event) => Effect.succeed({ ...event, sequence: 1 }),
126
- }),
127
- Layer.mock(ServerSettings.ServerSettingsService)({
128
- start: Effect.void,
129
- getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, defaultAutoPull: true }),
130
- }),
131
- Layer.mock(ServerEnvironment.ServerEnvironment)({
132
- getDescriptor: Effect.succeed({
133
- environmentId: EnvironmentId.make("auto-pull-environment"),
134
- label: "Test environment",
135
- platform: { os: "darwin", arch: "arm64" },
136
- serverVersion: "0.0.0-test",
137
- capabilities: { repositoryIdentity: true },
138
- }),
139
- }),
140
- Layer.mock(ProjectStore.ProjectStoreV2)({
141
- listShells: () => Effect.succeed(snapshot.projects),
142
- }),
143
- Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }),
144
- Layer.mock(ThreadManagement.ThreadManagementService)({
145
- countThreads: () => Effect.succeed(0),
146
- }),
147
- Layer.mock(ThreadLaunch.ThreadLaunchService)({}),
148
- Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
149
- managed: true,
150
- protocol: SERVICE_LAUNCHER_PROTOCOL,
151
- prepareTrial: () =>
152
- Deferred.succeed(prepared, undefined).pipe(
153
- Effect.andThen(Deferred.await(commitTrial)),
154
- Effect.as(undefined),
155
- ),
156
- }),
157
- Layer.mock(GitVcsDriver.GitVcsDriver)({
158
- statusDetails: (root) =>
159
- Deferred.succeed(statusCalled, root).pipe(
160
- Effect.andThen(Effect.never),
161
- Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)),
162
- ),
163
- }),
164
- Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }),
165
- // No provider logins or Connect link, so startup records no owners.
166
- FileSystem.layerNoop({}),
167
- Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
168
- NodeCrypto.layer,
169
- Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
170
- Layer.mock(ExternalLauncher.ExternalLauncher)({}),
171
- Layer.mock(HttpServer.HttpServer)({
172
- address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
173
- }),
174
- Path.layer,
175
- );
136
+ }),
137
+ Layer.mock(ProjectStore.ProjectStoreV2)({
138
+ listShells: () => Effect.succeed(snapshot.projects),
139
+ }),
140
+ Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }),
141
+ Layer.mock(ThreadManagement.ThreadManagementService)({
142
+ countThreads: () => Effect.succeed(0),
143
+ }),
144
+ Layer.mock(ThreadLaunch.ThreadLaunchService)({}),
145
+ Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
146
+ managed: true,
147
+ protocol: SERVICE_LAUNCHER_PROTOCOL,
148
+ prepareTrial: () =>
149
+ Deferred.succeed(prepared, undefined).pipe(
150
+ Effect.andThen(Deferred.await(commitTrial)),
151
+ Effect.as(undefined),
152
+ ),
153
+ }),
154
+ Layer.mock(GitVcsDriver.GitVcsDriver)({
155
+ statusDetails: (root) =>
156
+ Deferred.succeed(statusCalled, root).pipe(
157
+ Effect.andThen(Effect.never),
158
+ Effect.onInterrupt(() => Deferred.succeed(statusInterrupted, undefined)),
159
+ ),
160
+ }),
161
+ Layer.mock(AnalyticsService.AnalyticsService)({ record: () => Effect.void }),
162
+ // No provider logins or Connect link, so startup records no owners.
163
+ FileSystem.layerNoop({}),
164
+ Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
165
+ NodeCrypto.layer,
166
+ Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
167
+ Layer.mock(ExternalLauncher.ExternalLauncher)({}),
168
+ Layer.mock(HttpServer.HttpServer)({
169
+ address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
170
+ }),
171
+ Path.layer,
172
+ );
173
177
- yield* Effect.gen(function* () {
178
- const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
179
- yield* startup.markHttpListening;
174
+ yield* Effect.gen(function* () {
175
+ const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
176
+ yield* startup.markHttpListening;
177
181
- yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled));
182
- expect(yield* Deferred.isDone(activation)).toBe(false);
183
- expect(yield* Deferred.isDone(statusCalled)).toBe(false);
184
- expect(yield* Deferred.isDone(prepared)).toBe(true);
178
+ yield* Effect.raceFirst(Deferred.await(prepared), Deferred.await(statusCalled));
179
+ expect(yield* Deferred.isDone(activation)).toBe(false);
180
+ expect(yield* Deferred.isDone(statusCalled)).toBe(false);
181
+ expect(yield* Deferred.isDone(prepared)).toBe(true);
182
186
- yield* Deferred.succeed(commitTrial, undefined);
187
- yield* Deferred.await(activation);
188
- expect(yield* Deferred.await(statusCalled)).toBe(cwd);
189
- yield* startup.awaitCommandReady;
190
- }).pipe(
191
- Effect.provide(
192
- ServerRuntimeStartup.layerWithOptions({
193
- activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
194
- awaitAuxiliaryParked: Effect.void,
195
- }).pipe(Layer.provide(dependencies)),
196
- ),
197
- Effect.provideService(ServerActivation, Deferred.await(activation)),
198
- );
199
- expect(yield* Deferred.isDone(statusInterrupted)).toBe(true);
200
- }),
201
- ),
183
+ yield* Deferred.succeed(commitTrial, undefined);
184
+ yield* Deferred.await(activation);
185
+ expect(yield* Deferred.await(statusCalled)).toBe(cwd);
186
+ yield* startup.awaitCommandReady;
187
+ }).pipe(
188
+ Effect.provide(
189
+ ServerRuntimeStartup.layerWithOptions({
190
+ activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
191
+ awaitAuxiliaryParked: Effect.void,
192
+ }).pipe(Layer.provide(dependencies)),
193
+ ),
194
+ Effect.provideService(ServerActivation, Deferred.await(activation)),
195
+ );
196
+ expect(yield* Deferred.isDone(statusInterrupted)).toBe(true);
197
+ }),
198
);
apps/server/src/serverRuntimeStartup.test.ts
+216
-226
@@ -53,252 +53,242 @@ it.effect.each([
53
"launch-failure",
54
"project-failure",
55
] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) =>
56
- Effect.scoped(
57
- Effect.gen(function* () {
58
- const projectId = ProjectId.make("bootstrap-project");
59
- const instanceId = ProviderInstanceId.make(
60
- scenario === "disabled-default" ? "custom" : "codex",
61
- );
62
- const events: ServerLifecycleStreamEvent[] = [];
63
- const recovery = {
64
- terminalizedRuns: 0,
65
- stoppedSessions: 0,
66
- closedRequests: 0,
67
- retiredEffects: 0,
68
- requeuedEffects: 0,
69
- };
70
- const imports = { importedThreadCount: 0, importedMessageCount: 0 };
71
- const dependencies = Layer.mergeAll(
72
- NodeCrypto.layer,
73
- Path.layer,
74
- Layer.mock(ServerConfig.ServerConfig)({
75
- ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe(
76
- Effect.provide(Path.layer),
77
- )),
78
- baseDir: "/bootstrap-project",
79
- logLevel: "Error",
80
- traceMinLevel: "Info",
81
- traceTimingEnabled: false,
82
- traceBatchWindowMs: 200,
83
- traceMaxBytes: 1024,
84
- traceMaxFiles: 1,
85
- otlpTracesUrl: undefined,
86
- otlpMetricsUrl: undefined,
87
- otlpLogsUrl: undefined,
88
- otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
89
- otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
90
- otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
91
- otelEnvironment: OtelEnvironment.none,
92
- staticDir: undefined,
93
- devAllowedOrigins: [],
94
- desktopBootstrapToken: undefined,
95
- logWebSocketEvents: false,
96
- tailscaleServeEnabled: false,
97
- tailscaleServePort: 443,
98
- mode: "web",
99
- cwd: "/bootstrap-project",
100
- host: "localhost",
101
- port: 3773,
102
- devUrl: undefined,
103
- noBrowser: true,
104
- startupPresentation: "browser",
105
- autoBootstrapProjectFromCwd: true,
106
- }),
107
- Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
108
- Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
109
- pendingThreadCount: Effect.succeed(0),
110
- reconcileShells: Effect.succeed(imports),
111
- importPendingTranscripts: Effect.succeed(imports),
112
- }),
113
- Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
114
- recover: Effect.succeed(recovery),
115
- prepareForShutdown: Effect.void,
116
- reconcile: () => Effect.succeed(recovery),
117
- }),
118
- Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
119
- Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
120
- Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
121
- Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }),
122
- Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
123
- publish: (event) =>
124
- Effect.sync(() => {
125
- const published = { ...event, sequence: events.length + 1 };
126
- events.push(published);
127
- return published;
128
- }),
129
- }),
130
- Layer.mock(ServerSettings.ServerSettingsService)({
131
- start: Effect.void,
132
- getSettings: Effect.succeed({
133
- ...DEFAULT_SERVER_SETTINGS,
134
- defaultModelSelection:
135
- scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
136
- providerInstances: {
137
- [instanceId]: {
138
- driver: ProviderDriverKind.make("codex"),
139
- enabled: false,
140
- config: {},
141
- },
142
- },
143
- }),
144
- }),
145
- Layer.mock(ServerEnvironment.ServerEnvironment)({
146
- getDescriptor: Effect.succeed({
147
- environmentId: EnvironmentId.make("bootstrap-environment"),
148
- label: "Test environment",
149
- platform: { os: "linux", arch: "x64" },
150
- serverVersion: "0.0.0-test",
151
- capabilities: { repositoryIdentity: true },
56
+ Effect.gen(function* () {
57
+ const projectId = ProjectId.make("bootstrap-project");
58
+ const instanceId = ProviderInstanceId.make(
59
+ scenario === "disabled-default" ? "custom" : "codex",
60
+ );
61
+ const events: ServerLifecycleStreamEvent[] = [];
62
+ const recovery = {
63
+ terminalizedRuns: 0,
64
+ stoppedSessions: 0,
65
+ closedRequests: 0,
66
+ retiredEffects: 0,
67
+ requeuedEffects: 0,
68
+ };
69
+ const imports = { importedThreadCount: 0, importedMessageCount: 0 };
70
+ const dependencies = Layer.mergeAll(
71
+ NodeCrypto.layer,
72
+ Path.layer,
73
+ Layer.mock(ServerConfig.ServerConfig)({
74
+ ...(yield* ServerConfig.deriveServerPaths("/bootstrap-project", undefined).pipe(
75
+ Effect.provide(Path.layer),
76
+ )),
77
+ baseDir: "/bootstrap-project",
78
+ logLevel: "Error",
79
+ traceMinLevel: "Info",
80
+ traceTimingEnabled: false,
81
+ traceBatchWindowMs: 200,
82
+ traceMaxBytes: 1024,
83
+ traceMaxFiles: 1,
84
+ otlpTracesUrl: undefined,
85
+ otlpMetricsUrl: undefined,
86
+ otlpLogsUrl: undefined,
87
+ otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
88
+ otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
89
+ otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
90
+ otelEnvironment: OtelEnvironment.none,
91
+ staticDir: undefined,
92
+ devAllowedOrigins: [],
93
+ desktopBootstrapToken: undefined,
94
+ logWebSocketEvents: false,
95
+ tailscaleServeEnabled: false,
96
+ tailscaleServePort: 443,
97
+ mode: "web",
98
+ cwd: "/bootstrap-project",
99
+ host: "localhost",
100
+ port: 3773,
101
+ devUrl: undefined,
102
+ noBrowser: true,
103
+ startupPresentation: "browser",
104
+ autoBootstrapProjectFromCwd: true,
105
+ }),
106
+ Layer.mock(Keybindings.Keybindings)({ start: Effect.void }),
107
+ Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
108
+ pendingThreadCount: Effect.succeed(0),
109
+ reconcileShells: Effect.succeed(imports),
110
+ importPendingTranscripts: Effect.succeed(imports),
111
+ }),
112
+ Layer.mock(ProviderRuntimeRecovery.ProviderRuntimeRecoveryService)({
113
+ recover: Effect.succeed(recovery),
114
+ prepareForShutdown: Effect.void,
115
+ reconcile: () => Effect.succeed(recovery),
116
+ }),
117
+ Layer.mock(Orchestrator.OrchestratorV2)({ recoverDelegatedTasks: Effect.void }),
118
+ Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ shutdown: Effect.void }),
119
+ Layer.mock(AgentAwarenessRelay.AgentAwarenessRelay)({ start: () => Effect.void }),
120
+ Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({ runOnce: () => Effect.never }),
121
+ Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({
122
+ publish: (event) =>
123
+ Effect.sync(() => {
124
+ const published = { ...event, sequence: events.length + 1 };
125
+ events.push(published);
126
+ return published;
127
}),
153
- }),
154
- Layer.mock(ProjectStore.ProjectStoreV2)({}),
155
- Layer.mock(ProjectService.ProjectService)({
156
- bootstrap: () =>
157
- scenario === "project-failure"
158
- ? Effect.die("project bootstrap failed")
159
- : Effect.succeed({
160
- created: true,
161
- project: {
162
- id: projectId,
163
- title: "Project",
164
- workspaceRoot: "/bootstrap-project",
165
- repositoryIdentity: null,
166
- faviconPath: null,
167
- scripts: [],
168
- createdAt: "2026-01-01T00:00:00Z",
169
- updatedAt: "2026-01-01T00:00:00Z",
170
- deletedAt: null,
171
- defaultModelSelection:
172
- scenario === "disabled-default"
173
- ? { instanceId, model: "custom-model" }
174
- : null,
175
- },
176
- }),
177
- }),
178
- Layer.mock(ThreadManagement.ThreadManagementService)({
179
- countThreads: () => Effect.succeed(0),
180
- listActiveShellIndex: () => Effect.succeed([]),
181
- }),
182
- Layer.mock(ThreadLaunch.ThreadLaunchService)({
183
- launch: (input) => {
184
- assert.equal(input.modelSelection.instanceId, instanceId);
185
- return scenario === "launch-failure"
186
- ? Effect.fail(
187
- new ThreadLaunch.ThreadLaunchError({
188
- operation: "create-thread",
189
- commandId: CommandId.make("bootstrap-command"),
190
- projectId,
191
- cause: "test launch failure",
192
- }),
193
- )
194
- : Effect.fail(
195
- new ThreadManagement.ThreadManagementProviderInstanceDisabledError({
196
- projectId,
197
- instanceId,
198
- }),
199
- );
128
+ }),
129
+ Layer.mock(ServerSettings.ServerSettingsService)({
130
+ start: Effect.void,
131
+ getSettings: Effect.succeed({
132
+ ...DEFAULT_SERVER_SETTINGS,
133
+ defaultModelSelection:
134
+ scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
135
+ providerInstances: {
136
+ [instanceId]: {
137
+ driver: ProviderDriverKind.make("codex"),
138
+ enabled: false,
139
+ config: {},
140
+ },
141
},
142
}),
202
- Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
203
- managed: false,
204
- protocol: undefined,
205
- prepareTrial: () => Effect.undefined,
206
- }),
207
- Layer.mock(GitVcsDriver.GitVcsDriver)({}),
208
- Layer.mock(AnalyticsService.AnalyticsService)({}),
209
- // No provider logins or Connect link, so startup records no owners.
210
- FileSystem.layerNoop({}),
211
- Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
212
- Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
213
- Layer.mock(ExternalLauncher.ExternalLauncher)({}),
214
- Layer.mock(HttpServer.HttpServer)({
215
- address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
143
+ }),
144
+ Layer.mock(ServerEnvironment.ServerEnvironment)({
145
+ getDescriptor: Effect.succeed({
146
+ environmentId: EnvironmentId.make("bootstrap-environment"),
147
+ label: "Test environment",
148
+ platform: { os: "linux", arch: "x64" },
149
+ serverVersion: "0.0.0-test",
150
+ capabilities: { repositoryIdentity: true },
151
}),
217
- );
218
- yield* Effect.gen(function* () {
219
- const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
220
- yield* startup.markHttpListening;
221
- const ready = yield* Effect.exit(startup.awaitCommandReady);
222
- assert.equal(Exit.isSuccess(ready), scenario !== "project-failure");
223
- const welcome = events.find((event) => event.type === "welcome");
224
- if (scenario === "project-failure") {
225
- assert.isUndefined(welcome);
226
- } else {
227
- assert.isDefined(welcome);
228
- if (welcome?.type === "welcome") {
229
- assert.equal(welcome.payload.bootstrapProjectId, projectId);
230
- assert.isUndefined(welcome.payload.bootstrapThreadId);
231
- }
152
+ }),
153
+ Layer.mock(ProjectStore.ProjectStoreV2)({}),
154
+ Layer.mock(ProjectService.ProjectService)({
155
+ bootstrap: () =>
156
+ scenario === "project-failure"
157
+ ? Effect.die("project bootstrap failed")
158
+ : Effect.succeed({
159
+ created: true,
160
+ project: {
161
+ id: projectId,
162
+ title: "Project",
163
+ workspaceRoot: "/bootstrap-project",
164
+ repositoryIdentity: null,
165
+ faviconPath: null,
166
+ scripts: [],
167
+ createdAt: "2026-01-01T00:00:00Z",
168
+ updatedAt: "2026-01-01T00:00:00Z",
169
+ deletedAt: null,
170
+ defaultModelSelection:
171
+ scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null,
172
+ },
173
+ }),
174
+ }),
175
+ Layer.mock(ThreadManagement.ThreadManagementService)({
176
+ countThreads: () => Effect.succeed(0),
177
+ listActiveShellIndex: () => Effect.succeed([]),
178
+ }),
179
+ Layer.mock(ThreadLaunch.ThreadLaunchService)({
180
+ launch: (input) => {
181
+ assert.equal(input.modelSelection.instanceId, instanceId);
182
+ return scenario === "launch-failure"
183
+ ? Effect.fail(
184
+ new ThreadLaunch.ThreadLaunchError({
185
+ operation: "create-thread",
186
+ commandId: CommandId.make("bootstrap-command"),
187
+ projectId,
188
+ cause: "test launch failure",
189
+ }),
190
+ )
191
+ : Effect.fail(
192
+ new ThreadManagement.ThreadManagementProviderInstanceDisabledError({
193
+ projectId,
194
+ instanceId,
195
+ }),
196
+ );
197
+ },
198
+ }),
199
+ Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({
200
+ managed: false,
201
+ protocol: undefined,
202
+ prepareTrial: () => Effect.undefined,
203
+ }),
204
+ Layer.mock(GitVcsDriver.GitVcsDriver)({}),
205
+ Layer.mock(AnalyticsService.AnalyticsService)({}),
206
+ // No provider logins or Connect link, so startup records no owners.
207
+ FileSystem.layerNoop({}),
208
+ Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedNone }),
209
+ Layer.mock(EnvironmentAuth.EnvironmentAuth)({}),
210
+ Layer.mock(ExternalLauncher.ExternalLauncher)({}),
211
+ Layer.mock(HttpServer.HttpServer)({
212
+ address: NetAddress.inetAddressFromIpStringUnsafe("127.0.0.1", 3773),
213
+ }),
214
+ );
215
+ yield* Effect.gen(function* () {
216
+ const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
217
+ yield* startup.markHttpListening;
218
+ const ready = yield* Effect.exit(startup.awaitCommandReady);
219
+ assert.equal(Exit.isSuccess(ready), scenario !== "project-failure");
220
+ const welcome = events.find((event) => event.type === "welcome");
221
+ if (scenario === "project-failure") {
222
+ assert.isUndefined(welcome);
223
+ } else {
224
+ assert.isDefined(welcome);
225
+ if (welcome?.type === "welcome") {
226
+ assert.equal(welcome.payload.bootstrapProjectId, projectId);
227
+ assert.isUndefined(welcome.payload.bootstrapThreadId);
228
}
233
- }).pipe(
234
- Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))),
235
- Effect.provideService(ServerActivation, Effect.never),
236
- );
237
- }),
238
- ),
229
+ }
230
+ }).pipe(
231
+ Effect.provide(ServerRuntimeStartup.layerWithOptions().pipe(Layer.provide(dependencies))),
232
+ Effect.provideService(ServerActivation, Effect.never),
233
+ );
234
+ }),
235
);
236
237
it.effect("interrupts the effect worker when awareness relay startup fails", () =>
242
- Effect.scoped(
243
- Effect.gen(function* () {
244
- const workerInterrupted = yield* Ref.make(false);
245
- const workerFiberRef = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
238
+ Effect.gen(function* () {
239
+ const workerInterrupted = yield* Ref.make(false);
240
+ const workerFiberRef = yield* Ref.make<Fiber.Fiber<void, never> | null>(null);
241
247
- const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({
248
- runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))),
249
- startRelay: Effect.yieldNow.pipe(
250
- Effect.andThen(Effect.die("awareness relay startup failed")),
251
- ),
252
- workerFiberRef,
253
- }).pipe(Effect.exit);
242
+ const exit = yield* ServerRuntimeStartup.startEffectWorkerWithRelay({
243
+ runWorker: Effect.never.pipe(Effect.ensuring(Ref.set(workerInterrupted, true))),
244
+ startRelay: Effect.yieldNow.pipe(
245
+ Effect.andThen(Effect.die("awareness relay startup failed")),
246
+ ),
247
+ workerFiberRef,
248
+ }).pipe(Effect.exit);
249
255
- assert.isTrue(Exit.isFailure(exit));
256
- assert.isTrue(yield* Ref.get(workerInterrupted));
257
- assert.isNull(yield* Ref.get(workerFiberRef));
258
- }),
259
- ),
250
+ assert.isTrue(Exit.isFailure(exit));
251
+ assert.isTrue(yield* Ref.get(workerInterrupted));
252
+ assert.isNull(yield* Ref.get(workerFiberRef));
253
+ }),
254
);
255
256
it.effect("queues commands until startup signals readiness", () =>
263
- Effect.scoped(
264
- Effect.gen(function* () {
265
- const gate = yield* ServerRuntimeStartup.makeCommandGate;
266
- const count = yield* Ref.make(0);
267
- const queued = yield* gate
268
- .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1))
269
- .pipe(Effect.forkScoped);
257
+ Effect.gen(function* () {
258
+ const gate = yield* ServerRuntimeStartup.makeCommandGate;
259
+ const count = yield* Ref.make(0);
260
+ const queued = yield* gate
261
+ .enqueueCommand(Ref.updateAndGet(count, (value) => value + 1))
262
+ .pipe(Effect.forkScoped);
263
271
- yield* Effect.yieldNow;
272
- assert.equal(yield* Ref.get(count), 0);
273
- yield* gate.signalCommandReady;
274
- assert.equal(yield* Fiber.join(queued), 1);
275
- }),
276
- ),
264
+ yield* Effect.yieldNow;
265
+ assert.equal(yield* Ref.get(count), 0);
266
+ yield* gate.signalCommandReady;
267
+ assert.equal(yield* Fiber.join(queued), 1);
268
+ }),
269
);
270
271
it.effect("enqueueCommand fails queued work when readiness fails", () =>
280
- Effect.scoped(
281
- Effect.gen(function* () {
282
- const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
283
- const failure = yield* Deferred.make<void, never>();
272
+ Effect.gen(function* () {
273
+ const commandGate = yield* ServerRuntimeStartup.makeCommandGate;
274
+ const failure = yield* Deferred.make<void, never>();
275
285
- const queuedCommandFiber = yield* commandGate
286
- .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
287
- .pipe(Effect.forkScoped);
276
+ const queuedCommandFiber = yield* commandGate
277
+ .enqueueCommand(Deferred.await(failure).pipe(Effect.as("should-not-run")))
278
+ .pipe(Effect.forkScoped);
279
289
- yield* commandGate.failCommandReady(
290
- new ServerRuntimeStartup.ServerRuntimeStartupError({
291
- mode: "web",
292
- host: "127.0.0.1",
293
- port: 3773,
294
- cause: new Error("test startup failure"),
295
- }),
296
- );
280
+ yield* commandGate.failCommandReady(
281
+ new ServerRuntimeStartup.ServerRuntimeStartupError({
282
+ mode: "web",
283
+ host: "127.0.0.1",
284
+ port: 3773,
285
+ cause: new Error("test startup failure"),
286
+ }),
287
+ );
288
298
- const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
299
- assert.equal(error.message, "Server runtime startup failed before command readiness.");
300
- }),
301
- ),
289
+ const error = yield* Effect.flip(Fiber.join(queuedCommandFiber));
290
+ assert.equal(error.message, "Server runtime startup failed before command readiness.");
291
+ }),
292
);
293
294
it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () =>
apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts
+1
-1
@@ -283,7 +283,7 @@ it.effect(
283
url,
284
);
285
}
286
- }).pipe(Effect.scoped),
286
+ }),
287
);
288
289
it.effect("does not refine a context whose server address is empty", () =>
apps/server/src/speech/http.test.ts
+2
-2
@@ -269,7 +269,7 @@ effectIt.effect(
269
handler(new Request("http://localhost/api/voice/models"), context),
270
);
271
expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone");
272
- }).pipe(Effect.scoped),
272
+ }),
273
);
274
275
effectIt.effect.each([
@@ -361,5 +361,5 @@ effectIt.effect.each([
361
code: "invalid_request",
362
reason,
363
});
364
- }).pipe(Effect.scoped),
364
+ }),
365
);
apps/server/src/storageCleanup.test.ts
+16
-16
@@ -610,7 +610,7 @@ const runCleanupTest = <A, E>(
610
| Path.Path
611
| Scope.Scope
612
>,
613
-) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped);
613
+) => effect.pipe(Effect.provide(cleanupTestLayer));
614
615
it.live.each(["repository", "uppercase", "bare"] as const)(
616
"keeps a worktree holding an ignored nested %s",
@@ -1005,7 +1005,7 @@ describe("subagent worktree ownership", () => {
1005
? "Thread is running or has pending work"
1006
: "Not settled",
1007
});
1008
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1008
+ }).pipe(Effect.provide(cleanupTestLayer)),
1009
);
1010
1011
it.effect.each([
@@ -1210,7 +1210,7 @@ describe("subagent worktree ownership", () => {
1210
? "Settled moments ago"
1211
: "Not settled",
1212
});
1213
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1213
+ }).pipe(Effect.provide(cleanupTestLayer)),
1214
);
1215
1216
it.effect("keeps a checkout two top-level threads store through a symlinked parent", () =>
@@ -1232,7 +1232,7 @@ describe("subagent worktree ownership", () => {
1232
expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }),
1233
]);
1234
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
1235
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1235
+ }).pipe(Effect.provide(cleanupTestLayer)),
1236
);
1237
1238
it.effect("keeps a checkout two top-level threads store in different case on Windows", () =>
@@ -1256,7 +1256,7 @@ describe("subagent worktree ownership", () => {
1256
expect.objectContaining({ outcome: "kept", reason: "Shared by 2 threads" }),
1257
]);
1258
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
1259
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1259
+ }).pipe(Effect.provide(cleanupTestLayer)),
1260
);
1261
1262
it.effect.each([
@@ -1361,7 +1361,7 @@ describe("deleted thread worktrees", () => {
1361
reason: "Thread was deleted",
1362
});
1363
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1364
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1364
+ }).pipe(Effect.provide(cleanupTestLayer)),
1365
);
1366
1367
it.effect("applies the remaining subagent's rules when deletion cleanup is off", () =>
@@ -1383,7 +1383,7 @@ describe("deleted thread worktrees", () => {
1383
reason: "Inactive for 30 days",
1384
});
1385
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1386
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1386
+ }).pipe(Effect.provide(cleanupTestLayer)),
1387
);
1388
1389
// Releases one stopped-session event after the startup sweep and returns the snapshot reads it caused.
@@ -1442,7 +1442,7 @@ describe("deleted thread worktrees", () => {
1442
const fixture = yield* cleanupFixture();
1443
const reads = yield* stopSessionAfterStartupSweep(fixture, ThreadId.make("thread-1"));
1444
expect(reads, "a live thread's stopped session re-read every thread").toBe(0);
1445
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1445
+ }).pipe(Effect.provide(cleanupTestLayer)),
1446
);
1447
1448
it.effect("removes a deleted thread's worktree once its session stops", () =>
@@ -1464,7 +1464,7 @@ describe("deleted thread worktrees", () => {
1464
);
1465
expect(reads).toBeGreaterThan(0);
1466
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1467
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1467
+ }).pipe(Effect.provide(cleanupTestLayer)),
1468
);
1469
1470
it.effect("removes a deleted thread's worktree once a live thread's session in it stops", () =>
@@ -1494,7 +1494,7 @@ describe("deleted thread worktrees", () => {
1494
);
1495
expect(reads).toBeGreaterThan(0);
1496
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1497
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1497
+ }).pipe(Effect.provide(cleanupTestLayer)),
1498
);
1499
1500
it.effect(
@@ -1540,7 +1540,7 @@ describe("deleted thread worktrees", () => {
1540
);
1541
expect(reads).toBeGreaterThan(0);
1542
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1543
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1543
+ }).pipe(Effect.provide(cleanupTestLayer)),
1544
);
1545
1546
it.effect(
@@ -1573,7 +1573,7 @@ describe("deleted thread worktrees", () => {
1573
);
1574
expect(reads).toBeGreaterThan(0);
1575
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1576
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1576
+ }).pipe(Effect.provide(cleanupTestLayer)),
1577
);
1578
1579
it.effect("does not sweep for a kept deleted worktree when a session elsewhere stops", () =>
@@ -1595,7 +1595,7 @@ describe("deleted thread worktrees", () => {
1595
);
1596
expect(reads).toBe(0);
1597
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
1598
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1598
+ }).pipe(Effect.provide(cleanupTestLayer)),
1599
);
1600
1601
it.effect(
@@ -1625,7 +1625,7 @@ describe("deleted thread worktrees", () => {
1625
fixture.repo,
1626
);
1627
expect(reads).toBe(0);
1628
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1628
+ }).pipe(Effect.provide(cleanupTestLayer)),
1629
);
1630
1631
it.effect(
@@ -1699,7 +1699,7 @@ describe("deleted thread worktrees", () => {
1699
yield* Deferred.await(delivered);
1700
yield* fixture.service.drain;
1701
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false);
1702
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1702
+ }).pipe(Effect.provide(cleanupTestLayer)),
1703
);
1704
1705
it.effect("waits out the settle grace of a subagent that just settled", () =>
@@ -1720,7 +1720,7 @@ describe("deleted thread worktrees", () => {
1720
reason: "Settled moments ago",
1721
});
1722
expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true);
1723
- }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped),
1723
+ }).pipe(Effect.provide(cleanupTestLayer)),
1724
);
1725
});
1726
apps/server/src/terminal/Manager.test.ts
+5
-5
@@ -2442,7 +2442,7 @@ it.layer(
2442
{ type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } },
2443
]);
2444
expect(ptyAdapter.processes).toHaveLength(1);
2445
- }).pipe(Effect.scoped),
2445
+ }),
2446
);
2447
2448
it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () =>
@@ -2516,7 +2516,7 @@ it.layer(
2516
ptyAdapter.processes.at(-1)!.emitData("new session only\n");
2517
expect(yield* pull).toMatchObject([{ type: "output", data: "new session only\n" }]);
2518
expect(ptyAdapter.spawnInputs).toHaveLength(4);
2519
- }).pipe(Effect.scoped),
2519
+ }),
2520
);
2521
2522
it.effect.each([
@@ -2563,7 +2563,7 @@ it.layer(
2563
2564
yield* Deferred.await(restored);
2565
expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
2566
- }).pipe(Effect.scoped),
2566
+ }),
2567
);
2568
2569
it.effect("sends bounded attach streams only the history the client retains", () =>
@@ -2614,7 +2614,7 @@ it.layer(
2614
expect(yield* full).toEqual(yield* bounded);
2615
yield* manager.attachStream({ ...openInput(), restartIfNotRunning: true }, () => Effect.void);
2616
yield* expectRetained();
2617
- }).pipe(Effect.scoped),
2617
+ }),
2618
);
2619
2620
it.effect("does not replay in-flight output already included in an observer snapshot", () =>
@@ -2651,7 +2651,7 @@ it.layer(
2651
expect(observed.filter((event) => event.type === "output")).toMatchObject([
2652
{ data: "after\n" },
2653
]);
2654
- }).pipe(Effect.scoped),
2654
+ }),
2655
);
2656
2657
it.effect("observes terminal history and live output without changing the process", () =>
apps/server/src/terminal/OutputProtocol.test.ts
+6
-6
@@ -101,7 +101,7 @@ describe("terminal output window", () => {
101
assert.equal(yield* Queue.size(responses), 0);
102
yield* write(0, { _tag: "Interrupt", requestId: "1" });
103
assert.equal((yield* Queue.take(responses))._tag, "Exit");
104
- }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
104
+ }).pipe(Effect.provide(RpcSerialization.layerJson)),
105
);
106
});
107
@@ -261,7 +261,7 @@ describe("terminal output stream", () => {
261
assert.deepEqual(yield* takeChunk(healthy), [after]);
262
assert.deepEqual(yield* takeChunk(stalled), [after]);
263
assert.equal(yield* Queue.size(stalled), 0);
264
- }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped),
264
+ }).pipe(Effect.provide(RpcSerialization.layerJson)),
265
);
266
267
it.effect("interrupts recovery while its subscription is still waiting", () =>
@@ -290,7 +290,7 @@ describe("terminal output stream", () => {
290
yield* Fiber.interrupt(recovery);
291
yield* Deferred.await(interrupted);
292
assert.equal(publisher.listeners.size, 0);
293
- }).pipe(Effect.scoped),
293
+ }),
294
);
295
296
it.effect("cleans listeners when cancelled during a successful acquisition handoff", () =>
@@ -324,7 +324,7 @@ describe("terminal output stream", () => {
324
yield* Fiber.join(cancellation);
325
assert.equal(publisher.listeners.size, 0);
326
}
327
- }).pipe(Effect.scoped),
327
+ }),
328
);
329
330
it.effect("caps each delivered batch at the output window in UTF-8 bytes", () =>
@@ -349,7 +349,7 @@ describe("terminal output stream", () => {
349
delivered += batch.length;
350
}
351
assert.equal(delivered, 1024);
352
- }).pipe(Effect.scoped),
352
+ }),
353
);
354
355
it.effect("charges snapshot history but never overflows on one snapshot", () =>
@@ -367,6 +367,6 @@ describe("terminal output stream", () => {
367
assert.equal(publisher.listeners.size, 1);
368
yield* publisher.publish(snapshot(history));
369
assert.equal(publisher.listeners.size, 0);
370
- }).pipe(Effect.scoped),
370
+ }),
371
);
372
});
apps/server/src/textGeneration/AntigravityTextGeneration.test.ts
+15
-15
@@ -343,7 +343,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
343
{ type: "text", text: expect.stringContaining("+handleRemoteCallback()") },
344
]);
345
yield* fixture.assertCleaned;
346
- }).pipe(Effect.scoped),
346
+ }),
347
);
348
349
it.effect.each(["tool_call", "tool_call_update"] as const)(
@@ -362,7 +362,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
362
expect(error.detail).toContain("tool work");
363
expect(fixture.state.cancellations).toBe(1);
364
yield* fixture.assertCleaned;
365
- }).pipe(Effect.scoped),
365
+ }),
366
);
367
368
it.effect("rejects native permission and choice requests instead of answering them", () =>
@@ -387,7 +387,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
387
expect(reply).toEqual({ outcome: { outcome: "cancelled" } });
388
expect(error.detail).toContain("permission or user input");
389
yield* fixture.assertCleaned;
390
- }).pipe(Effect.scoped),
390
+ }),
391
);
392
393
it.effect.each(["file", "terminal", "extension"] as const)(
@@ -416,7 +416,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
416
const error = yield* Fiber.join(child).pipe(Effect.flip);
417
expect(error.detail).toContain("tool or user input");
418
yield* fixture.assertCleaned;
419
- }).pipe(Effect.scoped),
419
+ }),
420
);
421
422
it.effect.each([
@@ -432,7 +432,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
432
.pipe(Effect.flip);
433
expect(error.detail).toContain(detail);
434
yield* fixture.assertCleaned;
435
- }).pipe(Effect.scoped),
435
+ }),
436
);
437
438
it.effect("does not return partial JSON after native cancellation", () =>
@@ -449,7 +449,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
449
.pipe(Effect.flip);
450
expect(error.detail).toContain("cancelled");
451
yield* fixture.assertCleaned;
452
- }).pipe(Effect.scoped),
452
+ }),
453
);
454
455
it.effect.each([
@@ -470,7 +470,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
470
expect(error.detail).toBe(detail);
471
expect(error.detail).not.toContain("Raw provider failure text.");
472
yield* fixture.assertCleaned;
473
- }).pipe(Effect.scoped),
473
+ }),
474
);
475
476
it.effect.each([
@@ -517,7 +517,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
517
expect(error.detail).toContain("wrote files");
518
if (target !== undefined) expect(yield* fs.exists(target)).toBe(true);
519
yield* fixture.assertCleaned;
520
- }).pipe(Effect.scoped),
520
+ }),
521
);
522
523
it.effect("uses the native default without sending T3's default selection as a model ID", () =>
@@ -530,7 +530,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
530
expect(result).toEqual({ title: "Repair login" });
531
expect(fixture.state.selectedModels).toEqual([]);
532
yield* fixture.assertCleaned;
533
- }).pipe(Effect.scoped),
533
+ }),
534
);
535
536
it.effect.each([
@@ -562,7 +562,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
562
expect(Exit.isSuccess(result)).toBe(available);
563
expect(fixture.state.workspaces.length).toBe(available ? 1 : 0);
564
yield* fixture.assertCleaned;
565
- }).pipe(Effect.scoped),
565
+ }),
566
);
567
568
it.effect("does not launch during sign-out or before sign-in", () =>
@@ -575,7 +575,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
575
expect(error.detail).toBe("Sign in before starting Antigravity.");
576
expect(fixture.state.workspaces).toEqual([]);
577
yield* fixture.assertCleaned;
578
- }).pipe(Effect.scoped),
578
+ }),
579
);
580
581
it.effect.each(["caller", "sign-out"] as const)(
@@ -596,7 +596,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
596
}
597
expect(fixture.state.cancellations).toBe(1);
598
yield* fixture.assertCleaned;
599
- }).pipe(Effect.scoped),
599
+ }),
600
);
601
602
it.effect("refuses unsafe native session IDs without deleting other files", () =>
@@ -609,7 +609,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
609
expect(fixture.state.prompts).toEqual([]);
610
expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.db`)).toBe("helper session");
611
expect(fixture.state.closed).toEqual(fixture.state.workspaces);
612
- }).pipe(Effect.scoped),
612
+ }),
613
);
614
615
it.effect("keeps native sessions whose metadata belongs to a different workspace", () =>
@@ -627,7 +627,7 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => {
627
"keep this session",
628
);
629
expect(yield* fixture.fs.readFileString(`${fixture.sessionBase}.meta`)).toBe(metadata);
630
- }).pipe(Effect.scoped),
630
+ }),
631
);
632
});
633
@@ -640,5 +640,5 @@ it.effect("retains filesystem services supplied only during construction", () =>
640
title: "Repair login",
641
});
642
yield* fixture.assertCleaned;
643
- }).pipe(Effect.scoped),
643
+ }),
644
);
apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts
+3
-3
@@ -70,7 +70,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => {
70
files: [{ uri: NodeURL.pathToFileURL(screenshotPath).href, name: "screen.png" }],
71
});
72
}
73
- }).pipe(Effect.scoped),
73
+ }),
74
);
75
76
it.effect("keeps a provider's own error message out of the caller-visible detail", () =>
@@ -153,7 +153,7 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => {
153
.pipe(Effect.flip);
154
assert.equal(failure.detail, "OpenCode could not generate the text.");
155
assert.deepEqual(failure.cause, refusal);
156
- }).pipe(Effect.scoped),
156
+ }),
157
);
158
159
it.effect("times out when the prompt request and its interrupt never answer", () =>
@@ -219,6 +219,6 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => {
219
yield* TestClock.adjust("5 seconds");
220
const failure = yield* Fiber.join(generation);
221
assert.equal(failure.detail, "OpenCode did not finish generating in time.");
222
- }).pipe(Effect.scoped),
222
+ }),
223
);
224
});
apps/server/src/usage/UsageLimitSources.test.ts
-2
@@ -87,7 +87,6 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () =>
87
),
88
NodeCrypto.layer,
89
]),
90
- Effect.scoped,
90
),
91
);
92
@@ -154,6 +153,5 @@ it.effect("reads a management key from its secret provider", () => {
153
),
154
NodeCrypto.layer,
155
]),
157
- Effect.scoped,
156
);
157
});
apps/server/src/usage/UsageService.test.ts
+42
-42
@@ -631,7 +631,7 @@ describe("UsageService", () => {
631
Effect.scoped,
632
Effect.provide(layerService({ prefix: "usage-compressed-codex", home, settings })),
633
);
634
- }).pipe(Effect.scoped),
634
+ }),
635
);
636
637
it.effect("keeps the first host identity across recreation and explicit override removal", () =>
@@ -662,7 +662,7 @@ describe("UsageService", () => {
662
const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
663
assert.strictEqual(source?.fingerprint.hostId, expected);
664
}
665
- }).pipe(Effect.scoped),
665
+ }),
666
);
667
668
it.effect("concurrent initialization keeps one host identity across service recreation", () =>
@@ -718,7 +718,7 @@ describe("UsageService", () => {
718
const source = summary.sources.find((source) => source.fingerprint.provider === "claude");
719
assert.strictEqual(source?.fingerprint.hostId, hostId);
720
}
721
- }).pipe(Effect.scoped),
721
+ }),
722
);
723
724
it.effect(
@@ -870,7 +870,7 @@ describe("UsageService", () => {
870
}),
871
),
872
);
873
- }).pipe(Effect.scoped),
873
+ }),
874
);
875
876
it.effect(
@@ -966,7 +966,7 @@ describe("UsageService", () => {
966
}),
967
),
968
);
969
- }).pipe(Effect.scoped),
969
+ }),
970
);
971
972
it.effect(
@@ -1155,7 +1155,7 @@ describe("UsageService", () => {
1155
}),
1156
),
1157
);
1158
- }).pipe(Effect.scoped),
1158
+ }),
1159
);
1160
1161
it.effect(
@@ -1377,7 +1377,7 @@ describe("UsageService", () => {
1377
}),
1378
),
1379
);
1380
- }).pipe(Effect.scoped),
1380
+ }),
1381
);
1382
1383
it.effect("returns other providers' usage while Muse home discovery is still pending", () =>
@@ -1437,7 +1437,7 @@ describe("UsageService", () => {
1437
assert.deepStrictEqual(museSources(refreshed), [
1438
[NodePath.join(museHome, "sessions"), "ok", undefined],
1439
]);
1440
- }).pipe(Effect.scoped),
1440
+ }),
1441
);
1442
1443
it.effect(
@@ -1502,7 +1502,7 @@ describe("UsageService", () => {
1502
Effect.scoped,
1503
Effect.provide(layerService({ prefix: "usage-pi-malformed", home, settings })),
1504
);
1505
- }).pipe(Effect.scoped),
1505
+ }),
1506
);
1507
1508
it.effect("discovers Pi history in its default home and directory overrides", () =>
@@ -1609,7 +1609,7 @@ describe("UsageService", () => {
1609
Effect.provideService(HostProcess.HomeDirectory, home),
1610
);
1611
}
1612
- }).pipe(Effect.scoped),
1612
+ }),
1613
);
1614
1615
it.effect("reads shared managed default and disabled extra account history once", () =>
@@ -1689,7 +1689,7 @@ describe("UsageService", () => {
1689
).length,
1690
1,
1691
);
1692
- }).pipe(Effect.scoped),
1692
+ }),
1693
);
1694
1695
it.effect("restores the Cursor account cache after a restart", () =>
@@ -1731,7 +1731,7 @@ describe("UsageService", () => {
1731
}),
1732
),
1733
);
1734
- }).pipe(Effect.scoped),
1734
+ }),
1735
);
1736
1737
it.effect("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () =>
@@ -1783,7 +1783,7 @@ describe("UsageService", () => {
1783
]);
1784
assert.strictEqual(cursorSource(summary)?.status, "ok");
1785
}
1786
- }).pipe(Effect.scoped),
1786
+ }),
1787
);
1788
1789
it.effect("does not show a previous Cursor account's history after the API key changes", () =>
@@ -1825,7 +1825,7 @@ describe("UsageService", () => {
1825
}),
1826
),
1827
);
1828
- }).pipe(Effect.scoped),
1828
+ }),
1829
);
1830
1831
it.effect("keeps a new Cursor key's refresh visible beside a failing key", () =>
@@ -1910,7 +1910,7 @@ describe("UsageService", () => {
1910
}),
1911
),
1912
);
1913
- }).pipe(Effect.scoped),
1913
+ }),
1914
);
1915
1916
it.effect("reports one Cursor source when two API keys belong to the same account", () =>
@@ -1972,7 +1972,7 @@ describe("UsageService", () => {
1972
}),
1973
),
1974
);
1975
- }).pipe(Effect.scoped),
1975
+ }),
1976
);
1977
1978
it.effect(
@@ -2029,7 +2029,7 @@ describe("UsageService", () => {
2029
?.distinctSessions,
2030
1,
2031
);
2032
- }).pipe(Effect.scoped),
2032
+ }),
2033
);
2034
2035
it.effect("counts unpriced tokens from the unpriced records of a mixed model", () =>
@@ -2066,7 +2066,7 @@ describe("UsageService", () => {
2066
assert.strictEqual(model?.costUsd, 1);
2067
assert.strictEqual(model?.totalTokens, 10_000);
2068
assert.strictEqual(model?.unpricedTokens, 9_900);
2069
- }).pipe(Effect.scoped),
2069
+ }),
2070
);
2071
2072
it.effect("includes host and merged OpenCode instance histories once across list aliases", () =>
@@ -2145,7 +2145,7 @@ describe("UsageService", () => {
2145
.sort((a, b) => a - b),
2146
[5, 7, 11],
2147
);
2148
- }).pipe(Effect.scoped),
2148
+ }),
2149
);
2150
2151
it.effect("counts aliased OpenCode and Antigravity directories once", () =>
@@ -2199,7 +2199,7 @@ describe("UsageService", () => {
2199
sourcesFor("antigravity")[0]?.fingerprint.resolvedHomePath,
2200
yield* Effect.promise(() => NodeFSP.realpath(conversations)),
2201
);
2202
- }).pipe(Effect.scoped),
2202
+ }),
2203
);
2204
2205
it.effect("reads Antigravity history from each instance's data directory", () =>
@@ -2270,7 +2270,7 @@ describe("UsageService", () => {
2270
outputTokens,
2271
);
2272
}
2273
- }).pipe(Effect.scoped),
2273
+ }),
2274
);
2275
2276
it.effect("reads configured and disabled accounts once across shared and aliased homes", () =>
@@ -2389,7 +2389,7 @@ describe("UsageService", () => {
2389
sources.filter((source) => source.fingerprint.provider === "codex").length,
2390
1,
2391
);
2392
- }).pipe(Effect.scoped),
2392
+ }),
2393
);
2394
2395
it.effect(
@@ -2472,7 +2472,7 @@ describe("UsageService", () => {
2472
}),
2473
),
2474
);
2475
- }).pipe(Effect.scoped),
2475
+ }),
2476
);
2477
2478
it.effect(
@@ -2518,7 +2518,7 @@ describe("UsageService", () => {
2518
.resolvedHomePath,
2519
NodePath.join(home, "grok", "sessions"),
2520
);
2521
- }).pipe(Effect.scoped),
2521
+ }),
2522
);
2523
2524
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)(
@@ -2546,7 +2546,7 @@ describe("UsageService", () => {
2546
}).pipe(
2547
Effect.provide(layerService({ prefix: "usage-service-unreadable", home, settings })),
2548
);
2549
- }).pipe(Effect.scoped),
2549
+ }),
2550
);
2551
2552
it.effect(
@@ -2615,7 +2615,7 @@ describe("UsageService", () => {
2615
Effect.scoped,
2616
Effect.provide(layerService({ prefix: "usage-service-provisional", home, settings })),
2617
);
2618
- }).pipe(Effect.scoped),
2618
+ }),
2619
);
2620
2621
it.effect("filters original model IDs before aliases, pricing, buckets and session counts", () =>
@@ -2720,7 +2720,7 @@ describe("UsageService", () => {
2720
}),
2721
),
2722
);
2723
- }).pipe(Effect.scoped),
2723
+ }),
2724
);
2725
2726
it.effect("reprices unchanged transcripts when custom prices are added, edited, or removed", () =>
@@ -2764,7 +2764,7 @@ describe("UsageService", () => {
2764
layerService({ prefix: "usage-service-price-overrides-test", home, settings }),
2765
),
2766
);
2767
- }).pipe(Effect.scoped),
2767
+ }),
2768
);
2769
2770
it.effect(
@@ -2887,7 +2887,7 @@ describe("UsageService", () => {
2887
}),
2888
),
2889
);
2890
- }).pipe(Effect.scoped),
2890
+ }),
2891
);
2892
2893
it.effect(
@@ -2946,7 +2946,7 @@ describe("UsageService", () => {
2946
}),
2947
),
2948
);
2949
- }).pipe(Effect.scoped),
2949
+ }),
2950
);
2951
2952
it.effect(
@@ -3001,7 +3001,7 @@ describe("UsageService", () => {
3001
}),
3002
),
3003
);
3004
- }).pipe(Effect.scoped),
3004
+ }),
3005
);
3006
3007
it.effect.each([4, 5, 6, 7, 8, 10, 11, 12, 13, 14])(
@@ -3132,7 +3132,7 @@ describe("UsageService", () => {
3132
}),
3133
),
3134
);
3135
- }).pipe(Effect.scoped),
3135
+ }),
3136
);
3137
3138
it.effect("re-parses a clean v10 Codex rollout that grew after an interrupted request", () =>
@@ -3232,7 +3232,7 @@ describe("UsageService", () => {
3232
}),
3233
),
3234
);
3235
- }).pipe(Effect.scoped),
3235
+ }),
3236
);
3237
3238
it.effect("preserves saved tokens, costs and sessions after transcript cleanup and restart", () =>
@@ -3333,7 +3333,7 @@ describe("UsageService", () => {
3333
}),
3334
),
3335
);
3336
- }).pipe(Effect.scoped),
3336
+ }),
3337
);
3338
3339
it.effect("credits the same copy of a duplicate after its transcripts are deleted", () =>
@@ -3371,7 +3371,7 @@ describe("UsageService", () => {
3371
}).pipe(
3372
Effect.provide(layerService({ prefix: "usage-service-copy-order-test", home, settings })),
3373
);
3374
- }).pipe(Effect.scoped),
3374
+ }),
3375
);
3376
3377
it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () =>
@@ -3429,7 +3429,7 @@ describe("UsageService", () => {
3429
}).pipe(
3430
Effect.provide(layerService({ prefix: "usage-service-narrow-order-test", home, settings })),
3431
);
3432
- }).pipe(Effect.scoped),
3432
+ }),
3433
);
3434
3435
it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
@@ -3459,7 +3459,7 @@ describe("UsageService", () => {
3459
}).pipe(
3460
Effect.provide(layerService({ prefix: "usage-service-stale-read-test", home, settings })),
3461
);
3462
- }).pipe(Effect.scoped),
3462
+ }),
3463
);
3464
3465
it.effect(
@@ -3505,7 +3505,7 @@ describe("UsageService", () => {
3505
layerService({ prefix: "usage-service-missing-diagnostics", home, settings }),
3506
),
3507
);
3508
- }).pipe(Effect.scoped),
3508
+ }),
3509
);
3510
3511
it.effect("reports saved usage of a removed directory only for windows it reaches", () =>
@@ -3539,7 +3539,7 @@ describe("UsageService", () => {
3539
assert.deepStrictEqual(later.buckets, []);
3540
assert.strictEqual(later.sources[0]?.status, "missing");
3541
assert.strictEqual(later.sources[0]?.scannedFiles, 0);
3542
- }).pipe(Effect.scoped),
3542
+ }),
3543
);
3544
3545
it.effect("does not share an in-flight scan after custom prices change", () =>
@@ -3608,7 +3608,7 @@ describe("UsageService", () => {
3608
}).pipe(
3609
Effect.provide(layerService({ prefix: "usage-service-price-race-test", home, settings })),
3610
);
3611
- }).pipe(Effect.scoped),
3611
+ }),
3612
);
3613
3614
it.effect.each(["network", "http", "invalidJson", "empty"] as const)(
@@ -3667,7 +3667,7 @@ describe("UsageService", () => {
3667
assert.strictEqual(cached.pricing.status, "cached");
3668
assert.deepStrictEqual(cached.buckets, summary.buckets);
3669
assert.strictEqual(requests.length, 2);
3670
- }).pipe(Effect.scoped),
3670
+ }),
3671
);
3672
3673
it.effect("does not orphan an in-flight scan when its first caller is interrupted", () =>
@@ -3745,6 +3745,6 @@ describe("UsageService", () => {
3745
orphanedAt,
3746
`interruption left the next matching request pending at scheduler check ${orphanedAt}`,
3747
);
3748
- }).pipe(Effect.scoped),
3748
+ }),
3749
);
3750
});
apps/server/src/utils/subscribeBeforeSnapshot.test.ts
+52
-56
@@ -15,70 +15,66 @@ import {
15
16
describe("subscribeBeforeSnapshot", () => {
17
it.effect("atomically reads the initial snapshot before receiving later changes", () =>
18
- Effect.scoped(
19
- Effect.gen(function* () {
20
- const changes = yield* PubSub.sliding<number>(1);
21
- const latest = yield* Ref.make(1);
22
- const mutex = yield* Semaphore.make(1);
23
- const snapshotStarted = yield* Deferred.make<void>();
24
- const finishSnapshot = yield* Deferred.make<void>();
25
- const subscriptionFiber = yield* subscribeBeforeSnapshot(
26
- changes,
27
- Deferred.succeed(snapshotStarted, undefined).pipe(
28
- Effect.andThen(Deferred.await(finishSnapshot)),
29
- Effect.andThen(Ref.get(latest)),
30
- ),
31
- mutex,
32
- ).pipe(Effect.forkChild);
18
+ Effect.gen(function* () {
19
+ const changes = yield* PubSub.sliding<number>(1);
20
+ const latest = yield* Ref.make(1);
21
+ const mutex = yield* Semaphore.make(1);
22
+ const snapshotStarted = yield* Deferred.make<void>();
23
+ const finishSnapshot = yield* Deferred.make<void>();
24
+ const subscriptionFiber = yield* subscribeBeforeSnapshot(
25
+ changes,
26
+ Deferred.succeed(snapshotStarted, undefined).pipe(
27
+ Effect.andThen(Deferred.await(finishSnapshot)),
28
+ Effect.andThen(Ref.get(latest)),
29
+ ),
30
+ mutex,
31
+ ).pipe(Effect.forkChild);
32
34
- yield* Deferred.await(snapshotStarted);
35
- const publishFiber = yield* mutex
36
- .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2))))
37
- .pipe(Effect.forkChild);
38
- yield* Deferred.succeed(finishSnapshot, undefined);
33
+ yield* Deferred.await(snapshotStarted);
34
+ const publishFiber = yield* mutex
35
+ .withPermits(1)(Ref.set(latest, 2).pipe(Effect.andThen(PubSub.publish(changes, 2))))
36
+ .pipe(Effect.forkChild);
37
+ yield* Deferred.succeed(finishSnapshot, undefined);
38
40
- const subscription = yield* Fiber.join(subscriptionFiber);
41
- yield* Fiber.join(publishFiber);
42
- const firstChange = yield* subscription.changes.pipe(
43
- Stream.runHead,
44
- Effect.timeout("1 second"),
45
- );
39
+ const subscription = yield* Fiber.join(subscriptionFiber);
40
+ yield* Fiber.join(publishFiber);
41
+ const firstChange = yield* subscription.changes.pipe(
42
+ Stream.runHead,
43
+ Effect.timeout("1 second"),
44
+ );
45
47
- expect(subscription.latest).toBe(1);
48
- expect(firstChange).toEqual(Option.some(2));
49
- }),
50
- ),
46
+ expect(subscription.latest).toBe(1);
47
+ expect(firstChange).toEqual(Option.some(2));
48
+ }),
49
);
50
51
it.effect("subscribes before an uncoordinated snapshot can change", () =>
54
- Effect.scoped(
55
- Effect.gen(function* () {
56
- const changes = yield* PubSub.sliding<number>(1);
57
- const latest = yield* Ref.make(1);
58
- const snapshotStarted = yield* Deferred.make<void>();
59
- const finishSnapshot = yield* Deferred.make<void>();
60
- const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex(
61
- changes,
62
- Deferred.succeed(snapshotStarted, undefined).pipe(
63
- Effect.andThen(Deferred.await(finishSnapshot)),
64
- Effect.andThen(Ref.get(latest)),
65
- ),
66
- ).pipe(Effect.forkChild);
52
+ Effect.gen(function* () {
53
+ const changes = yield* PubSub.sliding<number>(1);
54
+ const latest = yield* Ref.make(1);
55
+ const snapshotStarted = yield* Deferred.make<void>();
56
+ const finishSnapshot = yield* Deferred.make<void>();
57
+ const subscriptionFiber = yield* subscribeBeforeSnapshotWithoutMutex(
58
+ changes,
59
+ Deferred.succeed(snapshotStarted, undefined).pipe(
60
+ Effect.andThen(Deferred.await(finishSnapshot)),
61
+ Effect.andThen(Ref.get(latest)),
62
+ ),
63
+ ).pipe(Effect.forkChild);
64
68
- yield* Deferred.await(snapshotStarted);
69
- yield* Ref.set(latest, 2);
70
- yield* PubSub.publish(changes, 2);
71
- yield* Deferred.succeed(finishSnapshot, undefined);
65
+ yield* Deferred.await(snapshotStarted);
66
+ yield* Ref.set(latest, 2);
67
+ yield* PubSub.publish(changes, 2);
68
+ yield* Deferred.succeed(finishSnapshot, undefined);
69
73
- const subscription = yield* Fiber.join(subscriptionFiber);
74
- const firstChange = yield* subscription.changes.pipe(
75
- Stream.runHead,
76
- Effect.timeout("1 second"),
77
- );
70
+ const subscription = yield* Fiber.join(subscriptionFiber);
71
+ const firstChange = yield* subscription.changes.pipe(
72
+ Stream.runHead,
73
+ Effect.timeout("1 second"),
74
+ );
75
79
- expect(subscription.latest).toBe(2);
80
- expect(firstChange).toEqual(Option.some(2));
81
- }),
82
- ),
76
+ expect(subscription.latest).toBe(2);
77
+ expect(firstChange).toEqual(Option.some(2));
78
+ }),
79
);
80
});
apps/server/src/vcs/VcsProcess.test.ts
+1
-1
@@ -92,7 +92,7 @@ describe("VcsProcess.run", () => {
92
yield* fs.remove(lock);
93
yield* git(restore);
94
expect(yield* fs.readFileString(file)).toBe("before\n");
95
- }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),
95
+ }).pipe(provideLive, Effect.provide(NodeServices.layer)),
96
);
97
98
it.effect.each([
apps/server/src/vcs/VcsStatusBroadcaster.test.ts
+20
-20
@@ -250,7 +250,7 @@ describe("VcsStatusBroadcaster", () => {
250
251
yield* broadcaster.refreshLocalStatus("/repo");
252
assert.strictEqual(state.localStatusCalls, 3);
253
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
253
+ }).pipe(Effect.provide(layerTestFor(state)));
254
});
255
256
it.effect(
@@ -345,7 +345,7 @@ describe("VcsStatusBroadcaster", () => {
345
]);
346
assert.deepEqual(yield* branches, [{ refName: null, isRepo: false }]);
347
assert.equal(state.remoteStatusCalls, 0);
348
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
348
+ }).pipe(Effect.provide(layerTestFor(state)));
349
},
350
);
351
@@ -382,7 +382,7 @@ describe("VcsStatusBroadcaster", () => {
382
yield* Fiber.join(detailsFiber),
383
Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }),
384
);
385
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
385
+ }).pipe(Effect.provide(layerTestFor(state)));
386
});
387
388
it.effect("publishes terminal branch switches and validates cached status reads", () => {
@@ -577,7 +577,7 @@ describe("VcsStatusBroadcaster", () => {
577
const afterLookup = yield* broadcaster.getStatus({ cwd: "/repo" });
578
assert.equal(afterLookup.aheadCount, 4);
579
assert.equal(afterLookup.behindCount, behindAfterLookup);
580
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
580
+ }).pipe(Effect.provide(layerTestFor(state)));
581
},
582
);
583
@@ -800,7 +800,7 @@ describe("VcsStatusBroadcaster", () => {
800
assert.deepStrictEqual(refreshed, remoteStatusWithPr);
801
const final = yield* broadcaster.getStatus({ cwd: "/repo" });
802
assert.deepStrictEqual(final.pr, remoteStatusWithPr.pr);
803
- }).pipe(Effect.provide(layer), Effect.scoped);
803
+ }).pipe(Effect.provide(layer));
804
});
805
806
it.effect("an initial status read cannot overwrite an explicit refresh", () => {
@@ -844,7 +844,7 @@ describe("VcsStatusBroadcaster", () => {
844
(yield* broadcaster.getStatus({ cwd: "/repo" })).pr,
845
remoteStatusWithPr.pr,
846
);
847
- }).pipe(Effect.provide(layer), Effect.scoped);
847
+ }).pipe(Effect.provide(layer));
848
});
849
850
it.effect("keeps the published local snapshot when a refresh remote read fails", () => {
@@ -1030,7 +1030,7 @@ describe("VcsStatusBroadcaster", () => {
1030
yield* Deferred.await(polled);
1031
const status = yield* broadcaster.getStatus({ cwd: "/repo" });
1032
assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges);
1033
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1033
+ }).pipe(Effect.provide(layerTestFor(state)));
1034
});
1035
1036
it.effect("an explicit refresh reads local totals after the fetch", () => {
@@ -1130,7 +1130,7 @@ describe("VcsStatusBroadcaster", () => {
1130
const status = yield* Fiber.join(refresh);
1131
assert.isTrue(status.hasWorkingTreeChanges);
1132
assert.deepStrictEqual(status.pr, remoteStatusWithPr.pr);
1133
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1133
+ }).pipe(Effect.provide(layerTestFor(state)));
1134
});
1135
1136
it.effect("publishes local changes before a remote error and propagates that error", () => {
@@ -1192,7 +1192,7 @@ describe("VcsStatusBroadcaster", () => {
1192
assert.isTrue(cached.hasWorkingTreeChanges);
1193
assert.deepStrictEqual(cached.pr, remoteStatusWithPr.pr);
1194
assert.deepStrictEqual(yield* Deferred.await(published), state.currentLocalStatus);
1195
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1195
+ }).pipe(Effect.provide(layerTestFor(state)));
1196
});
1197
1198
it.effect.each(["getStatus", "refreshStatus", "autoPull", "autoPullFailure"] as const)(
@@ -1278,7 +1278,7 @@ describe("VcsStatusBroadcaster", () => {
1278
assert.isNull(status.pr);
1279
assert.equal(status.aheadCount, 0);
1280
assert.equal(status.behindCount, 0);
1281
- }).pipe(Effect.provide(layerTest), Effect.scoped);
1281
+ }).pipe(Effect.provide(layerTest));
1282
},
1283
);
1284
@@ -1328,7 +1328,7 @@ describe("VcsStatusBroadcaster", () => {
1328
assert.deepStrictEqual(cached.pr, state.currentRemoteStatus.pr);
1329
assert.equal(cached.aheadCount, 2);
1330
assert.equal(state.remoteStatusCalls, 2);
1331
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1331
+ }).pipe(Effect.provide(layerTestFor(state)));
1332
});
1333
1334
it.effect("a terminal checkout publishes the new branch without waiting for a poll", () =>
@@ -1380,7 +1380,7 @@ describe("VcsStatusBroadcaster", () => {
1380
// A checkout must not trigger a network fetch.
1381
assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues.slice(1), [false]);
1382
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1383
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1383
+ }).pipe(Effect.provide(NodeServices.layer)),
1384
);
1385
1386
it.effect("a terminal checkout updates branch-only subscribers without full status", () =>
@@ -1413,7 +1413,7 @@ describe("VcsStatusBroadcaster", () => {
1413
assert.deepEqual(yield* branches, [{ refName: "repro", isRepo: true }]);
1414
assert.equal(state.localStatusCalls, 0);
1415
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1416
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1416
+ }).pipe(Effect.provide(NodeServices.layer)),
1417
);
1418
1419
it.effect("a checkout read that fails while index.lock is held retries until it succeeds", () =>
@@ -1468,7 +1468,7 @@ describe("VcsStatusBroadcaster", () => {
1468
yield* Deferred.await(checkedOut);
1469
assert.strictEqual(state.localStatusCalls, failedCalls + 1);
1470
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1471
- }).pipe(Effect.scoped),
1471
+ }),
1472
);
1473
1474
it.effect("subscribers share one HEAD watch that ends with the last of them", () =>
@@ -1510,7 +1510,7 @@ describe("VcsStatusBroadcaster", () => {
1510
yield* subscribe;
1511
assert.strictEqual(state.headPathCalls, 2);
1512
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1513
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1513
+ }).pipe(Effect.provide(NodeServices.layer)),
1514
);
1515
1516
it.effect("a HEAD watch that ended restarts for the next subscriber and keeps earlier ones", () =>
@@ -1578,7 +1578,7 @@ describe("VcsStatusBroadcaster", () => {
1578
yield* checkout("two");
1579
yield* Deferred.await(first.sawRef("two"));
1580
}).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1581
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
1581
+ }).pipe(Effect.provide(NodeServices.layer)),
1582
);
1583
1584
it.effect("a HEAD watch ends when its git directory is removed", () =>
@@ -1762,7 +1762,7 @@ it.effect("detail join during invalidation must get fresh totals", () => {
1762
yield* Fiber.join(snapshotFiber),
1763
Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }),
1764
);
1765
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1765
+ }).pipe(Effect.provide(layerTestFor(state)));
1766
});
1767
it.effect("serializes branch reads with detailed refresh publication", () => {
1768
const state = newState();
@@ -1788,7 +1788,7 @@ it.effect("serializes branch reads with detailed refresh publication", () => {
1788
const result = yield* b.getStatus({ cwd: "/repo" });
1789
assert.equal(result.refName, "new");
1790
assert.equal(state.localStatusCalls, 1);
1791
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1791
+ }).pipe(Effect.provide(layerTestFor(state)));
1792
});
1793
1794
it.effect("publishes overlapping branch reads in checkout order", () => {
@@ -1819,7 +1819,7 @@ it.effect("publishes overlapping branch reads in checkout order", () => {
1819
{ refName: "old", isRepo: true },
1820
{ refName: "new", isRepo: true },
1821
]);
1822
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1822
+ }).pipe(Effect.provide(layerTestFor(state)));
1823
});
1824
1825
it.effect("does not replay older queued branches after a new subscriber snapshot", () => {
@@ -1852,5 +1852,5 @@ it.effect("does not replay older queued branches after a new subscriber snapshot
1852
yield* b.refreshBranchStatus({ cwd: "/repo" });
1853
assert.deepEqual(yield* Queue.take(values), { refName: "latest", isRepo: true });
1854
yield* Fiber.join(subscriber);
1855
- }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped);
1855
+ }).pipe(Effect.provide(layerTestFor(state)));
1856
});
apps/server/src/ws.test.ts
+1
-8
@@ -237,7 +237,7 @@ it.effect("resends a reveal kind and remote targets that outlast the snapshot ti
237
assert.deepEqual(remote.config.remoteOpenTargets, targets);
238
assert.equal(remote.config.shellRevealInFileManagerKind, "file-explorer");
239
}
240
- }).pipe(Effect.scoped),
240
+ }),
241
);
242
243
it.effect("runs editor, remote open target and direct endpoint discovery side by side", () =>
@@ -1144,7 +1144,6 @@ it.effect.each([
1144
Layer.mock(ServerBrowser.ServerBrowser)({}),
1145
),
1146
),
1147
- Effect.scoped,
1147
),
1148
);
1149
@@ -1256,7 +1255,6 @@ it.effect("access changes made while the snapshot loads reach the client after i
1255
Layer.mock(ServerBrowser.ServerBrowser)({}),
1256
),
1257
),
1259
- Effect.scoped,
1258
),
1259
);
1260
@@ -1611,7 +1609,6 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
1609
Layer.mock(ServerBrowser.ServerBrowser)({}),
1610
),
1611
),
1614
- Effect.scoped,
1612
),
1613
);
1614
@@ -1783,7 +1780,6 @@ it.effect("a missing thread worktree gets its project's skills in the cwd snapsh
1780
Layer.mock(ServerBrowser.ServerBrowser)({}),
1781
),
1782
),
1786
- Effect.scoped,
1783
),
1784
);
1785
@@ -1857,7 +1853,6 @@ it.effect("a git action that fails partway still refreshes the repository status
1853
Layer.mock(ServerBrowser.ServerBrowser)({}),
1854
),
1855
),
1860
- Effect.scoped,
1856
),
1857
);
1858
@@ -1945,7 +1940,6 @@ it.effect("a publish whose push fails still refreshes the new remote", () =>
1940
Layer.mock(ServerBrowser.ServerBrowser)({}),
1941
),
1942
),
1948
- Effect.scoped,
1943
),
1944
);
1945
@@ -2449,6 +2443,5 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i
2443
Layer.mock(ServerBrowser.ServerBrowser)({}),
2444
),
2445
),
2452
- Effect.scoped,
2446
),
2447
);
apps/web/src/connection/storage.browser.test.ts
+1
-1
@@ -57,7 +57,7 @@ describe("IndexedDB query cache", () => {
57
);
58
expect(keptBytes).toBeLessThanOrEqual(32 * 1024 * 1024);
59
expect(yield* tabs[1]!.load(environmentId, "large-8")).toEqual(Option.some(answer));
60
- }).pipe(Effect.scoped),
60
+ }),
61
);
62
63
it.effect("drops the older copy when an answer grows too large to keep", () =>
apps/web/src/connection/storage.test.ts
+1
-1
@@ -282,6 +282,6 @@ describe("browser GitHub routing permissions", () => {
282
ConnectionTransientError,
283
);
284
expect(yield* second.get(entry)).toBe("off");
285
- }).pipe(Effect.scoped),
285
+ }),
286
);
287
});
apps/web/src/lib/backgroundActivityReporter.test.ts
+2
-2
@@ -109,7 +109,7 @@ describe("layer", () => {
109
110
yield* TestClock.adjust("25 seconds");
111
expect(calls).toBe(2);
112
- }).pipe(Effect.scoped),
112
+ }),
113
);
114
115
it.effect("keeps reporting after a report never settles", () =>
@@ -134,6 +134,6 @@ describe("layer", () => {
134
135
yield* TestClock.adjust("25 seconds");
136
expect(calls).toBe(2);
137
- }).pipe(Effect.scoped),
137
+ }),
138
);
139
});
packages/client-runtime/src/relay/discovery.test.ts
+37
-39
@@ -185,48 +185,46 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () {
185
186
describe("RelayEnvironmentDiscovery", () => {
187
it.effect("fetches a fresh list after removal while an older refresh is checking statuses", () =>
188
- Effect.scoped(
189
- Effect.gen(function* () {
190
- const harness = yield* makeHarness();
191
- yield* Effect.gen(function* () {
192
- const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
193
- const atoms = createRelayEnvironmentDiscoveryAtoms(
194
- Atom.runtime(
195
- Layer.succeed(RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, discovery),
196
- ),
197
- );
198
- const registry = AtomRegistry.make();
199
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
188
+ Effect.gen(function* () {
189
+ const harness = yield* makeHarness();
190
+ yield* Effect.gen(function* () {
191
+ const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
192
+ const atoms = createRelayEnvironmentDiscoveryAtoms(
193
+ Atom.runtime(
194
+ Layer.succeed(RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, discovery),
195
+ ),
196
+ );
197
+ const registry = AtomRegistry.make();
198
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
199
201
- const refresh = atoms.refresh.run(registry, undefined);
202
- yield* SubscriptionRef.changes(discovery.state).pipe(
203
- Stream.filter((state) => state.environments.size === environments.length),
204
- Stream.runHead,
205
- );
206
- const coalescedRefresh = atoms.refresh.run(registry, undefined);
207
- yield* Ref.set(harness.listedEnvironments, [environments[1]!]);
208
- const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined);
200
+ const refresh = atoms.refresh.run(registry, undefined);
201
+ yield* SubscriptionRef.changes(discovery.state).pipe(
202
+ Stream.filter((state) => state.environments.size === environments.length),
203
+ Stream.runHead,
204
+ );
205
+ const coalescedRefresh = atoms.refresh.run(registry, undefined);
206
+ yield* Ref.set(harness.listedEnvironments, [environments[1]!]);
207
+ const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined);
208
210
- const requests = yield* Ref.get(harness.statusRequests);
211
- for (const environment of environments) {
212
- yield* Deferred.succeed(
213
- requests.get(environment.environmentId)!,
214
- status(environment, "online"),
215
- );
216
- }
217
- const results = yield* Effect.promise(() =>
218
- Promise.all([refresh, coalescedRefresh, mutationRefresh]),
209
+ const requests = yield* Ref.get(harness.statusRequests);
210
+ for (const environment of environments) {
211
+ yield* Deferred.succeed(
212
+ requests.get(environment.environmentId)!,
213
+ status(environment, "online"),
214
);
220
- for (const result of results) {
221
- expect(result._tag).toBe("Success");
222
- }
223
- expect(yield* Ref.get(harness.listCalls)).toBe(2);
224
- const complete = yield* SubscriptionRef.get(discovery.state);
225
- expect([...complete.environments.keys()]).toEqual([environments[1]!.environmentId]);
226
- expect(complete.refreshing).toBe(false);
227
- }).pipe(Effect.provide(harness.layer));
228
- }),
229
- ),
215
+ }
216
+ const results = yield* Effect.promise(() =>
217
+ Promise.all([refresh, coalescedRefresh, mutationRefresh]),
218
+ );
219
+ for (const result of results) {
220
+ expect(result._tag).toBe("Success");
221
+ }
222
+ expect(yield* Ref.get(harness.listCalls)).toBe(2);
223
+ const complete = yield* SubscriptionRef.get(discovery.state);
224
+ expect([...complete.environments.keys()]).toEqual([environments[1]!.environmentId]);
225
+ expect(complete.refreshing).toBe(false);
226
+ }).pipe(Effect.provide(harness.layer));
227
+ }),
228
);
229
230
it.effect("publishes each environment status as soon as that lookup completes", () =>
packages/client-runtime/src/rpc/client.test.ts
+2
-2
@@ -445,7 +445,7 @@ it.effect.each([true, false])(
445
),
446
).toBeUndefined();
447
expect(inputs).toEqual(supported ? [{ cwd: "/repo" }] : []);
448
- }).pipe(Effect.scoped),
448
+ }),
449
);
450
451
it.effect("binds branch capability selection and execution to one session", () =>
@@ -481,5 +481,5 @@ it.effect("binds branch capability selection and execution to one session", () =
481
} as ServerConfig);
482
expect(yield* Fiber.join(refresh)).toBeUndefined();
483
yield* Deferred.await(executed);
484
- }).pipe(Effect.scoped),
484
+ }),
485
);
packages/client-runtime/src/rpc/session.test.ts
+474
-490
@@ -450,544 +450,528 @@ describe("RpcSessionFactory", () => {
450
);
451
452
it.effect("replays current config and broadcasts updates to every subscriber", () =>
453
- Effect.scoped(
454
- Effect.gen(function* () {
455
- const { factory, sockets } = yield* makeFactory();
456
- const session = yield* factory.connect(PREPARED);
457
- const readyFiber = yield* Effect.forkChild(session.ready);
458
- const socket = yield* awaitSocket(sockets);
459
- socket.open();
460
- yield* completeInitialConfig(socket);
461
- yield* Fiber.join(readyFiber);
462
-
463
- const collectTwo = session
464
- .subscribeServerConfig({})
465
- .pipe(Stream.take(2), Stream.runCollect);
466
- const firstSubscriber = yield* Effect.forkChild(collectTwo);
467
- const secondSubscriber = yield* Effect.forkChild(collectTwo);
468
- yield* Effect.yieldNow;
469
-
470
- const shortcut = {
471
- key: "k",
472
- metaKey: false,
473
- ctrlKey: false,
474
- shiftKey: false,
475
- altKey: false,
476
- modKey: true,
477
- };
478
- const request = yield* awaitRequest(socket);
479
- socket.serverMessage(
480
- encodeJson({
481
- _tag: "Chunk",
482
- requestId: request.id,
483
- values: [
484
- {
485
- version: 1,
486
- type: "keybindingsUpdated",
487
- payload: {
488
- keybindings: [{ command: "terminal.toggle", shortcut }],
489
- issues: [],
490
- },
453
+ Effect.gen(function* () {
454
+ const { factory, sockets } = yield* makeFactory();
455
+ const session = yield* factory.connect(PREPARED);
456
+ const readyFiber = yield* Effect.forkChild(session.ready);
457
+ const socket = yield* awaitSocket(sockets);
458
+ socket.open();
459
+ yield* completeInitialConfig(socket);
460
+ yield* Fiber.join(readyFiber);
461
+
462
+ const collectTwo = session.subscribeServerConfig({}).pipe(Stream.take(2), Stream.runCollect);
463
+ const firstSubscriber = yield* Effect.forkChild(collectTwo);
464
+ const secondSubscriber = yield* Effect.forkChild(collectTwo);
465
+ yield* Effect.yieldNow;
466
+
467
+ const shortcut = {
468
+ key: "k",
469
+ metaKey: false,
470
+ ctrlKey: false,
471
+ shiftKey: false,
472
+ altKey: false,
473
+ modKey: true,
474
+ };
475
+ const request = yield* awaitRequest(socket);
476
+ socket.serverMessage(
477
+ encodeJson({
478
+ _tag: "Chunk",
479
+ requestId: request.id,
480
+ values: [
481
+ {
482
+ version: 1,
483
+ type: "keybindingsUpdated",
484
+ payload: {
485
+ keybindings: [{ command: "terminal.toggle", shortcut }],
486
+ issues: [],
487
},
492
- ],
493
- }),
494
- );
488
+ },
489
+ ],
490
+ }),
491
+ );
492
496
- const firstEvents = Array.from(yield* Fiber.join(firstSubscriber));
497
- const secondEvents = Array.from(yield* Fiber.join(secondSubscriber));
498
- expect(firstEvents.map((event) => event.type)).toEqual(["snapshot", "keybindingsUpdated"]);
499
- expect(secondEvents).toEqual(firstEvents);
500
-
501
- const replay = yield* session.subscribeServerConfig({}).pipe(Stream.runHead);
502
- expect(replay).toMatchObject({
503
- _tag: "Some",
504
- value: {
505
- type: "snapshot",
506
- config: { keybindings: [{ command: "terminal.toggle", shortcut }] },
507
- },
508
- });
509
- }),
510
- ),
493
+ const firstEvents = Array.from(yield* Fiber.join(firstSubscriber));
494
+ const secondEvents = Array.from(yield* Fiber.join(secondSubscriber));
495
+ expect(firstEvents.map((event) => event.type)).toEqual(["snapshot", "keybindingsUpdated"]);
496
+ expect(secondEvents).toEqual(firstEvents);
497
+
498
+ const replay = yield* session.subscribeServerConfig({}).pipe(Stream.runHead);
499
+ expect(replay).toMatchObject({
500
+ _tag: "Some",
501
+ value: {
502
+ type: "snapshot",
503
+ config: { keybindings: [{ command: "terminal.toggle", shortcut }] },
504
+ },
505
+ });
506
+ }),
507
);
508
509
it.effect.each([
510
{ usageLimitSources: true },
511
{ environmentThemes: true, usageLimitSources: true },
512
])("replays usage sources and removal with %j", (options) =>
517
- Effect.scoped(
518
- Effect.gen(function* () {
519
- const { factory, sockets } = yield* makeFactory(options);
520
- const session = yield* factory.connect(PREPARED);
521
- const ready = yield* Effect.forkChild(session.ready);
522
- const socket = yield* awaitSocket(sockets);
523
- socket.open();
524
- yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), options);
525
- yield* Fiber.join(ready);
526
- const observed = yield* Queue.unbounded<ServerConfigStreamEventType>();
527
- yield* session.subscribeServerConfig().pipe(
528
- Stream.runForEach((event) => Queue.offer(observed, event)),
513
+ Effect.gen(function* () {
514
+ const { factory, sockets } = yield* makeFactory(options);
515
+ const session = yield* factory.connect(PREPARED);
516
+ const ready = yield* Effect.forkChild(session.ready);
517
+ const socket = yield* awaitSocket(sockets);
518
+ socket.open();
519
+ yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), options);
520
+ yield* Fiber.join(ready);
521
+ const observed = yield* Queue.unbounded<ServerConfigStreamEventType>();
522
+ yield* session.subscribeServerConfig().pipe(
523
+ Stream.runForEach((event) => Queue.offer(observed, event)),
524
+ Effect.forkChild,
525
+ );
526
+ expect((yield* Queue.take(observed)).type).toBe("snapshot");
527
+ const themes: ServerConfigStreamEventType[] = options.environmentThemes
528
+ ? [{ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } }]
529
+ : [];
530
+ for (const event of themes) {
531
+ yield* publishConfigEvents(socket, [event]);
532
+ expect(yield* Queue.take(observed)).toEqual(event);
533
+ }
534
+ const events: ServerConfigStreamEventType[] = [
535
+ SOURCE_EVENT,
536
+ { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
537
+ SOURCE_EVENT,
538
+ ];
539
+ for (const event of events) {
540
+ yield* publishConfigEvents(socket, [event]);
541
+ expect(yield* Queue.take(observed)).toEqual(event);
542
+ const started = yield* Deferred.make<void>();
543
+ const replay = yield* session.subscribeServerConfig(options).pipe(
544
+ Stream.tap(() => Deferred.succeed(started, undefined)),
545
+ Stream.takeUntil((item) => item.type === "keybindingsUpdated"),
546
+ Stream.runCollect,
547
Effect.forkChild,
548
);
531
- expect((yield* Queue.take(observed)).type).toBe("snapshot");
532
- const themes: ServerConfigStreamEventType[] = options.environmentThemes
533
- ? [{ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } }]
534
- : [];
535
- for (const event of themes) {
536
- yield* publishConfigEvents(socket, [event]);
537
- expect(yield* Queue.take(observed)).toEqual(event);
538
- }
539
- const events: ServerConfigStreamEventType[] = [
540
- SOURCE_EVENT,
541
- { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
542
- SOURCE_EVENT,
543
- ];
544
- for (const event of events) {
545
- yield* publishConfigEvents(socket, [event]);
546
- expect(yield* Queue.take(observed)).toEqual(event);
547
- const started = yield* Deferred.make<void>();
548
- const replay = yield* session.subscribeServerConfig(options).pipe(
549
- Stream.tap(() => Deferred.succeed(started, undefined)),
550
- Stream.takeUntil((item) => item.type === "keybindingsUpdated"),
551
- Stream.runCollect,
552
- Effect.forkChild,
553
- );
554
- yield* Deferred.await(started);
555
- const marker: ServerConfigStreamEventType = {
556
- version: 1,
557
- type: "keybindingsUpdated",
558
- payload: { keybindings: [], issues: [] },
559
- };
560
- yield* publishConfigEvents(socket, [marker]);
561
- expect(yield* Queue.take(observed)).toEqual(marker);
562
- const replayed = Array.from(yield* Fiber.join(replay));
563
- expect(replayed.slice(1)).toEqual([...themes, event, marker]);
564
- let projection = applyServerConfigProjection(Option.none(), {
565
- version: 1,
566
- type: "snapshot",
567
- config: SOURCE_SERVER_CONFIG,
568
- });
569
- projection = applyServerConfigProjection(projection, SOURCE_EVENT);
570
- for (const item of replayed) projection = applyServerConfigProjection(projection, item);
571
- expect(Option.getOrThrow(projection).config.usageLimitSources).toEqual(
572
- event.type === "usageLimitSourcesUpdated" && event.payload.sources.length > 0
573
- ? event.payload.sources
574
- : undefined,
575
- );
576
- }
577
- expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
578
- 1,
549
+ yield* Deferred.await(started);
550
+ const marker: ServerConfigStreamEventType = {
551
+ version: 1,
552
+ type: "keybindingsUpdated",
553
+ payload: { keybindings: [], issues: [] },
554
+ };
555
+ yield* publishConfigEvents(socket, [marker]);
556
+ expect(yield* Queue.take(observed)).toEqual(marker);
557
+ const replayed = Array.from(yield* Fiber.join(replay));
558
+ expect(replayed.slice(1)).toEqual([...themes, event, marker]);
559
+ let projection = applyServerConfigProjection(Option.none(), {
560
+ version: 1,
561
+ type: "snapshot",
562
+ config: SOURCE_SERVER_CONFIG,
563
+ });
564
+ projection = applyServerConfigProjection(projection, SOURCE_EVENT);
565
+ for (const item of replayed) projection = applyServerConfigProjection(projection, item);
566
+ expect(Option.getOrThrow(projection).config.usageLimitSources).toEqual(
567
+ event.type === "usageLimitSourcesUpdated" && event.payload.sources.length > 0
568
+ ? event.payload.sources
569
+ : undefined,
570
);
580
- }),
581
- ),
571
+ }
572
+ expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
573
+ 1,
574
+ );
575
+ }),
576
);
577
578
it.effect("replays theme updates and deletion as authoritative events", () =>
585
- Effect.scoped(
586
- Effect.gen(function* () {
587
- const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
588
- const session = yield* factory.connect(PREPARED);
589
- const readyFiber = yield* Effect.forkChild(session.ready);
590
- const socket = yield* awaitSocket(sockets);
591
- socket.open();
592
- yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
593
- environmentThemes: true,
594
- });
595
- yield* Fiber.join(readyFiber);
579
+ Effect.gen(function* () {
580
+ const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
581
+ const session = yield* factory.connect(PREPARED);
582
+ const readyFiber = yield* Effect.forkChild(session.ready);
583
+ const socket = yield* awaitSocket(sockets);
584
+ socket.open();
585
+ yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
586
+ environmentThemes: true,
587
+ });
588
+ yield* Fiber.join(readyFiber);
589
597
- const firstThemes = [
598
- {
599
- id: "nightfall",
600
- name: "Nightfall",
601
- appearance: "dark" as const,
602
- canvas: "#1a1b26",
603
- accent: "#7aa2f7",
604
- },
605
- ];
606
- const replacementThemes = [
607
- {
608
- id: "midnight",
609
- name: "Midnight",
610
- appearance: "dark" as const,
611
- canvas: "#000000",
612
- accent: "#ffffff",
613
- },
614
- ];
615
- const subscriberStarted = yield* Deferred.make<void>();
616
- const subscriber = yield* session.subscribeServerConfig({ environmentThemes: true }).pipe(
617
- Stream.mapEffect((event) =>
618
- Deferred.succeed(subscriberStarted, undefined).pipe(Effect.as(event)),
619
- ),
590
+ const firstThemes = [
591
+ {
592
+ id: "nightfall",
593
+ name: "Nightfall",
594
+ appearance: "dark" as const,
595
+ canvas: "#1a1b26",
596
+ accent: "#7aa2f7",
597
+ },
598
+ ];
599
+ const replacementThemes = [
600
+ {
601
+ id: "midnight",
602
+ name: "Midnight",
603
+ appearance: "dark" as const,
604
+ canvas: "#000000",
605
+ accent: "#ffffff",
606
+ },
607
+ ];
608
+ const subscriberStarted = yield* Deferred.make<void>();
609
+ const subscriber = yield* session.subscribeServerConfig({ environmentThemes: true }).pipe(
610
+ Stream.mapEffect((event) =>
611
+ Deferred.succeed(subscriberStarted, undefined).pipe(Effect.as(event)),
612
+ ),
613
+ Stream.take(4),
614
+ Stream.runCollect,
615
+ Effect.forkChild,
616
+ );
617
+ yield* Deferred.await(subscriberStarted);
618
+ yield* publishConfigEvents(socket, [
619
+ {
620
+ version: 1,
621
+ type: "environmentThemesUpdated",
622
+ payload: { themes: firstThemes },
623
+ },
624
+ {
625
+ version: 1,
626
+ type: "environmentThemesUpdated",
627
+ payload: { themes: replacementThemes },
628
+ },
629
+ {
630
+ version: 1,
631
+ type: "environmentThemesUpdated",
632
+ payload: { themes: [] },
633
+ },
634
+ ]);
635
+
636
+ const liveEvents = Array.from(yield* Fiber.join(subscriber));
637
+ expect(liveEvents.map((event) => event.type)).toEqual([
638
+ "snapshot",
639
+ "environmentThemesUpdated",
640
+ "environmentThemesUpdated",
641
+ "environmentThemesUpdated",
642
+ ]);
643
+ expect(liveEvents[2]).toMatchObject({ payload: { themes: replacementThemes } });
644
+
645
+ const replay = Array.from(
646
+ yield* session
647
+ .subscribeServerConfig({ environmentThemes: true })
648
+ .pipe(Stream.take(2), Stream.runCollect),
649
+ );
650
+ expect(replay.map((event) => event.type)).toEqual(["snapshot", "environmentThemesUpdated"]);
651
+ expect(replay[1]).toMatchObject({ payload: { themes: [] } });
652
+
653
+ let projection = applyServerConfigProjection(Option.none(), {
654
+ version: 1,
655
+ type: "snapshot",
656
+ config: THEME_SERVER_CONFIG,
657
+ });
658
+ projection = applyServerConfigProjection(projection, {
659
+ version: 1,
660
+ type: "environmentThemesUpdated",
661
+ payload: { themes: firstThemes },
662
+ });
663
+ for (const event of replay) {
664
+ projection = applyServerConfigProjection(projection, event);
665
+ }
666
+ expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
667
+ }),
668
+ );
669
+
670
+ it.effect("recovers a slow subscriber after it misses theme and usage-source deletion", () =>
671
+ Effect.gen(function* () {
672
+ const { factory, sockets } = yield* makeFactory({
673
+ environmentThemes: true,
674
+ usageLimitSources: true,
675
+ });
676
+ const session = yield* factory.connect(PREPARED);
677
+ const readyFiber = yield* Effect.forkChild(session.ready);
678
+ const socket = yield* awaitSocket(sockets);
679
+ socket.open();
680
+ yield* completeInitialConfig(
681
+ socket,
682
+ encodeServerConfig({ ...SOURCE_SERVER_CONFIG, providers: [PROVIDER] }),
683
+ { environmentThemes: true, usageLimitSources: true },
684
+ );
685
+ yield* Fiber.join(readyFiber);
686
+
687
+ const slowSubscriberStarted = yield* Deferred.make<void>();
688
+ const releaseSlowSubscriber = yield* Deferred.make<void>();
689
+ let firstEvent = true;
690
+ const slowSubscriber = yield* session
691
+ .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
692
+ .pipe(
693
+ Stream.mapEffect((event) => {
694
+ if (!firstEvent) return Effect.succeed(event);
695
+ firstEvent = false;
696
+ return Deferred.succeed(slowSubscriberStarted, undefined).pipe(
697
+ Effect.andThen(Deferred.await(releaseSlowSubscriber)),
698
+ Effect.as(event),
699
+ );
700
+ }),
701
Stream.take(4),
702
Stream.runCollect,
703
Effect.forkChild,
704
);
624
- yield* Deferred.await(subscriberStarted);
625
- yield* publishConfigEvents(socket, [
626
- {
627
- version: 1,
628
- type: "environmentThemesUpdated",
629
- payload: { themes: firstThemes },
630
- },
631
- {
632
- version: 1,
633
- type: "environmentThemesUpdated",
634
- payload: { themes: replacementThemes },
635
- },
636
- {
637
- version: 1,
638
- type: "environmentThemesUpdated",
639
- payload: { themes: [] },
705
+ yield* Deferred.await(slowSubscriberStarted);
706
+
707
+ const firstThemes = [
708
+ {
709
+ id: "nightfall",
710
+ name: "Nightfall",
711
+ appearance: "dark" as const,
712
+ canvas: "#1a1b26",
713
+ accent: "#7aa2f7",
714
+ },
715
+ ];
716
+ const themeEvents: ServerConfigStreamEventType[] = [
717
+ {
718
+ version: 1,
719
+ type: "environmentThemesUpdated",
720
+ payload: { themes: firstThemes },
721
+ },
722
+ {
723
+ version: 1,
724
+ type: "environmentThemesUpdated",
725
+ payload: {
726
+ themes: [{ ...firstThemes[0]!, name: "Nightfall 2" }],
727
},
641
- ]);
728
+ },
729
+ {
730
+ version: 1,
731
+ type: "environmentThemesUpdated",
732
+ payload: { themes: [] },
733
+ },
734
+ ];
735
+ const settingsEvents = Array.from({ length: 65 }, (): ServerConfigStreamEventType => ({
736
+ version: 1,
737
+ type: "settingsUpdated",
738
+ payload: { settings: DEFAULT_SERVER_SETTINGS },
739
+ }));
740
+ const sourceEvents: ServerConfigStreamEventType[] = [
741
+ SOURCE_EVENT,
742
+ { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
743
+ ];
744
+ // A delta carries no lists; a subscriber that misses it must still get its result.
745
+ const { models: _models, slashCommands: _commands, skills: _skills, ...status } = PROVIDER;
746
+ const providerEvent: ServerConfigStreamEventType = {
747
+ version: 1,
748
+ type: "providerStatusDeltas",
749
+ payload: {
750
+ providers: [{ ...status, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }],
751
+ },
752
+ };
753
+ const allEvents = [providerEvent, ...themeEvents, ...sourceEvents, ...settingsEvents];
754
+ const observedByFastSubscriber = yield* Queue.unbounded<ServerConfigStreamEventType>();
755
+ yield* session
756
+ .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
757
+ .pipe(
758
+ Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)),
759
+ Effect.forkChild,
760
+ );
761
+ expect((yield* Queue.take(observedByFastSubscriber)).type).toBe("snapshot");
762
+ for (const event of allEvents) {
763
+ yield* publishConfigEvents(socket, [event]);
764
+ expect(yield* Queue.take(observedByFastSubscriber)).toEqual(event);
765
+ }
766
+ yield* Deferred.succeed(releaseSlowSubscriber, undefined);
767
+
768
+ const recovered = Array.from(yield* Fiber.join(slowSubscriber));
769
+ expect(recovered.map((event) => event.type)).toEqual([
770
+ "snapshot",
771
+ "snapshot",
772
+ "environmentThemesUpdated",
773
+ "usageLimitSourcesUpdated",
774
+ ]);
775
+ expect(recovered[1]).toMatchObject({
776
+ config: {
777
+ providers: [{ ...PROVIDER, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }],
778
+ },
779
+ });
780
+ expect(recovered[2]).toMatchObject({ payload: { themes: [] } });
781
+ expect(recovered[3]).toMatchObject({ payload: { sources: [] } });
782
643
- const liveEvents = Array.from(yield* Fiber.join(subscriber));
644
- expect(liveEvents.map((event) => event.type)).toEqual([
645
- "snapshot",
646
- "environmentThemesUpdated",
647
- "environmentThemesUpdated",
648
- "environmentThemesUpdated",
649
- ]);
650
- expect(liveEvents[2]).toMatchObject({ payload: { themes: replacementThemes } });
783
+ let projection = applyServerConfigProjection(Option.none(), {
784
+ version: 1,
785
+ type: "snapshot",
786
+ config: SOURCE_SERVER_CONFIG,
787
+ });
788
+ projection = applyServerConfigProjection(projection, themeEvents[0]!);
789
+ projection = applyServerConfigProjection(projection, SOURCE_EVENT);
790
+ for (const event of recovered.slice(1)) {
791
+ projection = applyServerConfigProjection(projection, event);
792
+ }
793
+ expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
794
+ expect(Option.getOrThrow(projection).config.usageLimitSources).toBeUndefined();
795
+ }),
796
+ );
797
652
- const replay = Array.from(
653
- yield* session
654
- .subscribeServerConfig({ environmentThemes: true })
655
- .pipe(Stream.take(2), Stream.runCollect),
656
- );
657
- expect(replay.map((event) => event.type)).toEqual(["snapshot", "environmentThemesUpdated"]);
658
- expect(replay[1]).toMatchObject({ payload: { themes: [] } });
798
+ it.effect("closes the session when the config source dies", () =>
799
+ Effect.gen(function* () {
800
+ const { factory, sockets } = yield* makeFactory();
801
+ const session = yield* factory.connect(PREPARED);
802
+ const readyFiber = yield* Effect.forkChild(session.ready);
803
+ const socket = yield* awaitSocket(sockets);
804
+ socket.open();
805
+ yield* completeInitialConfig(socket);
806
+ yield* Fiber.join(readyFiber);
807
660
- let projection = applyServerConfigProjection(Option.none(), {
661
- version: 1,
662
- type: "snapshot",
663
- config: THEME_SERVER_CONFIG,
664
- });
665
- projection = applyServerConfigProjection(projection, {
666
- version: 1,
667
- type: "environmentThemesUpdated",
668
- payload: { themes: firstThemes },
669
- });
670
- for (const event of replay) {
671
- projection = applyServerConfigProjection(projection, event);
672
- }
673
- expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
674
- }),
675
- ),
808
+ const closedFiber = yield* session.closed.pipe(Effect.exit, Effect.forkChild);
809
+ socket.serverMessage(
810
+ encodeJson({
811
+ _tag: "Defect",
812
+ defect: encodeDefect(new Error("config stream died")),
813
+ }),
814
+ );
815
+
816
+ const closed = yield* Fiber.join(closedFiber);
817
+ expect(Exit.isFailure(closed)).toBe(true);
818
+ if (Exit.isFailure(closed)) {
819
+ expect(Cause.hasDies(closed.cause)).toBe(true);
820
+ }
821
+ }),
822
);
823
678
- it.effect("recovers a slow subscriber after it misses theme and usage-source deletion", () =>
679
- Effect.scoped(
824
+ it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])(
825
+ "keeps durable config state alive after an owned $failure failure",
826
+ ({ failure }) =>
827
Effect.gen(function* () {
681
- const { factory, sockets } = yield* makeFactory({
828
+ const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
829
+ const firstSession = yield* factory.connect(PREPARED);
830
+ const firstReady = yield* Effect.forkChild(firstSession.ready);
831
+ const firstSocket = yield* awaitSocket(sockets);
832
+ firstSocket.open();
833
+ yield* completeInitialConfig(firstSocket, ENCODED_THEME_SERVER_CONFIG, {
834
environmentThemes: true,
683
- usageLimitSources: true,
835
});
685
- const session = yield* factory.connect(PREPARED);
686
- const readyFiber = yield* Effect.forkChild(session.ready);
687
- const socket = yield* awaitSocket(sockets);
688
- socket.open();
689
- yield* completeInitialConfig(
690
- socket,
691
- encodeServerConfig({ ...SOURCE_SERVER_CONFIG, providers: [PROVIDER] }),
692
- { environmentThemes: true, usageLimitSources: true },
836
+ yield* Fiber.join(firstReady);
837
+
838
+ const activeSession = yield* SubscriptionRef.make(Option.some(firstSession));
839
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
840
+ target: TARGET,
841
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
842
+ session: activeSession,
843
+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
844
+ connect: Effect.void,
845
+ disconnect: Effect.void,
846
+ retryNow: Effect.void,
847
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
848
+ const cache = Persistence.EnvironmentCacheStore.of({
849
+ loadShell: () => Effect.succeedNone,
850
+ saveShell: () => Effect.void,
851
+ loadThread: () => Effect.succeedNone,
852
+ saveThread: () => Effect.void,
853
+ removeThread: () => Effect.void,
854
+ loadServerConfig: () => Effect.succeedNone,
855
+ saveServerConfig: () => Effect.void,
856
+ loadVcsRefs: () => Effect.succeedNone,
857
+ saveVcsRefs: () => Effect.void,
858
+ removeVcsRefs: () => Effect.void,
859
+ clearVcsRefs: () => Effect.void,
860
+ clear: () => Effect.void,
861
+ });
862
+ const configState = yield* makeEnvironmentServerConfigState({
863
+ environmentThemes: true,
864
+ }).pipe(
865
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
866
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
867
);
694
- yield* Fiber.join(readyFiber);
695
-
696
- const slowSubscriberStarted = yield* Deferred.make<void>();
697
- const releaseSlowSubscriber = yield* Deferred.make<void>();
698
- let firstEvent = true;
699
- const slowSubscriber = yield* session
700
- .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
701
- .pipe(
702
- Stream.mapEffect((event) => {
703
- if (!firstEvent) return Effect.succeed(event);
704
- firstEvent = false;
705
- return Deferred.succeed(slowSubscriberStarted, undefined).pipe(
706
- Effect.andThen(Deferred.await(releaseSlowSubscriber)),
707
- Effect.as(event),
708
- );
709
- }),
710
- Stream.take(4),
711
- Stream.runCollect,
712
- Effect.forkChild,
868
+ const awaitConfig = (predicate: (config: ServerConfigType) => boolean) =>
869
+ SubscriptionRef.changes(configState).pipe(
870
+ Stream.filter(Option.isSome),
871
+ Stream.map((projection) => projection.value.config),
872
+ Stream.filter(predicate),
873
+ Stream.runHead,
874
+ Effect.map(Option.getOrThrow),
875
);
714
- yield* Deferred.await(slowSubscriberStarted);
876
877
const firstThemes = [
878
{
718
- id: "nightfall",
719
- name: "Nightfall",
879
+ id: "first-theme",
880
+ name: "First theme",
881
appearance: "dark" as const,
721
- canvas: "#1a1b26",
722
- accent: "#7aa2f7",
882
+ canvas: "#111111",
883
+ accent: "#ffffff",
884
},
885
];
725
- const themeEvents: ServerConfigStreamEventType[] = [
886
+ const firstThemeState = yield* awaitConfig(
887
+ (config) => config.environmentThemes?.[0]?.id === "first-theme",
888
+ ).pipe(Effect.forkChild);
889
+ yield* publishConfigEvents(firstSocket, [
890
{
891
version: 1,
892
type: "environmentThemesUpdated",
893
payload: { themes: firstThemes },
894
},
895
+ ]);
896
+ expect((yield* Fiber.join(firstThemeState)).environmentThemes).toEqual(firstThemes);
897
+
898
+ const firstClosed = yield* firstSession.closed.pipe(Effect.exit, Effect.forkChild);
899
+ const firstRequest = yield* awaitRequest(firstSocket);
900
+ firstSocket.serverMessage(
901
+ failure === "defect"
902
+ ? encodeJson({
903
+ _tag: "Defect",
904
+ defect: encodeDefect(new Error("config stream died")),
905
+ })
906
+ : encodeJson({
907
+ _tag: "Exit",
908
+ requestId: firstRequest.id,
909
+ exit: {
910
+ _tag: "Failure",
911
+ cause: [
912
+ {
913
+ _tag: "Fail",
914
+ error: {
915
+ _tag: "EnvironmentAuthorizationError",
916
+ message: "config subscription rejected",
917
+ requiredScope: "orchestration:read",
918
+ },
919
+ },
920
+ ],
921
+ },
922
+ }),
923
+ );
924
+ const firstClosedExit = yield* Fiber.join(firstClosed);
925
+ expect(Exit.isFailure(firstClosedExit)).toBe(true);
926
+ if (failure === "typed" && Exit.isFailure(firstClosedExit)) {
927
+ expect(Cause.squash(firstClosedExit.cause)).toBeInstanceOf(ConnectionBlockedError);
928
+ expect(Cause.squash(firstClosedExit.cause)).toMatchObject({ reason: "permission" });
929
+ }
930
+ yield* SubscriptionRef.set(activeSession, Option.none());
931
+
932
+ const recoveredConfig = {
933
+ ...THEME_SERVER_CONFIG,
934
+ environment: {
935
+ ...THEME_SERVER_CONFIG.environment,
936
+ label: "Recovered environment",
937
+ },
938
+ } satisfies ServerConfigType;
939
+ const secondSession = yield* factory.connect(PREPARED);
940
+ const secondReady = yield* Effect.forkChild(secondSession.ready);
941
+ const secondSocket = yield* awaitSocket(sockets, 1);
942
+ secondSocket.open();
943
+ yield* completeInitialConfig(secondSocket, encodeServerConfig(recoveredConfig), {
944
+ environmentThemes: true,
945
+ });
946
+ yield* Fiber.join(secondReady);
947
+
948
+ const recoveredState = yield* awaitConfig(
949
+ (config) => config.environment.label === "Recovered environment",
950
+ ).pipe(Effect.forkChild);
951
+ yield* SubscriptionRef.set(activeSession, Option.some(secondSession));
952
+ expect((yield* Fiber.join(recoveredState)).environmentThemes).toEqual(firstThemes);
953
+
954
+ const recoveredThemes = [
955
{
732
- version: 1,
733
- type: "environmentThemesUpdated",
734
- payload: {
735
- themes: [{ ...firstThemes[0]!, name: "Nightfall 2" }],
736
- },
956
+ id: "recovered-theme",
957
+ name: "Recovered theme",
958
+ appearance: "dark" as const,
959
+ canvas: "#000000",
960
+ accent: "#eeeeee",
961
},
962
+ ];
963
+ const liveRecoveredState = yield* awaitConfig(
964
+ (config) => config.environmentThemes?.[0]?.id === "recovered-theme",
965
+ ).pipe(Effect.forkChild);
966
+ yield* publishConfigEvents(secondSocket, [
967
{
968
version: 1,
969
type: "environmentThemesUpdated",
741
- payload: { themes: [] },
742
- },
743
- ];
744
- const settingsEvents = Array.from({ length: 65 }, (): ServerConfigStreamEventType => ({
745
- version: 1,
746
- type: "settingsUpdated",
747
- payload: { settings: DEFAULT_SERVER_SETTINGS },
748
- }));
749
- const sourceEvents: ServerConfigStreamEventType[] = [
750
- SOURCE_EVENT,
751
- { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } },
752
- ];
753
- // A delta carries no lists; a subscriber that misses it must still get its result.
754
- const { models: _models, slashCommands: _commands, skills: _skills, ...status } = PROVIDER;
755
- const providerEvent: ServerConfigStreamEventType = {
756
- version: 1,
757
- type: "providerStatusDeltas",
758
- payload: {
759
- providers: [{ ...status, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }],
970
+ payload: { themes: recoveredThemes },
971
},
761
- };
762
- const allEvents = [providerEvent, ...themeEvents, ...sourceEvents, ...settingsEvents];
763
- const observedByFastSubscriber = yield* Queue.unbounded<ServerConfigStreamEventType>();
764
- yield* session
765
- .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true })
766
- .pipe(
767
- Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)),
768
- Effect.forkChild,
769
- );
770
- expect((yield* Queue.take(observedByFastSubscriber)).type).toBe("snapshot");
771
- for (const event of allEvents) {
772
- yield* publishConfigEvents(socket, [event]);
773
- expect(yield* Queue.take(observedByFastSubscriber)).toEqual(event);
774
- }
775
- yield* Deferred.succeed(releaseSlowSubscriber, undefined);
776
-
777
- const recovered = Array.from(yield* Fiber.join(slowSubscriber));
778
- expect(recovered.map((event) => event.type)).toEqual([
779
- "snapshot",
780
- "snapshot",
781
- "environmentThemesUpdated",
782
- "usageLimitSourcesUpdated",
972
]);
784
- expect(recovered[1]).toMatchObject({
785
- config: {
786
- providers: [{ ...PROVIDER, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }],
787
- },
788
- });
789
- expect(recovered[2]).toMatchObject({ payload: { themes: [] } });
790
- expect(recovered[3]).toMatchObject({ payload: { sources: [] } });
791
-
792
- let projection = applyServerConfigProjection(Option.none(), {
793
- version: 1,
794
- type: "snapshot",
795
- config: SOURCE_SERVER_CONFIG,
796
- });
797
- projection = applyServerConfigProjection(projection, themeEvents[0]!);
798
- projection = applyServerConfigProjection(projection, SOURCE_EVENT);
799
- for (const event of recovered.slice(1)) {
800
- projection = applyServerConfigProjection(projection, event);
801
- }
802
- expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
803
- expect(Option.getOrThrow(projection).config.usageLimitSources).toBeUndefined();
973
+ expect((yield* Fiber.join(liveRecoveredState)).environmentThemes).toEqual(recoveredThemes);
974
}),
805
- ),
806
- );
807
-
808
- it.effect("closes the session when the config source dies", () =>
809
- Effect.scoped(
810
- Effect.gen(function* () {
811
- const { factory, sockets } = yield* makeFactory();
812
- const session = yield* factory.connect(PREPARED);
813
- const readyFiber = yield* Effect.forkChild(session.ready);
814
- const socket = yield* awaitSocket(sockets);
815
- socket.open();
816
- yield* completeInitialConfig(socket);
817
- yield* Fiber.join(readyFiber);
818
-
819
- const closedFiber = yield* session.closed.pipe(Effect.exit, Effect.forkChild);
820
- socket.serverMessage(
821
- encodeJson({
822
- _tag: "Defect",
823
- defect: encodeDefect(new Error("config stream died")),
824
- }),
825
- );
826
-
827
- const closed = yield* Fiber.join(closedFiber);
828
- expect(Exit.isFailure(closed)).toBe(true);
829
- if (Exit.isFailure(closed)) {
830
- expect(Cause.hasDies(closed.cause)).toBe(true);
831
- }
832
- }),
833
- ),
834
- );
835
-
836
- it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])(
837
- "keeps durable config state alive after an owned $failure failure",
838
- ({ failure }) =>
839
- Effect.scoped(
840
- Effect.gen(function* () {
841
- const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
842
- const firstSession = yield* factory.connect(PREPARED);
843
- const firstReady = yield* Effect.forkChild(firstSession.ready);
844
- const firstSocket = yield* awaitSocket(sockets);
845
- firstSocket.open();
846
- yield* completeInitialConfig(firstSocket, ENCODED_THEME_SERVER_CONFIG, {
847
- environmentThemes: true,
848
- });
849
- yield* Fiber.join(firstReady);
850
-
851
- const activeSession = yield* SubscriptionRef.make(Option.some(firstSession));
852
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
853
- target: TARGET,
854
- state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
855
- session: activeSession,
856
- prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
857
- connect: Effect.void,
858
- disconnect: Effect.void,
859
- retryNow: Effect.void,
860
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
861
- const cache = Persistence.EnvironmentCacheStore.of({
862
- loadShell: () => Effect.succeedNone,
863
- saveShell: () => Effect.void,
864
- loadThread: () => Effect.succeedNone,
865
- saveThread: () => Effect.void,
866
- removeThread: () => Effect.void,
867
- loadServerConfig: () => Effect.succeedNone,
868
- saveServerConfig: () => Effect.void,
869
- loadVcsRefs: () => Effect.succeedNone,
870
- saveVcsRefs: () => Effect.void,
871
- removeVcsRefs: () => Effect.void,
872
- clearVcsRefs: () => Effect.void,
873
- clear: () => Effect.void,
874
- });
875
- const configState = yield* makeEnvironmentServerConfigState({
876
- environmentThemes: true,
877
- }).pipe(
878
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
879
- Effect.provideService(Persistence.EnvironmentCacheStore, cache),
880
- );
881
- const awaitConfig = (predicate: (config: ServerConfigType) => boolean) =>
882
- SubscriptionRef.changes(configState).pipe(
883
- Stream.filter(Option.isSome),
884
- Stream.map((projection) => projection.value.config),
885
- Stream.filter(predicate),
886
- Stream.runHead,
887
- Effect.map(Option.getOrThrow),
888
- );
889
-
890
- const firstThemes = [
891
- {
892
- id: "first-theme",
893
- name: "First theme",
894
- appearance: "dark" as const,
895
- canvas: "#111111",
896
- accent: "#ffffff",
897
- },
898
- ];
899
- const firstThemeState = yield* awaitConfig(
900
- (config) => config.environmentThemes?.[0]?.id === "first-theme",
901
- ).pipe(Effect.forkChild);
902
- yield* publishConfigEvents(firstSocket, [
903
- {
904
- version: 1,
905
- type: "environmentThemesUpdated",
906
- payload: { themes: firstThemes },
907
- },
908
- ]);
909
- expect((yield* Fiber.join(firstThemeState)).environmentThemes).toEqual(firstThemes);
910
-
911
- const firstClosed = yield* firstSession.closed.pipe(Effect.exit, Effect.forkChild);
912
- const firstRequest = yield* awaitRequest(firstSocket);
913
- firstSocket.serverMessage(
914
- failure === "defect"
915
- ? encodeJson({
916
- _tag: "Defect",
917
- defect: encodeDefect(new Error("config stream died")),
918
- })
919
- : encodeJson({
920
- _tag: "Exit",
921
- requestId: firstRequest.id,
922
- exit: {
923
- _tag: "Failure",
924
- cause: [
925
- {
926
- _tag: "Fail",
927
- error: {
928
- _tag: "EnvironmentAuthorizationError",
929
- message: "config subscription rejected",
930
- requiredScope: "orchestration:read",
931
- },
932
- },
933
- ],
934
- },
935
- }),
936
- );
937
- const firstClosedExit = yield* Fiber.join(firstClosed);
938
- expect(Exit.isFailure(firstClosedExit)).toBe(true);
939
- if (failure === "typed" && Exit.isFailure(firstClosedExit)) {
940
- expect(Cause.squash(firstClosedExit.cause)).toBeInstanceOf(ConnectionBlockedError);
941
- expect(Cause.squash(firstClosedExit.cause)).toMatchObject({ reason: "permission" });
942
- }
943
- yield* SubscriptionRef.set(activeSession, Option.none());
944
-
945
- const recoveredConfig = {
946
- ...THEME_SERVER_CONFIG,
947
- environment: {
948
- ...THEME_SERVER_CONFIG.environment,
949
- label: "Recovered environment",
950
- },
951
- } satisfies ServerConfigType;
952
- const secondSession = yield* factory.connect(PREPARED);
953
- const secondReady = yield* Effect.forkChild(secondSession.ready);
954
- const secondSocket = yield* awaitSocket(sockets, 1);
955
- secondSocket.open();
956
- yield* completeInitialConfig(secondSocket, encodeServerConfig(recoveredConfig), {
957
- environmentThemes: true,
958
- });
959
- yield* Fiber.join(secondReady);
960
-
961
- const recoveredState = yield* awaitConfig(
962
- (config) => config.environment.label === "Recovered environment",
963
- ).pipe(Effect.forkChild);
964
- yield* SubscriptionRef.set(activeSession, Option.some(secondSession));
965
- expect((yield* Fiber.join(recoveredState)).environmentThemes).toEqual(firstThemes);
966
-
967
- const recoveredThemes = [
968
- {
969
- id: "recovered-theme",
970
- name: "Recovered theme",
971
- appearance: "dark" as const,
972
- canvas: "#000000",
973
- accent: "#eeeeee",
974
- },
975
- ];
976
- const liveRecoveredState = yield* awaitConfig(
977
- (config) => config.environmentThemes?.[0]?.id === "recovered-theme",
978
- ).pipe(Effect.forkChild);
979
- yield* publishConfigEvents(secondSocket, [
980
- {
981
- version: 1,
982
- type: "environmentThemesUpdated",
983
- payload: { themes: recoveredThemes },
984
- },
985
- ]);
986
- expect((yield* Fiber.join(liveRecoveredState)).environmentThemes).toEqual(
987
- recoveredThemes,
988
- );
989
- }),
990
- ),
975
);
976
977
it.effect("rejects a server config for a different environment", () =>
@@ -1061,7 +1045,7 @@ describe("RpcSessionFactory", () => {
1045
}),
1046
);
1047
yield* Fiber.join(probeFiber);
1064
- }).pipe(Effect.scoped),
1048
+ }),
1049
);
1050
1051
it.effect("reaches ready when a newer server sends unknown config members", () =>
packages/client-runtime/src/state/assets.test.ts
+49
-57
@@ -184,58 +184,52 @@ describe("asset URL requests", () => {
184
const other = EnvironmentId.make("asset-other");
185
186
it.effect("keeps a thread of images from flooding one environment with requests", () =>
187
- Effect.scoped(
188
- Effect.gen(function* () {
189
- const harness = yield* makeAssetUrlHarness([remote]);
190
- const total = ASSET_URL_MAX_IN_FLIGHT * 3;
191
- harness.mountImages(remote, total);
192
-
193
- for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
194
- yield* Queue.take(harness.started);
195
- }
196
- expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
197
-
198
- // Each answer admits the next waiting request.
199
- for (let call = 0; call < total; call += 1) {
200
- yield* harness.release(remote);
201
- if (call < total - ASSET_URL_MAX_IN_FLIGHT) yield* Queue.take(harness.started);
202
- }
203
- expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
204
- }),
205
- ),
187
+ Effect.gen(function* () {
188
+ const harness = yield* makeAssetUrlHarness([remote]);
189
+ const total = ASSET_URL_MAX_IN_FLIGHT * 3;
190
+ harness.mountImages(remote, total);
191
+
192
+ for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
193
+ yield* Queue.take(harness.started);
194
+ }
195
+ expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
196
+
197
+ // Each answer admits the next waiting request.
198
+ for (let call = 0; call < total; call += 1) {
199
+ yield* harness.release(remote);
200
+ if (call < total - ASSET_URL_MAX_IN_FLIGHT) yield* Queue.take(harness.started);
201
+ }
202
+ expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
203
+ }),
204
);
205
206
it.effect("limits each environment on its own", () =>
209
- Effect.scoped(
210
- Effect.gen(function* () {
211
- const harness = yield* makeAssetUrlHarness([remote, other]);
212
- harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT + 2);
213
- for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
214
- yield* Queue.take(harness.started);
215
- }
216
- harness.mountImages(other, 1);
217
- expect(yield* Queue.take(harness.started)).toBe(other);
218
- expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
219
- }),
220
- ),
207
+ Effect.gen(function* () {
208
+ const harness = yield* makeAssetUrlHarness([remote, other]);
209
+ harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT + 2);
210
+ for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
211
+ yield* Queue.take(harness.started);
212
+ }
213
+ harness.mountImages(other, 1);
214
+ expect(yield* Queue.take(harness.started)).toBe(other);
215
+ expect(harness.inFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
216
+ }),
217
);
218
219
it.effect("frees the limit when the session behind the requests is replaced", () =>
224
- Effect.scoped(
225
- Effect.gen(function* () {
226
- const harness = yield* makeAssetUrlHarness([remote]);
227
- harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT * 2);
228
- for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
229
- yield* Queue.take(harness.started);
230
- }
231
-
232
- yield* harness.replaceSession(remote);
233
- for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
234
- yield* Queue.take(harness.started);
235
- }
236
- expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
237
- }),
238
- ),
220
+ Effect.gen(function* () {
221
+ const harness = yield* makeAssetUrlHarness([remote]);
222
+ harness.mountImages(remote, ASSET_URL_MAX_IN_FLIGHT * 2);
223
+ for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
224
+ yield* Queue.take(harness.started);
225
+ }
226
+
227
+ yield* harness.replaceSession(remote);
228
+ for (let call = 0; call < ASSET_URL_MAX_IN_FLIGHT; call += 1) {
229
+ yield* Queue.take(harness.started);
230
+ }
231
+ expect(harness.maxInFlight(remote)).toBe(ASSET_URL_MAX_IN_FLIGHT);
232
+ }),
233
);
234
});
235
@@ -325,17 +319,15 @@ describe("desktop-local media fallback", () => {
319
});
320
321
it.effect("keeps a relative Markdown image on the thread's environment", () =>
328
- Effect.scoped(
329
- Effect.gen(function* () {
330
- const { load } = yield* makeFallback();
331
- expect(yield* load("docs/report.png")).toEqual({ loaded: false, calls: [remote] });
332
- // The same resolved path written absolute still falls back, and shares no cached result.
333
- expect(yield* load("/tmp/repo/docs/report.png")).toEqual({
334
- loaded: true,
335
- calls: [remote, local],
336
- });
337
- }),
338
- ),
322
+ Effect.gen(function* () {
323
+ const { load } = yield* makeFallback();
324
+ expect(yield* load("docs/report.png")).toEqual({ loaded: false, calls: [remote] });
325
+ // The same resolved path written absolute still falls back, and shares no cached result.
326
+ expect(yield* load("/tmp/repo/docs/report.png")).toEqual({
327
+ loaded: true,
328
+ calls: [remote, local],
329
+ });
330
+ }),
331
);
332
});
333
packages/client-runtime/src/state/commandPermissions.test.ts
+350
-379
@@ -70,192 +70,173 @@ const setup = Effect.gen(function* () {
70
71
describe("command permissions", () => {
72
it.effect("requires the destination read grant to refresh providers", () =>
73
- Effect.scoped(
74
- Effect.gen(function* () {
75
- const registry = yield* setup;
76
- const refresh = createCommandPermissions(runtime, WS_METHODS.serverRefreshProviders);
77
- registry.set(sessions(env), AsyncResult.success(grant(true)));
78
- expect(registry.get(refresh.permissionAtom(env))).toBe(false);
79
- expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
80
- "EnvironmentAuthorizationError",
81
- );
82
- registry.set(
83
- sessions(env),
84
- AsyncResult.success({
85
- ...grant(false),
86
- scopes: [AuthOrchestrationReadScope],
87
- permissions: [AuthOrchestrationReadScope],
88
- }),
89
- );
90
- expect(registry.get(refresh.permissionAtom(env))).toBe(true);
91
- yield* refresh.authorize(registry, env);
92
- registry.set(sessions(other), AsyncResult.success(grant(false)));
93
- expect(registry.get(refresh.permissionAtom(other))).toBe(false);
94
- expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
95
- "EnvironmentAuthorizationError",
96
- );
97
- registry.set(sessions(env), AsyncResult.success(grant(false)));
98
- expect(registry.get(refresh.permissionAtom(env))).toBe(false);
99
- expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
100
- "EnvironmentAuthorizationError",
101
- );
102
- }),
103
- ),
73
+ Effect.gen(function* () {
74
+ const registry = yield* setup;
75
+ const refresh = createCommandPermissions(runtime, WS_METHODS.serverRefreshProviders);
76
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
77
+ expect(registry.get(refresh.permissionAtom(env))).toBe(false);
78
+ expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
79
+ "EnvironmentAuthorizationError",
80
+ );
81
+ registry.set(
82
+ sessions(env),
83
+ AsyncResult.success({
84
+ ...grant(false),
85
+ scopes: [AuthOrchestrationReadScope],
86
+ permissions: [AuthOrchestrationReadScope],
87
+ }),
88
+ );
89
+ expect(registry.get(refresh.permissionAtom(env))).toBe(true);
90
+ yield* refresh.authorize(registry, env);
91
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
92
+ expect(registry.get(refresh.permissionAtom(other))).toBe(false);
93
+ expect((yield* refresh.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
94
+ "EnvironmentAuthorizationError",
95
+ );
96
+ registry.set(sessions(env), AsyncResult.success(grant(false)));
97
+ expect(registry.get(refresh.permissionAtom(env))).toBe(false);
98
+ expect((yield* refresh.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
99
+ "EnvironmentAuthorizationError",
100
+ );
101
+ }),
102
);
103
104
it.effect("requires the destination preview grant to close a browser tab", () =>
107
- Effect.scoped(
108
- Effect.gen(function* () {
109
- const registry = yield* setup;
110
- const close = createCommandPermissions(runtime, WS_METHODS.previewClose);
111
- registry.set(sessions(env), AsyncResult.success(grant(true)));
112
- expect(registry.get(close.permissionAtom(env))).toBe(false);
113
- expect((yield* close.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
114
- "EnvironmentAuthorizationError",
115
- );
116
- registry.set(
117
- sessions(env),
118
- AsyncResult.success({
119
- ...grant(false),
120
- scopes: [AuthPreviewOperateScope],
121
- permissions: [AuthPreviewOperateScope],
122
- }),
123
- );
124
- expect(registry.get(close.permissionAtom(env))).toBe(true);
125
- yield* close.authorize(registry, env);
126
- registry.set(sessions(other), AsyncResult.success(grant(false)));
127
- expect(registry.get(close.permissionAtom(other))).toBe(false);
128
- expect((yield* close.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
129
- "EnvironmentAuthorizationError",
130
- );
131
- }),
132
- ),
105
+ Effect.gen(function* () {
106
+ const registry = yield* setup;
107
+ const close = createCommandPermissions(runtime, WS_METHODS.previewClose);
108
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
109
+ expect(registry.get(close.permissionAtom(env))).toBe(false);
110
+ expect((yield* close.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
111
+ "EnvironmentAuthorizationError",
112
+ );
113
+ registry.set(
114
+ sessions(env),
115
+ AsyncResult.success({
116
+ ...grant(false),
117
+ scopes: [AuthPreviewOperateScope],
118
+ permissions: [AuthPreviewOperateScope],
119
+ }),
120
+ );
121
+ expect(registry.get(close.permissionAtom(env))).toBe(true);
122
+ yield* close.authorize(registry, env);
123
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
124
+ expect(registry.get(close.permissionAtom(other))).toBe(false);
125
+ expect((yield* close.authorize(registry, other).pipe(Effect.flip))._tag).toBe(
126
+ "EnvironmentAuthorizationError",
127
+ );
128
+ }),
129
);
130
131
it.effect("requires the destination provider grant to remove an incomplete connection", () =>
136
- Effect.scoped(
137
- Effect.gen(function* () {
138
- const registry = yield* setup;
139
- const remove = createCommandPermissions(runtime, WS_METHODS.providerAuthRemoveMethod);
140
- registry.set(sessions(env), AsyncResult.success(grant(true)));
141
- expect(registry.get(remove.permissionAtom(env))).toBe(false);
142
- expect((yield* remove.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
143
- "EnvironmentAuthorizationError",
144
- );
145
- registry.set(
146
- sessions(env),
147
- AsyncResult.success({
148
- ...grant(false),
149
- scopes: [AuthProvidersManageScope],
150
- permissions: [AuthProvidersManageScope],
151
- }),
152
- );
153
- expect(registry.get(remove.permissionAtom(env))).toBe(true);
154
- yield* remove.authorize(registry, env);
155
- registry.set(sessions(other), AsyncResult.success(grant(false)));
156
- expect(registry.get(remove.permissionAtom(other))).toBe(false);
157
- }),
158
- ),
132
+ Effect.gen(function* () {
133
+ const registry = yield* setup;
134
+ const remove = createCommandPermissions(runtime, WS_METHODS.providerAuthRemoveMethod);
135
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
136
+ expect(registry.get(remove.permissionAtom(env))).toBe(false);
137
+ expect((yield* remove.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
138
+ "EnvironmentAuthorizationError",
139
+ );
140
+ registry.set(
141
+ sessions(env),
142
+ AsyncResult.success({
143
+ ...grant(false),
144
+ scopes: [AuthProvidersManageScope],
145
+ permissions: [AuthProvidersManageScope],
146
+ }),
147
+ );
148
+ expect(registry.get(remove.permissionAtom(env))).toBe(true);
149
+ yield* remove.authorize(registry, env);
150
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
151
+ expect(registry.get(remove.permissionAtom(other))).toBe(false);
152
+ }),
153
);
154
155
it.effect.each([
156
{ method: WS_METHODS.serverRunStorageCleanup, scope: AuthSettingsWriteScope },
157
{ method: WS_METHODS.serverReclaimDatabaseSpace, scope: AuthEnvironmentMaintainScope },
158
])("requires the destination $scope grant for $method", ({ method, scope }) =>
165
- Effect.scoped(
159
+ Effect.gen(function* () {
160
+ const registry = yield* setup;
161
+ const command = createCommandPermissions(runtime, method);
162
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
163
+ expect(registry.get(command.permissionAtom(env))).toBe(false);
164
+ expect((yield* command.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
165
+ "EnvironmentAuthorizationError",
166
+ );
167
+ registry.set(
168
+ sessions(env),
169
+ AsyncResult.success({ ...grant(true), scopes: [scope], permissions: [scope] }),
170
+ );
171
+ expect(registry.get(command.permissionAtom(env))).toBe(true);
172
+ yield* command.authorize(registry, env);
173
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
174
+ expect(registry.get(command.permissionAtom(other))).toBe(false);
175
+ }),
176
+ );
177
+
178
+ it.effect.each([WS_METHODS.serverCheckOtlpEndpoint, WS_METHODS.serverCheckSecretSource])(
179
+ "requires the destination settings grant for %s",
180
+ (method) =>
181
Effect.gen(function* () {
182
const registry = yield* setup;
168
- const command = createCommandPermissions(runtime, method);
183
+ const check = createCommandPermissions(runtime, method);
184
registry.set(sessions(env), AsyncResult.success(grant(true)));
170
- expect(registry.get(command.permissionAtom(env))).toBe(false);
171
- expect((yield* command.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
172
- "EnvironmentAuthorizationError",
173
- );
185
+ expect(registry.get(check.permissionAtom(env))).toBe(false);
186
registry.set(
187
sessions(env),
176
- AsyncResult.success({ ...grant(true), scopes: [scope], permissions: [scope] }),
188
+ AsyncResult.success({
189
+ ...grant(false),
190
+ scopes: [AuthSettingsWriteScope],
191
+ permissions: [AuthSettingsWriteScope],
192
+ }),
193
);
178
- expect(registry.get(command.permissionAtom(env))).toBe(true);
179
- yield* command.authorize(registry, env);
180
- registry.set(sessions(other), AsyncResult.success(grant(false)));
181
- expect(registry.get(command.permissionAtom(other))).toBe(false);
194
+ expect(registry.get(check.permissionAtom(env))).toBe(true);
195
+ yield* check.authorize(registry, env);
196
}),
183
- ),
184
- );
185
-
186
- it.effect.each([WS_METHODS.serverCheckOtlpEndpoint, WS_METHODS.serverCheckSecretSource])(
187
- "requires the destination settings grant for %s",
188
- (method) =>
189
- Effect.scoped(
190
- Effect.gen(function* () {
191
- const registry = yield* setup;
192
- const check = createCommandPermissions(runtime, method);
193
- registry.set(sessions(env), AsyncResult.success(grant(true)));
194
- expect(registry.get(check.permissionAtom(env))).toBe(false);
195
- registry.set(
196
- sessions(env),
197
- AsyncResult.success({
198
- ...grant(false),
199
- scopes: [AuthSettingsWriteScope],
200
- permissions: [AuthSettingsWriteScope],
201
- }),
202
- );
203
- expect(registry.get(check.permissionAtom(env))).toBe(true);
204
- yield* check.authorize(registry, env);
205
- }),
206
- ),
197
);
198
199
it.effect.each([WS_METHODS.scheduledTasksDelete, ORCHESTRATION_V2_WS_METHODS.stopWorkflow])(
200
"uses the target grant for both availability and execution of %s",
201
(method) =>
212
- Effect.scoped(
213
- Effect.gen(function* () {
214
- const registry = yield* setup;
215
- const permissions = createCommandPermissions(runtime, method);
216
- registry.set(sessions(env), AsyncResult.success(grant(true)));
217
- expect(registry.get(permissions.permissionAtom(env))).toBe(true);
218
- expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
219
- yield* permissions.authorize(registry, env);
220
- registry.set(sessions(other), AsyncResult.success(grant(false)));
221
- expect(registry.get(permissions.permissionAtom(other))).toBe(false);
222
- const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
223
- expect(denied._tag).toBe("EnvironmentAuthorizationError");
224
- }),
225
- ),
226
- );
227
- it.effect("waits for an initial grant", () =>
228
- Effect.scoped(
202
Effect.gen(function* () {
203
const registry = yield* setup;
231
- const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);
232
- yield* Effect.yieldNow;
204
+ const permissions = createCommandPermissions(runtime, method);
205
registry.set(sessions(env), AsyncResult.success(grant(true)));
234
- yield* Fiber.join(fiber);
206
+ expect(registry.get(permissions.permissionAtom(env))).toBe(true);
207
+ expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env));
208
+ yield* permissions.authorize(registry, env);
209
+ registry.set(sessions(other), AsyncResult.success(grant(false)));
210
+ expect(registry.get(permissions.permissionAtom(other))).toBe(false);
211
+ const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip);
212
+ expect(denied._tag).toBe("EnvironmentAuthorizationError");
213
}),
236
- ),
214
+ );
215
+ it.effect("waits for an initial grant", () =>
216
+ Effect.gen(function* () {
217
+ const registry = yield* setup;
218
+ const fiber = yield* permissions.authorize(registry, env).pipe(Effect.forkChild);
219
+ yield* Effect.yieldNow;
220
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
221
+ yield* Fiber.join(fiber);
222
+ }),
223
);
224
it.effect(
225
"denies failed and unauthenticated sessions, but accepts a cached refreshing grant",
226
() =>
241
- Effect.scoped(
242
- Effect.gen(function* () {
243
- const registry = yield* setup;
244
- registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));
245
- expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
246
- "EnvironmentAuthorizationError",
247
- );
248
- registry.set(
249
- sessions(env),
250
- AsyncResult.success({ ...grant(true), authenticated: false }),
251
- );
252
- expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
253
- "EnvironmentAuthorizationError",
254
- );
255
- registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));
256
- yield* permissions.authorize(registry, env);
257
- }),
258
- ),
227
+ Effect.gen(function* () {
228
+ const registry = yield* setup;
229
+ registry.set(sessions(env), AsyncResult.failure(Cause.fail("offline")));
230
+ expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
231
+ "EnvironmentAuthorizationError",
232
+ );
233
+ registry.set(sessions(env), AsyncResult.success({ ...grant(true), authenticated: false }));
234
+ expect((yield* permissions.authorize(registry, env).pipe(Effect.flip))._tag).toBe(
235
+ "EnvironmentAuthorizationError",
236
+ );
237
+ registry.set(sessions(env), AsyncResult.waiting(AsyncResult.success(grant(true))));
238
+ yield* permissions.authorize(registry, env);
239
+ }),
240
);
241
it("rechecks permission after waiting in a serial command lane", async () => {
242
const registry = AtomRegistry.make();
@@ -302,261 +283,251 @@ describe("command permissions", () => {
283
it.effect(
284
"requires source control alone for git, and both grants when attaching a worktree to a thread",
285
() =>
305
- Effect.scoped(
306
- Effect.gen(function* () {
307
- const registry = yield* setup;
308
- registry.set(sessions(env), AsyncResult.success(grant(true)));
309
- const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
310
- expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
311
- AuthSourceControlWriteScope,
312
- );
313
- registry.set(
314
- sessions(env),
315
- AsyncResult.success({
316
- ...grant(false),
317
- scopes: [AuthSourceControlWriteScope],
318
- permissions: [AuthSourceControlWriteScope],
319
- }),
320
- );
321
- yield* git.authorize(registry, env);
322
- const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
323
- const input = {
324
- cwd: "/repo",
325
- reference: "123",
326
- mode: "worktree",
327
- threadId: ThreadId.make("thread"),
328
- };
329
- expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
330
- expect(
331
- (yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope,
332
- ).toBe(AuthOrchestrationOperateScope);
333
- yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
334
- registry.set(
335
- sessions(env),
336
- AsyncResult.success({
337
- ...grant(true),
338
- scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
339
- permissions: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
340
- }),
341
- );
342
- expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
343
- yield* prepare.authorize(registry, env, input);
344
- }),
345
- ),
286
+ Effect.gen(function* () {
287
+ const registry = yield* setup;
288
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
289
+ const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
290
+ expect((yield* git.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
291
+ AuthSourceControlWriteScope,
292
+ );
293
+ registry.set(
294
+ sessions(env),
295
+ AsyncResult.success({
296
+ ...grant(false),
297
+ scopes: [AuthSourceControlWriteScope],
298
+ permissions: [AuthSourceControlWriteScope],
299
+ }),
300
+ );
301
+ yield* git.authorize(registry, env);
302
+ const prepare = createCommandPermissions(runtime, WS_METHODS.gitPreparePullRequestThread);
303
+ const input = {
304
+ cwd: "/repo",
305
+ reference: "123",
306
+ mode: "worktree",
307
+ threadId: ThreadId.make("thread"),
308
+ };
309
+ expect(registry.get(prepare.permissionAtom(env, input))).toBe(false);
310
+ expect((yield* prepare.authorize(registry, env, input).pipe(Effect.flip)).requiredScope).toBe(
311
+ AuthOrchestrationOperateScope,
312
+ );
313
+ yield* prepare.authorize(registry, env, { ...input, threadId: undefined });
314
+ registry.set(
315
+ sessions(env),
316
+ AsyncResult.success({
317
+ ...grant(true),
318
+ scopes: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
319
+ permissions: [AuthSourceControlWriteScope, AuthOrchestrationOperateScope],
320
+ }),
321
+ );
322
+ expect(registry.get(prepare.permissionAtom(env, input))).toBe(true);
323
+ yield* prepare.authorize(registry, env, input);
324
+ }),
325
);
326
327
it.effect.each(["commit", "push", "commit_push", "create_pr", "commit_push_pr"] as const)(
328
"%s needs thread read permission only when generating a PR from a thread",
329
(action) =>
351
- Effect.scoped(
352
- Effect.gen(function* () {
353
- const registry = yield* setup;
354
- const command = createCommandPermissions(runtime, WS_METHODS.gitRunStackedAction);
355
- const input = { actionId: "action", cwd: "/repo", action };
356
- const withThread = { ...input, threadId: ThreadId.make("thread") };
357
- const session = {
358
- ...grant(false),
359
- scopes: [AuthSourceControlWriteScope],
360
- permissions: [AuthSourceControlWriteScope],
361
- };
362
- registry.set(sessions(env), AsyncResult.success(session));
363
- expect(registry.get(command.permissionAtom(env, input))).toBe(true);
364
- yield* command.authorize(registry, env, input);
365
- const readsThread = action === "create_pr" || action === "commit_push_pr";
366
- expect(registry.get(command.permissionAtom(env, withThread))).toBe(!readsThread);
367
- if (readsThread) {
368
- expect(
369
- yield* command.authorize(registry, env, withThread).pipe(Effect.flip),
370
- ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope });
371
- } else {
372
- yield* command.authorize(registry, env, withThread);
373
- }
374
- registry.set(
375
- sessions(env),
376
- AsyncResult.success({
377
- ...session,
378
- scopes: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
379
- permissions: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
380
- }),
330
+ Effect.gen(function* () {
331
+ const registry = yield* setup;
332
+ const command = createCommandPermissions(runtime, WS_METHODS.gitRunStackedAction);
333
+ const input = { actionId: "action", cwd: "/repo", action };
334
+ const withThread = { ...input, threadId: ThreadId.make("thread") };
335
+ const session = {
336
+ ...grant(false),
337
+ scopes: [AuthSourceControlWriteScope],
338
+ permissions: [AuthSourceControlWriteScope],
339
+ };
340
+ registry.set(sessions(env), AsyncResult.success(session));
341
+ expect(registry.get(command.permissionAtom(env, input))).toBe(true);
342
+ yield* command.authorize(registry, env, input);
343
+ const readsThread = action === "create_pr" || action === "commit_push_pr";
344
+ expect(registry.get(command.permissionAtom(env, withThread))).toBe(!readsThread);
345
+ if (readsThread) {
346
+ expect(yield* command.authorize(registry, env, withThread).pipe(Effect.flip)).toMatchObject(
347
+ { requiredPermission: AuthOrchestrationReadScope },
348
);
382
- expect(registry.get(command.permissionAtom(env, withThread))).toBe(true);
349
+ } else {
350
yield* command.authorize(registry, env, withThread);
384
- }),
385
- ),
351
+ }
352
+ registry.set(
353
+ sessions(env),
354
+ AsyncResult.success({
355
+ ...session,
356
+ scopes: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
357
+ permissions: [AuthSourceControlWriteScope, AuthOrchestrationReadScope],
358
+ }),
359
+ );
360
+ expect(registry.get(command.permissionAtom(env, withThread))).toBe(true);
361
+ yield* command.authorize(registry, env, withThread);
362
+ }),
363
);
364
365
it.effect(
366
"refreshes linked environments after permitted writes and blocks a read-only session",
367
() =>
391
- Effect.scoped(
392
- Effect.gen(function* () {
393
- const registry = yield* setup;
394
- const peer: PeerLinkSummary = {
395
- environmentId: EnvironmentId.make("peer"),
396
- label: "Box",
397
- urls: ["https://box.example.test"],
398
- access: "auto",
399
- linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"),
400
- expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"),
401
- lastReachedAt: null,
402
- lastError: null,
403
- status: "reachable",
404
- };
405
- let links: ReadonlyArray<PeerLinkSummary> = [];
406
- const client = {
407
- [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })),
408
- [WS_METHODS.peerLinksLink]: vi.fn(() =>
409
- Effect.sync(() => {
410
- links = [peer];
411
- return peer;
412
- }),
413
- ),
414
- [WS_METHODS.peerLinksUnlink]: vi.fn(() =>
415
- Effect.sync(() => {
416
- links = [];
417
- return { removed: true };
418
- }),
419
- ),
420
- };
421
- const supervisor = {
422
- target: new BearerConnectionTarget({
423
- environmentId: env,
424
- label: "Test",
425
- connectionId: "test",
368
+ Effect.gen(function* () {
369
+ const registry = yield* setup;
370
+ const peer: PeerLinkSummary = {
371
+ environmentId: EnvironmentId.make("peer"),
372
+ label: "Box",
373
+ urls: ["https://box.example.test"],
374
+ access: "auto",
375
+ linkedAt: DateTime.makeUnsafe("2026-10-01T12:00:00Z"),
376
+ expiresAt: DateTime.makeUnsafe("2026-10-31T12:00:00Z"),
377
+ lastReachedAt: null,
378
+ lastError: null,
379
+ status: "reachable",
380
+ };
381
+ let links: ReadonlyArray<PeerLinkSummary> = [];
382
+ const client = {
383
+ [WS_METHODS.peerLinksList]: () => Effect.sync(() => ({ links })),
384
+ [WS_METHODS.peerLinksLink]: vi.fn(() =>
385
+ Effect.sync(() => {
386
+ links = [peer];
387
+ return peer;
388
}),
427
- session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),
428
- state: yield* SubscriptionRef.make({
429
- ...AVAILABLE_CONNECTION_STATE,
430
- phase: "connected" as const,
389
+ ),
390
+ [WS_METHODS.peerLinksUnlink]: vi.fn(() =>
391
+ Effect.sync(() => {
392
+ links = [];
393
+ return { removed: true };
394
}),
432
- } as EnvironmentSupervisor["Service"];
433
- const peerRuntime = Atom.runtime(
434
- Layer.succeed(EnvironmentRegistry, {
435
- run: (id, effect) => {
436
- expect(id).toBe(env);
437
- return Effect.provideService(effect, EnvironmentSupervisor, supervisor);
438
- },
439
- followStream: (id, stream) => {
440
- expect(id).toBe(env);
441
- return Stream.provideService(stream, EnvironmentSupervisor, supervisor);
442
- },
443
- } as EnvironmentRegistry["Service"]),
444
- );
445
- const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime);
446
- const list = peerLinks.list({ environmentId: env, input: {} });
447
- registry.mount(list);
448
- const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true });
449
- const setAccess = (writable: boolean) =>
450
- registry.set(
451
- sessions(env),
452
- AsyncResult.success({
453
- ...grant(false),
454
- scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
455
- permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
456
- }),
457
- );
458
- registry.mount(sessions(other));
395
+ ),
396
+ };
397
+ const supervisor = {
398
+ target: new BearerConnectionTarget({
399
+ environmentId: env,
400
+ label: "Test",
401
+ connectionId: "test",
402
+ }),
403
+ session: yield* SubscriptionRef.make(Option.some({ client } as unknown as RpcSession)),
404
+ state: yield* SubscriptionRef.make({
405
+ ...AVAILABLE_CONNECTION_STATE,
406
+ phase: "connected" as const,
407
+ }),
408
+ } as EnvironmentSupervisor["Service"];
409
+ const peerRuntime = Atom.runtime(
410
+ Layer.succeed(EnvironmentRegistry, {
411
+ run: (id, effect) => {
412
+ expect(id).toBe(env);
413
+ return Effect.provideService(effect, EnvironmentSupervisor, supervisor);
414
+ },
415
+ followStream: (id, stream) => {
416
+ expect(id).toBe(env);
417
+ return Stream.provideService(stream, EnvironmentSupervisor, supervisor);
418
+ },
419
+ } as EnvironmentRegistry["Service"]),
420
+ );
421
+ const peerLinks = createPeerLinkEnvironmentAtoms(peerRuntime);
422
+ const list = peerLinks.list({ environmentId: env, input: {} });
423
+ registry.mount(list);
424
+ const readLinks = AtomRegistry.getResult(registry, list, { suspendOnWaiting: true });
425
+ const setAccess = (writable: boolean) =>
426
registry.set(
460
- sessions(other),
427
+ sessions(env),
428
AsyncResult.success({
429
...grant(false),
463
- scopes: [AuthAccessWriteScope],
464
- permissions: [AuthAccessWriteScope],
430
+ scopes: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
431
+ permissions: [AuthAccessReadScope, ...(writable ? [AuthAccessWriteScope] : [])],
432
}),
433
);
467
- setAccess(false);
468
- expect(yield* readLinks).toEqual({ links: [] });
469
- const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };
470
- const link = Effect.promise(() =>
471
- peerLinks.link.run(registry, { environmentId: env, input: linkInput }),
472
- );
473
- const unlink = Effect.promise(() =>
474
- peerLinks.unlink.run(registry, {
475
- environmentId: env,
476
- input: { environmentId: peer.environmentId },
477
- }),
478
- );
479
- expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false);
480
- const deniedLink = yield* link;
481
- expect(deniedLink._tag).toBe("Failure");
482
- if (deniedLink._tag === "Failure") {
483
- expect(Cause.squash(deniedLink.cause)).toMatchObject({
484
- _tag: "EnvironmentAuthorizationError",
485
- requiredPermission: AuthAccessWriteScope,
486
- });
487
- }
488
- expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled();
489
- setAccess(true);
490
- expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true);
491
- expect((yield* link)._tag).toBe("Success");
492
- expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput);
493
- expect(yield* readLinks).toEqual({ links: [peer] });
494
-
495
- setAccess(false);
496
- expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false);
497
- const deniedUnlink = yield* unlink;
498
- expect(deniedUnlink._tag).toBe("Failure");
499
- if (deniedUnlink._tag === "Failure") {
500
- expect(Cause.squash(deniedUnlink.cause)).toMatchObject({
501
- _tag: "EnvironmentAuthorizationError",
502
- requiredPermission: AuthAccessWriteScope,
503
- });
504
- }
505
- expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled();
506
- expect(yield* readLinks).toEqual({ links: [peer] });
507
- setAccess(true);
508
- expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true);
509
- expect((yield* unlink)._tag).toBe("Success");
510
- expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({
511
- environmentId: peer.environmentId,
512
- });
513
- expect(yield* readLinks).toEqual({ links: [] });
514
- }),
515
- ),
516
-);
517
-
518
-it.effect("requires access management to answer a link request", () =>
519
- Effect.scoped(
520
- Effect.gen(function* () {
521
- const registry = yield* setup;
522
- registry.set(sessions(env), AsyncResult.success(grant(true)));
523
- const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest);
524
- expect(registry.get(answer.permissionAtom(env))).toBe(false);
525
- expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
526
- AuthAccessWriteScope,
527
- );
434
+ registry.mount(sessions(other));
435
registry.set(
529
- sessions(env),
436
+ sessions(other),
437
AsyncResult.success({
438
...grant(false),
439
scopes: [AuthAccessWriteScope],
440
permissions: [AuthAccessWriteScope],
441
}),
442
);
536
- expect(registry.get(answer.permissionAtom(env))).toBe(true);
537
- yield* answer.authorize(registry, env);
443
+ setAccess(false);
444
+ expect(yield* readLinks).toEqual({ links: [] });
445
+ const linkInput = { url: peer.urls[0]!, pairingCode: "test-code", access: peer.access };
446
+ const link = Effect.promise(() =>
447
+ peerLinks.link.run(registry, { environmentId: env, input: linkInput }),
448
+ );
449
+ const unlink = Effect.promise(() =>
450
+ peerLinks.unlink.run(registry, {
451
+ environmentId: env,
452
+ input: { environmentId: peer.environmentId },
453
+ }),
454
+ );
455
+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(false);
456
+ const deniedLink = yield* link;
457
+ expect(deniedLink._tag).toBe("Failure");
458
+ if (deniedLink._tag === "Failure") {
459
+ expect(Cause.squash(deniedLink.cause)).toMatchObject({
460
+ _tag: "EnvironmentAuthorizationError",
461
+ requiredPermission: AuthAccessWriteScope,
462
+ });
463
+ }
464
+ expect(client[WS_METHODS.peerLinksLink]).not.toHaveBeenCalled();
465
+ setAccess(true);
466
+ expect(registry.get(peerLinks.link.permissionAtom(env))).toBe(true);
467
+ expect((yield* link)._tag).toBe("Success");
468
+ expect(client[WS_METHODS.peerLinksLink]).toHaveBeenCalledExactlyOnceWith(linkInput);
469
+ expect(yield* readLinks).toEqual({ links: [peer] });
470
+
471
+ setAccess(false);
472
+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(false);
473
+ const deniedUnlink = yield* unlink;
474
+ expect(deniedUnlink._tag).toBe("Failure");
475
+ if (deniedUnlink._tag === "Failure") {
476
+ expect(Cause.squash(deniedUnlink.cause)).toMatchObject({
477
+ _tag: "EnvironmentAuthorizationError",
478
+ requiredPermission: AuthAccessWriteScope,
479
+ });
480
+ }
481
+ expect(client[WS_METHODS.peerLinksUnlink]).not.toHaveBeenCalled();
482
+ expect(yield* readLinks).toEqual({ links: [peer] });
483
+ setAccess(true);
484
+ expect(registry.get(peerLinks.unlink.permissionAtom(env))).toBe(true);
485
+ expect((yield* unlink)._tag).toBe("Success");
486
+ expect(client[WS_METHODS.peerLinksUnlink]).toHaveBeenCalledExactlyOnceWith({
487
+ environmentId: peer.environmentId,
488
+ });
489
+ expect(yield* readLinks).toEqual({ links: [] });
490
}),
539
- ),
491
+);
492
+
493
+it.effect("requires access management to answer a link request", () =>
494
+ Effect.gen(function* () {
495
+ const registry = yield* setup;
496
+ registry.set(sessions(env), AsyncResult.success(grant(true)));
497
+ const answer = createCommandPermissions(runtime, WS_METHODS.peerLinksAnswerRequest);
498
+ expect(registry.get(answer.permissionAtom(env))).toBe(false);
499
+ expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe(
500
+ AuthAccessWriteScope,
501
+ );
502
+ registry.set(
503
+ sessions(env),
504
+ AsyncResult.success({
505
+ ...grant(false),
506
+ scopes: [AuthAccessWriteScope],
507
+ permissions: [AuthAccessWriteScope],
508
+ }),
509
+ );
510
+ expect(registry.get(answer.permissionAtom(env))).toBe(true);
511
+ yield* answer.authorize(registry, env);
512
+ }),
513
);
514
515
it.effect("honors exact empty permissions and preserves legacy parent grants", () =>
543
- Effect.scoped(
544
- Effect.gen(function* () {
545
- const registry = yield* setup;
546
- const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
547
- registry.set(sessions(env), AsyncResult.success({ ...grant(true), permissions: [] }));
548
- expect(registry.get(git.permissionAtom(env))).toBe(false);
549
- const denied = yield* git.authorize(registry, env).pipe(Effect.flip);
550
- expect(denied).toMatchObject({
551
- requiredPermission: AuthSourceControlWriteScope,
552
- requiredScope: AuthOrchestrationOperateScope,
553
- });
554
- const { permissions: _exact, ...legacy } = grant(true);
555
- registry.set(sessions(env), AsyncResult.success(legacy));
556
- expect(registry.get(git.permissionAtom(env))).toBe(true);
557
- yield* git.authorize(registry, env);
558
- }),
559
- ),
516
+ Effect.gen(function* () {
517
+ const registry = yield* setup;
518
+ const git = createCommandPermissions(runtime, WS_METHODS.vcsInit);
519
+ registry.set(sessions(env), AsyncResult.success({ ...grant(true), permissions: [] }));
520
+ expect(registry.get(git.permissionAtom(env))).toBe(false);
521
+ const denied = yield* git.authorize(registry, env).pipe(Effect.flip);
522
+ expect(denied).toMatchObject({
523
+ requiredPermission: AuthSourceControlWriteScope,
524
+ requiredScope: AuthOrchestrationOperateScope,
525
+ });
526
+ const { permissions: _exact, ...legacy } = grant(true);
527
+ registry.set(sessions(env), AsyncResult.success(legacy));
528
+ expect(registry.get(git.permissionAtom(env))).toBe(true);
529
+ yield* git.authorize(registry, env);
530
+ }),
531
);
532
533
it.effect("rejects protected unary and streamed RPCs outside a guarded command", () =>
packages/client-runtime/src/state/connections.test.ts
+35
-39
@@ -75,48 +75,44 @@ const newSession = () => Option.some({} as RpcSession.RpcSession);
75
76
describe("environment catalog atoms", () => {
77
it.effect("changes the session generation only when a new session comes up", () =>
78
- Effect.scoped(
79
- Effect.gen(function* () {
80
- const { generation, generationAfter } = yield* makeCatalogHarness();
81
- const first = generation();
82
- // A retry reports the generation it is attempting before it is established.
83
- expect(
84
- yield* generationAfter(
85
- connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
86
- ),
87
- ).toBe(first);
88
- expect(
89
- yield* generationAfter(
90
- connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
91
- ),
92
- ).toBe(first);
93
- expect(
94
- yield* generationAfter(
95
- connectionState({ phase: "connected", attempt: 2, generation: 2 }),
96
- newSession(),
97
- ),
98
- ).not.toBe(first);
99
- }),
100
- ),
78
+ Effect.gen(function* () {
79
+ const { generation, generationAfter } = yield* makeCatalogHarness();
80
+ const first = generation();
81
+ // A retry reports the generation it is attempting before it is established.
82
+ expect(
83
+ yield* generationAfter(
84
+ connectionState({ phase: "connecting", stage: "opening", generation: 2, lastFailure }),
85
+ ),
86
+ ).toBe(first);
87
+ expect(
88
+ yield* generationAfter(
89
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
90
+ ),
91
+ ).toBe(first);
92
+ expect(
93
+ yield* generationAfter(
94
+ connectionState({ phase: "connected", attempt: 2, generation: 2 }),
95
+ newSession(),
96
+ ),
97
+ ).not.toBe(first);
98
+ }),
99
);
100
101
it.effect("changes when a replaced supervisor's first session reuses an old generation", () =>
104
- Effect.scoped(
105
- Effect.gen(function* () {
106
- const { generation, generationAfter } = yield* makeCatalogHarness();
107
- const first = generation();
102
+ Effect.gen(function* () {
103
+ const { generation, generationAfter } = yield* makeCatalogHarness();
104
+ const first = generation();
105
+ yield* generationAfter(
106
+ connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
107
+ );
108
+ // Re-pairing or editing a route installs a new supervisor, whose counter starts over.
109
+ yield* generationAfter(connectionState({ phase: "available", generation: 0 }));
110
+ expect(
111
yield* generationAfter(
109
- connectionState({ phase: "backoff", generation: 1, lastFailure, retryAt: 1 }),
110
- );
111
- // Re-pairing or editing a route installs a new supervisor, whose counter starts over.
112
- yield* generationAfter(connectionState({ phase: "available", generation: 0 }));
113
- expect(
114
- yield* generationAfter(
115
- connectionState({ phase: "connected", attempt: 1, generation: 1 }),
116
- newSession(),
117
- ),
118
- ).not.toBe(first);
119
- }),
120
- ),
112
+ connectionState({ phase: "connected", attempt: 1, generation: 1 }),
113
+ newSession(),
114
+ ),
115
+ ).not.toBe(first);
116
+ }),
117
);
118
});
packages/client-runtime/src/state/fileMetadata.test.ts
+12
-12
@@ -160,7 +160,7 @@ describe("file metadata", () => {
160
yield* TestClock.adjust(60_001);
161
yield* Effect.promise(() => vi.advanceTimersByTimeAsync(60_000));
162
expect(h.batches).toEqual([[path], ["/workspace/known"], [path], [path]]);
163
- }).pipe(Effect.scoped),
163
+ }),
164
);
165
166
it.effect("does not seed a different path from a literal name with a numeric suffix", () =>
@@ -179,7 +179,7 @@ describe("file metadata", () => {
179
expect(yield* h.read("/workspace/read:12:3")).toEqual({ kind: "file", byteLength: 100 });
180
expect(yield* h.read("/workspace/read")).toBeNull();
181
expect(h.batches).toEqual([["/workspace/report"], ["/workspace/read"]]);
182
- }).pipe(Effect.scoped),
182
+ }),
183
);
184
185
it.effect("retries only paths invalidated while their response is in flight", () =>
@@ -216,7 +216,7 @@ describe("file metadata", () => {
216
byteLength: 10,
217
});
218
expect(h.batches).toHaveLength(2);
219
- }).pipe(Effect.scoped),
219
+ }),
220
);
221
222
it.effect("an offscreen invalidation waits until that path is read again", () =>
@@ -236,7 +236,7 @@ describe("file metadata", () => {
236
kind: "directory",
237
});
238
expect(h.batches).toHaveLength(2);
239
- }).pipe(Effect.scoped),
239
+ }),
240
);
241
242
it.effect("invalidates a changed retained path without refetching other paths", () =>
@@ -262,7 +262,7 @@ describe("file metadata", () => {
262
h.registry.refresh(h.atom("/workspace/unchanged", ENVIRONMENT_ID, threadId));
263
yield* h.read("/workspace/unchanged", ENVIRONMENT_ID, threadId);
264
expect(h.batches.slice(before)).toEqual([["/workspace/file"]]);
265
- }).pipe(Effect.scoped),
265
+ }),
266
);
267
268
it.effect("a reconnect discards retained metadata from the previous session", () =>
@@ -279,7 +279,7 @@ describe("file metadata", () => {
279
kind: "directory",
280
});
281
expect(h.batches).toHaveLength(2);
282
- }).pipe(Effect.scoped),
282
+ }),
283
);
284
285
it.effect("keeps batches and cached paths separate across environments", () =>
@@ -293,7 +293,7 @@ describe("file metadata", () => {
293
{ concurrency: "unbounded" },
294
);
295
expect(h.batches.slice(1)).toEqual([["/workspace/new"], ["/workspace/new"]]);
296
- }).pipe(Effect.scoped),
296
+ }),
297
);
298
299
it.effect("settles a failed batch and can retry after access is granted", () =>
@@ -309,7 +309,7 @@ describe("file metadata", () => {
309
h.values.set("/workspace/a", { kind: "directory" });
310
h.registry.refresh(h.atom("/workspace/a"));
311
expect(yield* h.read("/workspace/a")).toEqual({ kind: "directory" });
312
- }).pipe(Effect.scoped),
312
+ }),
313
);
314
315
it.effect("reuses file read sizes and normalizes Windows cache keys", () =>
@@ -323,7 +323,7 @@ describe("file metadata", () => {
323
.pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, h.supervisor));
324
expect(yield* h.read("c:/workspace/file/")).toEqual({ kind: "file", byteLength: 100 });
325
expect(h.batches).toHaveLength(0);
326
- }).pipe(Effect.scoped),
326
+ }),
327
);
328
329
it.effect("batches mounted paths and deduplicates repeated chips", () =>
@@ -343,7 +343,7 @@ describe("file metadata", () => {
343
]);
344
yield* h.read("/workspace/file");
345
expect(h.batches).toHaveLength(1);
346
- }).pipe(Effect.scoped),
346
+ }),
347
);
348
349
it.effect("uses search and tree kinds without another request", () =>
@@ -352,7 +352,7 @@ describe("file metadata", () => {
352
yield* h.seed("folder.ts", "directory");
353
expect(yield* h.read("/workspace/folder.ts")).toEqual({ kind: "directory" });
354
expect(h.batches).toHaveLength(0);
355
- }).pipe(Effect.scoped),
355
+ }),
356
);
357
358
it.effect("splits large mounts into bounded batches and caches misses", () =>
@@ -368,6 +368,6 @@ describe("file metadata", () => {
368
const count = h.batches.length;
369
yield* h.read("/workspace/0");
370
expect(h.batches).toHaveLength(count);
371
- }).pipe(Effect.scoped),
371
+ }),
372
);
373
});
packages/client-runtime/src/state/projectCommands.test.ts
+4
-4
@@ -172,7 +172,7 @@ describe("writeFile metadata", () => {
172
yield* AtomRegistry.getResult(h.registry, metadata, { suspendOnWaiting: true }),
173
).toBeNull();
174
expect(h.metadataRequests).toEqual([["/repo/foo"]]);
175
- }).pipe(Effect.scoped),
175
+ }),
176
);
177
178
it.effect("does not restore old metadata from a read completed after a write", () =>
@@ -215,7 +215,7 @@ describe("writeFile metadata", () => {
215
h.registry.refresh(metadata);
216
expect(yield* readMetadata()).toEqual({ kind: "file", byteLength: 10 });
217
expect(h.metadataRequests).toHaveLength(2);
218
- }).pipe(Effect.scoped),
218
+ }),
219
);
220
221
it.effect("refreshes retained canonical and original paths after an aliased write", () =>
@@ -254,7 +254,7 @@ describe("writeFile metadata", () => {
254
"/repo/foo",
255
"/repo/./foo",
256
]);
257
- }).pipe(Effect.scoped),
257
+ }),
258
);
259
});
260
@@ -267,6 +267,6 @@ describe("openScratch", () => {
267
registry.set(storedProject, PROJECT);
268
const result = yield* Fiber.join(opening);
269
expect(result).toMatchObject({ _tag: "Success", value: PROJECT });
270
- }).pipe(Effect.scoped),
270
+ }),
271
);
272
});
packages/client-runtime/src/state/pullRequests.test.ts
+1794
-1867
@@ -73,429 +73,414 @@ it.effect.each([
73
"does not dispatch after the alternate is disabled during the probe",
74
"preserves a local source account rejection when alternate accounts differ",
75
] as const)("%s", (scenario) =>
76
- Effect.scoped(
76
+ Effect.gen(function* () {
77
+ const stalls = scenario === "returns a successful mutation when source invalidation stalls";
78
+ const invalidationStalled = yield* Deferred.make<void>();
79
+ const calls: string[] = [];
80
+ const inputs: unknown[] = [];
81
+ let trusted = true;
82
+ let disableAlternate = Effect.void;
83
+ const switchedAccount =
84
+ scenario === "preserves a local source account rejection when alternate accounts differ";
85
+ const mismatch =
86
+ scenario === "falls back before mutation when the local account differs" || switchedAccount;
87
+ const ambiguous = scenario === "never retries an ambiguous mutation failure";
88
+ const reading =
89
+ scenario === "returns a fast local source read without checking alternate identities";
90
+ const single = scenario === "keeps single-environment requests free of identity lookups";
91
+ const localOrigin =
92
+ scenario === "keeps a local origin ahead of another local environment" ||
93
+ switchedAccount ||
94
+ reading;
95
+ const oldOrigin = scenario === "keeps mutations on an old origin server without retrying them";
96
+ const oldAlternate = scenario === "skips an old alternate server before dispatching a mutation";
97
+ const failure = new PullRequestOperationError({
98
+ operation: switchedAccount ? "routeIdentity" : "runAction",
99
+ detail: "connection lost after dispatch",
100
+ });
101
+ const clientFor = (local: boolean) => {
102
+ const name = local ? "local" : "origin";
103
+ return {
104
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
105
+ input: unknown,
106
+ ) =>
107
+ Effect.gen(function* () {
108
+ if (local) expect(input).toEqual({ host: "github.com" });
109
+ calls.push(`${name}:identity`);
110
+ if (
111
+ local &&
112
+ scenario === "does not dispatch after the alternate is disabled during the probe"
113
+ )
114
+ yield* disableAlternate;
115
+ if (
116
+ local &&
117
+ scenario === "does not dispatch after routing permission is revoked during the probe"
118
+ )
119
+ trusted = false;
120
+ if ((!local && oldOrigin) || (local && oldAlternate)) {
121
+ return yield* Effect.die(`Unknown request tag: ${WS_METHODS.pullRequestsRouting}`);
122
+ }
123
+ return {
124
+ host: "github.com",
125
+ provider: "github",
126
+ viewer: "maria-rcks",
127
+ accountId: local && mismatch ? "456" : "123",
128
+ };
129
+ }),
130
+ [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
131
+ Effect.gen(function* () {
132
+ calls.push(`${name}:mutation`);
133
+ inputs.push(input);
134
+ if (
135
+ !local &&
136
+ switchedAccount &&
137
+ (input as { expectedAccountId?: string }).expectedAccountId === "123"
138
+ )
139
+ return yield* failure;
140
+ if (local && ambiguous) return yield* failure;
141
+ }),
142
+ [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
143
+ Effect.gen(function* () {
144
+ calls.push(`${name}:read`);
145
+ expect(input.allowStale).toBe(false);
146
+ if (local) return yield* failure;
147
+ return null;
148
+ }),
149
+ [WS_METHODS.pullRequestsInvalidate]: () =>
150
+ Effect.gen(function* () {
151
+ calls.push(`${name}:invalidate`);
152
+ if (!local && stalls) {
153
+ yield* Deferred.succeed(invalidationStalled, undefined);
154
+ return yield* Effect.never;
155
+ }
156
+ }),
157
+ } as unknown as WsRpcProtocolClient;
158
+ };
159
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
160
+ clientFor(false),
161
+ single ? undefined : clientFor(true),
162
+ localOrigin,
163
+ );
164
+ disableAlternate = SubscriptionRef.update(
165
+ environmentRegistry.entries,
166
+ (entries) =>
167
+ new Map(
168
+ [...entries].map(([id, entry]) => [
169
+ id,
170
+ id === TARGET.environmentId ? entry : { ...entry, enabled: false },
171
+ ]),
172
+ ),
173
+ );
174
+ const disabled = scenario === "keeps mutations on the origin when the alternate is disabled";
175
+ const disabledDuringProbe =
176
+ scenario === "does not dispatch after the alternate is disabled during the probe";
177
+ if (disabled) yield* disableAlternate;
178
+ const input = {
179
+ projectId: ProjectId.make("project-1"),
180
+ host: "github.com",
181
+ repository: "acme/web",
182
+ number: 7,
183
+ action: "merge" as const,
184
+ };
185
+ const route = createPullRequestRouter();
186
+ const routed = (
187
+ reading
188
+ ? route(WS_METHODS.pullRequestsSummary, input)
189
+ : route(WS_METHODS.pullRequestsRunAction, input)
190
+ ).pipe(
191
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
192
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
193
+ Effect.provideService(PullRequestRoutingPermissions, {
194
+ ...trustedRouting,
195
+ get: () => Effect.succeed(trusted ? "read-write" : "off"),
196
+ }),
197
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
198
+ Effect.result,
199
+ );
200
+ const result = stalls
201
+ ? yield* Effect.gen(function* () {
202
+ const fiber = yield* Effect.forkChild(routed);
203
+ yield* Deferred.await(invalidationStalled);
204
+ yield* TestClock.adjust("1 second");
205
+ return yield* Fiber.join(fiber);
206
+ })
207
+ : yield* routed;
208
+
209
+ if (switchedAccount) {
210
+ expect(result).toMatchObject({ _tag: "Failure", failure });
211
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
212
+ expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
213
+ } else if (ambiguous) {
214
+ expect(result).toMatchObject({ _tag: "Failure", failure });
215
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
216
+ } else {
217
+ expect(result._tag).toBe("Success");
218
+ if (single || disabled) {
219
+ expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual(["origin:mutation"]);
220
+ } else if (reading) expect(calls).toEqual(["origin:read"]);
221
+ else if (
222
+ mismatch ||
223
+ localOrigin ||
224
+ oldOrigin ||
225
+ oldAlternate ||
226
+ !trusted ||
227
+ disabledDuringProbe
228
+ )
229
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
230
+ else {
231
+ expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
232
+ expect(calls).toContain("origin:invalidate");
233
+ expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
234
+ }
235
+ }
236
+ }),
237
+);
238
+
239
+it.effect.each([
240
+ { probe: "origin", cancelled: "first" },
241
+ { probe: "origin", cancelled: "waiter" },
242
+ { probe: "alternate", cancelled: "first" },
243
+ { probe: "alternate", cancelled: "waiter" },
244
+] as const)(
245
+ "preserves a shared $probe probe's other reader when the $cancelled cancels",
246
+ ({ probe, cancelled }) =>
247
Effect.gen(function* () {
78
- const stalls = scenario === "returns a successful mutation when source invalidation stalls";
79
- const invalidationStalled = yield* Deferred.make<void>();
80
- const calls: string[] = [];
81
- const inputs: unknown[] = [];
82
- let trusted = true;
83
- let disableAlternate = Effect.void;
84
- const switchedAccount =
85
- scenario === "preserves a local source account rejection when alternate accounts differ";
86
- const mismatch =
87
- scenario === "falls back before mutation when the local account differs" || switchedAccount;
88
- const ambiguous = scenario === "never retries an ambiguous mutation failure";
89
- const reading =
90
- scenario === "returns a fast local source read without checking alternate identities";
91
- const single = scenario === "keeps single-environment requests free of identity lookups";
92
- const localOrigin =
93
- scenario === "keeps a local origin ahead of another local environment" ||
94
- switchedAccount ||
95
- reading;
96
- const oldOrigin =
97
- scenario === "keeps mutations on an old origin server without retrying them";
98
- const oldAlternate =
99
- scenario === "skips an old alternate server before dispatching a mutation";
100
- const failure = new PullRequestOperationError({
101
- operation: switchedAccount ? "routeIdentity" : "runAction",
102
- detail: "connection lost after dispatch",
103
- });
104
- const clientFor = (local: boolean) => {
105
- const name = local ? "local" : "origin";
106
- return {
107
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: (
108
- input: unknown,
109
- ) =>
248
+ const started = yield* Deferred.make<void>();
249
+ const release = yield* Deferred.make<void>();
250
+ let probes = 0;
251
+ const clientFor = (local: boolean) =>
252
+ ({
253
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
254
Effect.gen(function* () {
111
- if (local) expect(input).toEqual({ host: "github.com" });
112
- calls.push(`${name}:identity`);
113
- if (
114
- local &&
115
- scenario === "does not dispatch after the alternate is disabled during the probe"
116
- )
117
- yield* disableAlternate;
118
- if (
119
- local &&
120
- scenario ===
121
- "does not dispatch after routing permission is revoked during the probe"
122
- )
123
- trusted = false;
124
- if ((!local && oldOrigin) || (local && oldAlternate)) {
125
- return yield* Effect.die(`Unknown request tag: ${WS_METHODS.pullRequestsRouting}`);
255
+ if (local === (probe === "alternate")) {
256
+ probes++;
257
+ yield* Deferred.succeed(started, undefined);
258
+ yield* Deferred.await(release);
259
}
260
return {
261
host: "github.com",
262
provider: "github",
130
- viewer: "maria-rcks",
131
- accountId: local && mismatch ? "456" : "123",
263
+ viewer: "maria",
264
+ accountId: "123",
265
};
266
}),
134
- [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
267
+ [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
268
+ }) as unknown as WsRpcProtocolClient;
269
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
270
+ clientFor(false),
271
+ clientFor(true),
272
+ );
273
+ const read = () =>
274
+ createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
275
+ projectId: ProjectId.make("project-1"),
276
+ repository: "acme/web",
277
+ number: 7,
278
+ }).pipe(
279
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
280
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
281
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
282
+ );
283
+ const first = yield* read().pipe(Effect.forkChild);
284
+ yield* Deferred.await(started);
285
+ const waiter = yield* read().pipe(Effect.forkChild);
286
+ yield* Effect.yieldNow;
287
+ yield* Fiber.interrupt(cancelled === "first" ? first : waiter);
288
+ yield* Deferred.succeed(release, undefined);
289
+ expect(yield* Fiber.join(cancelled === "first" ? waiter : first)).toBeNull();
290
+ expect(probes).toBe(cancelled === "first" ? 2 : 1);
291
+ yield* read();
292
+ expect(probes).toBe(cancelled === "first" ? 3 : 2);
293
+ }),
294
+);
295
+
296
+it.effect.each(["revoked", "disabled"] as const)(
297
+ "rechecks routing after an alternate with a shared probe is %s",
298
+ (change) =>
299
+ Effect.gen(function* () {
300
+ const started = yield* Deferred.make<void>();
301
+ const release = yield* Deferred.make<void>();
302
+ const reads: string[] = [];
303
+ let trusted = true;
304
+ let probes = 0;
305
+ const clientFor = (local: boolean) =>
306
+ ({
307
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
308
Effect.gen(function* () {
136
- calls.push(`${name}:mutation`);
137
- inputs.push(input);
138
- if (
139
- !local &&
140
- switchedAccount &&
141
- (input as { expectedAccountId?: string }).expectedAccountId === "123"
142
- )
143
- return yield* failure;
144
- if (local && ambiguous) return yield* failure;
309
+ if (local) {
310
+ probes++;
311
+ yield* Deferred.succeed(started, undefined);
312
+ yield* Deferred.await(release);
313
+ }
314
+ return {
315
+ host: "github.com",
316
+ provider: "github",
317
+ viewer: "maria",
318
+ accountId: "123",
319
+ };
320
}),
146
- [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
147
- Effect.gen(function* () {
148
- calls.push(`${name}:read`);
149
- expect(input.allowStale).toBe(false);
150
- if (local) return yield* failure;
321
+ [WS_METHODS.pullRequestsSummary]: () =>
322
+ Effect.sync(() => {
323
+ reads.push(local ? "local" : "origin");
324
return null;
325
}),
153
- [WS_METHODS.pullRequestsInvalidate]: () =>
154
- Effect.gen(function* () {
155
- calls.push(`${name}:invalidate`);
156
- if (!local && stalls) {
157
- yield* Deferred.succeed(invalidationStalled, undefined);
158
- return yield* Effect.never;
159
- }
160
- }),
161
- } as unknown as WsRpcProtocolClient;
162
- };
326
+ }) as unknown as WsRpcProtocolClient;
327
const { environmentRegistry, supervisor } = yield* makeTestRuntime(
328
clientFor(false),
165
- single ? undefined : clientFor(true),
166
- localOrigin,
167
- );
168
- disableAlternate = SubscriptionRef.update(
169
- environmentRegistry.entries,
170
- (entries) =>
171
- new Map(
172
- [...entries].map(([id, entry]) => [
173
- id,
174
- id === TARGET.environmentId ? entry : { ...entry, enabled: false },
175
- ]),
176
- ),
329
+ clientFor(true),
330
);
178
- const disabled = scenario === "keeps mutations on the origin when the alternate is disabled";
179
- const disabledDuringProbe =
180
- scenario === "does not dispatch after the alternate is disabled during the probe";
181
- if (disabled) yield* disableAlternate;
182
- const input = {
183
- projectId: ProjectId.make("project-1"),
184
- host: "github.com",
185
- repository: "acme/web",
186
- number: 7,
187
- action: "merge" as const,
188
- };
189
- const route = createPullRequestRouter();
190
- const routed = (
191
- reading
192
- ? route(WS_METHODS.pullRequestsSummary, input)
193
- : route(WS_METHODS.pullRequestsRunAction, input)
331
+ const readers = yield* Effect.all(
332
+ Array.from({ length: 2 }, () =>
333
+ createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
334
+ projectId: ProjectId.make("project-1"),
335
+ repository: "acme/web",
336
+ number: 7,
337
+ }),
338
+ ),
339
+ { concurrency: "unbounded" },
340
).pipe(
341
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
196
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
342
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
343
Effect.provideService(PullRequestRoutingPermissions, {
344
...trustedRouting,
199
- get: () => Effect.succeed(trusted ? "read-write" : "off"),
345
+ get: () => Effect.sync(() => (trusted ? "read-write" : "off")),
346
}),
201
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
202
- Effect.result,
347
+ Effect.forkChild,
348
);
204
- const result = stalls
205
- ? yield* Effect.gen(function* () {
206
- const fiber = yield* Effect.forkChild(routed);
207
- yield* Deferred.await(invalidationStalled);
208
- yield* TestClock.adjust("1 second");
209
- return yield* Fiber.join(fiber);
210
- })
211
- : yield* routed;
212
-
213
- if (switchedAccount) {
214
- expect(result).toMatchObject({ _tag: "Failure", failure });
215
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
216
- expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
217
- } else if (ambiguous) {
218
- expect(result).toMatchObject({ _tag: "Failure", failure });
219
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
220
- } else {
221
- expect(result._tag).toBe("Success");
222
- if (single || disabled) {
223
- expect(calls.filter((call) => !call.endsWith(":invalidate"))).toEqual([
224
- "origin:mutation",
225
- ]);
226
- } else if (reading) expect(calls).toEqual(["origin:read"]);
227
- else if (
228
- mismatch ||
229
- localOrigin ||
230
- oldOrigin ||
231
- oldAlternate ||
232
- !trusted ||
233
- disabledDuringProbe
234
- )
235
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["origin:mutation"]);
236
- else {
237
- expect(calls.filter((call) => call.endsWith(":mutation"))).toEqual(["local:mutation"]);
238
- expect(calls).toContain("origin:invalidate");
239
- expect(inputs).toEqual([{ ...input, expectedAccountId: "123" }]);
240
- }
241
- }
242
- }),
243
- ),
244
-);
245
-
246
-it.effect.each([
247
- { probe: "origin", cancelled: "first" },
248
- { probe: "origin", cancelled: "waiter" },
249
- { probe: "alternate", cancelled: "first" },
250
- { probe: "alternate", cancelled: "waiter" },
251
-] as const)(
252
- "preserves a shared $probe probe's other reader when the $cancelled cancels",
253
- ({ probe, cancelled }) =>
254
- Effect.scoped(
255
- Effect.gen(function* () {
256
- const started = yield* Deferred.make<void>();
257
- const release = yield* Deferred.make<void>();
258
- let probes = 0;
259
- const clientFor = (local: boolean) =>
260
- ({
261
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
262
- Effect.gen(function* () {
263
- if (local === (probe === "alternate")) {
264
- probes++;
265
- yield* Deferred.succeed(started, undefined);
266
- yield* Deferred.await(release);
267
- }
268
- return {
269
- host: "github.com",
270
- provider: "github",
271
- viewer: "maria",
272
- accountId: "123",
273
- };
274
- }),
275
- [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
276
- }) as unknown as WsRpcProtocolClient;
277
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
278
- clientFor(false),
279
- clientFor(true),
349
+ yield* Deferred.await(started);
350
+ yield* Effect.yieldNow;
351
+ if (change === "revoked") trusted = false;
352
+ else
353
+ yield* SubscriptionRef.update(
354
+ environmentRegistry.entries,
355
+ (entries) =>
356
+ new Map(
357
+ [...entries].map(([id, entry]) => [
358
+ id,
359
+ id === TARGET.environmentId ? entry : { ...entry, enabled: false },
360
+ ]),
361
+ ),
362
);
281
- const read = () =>
282
- createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
283
- projectId: ProjectId.make("project-1"),
284
- repository: "acme/web",
285
- number: 7,
286
- }).pipe(
287
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
288
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
289
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
290
- );
291
- const first = yield* read().pipe(Effect.forkChild);
292
- yield* Deferred.await(started);
293
- const waiter = yield* read().pipe(Effect.forkChild);
294
- yield* Effect.yieldNow;
295
- yield* Fiber.interrupt(cancelled === "first" ? first : waiter);
296
- yield* Deferred.succeed(release, undefined);
297
- expect(yield* Fiber.join(cancelled === "first" ? waiter : first)).toBeNull();
298
- expect(probes).toBe(cancelled === "first" ? 2 : 1);
299
- yield* read();
300
- expect(probes).toBe(cancelled === "first" ? 3 : 2);
301
- }),
302
- ),
363
+ yield* Deferred.succeed(release, undefined);
364
+ expect(yield* Fiber.join(readers)).toEqual([null, null]);
365
+ expect(probes).toBe(1);
366
+ expect(reads).toEqual(["origin", "origin"]);
367
+ }),
368
);
369
305
-it.effect.each(["revoked", "disabled"] as const)(
306
- "rechecks routing after an alternate with a shared probe is %s",
307
- (change) =>
308
- Effect.scoped(
309
- Effect.gen(function* () {
310
- const started = yield* Deferred.make<void>();
311
- const release = yield* Deferred.make<void>();
312
- const reads: string[] = [];
313
- let trusted = true;
314
- let probes = 0;
315
- const clientFor = (local: boolean) =>
316
- ({
317
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
318
- Effect.gen(function* () {
319
- if (local) {
320
- probes++;
370
+it.effect.each(["origin", "alternate"] as const)(
371
+ "keeps pending metadata from an old %s connection separate from its replacement",
372
+ (reconnected) =>
373
+ Effect.gen(function* () {
374
+ const started = yield* Deferred.make<void>();
375
+ const release = yield* Deferred.make<void>();
376
+ const probes: string[] = [];
377
+ const clientFor = (local: boolean, replacement = false) =>
378
+ ({
379
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
380
+ Effect.gen(function* () {
381
+ if (local === (reconnected === "alternate")) {
382
+ probes.push(replacement ? "new" : "old");
383
+ if (!replacement) {
384
yield* Deferred.succeed(started, undefined);
385
yield* Deferred.await(release);
386
}
324
- return {
325
- host: "github.com",
326
- provider: "github",
327
- viewer: "maria",
328
- accountId: "123",
329
- };
330
- }),
331
- [WS_METHODS.pullRequestsSummary]: () =>
332
- Effect.sync(() => {
333
- reads.push(local ? "local" : "origin");
334
- return null;
335
- }),
336
- }) as unknown as WsRpcProtocolClient;
337
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
338
- clientFor(false),
339
- clientFor(true),
340
- );
341
- const readers = yield* Effect.all(
342
- Array.from({ length: 2 }, () =>
343
- createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
344
- projectId: ProjectId.make("project-1"),
345
- repository: "acme/web",
346
- number: 7,
387
+ }
388
+ return {
389
+ host: "github.com",
390
+ provider: "github",
391
+ viewer: "maria",
392
+ accountId: "123",
393
+ };
394
}),
348
- ),
349
- { concurrency: "unbounded" },
350
- ).pipe(
395
+ [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
396
+ }) as unknown as WsRpcProtocolClient;
397
+ const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
398
+ clientFor(false),
399
+ clientFor(true),
400
+ );
401
+ const read = () =>
402
+ createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
403
+ projectId: ProjectId.make("project-1"),
404
+ repository: "acme/web",
405
+ number: 7,
406
+ }).pipe(
407
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
408
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
353
- Effect.provideService(PullRequestRoutingPermissions, {
354
- ...trustedRouting,
355
- get: () => Effect.sync(() => (trusted ? "read-write" : "off")),
356
- }),
357
- Effect.forkChild,
358
- );
359
- yield* Deferred.await(started);
360
- yield* Effect.yieldNow;
361
- if (change === "revoked") trusted = false;
362
- else
363
- yield* SubscriptionRef.update(
364
- environmentRegistry.entries,
365
- (entries) =>
366
- new Map(
367
- [...entries].map(([id, entry]) => [
368
- id,
369
- id === TARGET.environmentId ? entry : { ...entry, enabled: false },
370
- ]),
371
- ),
372
- );
373
- yield* Deferred.succeed(release, undefined);
374
- expect(yield* Fiber.join(readers)).toEqual([null, null]);
375
- expect(probes).toBe(1);
376
- expect(reads).toEqual(["origin", "origin"]);
377
- }),
378
- ),
379
-);
380
-
381
-it.effect.each(["origin", "alternate"] as const)(
382
- "keeps pending metadata from an old %s connection separate from its replacement",
383
- (reconnected) =>
384
- Effect.scoped(
385
- Effect.gen(function* () {
386
- const started = yield* Deferred.make<void>();
387
- const release = yield* Deferred.make<void>();
388
- const probes: string[] = [];
389
- const clientFor = (local: boolean, replacement = false) =>
390
- ({
391
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
392
- Effect.gen(function* () {
393
- if (local === (reconnected === "alternate")) {
394
- probes.push(replacement ? "new" : "old");
395
- if (!replacement) {
396
- yield* Deferred.succeed(started, undefined);
397
- yield* Deferred.await(release);
398
- }
399
- }
400
- return {
401
- host: "github.com",
402
- provider: "github",
403
- viewer: "maria",
404
- accountId: "123",
405
- };
406
- }),
407
- [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(null),
408
- }) as unknown as WsRpcProtocolClient;
409
- const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
410
- clientFor(false),
411
- clientFor(true),
412
- );
413
- const read = () =>
414
- createPullRequestRouter()(WS_METHODS.pullRequestsSummary, {
415
- projectId: ProjectId.make("project-1"),
416
- repository: "acme/web",
417
- number: 7,
418
- }).pipe(
419
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
420
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
421
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
422
- );
423
- const first = yield* read().pipe(Effect.forkChild);
424
- yield* Deferred.await(started);
425
- yield* SubscriptionRef.set(
426
- (reconnected === "origin" ? supervisor : localSupervisor).session,
427
- Option.some(session(clientFor(reconnected === "alternate", true))),
409
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
410
);
429
- expect(yield* read()).toBeNull();
430
- expect(probes).toEqual(["old", "new"]);
431
- yield* Deferred.succeed(release, undefined);
432
- expect(yield* Fiber.join(first)).toBeNull();
433
- }),
434
- ),
411
+ const first = yield* read().pipe(Effect.forkChild);
412
+ yield* Deferred.await(started);
413
+ yield* SubscriptionRef.set(
414
+ (reconnected === "origin" ? supervisor : localSupervisor).session,
415
+ Option.some(session(clientFor(reconnected === "alternate", true))),
416
+ );
417
+ expect(yield* read()).toBeNull();
418
+ expect(probes).toEqual(["old", "new"]);
419
+ yield* Deferred.succeed(release, undefined);
420
+ expect(yield* Fiber.join(first)).toBeNull();
421
+ }),
422
);
423
424
it.effect("forgets routed viewed marks when a viewed-files batch fails", () =>
438
- Effect.scoped(
439
- Effect.gen(function* () {
440
- const reference = {
441
- projectId: ProjectId.make("project-1"),
442
- host: "github.com",
443
- repository: "acme/web",
444
- number: 7,
445
- };
446
- const invalidations: { environment: string; input: unknown }[] = [];
447
- const identity = () =>
448
- Effect.succeed({
449
- host: reference.host,
450
- provider: "github",
451
- accountId: "123",
452
- viewer: "maria-rcks",
453
- });
454
- const clientFor = (environment: string) =>
455
- ({
456
- [WS_METHODS.pullRequestsRouting]: identity,
457
- [WS_METHODS.pullRequestsRoutingIdentity]: identity,
458
- [WS_METHODS.pullRequestsFilesViewed]: () =>
459
- Effect.succeed({ files: [{ path: "a.ts", state: "unviewed" }], truncated: false }),
460
- // The host may have applied part of the batch before refusing the rest.
461
- [WS_METHODS.pullRequestsSetFilesViewed]: () => Effect.fail("second path refused"),
462
- [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
463
- Effect.sync(() => {
464
- invalidations.push({ environment, input });
465
- }),
466
- }) as unknown as WsRpcProtocolClient;
467
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
468
- clientFor("origin"),
469
- clientFor("local"),
470
- );
471
- const route = createPullRequestRouter();
472
- const write = yield* Effect.gen(function* () {
473
- yield* route(WS_METHODS.pullRequestsFilesViewed, reference);
474
- return yield* Effect.exit(
475
- route(WS_METHODS.pullRequestsSetFilesViewed, {
476
- ...reference,
477
- files: [
478
- { path: "a.ts", viewed: true },
479
- { path: "b.ts", viewed: true },
480
- ],
425
+ Effect.gen(function* () {
426
+ const reference = {
427
+ projectId: ProjectId.make("project-1"),
428
+ host: "github.com",
429
+ repository: "acme/web",
430
+ number: 7,
431
+ };
432
+ const invalidations: { environment: string; input: unknown }[] = [];
433
+ const identity = () =>
434
+ Effect.succeed({
435
+ host: reference.host,
436
+ provider: "github",
437
+ accountId: "123",
438
+ viewer: "maria-rcks",
439
+ });
440
+ const clientFor = (environment: string) =>
441
+ ({
442
+ [WS_METHODS.pullRequestsRouting]: identity,
443
+ [WS_METHODS.pullRequestsRoutingIdentity]: identity,
444
+ [WS_METHODS.pullRequestsFilesViewed]: () =>
445
+ Effect.succeed({ files: [{ path: "a.ts", state: "unviewed" }], truncated: false }),
446
+ // The host may have applied part of the batch before refusing the rest.
447
+ [WS_METHODS.pullRequestsSetFilesViewed]: () => Effect.fail("second path refused"),
448
+ [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
449
+ Effect.sync(() => {
450
+ invalidations.push({ environment, input });
451
}),
482
- );
483
- }).pipe(
484
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
485
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
486
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
487
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
452
+ }) as unknown as WsRpcProtocolClient;
453
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
454
+ clientFor("origin"),
455
+ clientFor("local"),
456
+ );
457
+ const route = createPullRequestRouter();
458
+ const write = yield* Effect.gen(function* () {
459
+ yield* route(WS_METHODS.pullRequestsFilesViewed, reference);
460
+ return yield* Effect.exit(
461
+ route(WS_METHODS.pullRequestsSetFilesViewed, {
462
+ ...reference,
463
+ files: [
464
+ { path: "a.ts", viewed: true },
465
+ { path: "b.ts", viewed: true },
466
+ ],
467
+ }),
468
);
489
- expect(write._tag).toBe("Failure");
490
- expect(invalidations).toContainEqual({
491
- environment: "local",
492
- input: { reference: expect.objectContaining(reference), filesViewedOnly: true },
493
- });
494
- for (const call of invalidations) {
495
- expect(call.input).toMatchObject({ filesViewedOnly: true });
496
- }
497
- }),
498
- ),
469
+ }).pipe(
470
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
471
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
472
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
473
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
474
+ );
475
+ expect(write._tag).toBe("Failure");
476
+ expect(invalidations).toContainEqual({
477
+ environment: "local",
478
+ input: { reference: expect.objectContaining(reference), filesViewedOnly: true },
479
+ });
480
+ for (const call of invalidations) {
481
+ expect(call.input).toMatchObject({ filesViewedOnly: true });
482
+ }
483
+ }),
484
);
485
486
const TARGET = new PrimaryConnectionTarget({
@@ -618,491 +603,477 @@ it.effect.each([
603
] as const)(
604
"preserves source requests when routing to another environment is blocked by %s",
605
(permission) =>
621
- Effect.scoped(
622
- Effect.gen(function* () {
623
- const calls: string[] = [];
624
- const failure = new PullRequestOperationError({
625
- operation: "summary",
626
- detail: "source failed",
627
- });
628
- const client = {
629
- [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
630
- Effect.suspend(() => {
631
- calls.push("source-read");
632
- expect(input.allowStale).toBeUndefined();
633
- return Effect.fail(failure);
634
- }),
635
- [WS_METHODS.pullRequestsRunAction]: () =>
636
- Effect.sync(() => {
637
- calls.push("source-write");
638
- }),
639
- } as unknown as WsRpcProtocolClient;
640
- const alternate = {
641
- [WS_METHODS.pullRequestsRoutingIdentity]: () =>
642
- Effect.die("untrusted environment was contacted"),
643
- } as unknown as WsRpcProtocolClient;
644
- const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
645
- client,
646
- alternate,
647
- );
648
- if (permission === "destination-disabled" || permission === "destination-unsupported") {
649
- yield* SubscriptionRef.update(
650
- environmentRegistry.entries,
651
- (entries) =>
652
- new Map(
653
- [...entries].map(([id, entry]) => [
654
- id,
655
- id === TARGET.environmentId
656
- ? entry
657
- : {
658
- ...entry,
659
- enabled: permission !== "destination-disabled",
660
- ...(permission === "destination-unsupported"
661
- ? { unsupportedReason: "Protocol version mismatch" }
662
- : {}),
663
- },
664
- ]),
665
- ),
666
- );
667
- yield* SubscriptionRef.set(localSupervisor.session, Option.none());
668
- }
669
- const ref = {
670
- projectId: ProjectId.make("project-1"),
671
- repository: "private/repo",
672
- number: 7,
673
- };
674
- const request = Effect.gen(function* () {
675
- const route = createPullRequestRouter();
676
- if (permission !== "read-only")
677
- yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip);
678
- yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" });
679
- }).pipe(
680
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
681
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
682
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
683
- );
684
- yield* permission === "default"
685
- ? request
686
- : request.pipe(
687
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
688
- Effect.provideService(PullRequestRoutingPermissions, {
689
- ...trustedRouting,
690
- get: (entry) =>
691
- Effect.succeed(
692
- permission === "read-only"
693
- ? "read"
694
- : permission === "destination-disabled" ||
695
- permission === "destination-unsupported"
696
- ? "read-write"
697
- : (entry.target.environmentId === TARGET.environmentId) ===
698
- (permission === "origin-off")
699
- ? "off"
700
- : "read-write",
701
- ),
702
- }),
703
- );
704
- expect(calls).toEqual(
705
- permission === "read-only" ? ["source-write"] : ["source-read", "source-write"],
706
- );
707
- }),
708
- ),
709
-);
710
-
711
-it.effect.each(
712
- (["origin", "destination"] as const).flatMap((side) =>
713
- (["matching", "changed", "missing", "unavailable", "failed"] as const).map((stored) => ({
714
- side,
715
- stored,
716
- })),
717
- ),
718
-)("checks the current $side SSH profile before routing with $stored storage", ({ side, stored }) =>
719
- Effect.scoped(
606
Effect.gen(function* () {
607
const calls: string[] = [];
722
- const identity = {
723
- host: "github.com",
724
- provider: "github",
725
- viewer: "maria",
726
- accountId: "123",
727
- };
608
+ const failure = new PullRequestOperationError({
609
+ operation: "summary",
610
+ detail: "source failed",
611
+ });
612
const client = {
729
- [WS_METHODS.pullRequestsRouting]: () =>
613
+ [WS_METHODS.pullRequestsSummary]: (input: { allowStale?: boolean }) =>
614
+ Effect.suspend(() => {
615
+ calls.push("source-read");
616
+ expect(input.allowStale).toBeUndefined();
617
+ return Effect.fail(failure);
618
+ }),
619
+ [WS_METHODS.pullRequestsRunAction]: () =>
620
Effect.sync(() => {
731
- calls.push("source-probe");
732
- return identity;
621
+ calls.push("source-write");
622
}),
734
- [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
735
- Effect.gen(function* () {
736
- if (input.expectedAccountId !== undefined) {
737
- return yield* new PullRequestOperationError({
738
- operation: "routeIdentity",
739
- detail: "Source guard refused.",
740
- });
741
- }
742
- calls.push("source-write");
743
- }),
744
- [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
623
} as unknown as WsRpcProtocolClient;
624
const alternate = {
625
[WS_METHODS.pullRequestsRoutingIdentity]: () =>
748
- Effect.sync(() => {
749
- calls.push("alternate-probe");
750
- return identity;
751
- }),
752
- [WS_METHODS.pullRequestsRunAction]: () =>
753
- Effect.sync(() => {
754
- calls.push("alternate-write");
755
- }),
756
- [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
626
+ Effect.die("untrusted environment was contacted"),
627
} as unknown as WsRpcProtocolClient;
758
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
759
- const environmentId =
760
- side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
761
- const profile = new SshConnectionProfile({
762
- connectionId: "ssh-1",
763
- environmentId,
764
- label: "SSH",
765
- target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
766
- });
767
- yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
768
- new Map(entries).set(environmentId, {
769
- target: new SshConnectionTarget({
770
- environmentId,
771
- connectionId: profile.connectionId,
772
- label: "SSH",
773
- }),
774
- profile: Option.some(profile),
775
- enabled: true,
776
- }),
628
+ const { environmentRegistry, supervisor, localSupervisor } = yield* makeTestRuntime(
629
+ client,
630
+ alternate,
631
);
778
- const read = Effect.suspend(() =>
779
- stored === "failed"
780
- ? Effect.fail(
781
- new ConnectionTransientError({
782
- reason: "remote-unavailable",
783
- detail: "Profile storage unavailable.",
784
- }),
785
- )
786
- : Effect.succeed(
787
- stored === "missing"
788
- ? Option.none()
789
- : Option.some(
790
- stored === "changed"
791
- ? new SshConnectionProfile({
792
- ...profile,
793
- target: { ...profile.target, hostname: "replacement.example.test" },
794
- })
795
- : profile,
796
- ),
632
+ if (permission === "destination-disabled" || permission === "destination-unsupported") {
633
+ yield* SubscriptionRef.update(
634
+ environmentRegistry.entries,
635
+ (entries) =>
636
+ new Map(
637
+ [...entries].map(([id, entry]) => [
638
+ id,
639
+ id === TARGET.environmentId
640
+ ? entry
641
+ : {
642
+ ...entry,
643
+ enabled: permission !== "destination-disabled",
644
+ ...(permission === "destination-unsupported"
645
+ ? { unsupportedReason: "Protocol version mismatch" }
646
+ : {}),
647
+ },
648
+ ]),
649
),
798
- );
799
- const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
650
+ );
651
+ yield* SubscriptionRef.set(localSupervisor.session, Option.none());
652
+ }
653
+ const ref = {
654
projectId: ProjectId.make("project-1"),
655
repository: "private/repo",
656
number: 7,
803
- action: "merge",
657
+ };
658
+ const request = Effect.gen(function* () {
659
+ const route = createPullRequestRouter();
660
+ if (permission !== "read-only")
661
+ yield* route(WS_METHODS.pullRequestsSummary, ref).pipe(Effect.flip);
662
+ yield* route(WS_METHODS.pullRequestsRunAction, { ...ref, action: "merge" });
663
}).pipe(
664
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
665
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
807
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
666
Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
667
);
810
- yield* stored === "unavailable"
811
- ? route
812
- : route.pipe(
813
- Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, {
814
- get: () => read,
815
- put: () => Effect.die("unused"),
816
- remove: () => Effect.die("unused"),
668
+ yield* permission === "default"
669
+ ? request
670
+ : request.pipe(
671
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
672
+ Effect.provideService(PullRequestRoutingPermissions, {
673
+ ...trustedRouting,
674
+ get: (entry) =>
675
+ Effect.succeed(
676
+ permission === "read-only"
677
+ ? "read"
678
+ : permission === "destination-disabled" ||
679
+ permission === "destination-unsupported"
680
+ ? "read-write"
681
+ : (entry.target.environmentId === TARGET.environmentId) ===
682
+ (permission === "origin-off")
683
+ ? "off"
684
+ : "read-write",
685
+ ),
686
}),
687
);
688
expect(calls).toEqual(
820
- stored === "matching"
821
- ? ["source-probe", "alternate-probe", "alternate-write"]
822
- : ["source-write"],
689
+ permission === "read-only" ? ["source-write"] : ["source-read", "source-write"],
690
);
691
}),
692
+);
693
+
694
+it.effect.each(
695
+ (["origin", "destination"] as const).flatMap((side) =>
696
+ (["matching", "changed", "missing", "unavailable", "failed"] as const).map((stored) => ({
697
+ side,
698
+ stored,
699
+ })),
700
),
701
+)("checks the current $side SSH profile before routing with $stored storage", ({ side, stored }) =>
702
+ Effect.gen(function* () {
703
+ const calls: string[] = [];
704
+ const identity = {
705
+ host: "github.com",
706
+ provider: "github",
707
+ viewer: "maria",
708
+ accountId: "123",
709
+ };
710
+ const client = {
711
+ [WS_METHODS.pullRequestsRouting]: () =>
712
+ Effect.sync(() => {
713
+ calls.push("source-probe");
714
+ return identity;
715
+ }),
716
+ [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId?: string }) =>
717
+ Effect.gen(function* () {
718
+ if (input.expectedAccountId !== undefined) {
719
+ return yield* new PullRequestOperationError({
720
+ operation: "routeIdentity",
721
+ detail: "Source guard refused.",
722
+ });
723
+ }
724
+ calls.push("source-write");
725
+ }),
726
+ [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
727
+ } as unknown as WsRpcProtocolClient;
728
+ const alternate = {
729
+ [WS_METHODS.pullRequestsRoutingIdentity]: () =>
730
+ Effect.sync(() => {
731
+ calls.push("alternate-probe");
732
+ return identity;
733
+ }),
734
+ [WS_METHODS.pullRequestsRunAction]: () =>
735
+ Effect.sync(() => {
736
+ calls.push("alternate-write");
737
+ }),
738
+ [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
739
+ } as unknown as WsRpcProtocolClient;
740
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(client, alternate);
741
+ const environmentId =
742
+ side === "origin" ? TARGET.environmentId : EnvironmentId.make("local-environment");
743
+ const profile = new SshConnectionProfile({
744
+ connectionId: "ssh-1",
745
+ environmentId,
746
+ label: "SSH",
747
+ target: { alias: "work", hostname: "work.example.test", username: "maria", port: 22 },
748
+ });
749
+ yield* SubscriptionRef.update(environmentRegistry.entries, (entries) =>
750
+ new Map(entries).set(environmentId, {
751
+ target: new SshConnectionTarget({
752
+ environmentId,
753
+ connectionId: profile.connectionId,
754
+ label: "SSH",
755
+ }),
756
+ profile: Option.some(profile),
757
+ enabled: true,
758
+ }),
759
+ );
760
+ const read = Effect.suspend(() =>
761
+ stored === "failed"
762
+ ? Effect.fail(
763
+ new ConnectionTransientError({
764
+ reason: "remote-unavailable",
765
+ detail: "Profile storage unavailable.",
766
+ }),
767
+ )
768
+ : Effect.succeed(
769
+ stored === "missing"
770
+ ? Option.none()
771
+ : Option.some(
772
+ stored === "changed"
773
+ ? new SshConnectionProfile({
774
+ ...profile,
775
+ target: { ...profile.target, hostname: "replacement.example.test" },
776
+ })
777
+ : profile,
778
+ ),
779
+ ),
780
+ );
781
+ const route = createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
782
+ projectId: ProjectId.make("project-1"),
783
+ repository: "private/repo",
784
+ number: 7,
785
+ action: "merge",
786
+ }).pipe(
787
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
788
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
789
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
790
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
791
+ );
792
+ yield* stored === "unavailable"
793
+ ? route
794
+ : route.pipe(
795
+ Effect.provideService(ConnectionProfileStore.ConnectionProfileStore, {
796
+ get: () => read,
797
+ put: () => Effect.die("unused"),
798
+ remove: () => Effect.die("unused"),
799
+ }),
800
+ );
801
+ expect(calls).toEqual(
802
+ stored === "matching"
803
+ ? ["source-probe", "alternate-probe", "alternate-write"]
804
+ : ["source-write"],
805
+ );
806
+ }),
807
);
808
809
it.effect.each([undefined, true, false])(
810
"keeps source workspace metadata and reports draft %s when an alternate answers a detail read",
811
(isDraft) =>
831
- Effect.scoped(
832
- Effect.gen(function* () {
833
- const noted = yield* Deferred.make<unknown>();
834
- const clientFor = (local: boolean) =>
835
- ({
836
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
837
- Effect.succeed({
838
- host: "github.com",
839
- provider: "github",
840
- viewer: "maria-rcks",
841
- accountId: "123",
842
- projectTitle: local ? "local project" : "source project",
843
- workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
844
- }),
845
- [WS_METHODS.pullRequestsDetail]: () =>
846
- local
847
- ? Effect.succeed({
848
- projectId: "local-project",
849
- projectTitle: "local project",
850
- workspaceRoot: "/Users/local/repo",
851
- title: "github title",
852
- state: "closed",
853
- ...(isDraft === undefined ? {} : { isDraft }),
854
- updatedAt: "2026-10-10T01:52:36Z",
855
- })
856
- : Effect.never,
857
- [WS_METHODS.pullRequestsReportState]: (input: unknown) =>
858
- Deferred.succeed(noted, input).pipe(Effect.asVoid),
859
- }) as unknown as WsRpcProtocolClient;
860
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
861
- clientFor(false),
862
- clientFor(true),
863
- );
864
- const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
865
- projectId: ProjectId.make("project-1"),
866
- repository: "acme/web",
867
- number: 7,
868
- }).pipe(
869
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
870
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
871
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
872
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
873
- );
874
- expect(result).toEqual({
875
- projectId: "project-1",
876
- projectTitle: "source project",
877
- workspaceRoot: "/srv/source/repo",
878
- title: "github title",
879
- state: "closed",
880
- ...(isDraft === undefined ? {} : { isDraft }),
881
- updatedAt: "2026-10-10T01:52:36Z",
882
- });
883
- expect(yield* Deferred.await(noted)).toEqual({
884
- reference: { projectId: "project-1", repository: "acme/web", number: 7 },
885
- state: "closed",
886
- ...(isDraft === undefined ? {} : { isDraft }),
887
- });
888
- }),
889
- ),
812
+ Effect.gen(function* () {
813
+ const noted = yield* Deferred.make<unknown>();
814
+ const clientFor = (local: boolean) =>
815
+ ({
816
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
817
+ Effect.succeed({
818
+ host: "github.com",
819
+ provider: "github",
820
+ viewer: "maria-rcks",
821
+ accountId: "123",
822
+ projectTitle: local ? "local project" : "source project",
823
+ workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
824
+ }),
825
+ [WS_METHODS.pullRequestsDetail]: () =>
826
+ local
827
+ ? Effect.succeed({
828
+ projectId: "local-project",
829
+ projectTitle: "local project",
830
+ workspaceRoot: "/Users/local/repo",
831
+ title: "github title",
832
+ state: "closed",
833
+ ...(isDraft === undefined ? {} : { isDraft }),
834
+ updatedAt: "2026-10-10T01:52:36Z",
835
+ })
836
+ : Effect.never,
837
+ [WS_METHODS.pullRequestsReportState]: (input: unknown) =>
838
+ Deferred.succeed(noted, input).pipe(Effect.asVoid),
839
+ }) as unknown as WsRpcProtocolClient;
840
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
841
+ clientFor(false),
842
+ clientFor(true),
843
+ );
844
+ const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
845
+ projectId: ProjectId.make("project-1"),
846
+ repository: "acme/web",
847
+ number: 7,
848
+ }).pipe(
849
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
850
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
851
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
852
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
853
+ );
854
+ expect(result).toEqual({
855
+ projectId: "project-1",
856
+ projectTitle: "source project",
857
+ workspaceRoot: "/srv/source/repo",
858
+ title: "github title",
859
+ state: "closed",
860
+ ...(isDraft === undefined ? {} : { isDraft }),
861
+ updatedAt: "2026-10-10T01:52:36Z",
862
+ });
863
+ expect(yield* Deferred.await(noted)).toEqual({
864
+ reference: { projectId: "project-1", repository: "acme/web", number: 7 },
865
+ state: "closed",
866
+ ...(isDraft === undefined ? {} : { isDraft }),
867
+ });
868
+ }),
869
);
870
871
it.effect(
872
"refreshes identity before writes and invalidates prior readers across router instances",
873
() =>
895
- Effect.scoped(
896
- Effect.gen(function* () {
897
- let originAccountId = "123";
898
- const mutations: { environment: string; expectedAccountId: string }[] = [];
899
- const invalidations: { environment: string; input: unknown }[] = [];
900
- const identities: string[] = [];
901
- const clientFor = (local: boolean) => {
902
- const environment = local ? "local" : "origin";
903
- return {
904
- [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
905
- Effect.sync(() => {
906
- identities.push(environment);
907
- return {
908
- host: "github.com",
909
- provider: "github",
910
- viewer: "maria-rcks",
911
- accountId: local ? "123" : originAccountId,
912
- };
913
- }),
914
- [WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never),
915
- [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) =>
916
- Effect.sync(() => {
917
- mutations.push({ environment, expectedAccountId: input.expectedAccountId });
918
- }),
919
- [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
920
- Effect.sync(() => {
921
- invalidations.push({ environment, input });
922
- }),
923
- } as unknown as WsRpcProtocolClient;
924
- };
925
- const { environmentRegistry, supervisor } = yield* makeTestRuntime(
926
- clientFor(false),
927
- clientFor(true),
874
+ Effect.gen(function* () {
875
+ let originAccountId = "123";
876
+ const mutations: { environment: string; expectedAccountId: string }[] = [];
877
+ const invalidations: { environment: string; input: unknown }[] = [];
878
+ const identities: string[] = [];
879
+ const clientFor = (local: boolean) => {
880
+ const environment = local ? "local" : "origin";
881
+ return {
882
+ [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
883
+ Effect.sync(() => {
884
+ identities.push(environment);
885
+ return {
886
+ host: "github.com",
887
+ provider: "github",
888
+ viewer: "maria-rcks",
889
+ accountId: local ? "123" : originAccountId,
890
+ };
891
+ }),
892
+ [WS_METHODS.pullRequestsSummary]: () => (local ? Effect.succeed(null) : Effect.never),
893
+ [WS_METHODS.pullRequestsRunAction]: (input: { expectedAccountId: string }) =>
894
+ Effect.sync(() => {
895
+ mutations.push({ environment, expectedAccountId: input.expectedAccountId });
896
+ }),
897
+ [WS_METHODS.pullRequestsInvalidate]: (input: unknown) =>
898
+ Effect.sync(() => {
899
+ invalidations.push({ environment, input });
900
+ }),
901
+ } as unknown as WsRpcProtocolClient;
902
+ };
903
+ const { environmentRegistry, supervisor } = yield* makeTestRuntime(
904
+ clientFor(false),
905
+ clientFor(true),
906
+ );
907
+ const reference = {
908
+ projectId: ProjectId.make("project-1"),
909
+ repository: "acme/web",
910
+ number: 7,
911
+ };
912
+ const hostedReference = { ...reference, host: "github.com", allowStale: false };
913
+ const route = createPullRequestRouter();
914
+ yield* Effect.gen(function* () {
915
+ yield* route(WS_METHODS.pullRequestsSummary, reference);
916
+ originAccountId = "456";
917
+ yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" });
918
+
919
+ expect(identities.filter((environment) => environment === "origin")).toHaveLength(2);
920
+ expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]);
921
+ expect(invalidations).toEqual(
922
+ expect.arrayContaining([
923
+ { environment: "origin", input: { reference: expect.objectContaining(reference) } },
924
+ { environment: "origin", input: { reference: hostedReference } },
925
+ { environment: "local", input: { reference: hostedReference } },
926
+ { environment: "origin", input: {} },
927
+ { environment: "local", input: {} },
928
+ ]),
929
);
929
- const reference = {
930
- projectId: ProjectId.make("project-1"),
931
- repository: "acme/web",
932
- number: 7,
933
- };
934
- const hostedReference = { ...reference, host: "github.com", allowStale: false };
935
- const route = createPullRequestRouter();
936
- yield* Effect.gen(function* () {
937
- yield* route(WS_METHODS.pullRequestsSummary, reference);
938
- originAccountId = "456";
939
- yield* route(WS_METHODS.pullRequestsRunAction, { ...reference, action: "merge" });
940
-
941
- expect(identities.filter((environment) => environment === "origin")).toHaveLength(2);
942
- expect(mutations).toEqual([{ environment: "origin", expectedAccountId: "456" }]);
943
- expect(invalidations).toEqual(
944
- expect.arrayContaining([
945
- { environment: "origin", input: { reference: expect.objectContaining(reference) } },
946
- { environment: "origin", input: { reference: hostedReference } },
947
- { environment: "local", input: { reference: hostedReference } },
948
- { environment: "origin", input: {} },
949
- { environment: "local", input: {} },
950
- ]),
951
- );
930
953
- invalidations.length = 0;
954
- const refresh = createPullRequestRouter();
955
- yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference });
956
- expect(invalidations).toContainEqual({
957
- environment: "local",
958
- input: { reference: hostedReference },
959
- });
960
-
961
- invalidations.length = 0;
962
- yield* refresh(WS_METHODS.pullRequestsInvalidate, {});
963
- expect(invalidations).toContainEqual({ environment: "local", input: {} });
964
- }).pipe(
965
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
966
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
967
- Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
968
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
969
- );
970
- }),
971
- ),
931
+ invalidations.length = 0;
932
+ const refresh = createPullRequestRouter();
933
+ yield* refresh(WS_METHODS.pullRequestsInvalidate, { reference });
934
+ expect(invalidations).toContainEqual({
935
+ environment: "local",
936
+ input: { reference: hostedReference },
937
+ });
938
+
939
+ invalidations.length = 0;
940
+ yield* refresh(WS_METHODS.pullRequestsInvalidate, {});
941
+ expect(invalidations).toContainEqual({ environment: "local", input: {} });
942
+ }).pipe(
943
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
944
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
945
+ Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
946
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
947
+ );
948
+ }),
949
);
950
951
it.effect("keeps concurrent diff file reads on different hosts separate", () =>
975
- Effect.scoped(
952
+ Effect.gen(function* () {
953
+ const release = yield* Latch.make();
954
+ const started = yield* Latch.make();
955
+ const calls: string[] = [];
956
+ const client = {
957
+ [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
958
+ Effect.gen(function* () {
959
+ calls.push(input.host);
960
+ yield* started.open;
961
+ yield* release.await;
962
+ return { oldContents: "", newContents: input.host };
963
+ }),
964
+ } as unknown as WsRpcProtocolClient;
965
+ const { atoms, registry } = yield* makeTestRuntime(client);
966
+ const input = {
967
+ projectId: ProjectId.make("project-1"),
968
+ repository: "acme/web",
969
+ number: 1,
970
+ changeType: "change",
971
+ oldPath: "src/app.ts",
972
+ newPath: "src/app.ts",
973
+ } as const;
974
+ const first = atoms.diffFileContents.run(registry, {
975
+ environmentId: TARGET.environmentId,
976
+ input: { ...input, host: "github.com" },
977
+ });
978
+ yield* started.await;
979
+ const second = atoms.diffFileContents.run(registry, {
980
+ environmentId: TARGET.environmentId,
981
+ input: { ...input, host: "github.example.com" },
982
+ });
983
+ yield* release.open;
984
+
985
+ const results = yield* Effect.promise(() => Promise.all([first, second]));
986
+ expect(results).toMatchObject([
987
+ { _tag: "Success", value: { newContents: "github.com" } },
988
+ { _tag: "Success", value: { newContents: "github.example.com" } },
989
+ ]);
990
+ expect(calls).toEqual(["github.com", "github.example.com"]);
991
+ }),
992
+);
993
+
994
+it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)(
995
+ "rejects an unsafe quick merge with %s and keeps later actions running",
996
+ (reason) =>
997
Effect.gen(function* () {
977
- const release = yield* Latch.make();
978
- const started = yield* Latch.make();
998
const calls: string[] = [];
999
const client = {
981
- [WS_METHODS.pullRequestsDiffFileContents]: (input: { readonly host: string }) =>
982
- Effect.gen(function* () {
983
- calls.push(input.host);
984
- yield* started.open;
985
- yield* release.await;
986
- return { oldContents: "", newContents: input.host };
1000
+ [WS_METHODS.pullRequestsDetail]: () =>
1001
+ Effect.succeed({
1002
+ state: reason === "closed" ? "closed" : "open",
1003
+ isDraft: reason === "draft",
1004
+ capabilities: { actions: ["merge"], stackActions: true },
1005
+ viewerPermissions: { actions: reason === "permission" ? [] : ["merge"] },
1006
}),
1007
+ [WS_METHODS.pullRequestsStack]: () => Effect.succeed(reason === "stack" ? {} : null),
1008
+ [WS_METHODS.pullRequestsRunAction]: (input: { action: string }) =>
1009
+ Effect.sync(() => calls.push(input.action)),
1010
} as unknown as WsRpcProtocolClient;
1011
const { atoms, registry } = yield* makeTestRuntime(client);
990
- const input = {
991
- projectId: ProjectId.make("project-1"),
992
- repository: "acme/web",
993
- number: 1,
994
- changeType: "change",
995
- oldPath: "src/app.ts",
996
- newPath: "src/app.ts",
997
- } as const;
998
- const first = atoms.diffFileContents.run(registry, {
1012
+ const target = {
1013
environmentId: TARGET.environmentId,
1000
- input: { ...input, host: "github.com" },
1014
+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1015
+ };
1016
+ const merge = atoms.runAction.run(registry, {
1017
+ ...target,
1018
+ input: {
1019
+ ...target.input,
1020
+ action: "merge",
1021
+ resolveMergeMethod: () => {
1022
+ if (reason === "method") throw new Error("No merge method is available.");
1023
+ return "squash";
1024
+ },
1025
+ },
1026
});
1002
- yield* started.await;
1003
- const second = atoms.diffFileContents.run(registry, {
1004
- environmentId: TARGET.environmentId,
1005
- input: { ...input, host: "github.example.com" },
1027
+ const close = atoms.runAction.run(registry, {
1028
+ ...target,
1029
+ input: { ...target.input, action: "close" },
1030
});
1007
- yield* release.open;
1008
-
1009
- const results = yield* Effect.promise(() => Promise.all([first, second]));
1010
- expect(results).toMatchObject([
1011
- { _tag: "Success", value: { newContents: "github.com" } },
1012
- { _tag: "Success", value: { newContents: "github.example.com" } },
1013
- ]);
1014
- expect(calls).toEqual(["github.com", "github.example.com"]);
1031
+ const results = yield* Effect.promise(() => Promise.all([merge, close]));
1032
+ expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]);
1033
+ expect(calls).toEqual(["close"]);
1034
}),
1016
- ),
1017
-);
1018
-
1019
-it.effect.each(["closed", "draft", "permission", "stack", "method"] as const)(
1020
- "rejects an unsafe quick merge with %s and keeps later actions running",
1021
- (reason) =>
1022
- Effect.scoped(
1023
- Effect.gen(function* () {
1024
- const calls: string[] = [];
1025
- const client = {
1026
- [WS_METHODS.pullRequestsDetail]: () =>
1027
- Effect.succeed({
1028
- state: reason === "closed" ? "closed" : "open",
1029
- isDraft: reason === "draft",
1030
- capabilities: { actions: ["merge"], stackActions: true },
1031
- viewerPermissions: { actions: reason === "permission" ? [] : ["merge"] },
1032
- }),
1033
- [WS_METHODS.pullRequestsStack]: () => Effect.succeed(reason === "stack" ? {} : null),
1034
- [WS_METHODS.pullRequestsRunAction]: (input: { action: string }) =>
1035
- Effect.sync(() => calls.push(input.action)),
1036
- } as unknown as WsRpcProtocolClient;
1037
- const { atoms, registry } = yield* makeTestRuntime(client);
1038
- const target = {
1039
- environmentId: TARGET.environmentId,
1040
- input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1041
- };
1042
- const merge = atoms.runAction.run(registry, {
1043
- ...target,
1044
- input: {
1045
- ...target.input,
1046
- action: "merge",
1047
- resolveMergeMethod: () => {
1048
- if (reason === "method") throw new Error("No merge method is available.");
1049
- return "squash";
1050
- },
1051
- },
1052
- });
1053
- const close = atoms.runAction.run(registry, {
1054
- ...target,
1055
- input: { ...target.input, action: "close" },
1056
- });
1057
- const results = yield* Effect.promise(() => Promise.all([merge, close]));
1058
- expect(results.map((result) => result._tag)).toEqual(["Failure", "Success"]);
1059
- expect(calls).toEqual(["close"]);
1060
- }),
1061
- ),
1035
);
1036
1037
it.effect("keeps a close batch ordered and continues after a refused close", () =>
1065
- Effect.scoped(
1066
- Effect.gen(function* () {
1067
- const calls: number[] = [];
1068
- const started = yield* Deferred.make<void>();
1069
- const release = yield* Deferred.make<void>();
1070
- const client = {
1071
- [WS_METHODS.pullRequestsRunAction]: (input: { number: number; action: string }) =>
1072
- Effect.gen(function* () {
1073
- expect(input.action).toBe("close");
1074
- calls.push(input.number);
1075
- if (input.number === 6) {
1076
- yield* Deferred.succeed(started, undefined);
1077
- yield* Deferred.await(release);
1078
- }
1079
- if (input.number === 5)
1080
- return yield* new PullRequestOperationError({
1081
- operation: "runAction",
1082
- detail: "You cannot close this pull request.",
1083
- });
1084
- }),
1085
- } as unknown as WsRpcProtocolClient;
1086
- const { atoms, registry } = yield* makeTestRuntime(client);
1087
- const batch = [6, 5, 4].map((number) =>
1088
- atoms.runAction.run(registry, {
1089
- environmentId: TARGET.environmentId,
1090
- input: {
1091
- projectId: ProjectId.make("project-1"),
1092
- repository: "acme/web",
1093
- number,
1094
- action: "close",
1095
- },
1038
+ Effect.gen(function* () {
1039
+ const calls: number[] = [];
1040
+ const started = yield* Deferred.make<void>();
1041
+ const release = yield* Deferred.make<void>();
1042
+ const client = {
1043
+ [WS_METHODS.pullRequestsRunAction]: (input: { number: number; action: string }) =>
1044
+ Effect.gen(function* () {
1045
+ expect(input.action).toBe("close");
1046
+ calls.push(input.number);
1047
+ if (input.number === 6) {
1048
+ yield* Deferred.succeed(started, undefined);
1049
+ yield* Deferred.await(release);
1050
+ }
1051
+ if (input.number === 5)
1052
+ return yield* new PullRequestOperationError({
1053
+ operation: "runAction",
1054
+ detail: "You cannot close this pull request.",
1055
+ });
1056
}),
1097
- );
1098
- yield* Deferred.await(started);
1099
- expect(calls).toEqual([6]);
1100
- yield* Deferred.succeed(release, undefined);
1101
- const results = yield* Effect.promise(() => Promise.all(batch));
1102
- expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]);
1103
- expect(calls).toEqual([6, 5, 4]);
1104
- }),
1105
- ),
1057
+ } as unknown as WsRpcProtocolClient;
1058
+ const { atoms, registry } = yield* makeTestRuntime(client);
1059
+ const batch = [6, 5, 4].map((number) =>
1060
+ atoms.runAction.run(registry, {
1061
+ environmentId: TARGET.environmentId,
1062
+ input: {
1063
+ projectId: ProjectId.make("project-1"),
1064
+ repository: "acme/web",
1065
+ number,
1066
+ action: "close",
1067
+ },
1068
+ }),
1069
+ );
1070
+ yield* Deferred.await(started);
1071
+ expect(calls).toEqual([6]);
1072
+ yield* Deferred.succeed(release, undefined);
1073
+ const results = yield* Effect.promise(() => Promise.all(batch));
1074
+ expect(results.map((result) => result._tag)).toEqual(["Success", "Failure", "Success"]);
1075
+ expect(calls).toEqual([6, 5, 4]);
1076
+ }),
1077
);
1078
1079
const actionReference = {
@@ -1133,1042 +1104,1006 @@ function actionReplyClient(overrides: Record<string, unknown> = {}) {
1104
}
1105
1106
it.effect("shows an action's reply in loaded readers and moves list rows without reads", () =>
1136
- Effect.scoped(
1137
- Effect.gen(function* () {
1138
- const reads: string[] = [];
1139
- const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 };
1140
- const read = (name: string) => () =>
1107
+ Effect.gen(function* () {
1108
+ const reads: string[] = [];
1109
+ const open = { ...actionReference, state: "open", isDraft: true, observedAt: 100 };
1110
+ const read = (name: string) => () =>
1111
+ Effect.sync(() => {
1112
+ reads.push(name);
1113
+ return open;
1114
+ });
1115
+ const replies: unknown[] = [];
1116
+ const listAnswers: unknown[] = [];
1117
+ const client = actionReplyClient({
1118
+ [WS_METHODS.pullRequestsDetail]: read("detail"),
1119
+ [WS_METHODS.pullRequestsPreview]: read("preview"),
1120
+ [WS_METHODS.pullRequestsSummary]: read("summary"),
1121
+ [WS_METHODS.pullRequestsList]: (input: { readonly state: string }) =>
1122
Effect.sync(() => {
1142
- reads.push(name);
1143
- return open;
1144
- });
1145
- const replies: unknown[] = [];
1146
- const listAnswers: unknown[] = [];
1147
- const client = actionReplyClient({
1148
- [WS_METHODS.pullRequestsDetail]: read("detail"),
1149
- [WS_METHODS.pullRequestsPreview]: read("preview"),
1150
- [WS_METHODS.pullRequestsSummary]: read("summary"),
1151
- [WS_METHODS.pullRequestsList]: (input: { readonly state: string }) =>
1152
- Effect.sync(() => {
1153
- reads.push(`list:${input.state}`);
1154
- return {
1155
- entries: input.state === "merged" ? [] : [open],
1156
- viewers: {},
1157
- providers: [],
1158
- errors: [],
1159
- truncated: false,
1160
- nextCursors: {},
1161
- };
1162
- }),
1123
+ reads.push(`list:${input.state}`);
1124
+ return {
1125
+ entries: input.state === "merged" ? [] : [open],
1126
+ viewers: {},
1127
+ providers: [],
1128
+ errors: [],
1129
+ truncated: false,
1130
+ nextCursors: {},
1131
+ };
1132
+ }),
1133
+ });
1134
+ const saved = new Map<string, string>();
1135
+ const { atoms, registry, runtime } = yield* makeTestRuntime(
1136
+ client,
1137
+ undefined,
1138
+ false,
1139
+ {
1140
+ actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })),
1141
+ list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)),
1142
+ },
1143
+ {
1144
+ load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
1145
+ save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
1146
+ },
1147
+ );
1148
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1149
+ const list = (input: PullRequestListInput) =>
1150
+ atoms.list({ environmentId: target.environmentId, input });
1151
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1152
+ atoms.detail(target),
1153
+ atoms.preview(target),
1154
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1155
+ ];
1156
+ const all = list({ state: "all" });
1157
+ const openDrafts = list({ state: "open", filters: { draft: "only" } });
1158
+ const merged = list({ state: "merged" });
1159
+ for (const atom of [...readers, all, openDrafts, merged]) {
1160
+ registry.mount(atom);
1161
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1162
+ }
1163
+ reads.length = 0;
1164
+
1165
+ const answer = yield* Effect.promise(() =>
1166
+ atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
1167
+ );
1168
+
1169
+ expect(answer).toMatchObject({ _tag: "Success", value: actionReply });
1170
+ for (const atom of readers) {
1171
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1172
+ state: "merged",
1173
+ isDraft: false,
1174
+ title: "Ship it",
1175
});
1164
- const saved = new Map<string, string>();
1165
- const { atoms, registry, runtime } = yield* makeTestRuntime(
1166
- client,
1167
- undefined,
1168
- false,
1169
- {
1170
- actionReply: (target, reply) => Effect.sync(() => replies.push({ target, reply })),
1171
- list: (_target, value) => Effect.sync(() => listAnswers.push(value.entries)),
1172
- },
1173
- {
1174
- load: (_environmentId, key) => Effect.sync(() => Option.fromUndefinedOr(saved.get(key))),
1175
- save: (_environmentId, key, payload) => Effect.sync(() => void saved.set(key, payload)),
1176
- },
1177
- );
1178
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1179
- const list = (input: PullRequestListInput) =>
1180
- atoms.list({ environmentId: target.environmentId, input });
1181
- const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1182
- atoms.detail(target),
1183
- atoms.preview(target),
1184
- createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1185
- ];
1186
- const all = list({ state: "all" });
1187
- const openDrafts = list({ state: "open", filters: { draft: "only" } });
1188
- const merged = list({ state: "merged" });
1189
- for (const atom of [...readers, all, openDrafts, merged]) {
1190
- registry.mount(atom);
1191
- yield* Effect.promise(() => executeAtomQuery(registry, atom));
1192
- }
1193
- reads.length = 0;
1194
-
1195
- const answer = yield* Effect.promise(() =>
1196
- atoms.runAction.run(registry, { ...target, input: { ...target.input, action: "merge" } }),
1197
- );
1198
-
1199
- expect(answer).toMatchObject({ _tag: "Success", value: actionReply });
1200
- for (const atom of readers) {
1201
- expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1202
- state: "merged",
1203
- isDraft: false,
1204
- title: "Ship it",
1205
- });
1206
- }
1207
- expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([
1208
- // The row keeps its own read time: the reply does not carry its checks or labels.
1209
- { state: "merged", isDraft: false, observedAt: 100 },
1210
- ]);
1211
- expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]);
1212
- expect(replies).toEqual([{ target, reply: actionReply }]);
1213
- // A cold start paints the saved copy, so the patch must replace the saved answer.
1214
- const summaryKey = queryPersistenceKey(
1215
- "environment-data:pull-requests:linked-summary",
1216
- actionReference,
1217
- );
1218
- expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" });
1219
- // Snapshot writers see the patched rows the way they see an answer.
1220
- expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]);
1221
- // Only a read can place a row the listing did not hold.
1222
- yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true });
1223
- expect(reads).toEqual(["list:merged"]);
1224
- }),
1225
- ),
1176
+ }
1177
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(all))).entries).toMatchObject([
1178
+ // The row keeps its own read time: the reply does not carry its checks or labels.
1179
+ { state: "merged", isDraft: false, observedAt: 100 },
1180
+ ]);
1181
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(openDrafts))).entries).toEqual([]);
1182
+ expect(replies).toEqual([{ target, reply: actionReply }]);
1183
+ // A cold start paints the saved copy, so the patch must replace the saved answer.
1184
+ const summaryKey = queryPersistenceKey(
1185
+ "environment-data:pull-requests:linked-summary",
1186
+ actionReference,
1187
+ );
1188
+ expect(JSON.parse(saved.get(summaryKey) ?? "null")).toMatchObject({ state: "merged" });
1189
+ // Snapshot writers see the patched rows the way they see an answer.
1190
+ expect(listAnswers).toContainEqual([expect.objectContaining({ state: "merged" })]);
1191
+ // Only a read can place a row the listing did not hold.
1192
+ yield* AtomRegistry.getResult(registry, merged, { suspendOnWaiting: true });
1193
+ expect(reads).toEqual(["list:merged"]);
1194
+ }),
1195
);
1196
1197
it.effect("keeps an action's reply when a refresh started before the action answers late", () =>
1229
- Effect.scoped(
1230
- Effect.gen(function* () {
1231
- let state: "open" | "merged" = "open";
1232
- let reads = 0;
1233
- const started = yield* Deferred.make<void>();
1234
- const release = yield* Deferred.make<void>();
1235
- const settled = yield* Deferred.make<void>();
1236
- const client = actionReplyClient({
1237
- [WS_METHODS.pullRequestsDetail]: () =>
1238
- Effect.gen(function* () {
1239
- reads++;
1240
- const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 };
1241
- if (reads === 2) {
1242
- yield* Deferred.succeed(started, undefined);
1243
- yield* Deferred.await(release).pipe(
1244
- Effect.onExit(() => Deferred.succeed(settled, undefined)),
1245
- );
1246
- }
1247
- return snapshot;
1248
- }),
1249
- [WS_METHODS.pullRequestsRunAction]: () =>
1250
- Effect.sync(() => {
1251
- state = "merged";
1252
- return actionReply;
1253
- }),
1254
- });
1255
- const { atoms, registry } = yield* makeTestRuntime(client);
1256
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1257
- const detail = atoms.detail(target);
1258
- registry.mount(detail);
1259
- yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1260
- registry.refresh(detail);
1261
- yield* Deferred.await(started);
1262
-
1263
- yield* Effect.promise(() =>
1264
- atoms.runAction.run(registry, {
1265
- ...target,
1266
- input: { ...actionReference, action: "merge" },
1198
+ Effect.gen(function* () {
1199
+ let state: "open" | "merged" = "open";
1200
+ let reads = 0;
1201
+ const started = yield* Deferred.make<void>();
1202
+ const release = yield* Deferred.make<void>();
1203
+ const settled = yield* Deferred.make<void>();
1204
+ const client = actionReplyClient({
1205
+ [WS_METHODS.pullRequestsDetail]: () =>
1206
+ Effect.gen(function* () {
1207
+ reads++;
1208
+ const snapshot = { ...actionReference, state, isDraft: false, observedAt: 100 };
1209
+ if (reads === 2) {
1210
+ yield* Deferred.succeed(started, undefined);
1211
+ yield* Deferred.await(release).pipe(
1212
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
1213
+ );
1214
+ }
1215
+ return snapshot;
1216
}),
1268
- );
1269
- yield* Deferred.succeed(release, undefined);
1270
- yield* Deferred.await(settled);
1271
-
1272
- expect(
1273
- (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state,
1274
- ).toBe("merged");
1275
- expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged");
1276
- }),
1277
- ),
1217
+ [WS_METHODS.pullRequestsRunAction]: () =>
1218
+ Effect.sync(() => {
1219
+ state = "merged";
1220
+ return actionReply;
1221
+ }),
1222
+ });
1223
+ const { atoms, registry } = yield* makeTestRuntime(client);
1224
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1225
+ const detail = atoms.detail(target);
1226
+ registry.mount(detail);
1227
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1228
+ registry.refresh(detail);
1229
+ yield* Deferred.await(started);
1230
+
1231
+ yield* Effect.promise(() =>
1232
+ atoms.runAction.run(registry, {
1233
+ ...target,
1234
+ input: { ...actionReference, action: "merge" },
1235
+ }),
1236
+ );
1237
+ yield* Deferred.succeed(release, undefined);
1238
+ yield* Deferred.await(settled);
1239
+
1240
+ expect(
1241
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).state,
1242
+ ).toBe("merged");
1243
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("merged");
1244
+ }),
1245
);
1246
1247
it.effect("keeps a list read the server's refresh started before the action replied", () =>
1281
- Effect.scoped(
1282
- Effect.gen(function* () {
1283
- const refreshEvents = yield* PubSub.unbounded<number>();
1284
- let state: "open" | "merged" = "open";
1285
- let reads = 0;
1286
- const actionInputs: unknown[] = [];
1287
- const listWaiting = Latch.makeUnsafe();
1288
- const release = yield* Deferred.make<void>();
1289
- const client = actionReplyClient({
1290
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1291
- [WS_METHODS.pullRequestsList]: () =>
1292
- Effect.gen(function* () {
1293
- reads++;
1294
- const entries = [
1295
- { ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt },
1296
- ];
1297
- if (reads === 2) yield* Deferred.await(release);
1298
- return {
1299
- entries,
1300
- viewers: {},
1301
- providers: [],
1302
- errors: [],
1303
- truncated: false,
1304
- nextCursors: {},
1305
- };
1306
- }),
1307
- [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
1308
- Effect.gen(function* () {
1309
- actionInputs.push(input);
1310
- state = "merged";
1311
- // The server announces its refresh before it replies.
1312
- yield* PubSub.publish(refreshEvents, 1);
1313
- yield* listWaiting.await;
1314
- return actionReply;
1315
- }),
1316
- });
1317
- const { atoms, registry } = yield* makeTestRuntime(client);
1318
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1319
- const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1320
- const unmount = registry.mount(list);
1321
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1322
- yield* Effect.promise(() => executeAtomQuery(registry, list));
1323
- const stop = registry.subscribe(list, (result) => {
1324
- if (result.waiting) listWaiting.openUnsafe();
1325
- });
1326
- yield* Effect.addFinalizer(() => Effect.sync(stop));
1327
-
1328
- yield* Effect.promise(() =>
1329
- atoms.runAction.run(registry, {
1330
- ...target,
1331
- input: { ...actionReference, action: "merge" },
1248
+ Effect.gen(function* () {
1249
+ const refreshEvents = yield* PubSub.unbounded<number>();
1250
+ let state: "open" | "merged" = "open";
1251
+ let reads = 0;
1252
+ const actionInputs: unknown[] = [];
1253
+ const listWaiting = Latch.makeUnsafe();
1254
+ const release = yield* Deferred.make<void>();
1255
+ const client = actionReplyClient({
1256
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1257
+ [WS_METHODS.pullRequestsList]: () =>
1258
+ Effect.gen(function* () {
1259
+ reads++;
1260
+ const entries = [
1261
+ { ...actionReference, state, isDraft: false, updatedAt: actionReply.updatedAt },
1262
+ ];
1263
+ if (reads === 2) yield* Deferred.await(release);
1264
+ return {
1265
+ entries,
1266
+ viewers: {},
1267
+ providers: [],
1268
+ errors: [],
1269
+ truncated: false,
1270
+ nextCursors: {},
1271
+ };
1272
}),
1333
- );
1334
- yield* Deferred.succeed(release, undefined);
1335
-
1336
- expect(
1337
- (yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries,
1338
- ).toMatchObject([{ state: "merged" }]);
1339
- expect(reads).toBe(2);
1340
- expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]);
1341
- }),
1342
- ),
1273
+ [WS_METHODS.pullRequestsRunAction]: (input: unknown) =>
1274
+ Effect.gen(function* () {
1275
+ actionInputs.push(input);
1276
+ state = "merged";
1277
+ // The server announces its refresh before it replies.
1278
+ yield* PubSub.publish(refreshEvents, 1);
1279
+ yield* listWaiting.await;
1280
+ return actionReply;
1281
+ }),
1282
+ });
1283
+ const { atoms, registry } = yield* makeTestRuntime(client);
1284
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1285
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1286
+ const unmount = registry.mount(list);
1287
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1288
+ yield* Effect.promise(() => executeAtomQuery(registry, list));
1289
+ const stop = registry.subscribe(list, (result) => {
1290
+ if (result.waiting) listWaiting.openUnsafe();
1291
+ });
1292
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
1293
+
1294
+ yield* Effect.promise(() =>
1295
+ atoms.runAction.run(registry, {
1296
+ ...target,
1297
+ input: { ...actionReference, action: "merge" },
1298
+ }),
1299
+ );
1300
+ yield* Deferred.succeed(release, undefined);
1301
+
1302
+ expect(
1303
+ (yield* AtomRegistry.getResult(registry, list, { suspendOnWaiting: true })).entries,
1304
+ ).toMatchObject([{ state: "merged" }]);
1305
+ expect(reads).toBe(2);
1306
+ expect(actionInputs).toEqual([expect.objectContaining({ replyWithSummary: true })]);
1307
+ }),
1308
);
1309
1310
it.effect("restarts a list page read sent while the action was in flight", () =>
1346
- Effect.scoped(
1347
- Effect.gen(function* () {
1348
- const refreshEvents = yield* PubSub.unbounded<number>();
1349
- let state: "open" | "closed" = "open";
1350
- let pageReads = 0;
1351
- const actionSent = yield* Deferred.make<void>();
1352
- const pageStarted = yield* Deferred.make<void>();
1353
- const release = yield* Deferred.make<void>();
1354
- const settled = yield* Deferred.make<void>();
1355
- const listResult = (entries: ReadonlyArray<object>) => ({
1356
- entries,
1357
- viewers: {},
1358
- providers: [],
1359
- errors: [],
1360
- truncated: false,
1361
- nextCursors: {},
1362
- });
1363
- const client = actionReplyClient({
1364
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1365
- [WS_METHODS.pullRequestsList]: (input: PullRequestListInput) =>
1366
- Effect.gen(function* () {
1367
- const entries =
1368
- state === "open"
1369
- ? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }]
1370
- : [];
1371
- if (input.cursors !== undefined && ++pageReads === 2) {
1372
- yield* Deferred.succeed(pageStarted, undefined);
1373
- yield* Deferred.await(release).pipe(
1374
- Effect.onExit(() => Deferred.succeed(settled, undefined)),
1375
- );
1376
- }
1377
- return listResult(input.cursors === undefined ? [] : entries);
1378
- }),
1379
- [WS_METHODS.pullRequestsRunAction]: () =>
1380
- Effect.gen(function* () {
1381
- yield* Deferred.succeed(actionSent, undefined);
1382
- yield* Deferred.await(pageStarted);
1383
- state = "closed";
1384
- yield* PubSub.publish(refreshEvents, 1);
1385
- return { ...actionReply, state: "closed" };
1386
- }),
1387
- });
1388
- const { atoms, registry } = yield* makeTestRuntime(client);
1389
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1390
- const listInput = { state: "open" } as const;
1391
- const head = atoms.list({ environmentId: target.environmentId, input: listInput });
1392
- const page = atoms.list({
1393
- environmentId: target.environmentId,
1394
- input: { ...listInput, cursors: { "github.example.com": "page-2" } },
1395
- });
1396
- for (const atom of [head, page]) {
1397
- const unmount = registry.mount(atom);
1398
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1399
- yield* Effect.promise(() => executeAtomQuery(registry, atom));
1400
- }
1401
-
1402
- const action = yield* Effect.promise(() =>
1403
- atoms.runAction.run(registry, {
1404
- ...target,
1405
- input: { ...actionReference, action: "close" },
1311
+ Effect.gen(function* () {
1312
+ const refreshEvents = yield* PubSub.unbounded<number>();
1313
+ let state: "open" | "closed" = "open";
1314
+ let pageReads = 0;
1315
+ const actionSent = yield* Deferred.make<void>();
1316
+ const pageStarted = yield* Deferred.make<void>();
1317
+ const release = yield* Deferred.make<void>();
1318
+ const settled = yield* Deferred.make<void>();
1319
+ const listResult = (entries: ReadonlyArray<object>) => ({
1320
+ entries,
1321
+ viewers: {},
1322
+ providers: [],
1323
+ errors: [],
1324
+ truncated: false,
1325
+ nextCursors: {},
1326
+ });
1327
+ const client = actionReplyClient({
1328
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1329
+ [WS_METHODS.pullRequestsList]: (input: PullRequestListInput) =>
1330
+ Effect.gen(function* () {
1331
+ const entries =
1332
+ state === "open"
1333
+ ? [{ ...actionReference, state, isDraft: false, updatedAt: "2026-10-27T09:00:00Z" }]
1334
+ : [];
1335
+ if (input.cursors !== undefined && ++pageReads === 2) {
1336
+ yield* Deferred.succeed(pageStarted, undefined);
1337
+ yield* Deferred.await(release).pipe(
1338
+ Effect.onExit(() => Deferred.succeed(settled, undefined)),
1339
+ );
1340
+ }
1341
+ return listResult(input.cursors === undefined ? [] : entries);
1342
}),
1407
- ).pipe(Effect.forkScoped);
1408
- yield* Deferred.await(actionSent);
1409
- // Loading more rows re-reads a page while the close is on the wire.
1410
- registry.refresh(page);
1411
- yield* Fiber.join(action);
1412
- yield* Deferred.succeed(release, undefined);
1413
- yield* Deferred.await(settled);
1343
+ [WS_METHODS.pullRequestsRunAction]: () =>
1344
+ Effect.gen(function* () {
1345
+ yield* Deferred.succeed(actionSent, undefined);
1346
+ yield* Deferred.await(pageStarted);
1347
+ state = "closed";
1348
+ yield* PubSub.publish(refreshEvents, 1);
1349
+ return { ...actionReply, state: "closed" };
1350
+ }),
1351
+ });
1352
+ const { atoms, registry } = yield* makeTestRuntime(client);
1353
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1354
+ const listInput = { state: "open" } as const;
1355
+ const head = atoms.list({ environmentId: target.environmentId, input: listInput });
1356
+ const page = atoms.list({
1357
+ environmentId: target.environmentId,
1358
+ input: { ...listInput, cursors: { "github.example.com": "page-2" } },
1359
+ });
1360
+ for (const atom of [head, page]) {
1361
+ const unmount = registry.mount(atom);
1362
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1363
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1364
+ }
1365
1415
- expect(
1416
- (yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries,
1417
- ).toEqual([]);
1418
- }),
1419
- ),
1366
+ const action = yield* Effect.promise(() =>
1367
+ atoms.runAction.run(registry, {
1368
+ ...target,
1369
+ input: { ...actionReference, action: "close" },
1370
+ }),
1371
+ ).pipe(Effect.forkScoped);
1372
+ yield* Deferred.await(actionSent);
1373
+ // Loading more rows re-reads a page while the close is on the wire.
1374
+ registry.refresh(page);
1375
+ yield* Fiber.join(action);
1376
+ yield* Deferred.succeed(release, undefined);
1377
+ yield* Deferred.await(settled);
1378
+
1379
+ expect(
1380
+ (yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true })).entries,
1381
+ ).toEqual([]);
1382
+ }),
1383
);
1384
1385
it.effect("shows a reopen reply at once and re-reads the fields it lacks", () =>
1423
- Effect.scoped(
1424
- Effect.gen(function* () {
1425
- let reads = 0;
1426
- const release = yield* Deferred.make<void>();
1427
- const client = actionReplyClient({
1428
- [WS_METHODS.pullRequestsDetail]: () =>
1429
- Effect.gen(function* () {
1430
- reads++;
1431
- if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1432
- yield* Deferred.await(release);
1433
- return { ...actionReference, state: "open", observedAt: 300 };
1434
- }),
1435
- [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1436
- });
1437
- const { atoms, registry } = yield* makeTestRuntime(client);
1438
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1439
- const detail = atoms.detail(target);
1440
- registry.mount(detail);
1441
- yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1442
-
1443
- yield* Effect.promise(() =>
1444
- atoms.runAction.run(registry, {
1445
- ...target,
1446
- input: { ...actionReference, action: "reopen" },
1386
+ Effect.gen(function* () {
1387
+ let reads = 0;
1388
+ const release = yield* Deferred.make<void>();
1389
+ const client = actionReplyClient({
1390
+ [WS_METHODS.pullRequestsDetail]: () =>
1391
+ Effect.gen(function* () {
1392
+ reads++;
1393
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1394
+ yield* Deferred.await(release);
1395
+ return { ...actionReference, state: "open", observedAt: 300 };
1396
}),
1448
- );
1449
-
1450
- expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1451
- expect(reads).toBe(2);
1452
- yield* Deferred.succeed(release, undefined);
1453
- expect(
1454
- (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1455
- ).toBe(300);
1456
- }),
1457
- ),
1397
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1398
+ });
1399
+ const { atoms, registry } = yield* makeTestRuntime(client);
1400
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1401
+ const detail = atoms.detail(target);
1402
+ registry.mount(detail);
1403
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1404
+
1405
+ yield* Effect.promise(() =>
1406
+ atoms.runAction.run(registry, {
1407
+ ...target,
1408
+ input: { ...actionReference, action: "reopen" },
1409
+ }),
1410
+ );
1411
+
1412
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1413
+ expect(reads).toBe(2);
1414
+ yield* Deferred.succeed(release, undefined);
1415
+ expect(
1416
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1417
+ ).toBe(300);
1418
+ }),
1419
);
1420
1421
it.effect("keeps each reader's read time when a reply leaves its checks as they were", () =>
1461
- Effect.scoped(
1462
- Effect.gen(function* () {
1463
- const shown = {
1464
- ...actionReference,
1465
- state: "open",
1466
- isDraft: true,
1467
- updatedAt: "2026-10-27T09:00:00Z",
1468
- observedAt: 100,
1469
- checks: [{ status: "success" }],
1470
- checksState: "passing",
1471
- };
1472
- const client = actionReplyClient({
1473
- [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1474
- [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown),
1475
- [WS_METHODS.pullRequestsList]: () =>
1476
- Effect.succeed({
1477
- entries: [shown],
1478
- viewers: {},
1479
- providers: [],
1480
- errors: [],
1481
- truncated: false,
1482
- nextCursors: {},
1483
- }),
1484
- [WS_METHODS.pullRequestsRunAction]: () =>
1485
- Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }),
1486
- });
1487
- const answeredAt: Array<number | undefined> = [];
1488
- const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, {
1489
- detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)),
1490
- });
1491
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1492
- const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1493
- atoms.detail(target),
1494
- createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1495
- ];
1496
- const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1497
- for (const atom of [...readers, list]) {
1498
- registry.mount(atom);
1499
- yield* Effect.promise(() => executeAtomQuery(registry, atom));
1500
- }
1501
-
1502
- yield* Effect.promise(() =>
1503
- atoms.runAction.run(registry, {
1504
- ...target,
1505
- input: { ...actionReference, action: "ready" },
1422
+ Effect.gen(function* () {
1423
+ const shown = {
1424
+ ...actionReference,
1425
+ state: "open",
1426
+ isDraft: true,
1427
+ updatedAt: "2026-10-27T09:00:00Z",
1428
+ observedAt: 100,
1429
+ checks: [{ status: "success" }],
1430
+ checksState: "passing",
1431
+ };
1432
+ const client = actionReplyClient({
1433
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1434
+ [WS_METHODS.pullRequestsSummary]: () => Effect.succeed(shown),
1435
+ [WS_METHODS.pullRequestsList]: () =>
1436
+ Effect.succeed({
1437
+ entries: [shown],
1438
+ viewers: {},
1439
+ providers: [],
1440
+ errors: [],
1441
+ truncated: false,
1442
+ nextCursors: {},
1443
}),
1507
- );
1444
+ [WS_METHODS.pullRequestsRunAction]: () =>
1445
+ Effect.succeed({ ...actionReply, state: "open", observedAt: 300 }),
1446
+ });
1447
+ const answeredAt: Array<number | undefined> = [];
1448
+ const { atoms, registry, runtime } = yield* makeTestRuntime(client, undefined, false, {
1449
+ detail: (_target, value) => Effect.sync(() => answeredAt.push(value.observedAt)),
1450
+ });
1451
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1452
+ const readers: ReadonlyArray<Atom.Atom<AsyncResult.AsyncResult<object, unknown>>> = [
1453
+ atoms.detail(target),
1454
+ createLinkedPullRequestSummaryAtomFamily(runtime, atoms.refreshes)(target),
1455
+ ];
1456
+ const list = atoms.list({ environmentId: target.environmentId, input: { state: "all" } });
1457
+ for (const atom of [...readers, list]) {
1458
+ registry.mount(atom);
1459
+ yield* Effect.promise(() => executeAtomQuery(registry, atom));
1460
+ }
1461
+
1462
+ yield* Effect.promise(() =>
1463
+ atoms.runAction.run(registry, {
1464
+ ...target,
1465
+ input: { ...actionReference, action: "ready" },
1466
+ }),
1467
+ );
1468
1509
- // Checks read at 100 must not pass for a read at 300 against a newer checks read.
1510
- for (const atom of readers) {
1511
- expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1512
- isDraft: false,
1513
- observedAt: 100,
1514
- });
1515
- }
1516
- expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
1517
- { isDraft: false, checksState: "passing", observedAt: 100 },
1518
- ]);
1519
- expect(answeredAt).toEqual([100, 100]);
1520
- }),
1521
- ),
1469
+ // Checks read at 100 must not pass for a read at 300 against a newer checks read.
1470
+ for (const atom of readers) {
1471
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(atom)))).toMatchObject({
1472
+ isDraft: false,
1473
+ observedAt: 100,
1474
+ });
1475
+ }
1476
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(list))).entries).toMatchObject([
1477
+ { isDraft: false, checksState: "passing", observedAt: 100 },
1478
+ ]);
1479
+ expect(answeredAt).toEqual([100, 100]);
1480
+ }),
1481
);
1482
1483
it.effect("re-reads an unstamped preview rather than order a reply against it", () =>
1525
- Effect.scoped(
1526
- Effect.gen(function* () {
1527
- let reads = 0;
1528
- const client = actionReplyClient({
1529
- // Previews from servers before action replies carry neither update nor read time.
1530
- [WS_METHODS.pullRequestsPreview]: () =>
1531
- Effect.sync(() => {
1532
- reads++;
1533
- return {
1534
- ...actionReference,
1535
- title: "Reopened elsewhere",
1536
- url: actionReply.url,
1537
- author: null,
1538
- state: "open",
1539
- isDraft: false,
1540
- createdAt: "2026-10-27T08:00:00Z",
1541
- };
1542
- }),
1543
- [WS_METHODS.pullRequestsRunAction]: () =>
1544
- Effect.succeed({ ...actionReply, state: "closed" }),
1545
- });
1546
- const { atoms, registry } = yield* makeTestRuntime(client);
1547
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1548
- const preview = atoms.preview(target);
1549
- registry.mount(preview);
1550
- yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
1551
-
1552
- yield* Effect.promise(() =>
1553
- atoms.runAction.run(registry, {
1554
- ...target,
1555
- input: { ...actionReference, action: "close" },
1484
+ Effect.gen(function* () {
1485
+ let reads = 0;
1486
+ const client = actionReplyClient({
1487
+ // Previews from servers before action replies carry neither update nor read time.
1488
+ [WS_METHODS.pullRequestsPreview]: () =>
1489
+ Effect.sync(() => {
1490
+ reads++;
1491
+ return {
1492
+ ...actionReference,
1493
+ title: "Reopened elsewhere",
1494
+ url: actionReply.url,
1495
+ author: null,
1496
+ state: "open",
1497
+ isDraft: false,
1498
+ createdAt: "2026-10-27T08:00:00Z",
1499
+ };
1500
}),
1557
- );
1558
-
1559
- expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open");
1560
- expect(
1561
- (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state,
1562
- ).toBe("open");
1563
- expect(reads).toBe(2);
1564
- }),
1565
- ),
1501
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "closed" }),
1502
+ });
1503
+ const { atoms, registry } = yield* makeTestRuntime(client);
1504
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1505
+ const preview = atoms.preview(target);
1506
+ registry.mount(preview);
1507
+ yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true });
1508
+
1509
+ yield* Effect.promise(() =>
1510
+ atoms.runAction.run(registry, {
1511
+ ...target,
1512
+ input: { ...actionReference, action: "close" },
1513
+ }),
1514
+ );
1515
+
1516
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(preview))).state).toBe("open");
1517
+ expect(
1518
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).state,
1519
+ ).toBe("open");
1520
+ expect(reads).toBe(2);
1521
+ }),
1522
);
1523
1524
it.effect("leaves a loaded list page alone when the reply concerns none of its rows", () =>
1569
- Effect.scoped(
1570
- Effect.gen(function* () {
1571
- let pageReads = 0;
1572
- const client = actionReplyClient({
1573
- [WS_METHODS.pullRequestsList]: () =>
1574
- Effect.sync(() => {
1575
- pageReads++;
1576
- return {
1577
- entries: [
1578
- {
1579
- ...actionReference,
1580
- number: 2,
1581
- state: "open",
1582
- isDraft: false,
1583
- updatedAt: "2026-10-27T09:00:00Z",
1584
- },
1585
- ],
1586
- viewers: {},
1587
- providers: [],
1588
- errors: [],
1589
- truncated: false,
1590
- nextCursors: {},
1591
- };
1592
- }),
1593
- [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1594
- });
1595
- const { atoms, registry } = yield* makeTestRuntime(client);
1596
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1597
- const page = atoms.list({
1598
- environmentId: target.environmentId,
1599
- input: { state: "open", cursors: { "github.example.com": "page-2" } },
1600
- });
1601
- const unmount = registry.mount(page);
1602
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1603
- yield* Effect.promise(() => executeAtomQuery(registry, page));
1604
-
1605
- yield* Effect.promise(() =>
1606
- atoms.runAction.run(registry, {
1607
- ...target,
1608
- input: { ...actionReference, action: "ready" },
1525
+ Effect.gen(function* () {
1526
+ let pageReads = 0;
1527
+ const client = actionReplyClient({
1528
+ [WS_METHODS.pullRequestsList]: () =>
1529
+ Effect.sync(() => {
1530
+ pageReads++;
1531
+ return {
1532
+ entries: [
1533
+ {
1534
+ ...actionReference,
1535
+ number: 2,
1536
+ state: "open",
1537
+ isDraft: false,
1538
+ updatedAt: "2026-10-27T09:00:00Z",
1539
+ },
1540
+ ],
1541
+ viewers: {},
1542
+ providers: [],
1543
+ errors: [],
1544
+ truncated: false,
1545
+ nextCursors: {},
1546
+ };
1547
}),
1610
- );
1548
+ [WS_METHODS.pullRequestsRunAction]: () => Effect.succeed({ ...actionReply, state: "open" }),
1549
+ });
1550
+ const { atoms, registry } = yield* makeTestRuntime(client);
1551
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1552
+ const page = atoms.list({
1553
+ environmentId: target.environmentId,
1554
+ input: { state: "open", cursors: { "github.example.com": "page-2" } },
1555
+ });
1556
+ const unmount = registry.mount(page);
1557
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1558
+ yield* Effect.promise(() => executeAtomQuery(registry, page));
1559
+
1560
+ yield* Effect.promise(() =>
1561
+ atoms.runAction.run(registry, {
1562
+ ...target,
1563
+ input: { ...actionReference, action: "ready" },
1564
+ }),
1565
+ );
1566
1612
- yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true });
1613
- expect(pageReads).toBe(1);
1614
- }),
1615
- ),
1567
+ yield* AtomRegistry.getResult(registry, page, { suspendOnWaiting: true });
1568
+ expect(pageReads).toBe(1);
1569
+ }),
1570
);
1571
1572
it.effect("keeps the server's post-commit read when a reopen reply lacks fields", () =>
1619
- Effect.scoped(
1573
+ Effect.gen(function* () {
1574
+ const refreshEvents = yield* PubSub.unbounded<number>();
1575
+ let reads = 0;
1576
+ const detailWaiting = Latch.makeUnsafe();
1577
+ const release = yield* Deferred.make<void>();
1578
+ const client = actionReplyClient({
1579
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1580
+ [WS_METHODS.pullRequestsDetail]: () =>
1581
+ Effect.gen(function* () {
1582
+ reads++;
1583
+ if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1584
+ yield* Deferred.await(release);
1585
+ return { ...actionReference, state: "open", observedAt: 300 };
1586
+ }),
1587
+ [WS_METHODS.pullRequestsRunAction]: () =>
1588
+ Effect.gen(function* () {
1589
+ // The server announces its refresh before it replies.
1590
+ yield* PubSub.publish(refreshEvents, 1);
1591
+ yield* detailWaiting.await;
1592
+ return { ...actionReply, state: "open" };
1593
+ }),
1594
+ });
1595
+ const { atoms, registry } = yield* makeTestRuntime(client);
1596
+ const target = { environmentId: TARGET.environmentId, input: actionReference };
1597
+ const detail = atoms.detail(target);
1598
+ const unmount = registry.mount(detail);
1599
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1600
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1601
+ const stop = registry.subscribe(detail, (result) => {
1602
+ if (result.waiting) detailWaiting.openUnsafe();
1603
+ });
1604
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
1605
+
1606
+ yield* Effect.promise(() =>
1607
+ atoms.runAction.run(registry, {
1608
+ ...target,
1609
+ input: { ...actionReference, action: "reopen" },
1610
+ }),
1611
+ );
1612
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1613
+ yield* Deferred.succeed(release, undefined);
1614
+
1615
+ expect(
1616
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1617
+ ).toBe(300);
1618
+ expect(reads).toBe(2);
1619
+ }),
1620
+);
1621
+
1622
+it.effect.each([
1623
+ ["a newer update", "open", "2026-10-27T10:00:01Z", 100, "open"],
1624
+ ["a merge", "merged", "2026-10-27T09:00:00Z", 100, "open"],
1625
+] as const)(
1626
+ "keeps %s when an older or reverting action reply arrives",
1627
+ ([, shownState, updatedAt, observedAt, replyState]) =>
1628
Effect.gen(function* () {
1621
- const refreshEvents = yield* PubSub.unbounded<number>();
1622
- let reads = 0;
1623
- const detailWaiting = Latch.makeUnsafe();
1624
- const release = yield* Deferred.make<void>();
1629
+ const shown = {
1630
+ ...actionReference,
1631
+ state: shownState,
1632
+ isDraft: true,
1633
+ updatedAt,
1634
+ observedAt,
1635
+ };
1636
const client = actionReplyClient({
1626
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1627
- [WS_METHODS.pullRequestsDetail]: () =>
1628
- Effect.gen(function* () {
1629
- reads++;
1630
- if (reads === 1) return { ...actionReference, state: "closed", observedAt: 100 };
1631
- yield* Deferred.await(release);
1632
- return { ...actionReference, state: "open", observedAt: 300 };
1633
- }),
1637
+ [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1638
+ [WS_METHODS.pullRequestsPreview]: () => Effect.succeed(shown),
1639
[WS_METHODS.pullRequestsRunAction]: () =>
1635
- Effect.gen(function* () {
1636
- // The server announces its refresh before it replies.
1637
- yield* PubSub.publish(refreshEvents, 1);
1638
- yield* detailWaiting.await;
1639
- return { ...actionReply, state: "open" };
1640
- }),
1640
+ Effect.succeed({ ...actionReply, state: replyState }),
1641
});
1642
const { atoms, registry } = yield* makeTestRuntime(client);
1643
const target = { environmentId: TARGET.environmentId, input: actionReference };
1644
- const detail = atoms.detail(target);
1645
- const unmount = registry.mount(detail);
1646
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1647
- yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
1648
- const stop = registry.subscribe(detail, (result) => {
1649
- if (result.waiting) detailWaiting.openUnsafe();
1650
- });
1651
- yield* Effect.addFinalizer(() => Effect.sync(stop));
1644
+ const readers = [atoms.detail(target), atoms.preview(target), atoms.previewCard(target)];
1645
+ for (const reader of readers) {
1646
+ registry.mount(reader);
1647
+ yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true });
1648
+ }
1649
1650
yield* Effect.promise(() =>
1651
atoms.runAction.run(registry, {
1652
...target,
1656
- input: { ...actionReference, action: "reopen" },
1653
+ input: { ...actionReference, action: "ready" },
1654
}),
1655
);
1659
- expect(Option.getOrThrow(AsyncResult.value(registry.get(detail))).state).toBe("open");
1660
- yield* Deferred.succeed(release, undefined);
1661
-
1662
- expect(
1663
- (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).observedAt,
1664
- ).toBe(300);
1665
- expect(reads).toBe(2);
1666
- }),
1667
- ),
1668
-);
1669
-
1670
-it.effect.each([
1671
- ["a newer update", "open", "2026-10-27T10:00:01Z", 100, "open"],
1672
- ["a merge", "merged", "2026-10-27T09:00:00Z", 100, "open"],
1673
-] as const)(
1674
- "keeps %s when an older or reverting action reply arrives",
1675
- ([, shownState, updatedAt, observedAt, replyState]) =>
1676
- Effect.scoped(
1677
- Effect.gen(function* () {
1678
- const shown = {
1679
- ...actionReference,
1656
+ for (const reader of readers) {
1657
+ expect(Option.getOrThrow(AsyncResult.value(registry.get(reader)))).toMatchObject({
1658
state: shownState,
1659
isDraft: true,
1682
- updatedAt,
1683
- observedAt,
1684
- };
1685
- const client = actionReplyClient({
1686
- [WS_METHODS.pullRequestsDetail]: () => Effect.succeed(shown),
1687
- [WS_METHODS.pullRequestsPreview]: () => Effect.succeed(shown),
1688
- [WS_METHODS.pullRequestsRunAction]: () =>
1689
- Effect.succeed({ ...actionReply, state: replyState }),
1660
});
1691
- const { atoms, registry } = yield* makeTestRuntime(client);
1692
- const target = { environmentId: TARGET.environmentId, input: actionReference };
1693
- const readers = [atoms.detail(target), atoms.preview(target), atoms.previewCard(target)];
1694
- for (const reader of readers) {
1695
- registry.mount(reader);
1696
- yield* AtomRegistry.getResult(registry, reader, { suspendOnWaiting: true });
1697
- }
1698
-
1699
- yield* Effect.promise(() =>
1700
- atoms.runAction.run(registry, {
1701
- ...target,
1702
- input: { ...actionReference, action: "ready" },
1703
- }),
1704
- );
1705
- for (const reader of readers) {
1706
- expect(Option.getOrThrow(AsyncResult.value(registry.get(reader)))).toMatchObject({
1707
- state: shownState,
1708
- isDraft: true,
1709
- });
1710
- }
1711
- }),
1712
- ),
1661
+ }
1662
+ }),
1663
);
1664
1665
it.effect("keeps hover previews fresh after edits and turns", () =>
1716
- Effect.scoped(
1717
- Effect.gen(function* () {
1718
- const refreshEvents = yield* PubSub.unbounded<number>();
1719
- let title = "Original title";
1720
- let reads = 0;
1721
- const read = (input: unknown) =>
1666
+ Effect.gen(function* () {
1667
+ const refreshEvents = yield* PubSub.unbounded<number>();
1668
+ let title = "Original title";
1669
+ let reads = 0;
1670
+ const read = (input: unknown) =>
1671
+ Effect.sync(() => {
1672
+ expect(input).toEqual(reference);
1673
+ reads++;
1674
+ return { ...reference, title };
1675
+ });
1676
+ const reference = {
1677
+ projectId: ProjectId.make("project-1"),
1678
+ repository: "acme/web",
1679
+ number: 1,
1680
+ host: "github.example.com",
1681
+ };
1682
+ const client = {
1683
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1684
+ [WS_METHODS.pullRequestsPreview]: read,
1685
+ [WS_METHODS.pullRequestsDetail]: read,
1686
+ [WS_METHODS.pullRequestsUpdate]: (input: { title: string }) =>
1687
Effect.sync(() => {
1723
- expect(input).toEqual(reference);
1724
- reads++;
1725
- return { ...reference, title };
1726
- });
1727
- const reference = {
1728
- projectId: ProjectId.make("project-1"),
1729
- repository: "acme/web",
1730
- number: 1,
1731
- host: "github.example.com",
1732
- };
1733
- const client = {
1734
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.fromPubSub(refreshEvents),
1735
- [WS_METHODS.pullRequestsPreview]: read,
1736
- [WS_METHODS.pullRequestsDetail]: read,
1737
- [WS_METHODS.pullRequestsUpdate]: (input: { title: string }) =>
1738
- Effect.sync(() => {
1739
- title = input.title;
1740
- }),
1741
- [WS_METHODS.pullRequestsRunAction]: () =>
1742
- Effect.sync(() => {
1743
- title = "Closed";
1744
- }),
1745
- [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
1746
- } as unknown as WsRpcProtocolClient;
1747
- const { atoms, registry } = yield* makeTestRuntime(client);
1748
- const target = { environmentId: TARGET.environmentId, input: reference };
1749
- const preview = atoms.preview(target);
1750
- const unmount = registry.mount(preview);
1751
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1752
- expect(
1753
- (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1754
- ).toBe(title);
1755
- yield* Effect.promise(() => executeAtomQuery(registry, preview));
1756
- expect(reads).toBe(1);
1757
- const edited = yield* Effect.promise(() =>
1758
- atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }),
1759
- );
1760
- expect(AsyncResult.isSuccess(edited)).toBe(true);
1761
- expect(
1762
- (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1763
- ).toBe("Edited");
1764
- yield* Effect.promise(() =>
1765
- atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }),
1766
- );
1767
- expect(
1768
- (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1769
- ).toBe("Closed");
1770
- title = "Refreshed";
1771
- yield* Effect.promise(() =>
1772
- atoms.invalidate.run(registry, {
1773
- environmentId: target.environmentId,
1774
- input: { reference },
1688
+ title = input.title;
1689
}),
1776
- );
1777
- expect(
1778
- (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1779
- ).toBe("Refreshed");
1780
- const refreshed = Latch.makeUnsafe();
1781
- const stop = registry.subscribe(preview, (result) => {
1782
- if (AsyncResult.isSuccess(result) && result.value.title === "After turn")
1783
- refreshed.openUnsafe();
1784
- });
1785
- yield* Effect.addFinalizer(() => Effect.sync(stop));
1786
- title = "After turn";
1787
- yield* PubSub.publish(refreshEvents, 1);
1788
- yield* refreshed.await;
1789
- }),
1790
- ),
1690
+ [WS_METHODS.pullRequestsRunAction]: () =>
1691
+ Effect.sync(() => {
1692
+ title = "Closed";
1693
+ }),
1694
+ [WS_METHODS.pullRequestsInvalidate]: () => Effect.void,
1695
+ } as unknown as WsRpcProtocolClient;
1696
+ const { atoms, registry } = yield* makeTestRuntime(client);
1697
+ const target = { environmentId: TARGET.environmentId, input: reference };
1698
+ const preview = atoms.preview(target);
1699
+ const unmount = registry.mount(preview);
1700
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1701
+ expect(
1702
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1703
+ ).toBe(title);
1704
+ yield* Effect.promise(() => executeAtomQuery(registry, preview));
1705
+ expect(reads).toBe(1);
1706
+ const edited = yield* Effect.promise(() =>
1707
+ atoms.update.run(registry, { ...target, input: { ...reference, title: "Edited" } }),
1708
+ );
1709
+ expect(AsyncResult.isSuccess(edited)).toBe(true);
1710
+ expect(
1711
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1712
+ ).toBe("Edited");
1713
+ yield* Effect.promise(() =>
1714
+ atoms.runAction.run(registry, { ...target, input: { ...reference, action: "close" } }),
1715
+ );
1716
+ expect(
1717
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1718
+ ).toBe("Closed");
1719
+ title = "Refreshed";
1720
+ yield* Effect.promise(() =>
1721
+ atoms.invalidate.run(registry, {
1722
+ environmentId: target.environmentId,
1723
+ input: { reference },
1724
+ }),
1725
+ );
1726
+ expect(
1727
+ (yield* AtomRegistry.getResult(registry, preview, { suspendOnWaiting: true })).title,
1728
+ ).toBe("Refreshed");
1729
+ const refreshed = Latch.makeUnsafe();
1730
+ const stop = registry.subscribe(preview, (result) => {
1731
+ if (AsyncResult.isSuccess(result) && result.value.title === "After turn")
1732
+ refreshed.openUnsafe();
1733
+ });
1734
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
1735
+ title = "After turn";
1736
+ yield* PubSub.publish(refreshEvents, 1);
1737
+ yield* refreshed.await;
1738
+ }),
1739
);
1740
1741
it.effect("shares one refresh stream between independently created pull request readers", () =>
1794
- Effect.scoped(
1795
- Effect.gen(function* () {
1796
- const revision = yield* SubscriptionRef.make(0);
1797
- let subscriptions = 0;
1798
- let title = "Original title";
1799
- const client = {
1800
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () =>
1801
- Stream.unwrap(
1802
- Effect.sync(() => {
1803
- subscriptions++;
1804
- return SubscriptionRef.changes(revision);
1805
- }),
1806
- ),
1807
- [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ title, state: "open" })),
1808
- [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ title, state: "open" })),
1809
- } as unknown as WsRpcProtocolClient;
1810
- const { runtime, atoms, registry } = yield* makeTestRuntime(client);
1811
- const target = {
1812
- environmentId: TARGET.environmentId,
1813
- input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1814
- };
1815
- const summary = createLinkedPullRequestSummaryAtomFamily(runtime)(target);
1816
- const detail = atoms.detail(target);
1817
- for (const atom of [summary, detail]) {
1818
- const unmount = registry.mount(atom);
1819
- yield* Effect.addFinalizer(() => Effect.sync(unmount));
1820
- expect((yield* AtomRegistry.getResult(registry, atom)).title).toBe(title);
1821
- }
1822
- yield* AtomRegistry.getResult(
1823
- registry,
1824
- atoms.refreshes({ environmentId: target.environmentId, input: {} }),
1825
- );
1826
- expect(subscriptions).toBe(1);
1827
-
1828
- const changed = [summary, detail].map((atom) => {
1829
- const ready = Latch.makeUnsafe();
1830
- const stop = registry.subscribe(atom, (result) => {
1831
- if (AsyncResult.isSuccess(result) && result.value.title === "Updated title") {
1832
- ready.openUnsafe();
1833
- }
1834
- });
1835
- return { ready, stop };
1742
+ Effect.gen(function* () {
1743
+ const revision = yield* SubscriptionRef.make(0);
1744
+ let subscriptions = 0;
1745
+ let title = "Original title";
1746
+ const client = {
1747
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () =>
1748
+ Stream.unwrap(
1749
+ Effect.sync(() => {
1750
+ subscriptions++;
1751
+ return SubscriptionRef.changes(revision);
1752
+ }),
1753
+ ),
1754
+ [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ title, state: "open" })),
1755
+ [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ title, state: "open" })),
1756
+ } as unknown as WsRpcProtocolClient;
1757
+ const { runtime, atoms, registry } = yield* makeTestRuntime(client);
1758
+ const target = {
1759
+ environmentId: TARGET.environmentId,
1760
+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1761
+ };
1762
+ const summary = createLinkedPullRequestSummaryAtomFamily(runtime)(target);
1763
+ const detail = atoms.detail(target);
1764
+ for (const atom of [summary, detail]) {
1765
+ const unmount = registry.mount(atom);
1766
+ yield* Effect.addFinalizer(() => Effect.sync(unmount));
1767
+ expect((yield* AtomRegistry.getResult(registry, atom)).title).toBe(title);
1768
+ }
1769
+ yield* AtomRegistry.getResult(
1770
+ registry,
1771
+ atoms.refreshes({ environmentId: target.environmentId, input: {} }),
1772
+ );
1773
+ expect(subscriptions).toBe(1);
1774
+
1775
+ const changed = [summary, detail].map((atom) => {
1776
+ const ready = Latch.makeUnsafe();
1777
+ const stop = registry.subscribe(atom, (result) => {
1778
+ if (AsyncResult.isSuccess(result) && result.value.title === "Updated title") {
1779
+ ready.openUnsafe();
1780
+ }
1781
});
1837
- yield* Effect.addFinalizer(() => Effect.sync(() => changed.forEach(({ stop }) => stop())));
1838
- title = "Updated title";
1839
- yield* SubscriptionRef.update(revision, (value) => value + 1);
1840
- for (const { ready } of changed) yield* ready.await;
1841
- expect(subscriptions).toBe(1);
1842
- }),
1843
- ),
1782
+ return { ready, stop };
1783
+ });
1784
+ yield* Effect.addFinalizer(() => Effect.sync(() => changed.forEach(({ stop }) => stop())));
1785
+ title = "Updated title";
1786
+ yield* SubscriptionRef.update(revision, (value) => value + 1);
1787
+ for (const { ready } of changed) yield* ready.await;
1788
+ expect(subscriptions).toBe(1);
1789
+ }),
1790
);
1791
1792
it.effect("shares close, reopen, and merge with an untouched client's mounted PR readers", () =>
1847
- Effect.scoped(
1848
- Effect.gen(function* () {
1849
- const revision = yield* SubscriptionRef.make(0);
1850
- let state: "open" | "closed" | "merged" = "open";
1851
- const client = {
1852
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision),
1853
- [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })),
1854
- [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })),
1855
- [WS_METHODS.pullRequestsList]: () =>
1856
- Effect.sync(() => ({ entries: [{ number: 1, state }] })),
1857
- [WS_METHODS.pullRequestsRunAction]: (input: {
1858
- readonly action: "close" | "reopen" | "merge";
1859
- }) =>
1860
- Effect.gen(function* () {
1861
- state =
1862
- input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open";
1863
- yield* SubscriptionRef.update(revision, (value) => value + 1);
1864
- }),
1865
- } as unknown as WsRpcProtocolClient;
1866
- const writer = yield* makeTestRuntime(client);
1867
- const reader = yield* makeTestRuntime(client);
1868
- const target = {
1869
- environmentId: TARGET.environmentId,
1870
- input: {
1871
- projectId: ProjectId.make("project-1"),
1872
- host: "github.example.com",
1873
- repository: "acme/web",
1874
- number: 1,
1875
- },
1876
- };
1877
- const detail = reader.atoms.detail(target);
1878
- const summary = createLinkedPullRequestSummaryAtomFamily(
1879
- reader.runtime,
1880
- reader.atoms.refreshes,
1881
- )(target);
1882
- const list = reader.atoms.list({
1883
- environmentId: TARGET.environmentId,
1884
- input: { state: "all" },
1885
- });
1886
- const unmountDetail = reader.registry.mount(detail);
1887
- const unmountSummary = reader.registry.mount(summary);
1888
- const unmountList = reader.registry.mount(list);
1889
- yield* Effect.addFinalizer(() =>
1890
- Effect.sync(() => {
1891
- unmountDetail();
1892
- unmountSummary();
1893
- unmountList();
1793
+ Effect.gen(function* () {
1794
+ const revision = yield* SubscriptionRef.make(0);
1795
+ let state: "open" | "closed" | "merged" = "open";
1796
+ const client = {
1797
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => SubscriptionRef.changes(revision),
1798
+ [WS_METHODS.pullRequestsSummary]: () => Effect.sync(() => ({ state })),
1799
+ [WS_METHODS.pullRequestsDetail]: () => Effect.sync(() => ({ state })),
1800
+ [WS_METHODS.pullRequestsList]: () => Effect.sync(() => ({ entries: [{ number: 1, state }] })),
1801
+ [WS_METHODS.pullRequestsRunAction]: (input: {
1802
+ readonly action: "close" | "reopen" | "merge";
1803
+ }) =>
1804
+ Effect.gen(function* () {
1805
+ state =
1806
+ input.action === "close" ? "closed" : input.action === "merge" ? "merged" : "open";
1807
+ yield* SubscriptionRef.update(revision, (value) => value + 1);
1808
+ }),
1809
+ } as unknown as WsRpcProtocolClient;
1810
+ const writer = yield* makeTestRuntime(client);
1811
+ const reader = yield* makeTestRuntime(client);
1812
+ const target = {
1813
+ environmentId: TARGET.environmentId,
1814
+ input: {
1815
+ projectId: ProjectId.make("project-1"),
1816
+ host: "github.example.com",
1817
+ repository: "acme/web",
1818
+ number: 1,
1819
+ },
1820
+ };
1821
+ const detail = reader.atoms.detail(target);
1822
+ const summary = createLinkedPullRequestSummaryAtomFamily(
1823
+ reader.runtime,
1824
+ reader.atoms.refreshes,
1825
+ )(target);
1826
+ const list = reader.atoms.list({
1827
+ environmentId: TARGET.environmentId,
1828
+ input: { state: "all" },
1829
+ });
1830
+ const unmountDetail = reader.registry.mount(detail);
1831
+ const unmountSummary = reader.registry.mount(summary);
1832
+ const unmountList = reader.registry.mount(list);
1833
+ yield* Effect.addFinalizer(() =>
1834
+ Effect.sync(() => {
1835
+ unmountDetail();
1836
+ unmountSummary();
1837
+ unmountList();
1838
+ }),
1839
+ );
1840
+ expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open");
1841
+ expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open");
1842
+ expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open");
1843
+
1844
+ for (const [action, expected] of [
1845
+ ["close", "closed"],
1846
+ ["reopen", "open"],
1847
+ ["merge", "merged"],
1848
+ ] as const) {
1849
+ const detailChanged = Latch.makeUnsafe();
1850
+ const summaryChanged = Latch.makeUnsafe();
1851
+ const listChanged = Latch.makeUnsafe();
1852
+ const stops = [
1853
+ reader.registry.subscribe(detail, (result) => {
1854
+ if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1855
+ detailChanged.openUnsafe();
1856
+ }
1857
+ }),
1858
+ reader.registry.subscribe(summary, (result) => {
1859
+ if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1860
+ summaryChanged.openUnsafe();
1861
+ }
1862
+ }),
1863
+ reader.registry.subscribe(list, (result) => {
1864
+ if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) {
1865
+ listChanged.openUnsafe();
1866
+ }
1867
+ }),
1868
+ ];
1869
+ yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
1870
+ const result = yield* Effect.promise(() =>
1871
+ writer.atoms.runAction.run(writer.registry, {
1872
+ ...target,
1873
+ input: { ...target.input, action },
1874
}),
1875
);
1896
- expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe("open");
1897
- expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe("open");
1898
- expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe("open");
1899
-
1900
- for (const [action, expected] of [
1901
- ["close", "closed"],
1902
- ["reopen", "open"],
1903
- ["merge", "merged"],
1904
- ] as const) {
1905
- const detailChanged = Latch.makeUnsafe();
1906
- const summaryChanged = Latch.makeUnsafe();
1907
- const listChanged = Latch.makeUnsafe();
1908
- const stops = [
1909
- reader.registry.subscribe(detail, (result) => {
1910
- if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1911
- detailChanged.openUnsafe();
1912
- }
1913
- }),
1914
- reader.registry.subscribe(summary, (result) => {
1915
- if (AsyncResult.isSuccess(result) && result.value.state === expected) {
1916
- summaryChanged.openUnsafe();
1917
- }
1918
- }),
1919
- reader.registry.subscribe(list, (result) => {
1920
- if (AsyncResult.isSuccess(result) && result.value.entries[0]?.state === expected) {
1921
- listChanged.openUnsafe();
1922
- }
1923
- }),
1924
- ];
1925
- yield* Effect.addFinalizer(() => Effect.sync(() => stops.forEach((stop) => stop())));
1926
- const result = yield* Effect.promise(() =>
1927
- writer.atoms.runAction.run(writer.registry, {
1928
- ...target,
1929
- input: { ...target.input, action },
1930
- }),
1931
- );
1932
- expect(AsyncResult.isSuccess(result)).toBe(true);
1933
- yield* detailChanged.await;
1934
- yield* summaryChanged.await;
1935
- yield* listChanged.await;
1936
- expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected);
1937
- expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected);
1938
- expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe(
1939
- expected,
1940
- );
1941
- stops.forEach((stop) => stop());
1942
- }
1943
- }),
1944
- ),
1876
+ expect(AsyncResult.isSuccess(result)).toBe(true);
1877
+ yield* detailChanged.await;
1878
+ yield* summaryChanged.await;
1879
+ yield* listChanged.await;
1880
+ expect((yield* AtomRegistry.getResult(reader.registry, detail)).state).toBe(expected);
1881
+ expect((yield* AtomRegistry.getResult(reader.registry, summary)).state).toBe(expected);
1882
+ expect((yield* AtomRegistry.getResult(reader.registry, list)).entries[0]?.state).toBe(
1883
+ expected,
1884
+ );
1885
+ stops.forEach((stop) => stop());
1886
+ }
1887
+ }),
1888
);
1889
1890
it.effect("shares checks reads across reference property order", () =>
1948
- Effect.scoped(
1949
- Effect.gen(function* () {
1950
- let reads = 0;
1951
- const client = {
1952
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1953
- [WS_METHODS.pullRequestsChecks]: () =>
1954
- Effect.sync(() => {
1955
- reads += 1;
1956
- return { state: "open", checks: [], observedAt: 1_000 };
1957
- }),
1958
- } as unknown as WsRpcProtocolClient;
1959
- const { atoms, registry } = yield* makeTestRuntime(client);
1960
- const projectId = ProjectId.make("project-1");
1961
- const row = atoms.checks({
1962
- environmentId: TARGET.environmentId,
1963
- input: { host: "github.com", repository: "acme/web", number: 1, projectId },
1964
- });
1965
- const panel = atoms.checks({
1966
- environmentId: TARGET.environmentId,
1967
- input: { projectId, host: "github.com", repository: "acme/web", number: 1 },
1968
- });
1969
- yield* AtomRegistry.getResult(registry, row);
1970
- yield* AtomRegistry.getResult(registry, panel);
1971
- expect(reads).toBe(1);
1972
- }),
1973
- ),
1891
+ Effect.gen(function* () {
1892
+ let reads = 0;
1893
+ const client = {
1894
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1895
+ [WS_METHODS.pullRequestsChecks]: () =>
1896
+ Effect.sync(() => {
1897
+ reads += 1;
1898
+ return { state: "open", checks: [], observedAt: 1_000 };
1899
+ }),
1900
+ } as unknown as WsRpcProtocolClient;
1901
+ const { atoms, registry } = yield* makeTestRuntime(client);
1902
+ const projectId = ProjectId.make("project-1");
1903
+ const row = atoms.checks({
1904
+ environmentId: TARGET.environmentId,
1905
+ input: { host: "github.com", repository: "acme/web", number: 1, projectId },
1906
+ });
1907
+ const panel = atoms.checks({
1908
+ environmentId: TARGET.environmentId,
1909
+ input: { projectId, host: "github.com", repository: "acme/web", number: 1 },
1910
+ });
1911
+ yield* AtomRegistry.getResult(registry, row);
1912
+ yield* AtomRegistry.getResult(registry, panel);
1913
+ expect(reads).toBe(1);
1914
+ }),
1915
);
1916
1917
it.effect("keeps live detail reads separate from reads that allow stale data", () =>
1977
- Effect.scoped(
1978
- Effect.gen(function* () {
1979
- let reads = 0;
1980
- let hostStamp: number | undefined;
1981
- let hold = false;
1982
- const readStarted = yield* Latch.make();
1983
- const releaseRead = yield* Latch.make();
1984
- const client = {
1985
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1986
- [WS_METHODS.pullRequestsDetail]: (input: { allowStale?: boolean }) =>
1987
- Effect.gen(function* () {
1988
- reads++;
1989
- if (hold) {
1990
- yield* readStarted.open;
1991
- yield* releaseRead.await;
1992
- }
1993
- return {
1994
- title: input.allowStale === false ? "latest checks" : "cached checks",
1995
- ...(hostStamp === undefined ? {} : { observedAt: hostStamp }),
1996
- };
1997
- }),
1998
- } as unknown as WsRpcProtocolClient;
1999
- const { atoms, registry, supervisor } = yield* makeTestRuntime(client);
2000
- const target = {
2001
- environmentId: TARGET.environmentId,
2002
- input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
2003
- };
2004
- const cached = atoms.detail(target);
2005
- const live = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
2006
- const first = yield* AtomRegistry.getResult(registry, cached);
2007
- expect(first.title).toBe("cached checks");
2008
- expect(first.observedAt).toBeUndefined();
2009
- const reading = atoms.detailReadVersion(target);
2010
- const firstVersion = registry.get(reading);
2011
- expect(firstVersion).toBeGreaterThan(0);
2012
- expect((yield* AtomRegistry.getResult(registry, live)).title).toBe("latest checks");
2013
- expect(reads).toBe(2);
2014
- hold = true;
2015
- registry.refresh(cached);
2016
- yield* readStarted.await;
2017
- expect(registry.get(reading)).toBe(firstVersion);
2018
- yield* releaseRead.open;
2019
- expect(yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).toBe(
2020
- first,
2021
- );
2022
- const settledVersion = registry.get(reading);
2023
- expect(settledVersion).toBeGreaterThan(firstVersion);
2024
- hold = false;
2025
-
2026
- yield* SubscriptionRef.update(supervisor.state, (state) => ({
2027
- ...state,
2028
- phase: "offline" as const,
2029
- }));
2030
- yield* Effect.yieldNow;
2031
- registry.refresh(cached);
2032
- const offline = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
2033
- expect(offline.observedAt).toBeUndefined();
2034
- expect(registry.get(reading)).toBe(settledVersion);
2035
- expect(reads).toBe(3);
2036
-
2037
- yield* SubscriptionRef.update(supervisor.state, (state) => ({
2038
- ...state,
2039
- phase: "connected" as const,
2040
- }));
2041
- yield* Effect.yieldNow;
2042
- registry.refresh(cached);
2043
- const reread = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
2044
- expect(reread).toBe(first);
2045
- expect(reread.observedAt).toBeUndefined();
2046
- expect(registry.get(reading)).toBeGreaterThan(settledVersion);
2047
-
2048
- hostStamp = 27;
2049
- registry.refresh(cached);
2050
- expect(
2051
- (yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).observedAt,
2052
- ).toBe(hostStamp);
2053
- }),
2054
- ),
1918
+ Effect.gen(function* () {
1919
+ let reads = 0;
1920
+ let hostStamp: number | undefined;
1921
+ let hold = false;
1922
+ const readStarted = yield* Latch.make();
1923
+ const releaseRead = yield* Latch.make();
1924
+ const client = {
1925
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
1926
+ [WS_METHODS.pullRequestsDetail]: (input: { allowStale?: boolean }) =>
1927
+ Effect.gen(function* () {
1928
+ reads++;
1929
+ if (hold) {
1930
+ yield* readStarted.open;
1931
+ yield* releaseRead.await;
1932
+ }
1933
+ return {
1934
+ title: input.allowStale === false ? "latest checks" : "cached checks",
1935
+ ...(hostStamp === undefined ? {} : { observedAt: hostStamp }),
1936
+ };
1937
+ }),
1938
+ } as unknown as WsRpcProtocolClient;
1939
+ const { atoms, registry, supervisor } = yield* makeTestRuntime(client);
1940
+ const target = {
1941
+ environmentId: TARGET.environmentId,
1942
+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
1943
+ };
1944
+ const cached = atoms.detail(target);
1945
+ const live = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
1946
+ const first = yield* AtomRegistry.getResult(registry, cached);
1947
+ expect(first.title).toBe("cached checks");
1948
+ expect(first.observedAt).toBeUndefined();
1949
+ const reading = atoms.detailReadVersion(target);
1950
+ const firstVersion = registry.get(reading);
1951
+ expect(firstVersion).toBeGreaterThan(0);
1952
+ expect((yield* AtomRegistry.getResult(registry, live)).title).toBe("latest checks");
1953
+ expect(reads).toBe(2);
1954
+ hold = true;
1955
+ registry.refresh(cached);
1956
+ yield* readStarted.await;
1957
+ expect(registry.get(reading)).toBe(firstVersion);
1958
+ yield* releaseRead.open;
1959
+ expect(yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).toBe(first);
1960
+ const settledVersion = registry.get(reading);
1961
+ expect(settledVersion).toBeGreaterThan(firstVersion);
1962
+ hold = false;
1963
+
1964
+ yield* SubscriptionRef.update(supervisor.state, (state) => ({
1965
+ ...state,
1966
+ phase: "offline" as const,
1967
+ }));
1968
+ yield* Effect.yieldNow;
1969
+ registry.refresh(cached);
1970
+ const offline = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
1971
+ expect(offline.observedAt).toBeUndefined();
1972
+ expect(registry.get(reading)).toBe(settledVersion);
1973
+ expect(reads).toBe(3);
1974
+
1975
+ yield* SubscriptionRef.update(supervisor.state, (state) => ({
1976
+ ...state,
1977
+ phase: "connected" as const,
1978
+ }));
1979
+ yield* Effect.yieldNow;
1980
+ registry.refresh(cached);
1981
+ const reread = yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true });
1982
+ expect(reread).toBe(first);
1983
+ expect(reread.observedAt).toBeUndefined();
1984
+ expect(registry.get(reading)).toBeGreaterThan(settledVersion);
1985
+
1986
+ hostStamp = 27;
1987
+ registry.refresh(cached);
1988
+ expect(
1989
+ (yield* AtomRegistry.getResult(registry, cached, { suspendOnWaiting: true })).observedAt,
1990
+ ).toBe(hostStamp);
1991
+ }),
1992
);
1993
1994
it.effect("updates cached labels after successful edits without rereading the host", () =>
2058
- Effect.scoped(
2059
- Effect.gen(function* () {
2060
- let detailReads = 0;
2061
- let candidateReads = 0;
2062
- let refuse = false;
2063
- let failDetail = false;
2064
- const existing = { name: "existing", color: "111111" };
2065
- const addedLabel = { name: "new", color: "abcdef" };
2066
- const detailRefreshStarted = yield* Latch.make();
2067
- const releaseDetailRefresh = yield* Latch.make();
2068
- const client = {
2069
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
2070
- [WS_METHODS.pullRequestsDetail]: () =>
2071
- Effect.gen(function* () {
2072
- detailReads++;
2073
- if (failDetail) {
2074
- yield* detailRefreshStarted.open;
2075
- yield* releaseDetailRefresh.await;
2076
- return yield* new MutationRefused();
2077
- }
2078
- return { title: "keep this title", labels: [existing] };
2079
- }),
2080
- [WS_METHODS.pullRequestsLabelCandidates]: () =>
2081
- Effect.sync(() => {
2082
- candidateReads++;
2083
- return {
2084
- candidates: [
2085
- { ...existing, description: null, isApplied: true },
2086
- { ...addedLabel, description: "description", isApplied: false },
2087
- ],
2088
- truncated: false,
2089
- };
2090
- }),
2091
- [WS_METHODS.pullRequestsSetLabels]: () =>
2092
- refuse ? Effect.fail(new MutationRefused()) : Effect.void,
2093
- } as unknown as WsRpcProtocolClient;
2094
- const { atoms, registry } = yield* makeTestRuntime(client);
2095
- const target = {
2096
- environmentId: TARGET.environmentId,
1995
+ Effect.gen(function* () {
1996
+ let detailReads = 0;
1997
+ let candidateReads = 0;
1998
+ let refuse = false;
1999
+ let failDetail = false;
2000
+ const existing = { name: "existing", color: "111111" };
2001
+ const addedLabel = { name: "new", color: "abcdef" };
2002
+ const detailRefreshStarted = yield* Latch.make();
2003
+ const releaseDetailRefresh = yield* Latch.make();
2004
+ const client = {
2005
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
2006
+ [WS_METHODS.pullRequestsDetail]: () =>
2007
+ Effect.gen(function* () {
2008
+ detailReads++;
2009
+ if (failDetail) {
2010
+ yield* detailRefreshStarted.open;
2011
+ yield* releaseDetailRefresh.await;
2012
+ return yield* new MutationRefused();
2013
+ }
2014
+ return { title: "keep this title", labels: [existing] };
2015
+ }),
2016
+ [WS_METHODS.pullRequestsLabelCandidates]: () =>
2017
+ Effect.sync(() => {
2018
+ candidateReads++;
2019
+ return {
2020
+ candidates: [
2021
+ { ...existing, description: null, isApplied: true },
2022
+ { ...addedLabel, description: "description", isApplied: false },
2023
+ ],
2024
+ truncated: false,
2025
+ };
2026
+ }),
2027
+ [WS_METHODS.pullRequestsSetLabels]: () =>
2028
+ refuse ? Effect.fail(new MutationRefused()) : Effect.void,
2029
+ } as unknown as WsRpcProtocolClient;
2030
+ const { atoms, registry } = yield* makeTestRuntime(client);
2031
+ const target = {
2032
+ environmentId: TARGET.environmentId,
2033
+ input: {
2034
+ projectId: ProjectId.make("project-1"),
2035
+ repository: "acme/web",
2036
+ number: 1,
2037
+ host: "github.example.com",
2038
+ },
2039
+ };
2040
+ const detail = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
2041
+ const candidates = atoms.labelCandidates(target);
2042
+ registry.mount(detail);
2043
+ const unmountCandidates = registry.mount(candidates);
2044
+ yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
2045
+ yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
2046
+
2047
+ const added = yield* Effect.promise(() =>
2048
+ atoms.setLabels.run(registry, {
2049
+ ...target,
2050
input: {
2098
- projectId: ProjectId.make("project-1"),
2099
- repository: "acme/web",
2100
- number: 1,
2101
- host: "github.example.com",
2051
+ host: target.input.host,
2052
+ projectId: target.input.projectId,
2053
+ repository: target.input.repository,
2054
+ number: target.input.number,
2055
+ labels: ["new"],
2056
+ applied: true,
2057
},
2103
- };
2104
- const detail = atoms.detail({ ...target, input: { ...target.input, allowStale: false } });
2105
- const candidates = atoms.labelCandidates(target);
2106
- registry.mount(detail);
2107
- const unmountCandidates = registry.mount(candidates);
2108
- yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true });
2109
- yield* AtomRegistry.getResult(registry, candidates, { suspendOnWaiting: true });
2110
-
2111
- const added = yield* Effect.promise(() =>
2058
+ }),
2059
+ );
2060
+ expect(AsyncResult.isSuccess(added)).toBe(true);
2061
+ expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
2062
+ title: "keep this title",
2063
+ labels: [existing, addedLabel],
2064
+ });
2065
+ unmountCandidates();
2066
+ registry.mount(atoms.labelCandidates(target));
2067
+ expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
2068
+ ...addedLabel,
2069
+ description: "description",
2070
+ isApplied: true,
2071
+ });
2072
+
2073
+ for (const name of ["existing", "new"]) {
2074
+ refuse = name === "new";
2075
+ const result = yield* Effect.promise(() =>
2076
atoms.setLabels.run(registry, {
2077
...target,
2114
- input: {
2115
- host: target.input.host,
2116
- projectId: target.input.projectId,
2117
- repository: target.input.repository,
2118
- number: target.input.number,
2119
- labels: ["new"],
2120
- applied: true,
2121
- },
2078
+ input: { ...target.input, labels: [name], applied: false },
2079
}),
2080
);
2124
- expect(AsyncResult.isSuccess(added)).toBe(true);
2125
- expect(yield* AtomRegistry.getResult(registry, detail)).toEqual({
2126
- title: "keep this title",
2127
- labels: [existing, addedLabel],
2128
- });
2129
- unmountCandidates();
2130
- registry.mount(atoms.labelCandidates(target));
2131
- expect((yield* AtomRegistry.getResult(registry, candidates)).candidates[1]).toEqual({
2132
- ...addedLabel,
2133
- description: "description",
2134
- isApplied: true,
2135
- });
2136
-
2137
- for (const name of ["existing", "new"]) {
2138
- refuse = name === "new";
2139
- const result = yield* Effect.promise(() =>
2140
- atoms.setLabels.run(registry, {
2141
- ...target,
2142
- input: { ...target.input, labels: [name], applied: false },
2143
- }),
2144
- );
2145
- expect(result._tag).toBe(refuse ? "Failure" : "Success");
2146
- expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
2147
- expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
2148
- { name: "existing", isApplied: false },
2149
- { name: "new", isApplied: true },
2150
- ]);
2151
- }
2152
- expect(detailReads).toBe(1);
2153
- expect(candidateReads).toBe(1);
2154
-
2155
- failDetail = true;
2156
- registry.refresh(detail);
2157
- yield* detailRefreshStarted.await;
2158
- expect(registry.get(detail).waiting).toBe(true);
2159
- expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
2160
- yield* releaseDetailRefresh.open;
2161
- yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
2162
- expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
2163
- expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
2164
- failDetail = false;
2165
- registry.refresh(detail);
2166
- expect(
2167
- (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
2168
- ).toEqual([existing]);
2169
- expect(detailReads).toBe(3);
2170
- }),
2171
- ),
2081
+ expect(result._tag).toBe(refuse ? "Failure" : "Success");
2082
+ expect((yield* AtomRegistry.getResult(registry, detail)).labels).toEqual([addedLabel]);
2083
+ expect((yield* AtomRegistry.getResult(registry, candidates)).candidates).toMatchObject([
2084
+ { name: "existing", isApplied: false },
2085
+ { name: "new", isApplied: true },
2086
+ ]);
2087
+ }
2088
+ expect(detailReads).toBe(1);
2089
+ expect(candidateReads).toBe(1);
2090
+
2091
+ failDetail = true;
2092
+ registry.refresh(detail);
2093
+ yield* detailRefreshStarted.await;
2094
+ expect(registry.get(detail).waiting).toBe(true);
2095
+ expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
2096
+ yield* releaseDetailRefresh.open;
2097
+ yield* Effect.exit(AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true }));
2098
+ expect(AsyncResult.isFailure(registry.get(detail))).toBe(true);
2099
+ expect(AsyncResult.getOrThrow(registry.get(detail)).labels).toEqual([addedLabel]);
2100
+ failDetail = false;
2101
+ registry.refresh(detail);
2102
+ expect(
2103
+ (yield* AtomRegistry.getResult(registry, detail, { suspendOnWaiting: true })).labels,
2104
+ ).toEqual([existing]);
2105
+ expect(detailReads).toBe(3);
2106
+ }),
2107
);
2108
2109
vi.mock("./session.ts", () => ({
@@ -2190,101 +2125,93 @@ const grantedSessions = Atom.family((_id: EnvironmentId) =>
2125
);
2126
2127
it.effect("denies a routed write when only the origin has source-control permission", () =>
2193
- Effect.scoped(
2194
- Effect.gen(function* () {
2195
- let writes = 0;
2196
- const identity = { host: "github.com", provider: "github", viewer: "test", accountId: "123" };
2197
- const client = {
2198
- [WS_METHODS.pullRequestsRouting]: () => Effect.succeed(identity),
2199
- [WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.succeed(identity),
2200
- [WS_METHODS.pullRequestsRunAction]: () =>
2201
- Effect.sync(() => {
2202
- writes++;
2203
- }),
2204
- } as unknown as WsRpcProtocolClient;
2205
- const fixture = yield* makeTestRuntime(client, client);
2206
- const local = EnvironmentId.make("local-environment");
2207
- const stop = fixture.registry.mount(grantedSessions(local));
2208
- yield* Effect.addFinalizer(() => Effect.sync(stop));
2209
- fixture.registry.set(
2210
- grantedSessions(local),
2211
- AsyncResult.success({
2212
- authenticated: true,
2213
- scopes: [],
2214
- auth: {
2215
- policy: "remote-reachable" as const,
2216
- bootstrapMethods: [],
2217
- sessionMethods: [],
2218
- sessionCookieName: "test",
2219
- },
2220
- }),
2221
- );
2222
- const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
2223
- projectId: ProjectId.make("project"),
2224
- repository: "acme/repo",
2225
- number: 1,
2226
- action: "merge",
2227
- }).pipe(
2228
- Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, fixture.environmentRegistry),
2229
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, fixture.supervisor),
2230
- Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
2231
- Effect.provideService(RpcPermissionGuard, {
2232
- authorize: (id, method, input) =>
2233
- createCommandPermissions(fixture.runtime, method).authorize(
2234
- fixture.registry,
2235
- id,
2236
- input,
2237
- ),
2128
+ Effect.gen(function* () {
2129
+ let writes = 0;
2130
+ const identity = { host: "github.com", provider: "github", viewer: "test", accountId: "123" };
2131
+ const client = {
2132
+ [WS_METHODS.pullRequestsRouting]: () => Effect.succeed(identity),
2133
+ [WS_METHODS.pullRequestsRoutingIdentity]: () => Effect.succeed(identity),
2134
+ [WS_METHODS.pullRequestsRunAction]: () =>
2135
+ Effect.sync(() => {
2136
+ writes++;
2137
}),
2239
- Effect.flip,
2240
- );
2241
- expect(error._tag).toBe("EnvironmentAuthorizationError");
2242
- expect(writes).toBe(0);
2243
- }),
2244
- ),
2138
+ } as unknown as WsRpcProtocolClient;
2139
+ const fixture = yield* makeTestRuntime(client, client);
2140
+ const local = EnvironmentId.make("local-environment");
2141
+ const stop = fixture.registry.mount(grantedSessions(local));
2142
+ yield* Effect.addFinalizer(() => Effect.sync(stop));
2143
+ fixture.registry.set(
2144
+ grantedSessions(local),
2145
+ AsyncResult.success({
2146
+ authenticated: true,
2147
+ scopes: [],
2148
+ auth: {
2149
+ policy: "remote-reachable" as const,
2150
+ bootstrapMethods: [],
2151
+ sessionMethods: [],
2152
+ sessionCookieName: "test",
2153
+ },
2154
+ }),
2155
+ );
2156
+ const error = yield* createPullRequestRouter()(WS_METHODS.pullRequestsRunAction, {
2157
+ projectId: ProjectId.make("project"),
2158
+ repository: "acme/repo",
2159
+ number: 1,
2160
+ action: "merge",
2161
+ }).pipe(
2162
+ Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, fixture.environmentRegistry),
2163
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, fixture.supervisor),
2164
+ Effect.provideService(PullRequestRoutingPermissions, trustedRouting),
2165
+ Effect.provideService(RpcPermissionGuard, {
2166
+ authorize: (id, method, input) =>
2167
+ createCommandPermissions(fixture.runtime, method).authorize(fixture.registry, id, input),
2168
+ }),
2169
+ Effect.flip,
2170
+ );
2171
+ expect(error._tag).toBe("EnvironmentAuthorizationError");
2172
+ expect(writes).toBe(0);
2173
+ }),
2174
);
2175
2176
it.effect("publishes the accepted guide run before the follow-up read finishes", () =>
2248
- Effect.scoped(
2249
- Effect.gen(function* () {
2250
- const accepted = {
2251
- guide: null,
2252
- currentHeadSha: "head",
2253
- run: { _tag: "Running" as const, headSha: "head", startedAt: "2026-10-11T00:00:00.000Z" },
2254
- };
2255
- let reads = 0;
2256
- const refreshStarted = yield* Latch.make();
2257
- const client = {
2258
- [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
2259
- [WS_METHODS.pullRequestsReviewGuide]: () =>
2260
- Effect.gen(function* () {
2261
- if (++reads > 1) {
2262
- yield* refreshStarted.open;
2263
- return yield* Effect.never;
2264
- }
2265
- return { guide: null, run: null, currentHeadSha: "head" };
2266
- }),
2267
- [WS_METHODS.pullRequestsGenerateReviewGuide]: () => Effect.succeed(accepted),
2268
- } as unknown as WsRpcProtocolClient;
2269
- const { atoms, registry } = yield* makeTestRuntime(client);
2270
- const target = {
2271
- environmentId: TARGET.environmentId,
2272
- input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
2273
- };
2274
- registry.update(
2275
- grantedSessions(target.environmentId),
2276
- AsyncResult.map((session) => ({
2277
- ...session,
2278
- scopes: [...(session.scopes ?? []), AuthOrchestrationOperateScope],
2279
- })),
2280
- );
2281
- const query = atoms.reviewGuide(target);
2282
- registry.mount(query);
2283
- yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
2284
- const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target));
2285
- expect(result._tag).toBe("Success");
2286
- yield* refreshStarted.await;
2287
- expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted);
2288
- }),
2289
- ),
2177
+ Effect.gen(function* () {
2178
+ const accepted = {
2179
+ guide: null,
2180
+ currentHeadSha: "head",
2181
+ run: { _tag: "Running" as const, headSha: "head", startedAt: "2026-10-11T00:00:00.000Z" },
2182
+ };
2183
+ let reads = 0;
2184
+ const refreshStarted = yield* Latch.make();
2185
+ const client = {
2186
+ [WS_METHODS.pullRequestsSubscribeRefreshes]: () => Stream.never,
2187
+ [WS_METHODS.pullRequestsReviewGuide]: () =>
2188
+ Effect.gen(function* () {
2189
+ if (++reads > 1) {
2190
+ yield* refreshStarted.open;
2191
+ return yield* Effect.never;
2192
+ }
2193
+ return { guide: null, run: null, currentHeadSha: "head" };
2194
+ }),
2195
+ [WS_METHODS.pullRequestsGenerateReviewGuide]: () => Effect.succeed(accepted),
2196
+ } as unknown as WsRpcProtocolClient;
2197
+ const { atoms, registry } = yield* makeTestRuntime(client);
2198
+ const target = {
2199
+ environmentId: TARGET.environmentId,
2200
+ input: { projectId: ProjectId.make("project-1"), repository: "acme/web", number: 1 },
2201
+ };
2202
+ registry.update(
2203
+ grantedSessions(target.environmentId),
2204
+ AsyncResult.map((session) => ({
2205
+ ...session,
2206
+ scopes: [...(session.scopes ?? []), AuthOrchestrationOperateScope],
2207
+ })),
2208
+ );
2209
+ const query = atoms.reviewGuide(target);
2210
+ registry.mount(query);
2211
+ yield* AtomRegistry.getResult(registry, query, { suspendOnWaiting: true });
2212
+ const result = yield* Effect.promise(() => atoms.generateReviewGuide.run(registry, target));
2213
+ expect(result._tag).toBe("Success");
2214
+ yield* refreshStarted.await;
2215
+ expect(AsyncResult.getOrElse(registry.get(query), () => null)).toEqual(accepted);
2216
+ }),
2217
);
packages/client-runtime/src/state/runtime.test.ts
+787
-849
@@ -201,119 +201,175 @@ const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function*
201
});
202
203
it.effect("keeps complete review metadata visible while a refresh is held", () =>
204
- Effect.scoped(
204
+ Effect.gen(function* () {
205
+ const started = yield* Deferred.make<void>();
206
+ const release = yield* Deferred.make<void>();
207
+ let fullReads = 0;
208
+ const rpcSession = {
209
+ client: {
210
+ [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) =>
211
+ Effect.gen(function* () {
212
+ if (!input.trackedOnly && ++fullReads > 1) {
213
+ yield* Deferred.succeed(started, undefined);
214
+ yield* Deferred.await(release);
215
+ }
216
+ return {
217
+ cwd: input.cwd,
218
+ generatedAt: DateTime.makeUnsafe(0),
219
+ ...(input.trackedOnly ? { incomplete: true } : {}),
220
+ sources: [
221
+ {
222
+ id: "working-tree",
223
+ kind: "working-tree" as const,
224
+ title: "Uncommitted",
225
+ baseRef: "HEAD",
226
+ headRef: null,
227
+ diff: "",
228
+ diffHash: String(fullReads),
229
+ truncated: false,
230
+ patchesDeferred: true,
231
+ files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map(
232
+ (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }),
233
+ ),
234
+ },
235
+ ],
236
+ };
237
+ }),
238
+ },
239
+ } as unknown as RpcSession.RpcSession;
240
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
241
+ const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({
242
+ environmentId: QUERY_ENVIRONMENT.environmentId,
243
+ input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true },
244
+ });
245
+ const registry = yield* mountEnvironmentQuery(atom);
246
+ expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2);
247
+ registry.refresh(atom);
248
+ yield* Deferred.await(started);
249
+ yield* Effect.sync(() => {
250
+ const value = AsyncResult.getOrElse(registry.get(atom), () => null);
251
+ expect(value?.incomplete).not.toBe(true);
252
+ expect(value?.sources[0]!.files).toHaveLength(2);
253
+ }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
254
+ expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2");
255
+ }),
256
+);
257
+
258
+describe("preview event subscriptions", () => {
259
+ it.effect("delivers every open and close when RPC events arrive in batches", () =>
260
Effect.gen(function* () {
206
- const started = yield* Deferred.make<void>();
207
- const release = yield* Deferred.make<void>();
208
- let fullReads = 0;
209
- const rpcSession = {
210
- client: {
211
- [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) =>
212
- Effect.gen(function* () {
213
- if (!input.trackedOnly && ++fullReads > 1) {
214
- yield* Deferred.succeed(started, undefined);
215
- yield* Deferred.await(release);
216
- }
217
- return {
218
- cwd: input.cwd,
219
- generatedAt: DateTime.makeUnsafe(0),
220
- ...(input.trackedOnly ? { incomplete: true } : {}),
221
- sources: [
222
- {
223
- id: "working-tree",
224
- kind: "working-tree" as const,
225
- title: "Uncommitted",
226
- baseRef: "HEAD",
227
- headRef: null,
228
- diff: "",
229
- diffHash: String(fullReads),
230
- truncated: false,
231
- patchesDeferred: true,
232
- files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map(
233
- (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }),
234
- ),
235
- },
236
- ],
237
- };
238
- }),
261
+ const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
262
+ type: "opened",
263
+ threadId,
264
+ tabId: `tab-${index}`,
265
+ serverEpoch: "epoch-1",
266
+ revision: index + 1,
267
+ createdAt: "2026-10-02T00:00:00.000Z",
268
+ snapshot: {
269
+ threadId,
270
+ tabId: `tab-${index}`,
271
+ navStatus: { _tag: "Idle" },
272
+ canGoBack: false,
273
+ canGoForward: false,
274
+ updatedAt: "2026-10-02T00:00:00.000Z",
275
},
240
- } as unknown as RpcSession.RpcSession;
241
- const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession });
242
- const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({
276
+ }));
277
+ const closed: PreviewEvent[] = opened.map((event, index) => ({
278
+ type: "closed",
279
+ threadId: event.threadId,
280
+ tabId: event.tabId,
281
+ serverEpoch: event.serverEpoch,
282
+ revision: opened.length + index + 1,
283
+ createdAt: event.createdAt,
284
+ }));
285
+ const releaseEvents = yield* Deferred.make<void>();
286
+ // Each iterable is one RPC chunk; separate emissions would hide lost events.
287
+ const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
288
+ Stream.flatMap(() =>
289
+ Stream.fromIterable(opened).pipe(
290
+ Stream.concat(Stream.fromIterable(closed)),
291
+ Stream.concat(Stream.never),
292
+ ),
293
+ ),
294
+ );
295
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
296
+ rpcSession: {
297
+ client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
298
+ } as unknown as RpcSession.RpcSession,
299
+ });
300
+ const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
301
environmentId: QUERY_ENVIRONMENT.environmentId,
244
- input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true },
302
+ input: {},
303
});
246
- const registry = yield* mountEnvironmentQuery(atom);
247
- expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2);
248
- registry.refresh(atom);
249
- yield* Deferred.await(started);
250
- yield* Effect.sync(() => {
251
- const value = AsyncResult.getOrElse(registry.get(atom), () => null);
252
- expect(value?.incomplete).not.toBe(true);
253
- expect(value?.sources[0]!.files).toHaveLength(2);
254
- }).pipe(Effect.ensuring(Deferred.succeed(release, undefined)));
255
- expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2");
304
+ const registry = AtomRegistry.make();
305
+ const observed: PreviewEvent[] = [];
306
+ const sawLast = yield* Deferred.make<void>();
307
+ const unsubscribe = registry.subscribe(
308
+ atom,
309
+ (result) => {
310
+ if (!AsyncResult.isSuccess(result)) return;
311
+ observed.push(result.value);
312
+ if (result.value === closed[closed.length - 1]) {
313
+ Deferred.doneUnsafe(sawLast, Exit.void);
314
+ }
315
+ },
316
+ { immediate: true },
317
+ );
318
+ yield* Effect.addFinalizer(() =>
319
+ Effect.sync(() => {
320
+ unsubscribe();
321
+ registry.dispose();
322
+ }),
323
+ );
324
+
325
+ yield* Deferred.succeed(releaseEvents, undefined);
326
+ yield* Deferred.await(sawLast);
327
+ expect(observed).toEqual([...opened, ...closed]);
328
}),
257
- ),
258
-);
329
+ );
330
+});
331
260
-describe("preview event subscriptions", () => {
261
- it.effect("delivers every open and close when RPC events arrive in batches", () =>
262
- Effect.scoped(
332
+describe("finite environment subscription lifecycle", () => {
333
+ it.effect(
334
+ "exposes early values and settles on the terminal value without waiting for a reconnect",
335
+ () =>
336
Effect.gen(function* () {
264
- const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
265
- type: "opened",
266
- threadId,
267
- tabId: `tab-${index}`,
268
- serverEpoch: "epoch-1",
269
- revision: index + 1,
270
- createdAt: "2026-10-02T00:00:00.000Z",
271
- snapshot: {
272
- threadId,
273
- tabId: `tab-${index}`,
274
- navStatus: { _tag: "Idle" },
275
- canGoBack: false,
276
- canGoForward: false,
277
- updatedAt: "2026-10-02T00:00:00.000Z",
278
- },
279
- }));
280
- const closed: PreviewEvent[] = opened.map((event, index) => ({
281
- type: "closed",
282
- threadId: event.threadId,
283
- tabId: event.tabId,
284
- serverEpoch: event.serverEpoch,
285
- revision: opened.length + index + 1,
286
- createdAt: event.createdAt,
287
- }));
288
- const releaseEvents = yield* Deferred.make<void>();
289
- // Each iterable is one RPC chunk; separate emissions would hide lost events.
290
- const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
291
- Stream.flatMap(() =>
292
- Stream.fromIterable(opened).pipe(
293
- Stream.concat(Stream.fromIterable(closed)),
294
- Stream.concat(Stream.never),
295
- ),
337
+ const releaseFinal = yield* Deferred.make<void>();
338
+ const sawEarly = yield* Deferred.make<void>();
339
+ const sawFinal = yield* Deferred.make<void>();
340
+ const closed = yield* Deferred.make<void>();
341
+ const stream = Stream.concat(
342
+ Stream.succeed({ complete: false, count: 1 }),
343
+ Stream.fromEffect(
344
+ Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),
345
),
346
+ ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));
347
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
348
+ followStream: (_environmentId: EnvironmentId, source: typeof stream) =>
349
+ Stream.concat(source, Stream.never),
350
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
351
+ const runtime = Atom.runtime(
352
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
353
);
298
- const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
299
- rpcSession: {
300
- client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
301
- } as unknown as RpcSession.RpcSession,
302
- });
303
- const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
304
- environmentId: QUERY_ENVIRONMENT.environmentId,
305
- input: {},
354
+ const family = createEnvironmentSubscriptionAtomFamily(runtime, {
355
+ label: "test.finite-subscription",
356
+ subscribe: () => stream,
357
+ completeWhen: (value) => value.complete,
358
+ idleTtlMs: 0,
359
});
360
+ const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
361
const registry = AtomRegistry.make();
308
- const observed: PreviewEvent[] = [];
309
- const sawLast = yield* Deferred.make<void>();
362
+ const observed: Array<
363
+ AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>
364
+ > = [];
365
const unsubscribe = registry.subscribe(
366
atom,
367
(result) => {
313
- if (!AsyncResult.isSuccess(result)) return;
314
- observed.push(result.value);
315
- if (result.value === closed[closed.length - 1]) {
316
- Deferred.doneUnsafe(sawLast, Exit.void);
368
+ observed.push(result);
369
+ if (AsyncResult.isSuccess(result)) {
370
+ if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);
371
+ if (result.value.complete && !result.waiting)
372
+ Deferred.doneUnsafe(sawFinal, Exit.void);
373
}
374
},
375
{ immediate: true },
@@ -324,80 +380,18 @@ describe("preview event subscriptions", () => {
380
registry.dispose();
381
}),
382
);
327
-
328
- yield* Deferred.succeed(releaseEvents, undefined);
329
- yield* Deferred.await(sawLast);
330
- expect(observed).toEqual([...opened, ...closed]);
383
+ yield* Deferred.await(sawEarly);
384
+ const early = registry.get(atom);
385
+ expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);
386
+ expect(early.waiting).toBe(true);
387
+ yield* Deferred.succeed(releaseFinal, undefined);
388
+ yield* Deferred.await(sawFinal);
389
+ yield* Deferred.await(closed);
390
+ const final = registry.get(atom);
391
+ expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);
392
+ expect(final.waiting).toBe(false);
393
+ expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);
394
}),
332
- ),
333
- );
334
-});
335
-
336
-describe("finite environment subscription lifecycle", () => {
337
- it.effect(
338
- "exposes early values and settles on the terminal value without waiting for a reconnect",
339
- () =>
340
- Effect.scoped(
341
- Effect.gen(function* () {
342
- const releaseFinal = yield* Deferred.make<void>();
343
- const sawEarly = yield* Deferred.make<void>();
344
- const sawFinal = yield* Deferred.make<void>();
345
- const closed = yield* Deferred.make<void>();
346
- const stream = Stream.concat(
347
- Stream.succeed({ complete: false, count: 1 }),
348
- Stream.fromEffect(
349
- Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),
350
- ),
351
- ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));
352
- const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
353
- followStream: (_environmentId: EnvironmentId, source: typeof stream) =>
354
- Stream.concat(source, Stream.never),
355
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
356
- const runtime = Atom.runtime(
357
- Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
358
- );
359
- const family = createEnvironmentSubscriptionAtomFamily(runtime, {
360
- label: "test.finite-subscription",
361
- subscribe: () => stream,
362
- completeWhen: (value) => value.complete,
363
- idleTtlMs: 0,
364
- });
365
- const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
366
- const registry = AtomRegistry.make();
367
- const observed: Array<
368
- AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>
369
- > = [];
370
- const unsubscribe = registry.subscribe(
371
- atom,
372
- (result) => {
373
- observed.push(result);
374
- if (AsyncResult.isSuccess(result)) {
375
- if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);
376
- if (result.value.complete && !result.waiting)
377
- Deferred.doneUnsafe(sawFinal, Exit.void);
378
- }
379
- },
380
- { immediate: true },
381
- );
382
- yield* Effect.addFinalizer(() =>
383
- Effect.sync(() => {
384
- unsubscribe();
385
- registry.dispose();
386
- }),
387
- );
388
- yield* Deferred.await(sawEarly);
389
- const early = registry.get(atom);
390
- expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);
391
- expect(early.waiting).toBe(true);
392
- yield* Deferred.succeed(releaseFinal, undefined);
393
- yield* Deferred.await(sawFinal);
394
- yield* Deferred.await(closed);
395
- const final = registry.get(atom);
396
- expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);
397
- expect(final.waiting).toBe(false);
398
- expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);
399
- }),
400
- ),
395
);
396
it.effect.each([
397
{ completedTtlMs: undefined, subscriptions: 2 },
@@ -610,104 +604,14 @@ describe("environment query lifecycle", () => {
604
it.effect(
605
"hides a session replacement, reports the relay backoff, and recovers on reconnect",
606
() =>
613
- Effect.scoped(
614
- Effect.gen(function* () {
615
- const firstStarted = Latch.makeUnsafe();
616
- const failFirst = Latch.makeUnsafe();
617
- const firstSettled = Latch.makeUnsafe();
618
- const unavailable = new EnvironmentRpcUnavailableError({
619
- environmentId: QUERY_ENVIRONMENT.environmentId,
620
- message: "Query environment is not connected.",
621
- });
622
- let executions = 0;
623
- const execute = Effect.suspend(() => {
624
- executions += 1;
625
- if (executions > 1) {
626
- return Effect.succeed("recovered");
627
- }
628
- firstStarted.openUnsafe();
629
- return failFirst.await.pipe(
630
- Effect.andThen(Effect.fail(unavailable)),
631
- Effect.ensuring(
632
- Effect.sync(() => {
633
- firstSettled.openUnsafe();
634
- }),
635
- ),
636
- );
637
- });
638
- const harness = yield* makeEnvironmentQueryHarness(execute);
639
- const registry = AtomRegistry.make();
640
- const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
641
- const unsubscribe = registry.subscribe(
642
- harness.atom,
643
- (result) => {
644
- observed.push(result);
645
- },
646
- { immediate: true },
647
- );
648
- yield* Effect.addFinalizer(() =>
649
- Effect.sync(() => {
650
- unsubscribe();
651
- registry.dispose();
652
- }),
653
- );
654
-
655
- yield* firstStarted.await;
656
- yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
657
- yield* Effect.yieldNow;
658
- failFirst.openUnsafe();
659
- yield* firstSettled.await;
660
- yield* Effect.yieldNow;
661
-
662
- expect(observed.some(AsyncResult.isFailure)).toBe(false);
663
-
664
- yield* SubscriptionRef.set(
665
- harness.supervisorState,
666
- queryConnectionState({ phase: "connecting", stage: "preparing" }),
667
- );
668
- yield* Effect.yieldNow;
669
- const relayFailure = new ConnectionTransientError({
670
- reason: "transport",
671
- detail: "Relay session is reconnecting.",
672
- });
673
- yield* SubscriptionRef.set(
674
- harness.supervisorState,
675
- queryConnectionState({
676
- phase: "backoff",
677
- stage: null,
678
- lastFailure: relayFailure,
679
- retryAt: 1,
680
- }),
681
- );
682
- yield* Effect.yieldNow;
683
- // The query has never answered, so it reports why the environment is retrying.
684
- const backingOff = registry.get(harness.atom);
685
- expect(backingOff.waiting).toBe(false);
686
- expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
687
- relayFailure,
688
- );
689
-
690
- yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
691
- yield* SubscriptionRef.set(
692
- harness.supervisorState,
693
- queryConnectionState({ generation: 2 }),
694
- );
695
- yield* Effect.yieldNow;
696
- expect(
697
- yield* AtomRegistry.getResult(registry, harness.atom, {
698
- suspendOnWaiting: true,
699
- }),
700
- ).toBe("recovered");
701
- }),
702
- ),
703
- );
704
-
705
- it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
706
- Effect.scoped(
607
Effect.gen(function* () {
608
const firstStarted = Latch.makeUnsafe();
609
const failFirst = Latch.makeUnsafe();
610
const firstSettled = Latch.makeUnsafe();
611
+ const unavailable = new EnvironmentRpcUnavailableError({
612
+ environmentId: QUERY_ENVIRONMENT.environmentId,
613
+ message: "Query environment is not connected.",
614
+ });
615
let executions = 0;
616
const execute = Effect.suspend(() => {
617
executions += 1;
@@ -716,14 +620,7 @@ describe("environment query lifecycle", () => {
620
}
621
firstStarted.openUnsafe();
622
return failFirst.await.pipe(
719
- Effect.andThen(
720
- Effect.fail(
721
- new EnvironmentRpcUnavailableError({
722
- environmentId: QUERY_ENVIRONMENT.environmentId,
723
- message: "Query environment is not connected.",
724
- }),
725
- ),
726
- ),
623
+ Effect.andThen(Effect.fail(unavailable)),
624
Effect.ensuring(
625
Effect.sync(() => {
626
firstSettled.openUnsafe();
@@ -749,47 +646,135 @@ describe("environment query lifecycle", () => {
646
);
647
648
yield* firstStarted.await;
752
- // No yield before the failure: the request finds its session gone
753
- // before the atom has processed the session change.
649
yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
650
+ yield* Effect.yieldNow;
651
failFirst.openUnsafe();
652
yield* firstSettled.await;
653
yield* Effect.yieldNow;
654
655
expect(observed.some(AsyncResult.isFailure)).toBe(false);
656
657
+ yield* SubscriptionRef.set(
658
+ harness.supervisorState,
659
+ queryConnectionState({ phase: "connecting", stage: "preparing" }),
660
+ );
661
+ yield* Effect.yieldNow;
662
+ const relayFailure = new ConnectionTransientError({
663
+ reason: "transport",
664
+ detail: "Relay session is reconnecting.",
665
+ });
666
+ yield* SubscriptionRef.set(
667
+ harness.supervisorState,
668
+ queryConnectionState({
669
+ phase: "backoff",
670
+ stage: null,
671
+ lastFailure: relayFailure,
672
+ retryAt: 1,
673
+ }),
674
+ );
675
+ yield* Effect.yieldNow;
676
+ // The query has never answered, so it reports why the environment is retrying.
677
+ const backingOff = registry.get(harness.atom);
678
+ expect(backingOff.waiting).toBe(false);
679
+ expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe(
680
+ relayFailure,
681
+ );
682
+
683
yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
684
yield* SubscriptionRef.set(
685
harness.supervisorState,
686
queryConnectionState({ generation: 2 }),
687
);
688
+ yield* Effect.yieldNow;
689
expect(
690
yield* AtomRegistry.getResult(registry, harness.atom, {
691
suspendOnWaiting: true,
692
}),
693
).toBe("recovered");
771
- expect(observed.some(AsyncResult.isFailure)).toBe(false);
694
}),
773
- ),
695
);
696
776
- it.effect("fails a query that reports unavailable while its session is still live", () =>
777
- Effect.scoped(
778
- Effect.gen(function* () {
779
- const unavailable = new EnvironmentRpcUnavailableError({
780
- environmentId: QUERY_ENVIRONMENT.environmentId,
781
- message: "The environment did not respond to the request.",
782
- });
783
- const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
784
- const registry = yield* mountEnvironmentQuery(harness.atom);
697
+ it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
698
+ Effect.gen(function* () {
699
+ const firstStarted = Latch.makeUnsafe();
700
+ const failFirst = Latch.makeUnsafe();
701
+ const firstSettled = Latch.makeUnsafe();
702
+ let executions = 0;
703
+ const execute = Effect.suspend(() => {
704
+ executions += 1;
705
+ if (executions > 1) {
706
+ return Effect.succeed("recovered");
707
+ }
708
+ firstStarted.openUnsafe();
709
+ return failFirst.await.pipe(
710
+ Effect.andThen(
711
+ Effect.fail(
712
+ new EnvironmentRpcUnavailableError({
713
+ environmentId: QUERY_ENVIRONMENT.environmentId,
714
+ message: "Query environment is not connected.",
715
+ }),
716
+ ),
717
+ ),
718
+ Effect.ensuring(
719
+ Effect.sync(() => {
720
+ firstSettled.openUnsafe();
721
+ }),
722
+ ),
723
+ );
724
+ });
725
+ const harness = yield* makeEnvironmentQueryHarness(execute);
726
+ const registry = AtomRegistry.make();
727
+ const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
728
+ const unsubscribe = registry.subscribe(
729
+ harness.atom,
730
+ (result) => {
731
+ observed.push(result);
732
+ },
733
+ { immediate: true },
734
+ );
735
+ yield* Effect.addFinalizer(() =>
736
+ Effect.sync(() => {
737
+ unsubscribe();
738
+ registry.dispose();
739
+ }),
740
+ );
741
+
742
+ yield* firstStarted.await;
743
+ // No yield before the failure: the request finds its session gone
744
+ // before the atom has processed the session change.
745
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
746
+ failFirst.openUnsafe();
747
+ yield* firstSettled.await;
748
+ yield* Effect.yieldNow;
749
+
750
+ expect(observed.some(AsyncResult.isFailure)).toBe(false);
751
786
- const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
752
+ yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
753
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
754
+ expect(
755
+ yield* AtomRegistry.getResult(registry, harness.atom, {
756
suspendOnWaiting: true,
788
- }).pipe(Effect.exit);
757
+ }),
758
+ ).toBe("recovered");
759
+ expect(observed.some(AsyncResult.isFailure)).toBe(false);
760
+ }),
761
+ );
762
790
- expect(exit).toStrictEqual(Exit.fail(unavailable));
791
- }),
792
- ),
763
+ it.effect("fails a query that reports unavailable while its session is still live", () =>
764
+ Effect.gen(function* () {
765
+ const unavailable = new EnvironmentRpcUnavailableError({
766
+ environmentId: QUERY_ENVIRONMENT.environmentId,
767
+ message: "The environment did not respond to the request.",
768
+ });
769
+ const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
770
+ const registry = yield* mountEnvironmentQuery(harness.atom);
771
+
772
+ const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
773
+ suspendOnWaiting: true,
774
+ }).pipe(Effect.exit);
775
+
776
+ expect(exit).toStrictEqual(Exit.fail(unavailable));
777
+ }),
778
);
779
780
it.effect.each([
@@ -823,28 +808,26 @@ describe("environment query lifecycle", () => {
808
expectedFailure: BLOCKED_QUERY_FAILURE,
809
},
810
] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
826
- Effect.scoped(
827
- Effect.gen(function* () {
828
- const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
829
- const registry = yield* mountEnvironmentQuery(harness.atom);
811
+ Effect.gen(function* () {
812
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
813
+ const registry = yield* mountEnvironmentQuery(harness.atom);
814
831
- expect(
832
- yield* AtomRegistry.getResult(registry, harness.atom, {
833
- suspendOnWaiting: true,
834
- }),
835
- ).toBe("connected");
815
+ expect(
816
+ yield* AtomRegistry.getResult(registry, harness.atom, {
817
+ suspendOnWaiting: true,
818
+ }),
819
+ ).toBe("connected");
820
837
- yield* SubscriptionRef.set(harness.supervisorState, state);
838
- yield* Effect.yieldNow;
821
+ yield* SubscriptionRef.set(harness.supervisorState, state);
822
+ yield* Effect.yieldNow;
823
840
- const result = registry.get(harness.atom);
841
- expect(AsyncResult.isFailure(result)).toBe(true);
842
- expect(result.waiting).toBe(false);
843
- if (AsyncResult.isFailure(result) && expectedFailure !== null) {
844
- expect(Cause.squash(result.cause)).toBe(expectedFailure);
845
- }
846
- }),
847
- ),
824
+ const result = registry.get(harness.atom);
825
+ expect(AsyncResult.isFailure(result)).toBe(true);
826
+ expect(result.waiting).toBe(false);
827
+ if (AsyncResult.isFailure(result) && expectedFailure !== null) {
828
+ expect(Cause.squash(result.cause)).toBe(expectedFailure);
829
+ }
830
+ }),
831
);
832
833
it.effect.each([
@@ -853,459 +836,428 @@ describe("environment query lifecycle", () => {
836
] as const)(
837
"settles a query it never answered while its environment retries ($phase)",
838
(retrying) =>
856
- Effect.scoped(
857
- Effect.gen(function* () {
858
- const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
859
- initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
860
- });
861
- const registry = yield* mountEnvironmentQuery(harness.atom);
862
- yield* Effect.yieldNow;
863
-
864
- const result = registry.get(harness.atom);
865
- expect(result.waiting).toBe(false);
866
- expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
867
- OFFLINE_QUERY_FAILURE,
868
- );
869
-
870
- yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
871
- yield* Effect.yieldNow;
872
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
873
- }),
874
- ),
875
- );
876
-
877
- it.effect("a refresh started on a new session generation answers from that session", () =>
878
- Effect.scoped(
839
Effect.gen(function* () {
840
const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
881
- initialState: queryConnectionState({
882
- phase: "backoff",
883
- stage: null,
884
- lastFailure: OFFLINE_QUERY_FAILURE,
885
- retryAt: 1,
886
- }),
841
+ initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }),
842
});
843
const registry = yield* mountEnvironmentQuery(harness.atom);
889
- // Callers hold the failure a read got while the environment was retrying.
890
- const failed = yield* Effect.promise(() =>
891
- executeAtomQuery(registry, harness.atom, { reportFailure: false }),
892
- );
893
- expect(AsyncResult.isFailure(failed)).toBe(true);
894
-
895
- const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
896
- const sessionGeneration = environmentSessionGenerationAtom(
897
- harness.runtime,
898
- QUERY_ENVIRONMENT.environmentId,
899
- );
900
- const unmount = registry.mount(sessionGeneration);
901
- const unsubscribe = registry.subscribe(sessionGeneration, () => {
902
- void executeAtomQuery(registry, harness.atom, {
903
- refresh: true,
904
- reportFailure: false,
905
- }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
906
- });
907
- yield* Effect.addFinalizer(() =>
908
- Effect.sync(() => {
909
- unsubscribe();
910
- unmount();
911
- }),
912
- );
844
yield* Effect.yieldNow;
845
915
- yield* SubscriptionRef.set(
916
- harness.supervisorSession,
917
- Option.some({} as RpcSession.RpcSession),
918
- );
919
- yield* SubscriptionRef.set(
920
- harness.supervisorState,
921
- queryConnectionState({ generation: 2 }),
846
+ const result = registry.get(harness.atom);
847
+ expect(result.waiting).toBe(false);
848
+ expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe(
849
+ OFFLINE_QUERY_FAILURE,
850
);
923
- expect(yield* Deferred.await(answered)).toMatchObject({
924
- _tag: "Success",
925
- value: "connected",
926
- });
851
+
852
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
853
+ yield* Effect.yieldNow;
854
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected");
855
}),
928
- ),
856
);
857
931
- it.effect("keeps a genuine query failure settled while reconnecting", () =>
932
- Effect.scoped(
933
- Effect.gen(function* () {
934
- const expectedFailure = new TestQueryError({ message: "Query failed." });
935
- const firstStarted = Latch.makeUnsafe();
936
- const failFirst = Latch.makeUnsafe();
937
- const refreshStarted = Latch.makeUnsafe();
938
- const finishRefresh = Latch.makeUnsafe();
939
- let executions = 0;
940
- const execute = Effect.suspend(() => {
941
- executions += 1;
942
- if (executions === 1) {
943
- firstStarted.openUnsafe();
944
- return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
945
- }
946
- refreshStarted.openUnsafe();
947
- return finishRefresh.await.pipe(Effect.as("recovered"));
948
- });
949
- const harness = yield* makeEnvironmentQueryHarness(execute);
950
- const registry = yield* mountEnvironmentQuery(harness.atom);
858
+ it.effect("a refresh started on a new session generation answers from that session", () =>
859
+ Effect.gen(function* () {
860
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), {
861
+ initialState: queryConnectionState({
862
+ phase: "backoff",
863
+ stage: null,
864
+ lastFailure: OFFLINE_QUERY_FAILURE,
865
+ retryAt: 1,
866
+ }),
867
+ });
868
+ const registry = yield* mountEnvironmentQuery(harness.atom);
869
+ // Callers hold the failure a read got while the environment was retrying.
870
+ const failed = yield* Effect.promise(() =>
871
+ executeAtomQuery(registry, harness.atom, { reportFailure: false }),
872
+ );
873
+ expect(AsyncResult.isFailure(failed)).toBe(true);
874
952
- yield* firstStarted.await;
953
- failFirst.openUnsafe();
954
- const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
955
- suspendOnWaiting: true,
956
- }).pipe(Effect.exit);
957
- expect(Exit.isFailure(initial)).toBe(true);
958
- if (Exit.isFailure(initial)) {
959
- expect(Cause.squash(initial.cause)).toBe(expectedFailure);
960
- }
875
+ const answered = yield* Deferred.make<AsyncResult.AsyncResult<string, unknown>>();
876
+ const sessionGeneration = environmentSessionGenerationAtom(
877
+ harness.runtime,
878
+ QUERY_ENVIRONMENT.environmentId,
879
+ );
880
+ const unmount = registry.mount(sessionGeneration);
881
+ const unsubscribe = registry.subscribe(sessionGeneration, () => {
882
+ void executeAtomQuery(registry, harness.atom, {
883
+ refresh: true,
884
+ reportFailure: false,
885
+ }).then((result) => Deferred.doneUnsafe(answered, Effect.succeed(result)));
886
+ });
887
+ yield* Effect.addFinalizer(() =>
888
+ Effect.sync(() => {
889
+ unsubscribe();
890
+ unmount();
891
+ }),
892
+ );
893
+ yield* Effect.yieldNow;
894
962
- yield* SubscriptionRef.set(
963
- harness.supervisorState,
964
- queryConnectionState({ phase: "connecting", stage: "opening" }),
965
- );
966
- yield* Effect.yieldNow;
895
+ yield* SubscriptionRef.set(
896
+ harness.supervisorSession,
897
+ Option.some({} as RpcSession.RpcSession),
898
+ );
899
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
900
+ expect(yield* Deferred.await(answered)).toMatchObject({
901
+ _tag: "Success",
902
+ value: "connected",
903
+ });
904
+ }),
905
+ );
906
968
- const refreshing = registry.get(harness.atom);
969
- expect(AsyncResult.isFailure(refreshing)).toBe(true);
970
- expect(refreshing.waiting).toBe(true);
971
- if (AsyncResult.isFailure(refreshing)) {
972
- expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
907
+ it.effect("keeps a genuine query failure settled while reconnecting", () =>
908
+ Effect.gen(function* () {
909
+ const expectedFailure = new TestQueryError({ message: "Query failed." });
910
+ const firstStarted = Latch.makeUnsafe();
911
+ const failFirst = Latch.makeUnsafe();
912
+ const refreshStarted = Latch.makeUnsafe();
913
+ const finishRefresh = Latch.makeUnsafe();
914
+ let executions = 0;
915
+ const execute = Effect.suspend(() => {
916
+ executions += 1;
917
+ if (executions === 1) {
918
+ firstStarted.openUnsafe();
919
+ return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
920
}
974
-
975
- yield* SubscriptionRef.set(
976
- harness.supervisorState,
977
- queryConnectionState({ generation: 2 }),
978
- );
979
- yield* refreshStarted.await;
980
- finishRefresh.openUnsafe();
981
- expect(
982
- yield* AtomRegistry.getResult(registry, harness.atom, {
983
- suspendOnWaiting: true,
984
- }),
985
- ).toBe("recovered");
986
- }),
987
- ),
921
+ refreshStarted.openUnsafe();
922
+ return finishRefresh.await.pipe(Effect.as("recovered"));
923
+ });
924
+ const harness = yield* makeEnvironmentQueryHarness(execute);
925
+ const registry = yield* mountEnvironmentQuery(harness.atom);
926
+
927
+ yield* firstStarted.await;
928
+ failFirst.openUnsafe();
929
+ const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
930
+ suspendOnWaiting: true,
931
+ }).pipe(Effect.exit);
932
+ expect(Exit.isFailure(initial)).toBe(true);
933
+ if (Exit.isFailure(initial)) {
934
+ expect(Cause.squash(initial.cause)).toBe(expectedFailure);
935
+ }
936
+
937
+ yield* SubscriptionRef.set(
938
+ harness.supervisorState,
939
+ queryConnectionState({ phase: "connecting", stage: "opening" }),
940
+ );
941
+ yield* Effect.yieldNow;
942
+
943
+ const refreshing = registry.get(harness.atom);
944
+ expect(AsyncResult.isFailure(refreshing)).toBe(true);
945
+ expect(refreshing.waiting).toBe(true);
946
+ if (AsyncResult.isFailure(refreshing)) {
947
+ expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
948
+ }
949
+
950
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
951
+ yield* refreshStarted.await;
952
+ finishRefresh.openUnsafe();
953
+ expect(
954
+ yield* AtomRegistry.getResult(registry, harness.atom, {
955
+ suspendOnWaiting: true,
956
+ }),
957
+ ).toBe("recovered");
958
+ }),
959
);
960
961
it.effect("retains the last successful value while reconnecting", () =>
991
- Effect.scoped(
992
- Effect.gen(function* () {
993
- const refreshStarted = Latch.makeUnsafe();
994
- const finishRefresh = Latch.makeUnsafe();
995
- let executions = 0;
996
- const execute = Effect.suspend(() => {
997
- executions += 1;
998
- if (executions === 1) {
999
- return Effect.succeed("cached");
1000
- }
1001
- refreshStarted.openUnsafe();
1002
- return finishRefresh.await.pipe(Effect.as("updated"));
1003
- });
1004
- const harness = yield* makeEnvironmentQueryHarness(execute);
1005
- const registry = yield* mountEnvironmentQuery(harness.atom);
962
+ Effect.gen(function* () {
963
+ const refreshStarted = Latch.makeUnsafe();
964
+ const finishRefresh = Latch.makeUnsafe();
965
+ let executions = 0;
966
+ const execute = Effect.suspend(() => {
967
+ executions += 1;
968
+ if (executions === 1) {
969
+ return Effect.succeed("cached");
970
+ }
971
+ refreshStarted.openUnsafe();
972
+ return finishRefresh.await.pipe(Effect.as("updated"));
973
+ });
974
+ const harness = yield* makeEnvironmentQueryHarness(execute);
975
+ const registry = yield* mountEnvironmentQuery(harness.atom);
976
1007
- expect(
1008
- yield* AtomRegistry.getResult(registry, harness.atom, {
1009
- suspendOnWaiting: true,
1010
- }),
1011
- ).toBe("cached");
977
+ expect(
978
+ yield* AtomRegistry.getResult(registry, harness.atom, {
979
+ suspendOnWaiting: true,
980
+ }),
981
+ ).toBe("cached");
982
1013
- yield* SubscriptionRef.set(
1014
- harness.supervisorState,
1015
- queryConnectionState({ phase: "connecting", stage: "opening" }),
1016
- );
1017
- yield* Effect.yieldNow;
1018
- expect(registry.get(harness.atom)).toMatchObject({
1019
- _tag: "Success",
1020
- value: "cached",
1021
- waiting: true,
1022
- });
983
+ yield* SubscriptionRef.set(
984
+ harness.supervisorState,
985
+ queryConnectionState({ phase: "connecting", stage: "opening" }),
986
+ );
987
+ yield* Effect.yieldNow;
988
+ expect(registry.get(harness.atom)).toMatchObject({
989
+ _tag: "Success",
990
+ value: "cached",
991
+ waiting: true,
992
+ });
993
1024
- yield* SubscriptionRef.set(
1025
- harness.supervisorState,
1026
- queryConnectionState({
1027
- phase: "backoff",
1028
- stage: null,
1029
- lastFailure: new ConnectionTransientError({
1030
- reason: "transport",
1031
- detail: "Retrying.",
1032
- }),
1033
- retryAt: 1,
994
+ yield* SubscriptionRef.set(
995
+ harness.supervisorState,
996
+ queryConnectionState({
997
+ phase: "backoff",
998
+ stage: null,
999
+ lastFailure: new ConnectionTransientError({
1000
+ reason: "transport",
1001
+ detail: "Retrying.",
1002
}),
1035
- );
1036
- yield* Effect.yieldNow;
1037
- expect(registry.get(harness.atom)).toMatchObject({
1038
- _tag: "Success",
1039
- value: "cached",
1040
- waiting: true,
1041
- });
1003
+ retryAt: 1,
1004
+ }),
1005
+ );
1006
+ yield* Effect.yieldNow;
1007
+ expect(registry.get(harness.atom)).toMatchObject({
1008
+ _tag: "Success",
1009
+ value: "cached",
1010
+ waiting: true,
1011
+ });
1012
1043
- yield* SubscriptionRef.set(
1044
- harness.supervisorState,
1045
- queryConnectionState({ generation: 2 }),
1046
- );
1047
- yield* refreshStarted.await;
1048
- expect(registry.get(harness.atom)).toMatchObject({
1049
- _tag: "Success",
1050
- value: "cached",
1051
- waiting: true,
1052
- });
1013
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 }));
1014
+ yield* refreshStarted.await;
1015
+ expect(registry.get(harness.atom)).toMatchObject({
1016
+ _tag: "Success",
1017
+ value: "cached",
1018
+ waiting: true,
1019
+ });
1020
1054
- finishRefresh.openUnsafe();
1055
- expect(
1056
- yield* AtomRegistry.getResult(registry, harness.atom, {
1057
- suspendOnWaiting: true,
1058
- }),
1059
- ).toBe("updated");
1060
- }),
1061
- ),
1021
+ finishRefresh.openUnsafe();
1022
+ expect(
1023
+ yield* AtomRegistry.getResult(registry, harness.atom, {
1024
+ suspendOnWaiting: true,
1025
+ }),
1026
+ ).toBe("updated");
1027
+ }),
1028
);
1029
1030
it.effect("filesystem browse lists the directory afresh when a picker reopens it", () =>
1065
- Effect.scoped(
1066
- Effect.gen(function* () {
1067
- const harness = yield* makeEnvironmentQueryHarness(Effect.void);
1068
- const entry = (name: string): FilesystemBrowseEntry => ({
1069
- name,
1070
- fullPath: `/tmp/t3-11476-repro/${name}`,
1071
- });
1072
- let onDisk = [entry("existing")];
1073
- const client = {
1074
- [WS_METHODS.filesystemBrowse]: () =>
1075
- Effect.sync(() => ({ parentPath: "/tmp/t3-11476-repro/", entries: onDisk })),
1076
- } as unknown as RpcSession.RpcSession["client"];
1077
- yield* SubscriptionRef.set(
1078
- harness.supervisorSession,
1079
- Option.some({ ...QUERY_RPC_SESSION, client }),
1080
- );
1081
- const atom = createFilesystemEnvironmentAtoms(harness.runtime).browse({
1082
- environmentId: QUERY_ENVIRONMENT.environmentId,
1083
- input: { partialPath: "/tmp/t3-11476-repro/" },
1084
- });
1085
- const registry = AtomRegistry.make();
1086
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1087
- // Stale-while-revalidate refreshes from a task on the registry scheduler;
1088
- // queue behind it so the read sees the revalidation instead of racing it.
1089
- const afterScheduledTasks = Effect.callback<void>((resume) => {
1090
- registry.schedulerAsync.makeDispatcher().scheduleTask(() => resume(Effect.void), 0);
1091
- });
1092
- const listNames = afterScheduledTasks.pipe(
1093
- Effect.andThen(readEnvironmentQuery(registry, atom)),
1094
- Effect.map((result) => result.entries.map((browseEntry) => browseEntry.name)),
1095
- );
1031
+ Effect.gen(function* () {
1032
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void);
1033
+ const entry = (name: string): FilesystemBrowseEntry => ({
1034
+ name,
1035
+ fullPath: `/tmp/t3-11476-repro/${name}`,
1036
+ });
1037
+ let onDisk = [entry("existing")];
1038
+ const client = {
1039
+ [WS_METHODS.filesystemBrowse]: () =>
1040
+ Effect.sync(() => ({ parentPath: "/tmp/t3-11476-repro/", entries: onDisk })),
1041
+ } as unknown as RpcSession.RpcSession["client"];
1042
+ yield* SubscriptionRef.set(
1043
+ harness.supervisorSession,
1044
+ Option.some({ ...QUERY_RPC_SESSION, client }),
1045
+ );
1046
+ const atom = createFilesystemEnvironmentAtoms(harness.runtime).browse({
1047
+ environmentId: QUERY_ENVIRONMENT.environmentId,
1048
+ input: { partialPath: "/tmp/t3-11476-repro/" },
1049
+ });
1050
+ const registry = AtomRegistry.make();
1051
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1052
+ // Stale-while-revalidate refreshes from a task on the registry scheduler;
1053
+ // queue behind it so the read sees the revalidation instead of racing it.
1054
+ const afterScheduledTasks = Effect.callback<void>((resume) => {
1055
+ registry.schedulerAsync.makeDispatcher().scheduleTask(() => resume(Effect.void), 0);
1056
+ });
1057
+ const listNames = afterScheduledTasks.pipe(
1058
+ Effect.andThen(readEnvironmentQuery(registry, atom)),
1059
+ Effect.map((result) => result.entries.map((browseEntry) => browseEntry.name)),
1060
+ );
1061
1097
- const closePicker = registry.mount(atom);
1098
- expect(yield* listNames).toEqual(["existing"]);
1099
- closePicker();
1100
- // A closed picker stays closed past the registry's scheduled node
1101
- // removal; a remount within the same tick keeps the live node.
1102
- yield* afterScheduledTasks;
1062
+ const closePicker = registry.mount(atom);
1063
+ expect(yield* listNames).toEqual(["existing"]);
1064
+ closePicker();
1065
+ // A closed picker stays closed past the registry's scheduled node
1066
+ // removal; a remount within the same tick keeps the live node.
1067
+ yield* afterScheduledTasks;
1068
1104
- onDisk = [entry("created-externally"), entry("existing")];
1105
- registry.mount(atom);
1106
- expect(yield* listNames).toEqual(["created-externally", "existing"]);
1107
- }),
1108
- ),
1069
+ onDisk = [entry("created-externally"), entry("existing")];
1070
+ registry.mount(atom);
1071
+ expect(yield* listNames).toEqual(["created-externally", "existing"]);
1072
+ }),
1073
);
1074
1075
it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
1112
- Effect.scoped(
1113
- Effect.gen(function* () {
1114
- let executions = 0;
1115
- const trigger = Atom.make(0).pipe(Atom.keepAlive);
1116
- const harness = yield* makeEnvironmentQueryHarness(
1117
- Effect.sync(() => (executions += 1)),
1118
- { refreshTrigger: trigger },
1119
- );
1120
- const registry = AtomRegistry.make();
1121
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1122
- const read = readEnvironmentQuery(registry, harness.atom);
1076
+ Effect.gen(function* () {
1077
+ let executions = 0;
1078
+ const trigger = Atom.make(0).pipe(Atom.keepAlive);
1079
+ const harness = yield* makeEnvironmentQueryHarness(
1080
+ Effect.sync(() => (executions += 1)),
1081
+ { refreshTrigger: trigger },
1082
+ );
1083
+ const registry = AtomRegistry.make();
1084
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1085
+ const read = readEnvironmentQuery(registry, harness.atom);
1086
1124
- const unmount = registry.mount(harness.atom);
1125
- expect(yield* read).toBe(1);
1126
- registry.set(trigger, 1);
1127
- expect(yield* read).toBe(2);
1087
+ const unmount = registry.mount(harness.atom);
1088
+ expect(yield* read).toBe(1);
1089
+ registry.set(trigger, 1);
1090
+ expect(yield* read).toBe(2);
1091
1129
- unmount();
1130
- registry.set(trigger, 2);
1131
- registry.set(trigger, 3);
1132
- expect(executions).toBe(2);
1092
+ unmount();
1093
+ registry.set(trigger, 2);
1094
+ registry.set(trigger, 3);
1095
+ expect(executions).toBe(2);
1096
1134
- expect(yield* read).toBe(3);
1135
- }),
1136
- ),
1097
+ expect(yield* read).toBe(3);
1098
+ }),
1099
);
1100
1101
it.effect("refetches when mounted again after its stale time, while still cached", () =>
1140
- Effect.scoped(
1141
- Effect.gen(function* () {
1142
- let now = 0;
1143
- using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1144
- let contents = "before edit";
1145
- let fetches = 0;
1146
- const harness = yield* makeEnvironmentQueryHarness(
1147
- Effect.sync(() => {
1148
- fetches += 1;
1149
- return contents;
1150
- }),
1151
- );
1152
- const registry = AtomRegistry.make();
1153
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1154
- const read = readEnvironmentQuery(registry, harness.atom);
1155
- const remount = Effect.gen(function* () {
1156
- const unmount = registry.mount(harness.atom);
1157
- yield* Effect.yieldNow;
1158
- const value = yield* read;
1159
- unmount();
1160
- yield* Effect.yieldNow;
1161
- return value;
1162
- });
1102
+ Effect.gen(function* () {
1103
+ let now = 0;
1104
+ using _now = vi.spyOn(Date, "now").mockImplementation(() => now);
1105
+ let contents = "before edit";
1106
+ let fetches = 0;
1107
+ const harness = yield* makeEnvironmentQueryHarness(
1108
+ Effect.sync(() => {
1109
+ fetches += 1;
1110
+ return contents;
1111
+ }),
1112
+ );
1113
+ const registry = AtomRegistry.make();
1114
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1115
+ const read = readEnvironmentQuery(registry, harness.atom);
1116
+ const remount = Effect.gen(function* () {
1117
+ const unmount = registry.mount(harness.atom);
1118
+ yield* Effect.yieldNow;
1119
+ const value = yield* read;
1120
+ unmount();
1121
+ yield* Effect.yieldNow;
1122
+ return value;
1123
+ });
1124
1164
- expect(yield* remount).toBe("before edit");
1165
- contents = "after edit";
1125
+ expect(yield* remount).toBe("before edit");
1126
+ contents = "after edit";
1127
1167
- // Inside the harness's 60s stale time: the cached value stands.
1168
- now = 30_000;
1169
- expect(yield* remount).toBe("before edit");
1170
- expect(fetches).toBe(1);
1128
+ // Inside the harness's 60s stale time: the cached value stands.
1129
+ now = 30_000;
1130
+ expect(yield* remount).toBe("before edit");
1131
+ expect(fetches).toBe(1);
1132
1172
- // Past the stale time, well inside the default 5 minute idle TTL.
1173
- now = 61_000;
1174
- expect(yield* remount).toBe("after edit");
1175
- expect(fetches).toBe(2);
1176
- }),
1177
- ),
1133
+ // Past the stale time, well inside the default 5 minute idle TTL.
1134
+ now = 61_000;
1135
+ expect(yield* remount).toBe("after edit");
1136
+ expect(fetches).toBe(2);
1137
+ }),
1138
);
1139
1140
it.effect("keeps its cache when collected while unmounted, inside its stale time", () =>
1181
- Effect.scoped(
1182
- Effect.gen(function* () {
1183
- NodeV8.setFlagsFromString("--expose-gc");
1184
- const gc = NodeVM.runInNewContext("gc") as () => void;
1185
- using _now = vi.spyOn(Date, "now").mockReturnValue(0);
1186
- let fetches = 0;
1187
- const harness = yield* makeEnvironmentQueryHarness(
1188
- Effect.sync(() => {
1189
- fetches += 1;
1190
- return fetches;
1191
- }),
1192
- );
1193
- const registry = AtomRegistry.make();
1194
- yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1195
- // `Atom.family` holds members weakly, so the test must hold none: another environment
1196
- // than `harness.atom`'s, which the harness holds.
1197
- const environmentId = EnvironmentId.make("unheld-environment");
1198
- const query = () => harness.family({ environmentId, input: undefined });
1199
- const first = new WeakRef(query());
1200
- const remount = Effect.gen(function* () {
1201
- const unmount = registry.mount(query());
1202
- yield* Effect.yieldNow;
1203
- const value = yield* readEnvironmentQuery(registry, query());
1204
- unmount();
1205
- return value;
1206
- });
1207
- // A WeakRef target survives until the current job ends, so collect after it.
1208
- const collect = Effect.yieldNow.pipe(Effect.andThen(Effect.sync(gc)));
1209
-
1210
- expect(yield* remount).toBe(1);
1211
- yield* collect;
1212
- expect(yield* remount).toBe(1);
1213
- yield* collect;
1214
- expect(first.deref()).toBe(query());
1215
- expect(fetches).toBe(1);
1216
- }),
1217
- ),
1141
+ Effect.gen(function* () {
1142
+ NodeV8.setFlagsFromString("--expose-gc");
1143
+ const gc = NodeVM.runInNewContext("gc") as () => void;
1144
+ using _now = vi.spyOn(Date, "now").mockReturnValue(0);
1145
+ let fetches = 0;
1146
+ const harness = yield* makeEnvironmentQueryHarness(
1147
+ Effect.sync(() => {
1148
+ fetches += 1;
1149
+ return fetches;
1150
+ }),
1151
+ );
1152
+ const registry = AtomRegistry.make();
1153
+ yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
1154
+ // `Atom.family` holds members weakly, so the test must hold none: another environment
1155
+ // than `harness.atom`'s, which the harness holds.
1156
+ const environmentId = EnvironmentId.make("unheld-environment");
1157
+ const query = () => harness.family({ environmentId, input: undefined });
1158
+ const first = new WeakRef(query());
1159
+ const remount = Effect.gen(function* () {
1160
+ const unmount = registry.mount(query());
1161
+ yield* Effect.yieldNow;
1162
+ const value = yield* readEnvironmentQuery(registry, query());
1163
+ unmount();
1164
+ return value;
1165
+ });
1166
+ // A WeakRef target survives until the current job ends, so collect after it.
1167
+ const collect = Effect.yieldNow.pipe(Effect.andThen(Effect.sync(gc)));
1168
+
1169
+ expect(yield* remount).toBe(1);
1170
+ yield* collect;
1171
+ expect(yield* remount).toBe(1);
1172
+ yield* collect;
1173
+ expect(first.deref()).toBe(query());
1174
+ expect(fetches).toBe(1);
1175
+ }),
1176
);
1177
1178
it.effect.each([true, false])("loads thread link metadata with server support %s", (supported) =>
1221
- Effect.scoped(
1222
- Effect.gen(function* () {
1223
- const projectId = ProjectId.make("project");
1224
- const tag = supported
1225
- ? ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata
1226
- : ORCHESTRATION_V2_WS_METHODS.getThreadTitles;
1227
- const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1228
- rpcSession: {
1229
- initialConfig: Effect.succeed({ threadLinkMetadata: supported }),
1230
- client: {
1231
- [tag]: () =>
1232
- Effect.succeed(
1233
- supported ? { fork: { title: "Fork", projectId } } : { fork: "Fork" },
1234
- ),
1235
- },
1236
- } as unknown as RpcSession.RpcSession,
1237
- });
1238
- const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1239
- EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1240
- >;
1241
- const atom = createOrchestrationEnvironmentAtoms(runtime).threadLinkMetadata({
1242
- environmentId: QUERY_ENVIRONMENT.environmentId,
1243
- input: { threadIds: [ThreadId.make("fork")] },
1244
- });
1245
- const registry = yield* mountEnvironmentQuery(atom);
1246
- expect(yield* readEnvironmentQuery(registry, atom)).toEqual({
1247
- fork: { title: "Fork", projectId: supported ? projectId : null },
1248
- });
1249
- }),
1250
- ),
1179
+ Effect.gen(function* () {
1180
+ const projectId = ProjectId.make("project");
1181
+ const tag = supported
1182
+ ? ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata
1183
+ : ORCHESTRATION_V2_WS_METHODS.getThreadTitles;
1184
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1185
+ rpcSession: {
1186
+ initialConfig: Effect.succeed({ threadLinkMetadata: supported }),
1187
+ client: {
1188
+ [tag]: () =>
1189
+ Effect.succeed(supported ? { fork: { title: "Fork", projectId } } : { fork: "Fork" }),
1190
+ },
1191
+ } as unknown as RpcSession.RpcSession,
1192
+ });
1193
+ const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1194
+ EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1195
+ >;
1196
+ const atom = createOrchestrationEnvironmentAtoms(runtime).threadLinkMetadata({
1197
+ environmentId: QUERY_ENVIRONMENT.environmentId,
1198
+ input: { threadIds: [ThreadId.make("fork")] },
1199
+ });
1200
+ const registry = yield* mountEnvironmentQuery(atom);
1201
+ expect(yield* readEnvironmentQuery(registry, atom)).toEqual({
1202
+ fork: { title: "Fork", projectId: supported ? projectId : null },
1203
+ });
1204
+ }),
1205
);
1206
1207
it.effect("re-checks thread titles when one of their threads leaves the shell", () =>
1254
- Effect.scoped(
1255
- Effect.gen(function* () {
1256
- const requests = yield* Queue.unbounded<Deferred.Deferred<Record<string, string>>>();
1257
- const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1258
- rpcSession: {
1259
- client: {
1260
- [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: () =>
1261
- Effect.gen(function* () {
1262
- const answer = yield* Deferred.make<Record<string, string>>();
1263
- yield* Queue.offer(requests, answer);
1264
- return yield* Deferred.await(answer);
1265
- }),
1266
- },
1267
- } as unknown as RpcSession.RpcSession,
1268
- });
1269
- const shellState = Atom.make<Pick<EnvironmentShellState, "removedAt">>({
1270
- removedAt: new Map(),
1271
- }).pipe(Atom.keepAlive);
1272
- const removed = (entries: ReadonlyArray<readonly [string, number]>) => ({
1273
- removedAt: new Map(entries.map(([id, sequence]) => [ThreadId.make(id), sequence])),
1274
- });
1275
- // Thread titles never use the HTTP client.
1276
- const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1277
- EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1278
- >;
1279
- const atom = createOrchestrationEnvironmentAtoms(runtime, {
1280
- shellState: () => shellState,
1281
- }).threadTitles({
1282
- environmentId: QUERY_ENVIRONMENT.environmentId,
1283
- input: { threadIds: [ThreadId.make("fork")] },
1284
- });
1285
- const registry = yield* mountEnvironmentQuery(atom);
1286
- const settled: Array<Record<string, string>> = [];
1287
- const unsubscribe = registry.subscribe(atom, (result) => {
1288
- if (AsyncResult.isSuccess(result) && !result.waiting) settled.push(result.value);
1289
- });
1290
- yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1291
-
1292
- yield* Deferred.succeed(yield* Queue.take(requests), { fork: "Fork" });
1293
- expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: "Fork" });
1294
-
1295
- registry.set(shellState, removed([["other", 5]]));
1296
- expect(registry.get(atom).waiting).toBe(false);
1297
-
1298
- // Archiving and then deleting the fork both remove it from the shell.
1299
- registry.set(shellState, removed([["fork", 6]]));
1300
- const beforeDelete = yield* Queue.take(requests);
1301
- registry.set(shellState, removed([["fork", 7]]));
1302
- const afterDelete = yield* Queue.take(requests);
1303
- yield* Deferred.succeed(beforeDelete, { fork: "Fork" });
1304
- yield* Deferred.succeed(afterDelete, {});
1305
- expect(yield* readEnvironmentQuery(registry, atom)).toEqual({});
1306
- expect(settled).toEqual([{ fork: "Fork" }, {}]);
1307
- }),
1308
- ),
1208
+ Effect.gen(function* () {
1209
+ const requests = yield* Queue.unbounded<Deferred.Deferred<Record<string, string>>>();
1210
+ const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
1211
+ rpcSession: {
1212
+ client: {
1213
+ [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: () =>
1214
+ Effect.gen(function* () {
1215
+ const answer = yield* Deferred.make<Record<string, string>>();
1216
+ yield* Queue.offer(requests, answer);
1217
+ return yield* Deferred.await(answer);
1218
+ }),
1219
+ },
1220
+ } as unknown as RpcSession.RpcSession,
1221
+ });
1222
+ const shellState = Atom.make<Pick<EnvironmentShellState, "removedAt">>({
1223
+ removedAt: new Map(),
1224
+ }).pipe(Atom.keepAlive);
1225
+ const removed = (entries: ReadonlyArray<readonly [string, number]>) => ({
1226
+ removedAt: new Map(entries.map(([id, sequence]) => [ThreadId.make(id), sequence])),
1227
+ });
1228
+ // Thread titles never use the HTTP client.
1229
+ const runtime = harness.runtime as unknown as Atom.AtomRuntime<
1230
+ EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient
1231
+ >;
1232
+ const atom = createOrchestrationEnvironmentAtoms(runtime, {
1233
+ shellState: () => shellState,
1234
+ }).threadTitles({
1235
+ environmentId: QUERY_ENVIRONMENT.environmentId,
1236
+ input: { threadIds: [ThreadId.make("fork")] },
1237
+ });
1238
+ const registry = yield* mountEnvironmentQuery(atom);
1239
+ const settled: Array<Record<string, string>> = [];
1240
+ const unsubscribe = registry.subscribe(atom, (result) => {
1241
+ if (AsyncResult.isSuccess(result) && !result.waiting) settled.push(result.value);
1242
+ });
1243
+ yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1244
+
1245
+ yield* Deferred.succeed(yield* Queue.take(requests), { fork: "Fork" });
1246
+ expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: "Fork" });
1247
+
1248
+ registry.set(shellState, removed([["other", 5]]));
1249
+ expect(registry.get(atom).waiting).toBe(false);
1250
+
1251
+ // Archiving and then deleting the fork both remove it from the shell.
1252
+ registry.set(shellState, removed([["fork", 6]]));
1253
+ const beforeDelete = yield* Queue.take(requests);
1254
+ registry.set(shellState, removed([["fork", 7]]));
1255
+ const afterDelete = yield* Queue.take(requests);
1256
+ yield* Deferred.succeed(beforeDelete, { fork: "Fork" });
1257
+ yield* Deferred.succeed(afterDelete, {});
1258
+ expect(yield* readEnvironmentQuery(registry, atom)).toEqual({});
1259
+ expect(settled).toEqual([{ fork: "Fork" }, {}]);
1260
+ }),
1261
);
1262
});
1263
@@ -1563,156 +1515,142 @@ describe("runtime command runner", () => {
1515
1516
describe("persisted environment queries", () => {
1517
it.effect("keeps an in-memory cached page pending until revalidation settles", () =>
1566
- Effect.scoped(
1567
- Effect.gen(function* () {
1568
- const refreshStarted = Latch.makeUnsafe();
1569
- const finishRefresh = Latch.makeUnsafe();
1570
- let executions = 0;
1571
- const harness = yield* makeEnvironmentQueryHarness(
1572
- Effect.suspend(() => {
1573
- if (++executions === 1) return Effect.succeed("cached");
1574
- refreshStarted.openUnsafe();
1575
- return finishRefresh.await.pipe(Effect.as("fresh"));
1576
- }),
1577
- { persistence: { load: () => Effect.succeedNone, save: () => Effect.void } },
1578
- );
1579
- const registry = yield* mountEnvironmentQuery(harness.atom);
1580
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1581
- registry.refresh(harness.atom);
1582
- yield* refreshStarted.await;
1583
- expect(registry.get(harness.atom)).toMatchObject({
1584
- _tag: "Success",
1585
- value: "cached",
1586
- waiting: true,
1587
- });
1588
- finishRefresh.openUnsafe();
1589
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1590
- }),
1591
- ),
1518
+ Effect.gen(function* () {
1519
+ const refreshStarted = Latch.makeUnsafe();
1520
+ const finishRefresh = Latch.makeUnsafe();
1521
+ let executions = 0;
1522
+ const harness = yield* makeEnvironmentQueryHarness(
1523
+ Effect.suspend(() => {
1524
+ if (++executions === 1) return Effect.succeed("cached");
1525
+ refreshStarted.openUnsafe();
1526
+ return finishRefresh.await.pipe(Effect.as("fresh"));
1527
+ }),
1528
+ { persistence: { load: () => Effect.succeedNone, save: () => Effect.void } },
1529
+ );
1530
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1531
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1532
+ registry.refresh(harness.atom);
1533
+ yield* refreshStarted.await;
1534
+ expect(registry.get(harness.atom)).toMatchObject({
1535
+ _tag: "Success",
1536
+ value: "cached",
1537
+ waiting: true,
1538
+ });
1539
+ finishRefresh.openUnsafe();
1540
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1541
+ }),
1542
);
1543
1544
it.effect(
1545
"restores cached data in a new registry while offline, then refreshes on reconnect",
1546
() =>
1597
- Effect.scoped(
1598
- Effect.gen(function* () {
1599
- let saved = Option.none<string>();
1600
- const saves = yield* Queue.unbounded<string>();
1601
- const persistence: QueryPersistence<string> = {
1602
- load: () => Effect.sync(() => saved),
1603
- save: (_environmentId, _key, value) =>
1604
- Effect.sync(() => {
1605
- saved = Option.some(value);
1606
- }).pipe(Effect.andThen(Queue.offer(saves, value))),
1607
- };
1608
- const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1609
- persistence,
1610
- });
1611
- const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1612
- expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1613
- expect(yield* Queue.take(saves)).toBe("first");
1614
-
1615
- const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1616
- persistence,
1617
- initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1618
- });
1619
- const registry = yield* mountEnvironmentQuery(restarted.atom);
1620
- expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1621
- yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1622
- yield* Effect.yieldNow;
1623
- expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1624
- expect(yield* Queue.take(saves)).toBe("updated");
1625
- }),
1626
- ),
1627
- );
1628
-
1629
- it.effect("answers readers while its save is pending, and ends the save with the query", () =>
1630
- Effect.scoped(
1547
Effect.gen(function* () {
1632
- const saveEnded = Latch.makeUnsafe();
1633
- const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
1634
- persistence: {
1635
- load: () => Effect.succeedNone,
1636
- // The registry's scheduler stops on dispose, so signal synchronously.
1637
- save: () =>
1638
- Effect.never.pipe(
1639
- Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe())),
1640
- ),
1641
- },
1548
+ let saved = Option.none<string>();
1549
+ const saves = yield* Queue.unbounded<string>();
1550
+ const persistence: QueryPersistence<string> = {
1551
+ load: () => Effect.sync(() => saved),
1552
+ save: (_environmentId, _key, value) =>
1553
+ Effect.sync(() => {
1554
+ saved = Option.some(value);
1555
+ }).pipe(Effect.andThen(Queue.offer(saves, value))),
1556
+ };
1557
+ const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1558
+ persistence,
1559
});
1643
- yield* Effect.scoped(
1644
- Effect.gen(function* () {
1645
- const registry = yield* mountEnvironmentQuery(harness.atom);
1646
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1647
- }),
1648
- );
1649
- yield* saveEnded.await;
1560
+ const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1561
+ expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1562
+ expect(yield* Queue.take(saves)).toBe("first");
1563
+
1564
+ const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1565
+ persistence,
1566
+ initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1567
+ });
1568
+ const registry = yield* mountEnvironmentQuery(restarted.atom);
1569
+ expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1570
+ yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1571
+ yield* Effect.yieldNow;
1572
+ expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1573
+ expect(yield* Queue.take(saves)).toBe("updated");
1574
}),
1651
- ),
1575
+ );
1576
+
1577
+ it.effect("answers readers while its save is pending, and ends the save with the query", () =>
1578
+ Effect.gen(function* () {
1579
+ const saveEnded = Latch.makeUnsafe();
1580
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), {
1581
+ persistence: {
1582
+ load: () => Effect.succeedNone,
1583
+ // The registry's scheduler stops on dispose, so signal synchronously.
1584
+ save: () =>
1585
+ Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe()))),
1586
+ },
1587
+ });
1588
+ yield* Effect.scoped(
1589
+ Effect.gen(function* () {
1590
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1591
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1592
+ }),
1593
+ );
1594
+ yield* saveEnded.await;
1595
+ }),
1596
);
1597
1598
it.effect("hands each server answer to onAnswer before readers see it", () =>
1655
- Effect.scoped(
1656
- Effect.gen(function* () {
1657
- const answers: Array<readonly [string, string | null]> = [];
1658
- let served = 0;
1659
- const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1660
- const harness = yield* makeEnvironmentQueryHarness(
1661
- Effect.sync(() => `answer-${++served}`),
1662
- {
1663
- onAnswer: (_target, value, registry) =>
1664
- Effect.sync(() => {
1665
- answers.push([value, registry.get(recorded)]);
1666
- registry.set(recorded, value);
1667
- }),
1668
- },
1669
- );
1670
- const registry = yield* mountEnvironmentQuery(harness.atom);
1671
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1672
- expect(registry.get(recorded)).toBe("answer-1");
1673
- registry.refresh(harness.atom);
1674
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1675
- expect(answers).toEqual([
1676
- ["answer-1", null],
1677
- ["answer-2", "answer-1"],
1678
- ]);
1679
- }),
1680
- ),
1599
+ Effect.gen(function* () {
1600
+ const answers: Array<readonly [string, string | null]> = [];
1601
+ let served = 0;
1602
+ const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1603
+ const harness = yield* makeEnvironmentQueryHarness(
1604
+ Effect.sync(() => `answer-${++served}`),
1605
+ {
1606
+ onAnswer: (_target, value, registry) =>
1607
+ Effect.sync(() => {
1608
+ answers.push([value, registry.get(recorded)]);
1609
+ registry.set(recorded, value);
1610
+ }),
1611
+ },
1612
+ );
1613
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1614
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1615
+ expect(registry.get(recorded)).toBe("answer-1");
1616
+ registry.refresh(harness.atom);
1617
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1618
+ expect(answers).toEqual([
1619
+ ["answer-1", null],
1620
+ ["answer-2", "answer-1"],
1621
+ ]);
1622
+ }),
1623
);
1624
1625
it.effect("does not hand a value restored from persistence to onAnswer", () =>
1684
- Effect.scoped(
1685
- Effect.gen(function* () {
1686
- const answers: Array<string> = [];
1687
- const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1688
- persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1689
- initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1690
- onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1691
- });
1692
- const registry = yield* mountEnvironmentQuery(harness.atom);
1693
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1694
- expect(answers).toEqual([]);
1695
- yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1696
- yield* Effect.yieldNow;
1697
- expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1698
- expect(answers).toEqual(["server"]);
1699
- }),
1700
- ),
1626
+ Effect.gen(function* () {
1627
+ const answers: Array<string> = [];
1628
+ const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1629
+ persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1630
+ initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1631
+ onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1632
+ });
1633
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1634
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1635
+ expect(answers).toEqual([]);
1636
+ yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1637
+ yield* Effect.yieldNow;
1638
+ expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1639
+ expect(answers).toEqual(["server"]);
1640
+ }),
1641
);
1642
1643
it.effect("keeps cached content available when revalidation fails", () =>
1704
- Effect.scoped(
1705
- Effect.gen(function* () {
1706
- const harness = yield* makeEnvironmentQueryHarness(
1707
- Effect.fail(new TestQueryError({ message: "failed" })),
1708
- {
1709
- persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1710
- },
1711
- );
1712
- const registry = yield* mountEnvironmentQuery(harness.atom);
1713
- yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1714
- expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached");
1715
- }),
1716
- ),
1644
+ Effect.gen(function* () {
1645
+ const harness = yield* makeEnvironmentQueryHarness(
1646
+ Effect.fail(new TestQueryError({ message: "failed" })),
1647
+ {
1648
+ persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1649
+ },
1650
+ );
1651
+ const registry = yield* mountEnvironmentQuery(harness.atom);
1652
+ yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1653
+ expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached");
1654
+ }),
1655
);
1656
});
packages/client-runtime/src/state/server.test.ts
+58
-70
@@ -393,7 +393,7 @@ describe("accepted server update recovery", () => {
393
expect(registry.get(serverUpdateStateAtom(TARGET.environmentId))).toEqual({
394
status: "idle",
395
});
396
- }).pipe(Effect.scoped),
396
+ }),
397
);
398
});
399
@@ -1597,96 +1597,84 @@ describe("launcher update resume", () => {
1597
};
1598
1599
it.effect("fails promptly when a server the launcher did not start comes back", () =>
1600
- Effect.scoped(
1600
+ Effect.gen(function* () {
1601
+ const update = yield* launchUpdate({
1602
+ accepting: Stream.make(ACCEPTING),
1603
+ resumed: after("1 second", ACCEPTING).pipe(Stream.concat(after("1 minute", REPLACEMENT))),
1604
+ });
1605
+ yield* update.resumeSubscribed;
1606
+
1607
+ yield* TestClock.adjust("1 second");
1608
+ expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1609
+ yield* TestClock.adjust("1 minute");
1610
+ expect(update.state()).toEqual(UNCOMMITTED_RESUME);
1611
+ }),
1612
+ );
1613
+
1614
+ it.effect(
1615
+ "fails promptly when the accepting server's replay arrives after a quick acknowledgement",
1616
+ () =>
1617
Effect.gen(function* () {
1618
const update = yield* launchUpdate({
1603
- accepting: Stream.make(ACCEPTING),
1604
- resumed: after("1 second", ACCEPTING).pipe(Stream.concat(after("1 minute", REPLACEMENT))),
1619
+ accepting: after("3 seconds", ACCEPTING),
1620
+ resumed: after("1 second", REPLACEMENT),
1621
});
1622
+ yield* update.started;
1623
+ yield* TestClock.adjust("3 seconds");
1624
yield* update.resumeSubscribed;
1625
1608
- yield* TestClock.adjust("1 second");
1609
- expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1626
yield* TestClock.adjust("1 minute");
1627
expect(update.state()).toEqual(UNCOMMITTED_RESUME);
1628
}),
1613
- ),
1614
- );
1615
-
1616
- it.effect(
1617
- "fails promptly when the accepting server's replay arrives after a quick acknowledgement",
1618
- () =>
1619
- Effect.scoped(
1620
- Effect.gen(function* () {
1621
- const update = yield* launchUpdate({
1622
- accepting: after("3 seconds", ACCEPTING),
1623
- resumed: after("1 second", REPLACEMENT),
1624
- });
1625
- yield* update.started;
1626
- yield* TestClock.adjust("3 seconds");
1627
- yield* update.resumeSubscribed;
1628
-
1629
- yield* TestClock.adjust("1 minute");
1630
- expect(update.state()).toEqual(UNCOMMITTED_RESUME);
1631
- }),
1632
- ),
1629
);
1630
1631
it.effect(
1632
"waits for this update's outcome when a reconnect lands between the baseline and the request",
1633
() =>
1638
- Effect.scoped(
1639
- Effect.gen(function* () {
1640
- const update = yield* launchUpdate({
1641
- reconnectAfterBaseline: true,
1642
- accepting: Stream.make(ACCEPTING),
1643
- // The process that accepted the update over the new session replays its own ready first.
1644
- resumed: after("1 second", ready("2026-08-01T00:01:00.000Z", "0.0.30")).pipe(
1645
- Stream.concat(
1646
- after(
1647
- "1 minute",
1648
- ready(
1649
- "2026-08-01T00:05:00.000Z",
1650
- "0.0.31",
1651
- committed("update-1", "0.0.30", "0.0.31"),
1652
- ),
1634
+ Effect.gen(function* () {
1635
+ const update = yield* launchUpdate({
1636
+ reconnectAfterBaseline: true,
1637
+ accepting: Stream.make(ACCEPTING),
1638
+ // The process that accepted the update over the new session replays its own ready first.
1639
+ resumed: after("1 second", ready("2026-08-01T00:01:00.000Z", "0.0.30")).pipe(
1640
+ Stream.concat(
1641
+ after(
1642
+ "1 minute",
1643
+ ready(
1644
+ "2026-08-01T00:05:00.000Z",
1645
+ "0.0.31",
1646
+ committed("update-1", "0.0.30", "0.0.31"),
1647
),
1648
),
1649
),
1656
- });
1657
- yield* update.resumeSubscribed;
1650
+ ),
1651
+ });
1652
+ yield* update.resumeSubscribed;
1653
1659
- yield* TestClock.adjust("1 second");
1660
- expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1661
- yield* TestClock.adjust("1 minute");
1662
- expect(update.state()).toMatchObject({ status: "idle" });
1663
- }),
1664
- ),
1654
+ yield* TestClock.adjust("1 second");
1655
+ expect(update.state()).toMatchObject({ status: "running", stage: "resuming" });
1656
+ yield* TestClock.adjust("1 minute");
1657
+ expect(update.state()).toMatchObject({ status: "idle" });
1658
+ }),
1659
);
1660
1661
it.effect(
1662
"sends the update without a baseline when the accepting server never replays ready",
1663
() =>
1670
- Effect.scoped(
1671
- Effect.gen(function* () {
1672
- const update = yield* launchUpdate({
1673
- accepting: Stream.never,
1674
- resumed: after(
1675
- "1 second",
1676
- ready(
1677
- "2026-08-01T00:05:00.000Z",
1678
- "0.0.31",
1679
- committed("update-1", "0.0.30", "0.0.31"),
1680
- ),
1681
- ),
1682
- });
1683
- yield* update.started;
1664
+ Effect.gen(function* () {
1665
+ const update = yield* launchUpdate({
1666
+ accepting: Stream.never,
1667
+ resumed: after(
1668
+ "1 second",
1669
+ ready("2026-08-01T00:05:00.000Z", "0.0.31", committed("update-1", "0.0.30", "0.0.31")),
1670
+ ),
1671
+ });
1672
+ yield* update.started;
1673
1685
- yield* TestClock.adjust("5 seconds");
1686
- yield* TestClock.adjust("1 second");
1687
- expect(update.state()).toMatchObject({ status: "idle" });
1688
- }),
1689
- ),
1674
+ yield* TestClock.adjust("5 seconds");
1675
+ yield* TestClock.adjust("1 second");
1676
+ expect(update.state()).toMatchObject({ status: "idle" });
1677
+ }),
1678
);
1679
});
1680
@@ -1768,7 +1756,7 @@ describe("provider setup commands", () => {
1756
value: { driver: "antigravity" },
1757
});
1758
expect(yield* Queue.takeAll(requested)).toEqual(["antigravity"]);
1771
- }).pipe(Effect.scoped),
1759
+ }),
1760
);
1761
1762
it.effect("toggles a provider while another provider's update is still running", () =>
@@ -1840,7 +1828,7 @@ describe("provider setup commands", () => {
1828
);
1829
yield* TestClock.adjust(Duration.seconds(1));
1830
expect(yield* Fiber.join(saved)).toBe(true);
1843
- }).pipe(Effect.scoped),
1831
+ }),
1832
);
1833
});
1834
packages/client-runtime/src/state/serverUsage.test.ts
+66
-74
@@ -260,84 +260,76 @@ function waitForCost<E>(
260
}
261
262
it.effect("restarts a pending usage read after a price change", () =>
263
- Effect.scoped(
264
- Effect.gen(function* () {
265
- const started = yield* Deferred.make<void>();
266
- const interrupted = yield* Deferred.make<void>();
267
- const harness = yield* makeHarness((request) =>
268
- request === 1
269
- ? Deferred.succeed(started, undefined).pipe(
270
- Effect.andThen(Effect.never),
271
- Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
272
- )
273
- : Effect.void,
274
- );
275
- const summary = harness.summary();
276
- const unmount = harness.registry.mount(summary);
277
- yield* Deferred.await(started);
278
- yield* harness.updateSettings({
279
- ...DEFAULT_SERVER_SETTINGS,
280
- usagePriceOverrides: {
281
- "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
282
- },
283
- });
284
- yield* waitForCost(harness.registry, summary, 5);
285
- yield* Deferred.await(interrupted);
286
- expect(harness.requests()).toBe(2);
287
- unmount();
288
- }),
289
- ),
263
+ Effect.gen(function* () {
264
+ const started = yield* Deferred.make<void>();
265
+ const interrupted = yield* Deferred.make<void>();
266
+ const harness = yield* makeHarness((request) =>
267
+ request === 1
268
+ ? Deferred.succeed(started, undefined).pipe(
269
+ Effect.andThen(Effect.never),
270
+ Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)),
271
+ )
272
+ : Effect.void,
273
+ );
274
+ const summary = harness.summary();
275
+ const unmount = harness.registry.mount(summary);
276
+ yield* Deferred.await(started);
277
+ yield* harness.updateSettings({
278
+ ...DEFAULT_SERVER_SETTINGS,
279
+ usagePriceOverrides: {
280
+ "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
281
+ },
282
+ });
283
+ yield* waitForCost(harness.registry, summary, 5);
284
+ yield* Deferred.await(interrupted);
285
+ expect(harness.requests()).toBe(2);
286
+ unmount();
287
+ }),
288
);
289
290
it.effect("keeps the cached usage summary when the awaited refresh fails", () =>
293
- Effect.scoped(
294
- Effect.gen(function* () {
295
- const harness = yield* makeRefreshingHarness(
296
- Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "Cursor is down" })),
297
- );
298
- const summary = harness.summary();
299
- const unmount = harness.registry.mount(summary);
300
- expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
301
- cursorSource(true),
302
- ]);
303
- expect(AsyncResult.isSuccess(harness.registry.get(summary))).toBe(true);
304
- // The saved answer is followed by a plain read before the one that waits for Cursor.
305
- expect(
306
- harness.inputs().map(({ provisional, awaitRefresh }) => ({ provisional, awaitRefresh })),
307
- ).toEqual([
308
- { provisional: true, awaitRefresh: undefined },
309
- { provisional: undefined, awaitRefresh: undefined },
310
- { provisional: undefined, awaitRefresh: true },
311
- ]);
312
- // With figures on screen, a refresh reads them exactly instead of asking for saved ones.
313
- yield* harness.updateSettings({
314
- ...DEFAULT_SERVER_SETTINGS,
315
- usagePriceOverrides: {
316
- "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
317
- },
318
- });
319
- yield* waitForCost(harness.registry, summary, 5);
320
- expect(harness.inputs()[3]?.provisional).toBeUndefined();
321
- unmount();
322
- }),
323
- ),
291
+ Effect.gen(function* () {
292
+ const harness = yield* makeRefreshingHarness(
293
+ Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "Cursor is down" })),
294
+ );
295
+ const summary = harness.summary();
296
+ const unmount = harness.registry.mount(summary);
297
+ expect((yield* settledSummary(harness.registry, summary)).sources).toEqual([
298
+ cursorSource(true),
299
+ ]);
300
+ expect(AsyncResult.isSuccess(harness.registry.get(summary))).toBe(true);
301
+ // The saved answer is followed by a plain read before the one that waits for Cursor.
302
+ expect(
303
+ harness.inputs().map(({ provisional, awaitRefresh }) => ({ provisional, awaitRefresh })),
304
+ ).toEqual([
305
+ { provisional: true, awaitRefresh: undefined },
306
+ { provisional: undefined, awaitRefresh: undefined },
307
+ { provisional: undefined, awaitRefresh: true },
308
+ ]);
309
+ // With figures on screen, a refresh reads them exactly instead of asking for saved ones.
310
+ yield* harness.updateSettings({
311
+ ...DEFAULT_SERVER_SETTINGS,
312
+ usagePriceOverrides: {
313
+ "custom-model": { inputCostPerMillionTokens: 5, outputCostPerMillionTokens: 10 },
314
+ },
315
+ });
316
+ yield* waitForCost(harness.registry, summary, 5);
317
+ expect(harness.inputs()[3]?.provisional).toBeUndefined();
318
+ unmount();
319
+ }),
320
);
321
322
it.effect("reads usage in full when the saved answer cannot be read", () =>
327
- Effect.scoped(
328
- Effect.gen(function* () {
329
- const harness = yield* makeHarness((_request, input) =>
330
- input.provisional === true
331
- ? Effect.fail(
332
- new UsageReadError({ reason: "scanFailed", detail: "saved scan unreadable" }),
333
- )
334
- : Effect.void,
335
- );
336
- const summary = harness.summary();
337
- const unmount = harness.registry.mount(summary);
338
- yield* settledSummary(harness.registry, summary);
339
- expect(harness.inputs().map(({ provisional }) => provisional)).toEqual([true, undefined]);
340
- unmount();
341
- }),
342
- ),
323
+ Effect.gen(function* () {
324
+ const harness = yield* makeHarness((_request, input) =>
325
+ input.provisional === true
326
+ ? Effect.fail(new UsageReadError({ reason: "scanFailed", detail: "saved scan unreadable" }))
327
+ : Effect.void,
328
+ );
329
+ const summary = harness.summary();
330
+ const unmount = harness.registry.mount(summary);
331
+ yield* settledSummary(harness.registry, summary);
332
+ expect(harness.inputs().map(({ provisional }) => provisional)).toEqual([true, undefined]);
333
+ unmount();
334
+ }),
335
);
packages/client-runtime/src/state/shell-sync.test.ts
+1
-1
@@ -308,7 +308,7 @@ describe("environment shell synchronization", () => {
308
expect(Option.getOrThrow(resetState.snapshot).threads).toEqual([
309
{ ...resetRow, title: "After completion" },
310
]);
311
- }).pipe(Effect.scoped),
311
+ }),
312
);
313
314
it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>
packages/client-runtime/src/state/threadFamilies.test.ts
+107
-109
@@ -119,118 +119,116 @@ describe("createThreadFamilyAtoms", () => {
119
});
120
121
it.effect("reads a family per shell generation and retries a failed read", () =>
122
- Effect.scoped(
123
- Effect.gen(function* () {
124
- const replies =
125
- yield* Queue.unbounded<
126
- Effect.Effect<OrchestrationV2ThreadFamily, OrchestrationV2GetShellSnapshotError>
127
- >();
128
- const client = {
129
- [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: () => Effect.flatten(Queue.take(replies)),
130
- } as unknown as WsRpcProtocolClient;
131
- const session = {
132
- client,
133
- initialConfig: Effect.succeed({ shellThreadFamilies: true } as never),
134
- ready: Effect.void,
135
- probe: Effect.void,
136
- closed: Effect.never,
137
- } as unknown as RpcSession.RpcSession;
138
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
139
- target: TARGET,
140
- state: yield* SubscriptionRef.make<SupervisorConnectionState>({
141
- ...AVAILABLE_CONNECTION_STATE,
142
- desired: true,
143
- network: "online",
144
- phase: "connected",
145
- attempt: 1,
146
- generation: 1,
147
- }),
148
- session: yield* SubscriptionRef.make(Option.some(session)),
149
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
150
- connect: Effect.void,
151
- disconnect: Effect.void,
152
- retryNow: Effect.void,
153
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
154
- const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
155
- _environmentId,
156
- effect,
157
- ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
158
- const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
159
- _environmentId,
160
- stream,
161
- ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
162
- const runtime = Atom.runtime(
163
- Layer.succeed(
164
- EnvironmentRegistry.EnvironmentRegistry,
165
- EnvironmentRegistry.EnvironmentRegistry.of({
166
- run,
167
- followStream,
168
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
169
- ),
170
- );
171
- const parent = row("parent");
172
- const child = row("idle-child");
173
- const shellSnapshot = {
174
- schemaVersion: 1,
175
- snapshotSequence: 3,
176
- projects: [],
177
- threads: [parent],
178
- archivedThreads: [],
179
- } as OrchestrationV2ShellSnapshot;
180
- const shellAt = (generation: number): EnvironmentShellState => ({
181
- ...EMPTY_SHELL_STATE,
182
- status: "live",
183
- snapshot: Option.some(shellSnapshot),
184
- generation,
185
- });
186
- const shellState = Atom.make<AsyncResult.AsyncResult<EnvironmentShellState>>(
187
- AsyncResult.success(shellAt(0)),
188
- );
189
- const families = createThreadFamilyAtoms(runtime, () => shellState);
190
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
191
- Effect.sync(() => registry.dispose()),
192
- );
193
- const family = families.familyAtom(TARGET.environmentId, parent.id);
194
- const mergedIds = () =>
195
- registry.get(families.snapshotAtom(TARGET.environmentId))?.threads.map(({ id }) => id);
196
- // Waits for the read to finish either way; the assertions read its outcome.
197
- const settle = AtomRegistry.getResult(registry, family, { suspendOnWaiting: true }).pipe(
198
- Effect.ignore,
199
- Effect.tap(() => Effect.yieldNow),
200
- );
201
- registry.mount(families.snapshotAtom(TARGET.environmentId));
202
- families.mount(registry, TARGET.environmentId, parent.id);
122
+ Effect.gen(function* () {
123
+ const replies =
124
+ yield* Queue.unbounded<
125
+ Effect.Effect<OrchestrationV2ThreadFamily, OrchestrationV2GetShellSnapshotError>
126
+ >();
127
+ const client = {
128
+ [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: () => Effect.flatten(Queue.take(replies)),
129
+ } as unknown as WsRpcProtocolClient;
130
+ const session = {
131
+ client,
132
+ initialConfig: Effect.succeed({ shellThreadFamilies: true } as never),
133
+ ready: Effect.void,
134
+ probe: Effect.void,
135
+ closed: Effect.never,
136
+ } as unknown as RpcSession.RpcSession;
137
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
138
+ target: TARGET,
139
+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({
140
+ ...AVAILABLE_CONNECTION_STATE,
141
+ desired: true,
142
+ network: "online",
143
+ phase: "connected",
144
+ attempt: 1,
145
+ generation: 1,
146
+ }),
147
+ session: yield* SubscriptionRef.make(Option.some(session)),
148
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
149
+ connect: Effect.void,
150
+ disconnect: Effect.void,
151
+ retryNow: Effect.void,
152
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
153
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
154
+ _environmentId,
155
+ effect,
156
+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
157
+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
158
+ _environmentId,
159
+ stream,
160
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
161
+ const runtime = Atom.runtime(
162
+ Layer.succeed(
163
+ EnvironmentRegistry.EnvironmentRegistry,
164
+ EnvironmentRegistry.EnvironmentRegistry.of({
165
+ run,
166
+ followStream,
167
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
168
+ ),
169
+ );
170
+ const parent = row("parent");
171
+ const child = row("idle-child");
172
+ const shellSnapshot = {
173
+ schemaVersion: 1,
174
+ snapshotSequence: 3,
175
+ projects: [],
176
+ threads: [parent],
177
+ archivedThreads: [],
178
+ } as OrchestrationV2ShellSnapshot;
179
+ const shellAt = (generation: number): EnvironmentShellState => ({
180
+ ...EMPTY_SHELL_STATE,
181
+ status: "live",
182
+ snapshot: Option.some(shellSnapshot),
183
+ generation,
184
+ });
185
+ const shellState = Atom.make<AsyncResult.AsyncResult<EnvironmentShellState>>(
186
+ AsyncResult.success(shellAt(0)),
187
+ );
188
+ const families = createThreadFamilyAtoms(runtime, () => shellState);
189
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
190
+ Effect.sync(() => registry.dispose()),
191
+ );
192
+ const family = families.familyAtom(TARGET.environmentId, parent.id);
193
+ const mergedIds = () =>
194
+ registry.get(families.snapshotAtom(TARGET.environmentId))?.threads.map(({ id }) => id);
195
+ // Waits for the read to finish either way; the assertions read its outcome.
196
+ const settle = AtomRegistry.getResult(registry, family, { suspendOnWaiting: true }).pipe(
197
+ Effect.ignore,
198
+ Effect.tap(() => Effect.yieldNow),
199
+ );
200
+ registry.mount(families.snapshotAtom(TARGET.environmentId));
201
+ families.mount(registry, TARGET.environmentId, parent.id);
202
204
- // A cached shell from before this session's first snapshot reads nothing.
205
- expect(threadFamilyRead(registry.get(family))).toBe("pending");
206
- expect(yield* Queue.size(replies)).toBe(0);
203
+ // A cached shell from before this session's first snapshot reads nothing.
204
+ expect(threadFamilyRead(registry.get(family))).toBe("pending");
205
+ expect(yield* Queue.size(replies)).toBe(0);
206
208
- registry.set(shellState, AsyncResult.success(shellAt(1)));
209
- yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 3, threads: [child] }));
210
- yield* settle;
211
- expect(threadFamilyRead(registry.get(family))).toBe("settled");
212
- expect(mergedIds()).toEqual(["parent", "idle-child"]);
207
+ registry.set(shellState, AsyncResult.success(shellAt(1)));
208
+ yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 3, threads: [child] }));
209
+ yield* settle;
210
+ expect(threadFamilyRead(registry.get(family))).toBe("settled");
211
+ expect(mergedIds()).toEqual(["parent", "idle-child"]);
212
214
- // A new authoritative snapshot never reuses the old read, even while the next one waits
215
- // or fails.
216
- registry.set(shellState, AsyncResult.success(shellAt(2)));
217
- expect(threadFamilyRead(registry.get(family))).toBe("pending");
218
- expect(mergedIds()).toEqual(["parent"]);
219
- yield* Queue.offer(
220
- replies,
221
- Effect.fail(new OrchestrationV2GetShellSnapshotError({ message: "read failed" })),
222
- );
223
- yield* settle;
224
- expect(threadFamilyRead(registry.get(family))).toBe("failed");
225
- expect(mergedIds()).toEqual(["parent"]);
213
+ // A new authoritative snapshot never reuses the old read, even while the next one waits
214
+ // or fails.
215
+ registry.set(shellState, AsyncResult.success(shellAt(2)));
216
+ expect(threadFamilyRead(registry.get(family))).toBe("pending");
217
+ expect(mergedIds()).toEqual(["parent"]);
218
+ yield* Queue.offer(
219
+ replies,
220
+ Effect.fail(new OrchestrationV2GetShellSnapshotError({ message: "read failed" })),
221
+ );
222
+ yield* settle;
223
+ expect(threadFamilyRead(registry.get(family))).toBe("failed");
224
+ expect(mergedIds()).toEqual(["parent"]);
225
227
- families.refresh(registry, TARGET.environmentId, parent.id);
228
- expect(threadFamilyRead(registry.get(family))).toBe("pending");
229
- yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 5, threads: [child] }));
230
- yield* settle;
231
- expect(threadFamilyRead(registry.get(family))).toBe("settled");
232
- expect(mergedIds()).toEqual(["parent", "idle-child"]);
233
- }),
234
- ),
226
+ families.refresh(registry, TARGET.environmentId, parent.id);
227
+ expect(threadFamilyRead(registry.get(family))).toBe("pending");
228
+ yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 5, threads: [child] }));
229
+ yield* settle;
230
+ expect(threadFamilyRead(registry.get(family))).toBe("settled");
231
+ expect(mergedIds()).toEqual(["parent", "idle-child"]);
232
+ }),
233
);
234
});
packages/client-runtime/src/state/vcs.test.ts
+531
-553
@@ -198,7 +198,7 @@ describe("branch subscriptions", () => {
198
expect(yield* second).toEqual([{ refName: "external", isRepo: true }]);
199
registry.dispose();
200
expect(yield* Queue.take(released)).toBe("external");
201
- }).pipe(Effect.scoped),
201
+ }),
202
);
203
});
204
@@ -235,617 +235,595 @@ describe("cached VCS refs", () => {
235
});
236
237
it.effect("bypasses the server ref snapshot when a mounted list is invalidated", () =>
238
- Effect.scoped(
239
- Effect.gen(function* () {
240
- const requests = yield* Queue.unbounded<VcsListRefsInput>();
241
- const client = {
242
- [WS_METHODS.vcsListRefs]: (input: VcsListRefsInput) =>
243
- Effect.sync(() => {
244
- Queue.offerUnsafe(requests, input);
245
- return LIVE_REFS;
238
+ Effect.gen(function* () {
239
+ const requests = yield* Queue.unbounded<VcsListRefsInput>();
240
+ const client = {
241
+ [WS_METHODS.vcsListRefs]: (input: VcsListRefsInput) =>
242
+ Effect.sync(() => {
243
+ Queue.offerUnsafe(requests, input);
244
+ return LIVE_REFS;
245
+ }),
246
+ } as unknown as WsRpcProtocolClient;
247
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
248
+ target: TARGET,
249
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
250
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
251
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
252
+ connect: Effect.void,
253
+ disconnect: Effect.void,
254
+ retryNow: Effect.void,
255
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
256
+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
257
+ _environmentId,
258
+ stream,
259
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
260
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
261
+ followStream,
262
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
263
+ const runtime = Atom.runtime(
264
+ Layer.merge(
265
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
266
+ Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
267
+ ),
268
+ );
269
+ const atoms = createVcsEnvironmentAtoms(runtime);
270
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
271
+ Effect.sync(() => registry.dispose()),
272
+ );
273
+ yield* Effect.acquireRelease(
274
+ Effect.sync(() =>
275
+ registry.mount(
276
+ atoms.listRefs({
277
+ environmentId: TARGET.environmentId,
278
+ input: { cwd: "/repo", limit: 100 },
279
}),
247
- } as unknown as WsRpcProtocolClient;
248
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
249
- target: TARGET,
250
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
251
- session: yield* SubscriptionRef.make(Option.some(session(client))),
252
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
253
- connect: Effect.void,
254
- disconnect: Effect.void,
255
- retryNow: Effect.void,
256
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
257
- const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
258
- _environmentId,
259
- stream,
260
- ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
261
- const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
262
- followStream,
263
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
264
- const runtime = Atom.runtime(
265
- Layer.merge(
266
- Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
267
- Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
268
- ),
269
- );
270
- const atoms = createVcsEnvironmentAtoms(runtime);
271
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
272
- Effect.sync(() => registry.dispose()),
273
- );
274
- yield* Effect.acquireRelease(
275
- Effect.sync(() =>
276
- registry.mount(
277
- atoms.listRefs({
278
- environmentId: TARGET.environmentId,
279
- input: { cwd: "/repo", limit: 100 },
280
- }),
281
- ),
280
),
283
- (unmount) => Effect.sync(unmount),
284
- );
281
+ ),
282
+ (unmount) => Effect.sync(unmount),
283
+ );
284
286
- expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100 });
285
+ expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100 });
286
288
- invalidateVcsRefs(registry, TARGET);
287
+ invalidateVcsRefs(registry, TARGET);
288
290
- expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100, refresh: true });
289
+ expect(yield* Queue.take(requests)).toEqual({ cwd: "/repo", limit: 100, refresh: true });
290
292
- yield* Effect.acquireRelease(
293
- Effect.sync(() =>
294
- registry.mount(
295
- atoms.listRefs({
296
- environmentId: TARGET.environmentId,
297
- input: { cwd: "/other-repo", limit: 100 },
298
- }),
299
- ),
291
+ yield* Effect.acquireRelease(
292
+ Effect.sync(() =>
293
+ registry.mount(
294
+ atoms.listRefs({
295
+ environmentId: TARGET.environmentId,
296
+ input: { cwd: "/other-repo", limit: 100 },
297
+ }),
298
),
301
- (unmount) => Effect.sync(unmount),
302
- );
303
- expect(yield* Queue.take(requests)).toEqual({
304
- cwd: "/other-repo",
305
- limit: 100,
306
- refresh: true,
307
- });
308
-
309
- yield* Effect.acquireRelease(
310
- Effect.sync(() =>
311
- registry.mount(
312
- atoms.listRefs({
313
- environmentId: TARGET.environmentId,
314
- input: { cwd: "/other-repo", query: "release", limit: 100 },
315
- }),
316
- ),
299
+ ),
300
+ (unmount) => Effect.sync(unmount),
301
+ );
302
+ expect(yield* Queue.take(requests)).toEqual({
303
+ cwd: "/other-repo",
304
+ limit: 100,
305
+ refresh: true,
306
+ });
307
+
308
+ yield* Effect.acquireRelease(
309
+ Effect.sync(() =>
310
+ registry.mount(
311
+ atoms.listRefs({
312
+ environmentId: TARGET.environmentId,
313
+ input: { cwd: "/other-repo", query: "release", limit: 100 },
314
+ }),
315
),
318
- (unmount) => Effect.sync(unmount),
319
- );
320
- expect(yield* Queue.take(requests)).toEqual({
321
- cwd: "/other-repo",
322
- query: "release",
323
- limit: 100,
324
- });
325
- }),
326
- ),
316
+ ),
317
+ (unmount) => Effect.sync(unmount),
318
+ );
319
+ expect(yield* Queue.take(requests)).toEqual({
320
+ cwd: "/other-repo",
321
+ query: "release",
322
+ limit: 100,
323
+ });
324
+ }),
325
);
326
327
it.effect("does not repersist a refresh superseded by ref invalidation", () =>
330
- Effect.scoped(
331
- Effect.gen(function* () {
332
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
333
- Effect.sync(() => registry.dispose()),
334
- );
335
- const saved = yield* Ref.make<ReadonlyArray<VcsListRefsResult>>([]);
336
- const clears = yield* Ref.make(0);
337
- const revisionsObservedDuringClear = yield* Ref.make<ReadonlyArray<number>>([]);
338
- const cache = cacheWithRefs(Option.none(), {
339
- saveVcsRefs: (_environmentId, _cwd, refs) =>
340
- Ref.update(saved, (current) => [...current, refs]),
341
- clearVcsRefs: () =>
342
- Effect.all([
343
- Ref.update(clears, (count) => count + 1),
344
- Ref.update(revisionsObservedDuringClear, (current) => [
345
- ...current,
346
- registry.get(vcsRefsCacheStateAtom(TARGET)).revision,
347
- ]),
348
- ]).pipe(Effect.asVoid),
349
- });
350
-
351
- yield* invalidateCachedVcsRefs(registry, {
328
+ Effect.gen(function* () {
329
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
330
+ Effect.sync(() => registry.dispose()),
331
+ );
332
+ const saved = yield* Ref.make<ReadonlyArray<VcsListRefsResult>>([]);
333
+ const clears = yield* Ref.make(0);
334
+ const revisionsObservedDuringClear = yield* Ref.make<ReadonlyArray<number>>([]);
335
+ const cache = cacheWithRefs(Option.none(), {
336
+ saveVcsRefs: (_environmentId, _cwd, refs) =>
337
+ Ref.update(saved, (current) => [...current, refs]),
338
+ clearVcsRefs: () =>
339
+ Effect.all([
340
+ Ref.update(clears, (count) => count + 1),
341
+ Ref.update(revisionsObservedDuringClear, (current) => [
342
+ ...current,
343
+ registry.get(vcsRefsCacheStateAtom(TARGET)).revision,
344
+ ]),
345
+ ]).pipe(Effect.asVoid),
346
+ });
347
+
348
+ yield* invalidateCachedVcsRefs(registry, {
349
+ environmentId: TARGET.environmentId,
350
+ cwd: "/repo-worktree",
351
+ }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
352
+
353
+ expect(
354
+ yield* commitVcsRefsRefresh(registry, cache, {
355
environmentId: TARGET.environmentId,
353
- cwd: "/repo-worktree",
354
- }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
355
-
356
- expect(
357
- yield* commitVcsRefsRefresh(registry, cache, {
358
- environmentId: TARGET.environmentId,
359
- cwd: "/repo",
360
- refs: CACHED_REFS,
361
- expectedRevision: 0,
362
- persist: true,
363
- }),
364
- ).toBe(false);
365
-
366
- expect(yield* Ref.get(saved)).toEqual([]);
367
- expect(yield* Ref.get(clears)).toBe(1);
368
- expect(yield* Ref.get(revisionsObservedDuringClear)).toEqual([0]);
369
- expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual({
370
- revision: 1,
371
- persistedCacheReadable: true,
372
- });
373
-
374
- expect(
375
- yield* commitVcsRefsRefresh(registry, cache, {
376
- environmentId: TARGET.environmentId,
377
- cwd: "/repo",
378
- refs: LIVE_REFS,
379
- expectedRevision: 1,
380
- persist: true,
381
- }),
382
- ).toBe(true);
383
- expect(yield* Ref.get(saved)).toEqual([LIVE_REFS]);
384
- }),
385
- ),
356
+ cwd: "/repo",
357
+ refs: CACHED_REFS,
358
+ expectedRevision: 0,
359
+ persist: true,
360
+ }),
361
+ ).toBe(false);
362
+
363
+ expect(yield* Ref.get(saved)).toEqual([]);
364
+ expect(yield* Ref.get(clears)).toBe(1);
365
+ expect(yield* Ref.get(revisionsObservedDuringClear)).toEqual([0]);
366
+ expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual({
367
+ revision: 1,
368
+ persistedCacheReadable: true,
369
+ });
370
+
371
+ expect(
372
+ yield* commitVcsRefsRefresh(registry, cache, {
373
+ environmentId: TARGET.environmentId,
374
+ cwd: "/repo",
375
+ refs: LIVE_REFS,
376
+ expectedRevision: 1,
377
+ persist: true,
378
+ }),
379
+ ).toBe(true);
380
+ expect(yield* Ref.get(saved)).toEqual([LIVE_REFS]);
381
+ }),
382
);
383
384
it.effect("invalidates persisted refs when ref-affecting commands settle", () =>
389
- Effect.scoped(
390
- Effect.gen(function* () {
391
- const expectedError = new EnvironmentRpcUnavailableError({
392
- environmentId: TARGET.environmentId,
393
- message: "pull failed after fetching refs",
394
- });
395
- const client = {
396
- [WS_METHODS.vcsPull]: () => Effect.fail(expectedError),
397
- [WS_METHODS.vcsRefreshStatus]: () => Effect.void,
398
- [WS_METHODS.gitPreparePullRequestThread]: () =>
399
- Effect.succeed({ branch: "feature/pr", worktreePath: null }),
400
- } as unknown as WsRpcProtocolClient;
401
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
402
- target: TARGET,
403
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
404
- session: yield* SubscriptionRef.make(Option.some(session(client))),
405
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
406
- connect: Effect.void,
407
- disconnect: Effect.void,
408
- retryNow: Effect.void,
409
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
410
- const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
411
- _environmentId,
412
- effect,
413
- ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
414
- const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
415
- run,
416
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
417
- const clears = yield* Ref.make(0);
418
- const runtime = Atom.runtime(
419
- Layer.merge(
420
- Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
421
- Layer.succeed(
422
- Persistence.EnvironmentCacheStore,
423
- cacheWithRefs(Option.none(), {
424
- clearVcsRefs: () => Ref.update(clears, (count) => count + 1),
425
- }),
426
- ),
385
+ Effect.gen(function* () {
386
+ const expectedError = new EnvironmentRpcUnavailableError({
387
+ environmentId: TARGET.environmentId,
388
+ message: "pull failed after fetching refs",
389
+ });
390
+ const client = {
391
+ [WS_METHODS.vcsPull]: () => Effect.fail(expectedError),
392
+ [WS_METHODS.vcsRefreshStatus]: () => Effect.void,
393
+ [WS_METHODS.gitPreparePullRequestThread]: () =>
394
+ Effect.succeed({ branch: "feature/pr", worktreePath: null }),
395
+ } as unknown as WsRpcProtocolClient;
396
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
397
+ target: TARGET,
398
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
399
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
400
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
401
+ connect: Effect.void,
402
+ disconnect: Effect.void,
403
+ retryNow: Effect.void,
404
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
405
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
406
+ _environmentId,
407
+ effect,
408
+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
409
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
410
+ run,
411
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
412
+ const clears = yield* Ref.make(0);
413
+ const runtime = Atom.runtime(
414
+ Layer.merge(
415
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
416
+ Layer.succeed(
417
+ Persistence.EnvironmentCacheStore,
418
+ cacheWithRefs(Option.none(), {
419
+ clearVcsRefs: () => Ref.update(clears, (count) => count + 1),
420
+ }),
421
),
428
- );
429
- const atoms = createVcsEnvironmentAtoms(runtime);
430
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
431
- Effect.sync(() => registry.dispose()),
432
- );
433
-
434
- const result = yield* Effect.promise(() =>
435
- atoms.pull.run(registry, {
436
- environmentId: TARGET.environmentId,
437
- input: { cwd: "/repo" },
438
- }),
439
- );
422
+ ),
423
+ );
424
+ const atoms = createVcsEnvironmentAtoms(runtime);
425
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
426
+ Effect.sync(() => registry.dispose()),
427
+ );
428
+
429
+ const result = yield* Effect.promise(() =>
430
+ atoms.pull.run(registry, {
431
+ environmentId: TARGET.environmentId,
432
+ input: { cwd: "/repo" },
433
+ }),
434
+ );
435
441
- expect(AsyncResult.isFailure(result)).toBe(true);
442
- expect(yield* Ref.get(clears)).toBe(1);
443
- expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1);
436
+ expect(AsyncResult.isFailure(result)).toBe(true);
437
+ expect(yield* Ref.get(clears)).toBe(1);
438
+ expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(1);
439
445
- const refreshResult = yield* Effect.promise(() =>
446
- atoms.refreshStatus.run(registry, {
447
- environmentId: TARGET.environmentId,
448
- input: { cwd: "/repo" },
449
- }),
450
- );
440
+ const refreshResult = yield* Effect.promise(() =>
441
+ atoms.refreshStatus.run(registry, {
442
+ environmentId: TARGET.environmentId,
443
+ input: { cwd: "/repo" },
444
+ }),
445
+ );
446
452
- expect(AsyncResult.isSuccess(refreshResult)).toBe(true);
453
- expect(yield* Ref.get(clears)).toBe(2);
454
- expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
447
+ expect(AsyncResult.isSuccess(refreshResult)).toBe(true);
448
+ expect(yield* Ref.get(clears)).toBe(2);
449
+ expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(2);
450
456
- const prepareResult = yield* Effect.promise(() =>
457
- createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, {
458
- environmentId: TARGET.environmentId,
459
- input: { cwd: "/repo", reference: "42", mode: "local" },
460
- }),
461
- );
451
+ const prepareResult = yield* Effect.promise(() =>
452
+ createGitEnvironmentAtoms(runtime).preparePullRequestThread.run(registry, {
453
+ environmentId: TARGET.environmentId,
454
+ input: { cwd: "/repo", reference: "42", mode: "local" },
455
+ }),
456
+ );
457
463
- expect(AsyncResult.isSuccess(prepareResult)).toBe(true);
464
- expect(yield* Ref.get(clears)).toBe(3);
465
- expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3);
466
- }),
467
- ),
458
+ expect(AsyncResult.isSuccess(prepareResult)).toBe(true);
459
+ expect(yield* Ref.get(clears)).toBe(3);
460
+ expect(registry.get(vcsRefsCacheStateAtom(TARGET)).revision).toBe(3);
461
+ }),
462
);
463
464
it.effect("a checkout does not wait behind a picker's local status refresh", () =>
471
- Effect.scoped(
472
- Effect.gen(function* () {
473
- const refreshStarted = yield* Deferred.make<void>();
474
- const releaseRefresh = yield* Deferred.make<void>();
475
- const client = {
476
- [WS_METHODS.vcsRefreshStatus]: () =>
477
- Deferred.succeed(refreshStarted, undefined).pipe(
478
- Effect.andThen(Deferred.await(releaseRefresh)),
479
- ),
480
- [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }),
481
- } as unknown as WsRpcProtocolClient;
482
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
483
- target: TARGET,
484
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
485
- session: yield* SubscriptionRef.make(Option.some(session(client))),
486
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
487
- connect: Effect.void,
488
- disconnect: Effect.void,
489
- retryNow: Effect.void,
490
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
491
- const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
492
- _environmentId,
493
- effect,
494
- ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
495
- const runtime = Atom.runtime(
496
- Layer.merge(
497
- Layer.succeed(
498
- EnvironmentRegistry.EnvironmentRegistry,
499
- EnvironmentRegistry.EnvironmentRegistry.of({
500
- run,
501
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
502
- ),
503
- Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
465
+ Effect.gen(function* () {
466
+ const refreshStarted = yield* Deferred.make<void>();
467
+ const releaseRefresh = yield* Deferred.make<void>();
468
+ const client = {
469
+ [WS_METHODS.vcsRefreshStatus]: () =>
470
+ Deferred.succeed(refreshStarted, undefined).pipe(
471
+ Effect.andThen(Deferred.await(releaseRefresh)),
472
),
505
- );
506
- const atoms = createVcsEnvironmentAtoms(runtime);
507
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
508
- Effect.sync(() => registry.dispose()),
509
- );
510
- const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
511
-
512
- const refresh = atoms.refreshLocalStatusForPicker.run(registry, {
473
+ [WS_METHODS.vcsSwitchRef]: () => Effect.succeed({ refName: "feature" }),
474
+ } as unknown as WsRpcProtocolClient;
475
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
476
+ target: TARGET,
477
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
478
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
479
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
480
+ connect: Effect.void,
481
+ disconnect: Effect.void,
482
+ retryNow: Effect.void,
483
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
484
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
485
+ _environmentId,
486
+ effect,
487
+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
488
+ const runtime = Atom.runtime(
489
+ Layer.merge(
490
+ Layer.succeed(
491
+ EnvironmentRegistry.EnvironmentRegistry,
492
+ EnvironmentRegistry.EnvironmentRegistry.of({
493
+ run,
494
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),
495
+ ),
496
+ Layer.succeed(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
497
+ ),
498
+ );
499
+ const atoms = createVcsEnvironmentAtoms(runtime);
500
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
501
+ Effect.sync(() => registry.dispose()),
502
+ );
503
+ const target = { environmentId: TARGET.environmentId, input: { cwd: "/repo" } };
504
+
505
+ const refresh = atoms.refreshLocalStatusForPicker.run(registry, {
506
+ ...target,
507
+ input: { cwd: "/repo", localOnly: true },
508
+ });
509
+ yield* Deferred.await(refreshStarted);
510
+ const checkout = yield* Effect.promise(() =>
511
+ atoms.switchRef.run(registry, {
512
...target,
514
- input: { cwd: "/repo", localOnly: true },
515
- });
516
- yield* Deferred.await(refreshStarted);
517
- const checkout = yield* Effect.promise(() =>
518
- atoms.switchRef.run(registry, {
519
- ...target,
520
- input: { cwd: "/repo", refName: "feature" },
521
- }),
522
- );
513
+ input: { cwd: "/repo", refName: "feature" },
514
+ }),
515
+ );
516
524
- expect(AsyncResult.isSuccess(checkout)).toBe(true);
525
- yield* Deferred.succeed(releaseRefresh, undefined);
526
- expect(AsyncResult.isSuccess(yield* Effect.promise(() => refresh))).toBe(true);
527
- }),
528
- ),
517
+ expect(AsyncResult.isSuccess(checkout)).toBe(true);
518
+ yield* Deferred.succeed(releaseRefresh, undefined);
519
+ expect(AsyncResult.isSuccess(yield* Effect.promise(() => refresh))).toBe(true);
520
+ }),
521
);
522
523
it.effect("suppresses persisted snapshots after an environment-wide clear fails", () =>
532
- Effect.scoped(
533
- Effect.gen(function* () {
534
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
535
- Effect.sync(() => registry.dispose()),
536
- );
537
- const persisted = yield* Ref.make<Option.Option<VcsListRefsResult>>(
538
- Option.some(CACHED_REFS),
539
- );
540
- const loads = yield* Ref.make(0);
541
- const clearAttempts = yield* Ref.make(0);
542
- const cache = cacheWithRefs(Option.none(), {
543
- loadVcsRefs: () =>
544
- Ref.update(loads, (count) => count + 1).pipe(Effect.andThen(Ref.get(persisted))),
545
- saveVcsRefs: (_environmentId, _cwd, refs) => Ref.set(persisted, Option.some(refs)),
546
- clearVcsRefs: () =>
547
- Ref.updateAndGet(clearAttempts, (count) => count + 1).pipe(
548
- Effect.flatMap((attempt) =>
549
- attempt === 1
550
- ? Effect.fail(
551
- new Persistence.ConnectionPersistenceError({
552
- operation: "clear-vcs-refs",
553
- message: "storage unavailable",
554
- }),
555
- )
556
- : Ref.set(persisted, Option.none()),
557
- ),
524
+ Effect.gen(function* () {
525
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
526
+ Effect.sync(() => registry.dispose()),
527
+ );
528
+ const persisted = yield* Ref.make<Option.Option<VcsListRefsResult>>(Option.some(CACHED_REFS));
529
+ const loads = yield* Ref.make(0);
530
+ const clearAttempts = yield* Ref.make(0);
531
+ const cache = cacheWithRefs(Option.none(), {
532
+ loadVcsRefs: () =>
533
+ Ref.update(loads, (count) => count + 1).pipe(Effect.andThen(Ref.get(persisted))),
534
+ saveVcsRefs: (_environmentId, _cwd, refs) => Ref.set(persisted, Option.some(refs)),
535
+ clearVcsRefs: () =>
536
+ Ref.updateAndGet(clearAttempts, (count) => count + 1).pipe(
537
+ Effect.flatMap((attempt) =>
538
+ attempt === 1
539
+ ? Effect.fail(
540
+ new Persistence.ConnectionPersistenceError({
541
+ operation: "clear-vcs-refs",
542
+ message: "storage unavailable",
543
+ }),
544
+ )
545
+ : Ref.set(persisted, Option.none()),
546
),
559
- });
560
-
561
- yield* invalidateCachedVcsRefs(registry, {
547
+ ),
548
+ });
549
+
550
+ yield* invalidateCachedVcsRefs(registry, {
551
+ environmentId: TARGET.environmentId,
552
+ cwd: "/repo",
553
+ }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
554
+
555
+ const state = registry.get(vcsRefsCacheStateAtom(TARGET));
556
+ expect(state).toEqual({
557
+ revision: 1,
558
+ persistedCacheReadable: false,
559
+ });
560
+
561
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
562
+ target: TARGET,
563
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
564
+ session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
565
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
566
+ connect: Effect.void,
567
+ disconnect: Effect.void,
568
+ retryNow: Effect.void,
569
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
570
+ const refs = yield* Stream.unwrap(
571
+ makeCachedVcsRefsChanges(
572
+ { cwd: "/repo", limit: 100 },
573
+ state.revision,
574
+ registry,
575
+ state.persistedCacheReadable,
576
+ ).pipe(
577
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
578
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
579
+ ),
580
+ ).pipe(Stream.runHead, Effect.forkChild({ startImmediately: true }));
581
+
582
+ yield* Effect.yieldNow;
583
+ expect(yield* Ref.get(loads)).toBe(0);
584
+ yield* Fiber.interrupt(refs);
585
+ expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual(state);
586
+
587
+ expect(
588
+ yield* commitVcsRefsRefresh(registry, cache, {
589
environmentId: TARGET.environmentId,
590
cwd: "/repo",
564
- }).pipe(Effect.provideService(Persistence.EnvironmentCacheStore, cache));
565
-
566
- const state = registry.get(vcsRefsCacheStateAtom(TARGET));
567
- expect(state).toEqual({
568
- revision: 1,
569
- persistedCacheReadable: false,
570
- });
571
-
572
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
573
- target: TARGET,
574
- state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
575
- session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
576
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
577
- connect: Effect.void,
578
- disconnect: Effect.void,
579
- retryNow: Effect.void,
580
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
581
- const refs = yield* Stream.unwrap(
582
- makeCachedVcsRefsChanges(
583
- { cwd: "/repo", limit: 100 },
584
- state.revision,
585
- registry,
586
- state.persistedCacheReadable,
587
- ).pipe(
588
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
589
- Effect.provideService(Persistence.EnvironmentCacheStore, cache),
590
- ),
591
- ).pipe(Stream.runHead, Effect.forkChild({ startImmediately: true }));
592
-
593
- yield* Effect.yieldNow;
594
- expect(yield* Ref.get(loads)).toBe(0);
595
- yield* Fiber.interrupt(refs);
596
- expect(registry.get(vcsRefsCacheStateAtom(TARGET))).toEqual(state);
597
-
598
- expect(
599
- yield* commitVcsRefsRefresh(registry, cache, {
600
- environmentId: TARGET.environmentId,
601
- cwd: "/repo",
602
- refs: LIVE_REFS,
603
- expectedRevision: state.revision,
604
- persist: true,
605
- }),
606
- ).toBe(true);
607
- const recoveredState = registry.get(vcsRefsCacheStateAtom(TARGET));
608
- expect(recoveredState).toEqual({
609
- revision: 1,
610
- persistedCacheReadable: true,
611
- });
612
- expect(yield* Ref.get(clearAttempts)).toBe(2);
613
-
614
- const recoveredRefs = yield* Stream.unwrap(
615
- makeCachedVcsRefsChanges(
616
- { cwd: "/repo", limit: 100 },
617
- recoveredState.revision,
618
- registry,
619
- recoveredState.persistedCacheReadable,
620
- ).pipe(
621
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
622
- Effect.provideService(Persistence.EnvironmentCacheStore, cache),
623
- ),
624
- ).pipe(Stream.runHead);
591
+ refs: LIVE_REFS,
592
+ expectedRevision: state.revision,
593
+ persist: true,
594
+ }),
595
+ ).toBe(true);
596
+ const recoveredState = registry.get(vcsRefsCacheStateAtom(TARGET));
597
+ expect(recoveredState).toEqual({
598
+ revision: 1,
599
+ persistedCacheReadable: true,
600
+ });
601
+ expect(yield* Ref.get(clearAttempts)).toBe(2);
602
+
603
+ const recoveredRefs = yield* Stream.unwrap(
604
+ makeCachedVcsRefsChanges(
605
+ { cwd: "/repo", limit: 100 },
606
+ recoveredState.revision,
607
+ registry,
608
+ recoveredState.persistedCacheReadable,
609
+ ).pipe(
610
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
611
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
612
+ ),
613
+ ).pipe(Stream.runHead);
614
626
- expect(Option.getOrThrow(recoveredRefs)).toEqual(LIVE_REFS);
627
- expect(yield* Ref.get(loads)).toBe(1);
628
- }),
629
- ),
615
+ expect(Option.getOrThrow(recoveredRefs)).toEqual(LIVE_REFS);
616
+ expect(yield* Ref.get(loads)).toBe(1);
617
+ }),
618
);
619
620
it.effect("loads an unfiltered branch list without a connection", () =>
633
- Effect.scoped(
634
- Effect.gen(function* () {
635
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
636
- target: TARGET,
637
- state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
638
- session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
639
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
640
- connect: Effect.void,
641
- disconnect: Effect.void,
642
- retryNow: Effect.void,
643
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
644
- const refs = yield* Stream.unwrap(
645
- makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
646
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
647
- Effect.provideService(
648
- Persistence.EnvironmentCacheStore,
649
- cacheWithRefs(Option.some(CACHED_REFS)),
650
- ),
621
+ Effect.gen(function* () {
622
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
623
+ target: TARGET,
624
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
625
+ session: yield* SubscriptionRef.make(Option.none<RpcSession>()),
626
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
627
+ connect: Effect.void,
628
+ disconnect: Effect.void,
629
+ retryNow: Effect.void,
630
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
631
+ const refs = yield* Stream.unwrap(
632
+ makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
633
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
634
+ Effect.provideService(
635
+ Persistence.EnvironmentCacheStore,
636
+ cacheWithRefs(Option.some(CACHED_REFS)),
637
),
652
- ).pipe(Stream.runHead);
638
+ ),
639
+ ).pipe(Stream.runHead);
640
654
- expect(Option.getOrThrow(refs)).toEqual(CACHED_REFS);
655
- }),
656
- ),
641
+ expect(Option.getOrThrow(refs)).toEqual(CACHED_REFS);
642
+ }),
643
);
644
645
it.effect("waits silently for a session while the connection phase is still connected", () =>
660
- Effect.scoped(
661
- Effect.gen(function* () {
662
- const logs: unknown[] = [];
663
- const logger = Logger.make(({ message }) => logs.push(message));
664
- const liveSession = yield* SubscriptionRef.make(Option.none<RpcSession>());
665
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
666
- target: TARGET,
667
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
668
- session: liveSession,
669
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
670
- connect: Effect.void,
671
- disconnect: Effect.void,
672
- retryNow: Effect.void,
673
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
674
- const refs = yield* Stream.unwrap(
675
- makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
676
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
677
- Effect.provideService(
678
- Persistence.EnvironmentCacheStore,
679
- cacheWithRefs(Option.some(CACHED_REFS)),
680
- ),
646
+ Effect.gen(function* () {
647
+ const logs: unknown[] = [];
648
+ const logger = Logger.make(({ message }) => logs.push(message));
649
+ const liveSession = yield* SubscriptionRef.make(Option.none<RpcSession>());
650
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
651
+ target: TARGET,
652
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
653
+ session: liveSession,
654
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
655
+ connect: Effect.void,
656
+ disconnect: Effect.void,
657
+ retryNow: Effect.void,
658
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
659
+ const refs = yield* Stream.unwrap(
660
+ makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
661
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
662
+ Effect.provideService(
663
+ Persistence.EnvironmentCacheStore,
664
+ cacheWithRefs(Option.some(CACHED_REFS)),
665
),
682
- ).pipe(
683
- Stream.take(2),
684
- Stream.runCollect,
685
- Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
686
- Effect.forkChild({ startImmediately: true }),
687
- );
688
-
689
- yield* TestClock.adjust("1 minute");
690
- expect(logs).toEqual([]);
691
-
692
- const client = {
693
- [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
694
- } as unknown as WsRpcProtocolClient;
695
- yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
696
- expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
697
- expect(logs).toEqual([]);
698
- }),
699
- ),
666
+ ),
667
+ ).pipe(
668
+ Stream.take(2),
669
+ Stream.runCollect,
670
+ Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
671
+ Effect.forkChild({ startImmediately: true }),
672
+ );
673
+
674
+ yield* TestClock.adjust("1 minute");
675
+ expect(logs).toEqual([]);
676
+
677
+ const client = {
678
+ [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
679
+ } as unknown as WsRpcProtocolClient;
680
+ yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
681
+ expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
682
+ expect(logs).toEqual([]);
683
+ }),
684
);
685
686
it.effect("cancels an in-flight refresh and restarts when the RPC session changes", () =>
703
- Effect.scoped(
704
- Effect.gen(function* () {
705
- const started = yield* Deferred.make<void>();
706
- const interrupted = yield* Deferred.make<void>();
707
- const calls = yield* Ref.make(0);
708
- const interruptions = yield* Ref.make(0);
709
- const client = {
710
- [WS_METHODS.vcsListRefs]: () =>
711
- Ref.updateAndGet(calls, (count) => count + 1).pipe(
712
- Effect.flatMap((count) =>
713
- count === 1
714
- ? Deferred.succeed(started, undefined).pipe(
715
- Effect.andThen(Effect.never),
716
- Effect.onInterrupt(() =>
717
- Ref.update(interruptions, (interruptions) => interruptions + 1).pipe(
718
- Effect.andThen(Deferred.succeed(interrupted, undefined)),
719
- ),
687
+ Effect.gen(function* () {
688
+ const started = yield* Deferred.make<void>();
689
+ const interrupted = yield* Deferred.make<void>();
690
+ const calls = yield* Ref.make(0);
691
+ const interruptions = yield* Ref.make(0);
692
+ const client = {
693
+ [WS_METHODS.vcsListRefs]: () =>
694
+ Ref.updateAndGet(calls, (count) => count + 1).pipe(
695
+ Effect.flatMap((count) =>
696
+ count === 1
697
+ ? Deferred.succeed(started, undefined).pipe(
698
+ Effect.andThen(Effect.never),
699
+ Effect.onInterrupt(() =>
700
+ Ref.update(interruptions, (interruptions) => interruptions + 1).pipe(
701
+ Effect.andThen(Deferred.succeed(interrupted, undefined)),
702
),
721
- )
722
- : Effect.succeed(LIVE_REFS),
723
- ),
703
+ ),
704
+ )
705
+ : Effect.succeed(LIVE_REFS),
706
),
725
- } as unknown as WsRpcProtocolClient;
726
- const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
727
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
728
- target: TARGET,
729
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
730
- session: liveSession,
731
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
732
- connect: Effect.void,
733
- disconnect: Effect.void,
734
- retryNow: Effect.void,
735
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
736
-
737
- const fiber = yield* Stream.unwrap(
738
- makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
739
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
740
- Effect.provideService(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
707
),
742
- ).pipe(Stream.runHead, Effect.forkChild);
743
-
744
- yield* Deferred.await(started);
745
- yield* SubscriptionRef.set(liveSession, Option.none());
746
- yield* Deferred.await(interrupted);
747
- expect(yield* Ref.get(interruptions)).toBe(1);
748
-
749
- yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
750
- expect(Option.getOrThrow(yield* Fiber.join(fiber))).toEqual(LIVE_REFS);
751
- expect(yield* Ref.get(calls)).toBe(2);
752
- }),
753
- ),
708
+ } as unknown as WsRpcProtocolClient;
709
+ const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
710
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
711
+ target: TARGET,
712
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
713
+ session: liveSession,
714
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
715
+ connect: Effect.void,
716
+ disconnect: Effect.void,
717
+ retryNow: Effect.void,
718
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
719
+
720
+ const fiber = yield* Stream.unwrap(
721
+ makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
722
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
723
+ Effect.provideService(Persistence.EnvironmentCacheStore, cacheWithRefs(Option.none())),
724
+ ),
725
+ ).pipe(Stream.runHead, Effect.forkChild);
726
+
727
+ yield* Deferred.await(started);
728
+ yield* SubscriptionRef.set(liveSession, Option.none());
729
+ yield* Deferred.await(interrupted);
730
+ expect(yield* Ref.get(interruptions)).toBe(1);
731
+
732
+ yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
733
+ expect(Option.getOrThrow(yield* Fiber.join(fiber))).toEqual(LIVE_REFS);
734
+ expect(yield* Ref.get(calls)).toBe(2);
735
+ }),
736
);
737
738
it.effect("retries Git failures and cancels pending retries when the session is removed", () =>
757
- Effect.scoped(
758
- Effect.gen(function* () {
759
- const calls = yield* Ref.make(0);
760
- const warnings = yield* Queue.unbounded<unknown>();
761
- const logger = Logger.make(({ message }) => Queue.offerUnsafe(warnings, message));
762
- const failure = new VcsProcessExitError({
763
- operation: "listRefs",
764
- command: "git",
765
- cwd: "/repo",
766
- exitCode: 128,
767
- detail: "Could not read refs.",
768
- });
769
- const client = {
770
- [WS_METHODS.vcsListRefs]: () =>
771
- Ref.updateAndGet(calls, (count) => count + 1).pipe(
772
- Effect.flatMap((count) =>
773
- count < 3 ? Effect.fail(failure) : Effect.succeed(LIVE_REFS),
774
- ),
775
- ),
776
- } as unknown as WsRpcProtocolClient;
777
- const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
778
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
779
- target: TARGET,
780
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
781
- session: liveSession,
782
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
783
- connect: Effect.void,
784
- disconnect: Effect.void,
785
- retryNow: Effect.void,
786
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
787
- const refs = yield* Stream.unwrap(
788
- makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
789
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
790
- Effect.provideService(
791
- Persistence.EnvironmentCacheStore,
792
- cacheWithRefs(Option.some(CACHED_REFS)),
739
+ Effect.gen(function* () {
740
+ const calls = yield* Ref.make(0);
741
+ const warnings = yield* Queue.unbounded<unknown>();
742
+ const logger = Logger.make(({ message }) => Queue.offerUnsafe(warnings, message));
743
+ const failure = new VcsProcessExitError({
744
+ operation: "listRefs",
745
+ command: "git",
746
+ cwd: "/repo",
747
+ exitCode: 128,
748
+ detail: "Could not read refs.",
749
+ });
750
+ const client = {
751
+ [WS_METHODS.vcsListRefs]: () =>
752
+ Ref.updateAndGet(calls, (count) => count + 1).pipe(
753
+ Effect.flatMap((count) =>
754
+ count < 3 ? Effect.fail(failure) : Effect.succeed(LIVE_REFS),
755
),
756
),
795
- ).pipe(
796
- Stream.take(2),
797
- Stream.runCollect,
798
- Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
799
- Effect.forkChild({ startImmediately: true }),
800
- );
801
-
802
- yield* Queue.take(warnings);
803
- expect(yield* Ref.get(calls)).toBe(1);
804
- yield* TestClock.adjust("1 second");
805
- expect(yield* Ref.get(calls)).toBe(2);
806
- expect(yield* Queue.size(warnings)).toBe(1);
807
-
808
- yield* SubscriptionRef.set(liveSession, Option.none());
809
- yield* TestClock.adjust("1 minute");
810
- expect(yield* Ref.get(calls)).toBe(2);
811
- expect(yield* Queue.size(warnings)).toBe(1);
812
-
813
- yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
814
- expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
815
- expect(yield* Ref.get(calls)).toBe(3);
816
- }),
817
- ),
757
+ } as unknown as WsRpcProtocolClient;
758
+ const liveSession = yield* SubscriptionRef.make(Option.some(session(client)));
759
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
760
+ target: TARGET,
761
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
762
+ session: liveSession,
763
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
764
+ connect: Effect.void,
765
+ disconnect: Effect.void,
766
+ retryNow: Effect.void,
767
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
768
+ const refs = yield* Stream.unwrap(
769
+ makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
770
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
771
+ Effect.provideService(
772
+ Persistence.EnvironmentCacheStore,
773
+ cacheWithRefs(Option.some(CACHED_REFS)),
774
+ ),
775
+ ),
776
+ ).pipe(
777
+ Stream.take(2),
778
+ Stream.runCollect,
779
+ Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
780
+ Effect.forkChild({ startImmediately: true }),
781
+ );
782
+
783
+ yield* Queue.take(warnings);
784
+ expect(yield* Ref.get(calls)).toBe(1);
785
+ yield* TestClock.adjust("1 second");
786
+ expect(yield* Ref.get(calls)).toBe(2);
787
+ expect(yield* Queue.size(warnings)).toBe(1);
788
+
789
+ yield* SubscriptionRef.set(liveSession, Option.none());
790
+ yield* TestClock.adjust("1 minute");
791
+ expect(yield* Ref.get(calls)).toBe(2);
792
+ expect(yield* Queue.size(warnings)).toBe(1);
793
+
794
+ yield* SubscriptionRef.set(liveSession, Option.some(session(client)));
795
+ expect(yield* Fiber.join(refs)).toEqual([CACHED_REFS, LIVE_REFS]);
796
+ expect(yield* Ref.get(calls)).toBe(3);
797
+ }),
798
);
799
800
it.effect("emits persisted refs before a live refresh", () =>
821
- Effect.scoped(
822
- Effect.gen(function* () {
823
- const client = {
824
- [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
825
- } as unknown as WsRpcProtocolClient;
826
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
827
- target: TARGET,
828
- state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
829
- session: yield* SubscriptionRef.make(Option.some(session(client))),
830
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
831
- connect: Effect.void,
832
- disconnect: Effect.void,
833
- retryNow: Effect.void,
834
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
835
-
836
- const refs = yield* Stream.unwrap(
837
- makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
838
- Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
839
- Effect.provideService(
840
- Persistence.EnvironmentCacheStore,
841
- cacheWithRefs(Option.some(CACHED_REFS)),
842
- ),
801
+ Effect.gen(function* () {
802
+ const client = {
803
+ [WS_METHODS.vcsListRefs]: () => Effect.succeed(LIVE_REFS),
804
+ } as unknown as WsRpcProtocolClient;
805
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
806
+ target: TARGET,
807
+ state: yield* SubscriptionRef.make(CONNECTED_CONNECTION_STATE),
808
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
809
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
810
+ connect: Effect.void,
811
+ disconnect: Effect.void,
812
+ retryNow: Effect.void,
813
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
814
+
815
+ const refs = yield* Stream.unwrap(
816
+ makeCachedVcsRefsChanges({ cwd: "/repo", limit: 100 }).pipe(
817
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
818
+ Effect.provideService(
819
+ Persistence.EnvironmentCacheStore,
820
+ cacheWithRefs(Option.some(CACHED_REFS)),
821
),
844
- ).pipe(Stream.take(2), Stream.runCollect);
822
+ ),
823
+ ).pipe(Stream.take(2), Stream.runCollect);
824
846
- expect(refs).toEqual([CACHED_REFS, LIVE_REFS]);
847
- }),
848
- ),
825
+ expect(refs).toEqual([CACHED_REFS, LIVE_REFS]);
826
+ }),
827
);
828
});
829
packages/client-runtime/src/state/vcsAction.test.ts
+129
-134
@@ -433,147 +433,142 @@ describe("vcsActionState", () => {
433
});
434
435
it.effect("invalidates persisted refs after successful and failed stacked actions", () =>
436
- Effect.scoped(
437
- Effect.gen(function* () {
438
- const connectionState: SupervisorConnectionState = {
439
- ...AVAILABLE_CONNECTION_STATE,
440
- desired: true,
441
- network: "online",
442
- phase: "connected",
443
- attempt: 1,
444
- generation: 1,
445
- };
446
- const targetKey = { environmentId, cwd };
447
- const successfulActionId = "invalidate-success";
448
- const failedActionId = "invalidate-failure";
449
- const interruptedActionId = "invalidate-interrupted";
450
- const successfulTransportActionId = createVcsActionTransportId(
451
- targetKey,
452
- successfulActionId,
453
- );
454
- const failedTransportActionId = createVcsActionTransportId(targetKey, failedActionId);
455
- const interruptedTransportActionId = createVcsActionTransportId(
456
- targetKey,
457
- interruptedActionId,
458
- );
459
- const rpcInputs = new Array<GitRunStackedActionInput>();
460
- const client = {
461
- [WS_METHODS.gitRunStackedAction]: (input: GitRunStackedActionInput) =>
462
- (rpcInputs.push(input), input.actionId === successfulTransportActionId)
463
- ? Stream.make(
436
+ Effect.gen(function* () {
437
+ const connectionState: SupervisorConnectionState = {
438
+ ...AVAILABLE_CONNECTION_STATE,
439
+ desired: true,
440
+ network: "online",
441
+ phase: "connected",
442
+ attempt: 1,
443
+ generation: 1,
444
+ };
445
+ const targetKey = { environmentId, cwd };
446
+ const successfulActionId = "invalidate-success";
447
+ const failedActionId = "invalidate-failure";
448
+ const interruptedActionId = "invalidate-interrupted";
449
+ const successfulTransportActionId = createVcsActionTransportId(targetKey, successfulActionId);
450
+ const failedTransportActionId = createVcsActionTransportId(targetKey, failedActionId);
451
+ const interruptedTransportActionId = createVcsActionTransportId(
452
+ targetKey,
453
+ interruptedActionId,
454
+ );
455
+ const rpcInputs = new Array<GitRunStackedActionInput>();
456
+ const client = {
457
+ [WS_METHODS.gitRunStackedAction]: (input: GitRunStackedActionInput) =>
458
+ (rpcInputs.push(input), input.actionId === successfulTransportActionId)
459
+ ? Stream.make(
460
+ progress({
461
+ kind: "action_finished",
462
+ actionId: successfulTransportActionId,
463
+ cwd,
464
+ action,
465
+ result,
466
+ }),
467
+ )
468
+ : input.actionId === interruptedTransportActionId
469
+ ? Stream.fromEffect(Effect.interrupt)
470
+ : Stream.make(
471
progress({
465
- kind: "action_finished",
466
- actionId: successfulTransportActionId,
472
+ kind: "action_failed",
473
+ actionId: failedTransportActionId,
474
cwd,
475
action,
469
- result,
476
+ phase: "push",
477
+ message: "push failed after creating the branch",
478
}),
471
- )
472
- : input.actionId === interruptedTransportActionId
473
- ? Stream.fromEffect(Effect.interrupt)
474
- : Stream.make(
475
- progress({
476
- kind: "action_failed",
477
- actionId: failedTransportActionId,
478
- cwd,
479
- action,
480
- phase: "push",
481
- message: "push failed after creating the branch",
482
- }),
483
- ),
484
- } as unknown as WsRpcProtocolClient;
485
- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
486
- target,
487
- state: yield* SubscriptionRef.make(connectionState),
488
- session: yield* SubscriptionRef.make(Option.some(session(client))),
489
- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
490
- connect: Effect.void,
491
- disconnect: Effect.void,
492
- retryNow: Effect.void,
493
- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
494
- const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
495
- _environmentId,
496
- effect,
497
- ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
498
- const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = (
499
- _environmentId,
500
- stream,
501
- ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
502
- const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
503
- run,
504
- runStream,
505
- } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
506
- const removed = new Array<string>();
507
- const runtime = Atom.runtime(
508
- Layer.merge(
509
- Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
510
- Layer.succeed(
511
- Persistence.EnvironmentCacheStore,
512
- cacheStore((removedEnvironmentId) => {
513
- removed.push(`${removedEnvironmentId}:*`);
514
- }),
515
- ),
479
+ ),
480
+ } as unknown as WsRpcProtocolClient;
481
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
482
+ target,
483
+ state: yield* SubscriptionRef.make(connectionState),
484
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
485
+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
486
+ connect: Effect.void,
487
+ disconnect: Effect.void,
488
+ retryNow: Effect.void,
489
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
490
+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
491
+ _environmentId,
492
+ effect,
493
+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
494
+ const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = (
495
+ _environmentId,
496
+ stream,
497
+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
498
+ const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
499
+ run,
500
+ runStream,
501
+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
502
+ const removed = new Array<string>();
503
+ const runtime = Atom.runtime(
504
+ Layer.merge(
505
+ Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
506
+ Layer.succeed(
507
+ Persistence.EnvironmentCacheStore,
508
+ cacheStore((removedEnvironmentId) => {
509
+ removed.push(`${removedEnvironmentId}:*`);
510
+ }),
511
),
517
- );
518
- const manager = createVcsActionManager(runtime);
519
- const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
520
- Effect.sync(() => registry.dispose()),
521
- );
522
- const state = vcsRefsCacheStateAtom({ environmentId });
523
-
524
- expect(registry.get(state).revision).toBe(0);
525
- const threadId = ThreadId.make("thread-stacked-action");
526
- const projectId = ProjectId.make("project-stacked-action");
527
- const successfulResult = yield* Effect.promise(() =>
528
- manager.runStackedAction(targetKey).run(registry, {
529
- actionId: successfulActionId,
530
- action,
531
- threadId,
532
- projectId,
533
- }),
534
- );
535
-
536
- expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
537
- expect(registry.get(manager.stateAtom(targetKey))).toEqual(EMPTY_VCS_ACTION_STATE);
538
- expect(registry.get(state).revision).toBe(1);
539
- expect(removed).toEqual([`${environmentId}:*`]);
540
- expect(rpcInputs).toEqual([
541
- { actionId: successfulTransportActionId, cwd, action, threadId, projectId },
542
- ]);
543
-
544
- const failedResult = yield* Effect.promise(() =>
545
- manager.runStackedAction(targetKey).run(registry, {
546
- actionId: failedActionId,
547
- action,
548
- }),
549
- );
512
+ ),
513
+ );
514
+ const manager = createVcsActionManager(runtime);
515
+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
516
+ Effect.sync(() => registry.dispose()),
517
+ );
518
+ const state = vcsRefsCacheStateAtom({ environmentId });
519
+
520
+ expect(registry.get(state).revision).toBe(0);
521
+ const threadId = ThreadId.make("thread-stacked-action");
522
+ const projectId = ProjectId.make("project-stacked-action");
523
+ const successfulResult = yield* Effect.promise(() =>
524
+ manager.runStackedAction(targetKey).run(registry, {
525
+ actionId: successfulActionId,
526
+ action,
527
+ threadId,
528
+ projectId,
529
+ }),
530
+ );
531
+
532
+ expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
533
+ expect(registry.get(manager.stateAtom(targetKey))).toEqual(EMPTY_VCS_ACTION_STATE);
534
+ expect(registry.get(state).revision).toBe(1);
535
+ expect(removed).toEqual([`${environmentId}:*`]);
536
+ expect(rpcInputs).toEqual([
537
+ { actionId: successfulTransportActionId, cwd, action, threadId, projectId },
538
+ ]);
539
551
- expect(AsyncResult.isFailure(failedResult)).toBe(true);
552
- expect(registry.get(manager.stateAtom(targetKey))).toMatchObject({
553
- isRunning: false,
554
- operation: "run_change_request",
540
+ const failedResult = yield* Effect.promise(() =>
541
+ manager.runStackedAction(targetKey).run(registry, {
542
actionId: failedActionId,
556
- error: "Source control action 'commit_push' failed during push.",
557
- });
558
- expect(registry.get(state).revision).toBe(2);
559
- expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]);
560
-
561
- const interruptedResult = yield* Effect.promise(() =>
562
- manager.runStackedAction(targetKey).run(registry, {
563
- actionId: interruptedActionId,
564
- action,
565
- }),
566
- );
567
-
568
- expect(AsyncResult.isFailure(interruptedResult)).toBe(true);
569
- if (AsyncResult.isFailure(interruptedResult)) {
570
- expect(Cause.hasInterruptsOnly(interruptedResult.cause)).toBe(true);
571
- }
572
- expect(registry.get(manager.stateAtom(targetKey))).toEqual(EMPTY_VCS_ACTION_STATE);
573
- expect(registry.get(state).revision).toBe(3);
574
- expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`, `${environmentId}:*`]);
575
- }),
576
- ),
543
+ action,
544
+ }),
545
+ );
546
+
547
+ expect(AsyncResult.isFailure(failedResult)).toBe(true);
548
+ expect(registry.get(manager.stateAtom(targetKey))).toMatchObject({
549
+ isRunning: false,
550
+ operation: "run_change_request",
551
+ actionId: failedActionId,
552
+ error: "Source control action 'commit_push' failed during push.",
553
+ });
554
+ expect(registry.get(state).revision).toBe(2);
555
+ expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]);
556
+
557
+ const interruptedResult = yield* Effect.promise(() =>
558
+ manager.runStackedAction(targetKey).run(registry, {
559
+ actionId: interruptedActionId,
560
+ action,
561
+ }),
562
+ );
563
+
564
+ expect(AsyncResult.isFailure(interruptedResult)).toBe(true);
565
+ if (AsyncResult.isFailure(interruptedResult)) {
566
+ expect(Cause.hasInterruptsOnly(interruptedResult.cause)).toBe(true);
567
+ }
568
+ expect(registry.get(manager.stateAtom(targetKey))).toEqual(EMPTY_VCS_ACTION_STATE);
569
+ expect(registry.get(state).revision).toBe(3);
570
+ expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`, `${environmentId}:*`]);
571
+ }),
572
);
573
});
574
packages/effect-acp/src/client.test.ts
+5
-5
@@ -1491,7 +1491,7 @@ it.layer(NodeServices.layer)("effect-acp client", (it) => {
1491
]),
1492
);
1493
assert.deepEqual(yield* Fiber.join(prompt), { stopReason: "error", error });
1494
- }).pipe(Effect.scoped),
1494
+ }),
1495
);
1496
1497
it.effect("routes MCP-over-ACP connect, message, notification, and disconnect callbacks", () =>
@@ -1713,7 +1713,7 @@ it.effect.each(["accept", "decline", "cancel"] as const)(
1713
method === "elicitation/create" ? response : { action: answer, _meta: response._meta },
1714
});
1715
}
1716
- }).pipe(Effect.scoped),
1716
+ }),
1717
);
1718
1719
it.effect.each(["elicitation/complete", "session/elicitation/complete"])(
@@ -1735,7 +1735,7 @@ it.effect.each(["elicitation/complete", "session/elicitation/complete"])(
1735
}),
1736
);
1737
assert.deepEqual(yield* Deferred.await(received), { elicitationId: "elicitation-1" });
1738
- }).pipe(Effect.scoped),
1738
+ }),
1739
);
1740
1741
it.effect("rejects malformed SDK elicitation without calling the question handler", () =>
@@ -1760,7 +1760,7 @@ it.effect("rejects malformed SDK elicitation without calling the question handle
1760
const response = yield* decodeWireError(yield* Queue.take(output));
1761
assert.equal(response.error.code, -32602);
1762
assert.equal(calls, 0);
1763
- }).pipe(Effect.scoped),
1763
+ }),
1764
);
1765
1766
it.effect("returns method-not-found when SDK elicitation has no question handler", () =>
@@ -1779,5 +1779,5 @@ it.effect("returns method-not-found when SDK elicitation has no question handler
1779
);
1780
const response = yield* decodeWireError(yield* Queue.take(output));
1781
assert.equal(response.error.code, -32601);
1782
- }).pipe(Effect.scoped),
1782
+ }),
1783
);
packages/provider-acp-registry/src/server/AcpRegistryRuntimeCoordinator.test.ts
+7
-7
@@ -29,7 +29,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
29
30
yield* Deferred.succeed(releaseForeground, undefined);
31
yield* Fiber.join(foreground);
32
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
32
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
33
);
34
35
it.effect("interrupts an active background probe when foreground startup begins", () =>
@@ -57,7 +57,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
57
58
yield* Deferred.succeed(releaseForeground, undefined);
59
yield* Fiber.join(foreground);
60
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
60
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
61
);
62
63
it.effect("serializes native session mutations across callers", () =>
@@ -84,7 +84,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
84
yield* Fiber.join(first);
85
yield* Fiber.join(second);
86
expect(Option.isSome(yield* Deferred.poll(secondEntered))).toBe(true);
87
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
87
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
88
);
89
90
it.effect("replays and replaces late command advertisements per provider instance", () =>
@@ -132,7 +132,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
132
);
133
yield* coordinator.clearAvailableCommands(codex);
134
expect(Option.isNone(yield* coordinator.getAvailableCommands(codex))).toBe(true);
135
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
135
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
136
);
137
138
it.effect("requires matching user consent before accepting URL authentication", () =>
@@ -174,7 +174,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
174
expect(yield* Fiber.join(request)).toBe(true);
175
expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true);
176
yield* Fiber.interrupt(consumer);
177
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
177
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
178
);
179
180
it.effect("publishes a replacement URL action before retiring the previous request", () =>
@@ -226,7 +226,7 @@ describe("AcpRegistryRuntimeCoordinator", () => {
226
).toBe(true);
227
expect(yield* Fiber.join(replacement)).toBe(true);
228
yield* Fiber.interrupt(consumer);
229
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
229
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
230
);
231
232
it.effect("clears a published URL action when its request is interrupted", () =>
@@ -255,6 +255,6 @@ describe("AcpRegistryRuntimeCoordinator", () => {
255
yield* Deferred.await(cleared);
256
expect(Option.isNone(yield* coordinator.getUrlAuthAction(instanceId))).toBe(true);
257
yield* Fiber.interrupt(consumer);
258
- }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer), Effect.scoped),
258
+ }).pipe(Effect.provide(AcpRegistryRuntimeCoordinator.layer)),
259
);
260
});
packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts
+1
-1
@@ -1903,6 +1903,6 @@ describe("acpRegistryManagedBinaryDirectories", () => {
1903
architecture: "x64",
1904
});
1905
expect(missing).toEqual([]);
1906
- }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped),
1906
+ }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
1907
);
1908
});
packages/provider-acp/src/server/clientTerminals.test.ts
+7
-7
@@ -22,7 +22,7 @@ const withTerminals = <A, E>(use: (terminals: AcpClientTerminals) => Effect.Effe
22
defaultCwd: process.cwd(),
23
});
24
return yield* use(terminals).pipe(Effect.ensuring(terminals.disposeAll));
25
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped);
25
+ }).pipe(Effect.provide(NodeServices.layer));
26
27
describe("AcpClientTerminals", () => {
28
it.live("runs a command, buffers output, and reports the exit status", () =>
@@ -94,7 +94,7 @@ describe("AcpClientTerminals", () => {
94
expect(terminals.readOutputSnapshot("session", terminal.terminalId)?.output).toBe(
95
output.output,
96
);
97
- }).pipe(Effect.scoped),
97
+ }),
98
);
99
100
it.live("resolves terminal environment from the requesting ACP session", () =>
@@ -120,7 +120,7 @@ describe("AcpClientTerminals", () => {
120
const output = yield* terminals.output({ sessionId, terminalId: created.terminalId });
121
expect(output.output).toBe(expected);
122
}
123
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
123
+ }).pipe(Effect.provide(NodeServices.layer)),
124
);
125
126
it.live("runs Devin shell source with arguments, pipes, and session fallback variables", () =>
@@ -139,7 +139,7 @@ describe("AcpClientTerminals", () => {
139
const output = yield* terminals.output({ sessionId: "devin", ...terminal });
140
expect(exit.exitCode).toBe(0);
141
expect(output.output.trim()).toBe("MAILBOX-PROBE");
142
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
142
+ }).pipe(Effect.provide(NodeServices.layer)),
143
);
144
145
it.live.each([
@@ -237,7 +237,7 @@ describe("AcpClientTerminals", () => {
237
const output = yield* terminals.output(request);
238
expect(output.output).toBe("done\n");
239
expect(output.exitStatus).toEqual({ exitCode: 0, signal: null });
240
- }).pipe(Effect.scoped),
240
+ }),
241
);
242
243
it.effect.each([
@@ -298,7 +298,7 @@ describe("AcpClientTerminals", () => {
298
expect(yield* child.isRunning).toBe(false);
299
yield* Fiber.join(killing);
300
expect(yield* Fiber.join(waiting)).toEqual({ exitCode: 137, signal: null });
301
- }).pipe(Effect.scoped),
301
+ }),
302
);
303
304
it.live("force-kills commands that ignore SIGTERM and resolves wait_for_exit", () =>
@@ -352,7 +352,7 @@ describe("AcpClientTerminals", () => {
352
expect(exit).toEqual({ exitCode: null, signal: "SIGKILL" });
353
}
354
expect(yield* child.isRunning).toBe(false);
355
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
355
+ }).pipe(Effect.provide(NodeServices.layer)),
356
);
357
358
it.live("reserves terminal capacity across concurrent creates", () =>
packages/provider-acp/src/server/mcpOverAcpBridge.test.ts
+3
-3
@@ -78,7 +78,7 @@ describe("AcpMcpOverAcpBridge", () => {
78
expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18");
79
expect(requests.at(-1)?.method).toBe("DELETE");
80
expect(requests.at(-1)?.headers.get("mcp-session-id")).toBe("session-42");
81
- }).pipe(Effect.scoped),
81
+ }),
82
);
83
84
it.effect("aborts an in-flight HTTP request when the ACP call is interrupted", () =>
@@ -101,7 +101,7 @@ describe("AcpMcpOverAcpBridge", () => {
101
const signal = yield* Effect.promise(() => started.promise);
102
yield* Fiber.interrupt(request);
103
expect(signal.aborted).toBe(true);
104
- }).pipe(Effect.scoped),
104
+ }),
105
);
106
107
it.effect("answers a call while a long call on the same connection is pending", () =>
@@ -142,7 +142,7 @@ describe("AcpMcpOverAcpBridge", () => {
142
143
waitResponse.resolve(reply(2, { content: [] }));
144
expect(yield* Fiber.join(wait)).toEqual({ content: [] });
145
- }).pipe(Effect.scoped),
145
+ }),
146
);
147
148
it.effect("rejects unknown servers, connections, and oversized messages", () =>
packages/provider-cursor/src/server/auth.test.ts
+9
-9
@@ -124,7 +124,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
124
expect(closedRequest).toBe(true);
125
expect(Exit.isFailure(yield* Fiber.await(request))).toBe(true);
126
expect(yield* harness.auth.readApiKey).toBeUndefined();
127
- }).pipe(Effect.scoped),
127
+ }),
128
);
129
130
it.effect("completes a remote browser login, saves its key and refreshes provider status", () =>
@@ -152,7 +152,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
152
expect(harness.changes).toEqual([true]);
153
expect(Object.values(succeeded)).not.toContain("browser-key");
154
expect(yield* Effect.promise(() => harness.store.load())).toEqual(harness.credentials);
155
- }).pipe(Effect.scoped),
155
+ }),
156
);
157
158
it.effect("keeps the login link private to its owner and rejects other clients' mutations", () =>
@@ -177,7 +177,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
177
),
178
).toBe(true);
179
expect((yield* phase(auth, "waiting")).authorizationUrl).toBe(authorizationUrl);
180
- }).pipe(Effect.scoped),
180
+ }),
181
);
182
183
it.effect("aborts cancellation and ignores a late successful SDK login", () => {
@@ -227,7 +227,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
227
yield* harness.auth.controller.start(owner);
228
yield* phase(harness.auth, "succeeded");
229
expect(yield* harness.auth.requireApiKey).toBe("browser-key");
230
- }).pipe(Effect.scoped),
230
+ }),
231
);
232
233
it.effect("shows a fixed reason when browser login fails and logs the SDK cause", () => {
@@ -264,7 +264,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
264
expect(yield* harness.auth.readApiKey).toBeUndefined();
265
expect(yield* other.auth.requireApiKey).toBe("other-key");
266
expect(harness.changes).toEqual([false]);
267
- }).pipe(Effect.scoped),
267
+ }),
268
);
269
270
it.effect("cancels a pending sign-in on logout without saving its eventual key", () =>
@@ -277,7 +277,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
277
yield* Effect.sync(() => harness.complete.resolve());
278
yield* Effect.promise(() => harness.returned.promise);
279
expect(yield* harness.auth.readApiKey).toBeUndefined();
280
- }).pipe(Effect.scoped),
280
+ }),
281
);
282
283
it.effect("retains credentials if sessions cannot be stopped for logout", () =>
@@ -297,7 +297,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
297
);
298
expect(Exit.isFailure(result)).toBe(true);
299
expect(yield* harness.auth.requireApiKey).toBe("browser-key");
300
- }).pipe(Effect.scoped),
300
+ }),
301
);
302
303
it.effect(
@@ -313,7 +313,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
313
).toBe(true);
314
expect(harness.loginOptions()).toBeUndefined();
315
expect((yield* Effect.promise(() => harness.store.load()))?.apiKey).toBe("browser-key");
316
- }).pipe(Effect.scoped),
316
+ }),
317
);
318
319
it.effect("ignores expired browser credentials and rejects disabled sign-in", () =>
@@ -324,6 +324,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("CursorAuth", (it
324
);
325
expect(yield* harness.auth.readApiKey).toBeUndefined();
326
expect(Exit.isFailure(yield* Effect.exit(harness.auth.controller.start(owner)))).toBe(true);
327
- }).pipe(Effect.scoped),
327
+ }),
328
);
329
});
packages/provider-cursor/src/server/driver.test.ts
+2
-2
@@ -183,7 +183,7 @@ it.layer(layerTest)("CursorDriver", (it) => {
183
).toBe("Failure");
184
expect(openedKeys).toEqual(["instance-browser-key"]);
185
expect(closed).toBe(1);
186
- }).pipe(Effect.scoped),
186
+ }),
187
);
188
189
it.effect("budgets handoffs for the SDK model across catalog refreshes and option changes", () =>
@@ -405,6 +405,6 @@ it.layer(layerTest)("CursorDriver", (it) => {
405
},
406
retainedDefault: catalogDefault,
407
});
408
- }).pipe(Effect.scoped),
408
+ }),
409
);
410
});
packages/provider-fx/src/server/driver.test.ts
+1
-1
@@ -76,6 +76,6 @@ it.layer(layerTest)("FxDriver binary path", (it) => {
76
assert.isNotEmpty(launches);
77
assert.deepEqual([...new Set(launches)], [path.join("/test-home", ".local", "bin", "fx")]);
78
assert.isTrue(snapshot.installed);
79
- }).pipe(Effect.scoped),
79
+ }),
80
);
81
});
packages/provider-fx/src/server/skills.test.ts
+3
-3
@@ -52,7 +52,7 @@ describe("discoverFxSkills", () => {
52
"home-claude",
53
],
54
);
55
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
55
+ }).pipe(Effect.provide(NodeServices.layer)),
56
);
57
58
// For `$review` with two skills of exactly that name, fx's model loads the
@@ -159,7 +159,7 @@ describe("discoverFxSkills", () => {
159
["Review", path.join(home, ".claude/skills/review/SKILL.md")],
160
],
161
);
162
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
162
+ }).pipe(Effect.provide(NodeServices.layer)),
163
);
164
165
// Nix home-manager and dotfile setups link ~/.fx/skills; fx then loads
@@ -194,6 +194,6 @@ describe("discoverFxSkills", () => {
194
skills.map((skill) => skill.name),
195
["compat"],
196
);
197
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
197
+ }).pipe(Effect.provide(NodeServices.layer)),
198
);
199
});
packages/provider-grok/src/server/driver.test.ts
+1
-5
@@ -168,7 +168,6 @@ it.layer(layerTest)("GrokDriver", (it) => {
168
return JSON.stringify({ casks: [{ version: "1.2.4,789" }] });
169
}),
170
),
171
- Effect.scoped,
171
);
172
});
173
}
@@ -186,9 +185,6 @@ it.layer(layerTest)("GrokDriver", (it) => {
185
config: { ...GrokDriver.defaultConfig(), binaryPath: path.join(tempDir, "grok") },
186
});
187
expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
189
- }).pipe(
190
- Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawner),
191
- Effect.scoped,
192
- ),
188
+ }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawner)),
189
);
190
});
packages/provider-kiro/src/server/driver.test.ts
+1
-1
@@ -139,6 +139,6 @@ it.layer(layerTest)("KiroDriver binary path", (it) => {
139
[path.join("/test-home", ".local", "bin", "kiro-cli")],
140
);
141
assert.isTrue(snapshot.installed);
142
- }).pipe(Effect.scoped),
142
+ }),
143
);
144
});
packages/provider-muse/src/server/driver.test.ts
+1
-1
@@ -211,6 +211,6 @@ it.layer(layerTest)("MuseDriver usage", (it) => {
211
const refreshed = yield* instance.snapshot.refresh;
212
expect(refreshed.usageLimits).toEqual(latest.usageLimits);
213
expect(refreshed.auth.label).toBe("tier-2");
214
- }).pipe(Effect.scoped),
214
+ }),
215
);
216
});
packages/provider-muse/src/server/maintenance.test.ts
+35
-37
@@ -78,42 +78,40 @@ it.layer(NodeServices.layer)("Muse maintenance", (it) => {
78
);
79
80
it.effect("updates only a recognized launcher at the resolved instance path", () =>
81
- Effect.scoped(
82
- Effect.gen(function* () {
83
- const fs = yield* FileSystem.FileSystem;
84
- const directory = yield* fs.makeTempDirectoryScoped({ prefix: "muse-maintenance-" });
85
- const binaryPath = `${directory}/custom muse`;
86
- const context = {
87
- binaryPath,
88
- resolvedCommandPath: binaryPath,
89
- realCommandPath: binaryPath,
90
- platform: "linux" as const,
91
- env: { MUSE_CHANNEL: "muse-canary" },
92
- };
93
- yield* fs.writeFileString(
94
- binaryPath,
95
- "#!/bin/bash\n# muse-code/launcher-2\n# MUSE_SYNC_UPDATE\n",
96
- );
97
- const result = yield* museMaintenance.resolve(context);
98
- expect(result.update).toMatchObject({
99
- executable: binaryPath,
100
- args: ["--version"],
101
- lockKey: `muse:${binaryPath}`,
102
- env: {
103
- MUSE_CHANNEL: "muse-canary",
104
- MUSE_NO_AUTO_UPDATE: "0",
105
- MUSE_SYNC_UPDATE: "1",
106
- MUSE_UPDATE_INTERVAL_SECONDS: "0",
107
- },
108
- });
109
- expect(result.update?.command).toBe(
110
- `MUSE_CHANNEL=muse-canary MUSE_NO_AUTO_UPDATE=0 MUSE_SYNC_UPDATE=1 MUSE_UPDATE_INTERVAL_SECONDS=0 '${binaryPath}' --version`,
111
- );
112
- expect(result.compareVersions).toBe(compareMuseVersions);
113
- yield* fs.writeFileString(binaryPath, "standalone binary");
114
- expect((yield* museMaintenance.resolve(context)).update).toBeNull();
115
- expect((yield* museMaintenance.resolve(null)).update).toBeNull();
116
- }),
117
- ),
81
+ Effect.gen(function* () {
82
+ const fs = yield* FileSystem.FileSystem;
83
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "muse-maintenance-" });
84
+ const binaryPath = `${directory}/custom muse`;
85
+ const context = {
86
+ binaryPath,
87
+ resolvedCommandPath: binaryPath,
88
+ realCommandPath: binaryPath,
89
+ platform: "linux" as const,
90
+ env: { MUSE_CHANNEL: "muse-canary" },
91
+ };
92
+ yield* fs.writeFileString(
93
+ binaryPath,
94
+ "#!/bin/bash\n# muse-code/launcher-2\n# MUSE_SYNC_UPDATE\n",
95
+ );
96
+ const result = yield* museMaintenance.resolve(context);
97
+ expect(result.update).toMatchObject({
98
+ executable: binaryPath,
99
+ args: ["--version"],
100
+ lockKey: `muse:${binaryPath}`,
101
+ env: {
102
+ MUSE_CHANNEL: "muse-canary",
103
+ MUSE_NO_AUTO_UPDATE: "0",
104
+ MUSE_SYNC_UPDATE: "1",
105
+ MUSE_UPDATE_INTERVAL_SECONDS: "0",
106
+ },
107
+ });
108
+ expect(result.update?.command).toBe(
109
+ `MUSE_CHANNEL=muse-canary MUSE_NO_AUTO_UPDATE=0 MUSE_SYNC_UPDATE=1 MUSE_UPDATE_INTERVAL_SECONDS=0 '${binaryPath}' --version`,
110
+ );
111
+ expect(result.compareVersions).toBe(compareMuseVersions);
112
+ yield* fs.writeFileString(binaryPath, "standalone binary");
113
+ expect((yield* museMaintenance.resolve(context)).update).toBeNull();
114
+ expect((yield* museMaintenance.resolve(null)).update).toBeNull();
115
+ }),
116
);
117
});
packages/provider-muse/src/server/status.test.ts
+68
-76
@@ -56,90 +56,82 @@ const fakeCli = (source = 'process.stdout.write("muse 1.0.3-R2198.1\\n");') =>
56
57
it.layer(NodeServices.layer)("Muse status", (it) => {
58
it.effect("does not expose CLI stderr or start an SDK host after a failed version check", () =>
59
- Effect.scoped(
60
- Effect.gen(function* () {
61
- const binaryPath = yield* fakeCli(
62
- 'process.stderr.write("secret-test-value");process.exit(2);',
63
- );
64
- const createHost = vi.fn(async () => makeHost(metaCatalog));
65
- const snapshot = yield* checkMuseProviderStatus(
66
- settings({ enabled: true, binaryPath }),
67
- undefined,
68
- undefined,
69
- createHost,
70
- );
71
- expect(snapshot.installed).toBe(true);
72
- expect(snapshot.status).toBe("error");
73
- expect(snapshot.message).not.toContain("secret-test-value");
74
- expect(createHost).not.toHaveBeenCalled();
75
- }),
76
- ),
59
+ Effect.gen(function* () {
60
+ const binaryPath = yield* fakeCli(
61
+ 'process.stderr.write("secret-test-value");process.exit(2);',
62
+ );
63
+ const createHost = vi.fn(async () => makeHost(metaCatalog));
64
+ const snapshot = yield* checkMuseProviderStatus(
65
+ settings({ enabled: true, binaryPath }),
66
+ undefined,
67
+ undefined,
68
+ createHost,
69
+ );
70
+ expect(snapshot.installed).toBe(true);
71
+ expect(snapshot.status).toBe("error");
72
+ expect(snapshot.message).not.toContain("secret-test-value");
73
+ expect(createHost).not.toHaveBeenCalled();
74
+ }),
75
);
76
77
it.effect("tells the user to finish setup when the launcher has not installed its runtime", () =>
80
- Effect.scoped(
81
- Effect.gen(function* () {
82
- // What Muse's launcher prints when a fresh install runs under MUSE_NO_AUTO_UPDATE=1.
83
- const binaryPath = yield* fakeCli(
84
- 'process.stderr.write("muse: installed binary is missing; rerun the installer\\n");process.exit(1);',
85
- );
86
- const snapshot = yield* checkMuseProviderStatus(settings({ enabled: true, binaryPath }));
87
- expect(snapshot.status).toBe("error");
88
- expect(snapshot.message).toContain("muse --version");
89
- }),
90
- ),
78
+ Effect.gen(function* () {
79
+ // What Muse's launcher prints when a fresh install runs under MUSE_NO_AUTO_UPDATE=1.
80
+ const binaryPath = yield* fakeCli(
81
+ 'process.stderr.write("muse: installed binary is missing; rerun the installer\\n");process.exit(1);',
82
+ );
83
+ const snapshot = yield* checkMuseProviderStatus(settings({ enabled: true, binaryPath }));
84
+ expect(snapshot.status).toBe("error");
85
+ expect(snapshot.message).toContain("muse --version");
86
+ }),
87
);
88
89
it.effect("discovers the Meta catalog without treating it as authentication proof", () =>
94
- Effect.scoped(
95
- Effect.gen(function* () {
96
- const binaryPath = yield* fakeCli();
97
- const host = makeHost(metaCatalog);
98
- const snapshot = yield* checkMuseProviderStatus(
99
- settings({ enabled: true, binaryPath, customModels: ["muse-custom"] }),
100
- undefined,
101
- undefined,
102
- async () => host,
103
- );
104
- expect(snapshot.status).toBe("ready");
105
- expect(snapshot.message).toBeUndefined();
106
- expect(snapshot.slashCommands).toEqual([COMPACT_SLASH_COMMAND]);
107
- expect(snapshot.auth).toEqual({ status: "unknown" });
108
- expect(snapshot.version).toBe("1.0.3-R2198.1");
109
- expect(snapshot.models.map((model) => model.slug)).toEqual([
110
- "muse-wonder-1.0",
111
- "muse-custom",
112
- ]);
113
- expect(snapshot.models.map((model) => model.name)).toEqual([
114
- "Muse Wonder 1.0",
115
- "muse-custom",
116
- ]);
117
- const descriptor = snapshot.models[0]?.capabilities?.optionDescriptors?.[0];
118
- expect(
119
- descriptor?.type === "select" && descriptor.options.map((option) => option.id),
120
- ).toEqual(["low", "medium", "high", "xhigh", "max"]);
121
- expect(host.connection.request).toHaveBeenCalledWith("model/list", {});
122
- expect(host.connection.command).not.toHaveBeenCalled();
123
- expect(host.close).toHaveBeenCalledOnce();
124
- }),
125
- ),
90
+ Effect.gen(function* () {
91
+ const binaryPath = yield* fakeCli();
92
+ const host = makeHost(metaCatalog);
93
+ const snapshot = yield* checkMuseProviderStatus(
94
+ settings({ enabled: true, binaryPath, customModels: ["muse-custom"] }),
95
+ undefined,
96
+ undefined,
97
+ async () => host,
98
+ );
99
+ expect(snapshot.status).toBe("ready");
100
+ expect(snapshot.message).toBeUndefined();
101
+ expect(snapshot.slashCommands).toEqual([COMPACT_SLASH_COMMAND]);
102
+ expect(snapshot.auth).toEqual({ status: "unknown" });
103
+ expect(snapshot.version).toBe("1.0.3-R2198.1");
104
+ expect(snapshot.models.map((model) => model.slug)).toEqual([
105
+ "muse-wonder-1.0",
106
+ "muse-custom",
107
+ ]);
108
+ expect(snapshot.models.map((model) => model.name)).toEqual([
109
+ "Muse Wonder 1.0",
110
+ "muse-custom",
111
+ ]);
112
+ const descriptor = snapshot.models[0]?.capabilities?.optionDescriptors?.[0];
113
+ expect(
114
+ descriptor?.type === "select" && descriptor.options.map((option) => option.id),
115
+ ).toEqual(["low", "medium", "high", "xhigh", "max"]);
116
+ expect(host.connection.request).toHaveBeenCalledWith("model/list", {});
117
+ expect(host.connection.command).not.toHaveBeenCalled();
118
+ expect(host.close).toHaveBeenCalledOnce();
119
+ }),
120
);
121
122
it.effect("keeps an empty discovered catalog empty instead of advertising a fallback model", () =>
129
- Effect.scoped(
130
- Effect.gen(function* () {
131
- const binaryPath = yield* fakeCli();
132
- const host = makeHost({ providerId: "meta", models: [] });
133
- const snapshot = yield* checkMuseProviderStatus(
134
- settings({ enabled: true, binaryPath }),
135
- undefined,
136
- undefined,
137
- async () => host,
138
- );
139
- expect(snapshot.status).toBe("warning");
140
- expect(snapshot.models).toEqual([]);
141
- expect(host.close).toHaveBeenCalledOnce();
142
- }),
143
- ),
123
+ Effect.gen(function* () {
124
+ const binaryPath = yield* fakeCli();
125
+ const host = makeHost({ providerId: "meta", models: [] });
126
+ const snapshot = yield* checkMuseProviderStatus(
127
+ settings({ enabled: true, binaryPath }),
128
+ undefined,
129
+ undefined,
130
+ async () => host,
131
+ );
132
+ expect(snapshot.status).toBe("warning");
133
+ expect(snapshot.models).toEqual([]);
134
+ expect(host.close).toHaveBeenCalledOnce();
135
+ }),
136
);
137
});
packages/provider-opencode/src/server/adapter.test.ts
+29
-116
@@ -339,10 +339,7 @@ describe("OpenCodeAdapterV2", () => {
339
assert.equal(Object.hasOwn(payload, "variant"), false);
340
}
341
if (kind === "unset") assert.equal(inventoryCalls, 0);
342
- }).pipe(
343
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
344
- Effect.scoped,
345
- ),
342
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
343
);
344
345
it.effect("reuses successful model variants for the session and retries failed inventories", () =>
@@ -418,10 +415,7 @@ describe("OpenCodeAdapterV2", () => {
415
variants = { medium: {} };
416
assert.isFalse(Object.hasOwn(yield* submit(), "variant"));
417
assert.equal(inventoryCalls, 2);
421
- }).pipe(
422
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
423
- Effect.scoped,
424
- ),
418
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
419
);
420
421
it.effect("keeps queued steers behind a cold catalog lookup and cancels them on stop", () =>
@@ -511,10 +505,7 @@ describe("OpenCodeAdapterV2", () => {
505
assert.isTrue(Exit.isFailure(yield* Fiber.join(firstSteer)));
506
assert.isTrue(Exit.isFailure(yield* Fiber.join(secondSteer)));
507
assert.deepEqual(calls, ["catalog", "catalog-aborted", "abort"]);
514
- }).pipe(
515
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
516
- Effect.scoped,
517
- ),
508
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
509
);
510
511
it.effect.each([
@@ -575,10 +566,7 @@ describe("OpenCodeAdapterV2", () => {
566
const terminal = events.findLast((event) => event.type === "turn.terminal");
567
assert.strictEqual(session?.providerSession.lastError, sample.expected);
568
assert.strictEqual(terminal?.failure?.message, sample.expected);
578
- }).pipe(
579
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
580
- Effect.scoped,
581
- ),
569
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
570
);
571
572
it.effect("classifies APIError 429 as a usage limit", () =>
@@ -620,10 +608,7 @@ describe("OpenCodeAdapterV2", () => {
608
);
609
assert.equal(terminal?.status, "failed");
610
assert.equal(terminal?.failure?.class, "usage_limit");
623
- }).pipe(
624
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
625
- Effect.scoped,
626
- ),
611
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
612
);
613
614
it.effect("applies a changed runtime policy to the session on resume and turn start", () =>
@@ -676,10 +661,7 @@ describe("OpenCodeAdapterV2", () => {
661
assert.deepStrictEqual(updates.slice(1), [
662
{ sessionID: "root", permission: openCodePermissionRules(fullAccess) },
663
]);
679
- }).pipe(
680
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
681
- Effect.scoped,
682
- ),
664
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
665
);
666
667
it.effect("applies a changed runtime policy to existing subagent sessions", () =>
@@ -782,10 +764,7 @@ describe("OpenCodeAdapterV2", () => {
764
});
765
assert.equal(permissionAction(nativePermissions.get(child)!, "bash"), "ask");
766
assert.equal(permissionAction(nativePermissions.get(child)!, "task"), "deny");
785
- }).pipe(
786
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
787
- Effect.scoped,
788
- ),
767
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
768
);
769
770
it.effect.each(["completed", "failed", "unavailable"] as const)(
@@ -916,10 +895,7 @@ describe("OpenCodeAdapterV2", () => {
895
hasSubagents: false,
896
},
897
);
919
- }).pipe(
920
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
921
- Effect.scoped,
922
- ),
898
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
899
);
900
901
// OpenCode 1.18.18 reports a context overflow as session.error, then auto-compacts and continues.
@@ -1022,10 +998,7 @@ describe("OpenCodeAdapterV2", () => {
998
event.turnItem.text === "Post-compaction step",
999
),
1000
);
1025
- }).pipe(
1026
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1027
- Effect.scoped,
1028
- ),
1001
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1002
);
1003
1004
it.effect("fails an explicit compaction that OpenCode reports as a context overflow", () =>
@@ -1069,10 +1042,7 @@ describe("OpenCodeAdapterV2", () => {
1042
(event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction",
1043
),
1044
);
1072
- }).pipe(
1073
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1074
- Effect.scoped,
1075
- ),
1045
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1046
);
1047
1048
it.effect("preserves native multi-select and custom-answer flags through a live reply", () =>
@@ -1147,10 +1117,7 @@ describe("OpenCodeAdapterV2", () => {
1117
answers: { "question-0-drinks": ["Tea", "Water"] },
1118
});
1119
assert.deepInclude(delivered, { answers: [["Tea", "Water"]] });
1150
- }).pipe(
1151
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1152
- Effect.scoped,
1153
- ),
1120
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1121
);
1122
1123
it.effect(
@@ -1399,10 +1366,7 @@ describe("OpenCodeAdapterV2", () => {
1366
const assistant = items.filter((item) => item.type === "assistant_message");
1367
assert.equal(assistant.at(-1)?.text, "Tool results received");
1368
assert.equal(assistant.at(-1)?.status, "completed");
1402
- }).pipe(
1403
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1404
- Effect.scoped,
1405
- ),
1369
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1370
);
1371
1372
// OpenCode 1.18.32 background tasks complete at launch; children stay busy after root settlement.
@@ -1495,10 +1459,7 @@ describe("OpenCodeAdapterV2", () => {
1459
yield* push(status(child, "idle"));
1460
yield* push({ type: "session.idle", properties: { sessionID: child } });
1461
assert.isFalse(yield* hasPendingBackgroundWork, "an idle child must not pin idle release");
1498
- }).pipe(
1499
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1500
- Effect.scoped,
1501
- ),
1462
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1463
);
1464
1465
it.effect("projects OpenCode read output and search titles from native tool calls", () =>
@@ -1625,10 +1586,7 @@ describe("OpenCodeAdapterV2", () => {
1586
);
1587
assert.ok(emptyWebSearch?.type === "web_search");
1588
assert.equal(emptyWebSearch.results, undefined);
1628
- }).pipe(
1629
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1630
- Effect.scoped,
1631
- ),
1589
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1590
);
1591
1592
it.effect("drops cancelled OpenCode todos so a finished list completes", () =>
@@ -1681,10 +1639,7 @@ describe("OpenCodeAdapterV2", () => {
1639
],
1640
);
1641
assert.equal(plan.status, "completed");
1684
- }).pipe(
1685
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1686
- Effect.scoped,
1687
- ),
1642
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1643
);
1644
1645
it.effect("presents OpenCode MCP calls without treating remote tools as local edits", () =>
@@ -1852,10 +1807,7 @@ describe("OpenCodeAdapterV2", () => {
1807
assert.equal(items[3]?.toolName, "ambiguous_server_edit_document");
1808
assert.isUndefined(items[3]?.toolSource);
1809
assert.equal(statusReads, 1);
1855
- }).pipe(
1856
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1857
- Effect.scoped,
1858
- ),
1810
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1811
);
1812
1813
it.effect("admits a native command on its user receipt before generation completes", () =>
@@ -1918,10 +1870,7 @@ describe("OpenCodeAdapterV2", () => {
1870
yield* Fiber.join(start);
1871
assert.equal(promptCalls, 0);
1872
release.resolve();
1921
- }).pipe(
1922
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
1923
- Effect.scoped,
1924
- ),
1873
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1874
);
1875
1876
it.effect("keeps an admitted native command running when its HTTP request times out", () =>
@@ -1998,10 +1947,7 @@ describe("OpenCodeAdapterV2", () => {
1947
"completed",
1948
"a command admitted by its user receipt must not fail when its HTTP request times out",
1949
);
2001
- }).pipe(
2002
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2003
- Effect.scoped,
2004
- ),
1950
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
1951
);
1952
1953
it.effect("compacts with the native summarize API and emits a completed compaction", () =>
@@ -2056,10 +2002,7 @@ describe("OpenCodeAdapterV2", () => {
2002
assert.isTrue(
2003
events.some((event) => event.type === "turn.terminal" && event.status === "completed"),
2004
);
2059
- }).pipe(
2060
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2061
- Effect.scoped,
2062
- ),
2005
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2006
);
2007
2008
it.effect("ends a turn on the provider thread it started on", () =>
@@ -2096,10 +2039,7 @@ describe("OpenCodeAdapterV2", () => {
2039
Stream.runHead,
2040
);
2041
assert.equal(Option.getOrUndefined(terminal)?.providerThreadId, forkedRow.id);
2099
- }).pipe(
2100
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2101
- Effect.scoped,
2102
- ),
2042
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2043
);
2044
2045
it.effect("does not restore messages beyond OpenCode's persisted revert boundary", () =>
@@ -2184,10 +2124,7 @@ describe("OpenCodeAdapterV2", () => {
2124
["user-kept", "assistant-kept"],
2125
);
2126
assert.equal(snapshot.providerThread.nativeConversationHeadRef?.nativeId, "user-kept");
2187
- }).pipe(
2188
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2189
- Effect.scoped,
2190
- ),
2127
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2128
);
2129
2130
it.effect("steers with the turn's agent, reasoning variant and system instructions", () =>
@@ -2240,10 +2177,7 @@ describe("OpenCodeAdapterV2", () => {
2177
{ agent: steer?.agent, variant: steer?.variant, system: steer?.system },
2178
{ agent: start?.agent, variant: start?.variant, system: start?.system },
2179
);
2243
- }).pipe(
2244
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2245
- Effect.scoped,
2246
- ),
2180
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2181
);
2182
2183
it.effect("keeps a newly admitted prompt alive across stale idle and delayed busy evidence", () =>
@@ -2560,10 +2494,7 @@ describe("OpenCodeAdapterV2", () => {
2494
);
2495
const interrupted = yield* runtime.readThreadSnapshot({ providerThread });
2496
assert.equal(interrupted.providerTurns.at(-1)?.status, "interrupted");
2563
- }).pipe(
2564
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2565
- Effect.scoped,
2566
- ),
2497
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2498
);
2499
2500
it.effect("rejects steering when stop wins the extracted-text lookup", () =>
@@ -2651,10 +2582,7 @@ describe("OpenCodeAdapterV2", () => {
2582
providerThread: harness.providerThread,
2583
});
2584
assert.equal(stopped.providerTurns.at(-1)?.status, "interrupted");
2654
- }).pipe(
2655
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2656
- Effect.scoped,
2657
- ),
2585
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2586
);
2587
2588
it.effect("interrupts an initial prompt while its SDK request is pending", () =>
@@ -2819,10 +2747,7 @@ describe("OpenCodeAdapterV2", () => {
2747
(event.type === "provider_session.updated" && event.providerSession.status === "error"),
2748
),
2749
);
2822
- }).pipe(
2823
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2824
- Effect.scoped,
2825
- ),
2750
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2751
);
2752
2753
it.effect("fails an active turn when the OpenCode event stream ends cleanly", () =>
@@ -2865,10 +2790,7 @@ describe("OpenCodeAdapterV2", () => {
2790
assert.equal(terminal?.failure?.class, "transport_error");
2791
assert.equal(terminal?.threadDisposition, "broken");
2792
assert.equal((yield* Effect.exit(harness.startTurn()))._tag, "Failure");
2868
- }).pipe(
2869
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2870
- Effect.scoped,
2871
- ),
2793
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2794
);
2795
2796
it.effect("fails compaction when its response races stream termination", () =>
@@ -2929,10 +2851,7 @@ describe("OpenCodeAdapterV2", () => {
2851
event.turnItem.status === "completed",
2852
),
2853
);
2932
- }).pipe(
2933
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2934
- Effect.scoped,
2935
- ),
2854
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2855
);
2856
2857
it.effect("does not register a turn after the OpenCode event stream ends", () =>
@@ -2990,10 +2909,7 @@ describe("OpenCodeAdapterV2", () => {
2909
2910
assert.isTrue(Exit.isFailure(yield* Fiber.join(start)));
2911
assert.equal(promptCalls, 0);
2993
- }).pipe(
2994
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2995
- Effect.scoped,
2996
- ),
2912
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2913
);
2914
2915
it("holds stale idle through prompt admission until the new user message is observed", () => {
@@ -3401,10 +3317,7 @@ it.effect.each([false, true])(
3317
assert.equal(result.messages.length, 0);
3318
assert.deepEqual(calls, ["fork", "permissions"]);
3319
}
3404
- }).pipe(
3405
- Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
3406
- Effect.scoped,
3407
- ),
3320
+ }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
3321
);
3322
3323
it.live.each([true, false])("opens an authenticated OpenCode session (external=%s)", (external) =>
packages/provider-opencode/src/server/driver.test.ts
+11
-11
@@ -279,7 +279,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
279
}),
280
);
281
assert.deepStrictEqual(serverStarts, ["start"]);
282
- }).pipe(Effect.scoped),
282
+ }),
283
);
284
285
it.effect.each(["2.1.2", null])(
@@ -312,7 +312,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
312
assert.strictEqual(maintenance.packageName, "@opencode/cli");
313
assert.isNotEmpty(probeOffline);
314
assert.isTrue(probeOffline.every((offline) => offline === "1"));
315
- }).pipe(Effect.scoped),
315
+ }),
316
);
317
318
it.effect("skips the installed CLI probe when a localhost provider is disabled", () =>
@@ -333,7 +333,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
333
const snapshot = yield* instance.snapshot.refresh;
334
assert.isFalse(snapshot.enabled);
335
assert.deepStrictEqual(probed, []);
336
- }).pipe(Effect.scoped),
336
+ }),
337
);
338
339
it.effect("opens a session through OpenCode 2 that a lazy mise shim installs on first use", () =>
@@ -356,7 +356,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
356
assert.deepStrictEqual(serverStarts, ["start"], "the OpenCode 2 adapter starts its server");
357
const capabilities = yield* instance.orchestrationAdapter.getCapabilities();
358
assert.isTrue(capabilities.sessions.supportsRuntimeModeSwitchInSession);
359
- }).pipe(Effect.scoped),
359
+ }),
360
);
361
362
it.effect("does not scan a workspace through a 1.x server it could not probe offline", () =>
@@ -368,7 +368,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
368
369
yield* Effect.flip(instance.snapshotForCwd!(process.cwd()));
370
assert.deepStrictEqual(serverStarts, []);
371
- }).pipe(Effect.scoped),
371
+ }),
372
);
373
374
it.effect.each([
@@ -404,7 +404,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
404
capabilities.turns.supportsNativeGoals === true,
405
version.endsWith("2.2.5") || version.endsWith("2.2.6"),
406
);
407
- }).pipe(Effect.scoped),
407
+ }),
408
);
409
410
it.effect("uses the connected OpenCode version for goal support after an upgrade", () =>
@@ -479,7 +479,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
479
assert.isTrue(
480
(yield* instance.orchestrationAdapter.getCapabilities()).turns.supportsNativeGoals,
481
);
482
- }).pipe(Effect.scoped),
482
+ }),
483
);
484
485
it.effect("answers capability reads without waiting on an unreachable server", () =>
@@ -876,7 +876,7 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => {
876
} else {
877
assert.deepStrictEqual(snapshot?.usageLimits?.windows, []);
878
}
879
- }).pipe(Effect.scoped),
879
+ }),
880
);
881
882
it.effect.each(
@@ -1227,7 +1227,7 @@ it.layer(Layer.mergeAll(layer, Layer.succeed(OpenCodeRuntime.OpenCodeRuntime, op
1227
assert.deepStrictEqual(slugsOf(unreadable), ["opencode/big-pickle"]);
1228
assert.strictEqual(unreadable.workspaceModels, undefined);
1229
assert.strictEqual(unreadable.workspaceModelsPending, true);
1230
- }).pipe(Effect.scoped),
1230
+ }),
1231
);
1232
},
1233
);
@@ -1262,7 +1262,7 @@ it.layer(layerUpdate)("OpenCodeDriver updates", (it) => {
1262
const v2 = yield* instance.snapshot.resolveMaintenance({ fresh: true });
1263
assert.strictEqual(v2.packageName, "@opencode/cli");
1264
assert.isNull(v2.update);
1265
- }).pipe(Effect.scoped),
1265
+ }),
1266
);
1267
1268
it.effect(
@@ -1297,6 +1297,6 @@ it.layer(layerUpdate)("OpenCodeDriver updates", (it) => {
1297
"after upgrading to 2.x, the next session must not open through the 1.x adapter",
1298
);
1299
assert.include(serverStarts, "start", "the OpenCode 2 adapter starts its server");
1300
- }).pipe(Effect.scoped),
1300
+ }),
1301
);
1302
});
packages/provider-opencode/src/server/status.test.ts
+27
-29
@@ -801,37 +801,35 @@ it.layer(layerTest)("checkOpenCodeProviderStatus", (it) => {
801
);
802
803
it.effect("reports the upgraded CLI without restarting a borrowed OpenCode server", () =>
804
- Effect.scoped(
805
- Effect.gen(function* () {
806
- const settings = makeOpenCodeSettings();
807
- const owner = yield* OpenCodeServerOwner.make({
808
- binaryPath: settings.binaryPath,
809
- directory: process.cwd(),
810
- });
811
- yield* owner.withServer(() =>
812
- Effect.gen(function* () {
813
- runtimeMock.state.versionStdout = "opencode 1.14.20\n";
814
- const snapshot = yield* checkOpenCodeProviderStatus(
815
- settings,
816
- process.cwd(),
817
- probeOpenCodeRuntime(settings).pipe(
818
- Effect.provideService(
819
- HttpClient.HttpClient,
820
- replayOpenCodeServer(OPENCODE_1_RESPONSES, settings.serverPassword),
821
- ),
822
- Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
804
+ Effect.gen(function* () {
805
+ const settings = makeOpenCodeSettings();
806
+ const owner = yield* OpenCodeServerOwner.make({
807
+ binaryPath: settings.binaryPath,
808
+ directory: process.cwd(),
809
+ });
810
+ yield* owner.withServer(() =>
811
+ Effect.gen(function* () {
812
+ runtimeMock.state.versionStdout = "opencode 1.14.20\n";
813
+ const snapshot = yield* checkOpenCodeProviderStatus(
814
+ settings,
815
+ process.cwd(),
816
+ probeOpenCodeRuntime(settings).pipe(
817
+ Effect.provideService(
818
+ HttpClient.HttpClient,
819
+ replayOpenCodeServer(OPENCODE_1_RESPONSES, settings.serverPassword),
820
),
824
- Effect.succeed([]),
825
- ).pipe(Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, owner));
821
+ Effect.provideService(OpenCodeRuntime.OpenCodeRuntime, OpenCodeRuntimeTestDouble),
822
+ ),
823
+ Effect.succeed([]),
824
+ ).pipe(Effect.provideService(OpenCodeServerOwner.OpenCodeServerOwner, owner));
825
827
- NodeAssert.equal(snapshot.version, "1.14.19");
828
- NodeAssert.equal(snapshot.installedVersion, "1.14.20");
829
- NodeAssert.equal(runtimeMock.state.startCalls, 1);
830
- NodeAssert.equal(runtimeMock.state.closeCalls, 0);
831
- }),
832
- );
833
- }),
834
- ),
826
+ NodeAssert.equal(snapshot.version, "1.14.19");
827
+ NodeAssert.equal(snapshot.installedVersion, "1.14.20");
828
+ NodeAssert.equal(runtimeMock.state.startCalls, 1);
829
+ NodeAssert.equal(runtimeMock.state.closeCalls, 0);
830
+ }),
831
+ );
832
+ }),
833
);
834
835
it.effect("lists a local OpenCode 2 binary's models in Full access only, never via 1.x", () =>
packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts
+2
-2
@@ -81,7 +81,7 @@ describe("OpenCode2Client event subscription", () => {
81
assert.strictEqual(error._tag, "HttpClientError");
82
assert.strictEqual(error.reason._tag, "TransportError");
83
assert.isTrue(Cause.isTimeoutError(error.cause));
84
- }).pipe(Effect.scoped),
84
+ }),
85
);
86
});
87
@@ -198,7 +198,7 @@ it.effect("closes an event subscription that recovery has not started reading",
198
assert.isFalse(signals[0]!.aborted);
199
yield* Scope.close(scope, Exit.void);
200
assert.isTrue(signals[0]!.aborted);
201
- }).pipe(Effect.scoped),
201
+ }),
202
);
203
204
describe("OpenCode2Client native image jobs", () => {
packages/provider-opencode/src/server/v2/OpenCode2Service.test.ts
+1
-1
@@ -91,6 +91,6 @@ it.layer(NodeServices.layer)("replaceOutdatedService", (it) => {
91
command: [path.join(binDirectory, "opencode"), "serve", "--service"],
92
env: { ...environment, PATH: "/nowhere", ELECTRON_RUN_AS_NODE: undefined },
93
});
94
- }).pipe(Effect.scoped),
94
+ }),
95
);
96
});
packages/provider-pi/src/server/driver.test.ts
+4
-4
@@ -180,7 +180,7 @@ it.layer(layerTest)("PiDriver workspace discovery", (it) => {
180
["--offline"],
181
);
182
}
183
- }).pipe(Effect.scoped),
183
+ }),
184
);
185
186
it.effect("does not run a disabled provider's workspace probe", () =>
@@ -195,7 +195,7 @@ it.layer(layerTest)("PiDriver workspace discovery", (it) => {
195
const workspace = yield* instance.snapshotForCwd!("/first");
196
assert.isFalse(workspace.enabled);
197
assert.deepEqual(workspace.skills, []);
198
- }).pipe(Effect.scoped),
198
+ }),
199
);
200
201
it.effect.each([true, false])(
@@ -234,7 +234,7 @@ it.layer(layerTest)("PiDriver workspace discovery", (it) => {
234
["test/other", []],
235
],
236
);
237
- }).pipe(Effect.scoped),
237
+ }),
238
);
239
240
it.effect(
@@ -254,6 +254,6 @@ it.layer(layerTest)("PiDriver workspace discovery", (it) => {
254
(yield* instance.snapshot.getSnapshot).skills.map((skill) => skill.name),
255
["personal"],
256
);
257
- }).pipe(Effect.scoped),
257
+ }),
258
);
259
});
packages/shared/src/DrainableWorker.test.ts
+35
-37
@@ -81,51 +81,49 @@ describe("makeDrainableWorker", () => {
81
});
82
83
it.effect("waits for work enqueued during active processing before draining", () =>
84
- Effect.scoped(
85
- Effect.gen(function* () {
86
- const processed: string[] = [];
87
- const firstStarted = yield* Deferred.make<void>();
88
- const releaseFirst = yield* Deferred.make<void>();
89
- const secondStarted = yield* Deferred.make<void>();
90
- const releaseSecond = yield* Deferred.make<void>();
84
+ Effect.gen(function* () {
85
+ const processed: string[] = [];
86
+ const firstStarted = yield* Deferred.make<void>();
87
+ const releaseFirst = yield* Deferred.make<void>();
88
+ const secondStarted = yield* Deferred.make<void>();
89
+ const releaseSecond = yield* Deferred.make<void>();
90
92
- const worker = yield* makeDrainableWorker((item: string) =>
93
- Effect.gen(function* () {
94
- if (item === "first") {
95
- yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
96
- yield* Deferred.await(releaseFirst);
97
- }
91
+ const worker = yield* makeDrainableWorker((item: string) =>
92
+ Effect.gen(function* () {
93
+ if (item === "first") {
94
+ yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
95
+ yield* Deferred.await(releaseFirst);
96
+ }
97
99
- if (item === "second") {
100
- yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
101
- yield* Deferred.await(releaseSecond);
102
- }
98
+ if (item === "second") {
99
+ yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
100
+ yield* Deferred.await(releaseSecond);
101
+ }
102
104
- processed.push(item);
105
- }),
106
- );
103
+ processed.push(item);
104
+ }),
105
+ );
106
108
- yield* worker.enqueue("first");
109
- yield* Deferred.await(firstStarted);
107
+ yield* worker.enqueue("first");
108
+ yield* Deferred.await(firstStarted);
109
111
- const drained = yield* Deferred.make<void>();
112
- yield* Effect.forkChild(
113
- worker.drain.pipe(
114
- Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie)),
115
- ),
116
- );
110
+ const drained = yield* Deferred.make<void>();
111
+ yield* Effect.forkChild(
112
+ worker.drain.pipe(
113
+ Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie)),
114
+ ),
115
+ );
116
118
- yield* worker.enqueue("second");
119
- yield* Deferred.succeed(releaseFirst, undefined);
120
- yield* Deferred.await(secondStarted);
117
+ yield* worker.enqueue("second");
118
+ yield* Deferred.succeed(releaseFirst, undefined);
119
+ yield* Deferred.await(secondStarted);
120
122
- expect(yield* Deferred.isDone(drained)).toBe(false);
121
+ expect(yield* Deferred.isDone(drained)).toBe(false);
122
124
- yield* Deferred.succeed(releaseSecond, undefined);
125
- yield* Deferred.await(drained);
123
+ yield* Deferred.succeed(releaseSecond, undefined);
124
+ yield* Deferred.await(drained);
125
127
- expect(processed).toEqual(["first", "second"]);
128
- }),
129
- ),
126
+ expect(processed).toEqual(["first", "second"]);
127
+ }),
128
);
129
});
packages/shared/src/KeyedCoalescingWorker.test.ts
+162
-170
@@ -7,184 +7,176 @@ import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker.ts";
7
8
describe("makeKeyedCoalescingWorker", () => {
9
it.effect("lets a queued key drain before a continuously updated key finishes", () =>
10
- Effect.scoped(
11
- Effect.gen(function* () {
12
- const processed: string[] = [];
13
- const busyStarted = yield* Deferred.make<void>();
14
- const releaseBusy = yield* Deferred.make<void>();
15
-
16
- const worker = yield* makeKeyedCoalescingWorker<string, number, never, never>({
17
- merge: (_current, next) => next,
18
- process: (key, value): Effect.Effect<void> =>
19
- Effect.gen(function* () {
20
- processed.push(`${key}:${value}`);
21
- if (key !== "busy") return;
22
-
23
- if (value === 1) {
24
- yield* Deferred.succeed(busyStarted, undefined);
25
- yield* Deferred.await(releaseBusy);
26
- }
27
- if (value < 4) yield* worker.enqueue(key, value + 1);
28
- }),
29
- });
30
-
31
- yield* worker.enqueue("busy", 1);
32
- yield* Deferred.await(busyStarted);
33
- yield* worker.enqueue("quiet", 1);
34
- yield* Deferred.succeed(releaseBusy, undefined);
35
- yield* worker.drainKey("quiet");
36
- yield* worker.drainKey("busy");
37
-
38
- expect(processed).toEqual(["busy:1", "quiet:1", "busy:2", "busy:3", "busy:4"]);
39
- }),
40
- ),
10
+ Effect.gen(function* () {
11
+ const processed: string[] = [];
12
+ const busyStarted = yield* Deferred.make<void>();
13
+ const releaseBusy = yield* Deferred.make<void>();
14
+
15
+ const worker = yield* makeKeyedCoalescingWorker<string, number, never, never>({
16
+ merge: (_current, next) => next,
17
+ process: (key, value): Effect.Effect<void> =>
18
+ Effect.gen(function* () {
19
+ processed.push(`${key}:${value}`);
20
+ if (key !== "busy") return;
21
+
22
+ if (value === 1) {
23
+ yield* Deferred.succeed(busyStarted, undefined);
24
+ yield* Deferred.await(releaseBusy);
25
+ }
26
+ if (value < 4) yield* worker.enqueue(key, value + 1);
27
+ }),
28
+ });
29
+
30
+ yield* worker.enqueue("busy", 1);
31
+ yield* Deferred.await(busyStarted);
32
+ yield* worker.enqueue("quiet", 1);
33
+ yield* Deferred.succeed(releaseBusy, undefined);
34
+ yield* worker.drainKey("quiet");
35
+ yield* worker.drainKey("busy");
36
+
37
+ expect(processed).toEqual(["busy:1", "quiet:1", "busy:2", "busy:3", "busy:4"]);
38
+ }),
39
);
40
41
it.effect("merges updates while waiting behind another key and drains the merged batch", () =>
44
- Effect.scoped(
45
- Effect.gen(function* () {
46
- const processed: string[] = [];
47
- const busyStarted = yield* Deferred.make<void>();
48
- const releaseBusy = yield* Deferred.make<void>();
49
- const quietStarted = yield* Deferred.make<void>();
50
- const releaseQuiet = yield* Deferred.make<void>();
51
- const mergedStarted = yield* Deferred.make<void>();
52
- const releaseMerged = yield* Deferred.make<void>();
53
-
54
- const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
55
- merge: (current, next) => `${current}+${next}`,
56
- process: (key, value) =>
57
- Effect.gen(function* () {
58
- processed.push(`${key}:${value}`);
59
- if (value === "first") {
60
- yield* Deferred.succeed(busyStarted, undefined);
61
- yield* Deferred.await(releaseBusy);
62
- } else if (key === "quiet") {
63
- yield* Deferred.succeed(quietStarted, undefined);
64
- yield* Deferred.await(releaseQuiet);
65
- } else if (value === "a+b+c") {
66
- yield* Deferred.succeed(mergedStarted, undefined);
67
- yield* Deferred.await(releaseMerged);
68
- }
69
- }),
70
- });
71
-
72
- yield* worker.enqueue("busy", "first");
73
- yield* Deferred.await(busyStarted);
74
- yield* worker.enqueue("quiet", "quiet");
75
- yield* worker.enqueue("busy", "a");
76
- yield* Deferred.succeed(releaseBusy, undefined);
77
- yield* Deferred.await(quietStarted);
78
- expect(processed).toEqual(["busy:first", "quiet:quiet"]);
79
- yield* worker.enqueue("busy", "b");
80
- yield* worker.enqueue("busy", "c");
81
-
82
- const drained = yield* Deferred.make<void>();
83
- yield* Effect.forkChild(
84
- worker.drainKey("busy").pipe(Effect.andThen(Deferred.succeed(drained, undefined))),
85
- { startImmediately: true },
86
- );
87
- expect(yield* Deferred.isDone(drained)).toBe(false);
88
-
89
- yield* Deferred.succeed(releaseQuiet, undefined);
90
- yield* Deferred.await(mergedStarted);
91
- expect(yield* Deferred.isDone(drained)).toBe(false);
92
- yield* Deferred.succeed(releaseMerged, undefined);
93
- yield* Deferred.await(drained);
94
- yield* worker.drainKey("quiet");
95
-
96
- expect(processed).toEqual(["busy:first", "quiet:quiet", "busy:a+b+c"]);
97
- }),
98
- ),
42
+ Effect.gen(function* () {
43
+ const processed: string[] = [];
44
+ const busyStarted = yield* Deferred.make<void>();
45
+ const releaseBusy = yield* Deferred.make<void>();
46
+ const quietStarted = yield* Deferred.make<void>();
47
+ const releaseQuiet = yield* Deferred.make<void>();
48
+ const mergedStarted = yield* Deferred.make<void>();
49
+ const releaseMerged = yield* Deferred.make<void>();
50
+
51
+ const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
52
+ merge: (current, next) => `${current}+${next}`,
53
+ process: (key, value) =>
54
+ Effect.gen(function* () {
55
+ processed.push(`${key}:${value}`);
56
+ if (value === "first") {
57
+ yield* Deferred.succeed(busyStarted, undefined);
58
+ yield* Deferred.await(releaseBusy);
59
+ } else if (key === "quiet") {
60
+ yield* Deferred.succeed(quietStarted, undefined);
61
+ yield* Deferred.await(releaseQuiet);
62
+ } else if (value === "a+b+c") {
63
+ yield* Deferred.succeed(mergedStarted, undefined);
64
+ yield* Deferred.await(releaseMerged);
65
+ }
66
+ }),
67
+ });
68
+
69
+ yield* worker.enqueue("busy", "first");
70
+ yield* Deferred.await(busyStarted);
71
+ yield* worker.enqueue("quiet", "quiet");
72
+ yield* worker.enqueue("busy", "a");
73
+ yield* Deferred.succeed(releaseBusy, undefined);
74
+ yield* Deferred.await(quietStarted);
75
+ expect(processed).toEqual(["busy:first", "quiet:quiet"]);
76
+ yield* worker.enqueue("busy", "b");
77
+ yield* worker.enqueue("busy", "c");
78
+
79
+ const drained = yield* Deferred.make<void>();
80
+ yield* Effect.forkChild(
81
+ worker.drainKey("busy").pipe(Effect.andThen(Deferred.succeed(drained, undefined))),
82
+ { startImmediately: true },
83
+ );
84
+ expect(yield* Deferred.isDone(drained)).toBe(false);
85
+
86
+ yield* Deferred.succeed(releaseQuiet, undefined);
87
+ yield* Deferred.await(mergedStarted);
88
+ expect(yield* Deferred.isDone(drained)).toBe(false);
89
+ yield* Deferred.succeed(releaseMerged, undefined);
90
+ yield* Deferred.await(drained);
91
+ yield* worker.drainKey("quiet");
92
+
93
+ expect(processed).toEqual(["busy:first", "quiet:quiet", "busy:a+b+c"]);
94
+ }),
95
);
96
97
it.effect("waits for latest work enqueued during active processing before draining the key", () =>
102
- Effect.scoped(
103
- Effect.gen(function* () {
104
- const processed: string[] = [];
105
- const firstStarted = yield* Deferred.make<void>();
106
- const releaseFirst = yield* Deferred.make<void>();
107
- const secondStarted = yield* Deferred.make<void>();
108
- const releaseSecond = yield* Deferred.make<void>();
109
-
110
- const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
111
- merge: (_current, next) => next,
112
- process: (key, value) =>
113
- Effect.gen(function* () {
114
- processed.push(`${key}:${value}`);
115
-
116
- if (value === "first") {
117
- yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
118
- yield* Deferred.await(releaseFirst);
119
- }
120
-
121
- if (value === "second") {
122
- yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
123
- yield* Deferred.await(releaseSecond);
124
- }
125
- }),
126
- });
127
-
128
- yield* worker.enqueue("terminal-1", "first");
129
- yield* Deferred.await(firstStarted);
130
-
131
- const drained = yield* Deferred.make<void>();
132
- yield* Effect.forkChild(
133
- worker
134
- .drainKey("terminal-1")
135
- .pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
136
- );
137
-
138
- yield* worker.enqueue("terminal-1", "second");
139
- yield* Deferred.succeed(releaseFirst, undefined);
140
- yield* Deferred.await(secondStarted);
141
-
142
- expect(yield* Deferred.isDone(drained)).toBe(false);
143
-
144
- yield* Deferred.succeed(releaseSecond, undefined);
145
- yield* Deferred.await(drained);
146
-
147
- expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
148
- }),
149
- ),
98
+ Effect.gen(function* () {
99
+ const processed: string[] = [];
100
+ const firstStarted = yield* Deferred.make<void>();
101
+ const releaseFirst = yield* Deferred.make<void>();
102
+ const secondStarted = yield* Deferred.make<void>();
103
+ const releaseSecond = yield* Deferred.make<void>();
104
+
105
+ const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
106
+ merge: (_current, next) => next,
107
+ process: (key, value) =>
108
+ Effect.gen(function* () {
109
+ processed.push(`${key}:${value}`);
110
+
111
+ if (value === "first") {
112
+ yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
113
+ yield* Deferred.await(releaseFirst);
114
+ }
115
+
116
+ if (value === "second") {
117
+ yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
118
+ yield* Deferred.await(releaseSecond);
119
+ }
120
+ }),
121
+ });
122
+
123
+ yield* worker.enqueue("terminal-1", "first");
124
+ yield* Deferred.await(firstStarted);
125
+
126
+ const drained = yield* Deferred.make<void>();
127
+ yield* Effect.forkChild(
128
+ worker
129
+ .drainKey("terminal-1")
130
+ .pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
131
+ );
132
+
133
+ yield* worker.enqueue("terminal-1", "second");
134
+ yield* Deferred.succeed(releaseFirst, undefined);
135
+ yield* Deferred.await(secondStarted);
136
+
137
+ expect(yield* Deferred.isDone(drained)).toBe(false);
138
+
139
+ yield* Deferred.succeed(releaseSecond, undefined);
140
+ yield* Deferred.await(drained);
141
+
142
+ expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
143
+ }),
144
);
145
146
it.effect("requeues pending work for a key after a processor failure and keeps draining", () =>
153
- Effect.scoped(
154
- Effect.gen(function* () {
155
- const processed: string[] = [];
156
- const firstStarted = yield* Deferred.make<void>();
157
- const releaseFailure = yield* Deferred.make<void>();
158
- const secondProcessed = yield* Deferred.make<void>();
159
-
160
- const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
161
- merge: (_current, next) => next,
162
- process: (key, value) =>
163
- Effect.gen(function* () {
164
- processed.push(`${key}:${value}`);
165
-
166
- if (value === "first") {
167
- yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
168
- yield* Deferred.await(releaseFailure);
169
- return yield* Effect.fail("boom");
170
- }
171
-
172
- if (value === "second") {
173
- yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
174
- }
175
- }),
176
- });
177
-
178
- yield* worker.enqueue("terminal-1", "first");
179
- yield* Deferred.await(firstStarted);
180
- yield* worker.enqueue("terminal-2", "quiet");
181
- yield* worker.enqueue("terminal-1", "second");
182
- yield* Deferred.succeed(releaseFailure, undefined);
183
- yield* Deferred.await(secondProcessed);
184
- yield* worker.drainKey("terminal-1");
185
-
186
- expect(processed).toEqual(["terminal-1:first", "terminal-2:quiet", "terminal-1:second"]);
187
- }),
188
- ),
147
+ Effect.gen(function* () {
148
+ const processed: string[] = [];
149
+ const firstStarted = yield* Deferred.make<void>();
150
+ const releaseFailure = yield* Deferred.make<void>();
151
+ const secondProcessed = yield* Deferred.make<void>();
152
+
153
+ const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
154
+ merge: (_current, next) => next,
155
+ process: (key, value) =>
156
+ Effect.gen(function* () {
157
+ processed.push(`${key}:${value}`);
158
+
159
+ if (value === "first") {
160
+ yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
161
+ yield* Deferred.await(releaseFailure);
162
+ return yield* Effect.fail("boom");
163
+ }
164
+
165
+ if (value === "second") {
166
+ yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
167
+ }
168
+ }),
169
+ });
170
+
171
+ yield* worker.enqueue("terminal-1", "first");
172
+ yield* Deferred.await(firstStarted);
173
+ yield* worker.enqueue("terminal-2", "quiet");
174
+ yield* worker.enqueue("terminal-1", "second");
175
+ yield* Deferred.succeed(releaseFailure, undefined);
176
+ yield* Deferred.await(secondProcessed);
177
+ yield* worker.drainKey("terminal-1");
178
+
179
+ expect(processed).toEqual(["terminal-1:first", "terminal-2:quiet", "terminal-1:second"]);
180
+ }),
181
);
182
});
packages/shared/src/observability.test.ts
+274
-291
@@ -255,335 +255,318 @@ describe("observability", () => {
255
it.effect(
256
"keeps trace producers responsive during a slow write, bounds the backlog, and drains on close",
257
() =>
258
- Effect.scoped(
259
- Effect.gen(function* () {
260
- const fs = yield* FileSystem.FileSystem;
261
- const path = yield* Path.Path;
262
- const directory = yield* fs.makeTempDirectoryScoped({
263
- prefix: "t3-trace-backpressure-",
264
- });
265
- const tracePath = path.join(directory, "trace.ndjson");
266
- const started = yield* Deferred.make<void>();
267
- const release = yield* Deferred.make<void>();
268
- const closed = yield* Ref.make(false);
269
- const sink = yield* makeTraceSink({
270
- filePath: tracePath,
271
- maxBytes: 5_000_000,
272
- maxFiles: 2,
273
- batchWindowMs: 10_000,
274
- }).pipe(
275
- Effect.provideService(FileSystem.FileSystem, {
276
- ...fs,
277
- writeFile: (file, data, options) =>
278
- Effect.gen(function* () {
279
- yield* Deferred.succeed(started, undefined);
280
- yield* Deferred.await(release);
281
- yield* fs.writeFile(file, data, options);
282
- }),
283
- }),
284
- );
285
- sink.push(makeRecord("first"));
286
- const flushing = yield* Effect.forkChild(sink.flush);
287
- yield* Deferred.await(started);
288
- for (let index = 0; index < 2_000; index++)
289
- sink.push(makeRecord("small", String(index)));
290
- for (let index = 0; index < 3; index++)
291
- sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
292
- const closing = yield* Effect.forkChild(
293
- sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
294
- );
295
- yield* Effect.yieldNow;
296
- assert.isFalse(yield* Ref.get(closed));
297
- yield* Deferred.succeed(release, undefined);
298
- yield* Fiber.join(flushing);
299
- yield* Fiber.join(closing);
300
- const records = yield* readTraceRecords(tracePath);
301
- assert.deepStrictEqual(
302
- records.map((record) => record.name),
303
- ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
304
- );
305
- assert.isTrue(yield* Ref.get(closed));
306
- }),
307
- ),
308
- );
309
-
310
- it.effect("writes buffered records synchronously for process exit", () =>
311
- Effect.scoped(
258
Effect.gen(function* () {
313
- const fileSystem = yield* FileSystem.FileSystem;
259
+ const fs = yield* FileSystem.FileSystem;
260
const path = yield* Path.Path;
315
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
316
- const tracePath = path.join(tempDir, "exit.trace.ndjson");
261
+ const directory = yield* fs.makeTempDirectoryScoped({
262
+ prefix: "t3-trace-backpressure-",
263
+ });
264
+ const tracePath = path.join(directory, "trace.ndjson");
265
+ const started = yield* Deferred.make<void>();
266
+ const release = yield* Deferred.make<void>();
267
+ const closed = yield* Ref.make(false);
268
const sink = yield* makeTraceSink({
269
filePath: tracePath,
319
- maxBytes: 1_000_000,
270
+ maxBytes: 5_000_000,
271
maxFiles: 2,
272
batchWindowMs: 10_000,
322
- });
323
-
324
- sink.push(makeRecord("before-exit"));
325
- sink.flushSync();
326
- sink.flushSync();
327
-
273
+ }).pipe(
274
+ Effect.provideService(FileSystem.FileSystem, {
275
+ ...fs,
276
+ writeFile: (file, data, options) =>
277
+ Effect.gen(function* () {
278
+ yield* Deferred.succeed(started, undefined);
279
+ yield* Deferred.await(release);
280
+ yield* fs.writeFile(file, data, options);
281
+ }),
282
+ }),
283
+ );
284
+ sink.push(makeRecord("first"));
285
+ const flushing = yield* Effect.forkChild(sink.flush);
286
+ yield* Deferred.await(started);
287
+ for (let index = 0; index < 2_000; index++) sink.push(makeRecord("small", String(index)));
288
+ for (let index = 0; index < 3; index++)
289
+ sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
290
+ const closing = yield* Effect.forkChild(
291
+ sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
292
+ );
293
+ yield* Effect.yieldNow;
294
+ assert.isFalse(yield* Ref.get(closed));
295
+ yield* Deferred.succeed(release, undefined);
296
+ yield* Fiber.join(flushing);
297
+ yield* Fiber.join(closing);
298
const records = yield* readTraceRecords(tracePath);
299
assert.deepStrictEqual(
300
records.map((record) => record.name),
331
- ["before-exit"],
301
+ ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
302
);
303
+ assert.isTrue(yield* Ref.get(closed));
304
}),
334
- ),
305
);
306
337
- it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
338
- Effect.scoped(
339
- Effect.gen(function* () {
340
- const fileSystem = yield* FileSystem.FileSystem;
341
- const path = yield* Path.Path;
342
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
343
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
344
- const maxBytes = 1_024;
345
-
346
- const sink = yield* makeTraceSink({
347
- filePath: tracePath,
348
- maxBytes,
349
- maxFiles: 2,
350
- batchWindowMs: 10_000,
351
- });
352
-
353
- for (let index = 0; index < 256; index += 1) {
354
- sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
355
- }
356
- yield* sink.close();
307
+ it.effect("writes buffered records synchronously for process exit", () =>
308
+ Effect.gen(function* () {
309
+ const fileSystem = yield* FileSystem.FileSystem;
310
+ const path = yield* Path.Path;
311
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
312
+ const tracePath = path.join(tempDir, "exit.trace.ndjson");
313
+ const sink = yield* makeTraceSink({
314
+ filePath: tracePath,
315
+ maxBytes: 1_000_000,
316
+ maxFiles: 2,
317
+ batchWindowMs: 10_000,
318
+ });
319
+
320
+ sink.push(makeRecord("before-exit"));
321
+ sink.flushSync();
322
+ sink.flushSync();
323
+
324
+ const records = yield* readTraceRecords(tracePath);
325
+ assert.deepStrictEqual(
326
+ records.map((record) => record.name),
327
+ ["before-exit"],
328
+ );
329
+ }),
330
+ );
331
358
- const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
359
- (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
360
- );
361
- assert.include(matchingFiles, "shared.trace.ndjson.1");
362
- for (const entry of matchingFiles) {
363
- const stat = yield* fileSystem.stat(path.join(tempDir, entry));
364
- assert.isAtMost(Number(stat.size), maxBytes, entry);
365
- }
366
- }),
367
- ),
332
+ it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
333
+ Effect.gen(function* () {
334
+ const fileSystem = yield* FileSystem.FileSystem;
335
+ const path = yield* Path.Path;
336
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
337
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
338
+ const maxBytes = 1_024;
339
+
340
+ const sink = yield* makeTraceSink({
341
+ filePath: tracePath,
342
+ maxBytes,
343
+ maxFiles: 2,
344
+ batchWindowMs: 10_000,
345
+ });
346
+
347
+ for (let index = 0; index < 256; index += 1) {
348
+ sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
349
+ }
350
+ yield* sink.close();
351
+
352
+ const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
353
+ (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
354
+ );
355
+ assert.include(matchingFiles, "shared.trace.ndjson.1");
356
+ for (const entry of matchingFiles) {
357
+ const stat = yield* fileSystem.stat(path.join(tempDir, entry));
358
+ assert.isAtMost(Number(stat.size), maxBytes, entry);
359
+ }
360
+ }),
361
);
362
363
it.effect("drops a single trace record that cannot fit within the configured limit", () =>
371
- Effect.scoped(
372
- Effect.gen(function* () {
373
- const fileSystem = yield* FileSystem.FileSystem;
374
- const path = yield* Path.Path;
375
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
376
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
377
- const maxBytes = 1_024;
378
-
379
- const sink = yield* makeTraceSink({
380
- filePath: tracePath,
381
- maxBytes,
382
- maxFiles: 2,
383
- batchWindowMs: 10_000,
384
- });
385
-
386
- sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
387
- sink.push(makeRecord("retained"));
388
- yield* sink.close();
389
-
390
- const records = yield* readTraceRecords(tracePath);
391
- const stat = yield* fileSystem.stat(tracePath);
392
- assert.deepEqual(
393
- records.map((record) => record.name),
394
- ["retained"],
395
- );
396
- assert.isAtMost(Number(stat.size), maxBytes);
397
- }),
398
- ),
364
+ Effect.gen(function* () {
365
+ const fileSystem = yield* FileSystem.FileSystem;
366
+ const path = yield* Path.Path;
367
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
368
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
369
+ const maxBytes = 1_024;
370
+
371
+ const sink = yield* makeTraceSink({
372
+ filePath: tracePath,
373
+ maxBytes,
374
+ maxFiles: 2,
375
+ batchWindowMs: 10_000,
376
+ });
377
+
378
+ sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
379
+ sink.push(makeRecord("retained"));
380
+ yield* sink.close();
381
+
382
+ const records = yield* readTraceRecords(tracePath);
383
+ const stat = yield* fileSystem.stat(tracePath);
384
+ assert.deepEqual(
385
+ records.map((record) => record.name),
386
+ ["retained"],
387
+ );
388
+ assert.isAtMost(Number(stat.size), maxBytes);
389
+ }),
390
);
391
392
it.effect("keeps WebSocket credentials out of trace files and exported spans", () =>
402
- Effect.scoped(
403
- Effect.gen(function* () {
404
- const fileSystem = yield* FileSystem.FileSystem;
405
- const path = yield* Path.Path;
406
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
407
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
408
- const sink = yield* makeTraceSink({
409
- filePath: tracePath,
410
- maxBytes: 1024 * 1024,
411
- maxFiles: 2,
412
- batchWindowMs: 10_000,
413
- });
414
- const delegates: Array<Tracer.NativeSpan> = [];
415
- const tracer = yield* makeLocalFileTracer({
416
- filePath: tracePath,
417
- maxBytes: 1024 * 1024,
418
- maxFiles: 2,
419
- batchWindowMs: 10_000,
420
- sink,
421
- delegate: Tracer.make({
422
- span: (options) => {
423
- const span = new Tracer.NativeSpan(options);
424
- delegates.push(span);
425
- return span;
426
- },
427
- }),
428
- });
429
- const url = "/ws?wsTicket=ticket-secret&dpop=proof-secret&clientSurface=web";
430
-
431
- yield* Effect.annotateCurrentSpan({
432
- "url.full": `http://127.0.0.1:3773${url}`,
433
- "url.query": url.slice(4),
434
- }).pipe(
435
- Effect.withSpan("GET", { kind: "server" }),
436
- Effect.provideService(Tracer.Tracer, tracer),
437
- );
438
- yield* Effect.die(new Error(`RequestParseError (GET ${url})`)).pipe(
439
- Effect.tapCause((cause) => Effect.logError(cause)),
440
- Effect.withSpan("DeviceHubProxy.proxyWebSocket"),
441
- Effect.provideService(Tracer.Tracer, tracer),
442
- Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })),
443
- Effect.exit,
444
- );
445
- yield* sink.close();
446
-
447
- const written = yield* fileSystem.readFileString(tracePath);
448
- const exported = delegates.map((span) =>
449
- JSON.stringify({
450
- attributes: Object.fromEntries(span.attributes),
451
- events: span.events.map(([, , attributes]) => attributes),
452
- exit:
453
- span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
454
- ? Cause.pretty(span.status.exit.cause)
455
- : "",
456
- }),
457
- );
458
- for (const text of [written, ...exported]) {
459
- assert.notInclude(text, "ticket-secret");
460
- assert.notInclude(text, "proof-secret");
461
- }
462
- assert.include(written, "wsTicket=<redacted>&dpop=<redacted>&clientSurface=web");
463
- assert.include(exported.join("\n"), "effect.cause");
464
- }),
465
- ),
393
+ Effect.gen(function* () {
394
+ const fileSystem = yield* FileSystem.FileSystem;
395
+ const path = yield* Path.Path;
396
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
397
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
398
+ const sink = yield* makeTraceSink({
399
+ filePath: tracePath,
400
+ maxBytes: 1024 * 1024,
401
+ maxFiles: 2,
402
+ batchWindowMs: 10_000,
403
+ });
404
+ const delegates: Array<Tracer.NativeSpan> = [];
405
+ const tracer = yield* makeLocalFileTracer({
406
+ filePath: tracePath,
407
+ maxBytes: 1024 * 1024,
408
+ maxFiles: 2,
409
+ batchWindowMs: 10_000,
410
+ sink,
411
+ delegate: Tracer.make({
412
+ span: (options) => {
413
+ const span = new Tracer.NativeSpan(options);
414
+ delegates.push(span);
415
+ return span;
416
+ },
417
+ }),
418
+ });
419
+ const url = "/ws?wsTicket=ticket-secret&dpop=proof-secret&clientSurface=web";
420
+
421
+ yield* Effect.annotateCurrentSpan({
422
+ "url.full": `http://127.0.0.1:3773${url}`,
423
+ "url.query": url.slice(4),
424
+ }).pipe(
425
+ Effect.withSpan("GET", { kind: "server" }),
426
+ Effect.provideService(Tracer.Tracer, tracer),
427
+ );
428
+ yield* Effect.die(new Error(`RequestParseError (GET ${url})`)).pipe(
429
+ Effect.tapCause((cause) => Effect.logError(cause)),
430
+ Effect.withSpan("DeviceHubProxy.proxyWebSocket"),
431
+ Effect.provideService(Tracer.Tracer, tracer),
432
+ Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })),
433
+ Effect.exit,
434
+ );
435
+ yield* sink.close();
436
+
437
+ const written = yield* fileSystem.readFileString(tracePath);
438
+ const exported = delegates.map((span) =>
439
+ JSON.stringify({
440
+ attributes: Object.fromEntries(span.attributes),
441
+ events: span.events.map(([, , attributes]) => attributes),
442
+ exit:
443
+ span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
444
+ ? Cause.pretty(span.status.exit.cause)
445
+ : "",
446
+ }),
447
+ );
448
+ for (const text of [written, ...exported]) {
449
+ assert.notInclude(text, "ticket-secret");
450
+ assert.notInclude(text, "proof-secret");
451
+ }
452
+ assert.include(written, "wsTicket=<redacted>&dpop=<redacted>&clientSurface=web");
453
+ assert.include(exported.join("\n"), "effect.cause");
454
+ }),
455
);
456
457
it.effect("drops only the invalid trace record when serialization fails", () =>
469
- Effect.scoped(
470
- Effect.gen(function* () {
471
- const fileSystem = yield* FileSystem.FileSystem;
472
- const path = yield* Path.Path;
473
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
474
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
475
-
476
- const sink = yield* makeTraceSink({
477
- filePath: tracePath,
478
- maxBytes: 1024,
479
- maxFiles: 2,
480
- batchWindowMs: 10_000,
481
- });
482
-
483
- const circular: Array<unknown> = [];
484
- circular.push(circular);
485
-
486
- sink.push(makeRecord("alpha"));
487
- sink.push({
488
- ...makeRecord("invalid"),
489
- attributes: {
490
- circular,
491
- },
492
- } as TraceRecord);
493
- sink.push(makeRecord("beta"));
494
- yield* sink.close();
495
-
496
- const lines = yield* readTraceRecords(tracePath);
497
-
498
- assert.deepStrictEqual(
499
- lines.map((line) => line.name),
500
- ["alpha", "beta"],
501
- );
502
- }),
503
- ),
458
+ Effect.gen(function* () {
459
+ const fileSystem = yield* FileSystem.FileSystem;
460
+ const path = yield* Path.Path;
461
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
462
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
463
+
464
+ const sink = yield* makeTraceSink({
465
+ filePath: tracePath,
466
+ maxBytes: 1024,
467
+ maxFiles: 2,
468
+ batchWindowMs: 10_000,
469
+ });
470
+
471
+ const circular: Array<unknown> = [];
472
+ circular.push(circular);
473
+
474
+ sink.push(makeRecord("alpha"));
475
+ sink.push({
476
+ ...makeRecord("invalid"),
477
+ attributes: {
478
+ circular,
479
+ },
480
+ } as TraceRecord);
481
+ sink.push(makeRecord("beta"));
482
+ yield* sink.close();
483
+
484
+ const lines = yield* readTraceRecords(tracePath);
485
+
486
+ assert.deepStrictEqual(
487
+ lines.map((line) => line.name),
488
+ ["alpha", "beta"],
489
+ );
490
+ }),
491
);
492
493
it.effect("writes nested spans to disk and captures log messages as span events", () =>
507
- Effect.scoped(
508
- Effect.gen(function* () {
509
- const fileSystem = yield* FileSystem.FileSystem;
510
- const path = yield* Path.Path;
511
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
512
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
494
+ Effect.gen(function* () {
495
+ const fileSystem = yield* FileSystem.FileSystem;
496
+ const path = yield* Path.Path;
497
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
498
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
499
514
- yield* Effect.scoped(
515
- Effect.gen(function* () {
516
- const program = Effect.gen(function* () {
500
+ yield* Effect.scoped(
501
+ Effect.gen(function* () {
502
+ const program = Effect.gen(function* () {
503
+ yield* Effect.annotateCurrentSpan({
504
+ "demo.parent": true,
505
+ });
506
+ yield* Effect.logInfo("parent event");
507
+ yield* Effect.gen(function* () {
508
yield* Effect.annotateCurrentSpan({
518
- "demo.parent": true,
509
+ "demo.child": true,
510
});
520
- yield* Effect.logInfo("parent event");
521
- yield* Effect.gen(function* () {
522
- yield* Effect.annotateCurrentSpan({
523
- "demo.child": true,
524
- });
525
- yield* Effect.logInfo("child event");
526
- }).pipe(Effect.withSpan("child-span"));
527
- }).pipe(Effect.withSpan("parent-span"));
528
-
529
- yield* program.pipe(Effect.provide(layerTest(tracePath)));
530
- }),
531
- );
511
+ yield* Effect.logInfo("child event");
512
+ }).pipe(Effect.withSpan("child-span"));
513
+ }).pipe(Effect.withSpan("parent-span"));
514
533
- const records = yield* readTraceRecords(tracePath);
534
- assert.equal(records.length, 2);
515
+ yield* program.pipe(Effect.provide(layerTest(tracePath)));
516
+ }),
517
+ );
518
536
- const parent = records.find((record) => record.name === "parent-span");
537
- const child = records.find((record) => record.name === "child-span");
519
+ const records = yield* readTraceRecords(tracePath);
520
+ assert.equal(records.length, 2);
521
539
- assert.notEqual(parent, undefined);
540
- assert.notEqual(child, undefined);
541
- if (!parent || !child) {
542
- return;
543
- }
522
+ const parent = records.find((record) => record.name === "parent-span");
523
+ const child = records.find((record) => record.name === "child-span");
524
545
- assert.equal(child.parentSpanId, parent.spanId);
546
- assert.equal(parent.attributes["demo.parent"], true);
547
- assert.equal(child.attributes["demo.child"], true);
548
- assert.equal(
549
- parent.events.some((event) => event.name === "parent event"),
550
- true,
551
- );
552
- assert.equal(
553
- child.events.some((event) => event.name === "child event"),
554
- true,
555
- );
556
- assert.equal(
557
- child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
558
- true,
559
- );
560
- }),
561
- ),
525
+ assert.notEqual(parent, undefined);
526
+ assert.notEqual(child, undefined);
527
+ if (!parent || !child) {
528
+ return;
529
+ }
530
+
531
+ assert.equal(child.parentSpanId, parent.spanId);
532
+ assert.equal(parent.attributes["demo.parent"], true);
533
+ assert.equal(child.attributes["demo.child"], true);
534
+ assert.equal(
535
+ parent.events.some((event) => event.name === "parent event"),
536
+ true,
537
+ );
538
+ assert.equal(
539
+ child.events.some((event) => event.name === "child event"),
540
+ true,
541
+ );
542
+ assert.equal(
543
+ child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
544
+ true,
545
+ );
546
+ }),
547
);
548
549
it.effect("serializes interrupted spans with an interrupted exit status", () =>
565
- Effect.scoped(
566
- Effect.gen(function* () {
567
- const fileSystem = yield* FileSystem.FileSystem;
568
- const path = yield* Path.Path;
569
- const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
570
- const tracePath = path.join(tempDir, "shared.trace.ndjson");
571
-
572
- yield* Effect.scoped(
573
- Effect.exit(
574
- Effect.interrupt.pipe(
575
- Effect.withSpan("interrupt-span"),
576
- Effect.provide(layerTest(tracePath)),
577
- ),
550
+ Effect.gen(function* () {
551
+ const fileSystem = yield* FileSystem.FileSystem;
552
+ const path = yield* Path.Path;
553
+ const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
554
+ const tracePath = path.join(tempDir, "shared.trace.ndjson");
555
+
556
+ yield* Effect.scoped(
557
+ Effect.exit(
558
+ Effect.interrupt.pipe(
559
+ Effect.withSpan("interrupt-span"),
560
+ Effect.provide(layerTest(tracePath)),
561
),
579
- );
562
+ ),
563
+ );
564
581
- const records = yield* readTraceRecords(tracePath);
582
- assert.equal(records.length, 1);
583
- assert.equal(records[0]?.name, "interrupt-span");
584
- assert.equal(records[0]?.exit?._tag, "Interrupted");
585
- }),
586
- ),
565
+ const records = yield* readTraceRecords(tracePath);
566
+ assert.equal(records.length, 1);
567
+ assert.equal(records[0]?.name, "interrupt-span");
568
+ assert.equal(records[0]?.exit?._tag, "Interrupted");
569
+ }),
570
);
571
});
572
});
packages/shared/src/shell.test.ts
+25
-33
@@ -807,40 +807,32 @@ effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => {
807
it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
808
"runs the executable behind an npm shim directly when asked",
809
() =>
810
- Effect.scoped(
811
- Effect.gen(function* () {
812
- const fs = yield* FileSystem.FileSystem;
813
- const path = yield* Path.Path;
814
- const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
815
- const shim = path.join(prefix, "opencode.cmd");
816
- const executable = path.join(
817
- prefix,
818
- "node_modules",
819
- "opencode-ai",
820
- "bin",
821
- "opencode.exe",
810
+ Effect.gen(function* () {
811
+ const fs = yield* FileSystem.FileSystem;
812
+ const path = yield* Path.Path;
813
+ const prefix = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-shim-" });
814
+ const shim = path.join(prefix, "opencode.cmd");
815
+ const executable = path.join(prefix, "node_modules", "opencode-ai", "bin", "opencode.exe");
816
+ yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
817
+ yield* fs.writeFileString(executable, "");
818
+ yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
819
+ const resolve = (bypassNpmShim: boolean) =>
820
+ resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
821
+ env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
822
+ bypassNpmShim,
823
+ }).pipe(
824
+ Effect.provideService(HostProcess.Platform, "win32"),
825
+ Effect.provideService(CommandResolutionCache, new Map()),
826
+ Effect.provideService(SpawnExecutableResolution, () => shim),
827
);
823
- yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
824
- yield* fs.writeFileString(executable, "");
825
- yield* fs.writeFileString(shim, NPM_OPENCODE_SHIM);
826
- const resolve = (bypassNpmShim: boolean) =>
827
- resolveSpawnCommand("opencode", ["serve", "--port=4096"], {
828
- env: { PATH: "", PATHEXT: ".COM;.EXE;.BAT;.CMD" },
829
- bypassNpmShim,
830
- }).pipe(
831
- Effect.provideService(HostProcess.Platform, "win32"),
832
- Effect.provideService(CommandResolutionCache, new Map()),
833
- Effect.provideService(SpawnExecutableResolution, () => shim),
834
- );
835
-
836
- expect(yield* resolve(true)).toEqual({
837
- command: executable,
838
- args: ["serve", "--port=4096"],
839
- shell: false,
840
- });
841
- expect((yield* resolve(false)).shell).toBe(true);
842
- }),
843
- ),
828
+
829
+ expect(yield* resolve(true)).toEqual({
830
+ command: executable,
831
+ args: ["serve", "--port=4096"],
832
+ shell: false,
833
+ });
834
+ expect((yield* resolve(false)).shell).toBe(true);
835
+ }),
836
);
837
838
it.effect("builds one escaped cmd.exe line for Windows command shims", () =>
packages/source-control-bitbucket/src/server/BitbucketApi.test.ts
+1
-1
@@ -619,7 +619,7 @@ it.effect("creates pull requests using the official REST payload shape", () => {
619
branch: { name: "main" },
620
},
621
});
622
- }).pipe(Effect.provide(layer), Effect.scoped);
622
+ }).pipe(Effect.provide(layer));
623
});
624
625
it.effect("reports the account Bitbucket confirms for the configured credential", () => {
packages/source-control-github/src/server/GitHubRest.test.ts
+1
-1
@@ -360,7 +360,7 @@ describe("GitHubRest", () => {
360
expect(media?.status).toBe(401);
361
expect(directRequests).toEqual([mediaUrl]);
362
}).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
363
- }).pipe(Effect.scoped),
363
+ }),
364
);
365
366
it.effect.each(["", "unavailable"])(
packages/source-control-github/src/server/GitHubSourceControlProvider.test.ts
+2
-3
@@ -580,7 +580,7 @@ describe("GitHubSourceControlProvider writes", () => {
580
body: "Body",
581
maintainer_can_modify: true,
582
});
583
- }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)), Effect.scoped);
583
+ }).pipe(Effect.provide(Layer.merge(layer, NodeServices.layer)));
584
});
585
586
it.effect("creates a repository under an organization the viewer is not", () => {
@@ -1146,7 +1146,7 @@ it.live.each([
1146
remoteName: "enterprise",
1147
remoteBranch: "feature",
1148
});
1149
- }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}), Effect.scoped);
1149
+ }).pipe(Effect.provide(layer), Effect.provideService(HostProcess.Environment, {}));
1150
});
1151
1152
it.effect.each([
@@ -1228,7 +1228,6 @@ it.effect.each([
1228
}).pipe(
1229
Effect.provide(layer),
1230
Effect.provideService(HostProcess.Environment, { GH_REPO: envRepository }),
1231
- Effect.scoped,
1231
);
1232
},
1233
);
packages/source-control-github/src/server/gitHubMediaFetch.test.ts
+3
-5
@@ -122,7 +122,6 @@ describe("GitHubMediaFetch", () => {
122
);
123
}),
124
),
125
- Effect.scoped,
125
);
126
});
127
@@ -172,7 +171,6 @@ describe("GitHubMediaFetch", () => {
171
);
172
}),
173
),
175
- Effect.scoped,
174
);
175
});
176
@@ -201,7 +199,7 @@ describe("GitHubMediaFetch", () => {
199
{ url: fixture.signedUrls[0] },
200
{ url: fixture.signedUrls[0], range: "bytes=2-5" },
201
]);
204
- }).pipe(Effect.provide(fixture.layer), Effect.scoped);
202
+ }).pipe(Effect.provide(fixture.layer));
203
},
204
);
205
@@ -215,7 +213,7 @@ describe("GitHubMediaFetch", () => {
213
expect(fixture.rendered.map((input) => input.body)).toEqual([
214
{ text: ``, mode: "gfm", context: PR_REPOSITORY },
215
]);
218
- }).pipe(Effect.provide(fixture.layer), Effect.scoped);
216
+ }).pipe(Effect.provide(fixture.layer));
217
});
218
219
it.effect("renders a fresh signed URL after an account switch, early expiry, or its TTL", () => {
@@ -237,6 +235,6 @@ describe("GitHubMediaFetch", () => {
235
yield* fetchMedia(request);
236
expect(fixture.rendered).toHaveLength(4);
237
expect(fixture.requests.at(-1)?.url).toBe(fixture.signedUrls.at(-1));
240
- }).pipe(Effect.provide(fixture.layer), Effect.scoped);
238
+ }).pipe(Effect.provide(fixture.layer));
239
});
240
});
packages/source-control-github/src/server/githubStackRebase.test.ts
+4
-4
@@ -89,7 +89,7 @@ it.layer(layer)("cascadeRebaseStack", (it) => {
89
expect(yield* repo.git("log", "--format=%s", `${bottom}..${top}`)).toBe(
90
"B: document the answer",
91
);
92
- }).pipe(Effect.scoped),
92
+ }),
93
);
94
95
it.effect("drops a squash-merged lower layer's commits from the layer above it", () =>
@@ -142,7 +142,7 @@ it.layer(layer)("cascadeRebaseStack", (it) => {
142
const top = yield* repo.head("feat/on-top");
143
expect(yield* repo.git("rev-parse", `${top}~1`)).toBe(yield* repo.head("main"));
144
expect(yield* repo.git("log", "--format=%s", `main..${top}`)).toBe("B");
145
- }).pipe(Effect.scoped),
145
+ }),
146
);
147
148
it.effect("refuses to overwrite a layer pushed after it was reviewed", () =>
@@ -160,7 +160,7 @@ it.layer(layer)("cascadeRebaseStack", (it) => {
160
);
161
expect(error).toMatchObject({ _tag: "GitHubStackRebaseGitError", number: 2, completed: 1 });
162
expect(yield* repo.head("feat/answer-doc")).toBe(repo.layers[1]!.headSha);
163
- }).pipe(Effect.scoped),
163
+ }),
164
);
165
166
it.effect("stops at a conflicting layer and leaves it untouched", () =>
@@ -202,6 +202,6 @@ it.layer(layer)("cascadeRebaseStack", (it) => {
202
completed: 0,
203
});
204
expect(yield* repo.head("feat/answer-42")).toBe(repo.layers[0]!.headSha);
205
- }).pipe(Effect.scoped),
205
+ }),
206
);
207
});
packages/ssh/src/auth.test.ts
-2
@@ -84,7 +84,6 @@ describe("ssh auth", () => {
84
assert.include(yield* fs.readFileString(askpassPath), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
85
}).pipe(
86
Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
87
- Effect.scoped,
87
),
88
);
89
@@ -249,7 +248,6 @@ describe("ssh auth", () => {
248
assert.include(yield* fs.readFileString(first), 'printf "%s\\n" "$T3_SSH_AUTH_SECRET"');
249
}).pipe(
250
Effect.provide(Layer.merge(NodeServices.layer, Layer.succeed(HostProcess.Platform, "linux"))),
252
- Effect.scoped,
251
),
252
);
253
});
packages/ssh/src/config.test.ts
+6
-6
@@ -70,7 +70,7 @@ describe("ssh config", () => {
70
]),
71
],
72
);
73
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
73
+ }).pipe(Effect.provide(NodeServices.layer)),
74
);
75
76
it.effect("skips directories and implicit dotfile Include matches but keeps explicit ones", () =>
@@ -117,7 +117,7 @@ describe("ssh config", () => {
117
["team", "team.example.com", "ssh-config"],
118
],
119
);
120
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
120
+ }).pipe(Effect.provide(NodeServices.layer)),
121
);
122
123
it.effect("discovers ssh config hosts across included files", () =>
@@ -222,7 +222,7 @@ describe("ssh config", () => {
222
source: "ssh-config",
223
},
224
]);
225
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
225
+ }).pipe(Effect.provide(NodeServices.layer)),
226
);
227
228
it.effect("retains raw targets when included hostnames are inactive or uncertain", () =>
@@ -293,7 +293,7 @@ describe("ssh config", () => {
293
assert.equal(hosts.find((host) => host.alias === "prod")?.hostname, "prod");
294
assert.equal(hosts.find((host) => host.alias === "work")?.hostname, "work");
295
assert.equal(hosts.find((host) => host.alias === "matched")?.hostname, "matched");
296
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
296
+ }).pipe(Effect.provide(NodeServices.layer)),
297
);
298
299
it.effect("keeps each explicit known_hosts port as its own destination", () =>
@@ -320,7 +320,7 @@ describe("ssh config", () => {
320
.toSorted((left, right) => left.localeCompare(right)),
321
["100.64.0.1 2222", "100.64.0.1 2223", "fd7a:115c:a1e0::1 2222"],
322
);
323
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
323
+ }).pipe(Effect.provide(NodeServices.layer)),
324
);
325
326
it.effect("keeps known_hosts ports that a configured alias for the address does not use", () =>
@@ -362,7 +362,7 @@ describe("ssh config", () => {
362
hosts.map((host) => `${host.alias} ${host.port}`),
363
["192.0.2.10 2222", "192.0.2.10 2223", "box null", "fixture null", "prod null"],
364
);
365
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
365
+ }).pipe(Effect.provide(NodeServices.layer)),
366
);
367
368
it.effect("parses known_hosts entries without returning hashed hosts", () =>