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

SelectionRestart.integration.test.ts

639 lines24.5 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 type ModelSelection,
6 type OrchestrationV2ProviderCapabilities,
7 type OrchestrationV2ProviderSession,
8 type OrchestrationV2ProviderThread,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderThreadId,
13 ProviderTurnId,
14 type RunId,
15 ThreadId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Queue from "effect/Queue";
20import * as Ref from "effect/Ref";
21import * as Stream from "effect/Stream";
22​
23import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
24import { OrchestratorV2 } from "./Orchestrator.ts";
25import {
26 ProviderAdapterOpenSessionError,
27 type ProviderAdapterV2Event,
28 type ProviderAdapterV2Shape,
29 type ProviderAdapterV2TurnInput,
30} from "./ProviderAdapter.ts";
31import {
32 makeLayer as makeProviderAdapterRegistryLayer,
33 makeSingleLayer as makeSingleProviderAdapterRegistryLayer,
34} from "./ProviderAdapterRegistry.ts";
35import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
36import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
37​
38const driver = ProviderDriverKind.make("codex");
39const providerInstanceId = ProviderInstanceId.make("codex-restart-test");
40const initialSelection = {
41 instanceId: providerInstanceId,
42 model: "restart-model-a",
43} satisfies ModelSelection;
44const replacementSelection = {
45 instanceId: providerInstanceId,
46 model: "restart-model-b",
47} satisfies ModelSelection;
48const handoffDriver = ProviderDriverKind.make("claudeAgent");
49const handoffProviderInstanceId = ProviderInstanceId.make("claude-handoff-test");
50const handoffSelection = {
51 instanceId: handoffProviderInstanceId,
52 model: "handoff-model",
53} satisfies ModelSelection;
54const pooledCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2;
55const exclusiveCapabilities: OrchestrationV2ProviderCapabilities = {
56 ...CodexProviderCapabilitiesV2,
57 sessions: {
58 ...CodexProviderCapabilitiesV2.sessions,
59 supportsMultipleProviderThreadsPerSession: false,
60 supportsModelSwitchInSession: false,
61 },
62};
63​
64interface ActiveTurn {
65 readonly input: ProviderAdapterV2TurnInput;
66 readonly providerTurnId: ProviderTurnId;
68​
69interface RestartAdapterState {
70 readonly activeTurn: ActiveTurn | null;
71 readonly opened: ReadonlyArray<{
72 readonly model: string | null;
73 readonly cwd: string | null;
74 }>;
75 readonly started: ReadonlyArray<{
76 readonly model: string;
77 readonly cwd: string | null;
78 readonly attemptId: string;
79 }>;
80 readonly closedSessionCount: number;
81 readonly failedReplacementOpen: boolean;
83​
84function makeRestartAdapter(
85 state: Ref.Ref<RestartAdapterState>,
86 sessionCapabilities: OrchestrationV2ProviderCapabilities = pooledCapabilities,
87): ProviderAdapterV2Shape {
88 return {
89 instanceId: providerInstanceId,
90 driver,
91 getCapabilities: () => Effect.succeed(sessionCapabilities),
92 planSelectionTransition: ({ current, target }) =>
93 Effect.succeed(
94 current.model === target.model
95 ? ({ type: "apply_on_next_turn" } as const)
96 : ({ type: "restart_session" } as const),
97 ),
98 openSession: (sessionInput) =>
99 Effect.gen(function* () {
100 const failThisOpen = yield* Ref.modify(state, (current) => {
101 const shouldFail =
102 sessionInput.modelSelection.model === replacementSelection.model &&
103 !current.failedReplacementOpen;
104 return [
105 shouldFail,
106 {
107 ...current,
108 failedReplacementOpen: current.failedReplacementOpen || shouldFail,
109 opened: [
110 ...current.opened,
111 {
112 model: sessionInput.modelSelection.model,
113 cwd: sessionInput.runtimePolicy.cwd,
114 },
115 ],
116 },
117 ] as const;
118 });
119 if (failThisOpen) {
120 return yield* new ProviderAdapterOpenSessionError({
121 driver,
122 providerSessionId: sessionInput.providerSessionId,
123 cause: "simulated replacement open failure",
124 });
125 }
126​
127 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
128 const now = yield* DateTime.now;
129 const providerSession: OrchestrationV2ProviderSession = {
130 id: sessionInput.providerSessionId,
131 driver,
132 providerInstanceId,
133 status: "ready",
134 cwd: sessionInput.runtimePolicy.cwd ?? "/fallback",
135 model: sessionInput.modelSelection.model,
136 capabilities: sessionCapabilities,
137 createdAt: now,
138 updatedAt: now,
139 lastError: null,
140 };
141 yield* Effect.addFinalizer(() =>
142 Ref.update(state, (current) => ({
143 ...current,
144 closedSessionCount: current.closedSessionCount + 1,
145 })),
146 );
147​
148 const publishTerminal = (active: ActiveTurn, status: "completed" | "interrupted") =>
149 Effect.gen(function* () {
150 const occurredAt = yield* DateTime.now;
151 yield* Queue.offer(events, {
152 type: "provider_turn.updated",
153 driver,
154 providerTurn: {
155 id: active.providerTurnId,
156 providerThreadId: active.input.providerThread.id,
157 nodeId: active.input.rootNodeId,
158 runAttemptId: active.input.attemptId,
159 nativeTurnRef: {
160 driver,
161 nativeId: `native:${active.providerTurnId}`,
162 strength: "strong",
163 },
164 ordinal: active.input.providerTurnOrdinal,
165 status,
166 startedAt: occurredAt,
167 completedAt: occurredAt,
168 },
169 });
170 yield* Queue.offer(events, {
171 type: "turn.terminal",
172 driver,
173 providerThreadId: active.input.providerThread.id,
174 providerTurnId: active.providerTurnId,
175 runOrdinal: active.input.runOrdinal,
176 status,
177 failure: null,
178 threadDisposition: "reusable",
179 });
180 });
181​
182 return {
183 instanceId: providerInstanceId,
184 driver,
185 providerSessionId: sessionInput.providerSessionId,
186 providerSession,
187 events: Stream.fromQueue(events),
188 ensureThread: (threadInput) =>
189 Effect.gen(function* () {
190 const createdAt = yield* DateTime.now;
191 return {
192 id: ProviderThreadId.make(`provider-thread:${threadInput.threadId}`),
193 driver,
194 providerInstanceId,
195 providerSessionId: sessionInput.providerSessionId,
196 appThreadId: threadInput.threadId,
197 ownerNodeId: null,
198 nativeThreadRef: {
199 driver,
200 nativeId: `native-thread:${threadInput.threadId}`,
201 strength: "strong",
202 },
203 nativeConversationHeadRef: null,
204 status: "idle",
205 firstRunOrdinal: null,
206 lastRunOrdinal: null,
207 handoffIds: [],
208 forkedFrom: null,
209 createdAt,
210 updatedAt: createdAt,
211 } satisfies OrchestrationV2ProviderThread;
212 }),
213 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
214 startTurn: (input) =>
215 Effect.gen(function* () {
216 yield* Ref.update(state, (current) => ({
217 ...current,
218 started: [
219 ...current.started,
220 {
221 model: input.modelSelection.model,
222 cwd: input.runtimePolicy.cwd,
223 attemptId: input.attemptId,
224 },
225 ],
226 }));
227 const active = {
228 input,
229 providerTurnId: ProviderTurnId.make(`provider-turn:${input.attemptId}`),
230 } satisfies ActiveTurn;
231 if (input.modelSelection.model === initialSelection.model) {
232 const occurredAt = yield* DateTime.now;
233 yield* Ref.update(state, (current) => ({ ...current, activeTurn: active }));
234 yield* Queue.offer(events, {
235 type: "provider_turn.updated",
236 driver,
237 providerTurn: {
238 id: active.providerTurnId,
239 providerThreadId: input.providerThread.id,
240 nodeId: input.rootNodeId,
241 runAttemptId: input.attemptId,
242 nativeTurnRef: {
243 driver,
244 nativeId: `native:${active.providerTurnId}`,
245 strength: "strong",
246 },
247 ordinal: input.providerTurnOrdinal,
248 status: "running",
249 startedAt: occurredAt,
250 completedAt: null,
251 },
252 });
253 return;
254 }
255 yield* publishTerminal(active, "completed");
256 }),
257 steerTurn: () => Effect.void,
258 interruptTurn: () =>
259 Effect.gen(function* () {
260 const active = (yield* Ref.get(state)).activeTurn;
261 if (active !== null) {
262 const updatedAt = yield* DateTime.now;
263 yield* Queue.offer(events, {
264 type: "provider_thread.updated",
265 driver,
266 providerThread: {
267 ...active.input.providerThread,
268 status: "idle",
269 updatedAt,
270 },
271 });
272 yield* publishTerminal(active, "interrupted");
273 yield* Ref.update(state, (current) => ({ ...current, activeTurn: null }));
274 }
275 }),
276 respondToRuntimeRequest: () => Effect.void,
277 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
278 rollbackThread: () => Effect.die("unused rollbackThread"),
279 forkThread: () => Effect.die("unused forkThread"),
280 };
281 }),
282 };
284​
285function makeCompletingHandoffAdapter(startCount: Ref.Ref<number>): ProviderAdapterV2Shape {
286 return {
287 instanceId: handoffProviderInstanceId,
288 driver: handoffDriver,
289 getCapabilities: () => Effect.succeed(exclusiveCapabilities),
290 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
291 openSession: (sessionInput) =>
292 Effect.gen(function* () {
293 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
294 const now = yield* DateTime.now;
295 return {
296 instanceId: handoffProviderInstanceId,
297 driver: handoffDriver,
298 providerSessionId: sessionInput.providerSessionId,
299 providerSession: {
300 id: sessionInput.providerSessionId,
301 driver: handoffDriver,
302 providerInstanceId: handoffProviderInstanceId,
303 status: "ready",
304 cwd: sessionInput.runtimePolicy.cwd ?? "/fallback",
305 model: sessionInput.modelSelection.model,
306 capabilities: exclusiveCapabilities,
307 createdAt: now,
308 updatedAt: now,
309 lastError: null,
310 },
311 events: Stream.fromQueue(events),
312 ensureThread: (threadInput) =>
313 Effect.gen(function* () {
314 const createdAt = yield* DateTime.now;
315 return {
316 id: ProviderThreadId.make(`provider-thread:handoff:${threadInput.threadId}`),
317 driver: handoffDriver,
318 providerInstanceId: handoffProviderInstanceId,
319 providerSessionId: sessionInput.providerSessionId,
320 appThreadId: threadInput.threadId,
321 ownerNodeId: null,
322 nativeThreadRef: {
323 driver: handoffDriver,
324 nativeId: `native-thread:handoff:${threadInput.threadId}`,
325 strength: "strong",
326 },
327 nativeConversationHeadRef: null,
328 status: "idle",
329 firstRunOrdinal: null,
330 lastRunOrdinal: null,
331 handoffIds: [],
332 forkedFrom: null,
333 createdAt,
334 updatedAt: createdAt,
335 } satisfies OrchestrationV2ProviderThread;
336 }),
337 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
338 startTurn: (input) =>
339 Effect.gen(function* () {
340 yield* Ref.update(startCount, (count) => count + 1);
341 const occurredAt = yield* DateTime.now;
342 const providerTurnId = ProviderTurnId.make(
343 `provider-turn:handoff:${input.attemptId}`,
344 );
345 yield* Queue.offer(events, {
346 type: "provider_turn.updated",
347 driver: handoffDriver,
348 providerTurn: {
349 id: providerTurnId,
350 providerThreadId: input.providerThread.id,
351 nodeId: input.rootNodeId,
352 runAttemptId: input.attemptId,
353 nativeTurnRef: {
354 driver: handoffDriver,
355 nativeId: `native:${providerTurnId}`,
356 strength: "strong",
357 },
358 ordinal: input.providerTurnOrdinal,
359 status: "completed",
360 startedAt: occurredAt,
361 completedAt: occurredAt,
362 },
363 });
364 yield* Queue.offer(events, {
365 type: "turn.terminal",
366 driver: handoffDriver,
367 providerThreadId: input.providerThread.id,
368 providerTurnId,
369 runOrdinal: input.runOrdinal,
370 status: "completed",
371 failure: null,
372 threadDisposition: "reusable",
373 });
374 }),
375 steerTurn: () => Effect.void,
376 interruptTurn: () => Effect.void,
377 respondToRuntimeRequest: () => Effect.void,
378 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
379 rollbackThread: () => Effect.die("unused rollbackThread"),
380 forkThread: () => Effect.die("unused forkThread"),
381 };
382 }),
383 };
385​
386it.live("restarts selection as a new attempt and retries after old-session cleanup", () =>
387 Effect.scoped(
388 Effect.gen(function* () {
389 const cwd = yield* checkpointWorkspace("selection-restart-lifecycle");
390 const threadId = ThreadId.make("thread:selection-restart-lifecycle");
391 const state = yield* Ref.make<RestartAdapterState>({
392 activeTurn: null,
393 opened: [],
394 started: [],
395 closedSessionCount: 0,
396 failedReplacementOpen: false,
397 });
398 const registry = makeSingleProviderAdapterRegistryLayer(makeRestartAdapter(state));
399​
400 const result = yield* Effect.gen(function* () {
401 const orchestrator = yield* OrchestratorV2;
402 yield* orchestrator.dispatch({
403 type: "thread.create",
404 createdBy: "user",
405 creationSource: "web",
406 commandId: CommandId.make("command:selection-restart:create"),
407 threadId,
408 projectId: ProjectId.make("project:selection-restart"),
409 title: "Selection restart",
410 modelSelection: initialSelection,
411 runtimeMode: "full-access",
412 interactionMode: "default",
413 branch: null,
414 worktreePath: cwd,
415 });
416 yield* orchestrator.dispatch({
417 type: "message.dispatch",
418 createdBy: "user",
419 creationSource: "web",
420 commandId: CommandId.make("command:selection-restart:first"),
421 threadId,
422 messageId: MessageId.make("message:selection-restart:first"),
423 text: "first",
424 attachments: [],
425 modelSelection: initialSelection,
426 dispatchMode: { type: "start_immediately" },
427 });
428 for (let index = 0; index < 1_000; index += 1) {
429 const current = yield* orchestrator.getThreadProjection(threadId);
430 if (current.providerTurns.some((turn) => turn.status === "running")) break;
431 yield* Effect.sleep("5 millis");
432 }
433 const activeProjection = yield* orchestrator.getThreadProjection(threadId);
434 assert.isTrue(activeProjection.providerTurns.some((turn) => turn.status === "running"));
435 const activeRunId = activeProjection.runs[0]?.id;
436 if (activeRunId === undefined) {
437 return yield* Effect.die("active restart test run is missing");
438 }
439​
440 yield* orchestrator.dispatch({
441 type: "message.dispatch",
442 createdBy: "user",
443 creationSource: "web",
444 commandId: CommandId.make("command:selection-restart:second"),
445 threadId,
446 messageId: MessageId.make("message:selection-restart:second"),
447 text: "second",
448 attachments: [],
449 modelSelection: replacementSelection,
450 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
451 });
452 for (let index = 0; index < 1_000; index += 1) {
453 const current = yield* orchestrator.getThreadProjection(threadId);
454 if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") {
455 const captured = yield* Ref.get(state);
456 return { projection: current, captured };
457 }
458 yield* Effect.sleep("5 millis");
459 }
460 const current = yield* orchestrator.getThreadProjection(threadId);
461 const adapterState = yield* Ref.get(state);
462 yield* Effect.logError("selection restart did not complete", {
463 runs: current.runs.map((run) => [run.status, run.activeAttemptId]),
464 attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]),
465 providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]),
466 providerThreads: current.providerThreads.map((thread) => [
467 thread.providerSessionId,
468 thread.status,
469 ]),
470 adapterState,
471 });
472 return yield* Effect.die("selection restart did not complete");
473 }).pipe(
474 Effect.provide(
475 makeOrchestratorV2ReplayLayerWithRegistry(
476 { name: "selection-restart-lifecycle" },
477 registry,
478 ),
479 ),
480 );
481 const { projection, captured } = result;
482​
483 assert.lengthOf(projection.runs, 1);
484 assert.lengthOf(projection.attempts, 2);
485 assert.deepEqual(
486 projection.attempts.map((attempt) => attempt.status),
487 ["superseded", "completed"],
488 );
489 assert.deepEqual(
490 projection.providerTurns.map((turn) => turn.status),
491 ["interrupted", "completed"],
492 );
493 assert.isTrue(projection.turnItems.some((item) => item.type === "run_interrupt_result"));
494 assert.equal(projection.runs[0]?.modelSelection.model, replacementSelection.model);
495 assert.isTrue(captured.failedReplacementOpen);
496 // The old pooled process remains available to its other threads; this
497 // thread moved to a freshly allocated replacement session.
498 assert.equal(captured.closedSessionCount, 0);
499 assert.deepEqual(
500 captured.opened.map((open) => [open.model, open.cwd]),
501 [
502 [initialSelection.model, cwd],
503 [replacementSelection.model, cwd],
504 [replacementSelection.model, cwd],
505 ],
506 );
507 assert.deepEqual(
508 captured.started.map((turn) => [turn.model, turn.cwd]),
509 [
510 [initialSelection.model, cwd],
511 [replacementSelection.model, cwd],
512 ],
513 );
514 assert.notEqual(
515 projection.providerSessions[0]?.id,
516 projection.providerThreads[0]?.providerSessionId,
517 );
518 assert.equal(
519 projection.providerThreads[0]?.providerSessionId,
520 projection.providerSessions.find((session) => session.model === replacementSelection.model)
521 ?.id,
522 );
523 }),
524 ),
525);
526​
527it.live("detaches the old provider session after an active provider handoff", () =>
528 Effect.scoped(
529 Effect.gen(function* () {
530 const cwd = yield* checkpointWorkspace("selection-provider-handoff-lifecycle");
531 const threadId = ThreadId.make("thread:selection-provider-handoff-lifecycle");
532 const state = yield* Ref.make<RestartAdapterState>({
533 activeTurn: null,
534 opened: [],
535 started: [],
536 closedSessionCount: 0,
537 failedReplacementOpen: false,
538 });
539 const targetStartCount = yield* Ref.make(0);
540 const registry = makeProviderAdapterRegistryLayer([
541 makeRestartAdapter(state, exclusiveCapabilities),
542 makeCompletingHandoffAdapter(targetStartCount),
543 ]);
544​
545 const result = yield* Effect.gen(function* () {
546 const orchestrator = yield* OrchestratorV2;
547 yield* orchestrator.dispatch({
548 type: "thread.create",
549 createdBy: "user",
550 creationSource: "web",
551 commandId: CommandId.make("command:selection-handoff:create"),
552 threadId,
553 projectId: ProjectId.make("project:selection-handoff"),
554 title: "Selection provider handoff",
555 modelSelection: initialSelection,
556 runtimeMode: "full-access",
557 interactionMode: "default",
558 branch: null,
559 worktreePath: cwd,
560 });
561 yield* orchestrator.dispatch({
562 type: "message.dispatch",
563 createdBy: "user",
564 creationSource: "web",
565 commandId: CommandId.make("command:selection-handoff:first"),
566 threadId,
567 messageId: MessageId.make("message:selection-handoff:first"),
568 text: "first",
569 attachments: [],
570 modelSelection: initialSelection,
571 dispatchMode: { type: "start_immediately" },
572 });
573 let activeRunId: RunId | null = null;
574 for (let index = 0; index < 1_000; index += 1) {
575 const current = yield* orchestrator.getThreadProjection(threadId);
576 if (current.providerTurns.some((turn) => turn.status === "running")) {
577 activeRunId = current.runs[0]?.id ?? null;
578 break;
579 }
580 yield* Effect.sleep("5 millis");
581 }
582 if (activeRunId === null) {
583 return yield* Effect.die("active provider-handoff run is missing");
584 }
585​
586 yield* orchestrator.dispatch({
587 type: "message.dispatch",
588 createdBy: "user",
589 creationSource: "web",
590 commandId: CommandId.make("command:selection-handoff:second"),
591 threadId,
592 messageId: MessageId.make("message:selection-handoff:second"),
593 text: "second",
594 attachments: [],
595 modelSelection: handoffSelection,
596 dispatchMode: { type: "restart_active", targetRunId: activeRunId },
597 });
598 for (let index = 0; index < 1_000; index += 1) {
599 const current = yield* orchestrator.getThreadProjection(threadId);
600 if (current.attempts.length === 2 && current.attempts[1]?.status === "completed") {
601 const captured = yield* Ref.get(state);
602 return { projection: current, captured };
603 }
604 yield* Effect.sleep("5 millis");
605 }
606 const current = yield* orchestrator.getThreadProjection(threadId);
607 const adapterState = yield* Ref.get(state);
608 const capturedTargetStartCount = yield* Ref.get(targetStartCount);
609 yield* Effect.logError("active provider handoff did not complete", {
610 runs: current.runs.map((run) => [run.status, run.activeAttemptId]),
611 attempts: current.attempts.map((attempt) => [attempt.id, attempt.status]),
612 providerTurns: current.providerTurns.map((turn) => [turn.id, turn.status]),
613 providerThreads: current.providerThreads.map((thread) => [
614 thread.providerInstanceId,
615 thread.providerSessionId,
616 thread.status,
617 ]),
618 targetStartCount: capturedTargetStartCount,
619 adapterState,
620 });
621 return yield* Effect.die("active provider handoff did not complete");
622 }).pipe(
623 Effect.provide(
624 makeOrchestratorV2ReplayLayerWithRegistry(
625 { name: "selection-provider-handoff-lifecycle" },
626 registry,
627 ),
628 ),
629 );
630​
631 assert.lengthOf(result.projection.runs, 1);
632 assert.lengthOf(result.projection.attempts, 2);
633 assert.equal(result.projection.runs[0]?.providerInstanceId, handoffProviderInstanceId);
634 assert.equal(result.projection.contextHandoffs.length, 1);
635 assert.equal(result.captured.closedSessionCount, 1);
636 assert.equal(yield* Ref.get(targetStartCount), 1);
637 }),
638 ),
639);