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

RestartContinuation.test.ts

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