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

RestartContinuation.test.ts

970 lines34.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");
38// "No project" threads belong to the environment's Scratch project.
39const scratchProjectId = ProjectId.make("project:scratch");
40const now = DateTime.makeUnsafe("2026-10-03T12:00:00.000Z");
41​
42function makeProjection() {
43 return {
44 thread: {
45 id: threadId,
46 projectId: ProjectId.make("restart-project"),
47 providerInstanceId: instanceId,
48 archivedAt: null,
49 deletedAt: null,
50 },
51 runs: [
52 {
53 id: runId,
54 ordinal: 1,
55 providerInstanceId: instanceId,
56 modelSelection: { instanceId, model: "gpt-6" },
57 providerThreadId,
58 activeAttemptId: attemptId,
59 status: "running",
60 },
61 ],
62 providerThreads: [
63 {
64 id: providerThreadId,
65 appThreadId: threadId,
66 ownerNodeId: null,
67 driver,
68 providerInstanceId: instanceId,
69 providerSessionId: sessionId,
70 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
71 status: "active",
72 },
73 ],
74 providerSessions: [
75 { id: sessionId, driver, providerInstanceId: instanceId, status: "running" },
76 ],
77 providerTurns: [
78 {
79 id: ProviderTurnId.make("turn:restart"),
80 providerThreadId,
81 runAttemptId: attemptId,
82 status: "running",
83 },
84 ],
85 runtimeRequests: [],
86 attempts: [],
87 nodes: [],
88 subagents: [],
89 messages: [],
90 turnItems: [],
91 } as unknown as OrchestrationV2ThreadProjection;
93​
94it("requires matching saved native state for an unfinished root run", () => {
95 const projection = makeProjection();
96 assert.equal(restartContinuationRun(projection, now)?.id, runId);
97 for (const invalid of [
98 { ...projection, thread: { ...projection.thread, archivedAt: {} } },
99 { ...projection, thread: { ...projection.thread, deletedAt: {} } },
100 {
101 ...projection,
102 thread: { ...projection.thread, providerInstanceId: ProviderInstanceId.make("other") },
103 },
104 {
105 ...projection,
106 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
107 },
108 {
109 ...projection,
110 providerSessions: [
111 {
112 ...projection.providerSessions[0]!,
113 providerInstanceId: ProviderInstanceId.make("other"),
114 },
115 ],
116 },
117 { ...projection, providerTurns: [] },
118 ...[
119 "queued",
120 "preparing",
121 "starting",
122 "waiting",
123 "completed",
124 "cancelled",
125 "failed",
126 "interrupted",
127 ].map((status) => ({ ...projection, runs: [{ ...projection.runs[0]!, status }] })),
128 ])
129 assert.isUndefined(restartContinuationRun(invalid as OrchestrationV2ThreadProjection, now));
130});
131​
132it("continues a live turn whose session the adapter never marked running", () => {
133 const projection = makeProjection();
134 // Codex, Claude, Cursor and ACP sessions stay "ready" for their whole life.
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("does not continue a failed run that lost background work", () =>
227 Effect.gen(function* () {
228 const base = makeProjection();
229 const projection = {
230 ...base,
231 runs: [
232 {
233 ...base.runs[0]!,
234 status: "failed",
235 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
236 },
237 ],
238 providerTurns: [{ ...base.providerTurns[0]!, status: "failed" }],
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, 0);
259 }),
260);
261​
262it.effect.each([
263 [false, undefined],
264 [true, undefined],
265 [false, true],
266 [true, false],
267] as const)(
268 "atomically records restart intent with cancellation when opt-in is %s and project override is %s",
269 ([enabled, projectOverride]) =>
270 Effect.gen(function* () {
271 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
272 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
273 Effect.provide(
274 Layer.mergeAll(
275 ServerSettings.layerTest({
276 continueThreadsAfterServerUpdate: enabled,
277 projectSettingsOverrides:
278 projectOverride === undefined
279 ? {}
280 : {
281 [ProjectId.make("restart-project")]: {
282 continueThreadsAfterServerUpdate: projectOverride,
283 },
284 },
285 }),
286 Layer.mock(ProjectionStore.ProjectionStoreV2)({
287 getRecoveryThreadIds: () => Effect.succeed([threadId]),
288 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
289 }),
290 Layer.mock(EventSink.EventSinkV2)({
291 commitCommand: (input) => {
292 committed = input;
293 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
294 },
295 }),
296 IdAllocator.layer,
297 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
298 runRecoveryOnce: Effect.succeed(false),
299 }),
300 Layer.mock(EffectOutbox.EffectOutboxV2)({
301 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
302 }),
303 ),
304 ),
305 );
306 yield* recovery.reconcile("startup");
307 assert.isDefined(committed);
308 assert.isTrue(
309 committed!.events.some(
310 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
311 ),
312 );
313 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
314 if (projectOverride ?? enabled)
315 assert.deepEqual(committed!.effects[0]?.request, {
316 type: "provider-runtime.continue",
317 sourceRunId: runId,
318 });
319 }),
320);
321​
322it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
323 Effect.gen(function* () {
324 let projection = makeProjection();
325 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
326 const commands: Parameters<
327 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
328 >[0][] = [];
329 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
330 getThreadRecords: () => Effect.succeed(projection),
331 recoverDelegatedTask: () => Effect.void,
332 dispatch: (command) => {
333 commands.push(command);
334 if (command.type === "message.dispatch")
335 projection = { ...projection, messages: [{ id: command.messageId } as never] };
336 return Effect.succeed({} as never);
337 },
338 });
339 const layerEnabled = Layer.merge(
340 layerThreads,
341 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
342 );
343 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
344 Effect.provide(layerEnabled),
345 );
346 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
347 Effect.provide(layerEnabled),
348 );
349 assert.lengthOf(commands, 1);
350 assert.match(String(commands[0]!.commandId), /run:restart$/);
351 if (commands[0]!.type === "message.dispatch")
352 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
353 projection = {
354 ...projection,
355 messages: [],
356 runs: [
357 ...projection.runs,
358 {
359 ...projection.runs[0]!,
360 id: RunId.make("run:user-newer"),
361 ordinal: 2,
362 status: "completed",
363 },
364 ],
365 };
366 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
367 Effect.provide(layerEnabled),
368 );
369 assert.lengthOf(commands, 1);
370 projection = { ...projection, runs: [projection.runs[0]!] };
371 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
372 Effect.provide(
373 Layer.merge(
374 layerThreads,
375 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false }),
376 ),
377 ),
378 );
379 assert.lengthOf(commands, 1);
380 }),
381);
382​
383it.effect("prepares no continuation for background work another provider thread launched", () =>
384 Effect.gen(function* () {
385 const base = makeProjection();
386 const claudeThreadId = ProviderThreadId.make("provider-thread:claude");
387 // A Claude turn left a background subagent open, then the thread switched
388 // to Codex and its turn settled. Recovery would cancel Claude's work.
389 const projection = {
390 ...base,
391 runs: [{ ...base.runs[0]!, status: "completed" }],
392 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
393 turnItems: [
394 {
395 id: "turn-item:claude-subagent",
396 runId: RunId.make("run:claude"),
397 providerThreadId: claudeThreadId,
398 type: "subagent",
399 status: "running",
400 },
401 ],
402 } as unknown as OrchestrationV2ThreadProjection;
403 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
404 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
405 Effect.provide(
406 Layer.mergeAll(
407 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
408 Layer.mock(ProjectionStore.ProjectionStoreV2)({
409 getRecoveryThreadIds: () => Effect.succeed([threadId]),
410 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
411 }),
412 Layer.mock(EventSink.EventSinkV2)({
413 writeWithEffects: (input) =>
414 Effect.sync(() => {
415 writes.push(input);
416 return [];
417 }),
418 }),
419 IdAllocator.layer,
420 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
421 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
422 ),
423 ),
424 );
425 yield* recovery.prepareForShutdown;
426 assert.lengthOf(writes, 0);
427 // Work on the settled run's own provider thread must not wake it either.
428 const ownWork = {
429 ...projection,
430 turnItems: [{ ...projection.turnItems[0]!, providerThreadId }],
431 } as OrchestrationV2ThreadProjection;
432 const ownRecovery = yield* ProviderRuntimeRecovery.make.pipe(
433 Effect.provide(
434 Layer.mergeAll(
435 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
436 Layer.mock(ProjectionStore.ProjectionStoreV2)({
437 getRecoveryThreadIds: () => Effect.succeed([threadId]),
438 getRuntimeRecoveryProjection: () => Effect.succeed(ownWork),
439 }),
440 Layer.mock(EventSink.EventSinkV2)({
441 writeWithEffects: (input) =>
442 Effect.sync(() => {
443 writes.push(input);
444 return [];
445 }),
446 }),
447 IdAllocator.layer,
448 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
449 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
450 ),
451 ),
452 );
453 yield* ownRecovery.prepareForShutdown;
454 assert.lengthOf(writes, 0);
455 }),
456);
457​
458it.effect.each([
459 ["completed", scratchProjectId],
460 ["completed", ProjectId.make("restart-project")],
461 ["waiting", scratchProjectId],
462 ["waiting", ProjectId.make("restart-project")],
463] as const)(
464 "cleans up background work without waking a %s run in project %s",
465 ([status, projectId]) =>
466 Effect.gen(function* () {
467 const base = makeProjection();
468 const projection = {
469 ...base,
470 thread: { ...base.thread, projectId },
471 runs: [{ ...base.runs[0]!, status }],
472 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
473 turnItems: [
474 {
475 id: "turn-item:background-subagent",
476 runId,
477 nodeId: null,
478 providerThreadId,
479 providerInstanceId: instanceId,
480 type: "subagent",
481 subagentId: "subagent:background",
482 title: "Background reviewer",
483 status: "running",
484 },
485 ],
486 subagents: [
487 {
488 id: "subagent:background",
489 runId,
490 origin: "provider_native",
491 driver,
492 providerInstanceId: instanceId,
493 status: "running",
494 },
495 ],
496 } as unknown as OrchestrationV2ThreadProjection;
497 for (const trigger of ["startup", "shutdown"] as const) {
498 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
499 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
500 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
501 Effect.provide(
502 Layer.mergeAll(
503 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
504 Layer.mock(ProjectionStore.ProjectionStoreV2)({
505 getRecoveryThreadIds: () => Effect.succeed([threadId]),
506 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
507 }),
508 Layer.mock(EventSink.EventSinkV2)({
509 writeWithEffects: (input) =>
510 Effect.sync(() => {
511 writes.push(input);
512 return [];
513 }),
514 commitCommand: (input) =>
515 Effect.sync(() => {
516 commits.push(input);
517 return { committed: true, cancelledEffectCount: 0 } as never;
518 }),
519 }),
520 IdAllocator.layer,
521 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
522 runRecoveryOnce: Effect.succeed(false),
523 }),
524 Layer.mock(EffectOutbox.EffectOutboxV2)({
525 listByCommandId: () => Effect.succeed([]),
526 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
527 }),
528 ),
529 ),
530 );
531 if (trigger === "shutdown") yield* recovery.prepareForShutdown;
532 yield* recovery.reconcile(trigger);
533 assert.lengthOf(writes, 0);
534 assert.lengthOf(commits, 1);
535 assert.lengthOf(commits[0]!.effects, 0);
536 const events = commits[0]!.events;
537 for (const type of ["turn-item.updated", "subagent.updated"] as const)
538 assert.isTrue(
539 events.some((event) => event.type === type && event.payload.status === "cancelled"),
540 );
541 const note = events.find((event) => event.type === "run.background-work-cancelled");
542 assert.equal(note?.runId, runId);
543 assert.deepEqual(note?.payload.restartCancelledBackgroundWork, [
544 { kind: "subagent", label: "Background reviewer", id: "turn-item:background-subagent" },
545 ]);
546 if (status === "completed")
547 assert.isFalse(events.some((event) => event.type === "run.updated"));
548 }
549 }),
550);
551​
552it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
553 Effect.gen(function* () {
554 let projection = makeProjection();
555 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
556 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
557 Effect.provide(
558 Layer.mergeAll(
559 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
560 Layer.mock(ProjectionStore.ProjectionStoreV2)({
561 getRecoveryThreadIds: () => Effect.succeed([threadId]),
562 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
563 }),
564 Layer.mock(EventSink.EventSinkV2)({
565 writeWithEffects: (input) =>
566 Effect.sync(() => {
567 assert.lengthOf(input.events, 0);
568 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
569 projection = {
570 ...projection,
571 runs: [{ ...projection.runs[0]!, status: "completed" }],
572 };
573 return [];
574 }),
575 commitCommand: (input) =>
576 Effect.sync(() => {
577 commits.push(input);
578 return { committed: true, cancelledEffectCount: 0 } as never;
579 }),
580 }),
581 IdAllocator.layer,
582 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
583 runRecoveryOnce: Effect.succeed(false),
584 }),
585 Layer.mock(EffectOutbox.EffectOutboxV2)({
586 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
587 }),
588 ),
589 ),
590 );
591 yield* recovery.prepareForShutdown;
592 yield* recovery.reconcile("shutdown");
593 assert.isFalse(
594 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
595 );
596 let dispatched = false;
597 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
598 Effect.provide(
599 Layer.mergeAll(
600 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
601 Layer.mock(ThreadManagementService.ThreadManagementService)({
602 getThreadRecords: () => Effect.succeed(projection),
603 recoverDelegatedTask: () => Effect.void,
604 dispatch: () =>
605 Effect.sync(() => {
606 dispatched = true;
607 return {} as never;
608 }),
609 }),
610 ),
611 ),
612 );
613 assert.isFalse(dispatched);
614 }),
615);
616​
617const continuationDispatches = (projection: OrchestrationV2ThreadProjection) =>
618 Effect.gen(function* () {
619 const dispatches: Array<Extract<OrchestrationV2Command, { type: "message.dispatch" }>> = [];
620 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
621 Effect.provide(
622 Layer.merge(
623 Layer.mock(ThreadManagementService.ThreadManagementService)({
624 getThreadRecords: () => Effect.succeed(projection),
625 recoverDelegatedTask: () => Effect.void,
626 dispatch: (command) => {
627 if (command.type === "message.dispatch") dispatches.push(command);
628 return Effect.succeed({} as never);
629 },
630 }),
631 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
632 ),
633 ),
634 );
635 return dispatches;
636 });
637​
638const continuationTexts = (projection: OrchestrationV2ThreadProjection) =>
639 continuationDispatches(projection).pipe(
640 Effect.map((dispatches) => dispatches.map((command) => command.text)),
641 );
642​
643const cutMidTurn = (extra: Record<string, unknown> = {}) => {
644 const base = makeProjection();
645 return {
646 ...base,
647 runs: [
648 {
649 ...base.runs[0]!,
650 status: "cancelled",
651 userMessageId: MessageId.make("message:user"),
652 ...extra,
653 },
654 ],
655 providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }],
656 } as unknown as OrchestrationV2ThreadProjection;
657};
658​
659const queuedFollowUp = {
660 id: RunId.make("run:queued"),
661 ordinal: 2,
662 providerInstanceId: instanceId,
663 providerThreadId,
664 status: "queued",
665 queueHeld: true,
666};
667​
668it.effect("continues a cut run past queued follow-ups, which stay held", () =>
669 Effect.gen(function* () {
670 const live = makeProjection();
671 assert.equal(
672 restartContinuationRun(
673 {
674 ...live,
675 runs: [...live.runs, queuedFollowUp],
676 } as unknown as OrchestrationV2ThreadProjection,
677 now,
678 )?.id,
679 runId,
680 );
681 const cut = cutMidTurn();
682 const texts = yield* continuationTexts({
683 ...cut,
684 runs: [...cut.runs, queuedFollowUp],
685 } as unknown as OrchestrationV2ThreadProjection);
686 assert.deepEqual(texts, ["Continue where you left off."]);
687 }),
688);
689​
690it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
691 Effect.gen(function* () {
692 // The continuation (ordinal 3) ran ahead of the held queue, then the user
693 // resumed the queued run (ordinal 1 here) and the server restarted again.
694 const finishedContinuation = {
695 id: RunId.make("run:earlier-continuation"),
696 ordinal: 3,
697 providerInstanceId: instanceId,
698 providerThreadId,
699 status: "completed",
700 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
701 };
702 const live = makeProjection();
703 assert.equal(
704 restartContinuationRun(
705 {
706 ...live,
707 runs: [...live.runs, finishedContinuation],
708 } as unknown as OrchestrationV2ThreadProjection,
709 now,
710 )?.id,
711 runId,
712 );
713 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
714 const texts = yield* continuationTexts({
715 ...cut,
716 runs: [...cut.runs, finishedContinuation],
717 } as unknown as OrchestrationV2ThreadProjection);
718 assert.deepEqual(texts, ["Continue where you left off."]);
719 }),
720);
721​
722it.effect("does not continue a run the user asked to stop before the restart", () =>
723 Effect.gen(function* () {
724 const texts = yield* continuationTexts({
725 ...cutMidTurn(),
726 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
727 } as unknown as OrchestrationV2ThreadProjection);
728 assert.deepEqual(texts, []);
729 }),
730);
731​
732it.effect("does not continue a cut /compact or /logout turn", () =>
733 Effect.gen(function* () {
734 for (const text of ["/compact", " /LOGOUT "]) {
735 const texts = yield* continuationTexts({
736 ...cutMidTurn(),
737 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
738 } as unknown as OrchestrationV2ThreadProjection);
739 assert.deepEqual(texts, [], text);
740 }
741 const texts = yield* continuationTexts({
742 ...cutMidTurn(),
743 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
744 } as unknown as OrchestrationV2ThreadProjection);
745 assert.lengthOf(texts, 1);
746 }),
747);
748​
749it.effect("tells a turn cut mid-way about the background work it lost", () =>
750 Effect.gen(function* () {
751 const texts = yield* continuationTexts(
752 cutMidTurn({
753 restartCancelledBackgroundWork: [{ kind: "subagent", label: "Background reviewer" }],
754 }),
755 );
756 assert.lengthOf(texts, 1);
757 assert.include(texts[0]!, "Background reviewer");
758 assert.isTrue(texts[0]!.endsWith("Continue where you left off."));
759 }),
760);
761​
762it.effect("shows a continuation as a T3 Code notice whose detail is the prompt", () =>
763 Effect.gen(function* () {
764 const [resumed] = yield* continuationDispatches(cutMidTurn());
765 assert.deepEqual(resumed?.notification, {
766 source: { kind: "system" },
767 outcome: "updated",
768 summary: "T3 Code restarted and resumed this turn",
769 detail: "Continue where you left off.",
770 });
771 }),
772);
773​
774it.effect(
775 "carries the note forward when its continuation was cut before reaching the provider",
776 () =>
777 Effect.gen(function* () {
778 const base = makeProjection();
779 const original = {
780 ...base.runs[0]!,
781 id: RunId.make("run:original"),
782 status: "completed",
783 activeAttemptId: RunAttemptId.make("attempt:original"),
784 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
785 };
786 const projection = {
787 ...base,
788 runs: [
789 original,
790 {
791 ...base.runs[0]!,
792 ordinal: 2,
793 status: "cancelled",
794 restartContinuationOfRunId: original.id,
795 },
796 ],
797 // The original turn settled; the continuation's attempt never started one.
798 providerTurns: [
799 {
800 ...base.providerTurns[0]!,
801 runAttemptId: original.activeAttemptId,
802 status: "completed",
803 },
804 ],
805 } as unknown as OrchestrationV2ThreadProjection;
806 const texts = yield* continuationTexts(projection);
807 assert.lengthOf(texts, 1);
808 assert.include(texts[0]!, "sleep 25 && echo DONE");
809 assert.notInclude(texts[0]!, "Continue where");
810 }),
811);
812​
813it.effect("prepares later threads' continuations when one thread fails", () =>
814 Effect.gen(function* () {
815 const brokenThreadId = ThreadId.make("thread:broken");
816 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
817 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
818 Effect.provide(
819 Layer.mergeAll(
820 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
821 Layer.mock(ProjectionStore.ProjectionStoreV2)({
822 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
823 getRuntimeRecoveryProjection: (id) =>
824 id === brokenThreadId
825 ? Effect.fail(
826 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
827 )
828 : Effect.succeed(makeProjection()),
829 }),
830 Layer.mock(EventSink.EventSinkV2)({
831 writeWithEffects: (input) =>
832 Effect.sync(() => {
833 writes.push(input);
834 return [];
835 }),
836 }),
837 IdAllocator.layer,
838 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
839 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
840 ),
841 ),
842 );
843 yield* recovery.prepareForShutdown;
844 assert.deepEqual(
845 writes.map((write) => write.effects[0]?.request),
846 [{ type: "provider-runtime.continue", sourceRunId: runId }],
847 );
848 }),
849);
850​
851it.effect("stops continuing after three automatic restart continuations in a row", () =>
852 Effect.gen(function* () {
853 const first = RunId.make("run:first-continuation");
854 const second = RunId.make("run:second-continuation");
855 const cut = cutMidTurn({ restartContinuationOfRunId: second });
856 const withTwoLinks = {
857 ...cut,
858 runs: [
859 ...cut.runs,
860 { ...cut.runs[0]!, id: second, restartContinuationOfRunId: first },
861 { ...cut.runs[0]!, id: first, restartContinuationOfRunId: undefined },
862 ],
863 } as unknown as OrchestrationV2ThreadProjection;
864 assert.lengthOf(yield* continuationTexts(withTwoLinks), 1);
865​
866 const withThreeLinks = {
867 ...withTwoLinks,
868 runs: withTwoLinks.runs.map((run) =>
869 run.id === first ? { ...run, restartContinuationOfRunId: RunId.make("run:root") } : run,
870 ),
871 } as unknown as OrchestrationV2ThreadProjection;
872 assert.lengthOf(yield* continuationTexts(withThreeLinks), 0);
873 }),
874);
875​
876it.effect.each([
877 ["user_input", "pending", "live", false],
878 ["user_input", "expired", "not_resumable", false],
879 ["user_input", "cancelled", "not_resumable", false],
880 ["command", "pending", "live", false],
881 ["command", "expired", "not_resumable", false],
882 ["user_input", "resolved", "live", true],
883 ["command", "cancelled", "live", true],
884 ["user_input", "pending", "message", true],
885 ["dynamic_tool_call", "pending", "live", true],
886 ["auth_refresh", "pending", "live", true],
887] as const)(
888 "a %s request that is %s with %s capability allows continuation: %s",
889 ([kind, status, capability, shouldContinue]) =>
890 Effect.gen(function* () {
891 const base = makeProjection();
892 const runtimeRequests = [
893 {
894 id: RuntimeRequestId.make("request:restart"),
895 nodeId: NodeId.make("node:restart-question"),
896 providerTurnId: base.providerTurns[0]!.id,
897 kind,
898 status,
899 responseCapability:
900 capability === "live"
901 ? { type: capability, providerSessionId: sessionId }
902 : capability === "not_resumable"
903 ? { type: capability, reason: "The server restarted." }
904 : { type: capability },
905 },
906 ];
907 const live = { ...base, runtimeRequests } as unknown as OrchestrationV2ThreadProjection;
908 assert.equal(restartContinuationRun(live, now) !== undefined, shouldContinue);
909 const cut = {
910 ...cutMidTurn(),
911 runtimeRequests,
912 } as unknown as OrchestrationV2ThreadProjection;
913 assert.lengthOf(yield* continuationTexts(cut), shouldContinue ? 1 : 0);
914 }),
915);
916​
917it.effect("does not wake a snoozed or settled thread, but continues once a snooze elapsed", () =>
918 Effect.gen(function* () {
919 const live = makeProjection();
920 for (const held of [
921 { snoozedUntil: DateTime.add(now, { days: 1 }) },
922 { settledOverride: "settled" as const },
923 ]) {
924 const thread = { ...live.thread, ...held };
925 assert.isUndefined(restartContinuationRun({ ...live, thread }, now));
926 assert.deepEqual(yield* continuationTexts({ ...cutMidTurn(), thread }), []);
927 }
928 const thread = { ...live.thread, snoozedUntil: DateTime.subtract(now, { minutes: 1 }) };
929 assert.equal(restartContinuationRun({ ...live, thread }, now)?.id, runId);
930 }),
931);
932​
933it.effect("does not continue a run waiting on a secret the restart closed", () =>
934 Effect.gen(function* () {
935 const completedAt = DateTime.makeUnsafe("2026-10-03T10:05:00.000Z");
936 const secret = (secretStatus: string, at: DateTime.Utc | null) =>
937 ({ type: "secret_request", runId, secretStatus, completedAt: at }) as never;
938 assert.isUndefined(
939 restartContinuationRun({ ...makeProjection(), turnItems: [secret("pending", null)] }, now),
940 );
941 const cut = cutMidTurn({ completedAt });
942 assert.deepEqual(
943 yield* continuationTexts({ ...cut, turnItems: [secret("cancelled", completedAt)] }),
944 [],
945 );
946 // A secret the user dismissed earlier in the run does not hold it.
947 assert.lengthOf(
948 yield* continuationTexts({
949 ...cut,
950 turnItems: [secret("cancelled", DateTime.subtract(completedAt, { seconds: 1 }))],
951 }),
952 1,
953 );
954 }),
955);
956​
957it.effect.each(["completed", "failed", "interrupted"] as const)(
958 "does not continue when the provider turn %s before the app run settled",
959 (status) =>
960 Effect.gen(function* () {
961 const cut = cutMidTurn();
962 assert.deepEqual(
963 yield* continuationTexts({
964 ...cut,
965 providerTurns: [{ ...cut.providerTurns[0]!, status }],
966 }),
967 [],
968 );
969 }),
970);