Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexSessionRecovery.integration.test.ts

200 lines8.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import { CodexSettings, CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
4import * as Crypto from "effect/Crypto";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14​
15import * as ServerConfig from "../../config.ts";
16import * as ProviderEventLoggers from "../../provider/ProviderEventLoggers.ts";
17import * as EffectWorker from "../EffectWorker.ts";
18import * as EventSink from "../EventSink.ts";
19import * as IdAllocator from "../IdAllocator.ts";
20import * as Orchestrator from "../Orchestrator.ts";
21import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts";
22import * as ProviderSessionManager from "../ProviderSessionManager.ts";
23import * as ProviderReplayHarness from "../testkit/ProviderReplayHarness.ts";
24import * as CodexAdapterV2 from "./CodexAdapterV2.ts";
25​
26const modelSelection = { instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, model: "gpt-5.4" };
27const settings = Schema.decodeSync(CodexSettings)({});
28​
29describe("Codex shared session recovery", () => {
30 it.effect.each(["SIGKILL", "exit code"] as const)(
31 "fails active turns and replaces the shared app-server after %s",
32 (termination) =>
33 Effect.gen(function* () {
34 const fs = yield* FileSystem.FileSystem;
35 const path = yield* Path.Path;
36 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-session-recovery-" });
37 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
38 const handles: Array<ChildProcessSpawner.ChildProcessHandle> = [];
39 const testSpawner = ChildProcessSpawner.make(() =>
40 spawner
41 .spawn(
42 ChildProcess.make(
43 process.execPath,
44 [
45 path.join(
46 import.meta.dirname,
47 "../../provider/testFixtures/codexSessionRecoveryMockPeer.mjs",
48 ),
49 ],
50 { cwd },
51 ),
52 )
53 .pipe(Effect.tap((handle) => Effect.sync(() => handles.push(handle)))),
54 );
55 const layerFactory = CodexAdapterV2.layerAppServerClientFactory.pipe(
56 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, testSpawner)),
57 Layer.provide(
58 Layer.succeed(
59 ProviderEventLoggers.ProviderEventLoggers,
60 ProviderEventLoggers.NoOpProviderEventLoggers,
61 ),
62 ),
63 );
64 const layerRegistry = ProviderAdapterRegistry.layerFromAdaptersEffect(
65 Effect.gen(function* () {
66 const adapter = CodexAdapterV2.makeCodexAdapterV2({
67 instanceId: modelSelection.instanceId,
68 settings,
69 environment: {},
70 clientFactory: yield* CodexAdapterV2.CodexAppServerClientFactory,
71 crypto: yield* Crypto.Crypto,
72 fileSystem: yield* FileSystem.FileSystem,
73 idAllocator: yield* IdAllocator.IdAllocatorV2,
74 serverConfig: yield* ServerConfig.ServerConfig,
75 });
76 return [adapter];
77 }),
78 ).pipe(
79 Layer.provide(
80 Layer.mergeAll(
81 layerFactory,
82 IdAllocator.layer,
83 ServerConfig.layerTest(cwd, { prefix: "t3-codex-session-recovery-config-" }),
84 ).pipe(Layer.provideMerge(NodeServices.layer)),
85 ),
86 );
87​
88 yield* Effect.gen(function* () {
89 const orchestrator = yield* Orchestrator.OrchestratorV2;
90 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
91 const eventSink = yield* EventSink.EventSinkV2;
92 const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
93 const createAndStart = (threadId: ThreadId) =>
94 Effect.gen(function* () {
95 yield* orchestrator.dispatch({
96 type: "thread.create",
97 commandId: CommandId.make(`create:${threadId}`),
98 threadId,
99 projectId: ProjectId.make("project:codex-session-recovery"),
100 title: threadId,
101 modelSelection,
102 runtimeMode: "full-access",
103 interactionMode: "default",
104 branch: null,
105 worktreePath: cwd,
106 createdBy: "user",
107 creationSource: "web",
108 });
109 yield* send(threadId, "start");
110 });
111 const send = (threadId: ThreadId, text: string) =>
112 Effect.gen(function* () {
113 yield* orchestrator.dispatch({
114 type: "message.dispatch",
115 commandId: CommandId.make(`send:${threadId}:${text}`),
116 threadId,
117 messageId: MessageId.make(`message:${threadId}:${text}`),
118 text,
119 attachments: [],
120 dispatchMode: { type: "start_immediately" },
121 createdBy: "user",
122 creationSource: "web",
123 });
124 yield* worker.drain();
125 assert.equal(
126 (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status,
127 "running",
128 );
129 });
130 const threadA = ThreadId.make("thread:codex-recovery-a");
131 const threadB = ThreadId.make("thread:codex-recovery-b");
132 yield* createAndStart(threadA);
133 yield* createAndStart(threadB);
134 assert.equal(handles.length, 1);
135 const sessionA = (yield* orchestrator.getThreadProjection(threadA)).providerSessions.at(
136 -1,
137 )!;
138 const sessionB = (yield* orchestrator.getThreadProjection(threadB)).providerSessions.at(
139 -1,
140 )!;
141 assert.equal(sessionA.id, sessionB.id);
142 const beforeTermination = yield* eventSink.latestSequence();
143 const handle = handles[0]!;
144 if (termination === "SIGKILL") {
145 yield* handle.kill({ killSignal: "SIGKILL" });
146 } else {
147 const encoder = new TextEncoder();
148 yield* Stream.make(encoder.encode('{"id":999,"method":"test/exit"}\n')).pipe(
149 Stream.run(handle.stdin),
150 );
151 }
152 const exit = yield* Effect.exit(handle.exitCode);
153 assert.equal(Exit.isFailure(exit), termination === "SIGKILL");
154 if (Exit.isSuccess(exit)) assert.equal(Number(exit.value), 7);
155​
156 // Await committed failures, rather than guessing when the event pump ran.
157 yield* eventSink
158 .stream({ afterSequence: beforeTermination, eventType: "provider-session.updated" })
159 .pipe(
160 Stream.filter(
161 ({ event }) =>
162 event.type === "provider-session.updated" && event.payload.status === "error",
163 ),
164 Stream.take(2),
165 Stream.runDrain,
166 );
167 yield* eventSink
168 .stream({ afterSequence: beforeTermination, eventType: "run.updated" })
169 .pipe(
170 Stream.filter(
171 ({ event }) => event.type === "run.updated" && event.payload.status === "failed",
172 ),
173 Stream.take(2),
174 Stream.runDrain,
175 );
176 yield* worker.drain();
177 assert.isTrue(Option.isNone(yield* manager.get(sessionA.id)));
178 for (const threadId of [threadA, threadB]) {
179 const projection = yield* orchestrator.getThreadProjection(threadId);
180 assert.equal(projection.runs.at(-1)?.status, "failed");
181 assert.equal(projection.providerSessions.at(-1)?.status, "error");
182 }
183​
184 yield* createAndStart(ThreadId.make("thread:codex-recovery-new"));
185 assert.equal(handles.length, 2);
186 assert.notEqual(handles[0]!.pid, handles[1]!.pid);
187 yield* send(threadA, "retry");
188 assert.equal(handles.length, 2);
189 }).pipe(
190 Effect.provide(
191 ProviderReplayHarness.layerWithRegistry(
192 { name: `codex-session-recovery-${termination}`, runtimePolicyOverride: { cwd } },
193 layerRegistry,
194 { runEffectWorker: false },
195 ),
196 ),
197 );
198 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
199 );
200});