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

RestartContinuation.test.ts

1,263 lines44.8 KB

1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 NodeId,
5 ProjectId,
6 ProviderDriverKind,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ProviderThreadId,
10 ProviderTurnId,
11 RunAttemptId,
12 RunId,
13 RuntimeRequestId,
14 ThreadId,
15 type OrchestrationV2Command,
16 type OrchestrationV2ThreadProjection,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as Layer from "effect/Layer";
21import * as ServerSettings from "../serverSettings.ts";
22import { restartContinuationRun, continueRestartedRun } from "./RestartContinuation.ts";
23import * as ThreadManagementService from "./ThreadManagementService.ts";
24import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
25import * as ProjectionStore from "./ProjectionStore.ts";
26import * as EventSink from "./EventSink.ts";
27import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
28import * as EffectWorker from "./EffectWorker.ts";
29import * as EffectOutbox from "./EffectOutbox.ts";
30​
31const threadId = ThreadId.make("thread:restart");
32const runId = RunId.make("run:restart");
33const instanceId = ProviderInstanceId.make("codex");
34const driver = ProviderDriverKind.make("codex");
35const providerThreadId = ProviderThreadId.make("provider-thread:restart");
36const sessionId = ProviderSessionId.make("session:restart");
37const attemptId = RunAttemptId.make("attempt:restart");
38const scratchProjectId = ProjectId.make("project:scratch");
39const now = DateTime.makeUnsafe("2026-10-03T12:00:00.000Z");
40​
41function makeProjection() {
42 return {
43 thread: {
44 id: threadId,
45 projectId: ProjectId.make("restart-project"),
46 providerInstanceId: instanceId,
47 archivedAt: null,
48 deletedAt: null,
49 },
50 runs: [
51 {
52 id: runId,
53 ordinal: 1,
54 providerInstanceId: instanceId,
55 modelSelection: { instanceId, model: "gpt-6" },
56 providerThreadId,
57 activeAttemptId: attemptId,
58 status: "running",
59 },
60 ],
61 providerThreads: [
62 {
63 id: providerThreadId,
64 appThreadId: threadId,
65 ownerNodeId: null,
66 driver,
67 providerInstanceId: instanceId,
68 providerSessionId: sessionId,
69 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
70 status: "active",
71 },
72 ],
73 providerSessions: [
74 { id: sessionId, driver, providerInstanceId: instanceId, status: "running" },
75 ],
76 providerTurns: [
77 {
78 id: ProviderTurnId.make("turn:restart"),
79 providerThreadId,
80 runAttemptId: attemptId,
81 status: "running",
82 },
83 ],
84 runtimeRequests: [],
85 attempts: [],
86 nodes: [],
87 subagents: [],
88 messages: [],
89 turnItems: [],
90 } as unknown as OrchestrationV2ThreadProjection;
92​
93it("requires matching saved native state for an unfinished root run", () => {
94 const projection = makeProjection();
95 assert.equal(restartContinuationRun(projection, now)?.id, runId);
96 for (const invalid of [
97 { ...projection, thread: { ...projection.thread, archivedAt: {} } },
98 { ...projection, thread: { ...projection.thread, deletedAt: {} } },
99 {
100 ...projection,
101 thread: { ...projection.thread, providerInstanceId: ProviderInstanceId.make("other") },
102 },
103 {
104 ...projection,
105 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
106 },
107 {
108 ...projection,
109 providerSessions: [
110 {
111 ...projection.providerSessions[0]!,
112 providerInstanceId: ProviderInstanceId.make("other"),
113 },
114 ],
115 },
116 { ...projection, providerTurns: [] },
117 ...[
118 "queued",
119 "preparing",
120 "starting",
121 "waiting",
122 "completed",
123 "cancelled",
124 "failed",
125 "interrupted",
126 ].map((status) => ({ ...projection, runs: [{ ...projection.runs[0]!, status }] })),
127 ])
128 assert.isUndefined(restartContinuationRun(invalid as OrchestrationV2ThreadProjection, now));
129});
130​
131it("continues a live turn whose session the adapter never marked running", () => {
132 const projection = makeProjection();
133 const withSessionStatus = (status: string) =>
134 ({
135 ...projection,
136 providerSessions: [{ ...projection.providerSessions[0]!, status }],
137 }) as OrchestrationV2ThreadProjection;
138 for (const status of ["starting", "ready", "running", "waiting"])
139 assert.equal(restartContinuationRun(withSessionStatus(status), now)?.id, runId, status);
140 for (const status of ["stopped", "error"])
141 assert.isUndefined(restartContinuationRun(withSessionStatus(status), now), status);
142});
143​
144it("recovers an admitted continuation after another crash before provider start", () => {
145 const projection = makeProjection();
146 const starting = {
147 ...projection,
148 runs: [
149 {
150 ...projection.runs[0]!,
151 status: "starting" as const,
152 restartContinuationOfRunId: RunId.make("run:previous-crash"),
153 },
154 ],
155 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
156 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
157 providerTurns: [],
158 };
159 assert.equal(restartContinuationRun(starting, now)?.id, runId);
160});
161​
162it("does not continue settled root runs with restart-cancelled background work", () => {
163 const projection = makeProjection();
164 const settled = {
165 ...projection,
166 runs: [
167 {
168 ...projection.runs[0]!,
169 status: "completed" as const,
170 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
171 },
172 ],
173 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
174 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
175 providerTurns: [],
176 };
177 for (const projectId of [scratchProjectId, projection.thread.projectId])
178 for (const status of ["completed", "waiting"] as const)
179 assert.isUndefined(
180 restartContinuationRun(
181 {
182 ...settled,
183 thread: { ...settled.thread, projectId },
184 runs: [{ ...settled.runs[0]!, status }],
185 },
186 now,
187 ),
188 );
189});
190​
191it.effect.each(["completed", "waiting", "cancelled"] as const)(
192 "ignores a pending restart continuation for a %s run whose provider turn settled",
193 (status) =>
194 Effect.gen(function* () {
195 const base = makeProjection();
196 const work = [{ kind: "shell" as const, label: "sleep 25 && echo DONE" }];
197 const projection = {
198 ...base,
199 runs: [{ ...base.runs[0]!, status, restartCancelledBackgroundWork: work }],
200 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
201 } as unknown as OrchestrationV2ThreadProjection;
202 const commands: Parameters<
203 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
204 >[0][] = [];
205 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
206 Effect.provide(
207 Layer.merge(
208 Layer.mock(ThreadManagementService.ThreadManagementService)({
209 getThreadRecords: () => Effect.succeed(projection),
210 recoverDelegatedTask: () => Effect.void,
211 dispatch: (command) => {
212 commands.push(command);
213 return Effect.succeed({} as never);
214 },
215 }),
216 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
217 ),
218 ),
219 );
220 assert.lengthOf(commands, 0);
221 }),
222);
223​
224it.effect.each(["completed", "waiting", "cancelled"] as const)(
225 "wakes a %s run whose monitor the restart cancelled, with the note as its prompt",
226 (status) =>
227 Effect.gen(function* () {
228 const base = makeProjection();
229 const work = [
230 { kind: "monitor" as const, label: "Watch CI run 42" },
231 { kind: "shell" as const, label: "vp run dev" },
232 ];
233 const projection = {
234 ...base,
235 runs: [{ ...base.runs[0]!, status, restartCancelledBackgroundWork: work }],
236 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
237 } as unknown as OrchestrationV2ThreadProjection;
238 const commands: Parameters<
239 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
240 >[0][] = [];
241 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
242 Effect.provide(
243 Layer.merge(
244 Layer.mock(ThreadManagementService.ThreadManagementService)({
245 getThreadRecords: () => Effect.succeed(projection),
246 recoverDelegatedTask: () => Effect.void,
247 dispatch: (command) => {
248 commands.push(command);
249 return Effect.succeed({} as never);
250 },
251 }),
252 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
253 ),
254 ),
255 );
256 assert.lengthOf(commands, 1);
257 const command = commands[0]!;
258 assert.equal(command.type, "message.dispatch");
259 if (command.type !== "message.dispatch") return;
260 assert.equal(command.restartContinuationOfRunId, runId);
261 assert.include(command.text, "- monitor: Watch CI run 42");
262 assert.include(command.text, "- shell: vp run dev");
263 }),
264);
265​
266it.effect("does not continue a failed run that lost background work", () =>
267 Effect.gen(function* () {
268 const base = makeProjection();
269 const projection = {
270 ...base,
271 runs: [
272 {
273 ...base.runs[0]!,
274 status: "failed",
275 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
276 },
277 ],
278 providerTurns: [{ ...base.providerTurns[0]!, status: "failed" }],
279 } as unknown as OrchestrationV2ThreadProjection;
280 const commands: Parameters<
281 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
282 >[0][] = [];
283 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
284 Effect.provide(
285 Layer.merge(
286 Layer.mock(ThreadManagementService.ThreadManagementService)({
287 getThreadRecords: () => Effect.succeed(projection),
288 recoverDelegatedTask: () => Effect.void,
289 dispatch: (command) => {
290 commands.push(command);
291 return Effect.succeed({} as never);
292 },
293 }),
294 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
295 ),
296 ),
297 );
298 assert.lengthOf(commands, 0);
299 }),
300);
301​
302it.effect.each([
303 [false, undefined],
304 [true, undefined],
305 [false, true],
306 [true, false],
307] as const)(
308 "atomically records restart intent with cancellation when opt-in is %s and project override is %s",
309 ([enabled, projectOverride]) =>
310 Effect.gen(function* () {
311 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
312 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
313 Effect.provide(
314 Layer.mergeAll(
315 ServerSettings.layerTest({
316 continueThreadsAfterServerUpdate: enabled,
317 projectSettingsOverrides:
318 projectOverride === undefined
319 ? {}
320 : {
321 [ProjectId.make("restart-project")]: {
322 continueThreadsAfterServerUpdate: projectOverride,
323 },
324 },
325 }),
326 Layer.mock(ProjectionStore.ProjectionStoreV2)({
327 getRecoveryThreadIds: () => Effect.succeed([threadId]),
328 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
329 }),
330 Layer.mock(EventSink.EventSinkV2)({
331 commitCommand: (input) => {
332 committed = input;
333 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
334 },
335 }),
336 IdAllocator.layer,
337 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
338 runRecoveryOnce: Effect.succeed(false),
339 }),
340 Layer.mock(EffectOutbox.EffectOutboxV2)({
341 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
342 }),
343 ),
344 ),
345 );
346 yield* recovery.reconcile("startup");
347 assert.isDefined(committed);
348 assert.isTrue(
349 committed!.events.some(
350 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
351 ),
352 );
353 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
354 if (projectOverride ?? enabled)
355 assert.deepEqual(committed!.effects[0]?.request, {
356 type: "provider-runtime.continue",
357 sourceRunId: runId,
358 });
359 }),
360);
361​
362it.effect("lets a cut blocking delegate_task wake its parent like an async task", () =>
363 Effect.gen(function* () {
364 const base = makeProjection();
365 const task = (id: string, completionWake: "settled_only" | "always", status: string) => ({
366 id: NodeId.make(id),
367 threadId,
368 runId,
369 origin: "app_owned",
370 childThreadId: ThreadId.make(`thread:${id}`),
371 driver,
372 providerInstanceId: instanceId,
373 completionWake,
374 status,
375 });
376 const projection = {
377 ...base,
378 subagents: [
379 task("task:waited", "settled_only", "running"),
380 task("task:async", "always", "running"),
381 task("task:finished", "settled_only", "completed"),
382 ],
383 } as unknown as OrchestrationV2ThreadProjection;
384 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
385 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
386 Effect.provide(
387 Layer.mergeAll(
388 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
389 Layer.mock(ProjectionStore.ProjectionStoreV2)({
390 getRecoveryThreadIds: () => Effect.succeed([threadId]),
391 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
392 }),
393 Layer.mock(EventSink.EventSinkV2)({
394 commitCommand: (input) => {
395 committed = input;
396 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
397 },
398 }),
399 IdAllocator.layer,
400 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
401 Layer.mock(EffectOutbox.EffectOutboxV2)({
402 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
403 }),
404 ),
405 ),
406 );
407 yield* recovery.reconcile("startup");
408 const upgraded = (committed?.events ?? []).flatMap((event) =>
409 event.type === "subagent.updated" ? [event.payload] : [],
410 );
411 assert.deepEqual(
412 upgraded.map((row) => ({ id: row.id, completionWake: row.completionWake })),
413 [{ id: NodeId.make("task:waited"), completionWake: "always" }],
414 );
415 }),
416);
417​
418it.effect.each(["running", "waiting"])(
419 "wakes a %s run to restart the native subagent it waited on",
420 (status) =>
421 Effect.gen(function* () {
422 const base = makeProjection();
423 const item = (id: string, extra: Record<string, unknown>) => ({
424 id,
425 threadId,
426 runId,
427 nodeId: null,
428 status: "running",
429 ...extra,
430 });
431 const projection = {
432 ...base,
433 runs: [{ ...base.runs[0]!, status }],
434 providerTurns: [
435 { ...base.providerTurns[0]!, status: status === "waiting" ? "completed" : "running" },
436 ],
437 turnItems: [
438 // Codex keeps a native subagent on its own child provider thread.
439 item("item:native", {
440 type: "subagent",
441 origin: "provider_native",
442 providerThreadId: ProviderThreadId.make("provider-thread:child"),
443 nativeItemRef: { driver, nativeId: "agent-1" },
444 title: "Sleeper",
445 childThreadId: ThreadId.make("thread:child"),
446 }),
447 item("item:shell", { type: "command_execution", providerThreadId, input: "ls" }),
448 ],
449 } as unknown as OrchestrationV2ThreadProjection;
450 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
451 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
452 Effect.provide(
453 Layer.mergeAll(
454 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
455 Layer.mock(ProjectionStore.ProjectionStoreV2)({
456 getRecoveryThreadIds: () => Effect.succeed([threadId]),
457 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
458 }),
459 Layer.mock(EventSink.EventSinkV2)({
460 commitCommand: (input) => {
461 committed = input;
462 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
463 },
464 }),
465 IdAllocator.layer,
466 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
467 Layer.mock(EffectOutbox.EffectOutboxV2)({
468 listByCommandId: () => Effect.succeed([]),
469 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
470 }),
471 ),
472 ),
473 );
474 yield* recovery.reconcile("startup");
475 const work = (committed?.events ?? []).flatMap((event) =>
476 event.type === "run.background-work-cancelled" ? [event.payload] : [],
477 );
478 // The subagent is reported on the run that awaited it. A running run's
479 // shell died with its turn.
480 assert.deepEqual(work, [
481 {
482 runId,
483 restartCancelledBackgroundWork: [
484 { kind: "subagent", label: "Sleeper (id agent-1)", id: "item:native" },
485 ...(status === "waiting"
486 ? [{ kind: "shell" as const, label: "ls", id: "item:shell" }]
487 : []),
488 ],
489 },
490 ]);
491 assert.deepEqual(
492 committed?.effects.map((effect) => effect.request),
493 [{ type: "provider-runtime.continue", sourceRunId: runId }],
494 );
495 }),
496);
497​
498it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
499 Effect.gen(function* () {
500 let projection = makeProjection();
501 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
502 const commands: Parameters<
503 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
504 >[0][] = [];
505 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
506 getThreadRecords: () => Effect.succeed(projection),
507 recoverDelegatedTask: () => Effect.void,
508 dispatch: (command) => {
509 commands.push(command);
510 if (command.type === "message.dispatch")
511 projection = { ...projection, messages: [{ id: command.messageId } as never] };
512 return Effect.succeed({} as never);
513 },
514 });
515 const layerEnabled = Layer.merge(
516 layerThreads,
517 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
518 );
519 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
520 Effect.provide(layerEnabled),
521 );
522 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
523 Effect.provide(layerEnabled),
524 );
525 assert.lengthOf(commands, 1);
526 assert.match(String(commands[0]!.commandId), /run:restart$/);
527 if (commands[0]!.type === "message.dispatch")
528 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
529 projection = {
530 ...projection,
531 messages: [],
532 runs: [
533 ...projection.runs,
534 {
535 ...projection.runs[0]!,
536 id: RunId.make("run:user-newer"),
537 ordinal: 2,
538 status: "completed",
539 },
540 ],
541 };
542 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
543 Effect.provide(layerEnabled),
544 );
545 assert.lengthOf(commands, 1);
546 projection = { ...projection, runs: [projection.runs[0]!] };
547 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
548 Effect.provide(
549 Layer.merge(
550 layerThreads,
551 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false }),
552 ),
553 ),
554 );
555 assert.lengthOf(commands, 1);
556 }),
557);
558​
559it.effect("prepares no continuation for background work another provider thread launched", () =>
560 Effect.gen(function* () {
561 const base = makeProjection();
562 const claudeThreadId = ProviderThreadId.make("provider-thread:claude");
563 const projection = {
564 ...base,
565 runs: [{ ...base.runs[0]!, status: "completed" }],
566 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
567 turnItems: [
568 {
569 id: "turn-item:claude-subagent",
570 runId: RunId.make("run:claude"),
571 providerThreadId: claudeThreadId,
572 type: "subagent",
573 status: "running",
574 },
575 ],
576 } as unknown as OrchestrationV2ThreadProjection;
577 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
578 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
579 Effect.provide(
580 Layer.mergeAll(
581 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
582 Layer.mock(ProjectionStore.ProjectionStoreV2)({
583 getRecoveryThreadIds: () => Effect.succeed([threadId]),
584 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
585 }),
586 Layer.mock(EventSink.EventSinkV2)({
587 writeWithEffects: (input) =>
588 Effect.sync(() => {
589 writes.push(input);
590 return [];
591 }),
592 }),
593 IdAllocator.layer,
594 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
595 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
596 ),
597 ),
598 );
599 yield* recovery.prepareForShutdown;
600 assert.lengthOf(writes, 0);
601 const ownWork = {
602 ...projection,
603 turnItems: [{ ...projection.turnItems[0]!, providerThreadId }],
604 } as OrchestrationV2ThreadProjection;
605 const ownRecovery = yield* ProviderRuntimeRecovery.make.pipe(
606 Effect.provide(
607 Layer.mergeAll(
608 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
609 Layer.mock(ProjectionStore.ProjectionStoreV2)({
610 getRecoveryThreadIds: () => Effect.succeed([threadId]),
611 getRuntimeRecoveryProjection: () => Effect.succeed(ownWork),
612 }),
613 Layer.mock(EventSink.EventSinkV2)({
614 writeWithEffects: (input) =>
615 Effect.sync(() => {
616 writes.push(input);
617 return [];
618 }),
619 }),
620 IdAllocator.layer,
621 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
622 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
623 ),
624 ),
625 );
626 yield* ownRecovery.prepareForShutdown;
627 assert.lengthOf(writes, 1);
628 assert.deepEqual(writes[0]!.effects[0]?.request, {
629 type: "provider-runtime.continue",
630 sourceRunId: runId,
631 });
632 }),
633);
634​
635const backgroundSubagent = {
636 turnItem: {
637 id: "turn-item:background-subagent",
638 runId,
639 nodeId: null,
640 providerThreadId,
641 providerInstanceId: instanceId,
642 type: "subagent",
643 subagentId: "subagent:background",
644 title: "Background reviewer",
645 status: "running",
646 },
647 work: {
648 kind: "subagent" as const,
649 label: "Background reviewer",
650 id: "turn-item:background-subagent",
651 },
652};
653const devServer = {
654 turnItem: {
655 id: "turn-item:dev-server",
656 runId,
657 nodeId: null,
658 providerThreadId,
659 providerInstanceId: instanceId,
660 type: "command_execution",
661 input: "vp run dev",
662 status: "running",
663 },
664 work: { kind: "shell" as const, label: "vp run dev", id: "turn-item:dev-server" },
665};
666​
667it.effect.each([
668 ["completed", scratchProjectId, backgroundSubagent, true],
669 ["waiting", ProjectId.make("restart-project"), backgroundSubagent, true],
670 ["completed", ProjectId.make("restart-project"), devServer, false],
671 ["waiting", scratchProjectId, devServer, false],
672] as const)(
673 "cleans up background work of a %s run in project %s and wakes it only for awaited work",
674 ([status, projectId, background, wakes]) =>
675 Effect.gen(function* () {
676 const base = makeProjection();
677 const projection = {
678 ...base,
679 thread: { ...base.thread, projectId },
680 runs: [{ ...base.runs[0]!, status }],
681 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
682 turnItems: [background.turnItem],
683 subagents:
684 background === backgroundSubagent
685 ? [
686 {
687 id: "subagent:background",
688 runId,
689 origin: "provider_native",
690 driver,
691 providerInstanceId: instanceId,
692 status: "running",
693 },
694 ]
695 : [],
696 } as unknown as OrchestrationV2ThreadProjection;
697 for (const trigger of ["startup", "shutdown"] as const) {
698 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
699 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
700 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
701 Effect.provide(
702 Layer.mergeAll(
703 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
704 Layer.mock(ProjectionStore.ProjectionStoreV2)({
705 getRecoveryThreadIds: () => Effect.succeed([threadId]),
706 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
707 }),
708 Layer.mock(EventSink.EventSinkV2)({
709 writeWithEffects: (input) =>
710 Effect.sync(() => {
711 writes.push(input);
712 return [];
713 }),
714 commitCommand: (input) =>
715 Effect.sync(() => {
716 commits.push(input);
717 return { committed: true, cancelledEffectCount: 0 } as never;
718 }),
719 }),
720 IdAllocator.layer,
721 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
722 runRecoveryOnce: Effect.succeed(false),
723 }),
724 Layer.mock(EffectOutbox.EffectOutboxV2)({
725 listByCommandId: () => Effect.succeed([]),
726 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
727 }),
728 ),
729 ),
730 );
731 if (trigger === "shutdown") yield* recovery.prepareForShutdown;
732 yield* recovery.reconcile(trigger);
733 const recorded = [...writes.flatMap((write) => write.effects), ...commits[0]!.effects];
734 assert.deepEqual(
735 recorded.map((effect) => effect.request),
736 wakes ? [{ type: "provider-runtime.continue", sourceRunId: runId }] : [],
737 );
738 assert.lengthOf(commits, 1);
739 const events = commits[0]!.events;
740 assert.isTrue(
741 events.some(
742 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
743 ),
744 );
745 const note = events.find((event) => event.type === "run.background-work-cancelled");
746 assert.equal(note?.runId, runId);
747 assert.deepEqual(note?.payload.restartCancelledBackgroundWork, [background.work]);
748 if (status === "completed")
749 assert.isFalse(events.some((event) => event.type === "run.updated"));
750 }
751 }),
752);
753​
754it("does not wake a settled run for work left by a session that already stopped", () => {
755 const base = makeProjection();
756 const projection = {
757 ...base,
758 runs: [{ ...base.runs[0]!, status: "completed" }],
759 providerThreads: [{ ...base.providerThreads[0]!, status: "idle" }],
760 turnItems: [backgroundSubagent.turnItem],
761 } as unknown as OrchestrationV2ThreadProjection;
762 assert.equal(restartContinuationRun(projection, now)?.id, runId);
763 for (const status of ["stopped", "error"])
764 assert.isUndefined(
765 restartContinuationRun(
766 {
767 ...projection,
768 providerSessions: [{ ...projection.providerSessions[0]!, status }],
769 } as OrchestrationV2ThreadProjection,
770 now,
771 ),
772 status,
773 );
774});
775​
776it.effect("wakes a run whose subagent's own shell the restart cut, past a wake it cut first", () =>
777 Effect.gen(function* () {
778 const base = makeProjection();
779 const cutWake = {
780 ...base.runs[0]!,
781 id: RunId.make("run:wake"),
782 ordinal: 2,
783 status: "starting",
784 startedAt: null,
785 };
786 const withShell = (parentTaskId?: string) =>
787 ({
788 ...base,
789 runs: [{ ...base.runs[0]!, status: "waiting", startedAt: now }, cutWake],
790 providerThreads: [
791 {
792 ...base.providerThreads[0]!,
793 status: "idle",
794 pendingBackgroundTasks: [
795 {
796 kind: "command",
797 taskId: "shell:1",
798 description: "sleep 150",
799 ...(parentTaskId === undefined ? {} : { parentTaskId }),
800 },
801 ],
802 },
803 ],
804 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
805 }) as unknown as OrchestrationV2ThreadProjection;
806 assert.equal(restartContinuationRun(withShell("agent:1"), now)?.id, runId);
807 // A shell the agent started itself still does not wake it.
808 assert.isUndefined(restartContinuationRun(withShell(), now));
809​
810 const texts = yield* continuationTexts({
811 ...base,
812 runs: [
813 {
814 ...base.runs[0]!,
815 status: "completed",
816 startedAt: now,
817 completedAt: now,
818 restartCancelledBackgroundWork: [
819 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
820 ],
821 },
822 { ...cutWake, status: "cancelled", completedAt: now },
823 ],
824 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
825 } as unknown as OrchestrationV2ThreadProjection);
826 assert.lengthOf(texts, 1);
827 assert.include(texts[0], "- subagent: sleep 150 (subagent agent:1)");
828 // A run the user stopped before it started still takes precedence.
829 const stopped = yield* continuationTexts({
830 ...base,
831 runs: [
832 {
833 ...base.runs[0]!,
834 status: "completed",
835 startedAt: now,
836 completedAt: now,
837 restartCancelledBackgroundWork: [
838 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
839 ],
840 },
841 { ...cutWake, status: "interrupted", completedAt: now },
842 ],
843 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
844 } as unknown as OrchestrationV2ThreadProjection);
845 assert.lengthOf(stopped, 0);
846 }),
847);
848​
849it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
850 Effect.gen(function* () {
851 let projection = makeProjection();
852 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
853 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
854 Effect.provide(
855 Layer.mergeAll(
856 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
857 Layer.mock(ProjectionStore.ProjectionStoreV2)({
858 getRecoveryThreadIds: () => Effect.succeed([threadId]),
859 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
860 }),
861 Layer.mock(EventSink.EventSinkV2)({
862 writeWithEffects: (input) =>
863 Effect.sync(() => {
864 assert.lengthOf(input.events, 0);
865 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
866 projection = {
867 ...projection,
868 runs: [{ ...projection.runs[0]!, status: "completed" }],
869 };
870 return [];
871 }),
872 commitCommand: (input) =>
873 Effect.sync(() => {
874 commits.push(input);
875 return { committed: true, cancelledEffectCount: 0 } as never;
876 }),
877 }),
878 IdAllocator.layer,
879 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
880 runRecoveryOnce: Effect.succeed(false),
881 }),
882 Layer.mock(EffectOutbox.EffectOutboxV2)({
883 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
884 }),
885 ),
886 ),
887 );
888 yield* recovery.prepareForShutdown;
889 yield* recovery.reconcile("shutdown");
890 assert.isFalse(
891 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
892 );
893 let dispatched = false;
894 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
895 Effect.provide(
896 Layer.mergeAll(
897 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
898 Layer.mock(ThreadManagementService.ThreadManagementService)({
899 getThreadRecords: () => Effect.succeed(projection),
900 recoverDelegatedTask: () => Effect.void,
901 dispatch: () =>
902 Effect.sync(() => {
903 dispatched = true;
904 return {} as never;
905 }),
906 }),
907 ),
908 ),
909 );
910 assert.isFalse(dispatched);
911 }),
912);
913​
914const continuationDispatches = (projection: OrchestrationV2ThreadProjection) =>
915 Effect.gen(function* () {
916 const dispatches: Array<Extract<OrchestrationV2Command, { type: "message.dispatch" }>> = [];
917 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
918 Effect.provide(
919 Layer.merge(
920 Layer.mock(ThreadManagementService.ThreadManagementService)({
921 getThreadRecords: () => Effect.succeed(projection),
922 recoverDelegatedTask: () => Effect.void,
923 dispatch: (command) => {
924 if (command.type === "message.dispatch") dispatches.push(command);
925 return Effect.succeed({} as never);
926 },
927 }),
928 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
929 ),
930 ),
931 );
932 return dispatches;
933 });
934​
935const continuationTexts = (projection: OrchestrationV2ThreadProjection) =>
936 continuationDispatches(projection).pipe(
937 Effect.map((dispatches) => dispatches.map((command) => command.text)),
938 );
939​
940const cutMidTurn = (extra: Record<string, unknown> = {}) => {
941 const base = makeProjection();
942 return {
943 ...base,
944 runs: [
945 {
946 ...base.runs[0]!,
947 status: "cancelled",
948 userMessageId: MessageId.make("message:user"),
949 ...extra,
950 },
951 ],
952 providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }],
953 } as unknown as OrchestrationV2ThreadProjection;
954};
955​
956const queuedFollowUp = {
957 id: RunId.make("run:queued"),
958 ordinal: 2,
959 providerInstanceId: instanceId,
960 providerThreadId,
961 status: "queued",
962 queueHeld: true,
963};
964​
965it.effect("continues a cut run past queued follow-ups, which stay held", () =>
966 Effect.gen(function* () {
967 const live = makeProjection();
968 assert.equal(
969 restartContinuationRun(
970 {
971 ...live,
972 runs: [...live.runs, queuedFollowUp],
973 } as unknown as OrchestrationV2ThreadProjection,
974 now,
975 )?.id,
976 runId,
977 );
978 const cut = cutMidTurn();
979 const texts = yield* continuationTexts({
980 ...cut,
981 runs: [...cut.runs, queuedFollowUp],
982 } as unknown as OrchestrationV2ThreadProjection);
983 assert.deepEqual(texts, ["Continue where you left off."]);
984 }),
985);
986​
987it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
988 Effect.gen(function* () {
989 const finishedContinuation = {
990 id: RunId.make("run:earlier-continuation"),
991 ordinal: 3,
992 providerInstanceId: instanceId,
993 providerThreadId,
994 status: "completed",
995 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
996 };
997 const live = makeProjection();
998 assert.equal(
999 restartContinuationRun(
1001 ...live,
1002 runs: [...live.runs, finishedContinuation],
1003 } as unknown as OrchestrationV2ThreadProjection,
1004 now,
1005 )?.id,
1006 runId,
1007 );
1008 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
1009 const texts = yield* continuationTexts({
1010 ...cut,
1011 runs: [...cut.runs, finishedContinuation],
1012 } as unknown as OrchestrationV2ThreadProjection);
1013 assert.deepEqual(texts, ["Continue where you left off."]);
1014 }),
1016​
1017it.effect("does not continue a run the user asked to stop before the restart", () =>
1018 Effect.gen(function* () {
1019 const texts = yield* continuationTexts({
1020 ...cutMidTurn(),
1021 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
1022 } as unknown as OrchestrationV2ThreadProjection);
1023 assert.deepEqual(texts, []);
1024 }),
1026​
1027it.effect("does not continue a cut /compact or /logout turn", () =>
1028 Effect.gen(function* () {
1029 for (const text of ["/compact", " /LOGOUT "]) {
1030 const texts = yield* continuationTexts({
1031 ...cutMidTurn(),
1032 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
1033 } as unknown as OrchestrationV2ThreadProjection);
1034 assert.deepEqual(texts, [], text);
1036 const texts = yield* continuationTexts({
1037 ...cutMidTurn(),
1038 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
1039 } as unknown as OrchestrationV2ThreadProjection);
1040 assert.lengthOf(texts, 1);
1041 }),
1043​
1044it.effect("tells a turn cut mid-way about the background work it lost", () =>
1045 Effect.gen(function* () {
1046 const texts = yield* continuationTexts(
1047 cutMidTurn({
1048 restartCancelledBackgroundWork: [{ kind: "subagent", label: "Background reviewer" }],
1049 }),
1050 );
1051 assert.lengthOf(texts, 1);
1052 assert.include(texts[0]!, "Background reviewer");
1053 assert.isTrue(texts[0]!.endsWith("Continue where you left off."));
1054 }),
1056​
1057it.effect("shows a continuation as a T3 Code notice whose detail is the prompt", () =>
1058 Effect.gen(function* () {
1059 const [resumed] = yield* continuationDispatches(cutMidTurn());
1060 assert.deepEqual(resumed?.notification, {
1061 source: { kind: "system" },
1062 outcome: "updated",
1063 summary: "T3 Code restarted and resumed this turn",
1064 detail: "Continue where you left off.",
1065 });
1066 }),
1068​
1069it.effect(
1070 "carries the note forward when its continuation was cut before reaching the provider",
1071 () =>
1072 Effect.gen(function* () {
1073 const base = makeProjection();
1074 const original = {
1075 ...base.runs[0]!,
1076 id: RunId.make("run:original"),
1077 status: "completed",
1078 activeAttemptId: RunAttemptId.make("attempt:original"),
1079 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
1080 };
1081 const projection = {
1082 ...base,
1083 runs: [
1084 original,
1086 ...base.runs[0]!,
1087 ordinal: 2,
1088 status: "cancelled",
1089 restartContinuationOfRunId: original.id,
1090 },
1091 ],
1092 providerTurns: [
1094 ...base.providerTurns[0]!,
1095 runAttemptId: original.activeAttemptId,
1096 status: "completed",
1097 },
1098 ],
1099 } as unknown as OrchestrationV2ThreadProjection;
1100 const texts = yield* continuationTexts(projection);
1101 assert.lengthOf(texts, 1);
1102 assert.include(texts[0]!, "sleep 25 && echo DONE");
1103 assert.notInclude(texts[0]!, "Continue where");
1104 }),
1106​
1107it.effect("prepares later threads' continuations when one thread fails", () =>
1108 Effect.gen(function* () {
1109 const brokenThreadId = ThreadId.make("thread:broken");
1110 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
1111 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
1112 Effect.provide(
1113 Layer.mergeAll(
1114 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
1115 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1116 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
1117 getRuntimeRecoveryProjection: (id) =>
1118 id === brokenThreadId
1119 ? Effect.fail(
1120 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
1122 : Effect.succeed(makeProjection()),
1123 }),
1124 Layer.mock(EventSink.EventSinkV2)({
1125 writeWithEffects: (input) =>
1126 Effect.sync(() => {
1127 writes.push(input);
1128 return [];
1129 }),
1130 }),
1131 IdAllocator.layer,
1132 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
1133 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
1134 ),
1135 ),
1136 );
1137 yield* recovery.prepareForShutdown;
1138 assert.deepEqual(
1139 writes.map((write) => write.effects[0]?.request),
1140 [{ type: "provider-runtime.continue", sourceRunId: runId }],
1141 );
1142 }),
1144​
1145it.effect("stops continuing after three automatic restart continuations in a row", () =>
1146 Effect.gen(function* () {
1147 const first = RunId.make("run:first-continuation");
1148 const second = RunId.make("run:second-continuation");
1149 const cut = cutMidTurn({ restartContinuationOfRunId: second });
1150 const withTwoLinks = {
1151 ...cut,
1152 runs: [
1153 ...cut.runs,
1154 { ...cut.runs[0]!, id: second, restartContinuationOfRunId: first },
1155 { ...cut.runs[0]!, id: first, restartContinuationOfRunId: undefined },
1156 ],
1157 } as unknown as OrchestrationV2ThreadProjection;
1158 assert.lengthOf(yield* continuationTexts(withTwoLinks), 1);
1159​
1160 const withThreeLinks = {
1161 ...withTwoLinks,
1162 runs: withTwoLinks.runs.map((run) =>
1163 run.id === first ? { ...run, restartContinuationOfRunId: RunId.make("run:root") } : run,
1164 ),
1165 } as unknown as OrchestrationV2ThreadProjection;
1166 assert.lengthOf(yield* continuationTexts(withThreeLinks), 0);
1167 }),
1169​
1170it.effect.each([
1171 ["user_input", "pending", "live", false],
1172 ["user_input", "expired", "not_resumable", false],
1173 ["user_input", "cancelled", "not_resumable", false],
1174 ["command", "pending", "live", false],
1175 ["command", "expired", "not_resumable", false],
1176 ["user_input", "resolved", "live", true],
1177 ["command", "cancelled", "live", true],
1178 ["user_input", "pending", "message", true],
1179 ["dynamic_tool_call", "pending", "live", true],
1180 ["auth_refresh", "pending", "live", true],
1181] as const)(
1182 "a %s request that is %s with %s capability allows continuation: %s",
1183 ([kind, status, capability, shouldContinue]) =>
1184 Effect.gen(function* () {
1185 const base = makeProjection();
1186 const runtimeRequests = [
1188 id: RuntimeRequestId.make("request:restart"),
1189 nodeId: NodeId.make("node:restart-question"),
1190 providerTurnId: base.providerTurns[0]!.id,
1191 kind,
1192 status,
1193 responseCapability:
1194 capability === "live"
1195 ? { type: capability, providerSessionId: sessionId }
1196 : capability === "not_resumable"
1197 ? { type: capability, reason: "The server restarted." }
1198 : { type: capability },
1199 },
1200 ];
1201 const live = { ...base, runtimeRequests } as unknown as OrchestrationV2ThreadProjection;
1202 assert.equal(restartContinuationRun(live, now) !== undefined, shouldContinue);
1203 const cut = {
1204 ...cutMidTurn(),
1205 runtimeRequests,
1206 } as unknown as OrchestrationV2ThreadProjection;
1207 assert.lengthOf(yield* continuationTexts(cut), shouldContinue ? 1 : 0);
1208 }),
1210​
1211it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
1212 Effect.gen(function* () {
1213 const live = makeProjection();
1214 for (const held of [
1215 { snoozedUntil: DateTime.add(now, { days: 1 }) },
1216 { settledOverride: "settled" as const },
1217 ]) {
1218 const thread = { ...live.thread, ...held };
1219 assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
1220 assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
1222 const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
1223 assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
1224 }),
1226​
1227it.effect("does not continue a run waiting on a secret the restart closed", () =>
1228 Effect.gen(function* () {
1229 const completedAt = DateTime.makeUnsafe("2026-10-03T10:05:00.000Z");
1230 const secret = (secretStatus: string, at: DateTime.Utc | null) =>
1231 ({ type: "secret_request", runId, secretStatus, completedAt: at }) as never;
1232 assert.isUndefined(
1233 restartContinuationRun({ ...makeProjection(), turnItems: [secret("pending", null)] }, now),
1234 );
1235 const cut = cutMidTurn({ completedAt });
1236 assert.deepEqual(
1237 yield* continuationTexts({ ...cut, turnItems: [secret("cancelled", completedAt)] }),
1238 [],
1239 );
1240 assert.lengthOf(
1241 yield* continuationTexts({
1242 ...cut,
1243 turnItems: [secret("cancelled", DateTime.subtract(completedAt, { seconds: 1 }))],
1244 }),
1245 1,
1246 );
1247 }),
1249​
1250it.effect.each(["completed", "failed", "interrupted"] as const)(
1251 "does not continue when the provider turn %s before the app run settled",
1252 (status) =>
1253 Effect.gen(function* () {
1254 const cut = cutMidTurn();
1255 assert.deepEqual(
1256 yield* continuationTexts({
1257 ...cut,
1258 providerTurns: [{ ...cut.providerTurns[0]!, status }],
1259 }),
1260 [],
1261 );
1262 }),