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