Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 type OrchestrationSessionStatus,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 type ProviderSendTurnInput,
8 ThreadId,
9 TurnId,
10} from "@t3tools/contracts";
11import { assert, it } from "@effect/vitest";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Stream from "effect/Stream";
17
18import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
19import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
20import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
21import {
22 ProviderSessionDirectoryPersistenceError,
23 ProviderSessionNotFoundError,
24} from "./provider/Errors.ts";
25import * as ProviderService from "./provider/Services/ProviderService.ts";
26import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
27import { ServerActivation } from "./serverActivation.ts";
28import * as ServerSettings from "./serverSettings.ts";
29import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
30
31const providerInstanceId = ProviderInstanceId.make("codex");
32const updatedAt = "2026-08-20T12:00:00.000Z";
33
34const makeThread = (
35 id: string,
36 status: OrchestrationSessionStatus,
37 activeTurnId: TurnId | null = null,
38 archivedAt: string | null = null,
39 deletedAt: string | null = null,
40) => ({
41 id: ThreadId.make(id),
42 archivedAt,
43 deletedAt,
44 interactionMode: "default" as const,
45 session: {
46 threadId: ThreadId.make(id),
47 status,
48 providerName: "codex" as const,
49 providerInstanceId,
50 runtimeMode: "full-access" as const,
51 activeTurnId,
52 lastError: null,
53 updatedAt,
54 },
55});
56
57const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
58 ({
59 startSession: () => Effect.die("unused"),
60 sendTurn: () => Effect.die("unused"),
61 compactThread: () => Effect.die("unused"),
62 interruptTurn: () => Effect.die("unused"),
63 respondToRequest: () => Effect.die("unused"),
64 respondToUserInput: () => Effect.die("unused"),
65 stopSession: () => Effect.die("unused"),
66 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
67 getCapabilities: () => Effect.die("unused"),
68 assertConversationRollbackSupported: () => Effect.die("unused"),
69 getInstanceInfo: () => Effect.die("unused"),
70 rollbackConversation: () => Effect.die("unused"),
71 uploadFeedback: () => Effect.die("unused"),
72 streamEvents: Stream.empty,
73 }) satisfies ProviderService.ProviderService["Service"];
74
75const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
76 ({
77 getUserInputActivity: () => Effect.die("unused"),
78 getCommandReadModel: () => Effect.succeed({ threads } as never),
79 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
80
81const runReconciliation = (input: {
82 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
83 readonly continueAfterRestart?: boolean;
84 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
85 readonly providerService?: ProviderService.ProviderService["Service"];
86 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
87 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
88}) =>
89 ServerRuntimeStartup.reconcileProviderSessions.pipe(
90 Effect.provideService(
91 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
92 queryWithThreads(input.threads),
93 ),
94 Effect.provideService(
95 ProviderService.ProviderService,
96 input.providerService ?? makeProviderService(input.liveThreadIds),
97 ),
98 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
99 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
100 readEvents: () => Stream.empty,
101 readThreadEvents: () => Stream.empty,
102 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
103 dispatch: input.dispatch,
104 streamDomainEvents: Stream.empty,
105 subscribeDomainEvents: Effect.succeed(Stream.empty),
106 latestSequence: Effect.succeed(0),
107 }),
108 Effect.provide(
109 Layer.mergeAll(
110 ServerSettings.layerTest({
111 continueThreadsAfterServerUpdate: input.continueAfterRestart ?? false,
112 }),
113 NodeServices.layer,
114 ),
115 ),
116 );
117
118it.effect("marks active running sessions that have persisted resume state", () => {
119 const active = makeThread("thread-mark-active", "running", TurnId.make("turn-mark-active"));
120 const archived = makeThread(
121 "thread-mark-archived",
122 "running",
123 TurnId.make("turn-mark-archived"),
124 updatedAt,
125 );
126 const ready = makeThread("thread-mark-ready", "ready");
127 const missingResumeState = makeThread(
128 "thread-mark-missing-resume-state",
129 "running",
130 TurnId.make("turn-mark-missing-resume-state"),
131 );
132 const bindingReads: ThreadId[] = [];
133 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
134
135 return ServerRuntimeStartup.markRunningProviderSessionsForContinuation.pipe(
136 Effect.provideService(
137 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
138 queryWithThreads([active, archived, ready, missingResumeState]),
139 ),
140 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
141 getBinding: (threadId) =>
142 Effect.sync(() => bindingReads.push(threadId)).pipe(
143 Effect.as(
144 Option.some({
145 threadId,
146 provider: ProviderDriverKind.make("codex"),
147 providerInstanceId,
148 ...(threadId === active.id ? { resumeCursor: { threadId } } : {}),
149 runtimePayload: { activeTurnId: "turn-mark-active" },
150 }),
151 ),
152 ),
153 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
154 recordImportedTranscript: () => Effect.die("unused"),
155 getProvider: () => Effect.die("unused"),
156 listThreadIds: () => Effect.die("unused"),
157 listBindings: () => Effect.succeed([]),
158 }),
159 Effect.tap((marked) =>
160 Effect.sync(() => {
161 assert.deepStrictEqual(bindingReads, [active.id, missingResumeState.id]);
162 assert.deepStrictEqual(marked, [active.id]);
163 assert.deepStrictEqual(upserts[0]?.runtimePayload, {
164 activeTurnId: "turn-mark-active",
165 continueAfterServerUpdate: active.session.activeTurnId,
166 continueAfterServerUpdatePrepared: null,
167 });
168 }),
169 ),
170 );
171});
172
173it.effect.each(
174 (["marked update", "opt-in restart"] as const).flatMap((recovery) =>
175 (["current", "previous", "missing"] as const).map((persistedTurn) => ({
176 recovery,
177 persistedTurn,
178 })),
179 ),
180)(
181 "continues $recovery sessions with a $persistedTurn directory turn",
182 ({ recovery, persistedTurn }) =>
183 Effect.gen(function* () {
184 const codex = makeThread(
185 "thread-continue-codex",
186 "running",
187 TurnId.make("turn-continue-codex"),
188 );
189 const fallbackContinuationTurnId = TurnId.make("turn-continue-fallback");
190 const fallback = makeThread(
191 "thread-continue-fallback",
192 recovery === "marked update" ? "starting" : "running",
193 recovery === "marked update" ? null : fallbackContinuationTurnId,
194 );
195 const fallbackProviderInstanceId = ProviderInstanceId.make("claudeAgent");
196 const continuationSent = yield* Deferred.make<void>();
197 const continuationCleared = yield* Deferred.make<void>();
198 const sends: ProviderSendTurnInput[] = [];
199 const dispatched: OrchestrationCommand[] = [];
200 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
201 const bindings = new Map<ThreadId, ProviderSessionDirectory.ProviderRuntimeBinding>(
202 [codex, fallback].map((thread) => [
203 thread.id,
204 {
205 threadId: thread.id,
206 provider:
207 thread.id === codex.id
208 ? ProviderDriverKind.make("codex")
209 : ProviderDriverKind.make("claudeAgent"),
210 providerInstanceId:
211 thread.id === codex.id ? providerInstanceId : fallbackProviderInstanceId,
212 status: "running" as const,
213 resumeCursor: { threadId: thread.id },
214 runtimePayload: {
215 activeTurnId:
216 thread.id === codex.id && persistedTurn !== "current"
217 ? persistedTurn === "previous"
218 ? "previous-provider-turn"
219 : null
220 : thread.session.activeTurnId,
221 ...(recovery === "marked update"
222 ? {
223 continueAfterServerUpdate:
224 thread.id === codex.id
225 ? codex.session.activeTurnId
226 : fallbackContinuationTurnId,
227 }
228 : {}),
229 },
230 },
231 ]),
232 );
233 const providerService: ProviderService.ProviderService["Service"] = {
234 ...makeProviderService(),
235 getCapabilities: (instanceId) =>
236 Effect.succeed({
237 sessionModelSwitch: "in-session",
238 ...(instanceId === providerInstanceId ? { promptlessTurnContinuation: true } : {}),
239 }),
240 sendTurn: (input) =>
241 Effect.gen(function* () {
242 sends.push(input);
243 if (sends.length === 2) {
244 yield* Deferred.succeed(continuationSent, undefined);
245 }
246 return {
247 threadId: input.threadId,
248 turnId: TurnId.make(`continued-${String(input.threadId)}`),
249 };
250 }),
251 };
252
253 yield* runReconciliation({
254 threads: [codex, fallback],
255 continueAfterRestart: recovery === "opt-in restart",
256 providerService,
257 directory: {
258 getBinding: (threadId) =>
259 Effect.sync(() => {
260 const binding = bindings.get(threadId);
261 return binding === undefined ? Option.none() : Option.some(binding);
262 }),
263 upsert: (binding) =>
264 Effect.sync(() => {
265 bindings.set(binding.threadId, binding);
266 upserts.push(binding);
267 const clearedCount = upserts.filter((candidate) => {
268 const payload = candidate.runtimePayload;
269 return (
270 payload !== null &&
271 typeof payload === "object" &&
272 !Array.isArray(payload) &&
273 "continueAfterServerUpdate" in payload &&
274 payload.continueAfterServerUpdate === null
275 );
276 }).length;
277 return clearedCount === 1;
278 }).pipe(
279 Effect.flatMap((firstMarkerCleared) =>
280 firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
281 ),
282 ),
283 recordImportedTranscript: () => Effect.die("unused"),
284 getProvider: () => Effect.die("unused"),
285 listThreadIds: () => Effect.die("unused"),
286 listBindings: () => Effect.succeed([]),
287 },
288 dispatch: (command) =>
289 Effect.sync(() => dispatched.push(command)).pipe(
290 Effect.as({ sequence: dispatched.length }),
291 ),
292 });
293 assert.isTrue(
294 dispatched.every(
295 (command) =>
296 command.type === "thread.session.set" && command.session.status === "starting",
297 ),
298 );
299 yield* Deferred.await(continuationSent);
300 yield* Deferred.await(continuationCleared);
301
302 assert.deepStrictEqual(
303 sends.toSorted((left, right) =>
304 String(left.threadId).localeCompare(String(right.threadId)),
305 ),
306 [
307 { threadId: codex.id, continuation: true, interactionMode: "default" },
308 {
309 threadId: fallback.id,
310 input: "Continue where you left off.",
311 interactionMode: "default",
312 },
313 ],
314 );
315 assert.deepStrictEqual(
316 dispatched.map((command) =>
317 command.type === "thread.session.set"
318 ? {
319 threadId: command.threadId,
320 status: command.session.status,
321 activeTurnId: command.session.activeTurnId,
322 }
323 : null,
324 ),
325 [
326 {
327 threadId: codex.id,
328 status: "starting",
329 activeTurnId: null,
330 },
331 {
332 threadId: fallback.id,
333 status: "starting",
334 activeTurnId: null,
335 },
336 ],
337 );
338 for (const [thread, continuationTurnId] of [
339 [codex, codex.session.activeTurnId],
340 [fallback, fallbackContinuationTurnId],
341 ] as const) {
342 assert.deepStrictEqual(
343 upserts
344 .filter((binding) => binding.threadId === thread.id)
345 .map((binding) => binding.runtimePayload)[0],
346 {
347 continueAfterServerUpdate: continuationTurnId,
348 continueAfterServerUpdatePrepared: true,
349 activeTurnId: null,
350 },
351 );
352 }
353 assert.equal(
354 upserts.some((binding) => {
355 const payload = binding.runtimePayload;
356 return (
357 payload !== null &&
358 typeof payload === "object" &&
359 !Array.isArray(payload) &&
360 "continueAfterServerUpdate" in payload &&
361 payload.continueAfterServerUpdate === null
362 );
363 }),
364 true,
365 );
366 }),
367);
368
369it.effect("does not continue archived or deleted marked sessions", () => {
370 const archived = makeThread(
371 "thread-continue-archived",
372 "running",
373 TurnId.make("turn-continue-archived"),
374 updatedAt,
375 );
376 const deleted = makeThread(
377 "thread-continue-deleted",
378 "running",
379 TurnId.make("turn-continue-deleted"),
380 null,
381 updatedAt,
382 );
383 const sends: ProviderSendTurnInput[] = [];
384 const dispatched: OrchestrationCommand[] = [];
385
386 return runReconciliation({
387 threads: [archived, deleted],
388 providerService: {
389 ...makeProviderService(),
390 sendTurn: (input) =>
391 Effect.sync(() => {
392 sends.push(input);
393 return {
394 threadId: input.threadId,
395 turnId: TurnId.make("unexpected-archived-turn"),
396 };
397 }),
398 },
399 directory: {
400 getBinding: (threadId) => {
401 const thread = threadId === archived.id ? archived : deleted;
402 return Effect.succeed(
403 Option.some({
404 threadId,
405 provider: ProviderDriverKind.make("codex"),
406 providerInstanceId,
407 status: "running" as const,
408 resumeCursor: { cursor: threadId },
409 runtimePayload: {
410 continueAfterServerUpdate: thread.session.activeTurnId,
411 },
412 }),
413 );
414 },
415 upsert: () => Effect.void,
416 recordImportedTranscript: () => Effect.die("unused"),
417 getProvider: () => Effect.die("unused"),
418 listThreadIds: () => Effect.die("unused"),
419 listBindings: () => Effect.succeed([]),
420 },
421 dispatch: (command) =>
422 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
423 }).pipe(
424 Effect.tap(() =>
425 Effect.sync(() => {
426 assert.deepStrictEqual(sends, []);
427 assert.deepStrictEqual(
428 dispatched.map((command) =>
429 command.type === "thread.session.set"
430 ? { threadId: command.threadId, status: command.session.status }
431 : null,
432 ),
433 [
434 { threadId: archived.id, status: "error" },
435 { threadId: deleted.id, status: "error" },
436 ],
437 );
438 }),
439 ),
440 );
441});
442
443it.effect("retries continuation preparation before settling a persistent failure", () => {
444 const thread = makeThread(
445 "thread-continuation-preparation-failure",
446 "running",
447 TurnId.make("turn-continuation-preparation-failure"),
448 );
449 const dispatched: OrchestrationCommand[] = [];
450 const failure = new OrchestrationCommandInvariantError({
451 commandType: "thread.session.set",
452 detail: "simulated continuation preparation failure",
453 });
454
455 return runReconciliation({
456 threads: [thread],
457 directory: {
458 getBinding: () =>
459 Effect.succeed(
460 Option.some({
461 threadId: thread.id,
462 provider: ProviderDriverKind.make("codex"),
463 providerInstanceId,
464 status: "running" as const,
465 resumeCursor: { cursor: thread.id },
466 runtimePayload: {
467 continueAfterServerUpdate: thread.session.activeTurnId,
468 },
469 }),
470 ),
471 upsert: () => Effect.void,
472 recordImportedTranscript: () => Effect.die("unused"),
473 getProvider: () => Effect.die("unused"),
474 listThreadIds: () => Effect.die("unused"),
475 listBindings: () => Effect.succeed([]),
476 },
477 dispatch: (command) => {
478 if (command.type !== "thread.session.set") {
479 return Effect.die("unexpected command");
480 }
481 dispatched.push(command);
482 return command.session.status === "starting"
483 ? Effect.fail(failure)
484 : Effect.succeed({ sequence: dispatched.length });
485 },
486 }).pipe(
487 Effect.tap(() =>
488 Effect.sync(() =>
489 assert.deepStrictEqual(
490 dispatched.map(
491 (command) => command.type === "thread.session.set" && command.session.status,
492 ),
493 ["starting", "starting", "error"],
494 ),
495 ),
496 ),
497 );
498});
499
500it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
501 const starting = makeThread("thread-starting", "starting");
502 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
503 const staleActiveTurn = makeThread(
504 "thread-stale-active-turn",
505 "ready",
506 TurnId.make("turn-stale-active"),
507 );
508 const archived = makeThread(
509 "thread-archived",
510 "running",
511 TurnId.make("turn-archived"),
512 updatedAt,
513 );
514 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
515 const settled = makeThread("thread-ready", "ready");
516 const dispatched: OrchestrationCommand[] = [];
517 const bindingReads: ThreadId[] = [];
518 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
519
520 return runReconciliation({
521 threads: [starting, running, staleActiveTurn, archived, live, settled],
522 liveThreadIds: [live.id],
523 directory: {
524 getBinding: (candidate) =>
525 Effect.sync(() => bindingReads.push(candidate)).pipe(
526 Effect.as(
527 Option.some({
528 threadId: candidate,
529 provider: ProviderDriverKind.make("codex"),
530 providerInstanceId,
531 status: "running" as const,
532 resumeCursor: { cursor: candidate },
533 runtimePayload: {
534 activeTurnId: "stale",
535 unrelated: candidate,
536 ...(candidate === staleActiveTurn.id
537 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
538 : {}),
539 },
540 }),
541 ),
542 ),
543 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
544 recordImportedTranscript: () => Effect.die("unused"),
545 getProvider: () => Effect.die("unused"),
546 listThreadIds: () => Effect.die("unused"),
547 listBindings: () => Effect.succeed([]),
548 },
549 dispatch: (command) =>
550 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
551 }).pipe(
552 Effect.tap(() =>
553 Effect.sync(() => {
554 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
555 assert.deepStrictEqual(bindingReads, orphanIds);
556 assert.deepStrictEqual(
557 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
558 orphanIds,
559 );
560 assert.deepStrictEqual(
561 dispatched.map((command) =>
562 command.type === "thread.session.set"
563 ? {
564 status: command.session.status,
565 activeTurnId: command.session.activeTurnId,
566 }
567 : null,
568 ),
569 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
570 );
571 assert.equal(upserts.length, orphanIds.length);
572 for (const binding of upserts) {
573 assert.equal(binding.status, "stopped");
574 assert.deepStrictEqual(
575 binding.runtimePayload,
576 binding.threadId === staleActiveTurn.id
577 ? {
578 activeTurnId: null,
579 unrelated: binding.threadId,
580 continueAfterServerUpdate: null,
581 continueAfterServerUpdatePrepared: null,
582 }
583 : { activeTurnId: null, unrelated: binding.threadId },
584 );
585 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
586 }
587 }),
588 ),
589 );
590});
591
592it.effect(
593 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
594 () => {
595 const absent = makeThread("thread-binding-absent", "starting");
596 const corrupt = makeThread("thread-binding-corrupt", "running");
597 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
598 const dispatched: OrchestrationCommand[] = [];
599 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
600 operation: "ProviderSessionDirectory.getBinding",
601 detail: "corrupt persisted binding",
602 });
603 const writeFailure = new ProviderSessionDirectoryPersistenceError({
604 operation: "ProviderSessionDirectory.upsert",
605 detail: "failed binding write",
606 });
607
608 return runReconciliation({
609 threads: [absent, corrupt, upsertFailure],
610 directory: {
611 getBinding: (candidate) =>
612 candidate === absent.id
613 ? Effect.succeed(Option.none())
614 : candidate === corrupt.id
615 ? Effect.fail(corruptFailure)
616 : Effect.succeed(
617 Option.some({
618 threadId: candidate,
619 provider: ProviderDriverKind.make("codex"),
620 providerInstanceId,
621 }),
622 ),
623 upsert: () => Effect.fail(writeFailure),
624 recordImportedTranscript: () => Effect.die("unused"),
625 getProvider: () => Effect.die("unused"),
626 listThreadIds: () => Effect.die("unused"),
627 listBindings: () => Effect.succeed([]),
628 },
629 dispatch: (command) =>
630 Effect.sync(() => dispatched.push(command)).pipe(
631 Effect.as({ sequence: dispatched.length }),
632 ),
633 }).pipe(
634 Effect.tap(() =>
635 Effect.sync(() => {
636 assert.deepStrictEqual(
637 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
638 [absent.id, corrupt.id, upsertFailure.id],
639 );
640 }),
641 ),
642 );
643 },
644);
645
646it.effect("retries failed projections and continues after a persistent failure", () => {
647 const transient = makeThread("thread-dispatch-transient-failure", "running");
648 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
649 const later = makeThread("thread-dispatch-success", "running");
650 const attempted: ThreadId[] = [];
651 let transientAttempts = 0;
652 const failure = new OrchestrationCommandInvariantError({
653 commandType: "thread.session.set",
654 detail: "simulated startup reconciliation failure",
655 });
656
657 return runReconciliation({
658 threads: [transient, persistent, later],
659 directory: {
660 getBinding: () => Effect.succeed(Option.none()),
661 upsert: () => Effect.void,
662 recordImportedTranscript: () => Effect.die("unused"),
663 getProvider: () => Effect.die("unused"),
664 listThreadIds: () => Effect.die("unused"),
665 listBindings: () => Effect.succeed([]),
666 },
667 dispatch: (command) => {
668 if (command.type !== "thread.session.set") {
669 return Effect.die("unexpected command");
670 }
671 attempted.push(command.threadId);
672 if (command.threadId === transient.id && transientAttempts++ === 0) {
673 return Effect.fail(failure);
674 }
675 return command.threadId === persistent.id
676 ? Effect.fail(failure)
677 : Effect.succeed({ sequence: attempted.length });
678 },
679 }).pipe(
680 Effect.tap(() =>
681 Effect.sync(() =>
682 assert.deepStrictEqual(attempted, [
683 transient.id,
684 transient.id,
685 persistent.id,
686 persistent.id,
687 later.id,
688 ]),
689 ),
690 ),
691 );
692});
693
694it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
695 let queried = false;
696 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
697 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
698 getUserInputActivity: () => Effect.die("unused"),
699 getCommandReadModel: () =>
700 Effect.sync(() => {
701 queried = true;
702 return { threads: [] } as never;
703 }),
704 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
705 Effect.provideService(ProviderService.ProviderService, {
706 ...makeProviderService(),
707 listSessions: () => Effect.die("provider inventory unavailable"),
708 }),
709 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
710 getBinding: () => Effect.die("unused"),
711 upsert: () => Effect.die("unused"),
712 recordImportedTranscript: () => Effect.die("unused"),
713 getProvider: () => Effect.die("unused"),
714 listThreadIds: () => Effect.die("unused"),
715 listBindings: () => Effect.succeed([]),
716 }),
717 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
718 readEvents: () => Stream.empty,
719 readThreadEvents: () => Stream.empty,
720 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
721 dispatch: () => Effect.die("unused"),
722 streamDomainEvents: Stream.empty,
723 subscribeDomainEvents: Effect.succeed(Stream.empty),
724 latestSequence: Effect.succeed(0),
725 }),
726 Effect.provide(Layer.mergeAll(NodeServices.layer, ServerSettings.layerTest())),
727 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
728 );
729});
730
731for (const scenario of [
732 "disabled",
733 "stopped projection",
734 "finished projection",
735 "stopped binding",
736 "missing cursor",
737 "marked without cursor",
738 "marked stopped projection",
739 "marked superseded turn",
740] as const) {
741 it.effect(`does not recover an interrupted session with ${scenario}`, () => {
742 const turnId = TurnId.make("turn-excluded-recovery");
743 const thread = makeThread(
744 "thread-excluded-recovery",
745 scenario.includes("stopped projection")
746 ? "stopped"
747 : scenario === "finished projection"
748 ? "ready"
749 : scenario === "marked superseded turn"
750 ? "starting"
751 : "running",
752 scenario === "marked superseded turn" ? null : turnId,
753 );
754 const dispatched: OrchestrationCommand[] = [];
755 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
756 return runReconciliation({
757 threads: [thread],
758 continueAfterRestart: scenario !== "disabled",
759 directory: {
760 getBinding: () =>
761 Effect.succeed(
762 Option.some({
763 threadId: thread.id,
764 provider: ProviderDriverKind.make("codex"),
765 providerInstanceId,
766 status: scenario === "stopped binding" ? "stopped" : "running",
767 ...(scenario.includes("cursor") ? {} : { resumeCursor: { threadId: thread.id } }),
768 runtimePayload: {
769 activeTurnId: scenario === "marked superseded turn" ? "another-turn" : turnId,
770 ...(scenario.startsWith("marked") ? { continueAfterServerUpdate: turnId } : {}),
771 },
772 }),
773 ),
774 upsert: (binding) =>
775 Effect.sync(() => {
776 upserts.push(binding);
777 }),
778 recordImportedTranscript: () => Effect.die("unused"),
779 getProvider: () => Effect.die("unused"),
780 listThreadIds: () => Effect.die("unused"),
781 listBindings: () => Effect.succeed([]),
782 },
783 dispatch: (command) =>
784 Effect.sync(() => {
785 dispatched.push(command);
786 return { sequence: dispatched.length };
787 }),
788 }).pipe(
789 Effect.tap(() =>
790 Effect.sync(() => {
791 assert.deepStrictEqual(
792 dispatched.map(
793 (command) => command.type === "thread.session.set" && command.session.status,
794 ),
795 ["error"],
796 );
797 assert.deepStrictEqual(
798 upserts.map((binding) => binding.status),
799 ["stopped"],
800 );
801 }),
802 ),
803 );
804 });
805}
806
807for (const preparedStatus of [
808 "starting",
809 "ready",
810 "ready with failed scan",
811 "completed after update marking",
812] as const) {
813 it.effect(`recovers again if startup exits with a prepared ${preparedStatus} session`, () =>
814 Effect.gen(function* () {
815 const turnId = TurnId.make("turn-interrupted-startup");
816 const thread = makeThread("thread-interrupted-startup", "running", turnId);
817 const activation = yield* Deferred.make<void>();
818 const cleared = yield* Deferred.make<void>();
819 const sends: ProviderSendTurnInput[] = [];
820 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
821 threadId: thread.id,
822 provider: ProviderDriverKind.make("codex"),
823 providerInstanceId,
824 status: "running",
825 resumeCursor: { threadId: thread.id },
826 runtimePayload: { activeTurnId: turnId },
827 };
828 const input = {
829 threads: [thread],
830 continueAfterRestart: true,
831 providerService: {
832 ...makeProviderService(),
833 getCapabilities: () =>
834 Effect.succeed({
835 sessionModelSwitch: "in-session" as const,
836 promptlessTurnContinuation: true,
837 }),
838 sendTurn: (input: ProviderSendTurnInput) =>
839 Effect.sync(() => {
840 sends.push(input);
841 return { threadId: input.threadId, turnId: TurnId.make("turn-recovered") };
842 }),
843 },
844 directory: {
845 getBinding: () => Effect.sync(() => Option.some(binding)),
846 upsert: (next: ProviderSessionDirectory.ProviderRuntimeBinding) =>
847 Effect.gen(function* () {
848 binding = next;
849 if (binding.status !== "starting" || sends.length === 0) return;
850 yield* Deferred.succeed(cleared, undefined);
851 }),
852 recordImportedTranscript: () => Effect.die("unused"),
853 getProvider: () => Effect.die("unused"),
854 listThreadIds: () => Effect.die("unused"),
855 listBindings: () =>
856 preparedStatus === "ready with failed scan"
857 ? Effect.fail(
858 new ProviderSessionDirectoryPersistenceError({
859 operation: "listBindings",
860 detail: "unreadable unrelated binding",
861 }),
862 )
863 : Effect.sync(() => [{ ...binding, lastSeenAt: "2026-01-01T00:00:00.000Z" }]),
864 },
865 dispatch: (command: OrchestrationCommand) =>
866 Effect.sync(() => {
867 if (command.type === "thread.session.set") {
868 thread.session.status = command.session.status;
869 thread.session.activeTurnId = command.session.activeTurnId;
870 }
871 return { sequence: 1 };
872 }),
873 };
874
875 yield* runReconciliation(input).pipe(
876 Effect.provideService(ServerActivation, Deferred.await(activation)),
877 Effect.scoped,
878 );
879 assert.deepStrictEqual(sends, []);
880 assert.equal(thread.session.status, "starting");
881 assert.equal(thread.session.activeTurnId, null);
882 assert.deepStrictEqual(binding.runtimePayload, {
883 activeTurnId: null,
884 continueAfterServerUpdate: turnId,
885 continueAfterServerUpdatePrepared: true,
886 });
887
888 if (preparedStatus === "completed after update marking") {
889 thread.session.status = "ready";
890 binding = {
891 ...binding,
892 status: "stopped",
893 runtimePayload: {
894 activeTurnId: null,
895 continueAfterServerUpdate: turnId,
896 continueAfterServerUpdatePrepared: null,
897 },
898 };
899 yield* runReconciliation(input);
900 assert.deepStrictEqual(sends, []);
901 assert.equal(thread.session.status, "ready");
902 return;
903 }
904 thread.session.status =
905 preparedStatus === "ready with failed scan" ? "ready" : preparedStatus;
906 yield* runReconciliation(input);
907 yield* Deferred.await(cleared);
908 assert.deepStrictEqual(sends, [
909 { threadId: thread.id, continuation: true, interactionMode: "default" },
910 ]);
911 assert.deepStrictEqual(binding.runtimePayload, {
912 activeTurnId: null,
913 continueAfterServerUpdate: null,
914 continueAfterServerUpdatePrepared: null,
915 });
916 }),
917 );
918}
919
920it.effect("settles failed opt-in recovery without retrying the provider turn", () =>
921 Effect.gen(function* () {
922 const turnId = TurnId.make("turn-failed-recovery");
923 const thread = makeThread("thread-failed-recovery", "running", turnId);
924 const settled = yield* Deferred.make<void>();
925 const sends: ProviderSendTurnInput[] = [];
926 const dispatched: OrchestrationCommand[] = [];
927 const preparedPayloads: unknown[] = [];
928 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
929 threadId: thread.id,
930 provider: ProviderDriverKind.make("codex"),
931 providerInstanceId,
932 status: "running",
933 resumeCursor: { threadId: thread.id },
934 runtimePayload: { activeTurnId: turnId },
935 };
936 yield* runReconciliation({
937 threads: [thread],
938 continueAfterRestart: true,
939 providerService: {
940 ...makeProviderService(),
941 getCapabilities: () =>
942 Effect.succeed({ sessionModelSwitch: "in-session", promptlessTurnContinuation: true }),
943 sendTurn: (input) =>
944 Effect.gen(function* () {
945 sends.push(input);
946 preparedPayloads.push(binding.runtimePayload);
947 return yield* Effect.fail(
948 new ProviderSessionNotFoundError({ threadId: input.threadId }),
949 );
950 }),
951 },
952 directory: {
953 getBinding: () => Effect.sync(() => Option.some(binding)),
954 upsert: (next) =>
955 Effect.sync(() => {
956 binding = next;
957 }),
958 recordImportedTranscript: () => Effect.die("unused"),
959 getProvider: () => Effect.die("unused"),
960 listThreadIds: () => Effect.die("unused"),
961 listBindings: () => Effect.succeed([]),
962 },
963 dispatch: (command) =>
964 Effect.gen(function* () {
965 dispatched.push(command);
966 if (command.type === "thread.session.set" && command.session.status === "error") {
967 yield* Deferred.succeed(settled, undefined);
968 }
969 return { sequence: dispatched.length };
970 }),
971 });
972 yield* Deferred.await(settled);
973 assert.equal(sends.length, 1);
974 assert.deepStrictEqual(preparedPayloads, [
975 {
976 activeTurnId: null,
977 continueAfterServerUpdate: turnId,
978 continueAfterServerUpdatePrepared: true,
979 },
980 ]);
981 assert.deepStrictEqual(
982 dispatched.map(
983 (command) =>
984 command.type === "thread.session.set" && {
985 status: command.session.status,
986 activeTurnId: command.session.activeTurnId,
987 },
988 ),
989 [
990 { status: "starting", activeTurnId: null },
991 { status: "error", activeTurnId: null },
992 ],
993 );
994 assert.equal(binding.status, "stopped");
995 assert.deepStrictEqual(binding.runtimePayload, {
996 activeTurnId: null,
997 continueAfterServerUpdate: null,
998 continueAfterServerUpdatePrepared: null,
999 });
1000 }),
1001);