Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderSessionId,
11 ProviderTurnId,
12 RuntimeRequestId,
13 ThreadId,
14 TurnItemId,
15} from "@t3tools/contracts";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Layer from "effect/Layer";
20import * as Schema from "effect/Schema";
21import * as SqlClient from "effect/sql/SqlClient";
22import * as Stream from "effect/Stream";
23import * as EventStore from "./EventStore.ts";
24import * as TestClock from "effect/testing/TestClock";
25
26import * as SqlitePersistence from "../persistence/Sqlite.ts";
27import * as ServerSettings from "../serverSettings.ts";
28import { CLAUDE_PROVIDER } from "./Adapters/ClaudeAdapterV2.ts";
29import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
30import * as CommandReceiptStore from "./CommandReceiptStore.ts";
31import { OrchestrationEffectRequestV2 } from "./EffectOutbox.ts";
32import * as Orchestrator from "./Orchestrator.ts";
33import * as EffectWorker from "./EffectWorker.ts";
34import * as EffectOutbox from "./EffectOutbox.ts";
35import * as ProjectionStore from "./ProjectionStore.ts";
36import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
37import * as ThreadManagementService from "./ThreadManagementService.ts";
38import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
39import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
40
41const instanceId = ProviderInstanceId.make("codex");
42const modelSelection = { instanceId, model: "gpt-5.1-codex" };
43const adapter = {
44 instanceId,
45 driver: ProviderDriverKind.make("codex"),
46 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
47 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
48 openSession: () => Effect.die("Runs here never reach a provider"),
49} as ProviderAdapter.ProviderAdapterV2["Service"];
50const layerDatabase = SqlitePersistence.layerMemory;
51const layerTest = ThreadManagementService.layer.pipe(
52 Layer.provideMerge(
53 Layer.mergeAll(
54 layerDatabase,
55 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
56 EventStore.layer.pipe(Layer.provide(layerDatabase)),
57 EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
58 ProviderReplayHarness.layerWithRegistry(
59 { name: "thread-stop" },
60 ProviderAdapterRegistry.layerFromAdapters([adapter]),
61 { databaseLayer: layerDatabase, runEffectWorker: false },
62 ),
63 ),
64 ),
65 Layer.provideMerge(ServerSettings.layerTest()),
66 Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
67);
68
69const encodeEffectRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
70
71const pullRequest = (number: number) => ({
72 host: "github.com",
73 repository: "pingdotgg/t3code",
74 number,
75});
76
77const createWatchingThread = (threadId: ThreadId, number: number) =>
78 Effect.gen(function* () {
79 const orchestrator = yield* Orchestrator.OrchestratorV2;
80 yield* orchestrator.dispatch({
81 type: "thread.create",
82 commandId: CommandId.make(`create:${threadId}`),
83 threadId,
84 projectId: ProjectId.make("project:thread-stop"),
85 title: threadId,
86 modelSelection,
87 runtimeMode: "full-access",
88 interactionMode: "default",
89 branch: null,
90 worktreePath: null,
91 createdBy: "user",
92 creationSource: "web",
93 });
94 yield* watch(threadId, number);
95 });
96
97const watch = (threadId: ThreadId, number: number) =>
98 Effect.gen(function* () {
99 const orchestrator = yield* Orchestrator.OrchestratorV2;
100 yield* orchestrator.dispatch({
101 type: "thread.pull-request.watch",
102 commandId: CommandId.make(`watch:${threadId}:${number}`),
103 threadId,
104 ...pullRequest(number),
105 watching: true,
106 link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
107 });
108 });
109
110const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") =>
111 Effect.gen(function* () {
112 const orchestrator = yield* Orchestrator.OrchestratorV2;
113 yield* orchestrator.dispatch({
114 type: "message.dispatch",
115 commandId: CommandId.make(`send:${threadId}:${text}`),
116 threadId,
117 messageId: MessageId.make(`message:${threadId}:${text}`),
118 text,
119 attachments: [],
120 dispatchMode: { type },
121 createdBy: "user",
122 creationSource: "web",
123 });
124 });
125
126const delegate = (parentThreadId: ThreadId, task: string) =>
127 Effect.gen(function* () {
128 const orchestrator = yield* Orchestrator.OrchestratorV2;
129 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
130 yield* orchestrator.dispatch({
131 type: "delegated_task.request",
132 commandId: CommandId.make(`delegate:${task}`),
133 parentThreadId,
134 parentRunId: parentRun.id,
135 parentNodeId: parentRun.rootNodeId!,
136 task,
137 modelSelection,
138 runtimeMode: "full-access",
139 interactionMode: "default",
140 completionWake: "always",
141 createdBy: "agent",
142 creationSource: "mcp",
143 });
144 const projection = yield* orchestrator.getThreadProjection(parentThreadId);
145 return projection.subagents.find((candidate) => candidate.prompt === task)!.childThreadId!;
146 });
147
148const threadState = (threadId: ThreadId) =>
149 Effect.gen(function* () {
150 const orchestrator = yield* Orchestrator.OrchestratorV2;
151 const projection = yield* orchestrator.getThreadProjection(threadId);
152 return {
153 runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`),
154 watched: (projection.thread.pullRequests ?? [])
155 .filter((link) => link.watch !== undefined)
156 .map((link) => link.number),
157 };
158 });
159
160it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
161 Effect.gen(function* () {
162 const orchestrator = yield* Orchestrator.OrchestratorV2;
163 const projections = yield* ProjectionStore.ProjectionStoreV2;
164 const threads = yield* ThreadManagementService.ThreadManagementService;
165 const sql = yield* SqlClient.SqlClient;
166 const parentThreadId = ThreadId.make("thread:stop-parent");
167 yield* createWatchingThread(parentThreadId, 1);
168 yield* send(parentThreadId, "first", "start_immediately");
169 const childThreadId = yield* delegate(parentThreadId, "child task");
170 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
171 const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
172 yield* send(childThreadId, "child follow-up", "queue_after_active");
173
174 const now = yield* DateTime.now;
175 const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
176 yield* projections.apply({
177 id: EventId.make("event:stop-parent:first-run-completed"),
178 type: "run.updated",
179 threadId: parentThreadId,
180 runId: firstRun.id,
181 occurredAt: now,
182 payload: { ...firstRun, status: "completed", completedAt: now },
183 });
184 yield* send(parentThreadId, "second", "start_immediately");
185 const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
186
187 const stopCommandId = CommandId.make("stop-parent");
188 yield* orchestrator.dispatch({
189 type: "run.interrupt",
190 commandId: stopCommandId,
191 threadId: parentThreadId,
192 runId: secondRun.id,
193 holdQueue: true,
194 });
195
196 assert.deepEqual(yield* threadState(parentThreadId), {
197 runs: ["completed", "interrupted"],
198 watched: [],
199 });
200 const parent = yield* orchestrator.getThreadProjection(parentThreadId);
201 assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
202 const effects = yield* sql<{ readonly effect_type: string }>`
203 SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
204 `;
205 assert.include(
206 effects.map((row) => row.effect_type),
207 "delegated-tasks.stop",
208 );
209
210 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
211 assert.deepEqual(yield* threadState(childThreadId), {
212 runs: ["interrupted", "queued:held"],
213 watched: [],
214 });
215 assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
216
217 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
218 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
219 }).pipe(Effect.provide(layerTest)),
220);
221
222it.effect.each(["thread.stop", "run.interrupt"] as const)(
223 "%s cancels buffered wakes and preserves durable queued messages",
224 (type) =>
225 Effect.gen(function* () {
226 const orchestrator = yield* Orchestrator.OrchestratorV2;
227 const threadId = ThreadId.make(`thread:stop-buffered:${type}`);
228 yield* createWatchingThread(threadId, 5);
229 yield* send(threadId, "active", "start_immediately");
230 yield* send(threadId, "user follow-up", "queue_after_active");
231 for (const creationSource of ["provider", "server"] as const) {
232 yield* orchestrator.dispatch({
233 type: "message.dispatch",
234 commandId: CommandId.make(`notification:${type}:${creationSource}`),
235 threadId,
236 messageId: MessageId.make(`notification:${type}:${creationSource}`),
237 text: "Background activity updated",
238 attachments: [],
239 createdBy: "agent",
240 creationSource,
241 notification: {
242 source: { kind: "background_task" },
243 outcome: "updated",
244 summary: "Background activity updated",
245 },
246 dispatchMode: { type: "queue_after_active" },
247 });
248 }
249 const before = yield* orchestrator.getThreadProjection(threadId);
250 const buffered = before.runs.find((run) =>
251 before.messages.some(
252 (message) => message.id === run.userMessageId && message.creationSource === "provider",
253 ),
254 )!;
255 const stop = { commandId: CommandId.make(`stop:${type}`), threadId };
256 yield* orchestrator.dispatch(
257 type === "run.interrupt"
258 ? { ...stop, type, runId: before.runs[0]!.id, holdQueue: true }
259 : { ...stop, type },
260 );
261 const stopped = yield* orchestrator.getThreadProjection(threadId);
262 assert.equal(stopped.runs.find((run) => run.id === buffered.id)?.status, "cancelled");
263 assert.equal(
264 stopped.attempts.find((attempt) => attempt.runId === buffered.id)?.status,
265 "cancelled",
266 );
267 assert.equal(
268 stopped.nodes.find((node) => node.id === buffered.rootNodeId)?.status,
269 "cancelled",
270 );
271 assert.deepEqual(
272 stopped.runs.filter((run) => run.status === "queued").map((run) => run.queueHeld),
273 [true, true],
274 );
275 }).pipe(Effect.provide(layerTest)),
276);
277
278it.effect(
279 "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
280 () =>
281 Effect.gen(function* () {
282 const orchestrator = yield* Orchestrator.OrchestratorV2;
283 const threadId = ThreadId.make("thread:stop-idle");
284 yield* createWatchingThread(threadId, 3);
285
286 yield* orchestrator.dispatch({
287 type: "thread.stop",
288 commandId: CommandId.make("stop-idle"),
289 threadId,
290 });
291 assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
292
293 const again = yield* orchestrator.dispatch({
294 type: "thread.stop",
295 commandId: CommandId.make("stop-idle-again"),
296 threadId,
297 });
298 assert.lengthOf(again.storedEvents, 0);
299 }).pipe(Effect.provide(layerTest)),
300);
301
302it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
303 Effect.gen(function* () {
304 const orchestrator = yield* Orchestrator.OrchestratorV2;
305 const projections = yield* ProjectionStore.ProjectionStoreV2;
306 const threadId = ThreadId.make("thread:stop-barrier");
307 yield* createWatchingThread(threadId, 4);
308 yield* send(threadId, "work", "start_immediately");
309 const now = yield* DateTime.now;
310 const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
311 yield* projections.apply({
312 id: EventId.make("event:stop-barrier:running"),
313 type: "run.updated",
314 threadId,
315 runId: run.id,
316 occurredAt: now,
317 payload: { ...run, status: "running" },
318 });
319 yield* send(threadId, "queued", "queue_after_active");
320 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
321 yield* orchestrator.dispatch({
322 type: "queued-run.cancel",
323 commandId: CommandId.make("cancel-queued"),
324 threadId,
325 runId: queued.id,
326 });
327 yield* projections.apply({
328 id: EventId.make("event:stop-barrier:interrupt-request"),
329 type: "turn-item.updated",
330 threadId,
331 runId: run.id,
332 occurredAt: now,
333 payload: {
334 id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
335 threadId,
336 runId: run.id,
337 nodeId: run.rootNodeId!,
338 providerThreadId: run.providerThreadId!,
339 providerTurnId: null,
340 nativeItemRef: null,
341 parentItemId: null,
342 ordinal: 1_000,
343 status: "completed",
344 title: "Interrupt requested",
345 startedAt: now,
346 completedAt: now,
347 updatedAt: now,
348 type: "run_interrupt_request",
349 message: "Stop",
350 },
351 });
352
353 assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
354 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
355
356 yield* projections.apply({
357 id: EventId.make("event:stop-barrier:interrupted"),
358 type: "run.updated",
359 threadId,
360 runId: run.id,
361 occurredAt: now,
362 payload: { ...run, status: "interrupted", completedAt: now },
363 });
364 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
365 assert.deepEqual(yield* threadState(threadId), {
366 runs: ["interrupted", "cancelled"],
367 watched: [4],
368 });
369
370 for (const watching of [false, true]) {
371 yield* orchestrator.dispatch({
372 type: "thread.pull-request.watch",
373 commandId: CommandId.make(`manual-watch:${watching}`),
374 threadId,
375 ...pullRequest(4),
376 watching,
377 });
378 }
379 assert.deepEqual((yield* threadState(threadId)).watched, [4]);
380 }).pipe(Effect.provide(layerTest)),
381);
382
383it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
384 Effect.gen(function* () {
385 const orchestrator = yield* Orchestrator.OrchestratorV2;
386 const projections = yield* ProjectionStore.ProjectionStoreV2;
387 const sql = yield* SqlClient.SqlClient;
388 const threadId = ThreadId.make("thread:stop-restart");
389 yield* createWatchingThread(threadId, 8);
390 yield* send(threadId, "work", "start_immediately");
391 const now = yield* DateTime.now;
392 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
393 yield* projections.apply({
394 id: EventId.make("event:stop-restart:cancelled"),
395 type: "run.updated",
396 threadId,
397 runId: run.id,
398 occurredAt: now,
399 payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
400 });
401 const at = DateTime.formatIso(now);
402 yield* sql`
403 INSERT INTO orchestration_v2_effect_outbox (
404 effect_id, command_id, thread_id, effect_type, payload_json, status,
405 attempt_count, available_at, created_at, updated_at
406 ) VALUES (
407 ${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
408 'provider-runtime.continue',
409 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
410 'pending', 0, ${at}, ${at}, ${at}
411 )
412 `;
413
414 yield* orchestrator.dispatch({
415 type: "thread.stop",
416 commandId: CommandId.make("stop-restart"),
417 threadId,
418 });
419 yield* orchestrator.dispatch({
420 type: "message.dispatch",
421 commandId: CommandId.make("restart-continuation"),
422 threadId,
423 messageId: MessageId.make("message:restart-continuation"),
424 text: "Continue.",
425 attachments: [],
426 dispatchMode: { type: "start_immediately" },
427 createdBy: "agent",
428 creationSource: "server",
429 restartContinuationOfRunId: run.id,
430 });
431 assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
432 }).pipe(Effect.provide(layerTest)),
433);
434
435it.effect.each(["thread.stop", "run.interrupt"] as const)(
436 "a successful %s blocks a newer restart continuation when completion timestamps tie",
437 (stopType) =>
438 Effect.gen(function* () {
439 const orchestrator = yield* Orchestrator.OrchestratorV2;
440 const projections = yield* ProjectionStore.ProjectionStoreV2;
441 const sql = yield* SqlClient.SqlClient;
442 const threadId = ThreadId.make("thread:stop-resumed-queue");
443 yield* createWatchingThread(threadId, 12);
444 yield* send(threadId, "first", "start_immediately");
445 yield* send(threadId, "queued", "queue_after_active");
446 const now = yield* DateTime.now;
447 const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
448 assert.isDefined(first);
449 assert.isDefined(queued);
450 for (const run of [first!, queued!]) {
451 yield* projections.apply({
452 id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
453 type: "run.updated",
454 threadId,
455 runId: run.id,
456 occurredAt: now,
457 payload:
458 run.id === first!.id
459 ? { ...run, status: "completed", completedAt: now }
460 : { ...run, queueHeld: true },
461 });
462 }
463 yield* send(threadId, "restart source", "start_immediately");
464 const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
465 yield* projections.apply({
466 id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
467 type: "run.updated",
468 threadId,
469 runId: source.id,
470 occurredAt: now,
471 payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
472 });
473 const at = DateTime.formatIso(now);
474 yield* sql`
475 INSERT INTO orchestration_v2_effect_outbox (
476 effect_id, command_id, thread_id, effect_type, payload_json, status,
477 attempt_count, available_at, created_at, updated_at
478 ) VALUES (
479 ${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
480 'provider-runtime.continue',
481 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
482 'pending', 0, ${at}, ${at}, ${at}
483 )
484 `;
485 yield* orchestrator.dispatch({
486 type: "queue.resume",
487 commandId: CommandId.make("resume-older-queue"),
488 threadId,
489 });
490 assert.equal(
491 (yield* orchestrator.getThreadProjection(threadId)).runs.find(
492 (run) => run.id === queued!.id,
493 )?.status,
494 "starting",
495 );
496 yield* orchestrator.dispatch(
497 stopType === "thread.stop"
498 ? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
499 : {
500 type: "run.interrupt",
501 commandId: CommandId.make("stop-resumed-queue"),
502 threadId,
503 runId: queued!.id,
504 holdQueue: true,
505 },
506 );
507 const stopped = yield* orchestrator.getThreadProjection(threadId);
508 const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
509 assert.equal(interrupted.status, "interrupted");
510 assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
511 yield* orchestrator.dispatch({
512 type: "message.dispatch",
513 commandId: CommandId.make("restart-after-stop"),
514 threadId,
515 messageId: MessageId.make("message:restart-after-stop"),
516 text: "Continue.",
517 attachments: [],
518 dispatchMode: { type: "start_immediately" },
519 createdBy: "agent",
520 creationSource: "server",
521 restartContinuationOfRunId: source.id,
522 });
523 assert.deepEqual(yield* threadState(threadId), {
524 runs: ["completed", "interrupted", "cancelled"],
525 watched: [],
526 });
527 }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
528);
529
530it.effect.each([
531 { ending: "cancelled", question: "resolved" },
532 { ending: "interrupted", question: "resolved" },
533 { ending: "completed", question: "pending" },
534 { ending: "failed", question: "pending" },
535] as const)(
536 "a $ending delegated task leaves its async question $question",
537 ({ ending, question }) =>
538 Effect.gen(function* () {
539 const orchestrator = yield* Orchestrator.OrchestratorV2;
540 const projections = yield* ProjectionStore.ProjectionStoreV2;
541 const parentThreadId = ThreadId.make(`thread:stop-question-parent:${ending}`);
542 yield* createWatchingThread(parentThreadId, 20);
543 yield* send(parentThreadId, "first", "start_immediately");
544 const childThreadId = yield* delegate(parentThreadId, `question task ${ending}`);
545 const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!;
546 assert.equal(
547 (yield* orchestrator.getThreadProjection(childThreadId)).nodes.find(
548 (node) => node.id === childRun.rootNodeId,
549 )?.runId,
550 childRun.id,
551 );
552 const now = yield* DateTime.now;
553 yield* projections.apply({
554 id: EventId.make("event:stop-question:request"),
555 type: "runtime-request.updated",
556 threadId: childThreadId,
557 runId: childRun.id,
558 occurredAt: now,
559 payload: {
560 id: RuntimeRequestId.make("request:stop-question"),
561 nodeId: childRun.rootNodeId!,
562 providerTurnId: null,
563 nativeRequestRef: null,
564 kind: "user_input",
565 status: "pending",
566 responseCapability: { type: "message" },
567 createdAt: now,
568 resolvedAt: null,
569 },
570 });
571 const request = Effect.map(
572 orchestrator.getThreadProjection(childThreadId),
573 (projection) => projection.runtimeRequests[0],
574 );
575
576 yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
577 assert.equal((yield* request)?.status, "pending");
578 if (ending === "interrupted") {
579 yield* orchestrator.dispatch({
580 type: "thread.stop",
581 commandId: CommandId.make("stop-question-child"),
582 threadId: childThreadId,
583 });
584 } else {
585 yield* projections.apply({
586 id: EventId.make(`event:stop-question:${ending}`),
587 type: "run.updated",
588 threadId: childThreadId,
589 runId: childRun.id,
590 occurredAt: now,
591 payload: { ...childRun, status: ending, startedAt: now, completedAt: now },
592 });
593 }
594 yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
595 assert.equal((yield* request)?.status, question);
596 assert.equal((yield* request)?.decision, question === "resolved" ? "cancel" : undefined);
597 }).pipe(Effect.provide(layerTest)),
598);
599
600it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
601 Effect.gen(function* () {
602 const orchestrator = yield* Orchestrator.OrchestratorV2;
603 const projections = yield* ProjectionStore.ProjectionStoreV2;
604 const threads = yield* ThreadManagementService.ThreadManagementService;
605 const parentThreadId = ThreadId.make("thread:stop-partial");
606 yield* createWatchingThread(parentThreadId, 6);
607 yield* send(parentThreadId, "work", "start_immediately");
608 const childThreadId = yield* delegate(parentThreadId, "stoppable task");
609 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
610 yield* projections.apply({
611 id: EventId.make("event:stop-partial:missing-task"),
612 type: "subagent.updated",
613 threadId: parentThreadId,
614 runId: task.runId!,
615 nodeId: NodeId.make("node:stop-partial:missing"),
616 providerInstanceId: instanceId,
617 occurredAt: yield* DateTime.now,
618 payload: {
619 ...task,
620 id: NodeId.make("node:stop-partial:missing"),
621 childThreadId: ThreadId.make("thread:stop-partial:missing"),
622 startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
623 },
624 });
625
626 const walked = yield* Effect.exit(
627 threads.stopDelegatedTasks({
628 threadId: parentThreadId,
629 commandId: CommandId.make("stop-partial"),
630 }),
631 );
632 assert.isTrue(Exit.isFailure(walked));
633 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
634 }).pipe(Effect.provide(layerTest)),
635);
636
637it.effect("thread.stop on a finished thread refuses a late agent watch", () =>
638 Effect.gen(function* () {
639 const orchestrator = yield* Orchestrator.OrchestratorV2;
640 const projections = yield* ProjectionStore.ProjectionStoreV2;
641 const threadId = ThreadId.make("thread:stop-finished");
642 yield* createWatchingThread(threadId, 9);
643 yield* send(threadId, "work", "start_immediately");
644 const now = yield* DateTime.now;
645 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
646 yield* projections.apply({
647 id: EventId.make("event:stop-finished:completed"),
648 type: "run.updated",
649 threadId,
650 runId: run.id,
651 occurredAt: now,
652 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
653 });
654
655 yield* orchestrator.dispatch({
656 type: "thread.stop",
657 commandId: CommandId.make("stop-finished"),
658 threadId,
659 });
660 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 10))));
661 assert.deepEqual(yield* threadState(threadId), { runs: ["completed"], watched: [] });
662 }).pipe(Effect.provide(layerTest)),
663);
664
665it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
666 Effect.gen(function* () {
667 const orchestrator = yield* Orchestrator.OrchestratorV2;
668 const projections = yield* ProjectionStore.ProjectionStoreV2;
669 const threadId = ThreadId.make("thread:stop-lost-session");
670 yield* createWatchingThread(threadId, 11);
671 yield* send(threadId, "work", "start_immediately");
672 const now = yield* DateTime.now;
673 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
674 yield* projections.apply({
675 id: EventId.make("event:stop-lost-session:running"),
676 type: "run.updated",
677 threadId,
678 runId: run.id,
679 occurredAt: now,
680 payload: { ...run, status: "running", startedAt: now },
681 });
682 yield* projections.apply({
683 id: EventId.make("event:stop-lost-session:turn"),
684 type: "provider-turn.updated",
685 threadId,
686 occurredAt: now,
687 payload: {
688 id: ProviderTurnId.make("provider-turn:stop-lost-session"),
689 providerThreadId: run.providerThreadId!,
690 nodeId: run.rootNodeId!,
691 runAttemptId: run.activeAttemptId!,
692 nativeTurnRef: null,
693 ordinal: 1,
694 status: "running",
695 startedAt: now,
696 completedAt: null,
697 },
698 });
699
700 yield* orchestrator.dispatch({
701 type: "thread.stop",
702 commandId: CommandId.make("stop-lost-session"),
703 threadId,
704 });
705 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
706 assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
707 }).pipe(Effect.provide(layerTest)),
708);
709
710it.effect.each(["missing session", "completed", "failed", "cancelled"] as const)(
711 "a native child Stop only settles a confirmed %s outcome and preserves its owner and sibling",
712 (providerState) =>
713 Effect.gen(function* () {
714 const orchestrator = yield* Orchestrator.OrchestratorV2;
715 const projections = yield* ProjectionStore.ProjectionStoreV2;
716 const sql = yield* SqlClient.SqlClient;
717 const threadId = ThreadId.make("thread:native-child-stop");
718 yield* createWatchingThread(threadId, 20);
719 yield* send(threadId, "owner", "start_immediately");
720 yield* delegate(threadId, "native-child-fixture");
721 const before = yield* orchestrator.getThreadProjection(threadId);
722 const run = before.runs[0]!;
723 const now = yield* DateTime.now;
724 const subagent = {
725 ...before.subagents[0]!,
726 origin: "provider_native" as const,
727 driver: CLAUDE_PROVIDER,
728 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
729 nativeTaskRef: {
730 driver: CLAUDE_PROVIDER,
731 nativeId: "claude-task",
732 strength: "strong" as const,
733 },
734 status: "running" as const,
735 startedAt: now,
736 };
737 yield* projections.apply({
738 id: EventId.make("event:native-child-stop:agent"),
739 type: "subagent.updated",
740 threadId,
741 runId: run.id,
742 nodeId: subagent.id,
743 occurredAt: now,
744 payload: subagent,
745 });
746 const sibling = {
747 ...subagent,
748 id: NodeId.make("node:native-stop-sibling"),
749 childThreadId: null,
750 };
751 yield* projections.apply({
752 id: EventId.make("event:native-child-stop:sibling"),
753 type: "subagent.updated",
754 threadId,
755 runId: run.id,
756 nodeId: sibling.id,
757 occurredAt: now,
758 payload: sibling,
759 });
760 const item = before.turnItems.find(
761 (item) => item.type === "subagent" && item.subagentId === subagent.id,
762 )!;
763 yield* projections.apply({
764 id: EventId.make("event:native-child-stop:item"),
765 type: "turn-item.updated",
766 threadId,
767 runId: run.id,
768 occurredAt: now,
769 payload: { ...item, status: "running", completedAt: null },
770 });
771 const childRoot = {
772 ...before.nodes.find((node) => node.id === run.rootNodeId)!,
773 id: NodeId.make("node:native-stop-child-root"),
774 threadId: subagent.childThreadId!,
775 runId: null,
776 parentNodeId: null,
777 status: "running" as const,
778 countsForRun: false,
779 completedAt: null,
780 };
781 yield* projections.apply({
782 id: EventId.make("event:native-child-stop:child-root"),
783 type: "node.updated",
784 threadId: childRoot.threadId,
785 nodeId: childRoot.id,
786 occurredAt: now,
787 payload: childRoot,
788 });
789 const providerThread = before.providerThreads.find(
790 (thread) => thread.id === run.providerThreadId,
791 )!;
792 yield* projections.apply({
793 id: EventId.make("event:native-child-stop:provider-thread"),
794 type: "provider-thread.updated",
795 threadId,
796 occurredAt: now,
797 payload: {
798 ...providerThread,
799 driver: CLAUDE_PROVIDER,
800 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
801 providerSessionId: ProviderSessionId.make("session:native-child-stop"),
802 },
803 });
804 const providerTurnId = ProviderTurnId.make("turn:native-child-stop");
805 yield* projections.apply({
806 id: EventId.make("event:native-child-stop:provider-turn"),
807 type: "provider-turn.updated",
808 threadId,
809 occurredAt: now,
810 payload: {
811 id: providerTurnId,
812 providerThreadId: providerThread.id,
813 nodeId: run.rootNodeId!,
814 runAttemptId: run.activeAttemptId!,
815 nativeTurnRef: null,
816 ordinal: 1,
817 status: "completed",
818 startedAt: now,
819 completedAt: now,
820 },
821 });
822 yield* projections.apply({
823 id: EventId.make("event:native-child-stop:owner-completed"),
824 type: "run.updated",
825 threadId,
826 runId: run.id,
827 occurredAt: now,
828 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
829 });
830 yield* send(threadId, "queued", "queue_after_active");
831 const stateBefore = yield* threadState(threadId);
832 const eventStore = yield* EventStore.EventStoreV2;
833 const afterSequence = yield* eventStore.latestSequence({ threadId });
834 const confirmedStatus =
835 providerState === "completed" || providerState === "failed" || providerState === "cancelled"
836 ? providerState
837 : null;
838 const confirmedOutcome =
839 confirmedStatus === null
840 ? undefined
841 : { status: confirmedStatus, completedAt: now, result: "Actual provider outcome" };
842 const commandId = CommandId.make("stop-native-child");
843 yield* orchestrator.dispatch({
844 type: "subagent.stop",
845 commandId,
846 threadId,
847 runId: run.id,
848 subagentId: subagent.id,
849 });
850 assert.deepEqual(yield* threadState(threadId), stateBefore);
851 const effects = yield* sql<{ payload_json: string }>`
852 SELECT payload_json FROM orchestration_v2_effect_outbox WHERE command_id = ${commandId}
853 `;
854 assert.equal(effects.length, 1);
855 assert.deepEqual(JSON.parse(effects[0]!.payload_json), {
856 type: "provider-turn.interrupt",
857 providerSessionId: "session:native-child-stop",
858 providerThreadId: providerThread.id,
859 providerTurnId,
860 subagent: { id: subagent.id, nativeTaskId: "claude-task" },
861 });
862 assert.equal(
863 (yield* orchestrator.getThreadProjection(threadId)).subagents[0]?.status,
864 "running",
865 );
866 const unrelated = yield* Effect.exit(
867 orchestrator.dispatch({
868 type: "subagent.stop",
869 commandId: CommandId.make("stop-unknown-child"),
870 threadId,
871 runId: run.id,
872 subagentId: NodeId.make("unknown-child"),
873 }),
874 );
875 assert.isTrue(Exit.isFailure(unrelated));
876 yield* TestClock.adjust("1 second");
877 yield* sql`DELETE FROM orchestration_v2_effect_outbox WHERE command_id != ${commandId}`;
878 if (providerState === "missing session") {
879 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
880 yield* worker.drain();
881 } else {
882 yield* orchestrator.dispatch({
883 type: "thread.background-work.settle",
884 commandId: CommandId.make("repair-native-child"),
885 threadId,
886 providerThreadId: providerThread.id,
887 providerTurnId,
888 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome! },
889 });
890 }
891 const settled = yield* orchestrator.getThreadProjection(threadId);
892 const cancelled = settled.subagents.find((task) => task.id === subagent.id)!;
893 if (confirmedOutcome === undefined) {
894 const events = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
895 assert.isFalse(
896 events.some(
897 ({ event }) =>
898 (event.type === "subagent.updated" ||
899 event.type === "node.updated" ||
900 event.type === "turn-item.updated") &&
901 ["completed", "failed", "cancelled", "interrupted"].includes(event.payload.status),
902 ),
903 );
904 assert.equal(cancelled.status, "running");
905 assert.equal(
906 (yield* orchestrator.getThreadProjection(childRoot.threadId)).nodes.find(
907 (node) => node.id === childRoot.id,
908 )?.status,
909 "running",
910 );
911 assert.deepEqual(yield* threadState(threadId), stateBefore);
912 return;
913 }
914
915 const repaired = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
916 const terminal = repaired.flatMap(({ event }) =>
917 (event.type === "subagent.updated" ||
918 event.type === "node.updated" ||
919 event.type === "turn-item.updated") &&
920 event.payload.status === confirmedStatus
921 ? [event]
922 : [],
923 );
924 assert.deepEqual(terminal.map((event) => event.type).sort(), [
925 "node.updated",
926 "subagent.updated",
927 "turn-item.updated",
928 ]);
929 for (const event of terminal) {
930 assert.equal(event.nodeId, subagent.id);
931 assert.equal(
932 DateTime.toEpochMillis(event.payload.completedAt!),
933 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
934 );
935 if (event.type === "subagent.updated" || event.type === "turn-item.updated") {
936 assert.isDefined(event.payload.updatedAt);
937 }
938 }
939
940 assert.equal(cancelled.status, confirmedStatus);
941 assert.isNotNull(cancelled.completedAt);
942 assert.equal(
943 DateTime.toEpochMillis(cancelled.completedAt!),
944 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
945 );
946 assert.equal(cancelled.result, confirmedOutcome!.result);
947 assert.equal(
948 settled.turnItems.find((candidate) => candidate.id === item.id)?.status,
949 confirmedStatus,
950 );
951 const child = yield* orchestrator.getThreadProjection(childRoot.threadId);
952 assert.equal(child.nodes.find((node) => node.id === childRoot.id)?.status, confirmedStatus);
953 assert.isNotNull(child.nodes.find((node) => node.id === childRoot.id)?.completedAt);
954 assert.equal(settled.subagents.find((task) => task.id === sibling.id)?.status, "running");
955 assert.deepEqual(yield* threadState(threadId), stateBefore);
956 yield* TestClock.adjust("1 second");
957 const resumedAt = yield* DateTime.now;
958 yield* projections.apply({
959 id: EventId.make("event:native-child-stop:resume"),
960 type: "subagent.updated",
961 threadId,
962 runId: run.id,
963 nodeId: subagent.id,
964 occurredAt: resumedAt,
965 payload: { ...cancelled, status: "running", startedAt: resumedAt, completedAt: null },
966 });
967 yield* orchestrator.dispatch({
968 type: "thread.background-work.settle",
969 commandId: CommandId.make("old-stop-after-resume"),
970 threadId,
971 providerThreadId: providerThread.id,
972 providerTurnId,
973 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome },
974 });
975 assert.equal(
976 (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
977 (task) => task.id === subagent.id,
978 )?.status,
979 "running",
980 );
981 }).pipe(Effect.provide(layerTest)),
982);