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 awaited 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", awaited: true as const },
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 item("item:native", {
372 type: "subagent",
373 origin: "provider_native",
374 providerThreadId: ProviderThreadId.make("provider-thread:child"),
375 nativeItemRef: { driver, nativeId: "agent-1" },
376 title: "Sleeper",
377 childThreadId: ThreadId.make("thread:child"),
378 }),
379 item("item:shell", { type: "command_execution", providerThreadId, input: "ls" }),
380 ],
381 } as unknown as OrchestrationV2ThreadProjection;
382 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
383 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
384 Effect.provide(
385 Layer.mergeAll(
386 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
387 Layer.mock(ProjectionStore.ProjectionStoreV2)({
388 getRecoveryThreadIds: () => Effect.succeed([threadId]),
389 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
390 }),
391 Layer.mock(EventSink.EventSinkV2)({
392 commitCommand: (input) => {
393 committed = input;
394 return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
395 },
396 }),
397 IdAllocator.layer,
398 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
399 Layer.mock(EffectOutbox.EffectOutboxV2)({
400 listByCommandId: () => Effect.succeed([]),
401 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
402 }),
403 ),
404 ),
405 );
406 yield* recovery.reconcile("startup");
407 const work = (committed?.events ?? []).flatMap((event) =>
408 event.type === "run.background-work-cancelled" ? [event.payload] : [],
409 );
410 assert.deepEqual(work, [
411 {
412 runId,
413 restartCancelledBackgroundWork: [
414 { kind: "subagent", label: "Sleeper (id agent-1)", id: "item:native" },
415 ...(status === "waiting"
416 ? [{ kind: "shell" as const, label: "ls", id: "item:shell" }]
417 : []),
418 ],
419 },
420 ]);
421 assert.deepEqual(
422 committed?.effects.map((effect) => effect.request),
423 [{ type: "provider-runtime.continue", sourceRunId: runId }],
424 );
425 }),
426);
427
428it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
429 Effect.gen(function* () {
430 let projection = makeProjection();
431 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
432 const commands: Parameters<
433 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
434 >[0][] = [];
435 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
436 getThreadRecords: () => Effect.succeed(projection),
437 recoverDelegatedTask: () => Effect.void,
438 dispatch: (command) => {
439 commands.push(command);
440 if (command.type === "message.dispatch")
441 projection = { ...projection, messages: [{ id: command.messageId } as never] };
442 return Effect.succeed({} as never);
443 },
444 });
445 const layerEnabled = Layer.merge(
446 layerThreads,
447 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
448 );
449 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
450 Effect.provide(layerEnabled),
451 );
452 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
453 Effect.provide(layerEnabled),
454 );
455 assert.lengthOf(commands, 1);
456 assert.match(String(commands[0]!.commandId), /run:restart$/);
457 if (commands[0]!.type === "message.dispatch")
458 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
459 projection = {
460 ...projection,
461 messages: [],
462 runs: [
463 ...projection.runs,
464 {
465 ...projection.runs[0]!,
466 id: RunId.make("run:user-newer"),
467 ordinal: 2,
468 status: "completed",
469 },
470 ],
471 };
472 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
473 Effect.provide(layerEnabled),
474 );
475 assert.lengthOf(commands, 1);
476 projection = { ...projection, runs: [projection.runs[0]!] };
477 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
478 Effect.provide(
479 Layer.merge(
480 layerThreads,
481 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false }),
482 ),
483 ),
484 );
485 assert.lengthOf(commands, 1);
486 }),
487);
488
489it.effect("prepares no continuation for background work another provider thread launched", () =>
490 Effect.gen(function* () {
491 const base = makeProjection();
492 const claudeThreadId = ProviderThreadId.make("provider-thread:claude");
493 const projection = {
494 ...base,
495 runs: [{ ...base.runs[0]!, status: "completed" }],
496 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
497 turnItems: [
498 {
499 id: "turn-item:claude-subagent",
500 runId: RunId.make("run:claude"),
501 providerThreadId: claudeThreadId,
502 type: "subagent",
503 status: "running",
504 },
505 ],
506 } as unknown as OrchestrationV2ThreadProjection;
507 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
508 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
509 Effect.provide(
510 Layer.mergeAll(
511 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
512 Layer.mock(ProjectionStore.ProjectionStoreV2)({
513 getRecoveryThreadIds: () => Effect.succeed([threadId]),
514 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
515 }),
516 Layer.mock(EventSink.EventSinkV2)({
517 writeWithEffects: (input) =>
518 Effect.sync(() => {
519 writes.push(input);
520 return [];
521 }),
522 }),
523 IdAllocator.layer,
524 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
525 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
526 ),
527 ),
528 );
529 yield* recovery.prepareForShutdown;
530 assert.lengthOf(writes, 0);
531 const ownWork = {
532 ...projection,
533 turnItems: [{ ...projection.turnItems[0]!, providerThreadId }],
534 } as OrchestrationV2ThreadProjection;
535 const ownRecovery = yield* ProviderRuntimeRecovery.make.pipe(
536 Effect.provide(
537 Layer.mergeAll(
538 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
539 Layer.mock(ProjectionStore.ProjectionStoreV2)({
540 getRecoveryThreadIds: () => Effect.succeed([threadId]),
541 getRuntimeRecoveryProjection: () => Effect.succeed(ownWork),
542 }),
543 Layer.mock(EventSink.EventSinkV2)({
544 writeWithEffects: (input) =>
545 Effect.sync(() => {
546 writes.push(input);
547 return [];
548 }),
549 }),
550 IdAllocator.layer,
551 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
552 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
553 ),
554 ),
555 );
556 yield* ownRecovery.prepareForShutdown;
557 assert.lengthOf(writes, 1);
558 assert.deepEqual(writes[0]!.effects[0]?.request, {
559 type: "provider-runtime.continue",
560 sourceRunId: runId,
561 });
562 }),
563);
564
565const backgroundSubagent = {
566 turnItem: {
567 id: "turn-item:background-subagent",
568 runId,
569 nodeId: null,
570 providerThreadId,
571 providerInstanceId: instanceId,
572 type: "subagent",
573 subagentId: "subagent:background",
574 title: "Background reviewer",
575 status: "running",
576 },
577 work: {
578 kind: "subagent" as const,
579 label: "Background reviewer",
580 id: "turn-item:background-subagent",
581 },
582};
583const devServer = {
584 turnItem: {
585 id: "turn-item:dev-server",
586 runId,
587 nodeId: null,
588 providerThreadId,
589 providerInstanceId: instanceId,
590 type: "command_execution",
591 input: "vp run dev",
592 status: "running",
593 },
594 work: { kind: "shell" as const, label: "vp run dev", id: "turn-item:dev-server" },
595};
596
597it.effect.each([
598 ["completed", scratchProjectId, backgroundSubagent, true],
599 ["waiting", ProjectId.make("restart-project"), backgroundSubagent, true],
600 ["completed", ProjectId.make("restart-project"), devServer, false],
601 ["waiting", scratchProjectId, devServer, false],
602] as const)(
603 "cleans up background work of a %s run in project %s and wakes it only for awaited work",
604 ([status, projectId, background, wakes]) =>
605 Effect.gen(function* () {
606 const base = makeProjection();
607 const projection = {
608 ...base,
609 thread: { ...base.thread, projectId },
610 runs: [{ ...base.runs[0]!, status }],
611 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
612 turnItems: [background.turnItem],
613 subagents:
614 background === backgroundSubagent
615 ? [
616 {
617 id: "subagent:background",
618 runId,
619 origin: "provider_native",
620 driver,
621 providerInstanceId: instanceId,
622 status: "running",
623 },
624 ]
625 : [],
626 } as unknown as OrchestrationV2ThreadProjection;
627 for (const trigger of ["startup", "shutdown"] as const) {
628 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
629 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
630 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
631 Effect.provide(
632 Layer.mergeAll(
633 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
634 Layer.mock(ProjectionStore.ProjectionStoreV2)({
635 getRecoveryThreadIds: () => Effect.succeed([threadId]),
636 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
637 }),
638 Layer.mock(EventSink.EventSinkV2)({
639 writeWithEffects: (input) =>
640 Effect.sync(() => {
641 writes.push(input);
642 return [];
643 }),
644 commitCommand: (input) =>
645 Effect.sync(() => {
646 commits.push(input);
647 return { committed: true, cancelledEffectCount: 0 } as never;
648 }),
649 }),
650 IdAllocator.layer,
651 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
652 runRecoveryOnce: Effect.succeed(false),
653 }),
654 Layer.mock(EffectOutbox.EffectOutboxV2)({
655 listByCommandId: () => Effect.succeed([]),
656 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
657 }),
658 ),
659 ),
660 );
661 if (trigger === "shutdown") yield* recovery.prepareForShutdown;
662 yield* recovery.reconcile(trigger);
663 const recorded = [...writes.flatMap((write) => write.effects), ...commits[0]!.effects];
664 assert.deepEqual(
665 recorded.map((effect) => effect.request),
666 wakes ? [{ type: "provider-runtime.continue", sourceRunId: runId }] : [],
667 );
668 assert.lengthOf(commits, 1);
669 const events = commits[0]!.events;
670 assert.isTrue(
671 events.some(
672 (event) => event.type === "turn-item.updated" && event.payload.status === "cancelled",
673 ),
674 );
675 const note = events.find((event) => event.type === "run.background-work-cancelled");
676 assert.equal(note?.runId, runId);
677 assert.deepEqual(note?.payload.restartCancelledBackgroundWork, [background.work]);
678 if (status === "completed")
679 assert.isFalse(events.some((event) => event.type === "run.updated"));
680 }
681 }),
682);
683
684it("does not wake a settled run for work left by a session that already stopped", () => {
685 const base = makeProjection();
686 const projection = {
687 ...base,
688 runs: [{ ...base.runs[0]!, status: "completed" }],
689 providerThreads: [{ ...base.providerThreads[0]!, status: "idle" }],
690 turnItems: [backgroundSubagent.turnItem],
691 } as unknown as OrchestrationV2ThreadProjection;
692 assert.equal(restartContinuationRun(projection, now)?.id, runId);
693 for (const status of ["stopped", "error"])
694 assert.isUndefined(
695 restartContinuationRun(
696 {
697 ...projection,
698 providerSessions: [{ ...projection.providerSessions[0]!, status }],
699 } as OrchestrationV2ThreadProjection,
700 now,
701 ),
702 status,
703 );
704});
705
706it.effect("wakes a run whose subagent's own shell the restart cut, past a wake it cut first", () =>
707 Effect.gen(function* () {
708 const base = makeProjection();
709 const cutWake = {
710 ...base.runs[0]!,
711 id: RunId.make("run:wake"),
712 ordinal: 2,
713 status: "starting",
714 startedAt: null,
715 };
716 const withShell = (parentTaskId?: string) =>
717 ({
718 ...base,
719 runs: [{ ...base.runs[0]!, status: "waiting", startedAt: now }, cutWake],
720 providerThreads: [
721 {
722 ...base.providerThreads[0]!,
723 status: "idle",
724 pendingBackgroundTasks: [
725 {
726 kind: "command",
727 taskId: "shell:1",
728 description: "sleep 150",
729 ...(parentTaskId === undefined ? {} : { parentTaskId }),
730 },
731 ],
732 },
733 ],
734 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
735 }) as unknown as OrchestrationV2ThreadProjection;
736 assert.equal(restartContinuationRun(withShell("agent:1"), now)?.id, runId);
737 assert.isUndefined(restartContinuationRun(withShell(), now));
738
739 const texts = yield* continuationTexts({
740 ...base,
741 runs: [
742 {
743 ...base.runs[0]!,
744 status: "completed",
745 startedAt: now,
746 completedAt: now,
747 restartCancelledBackgroundWork: [
748 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
749 ],
750 },
751 { ...cutWake, status: "cancelled", completedAt: now },
752 ],
753 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
754 } as unknown as OrchestrationV2ThreadProjection);
755 assert.lengthOf(texts, 1);
756 assert.include(texts[0], "- subagent: sleep 150 (subagent agent:1)");
757 const stopped = yield* continuationTexts({
758 ...base,
759 runs: [
760 {
761 ...base.runs[0]!,
762 status: "completed",
763 startedAt: now,
764 completedAt: now,
765 restartCancelledBackgroundWork: [
766 { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
767 ],
768 },
769 { ...cutWake, status: "interrupted", completedAt: now },
770 ],
771 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
772 } as unknown as OrchestrationV2ThreadProjection);
773 assert.lengthOf(stopped, 0);
774 }),
775);
776
777it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
778 Effect.gen(function* () {
779 let projection = makeProjection();
780 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
781 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
782 Effect.provide(
783 Layer.mergeAll(
784 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
785 Layer.mock(ProjectionStore.ProjectionStoreV2)({
786 getRecoveryThreadIds: () => Effect.succeed([threadId]),
787 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
788 }),
789 Layer.mock(EventSink.EventSinkV2)({
790 writeWithEffects: (input) =>
791 Effect.sync(() => {
792 assert.lengthOf(input.events, 0);
793 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
794 projection = {
795 ...projection,
796 runs: [{ ...projection.runs[0]!, status: "completed" }],
797 };
798 return [];
799 }),
800 commitCommand: (input) =>
801 Effect.sync(() => {
802 commits.push(input);
803 return { committed: true, cancelledEffectCount: 0 } as never;
804 }),
805 }),
806 IdAllocator.layer,
807 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
808 runRecoveryOnce: Effect.succeed(false),
809 }),
810 Layer.mock(EffectOutbox.EffectOutboxV2)({
811 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
812 }),
813 ),
814 ),
815 );
816 yield* recovery.prepareForShutdown;
817 yield* recovery.reconcile("shutdown");
818 assert.isFalse(
819 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
820 );
821 let dispatched = false;
822 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
823 Effect.provide(
824 Layer.mergeAll(
825 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
826 Layer.mock(ThreadManagementService.ThreadManagementService)({
827 getThreadRecords: () => Effect.succeed(projection),
828 recoverDelegatedTask: () => Effect.void,
829 dispatch: () =>
830 Effect.sync(() => {
831 dispatched = true;
832 return {} as never;
833 }),
834 }),
835 ),
836 ),
837 );
838 assert.isFalse(dispatched);
839 }),
840);
841
842const continuationDispatches = (projection: OrchestrationV2ThreadProjection) =>
843 Effect.gen(function* () {
844 const dispatches: Array<Extract<OrchestrationV2Command, { type: "message.dispatch" }>> = [];
845 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
846 Effect.provide(
847 Layer.merge(
848 Layer.mock(ThreadManagementService.ThreadManagementService)({
849 getThreadRecords: () => Effect.succeed(projection),
850 recoverDelegatedTask: () => Effect.void,
851 dispatch: (command) => {
852 if (command.type === "message.dispatch") dispatches.push(command);
853 return Effect.succeed({} as never);
854 },
855 }),
856 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
857 ),
858 ),
859 );
860 return dispatches;
861 });
862
863const continuationTexts = (projection: OrchestrationV2ThreadProjection) =>
864 continuationDispatches(projection).pipe(
865 Effect.map((dispatches) => dispatches.map((command) => command.text)),
866 );
867
868const cutMidTurn = (extra: Record<string, unknown> = {}) => {
869 const base = makeProjection();
870 return {
871 ...base,
872 runs: [
873 {
874 ...base.runs[0]!,
875 status: "cancelled",
876 completedAt: now,
877 userMessageId: MessageId.make("message:user"),
878 ...extra,
879 },
880 ],
881 providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }],
882 } as unknown as OrchestrationV2ThreadProjection;
883};
884
885const queuedFollowUp = {
886 id: RunId.make("run:queued"),
887 ordinal: 2,
888 providerInstanceId: instanceId,
889 providerThreadId,
890 status: "queued",
891 queueHeld: true,
892};
893
894it.effect("continues a cut run past queued follow-ups, which stay held", () =>
895 Effect.gen(function* () {
896 const live = makeProjection();
897 assert.equal(
898 restartContinuationRun(
899 {
900 ...live,
901 runs: [...live.runs, queuedFollowUp],
902 } as unknown as OrchestrationV2ThreadProjection,
903 now,
904 )?.id,
905 runId,
906 );
907 const cut = cutMidTurn();
908 const texts = yield* continuationTexts({
909 ...cut,
910 runs: [...cut.runs, queuedFollowUp],
911 } as unknown as OrchestrationV2ThreadProjection);
912 assert.deepEqual(texts, ["Continue where you left off."]);
913 }),
914);
915
916it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
917 Effect.gen(function* () {
918 const finishedContinuation = {
919 id: RunId.make("run:earlier-continuation"),
920 ordinal: 3,
921 providerInstanceId: instanceId,
922 providerThreadId,
923 status: "completed",
924 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
925 };
926 const live = makeProjection();
927 assert.equal(
928 restartContinuationRun(
929 {
930 ...live,
931 runs: [...live.runs, finishedContinuation],
932 } as unknown as OrchestrationV2ThreadProjection,
933 now,
934 )?.id,
935 runId,
936 );
937 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
938 const texts = yield* continuationTexts({
939 ...cut,
940 runs: [...cut.runs, finishedContinuation],
941 } as unknown as OrchestrationV2ThreadProjection);
942 assert.deepEqual(texts, ["Continue where you left off."]);
943 }),
944);
945
946it.effect("does not continue a run the user asked to stop before the restart", () =>
947 Effect.gen(function* () {
948 const texts = yield* continuationTexts({
949 ...cutMidTurn(),
950 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
951 } as unknown as OrchestrationV2ThreadProjection);
952 assert.deepEqual(texts, []);
953 }),
954);
955
956it.effect("does not continue a cut /compact or /logout turn", () =>
957 Effect.gen(function* () {
958 for (const text of ["/compact", " /LOGOUT "]) {
959 const texts = yield* continuationTexts({
960 ...cutMidTurn(),
961 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
962 } as unknown as OrchestrationV2ThreadProjection);
963 assert.deepEqual(texts, [], text);
964 }
965 const texts = yield* continuationTexts({
966 ...cutMidTurn(),
967 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
968 } as unknown as OrchestrationV2ThreadProjection);
969 assert.lengthOf(texts, 1);
970 }),
971);
972
973it.effect(
974 "carries the note forward when its continuation was cut before reaching the provider",
975 () =>
976 Effect.gen(function* () {
977 const base = makeProjection();
978 const original = {
979 ...base.runs[0]!,
980 id: RunId.make("run:original"),
981 status: "completed",
982 activeAttemptId: RunAttemptId.make("attempt:original"),
983 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
984 };
985 const projection = {
986 ...base,
987 runs: [
988 original,
989 {
990 ...base.runs[0]!,
991 ordinal: 2,
992 status: "cancelled",
993 restartContinuationOfRunId: original.id,
994 },
995 ],
996 providerTurns: [
997 {
998 ...base.providerTurns[0]!,
999 runAttemptId: original.activeAttemptId,
1000 status: "completed",
1001 },
1002 ],
1003 } as unknown as OrchestrationV2ThreadProjection;
1004 const texts = yield* continuationTexts(projection);
1005 assert.lengthOf(texts, 1);
1006 assert.include(texts[0]!, "sleep 25 && echo DONE");
1007 assert.notInclude(texts[0]!, "Continue where");
1008 }),
1009);
1010
1011it.effect("prepares later threads' continuations when one thread fails", () =>
1012 Effect.gen(function* () {
1013 const brokenThreadId = ThreadId.make("thread:broken");
1014 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
1015 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
1016 Effect.provide(
1017 Layer.mergeAll(
1018 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
1019 Layer.mock(ProjectionStore.ProjectionStoreV2)({
1020 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
1021 getRuntimeRecoveryProjection: (id) =>
1022 id === brokenThreadId
1023 ? Effect.fail(
1024 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
1025 )
1026 : Effect.succeed(makeProjection()),
1027 }),
1028 Layer.mock(EventSink.EventSinkV2)({
1029 writeWithEffects: (input) =>
1030 Effect.sync(() => {
1031 writes.push(input);
1032 return [];
1033 }),
1034 }),
1035 IdAllocator.layer,
1036 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
1037 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
1038 ),
1039 ),
1040 );
1041 yield* recovery.prepareForShutdown;
1042 assert.deepEqual(
1043 writes.map((write) => write.effects[0]?.request),
1044 [{ type: "provider-runtime.continue", sourceRunId: runId }],
1045 );
1046 }),
1047);
1048
1049it.effect.each([
1050 ["user_input", "pending", "live", false],
1051 ["user_input", "expired", "not_resumable", false],
1052 ["user_input", "cancelled", "not_resumable", false],
1053 ["command", "pending", "live", false],
1054 ["command", "expired", "not_resumable", false],
1055 ["user_input", "resolved", "live", true],
1056 ["command", "cancelled", "live", true],
1057 ["user_input", "pending", "message", true],
1058 ["dynamic_tool_call", "pending", "live", true],
1059 ["auth_refresh", "pending", "live", true],
1060] as const)(
1061 "a %s request that is %s with %s capability allows continuation: %s",
1062 ([kind, status, capability, shouldContinue]) =>
1063 Effect.gen(function* () {
1064 const base = makeProjection();
1065 const runtimeRequests = [
1066 {
1067 id: RuntimeRequestId.make("request:restart"),
1068 nodeId: NodeId.make("node:restart-question"),
1069 providerTurnId: base.providerTurns[0]!.id,
1070 kind,
1071 status,
1072 responseCapability:
1073 capability === "live"
1074 ? { type: capability, providerSessionId: sessionId }
1075 : capability === "not_resumable"
1076 ? { type: capability, reason: "The server restarted." }
1077 : { type: capability },
1078 },
1079 ];
1080 const live = { ...base, runtimeRequests } as unknown as OrchestrationV2ThreadProjection;
1081 assert.equal(restartContinuationRun(live, now) !== undefined, shouldContinue);
1082 const cut = {
1083 ...cutMidTurn(),
1084 runtimeRequests,
1085 } as unknown as OrchestrationV2ThreadProjection;
1086 assert.lengthOf(yield* continuationTexts(cut), shouldContinue ? 1 : 0);
1087 }),
1088);
1089
1090it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
1091 Effect.gen(function* () {
1092 const live = makeProjection();
1093 for (const held of [
1094 { snoozedUntil: DateTime.add(now, { days: 1 }) },
1095 { settledOverride: "settled" as const },
1096 ]) {
1097 const thread = { ...live.thread, ...held };
1098 assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
1099 assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
1100 }
1101 const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
1102 assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
1103 }),
1104);
1105
1106it.effect("does not continue a run waiting on a secret the restart closed", () =>
1107 Effect.gen(function* () {
1108 const completedAt = DateTime.makeUnsafe("2026-10-03T10:05:00.000Z");
1109 const secret = (secretStatus: string, at: DateTime.Utc | null) =>
1110 ({ type: "secret_request", runId, secretStatus, completedAt: at }) as never;
1111 assert.isUndefined(
1112 restartContinuationRun({ ...makeProjection(), turnItems: [secret("pending", null)] }, now),
1113 );
1114 const cut = cutMidTurn({ completedAt });
1115 assert.deepEqual(
1116 yield* continuationTexts({ ...cut, turnItems: [secret("cancelled", completedAt)] }),
1117 [],
1118 );
1119 assert.lengthOf(
1120 yield* continuationTexts({
1121 ...cut,
1122 turnItems: [secret("cancelled", DateTime.subtract(completedAt, { seconds: 1 }))],
1123 }),
1124 1,
1125 );
1126 }),
1127);
1128
1129it.effect.each(["completed", "failed", "interrupted"] as const)(
1130 "does not continue when the provider turn %s before the app run settled",
1131 (status) =>
1132 Effect.gen(function* () {
1133 const cut = cutMidTurn();
1134 assert.deepEqual(
1135 yield* continuationTexts({
1136 ...cut,
1137 providerTurns: [{ ...cut.providerTurns[0]!, status }],
1138 }),
1139 [],
1140 );
1141 }),
1142);