Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import {
3 type OrchestrationCommand,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ProviderSendTurnInput,
7 ThreadId,
8 TurnId,
9} from "@t3tools/contracts";
10import { assert, it } from "@effect/vitest";
11import * as Deferred from "effect/Deferred";
12import * as Effect from "effect/Effect";
13import * as Option from "effect/Option";
14import * as Stream from "effect/Stream";
15
16import { OrchestrationCommandInvariantError } from "./orchestration/Errors.ts";
17import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
18import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
19import { ProviderSessionDirectoryPersistenceError } from "./provider/Errors.ts";
20import * as ProviderService from "./provider/Services/ProviderService.ts";
21import * as ProviderSessionDirectory from "./provider/Services/ProviderSessionDirectory.ts";
22import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
23
24const providerInstanceId = ProviderInstanceId.make("codex");
25const updatedAt = "2026-08-20T12:00:00.000Z";
26
27const makeThread = (
28 id: string,
29 status: "starting" | "running" | "ready" | "stopped" | "error",
30 activeTurnId: TurnId | null = null,
31 archivedAt: string | null = null,
32 deletedAt: string | null = null,
33) => ({
34 id: ThreadId.make(id),
35 archivedAt,
36 deletedAt,
37 interactionMode: "default" as const,
38 session: {
39 threadId: ThreadId.make(id),
40 status,
41 providerName: "codex" as const,
42 providerInstanceId,
43 runtimeMode: "full-access" as const,
44 activeTurnId,
45 lastError: null,
46 updatedAt,
47 },
48});
49
50const makeProviderService = (liveThreadIds: ReadonlyArray<ThreadId> = []) =>
51 ({
52 startSession: () => Effect.die("unused"),
53 sendTurn: () => Effect.die("unused"),
54 compactThread: () => Effect.die("unused"),
55 interruptTurn: () => Effect.die("unused"),
56 respondToRequest: () => Effect.die("unused"),
57 respondToUserInput: () => Effect.die("unused"),
58 stopSession: () => Effect.die("unused"),
59 listSessions: () => Effect.succeed(liveThreadIds.map((threadId) => ({ threadId }) as never)),
60 getCapabilities: () => Effect.die("unused"),
61 assertConversationRollbackSupported: () => Effect.die("unused"),
62 getInstanceInfo: () => Effect.die("unused"),
63 rollbackConversation: () => Effect.die("unused"),
64 uploadFeedback: () => Effect.die("unused"),
65 streamEvents: Stream.empty,
66 }) satisfies ProviderService.ProviderService["Service"];
67
68const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>) =>
69 ({
70 getUserInputActivity: () => Effect.die("unused"),
71 getCommandReadModel: () => Effect.succeed({ threads } as never),
72 }) as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"];
73
74const runReconciliation = (input: {
75 readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
76 readonly liveThreadIds?: ReadonlyArray<ThreadId>;
77 readonly providerService?: ProviderService.ProviderService["Service"];
78 readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
79 readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
80}) =>
81 ServerRuntimeStartup.reconcileProviderSessions.pipe(
82 Effect.provideService(
83 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
84 queryWithThreads(input.threads),
85 ),
86 Effect.provideService(
87 ProviderService.ProviderService,
88 input.providerService ?? makeProviderService(input.liveThreadIds),
89 ),
90 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
91 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
92 readEvents: () => Stream.empty,
93 dispatch: input.dispatch,
94 streamDomainEvents: Stream.empty,
95 subscribeDomainEvents: Effect.succeed(Stream.empty),
96 latestSequence: Effect.succeed(0),
97 }),
98 Effect.provide(NodeServices.layer),
99 );
100
101it.effect("marks active running sessions that have persisted resume state", () => {
102 const active = makeThread("thread-mark-active", "running", TurnId.make("turn-mark-active"));
103 const archived = makeThread(
104 "thread-mark-archived",
105 "running",
106 TurnId.make("turn-mark-archived"),
107 updatedAt,
108 );
109 const ready = makeThread("thread-mark-ready", "ready");
110 const missingResumeState = makeThread(
111 "thread-mark-missing-resume-state",
112 "running",
113 TurnId.make("turn-mark-missing-resume-state"),
114 );
115 const bindingReads: ThreadId[] = [];
116 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
117
118 return ServerRuntimeStartup.markRunningProviderSessionsForContinuation.pipe(
119 Effect.provideService(
120 ProjectionSnapshotQuery.ProjectionSnapshotQuery,
121 queryWithThreads([active, archived, ready, missingResumeState]),
122 ),
123 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
124 getBinding: (threadId) =>
125 Effect.sync(() => bindingReads.push(threadId)).pipe(
126 Effect.as(
127 Option.some({
128 threadId,
129 provider: ProviderDriverKind.make("codex"),
130 providerInstanceId,
131 ...(threadId === active.id ? { resumeCursor: { threadId } } : {}),
132 runtimePayload: { activeTurnId: "turn-mark-active" },
133 }),
134 ),
135 ),
136 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
137 getProvider: () => Effect.die("unused"),
138 listThreadIds: () => Effect.die("unused"),
139 listBindings: () => Effect.die("unused"),
140 }),
141 Effect.tap((marked) =>
142 Effect.sync(() => {
143 assert.deepStrictEqual(bindingReads, [active.id, missingResumeState.id]);
144 assert.deepStrictEqual(marked, [active.id]);
145 assert.deepStrictEqual(upserts[0]?.runtimePayload, {
146 activeTurnId: "turn-mark-active",
147 continueAfterServerUpdate: active.session.activeTurnId,
148 });
149 }),
150 ),
151 );
152});
153
154it.effect("continues marked sessions after activation with provider-specific input", () =>
155 Effect.gen(function* () {
156 const codex = makeThread(
157 "thread-continue-codex",
158 "running",
159 TurnId.make("turn-continue-codex"),
160 );
161 const fallback = makeThread("thread-continue-fallback", "starting");
162 const fallbackContinuationTurnId = TurnId.make("turn-continue-fallback");
163 const fallbackProviderInstanceId = ProviderInstanceId.make("claudeAgent");
164 const continuationSent = yield* Deferred.make<void>();
165 const continuationCleared = yield* Deferred.make<void>();
166 const sends: ProviderSendTurnInput[] = [];
167 const dispatched: OrchestrationCommand[] = [];
168 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
169 const bindings = new Map<ThreadId, ProviderSessionDirectory.ProviderRuntimeBinding>(
170 [codex, fallback].map((thread) => [
171 thread.id,
172 {
173 threadId: thread.id,
174 provider:
175 thread.id === codex.id
176 ? ProviderDriverKind.make("codex")
177 : ProviderDriverKind.make("claudeAgent"),
178 providerInstanceId:
179 thread.id === codex.id ? providerInstanceId : fallbackProviderInstanceId,
180 status: "running" as const,
181 runtimePayload: {
182 continueAfterServerUpdate:
183 thread.id === codex.id ? codex.session.activeTurnId : fallbackContinuationTurnId,
184 },
185 },
186 ]),
187 );
188 const providerService: ProviderService.ProviderService["Service"] = {
189 ...makeProviderService(),
190 getCapabilities: (instanceId) =>
191 Effect.succeed({
192 sessionModelSwitch: "in-session",
193 ...(instanceId === providerInstanceId ? { promptlessTurnContinuation: true } : {}),
194 }),
195 sendTurn: (input) =>
196 Effect.gen(function* () {
197 sends.push(input);
198 if (sends.length === 2) {
199 yield* Deferred.succeed(continuationSent, undefined);
200 }
201 return {
202 threadId: input.threadId,
203 turnId: TurnId.make(`continued-${String(input.threadId)}`),
204 };
205 }),
206 };
207
208 yield* runReconciliation({
209 threads: [codex, fallback],
210 providerService,
211 directory: {
212 getBinding: (threadId) =>
213 Effect.sync(() => {
214 const binding = bindings.get(threadId);
215 return binding === undefined ? Option.none() : Option.some(binding);
216 }),
217 upsert: (binding) =>
218 Effect.sync(() => {
219 bindings.set(binding.threadId, binding);
220 upserts.push(binding);
221 const clearedCount = upserts.filter((candidate) => {
222 const payload = candidate.runtimePayload;
223 return (
224 payload !== null &&
225 typeof payload === "object" &&
226 !Array.isArray(payload) &&
227 "continueAfterServerUpdate" in payload &&
228 payload.continueAfterServerUpdate === null
229 );
230 }).length;
231 return clearedCount === 1;
232 }).pipe(
233 Effect.flatMap((firstMarkerCleared) =>
234 firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
235 ),
236 ),
237 getProvider: () => Effect.die("unused"),
238 listThreadIds: () => Effect.die("unused"),
239 listBindings: () => Effect.die("unused"),
240 },
241 dispatch: (command) =>
242 Effect.sync(() => dispatched.push(command)).pipe(
243 Effect.as({ sequence: dispatched.length }),
244 ),
245 });
246 yield* Deferred.await(continuationSent);
247 yield* Deferred.await(continuationCleared);
248
249 assert.deepStrictEqual(
250 sends.toSorted((left, right) => String(left.threadId).localeCompare(String(right.threadId))),
251 [
252 { threadId: codex.id, continuation: true, interactionMode: "default" },
253 {
254 threadId: fallback.id,
255 input: "Continue where you left off.",
256 interactionMode: "default",
257 },
258 ],
259 );
260 assert.deepStrictEqual(
261 dispatched.map((command) =>
262 command.type === "thread.session.set"
263 ? {
264 threadId: command.threadId,
265 status: command.session.status,
266 activeTurnId: command.session.activeTurnId,
267 }
268 : null,
269 ),
270 [
271 {
272 threadId: codex.id,
273 status: "starting",
274 activeTurnId: null,
275 },
276 {
277 threadId: fallback.id,
278 status: "starting",
279 activeTurnId: fallback.session.activeTurnId,
280 },
281 ],
282 );
283 for (const [thread, continuationTurnId] of [
284 [codex, codex.session.activeTurnId],
285 [fallback, fallbackContinuationTurnId],
286 ] as const) {
287 assert.deepStrictEqual(
288 upserts
289 .filter((binding) => binding.threadId === thread.id)
290 .map((binding) => binding.runtimePayload)[0],
291 {
292 continueAfterServerUpdate: continuationTurnId,
293 activeTurnId: null,
294 },
295 );
296 }
297 assert.equal(
298 upserts.some((binding) => {
299 const payload = binding.runtimePayload;
300 return (
301 payload !== null &&
302 typeof payload === "object" &&
303 !Array.isArray(payload) &&
304 "continueAfterServerUpdate" in payload &&
305 payload.continueAfterServerUpdate === null
306 );
307 }),
308 true,
309 );
310 }),
311);
312
313it.effect("does not continue archived or deleted marked sessions", () => {
314 const archived = makeThread(
315 "thread-continue-archived",
316 "running",
317 TurnId.make("turn-continue-archived"),
318 updatedAt,
319 );
320 const deleted = makeThread(
321 "thread-continue-deleted",
322 "running",
323 TurnId.make("turn-continue-deleted"),
324 null,
325 updatedAt,
326 );
327 const sends: ProviderSendTurnInput[] = [];
328 const dispatched: OrchestrationCommand[] = [];
329
330 return runReconciliation({
331 threads: [archived, deleted],
332 providerService: {
333 ...makeProviderService(),
334 sendTurn: (input) =>
335 Effect.sync(() => {
336 sends.push(input);
337 return {
338 threadId: input.threadId,
339 turnId: TurnId.make("unexpected-archived-turn"),
340 };
341 }),
342 },
343 directory: {
344 getBinding: (threadId) => {
345 const thread = threadId === archived.id ? archived : deleted;
346 return Effect.succeed(
347 Option.some({
348 threadId,
349 provider: ProviderDriverKind.make("codex"),
350 providerInstanceId,
351 status: "running" as const,
352 resumeCursor: { cursor: threadId },
353 runtimePayload: {
354 continueAfterServerUpdate: thread.session.activeTurnId,
355 },
356 }),
357 );
358 },
359 upsert: () => Effect.void,
360 getProvider: () => Effect.die("unused"),
361 listThreadIds: () => Effect.die("unused"),
362 listBindings: () => Effect.die("unused"),
363 },
364 dispatch: (command) =>
365 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
366 }).pipe(
367 Effect.tap(() =>
368 Effect.sync(() => {
369 assert.deepStrictEqual(sends, []);
370 assert.deepStrictEqual(
371 dispatched.map((command) =>
372 command.type === "thread.session.set"
373 ? { threadId: command.threadId, status: command.session.status }
374 : null,
375 ),
376 [
377 { threadId: archived.id, status: "error" },
378 { threadId: deleted.id, status: "error" },
379 ],
380 );
381 }),
382 ),
383 );
384});
385
386it.effect("retries continuation preparation before settling a persistent failure", () => {
387 const thread = makeThread(
388 "thread-continuation-preparation-failure",
389 "running",
390 TurnId.make("turn-continuation-preparation-failure"),
391 );
392 const dispatched: OrchestrationCommand[] = [];
393 const failure = new OrchestrationCommandInvariantError({
394 commandType: "thread.session.set",
395 detail: "simulated continuation preparation failure",
396 });
397
398 return runReconciliation({
399 threads: [thread],
400 directory: {
401 getBinding: () =>
402 Effect.succeed(
403 Option.some({
404 threadId: thread.id,
405 provider: ProviderDriverKind.make("codex"),
406 providerInstanceId,
407 status: "running" as const,
408 resumeCursor: { cursor: thread.id },
409 runtimePayload: {
410 continueAfterServerUpdate: thread.session.activeTurnId,
411 },
412 }),
413 ),
414 upsert: () => Effect.void,
415 getProvider: () => Effect.die("unused"),
416 listThreadIds: () => Effect.die("unused"),
417 listBindings: () => Effect.die("unused"),
418 },
419 dispatch: (command) => {
420 if (command.type !== "thread.session.set") {
421 return Effect.die("unexpected command");
422 }
423 dispatched.push(command);
424 return command.session.status === "starting"
425 ? Effect.fail(failure)
426 : Effect.succeed({ sequence: dispatched.length });
427 },
428 }).pipe(
429 Effect.tap(() =>
430 Effect.sync(() =>
431 assert.deepStrictEqual(
432 dispatched.map(
433 (command) => command.type === "thread.session.set" && command.session.status,
434 ),
435 ["starting", "starting", "error"],
436 ),
437 ),
438 ),
439 );
440});
441
442it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
443 const starting = makeThread("thread-starting", "starting");
444 const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
445 const staleActiveTurn = makeThread(
446 "thread-stale-active-turn",
447 "ready",
448 TurnId.make("turn-stale-active"),
449 );
450 const archived = makeThread(
451 "thread-archived",
452 "running",
453 TurnId.make("turn-archived"),
454 updatedAt,
455 );
456 const live = makeThread("thread-live", "running", TurnId.make("turn-live"));
457 const settled = makeThread("thread-ready", "ready");
458 const dispatched: OrchestrationCommand[] = [];
459 const bindingReads: ThreadId[] = [];
460 const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
461
462 return runReconciliation({
463 threads: [starting, running, staleActiveTurn, archived, live, settled],
464 liveThreadIds: [live.id],
465 directory: {
466 getBinding: (candidate) =>
467 Effect.sync(() => bindingReads.push(candidate)).pipe(
468 Effect.as(
469 Option.some({
470 threadId: candidate,
471 provider: ProviderDriverKind.make("codex"),
472 providerInstanceId,
473 status: "running" as const,
474 resumeCursor: { cursor: candidate },
475 runtimePayload: {
476 activeTurnId: "stale",
477 unrelated: candidate,
478 ...(candidate === staleActiveTurn.id
479 ? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
480 : {}),
481 },
482 }),
483 ),
484 ),
485 upsert: (binding) => Effect.sync(() => upserts.push(binding)),
486 getProvider: () => Effect.die("unused"),
487 listThreadIds: () => Effect.die("unused"),
488 listBindings: () => Effect.die("unused"),
489 },
490 dispatch: (command) =>
491 Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
492 }).pipe(
493 Effect.tap(() =>
494 Effect.sync(() => {
495 const orphanIds = [starting.id, running.id, staleActiveTurn.id, archived.id];
496 assert.deepStrictEqual(bindingReads, orphanIds);
497 assert.deepStrictEqual(
498 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
499 orphanIds,
500 );
501 assert.deepStrictEqual(
502 dispatched.map((command) =>
503 command.type === "thread.session.set"
504 ? {
505 status: command.session.status,
506 activeTurnId: command.session.activeTurnId,
507 }
508 : null,
509 ),
510 orphanIds.map(() => ({ status: "error" as const, activeTurnId: null })),
511 );
512 assert.equal(upserts.length, orphanIds.length);
513 for (const binding of upserts) {
514 assert.equal(binding.status, "stopped");
515 assert.deepStrictEqual(
516 binding.runtimePayload,
517 binding.threadId === staleActiveTurn.id
518 ? {
519 activeTurnId: null,
520 unrelated: binding.threadId,
521 continueAfterServerUpdate: null,
522 }
523 : { activeTurnId: null, unrelated: binding.threadId },
524 );
525 assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
526 }
527 }),
528 ),
529 );
530});
531
532it.effect(
533 "settles projections when directory bindings are absent, corrupt, or fail to upsert",
534 () => {
535 const absent = makeThread("thread-binding-absent", "starting");
536 const corrupt = makeThread("thread-binding-corrupt", "running");
537 const upsertFailure = makeThread("thread-binding-upsert-failure", "running");
538 const dispatched: OrchestrationCommand[] = [];
539 const corruptFailure = new ProviderSessionDirectoryPersistenceError({
540 operation: "ProviderSessionDirectory.getBinding",
541 detail: "corrupt persisted binding",
542 });
543 const writeFailure = new ProviderSessionDirectoryPersistenceError({
544 operation: "ProviderSessionDirectory.upsert",
545 detail: "failed binding write",
546 });
547
548 return runReconciliation({
549 threads: [absent, corrupt, upsertFailure],
550 directory: {
551 getBinding: (candidate) =>
552 candidate === absent.id
553 ? Effect.succeed(Option.none())
554 : candidate === corrupt.id
555 ? Effect.fail(corruptFailure)
556 : Effect.succeed(
557 Option.some({
558 threadId: candidate,
559 provider: ProviderDriverKind.make("codex"),
560 providerInstanceId,
561 }),
562 ),
563 upsert: () => Effect.fail(writeFailure),
564 getProvider: () => Effect.die("unused"),
565 listThreadIds: () => Effect.die("unused"),
566 listBindings: () => Effect.die("unused"),
567 },
568 dispatch: (command) =>
569 Effect.sync(() => dispatched.push(command)).pipe(
570 Effect.as({ sequence: dispatched.length }),
571 ),
572 }).pipe(
573 Effect.tap(() =>
574 Effect.sync(() => {
575 assert.deepStrictEqual(
576 dispatched.map((command) => command.type === "thread.session.set" && command.threadId),
577 [absent.id, corrupt.id, upsertFailure.id],
578 );
579 }),
580 ),
581 );
582 },
583);
584
585it.effect("retries failed projections and continues after a persistent failure", () => {
586 const transient = makeThread("thread-dispatch-transient-failure", "running");
587 const persistent = makeThread("thread-dispatch-persistent-failure", "running");
588 const later = makeThread("thread-dispatch-success", "running");
589 const attempted: ThreadId[] = [];
590 let transientAttempts = 0;
591 const failure = new OrchestrationCommandInvariantError({
592 commandType: "thread.session.set",
593 detail: "simulated startup reconciliation failure",
594 });
595
596 return runReconciliation({
597 threads: [transient, persistent, later],
598 directory: {
599 getBinding: () => Effect.succeed(Option.none()),
600 upsert: () => Effect.void,
601 getProvider: () => Effect.die("unused"),
602 listThreadIds: () => Effect.die("unused"),
603 listBindings: () => Effect.die("unused"),
604 },
605 dispatch: (command) => {
606 if (command.type !== "thread.session.set") {
607 return Effect.die("unexpected command");
608 }
609 attempted.push(command.threadId);
610 if (command.threadId === transient.id && transientAttempts++ === 0) {
611 return Effect.fail(failure);
612 }
613 return command.threadId === persistent.id
614 ? Effect.fail(failure)
615 : Effect.succeed({ sequence: attempted.length });
616 },
617 }).pipe(
618 Effect.tap(() =>
619 Effect.sync(() =>
620 assert.deepStrictEqual(attempted, [
621 transient.id,
622 transient.id,
623 persistent.id,
624 persistent.id,
625 later.id,
626 ]),
627 ),
628 ),
629 );
630});
631
632it.effect("does not fail startup when the live provider session inventory cannot be read", () => {
633 let queried = false;
634 return ServerRuntimeStartup.reconcileProviderSessions.pipe(
635 Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
636 getUserInputActivity: () => Effect.die("unused"),
637 getCommandReadModel: () =>
638 Effect.sync(() => {
639 queried = true;
640 return { threads: [] } as never;
641 }),
642 } as unknown as ProjectionSnapshotQuery.ProjectionSnapshotQuery["Service"]),
643 Effect.provideService(ProviderService.ProviderService, {
644 ...makeProviderService(),
645 listSessions: () => Effect.die("provider inventory unavailable"),
646 }),
647 Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
648 getBinding: () => Effect.die("unused"),
649 upsert: () => Effect.die("unused"),
650 getProvider: () => Effect.die("unused"),
651 listThreadIds: () => Effect.die("unused"),
652 listBindings: () => Effect.die("unused"),
653 }),
654 Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
655 readEvents: () => Stream.empty,
656 dispatch: () => Effect.die("unused"),
657 streamDomainEvents: Stream.empty,
658 subscribeDomainEvents: Effect.succeed(Stream.empty),
659 latestSequence: Effect.succeed(0),
660 }),
661 Effect.provide(NodeServices.layer),
662 Effect.tap(() => Effect.sync(() => assert.equal(queried, false))),
663 );
664});