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