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.succeedSome({
403 threadId,
404 provider: ProviderDriverKind.make("codex"),
405 providerInstanceId,
406 status: "running" as const,
407 resumeCursor: { cursor: threadId },
408 runtimePayload: {
409 continueAfterServerUpdate: thread.session.activeTurnId,
410 },
411 });
412 },
413 upsert: () => Effect.void,
414 recordImportedTranscript: () => Effect.die("unused"),
415 getProvider: () => Effect.die("unused"),
416 listThreadIds: () => Effect.die("unused"),
417 listBindings: () => Effect.succeed([]),
418 },
419 dispatch: (command) =>
420 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
421 }).pipe(
422 Effect.tap(() =>
423 Effect.sync(() => {
424 assert.deepStrictEqual(sends, []);
425 assert.deepStrictEqual(
426 dispatched.map((command) =>
427 command.type === "thread.session.set"
428 ? { threadId: command.threadId, status: command.session.status }
429 : null,
430 ),
431 [
432 { threadId: archived.id, status: "error" },
433 { threadId: deleted.id, status: "error" },
434 ],
435 );
436 }),
437 ),
438 );
439});
440
441it.effect("retries continuation preparation before settling a persistent failure", () => {
442 const thread = makeThread(
443 "thread-continuation-preparation-failure",
444 "running",
445 TurnId.make("turn-continuation-preparation-failure"),
446 );
447 const dispatched: OrchestrationCommand[] = [];
448 const failure = new OrchestrationCommandInvariantError({
449 commandType: "thread.session.set",
450 detail: "simulated continuation preparation failure",
451 });
452
453 return runReconciliation({
454 threads: [thread],
455 directory: {
456 getBinding: () =>
457 Effect.succeedSome({
458 threadId: thread.id,
459 provider: ProviderDriverKind.make("codex"),
460 providerInstanceId,
461 status: "running" as const,
462 resumeCursor: { cursor: thread.id },
463 runtimePayload: {
464 continueAfterServerUpdate: thread.session.activeTurnId,
465 },
466 }),
467 upsert: () => Effect.void,
468 recordImportedTranscript: () => Effect.die("unused"),
469 getProvider: () => Effect.die("unused"),
470 listThreadIds: () => Effect.die("unused"),
471 listBindings: () => Effect.succeed([]),
472 },
473 dispatch: (command) => {
474 if (command.type !== "thread.session.set") {
475 return Effect.die("unexpected command");
476 }
477 dispatched.push(command);
478 return command.session.status === "starting"
479 ? Effect.fail(failure)
480 : Effect.succeed({ sequence: dispatched.length });
481 },
482 }).pipe(
483 Effect.tap(() =>
484 Effect.sync(() =>
485 assert.deepStrictEqual(
486 dispatched.map(
487 (command) => command.type === "thread.session.set" && command.session.status,
488 ),
489 ["starting", "starting", "error"],
490 ),
491 ),
492 ),
493 );
494});
495
496it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
497 const starting = makeThread("thread-starting", "starting");
498 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
499 const staleActiveTurn = makeThread(
500 "thread-stale-active-turn",
501 "ready",
502 TurnId.make("turn-stale-active"),
503 );
504 const archived = makeThread(
505 "thread-archived",
506 "running",
507 TurnId.make("turn-archived"),
508 updatedAt,
509 );
510 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
511 const settled = makeThread("thread-ready", "ready");
512 const dispatched: OrchestrationCommand[] = [];
513 const bindingReads: ThreadId[] = [];
514 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
515
516 return runReconciliation({
517 threads: [starting, running, staleActiveTurn, archived, live, settled],
518 liveThreadIds: [live.id],
519 directory: {
520 getBinding: (candidate) =>
521 Effect.sync(() => bindingReads.push(candidate)).pipe(
522 Effect.as(
523 Option.some({
524 threadId: candidate,
525 provider: ProviderDriverKind.make("codex"),
526 providerInstanceId,
527 status: "running" as const,
528 resumeCursor: { cursor: candidate },
529 runtimePayload: {
530 activeTurnId: "stale",
531 unrelated: candidate,
532 ...(candidate === staleActiveTurn.id
533 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
534 : {}),
535 },
536 }),
537 ),
538 ),
539 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
540 recordImportedTranscript: () => Effect.die("unused"),
541 getProvider: () => Effect.die("unused"),
542 listThreadIds: () => Effect.die("unused"),
543 listBindings: () => Effect.succeed([]),
544 },
545 dispatch: (command) =>
546 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
547 }).pipe(
548 Effect.tap(() =>
549 Effect.sync(() => {
550 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
551 assert.deepStrictEqual(bindingReads, orphanIds);
552 assert.deepStrictEqual(
553 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
554 orphanIds,
555 );
556 assert.deepStrictEqual(
557 dispatched.map((command) =>
558 command.type === "thread.session.set"
559 ? {
560 status: command.session.status,
561 activeTurnId: command.session.activeTurnId,
562 }
563 : null,
564 ),
565 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
566 );
567 assert.equal(upserts.length, orphanIds.length);
568 for (const binding of upserts) {
569 assert.equal(binding.status, "stopped");
570 assert.deepStrictEqual(
571 binding.runtimePayload,
572 binding.threadId === staleActiveTurn.id
573 ? {
574 activeTurnId: null,
575 unrelated: binding.threadId,
576 continueAfterServerUpdate: null,
577 continueAfterServerUpdatePrepared: null,
578 }
579 : { activeTurnId: null, unrelated: binding.threadId },
580 );
581 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
582 }
583 }),
584 ),
585 );
586});
587
588it.effect(
589 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
590 () => {
591 const absent = makeThread("thread-binding-absent", "starting");
592 const corrupt = makeThread("thread-binding-corrupt", "running");
593 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
594 const dispatched: OrchestrationCommand[] = [];
595 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
596 operation: "ProviderSessionDirectory.getBinding",
597 detail: "corrupt persisted binding",
598 });
599 const writeFailure = new ProviderSessionDirectoryPersistenceError({
600 operation: "ProviderSessionDirectory.upsert",
601 detail: "failed binding write",
602 });
603
604 return runReconciliation({
605 threads: [absent, corrupt, upsertFailure],
606 directory: {
607 getBinding: (candidate) =>
608 candidate === absent.id
609 ? Effect.succeedNone
610 : candidate === corrupt.id
611 ? Effect.fail(corruptFailure)
612 : Effect.succeedSome({
613 threadId: candidate,
614 provider: ProviderDriverKind.make("codex"),
615 providerInstanceId,
616 }),
617 upsert: () => Effect.fail(writeFailure),
618 recordImportedTranscript: () => Effect.die("unused"),
619 getProvider: () => Effect.die("unused"),
620 listThreadIds: () => Effect.die("unused"),
621 listBindings: () => Effect.succeed([]),
622 },
623 dispatch: (command) =>
624 Effect.sync(() => dispatched.push(command)).pipe(
625 Effect.as({ sequence: dispatched.length }),
626 ),
627 }).pipe(
628 Effect.tap(() =>
629 Effect.sync(() => {
630 assert.deepStrictEqual(
631 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
632 [absent.id, corrupt.id, upsertFailure.id],
633 );
634 }),
635 ),
636 );
637 },
638);
639
640it.effect("retries failed projections and continues after a persistent failure", () => {
641 const transient = makeThread("thread-dispatch-transient-failure", "running");
642 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
643 const later = makeThread("thread-dispatch-success", "running");
644 const attempted: ThreadId[] = [];
645 let transientAttempts = 0;
646 const failure = new OrchestrationCommandInvariantError({
647 commandType: "thread.session.set",
648 detail: "simulated startup reconciliation failure",
649 });
650
651 return runReconciliation({
652 threads: [transient, persistent, later],
653 directory: {
654 getBinding: () => Effect.succeedNone,
655 upsert: () => Effect.void,
656 recordImportedTranscript: () => Effect.die("unused"),
657 getProvider: () => Effect.die("unused"),
658 listThreadIds: () => Effect.die("unused"),
659 listBindings: () => Effect.succeed([]),
660 },
661 dispatch: (command) => {
662 if (command.type !== "thread.session.set") {
663 return Effect.die("unexpected command");
664 }
665 attempted.push(command.threadId);
666 if (command.threadId === transient.id && transientAttempts++ === 0) {
667 return Effect.fail(failure);
668 }
669 return command.threadId === persistent.id
670 ? Effect.fail(failure)
671 : Effect.succeed({ sequence: attempted.length });
672 },
673 }).pipe(
674 Effect.tap(() =>
675 Effect.sync(() =>
676 assert.deepStrictEqual(attempted, [
677 transient.id,
678 transient.id,
679 persistent.id,
680 persistent.id,
681 later.id,
682 ]),
683 ),
684 ),
685 );
686});
687
688it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
689 let queried = false;
690 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
691 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
692 getUserInputActivity: () => Effect.die("unused"),
693 getCommandReadModel: () =>
694 Effect.sync(() => {
695 queried = true;
696 return { threads: [] } as never;
697 }),
698 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
699 Effect.provideService(ProviderService.ProviderService, {
700 ...makeProviderService(),
701 listSessions: () => Effect.die("provider inventory unavailable"),
702 }),
703 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
704 getBinding: () => Effect.die("unused"),
705 upsert: () => Effect.die("unused"),
706 recordImportedTranscript: () => Effect.die("unused"),
707 getProvider: () => Effect.die("unused"),
708 listThreadIds: () => Effect.die("unused"),
709 listBindings: () => Effect.succeed([]),
710 }),
711 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
712 readEvents: () => Stream.empty,
713 readThreadEvents: () => Stream.empty,
714 getThreadReplayStats: () => Effect.die("unused thread replay stats"),
715 dispatch: () => Effect.die("unused"),
716 streamDomainEvents: Stream.empty,
717 subscribeDomainEvents: Effect.succeed(Stream.empty),
718 latestSequence: Effect.succeed(0),
719 }),
720 Effect.provide(Layer.mergeAll(NodeServices.layer, ServerSettings.layerTest())),
721 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
722 );
723});
724
725for (const scenario of [
726 "disabled",
727 "stopped projection",
728 "finished projection",
729 "stopped binding",
730 "missing cursor",
731 "marked without cursor",
732 "marked stopped projection",
733 "marked superseded turn",
734] as const) {
735 it.effect(`does not recover an interrupted session with ${scenario}`, () => {
736 const turnId = TurnId.make("turn-excluded-recovery");
737 const thread = makeThread(
738 "thread-excluded-recovery",
739 scenario.includes("stopped projection")
740 ? "stopped"
741 : scenario === "finished projection"
742 ? "ready"
743 : scenario === "marked superseded turn"
744 ? "starting"
745 : "running",
746 scenario === "marked superseded turn" ? null : turnId,
747 );
748 const dispatched: OrchestrationCommand[] = [];
749 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
750 return runReconciliation({
751 threads: [thread],
752 continueAfterRestart: scenario !== "disabled",
753 directory: {
754 getBinding: () =>
755 Effect.succeedSome({
756 threadId: thread.id,
757 provider: ProviderDriverKind.make("codex"),
758 providerInstanceId,
759 status: scenario === "stopped binding" ? "stopped" : "running",
760 ...(scenario.includes("cursor") ? {} : { resumeCursor: { threadId: thread.id } }),
761 runtimePayload: {
762 activeTurnId: scenario === "marked superseded turn" ? "another-turn" : turnId,
763 ...(scenario.startsWith("marked") ? { continueAfterServerUpdate: turnId } : {}),
764 },
765 }),
766 upsert: (binding) =>
767 Effect.sync(() => {
768 upserts.push(binding);
769 }),
770 recordImportedTranscript: () => Effect.die("unused"),
771 getProvider: () => Effect.die("unused"),
772 listThreadIds: () => Effect.die("unused"),
773 listBindings: () => Effect.succeed([]),
774 },
775 dispatch: (command) =>
776 Effect.sync(() => {
777 dispatched.push(command);
778 return { sequence: dispatched.length };
779 }),
780 }).pipe(
781 Effect.tap(() =>
782 Effect.sync(() => {
783 assert.deepStrictEqual(
784 dispatched.map(
785 (command) => command.type === "thread.session.set" && command.session.status,
786 ),
787 ["error"],
788 );
789 assert.deepStrictEqual(
790 upserts.map((binding) => binding.status),
791 ["stopped"],
792 );
793 }),
794 ),
795 );
796 });
797}
798
799for (const preparedStatus of [
800 "starting",
801 "ready",
802 "ready with failed scan",
803 "completed after update marking",
804] as const) {
805 it.effect(`recovers again if startup exits with a prepared ${preparedStatus} session`, () =>
806 Effect.gen(function* () {
807 const turnId = TurnId.make("turn-interrupted-startup");
808 const thread = makeThread("thread-interrupted-startup", "running", turnId);
809 const activation = yield* Deferred.make<void>();
810 const cleared = yield* Deferred.make<void>();
811 const sends: ProviderSendTurnInput[] = [];
812 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
813 threadId: thread.id,
814 provider: ProviderDriverKind.make("codex"),
815 providerInstanceId,
816 status: "running",
817 resumeCursor: { threadId: thread.id },
818 runtimePayload: { activeTurnId: turnId },
819 };
820 const input = {
821 threads: [thread],
822 continueAfterRestart: true,
823 providerService: {
824 ...makeProviderService(),
825 getCapabilities: () =>
826 Effect.succeed({
827 sessionModelSwitch: "in-session" as const,
828 promptlessTurnContinuation: true,
829 }),
830 sendTurn: (input: ProviderSendTurnInput) =>
831 Effect.sync(() => {
832 sends.push(input);
833 return { threadId: input.threadId, turnId: TurnId.make("turn-recovered") };
834 }),
835 },
836 directory: {
837 getBinding: () => Effect.sync(() => Option.some(binding)),
838 upsert: (next: ProviderSessionDirectory.ProviderRuntimeBinding) =>
839 Effect.gen(function* () {
840 binding = next;
841 if (binding.status !== "starting" || sends.length === 0) return;
842 yield* Deferred.succeed(cleared, undefined);
843 }),
844 recordImportedTranscript: () => Effect.die("unused"),
845 getProvider: () => Effect.die("unused"),
846 listThreadIds: () => Effect.die("unused"),
847 listBindings: () =>
848 preparedStatus === "ready with failed scan"
849 ? Effect.fail(
850 new ProviderSessionDirectoryPersistenceError({
851 operation: "listBindings",
852 detail: "unreadable unrelated binding",
853 }),
854 )
855 : Effect.sync(() => [{ ...binding, lastSeenAt: "2026-01-01T00:00:00.000Z" }]),
856 },
857 dispatch: (command: OrchestrationCommand) =>
858 Effect.sync(() => {
859 if (command.type === "thread.session.set") {
860 thread.session.status = command.session.status;
861 thread.session.activeTurnId = command.session.activeTurnId;
862 }
863 return { sequence: 1 };
864 }),
865 };
866
867 yield* runReconciliation(input).pipe(
868 Effect.provideService(ServerActivation, Deferred.await(activation)),
869 Effect.scoped,
870 );
871 assert.deepStrictEqual(sends, []);
872 assert.equal(thread.session.status, "starting");
873 assert.equal(thread.session.activeTurnId, null);
874 assert.deepStrictEqual(binding.runtimePayload, {
875 activeTurnId: null,
876 continueAfterServerUpdate: turnId,
877 continueAfterServerUpdatePrepared: true,
878 });
879
880 if (preparedStatus === "completed after update marking") {
881 thread.session.status = "ready";
882 binding = {
883 ...binding,
884 status: "stopped",
885 runtimePayload: {
886 activeTurnId: null,
887 continueAfterServerUpdate: turnId,
888 continueAfterServerUpdatePrepared: null,
889 },
890 };
891 yield* runReconciliation(input);
892 assert.deepStrictEqual(sends, []);
893 assert.equal(thread.session.status, "ready");
894 return;
895 }
896 thread.session.status =
897 preparedStatus === "ready with failed scan" ? "ready" : preparedStatus;
898 yield* runReconciliation(input);
899 yield* Deferred.await(cleared);
900 assert.deepStrictEqual(sends, [
901 { threadId: thread.id, continuation: true, interactionMode: "default" },
902 ]);
903 assert.deepStrictEqual(binding.runtimePayload, {
904 activeTurnId: null,
905 continueAfterServerUpdate: null,
906 continueAfterServerUpdatePrepared: null,
907 });
908 }),
909 );
910}
911
912it.effect("settles failed opt-in recovery without retrying the provider turn", () =>
913 Effect.gen(function* () {
914 const turnId = TurnId.make("turn-failed-recovery");
915 const thread = makeThread("thread-failed-recovery", "running", turnId);
916 const settled = yield* Deferred.make<void>();
917 const sends: ProviderSendTurnInput[] = [];
918 const dispatched: OrchestrationCommand[] = [];
919 const preparedPayloads: unknown[] = [];
920 let binding: ProviderSessionDirectory.ProviderRuntimeBinding = {
921 threadId: thread.id,
922 provider: ProviderDriverKind.make("codex"),
923 providerInstanceId,
924 status: "running",
925 resumeCursor: { threadId: thread.id },
926 runtimePayload: { activeTurnId: turnId },
927 };
928 yield* runReconciliation({
929 threads: [thread],
930 continueAfterRestart: true,
931 providerService: {
932 ...makeProviderService(),
933 getCapabilities: () =>
934 Effect.succeed({ sessionModelSwitch: "in-session", promptlessTurnContinuation: true }),
935 sendTurn: (input) =>
936 Effect.gen(function* () {
937 sends.push(input);
938 preparedPayloads.push(binding.runtimePayload);
939 return yield* new ProviderSessionNotFoundError({ threadId: input.threadId });
940 }),
941 },
942 directory: {
943 getBinding: () => Effect.sync(() => Option.some(binding)),
944 upsert: (next) =>
945 Effect.sync(() => {
946 binding = next;
947 }),
948 recordImportedTranscript: () => Effect.die("unused"),
949 getProvider: () => Effect.die("unused"),
950 listThreadIds: () => Effect.die("unused"),
951 listBindings: () => Effect.succeed([]),
952 },
953 dispatch: (command) =>
954 Effect.gen(function* () {
955 dispatched.push(command);
956 if (command.type === "thread.session.set" && command.session.status === "error") {
957 yield* Deferred.succeed(settled, undefined);
958 }
959 return { sequence: dispatched.length };
960 }),
961 });
962 yield* Deferred.await(settled);
963 assert.equal(sends.length, 1);
964 assert.deepStrictEqual(preparedPayloads, [
965 {
966 activeTurnId: null,
967 continueAfterServerUpdate: turnId,
968 continueAfterServerUpdatePrepared: true,
969 },
970 ]);
971 assert.deepStrictEqual(
972 dispatched.map(
973 (command) =>
974 command.type === "thread.session.set" && {
975 status: command.session.status,
976 activeTurnId: command.session.activeTurnId,
977 },
978 ),
979 [
980 { status: "starting", activeTurnId: null },
981 { status: "error", activeTurnId: null },
982 ],
983 );
984 assert.equal(binding.status, "stopped");
985 assert.deepStrictEqual(binding.runtimePayload, {
986 activeTurnId: null,
987 continueAfterServerUpdate: null,
988 continueAfterServerUpdatePrepared: null,
989 });
990 }),
991);