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

RestartContinuation.test.ts

1,283 lines45.5 KB

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