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

SteeringCompletion.integration.test.ts

1,468 lines56.1 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 (
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 [false, "during continuation"],
46 ] as const
47 ).map(([mailbox, timing]) => ({
48 mailbox,
49 timing,
50 label: mailbox ? "mailbox notification" : "steering",
51 })),
52)("delivers $label when completion wins $timing", ({ mailbox, timing }) =>
53 Effect.scoped(
54 Effect.gen(function* () {
55 const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`);
56 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
57 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
58 const steerEntered = yield* Deferred.make<void>();
59 const rejectSteer = yield* Deferred.make<void>();
60 let steerCalls = 0;
61 const capabilities = {
62 ...CodexProviderCapabilitiesV2,
63 turns: {
64 ...CodexProviderCapabilitiesV2.turns,
65 supportsActiveSteering: timing !== "without native steering",
66 activeSteeringInterruptsTools: timing === "with interrupting native steering",
67 },
68 };
69 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
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" || timing === "during continuation") return;
140 yield* Deferred.succeed(steerEntered, undefined);
141 yield* Deferred.await(rejectSteer);
142 return yield* new ProviderAdapter.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) => event.type === "provider-turn.updated" && event.payload.status === "running",
195 );
196 yield* worker.drain();
197 yield* Fiber.join(running);
198 const first = started[0]!;
199 const messageId = MessageId.make("message:steering");
200 const taskId = NodeId.make("task:mailbox");
201 if (mailbox) {
202 const sink = yield* EventSink.EventSinkV2;
203 const current = yield* orchestrator.getThreadProjection(threadId);
204 const parentRun = current.runs.find((run) => run.id === first.runId)!;
205 const now = yield* DateTime.now;
206 yield* sink.write({
207 events: [
208 {
209 id: EventId.make("mailbox:cohort"),
210 type: "run.updated",
211 threadId,
212 runId: first.runId,
213 occurredAt: now,
214 payload: {
215 ...parentRun,
216 delegatedCompletion: {
217 disposition: "open",
218 nextGeneration: 2,
219 delivery: { generation: 1, messageId, taskIds: [taskId] },
220 },
221 },
222 },
223 {
224 id: EventId.make("mailbox:task"),
225 type: "subagent.updated",
226 threadId,
227 runId: first.runId,
228 nodeId: taskId,
229 occurredAt: now,
230 payload: {
231 id: taskId,
232 threadId,
233 runId: first.runId,
234 parentNodeId: first.rootNodeId,
235 origin: "app_owned",
236 createdBy: "agent",
237 driver,
238 providerInstanceId: instanceId,
239 providerThreadId: null,
240 childThreadId: null,
241 nativeTaskRef: null,
242 prompt: "Do background work",
243 title: "Background test",
244 model: null,
245 completionWake: timing === "settled only" ? "settled_only" : "always",
246 completionDelivery: { state: "claimed", observedByRunId: null },
247 status: "completed",
248 result: "done",
249 startedAt: now,
250 completedAt: now,
251 updatedAt: now,
252 },
253 },
254 ],
255 });
256 }
257 const dispatchSteer = orchestrator.dispatch({
258 type: "message.dispatch",
259 commandId: CommandId.make("steer"),
260 threadId,
261 messageId,
262 text: "fix the popover",
263 attachments: [
264 {
265 type: "image",
266 id: "steering-screenshot",
267 name: "image.png",
268 mimeType: "image/png",
269 sizeBytes: 10,
270 },
271 ],
272 dispatchMode: mailbox
273 ? { type: "queue_after_active" }
274 : { type: "steer_active", targetRunId: first.runId },
275 createdBy: mailbox ? "agent" : "user",
276 creationSource: mailbox ? "server" : "web",
277 ...(mailbox
278 ? {
279 delegatedCompletion: {
280 parentRunId: first.runId,
281 generation: 1,
282 taskIds: [taskId],
283 },
284 }
285 : {}),
286 });
287 if (timing !== "before dispatch") yield* dispatchSteer;
288 if (timing === "during continuation") {
289 const projection = yield* orchestrator.getThreadProjection(threadId);
290 const turn = projection.providerTurns[0]!;
291 const failed = yield* watch(
292 (event) => event.type === "provider-turn.updated" && event.payload.status === "failed",
293 );
294 yield* Queue.offer(events, {
295 type: "provider_turn.updated",
296 driver,
297 providerTurn: { ...turn, status: "failed", completedAt: yield* DateTime.now },
298 });
299 yield* Fiber.join(failed);
300 yield* worker.drain();
301 assert.equal(steerCalls, 1);
302 assert.lengthOf(started, 1);
303 const continued = yield* orchestrator.getThreadProjection(threadId);
304 assert.equal(continued.runs[0]?.status, "running");
305 assert.equal(
306 continued.messages.find((message) => message.id === messageId)?.runId,
307 first.runId,
308 );
309 return;
310 }
311 if (timing === "after delivery") yield* worker.drain();
312 const delivery =
313 timing === "during delivery" ? yield* worker.runOnce.pipe(Effect.forkScoped) : null;
314 if (delivery !== null) yield* Deferred.await(steerEntered);
315 const completed = yield* watch(
316 (event) =>
317 event.type === "run.updated" &&
318 event.payload.id === first.runId &&
319 event.payload.status === "waiting",
320 );
321 const projection = yield* orchestrator.getThreadProjection(threadId);
322 const turn = projection.providerTurns[0]!;
323 yield* Queue.offer(events, {
324 type: "provider_turn.updated",
325 driver,
326 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
327 });
328 yield* Queue.offer(events, {
329 type: "turn.terminal",
330 driver,
331 providerThreadId: turn.providerThreadId,
332 providerTurnId: turn.id,
333 runOrdinal: first.runOrdinal,
334 status: "completed",
335 failure: null,
336 threadDisposition: "reusable",
337 });
338 yield* Fiber.join(completed);
339 if (delivery !== null) {
340 yield* Deferred.succeed(rejectSteer, undefined);
341 yield* Fiber.join(delivery);
342 const requeued = yield* orchestrator.getThreadProjection(threadId);
343 const item = requeued.turnItems.find(
344 (item) => item.type === "user_message" && item.messageId === messageId,
345 );
346 assert.equal(item?.status, "pending");
347 assert.isNull(item?.startedAt);
348 assert.isNull(item?.completedAt);
349 }
350 if (timing === "before dispatch") yield* dispatchSteer;
351 yield* worker.drain();
352 yield* orchestrator.resumeQueuedRuns;
353 yield* worker.drain();
354 if (timing === "after delivery") {
355 assert.equal(steerCalls, 1);
356 assert.equal(started.length, 1);
357 if (mailbox) {
358 const delivered = yield* orchestrator.getThreadProjection(threadId);
359 assert.equal(delivered.subagents[0]?.completionDelivery?.state, "delivered");
360 assert.equal(delivered.subagents[0]?.completionDelivery?.observedByRunId, null);
361 assert.equal(delivered.runs[0]?.delegatedCompletion?.delivery, null);
362 assert.equal(
363 delivered.turnItems.filter((item) => item.type === "notification").length,
364 1,
365 );
366 yield* orchestrator.dispatch({
367 type: "notification.delivery.accept",
368 commandId: CommandId.make("duplicate-acceptance"),
369 threadId,
370 messageId,
371 });
372 yield* worker.drain();
373 assert.equal(steerCalls, 1);
374 yield* orchestrator.dispatch({
375 type: "delegated_task.completion-delivery.acknowledge",
376 commandId: CommandId.make("read-result"),
377 parentThreadId: threadId,
378 taskId,
379 observedByRunId: first.runId,
380 });
381 const acknowledged = yield* orchestrator.getThreadProjection(threadId);
382 assert.equal(acknowledged.subagents[0]?.completionDelivery?.state, "acknowledged");
383 }
384 return;
385 }
386 assert.equal(started.length, 2);
387 assert.equal(started[1]?.message.messageId, messageId);
388 if (mailbox) assert.include(started[1]?.message.text ?? "", String(taskId));
389 else assert.equal(started[1]?.message.text, "fix the popover");
390 assert.deepEqual(started[1]?.message.attachments, [
391 {
392 type: "image",
393 id: "steering-screenshot",
394 name: "image.png",
395 mimeType: "image/png",
396 sizeBytes: 10,
397 },
398 ]);
399 assert.equal(steerCalls, timing === "during delivery" ? 1 : 0);
400 const final = yield* orchestrator.getThreadProjection(threadId);
401 if (!mailbox) {
402 assert.equal(
403 final.turnItems.find(
404 (item) => item.type === "user_message" && item.messageId === messageId,
405 )?.status,
406 "completed",
407 );
408 }
409 assert.equal(final.messages.filter((message) => message.id === messageId).length, 1);
410 assert.equal(
411 final.messages.find((message) => message.id === messageId)?.runId,
412 started[1]?.runId,
413 );
414 assert.equal(
415 final.turnItems.filter((item) =>
416 mailbox
417 ? item.type === "notification"
418 : item.type === "user_message" && item.messageId === messageId,
419 ).length,
420 1,
421 );
422 yield* worker.drain();
423 assert.equal(started.length, 2);
424 }).pipe(
425 Effect.provide(
426 ProviderReplayHarness.layerWithRegistry(
427 { name: `steering-completion-${timing}` },
428 ProviderAdapterRegistry.layerSingle(adapter),
429 { runEffectWorker: false },
430 ),
431 ),
432 );
433 }),
434 ),
435);
436​
437const runSelection = {
438 instanceId,
439 model: "test-model",
440 options: [{ id: "effort", value: "xhigh" }],
441};
442const composerSelection = {
443 ...runSelection,
444 options: [...runSelection.options, { id: "fastMode", value: false }],
445};
446​
447const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (
448 name: string,
449 canRestart = false,
450) {
451 const cwd = yield* checkpointWorkspace(name);
452 const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
453 const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = [];
454 const steered: string[] = [];
455 const capabilities = {
456 ...CodexProviderCapabilitiesV2,
457 turns: {
458 ...CodexProviderCapabilitiesV2.turns,
459 supportsActiveSteering: true,
460 supportsSteeringByInterruptRestart: canRestart,
461 },
462 };
463 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
464 instanceId,
465 driver,
466 getCapabilities: () => Effect.succeed(capabilities),
467 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
468 openSession: (input) =>
469 Effect.gen(function* () {
470 const now = yield* DateTime.now;
471 const startTurn = (turn: ProviderAdapter.ProviderAdapterV2TurnInput) =>
472 Effect.gen(function* () {
473 started.push(turn);
474 yield* Queue.offer(events, {
475 type: "provider_turn.updated",
476 driver,
477 providerTurn: {
478 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
479 providerThreadId: turn.providerThread.id,
480 nodeId: turn.rootNodeId,
481 runAttemptId: turn.attemptId,
482 nativeTurnRef: {
483 driver,
484 nativeId: `native:${turn.attemptId}`,
485 strength: "strong",
486 },
487 ordinal: turn.providerTurnOrdinal,
488 status: "running",
489 startedAt: now,
490 completedAt: null,
491 },
492 });
493 });
494 return {
495 instanceId,
496 driver,
497 providerSessionId: input.providerSessionId,
498 providerSession: {
499 id: input.providerSessionId,
500 driver,
501 providerInstanceId: instanceId,
502 status: "ready",
503 cwd,
504 model: runSelection.model,
505 capabilities,
506 createdAt: now,
507 updatedAt: now,
508 lastError: null,
509 },
510 events: Stream.fromQueue(events),
511 ensureThread: ({ threadId }) =>
512 Effect.succeed({
513 id: ProviderThreadId.make(`provider-thread:${threadId}`),
514 driver,
515 providerInstanceId: instanceId,
516 providerSessionId: input.providerSessionId,
517 appThreadId: threadId,
518 ownerNodeId: null,
519 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
520 nativeConversationHeadRef: null,
521 status: "idle",
522 firstRunOrdinal: null,
523 lastRunOrdinal: null,
524 handoffIds: [],
525 forkedFrom: null,
526 createdAt: now,
527 updatedAt: now,
528 }),
529 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
530 startTurn,
531 compactThread: startTurn,
532 steerTurn: (turn) =>
533 Effect.sync(() => {
534 steered.push(turn.message.text);
535 }),
536 interruptTurn: () => Effect.void,
537 respondToRuntimeRequest: () => Effect.void,
538 readThreadSnapshot: () => Effect.die("unused"),
539 rollbackThread: () => Effect.die("unused"),
540 forkThread: () => Effect.die("unused"),
541 };
542 }),
543 };
544 const layer = ProviderReplayHarness.layerWithRegistry(
545 { name },
546 ProviderAdapterRegistry.layerSingle(adapter),
547 { runEffectWorker: false },
548 );
549 const startFirstTurn = Effect.gen(function* () {
550 const orchestrator = yield* Orchestrator.OrchestratorV2;
551 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
552 const threadId = ThreadId.make(`thread:${name}`);
553 yield* orchestrator.dispatch({
554 type: "thread.create",
555 commandId: CommandId.make("create"),
556 threadId,
557 projectId: ProjectId.make(`project:${name}`),
558 title: "Steer with changed options",
559 modelSelection: runSelection,
560 runtimeMode: "full-access",
561 interactionMode: "default",
562 branch: null,
563 worktreePath: cwd,
564 createdBy: "user",
565 creationSource: "web",
566 });
567 const running = yield* orchestrator.streamDomainEvents.pipe(
568 Stream.filter(
569 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
570 ),
571 Stream.take(1),
572 Stream.runDrain,
573 Effect.forkScoped,
574 );
575 yield* orchestrator.dispatch({
576 type: "message.dispatch",
577 commandId: CommandId.make("first"),
578 threadId,
579 messageId: MessageId.make("message:first"),
580 text: "first",
581 attachments: [],
582 modelSelection: runSelection,
583 dispatchMode: { type: "start_immediately" },
584 createdBy: "user",
585 creationSource: "web",
586 });
587 yield* worker.drain();
588 yield* Fiber.join(running);
589 return threadId;
590 });
591 return { cwd, events, started, steered, layer, startFirstTurn };
592});
593​
594it.effect("sends a selected held message once and preserves the remaining queue order", () =>
595 Effect.scoped(
596 Effect.gen(function* () {
597 const { started, steered, layer, startFirstTurn } =
598 yield* nextTurnSelectionHarness("send-held-message");
599 yield* Effect.gen(function* () {
600 const orchestrator = yield* Orchestrator.OrchestratorV2;
601 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
602 const threadId = yield* startFirstTurn;
603 yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
604 orchestrator.dispatch({
605 type: "message.dispatch",
606 commandId: CommandId.make(text),
607 threadId,
608 messageId: MessageId.make(`message:${text}`),
609 text,
610 attachments: [],
611 modelSelection: runSelection,
612 dispatchMode: { type: "queue_after_active" },
613 createdBy: "user",
614 creationSource: "web",
615 }),
616 );
617 const before = yield* orchestrator.getThreadProjection(threadId);
618 const selected = before.runs.find(
619 (run) => run.userMessageId === MessageId.make("message:selected"),
620 )!;
621 const sink = yield* EventSink.EventSinkV2;
622 const now = yield* DateTime.now;
623 // Restart recovery cancels the active run and holds every queued message.
624 yield* sink.write({
625 events: [
626 ...before.runs.map((run) => ({
627 id: EventId.make(`restart:${run.id}`),
628 type: "run.updated" as const,
629 threadId,
630 runId: run.id,
631 occurredAt: now,
632 payload:
633 run.status === "queued"
634 ? { ...run, queueHeld: true }
635 : { ...run, status: "cancelled" as const, completedAt: now },
636 })),
637 ...before.providerTurns.map((turn) => ({
638 id: EventId.make(`restart:${turn.id}`),
639 type: "provider-turn.updated" as const,
640 threadId,
641 occurredAt: now,
642 payload: { ...turn, status: "cancelled" as const, completedAt: now },
643 })),
644 ],
645 });
646 const command = {
647 type: "queued-run.start" as const,
648 commandId: CommandId.make("send-selected"),
649 threadId,
650 runId: selected.id,
651 };
652 yield* orchestrator.dispatch(command);
653 yield* worker.drain();
654 yield* orchestrator.dispatch(command);
655 yield* worker.drain();
656 const after = yield* orchestrator.getThreadProjection(threadId);
657 assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
658 assert.deepEqual(
659 started.map((input) => input.message.text),
660 ["first", "selected"],
661 );
662 assert.equal(started[1]?.runId, selected.id);
663 assert.equal(started[1]?.message.messageId, selected.userMessageId);
664 assert.deepEqual(started[1]?.modelSelection, runSelection);
665 assert.deepEqual(steered, []);
666 assert.lengthOf(
667 after.messages.filter((message) => message.id === selected.userMessageId),
668 1,
669 );
670 assert.deepEqual(
671 after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
672 [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
673 );
674 assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
675 const duplicate = yield* orchestrator
676 .dispatch({
677 ...command,
678 commandId: CommandId.make("send-selected-again"),
679 })
680 .pipe(Effect.flip);
681 assert.equal(duplicate._tag, "OrchestratorDispatchError");
682 }).pipe(Effect.provide(layer));
683 }),
684 ),
685);
686​
687it.effect("force sends multiple queued messages and can force send a requeued message again", () =>
688 Effect.scoped(
689 Effect.gen(function* () {
690 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
691 "multiple-promoted-messages",
692 );
693 yield* Effect.gen(function* () {
694 const orchestrator = yield* Orchestrator.OrchestratorV2;
695 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
696 const threadId = yield* startFirstTurn;
697 const queue = (text: string, commandId: string) =>
698 orchestrator.dispatch({
699 type: "message.dispatch",
700 commandId: CommandId.make(commandId),
701 threadId,
702 messageId: MessageId.make(`message:${text}`),
703 text,
704 attachments: [],
705 dispatchMode: { type: "queue_after_active" },
706 createdBy: "user",
707 creationSource: "web",
708 });
709 for (const text of ["one", "two", "remaining"]) yield* queue(text, `queue-${text}`);
710 const promote = Effect.fn("test.promote")(function* (text: string, commandId: string) {
711 const projection = yield* orchestrator.getThreadProjection(threadId);
712 const queued = projection.runs.find(
713 (run) =>
714 run.status === "queued" && run.userMessageId === MessageId.make(`message:${text}`),
715 )!;
716 yield* orchestrator.dispatch({
717 type: "queued-message.promote-to-steer",
718 commandId: CommandId.make(commandId),
719 threadId,
720 queuedRunId: queued.id,
721 targetRunId: started[0]!.runId,
722 });
723 });
724 yield* promote("one", "promote-one");
725 yield* promote("two", "promote-two");
726 yield* worker.drain();
727 assert.deepEqual(steered, ["one", "two"]);
728​
729 // The completion-race fallback redispatches the same message into the queue.
730 yield* queue("one", "requeue-one");
731 const requeued = yield* orchestrator.getThreadProjection(threadId);
732 assert.equal(
733 requeued.turnItems.find(
734 (item) => item.type === "user_message" && item.messageId === "message:one",
735 )?.status,
736 "pending",
737 );
738 yield* promote("one", "promote-one-again");
739 yield* worker.drain();
740 assert.deepEqual(steered, ["one", "two", "one"]);
741 assert.lengthOf(started, 1);
742 const final = yield* orchestrator.getThreadProjection(threadId);
743 assert.deepEqual(
744 final.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
745 [MessageId.make("message:remaining")],
746 );
747 for (const text of ["one", "two"]) {
748 const items = final.turnItems.filter(
749 (item) => item.type === "user_message" && item.messageId === `message:${text}`,
750 );
751 assert.lengthOf(items, 1);
752 assert.equal(items[0]?.status, "completed");
753 }
754 }).pipe(Effect.provide(layer));
755 }),
756 ),
757);
758​
759it.effect("keeps a message queued when send now races with a running turn", () =>
760 Effect.scoped(
761 Effect.gen(function* () {
762 const { started, layer, startFirstTurn } =
763 yield* nextTurnSelectionHarness("send-queued-race");
764 yield* Effect.gen(function* () {
765 const orchestrator = yield* Orchestrator.OrchestratorV2;
766 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
767 const threadId = yield* startFirstTurn;
768 yield* orchestrator.dispatch({
769 type: "message.dispatch",
770 commandId: CommandId.make("queue"),
771 threadId,
772 messageId: MessageId.make("message:queued"),
773 text: "queued",
774 attachments: [],
775 dispatchMode: { type: "queue_after_active" },
776 createdBy: "user",
777 creationSource: "web",
778 });
779 const before = yield* orchestrator.getThreadProjection(threadId);
780 const queued = before.runs.find((run) => run.status === "queued")!;
781 const error = yield* orchestrator
782 .dispatch({
783 type: "queued-run.start",
784 commandId: CommandId.make("send-now"),
785 threadId,
786 runId: queued.id,
787 })
788 .pipe(Effect.flip);
789 yield* worker.drain();
790 assert.equal(error._tag, "OrchestratorDispatchError");
791 assert.equal(started.length, 1);
792 const after = yield* orchestrator.getThreadProjection(threadId);
793 assert.deepEqual(after.runs, before.runs);
794 }).pipe(Effect.provide(layer));
795 }),
796 ),
797);
798​
799// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
800it.effect(
801 "steers a changed turn-scoped selection into a running turn the provider could restart",
802 () =>
803 Effect.scoped(
804 Effect.gen(function* () {
805 const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
806 "steering-selection-change",
807 true,
808 );
809 yield* Effect.gen(function* () {
810 const orchestrator = yield* Orchestrator.OrchestratorV2;
811 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
812 const threadId = yield* startFirstTurn;
813 const steer = (id: string, selection: ModelSelection) =>
814 orchestrator
815 .dispatch({
816 type: "message.dispatch",
817 commandId: CommandId.make(id),
818 threadId,
819 messageId: MessageId.make(`message:${id}`),
820 text: id,
821 attachments: [],
822 modelSelection: selection,
823 dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId },
824 createdBy: "user",
825 creationSource: "web",
826 })
827 .pipe(Effect.andThen(worker.drain()));
828​
829 yield* steer("steer-changed", composerSelection);
830 const changed = yield* orchestrator.getThreadProjection(threadId);
831 assert.deepEqual(steered, ["steer-changed"]);
832 assert.equal(started.length, 1);
833 assert.lengthOf(changed.attempts, 1);
834 assert.equal(changed.runs[0]?.status, "running");
835 assert.deepEqual(changed.runs[0]?.modelSelection, runSelection);
836 assert.deepEqual(changed.thread.modelSelection, composerSelection);
837​
838 yield* steer("steer-reverted", runSelection);
839 const reverted = yield* orchestrator.getThreadProjection(threadId);
840 assert.deepEqual(steered, ["steer-changed", "steer-reverted"]);
841 assert.lengthOf(reverted.attempts, 1);
842 assert.deepEqual(reverted.thread.modelSelection, runSelection);
843​
844 const otherSelection = {
845 instanceId: ProviderInstanceId.make("codex-work"),
846 model: "other",
847 };
848 const sink = yield* EventSink.EventSinkV2;
849 yield* sink.write({
850 events: [
851 {
852 id: EventId.make("switched-away"),
853 type: "thread.provider-switched",
854 threadId,
855 providerInstanceId: otherSelection.instanceId,
856 occurredAt: yield* DateTime.now,
857 payload: {
858 ...reverted.thread,
859 providerInstanceId: otherSelection.instanceId,
860 modelSelection: otherSelection,
861 },
862 },
863 ],
864 });
865 yield* steer("steer-back", runSelection);
866 const back = yield* orchestrator.getThreadProjection(threadId);
867 assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]);
868 assert.equal(back.thread.providerInstanceId, instanceId);
869 assert.deepEqual(back.thread.modelSelection, runSelection);
870 }).pipe(Effect.provide(layer));
871 }),
872 ),
873);
874​
875it.effect("starts a steer that missed the turn on the saved next-turn selection", () =>
876 Effect.scoped(
877 Effect.gen(function* () {
878 const { events, started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness(
879 "steering-selection-follow-up",
880 );
881 yield* Effect.gen(function* () {
882 const orchestrator = yield* Orchestrator.OrchestratorV2;
883 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
884 const threadId = yield* startFirstTurn;
885 const first = started[0]!;
886 yield* orchestrator.dispatch({
887 type: "message.dispatch",
888 commandId: CommandId.make("steer"),
889 threadId,
890 messageId: MessageId.make("message:steer"),
891 text: "late steer",
892 attachments: [],
893 modelSelection: composerSelection,
894 dispatchMode: { type: "steer_active", targetRunId: first.runId },
895 createdBy: "user",
896 creationSource: "web",
897 });
898 const settled = yield* orchestrator.streamDomainEvents.pipe(
899 Stream.filter(
900 (event) =>
901 event.type === "run.updated" &&
902 event.payload.id === first.runId &&
903 event.payload.status === "waiting",
904 ),
905 Stream.take(1),
906 Stream.runDrain,
907 Effect.forkScoped,
908 );
909 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
910 yield* Queue.offer(events, {
911 type: "provider_turn.updated",
912 driver,
913 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
914 });
915 yield* Queue.offer(events, {
916 type: "turn.terminal",
917 driver,
918 providerThreadId: turn.providerThreadId,
919 providerTurnId: turn.id,
920 runOrdinal: first.runOrdinal,
921 status: "completed",
922 failure: null,
923 threadDisposition: "reusable",
924 });
925 yield* Fiber.join(settled);
926 yield* worker.drain();
927 yield* orchestrator.resumeQueuedRuns;
928 yield* worker.drain();
929​
930 const projection = yield* orchestrator.getThreadProjection(threadId);
931 assert.deepEqual(steered, []);
932 assert.equal(started.length, 2);
933 assert.equal(started[1]?.message.messageId, MessageId.make("message:steer"));
934 assert.deepEqual(started[1]?.modelSelection, composerSelection);
935 assert.deepEqual(projection.thread.modelSelection, composerSelection);
936 }).pipe(Effect.provide(layer));
937 }),
938 ),
939);
940​
941// Codex flushes held drafts after the final answer; reserve their pre-steer position before turn end.
942it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
943 Effect.scoped(
944 Effect.gen(function* () {
945 const { events, started, layer, startFirstTurn } =
946 yield* nextTurnSelectionHarness("steering-held-draft");
947 yield* Effect.gen(function* () {
948 const orchestrator = yield* Orchestrator.OrchestratorV2;
949 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
950 const threadId = yield* startFirstTurn;
951 const first = started[0]!;
952 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
953 const now = yield* DateTime.now;
954 const assistantItem = (id: string, text: string, streaming: boolean) =>
955 ({
956 type: "turn_item.updated",
957 driver,
958 turnItem: {
959 id: TurnItemId.make(id),
960 threadId,
961 runId: first.runId,
962 nodeId: first.rootNodeId,
963 providerThreadId: turn.providerThreadId,
964 providerTurnId: turn.id,
965 nativeItemRef: null,
966 parentItemId: null,
967 ordinal: 0,
968 status: streaming ? "running" : "completed",
969 title: null,
970 startedAt: now,
971 completedAt: streaming ? null : now,
972 updatedAt: now,
973 type: "assistant_message",
974 messageId: MessageId.make(`message:${id}`),
975 text,
976 streaming,
977 },
978 }) satisfies ProviderAdapter.ProviderAdapterV2Event;
979 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
980 orchestrator.streamDomainEvents.pipe(
981 Stream.filter(predicate),
982 Stream.take(1),
983 Stream.runDrain,
984 Effect.forkScoped,
985 );
986​
987 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
988 const commentaryWritten = yield* watch(
989 (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
990 );
991 yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
992 yield* Fiber.join(commentaryWritten);
993​
994 yield* orchestrator.dispatch({
995 type: "message.dispatch",
996 commandId: CommandId.make("steer"),
997 threadId,
998 messageId: MessageId.make("message:steer"),
999 text: "fix the popover",
1000 attachments: [],
1001 dispatchMode: { type: "steer_active", targetRunId: first.runId },
1002 createdBy: "user",
1003 creationSource: "web",
1004 });
1005 yield* worker.drain();
1006​
1007 const settled = yield* watch(
1008 (event) =>
1009 event.type === "run.updated" &&
1010 event.payload.id === first.runId &&
1011 event.payload.status === "waiting",
1012 );
1013 yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
1014 yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
1015 yield* Queue.offer(events, {
1016 type: "provider_turn.updated",
1017 driver,
1018 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1019 });
1020 yield* Queue.offer(events, {
1021 type: "turn.terminal",
1022 driver,
1023 providerThreadId: turn.providerThreadId,
1024 providerTurnId: turn.id,
1025 runOrdinal: first.runOrdinal,
1026 status: "completed",
1027 failure: null,
1028 threadDisposition: "reusable",
1029 });
1030 yield* Fiber.join(settled);
1031 yield* worker.drain();
1032​
1033 const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
1034 .toSorted((left, right) => left.ordinal - right.ordinal)
1035 .flatMap((item) =>
1036 item.type === "user_message"
1037 ? [String(item.messageId)]
1038 : item.type === "assistant_message"
1039 ? [String(item.id)]
1040 : [],
1041 );
1042 assert.deepEqual(items, [
1043 "message:first",
1044 "draft",
1045 "commentary",
1046 "message:steer",
1047 "answer",
1048 ]);
1049 }).pipe(Effect.provide(layer));
1050 }),
1051 ),
1053​
1054it.effect("keeps a queued message queued when promoted into a run that Stop reached", () =>
1055 Effect.scoped(
1056 Effect.gen(function* () {
1057 const { started, steered, layer, startFirstTurn } =
1058 yield* nextTurnSelectionHarness("steering-after-stop");
1059 yield* Effect.gen(function* () {
1060 const orchestrator = yield* Orchestrator.OrchestratorV2;
1061 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1062 const threadId = yield* startFirstTurn;
1063 const first = started[0]!;
1064 yield* orchestrator.dispatch({
1065 type: "message.dispatch",
1066 commandId: CommandId.make("queued"),
1067 threadId,
1068 messageId: MessageId.make("message:queued"),
1069 text: "queued",
1070 attachments: [],
1071 modelSelection: runSelection,
1072 dispatchMode: { type: "queue_after_active" },
1073 createdBy: "user",
1074 creationSource: "web",
1075 });
1076 const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1077 (run) => run.status === "queued",
1078 )!;
1079 // The worker has not delivered the interrupt yet, so the run still reads as running.
1080 yield* orchestrator.dispatch({
1081 type: "run.interrupt",
1082 commandId: CommandId.make("stop"),
1083 threadId,
1084 runId: first.runId,
1085 holdQueue: true,
1086 });
1087​
1088 const promoteError = yield* orchestrator
1089 .dispatch({
1090 type: "queued-message.promote-to-steer",
1091 commandId: CommandId.make("promote"),
1092 threadId,
1093 queuedRunId: queuedRun.id,
1094 targetRunId: first.runId,
1095 })
1096 .pipe(Effect.flip);
1097 yield* worker.drain();
1098​
1099 const projection = yield* orchestrator.getThreadProjection(threadId);
1100 assert.equal(promoteError._tag, "OrchestratorDispatchError");
1101 assert.deepEqual(steered, []);
1102 const queued = projection.runs.find((run) => run.id === queuedRun.id);
1103 assert.equal(queued?.status, "queued");
1104 assert.isTrue(queued?.queueHeld);
1105 }).pipe(Effect.provide(layer));
1106 }),
1107 ),
1109​
1110it.effect("queues a plain send behind the stopped queue and releases its hold", () =>
1111 Effect.scoped(
1112 Effect.gen(function* () {
1113 const { started, steered, layer, startFirstTurn } =
1114 yield* nextTurnSelectionHarness("plain-send-after-stop");
1115 yield* Effect.gen(function* () {
1116 const orchestrator = yield* Orchestrator.OrchestratorV2;
1117 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1118 const threadId = yield* startFirstTurn;
1119 const send = (id: string, delivery: "queue" | "auto") =>
1120 orchestrator.dispatch({
1121 type: "message.dispatch",
1122 commandId: CommandId.make(id),
1123 threadId,
1124 messageId: MessageId.make(`message:${id}`),
1125 text: id,
1126 attachments: [],
1127 modelSelection: runSelection,
1128 ...(delivery === "queue"
1129 ? { dispatchMode: { type: "queue_after_active" } }
1130 : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
1131 createdBy: "user",
1132 creationSource: "web",
1133 });
1134 yield* send("queued", "queue");
1135 yield* orchestrator.dispatch({
1136 type: "run.interrupt",
1137 commandId: CommandId.make("stop"),
1138 threadId,
1139 runId: started[0]!.runId,
1140 holdQueue: true,
1141 });
1142 // The provider has not stopped yet, so a plain send still resolves to a steer.
1143 yield* send("sent", "auto");
1144 yield* worker.drain();
1145​
1146 const projection = yield* orchestrator.getThreadProjection(threadId);
1147 assert.deepEqual(steered, []);
1148 assert.equal(started.length, 1);
1149 const queued = projection.runs
1150 .filter((run) => run.status === "queued")
1151 .sort((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0));
1152 assert.deepEqual(
1153 queued.map(
1154 (run) => projection.messages.find((message) => message.id === run.userMessageId)?.text,
1155 ),
1156 ["queued", "sent"],
1157 );
1158 // The user sent it, so the queue they stopped runs again once the provider stops.
1159 assert.isFalse(queued.some((run) => run.queueHeld === true));
1160 }).pipe(Effect.provide(layer));
1161 }),
1162 ),
1164​
1165const goalHarness = Effect.fn("goalHarness")(function* (name: string) {
1166 const harness = yield* nextTurnSelectionHarness(name);
1167 const send = (id: string, text: string, delivery: "queue" | "auto") =>
1168 Effect.gen(function* () {
1169 const orchestrator = yield* Orchestrator.OrchestratorV2;
1170 yield* orchestrator.dispatch({
1171 type: "message.dispatch",
1172 commandId: CommandId.make(id),
1173 threadId: ThreadId.make(`thread:${name}`),
1174 messageId: MessageId.make(`message:${id}`),
1175 text,
1176 attachments: [],
1177 modelSelection: runSelection,
1178 ...(delivery === "queue"
1179 ? { dispatchMode: { type: "queue_after_active" } }
1180 : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }),
1181 createdBy: "user",
1182 creationSource: "web",
1183 });
1184 });
1185 const read = (threadId: ThreadId) =>
1186 Effect.gen(function* () {
1187 const projection = yield* (yield* Orchestrator.OrchestratorV2).getThreadProjection(threadId);
1188 const textOf = (run: (typeof projection.runs)[number]) =>
1189 projection.messages.find((message) => message.id === run.userMessageId)?.text;
1190 return {
1191 queue: projection.runs
1192 .filter((run) => run.status === "queued")
1193 .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0))
1194 .map(textOf),
1195 started: harness.started.map((turn) => turn.message.text),
1196 stopRequested: projection.turnItems.some(
1197 (item) =>
1198 item.type === "run_interrupt_request" && item.runId === harness.started[0]?.runId,
1199 ),
1200 };
1201 });
1202 return { ...harness, send, read };
1203});
1204​
1205it.effect("stops the running turn and starts a goal sent into it next", () =>
1206 Effect.scoped(
1207 Effect.gen(function* () {
1208 const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-steer");
1209 yield* Effect.gen(function* () {
1210 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1211 const threadId = yield* startFirstTurn;
1212 yield* send("queued", "queued", "queue");
1213 yield* send("goal", "/goal all tests pass", "auto");
1214 yield* worker.drain();
1215​
1216 assert.deepEqual(steered, []);
1217 assert.deepEqual(yield* read(threadId), {
1218 queue: ["queued"],
1219 started: ["first", "/goal all tests pass"],
1220 stopRequested: true,
1221 });
1222 }).pipe(Effect.provide(layer));
1223 }),
1224 ),
1226​
1227it.effect("queues a goal clear without stopping work when no goal drives it", () =>
1228 Effect.scoped(
1229 Effect.gen(function* () {
1230 const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-clear");
1231 yield* Effect.gen(function* () {
1232 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1233 const threadId = yield* startFirstTurn;
1234 yield* send("queued", "queued", "queue");
1235 yield* send("clear", "/goal clear", "auto");
1236 yield* worker.drain();
1237​
1238 assert.deepEqual(steered, []);
1239 assert.deepEqual(yield* read(threadId), {
1240 queue: ["queued", "/goal clear"],
1241 started: ["first"],
1242 stopRequested: false,
1243 });
1244 }).pipe(Effect.provide(layer));
1245 }),
1246 ),
1248​
1249it.effect("promotes a queued goal by stopping the running turn", () =>
1250 Effect.scoped(
1251 Effect.gen(function* () {
1252 const { started, steered, layer, startFirstTurn, send, read } =
1253 yield* goalHarness("goal-promote");
1254 yield* Effect.gen(function* () {
1255 const orchestrator = yield* Orchestrator.OrchestratorV2;
1256 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1257 const threadId = yield* startFirstTurn;
1258 yield* send("queued", "queued", "queue");
1259 yield* send("goal", "/goal ship it", "queue");
1260 const goalRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1261 (run) => run.userMessageId === MessageId.make("message:goal"),
1262 )!;
1263 yield* orchestrator.dispatch({
1264 type: "queued-message.promote-to-steer",
1265 commandId: CommandId.make("promote"),
1266 threadId,
1267 queuedRunId: goalRun.id,
1268 targetRunId: started[0]!.runId,
1269 });
1270 yield* worker.drain();
1271​
1272 assert.deepEqual(steered, []);
1273 assert.deepEqual(yield* read(threadId), {
1274 queue: ["queued"],
1275 started: ["first", "/goal ship it"],
1276 stopRequested: true,
1277 });
1278 }).pipe(Effect.provide(layer));
1279 }),
1280 ),
1282​
1283it.effect.each(["next", "/goal ship it"])(
1284 "promoting %s into a compaction stops it and sends it next",
1285 (promoted) =>
1286 Effect.scoped(
1287 Effect.gen(function* () {
1288 const { events, layer, send, read, started, steered, startFirstTurn } = yield* goalHarness(
1289 `compaction-promote-${promoted.length}`,
1290 );
1291 yield* Effect.gen(function* () {
1292 const orchestrator = yield* Orchestrator.OrchestratorV2;
1293 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1294 const threadId = yield* startFirstTurn;
1295 yield* send("compact", "/compact", "queue");
1296 yield* send("queued", "queued", "queue");
1297 yield* send("next", promoted, "queue");
1298 const settled = yield* orchestrator.streamDomainEvents.pipe(
1299 Stream.filter(
1300 (event) =>
1301 event.type === "run.updated" &&
1302 event.payload.id === started[0]!.runId &&
1303 event.payload.status === "waiting",
1304 ),
1305 Stream.take(1),
1306 Stream.runDrain,
1307 Effect.forkScoped,
1308 );
1309 const compacting = yield* orchestrator.streamDomainEvents.pipe(
1310 Stream.filter(
1311 (event) =>
1312 event.type === "provider-turn.updated" &&
1313 event.payload.status === "running" &&
1314 event.payload.runAttemptId !== started[0]!.attemptId,
1315 ),
1316 Stream.take(1),
1317 Stream.runDrain,
1318 Effect.forkScoped,
1319 );
1320 const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
1321 yield* Queue.offer(events, {
1322 type: "provider_turn.updated",
1323 driver,
1324 providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
1325 });
1326 yield* Queue.offer(events, {
1327 type: "turn.terminal",
1328 driver,
1329 providerThreadId: turn.providerThreadId,
1330 providerTurnId: turn.id,
1331 runOrdinal: started[0]!.runOrdinal,
1332 status: "completed",
1333 failure: null,
1334 threadDisposition: "reusable",
1335 });
1336 yield* Fiber.join(settled);
1337 yield* worker.drain();
1338 yield* orchestrator.resumeQueuedRuns;
1339 yield* worker.drain();
1340 yield* Fiber.join(compacting);
1341 const compactRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1342 (run) => run.userMessageId === MessageId.make("message:compact"),
1343 )!;
1344 const nextRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1345 (run) => run.userMessageId === MessageId.make("message:next"),
1346 )!;
1347 yield* orchestrator.dispatch({
1348 type: "queued-message.promote-to-steer",
1349 commandId: CommandId.make("promote"),
1350 threadId,
1351 queuedRunId: nextRun.id,
1352 targetRunId: compactRun.id,
1353 });
1354 yield* worker.drain();
1355​
1356 const projection = yield* orchestrator.getThreadProjection(threadId);
1357 assert.deepEqual(steered, []);
1358 assert.isTrue(
1359 projection.turnItems.some(
1360 (item) => item.type === "run_interrupt_request" && item.runId === compactRun.id,
1361 ),
1362 );
1363 assert.deepEqual((yield* read(threadId)).queue, ["queued"]);
1364 assert.deepEqual(
1365 started.map((turn) => turn.message.text),
1366 ["first", "/compact", promoted],
1367 );
1368 }).pipe(Effect.provide(layer));
1369 }),
1370 ),
1372​
1373it.effect("stops a turn that is still starting when a goal is sent into it", () =>
1374 Effect.scoped(
1375 Effect.gen(function* () {
1376 const { cwd, layer, send, started } = yield* goalHarness("goal-during-start");
1377 yield* Effect.gen(function* () {
1378 const orchestrator = yield* Orchestrator.OrchestratorV2;
1379 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1380 const threadId = ThreadId.make("thread:goal-during-start");
1381 yield* orchestrator.dispatch({
1382 type: "thread.create",
1383 commandId: CommandId.make("create"),
1384 threadId,
1385 projectId: ProjectId.make("project:goal-during-start"),
1386 title: "Goal during start",
1387 modelSelection: runSelection,
1388 runtimeMode: "full-access",
1389 interactionMode: "default",
1390 branch: null,
1391 worktreePath: cwd,
1392 createdBy: "user",
1393 creationSource: "web",
1394 });
1395 // The stopped run's end starts the queue, which then needs one more drain.
1396 const goalStarting = yield* orchestrator.streamDomainEvents.pipe(
1397 Stream.filter(
1398 (event) => event.type === "run.updated" && event.payload.status === "starting",
1399 ),
1400 Stream.take(1),
1401 Stream.runDrain,
1402 Effect.forkScoped({ startImmediately: true }),
1403 );
1404 yield* send("first", "first", "auto");
1405 yield* send("goal", "/goal all tests pass", "auto");
1406 yield* worker.drain();
1407 yield* Fiber.join(goalStarting);
1408 yield* worker.drain();
1409​
1410 const projection = yield* orchestrator.getThreadProjection(threadId);
1411 const statusOf = (text: string) =>
1412 projection.runs.find(
1413 (run) =>
1414 projection.messages.find((message) => message.id === run.userMessageId)?.text ===
1415 text,
1416 )?.status;
1417 assert.equal(statusOf("first"), "interrupted");
1418 assert.deepEqual(
1419 started.map((turn) => turn.message.text),
1420 ["/goal all tests pass"],
1421 );
1422 }).pipe(Effect.provide(layer));
1423 }),
1424 ),
1426​
1427it.effect("stops the running turn when a goal clear ends the goal driving it", () =>
1428 Effect.scoped(
1429 Effect.gen(function* () {
1430 const { events, layer, startFirstTurn, send, read, steered } =
1431 yield* goalHarness("goal-clear-active");
1432 yield* Effect.gen(function* () {
1433 const orchestrator = yield* Orchestrator.OrchestratorV2;
1434 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1435 const threadId = yield* startFirstTurn;
1436 const providerThread = (yield* orchestrator.getThreadProjection(threadId))
1437 .providerThreads[0]!;
1438 const goalSeen = yield* orchestrator.streamDomainEvents.pipe(
1439 Stream.filter(
1440 (event) =>
1441 event.type === "provider-thread.updated" && event.payload.goal?.status === "active",
1442 ),
1443 Stream.take(1),
1444 Stream.runDrain,
1445 Effect.forkScoped({ startImmediately: true }),
1446 );
1447 yield* Queue.offer(events, {
1448 type: "provider_thread.updated",
1449 driver,
1450 providerThread: {
1451 ...providerThread,
1452 goal: { objective: "all tests pass", status: "active" },
1453 },
1454 });
1455 yield* Fiber.join(goalSeen);
1456 yield* send("clear", "/goal clear", "auto");
1457 yield* worker.drain();
1458​
1459 assert.deepEqual(steered, []);
1460 assert.deepEqual(yield* read(threadId), {
1461 queue: [],
1462 started: ["first", "/goal clear"],
1463 stopRequested: true,
1464 });
1465 }).pipe(Effect.provide(layer));
1466 }),
1467 ),