Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 MessageId,
4 ProjectId,
5 ProviderDriverKind,
6 ProviderInstanceId,
7 ProviderSessionId,
8 ProviderThreadId,
9 ProviderTurnId,
10 RunAttemptId,
11 RunId,
12 ThreadId,
13 type OrchestrationV2ThreadProjection,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as ServerSettings from "../serverSettings.ts";
19import { restartContinuationRun, continueRestartedRun } from "./RestartContinuation.ts";
20import * as ThreadManagementService from "./ThreadManagementService.ts";
21import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts";
22import * as ProjectionStore from "./ProjectionStore.ts";
23import * as EventSink from "./EventSink.ts";
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25import * as EffectWorker from "./EffectWorker.ts";
26import * as EffectOutbox from "./EffectOutbox.ts";
27
28const threadId = ThreadId.make("thread:restart");
29const runId = RunId.make("run:restart");
30const instanceId = ProviderInstanceId.make("codex");
31const driver = ProviderDriverKind.make("codex");
32const providerThreadId = ProviderThreadId.make("provider-thread:restart");
33const sessionId = ProviderSessionId.make("session:restart");
34const attemptId = RunAttemptId.make("attempt:restart");
35// "No project" threads belong to the environment's Scratch project.
36const scratchProjectId = ProjectId.make("project:scratch");
37
38function makeProjection() {
39 return {
40 thread: {
41 id: threadId,
42 projectId: ProjectId.make("restart-project"),
43 providerInstanceId: instanceId,
44 archivedAt: null,
45 deletedAt: null,
46 },
47 runs: [
48 {
49 id: runId,
50 ordinal: 1,
51 providerInstanceId: instanceId,
52 modelSelection: { instanceId, model: "gpt-6" },
53 providerThreadId,
54 activeAttemptId: attemptId,
55 status: "running",
56 },
57 ],
58 providerThreads: [
59 {
60 id: providerThreadId,
61 appThreadId: threadId,
62 ownerNodeId: null,
63 driver,
64 providerInstanceId: instanceId,
65 providerSessionId: sessionId,
66 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
67 status: "active",
68 },
69 ],
70 providerSessions: [
71 { id: sessionId, driver, providerInstanceId: instanceId, status: "running" },
72 ],
73 providerTurns: [
74 {
75 id: ProviderTurnId.make("turn:restart"),
76 providerThreadId,
77 runAttemptId: attemptId,
78 status: "running",
79 },
80 ],
81 runtimeRequests: [],
82 attempts: [],
83 nodes: [],
84 subagents: [],
85 messages: [],
86 turnItems: [],
87 } as unknown as OrchestrationV2ThreadProjection;
88}
89
90it("requires matching saved native state for an unfinished root run", () => {
91 const projection = makeProjection();
92 assert.equal(restartContinuationRun(projection)?.id, runId);
93 for (const invalid of [
94 { ...projection, thread: { ...projection.thread, archivedAt: {} } },
95 { ...projection, thread: { ...projection.thread, deletedAt: {} } },
96 {
97 ...projection,
98 thread: { ...projection.thread, providerInstanceId: ProviderInstanceId.make("other") },
99 },
100 {
101 ...projection,
102 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
103 },
104 {
105 ...projection,
106 providerSessions: [
107 {
108 ...projection.providerSessions[0]!,
109 providerInstanceId: ProviderInstanceId.make("other"),
110 },
111 ],
112 },
113 { ...projection, providerTurns: [] },
114 ...[
115 "queued",
116 "preparing",
117 "starting",
118 "waiting",
119 "completed",
120 "cancelled",
121 "failed",
122 "interrupted",
123 ].map((status) => ({ ...projection, runs: [{ ...projection.runs[0]!, status }] })),
124 ])
125 assert.isUndefined(restartContinuationRun(invalid as OrchestrationV2ThreadProjection));
126});
127
128it("continues a live turn whose session the adapter never marked running", () => {
129 const projection = makeProjection();
130 // Codex, Claude, Cursor and ACP sessions stay "ready" for their whole life.
131 const withSessionStatus = (status: string) =>
132 ({
133 ...projection,
134 providerSessions: [{ ...projection.providerSessions[0]!, status }],
135 }) as OrchestrationV2ThreadProjection;
136 for (const status of ["starting", "ready", "running", "waiting"])
137 assert.equal(restartContinuationRun(withSessionStatus(status))?.id, runId, status);
138 for (const status of ["stopped", "error"])
139 assert.isUndefined(restartContinuationRun(withSessionStatus(status)), status);
140});
141
142it("recovers an admitted continuation after another crash before provider start", () => {
143 const projection = makeProjection();
144 const starting = {
145 ...projection,
146 runs: [
147 {
148 ...projection.runs[0]!,
149 status: "starting" as const,
150 restartContinuationOfRunId: RunId.make("run:previous-crash"),
151 },
152 ],
153 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
154 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
155 providerTurns: [],
156 };
157 assert.equal(restartContinuationRun(starting)?.id, runId);
158});
159
160it("does not continue settled root runs with restart-cancelled background work", () => {
161 const projection = makeProjection();
162 const settled = {
163 ...projection,
164 runs: [
165 {
166 ...projection.runs[0]!,
167 status: "completed" as const,
168 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
169 },
170 ],
171 providerThreads: [{ ...projection.providerThreads[0]!, status: "idle" as const }],
172 providerSessions: [{ ...projection.providerSessions[0]!, status: "stopped" as const }],
173 providerTurns: [],
174 };
175 for (const projectId of [scratchProjectId, projection.thread.projectId])
176 for (const status of ["completed", "waiting"] as const)
177 assert.isUndefined(
178 restartContinuationRun({
179 ...settled,
180 thread: { ...settled.thread, projectId },
181 runs: [{ ...settled.runs[0]!, status }],
182 }),
183 );
184});
185
186it.effect.each(["completed", "waiting", "cancelled"] as const)(
187 "ignores a pending restart continuation for a %s run whose provider turn settled",
188 (status) =>
189 Effect.gen(function* () {
190 const base = makeProjection();
191 const work = [{ kind: "shell" as const, label: "sleep 25 && echo DONE" }];
192 const projection = {
193 ...base,
194 runs: [{ ...base.runs[0]!, status, restartCancelledBackgroundWork: work }],
195 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
196 } as unknown as OrchestrationV2ThreadProjection;
197 const commands: Parameters<
198 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
199 >[0][] = [];
200 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
201 Effect.provide(
202 Layer.merge(
203 Layer.mock(ThreadManagementService.ThreadManagementService)({
204 getThreadRecords: () => Effect.succeed(projection),
205 recoverDelegatedTask: () => Effect.void,
206 dispatch: (command) => {
207 commands.push(command);
208 return Effect.succeed({} as never);
209 },
210 }),
211 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
212 ),
213 ),
214 );
215 assert.lengthOf(commands, 0);
216 }),
217);
218
219it.effect("does not continue a failed run that lost background work", () =>
220 Effect.gen(function* () {
221 const base = makeProjection();
222 const projection = {
223 ...base,
224 runs: [
225 {
226 ...base.runs[0]!,
227 status: "failed",
228 restartCancelledBackgroundWork: [{ kind: "shell" as const, label: "sleep 25" }],
229 },
230 ],
231 providerTurns: [{ ...base.providerTurns[0]!, status: "failed" }],
232 } as unknown as OrchestrationV2ThreadProjection;
233 const commands: Parameters<
234 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
235 >[0][] = [];
236 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
237 Effect.provide(
238 Layer.merge(
239 Layer.mock(ThreadManagementService.ThreadManagementService)({
240 getThreadRecords: () => Effect.succeed(projection),
241 recoverDelegatedTask: () => Effect.void,
242 dispatch: (command) => {
243 commands.push(command);
244 return Effect.succeed({} as never);
245 },
246 }),
247 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
248 ),
249 ),
250 );
251 assert.lengthOf(commands, 0);
252 }),
253);
254
255it.effect.each([
256 [false, undefined],
257 [true, undefined],
258 [false, true],
259 [true, false],
260] as const)(
261 "atomically records restart intent with cancellation when opt-in is %s and project override is %s",
262 ([enabled, projectOverride]) =>
263 Effect.gen(function* () {
264 let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
265 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
266 Effect.provide(
267 Layer.mergeAll(
268 ServerSettings.layerTest({
269 continueThreadsAfterServerUpdate: enabled,
270 projectSettingsOverrides:
271 projectOverride === undefined
272 ? {}
273 : {
274 [ProjectId.make("restart-project")]: {
275 continueThreadsAfterServerUpdate: projectOverride,
276 },
277 },
278 }),
279 Layer.mock(ProjectionStore.ProjectionStoreV2)({
280 getRecoveryThreadIds: () => Effect.succeed([threadId]),
281 getRuntimeRecoveryProjection: () => Effect.succeed(makeProjection()),
282 }),
283 Layer.mock(EventSink.EventSinkV2)({
284 commitCommand: (input) => {
285 committed = input;
286 return Effect.succeed({ committed: true, cancelledEffectCount: 1 } as never);
287 },
288 }),
289 IdAllocator.layer,
290 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
291 runRecoveryOnce: Effect.succeed(false),
292 }),
293 Layer.mock(EffectOutbox.EffectOutboxV2)({
294 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
295 }),
296 ),
297 ),
298 );
299 yield* recovery.reconcile("startup");
300 assert.isDefined(committed);
301 assert.isTrue(
302 committed!.events.some(
303 (event) => event.type === "run.updated" && event.payload.status === "cancelled",
304 ),
305 );
306 assert.lengthOf(committed!.effects, (projectOverride ?? enabled) ? 1 : 0);
307 if (projectOverride ?? enabled)
308 assert.deepEqual(committed!.effects[0]?.request, {
309 type: "provider-runtime.continue",
310 sourceRunId: runId,
311 });
312 }),
313);
314
315it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
316 Effect.gen(function* () {
317 let projection = makeProjection();
318 projection = { ...projection, runs: [{ ...projection.runs[0]!, status: "cancelled" }] };
319 const commands: Parameters<
320 ThreadManagementService.ThreadManagementService["Service"]["dispatch"]
321 >[0][] = [];
322 const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({
323 getThreadRecords: () => Effect.succeed(projection),
324 recoverDelegatedTask: () => Effect.void,
325 dispatch: (command) => {
326 commands.push(command);
327 if (command.type === "message.dispatch")
328 projection = { ...projection, messages: [{ id: command.messageId } as never] };
329 return Effect.succeed({} as never);
330 },
331 });
332 const layerEnabled = Layer.merge(
333 layerThreads,
334 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
335 );
336 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
337 Effect.provide(layerEnabled),
338 );
339 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
340 Effect.provide(layerEnabled),
341 );
342 assert.lengthOf(commands, 1);
343 assert.match(String(commands[0]!.commandId), /run:restart$/);
344 if (commands[0]!.type === "message.dispatch")
345 assert.equal(commands[0]!.restartContinuationOfRunId, runId);
346 projection = {
347 ...projection,
348 messages: [],
349 runs: [
350 ...projection.runs,
351 {
352 ...projection.runs[0]!,
353 id: RunId.make("run:user-newer"),
354 ordinal: 2,
355 status: "completed",
356 },
357 ],
358 };
359 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
360 Effect.provide(layerEnabled),
361 );
362 assert.lengthOf(commands, 1);
363 projection = { ...projection, runs: [projection.runs[0]!] };
364 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
365 Effect.provide(
366 Layer.merge(
367 layerThreads,
368 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: false }),
369 ),
370 ),
371 );
372 assert.lengthOf(commands, 1);
373 }),
374);
375
376it.effect("prepares no continuation for background work another provider thread launched", () =>
377 Effect.gen(function* () {
378 const base = makeProjection();
379 const claudeThreadId = ProviderThreadId.make("provider-thread:claude");
380 // A Claude turn left a background subagent open, then the thread switched
381 // to Codex and its turn settled. Recovery would cancel Claude's work.
382 const projection = {
383 ...base,
384 runs: [{ ...base.runs[0]!, status: "completed" }],
385 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
386 turnItems: [
387 {
388 id: "turn-item:claude-subagent",
389 runId: RunId.make("run:claude"),
390 providerThreadId: claudeThreadId,
391 type: "subagent",
392 status: "running",
393 },
394 ],
395 } as unknown as OrchestrationV2ThreadProjection;
396 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
397 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
398 Effect.provide(
399 Layer.mergeAll(
400 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
401 Layer.mock(ProjectionStore.ProjectionStoreV2)({
402 getRecoveryThreadIds: () => Effect.succeed([threadId]),
403 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
404 }),
405 Layer.mock(EventSink.EventSinkV2)({
406 writeWithEffects: (input) =>
407 Effect.sync(() => {
408 writes.push(input);
409 return [];
410 }),
411 }),
412 IdAllocator.layer,
413 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
414 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
415 ),
416 ),
417 );
418 yield* recovery.prepareForShutdown;
419 assert.lengthOf(writes, 0);
420 // Work on the settled run's own provider thread must not wake it either.
421 const ownWork = {
422 ...projection,
423 turnItems: [{ ...projection.turnItems[0]!, providerThreadId }],
424 } as OrchestrationV2ThreadProjection;
425 const ownRecovery = yield* ProviderRuntimeRecovery.make.pipe(
426 Effect.provide(
427 Layer.mergeAll(
428 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
429 Layer.mock(ProjectionStore.ProjectionStoreV2)({
430 getRecoveryThreadIds: () => Effect.succeed([threadId]),
431 getRuntimeRecoveryProjection: () => Effect.succeed(ownWork),
432 }),
433 Layer.mock(EventSink.EventSinkV2)({
434 writeWithEffects: (input) =>
435 Effect.sync(() => {
436 writes.push(input);
437 return [];
438 }),
439 }),
440 IdAllocator.layer,
441 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
442 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
443 ),
444 ),
445 );
446 yield* ownRecovery.prepareForShutdown;
447 assert.lengthOf(writes, 0);
448 }),
449);
450
451it.effect.each([
452 ["completed", scratchProjectId],
453 ["completed", ProjectId.make("restart-project")],
454 ["waiting", scratchProjectId],
455 ["waiting", ProjectId.make("restart-project")],
456] as const)(
457 "cleans up background work without waking a %s run in project %s",
458 ([status, projectId]) =>
459 Effect.gen(function* () {
460 const base = makeProjection();
461 const projection = {
462 ...base,
463 thread: { ...base.thread, projectId },
464 runs: [{ ...base.runs[0]!, status }],
465 providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
466 turnItems: [
467 {
468 id: "turn-item:background-subagent",
469 runId,
470 nodeId: null,
471 providerThreadId,
472 providerInstanceId: instanceId,
473 type: "subagent",
474 subagentId: "subagent:background",
475 title: "Background reviewer",
476 status: "running",
477 },
478 ],
479 subagents: [
480 {
481 id: "subagent:background",
482 runId,
483 driver,
484 providerInstanceId: instanceId,
485 status: "running",
486 },
487 ],
488 } as unknown as OrchestrationV2ThreadProjection;
489 for (const trigger of ["startup", "shutdown"] as const) {
490 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
491 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
492 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
493 Effect.provide(
494 Layer.mergeAll(
495 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
496 Layer.mock(ProjectionStore.ProjectionStoreV2)({
497 getRecoveryThreadIds: () => Effect.succeed([threadId]),
498 getRuntimeRecoveryProjection: () => Effect.succeed(projection),
499 }),
500 Layer.mock(EventSink.EventSinkV2)({
501 writeWithEffects: (input) =>
502 Effect.sync(() => {
503 writes.push(input);
504 return [];
505 }),
506 commitCommand: (input) =>
507 Effect.sync(() => {
508 commits.push(input);
509 return { committed: true, cancelledEffectCount: 0 } as never;
510 }),
511 }),
512 IdAllocator.layer,
513 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
514 runRecoveryOnce: Effect.succeed(false),
515 }),
516 Layer.mock(EffectOutbox.EffectOutboxV2)({
517 listByCommandId: () => Effect.succeed([]),
518 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
519 }),
520 ),
521 ),
522 );
523 if (trigger === "shutdown") yield* recovery.prepareForShutdown;
524 yield* recovery.reconcile(trigger);
525 assert.lengthOf(writes, 0);
526 assert.lengthOf(commits, 1);
527 assert.lengthOf(commits[0]!.effects, 0);
528 const events = commits[0]!.events;
529 for (const type of ["turn-item.updated", "subagent.updated"] as const)
530 assert.isTrue(
531 events.some((event) => event.type === type && event.payload.status === "cancelled"),
532 );
533 const note = events.find((event) => event.type === "run.background-work-cancelled");
534 assert.equal(note?.runId, runId);
535 assert.deepEqual(note?.payload.restartCancelledBackgroundWork, [
536 { kind: "subagent", label: "Background reviewer", id: "turn-item:background-subagent" },
537 ]);
538 if (status === "completed")
539 assert.isFalse(events.some((event) => event.type === "run.updated"));
540 }
541 }),
542);
543
544it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
545 Effect.gen(function* () {
546 let projection = makeProjection();
547 const commits: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0][] = [];
548 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
549 Effect.provide(
550 Layer.mergeAll(
551 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
552 Layer.mock(ProjectionStore.ProjectionStoreV2)({
553 getRecoveryThreadIds: () => Effect.succeed([threadId]),
554 getRuntimeRecoveryProjection: () => Effect.sync(() => projection),
555 }),
556 Layer.mock(EventSink.EventSinkV2)({
557 writeWithEffects: (input) =>
558 Effect.sync(() => {
559 assert.lengthOf(input.events, 0);
560 assert.equal(input.effects[0]?.request.type, "provider-runtime.continue");
561 projection = {
562 ...projection,
563 runs: [{ ...projection.runs[0]!, status: "completed" }],
564 };
565 return [];
566 }),
567 commitCommand: (input) =>
568 Effect.sync(() => {
569 commits.push(input);
570 return { committed: true, cancelledEffectCount: 0 } as never;
571 }),
572 }),
573 IdAllocator.layer,
574 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({
575 runRecoveryOnce: Effect.succeed(false),
576 }),
577 Layer.mock(EffectOutbox.EffectOutboxV2)({
578 reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
579 }),
580 ),
581 ),
582 );
583 yield* recovery.prepareForShutdown;
584 yield* recovery.reconcile("shutdown");
585 assert.isFalse(
586 commits.some((commit) => commit.events.some((event) => event.type === "run.updated")),
587 );
588 let dispatched = false;
589 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
590 Effect.provide(
591 Layer.mergeAll(
592 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
593 Layer.mock(ThreadManagementService.ThreadManagementService)({
594 getThreadRecords: () => Effect.succeed(projection),
595 recoverDelegatedTask: () => Effect.void,
596 dispatch: () =>
597 Effect.sync(() => {
598 dispatched = true;
599 return {} as never;
600 }),
601 }),
602 ),
603 ),
604 );
605 assert.isFalse(dispatched);
606 }),
607);
608
609const continuationTexts = (projection: OrchestrationV2ThreadProjection) =>
610 Effect.gen(function* () {
611 const texts: Array<string> = [];
612 yield* continueRestartedRun({ threadId, sourceRunId: runId }).pipe(
613 Effect.provide(
614 Layer.merge(
615 Layer.mock(ThreadManagementService.ThreadManagementService)({
616 getThreadRecords: () => Effect.succeed(projection),
617 recoverDelegatedTask: () => Effect.void,
618 dispatch: (command) => {
619 if (command.type === "message.dispatch") texts.push(command.text);
620 return Effect.succeed({} as never);
621 },
622 }),
623 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
624 ),
625 ),
626 );
627 return texts;
628 });
629
630const cutMidTurn = (extra: Record<string, unknown> = {}) => {
631 const base = makeProjection();
632 return {
633 ...base,
634 runs: [
635 {
636 ...base.runs[0]!,
637 status: "cancelled",
638 userMessageId: MessageId.make("message:user"),
639 ...extra,
640 },
641 ],
642 providerTurns: [{ ...base.providerTurns[0]!, status: "cancelled" }],
643 } as unknown as OrchestrationV2ThreadProjection;
644};
645
646const queuedFollowUp = {
647 id: RunId.make("run:queued"),
648 ordinal: 2,
649 providerInstanceId: instanceId,
650 providerThreadId,
651 status: "queued",
652 queueHeld: true,
653};
654
655it.effect("continues a cut run past queued follow-ups, which stay held", () =>
656 Effect.gen(function* () {
657 const live = makeProjection();
658 assert.equal(
659 restartContinuationRun({
660 ...live,
661 runs: [...live.runs, queuedFollowUp],
662 } as unknown as OrchestrationV2ThreadProjection)?.id,
663 runId,
664 );
665 const cut = cutMidTurn();
666 const texts = yield* continuationTexts({
667 ...cut,
668 runs: [...cut.runs, queuedFollowUp],
669 } as unknown as OrchestrationV2ThreadProjection);
670 assert.deepEqual(texts, ["Continue where you left off."]);
671 }),
672);
673
674it.effect("continues a resumed queued run that ran after an earlier continuation", () =>
675 Effect.gen(function* () {
676 // The continuation (ordinal 3) ran ahead of the held queue, then the user
677 // resumed the queued run (ordinal 1 here) and the server restarted again.
678 const finishedContinuation = {
679 id: RunId.make("run:earlier-continuation"),
680 ordinal: 3,
681 providerInstanceId: instanceId,
682 providerThreadId,
683 status: "completed",
684 completedAt: DateTime.makeUnsafe("2026-10-03T10:00:00.000Z"),
685 };
686 const live = makeProjection();
687 assert.equal(
688 restartContinuationRun({
689 ...live,
690 runs: [...live.runs, finishedContinuation],
691 } as unknown as OrchestrationV2ThreadProjection)?.id,
692 runId,
693 );
694 const cut = cutMidTurn({ completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00.000Z") });
695 const texts = yield* continuationTexts({
696 ...cut,
697 runs: [...cut.runs, finishedContinuation],
698 } as unknown as OrchestrationV2ThreadProjection);
699 assert.deepEqual(texts, ["Continue where you left off."]);
700 }),
701);
702
703it.effect("does not continue a run the user asked to stop before the restart", () =>
704 Effect.gen(function* () {
705 const texts = yield* continuationTexts({
706 ...cutMidTurn(),
707 turnItems: [{ id: "turn-item:interrupt", runId, type: "run_interrupt_request" }],
708 } as unknown as OrchestrationV2ThreadProjection);
709 assert.deepEqual(texts, []);
710 }),
711);
712
713it.effect("does not continue a cut /compact or /logout turn", () =>
714 Effect.gen(function* () {
715 for (const text of ["/compact", " /LOGOUT "]) {
716 const texts = yield* continuationTexts({
717 ...cutMidTurn(),
718 messages: [{ id: MessageId.make("message:user"), text, attachments: [] }],
719 } as unknown as OrchestrationV2ThreadProjection);
720 assert.deepEqual(texts, [], text);
721 }
722 const texts = yield* continuationTexts({
723 ...cutMidTurn(),
724 messages: [{ id: MessageId.make("message:user"), text: "/compact later", attachments: [] }],
725 } as unknown as OrchestrationV2ThreadProjection);
726 assert.lengthOf(texts, 1);
727 }),
728);
729
730it.effect("tells a turn cut mid-way about the background work it lost", () =>
731 Effect.gen(function* () {
732 const texts = yield* continuationTexts(
733 cutMidTurn({
734 restartCancelledBackgroundWork: [{ kind: "subagent", label: "Background reviewer" }],
735 }),
736 );
737 assert.lengthOf(texts, 1);
738 assert.include(texts[0]!, "Background reviewer");
739 assert.isTrue(texts[0]!.endsWith("Continue where you left off."));
740 }),
741);
742
743it.effect(
744 "carries the note forward when its continuation was cut before reaching the provider",
745 () =>
746 Effect.gen(function* () {
747 const base = makeProjection();
748 const original = {
749 ...base.runs[0]!,
750 id: RunId.make("run:original"),
751 status: "completed",
752 activeAttemptId: RunAttemptId.make("attempt:original"),
753 restartCancelledBackgroundWork: [{ kind: "shell", label: "sleep 25 && echo DONE" }],
754 };
755 const projection = {
756 ...base,
757 runs: [
758 original,
759 {
760 ...base.runs[0]!,
761 ordinal: 2,
762 status: "cancelled",
763 restartContinuationOfRunId: original.id,
764 },
765 ],
766 // The original turn settled; the continuation's attempt never started one.
767 providerTurns: [
768 {
769 ...base.providerTurns[0]!,
770 runAttemptId: original.activeAttemptId,
771 status: "completed",
772 },
773 ],
774 } as unknown as OrchestrationV2ThreadProjection;
775 const texts = yield* continuationTexts(projection);
776 assert.lengthOf(texts, 1);
777 assert.include(texts[0]!, "sleep 25 && echo DONE");
778 assert.notInclude(texts[0]!, "Continue where");
779 }),
780);
781
782it.effect("prepares later threads' continuations when one thread fails", () =>
783 Effect.gen(function* () {
784 const brokenThreadId = ThreadId.make("thread:broken");
785 const writes: Parameters<EventSink.EventSinkV2["Service"]["writeWithEffects"]>[0][] = [];
786 const recovery = yield* ProviderRuntimeRecovery.make.pipe(
787 Effect.provide(
788 Layer.mergeAll(
789 ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
790 Layer.mock(ProjectionStore.ProjectionStoreV2)({
791 getRecoveryThreadIds: () => Effect.succeed([brokenThreadId, threadId]),
792 getRuntimeRecoveryProjection: (id) =>
793 id === brokenThreadId
794 ? Effect.fail(
795 new ProjectionStore.ProjectionStoreThreadNotFoundError({ threadId: id }),
796 )
797 : Effect.succeed(makeProjection()),
798 }),
799 Layer.mock(EventSink.EventSinkV2)({
800 writeWithEffects: (input) =>
801 Effect.sync(() => {
802 writes.push(input);
803 return [];
804 }),
805 }),
806 IdAllocator.layer,
807 Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
808 Layer.mock(EffectOutbox.EffectOutboxV2)({}),
809 ),
810 ),
811 );
812 yield* recovery.prepareForShutdown;
813 assert.deepEqual(
814 writes.map((write) => write.effects[0]?.request),
815 [{ type: "provider-runtime.continue", sourceRunId: runId }],
816 );
817 }),
818);