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
553// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
554it.effect(
555 "steers a changed turn-scoped selection into a running turn the provider could restart",
556 () =>
557 Effect.scoped(
558 Effect.gen(function* () {
559 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
560 "steering-selection-change",
561 true,
562 );
563 yield* Effect.gen(function* () {
564 const orchestrator = yield* Orchestrator.OrchestratorV2;
565 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
566 const threadId = yield* startFirstTurn;
567 const steer = (id: string, selection: ModelSelection) =>
568 orchestrator
569 .dispatch({
570 type: "message.dispatch",
571 commandId: CommandId.make(id),
572 threadId,
573 messageId: MessageId.make(`message:${id}`),
574 text: id,
575 attachments: [],
576 modelSelection: selection,
577 dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
578 createdBy: "user",
579 creationSource: "web",
580 })
581 .pipe(Effect.andThen(worker.drain()));
582
583 yield* steer("steer-changed", composerSelection);
584 const changed = yield* orchestrator.getThreadProjection(threadId);
585 assert.deepEqual(steered, ["steer-changed"]);
586 assert.equal(started.length, 1);
587 assert.lengthOf(changed.attempts, 1);
588 assert.equal(changed.runs[0]?.status, "running");
589 assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
590 assert.deepEqual(changed.thread.modelSelection, composerSelection);
591
592 yield* steer("steer-reverted", runSelection);
593 const reverted = yield* orchestrator.getThreadProjection(threadId);
594 assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
595 assert.lengthOf(reverted.attempts, 1);
596 assert.deepEqual(reverted.thread.modelSelection, runSelection);
597
598 const otherSelection = {
599 instanceId: ProviderInstanceId.make("codex-work"),
600 model: "other",
601 };
602 const sink = yield* EventSink.EventSinkV2;
603 yield* sink.write({
604 events: [
605 {
606 id: EventId.make("switched-away"),
607 type: "thread.provider-switched",
608 threadId,
609 providerInstanceId: otherSelection.instanceId,
610 occurredAt: yield* DateTime.now,
611 payload: {
612 ...reverted.thread,
613 providerInstanceId: otherSelection.instanceId,
614 modelSelection: otherSelection,
615 },
616 },
617 ],
618 });
619 yield* steer("steer-back", runSelection);
620 const back = yield* orchestrator.getThreadProjection(threadId);
621 assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
622 assert.equal(back.thread.providerInstanceId, instanceId);
623 assert.deepEqual(back.thread.modelSelection, runSelection);
624 }).pipe(Effect.provide(layer));
625 }),
626 ),
627);
628
629it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>
630 Effect.scoped(
631 Effect.gen(function* () {
632 const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
633 "steering-selection-follow-up",
634 );
635 yield* Effect.gen(function* () {
636 const orchestrator = yield* Orchestrator.OrchestratorV2;
637 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
638 const threadId = yield* startFirstTurn;
639 const first = started[0]!;
640 yield* orchestrator.dispatch({
641 type: "message.dispatch",
642 commandId: CommandId.make("steer"),
643 threadId,
644 messageId: MessageId.make("message:steer"),
645 text: "late steer",
646 attachments: [],
647 modelSelection: composerSelection,
648 dispatchMode: { type: "steer_active", targetRunId: first.runId },
649 createdBy: "user",
650 creationSource: "web",
651 });
652 const settled = yield* orchestrator.streamDomainEvents.pipe(
653 Stream.filter(
654 (event) =>
655 event.type === "run.updated" &&
656 event.payload.id === first.runId &&
657 event.payload.status === "waiting",
658 ),
659 Stream.take(1),
660 Stream.runDrain,
661 Effect.forkScoped,
662 );
663 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
664 yield* Queue.offer(events, {
665 type: "provider_turn.updated",
666 driver,
667 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
668 });
669 yield* Queue.offer(events, {
670 type: "turn.terminal",
671 driver,
672 providerThreadId: turn.providerThreadId,
673 providerTurnId: turn.id,
674 runOrdinal: first.runOrdinal,
675 status: "completed",
676 failure: null,
677 threadDisposition: "reusable",
678 });
679 yield* Fiber.join(settled);
680 yield* worker.drain();
681 yield* orchestrator.resumeQueuedRuns;
682 yield* worker.drain();
683
684 const projection = yield* orchestrator.getThreadProjection(threadId);
685 assert.deepEqual(steered, []);
686 assert.equal(started.length, 2);
687 assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
688 assert.deepEqual(started[1]?.modelSelection, composerSelection);
689 assert.deepEqual(projection.thread.modelSelection, composerSelection);
690 }).pipe(Effect.provide(layer));
691 }),
692 ),
693);
694
695// A draft that never reaches a paragraph boundary is held back while it
696// streams. Codex only flushes it at turn end, after the final answer is written,
697// so the draft must already own its place from before the steer.
698it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
699 Effect.scoped(
700 Effect.gen(function* () {
701 const { events, started, layer, startFirstTurn } =
702 yield* nextTurnSelectionHarness("steering-held-draft");
703 yield* Effect.gen(function* () {
704 const orchestrator = yield* Orchestrator.OrchestratorV2;
705 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
706 const threadId = yield* startFirstTurn;
707 const first = started[0]!;
708 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
709 const now = yield* DateTime.now;
710 const assistantItem = (id: string, text: string, streaming: boolean) =>
711 ({
712 type: "turn_item.updated",
713 driver,
714 turnItem: {
715 id: TurnItemId.make(id),
716 threadId,
717 runId: first.runId,
718 nodeId: first.rootNodeId,
719 providerThreadId: turn.providerThreadId,
720 providerTurnId: turn.id,
721 nativeItemRef: null,
722 parentItemId: null,
723 ordinal: 0,
724 status: streaming ? "running" : "completed",
725 title: null,
726 startedAt: now,
727 completedAt: streaming ? null : now,
728 updatedAt: now,
729 type: "assistant_message",
730 messageId: MessageId.make(`message:${id}`),
731 text,
732 streaming,
733 },
734 }) satisfies ProviderAdapter.ProviderAdapterV2Event;
735 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
736 orchestrator.streamDomainEvents.pipe(
737 Stream.filter(predicate),
738 Stream.take(1),
739 Stream.runDrain,
740 Effect.forkScoped,
741 );
742
743 // The cut-off draft starts first; the commentary after it is written,
744 // so the draft has been seen by the time the steer arrives.
745 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
746 const commentaryWritten = yield* watch(
747 (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
748 );
749 yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
750 yield* Fiber.join(commentaryWritten);
751
752 yield* orchestrator.dispatch({
753 type: "message.dispatch",
754 commandId: CommandId.make("steer"),
755 threadId,
756 messageId: MessageId.make("message:steer"),
757 text: "fix the popover",
758 attachments: [],
759 dispatchMode: { type: "steer_active", targetRunId: first.runId },
760 createdBy: "user",
761 creationSource: "web",
762 });
763 yield* worker.drain();
764
765 const settled = yield* watch(
766 (event) =>
767 event.type === "run.updated" &&
768 event.payload.id === first.runId &&
769 event.payload.status === "waiting",
770 );
771 yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
772 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
773 yield* Queue.offer(events, {
774 type: "provider_turn.updated",
775 driver,
776 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
777 });
778 yield* Queue.offer(events, {
779 type: "turn.terminal",
780 driver,
781 providerThreadId: turn.providerThreadId,
782 providerTurnId: turn.id,
783 runOrdinal: first.runOrdinal,
784 status: "completed",
785 failure: null,
786 threadDisposition: "reusable",
787 });
788 yield* Fiber.join(settled);
789 yield* worker.drain();
790
791 const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
792 .toSorted((left, right) => left.ordinal - right.ordinal)
793 .flatMap((item) =>
794 item.type === "user_message"
795 ? [String(item.messageId)]
796 : item.type === "assistant_message"
797 ? [String(item.id)]
798 : [],
799 );
800 assert.deepEqual(items, [
801 "message:first",
802 "draft",
803 "commentary",
804 "message:steer",
805 "answer",
806 ]);
807 }).pipe(Effect.provide(layer));
808 }),
809 ),
810);
811
812it.effect("keeps a queued message queued when promoted into a run that Stop reached", () =>
813 Effect.scoped(
814 Effect.gen(function* () {
815 const { started, steered, layer, startFirstTurn } =
816 yield* nextTurnSelectionHarness("steering-after-stop");
817 yield* Effect.gen(function* () {
818 const orchestrator = yield* Orchestrator.OrchestratorV2;
819 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
820 const threadId = yield* startFirstTurn;
821 const first = started[0]!;
822 yield* orchestrator.dispatch({
823 type: "message.dispatch",
824 commandId: CommandId.make("queued"),
825 threadId,
826 messageId: MessageId.make("message:queued"),
827 text: "queued",
828 attachments: [],
829 modelSelection: runSelection,
830 dispatchMode: { type: "queue_after_active" },
831 createdBy: "user",
832 creationSource: "web",
833 });
834 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
835 (run) => run.status === "queued",
836 )!;
837 // The worker has not delivered the interrupt yet, so the run still reads as running.
838 yield* orchestrator.dispatch({
839 type: "run.interrupt",
840 commandId: CommandId.make("stop"),
841 threadId,
842 runId: first.runId,
843 holdQueue: true,
844 });
845
846 const promoteError = yield* orchestrator
847 .dispatch({
848 type: "queued-message.promote-to-steer",
849 commandId: CommandId.make("promote"),
850 threadId,
851 queuedRunId: queuedRun.id,
852 targetRunId: first.runId,
853 })
854 .pipe(Effect.flip);
855 yield* worker.drain();
856
857 const projection = yield* orchestrator.getThreadProjection(threadId);
858 assert.equal(promoteError._tag, "OrchestratorDispatchError");
859 assert.deepEqual(steered, []);
860 const queued = projection.runs.find((run) => run.id === queuedRun.id);
861 assert.equal(queued?.status, "queued");
862 assert.isTrue(queued?.queueHeld);
863 }).pipe(Effect.provide(layer));
864 }),
865 ),
866);
867
868it.effect("queues a plain send behind the stopped queue and releases its hold", () =>
869 Effect.scoped(
870 Effect.gen(function* () {
871 const { started, steered, layer, startFirstTurn } =
872 yield* nextTurnSelectionHarness("plain-send-after-stop");
873 yield* Effect.gen(function* () {
874 const orchestrator = yield* Orchestrator.OrchestratorV2;
875 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
876 const threadId = yield* startFirstTurn;
877 const send = (id: string, delivery: "queue" | "auto") =>
878 orchestrator.dispatch({
879 type: "message.dispatch",
880 commandId: CommandId.make(id),
881 threadId,
882 messageId: MessageId.make(`message:${id}`),
883 text: id,
884 attachments: [],
885 modelSelection: runSelection,
886 ...(delivery === "queue"
887 ? { dispatchMode: { type: "queue_after_active" } }
888 : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
889 createdBy: "user",
890 creationSource: "web",
891 });
892 yield* send("queued", "queue");
893 yield* orchestrator.dispatch({
894 type: "run.interrupt",
895 commandId: CommandId.make("stop"),
896 threadId,
897 runId: started[0]!.runId,
898 holdQueue: true,
899 });
900 // The provider has not stopped yet, so a plain send still resolves to a steer.
901 yield* send("sent", "auto");
902 yield* worker.drain();
903
904 const projection = yield* orchestrator.getThreadProjection(threadId);
905 assert.deepEqual(steered, []);
906 assert.equal(started.length, 1);
907 const queued = projection.runs
908 .filter((run) => run.status === "queued")
909 .sort((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0));
910 assert.deepEqual(
911 queued.map(
912 (run) => projection.messages.find((message) => message.id === run.userMessageId)?.text,
913 ),
914 ["queued", "sent"],
915 );
916 // The user sent it, so the queue they stopped runs again once the provider stops.
917 assert.isFalse(queued.some((run) => run.queueHeld === true));
918 }).pipe(Effect.provide(layer));
919 }),
920 ),
921);