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

RestartContinuation.test.ts

1,264 lines45.1 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, [
919 "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it.",
920 ]);
921 }),
922);
923​
924it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
925 Effect.gen(function* () {
926 const finishedContinuation = {
927 id: RunId.make("run:earlier-continuation"),
928 ordinal: 3,
929 providerInstanceId: instanceId,
930 providerThreadId,
931 status: "completed",
932 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
933 };
934 const live = makeProjection();
935 assert.equal(
936 restartContinuationRun(
937 {
938 ...live,
939 runs: [...live.runs, finishedContinuation],
940 } as unknown as OrchestrationV2ThreadProjection,
941 now,
942 )?.id,
943 runId,
944 );
945 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
946 const texts = yield* continuationTexts({
947 ...cut,
948 runs: [...cut.runs, finishedContinuation],
949 } as unknown as OrchestrationV2ThreadProjection);
950 assert.deepEqual(texts, [
951 "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it.",
952 ]);
953 }),
954);
955​
956it("backs off twice from a continuation the provider never took, then lets it fail", () => {
957 const base = makeProjection();
958 const failedStart = (id: string, of: RunId) => ({
959 ...base.runs[0]!,
960 id: RunId.make(id),
961 activeAttemptId: RunAttemptId.make(`attempt:${id}`),
962 status: "failed" as const,
963 restartContinuationOfRunId: of,
964 });
965 const first = failedStart("run:retry-1", runId);
966 const second = failedStart("run:retry-2", first.id);
967 const third = failedStart("run:retry-3", second.id);
968 const projection = (failureClass = "provider_error", providerTurns = base.providerTurns) =>
969 ({
970 runs: [{ ...base.runs[0]!, status: "cancelled" }, first, second, third],
971 providerTurns,
972 turnItems: [first, second, third].map((run) => ({
973 id: `error:${run.id}`,
974 type: "error",
975 status: "failed",
976 runId: run.id,
977 nodeId: run.rootNodeId,
978 ordinal: 1,
979 updatedAt: now,
980 failure: { class: failureClass, message: "Failed.", code: null, retryable: null },
981 })),
982 }) as unknown as Parameters<typeof continuationStartRetryDelayMs>[1];
983 assert.deepEqual(
984 [first, second, third].map((run) => continuationStartRetryDelayMs(run, projection())),
985 [60_000, 180_000, undefined],
986 );
987 for (const failureClass of ["usage_limit", "permission_error", "validation_error"])
988 assert.isUndefined(continuationStartRetryDelayMs(first, projection(failureClass)));
989 // Once the provider took the prompt, starting again would repeat the turn.
990 assert.isUndefined(
991 continuationStartRetryDelayMs(
992 first,
993 projection("provider_error", [
994 { ...base.providerTurns[0]!, runAttemptId: first.activeAttemptId, status: "failed" },
995 ] as never),
996 ),
997 );
998});
999​
1000it.effect("continues again after a continuation fails before its prompt", () =>
1001 Effect.gen(function* () {
1002 const cut = cutMidTurn();
1003 const failedStart = {
1004 ...cut.runs[0]!,
1005 id: RunId.make("run:failed-start"),
1006 ordinal: 2,
1007 activeAttemptId: RunAttemptId.make("attempt:failed-start"),
1008 status: "failed",
1009 restartContinuationOfRunId: runId,
1010 };
1011 const dispatches = yield* continuationDispatches(
1012 { ...cut, runs: [...cut.runs, failedStart] } as unknown as OrchestrationV2ThreadProjection,
1013 failedStart.id,
1014 );
1015 assert.deepEqual(
1016 dispatches.map((command) => command.restartContinuationOfRunId),
1017 [failedStart.id],
1018 );
1019 }),
1021​
1022it.effect.each([
1023 ["running", null, 0],
1024 ["completed", "Done.", 1],
1025] as const)(
1026 "a parent's Stop on the task's run blocks the child only while the task is %s",
1027 ([status, result, expected]) =>
1028 Effect.gen(function* () {
1029 const parentThreadId = ThreadId.make("thread:parent");
1030 const parentRunId = RunId.make("run:parent");
1031 const taskId = NodeId.make("node:task");
1032 const cut = cutMidTurn();
1033 const child = {
1034 ...cut,
1035 thread: {
1036 ...cut.thread,
1037 lineage: { parentThreadId, relationshipToParent: "subagent" },
1038 forkedFrom: { type: "node", nodeId: taskId },
1039 },
1040 } as unknown as OrchestrationV2ThreadProjection;
1041 const parent = {
1042 thread: { id: parentThreadId },
1043 subagents: [{ id: taskId, runId: parentRunId, origin: "app_owned", status, result }],
1044 turnItems: [{ id: "turn-item:stop", runId: parentRunId, type: "run_interrupt_request" }],
1045 };
1046 let dispatched = 0;
1047 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
1048 Effect.provide(
1049 Layer.merge(
1050 Layer.mock(ThreadManagementService.ThreadManagementService)({
1051 getThreadRecords: (id) =>
1052 Effect.succeed((id === parentThreadId ? parent : child) as never),
1053 recoverDelegatedTask: () => Effect.void,
1054 dispatch: () =>
1055 Effect.sync(() => {
1056 dispatched += 1;
1057 return {} as never;
1058 }),
1059 }),
1060 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
1061 ),
1062 ),
1063 );
1064 assert.equal(dispatched, expected);
1065 }),
1067​
1068it.effect("does not continue a run the user asked to stop before the restart", () =>
1069 Effect.gen(function* () {
1070 const texts = yield* continuationTexts({
1071 ...cutMidTurn(),
1072 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
1073 } as unknown as OrchestrationV2ThreadProjection);
1074 assert.deepEqual(texts, []);
1075 }),
1077​
1078it.effect("does not continue a cut /compact or /logout turn", () =>
1079 Effect.gen(function* () {
1080 for (const text of ["/compact", " /LOGOUT "]) {
1081 const texts = yield* continuationTexts({
1082 ...cutMidTurn(),
1083 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
1084 } as unknown as OrchestrationV2ThreadProjection);
1085 assert.deepEqual(texts, [], text);
1087 const texts = yield* continuationTexts({
1088 ...cutMidTurn(),
1089 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
1090 } as unknown as OrchestrationV2ThreadProjection);
1091 assert.lengthOf(texts, 1);
1092 }),
1094​
1095it.effect(
1096 "carries the note forward when its continuation was cut before reaching the provider",
1097 () =>
1098 Effect.gen(function* () {
1099 const base = makeProjection();
1100 const original = {
1101 ...base.runs[0]!,
1102 id: RunId.make("run:original"),
1103 status: "completed",
1104 activeAttemptId: RunAttemptId.make("attempt:original"),
1105 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
1106 };
1107 const projection = {
1108 ...base,
1109 runs: [
1110 original,
1112 ...base.runs[0]!,
1113 ordinal: 2,
1114 status: "cancelled",
1115 restartContinuationOfRunId: original.id,
1116 },
1117 ],
1118 providerTurns: [
1120 ...base.providerTurns[0]!,
1121 runAttemptId: original.activeAttemptId,
1122 status: "completed",
1123 },
1124 ],
1125 } as unknown as OrchestrationV2ThreadProjection;
1126 const texts = yield* continuationTexts(projection);
1127 assert.lengthOf(texts, 1);
1128 assert.include(texts[0]!, "sleep 25 && echo DONE");
1129 assert.notInclude(texts[0]!, "Continue where");
1130 }),
1132​
1133it.effect("prepares later threads' continuations when one thread fails", () =>
1134 Effect.gen(function* () {
1135 const brokenThreadId = ThreadId.make("thread:broken");
1136 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
1137 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
1138 Effect.provide(
1139 Layer.mergeAll(
1140 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
1141 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1142 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
1143 getRuntimeRecoveryProjection: (id) =>
1144 id === brokenThreadId
1145 ? Effect.fail(
1146 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
1148 : Effect.succeed(makeProjection()),
1149 }),
1150 Layer.mock(EventSink.EventSinkV2)({
1151 writeWithEffects: (input) =>
1152 Effect.sync(() => {
1153 writes.push(input);
1154 return [];
1155 }),
1156 }),
1157 IdAllocator.layer,
1158 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
1159 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
1160 ),
1161 ),
1162 );
1163 yield* recovery.prepareForShutdown;
1164 assert.deepEqual(
1165 writes.map((write) => write.effects[0]?.request),
1166 [{ type: "provider-runtime.continue", sourceRunId: runId }],
1167 );
1168 }),
1170​
1171it.effect.each([
1172 ["user_input", "pending", "live", false],
1173 ["user_input", "expired", "not_resumable", false],
1174 ["user_input", "cancelled", "not_resumable", false],
1175 ["command", "pending", "live", false],
1176 ["command", "expired", "not_resumable", false],
1177 ["user_input", "resolved", "live", true],
1178 ["command", "cancelled", "live", true],
1179 ["user_input", "pending", "message", true],
1180 ["dynamic_tool_call", "pending", "live", true],
1181 ["auth_refresh", "pending", "live", true],
1182] as const)(
1183 "a %s request that is %s with %s capability allows continuation: %s",
1184 ([kind, status, capability, shouldContinue]) =>
1185 Effect.gen(function* () {
1186 const base = makeProjection();
1187 const runtimeRequests = [
1189 id: RuntimeRequestId.make("request:restart"),
1190 nodeId: NodeId.make("node:restart-question"),
1191 providerTurnId: base.providerTurns[0]!.id,
1192 kind,
1193 status,
1194 responseCapability:
1195 capability === "live"
1196 ? { type: capability, providerSessionId: sessionId }
1197 : capability === "not_resumable"
1198 ? { type: capability, reason: "The server restarted." }
1199 : { type: capability },
1200 },
1201 ];
1202 const live = { ...base, runtimeRequests } as unknown as OrchestrationV2ThreadProjection;
1203 assert.equal(restartContinuationRun(live, now) !== undefined, shouldContinue);
1204 const cut = {
1205 ...cutMidTurn(),
1206 runtimeRequests,
1207 } as unknown as OrchestrationV2ThreadProjection;
1208 assert.lengthOf(yield* continuationTexts(cut), shouldContinue ? 1 : 0);
1209 }),
1211​
1212it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
1213 Effect.gen(function* () {
1214 const live = makeProjection();
1215 for (const held of [
1216 { snoozedUntil: DateTime.add(now, { days: 1 }) },
1217 { settledOverride: "settled" as const },
1218 ]) {
1219 const thread = { ...live.thread, ...held };
1220 assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
1221 assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
1223 const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
1224 assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
1225 }),
1227​
1228it.effect("does not continue a run waiting on a secret the restart closed", () =>
1229 Effect.gen(function* () {
1230 const completedAt = DateTime.makeUnsafe("2026-10-03T10:05:00.000Z");
1231 const secret = (secretStatus: string, at: DateTime.Utc | null) =>
1232 ({ type: "secret_request", runId, secretStatus, completedAt: at }) as never;
1233 assert.isUndefined(
1234 restartContinuationRun({ ...makeProjection(), turnItems: [secret("pending", null)] }, now),
1235 );
1236 const cut = cutMidTurn({ completedAt });
1237 assert.deepEqual(
1238 yield* continuationTexts({ ...cut, turnItems: [secret("cancelled", completedAt)] }),
1239 [],
1240 );
1241 assert.lengthOf(
1242 yield* continuationTexts({
1243 ...cut,
1244 turnItems: [secret("cancelled", DateTime.subtract(completedAt, { seconds: 1 }))],
1245 }),
1246 1,
1247 );
1248 }),
1250​
1251it.effect.each(["completed", "failed", "interrupted"] as const)(
1252 "does not continue when the provider turn %s before the app run settled",
1253 (status) =>
1254 Effect.gen(function* () {
1255 const cut = cutMidTurn();
1256 assert.deepEqual(
1257 yield* continuationTexts({
1258 ...cut,
1259 providerTurns: [{ ...cut.providerTurns[0]!, status }],
1260 }),
1261 [],
1262 );
1263 }),