Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 EventId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 ThreadId,
13 type OrchestrationV2DomainEvent,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
22import * as EffectWorker from "./EffectWorker.ts";
23import * as EventSink from "./EventSink.ts";
24import * as Orchestrator from "./Orchestrator.ts";
25import {
26 ProviderAdapterSteerRunError,
27 type ProviderAdapterV2Event,
28 type ProviderAdapterV2Shape,
29 type ProviderAdapterV2TurnInput,
30} from "./ProviderAdapter.ts";
31import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
32import { makeOrchestratorV2ReplayLayerWithRegistry } from "./testkit/ProviderReplayHarness.ts";
33import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
34
35const driver = ProviderDriverKind.make("codex");
36const instanceId = ProviderInstanceId.make("codex");
37const modelSelection = { instanceId, model: "test-model" };
38
39for (const mailbox of [false, true]) {
40 for (const timing of [
41 "before delivery",
42 "during delivery",
43 "before dispatch",
44 "after delivery",
45 "without native steering",
46 "settled only",
47 ] as const) {
48 if (!mailbox && (timing === "without native steering" || timing === "settled only")) continue;
49 it.effect(
50 `delivers ${mailbox ? "mailbox notification" : "steering"} when completion wins ${timing}`,
51 () =>
52 Effect.scoped(
53 Effect.gen(function* () {
54 const cwd = yield* checkpointWorkspace(
55 `steering-completion-${timing.replaceAll(" ", "-")}`,
56 );
57 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
58 const started: ProviderAdapterV2TurnInput[] = [];
59 const steerEntered = yield* Deferred.make<void>();
60 const rejectSteer = yield* Deferred.make<void>();
61 let steerCalls = 0;
62 const capabilities = {
63 ...CodexProviderCapabilitiesV2,
64 turns: {
65 ...CodexProviderCapabilitiesV2.turns,
66 supportsActiveSteering: timing !== "without native steering",
67 },
68 };
69 const adapter: ProviderAdapterV2Shape = {
70 instanceId,
71 driver,
72 getCapabilities: () => Effect.succeed(capabilities),
73 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
74 openSession: (input) =>
75 Effect.gen(function* () {
76 const now = yield* DateTime.now;
77 return {
78 instanceId,
79 driver,
80 providerSessionId: input.providerSessionId,
81 providerSession: {
82 id: input.providerSessionId,
83 driver,
84 providerInstanceId: instanceId,
85 status: "ready",
86 cwd,
87 model: modelSelection.model,
88 capabilities,
89 createdAt: now,
90 updatedAt: now,
91 lastError: null,
92 },
93 events: Stream.fromQueue(events),
94 ensureThread: ({ threadId }) =>
95 Effect.succeed({
96 id: ProviderThreadId.make(`provider-thread:${threadId}`),
97 driver,
98 providerInstanceId: instanceId,
99 providerSessionId: input.providerSessionId,
100 appThreadId: threadId,
101 ownerNodeId: null,
102 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
103 nativeConversationHeadRef: null,
104 status: "idle",
105 firstRunOrdinal: null,
106 lastRunOrdinal: null,
107 handoffIds: [],
108 forkedFrom: null,
109 createdAt: now,
110 updatedAt: now,
111 }),
112 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
113 startTurn: (turn) =>
114 Effect.gen(function* () {
115 started.push(turn);
116 yield* Queue.offer(events, {
117 type: "provider_turn.updated",
118 driver,
119 providerTurn: {
120 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
121 providerThreadId: turn.providerThread.id,
122 nodeId: turn.rootNodeId,
123 runAttemptId: turn.attemptId,
124 nativeTurnRef: {
125 driver,
126 nativeId: `native:${turn.attemptId}`,
127 strength: "strong",
128 },
129 ordinal: turn.providerTurnOrdinal,
130 status: "running",
131 startedAt: now,
132 completedAt: null,
133 },
134 });
135 }),
136 steerTurn: (turn) =>
137 Effect.gen(function* () {
138 steerCalls += 1;
139 if (timing === "after delivery") return;
140 yield* Deferred.succeed(steerEntered, undefined);
141 yield* Deferred.await(rejectSteer);
142 return yield* new ProviderAdapterSteerRunError({
143 driver,
144 providerThreadId: turn.providerThread.id,
145 providerTurnId: turn.providerTurnId,
146 cause: "turn already completed",
147 });
148 }),
149 interruptTurn: () => Effect.void,
150 respondToRuntimeRequest: () => Effect.void,
151 readThreadSnapshot: () => Effect.die("unused"),
152 rollbackThread: () => Effect.die("unused"),
153 forkThread: () => Effect.die("unused"),
154 };
155 }),
156 };
157 yield* Effect.gen(function* () {
158 const orchestrator = yield* Orchestrator.OrchestratorV2;
159 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
160 const threadId = ThreadId.make("thread:steering-completion");
161 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
162 orchestrator.streamDomainEvents.pipe(
163 Stream.filter(predicate),
164 Stream.take(1),
165 Stream.runDrain,
166 Effect.forkScoped,
167 );
168 yield* orchestrator.dispatch({
169 type: "thread.create",
170 commandId: CommandId.make("create"),
171 threadId,
172 projectId: ProjectId.make("project:steering-completion"),
173 title: "Steering race",
174 modelSelection,
175 runtimeMode: "full-access",
176 interactionMode: "default",
177 branch: null,
178 worktreePath: cwd,
179 createdBy: "user",
180 creationSource: "web",
181 });
182 yield* orchestrator.dispatch({
183 type: "message.dispatch",
184 commandId: CommandId.make("first"),
185 threadId,
186 messageId: MessageId.make("message:first"),
187 text: "first",
188 attachments: [],
189 dispatchMode: { type: "start_immediately" },
190 createdBy: "user",
191 creationSource: "web",
192 });
193 const running = yield* watch(
194 (event) =>
195 event.type === "provider-turn.updated" && event.payload.status === "running",
196 );
197 yield* worker.drain();
198 yield* Fiber.join(running);
199 const first = started[0]!;
200 const messageId = MessageId.make("message:steering");
201 const taskId = NodeId.make("task:mailbox");
202 if (mailbox) {
203 const sink = yield* EventSink.EventSinkV2;
204 const current = yield* orchestrator.getThreadProjection(threadId);
205 const parentRun = current.runs.find((run) => run.id === first.runId)!;
206 const now = yield* DateTime.now;
207 yield* sink.write({
208 events: [
209 {
210 id: EventId.make("mailbox:cohort"),
211 type: "run.updated",
212 threadId,
213 runId: first.runId,
214 occurredAt: now,
215 payload: {
216 ...parentRun,
217 delegatedCompletion: {
218 disposition: "open",
219 nextGeneration: 2,
220 delivery: { generation: 1, messageId, taskIds: [taskId] },
221 },
222 },
223 },
224 {
225 id: EventId.make("mailbox:task"),
226 type: "subagent.updated",
227 threadId,
228 runId: first.runId,
229 nodeId: taskId,
230 occurredAt: now,
231 payload: {
232 id: taskId,
233 threadId,
234 runId: first.runId,
235 parentNodeId: first.rootNodeId,
236 origin: "app_owned",
237 createdBy: "agent",
238 driver,
239 providerInstanceId: instanceId,
240 providerThreadId: null,
241 childThreadId: null,
242 nativeTaskRef: null,
243 prompt: "Do background work",
244 title: "Background test",
245 model: null,
246 completionWake: timing === "settled only" ? "settled_only" : "always",
247 completionDelivery: { state: "claimed", observedByRunId: null },
248 status: "completed",
249 result: "done",
250 startedAt: now,
251 completedAt: now,
252 updatedAt: now,
253 },
254 },
255 ],
256 });
257 }
258 const dispatchSteer = orchestrator.dispatch({
259 type: "message.dispatch",
260 commandId: CommandId.make("steer"),
261 threadId,
262 messageId,
263 text: "fix the popover",
264 attachments: [
265 {
266 type: "image",
267 id: "steering-screenshot",
268 name: "image.png",
269 mimeType: "image/png",
270 sizeBytes: 10,
271 },
272 ],
273 dispatchMode: mailbox
274 ? { type: "queue_after_active" }
275 : { type: "steer_active", targetRunId: first.runId },
276 createdBy: mailbox ? "agent" : "user",
277 creationSource: mailbox ? "server" : "web",
278 ...(mailbox
279 ? {
280 delegatedCompletion: {
281 parentRunId: first.runId,
282 generation: 1,
283 taskIds: [taskId],
284 },
285 }
286 : {}),
287 });
288 if (timing !== "before dispatch") yield* dispatchSteer;
289 if (timing === "after delivery") yield* worker.drain();
290 const delivery =
291 timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
292 if (delivery !== null) yield* Deferred.await(steerEntered);
293 const completed = yield* watch(
294 (event) =>
295 event.type === "run.updated" &&
296 event.payload.id === first.runId &&
297 event.payload.status === "waiting",
298 );
299 const projection = yield* orchestrator.getThreadProjection(threadId);
300 const turn = projection.providerTurns[0]!;
301 yield* Queue.offer(events, {
302 type: "provider_turn.updated",
303 driver,
304 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
305 });
306 yield* Queue.offer(events, {
307 type: "turn.terminal",
308 driver,
309 providerThreadId: turn.providerThreadId,
310 providerTurnId: turn.id,
311 runOrdinal: first.runOrdinal,
312 status: "completed",
313 failure: null,
314 threadDisposition: "reusable",
315 });
316 yield* Fiber.join(completed);
317 if (delivery !== null) {
318 yield* Deferred.succeed(rejectSteer, undefined);
319 yield* Fiber.join(delivery);
320 }
321 if (timing === "before dispatch") yield* dispatchSteer;
322 yield* worker.drain();
323 yield* orchestrator.resumeQueuedRuns;
324 yield* worker.drain();
325 if (timing === "after delivery") {
326 assert.equal(steerCalls, 1);
327 assert.equal(started.length, 1);
328 if (mailbox) {
329 const delivered = yield* orchestrator.getThreadProjection(threadId);
330 assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
331 assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
332 assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
333 assert.equal(
334 delivered.turnItems.filter((item) => item.type === "notification").length,
335 1,
336 );
337 yield* orchestrator.dispatch({
338 type: "notification.delivery.accept",
339 commandId: CommandId.make("duplicate-acceptance"),
340 threadId,
341 messageId,
342 });
343 yield* worker.drain();
344 assert.equal(steerCalls, 1);
345 yield* orchestrator.dispatch({
346 type: "delegated_task.completion-delivery.acknowledge",
347 commandId: CommandId.make("read-result"),
348 parentThreadId: threadId,
349 taskId,
350 observedByRunId: first.runId,
351 });
352 const acknowledged = yield* orchestrator.getThreadProjection(threadId);
353 assert.equal(
354 acknowledged.subagents[0]?.completionDelivery?.state,
355 "acknowledged",
356 );
357 }
358 return;
359 }
360 assert.equal(started.length, 2);
361 assert.equal(started[1]?.message.messageId, messageId);
362 if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
363 else assert.equal(started[1]?.message.text, "fix the popover");
364 assert.deepEqual(started[1]?.message.attachments, [
365 {
366 type: "image",
367 id: "steering-screenshot",
368 name: "image.png",
369 mimeType: "image/png",
370 sizeBytes: 10,
371 },
372 ]);
373 assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
374 const final = yield* orchestrator.getThreadProjection(threadId);
375 assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
376 assert.equal(
377 final.messages.find((message) => message.id === messageId)?.runId,
378 started[1]?.runId,
379 );
380 assert.equal(
381 final.turnItems.filter((item) =>
382 mailbox
383 ? item.type === "notification"
384 : item.type === "user_message" && item.messageId === messageId,
385 ).length,
386 1,
387 );
388 yield* worker.drain();
389 assert.equal(started.length, 2);
390 }).pipe(
391 Effect.provide(
392 makeOrchestratorV2ReplayLayerWithRegistry(
393 { name: `steering-completion-${timing}` },
394 ProviderAdapterRegistry.makeSingleLayer(adapter),
395 { runEffectWorker: false },
396 ),
397 ),
398 );
399 }),
400 ),
401 );
402 }
403}
404
405// Claude steers live but cannot interrupt-and-restart. A composer whose model
406// options differ from the running run (an explicit `fastMode: false`) must still
407// steer, keeping the new selection for the next turn.
408it.effect("steers a changed turn-scoped selection into a provider that cannot restart", () =>
409 Effect.scoped(
410 Effect.gen(function* () {
411 const cwd = yield* checkpointWorkspace("steering-selection-change");
412 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
413 const started: ProviderAdapterV2TurnInput[] = [];
414 const steered: string[] = [];
415 const capabilities = {
416 ...CodexProviderCapabilitiesV2,
417 turns: {
418 ...CodexProviderCapabilitiesV2.turns,
419 supportsActiveSteering: true,
420 supportsSteeringByInterruptRestart: false,
421 },
422 };
423 const runSelection = {
424 instanceId,
425 model: "test-model",
426 options: [{ id: "effort", value: "xhigh" }],
427 };
428 const composerSelection = {
429 ...runSelection,
430 options: [...runSelection.options, { id: "fastMode", value: false }],
431 };
432 const adapter: ProviderAdapterV2Shape = {
433 instanceId,
434 driver,
435 getCapabilities: () => Effect.succeed(capabilities),
436 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
437 openSession: (input) =>
438 Effect.gen(function* () {
439 const now = yield* DateTime.now;
440 return {
441 instanceId,
442 driver,
443 providerSessionId: input.providerSessionId,
444 providerSession: {
445 id: input.providerSessionId,
446 driver,
447 providerInstanceId: instanceId,
448 status: "ready",
449 cwd,
450 model: runSelection.model,
451 capabilities,
452 createdAt: now,
453 updatedAt: now,
454 lastError: null,
455 },
456 events: Stream.fromQueue(events),
457 ensureThread: ({ threadId }) =>
458 Effect.succeed({
459 id: ProviderThreadId.make(`provider-thread:${threadId}`),
460 driver,
461 providerInstanceId: instanceId,
462 providerSessionId: input.providerSessionId,
463 appThreadId: threadId,
464 ownerNodeId: null,
465 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
466 nativeConversationHeadRef: null,
467 status: "idle",
468 firstRunOrdinal: null,
469 lastRunOrdinal: null,
470 handoffIds: [],
471 forkedFrom: null,
472 createdAt: now,
473 updatedAt: now,
474 }),
475 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
476 startTurn: (turn) =>
477 Effect.gen(function* () {
478 started.push(turn);
479 yield* Queue.offer(events, {
480 type: "provider_turn.updated",
481 driver,
482 providerTurn: {
483 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
484 providerThreadId: turn.providerThread.id,
485 nodeId: turn.rootNodeId,
486 runAttemptId: turn.attemptId,
487 nativeTurnRef: {
488 driver,
489 nativeId: `native:${turn.attemptId}`,
490 strength: "strong",
491 },
492 ordinal: turn.providerTurnOrdinal,
493 status: "running",
494 startedAt: now,
495 completedAt: null,
496 },
497 });
498 }),
499 steerTurn: (turn) =>
500 Effect.sync(() => {
501 steered.push(turn.message.text);
502 }),
503 interruptTurn: () => Effect.void,
504 respondToRuntimeRequest: () => Effect.void,
505 readThreadSnapshot: () => Effect.die("unused"),
506 rollbackThread: () => Effect.die("unused"),
507 forkThread: () => Effect.die("unused"),
508 };
509 }),
510 };
511 yield* Effect.gen(function* () {
512 const orchestrator = yield* Orchestrator.OrchestratorV2;
513 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
514 const threadId = ThreadId.make("thread:steering-selection-change");
515 yield* orchestrator.dispatch({
516 type: "thread.create",
517 commandId: CommandId.make("create"),
518 threadId,
519 projectId: ProjectId.make("project:steering-selection-change"),
520 title: "Steer with changed options",
521 modelSelection: runSelection,
522 runtimeMode: "full-access",
523 interactionMode: "default",
524 branch: null,
525 worktreePath: cwd,
526 createdBy: "user",
527 creationSource: "web",
528 });
529 const running = yield* orchestrator.streamDomainEvents.pipe(
530 Stream.filter(
531 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
532 ),
533 Stream.take(1),
534 Stream.runDrain,
535 Effect.forkScoped,
536 );
537 yield* orchestrator.dispatch({
538 type: "message.dispatch",
539 commandId: CommandId.make("first"),
540 threadId,
541 messageId: MessageId.make("message:first"),
542 text: "first",
543 attachments: [],
544 modelSelection: runSelection,
545 dispatchMode: { type: "start_immediately" },
546 createdBy: "user",
547 creationSource: "web",
548 });
549 yield* worker.drain();
550 yield* Fiber.join(running);
551
552 yield* orchestrator.dispatch({
553 type: "message.dispatch",
554 commandId: CommandId.make("steer"),
555 threadId,
556 messageId: MessageId.make("message:steer"),
557 text: "use the File component",
558 attachments: [],
559 modelSelection: composerSelection,
560 dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
561 createdBy: "user",
562 creationSource: "web",
563 });
564 yield* worker.drain();
565
566 const projection = yield* orchestrator.getThreadProjection(threadId);
567 assert.deepEqual(steered, ["use the File component"]);
568 assert.equal(started.length, 1);
569 assert.lengthOf(projection.attempts, 1);
570 assert.equal(projection.runs[0]?.status, "running");
571 assert.deepEqual(projection.runs[0]?.modelSelection, runSelection);
572 assert.deepEqual(projection.thread.modelSelection, composerSelection);
573 }).pipe(
574 Effect.provide(
575 makeOrchestratorV2ReplayLayerWithRegistry(
576 { name: "steering-selection-change" },
577 ProviderAdapterRegistry.makeSingleLayer(adapter),
578 { runEffectWorker: false },
579 ),
580 ),
581 );
582 }),
583 ),
584);