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 TurnItemId,
14 type ModelSelection,
15 type OrchestrationV2DomainEvent,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Fiber from "effect/Fiber";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
24import * as EffectWorker from "./EffectWorker.ts";
25import * as EventSink from "./EventSink.ts";
26import * as Orchestrator from "./Orchestrator.ts";
27import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
28import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
29import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
30import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
31
32const driver = ProviderDriverKind.make("codex");
33const instanceId = ProviderInstanceId.make("codex");
34const modelSelection = { instanceId, model: "test-model" };
35
36it.effect.each(
37 (
38 [
39 [false, "during delivery"],
40 [false, "before dispatch"],
41 [true, "after delivery"],
42 [true, "without native steering"],
43 [true, "with interrupting native steering"],
44 [true, "settled only"],
45 ] as const
46 ).map(([mailbox, timing]) => ({
47 mailbox,
48 timing,
49 label: mailbox ? "mailbox notification" : "steering",
50 })),
51)("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
52 Effect.scoped(
53 Effect.gen(function* () {
54 const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
55 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
56 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
57 const steerEntered = yield* Deferred.make<void>();
58 const rejectSteer = yield* Deferred.make<void>();
59 let steerCalls = 0;
60 const capabilities = {
61 ...CodexProviderCapabilitiesV2,
62 turns: {
63 ...CodexProviderCapabilitiesV2.turns,
64 supportsActiveSteering: timing !== "without native steering",
65 activeSteeringInterruptsTools: timing === "with interrupting native steering",
66 },
67 };
68 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
69 instanceId,
70 driver,
71 getCapabilities: () => Effect.succeed(capabilities),
72 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
73 openSession: (input) =>
74 Effect.gen(function* () {
75 const now = yield* DateTime.now;
76 return {
77 instanceId,
78 driver,
79 providerSessionId: input.providerSessionId,
80 providerSession: {
81 id: input.providerSessionId,
82 driver,
83 providerInstanceId: instanceId,
84 status: "ready",
85 cwd,
86 model: modelSelection.model,
87 capabilities,
88 createdAt: now,
89 updatedAt: now,
90 lastError: null,
91 },
92 events: Stream.fromQueue(events),
93 ensureThread: ({ threadId }) =>
94 Effect.succeed({
95 id: ProviderThreadId.make(`provider-thread:${threadId}`),
96 driver,
97 providerInstanceId: instanceId,
98 providerSessionId: input.providerSessionId,
99 appThreadId: threadId,
100 ownerNodeId: null,
101 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
102 nativeConversationHeadRef: null,
103 status: "idle",
104 firstRunOrdinal: null,
105 lastRunOrdinal: null,
106 handoffIds: [],
107 forkedFrom: null,
108 createdAt: now,
109 updatedAt: now,
110 }),
111 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
112 startTurn: (turn) =>
113 Effect.gen(function* () {
114 started.push(turn);
115 yield* Queue.offer(events, {
116 type: "provider_turn.updated",
117 driver,
118 providerTurn: {
119 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
120 providerThreadId: turn.providerThread.id,
121 nodeId: turn.rootNodeId,
122 runAttemptId: turn.attemptId,
123 nativeTurnRef: {
124 driver,
125 nativeId: `native:${turn.attemptId}`,
126 strength: "strong",
127 },
128 ordinal: turn.providerTurnOrdinal,
129 status: "running",
130 startedAt: now,
131 completedAt: null,
132 },
133 });
134 }),
135 steerTurn: (turn) =>
136 Effect.gen(function* () {
137 steerCalls += 1;
138 if (timing === "after delivery") return;
139 yield* Deferred.succeed(steerEntered, undefined);
140 yield* Deferred.await(rejectSteer);
141 return yield* new ProviderAdapter.ProviderAdapterSteerRunError({
142 driver,
143 providerThreadId: turn.providerThread.id,
144 providerTurnId: turn.providerTurnId,
145 cause: "turn already completed",
146 });
147 }),
148 interruptTurn: () => Effect.void,
149 respondToRuntimeRequest: () => Effect.void,
150 readThreadSnapshot: () => Effect.die("unused"),
151 rollbackThread: () => Effect.die("unused"),
152 forkThread: () => Effect.die("unused"),
153 };
154 }),
155 };
156 yield* Effect.gen(function* () {
157 const orchestrator = yield* Orchestrator.OrchestratorV2;
158 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
159 const threadId = ThreadId.make("thread:steering-completion");
160 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
161 orchestrator.streamDomainEvents.pipe(
162 Stream.filter(predicate),
163 Stream.take(1),
164 Stream.runDrain,
165 Effect.forkScoped,
166 );
167 yield* orchestrator.dispatch({
168 type: "thread.create",
169 commandId: CommandId.make("create"),
170 threadId,
171 projectId: ProjectId.make("project:steering-completion"),
172 title: "Steering race",
173 modelSelection,
174 runtimeMode: "full-access",
175 interactionMode: "default",
176 branch: null,
177 worktreePath: cwd,
178 createdBy: "user",
179 creationSource: "web",
180 });
181 yield* orchestrator.dispatch({
182 type: "message.dispatch",
183 commandId: CommandId.make("first"),
184 threadId,
185 messageId: MessageId.make("message:first"),
186 text: "first",
187 attachments: [],
188 dispatchMode: { type: "start_immediately" },
189 createdBy: "user",
190 creationSource: "web",
191 });
192 const running = yield* watch(
193 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
194 );
195 yield* worker.drain();
196 yield* Fiber.join(running);
197 const first = started[0]!;
198 const messageId = MessageId.make("message:steering");
199 const taskId = NodeId.make("task:mailbox");
200 if (mailbox) {
201 const sink = yield* EventSink.EventSinkV2;
202 const current = yield* orchestrator.getThreadProjection(threadId);
203 const parentRun = current.runs.find((run) => run.id === first.runId)!;
204 const now = yield* DateTime.now;
205 yield* sink.write({
206 events: [
207 {
208 id: EventId.make("mailbox:cohort"),
209 type: "run.updated",
210 threadId,
211 runId: first.runId,
212 occurredAt: now,
213 payload: {
214 ...parentRun,
215 delegatedCompletion: {
216 disposition: "open",
217 nextGeneration: 2,
218 delivery: { generation: 1, messageId, taskIds: [taskId] },
219 },
220 },
221 },
222 {
223 id: EventId.make("mailbox:task"),
224 type: "subagent.updated",
225 threadId,
226 runId: first.runId,
227 nodeId: taskId,
228 occurredAt: now,
229 payload: {
230 id: taskId,
231 threadId,
232 runId: first.runId,
233 parentNodeId: first.rootNodeId,
234 origin: "app_owned",
235 createdBy: "agent",
236 driver,
237 providerInstanceId: instanceId,
238 providerThreadId: null,
239 childThreadId: null,
240 nativeTaskRef: null,
241 prompt: "Do background work",
242 title: "Background test",
243 model: null,
244 completionWake: timing === "settled only" ? "settled_only" : "always",
245 completionDelivery: { state: "claimed", observedByRunId: null },
246 status: "completed",
247 result: "done",
248 startedAt: now,
249 completedAt: now,
250 updatedAt: now,
251 },
252 },
253 ],
254 });
255 }
256 const dispatchSteer = orchestrator.dispatch({
257 type: "message.dispatch",
258 commandId: CommandId.make("steer"),
259 threadId,
260 messageId,
261 text: "fix the popover",
262 attachments: [
263 {
264 type: "image",
265 id: "steering-screenshot",
266 name: "image.png",
267 mimeType: "image/png",
268 sizeBytes: 10,
269 },
270 ],
271 dispatchMode: mailbox
272 ? { type: "queue_after_active" }
273 : { type: "steer_active", targetRunId: first.runId },
274 createdBy: mailbox ? "agent" : "user",
275 creationSource: mailbox ? "server" : "web",
276 ...(mailbox
277 ? {
278 delegatedCompletion: {
279 parentRunId: first.runId,
280 generation: 1,
281 taskIds: [taskId],
282 },
283 }
284 : {}),
285 });
286 if (timing !== "before dispatch") yield* dispatchSteer;
287 if (timing === "after delivery") yield* worker.drain();
288 const delivery =
289 timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
290 if (delivery !== null) yield* Deferred.await(steerEntered);
291 const completed = yield* watch(
292 (event) =>
293 event.type === "run.updated" &&
294 event.payload.id === first.runId &&
295 event.payload.status === "waiting",
296 );
297 const projection = yield* orchestrator.getThreadProjection(threadId);
298 const turn = projection.providerTurns[0]!;
299 yield* Queue.offer(events, {
300 type: "provider_turn.updated",
301 driver,
302 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
303 });
304 yield* Queue.offer(events, {
305 type: "turn.terminal",
306 driver,
307 providerThreadId: turn.providerThreadId,
308 providerTurnId: turn.id,
309 runOrdinal: first.runOrdinal,
310 status: "completed",
311 failure: null,
312 threadDisposition: "reusable",
313 });
314 yield* Fiber.join(completed);
315 if (delivery !== null) {
316 yield* Deferred.succeed(rejectSteer, undefined);
317 yield* Fiber.join(delivery);
318 }
319 if (timing === "before dispatch") yield* dispatchSteer;
320 yield* worker.drain();
321 yield* orchestrator.resumeQueuedRuns;
322 yield* worker.drain();
323 if (timing === "after delivery") {
324 assert.equal(steerCalls, 1);
325 assert.equal(started.length, 1);
326 if (mailbox) {
327 const delivered = yield* orchestrator.getThreadProjection(threadId);
328 assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
329 assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
330 assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
331 assert.equal(
332 delivered.turnItems.filter((item) => item.type === "notification").length,
333 1,
334 );
335 yield* orchestrator.dispatch({
336 type: "notification.delivery.accept",
337 commandId: CommandId.make("duplicate-acceptance"),
338 threadId,
339 messageId,
340 });
341 yield* worker.drain();
342 assert.equal(steerCalls, 1);
343 yield* orchestrator.dispatch({
344 type: "delegated_task.completion-delivery.acknowledge",
345 commandId: CommandId.make("read-result"),
346 parentThreadId: threadId,
347 taskId,
348 observedByRunId: first.runId,
349 });
350 const acknowledged = yield* orchestrator.getThreadProjection(threadId);
351 assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
352 }
353 return;
354 }
355 assert.equal(started.length, 2);
356 assert.equal(started[1]?.message.messageId, messageId);
357 if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
358 else assert.equal(started[1]?.message.text, "fix the popover");
359 assert.deepEqual(started[1]?.message.attachments, [
360 {
361 type: "image",
362 id: "steering-screenshot",
363 name: "image.png",
364 mimeType: "image/png",
365 sizeBytes: 10,
366 },
367 ]);
368 assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
369 const final = yield* orchestrator.getThreadProjection(threadId);
370 assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
371 assert.equal(
372 final.messages.find((message) => message.id === messageId)?.runId,
373 started[1]?.runId,
374 );
375 assert.equal(
376 final.turnItems.filter((item) =>
377 mailbox
378 ? item.type === "notification"
379 : item.type === "user_message" && item.messageId === messageId,
380 ).length,
381 1,
382 );
383 yield* worker.drain();
384 assert.equal(started.length, 2);
385 }).pipe(
386 Effect.provide(
387 ProviderReplayHarness.layerWithRegistry(
388 { name: `steering-completion-${timing}` },
389 ProviderAdapterRegistry.layerSingle(adapter),
390 { runEffectWorker: false },
391 ),
392 ),
393 );
394 }),
395 ),
396);
397
398const runSelection = {
399 instanceId,
400 model: "test-model",
401 options: [{ id: "effort", value: "xhigh" }],
402};
403const composerSelection = {
404 ...runSelection,
405 options: [...runSelection.options, { id: "fastMode", value: false }],
406};
407
408const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (
409 name: string,
410 canRestart = false,
411) {
412 const cwd = yield* checkpointWorkspace(name);
413 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
414 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
415 const steered: string[] = [];
416 const capabilities = {
417 ...CodexProviderCapabilitiesV2,
418 turns: {
419 ...CodexProviderCapabilitiesV2.turns,
420 supportsActiveSteering: true,
421 supportsSteeringByInterruptRestart: canRestart,
422 },
423 };
424 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
425 instanceId,
426 driver,
427 getCapabilities: () => Effect.succeed(capabilities),
428 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
429 openSession: (input) =>
430 Effect.gen(function* () {
431 const now = yield* DateTime.now;
432 return {
433 instanceId,
434 driver,
435 providerSessionId: input.providerSessionId,
436 providerSession: {
437 id: input.providerSessionId,
438 driver,
439 providerInstanceId: instanceId,
440 status: "ready",
441 cwd,
442 model: runSelection.model,
443 capabilities,
444 createdAt: now,
445 updatedAt: now,
446 lastError: null,
447 },
448 events: Stream.fromQueue(events),
449 ensureThread: ({ threadId }) =>
450 Effect.succeed({
451 id: ProviderThreadId.make(`provider-thread:${threadId}`),
452 driver,
453 providerInstanceId: instanceId,
454 providerSessionId: input.providerSessionId,
455 appThreadId: threadId,
456 ownerNodeId: null,
457 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
458 nativeConversationHeadRef: null,
459 status: "idle",
460 firstRunOrdinal: null,
461 lastRunOrdinal: null,
462 handoffIds: [],
463 forkedFrom: null,
464 createdAt: now,
465 updatedAt: now,
466 }),
467 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
468 startTurn: (turn) =>
469 Effect.gen(function* () {
470 started.push(turn);
471 yield* Queue.offer(events, {
472 type: "provider_turn.updated",
473 driver,
474 providerTurn: {
475 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
476 providerThreadId: turn.providerThread.id,
477 nodeId: turn.rootNodeId,
478 runAttemptId: turn.attemptId,
479 nativeTurnRef: {
480 driver,
481 nativeId: `native:${turn.attemptId}`,
482 strength: "strong",
483 },
484 ordinal: turn.providerTurnOrdinal,
485 status: "running",
486 startedAt: now,
487 completedAt: null,
488 },
489 });
490 }),
491 steerTurn: (turn) =>
492 Effect.sync(() => {
493 steered.push(turn.message.text);
494 }),
495 interruptTurn: () => Effect.void,
496 respondToRuntimeRequest: () => Effect.void,
497 readThreadSnapshot: () => Effect.die("unused"),
498 rollbackThread: () => Effect.die("unused"),
499 forkThread: () => Effect.die("unused"),
500 };
501 }),
502 };
503 const layer = ProviderReplayHarness.layerWithRegistry(
504 { name },
505 ProviderAdapterRegistry.layerSingle(adapter),
506 { runEffectWorker: false },
507 );
508 const startFirstTurn = Effect.gen(function* () {
509 const orchestrator = yield* Orchestrator.OrchestratorV2;
510 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
511 const threadId = ThreadId.make(`thread:${name}`);
512 yield* orchestrator.dispatch({
513 type: "thread.create",
514 commandId: CommandId.make("create"),
515 threadId,
516 projectId: ProjectId.make(`project:${name}`),
517 title: "Steer with changed options",
518 modelSelection: runSelection,
519 runtimeMode: "full-access",
520 interactionMode: "default",
521 branch: null,
522 worktreePath: cwd,
523 createdBy: "user",
524 creationSource: "web",
525 });
526 const running = yield* orchestrator.streamDomainEvents.pipe(
527 Stream.filter(
528 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
529 ),
530 Stream.take(1),
531 Stream.runDrain,
532 Effect.forkScoped,
533 );
534 yield* orchestrator.dispatch({
535 type: "message.dispatch",
536 commandId: CommandId.make("first"),
537 threadId,
538 messageId: MessageId.make("message:first"),
539 text: "first",
540 attachments: [],
541 modelSelection: runSelection,
542 dispatchMode: { type: "start_immediately" },
543 createdBy: "user",
544 creationSource: "web",
545 });
546 yield* worker.drain();
547 yield* Fiber.join(running);
548 return threadId;
549 });
550 return { events, started, steered, layer, startFirstTurn };
551});
552
553it.effect("sends a selected held message once and preserves the remaining queue order", () =>
554 Effect.scoped(
555 Effect.gen(function* () {
556 const { started, steered, layer, startFirstTurn } =
557 yield* nextTurnSelectionHarness("send-held-message");
558 yield* Effect.gen(function* () {
559 const orchestrator = yield* Orchestrator.OrchestratorV2;
560 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
561 const threadId = yield* startFirstTurn;
562 yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
563 orchestrator.dispatch({
564 type: "message.dispatch",
565 commandId: CommandId.make(text),
566 threadId,
567 messageId: MessageId.make(`message:${text}`),
568 text,
569 attachments: [],
570 modelSelection: runSelection,
571 dispatchMode: { type: "queue_after_active" },
572 createdBy: "user",
573 creationSource: "web",
574 }),
575 );
576 const before = yield* orchestrator.getThreadProjection(threadId);
577 const selected = before.runs.find(
578 (run) => run.userMessageId === MessageId.make("message:selected"),
579 )!;
580 const sink = yield* EventSink.EventSinkV2;
581 const now = yield* DateTime.now;
582 // Restart recovery cancels the active run and holds every queued message.
583 yield* sink.write({
584 events: [
585 ...before.runs.map((run) => ({
586 id: EventId.make(`restart:${run.id}`),
587 type: "run.updated" as const,
588 threadId,
589 runId: run.id,
590 occurredAt: now,
591 payload:
592 run.status === "queued"
593 ? { ...run, queueHeld: true }
594 : { ...run, status: "cancelled" as const, completedAt: now },
595 })),
596 ...before.providerTurns.map((turn) => ({
597 id: EventId.make(`restart:${turn.id}`),
598 type: "provider-turn.updated" as const,
599 threadId,
600 occurredAt: now,
601 payload: { ...turn, status: "cancelled" as const, completedAt: now },
602 })),
603 ],
604 });
605 const command = {
606 type: "queued-run.start" as const,
607 commandId: CommandId.make("send-selected"),
608 threadId,
609 runId: selected.id,
610 };
611 yield* orchestrator.dispatch(command);
612 yield* worker.drain();
613 yield* orchestrator.dispatch(command);
614 yield* worker.drain();
615 const after = yield* orchestrator.getThreadProjection(threadId);
616 assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
617 assert.deepEqual(
618 started.map((input) => input.message.text),
619 ["first", "selected"],
620 );
621 assert.equal(started[1]?.runId, selected.id);
622 assert.equal(started[1]?.message.messageId, selected.userMessageId);
623 assert.deepEqual(started[1]?.modelSelection, runSelection);
624 assert.deepEqual(steered, []);
625 assert.lengthOf(
626 after.messages.filter((message) => message.id === selected.userMessageId),
627 1,
628 );
629 assert.deepEqual(
630 after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
631 [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
632 );
633 assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
634 const duplicate = yield* orchestrator
635 .dispatch({
636 ...command,
637 commandId: CommandId.make("send-selected-again"),
638 })
639 .pipe(Effect.flip);
640 assert.equal(duplicate._tag, "OrchestratorDispatchError");
641 }).pipe(Effect.provide(layer));
642 }),
643 ),
644);
645
646it.effect("keeps a message queued when send now races with a running turn", () =>
647 Effect.scoped(
648 Effect.gen(function* () {
649 const { started, layer, startFirstTurn } =
650 yield* nextTurnSelectionHarness("send-queued-race");
651 yield* Effect.gen(function* () {
652 const orchestrator = yield* Orchestrator.OrchestratorV2;
653 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
654 const threadId = yield* startFirstTurn;
655 yield* orchestrator.dispatch({
656 type: "message.dispatch",
657 commandId: CommandId.make("queue"),
658 threadId,
659 messageId: MessageId.make("message:queued"),
660 text: "queued",
661 attachments: [],
662 dispatchMode: { type: "queue_after_active" },
663 createdBy: "user",
664 creationSource: "web",
665 });
666 const before = yield* orchestrator.getThreadProjection(threadId);
667 const queued = before.runs.find((run) => run.status === "queued")!;
668 const error = yield* orchestrator
669 .dispatch({
670 type: "queued-run.start",
671 commandId: CommandId.make("send-now"),
672 threadId,
673 runId: queued.id,
674 })
675 .pipe(Effect.flip);
676 yield* worker.drain();
677 assert.equal(error._tag, "OrchestratorDispatchError");
678 assert.equal(started.length, 1);
679 const after = yield* orchestrator.getThreadProjection(threadId);
680 assert.deepEqual(after.runs, before.runs);
681 }).pipe(Effect.provide(layer));
682 }),
683 ),
684);
685
686// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
687it.effect(
688 "steers a changed turn-scoped selection into a running turn the provider could restart",
689 () =>
690 Effect.scoped(
691 Effect.gen(function* () {
692 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
693 "steering-selection-change",
694 true,
695 );
696 yield* Effect.gen(function* () {
697 const orchestrator = yield* Orchestrator.OrchestratorV2;
698 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
699 const threadId = yield* startFirstTurn;
700 const steer = (id: string, selection: ModelSelection) =>
701 orchestrator
702 .dispatch({
703 type: "message.dispatch",
704 commandId: CommandId.make(id),
705 threadId,
706 messageId: MessageId.make(`message:${id}`),
707 text: id,
708 attachments: [],
709 modelSelection: selection,
710 dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
711 createdBy: "user",
712 creationSource: "web",
713 })
714 .pipe(Effect.andThen(worker.drain()));
715
716 yield* steer("steer-changed", composerSelection);
717 const changed = yield* orchestrator.getThreadProjection(threadId);
718 assert.deepEqual(steered, ["steer-changed"]);
719 assert.equal(started.length, 1);
720 assert.lengthOf(changed.attempts, 1);
721 assert.equal(changed.runs[0]?.status, "running");
722 assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
723 assert.deepEqual(changed.thread.modelSelection, composerSelection);
724
725 yield* steer("steer-reverted", runSelection);
726 const reverted = yield* orchestrator.getThreadProjection(threadId);
727 assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
728 assert.lengthOf(reverted.attempts, 1);
729 assert.deepEqual(reverted.thread.modelSelection, runSelection);
730
731 const otherSelection = {
732 instanceId: ProviderInstanceId.make("codex-work"),
733 model: "other",
734 };
735 const sink = yield* EventSink.EventSinkV2;
736 yield* sink.write({
737 events: [
738 {
739 id: EventId.make("switched-away"),
740 type: "thread.provider-switched",
741 threadId,
742 providerInstanceId: otherSelection.instanceId,
743 occurredAt: yield* DateTime.now,
744 payload: {
745 ...reverted.thread,
746 providerInstanceId: otherSelection.instanceId,
747 modelSelection: otherSelection,
748 },
749 },
750 ],
751 });
752 yield* steer("steer-back", runSelection);
753 const back = yield* orchestrator.getThreadProjection(threadId);
754 assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
755 assert.equal(back.thread.providerInstanceId, instanceId);
756 assert.deepEqual(back.thread.modelSelection, runSelection);
757 }).pipe(Effect.provide(layer));
758 }),
759 ),
760);
761
762it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>
763 Effect.scoped(
764 Effect.gen(function* () {
765 const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
766 "steering-selection-follow-up",
767 );
768 yield* Effect.gen(function* () {
769 const orchestrator = yield* Orchestrator.OrchestratorV2;
770 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
771 const threadId = yield* startFirstTurn;
772 const first = started[0]!;
773 yield* orchestrator.dispatch({
774 type: "message.dispatch",
775 commandId: CommandId.make("steer"),
776 threadId,
777 messageId: MessageId.make("message:steer"),
778 text: "late steer",
779 attachments: [],
780 modelSelection: composerSelection,
781 dispatchMode: { type: "steer_active", targetRunId: first.runId },
782 createdBy: "user",
783 creationSource: "web",
784 });
785 const settled = yield* orchestrator.streamDomainEvents.pipe(
786 Stream.filter(
787 (event) =>
788 event.type === "run.updated" &&
789 event.payload.id === first.runId &&
790 event.payload.status === "waiting",
791 ),
792 Stream.take(1),
793 Stream.runDrain,
794 Effect.forkScoped,
795 );
796 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
797 yield* Queue.offer(events, {
798 type: "provider_turn.updated",
799 driver,
800 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
801 });
802 yield* Queue.offer(events, {
803 type: "turn.terminal",
804 driver,
805 providerThreadId: turn.providerThreadId,
806 providerTurnId: turn.id,
807 runOrdinal: first.runOrdinal,
808 status: "completed",
809 failure: null,
810 threadDisposition: "reusable",
811 });
812 yield* Fiber.join(settled);
813 yield* worker.drain();
814 yield* orchestrator.resumeQueuedRuns;
815 yield* worker.drain();
816
817 const projection = yield* orchestrator.getThreadProjection(threadId);
818 assert.deepEqual(steered, []);
819 assert.equal(started.length, 2);
820 assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
821 assert.deepEqual(started[1]?.modelSelection, composerSelection);
822 assert.deepEqual(projection.thread.modelSelection, composerSelection);
823 }).pipe(Effect.provide(layer));
824 }),
825 ),
826);
827
828// Codex flushes held drafts after the final answer; reserve their pre-steer position before turn end.
829it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
830 Effect.scoped(
831 Effect.gen(function* () {
832 const { events, started, layer, startFirstTurn } =
833 yield* nextTurnSelectionHarness("steering-held-draft");
834 yield* Effect.gen(function* () {
835 const orchestrator = yield* Orchestrator.OrchestratorV2;
836 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
837 const threadId = yield* startFirstTurn;
838 const first = started[0]!;
839 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
840 const now = yield* DateTime.now;
841 const assistantItem = (id: string, text: string, streaming: boolean) =>
842 ({
843 type: "turn_item.updated",
844 driver,
845 turnItem: {
846 id: TurnItemId.make(id),
847 threadId,
848 runId: first.runId,
849 nodeId: first.rootNodeId,
850 providerThreadId: turn.providerThreadId,
851 providerTurnId: turn.id,
852 nativeItemRef: null,
853 parentItemId: null,
854 ordinal: 0,
855 status: streaming ? "running" : "completed",
856 title: null,
857 startedAt: now,
858 completedAt: streaming ? null : now,
859 updatedAt: now,
860 type: "assistant_message",
861 messageId: MessageId.make(`message:${id}`),
862 text,
863 streaming,
864 },
865 }) satisfies ProviderAdapter.ProviderAdapterV2Event;
866 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
867 orchestrator.streamDomainEvents.pipe(
868 Stream.filter(predicate),
869 Stream.take(1),
870 Stream.runDrain,
871 Effect.forkScoped,
872 );
873
874 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
875 const commentaryWritten = yield* watch(
876 (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
877 );
878 yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
879 yield* Fiber.join(commentaryWritten);
880
881 yield* orchestrator.dispatch({
882 type: "message.dispatch",
883 commandId: CommandId.make("steer"),
884 threadId,
885 messageId: MessageId.make("message:steer"),
886 text: "fix the popover",
887 attachments: [],
888 dispatchMode: { type: "steer_active", targetRunId: first.runId },
889 createdBy: "user",
890 creationSource: "web",
891 });
892 yield* worker.drain();
893
894 const settled = yield* watch(
895 (event) =>
896 event.type === "run.updated" &&
897 event.payload.id === first.runId &&
898 event.payload.status === "waiting",
899 );
900 yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
901 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
902 yield* Queue.offer(events, {
903 type: "provider_turn.updated",
904 driver,
905 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
906 });
907 yield* Queue.offer(events, {
908 type: "turn.terminal",
909 driver,
910 providerThreadId: turn.providerThreadId,
911 providerTurnId: turn.id,
912 runOrdinal: first.runOrdinal,
913 status: "completed",
914 failure: null,
915 threadDisposition: "reusable",
916 });
917 yield* Fiber.join(settled);
918 yield* worker.drain();
919
920 const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
921 .toSorted((left, right) => left.ordinal - right.ordinal)
922 .flatMap((item) =>
923 item.type === "user_message"
924 ? [String(item.messageId)]
925 : item.type === "assistant_message"
926 ? [String(item.id)]
927 : [],
928 );
929 assert.deepEqual(items, [
930 "message:first",
931 "draft",
932 "commentary",
933 "message:steer",
934 "answer",
935 ]);
936 }).pipe(Effect.provide(layer));
937 }),
938 ),
939);
940
941it.effect("keeps a queued message queued when promoted into a run that Stop reached", () =>
942 Effect.scoped(
943 Effect.gen(function* () {
944 const { started, steered, layer, startFirstTurn } =
945 yield* nextTurnSelectionHarness("steering-after-stop");
946 yield* Effect.gen(function* () {
947 const orchestrator = yield* Orchestrator.OrchestratorV2;
948 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
949 const threadId = yield* startFirstTurn;
950 const first = started[0]!;
951 yield* orchestrator.dispatch({
952 type: "message.dispatch",
953 commandId: CommandId.make("queued"),
954 threadId,
955 messageId: MessageId.make("message:queued"),
956 text: "queued",
957 attachments: [],
958 modelSelection: runSelection,
959 dispatchMode: { type: "queue_after_active" },
960 createdBy: "user",
961 creationSource: "web",
962 });
963 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
964 (run) => run.status === "queued",
965 )!;
966 // The worker has not delivered the interrupt yet, so the run still reads as running.
967 yield* orchestrator.dispatch({
968 type: "run.interrupt",
969 commandId: CommandId.make("stop"),
970 threadId,
971 runId: first.runId,
972 holdQueue: true,
973 });
974
975 const promoteError = yield* orchestrator
976 .dispatch({
977 type: "queued-message.promote-to-steer",
978 commandId: CommandId.make("promote"),
979 threadId,
980 queuedRunId: queuedRun.id,
981 targetRunId: first.runId,
982 })
983 .pipe(Effect.flip);
984 yield* worker.drain();
985
986 const projection = yield* orchestrator.getThreadProjection(threadId);
987 assert.equal(promoteError._tag, "OrchestratorDispatchError");
988 assert.deepEqual(steered, []);
989 const queued = projection.runs.find((run) => run.id === queuedRun.id);
990 assert.equal(queued?.status, "queued");
991 assert.isTrue(queued?.queueHeld);
992 }).pipe(Effect.provide(layer));
993 }),
994 ),
995);
996
997it.effect("queues a plain send behind the stopped queue and releases its hold", () =>
998 Effect.scoped(
999 Effect.gen(function* () {
1000 const { started, steered, layer, startFirstTurn } =
1001 yield* nextTurnSelectionHarness("plain-send-after-stop");
1002 yield* Effect.gen(function* () {
1003 const orchestrator = yield* Orchestrator.OrchestratorV2;
1004 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1005 const threadId = yield* startFirstTurn;
1006 const send = (id: string, delivery: "queue" | "auto") =>
1007 orchestrator.dispatch({
1008 type: "message.dispatch",
1009 commandId: CommandId.make(id),
1010 threadId,
1011 messageId: MessageId.make(`message:${id}`),
1012 text: id,
1013 attachments: [],
1014 modelSelection: runSelection,
1015 ...(delivery === "queue"
1016 ? { dispatchMode: { type: "queue_after_active" } }
1017 : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
1018 createdBy: "user",
1019 creationSource: "web",
1020 });
1021 yield* send("queued", "queue");
1022 yield* orchestrator.dispatch({
1023 type: "run.interrupt",
1024 commandId: CommandId.make("stop"),
1025 threadId,
1026 runId: started[0]!.runId,
1027 holdQueue: true,
1028 });
1029 // The provider has not stopped yet, so a plain send still resolves to a steer.
1030 yield* send("sent", "auto");
1031 yield* worker.drain();
1032
1033 const projection = yield* orchestrator.getThreadProjection(threadId);
1034 assert.deepEqual(steered, []);
1035 assert.equal(started.length, 1);
1036 const queued = projection.runs
1037 .filter((run) => run.status === "queued")
1038 .sort((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0));
1039 assert.deepEqual(
1040 queued.map(
1041 (run) => projection.messages.find((message) => message.id === run.userMessageId)?.text,
1042 ),
1043 ["queued", "sent"],
1044 );
1045 // The user sent it, so the queue they stopped runs again once the provider stops.
1046 assert.isFalse(queued.some((run) => run.queueHeld === true));
1047 }).pipe(Effect.provide(layer));
1048 }),
1049 ),
1050);