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

RestartContinuation.test.ts

1,110 lines39.2 KB

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