Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 ProviderDriverKind,
4 ProviderInstanceId,
5 ProviderSessionId,
6 ProviderThreadId,
7 ThreadId,
8 type OrchestrationV2ThreadProjection,
9} from "@t3tools/contracts";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Layer from "effect/Layer";
13
14import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
15import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
16import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
17import { acpSelectionTransition } from "./ProviderSelectionTransition.ts";
18import * as ProviderSwitch from "./ProviderSwitchService.ts";
19
20const driver = ProviderDriverKind.make("codex");
21const currentInstanceId = ProviderInstanceId.make("codex_primary");
22const currentSessionId = ProviderSessionId.make("session_primary");
23const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
24const capabilitiesWithoutModelSwitch = {
25 ...CodexProviderCapabilitiesV2,
26 sessions: {
27 ...CodexProviderCapabilitiesV2.sessions,
28 supportsModelSwitchInSession: false,
29 },
30};
31
32function projection(): OrchestrationV2ThreadProjection {
33 return {
34 thread: {
35 id: ThreadId.make("thread_switch_service"),
36 modelSelection: { instanceId: currentInstanceId, model: "gpt-5.1-codex" },
37 runtimeMode: "full-access",
38 interactionMode: "default",
39 worktreePath: "/repo",
40 },
41 providerSessions: [
42 {
43 id: currentSessionId,
44 providerInstanceId: currentInstanceId,
45 status: "ready",
46 cwd: "/repo",
47 capabilities: capabilitiesWithoutModelSwitch,
48 updatedAt: now,
49 },
50 ],
51 providerThreads: [],
52 } as unknown as OrchestrationV2ThreadProjection;
53}
54
55function deadSessionRecord(
56 id: string,
57 status: "stopped" | "error",
58 updatedAt: DateTime.Utc = DateTime.add(now, { seconds: 1 }),
59) {
60 return {
61 ...projection().providerSessions[0]!,
62 id: ProviderSessionId.make(id),
63 status,
64 updatedAt,
65 };
66}
67
68function testLayer(
69 metadata: Readonly<Record<string, { continuationKey: string }>>,
70 planSelectionTransition: ProviderAdapterV2Shape["planSelectionTransition"] = () =>
71 Effect.succeed({ type: "restart_session" }),
72) {
73 const adapter = (instanceId: ProviderInstanceId): ProviderAdapterV2Shape => ({
74 instanceId,
75 driver,
76 getCapabilities: () => Effect.succeed(capabilitiesWithoutModelSwitch),
77 planSelectionTransition,
78 openSession: () => Effect.die("ProviderSwitchService tests do not open sessions."),
79 });
80 const registry = Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
81 get: (instanceId) =>
82 metadata[instanceId] === undefined
83 ? Effect.fail(
84 new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
85 )
86 : Effect.succeed(adapter(instanceId)),
87 list: () => Effect.succeed(Object.keys(metadata).map((id) => ProviderInstanceId.make(id))),
88 getMetadata: (instanceId) => {
89 const value = metadata[instanceId];
90 return value === undefined
91 ? Effect.fail(
92 new ProviderAdapterRegistry.ProviderAdapterRegistryLookupError({ instanceId }),
93 )
94 : Effect.succeed({
95 driver,
96 continuationKey: value.continuationKey,
97 enabled: true,
98 capabilities: capabilitiesWithoutModelSwitch,
99 });
100 },
101 });
102 return ProviderSwitch.layer.pipe(Layer.provide(registry));
103}
104
105it.effect(
106 "restarts and releases the current session for unsupported in-session model changes",
107 () =>
108 Effect.gen(function* () {
109 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
110 const result = yield* service.plan({
111 projection: projection(),
112 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
113 });
114 assert.equal(result.transition.type, "restart_and_resume");
115 assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
116 }).pipe(
117 Effect.provide(
118 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
119 ),
120 ),
121);
122
123it.effect.each(["stopped", "error"] as const)(
124 "restarts and releases the live session when a newer %s session exists",
125 (deadStatus) =>
126 Effect.gen(function* () {
127 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
128 const thread = projection();
129 const result = yield* service.plan({
130 projection: {
131 ...thread,
132 providerSessions: [
133 ...thread.providerSessions,
134 deadSessionRecord("dead_session", deadStatus),
135 ],
136 },
137 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
138 });
139 assert.equal(result.transition.type, "restart_and_resume");
140 assert.deepEqual(result.releaseProviderSessionIds, [currentSessionId]);
141 }).pipe(
142 Effect.provide(
143 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
144 ),
145 ),
146);
147
148it.effect("releases the newest live session, not the newest record overall", () =>
149 Effect.gen(function* () {
150 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
151 const thread = projection();
152 const newerLiveSessionId = ProviderSessionId.make("session_newer_live");
153 const result = yield* service.plan({
154 projection: {
155 ...thread,
156 providerSessions: [
157 ...thread.providerSessions,
158 {
159 ...thread.providerSessions[0]!,
160 id: newerLiveSessionId,
161 updatedAt: DateTime.add(now, { seconds: 1 }),
162 },
163 deadSessionRecord("dead_session", "stopped", DateTime.add(now, { seconds: 2 })),
164 ],
165 },
166 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
167 });
168 assert.equal(result.transition.type, "restart_and_resume");
169 assert.deepEqual(result.releaseProviderSessionIds, [newerLiveSessionId]);
170 }).pipe(
171 Effect.provide(
172 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
173 ),
174 ),
175);
176
177it.effect("creates a fresh session with handoff when every recorded session is dead", () =>
178 Effect.gen(function* () {
179 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
180 const thread = projection();
181 const result = yield* service.plan({
182 projection: {
183 ...thread,
184 providerSessions: [
185 deadSessionRecord("dead_session_older", "stopped"),
186 deadSessionRecord("dead_session_newer", "error", DateTime.add(now, { seconds: 2 })),
187 ],
188 },
189 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
190 });
191 assert.equal(result.transition.type, "create_with_handoff");
192 assert.deepEqual(result.releaseProviderSessionIds, []);
193 }).pipe(
194 Effect.provide(
195 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
196 ),
197 ),
198);
199
200function deadNativeThreadProjection(
201 status: "stopped" | "error",
202 capabilities = capabilitiesWithoutModelSwitch,
203): OrchestrationV2ThreadProjection {
204 const thread = projection();
205 return {
206 ...thread,
207 thread: {
208 ...thread.thread,
209 activeProviderThreadId: ProviderThreadId.make("provider-thread:native"),
210 },
211 providerSessions: [{ ...deadSessionRecord("dead_session", status), capabilities }],
212 providerThreads: [
213 {
214 id: ProviderThreadId.make("provider-thread:native"),
215 driver,
216 providerInstanceId: currentInstanceId,
217 providerSessionId: ProviderSessionId.make("dead_session"),
218 appThreadId: thread.thread.id,
219 ownerNodeId: null,
220 nativeThreadRef: {
221 driver,
222 nativeId: "native-thread:abc",
223 strength: "strong",
224 },
225 nativeConversationHeadRef: null,
226 status: "idle",
227 firstRunOrdinal: null,
228 lastRunOrdinal: null,
229 handoffIds: [],
230 forkedFrom: null,
231 createdAt: now,
232 updatedAt: now,
233 },
234 ],
235 } as OrchestrationV2ThreadProjection;
236}
237
238it.effect("falls back to the native provider thread when every recorded session is dead", () =>
239 Effect.gen(function* () {
240 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
241 const result = yield* service.plan({
242 projection: deadNativeThreadProjection("stopped"),
243 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
244 });
245 assert.equal(result.transition.type, "restart_and_resume");
246 assert.deepEqual(result.releaseProviderSessionIds, []);
247 }).pipe(
248 Effect.provide(
249 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }),
250 ),
251 ),
252);
253
254it.effect("hands off from a native provider thread after its session detaches", () =>
255 Effect.gen(function* () {
256 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
257 const result = yield* service.plan({
258 projection: { ...deadNativeThreadProjection("stopped"), providerSessions: [] },
259 targetModelSelection: {
260 instanceId: ProviderInstanceId.make("codex_other"),
261 model: "gpt-5.2-codex",
262 },
263 });
264 assert.equal(result.transition.type, "create_with_handoff");
265 assert.deepEqual(result.releaseProviderSessionIds, []);
266 }).pipe(
267 Effect.provide(
268 testLayer({
269 [currentInstanceId]: { continuationKey: "codex:account:primary" },
270 codex_other: { continuationKey: "codex:account:other" },
271 }),
272 ),
273 ),
274);
275
276it.effect.each(["stopped", "error"] as const)(
277 "applies a model change on next turn when a %s session negotiated model switching",
278 (deadStatus) =>
279 Effect.gen(function* () {
280 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
281 const result = yield* service.plan({
282 projection: deadNativeThreadProjection(deadStatus, CodexProviderCapabilitiesV2),
283 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
284 });
285 // Static capabilities report no in-session switch, but the dead
286 // record's negotiated capabilities describe the provider: without
287 // them the ACP classification rejects the selection instead of
288 // reopening with the requested model on the next run.
289 assert.equal(result.transition.type, "switch_model_in_session");
290 assert.deepEqual(result.releaseProviderSessionIds, []);
291 }).pipe(
292 Effect.provide(
293 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }, (input) =>
294 Effect.succeed(acpSelectionTransition(input)),
295 ),
296 ),
297 ),
298);
299
300it.effect("rejects a model change the dead record never negotiated support for", () =>
301 Effect.gen(function* () {
302 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
303 const result = yield* service
304 .plan({
305 projection: deadNativeThreadProjection("stopped"),
306 targetModelSelection: { instanceId: currentInstanceId, model: "gpt-5.2-codex" },
307 })
308 .pipe(Effect.flip);
309 assert.instanceOf(result, ProviderSwitch.ProviderSwitchPlanError);
310 }).pipe(
311 Effect.provide(
312 testLayer({ [currentInstanceId]: { continuationKey: "codex:account:primary" } }, (input) =>
313 Effect.succeed(acpSelectionTransition(input)),
314 ),
315 ),
316 ),
317);
318
319it.effect("distinguishes compatible and incompatible instances of the same driver", () =>
320 Effect.gen(function* () {
321 const service = yield* ProviderSwitch.ProviderSwitchServiceV2;
322 const compatibleId = ProviderInstanceId.make("codex_compatible");
323 const incompatibleId = ProviderInstanceId.make("codex_incompatible");
324 const compatible = yield* service.plan({
325 projection: projection(),
326 targetModelSelection: { instanceId: compatibleId, model: "gpt-5.1-codex" },
327 });
328 const incompatible = yield* service.plan({
329 projection: projection(),
330 targetModelSelection: { instanceId: incompatibleId, model: "gpt-5.1-codex" },
331 });
332 assert.equal(compatible.transition.type, "restart_and_resume");
333 assert.equal(incompatible.transition.type, "create_with_handoff");
334 }).pipe(
335 Effect.provide(
336 testLayer({
337 [currentInstanceId]: { continuationKey: "codex:account:primary" },
338 codex_compatible: { continuationKey: "codex:account:primary" },
339 codex_incompatible: { continuationKey: "codex:account:other" },
340 }),
341 ),
342 ),
343);