Open History to see the last commit
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 requestedAt: now,
60 completedAt: null,
61 },
62 ],
63 providerThreads: [
64 {
65 id: providerThreadId,
66 appThreadId: threadId,
67 ownerNodeId: null,
68 driver,
69 providerInstanceId: instanceId,
70 providerSessionId: sessionId,
71 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
72 status: "active",
73 },
74 ],
75 providerSessions: [
76 { id: sessionId, driver, providerInstanceId: instanceId, status: "running" },
77 ],
78 providerTurns: [
79 {
80 id: ProviderTurnId.make("turn:restart"),
81 providerThreadId,
82 runAttemptId: attemptId,
83 status: "running",
84 },
85 ],
86 runtimeRequests: [],
87 attempts: [],
88 nodes: [],
89 subagents: [],
90 messages: [],
91 turnItems: [],
92 } as unknown as OrchestrationV2ThreadProjection;
93}
94
95it("requires matching saved native state for an unfinished root run", () => {
96 const projection = makeProjection();
97 assert.equal(restartContinuationRun(projection, now)?.id, runId);
98 for (const invalid of [
99 { ...projection, thread: { ...projection.thread, archivedAt: {} } },
100 { ...projection, thread: { ...projection.thread, deletedAt: {} } },
101 {
102 ...projection,
103 thread: { ...projection.thread, providerInstanceId: ProviderInstanceId.make("other") },
104 },
105 {
106 ...projection,
107 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
108 },
109 {
110 ...projection,
111 providerSessions: [
112 {
113 ...projection.providerSessions[0]!,
114 providerInstanceId: ProviderInstanceId.make("other"),
115 },
116 ],
117 },
118 { ...projection, providerTurns: [] },
119 ...[
120 "queued",
121 "preparing",
122 "starting",
123 "waiting",
124 "completed",
125 "cancelled",
126 "failed",
127 "interrupted",
128 ].map((status) => ({ ...projection, runs: [{ ...projection.runs[0]!, status }] })),
129 ])
130 assert.isUndefined(restartContinuationRun(invalid as OrchestrationV2ThreadProjection, now));
131});
132
133it("continues a live turn whose session the adapter never marked running", () => {
134 const projection = makeProjection();
135 const withSessionStatus = (status: string) =>
136 ({
137 ...projection,
138 providerSessions: [{ ...projection.providerSessions[0]!, status }],
139 }) as OrchestrationV2ThreadProjection;
140 for (const status of ["starting", "ready", "running", "waiting"])
141 assert.equal(restartContinuationRun(withSessionStatus(status), now)?.id, runId, status);
142 for (const status of ["stopped", "error"])
143 assert.isUndefined(restartContinuationRun(withSessionStatus(status), now), status);
144});
145
146it("recovers an admitted continuation after another crash before provider start", () => {
147 const projection = makeProjection();
148 const starting = {
149 ...projection,
150 runs: [
151 {
152 ...projection.runs[0]!,
153 status: "starting" as const,
154 restartContinuationOfRunId: RunId.make("run:previous-crash"),
155 },
156 ],
157 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
158 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
159 providerTurns: [],
160 };
161 assert.equal(restartContinuationRun(starting, now)?.id, runId);
162});
163
164it("does not continue settled root runs with restart-cancelled background work", () => {
165 const projection = makeProjection();
166 const settled = {
167 ...projection,
168 runs: [
169 {
170 ...projection.runs[0]!,
171 status: "completed" as const,
172 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
173 },
174 ],
175 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
176 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
177 providerTurns: [],
178 };
179 for (const projectId of [scratchProjectId, projection.thread.projectId])
180 for (const status of ["completed", "waiting"] as const)
181 assert.isUndefined(
182 restartContinuationRun(
183 {
184 ...settled,
185 thread: { ...settled.thread, projectId },
186 runs: [{ ...settled.runs[0]!, status }],
187 },
188 now,
189 ),
190 );
191});
192
193it.effect.each(["completed", "waiting", "cancelled"] as const)(
194 "wakes a %s run whose monitor the restart cancelled, with the note as its prompt",
195 (status) =>
196 Effect.gen(function* () {
197 const base = makeProjection();
198 const work = [
199 { kind: "monitor" as const, label: "Watch CI run 42" },
200 { kind: "shell" as const, label: "vp run dev" },
201 ];
202 const projection = {
203 ...base,
204 runs: [{ ...base.runs[0]!, status, restartCancelledBackgroundWork: work }],
205 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
206 } as unknown as OrchestrationV2ThreadProjection;
207 const commands: Parameters<
208 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
209 >[0][] = [];
210 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
211 Effect.provide(
212 Layer.merge(
213 Layer.mock(ThreadManagementService.ThreadManagementService)({
214 getThreadRecords: () => Effect.succeed(projection),
215 recoverDelegatedTask: () => Effect.void,
216 dispatch: (command) => {
217 commands.push(command);
218 return Effect.succeed({} as never);
219 },
220 }),
221 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
222 ),
223 ),
224 );
225 assert.lengthOf(commands, 1);
226 const command = commands[0]!;
227 assert.equal(command.type, "message.dispatch");
228 if (command.type !== "message.dispatch") return;
229 assert.equal(command.restartContinuationOfRunId, runId);
230 assert.include(command.text, "- monitor: Watch CI run 42");
231 assert.include(command.text, "- shell: vp run dev");
232 }),
233);
234
235it.effect.each([
236 [false, undefined],
237 [true, undefined],
238 [false, true],
239 [true, false],
240] as const)(
241 "atomically records restart intent with cancellation when opt-in is %s and project override is %s",
242 ([enabled, projectOverride]) =>
243 Effect.gen(function* () {
244 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
245 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
246 Effect.provide(
247 Layer.mergeAll(
248 ServerSettings.layerTest({
249 continueThreadsAfterServerUpdate: enabled,
250 projectSettingsOverrides:
251 projectOverride === undefined
252 ? {}
253 : {
254 [ProjectId.make("restart-project")]: {
255 continueThreadsAfterServerUpdate: projectOverride,
256 },
257 },
258 }),
259 Layer.mock(ProjectionStore.ProjectionStoreV2)({
260 getRecoveryThreadIds: () => Effect.succeed([threadId]),
261 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
262 }),
263 Layer.mock(EventSink.EventSinkV2)({
264 commitCommand: (input) => {
265 committed = input;
266 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
267 },
268 }),
269 IdAllocator.layer,
270 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
271 runRecoveryOnce: Effect.succeed(false),
272 }),
273 Layer.mock(EffectOutbox.EffectOutboxV2)({
274 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
275 }),
276 ),
277 ),
278 );
279 yield* recovery.reconcile("startup");
280 assert.isDefined(committed);
281 assert.isTrue(
282 committed!.events.some(
283 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
284 ),
285 );
286 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
287 if (projectOverride ?? enabled)
288 assert.deepEqual(committed!.effects[0]?.request, {
289 type: "provider-runtime.continue",
290 sourceRunId: runId,
291 });
292 }),
293);
294
295it.effect("lets a cut blocking delegate_task wake its parent like an async task", () =>
296 Effect.gen(function* () {
297 const base = makeProjection();
298 const task = (id: string, completionWake: "settled_only" | "always", status: string) => ({
299 id: NodeId.make(id),
300 threadId,
301 runId,
302 origin: "app_owned",
303 childThreadId: ThreadId.make(`thread:${id}`),
304 driver,
305 providerInstanceId: instanceId,
306 completionWake,
307 status,
308 });
309 const projection = {
310 ...base,
311 subagents: [
312 task("task:waited", "settled_only", "running"),
313 task("task:async", "always", "running"),
314 task("task:finished", "settled_only", "completed"),
315 ],
316 } as unknown as OrchestrationV2ThreadProjection;
317 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
318 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
319 Effect.provide(
320 Layer.mergeAll(
321 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
322 Layer.mock(ProjectionStore.ProjectionStoreV2)({
323 getRecoveryThreadIds: () => Effect.succeed([threadId]),
324 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
325 }),
326 Layer.mock(EventSink.EventSinkV2)({
327 commitCommand: (input) => {
328 committed = input;
329 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
330 },
331 }),
332 IdAllocator.layer,
333 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
334 Layer.mock(EffectOutbox.EffectOutboxV2)({
335 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
336 }),
337 ),
338 ),
339 );
340 yield* recovery.reconcile("startup");
341 const upgraded = (committed?.events ?? []).flatMap((event) =>
342 event.type === "subagent.updated" ? [event.payload] : [],
343 );
344 assert.deepEqual(
345 upgraded.map((row) => ({ id: row.id, completionWake: row.completionWake })),
346 [{ id: NodeId.make("task:waited"), completionWake: "always" }],
347 );
348 }),
349);
350
351it.effect.each(["running", "waiting"])(
352 "wakes a %s run to restart the native subagent it waited on",
353 (status) =>
354 Effect.gen(function* () {
355 const base = makeProjection();
356 const item = (id: string, extra: Record<string, unknown>) => ({
357 id,
358 threadId,
359 runId,
360 nodeId: null,
361 status: "running",
362 ...extra,
363 });
364 const projection = {
365 ...base,
366 runs: [{ ...base.runs[0]!, status }],
367 providerTurns: [
368 { ...base.providerTurns[0]!, status: status === "waiting" ? "completed" : "running" },
369 ],
370 turnItems: [
371 // Codex keeps a native subagent on its own child provider thread.
372 item("item:native", {
373 type: "subagent",
374 origin: "provider_native",
375 providerThreadId: ProviderThreadId.make("provider-thread:child"),
376 nativeItemRef: { driver, nativeId: "agent-1" },
377 title: "Sleeper",
378 childThreadId: ThreadId.make("thread:child"),
379 }),
380 item("item:shell", { type: "command_execution", providerThreadId, input: "ls" }),
381 ],
382 } as unknown as OrchestrationV2ThreadProjection;
383 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
384 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
385 Effect.provide(
386 Layer.mergeAll(
387 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
388 Layer.mock(ProjectionStore.ProjectionStoreV2)({
389 getRecoveryThreadIds: () => Effect.succeed([threadId]),
390 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
391 }),
392 Layer.mock(EventSink.EventSinkV2)({
393 commitCommand: (input) => {
394 committed = input;
395 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
396 },
397 }),
398 IdAllocator.layer,
399 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
400 Layer.mock(EffectOutbox.EffectOutboxV2)({
401 listByCommandId: () => Effect.succeed([]),
402 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
403 }),
404 ),
405 ),
406 );
407 yield* recovery.reconcile("startup");
408 const work = (committed?.events ?? []).flatMap((event) =>
409 event.type === "run.background-work-cancelled" ? [event.payload] : [],
410 );
411 // The subagent is reported on the run that awaited it. A running run's
412 // shell died with its turn.
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 // A shell the agent started itself still does not wake it.
741 assert.isUndefined(restartContinuationRun(withShell(), now));
742
743 const texts = yield* continuationTexts({
744 ...base,
745 runs: [
746 {
747 ...base.runs[0]!,
748 status: "completed",
749 startedAt: now,
750 completedAt: now,
751 restartCancelledBackgroundWork: [
752 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
753 ],
754 },
755 { ...cutWake, status: "cancelled", completedAt: now },
756 ],
757 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
758 } as unknown as OrchestrationV2ThreadProjection);
759 assert.lengthOf(texts, 1);
760 assert.include(texts[0], "- subagent: sleep 150 (subagent agent:1)");
761 // A run the user stopped before it started still takes precedence.
762 const stopped = yield* continuationTexts({
763 ...base,
764 runs: [
765 {
766 ...base.runs[0]!,
767 status: "completed",
768 startedAt: now,
769 completedAt: now,
770 restartCancelledBackgroundWork: [
771 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
772 ],
773 },
774 { ...cutWake, status: "interrupted", completedAt: now },
775 ],
776 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
777 } as unknown as OrchestrationV2ThreadProjection);
778 assert.lengthOf(stopped, 0);
779 }),
780);
781
782it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
783 Effect.gen(function* () {
784 let projection = makeProjection();
785 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
786 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
787 Effect.provide(
788 Layer.mergeAll(
789 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
790 Layer.mock(ProjectionStore.ProjectionStoreV2)({
791 getRecoveryThreadIds: () => Effect.succeed([threadId]),
792 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
793 }),
794 Layer.mock(EventSink.EventSinkV2)({
795 writeWithEffects: (input) =>
796 Effect.sync(() => {
797 assert.lengthOf(input.events, 0);
798 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
799 projection = {
800 ...projection,
801 runs: [{ ...projection.runs[0]!, status: "completed" }],
802 };
803 return [];
804 }),
805 commitCommand: (input) =>
806 Effect.sync(() => {
807 commits.push(input);
808 return { committed: true, cancelledEffectCount: 0 } as never;
809 }),
810 }),
811 IdAllocator.layer,
812 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
813 runRecoveryOnce: Effect.succeed(false),
814 }),
815 Layer.mock(EffectOutbox.EffectOutboxV2)({
816 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
817 }),
818 ),
819 ),
820 );
821 yield* recovery.prepareForShutdown;
822 yield* recovery.reconcile("shutdown");
823 assert.isFalse(
824 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
825 );
826 let dispatched = false;
827 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
828 Effect.provide(
829 Layer.mergeAll(
830 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
831 Layer.mock(ThreadManagementService.ThreadManagementService)({
832 getThreadRecords: () => Effect.succeed(projection),
833 recoverDelegatedTask: () => Effect.void,
834 dispatch: () =>
835 Effect.sync(() => {
836 dispatched = true;
837 return {} as never;
838 }),
839 }),
840 ),
841 ),
842 );
843 assert.isFalse(dispatched);
844 }),
845);
846
847const continuationDispatches = (projection: OrchestrationV2ThreadProjection) =>
848 Effect.gen(function* () {
849 const dispatches: Array<Extract<OrchestrationV2Command, { type: "message.dispatch" }>> = [];
850 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
851 Effect.provide(
852 Layer.merge(
853 Layer.mock(ThreadManagementService.ThreadManagementService)({
854 getThreadRecords: () => Effect.succeed(projection),
855 recoverDelegatedTask: () => Effect.void,
856 dispatch: (command) => {
857 if (command.type === "message.dispatch") dispatches.push(command);
858 return Effect.succeed({} as never);
859 },
860 }),
861 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
862 ),
863 ),
864 );
865 return dispatches;
866 });
867
868const continuationTexts = (projection: OrchestrationV2ThreadProjection) =>
869 continuationDispatches(projection).pipe(
870 Effect.map((dispatches) => dispatches.map((command) => command.text)),
871 );
872
873const cutMidTurn = (extra: Record<string, unknown> = {}) => {
874 const base = makeProjection();
875 return {
876 ...base,
877 runs: [
878 {
879 ...base.runs[0]!,
880 status: "cancelled",
881 completedAt: now,
882 userMessageId: MessageId.make("message:user"),
883 ...extra,
884 },
885 ],
886 providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }],
887 } as unknown as OrchestrationV2ThreadProjection;
888};
889
890const queuedFollowUp = {
891 id: RunId.make("run:queued"),
892 ordinal: 2,
893 providerInstanceId: instanceId,
894 providerThreadId,
895 status: "queued",
896 queueHeld: true,
897};
898
899it.effect("continues a cut run past queued follow-ups, which stay held", () =>
900 Effect.gen(function* () {
901 const live = makeProjection();
902 assert.equal(
903 restartContinuationRun(
904 {
905 ...live,
906 runs: [...live.runs, queuedFollowUp],
907 } as unknown as OrchestrationV2ThreadProjection,
908 now,
909 )?.id,
910 runId,
911 );
912 const cut = cutMidTurn();
913 const texts = yield* continuationTexts({
914 ...cut,
915 runs: [...cut.runs, queuedFollowUp],
916 } as unknown as OrchestrationV2ThreadProjection);
917 assert.deepEqual(texts, ["Continue where you left off."]);
918 }),
919);
920
921it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
922 Effect.gen(function* () {
923 const finishedContinuation = {
924 id: RunId.make("run:earlier-continuation"),
925 ordinal: 3,
926 providerInstanceId: instanceId,
927 providerThreadId,
928 status: "completed",
929 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
930 };
931 const live = makeProjection();
932 assert.equal(
933 restartContinuationRun(
934 {
935 ...live,
936 runs: [...live.runs, finishedContinuation],
937 } as unknown as OrchestrationV2ThreadProjection,
938 now,
939 )?.id,
940 runId,
941 );
942 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
943 const texts = yield* continuationTexts({
944 ...cut,
945 runs: [...cut.runs, finishedContinuation],
946 } as unknown as OrchestrationV2ThreadProjection);
947 assert.deepEqual(texts, ["Continue where you left off."]);
948 }),
949);
950
951it.effect("does not continue a run the user asked to stop before the restart", () =>
952 Effect.gen(function* () {
953 const texts = yield* continuationTexts({
954 ...cutMidTurn(),
955 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
956 } as unknown as OrchestrationV2ThreadProjection);
957 assert.deepEqual(texts, []);
958 }),
959);
960
961it.effect("does not continue a cut /compact or /logout turn", () =>
962 Effect.gen(function* () {
963 for (const text of ["/compact", " /LOGOUT "]) {
964 const texts = yield* continuationTexts({
965 ...cutMidTurn(),
966 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
967 } as unknown as OrchestrationV2ThreadProjection);
968 assert.deepEqual(texts, [], text);
969 }
970 const texts = yield* continuationTexts({
971 ...cutMidTurn(),
972 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
973 } as unknown as OrchestrationV2ThreadProjection);
974 assert.lengthOf(texts, 1);
975 }),
976);
977
978it.effect(
979 "carries the note forward when its continuation was cut before reaching the provider",
980 () =>
981 Effect.gen(function* () {
982 const base = makeProjection();
983 const original = {
984 ...base.runs[0]!,
985 id: RunId.make("run:original"),
986 status: "completed",
987 activeAttemptId: RunAttemptId.make("attempt:original"),
988 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
989 };
990 const projection = {
991 ...base,
992 runs: [
993 original,
994 {
995 ...base.runs[0]!,
996 ordinal: 2,
997 status: "cancelled",
998 restartContinuationOfRunId: original.id,
999 },
1000 ],
1001 providerTurns: [
1002 {
1003 ...base.providerTurns[0]!,
1004 runAttemptId: original.activeAttemptId,
1005 status: "completed",
1006 },
1007 ],
1008 } as unknown as OrchestrationV2ThreadProjection;
1009 const texts = yield* continuationTexts(projection);
1010 assert.lengthOf(texts, 1);
1011 assert.include(texts[0]!, "sleep 25 && echo DONE");
1012 assert.notInclude(texts[0]!, "Continue where");
1013 }),
1014);
1015
1016it.effect("prepares later threads' continuations when one thread fails", () =>
1017 Effect.gen(function* () {
1018 const brokenThreadId = ThreadId.make("thread:broken");
1019 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
1020 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
1021 Effect.provide(
1022 Layer.mergeAll(
1023 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
1024 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1025 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
1026 getRuntimeRecoveryProjection: (id) =>
1027 id === brokenThreadId
1028 ? Effect.fail(
1029 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
1030 )
1031 : Effect.succeed(makeProjection()),
1032 }),
1033 Layer.mock(EventSink.EventSinkV2)({
1034 writeWithEffects: (input) =>
1035 Effect.sync(() => {
1036 writes.push(input);
1037 return [];
1038 }),
1039 }),
1040 IdAllocator.layer,
1041 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
1042 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
1043 ),
1044 ),
1045 );
1046 yield* recovery.prepareForShutdown;
1047 assert.deepEqual(
1048 writes.map((write) => write.effects[0]?.request),
1049 [{ type: "provider-runtime.continue", sourceRunId: runId }],
1050 );
1051 }),
1052);
1053
1054it.effect.each([
1055 ["user_input", "pending", "live", false],
1056 ["user_input", "expired", "not_resumable", false],
1057 ["user_input", "cancelled", "not_resumable", false],
1058 ["command", "pending", "live", false],
1059 ["command", "expired", "not_resumable", false],
1060 ["user_input", "resolved", "live", true],
1061 ["command", "cancelled", "live", true],
1062 ["user_input", "pending", "message", true],
1063 ["dynamic_tool_call", "pending", "live", true],
1064 ["auth_refresh", "pending", "live", true],
1065] as const)(
1066 "a %s request that is %s with %s capability allows continuation: %s",
1067 ([kind, status, capability, shouldContinue]) =>
1068 Effect.gen(function* () {
1069 const base = makeProjection();
1070 const runtimeRequests = [
1071 {
1072 id: RuntimeRequestId.make("request:restart"),
1073 nodeId: NodeId.make("node:restart-question"),
1074 providerTurnId: base.providerTurns[0]!.id,
1075 kind,
1076 status,
1077 responseCapability:
1078 capability === "live"
1079 ? { type: capability, providerSessionId: sessionId }
1080 : capability === "not_resumable"
1081 ? { type: capability, reason: "The server restarted." }
1082 : { type: capability },
1083 },
1084 ];
1085 const live = { ...base, runtimeRequests } as unknown as OrchestrationV2ThreadProjection;
1086 assert.equal(restartContinuationRun(live, now) !== undefined, shouldContinue);
1087 const cut = {
1088 ...cutMidTurn(),
1089 runtimeRequests,
1090 } as unknown as OrchestrationV2ThreadProjection;
1091 assert.lengthOf(yield* continuationTexts(cut), shouldContinue ? 1 : 0);
1092 }),
1093);
1094
1095it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
1096 Effect.gen(function* () {
1097 const live = makeProjection();
1098 for (const held of [
1099 { snoozedUntil: DateTime.add(now, { days: 1 }) },
1100 { settledOverride: "settled" as const },
1101 ]) {
1102 const thread = { ...live.thread, ...held };
1103 assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
1104 assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
1105 }
1106 const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
1107 assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
1108 }),
1109);
1110
1111it.effect("does not continue a run waiting on a secret the restart closed", () =>
1112 Effect.gen(function* () {
1113 const completedAt = DateTime.makeUnsafe("2026-10-03T10:05:00.000Z");
1114 const secret = (secretStatus: string, at: DateTime.Utc | null) =>
1115 ({ type: "secret_request", runId, secretStatus, completedAt: at }) as never;
1116 assert.isUndefined(
1117 restartContinuationRun({ ...makeProjection(), turnItems: [secret("pending", null)] }, now),
1118 );
1119 const cut = cutMidTurn({ completedAt });
1120 assert.deepEqual(
1121 yield* continuationTexts({ ...cut, turnItems: [secret("cancelled", completedAt)] }),
1122 [],
1123 );
1124 assert.lengthOf(
1125 yield* continuationTexts({
1126 ...cut,
1127 turnItems: [secret("cancelled", DateTime.subtract(completedAt, { seconds: 1 }))],
1128 }),
1129 1,
1130 );
1131 }),
1132);
1133
1134it.effect.each(["completed", "failed", "interrupted"] as const)(
1135 "does not continue when the provider turn %s before the app run settled",
1136 (status) =>
1137 Effect.gen(function* () {
1138 const cut = cutMidTurn();
1139 assert.deepEqual(
1140 yield* continuationTexts({
1141 ...cut,
1142 providerTurns: [{ ...cut.providerTurns[0]!, status }],
1143 }),
1144 [],
1145 );
1146 }),
1147);