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

BackgroundWorkStop.integration.test.ts

601 lines22.0 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16 type OrchestrationV2DomainEvent,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
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 type {
28 ProviderAdapterV2Event,
29 ProviderAdapterV2InterruptInput,
30 ProviderAdapterV2Shape,
31 ProviderAdapterV2TurnInput,
32} from "./ProviderAdapter.ts";
33import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
34import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
35import { checkpointWorkspace } from "./testkit/ReplayFixtureWorkspace.ts";
36​
37const driver = ProviderDriverKind.make("codex");
38const instanceId = ProviderInstanceId.make("codex");
39const modelSelection = { instanceId, model: "test-model" };
40​
41// Codex turns leave commands running, then the thread moves to another
42// provider thread (a provider switch). Stop must end all of the Codex work,
43// including when it selects an older resumed run on the other provider thread.
44const stopEarlierBackgroundWork = ({
45 failedStart = false,
46 stopWithQueue,
47 olderStart = false,
48}: {
49 readonly failedStart?: boolean;
50 readonly stopWithQueue?: "thread.stop" | "run.interrupt";
51 readonly olderStart?: boolean;
52}) =>
53 Effect.scoped(
54 Effect.gen(function* () {
55 const cwd = yield* checkpointWorkspace("background-work-stop");
56 const events = yield* Queue.unbounded<ProviderAdapterV2Event>();
57 const started: ProviderAdapterV2TurnInput[] = [];
58 const interrupts: ProviderAdapterV2InterruptInput[] = [];
59 const adapter: ProviderAdapterV2Shape = {
60 instanceId,
61 driver,
62 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
63 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
64 openSession: (input) =>
65 Effect.gen(function* () {
66 const now = yield* DateTime.now;
67 return {
68 instanceId,
69 driver,
70 providerSessionId: input.providerSessionId,
71 providerSession: {
72 id: input.providerSessionId,
73 driver,
74 providerInstanceId: instanceId,
75 status: "ready",
76 cwd,
77 model: modelSelection.model,
78 capabilities: CodexProviderCapabilitiesV2,
79 createdAt: now,
80 updatedAt: now,
81 lastError: null,
82 },
83 events: Stream.fromQueue(events),
84 ensureThread: ({ threadId }) =>
85 Effect.succeed({
86 id: ProviderThreadId.make(`provider-thread:codex:${threadId}`),
87 driver,
88 providerInstanceId: instanceId,
89 providerSessionId: input.providerSessionId,
90 appThreadId: threadId,
91 ownerNodeId: null,
92 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
93 nativeConversationHeadRef: null,
94 status: "idle",
95 firstRunOrdinal: null,
96 lastRunOrdinal: null,
97 handoffIds: [],
98 forkedFrom: null,
99 createdAt: now,
100 updatedAt: now,
101 }),
102 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
103 startTurn: (turn) =>
104 Effect.gen(function* () {
105 started.push(turn);
106 yield* Queue.offer(events, {
107 type: "provider_turn.updated",
108 driver,
109 providerTurn: {
110 id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`),
111 providerThreadId: turn.providerThread.id,
112 nodeId: turn.rootNodeId,
113 runAttemptId: turn.attemptId,
114 nativeTurnRef: {
115 driver,
116 nativeId: `native:${turn.attemptId}`,
117 strength: "strong",
118 },
119 ordinal: turn.providerTurnOrdinal,
120 status: "running",
121 startedAt: now,
122 completedAt: null,
123 },
124 });
125 }),
126 steerTurn: () => Effect.die("unused"),
127 interruptTurn: (interrupt) =>
128 Effect.sync(() => {
129 interrupts.push(interrupt);
130 }),
131 respondToRuntimeRequest: () => Effect.die("unused"),
132 readThreadSnapshot: () => Effect.die("unused"),
133 rollbackThread: () => Effect.die("unused"),
134 forkThread: () => Effect.die("unused"),
135 };
136 }),
137 };
138 yield* Effect.gen(function* () {
139 const orchestrator = yield* Orchestrator.OrchestratorV2;
140 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
141 const sink = yield* EventSink.EventSinkV2;
142 const threadId = ThreadId.make("thread:background-work-stop");
143 const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
144 orchestrator.streamDomainEvents.pipe(
145 Stream.filter(predicate),
146 Stream.take(1),
147 Stream.runDrain,
148 Effect.forkScoped,
149 );
150 yield* orchestrator.dispatch({
151 type: "thread.create",
152 commandId: CommandId.make("create"),
153 threadId,
154 projectId: ProjectId.make("project:background-work-stop"),
155 title: "Background work stop",
156 modelSelection,
157 runtimeMode: "full-access",
158 interactionMode: "default",
159 branch: null,
160 worktreePath: cwd,
161 createdBy: "user",
162 creationSource: "web",
163 });
164 const running = yield* watch(
165 (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
166 );
167 yield* orchestrator.dispatch({
168 type: "message.dispatch",
169 commandId: CommandId.make("start-dev-server"),
170 threadId,
171 messageId: MessageId.make("message:start-dev-server"),
172 text: "Start the dev server",
173 attachments: [],
174 dispatchMode: { type: "start_immediately" },
175 createdBy: "user",
176 creationSource: "web",
177 });
178 yield* worker.drain();
179 yield* Fiber.join(running);
180 const first = started[0]!;
181 const codexTurn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
182 const devServerId = TurnItemId.make("turn-item:dev-server");
183 const now = yield* DateTime.now;
184 yield* sink.write({
185 events: [
186 {
187 id: EventId.make("dev-server"),
188 type: "turn-item.updated",
189 threadId,
190 runId: first.runId,
191 occurredAt: now,
192 payload: {
193 id: devServerId,
194 threadId,
195 runId: first.runId,
196 nodeId: first.rootNodeId,
197 providerThreadId: codexTurn.providerThreadId,
198 providerTurnId: codexTurn.id,
199 nativeItemRef: null,
200 parentItemId: null,
201 ordinal: 100,
202 status: "running",
203 title: null,
204 startedAt: now,
205 completedAt: null,
206 updatedAt: now,
207 type: "command_execution",
208 input: "vp run dev --share",
209 },
210 },
211 ],
212 });
213 const settled = yield* watch(
214 (event) =>
215 event.type === "run.updated" &&
216 event.payload.id === first.runId &&
217 event.payload.status === "waiting",
218 );
219 yield* Queue.offer(events, {
220 type: "provider_turn.updated",
221 driver,
222 providerTurn: { ...codexTurn, status: "completed", completedAt: now },
223 });
224 yield* Queue.offer(events, {
225 type: "turn.terminal",
226 driver,
227 providerThreadId: codexTurn.providerThreadId,
228 providerTurnId: codexTurn.id,
229 runOrdinal: first.runOrdinal,
230 status: "completed",
231 failure: null,
232 threadDisposition: "reusable",
233 });
234 yield* Fiber.join(settled);
235 yield* worker.drain();
236​
237 const codexProviderThread = (yield* orchestrator.getThreadProjection(threadId))
238 .providerThreads[0]!;
239 // A settled run with its root node, attempt, provider turn and,
240 // optionally, a command or native subagent it left running.
241 const settledRun = (input: {
242 readonly ordinal: number;
243 readonly providerThreadId: ProviderThreadId;
244 readonly runningItem?: {
245 readonly id: TurnItemId;
246 readonly kind: "command" | "subagent";
247 };
248 }) => {
249 const runId = RunId.make(`run:${input.ordinal}`);
250 const attemptId = RunAttemptId.make(`attempt:${input.ordinal}`);
251 const nodeId = NodeId.make(`node:${input.ordinal}`);
252 const providerTurnId = ProviderTurnId.make(`provider-turn:${input.ordinal}`);
253 const events: Array<OrchestrationV2DomainEvent> = [
254 {
255 id: EventId.make(`run:${input.ordinal}`),
256 type: "run.created",
257 threadId,
258 occurredAt: now,
259 payload: {
260 id: runId,
261 threadId,
262 ordinal: input.ordinal,
263 providerInstanceId: instanceId,
264 modelSelection,
265 providerThreadId: input.providerThreadId,
266 userMessageId: MessageId.make(`message:${input.ordinal}`),
267 rootNodeId: nodeId,
268 activeAttemptId: attemptId,
269 status: "completed",
270 requestedAt: now,
271 startedAt: now,
272 completedAt: now,
273 checkpointId: null,
274 contextHandoffId: null,
275 },
276 },
277 {
278 id: EventId.make(`node:${input.ordinal}`),
279 type: "node.updated",
280 threadId,
281 runId,
282 occurredAt: now,
283 payload: {
284 id: nodeId,
285 threadId,
286 runId,
287 parentNodeId: null,
288 rootNodeId: nodeId,
289 kind: "root_turn",
290 status: "completed",
291 countsForRun: true,
292 providerThreadId: input.providerThreadId,
293 providerTurnId,
294 nativeItemRef: null,
295 runtimeRequestId: null,
296 checkpointScopeId: null,
297 startedAt: now,
298 completedAt: now,
299 },
300 },
301 {
302 id: EventId.make(`attempt:${input.ordinal}`),
303 type: "run-attempt.created",
304 threadId,
305 occurredAt: now,
306 payload: {
307 id: attemptId,
308 runId,
309 attemptOrdinal: 1,
310 rootNodeId: nodeId,
311 providerInstanceId: instanceId,
312 providerThreadId: input.providerThreadId,
313 providerTurnId,
314 reason: "initial",
315 status: "completed",
316 startedAt: now,
317 completedAt: now,
318 },
319 },
320 {
321 id: EventId.make(`provider-turn:${input.ordinal}`),
322 type: "provider-turn.updated",
323 threadId,
324 occurredAt: now,
325 payload: {
326 id: providerTurnId,
327 providerThreadId: input.providerThreadId,
328 nodeId,
329 runAttemptId: attemptId,
330 nativeTurnRef: null,
331 ordinal: input.ordinal,
332 status: "completed",
333 startedAt: now,
334 completedAt: now,
335 },
336 },
337 ];
338 const item = input.runningItem;
339 if (item !== undefined) {
340 const base = {
341 id: item.id,
342 threadId,
343 runId,
344 nodeId,
345 providerThreadId: input.providerThreadId,
346 providerTurnId,
347 nativeItemRef: null,
348 parentItemId: null,
349 ordinal: input.ordinal * 100,
350 status: "running",
351 title: null,
352 startedAt: now,
353 completedAt: null,
354 updatedAt: now,
355 } as const;
356 events.push({
357 id: EventId.make(`item:${input.ordinal}`),
358 type: "turn-item.updated",
359 threadId,
360 runId,
361 occurredAt: now,
362 payload:
363 item.kind === "command"
364 ? { ...base, type: "command_execution", input: "vp run test --watch" }
365 : {
366 ...base,
367 // A native subagent item names its own provider thread
368 // but its parent's provider turn.
369 providerThreadId: ProviderThreadId.make("provider-thread:codex-subagent"),
370 type: "subagent",
371 subagentId: NodeId.make(`subagent:${input.ordinal}`),
372 origin: "provider_native",
373 driver,
374 providerInstanceId: instanceId,
375 childThreadId: null,
376 prompt: "Review the change",
377 result: null,
378 },
379 });
380 }
381 return { runId, providerTurnId, events };
382 };
383​
384 // Later Codex runs leave a second command and a native subagent. Then
385 // the thread moves on to another provider thread, which also has a
386 // live session.
387 const watcherId = TurnItemId.make("turn-item:watcher");
388 const otherProviderThreadId = ProviderThreadId.make("provider-thread:other");
389 const watcherRun = settledRun({
390 ordinal: 2,
391 providerThreadId: olderStart ? otherProviderThreadId : codexProviderThread.id,
392 ...(olderStart ? {} : { runningItem: { id: watcherId, kind: "command" as const } }),
393 });
394 const reviewerId = TurnItemId.make("turn-item:reviewer");
395 const reviewerRun = settledRun({
396 ordinal: 3,
397 providerThreadId: codexProviderThread.id,
398 runningItem: { id: reviewerId, kind: "subagent" },
399 });
400 const latestRun = settledRun({ ordinal: 4, providerThreadId: otherProviderThreadId });
401 yield* sink.write({
402 events: [
403 ...watcherRun.events,
404 ...reviewerRun.events,
405 {
406 id: EventId.make("provider-thread:other"),
407 type: "provider-thread.updated",
408 threadId,
409 occurredAt: now,
410 payload: {
411 ...codexProviderThread,
412 id: otherProviderThreadId,
413 firstRunOrdinal: 4,
414 lastRunOrdinal: 4,
415 },
416 },
417 ...latestRun.events,
418 ],
419 });
420​
421 const failedRun = settledRun({ ordinal: 5, providerThreadId: otherProviderThreadId });
422 if (failedStart) {
423 yield* sink.write({
424 events: failedRun.events.flatMap((event): Array<OrchestrationV2DomainEvent> => {
425 switch (event.type) {
426 case "provider-turn.updated":
427 return [];
428 case "run.created":
429 return [{ ...event, payload: { ...event.payload, status: "failed" } }];
430 case "node.updated":
431 return [
432 {
433 ...event,
434 payload: { ...event.payload, status: "failed", providerTurnId: null },
435 },
436 ];
437 case "run-attempt.created":
438 return [
439 {
440 ...event,
441 payload: { ...event.payload, status: "failed", providerTurnId: null },
442 },
443 ];
444 default:
445 return [event];
446 }
447 }),
448 });
449 }
450​
451 if (stopWithQueue !== undefined) {
452 const owner = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
453 (run) => run.id === latestRun.runId,
454 )!;
455 // A message queues while checkpointing finishes, then the user holds the queue.
456 yield* sink.write({
457 events: [
458 {
459 id: EventId.make("latest-run-waiting"),
460 type: "run.updated",
461 threadId,
462 runId: owner.id,
463 occurredAt: now,
464 payload: { ...owner, status: "waiting", completedAt: null },
465 },
466 ],
467 });
468 yield* orchestrator.dispatch({
469 type: "message.dispatch",
470 commandId: CommandId.make("queue-follow-up"),
471 threadId,
472 messageId: MessageId.make("message:queue-follow-up"),
473 text: "Follow up after the background work",
474 attachments: [],
475 dispatchMode: { type: "queue_after_active" },
476 createdBy: "user",
477 creationSource: "web",
478 });
479 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
480 assert.equal(queued.status, "queued");
481 yield* sink.write({
482 events: [
483 {
484 id: EventId.make("queue-held"),
485 type: "run.updated",
486 threadId,
487 runId: queued.id,
488 occurredAt: now,
489 payload: { ...queued, queueHeld: true },
490 },
491 {
492 id: EventId.make("latest-run-settled"),
493 type: "run.updated",
494 threadId,
495 runId: owner.id,
496 occurredAt: now,
497 payload: owner,
498 },
499 ],
500 });
501 }
502​
503 if (olderStart) {
504 const older = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
505 (run) => run.id === watcherRun.runId,
506 )!;
507 // A resumed queue can start a lower-ordinal run after later runs have ended.
508 yield* sink.write({
509 events: [
510 {
511 id: EventId.make("older-run-starting"),
512 type: "run.updated",
513 threadId,
514 runId: older.id,
515 occurredAt: now,
516 payload: { ...older, status: "starting", startedAt: null, completedAt: null },
517 },
518 ],
519 });
520 }
521​
522 yield* orchestrator.dispatch(
523 stopWithQueue === "thread.stop"
524 ? {
525 type: "thread.stop",
526 commandId: CommandId.make("stop-background-work"),
527 threadId,
528 }
529 : {
530 type: "run.interrupt",
531 commandId: CommandId.make("stop-background-work"),
532 threadId,
533 runId: olderStart
534 ? watcherRun.runId
535 : failedStart
536 ? failedRun.runId
537 : latestRun.runId,
538 ...(stopWithQueue === undefined ? {} : { holdQueue: true }),
539 },
540 );
541 yield* worker.drain();
542​
543 // The Codex interrupt targets its latest pending work, the subagent's parent turn,
544 // so its settlement covers the Codex background work.
545 assert.sameDeepMembers(
546 interrupts.map((interrupt) => [interrupt.providerThread.id, interrupt.providerTurnId]),
547 [
548 ...(olderStart ? [] : [[otherProviderThreadId, latestRun.providerTurnId]]),
549 [codexProviderThread.id, reviewerRun.providerTurnId],
550 ],
551 );
552 const after = yield* orchestrator.getThreadProjection(threadId);
553 if (olderStart) {
554 assert.equal(
555 after.runs.find((run) => run.id === watcherRun.runId)?.status,
556 "interrupted",
557 );
558 }
559 if (stopWithQueue !== undefined) {
560 assert.equal(after.runs.at(-1)?.status, "queued");
561 assert.equal(after.runs.at(-1)?.queueHeld, true);
562 assert.lengthOf(started, 1);
563 }
564 assert.deepEqual(
565 [devServerId, ...(olderStart ? [] : [watcherId]), reviewerId].map(
566 (id) => after.turnItems.find((item) => item.id === id)?.status,
567 ),
568 olderStart
569 ? ["interrupted", "interrupted"]
570 : ["interrupted", "interrupted", "interrupted"],
571 );
572 }).pipe(
573 Effect.provide(
574 ProviderReplayHarness.layerWithRegistry(
575 { name: "background-work-stop" },
576 ProviderAdapterRegistry.layerSingle(adapter),
577 { runEffectWorker: false },
578 ),
579 ),
580 );
581 }),
582 );
583​
584it.effect("Stop reaches background work an earlier provider thread still runs", () =>
585 stopEarlierBackgroundWork({}),
586);
587​
588it.effect(
589 "Stop reaches earlier background work after the newest run fails before provider start",
590 () => stopEarlierBackgroundWork({ failedStart: true }),
591);
592​
593it.effect.each(["thread.stop", "run.interrupt"] as const)(
594 "%s stops background work when a later message is queued",
595 (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType }),
596);
597​
598it.effect.each(["thread.stop", "run.interrupt"] as const)(
599 "%s reaches later background work when an older run is starting",
600 (stopType) => stopEarlierBackgroundWork({ stopWithQueue: stopType, olderStart: true }),
601);