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

SteeringCompletion.integration.test.ts

820 lines30.8 KB

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 [false, true]
38 .flatMap((mailbox) =>
39 (
40 [
41 "before delivery",
42 "during delivery",
43 "before dispatch",
44 "after delivery",
45 "without native steering",
46 "with interrupting native steering",
47 "settled only",
48 ] as const
49 ).map((timing) => ({
50 mailbox,
51 timing,
52 label: mailbox ? "mailbox notification" : "steering",
53 })),
54 )
55 .filter(
56 ({ mailbox, timing }) =>
57 mailbox ||
58 (timing !== "without native steering" &&
59 timing !== "with interrupting native steering" &&
60 timing !== "settled only"),
61 ),
62)("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
63 Effect.scoped(
64 Effect.gen(function* () {
65 const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
66 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
67 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
68 const steerEntered = yield* Deferred.make<void>();
69 const rejectSteer = yield* Deferred.make<void>();
70 let steerCalls = 0;
71 const capabilities = {
72 ...CodexProviderCapabilitiesV2,
73 turns: {
74 ...CodexProviderCapabilitiesV2.turns,
75 supportsActiveSteering: timing !== "without native steering",
76 activeSteeringInterruptsTools: timing === "with interrupting native steering",
77 },
78 };
79 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
80 instanceId,
81 driver,
82 getCapabilities: () => Effect.succeed(capabilities),
83 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
84 openSession: (input) =>
85 Effect.gen(function* () {
86 const now = yield* DateTime.now;
87 return {
88 instanceId,
89 driver,
90 providerSessionId: input.providerSessionId,
91 providerSession: {
92 id: input.providerSessionId,
93 driver,
94 providerInstanceId: instanceId,
95 status: "ready",
96 cwd,
97 model: modelSelection.model,
98 capabilities,
99 createdAt: now,
100 updatedAt: now,
101 lastError: null,
102 },
103 events: Stream.fromQueue(events),
104 ensureThread: ({ threadId }) =>
105 Effect.succeed({
106 id: ProviderThreadId.make(`provider-thread:${threadId}`),
107 driver,
108 providerInstanceId: instanceId,
109 providerSessionId: input.providerSessionId,
110 appThreadId: threadId,
111 ownerNodeId: null,
112 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
113 nativeConversationHeadRef: null,
114 status: "idle",
115 firstRunOrdinal: null,
116 lastRunOrdinal: null,
117 handoffIds: [],
118 forkedFrom: null,
119 createdAt: now,
120 updatedAt: now,
121 }),
122 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
123 startTurn: (turn) =>
124 Effect.gen(function* () {
125 started.push(turn);
126 yield* Queue.offer(events, {
127 type: "provider_turn.updated",
128 driver,
129 providerTurn: {
130 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
131 providerThreadId: turn.providerThread.id,
132 nodeId: turn.rootNodeId,
133 runAttemptId: turn.attemptId,
134 nativeTurnRef: {
135 driver,
136 nativeId: `native:${turn.attemptId}`,
137 strength: "strong",
138 },
139 ordinal: turn.providerTurnOrdinal,
140 status: "running",
141 startedAt: now,
142 completedAt: null,
143 },
144 });
145 }),
146 steerTurn: (turn) =>
147 Effect.gen(function* () {
148 steerCalls += 1;
149 if (timing === "after delivery") return;
150 yield* Deferred.succeed(steerEntered, undefined);
151 yield* Deferred.await(rejectSteer);
152 return yield* new ProviderAdapter.ProviderAdapterSteerRunError({
153 driver,
154 providerThreadId: turn.providerThread.id,
155 providerTurnId: turn.providerTurnId,
156 cause: "turn already completed",
157 });
158 }),
159 interruptTurn: () => Effect.void,
160 respondToRuntimeRequest: () => Effect.void,
161 readThreadSnapshot: () => Effect.die("unused"),
162 rollbackThread: () => Effect.die("unused"),
163 forkThread: () => Effect.die("unused"),
164 };
165 }),
166 };
167 yield* Effect.gen(function* () {
168 const orchestrator = yield* Orchestrator.OrchestratorV2;
169 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
170 const threadId = ThreadId.make("thread:steering-completion");
171 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
172 orchestrator.streamDomainEvents.pipe(
173 Stream.filter(predicate),
174 Stream.take(1),
175 Stream.runDrain,
176 Effect.forkScoped,
177 );
178 yield* orchestrator.dispatch({
179 type: "thread.create",
180 commandId: CommandId.make("create"),
181 threadId,
182 projectId: ProjectId.make("project:steering-completion"),
183 title: "Steering race",
184 modelSelection,
185 runtimeMode: "full-access",
186 interactionMode: "default",
187 branch: null,
188 worktreePath: cwd,
189 createdBy: "user",
190 creationSource: "web",
191 });
192 yield* orchestrator.dispatch({
193 type: "message.dispatch",
194 commandId: CommandId.make("first"),
195 threadId,
196 messageId: MessageId.make("message:first"),
197 text: "first",
198 attachments: [],
199 dispatchMode: { type: "start_immediately" },
200 createdBy: "user",
201 creationSource: "web",
202 });
203 const running = yield* watch(
204 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
205 );
206 yield* worker.drain();
207 yield* Fiber.join(running);
208 const first = started[0]!;
209 const messageId = MessageId.make("message:steering");
210 const taskId = NodeId.make("task:mailbox");
211 if (mailbox) {
212 const sink = yield* EventSink.EventSinkV2;
213 const current = yield* orchestrator.getThreadProjection(threadId);
214 const parentRun = current.runs.find((run) => run.id === first.runId)!;
215 const now = yield* DateTime.now;
216 yield* sink.write({
217 events: [
218 {
219 id: EventId.make("mailbox:cohort"),
220 type: "run.updated",
221 threadId,
222 runId: first.runId,
223 occurredAt: now,
224 payload: {
225 ...parentRun,
226 delegatedCompletion: {
227 disposition: "open",
228 nextGeneration: 2,
229 delivery: { generation: 1, messageId, taskIds: [taskId] },
230 },
231 },
232 },
233 {
234 id: EventId.make("mailbox:task"),
235 type: "subagent.updated",
236 threadId,
237 runId: first.runId,
238 nodeId: taskId,
239 occurredAt: now,
240 payload: {
241 id: taskId,
242 threadId,
243 runId: first.runId,
244 parentNodeId: first.rootNodeId,
245 origin: "app_owned",
246 createdBy: "agent",
247 driver,
248 providerInstanceId: instanceId,
249 providerThreadId: null,
250 childThreadId: null,
251 nativeTaskRef: null,
252 prompt: "Do background work",
253 title: "Background test",
254 model: null,
255 completionWake: timing === "settled only" ? "settled_only" : "always",
256 completionDelivery: { state: "claimed", observedByRunId: null },
257 status: "completed",
258 result: "done",
259 startedAt: now,
260 completedAt: now,
261 updatedAt: now,
262 },
263 },
264 ],
265 });
266 }
267 const dispatchSteer = orchestrator.dispatch({
268 type: "message.dispatch",
269 commandId: CommandId.make("steer"),
270 threadId,
271 messageId,
272 text: "fix the popover",
273 attachments: [
274 {
275 type: "image",
276 id: "steering-screenshot",
277 name: "image.png",
278 mimeType: "image/png",
279 sizeBytes: 10,
280 },
281 ],
282 dispatchMode: mailbox
283 ? { type: "queue_after_active" }
284 : { type: "steer_active", targetRunId: first.runId },
285 createdBy: mailbox ? "agent" : "user",
286 creationSource: mailbox ? "server" : "web",
287 ...(mailbox
288 ? {
289 delegatedCompletion: {
290 parentRunId: first.runId,
291 generation: 1,
292 taskIds: [taskId],
293 },
294 }
295 : {}),
296 });
297 if (timing !== "before dispatch") yield* dispatchSteer;
298 if (timing === "after delivery") yield* worker.drain();
299 const delivery =
300 timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
301 if (delivery !== null) yield* Deferred.await(steerEntered);
302 const completed = yield* watch(
303 (event) =>
304 event.type === "run.updated" &&
305 event.payload.id === first.runId &&
306 event.payload.status === "waiting",
307 );
308 const projection = yield* orchestrator.getThreadProjection(threadId);
309 const turn = projection.providerTurns[0]!;
310 yield* Queue.offer(events, {
311 type: "provider_turn.updated",
312 driver,
313 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
314 });
315 yield* Queue.offer(events, {
316 type: "turn.terminal",
317 driver,
318 providerThreadId: turn.providerThreadId,
319 providerTurnId: turn.id,
320 runOrdinal: first.runOrdinal,
321 status: "completed",
322 failure: null,
323 threadDisposition: "reusable",
324 });
325 yield* Fiber.join(completed);
326 if (delivery !== null) {
327 yield* Deferred.succeed(rejectSteer, undefined);
328 yield* Fiber.join(delivery);
329 }
330 if (timing === "before dispatch") yield* dispatchSteer;
331 yield* worker.drain();
332 yield* orchestrator.resumeQueuedRuns;
333 yield* worker.drain();
334 if (timing === "after delivery") {
335 assert.equal(steerCalls, 1);
336 assert.equal(started.length, 1);
337 if (mailbox) {
338 const delivered = yield* orchestrator.getThreadProjection(threadId);
339 assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
340 assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
341 assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
342 assert.equal(
343 delivered.turnItems.filter((item) => item.type === "notification").length,
344 1,
345 );
346 yield* orchestrator.dispatch({
347 type: "notification.delivery.accept",
348 commandId: CommandId.make("duplicate-acceptance"),
349 threadId,
350 messageId,
351 });
352 yield* worker.drain();
353 assert.equal(steerCalls, 1);
354 yield* orchestrator.dispatch({
355 type: "delegated_task.completion-delivery.acknowledge",
356 commandId: CommandId.make("read-result"),
357 parentThreadId: threadId,
358 taskId,
359 observedByRunId: first.runId,
360 });
361 const acknowledged = yield* orchestrator.getThreadProjection(threadId);
362 assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
363 }
364 return;
365 }
366 assert.equal(started.length, 2);
367 assert.equal(started[1]?.message.messageId, messageId);
368 if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
369 else assert.equal(started[1]?.message.text, "fix the popover");
370 assert.deepEqual(started[1]?.message.attachments, [
371 {
372 type: "image",
373 id: "steering-screenshot",
374 name: "image.png",
375 mimeType: "image/png",
376 sizeBytes: 10,
377 },
378 ]);
379 assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
380 const final = yield* orchestrator.getThreadProjection(threadId);
381 assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
382 assert.equal(
383 final.messages.find((message) => message.id === messageId)?.runId,
384 started[1]?.runId,
385 );
386 assert.equal(
387 final.turnItems.filter((item) =>
388 mailbox
389 ? item.type === "notification"
390 : item.type === "user_message" && item.messageId === messageId,
391 ).length,
392 1,
393 );
394 yield* worker.drain();
395 assert.equal(started.length, 2);
396 }).pipe(
397 Effect.provide(
398 ProviderReplayHarness.layerWithRegistry(
399 { name: `steering-completion-${timing}` },
400 ProviderAdapterRegistry.layerSingle(adapter),
401 { runEffectWorker: false },
402 ),
403 ),
404 );
405 }),
406 ),
407);
408​
409const runSelection = {
410 instanceId,
411 model: "test-model",
412 options: [{ id: "effort", value: "xhigh" }],
413};
414const composerSelection = {
415 ...runSelection,
416 options: [...runSelection.options, { id: "fastMode", value: false }],
417};
418​
419const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (
420 name: string,
421 canRestart = false,
422) {
423 const cwd = yield* checkpointWorkspace(name);
424 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
425 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
426 const steered: string[] = [];
427 const capabilities = {
428 ...CodexProviderCapabilitiesV2,
429 turns: {
430 ...CodexProviderCapabilitiesV2.turns,
431 supportsActiveSteering: true,
432 supportsSteeringByInterruptRestart: canRestart,
433 },
434 };
435 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
436 instanceId,
437 driver,
438 getCapabilities: () => Effect.succeed(capabilities),
439 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
440 openSession: (input) =>
441 Effect.gen(function* () {
442 const now = yield* DateTime.now;
443 return {
444 instanceId,
445 driver,
446 providerSessionId: input.providerSessionId,
447 providerSession: {
448 id: input.providerSessionId,
449 driver,
450 providerInstanceId: instanceId,
451 status: "ready",
452 cwd,
453 model: runSelection.model,
454 capabilities,
455 createdAt: now,
456 updatedAt: now,
457 lastError: null,
458 },
459 events: Stream.fromQueue(events),
460 ensureThread: ({ threadId }) =>
461 Effect.succeed({
462 id: ProviderThreadId.make(`provider-thread:${threadId}`),
463 driver,
464 providerInstanceId: instanceId,
465 providerSessionId: input.providerSessionId,
466 appThreadId: threadId,
467 ownerNodeId: null,
468 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
469 nativeConversationHeadRef: null,
470 status: "idle",
471 firstRunOrdinal: null,
472 lastRunOrdinal: null,
473 handoffIds: [],
474 forkedFrom: null,
475 createdAt: now,
476 updatedAt: now,
477 }),
478 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
479 startTurn: (turn) =>
480 Effect.gen(function* () {
481 started.push(turn);
482 yield* Queue.offer(events, {
483 type: "provider_turn.updated",
484 driver,
485 providerTurn: {
486 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
487 providerThreadId: turn.providerThread.id,
488 nodeId: turn.rootNodeId,
489 runAttemptId: turn.attemptId,
490 nativeTurnRef: {
491 driver,
492 nativeId: `native:${turn.attemptId}`,
493 strength: "strong",
494 },
495 ordinal: turn.providerTurnOrdinal,
496 status: "running",
497 startedAt: now,
498 completedAt: null,
499 },
500 });
501 }),
502 steerTurn: (turn) =>
503 Effect.sync(() => {
504 steered.push(turn.message.text);
505 }),
506 interruptTurn: () => Effect.void,
507 respondToRuntimeRequest: () => Effect.void,
508 readThreadSnapshot: () => Effect.die("unused"),
509 rollbackThread: () => Effect.die("unused"),
510 forkThread: () => Effect.die("unused"),
511 };
512 }),
513 };
514 const layer = ProviderReplayHarness.layerWithRegistry(
515 { name },
516 ProviderAdapterRegistry.layerSingle(adapter),
517 { runEffectWorker: false },
518 );
519 const startFirstTurn = Effect.gen(function* () {
520 const orchestrator = yield* Orchestrator.OrchestratorV2;
521 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
522 const threadId = ThreadId.make(`thread:${name}`);
523 yield* orchestrator.dispatch({
524 type: "thread.create",
525 commandId: CommandId.make("create"),
526 threadId,
527 projectId: ProjectId.make(`project:${name}`),
528 title: "Steer with changed options",
529 modelSelection: runSelection,
530 runtimeMode: "full-access",
531 interactionMode: "default",
532 branch: null,
533 worktreePath: cwd,
534 createdBy: "user",
535 creationSource: "web",
536 });
537 const running = yield* orchestrator.streamDomainEvents.pipe(
538 Stream.filter(
539 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
540 ),
541 Stream.take(1),
542 Stream.runDrain,
543 Effect.forkScoped,
544 );
545 yield* orchestrator.dispatch({
546 type: "message.dispatch",
547 commandId: CommandId.make("first"),
548 threadId,
549 messageId: MessageId.make("message:first"),
550 text: "first",
551 attachments: [],
552 modelSelection: runSelection,
553 dispatchMode: { type: "start_immediately" },
554 createdBy: "user",
555 creationSource: "web",
556 });
557 yield* worker.drain();
558 yield* Fiber.join(running);
559 return threadId;
560 });
561 return { events, started, steered, layer, startFirstTurn };
562});
563​
564it.effect.each([{ canRestart: false }, { canRestart: true }])(
565 "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)",
566 ({ canRestart }) =>
567 Effect.scoped(
568 Effect.gen(function* () {
569 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
570 `steering-selection-change-${canRestart}`,
571 canRestart,
572 );
573 yield* Effect.gen(function* () {
574 const orchestrator = yield* Orchestrator.OrchestratorV2;
575 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
576 const threadId = yield* startFirstTurn;
577 const steer = (id: string, selection: ModelSelection) =>
578 orchestrator
579 .dispatch({
580 type: "message.dispatch",
581 commandId: CommandId.make(id),
582 threadId,
583 messageId: MessageId.make(`message:${id}`),
584 text: id,
585 attachments: [],
586 modelSelection: selection,
587 dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
588 createdBy: "user",
589 creationSource: "web",
590 })
591 .pipe(Effect.andThen(worker.drain()));
592​
593 yield* steer("steer-changed", composerSelection);
594 const changed = yield* orchestrator.getThreadProjection(threadId);
595 assert.deepEqual(steered, ["steer-changed"]);
596 assert.equal(started.length, 1);
597 assert.lengthOf(changed.attempts, 1);
598 assert.equal(changed.runs[0]?.status, "running");
599 assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
600 assert.deepEqual(changed.thread.modelSelection, composerSelection);
601​
602 yield* steer("steer-reverted", runSelection);
603 const reverted = yield* orchestrator.getThreadProjection(threadId);
604 assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
605 assert.lengthOf(reverted.attempts, 1);
606 assert.deepEqual(reverted.thread.modelSelection, runSelection);
607​
608 const otherSelection = {
609 instanceId: ProviderInstanceId.make("codex-work"),
610 model: "other",
611 };
612 const sink = yield* EventSink.EventSinkV2;
613 yield* sink.write({
614 events: [
615 {
616 id: EventId.make("switched-away"),
617 type: "thread.provider-switched",
618 threadId,
619 providerInstanceId: otherSelection.instanceId,
620 occurredAt: yield* DateTime.now,
621 payload: {
622 ...reverted.thread,
623 providerInstanceId: otherSelection.instanceId,
624 modelSelection: otherSelection,
625 },
626 },
627 ],
628 });
629 yield* steer("steer-back", runSelection);
630 const back = yield* orchestrator.getThreadProjection(threadId);
631 assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
632 assert.equal(back.thread.providerInstanceId, instanceId);
633 assert.deepEqual(back.thread.modelSelection, runSelection);
634 }).pipe(Effect.provide(layer));
635 }),
636 ),
637);
638​
639it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>
640 Effect.scoped(
641 Effect.gen(function* () {
642 const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
643 "steering-selection-follow-up",
644 );
645 yield* Effect.gen(function* () {
646 const orchestrator = yield* Orchestrator.OrchestratorV2;
647 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
648 const threadId = yield* startFirstTurn;
649 const first = started[0]!;
650 yield* orchestrator.dispatch({
651 type: "message.dispatch",
652 commandId: CommandId.make("steer"),
653 threadId,
654 messageId: MessageId.make("message:steer"),
655 text: "late steer",
656 attachments: [],
657 modelSelection: composerSelection,
658 dispatchMode: { type: "steer_active", targetRunId: first.runId },
659 createdBy: "user",
660 creationSource: "web",
661 });
662 const settled = yield* orchestrator.streamDomainEvents.pipe(
663 Stream.filter(
664 (event) =>
665 event.type === "run.updated" &&
666 event.payload.id === first.runId &&
667 event.payload.status === "waiting",
668 ),
669 Stream.take(1),
670 Stream.runDrain,
671 Effect.forkScoped,
672 );
673 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
674 yield* Queue.offer(events, {
675 type: "provider_turn.updated",
676 driver,
677 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
678 });
679 yield* Queue.offer(events, {
680 type: "turn.terminal",
681 driver,
682 providerThreadId: turn.providerThreadId,
683 providerTurnId: turn.id,
684 runOrdinal: first.runOrdinal,
685 status: "completed",
686 failure: null,
687 threadDisposition: "reusable",
688 });
689 yield* Fiber.join(settled);
690 yield* worker.drain();
691 yield* orchestrator.resumeQueuedRuns;
692 yield* worker.drain();
693​
694 const projection = yield* orchestrator.getThreadProjection(threadId);
695 assert.deepEqual(steered, []);
696 assert.equal(started.length, 2);
697 assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
698 assert.deepEqual(started[1]?.modelSelection, composerSelection);
699 assert.deepEqual(projection.thread.modelSelection, composerSelection);
700 }).pipe(Effect.provide(layer));
701 }),
702 ),
703);
704​
705// A draft that never reaches a paragraph boundary is held back while it
706// streams. Codex only flushes it at turn end, after the final answer is written,
707// so the draft must already own its place from before the steer.
708it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
709 Effect.scoped(
710 Effect.gen(function* () {
711 const { events, started, layer, startFirstTurn } =
712 yield* nextTurnSelectionHarness("steering-held-draft");
713 yield* Effect.gen(function* () {
714 const orchestrator = yield* Orchestrator.OrchestratorV2;
715 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
716 const threadId = yield* startFirstTurn;
717 const first = started[0]!;
718 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
719 const now = yield* DateTime.now;
720 const assistantItem = (id: string, text: string, streaming: boolean) =>
721 ({
722 type: "turn_item.updated",
723 driver,
724 turnItem: {
725 id: TurnItemId.make(id),
726 threadId,
727 runId: first.runId,
728 nodeId: first.rootNodeId,
729 providerThreadId: turn.providerThreadId,
730 providerTurnId: turn.id,
731 nativeItemRef: null,
732 parentItemId: null,
733 ordinal: 0,
734 status: streaming ? "running" : "completed",
735 title: null,
736 startedAt: now,
737 completedAt: streaming ? null : now,
738 updatedAt: now,
739 type: "assistant_message",
740 messageId: MessageId.make(`message:${id}`),
741 text,
742 streaming,
743 },
744 }) satisfies ProviderAdapter.ProviderAdapterV2Event;
745 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
746 orchestrator.streamDomainEvents.pipe(
747 Stream.filter(predicate),
748 Stream.take(1),
749 Stream.runDrain,
750 Effect.forkScoped,
751 );
752​
753 // The cut-off draft starts first; the commentary after it is written,
754 // so the draft has been seen by the time the steer arrives.
755 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
756 const commentaryWritten = yield* watch(
757 (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
758 );
759 yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
760 yield* Fiber.join(commentaryWritten);
761​
762 yield* orchestrator.dispatch({
763 type: "message.dispatch",
764 commandId: CommandId.make("steer"),
765 threadId,
766 messageId: MessageId.make("message:steer"),
767 text: "fix the popover",
768 attachments: [],
769 dispatchMode: { type: "steer_active", targetRunId: first.runId },
770 createdBy: "user",
771 creationSource: "web",
772 });
773 yield* worker.drain();
774​
775 const settled = yield* watch(
776 (event) =>
777 event.type === "run.updated" &&
778 event.payload.id === first.runId &&
779 event.payload.status === "waiting",
780 );
781 yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
782 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
783 yield* Queue.offer(events, {
784 type: "provider_turn.updated",
785 driver,
786 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
787 });
788 yield* Queue.offer(events, {
789 type: "turn.terminal",
790 driver,
791 providerThreadId: turn.providerThreadId,
792 providerTurnId: turn.id,
793 runOrdinal: first.runOrdinal,
794 status: "completed",
795 failure: null,
796 threadDisposition: "reusable",
797 });
798 yield* Fiber.join(settled);
799 yield* worker.drain();
800​
801 const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
802 .toSorted((left, right) => left.ordinal - right.ordinal)
803 .flatMap((item) =>
804 item.type === "user_message"
805 ? [String(item.messageId)]
806 : item.type === "assistant_message"
807 ? [String(item.id)]
808 : [],
809 );
810 assert.deepEqual(items, [
811 "message:first",
812 "draft",
813 "commentary",
814 "message:steer",
815 "answer",
816 ]);
817 }).pipe(Effect.provide(layer));
818 }),
819 ),
820);