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 ProviderTurnId,
11 ThreadId,
12 TurnItemId,
13} from "@t3tools/contracts";
14import * as DateTime from "effect/DateTime";
15import * as Effect from "effect/Effect";
16import * as Exit from "effect/Exit";
17import * as Layer from "effect/Layer";
18import * as Schema from "effect/Schema";
19import * as SqlClient from "effect/sql/SqlClient";
20import * as TestClock from "effect/testing/TestClock";
21
22import * as SqlitePersistence from "../persistence/Sqlite.ts";
23import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
24import { OrchestrationEffectRequestV2 } from "./EffectOutbox.ts";
25import * as Orchestrator from "./Orchestrator.ts";
26import * as ProjectionStore from "./ProjectionStore.ts";
27import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
28import * as ThreadManagementService from "./ThreadManagementService.ts";
29import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
30import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
31
32const instanceId = ProviderInstanceId.make("codex");
33const modelSelection = { instanceId, model: "gpt-5.1-codex" };
34const adapter = {
35 instanceId,
36 driver: ProviderDriverKind.make("codex"),
37 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
38 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
39 openSession: () => Effect.die("Runs here never reach a provider"),
40} as ProviderAdapter.ProviderAdapterV2["Service"];
41const layerDatabase = SqlitePersistence.layerMemory;
42// No effect worker: runs stay unstarted, so Stop ends them without a provider.
43const layerTest = ThreadManagementService.layer.pipe(
44 Layer.provideMerge(
45 Layer.mergeAll(
46 layerDatabase,
47 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
48 ProviderReplayHarness.layerWithRegistry(
49 { name: "thread-stop" },
50 ProviderAdapterRegistry.layerFromAdapters([adapter]),
51 { databaseLayer: layerDatabase, runEffectWorker: false },
52 ),
53 ),
54 ),
55);
56
57const encodeEffectRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
58
59const pullRequest = (number: number) => ({
60 host: "github.com",
61 repository: "pingdotgg/t3code",
62 number,
63});
64
65const createWatchingThread = (threadId: ThreadId, number: number) =>
66 Effect.gen(function* () {
67 const orchestrator = yield* Orchestrator.OrchestratorV2;
68 yield* orchestrator.dispatch({
69 type: "thread.create",
70 commandId: CommandId.make(`create:${threadId}`),
71 threadId,
72 projectId: ProjectId.make("project:thread-stop"),
73 title: threadId,
74 modelSelection,
75 runtimeMode: "full-access",
76 interactionMode: "default",
77 branch: null,
78 worktreePath: null,
79 createdBy: "user",
80 creationSource: "web",
81 });
82 yield* watch(threadId, number);
83 });
84
85const watch = (threadId: ThreadId, number: number) =>
86 Effect.gen(function* () {
87 const orchestrator = yield* Orchestrator.OrchestratorV2;
88 yield* orchestrator.dispatch({
89 type: "thread.pull-request.watch",
90 commandId: CommandId.make(`watch:${threadId}:${number}`),
91 threadId,
92 ...pullRequest(number),
93 watching: true,
94 link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
95 });
96 });
97
98const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") =>
99 Effect.gen(function* () {
100 const orchestrator = yield* Orchestrator.OrchestratorV2;
101 yield* orchestrator.dispatch({
102 type: "message.dispatch",
103 commandId: CommandId.make(`send:${threadId}:${text}`),
104 threadId,
105 messageId: MessageId.make(`message:${threadId}:${text}`),
106 text,
107 attachments: [],
108 dispatchMode: { type },
109 createdBy: "user",
110 creationSource: "web",
111 });
112 });
113
114/** Delegates `task` from the parent's latest run and returns the child thread. */
115const delegate = (parentThreadId: ThreadId, task: string) =>
116 Effect.gen(function* () {
117 const orchestrator = yield* Orchestrator.OrchestratorV2;
118 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
119 yield* orchestrator.dispatch({
120 type: "delegated_task.request",
121 commandId: CommandId.make(`delegate:${task}`),
122 parentThreadId,
123 parentRunId: parentRun.id,
124 parentNodeId: parentRun.rootNodeId!,
125 task,
126 modelSelection,
127 runtimeMode: "full-access",
128 interactionMode: "default",
129 completionWake: "always",
130 createdBy: "agent",
131 creationSource: "mcp",
132 });
133 const projection = yield* orchestrator.getThreadProjection(parentThreadId);
134 return projection.subagents.find((candidate) => candidate.prompt === task)!.childThreadId!;
135 });
136
137const threadState = (threadId: ThreadId) =>
138 Effect.gen(function* () {
139 const orchestrator = yield* Orchestrator.OrchestratorV2;
140 const projection = yield* orchestrator.getThreadProjection(threadId);
141 return {
142 runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`),
143 watched: (projection.thread.pullRequests ?? [])
144 .filter((link) => link.watch !== undefined)
145 .map((link) => link.number),
146 };
147 });
148
149it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
150 Effect.gen(function* () {
151 const orchestrator = yield* Orchestrator.OrchestratorV2;
152 const projections = yield* ProjectionStore.ProjectionStoreV2;
153 const threads = yield* ThreadManagementService.ThreadManagementService;
154 const sql = yield* SqlClient.SqlClient;
155 const parentThreadId = ThreadId.make("thread:stop-parent");
156 yield* createWatchingThread(parentThreadId, 1);
157 yield* send(parentThreadId, "first", "start_immediately");
158 const childThreadId = yield* delegate(parentThreadId, "child task");
159 // The parent owns its pull requests; a delegated task cannot watch one.
160 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
161 const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
162 yield* send(childThreadId, "child follow-up", "queue_after_active");
163
164 // The run that delegated the child ends before the run the user stops, so
165 // only a Stop that covers earlier runs keeps the stopped child from waking it.
166 const now = yield* DateTime.now;
167 const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
168 yield* projections.apply({
169 id: EventId.make("event:stop-parent:first-run-completed"),
170 type: "run.updated",
171 threadId: parentThreadId,
172 runId: firstRun.id,
173 occurredAt: now,
174 payload: { ...firstRun, status: "completed", completedAt: now },
175 });
176 yield* send(parentThreadId, "second", "start_immediately");
177 const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
178
179 const stopCommandId = CommandId.make("stop-parent");
180 yield* orchestrator.dispatch({
181 type: "run.interrupt",
182 commandId: stopCommandId,
183 threadId: parentThreadId,
184 runId: secondRun.id,
185 holdQueue: true,
186 });
187
188 assert.deepEqual(yield* threadState(parentThreadId), {
189 runs: ["completed", "interrupted"],
190 watched: [],
191 });
192 const parent = yield* orchestrator.getThreadProjection(parentThreadId);
193 assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
194 const effects = yield* sql<{ readonly effect_type: string }>`
195 SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
196 `;
197 assert.include(
198 effects.map((row) => row.effect_type),
199 "delegated-tasks.stop",
200 );
201
202 // What the delegated-tasks.stop effect runs once the Stop commits.
203 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
204 assert.deepEqual(yield* threadState(childThreadId), {
205 runs: ["interrupted", "queued:held"],
206 watched: [],
207 });
208 assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
209
210 // A retried effect stops nothing twice.
211 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
212 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
213 }).pipe(Effect.provide(layerTest)),
214);
215
216it.effect(
217 "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
218 () =>
219 Effect.gen(function* () {
220 const orchestrator = yield* Orchestrator.OrchestratorV2;
221 const threadId = ThreadId.make("thread:stop-idle");
222 yield* createWatchingThread(threadId, 3);
223
224 yield* orchestrator.dispatch({
225 type: "thread.stop",
226 commandId: CommandId.make("stop-idle"),
227 threadId,
228 });
229 assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
230
231 const again = yield* orchestrator.dispatch({
232 type: "thread.stop",
233 commandId: CommandId.make("stop-idle-again"),
234 threadId,
235 });
236 assert.lengthOf(again.storedEvents, 0);
237 }).pipe(Effect.provide(layerTest)),
238);
239
240it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
241 Effect.gen(function* () {
242 const orchestrator = yield* Orchestrator.OrchestratorV2;
243 const projections = yield* ProjectionStore.ProjectionStoreV2;
244 const threadId = ThreadId.make("thread:stop-barrier");
245 yield* createWatchingThread(threadId, 4);
246 yield* send(threadId, "work", "start_immediately");
247 const now = yield* DateTime.now;
248 const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
249 yield* projections.apply({
250 id: EventId.make("event:stop-barrier:running"),
251 type: "run.updated",
252 threadId,
253 runId: run.id,
254 occurredAt: now,
255 payload: { ...run, status: "running" },
256 });
257 // A queued message the user cancelled does not count as the latest run.
258 yield* send(threadId, "queued", "queue_after_active");
259 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
260 yield* orchestrator.dispatch({
261 type: "queued-run.cancel",
262 commandId: CommandId.make("cancel-queued"),
263 threadId,
264 runId: queued.id,
265 });
266 // Stop reached the run, but its provider has not stopped it yet.
267 yield* projections.apply({
268 id: EventId.make("event:stop-barrier:interrupt-request"),
269 type: "turn-item.updated",
270 threadId,
271 runId: run.id,
272 occurredAt: now,
273 payload: {
274 id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
275 threadId,
276 runId: run.id,
277 nodeId: run.rootNodeId!,
278 providerThreadId: run.providerThreadId!,
279 providerTurnId: null,
280 nativeItemRef: null,
281 parentItemId: null,
282 ordinal: 1_000,
283 status: "completed",
284 title: "Interrupt requested",
285 startedAt: now,
286 completedAt: now,
287 updatedAt: now,
288 type: "run_interrupt_request",
289 message: "Stop",
290 },
291 });
292
293 assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
294 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
295
296 // A slow watch_pull_request call can land after the stopped run ended.
297 yield* projections.apply({
298 id: EventId.make("event:stop-barrier:interrupted"),
299 type: "run.updated",
300 threadId,
301 runId: run.id,
302 occurredAt: now,
303 payload: { ...run, status: "interrupted", completedAt: now },
304 });
305 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
306 assert.deepEqual(yield* threadState(threadId), {
307 runs: ["interrupted", "cancelled"],
308 watched: [4],
309 });
310
311 // The user can still stop and restart a watch by hand.
312 for (const watching of [false, true]) {
313 yield* orchestrator.dispatch({
314 type: "thread.pull-request.watch",
315 commandId: CommandId.make(`manual-watch:${watching}`),
316 threadId,
317 ...pullRequest(4),
318 watching,
319 });
320 }
321 assert.deepEqual((yield* threadState(threadId)).watched, [4]);
322 }).pipe(Effect.provide(layerTest)),
323);
324
325it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
326 Effect.gen(function* () {
327 const orchestrator = yield* Orchestrator.OrchestratorV2;
328 const projections = yield* ProjectionStore.ProjectionStoreV2;
329 const sql = yield* SqlClient.SqlClient;
330 const threadId = ThreadId.make("thread:stop-restart");
331 yield* createWatchingThread(threadId, 8);
332 yield* send(threadId, "work", "start_immediately");
333 const now = yield* DateTime.now;
334 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
335 // A server restart cut the run before its provider started; its continuation is pending.
336 yield* projections.apply({
337 id: EventId.make("event:stop-restart:cancelled"),
338 type: "run.updated",
339 threadId,
340 runId: run.id,
341 occurredAt: now,
342 payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
343 });
344 const at = DateTime.formatIso(now);
345 yield* sql`
346 INSERT INTO orchestration_v2_effect_outbox (
347 effect_id, command_id, thread_id, effect_type, payload_json, status,
348 attempt_count, available_at, created_at, updated_at
349 ) VALUES (
350 ${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
351 'provider-runtime.continue',
352 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
353 'pending', 0, ${at}, ${at}, ${at}
354 )
355 `;
356
357 yield* orchestrator.dispatch({
358 type: "thread.stop",
359 commandId: CommandId.make("stop-restart"),
360 threadId,
361 });
362 yield* orchestrator.dispatch({
363 type: "message.dispatch",
364 commandId: CommandId.make("restart-continuation"),
365 threadId,
366 messageId: MessageId.make("message:restart-continuation"),
367 text: "Continue.",
368 attachments: [],
369 dispatchMode: { type: "start_immediately" },
370 createdBy: "agent",
371 creationSource: "server",
372 restartContinuationOfRunId: run.id,
373 });
374 assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
375 }).pipe(Effect.provide(layerTest)),
376);
377
378it.effect.each(["thread.stop", "run.interrupt"] as const)(
379 "a successful %s blocks a newer restart continuation when completion timestamps tie",
380 (stopType) =>
381 Effect.gen(function* () {
382 const orchestrator = yield* Orchestrator.OrchestratorV2;
383 const projections = yield* ProjectionStore.ProjectionStoreV2;
384 const sql = yield* SqlClient.SqlClient;
385 const threadId = ThreadId.make("thread:stop-resumed-queue");
386 yield* createWatchingThread(threadId, 12);
387 yield* send(threadId, "first", "start_immediately");
388 yield* send(threadId, "queued", "queue_after_active");
389 const now = yield* DateTime.now;
390 const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
391 assert.isDefined(first);
392 assert.isDefined(queued);
393 for (const run of [first!, queued!]) {
394 yield* projections.apply({
395 id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
396 type: "run.updated",
397 threadId,
398 runId: run.id,
399 occurredAt: now,
400 payload:
401 run.id === first!.id
402 ? { ...run, status: "completed", completedAt: now }
403 : { ...run, queueHeld: true },
404 });
405 }
406 // A later turn runs ahead of the held queue, then recovery cancels it.
407 yield* send(threadId, "restart source", "start_immediately");
408 const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
409 yield* projections.apply({
410 id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
411 type: "run.updated",
412 threadId,
413 runId: source.id,
414 occurredAt: now,
415 payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
416 });
417 const at = DateTime.formatIso(now);
418 yield* sql`
419 INSERT INTO orchestration_v2_effect_outbox (
420 effect_id, command_id, thread_id, effect_type, payload_json, status,
421 attempt_count, available_at, created_at, updated_at
422 ) VALUES (
423 ${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
424 'provider-runtime.continue',
425 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
426 'pending', 0, ${at}, ${at}, ${at}
427 )
428 `;
429 yield* orchestrator.dispatch({
430 type: "queue.resume",
431 commandId: CommandId.make("resume-older-queue"),
432 threadId,
433 });
434 assert.equal(
435 (yield* orchestrator.getThreadProjection(threadId)).runs.find(
436 (run) => run.id === queued!.id,
437 )?.status,
438 "starting",
439 );
440 yield* orchestrator.dispatch(
441 stopType === "thread.stop"
442 ? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
443 : {
444 type: "run.interrupt",
445 commandId: CommandId.make("stop-resumed-queue"),
446 threadId,
447 runId: queued!.id,
448 holdQueue: true,
449 },
450 );
451 const stopped = yield* orchestrator.getThreadProjection(threadId);
452 const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
453 assert.equal(interrupted.status, "interrupted");
454 assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
455 yield* orchestrator.dispatch({
456 type: "message.dispatch",
457 commandId: CommandId.make("restart-after-stop"),
458 threadId,
459 messageId: MessageId.make("message:restart-after-stop"),
460 text: "Continue.",
461 attachments: [],
462 dispatchMode: { type: "start_immediately" },
463 createdBy: "agent",
464 creationSource: "server",
465 restartContinuationOfRunId: source.id,
466 });
467 assert.deepEqual(yield* threadState(threadId), {
468 runs: ["completed", "interrupted", "cancelled"],
469 watched: [],
470 });
471 }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
472);
473
474it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
475 Effect.gen(function* () {
476 const orchestrator = yield* Orchestrator.OrchestratorV2;
477 const projections = yield* ProjectionStore.ProjectionStoreV2;
478 const threads = yield* ThreadManagementService.ThreadManagementService;
479 const parentThreadId = ThreadId.make("thread:stop-partial");
480 yield* createWatchingThread(parentThreadId, 6);
481 yield* send(parentThreadId, "work", "start_immediately");
482 const childThreadId = yield* delegate(parentThreadId, "stoppable task");
483 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
484 // A task whose thread is gone, listed before the one that can stop.
485 yield* projections.apply({
486 id: EventId.make("event:stop-partial:missing-task"),
487 type: "subagent.updated",
488 threadId: parentThreadId,
489 runId: task.runId!,
490 nodeId: NodeId.make("node:stop-partial:missing"),
491 providerInstanceId: instanceId,
492 occurredAt: yield* DateTime.now,
493 payload: {
494 ...task,
495 id: NodeId.make("node:stop-partial:missing"),
496 childThreadId: ThreadId.make("thread:stop-partial:missing"),
497 startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
498 },
499 });
500
501 const walked = yield* Effect.exit(
502 threads.stopDelegatedTasks({
503 threadId: parentThreadId,
504 commandId: CommandId.make("stop-partial"),
505 }),
506 );
507 assert.isTrue(Exit.isFailure(walked));
508 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
509 }).pipe(Effect.provide(layerTest)),
510);
511
512it.effect("thread.stop on a finished thread refuses a late agent watch", () =>
513 Effect.gen(function* () {
514 const orchestrator = yield* Orchestrator.OrchestratorV2;
515 const projections = yield* ProjectionStore.ProjectionStoreV2;
516 const threadId = ThreadId.make("thread:stop-finished");
517 yield* createWatchingThread(threadId, 9);
518 yield* send(threadId, "work", "start_immediately");
519 const now = yield* DateTime.now;
520 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
521 yield* projections.apply({
522 id: EventId.make("event:stop-finished:completed"),
523 type: "run.updated",
524 threadId,
525 runId: run.id,
526 occurredAt: now,
527 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
528 });
529
530 yield* orchestrator.dispatch({
531 type: "thread.stop",
532 commandId: CommandId.make("stop-finished"),
533 threadId,
534 });
535 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 10))));
536 assert.deepEqual(yield* threadState(threadId), { runs: ["completed"], watched: [] });
537 }).pipe(Effect.provide(layerTest)),
538);
539
540it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
541 Effect.gen(function* () {
542 const orchestrator = yield* Orchestrator.OrchestratorV2;
543 const projections = yield* ProjectionStore.ProjectionStoreV2;
544 const threadId = ThreadId.make("thread:stop-lost-session");
545 yield* createWatchingThread(threadId, 11);
546 yield* send(threadId, "work", "start_immediately");
547 const now = yield* DateTime.now;
548 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
549 // The turn is running, but its provider session is gone, so the interrupt fails.
550 yield* projections.apply({
551 id: EventId.make("event:stop-lost-session:running"),
552 type: "run.updated",
553 threadId,
554 runId: run.id,
555 occurredAt: now,
556 payload: { ...run, status: "running", startedAt: now },
557 });
558 yield* projections.apply({
559 id: EventId.make("event:stop-lost-session:turn"),
560 type: "provider-turn.updated",
561 threadId,
562 occurredAt: now,
563 payload: {
564 id: ProviderTurnId.make("provider-turn:stop-lost-session"),
565 providerThreadId: run.providerThreadId!,
566 nodeId: run.rootNodeId!,
567 runAttemptId: run.activeAttemptId!,
568 nativeTurnRef: null,
569 ordinal: 1,
570 status: "running",
571 startedAt: now,
572 completedAt: null,
573 },
574 });
575
576 yield* orchestrator.dispatch({
577 type: "thread.stop",
578 commandId: CommandId.make("stop-lost-session"),
579 threadId,
580 });
581 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
582 assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
583 }).pipe(Effect.provide(layerTest)),
584);