The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,969 lines 70.9 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
3 CheckpointId,
4 CheckpointRef,
5 CheckpointScopeId,
6 CommandId,
7 EventId,
8 MessageId,
9 NodeId,
10 ProjectId,
11 ProviderDriverKind,
12 ProviderInstanceId,
13 ProviderSessionId,
14 ProviderThreadId,
15 ProviderTurnId,
16 RunAttemptId,
17 RunId,
18 ScheduledTaskId,
19 ThreadId,
20 TurnItemId,
21 } from "@t3tools/contracts";
22 import * as DateTime from "effect/DateTime";
23 import * as Deferred from "effect/Deferred";
24 import * as Effect from "effect/Effect";
25 import * as Statement from "effect/sql/Statement";
26 import * as Stream from "effect/Stream";
27 import * as TestClock from "effect/testing/TestClock";
28
29 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
30 import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
31 import * as EffectWorker from "./EffectWorker.ts";
32 import * as EventSink from "./EventSink.ts";
33 import * as Orchestrator from "./Orchestrator.ts";
34 import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
35 import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
36 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
37
38 const forkCases = (
39 [
40 ["codex", "interrupted"],
41 ["claudeAgent", "failed"],
42 ] as const
43 ).map(([driverName, status]) => {
44 const driver = ProviderDriverKind.make(driverName);
45 const instanceId = ProviderInstanceId.make(driver);
46 const modelSelection = { instanceId, model: "test-model" };
47 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
48 instanceId,
49 driver,
50 getCapabilities: () =>
51 Effect.succeed(
52 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
53 ),
54 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
55 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
56 };
57 const layer = ProviderReplayHarness.layerWithRegistry(
58 { name: `fork-boundary-${driver}` },
59 ProviderAdapterRegistry.layerFromAdapters([adapter]),
60 { runEffectWorker: false },
61 );
62
63 return { driver, status, instanceId, modelSelection, layer };
64 });
65
66 it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
67 Effect.gen(function* () {
68 const orchestrator = yield* Orchestrator.OrchestratorV2;
69 const eventSink = yield* EventSink.EventSinkV2;
70 const now = yield* DateTime.now;
71 const { instanceId, modelSelection } = forkCases[0]!;
72 const sourceThreadId = ThreadId.make("fork-watch-source");
73 const targetThreadId = ThreadId.make("fork-watch-target");
74 const sourceRunId = RunId.make("fork-watch-source-run");
75 const key = { host: "github.com", repository: "example/repo", number: 1 };
76 const link = { url: "https://github.com/example/repo/pull/1", source: "agent" as const };
77
78 yield* orchestrator.dispatch({
79 type: "thread.create",
80 commandId: CommandId.make("fork-watch-create"),
81 threadId: sourceThreadId,
82 projectId: ProjectId.make("fork-watch-project"),
83 title: "Watching source",
84 modelSelection,
85 runtimeMode: "full-access",
86 interactionMode: "default",
87 branch: null,
88 worktreePath: null,
89 createdBy: "user",
90 creationSource: "web",
91 });
92 yield* eventSink.write({
93 events: [
94 {
95 id: EventId.make("fork-watch-source-run"),
96 type: "run.created",
97 threadId: sourceThreadId,
98 runId: sourceRunId,
99 occurredAt: now,
100 payload: {
101 id: sourceRunId,
102 threadId: sourceThreadId,
103 ordinal: 1,
104 providerInstanceId: instanceId,
105 modelSelection,
106 providerThreadId: null,
107 userMessageId: MessageId.make("fork-watch-source-message"),
108 rootNodeId: null,
109 activeAttemptId: null,
110 status: "completed",
111 requestedAt: now,
112 startedAt: now,
113 completedAt: now,
114 checkpointId: null,
115 contextHandoffId: null,
116 },
117 },
118 ],
119 });
120 yield* orchestrator.dispatch({
121 type: "thread.pull-request.watch",
122 commandId: CommandId.make("fork-watch-parent-start"),
123 threadId: sourceThreadId,
124 ...key,
125 watching: true,
126 link,
127 });
128 const parentBefore = yield* orchestrator.getThreadShell(sourceThreadId);
129 const parentWatch = parentBefore?.pullRequests?.[0]?.watch;
130 assert.isDefined(parentWatch);
131 assert.lengthOf(parentBefore?.pendingBackgroundTasks ?? [], 1);
132
133 yield* orchestrator.dispatch({
134 type: "thread.fork",
135 commandId: CommandId.make("fork-watch-fork"),
136 sourceThreadId,
137 targetThreadId,
138 sourcePoint: { type: "run", runId: sourceRunId },
139 createdBy: "user",
140 creationSource: "mcp",
141 });
142 const fork = yield* orchestrator.getThreadShell(targetThreadId);
143 assert.isNotNull(fork);
144 assert.deepEqual(fork.pullRequests, [
145 {
146 ...key,
147 ...link,
148 linkedAt: parentWatch.startedAt,
149 snapshot: null,
150 stack: null,
151 },
152 ]);
153 assert.deepEqual(fork.pendingBackgroundTasks, []);
154 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
155
156 const stale = yield* orchestrator
157 .dispatch({
158 type: "thread.pull-request-watch.sync",
159 commandId: CommandId.make("fork-watch-stale-sync"),
160 threadId: targetThreadId,
161 ...key,
162 startedAt: parentWatch.startedAt,
163 watch: parentWatch,
164 wake: {
165 messageId: MessageId.make("fork-watch-unwanted-wake"),
166 text: "A check failed",
167 notification: {
168 source: { kind: "monitor" },
169 outcome: "updated",
170 summary: "A check failed",
171 },
172 },
173 })
174 .pipe(Effect.flip);
175 assert.equal(stale._tag, "OrchestratorDispatchError");
176 assert.deepEqual((yield* orchestrator.getThreadProjection(targetThreadId)).runs, []);
177
178 yield* TestClock.adjust("1 second");
179 yield* orchestrator.dispatch({
180 type: "thread.pull-request.watch",
181 commandId: CommandId.make("fork-watch-opt-in"),
182 threadId: targetThreadId,
183 ...key,
184 watching: true,
185 link,
186 });
187 const watchingFork = yield* orchestrator.getThreadShell(targetThreadId);
188 assert.isDefined(watchingFork?.pullRequests?.[0]?.watch);
189 assert.notEqual(watchingFork.pullRequests[0].watch.startedAt, parentWatch.startedAt);
190 assert.lengthOf(watchingFork.pendingBackgroundTasks ?? [], 1);
191 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
192
193 yield* orchestrator.dispatch({
194 type: "thread.pull-request.watch",
195 commandId: CommandId.make("fork-watch-opt-out"),
196 threadId: targetThreadId,
197 ...key,
198 watching: false,
199 });
200 const stoppedFork = yield* orchestrator.getThreadShell(targetThreadId);
201 const [forkLink] = fork.pullRequests ?? [];
202 assert.isDefined(forkLink);
203 assert.deepEqual(stoppedFork?.pullRequests, [
204 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
205 ]);
206 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
207 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
208 }).pipe(Effect.provide(forkCases[0]!.layer)),
209 );
210
211 it.effect.each(forkCases)(
212 "bounds $driver context when continuing a fork of a $status run",
213 ({ driver, status, instanceId, modelSelection, layer }) =>
214 Effect.gen(function* () {
215 const orchestrator = yield* Orchestrator.OrchestratorV2;
216 const eventSink = yield* EventSink.EventSinkV2;
217 const now = yield* DateTime.now;
218 const sourceThreadId = ThreadId.make("fork-boundary-source");
219 const targetThreadId = ThreadId.make("fork-boundary-target");
220 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
221 const sourceRunId = RunId.make("fork-boundary-source-run");
222 const attemptId = RunAttemptId.make("interrupted-source-attempt");
223 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
224 const rootNodeId = NodeId.make("interrupted-source-root");
225 const grandparentThreadId = ThreadId.make("fork-boundary-grandparent");
226 const grandparentRunId = RunId.make("fork-boundary-grandparent-run");
227
228 yield* orchestrator.dispatch({
229 type: "thread.create",
230 commandId: CommandId.make("create-grandparent"),
231 threadId: grandparentThreadId,
232 projectId: ProjectId.make("fork-boundary-project"),
233 title: "Fork boundary grandparent",
234 modelSelection,
235 runtimeMode: "full-access",
236 interactionMode: "default",
237 branch: null,
238 worktreePath: null,
239 createdBy: "user",
240 creationSource: "web",
241 });
242 yield* writeParentRun({
243 threadId: grandparentThreadId,
244 runId: RunId.make("fork-boundary-grandparent-rolled-back-run"),
245 ordinal: 1,
246 status: "rolled_back",
247 text: "ROLLED_BACK_MARKER",
248 });
249 yield* writeParentRun({
250 threadId: grandparentThreadId,
251 runId: grandparentRunId,
252 ordinal: 2,
253 status: "completed",
254 text: "GRANDPARENT_MARKER",
255 });
256 yield* orchestrator.dispatch({
257 type: "thread.fork",
258 commandId: CommandId.make("fork-grandparent"),
259 sourceThreadId: grandparentThreadId,
260 targetThreadId: sourceThreadId,
261 sourcePoint: { type: "run", runId: grandparentRunId },
262 createdBy: "user",
263 creationSource: "web",
264 });
265 yield* eventSink.write({
266 events: [
267 {
268 id: EventId.make("source-provider-thread"),
269 type: "provider-thread.updated",
270 threadId: sourceThreadId,
271 occurredAt: now,
272 payload: {
273 id: providerThreadId,
274 driver,
275 providerInstanceId: instanceId,
276 providerSessionId: null,
277 appThreadId: sourceThreadId,
278 ownerNodeId: null,
279 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
280 nativeConversationHeadRef: null,
281 status: "idle",
282 firstRunOrdinal: 2,
283 lastRunOrdinal: 3,
284 handoffIds: [],
285 forkedFrom: null,
286 createdAt: now,
287 updatedAt: now,
288 },
289 },
290 ],
291 });
292 if (status === "interrupted") {
293 yield* eventSink.write({
294 events: [
295 {
296 id: EventId.make("source-attempt"),
297 type: "run-attempt.created",
298 threadId: sourceThreadId,
299 runId: sourceRunId,
300 occurredAt: now,
301 payload: {
302 id: attemptId,
303 runId: sourceRunId,
304 attemptOrdinal: 1,
305 rootNodeId,
306 providerInstanceId: instanceId,
307 providerThreadId,
308 providerTurnId,
309 reason: "initial",
310 status,
311 startedAt: now,
312 completedAt: now,
313 },
314 },
315 {
316 id: EventId.make("source-provider-turn"),
317 type: "provider-turn.updated",
318 threadId: sourceThreadId,
319 occurredAt: now,
320 payload: {
321 id: providerTurnId,
322 providerThreadId,
323 nodeId: rootNodeId,
324 runAttemptId: attemptId,
325 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
326 ordinal: 1,
327 status,
328 startedAt: now,
329 completedAt: now,
330 },
331 },
332 ],
333 });
334 }
335 yield* writeParentRun({
336 threadId: sourceThreadId,
337 runId: RunId.make("fork-boundary-source-rolled-back-run"),
338 ordinal: 1,
339 status: "rolled_back",
340 text: "SOURCE_ROLLED_BACK_MARKER",
341 });
342 for (const ordinal of [2, 3]) {
343 const runId = ordinal === 2 ? sourceRunId : RunId.make("later-run");
344 const messageId = MessageId.make(`source-message-${ordinal}`);
345 yield* eventSink.write({
346 events: [
347 {
348 id: EventId.make(`run-${ordinal}`),
349 type: "run.created",
350 threadId: sourceThreadId,
351 runId,
352 occurredAt: now,
353 payload: {
354 id: runId,
355 threadId: sourceThreadId,
356 ordinal,
357 providerInstanceId: instanceId,
358 modelSelection,
359 providerThreadId,
360 userMessageId: messageId,
361 rootNodeId: null,
362 activeAttemptId: ordinal === 2 && status === "interrupted" ? attemptId : null,
363 status: ordinal === 2 ? status : "completed",
364 queuePosition: null,
365 requestedAt: now,
366 startedAt: now,
367 completedAt: now,
368 checkpointId: null,
369 contextHandoffId: null,
370 },
371 },
372 {
373 id: EventId.make(`item-${ordinal}`),
374 type: "turn-item.updated",
375 threadId: sourceThreadId,
376 runId,
377 occurredAt: now,
378 payload: {
379 id: TurnItemId.make(`item-${ordinal}`),
380 threadId: sourceThreadId,
381 runId,
382 nodeId: null,
383 providerThreadId,
384 providerTurnId: null,
385 nativeItemRef: null,
386 parentItemId: null,
387 ordinal,
388 status: "completed",
389 title: null,
390 startedAt: now,
391 completedAt: now,
392 updatedAt: now,
393 type: "user_message",
394 createdBy: "user",
395 creationSource: "web",
396 inputIntent: "turn_start",
397 messageId,
398 text: ordinal === 2 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
399 attachments: [],
400 },
401 },
402 ],
403 });
404 }
405 yield* orchestrator.dispatch({
406 type: "thread.fork",
407 commandId: CommandId.make("fork-source"),
408 sourceThreadId,
409 targetThreadId,
410 sourcePoint: { type: "run", runId: sourceRunId },
411 createdBy: "user",
412 creationSource: "web",
413 });
414 yield* orchestrator.dispatch({
415 type: "message.dispatch",
416 commandId: CommandId.make("continue-fork"),
417 threadId: targetThreadId,
418 messageId: MessageId.make("continue-fork"),
419 text: "Continue from the selected source run",
420 attachments: [],
421 modelSelection,
422 dispatchMode: { type: "start_immediately" },
423 createdBy: "user",
424 creationSource: "web",
425 });
426 const target = yield* orchestrator.getThreadProjection(targetThreadId);
427 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
428 assert.lengthOf(target.contextHandoffs, 1);
429 const handoff = target.contextHandoffs[0]!;
430 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
431 assert.include(`${handoff.summaryText}\n${history}`, "GRANDPARENT_MARKER");
432 assert.notInclude(`${handoff.summaryText}\n${history}`, "SOURCE_ROLLED_BACK_MARKER");
433 assert.notInclude(`${handoff.summaryText}\n${history}`, "ROLLED_BACK_MARKER");
434 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
435 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
436 assert.isNull(target.providerThreads[0]?.forkedFrom);
437 }).pipe(Effect.provide(layer)),
438 );
439
440 it.effect.each([
441 { execution: "portable_context", rejected: true },
442 { execution: "native_fork", rejected: false },
443 ] as const)(
444 "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
445 ({ execution, rejected }) => {
446 const opened: Array<ProviderInstanceId> = [];
447 const adapter = (driverName: "claudeAgent" | "codex") => {
448 const driver = ProviderDriverKind.make(driverName);
449 const instanceId = ProviderInstanceId.make(driverName);
450 return {
451 instanceId,
452 driver,
453 getCapabilities: () =>
454 Effect.succeed(
455 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
456 ),
457 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
458 openSession: (input) =>
459 Effect.sync(() => opened.push(instanceId)).pipe(
460 Effect.andThen(
461 new ProviderAdapter.ProviderAdapterOpenSessionError({
462 driver,
463 providerSessionId: input.providerSessionId,
464 }),
465 ),
466 ),
467 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
468 };
469 const claude = adapter("claudeAgent");
470 const target = execution === "portable_context" ? adapter("codex") : claude;
471 return Effect.gen(function* () {
472 const orchestrator = yield* Orchestrator.OrchestratorV2;
473 const eventSink = yield* EventSink.EventSinkV2;
474 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
475 const now = yield* DateTime.now;
476 const sourceThreadId = ThreadId.make("fork-compact-source");
477 const targetThreadId = ThreadId.make("fork-compact-target");
478 const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
479 const sourceRunId = RunId.make("fork-compact-source-run");
480 const userMessageId = MessageId.make("fork-compact-source-message");
481 const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
482
483 yield* orchestrator.dispatch({
484 type: "thread.create",
485 commandId: CommandId.make("fork-compact-create-source"),
486 threadId: sourceThreadId,
487 projectId: ProjectId.make("fork-compact-project"),
488 title: "Fork compact source",
489 modelSelection: sourceSelection,
490 runtimeMode: "full-access",
491 interactionMode: "default",
492 branch: null,
493 worktreePath: null,
494 createdBy: "user",
495 creationSource: "web",
496 });
497 const item = {
498 threadId: sourceThreadId,
499 runId: sourceRunId,
500 nodeId: null,
501 providerThreadId,
502 providerTurnId: null,
503 nativeItemRef: null,
504 parentItemId: null,
505 status: "completed",
506 title: null,
507 startedAt: now,
508 completedAt: now,
509 updatedAt: now,
510 } as const;
511 yield* eventSink.write({
512 events: [
513 {
514 id: EventId.make("fork-compact-provider-thread"),
515 type: "provider-thread.updated",
516 threadId: sourceThreadId,
517 occurredAt: now,
518 payload: {
519 id: providerThreadId,
520 driver: claude.driver,
521 providerInstanceId: claude.instanceId,
522 providerSessionId: null,
523 appThreadId: sourceThreadId,
524 ownerNodeId: null,
525 nativeThreadRef: {
526 driver: claude.driver,
527 nativeId: "native-fork-compact-source",
528 strength: "strong",
529 },
530 nativeConversationHeadRef: null,
531 status: "idle",
532 firstRunOrdinal: 1,
533 lastRunOrdinal: 1,
534 handoffIds: [],
535 forkedFrom: null,
536 createdAt: now,
537 updatedAt: now,
538 },
539 },
540 {
541 id: EventId.make("fork-compact-source-run"),
542 type: "run.created",
543 threadId: sourceThreadId,
544 runId: sourceRunId,
545 occurredAt: now,
546 payload: {
547 id: sourceRunId,
548 threadId: sourceThreadId,
549 ordinal: 1,
550 providerInstanceId: claude.instanceId,
551 modelSelection: sourceSelection,
552 providerThreadId,
553 userMessageId,
554 rootNodeId: null,
555 activeAttemptId: null,
556 status: "completed",
557 queuePosition: null,
558 requestedAt: now,
559 startedAt: now,
560 completedAt: now,
561 checkpointId: null,
562 contextHandoffId: null,
563 },
564 },
565 // Each message alone exceeds the default 16k handoff budget, so a
566 // portable handoff omits both whole items.
567 {
568 id: EventId.make("fork-compact-user-item"),
569 type: "turn-item.updated",
570 threadId: sourceThreadId,
571 runId: sourceRunId,
572 occurredAt: now,
573 payload: {
574 ...item,
575 id: TurnItemId.make("fork-compact-user-item"),
576 ordinal: 1,
577 type: "user_message",
578 createdBy: "user",
579 creationSource: "web",
580 inputIntent: "turn_start",
581 messageId: userMessageId,
582 text: "u".repeat(17_000),
583 attachments: [],
584 },
585 },
586 {
587 id: EventId.make("fork-compact-assistant-item"),
588 type: "turn-item.updated",
589 threadId: sourceThreadId,
590 runId: sourceRunId,
591 occurredAt: now,
592 payload: {
593 ...item,
594 id: TurnItemId.make("fork-compact-assistant-item"),
595 ordinal: 2,
596 type: "assistant_message",
597 messageId: MessageId.make("fork-compact-assistant-message"),
598 text: "a".repeat(17_000),
599 streaming: false,
600 },
601 },
602 ],
603 });
604 yield* orchestrator.dispatch({
605 type: "thread.fork",
606 commandId: CommandId.make("fork-compact-fork"),
607 sourceThreadId,
608 targetThreadId,
609 sourcePoint: { type: "run", runId: sourceRunId },
610 createdBy: "user",
611 creationSource: "web",
612 });
613 yield* orchestrator.dispatch({
614 type: "message.dispatch",
615 commandId: CommandId.make("fork-compact-compact"),
616 threadId: targetThreadId,
617 messageId: MessageId.make("fork-compact-compact"),
618 text: "/compact",
619 attachments: [],
620 modelSelection: { instanceId: target.instanceId, model: "test-model" },
621 dispatchMode: { type: "start_immediately" },
622 createdBy: "user",
623 creationSource: "web",
624 });
625 yield* worker.drain();
626
627 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
628 if (execution === "portable_context") {
629 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
630 assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
631 } else {
632 assert.isEmpty(projection.contextHandoffs);
633 }
634 const emptyCompaction = projection.turnItems.some(
635 (turnItem) =>
636 turnItem.type === "error" &&
637 turnItem.failure.message === "Start a conversation before compacting this thread.",
638 );
639 assert.equal(emptyCompaction, rejected);
640 assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
641 }).pipe(
642 Effect.provide(
643 ProviderReplayHarness.layerWithRegistry(
644 { name: `fork-compact-${execution}` },
645 ProviderAdapterRegistry.layerFromAdapters(
646 target === claude ? [claude] : [claude, target],
647 ),
648 ),
649 ),
650 );
651 },
652 );
653
654 const writeParentRun = (input: {
655 readonly threadId: ThreadId;
656 readonly runId: RunId;
657 readonly ordinal: number;
658 /** Preparing, failed, and interrupted runs asked for a new worktree. */
659 readonly status:
660 | "preparing"
661 | "running"
662 | "queued"
663 | "completed"
664 | "rolled_back"
665 | "failed"
666 | "interrupted";
667 readonly text: string;
668 /** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */
669 readonly stable?: boolean;
670 }) =>
671 Effect.gen(function* () {
672 const eventSink = yield* EventSink.EventSinkV2;
673 const now = yield* DateTime.now;
674 const { driver, instanceId, modelSelection } = forkCases[0]!;
675 const messageId = MessageId.make(`${input.runId}:message`);
676 const providerThreadId = input.stable
677 ? ProviderThreadId.make(`${input.runId}:provider-thread`)
678 : null;
679 yield* eventSink.write({
680 events: [
681 ...(providerThreadId === null
682 ? []
683 : [
684 {
685 id: EventId.make(`${input.runId}:provider-thread`),
686 type: "provider-thread.updated" as const,
687 threadId: input.threadId,
688 occurredAt: now,
689 payload: {
690 id: providerThreadId,
691 driver,
692 providerInstanceId: instanceId,
693 providerSessionId: null,
694 appThreadId: input.threadId,
695 ownerNodeId: null,
696 nativeThreadRef: {
697 driver,
698 nativeId: `${input.runId}:native`,
699 strength: "strong" as const,
700 },
701 nativeConversationHeadRef: null,
702 status: "idle" as const,
703 firstRunOrdinal: input.ordinal,
704 lastRunOrdinal: input.ordinal,
705 handoffIds: [],
706 forkedFrom: null,
707 createdAt: now,
708 updatedAt: now,
709 },
710 },
711 ]),
712 {
713 id: EventId.make(`${input.runId}:created`),
714 type: "run.created",
715 threadId: input.threadId,
716 runId: input.runId,
717 occurredAt: now,
718 payload: {
719 id: input.runId,
720 threadId: input.threadId,
721 ordinal: input.ordinal,
722 providerInstanceId: instanceId,
723 modelSelection,
724 providerThreadId,
725 userMessageId: messageId,
726 rootNodeId: null,
727 activeAttemptId: null,
728 status: input.status,
729 queuePosition: null,
730 requestedAt: now,
731 startedAt: now,
732 completedAt:
733 input.status === "preparing" ||
734 input.status === "running" ||
735 input.status === "queued"
736 ? null
737 : now,
738 checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
739 contextHandoffId: null,
740 ...(input.status === "preparing" ||
741 input.status === "failed" ||
742 input.status === "interrupted"
743 ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }
744 : {}),
745 },
746 },
747 {
748 id: EventId.make(`${input.runId}:item`),
749 type: "turn-item.updated",
750 threadId: input.threadId,
751 runId: input.runId,
752 occurredAt: now,
753 payload: {
754 id: TurnItemId.make(`${input.runId}:item`),
755 threadId: input.threadId,
756 runId: input.runId,
757 nodeId: null,
758 providerThreadId,
759 providerTurnId: null,
760 nativeItemRef: null,
761 parentItemId: null,
762 ordinal: input.ordinal * 100,
763 status: "completed",
764 title: null,
765 startedAt: now,
766 completedAt: now,
767 updatedAt: now,
768 type: "user_message",
769 createdBy: "user",
770 creationSource: "web",
771 inputIntent: "turn_start",
772 messageId,
773 text: input.text,
774 attachments: [],
775 },
776 },
777 ],
778 });
779 });
780
781 /** Marks `threadId` as imported from V1 and gives it one runless imported user message. */
782 const writeImportedHistory = (threadId: ThreadId, text: string) =>
783 Effect.gen(function* () {
784 const orchestrator = yield* Orchestrator.OrchestratorV2;
785 const eventSink = yield* EventSink.EventSinkV2;
786 const now = yield* DateTime.now;
787 const { thread } = yield* orchestrator.getThreadProjection(threadId);
788 yield* eventSink.write({
789 events: [
790 {
791 id: EventId.make(`${threadId}:imported`),
792 type: "thread.metadata-updated",
793 threadId,
794 occurredAt: now,
795 payload: { ...thread, historyOrigin: "v1_import" },
796 },
797 {
798 id: EventId.make(`${threadId}:imported-item`),
799 type: "turn-item.updated",
800 threadId,
801 occurredAt: now,
802 payload: {
803 id: TurnItemId.make(`${threadId}:imported-item`),
804 threadId,
805 runId: null,
806 nodeId: null,
807 providerThreadId: null,
808 providerTurnId: null,
809 nativeItemRef: null,
810 parentItemId: null,
811 ordinal: 1,
812 status: "completed",
813 title: null,
814 startedAt: now,
815 completedAt: now,
816 updatedAt: now,
817 type: "user_message",
818 createdBy: "user",
819 creationSource: "web",
820 inputIntent: "turn_start",
821 messageId: MessageId.make(`${threadId}:imported-message`),
822 text,
823 attachments: [],
824 },
825 },
826 ],
827 });
828 });
829
830 const createParent = (threadId: ThreadId) =>
831 Effect.gen(function* () {
832 const orchestrator = yield* Orchestrator.OrchestratorV2;
833 yield* orchestrator.dispatch({
834 type: "thread.create",
835 commandId: CommandId.make(`${threadId}:create`),
836 threadId,
837 projectId: ProjectId.make("side-chat-project"),
838 title: "Side chat parent",
839 modelSelection: forkCases[0]!.modelSelection,
840 runtimeMode: "full-access",
841 interactionMode: "default",
842 branch: null,
843 worktreePath: null,
844 createdBy: "user",
845 creationSource: "web",
846 });
847 });
848
849 const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
850 Effect.gen(function* () {
851 const orchestrator = yield* Orchestrator.OrchestratorV2;
852 return yield* orchestrator.dispatch({
853 type: "thread.fork",
854 commandId: CommandId.make(commandId),
855 sourceThreadId,
856 targetThreadId,
857 sourcePoint: { type: "latest_stable" },
858 sideChat: true,
859 createdBy: "user",
860 creationSource: "web",
861 });
862 });
863
864 const askSideChat = (
865 threadId: ThreadId,
866 commandId: string,
867 modelSelection?: (typeof forkCases)[number]["modelSelection"],
868 ) =>
869 Effect.gen(function* () {
870 const orchestrator = yield* Orchestrator.OrchestratorV2;
871 yield* orchestrator.dispatch({
872 type: "message.dispatch",
873 commandId: CommandId.make(commandId),
874 threadId,
875 messageId: MessageId.make(commandId),
876 text: "What is the main thread doing?",
877 attachments: [],
878 ...(modelSelection === undefined ? {} : { modelSelection }),
879 dispatchMode: { type: "start_immediately" },
880 createdBy: "user",
881 creationSource: "web",
882 });
883 });
884
885 it.effect("resolves an explicit checkpoint fork to its source run", () =>
886 Effect.gen(function* () {
887 const orchestrator = yield* Orchestrator.OrchestratorV2;
888 const eventSink = yield* EventSink.EventSinkV2;
889 const now = yield* DateTime.now;
890 const parentId = ThreadId.make("checkpoint-fork-parent");
891 const childId = ThreadId.make("checkpoint-fork-child");
892 const runId = RunId.make("checkpoint-fork-run");
893 const checkpointId = CheckpointId.make("checkpoint-fork-checkpoint");
894 yield* createParent(parentId);
895 yield* writeParentRun({
896 threadId: parentId,
897 runId,
898 ordinal: 1,
899 status: "completed",
900 text: "Work",
901 });
902 yield* eventSink.write({
903 events: [
904 {
905 id: EventId.make("checkpoint-fork-captured"),
906 type: "checkpoint.captured",
907 threadId: parentId,
908 occurredAt: now,
909 payload: {
910 id: checkpointId,
911 threadId: parentId,
912 scopeId: CheckpointScopeId.make("checkpoint-fork-scope"),
913 runId,
914 nodeId: NodeId.make("checkpoint-fork-node"),
915 parentCheckpointId: null,
916 ordinalWithinScope: 1,
917 appRunOrdinal: 1,
918 ref: CheckpointRef.make("refs/t3/checkpoint-fork/1"),
919 status: "ready",
920 files: [],
921 capturedAt: now,
922 },
923 },
924 ],
925 });
926 yield* orchestrator.dispatch({
927 type: "thread.fork",
928 commandId: CommandId.make("checkpoint-fork"),
929 sourceThreadId: parentId,
930 targetThreadId: childId,
931 sourcePoint: { type: "checkpoint", checkpointId },
932 createdBy: "user",
933 creationSource: "mcp",
934 });
935 const child = yield* orchestrator.getThreadShell(childId);
936 assert.deepEqual(child?.forkedFrom, { type: "run", threadId: parentId, runId });
937 }).pipe(Effect.provide(forkCases[0]!.layer)),
938 );
939
940 it.effect("a fresh send in a fork that has not run yet starts without the fork's context", () =>
941 Effect.gen(function* () {
942 const orchestrator = yield* Orchestrator.OrchestratorV2;
943 const parentId = ThreadId.make("fresh-fork-parent");
944 const forkId = ThreadId.make("fresh-fork-child");
945 yield* createParent(parentId);
946 yield* writeParentRun({
947 threadId: parentId,
948 runId: RunId.make("fresh-fork-parent-run"),
949 ordinal: 1,
950 status: "completed",
951 text: "Work",
952 stable: true,
953 });
954 yield* orchestrator.dispatch({
955 type: "thread.fork",
956 commandId: CommandId.make("fresh-fork"),
957 sourceThreadId: parentId,
958 targetThreadId: forkId,
959 sourcePoint: { type: "latest_stable" },
960 createdBy: "user",
961 creationSource: "web",
962 });
963 const scheduled = yield* orchestrator
964 .dispatch({
965 type: "message.dispatch",
966 commandId: CommandId.make("fresh-fork-scheduled"),
967 threadId: forkId,
968 messageId: MessageId.make("fresh-fork-scheduled"),
969 scheduledTaskId: ScheduledTaskId.make("fresh-fork-task"),
970 text: "Scheduled",
971 attachments: [],
972 freshContext: true,
973 dispatchMode: { type: "start_immediately" },
974 createdBy: "user",
975 creationSource: "web",
976 })
977 .pipe(Effect.flip);
978 assert.include(String(scheduled.cause), "still being applied");
979 yield* orchestrator.dispatch({
980 type: "message.dispatch",
981 commandId: CommandId.make("fresh-fork-send"),
982 threadId: forkId,
983 messageId: MessageId.make("fresh-fork-send"),
984 text: "Start over",
985 attachments: [],
986 freshContext: true,
987 dispatchMode: { type: "start_immediately" },
988 createdBy: "user",
989 creationSource: "web",
990 });
991 const fork = yield* orchestrator.getThreadProjection(forkId);
992 assert.isTrue(fork.runs.at(-1)?.freshContext === true);
993 assert.deepEqual(
994 fork.contextTransfers.filter((transfer) => transfer.type === "fork").map((t) => t.status),
995 ["superseded"],
996 );
997 }).pipe(Effect.provide(forkCases[0]!.layer)),
998 );
999
1000 it.effect.each([
1001 {
1002 name: "a fresh send queued behind a side chat's failed first run gives later sends no note",
1003 scheduled: false,
1004 },
1005 {
1006 name: "a scheduled fresh run queued behind a side chat's failed first run keeps the fork",
1007 scheduled: true,
1008 },
1009 ] as const)("$name", ({ scheduled }) =>
1010 Effect.gen(function* () {
1011 const orchestrator = yield* Orchestrator.OrchestratorV2;
1012 const eventSink = yield* EventSink.EventSinkV2;
1013 const key = scheduled ? "queued-scheduled-side-chat" : "queued-fresh-side-chat";
1014 const parentId = ThreadId.make(`${key}-parent`);
1015 const sideChatId = ThreadId.make(`${key}-child`);
1016 yield* createParent(parentId);
1017 yield* writeParentRun({
1018 threadId: parentId,
1019 runId: RunId.make(`${key}-parent-run`),
1020 ordinal: 1,
1021 status: "completed",
1022 text: "Work",
1023 stable: true,
1024 });
1025 yield* forkSideChat(`${key}-fork`, parentId, sideChatId);
1026 const send = (name: string, freshContext = false) =>
1027 orchestrator.dispatch({
1028 type: "message.dispatch",
1029 commandId: CommandId.make(`${key}-${name}`),
1030 threadId: sideChatId,
1031 messageId: MessageId.make(`${key}-${name}`),
1032 text: name,
1033 attachments: [],
1034 dispatchMode: { type: "queue_after_active" },
1035 createdBy: "user",
1036 creationSource: "web",
1037 ...(freshContext ? { freshContext } : {}),
1038 ...(freshContext && scheduled
1039 ? { scheduledTaskId: ScheduledTaskId.make(`${key}-task`) }
1040 : {}),
1041 });
1042 const settle = (name: string, status: "failed" | "completed") =>
1043 Effect.gen(function* () {
1044 const run = (yield* orchestrator.getThreadProjection(sideChatId)).runs.find(
1045 (candidate) => candidate.userMessageId === MessageId.make(`${key}-${name}`),
1046 )!;
1047 const now = yield* DateTime.now;
1048 yield* eventSink.write({
1049 events: [
1050 {
1051 id: EventId.make(`${key}-${name}-${status}`),
1052 type: "run.updated",
1053 threadId: sideChatId,
1054 runId: run.id,
1055 occurredAt: now,
1056 payload: { ...run, status, completedAt: now },
1057 },
1058 ],
1059 });
1060 });
1061 yield* send("first");
1062 yield* send("fresh", true);
1063 // The first run fails before its provider forks the parent's session.
1064 yield* settle("first", "failed");
1065 yield* orchestrator.dispatch({
1066 type: "queue.resume",
1067 commandId: CommandId.make(`${key}-resume`),
1068 threadId: sideChatId,
1069 });
1070 assert.equal(
1071 (yield* orchestrator.getThreadProjection(sideChatId)).runs.find(
1072 (run) => run.userMessageId === MessageId.make(`${key}-fresh`),
1073 )?.status,
1074 "starting",
1075 );
1076 yield* settle("fresh", "completed");
1077 yield* send("next");
1078
1079 const sideChat = yield* orchestrator.getThreadProjection(sideChatId);
1080 assert.deepEqual(
1081 sideChat.contextTransfers.filter((transfer) => transfer.type === "fork").map((t) => t.status),
1082 [scheduled ? "pending" : "superseded"],
1083 );
1084 if (scheduled) return;
1085 const next = sideChat.runs.find((run) => run.userMessageId === MessageId.make(`${key}-next`));
1086 // A fork still pending would give the next send a new note, with a digest of the main thread.
1087 assert.deepEqual(
1088 sideChat.contextHandoffs.filter((handoff) => handoff.targetRunId === next?.id),
1089 [],
1090 );
1091 }).pipe(Effect.provide(forkCases[0]!.layer)),
1092 );
1093
1094 it.effect("a side chat of a busy parent points history recovery at the parent", () =>
1095 Effect.gen(function* () {
1096 const orchestrator = yield* Orchestrator.OrchestratorV2;
1097 const parentId = ThreadId.make("side-chat-recovery-parent");
1098 const sideChatId = ThreadId.make("side-chat-recovery-child");
1099 yield* createParent(parentId);
1100 yield* writeParentRun({
1101 threadId: parentId,
1102 runId: RunId.make("side-chat-recovery-stable-run"),
1103 ordinal: 1,
1104 status: "completed",
1105 text: "Earlier parent history",
1106 stable: true,
1107 });
1108 yield* writeParentRun({
1109 threadId: parentId,
1110 runId: RunId.make("side-chat-recovery-busy-run"),
1111 ordinal: 2,
1112 status: "running",
1113 text: "Parent work in progress",
1114 });
1115 yield* forkSideChat("side-chat-recovery-fork", parentId, sideChatId);
1116 yield* askSideChat(sideChatId, "side-chat-recovery-first-message");
1117
1118 const started = yield* orchestrator.getThreadProjection(sideChatId);
1119 assert.equal(started.contextTransfers[0]?.resolution?.strategy, "portable_context");
1120 const handoff = started.contextHandoffs.find((item) => item.strategy === "full_thread_summary");
1121 const coverage = handoff?.history?.coverage ?? "";
1122 assert.include(coverage, `t3_thread_read({threadId:"${parentId}"`);
1123 assert.notInclude(coverage, `threadId:"${sideChatId}"`);
1124 assert.isFalse(started.turnItems.some((item) => item.type === "handoff"));
1125 }).pipe(Effect.provide(forkCases[0]!.layer)),
1126 );
1127
1128 it.effect("a side chat of an idle parent still starts with the framing note", () =>
1129 Effect.gen(function* () {
1130 const orchestrator = yield* Orchestrator.OrchestratorV2;
1131 const parentId = ThreadId.make("side-chat-idle-parent");
1132 const sideChatId = ThreadId.make("side-chat-idle-child");
1133 yield* createParent(parentId);
1134 yield* writeParentRun({
1135 threadId: parentId,
1136 runId: RunId.make("side-chat-idle-parent-run"),
1137 ordinal: 1,
1138 status: "completed",
1139 text: "Parent work",
1140 stable: true,
1141 });
1142
1143 const reads: Array<string> = [];
1144 const recordReads: Statement.Transformer = (statement) => {
1145 const [query] = statement.compile();
1146 if (/^\s*SELECT/i.test(query)) reads.push(query);
1147 return Effect.succeed(statement);
1148 };
1149 yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId).pipe(
1150 Effect.provideService(Statement.CurrentTransformer, recordReads),
1151 );
1152 assert.isEmpty(
1153 reads.filter(
1154 (query) =>
1155 query.includes("FROM orchestration_v2_projection_checkpoints") ||
1156 query.includes("FROM orchestration_v2_projection_context_transfers"),
1157 ),
1158 );
1159 assert.equal(
1160 (yield* orchestrator.getThreadProjection(sideChatId)).thread.runtimeMode,
1161 "full-access",
1162 );
1163 yield* orchestrator.dispatch({
1164 type: "thread.runtime-mode.set",
1165 commandId: CommandId.make("side-chat-parent-mode-change"),
1166 threadId: parentId,
1167 runtimeMode: "approval-required",
1168 });
1169 assert.equal(
1170 (yield* orchestrator.getThreadProjection(sideChatId)).thread.runtimeMode,
1171 "full-access",
1172 );
1173 yield* orchestrator.dispatch({
1174 type: "thread.runtime-mode.set",
1175 commandId: CommandId.make("side-chat-child-mode-change"),
1176 threadId: sideChatId,
1177 runtimeMode: "auto",
1178 });
1179 yield* askSideChat(sideChatId, "side-chat-idle-first-message", {
1180 ...forkCases[0]!.modelSelection,
1181 model: "side-chat-model",
1182 });
1183
1184 const started = yield* orchestrator.getThreadProjection(sideChatId);
1185 assert.equal(started.thread.runtimeMode, "auto");
1186 assert.equal(
1187 (yield* orchestrator.getThreadProjection(parentId)).thread.runtimeMode,
1188 "approval-required",
1189 );
1190 assert.isNotNull(started.providerThreads[0]?.forkedFrom);
1191 // The side chat does not show the parent's run, so it is no baseline.
1192 assert.isFalse(
1193 started.turnItems.some((item) => item.type === "user_message" && item.modelSwitch),
1194 );
1195 assert.lengthOf(started.contextHandoffs, 1);
1196 const [handoff] = started.contextHandoffs;
1197 assert.isTrue(
1198 handoff!.summaryText.startsWith("You are in a side chat beside the main thread."),
1199 );
1200 assert.notInclude(handoff!.summaryText, "Main thread activity");
1201 }).pipe(Effect.provide(forkCases[0]!.layer)),
1202 );
1203
1204 it.effect("a side chat waits for the parent's new worktree, also after its setup ended", () =>
1205 Effect.gen(function* () {
1206 for (const status of ["preparing", "failed", "interrupted"] as const) {
1207 const parentId = ThreadId.make(`side-chat-worktree-parent-${status}`);
1208 yield* createParent(parentId);
1209 yield* writeParentRun({
1210 threadId: parentId,
1211 runId: RunId.make(`side-chat-worktree-parent-run-${status}`),
1212 ordinal: 1,
1213 status,
1214 text: "Parent work",
1215 });
1216
1217 const rejected = yield* forkSideChat(
1218 `side-chat-worktree-fork-${status}`,
1219 parentId,
1220 ThreadId.make(`side-chat-worktree-child-${status}`),
1221 ).pipe(Effect.flip);
1222 assert.include(String(rejected.cause), "has no worktree yet", status);
1223 }
1224 }).pipe(Effect.provide(forkCases[0]!.layer)),
1225 );
1226
1227 it.effect("a side chat opens once a later run has worked in the project checkout", () =>
1228 Effect.gen(function* () {
1229 const orchestrator = yield* Orchestrator.OrchestratorV2;
1230 const parentId = ThreadId.make("side-chat-worktree-abandoned-parent");
1231 const sideChatId = ThreadId.make("side-chat-worktree-abandoned-child");
1232 yield* createParent(parentId);
1233 yield* writeParentRun({
1234 threadId: parentId,
1235 runId: RunId.make("side-chat-worktree-abandoned-run-1"),
1236 ordinal: 1,
1237 status: "interrupted",
1238 text: "Stopped during setup",
1239 });
1240 yield* writeParentRun({
1241 threadId: parentId,
1242 runId: RunId.make("side-chat-worktree-abandoned-run-2"),
1243 ordinal: 2,
1244 status: "completed",
1245 text: "Worked in the project checkout",
1246 stable: true,
1247 });
1248
1249 yield* forkSideChat("side-chat-worktree-abandoned-fork", parentId, sideChatId);
1250 assert.isNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
1251
1252 // A retried setup that is running again, or failed again, comes after the later run.
1253 for (const status of ["preparing", "failed"] as const) {
1254 const retriedParentId = ThreadId.make(`side-chat-worktree-retried-parent-${status}`);
1255 yield* createParent(retriedParentId);
1256 yield* writeParentRun({
1257 threadId: retriedParentId,
1258 runId: RunId.make(`side-chat-worktree-retried-run-2-${status}`),
1259 ordinal: 2,
1260 status: "completed",
1261 text: "Worked in the project checkout",
1262 stable: true,
1263 });
1264 yield* TestClock.adjust("1 second");
1265 yield* writeParentRun({
1266 threadId: retriedParentId,
1267 runId: RunId.make(`side-chat-worktree-retried-run-1-${status}`),
1268 ordinal: 1,
1269 status,
1270 text: "Retried setup",
1271 });
1272 const rejected = yield* forkSideChat(
1273 `side-chat-worktree-retried-fork-${status}`,
1274 retriedParentId,
1275 ThreadId.make(`side-chat-worktree-retried-child-${status}`),
1276 ).pipe(Effect.flip);
1277 assert.include(String(rejected.cause), "has no worktree yet", status);
1278 }
1279 }).pipe(Effect.provide(forkCases[0]!.layer)),
1280 );
1281
1282 it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
1283 Effect.gen(function* () {
1284 const orchestrator = yield* Orchestrator.OrchestratorV2;
1285 const parentId = ThreadId.make("side-chat-close-parent");
1286 const unused = ThreadId.make("side-chat-close-unused");
1287 const used = ThreadId.make("side-chat-close-used");
1288 yield* createParent(parentId);
1289 yield* writeParentRun({
1290 threadId: parentId,
1291 runId: RunId.make("side-chat-close-parent-run"),
1292 ordinal: 1,
1293 status: "completed",
1294 text: "Parent work",
1295 stable: true,
1296 });
1297 yield* forkSideChat("side-chat-close-fork-unused", parentId, unused);
1298 yield* forkSideChat("side-chat-close-fork-used", parentId, used);
1299 yield* askSideChat(used, "side-chat-close-used-message");
1300 const close = (threadId: ThreadId) =>
1301 orchestrator.dispatch({
1302 type: "thread.delete",
1303 commandId: CommandId.make(`side-chat-close:${threadId}`),
1304 threadId,
1305 onlyIfUnused: true,
1306 });
1307
1308 yield* close(unused);
1309 yield* close(used);
1310 assert.isNotNull((yield* orchestrator.getThreadProjection(unused)).thread.deletedAt);
1311 assert.isNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
1312
1313 yield* orchestrator.dispatch({
1314 type: "thread.delete",
1315 commandId: CommandId.make("side-chat-close-delete-parent"),
1316 threadId: parentId,
1317 });
1318 assert.isNotNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
1319 const orphan = yield* forkSideChat(
1320 "side-chat-close-orphan",
1321 parentId,
1322 ThreadId.make("side-chat-close-orphan"),
1323 ).pipe(Effect.flip);
1324 assert.include(String(orphan.cause), "was deleted");
1325 }).pipe(Effect.provide(forkCases[0]!.layer)),
1326 );
1327
1328 it.effect(
1329 "archiving a parent stops and archives its side chats; unarchiving brings them back",
1330 () =>
1331 Effect.gen(function* () {
1332 const orchestrator = yield* Orchestrator.OrchestratorV2;
1333 const eventSink = yield* EventSink.EventSinkV2;
1334 const { driver, instanceId } = forkCases[0]!;
1335 const parentId = ThreadId.make("side-chat-archive-parent");
1336 const busy = ThreadId.make("side-chat-archive-busy");
1337 const archivedFirst = ThreadId.make("side-chat-archive-archived-first");
1338 const delegating = ThreadId.make("side-chat-archive-delegating");
1339 yield* createParent(parentId);
1340 yield* writeParentRun({
1341 threadId: parentId,
1342 runId: RunId.make("side-chat-archive-parent-run"),
1343 ordinal: 1,
1344 status: "completed",
1345 text: "Parent work",
1346 stable: true,
1347 });
1348 yield* forkSideChat("side-chat-archive-fork-busy", parentId, busy);
1349 yield* forkSideChat("side-chat-archive-fork-archived-first", parentId, archivedFirst);
1350 yield* forkSideChat("side-chat-archive-fork-delegating", parentId, delegating);
1351 const runningRunId = RunId.make("side-chat-archive-busy-running");
1352 const queuedRunId = RunId.make("side-chat-archive-busy-queued");
1353 yield* writeParentRun({
1354 threadId: busy,
1355 runId: runningRunId,
1356 ordinal: 1,
1357 status: "running",
1358 text: "Run a long command",
1359 });
1360 yield* writeParentRun({
1361 threadId: busy,
1362 runId: queuedRunId,
1363 ordinal: 2,
1364 status: "queued",
1365 text: "Then this",
1366 });
1367 const now = yield* DateTime.now;
1368 for (const threadId of [parentId, busy]) {
1369 yield* eventSink.write({
1370 events: [
1371 {
1372 id: EventId.make(`${threadId}:session`),
1373 type: "provider-session.attached",
1374 threadId,
1375 driver,
1376 providerInstanceId: instanceId,
1377 occurredAt: now,
1378 payload: {
1379 id: ProviderSessionId.make(`${threadId}:session`),
1380 driver,
1381 providerInstanceId: instanceId,
1382 status: "running",
1383 cwd: "/workspace",
1384 model: "test-model",
1385 capabilities: CodexProviderCapabilitiesV2,
1386 createdAt: now,
1387 updatedAt: now,
1388 lastError: null,
1389 },
1390 },
1391 ],
1392 });
1393 }
1394 const delegatingRunId = RunId.make("side-chat-archive-delegating-run");
1395 yield* writeParentRun({
1396 threadId: delegating,
1397 runId: delegatingRunId,
1398 ordinal: 1,
1399 status: "completed",
1400 text: "Delegate a review",
1401 });
1402 const taskId = NodeId.make("side-chat-archive-delegated-task");
1403 yield* eventSink.write({
1404 events: [
1405 {
1406 id: EventId.make(`${taskId}:running`),
1407 type: "subagent.updated",
1408 threadId: delegating,
1409 occurredAt: now,
1410 payload: {
1411 id: taskId,
1412 threadId: delegating,
1413 runId: delegatingRunId,
1414 parentNodeId: NodeId.make("side-chat-archive-delegating-node"),
1415 origin: "app_owned",
1416 createdBy: "agent",
1417 driver,
1418 providerInstanceId: instanceId,
1419 providerThreadId: null,
1420 childThreadId: ThreadId.make("side-chat-archive-delegated-child"),
1421 nativeTaskRef: null,
1422 prompt: "Review the changes",
1423 title: null,
1424 model: null,
1425 status: "running",
1426 result: null,
1427 startedAt: now,
1428 completedAt: null,
1429 updatedAt: now,
1430 },
1431 },
1432 ],
1433 });
1434 const archive = (commandId: string, threadId: ThreadId) =>
1435 orchestrator.dispatch({
1436 type: "thread.archive",
1437 commandId: CommandId.make(commandId),
1438 threadId,
1439 });
1440 const archivedAt = (threadId: ThreadId) =>
1441 orchestrator
1442 .getThreadProjection(threadId)
1443 .pipe(Effect.map(({ thread }) => thread.archivedAt));
1444
1445 // Archiving a side chat on its own leaves its parent alone.
1446 yield* archive("side-chat-archive-only-child", archivedFirst);
1447 const childArchivedAt = yield* archivedAt(archivedFirst);
1448 assert.isNotNull(childArchivedAt);
1449 assert.isNull(yield* archivedAt(parentId));
1450 yield* TestClock.adjust("1 second");
1451
1452 yield* archive("side-chat-archive-parent", parentId);
1453 assert.isNotNull(yield* archivedAt(parentId));
1454 const archivedBusy = yield* orchestrator.getThreadProjection(busy);
1455 assert.isNotNull(archivedBusy.thread.archivedAt);
1456 assert.equal(archivedBusy.runs.find((run) => run.id === queuedRunId)?.status, "cancelled");
1457 assert.isEmpty(archivedBusy.providerSessions);
1458 assert.deepEqual(yield* archivedAt(archivedFirst), childArchivedAt);
1459 // Archive refuses a thread still waiting on delegated tasks, so the cascade leaves it active.
1460 assert.isNull(yield* archivedAt(delegating));
1461
1462 yield* orchestrator.dispatch({
1463 type: "thread.unarchive",
1464 commandId: CommandId.make("side-chat-archive-unarchive-parent"),
1465 threadId: parentId,
1466 });
1467 assert.isNull(yield* archivedAt(parentId));
1468 assert.isNull(yield* archivedAt(busy));
1469 assert.deepEqual(yield* archivedAt(archivedFirst), childArchivedAt);
1470 }).pipe(Effect.provide(forkCases[0]!.layer)),
1471 );
1472
1473 it.effect("a side chat opened during the parent's first turn starts from a digest", () =>
1474 Effect.gen(function* () {
1475 const orchestrator = yield* Orchestrator.OrchestratorV2;
1476 const grandparentId = ThreadId.make("side-chat-busy-grandparent");
1477 const grandparentRunId = RunId.make("side-chat-busy-grandparent-run");
1478 const parentId = ThreadId.make("side-chat-busy-parent");
1479 const sideChatId = ThreadId.make("side-chat-busy-child");
1480 yield* createParent(grandparentId);
1481 yield* writeParentRun({
1482 threadId: grandparentId,
1483 runId: grandparentRunId,
1484 ordinal: 1,
1485 status: "completed",
1486 text: "GRANDPARENT_MARKER",
1487 stable: true,
1488 });
1489 yield* orchestrator.dispatch({
1490 type: "thread.fork",
1491 commandId: CommandId.make("side-chat-busy-parent-fork"),
1492 sourceThreadId: grandparentId,
1493 targetThreadId: parentId,
1494 sourcePoint: { type: "run", runId: grandparentRunId },
1495 createdBy: "user",
1496 creationSource: "web",
1497 });
1498 yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");
1499 yield* writeParentRun({
1500 threadId: parentId,
1501 runId: RunId.make("side-chat-rewound-parent-run"),
1502 ordinal: 1,
1503 status: "rolled_back",
1504 text: "PARENT_ROLLED_BACK_MARKER",
1505 });
1506 yield* writeParentRun({
1507 threadId: parentId,
1508 runId: RunId.make("side-chat-busy-parent-run"),
1509 ordinal: 2,
1510 status: "running",
1511 text: "PARENT_RUNNING_MARKER",
1512 });
1513 yield* writeParentRun({
1514 threadId: parentId,
1515 runId: RunId.make("side-chat-queued-parent-run"),
1516 ordinal: 3,
1517 status: "queued",
1518 text: "PARENT_QUEUED_MARKER",
1519 });
1520 const fork = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
1521 orchestrator.dispatch({
1522 type: "thread.fork",
1523 commandId: CommandId.make(commandId),
1524 sourceThreadId,
1525 targetThreadId,
1526 sourcePoint: { type: "latest_stable" },
1527 sideChat: true,
1528 createdBy: "user",
1529 creationSource: "web",
1530 });
1531
1532 yield* fork("side-chat-busy-fork", parentId, sideChatId);
1533 const created = yield* orchestrator.getThreadProjection(sideChatId);
1534 assert.isTrue(created.thread.lineage.sideChat);
1535 assert.equal(created.thread.runtimeMode, "full-access");
1536 assert.isNull(created.thread.forkedFrom);
1537 assert.deepEqual(created.contextTransfers[0]?.sourcePoint, { threadId: parentId });
1538
1539 const nested = yield* fork(
1540 "side-chat-busy-nested",
1541 sideChatId,
1542 ThreadId.make("side-chat-busy-nested"),
1543 ).pipe(Effect.flip);
1544 assert.equal(nested._tag, "OrchestratorDispatchError");
1545 // Either would take the side chat's lock before the parent's, against the delete cascade.
1546 const ontoParent = yield* fork("side-chat-busy-onto-parent", sideChatId, parentId).pipe(
1547 Effect.flip,
1548 );
1549 assert.equal(ontoParent._tag, "OrchestratorThreadAlreadyExistsError");
1550 const ontoExisting = yield* fork("side-chat-busy-onto-existing", parentId, sideChatId).pipe(
1551 Effect.flip,
1552 );
1553 assert.equal(ontoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1554 const plainOntoExisting = yield* orchestrator
1555 .dispatch({
1556 type: "thread.fork",
1557 commandId: CommandId.make("side-chat-busy-plain-onto-existing"),
1558 sourceThreadId: parentId,
1559 targetThreadId: sideChatId,
1560 sourcePoint: { type: "latest_stable" },
1561 createdBy: "user",
1562 creationSource: "web",
1563 })
1564 .pipe(Effect.flip);
1565 assert.equal(plainOntoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1566 const busyMergeBack = yield* orchestrator
1567 .dispatch({
1568 type: "thread.merge_back",
1569 commandId: CommandId.make("side-chat-busy-merge-back"),
1570 sourceThreadId: sideChatId,
1571 targetThreadId: parentId,
1572 sourcePoint: { type: "latest_stable" },
1573 createdBy: "user",
1574 creationSource: "web",
1575 })
1576 .pipe(Effect.flip);
1577 assert.include(String(busyMergeBack.cause), "active work");
1578
1579 yield* orchestrator.dispatch({
1580 type: "message.dispatch",
1581 commandId: CommandId.make("side-chat-busy-first-message"),
1582 threadId: sideChatId,
1583 messageId: MessageId.make("side-chat-busy-first-message"),
1584 text: "What is the main thread doing?",
1585 attachments: [],
1586 dispatchMode: { type: "start_immediately" },
1587 createdBy: "user",
1588 creationSource: "web",
1589 });
1590 const started = yield* orchestrator.getThreadProjection(sideChatId);
1591 const [handoff] = started.contextHandoffs;
1592 assert.lengthOf(started.contextHandoffs, 1);
1593 assert.deepEqual(started.contextTransfers[0]?.resolution, {
1594 strategy: "portable_context",
1595 contextHandoffId: handoff!.id,
1596 });
1597 assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");
1598 // Inherited rows come first, so the cap truncates them first.
1599 assert.isAbove(
1600 handoff!.summaryText.indexOf("- User: PARENT_IMPORTED_MARKER"),
1601 handoff!.summaryText.indexOf("- User: GRANDPARENT_MARKER"),
1602 );
1603 assert.include(handoff!.summaryText, "- User: GRANDPARENT_MARKER");
1604 assert.notInclude(handoff!.summaryText, "PARENT_ROLLED_BACK_MARKER");
1605 assert.notInclude(handoff!.summaryText, "PARENT_QUEUED_MARKER");
1606 assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");
1607 assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");
1608 assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);
1609 assert.equal(
1610 started.messages.find((message) => message.role === "user")?.text,
1611 "What is the main thread doing?",
1612 );
1613
1614 yield* orchestrator.dispatch({
1615 type: "thread.delete",
1616 commandId: CommandId.make("side-chat-busy-delete-parent"),
1617 threadId: parentId,
1618 });
1619 assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
1620 }).pipe(Effect.provide(forkCases[0]!.layer)),
1621 );
1622
1623 it.effect("merge-back rejects a second fork's context until the first is consumed", () =>
1624 Effect.gen(function* () {
1625 const orchestrator = yield* Orchestrator.OrchestratorV2;
1626 const parentId = ThreadId.make("merge-back-guard-parent");
1627 const parentRunId = RunId.make("merge-back-guard-parent-run");
1628 yield* createParent(parentId);
1629 yield* writeParentRun({
1630 threadId: parentId,
1631 runId: parentRunId,
1632 ordinal: 1,
1633 status: "completed",
1634 text: "Parent work",
1635 });
1636 const forkAndRun = (name: string) =>
1637 Effect.gen(function* () {
1638 const threadId = ThreadId.make(`merge-back-guard-${name}`);
1639 const runId = RunId.make(`merge-back-guard-${name}-run`);
1640 yield* orchestrator.dispatch({
1641 type: "thread.fork",
1642 commandId: CommandId.make(`merge-back-guard-fork-${name}`),
1643 sourceThreadId: parentId,
1644 targetThreadId: threadId,
1645 sourcePoint: { type: "run", runId: parentRunId },
1646 sideChat: true,
1647 createdBy: "user",
1648 creationSource: "web",
1649 });
1650 yield* writeParentRun({ threadId, runId, ordinal: 1, status: "completed", text: name });
1651 return { threadId, runId };
1652 });
1653 const mergeBack = (commandId: string, fork: { threadId: ThreadId; runId: RunId }) =>
1654 orchestrator.dispatch({
1655 type: "thread.merge_back",
1656 commandId: CommandId.make(commandId),
1657 sourceThreadId: fork.threadId,
1658 targetThreadId: parentId,
1659 sourcePoint: { type: "run", runId: fork.runId },
1660 createdBy: "user",
1661 creationSource: "web",
1662 });
1663 const first = yield* forkAndRun("first");
1664 const second = yield* forkAndRun("second");
1665
1666 yield* mergeBack("merge-back-guard-first", first);
1667 const refusedFresh = yield* orchestrator
1668 .dispatch({
1669 type: "message.dispatch",
1670 commandId: CommandId.make("merge-back-guard-fresh-send"),
1671 threadId: parentId,
1672 messageId: MessageId.make("merge-back-guard-fresh-send"),
1673 text: "Start over",
1674 attachments: [],
1675 dispatchMode: { type: "start_immediately" },
1676 freshContext: true,
1677 createdBy: "user",
1678 creationSource: "web",
1679 })
1680 .pipe(Effect.flip);
1681 assert.include(
1682 String(refusedFresh.cause),
1683 "Send a message without /clear to apply the merged context first.",
1684 );
1685 const rejected = yield* mergeBack("merge-back-guard-second", second).pipe(Effect.flip);
1686 assert.include(String(rejected.cause), "pending context from another side chat or fork");
1687 yield* mergeBack("merge-back-guard-first-again", first);
1688 // That pending merge-back targets the parent, so it does not block one into `first`.
1689 const nested = { threadId: ThreadId.make("merge-back-guard-nested") };
1690 const nestedRunId = RunId.make("merge-back-guard-nested-run");
1691 yield* orchestrator.dispatch({
1692 type: "thread.fork",
1693 commandId: CommandId.make("merge-back-guard-fork-nested"),
1694 sourceThreadId: first.threadId,
1695 targetThreadId: nested.threadId,
1696 sourcePoint: { type: "run", runId: first.runId },
1697 createdBy: "user",
1698 creationSource: "web",
1699 });
1700 yield* writeParentRun({
1701 threadId: nested.threadId,
1702 runId: nestedRunId,
1703 ordinal: 1,
1704 status: "completed",
1705 text: "nested",
1706 });
1707 yield* orchestrator.dispatch({
1708 type: "thread.merge_back",
1709 commandId: CommandId.make("merge-back-guard-nested"),
1710 sourceThreadId: nested.threadId,
1711 targetThreadId: first.threadId,
1712 sourcePoint: { type: "run", runId: nestedRunId },
1713 createdBy: "user",
1714 creationSource: "web",
1715 });
1716
1717 const parent = yield* orchestrator.getThreadProjection(parentId);
1718 assert.deepEqual(
1719 parent.contextTransfers
1720 .filter((transfer) => transfer.type === "merge_back")
1721 .map((transfer) => [transfer.sourceThreadId, transfer.status]),
1722 [
1723 [first.threadId, "superseded"],
1724 [first.threadId, "pending"],
1725 ],
1726 );
1727 }).pipe(Effect.provide(forkCases[0]!.layer)),
1728 );
1729
1730 const runForkWithFailingNativeSource = (forkFailures: number) => {
1731 const driver = ProviderDriverKind.make("claudeAgent");
1732 const instanceId = ProviderInstanceId.make("claudeAgent");
1733 const modelSelection = { instanceId, model: "test-model" };
1734 const started = Deferred.makeUnsafe<ProviderAdapter.ProviderAdapterV2TurnInput>();
1735 let forkCalls = 0;
1736 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
1737 instanceId,
1738 driver,
1739 getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2),
1740 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
1741 openSession: (input) =>
1742 Effect.gen(function* () {
1743 const now = yield* DateTime.now;
1744 return {
1745 instanceId,
1746 driver,
1747 providerSessionId: input.providerSessionId,
1748 providerSession: {
1749 id: input.providerSessionId,
1750 driver,
1751 providerInstanceId: instanceId,
1752 status: "ready",
1753 cwd: "/tmp/fork-missing-native-source",
1754 model: modelSelection.model,
1755 capabilities: ClaudeProviderCapabilitiesV2,
1756 createdAt: now,
1757 updatedAt: now,
1758 lastError: null,
1759 },
1760 events: Stream.never,
1761 ensureThread: ({ threadId, existingProviderThread }) =>
1762 Effect.succeed({
1763 ...existingProviderThread!,
1764 appThreadId: threadId,
1765 nativeThreadRef: { driver, nativeId: "native-fresh-fork", strength: "strong" },
1766 status: "idle",
1767 updatedAt: now,
1768 }),
1769 resumeThread: ({ providerThread }) => Effect.succeed(providerThread),
1770 startTurn: (turn) => Deferred.succeed(started, turn).pipe(Effect.asVoid),
1771 steerTurn: () => Effect.void,
1772 interruptTurn: () => Effect.void,
1773 respondToRuntimeRequest: () => Effect.void,
1774 readThreadSnapshot: () => Effect.die("unused"),
1775 rollbackThread: () => Effect.die("unused"),
1776 forkThread: ({ sourceProviderThread, targetThreadId }) =>
1777 ++forkCalls <= forkFailures
1778 ? Effect.fail(
1779 new ProviderAdapter.ProviderAdapterForkThreadError({
1780 driver,
1781 providerThreadId: sourceProviderThread.id,
1782 cause:
1783 "Session not found: native-deleted-source; authorization=BearerSyntheticSecret",
1784 }),
1785 )
1786 : Effect.succeed({
1787 ...sourceProviderThread,
1788 appThreadId: targetThreadId,
1789 nativeThreadRef: { driver, nativeId: "native-forked", strength: "strong" },
1790 updatedAt: now,
1791 }),
1792 } satisfies ProviderAdapter.ProviderAdapterV2SessionRuntime;
1793 }),
1794 };
1795 return Effect.gen(function* () {
1796 const orchestrator = yield* Orchestrator.OrchestratorV2;
1797 const eventSink = yield* EventSink.EventSinkV2;
1798 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1799 const now = yield* DateTime.now;
1800 const sourceThreadId = ThreadId.make("fork-missing-source");
1801 const targetThreadId = ThreadId.make("fork-missing-target");
1802 const providerThreadId = ProviderThreadId.make("fork-missing-native-thread");
1803 const sourceRunId = RunId.make("fork-missing-source-run");
1804 const userMessageId = MessageId.make("fork-missing-source-message");
1805
1806 yield* orchestrator.dispatch({
1807 type: "thread.create",
1808 commandId: CommandId.make("fork-missing-create-source"),
1809 threadId: sourceThreadId,
1810 projectId: ProjectId.make("fork-missing-project"),
1811 title: "Fork missing source",
1812 modelSelection,
1813 runtimeMode: "full-access",
1814 interactionMode: "default",
1815 branch: null,
1816 worktreePath: null,
1817 createdBy: "user",
1818 creationSource: "web",
1819 });
1820 yield* eventSink.write({
1821 events: [
1822 {
1823 id: EventId.make("fork-missing-provider-thread"),
1824 type: "provider-thread.updated",
1825 threadId: sourceThreadId,
1826 occurredAt: now,
1827 payload: {
1828 id: providerThreadId,
1829 driver,
1830 providerInstanceId: instanceId,
1831 providerSessionId: null,
1832 appThreadId: sourceThreadId,
1833 ownerNodeId: null,
1834 nativeThreadRef: { driver, nativeId: "native-deleted-source", strength: "strong" },
1835 nativeConversationHeadRef: null,
1836 status: "idle",
1837 firstRunOrdinal: 1,
1838 lastRunOrdinal: 1,
1839 handoffIds: [],
1840 forkedFrom: null,
1841 createdAt: now,
1842 updatedAt: now,
1843 },
1844 },
1845 {
1846 id: EventId.make("fork-missing-source-run"),
1847 type: "run.created",
1848 threadId: sourceThreadId,
1849 runId: sourceRunId,
1850 occurredAt: now,
1851 payload: {
1852 id: sourceRunId,
1853 threadId: sourceThreadId,
1854 ordinal: 1,
1855 providerInstanceId: instanceId,
1856 modelSelection,
1857 providerThreadId,
1858 userMessageId,
1859 rootNodeId: null,
1860 activeAttemptId: null,
1861 status: "completed",
1862 queuePosition: null,
1863 requestedAt: now,
1864 startedAt: now,
1865 completedAt: now,
1866 checkpointId: null,
1867 contextHandoffId: null,
1868 },
1869 },
1870 {
1871 id: EventId.make("fork-missing-user-item"),
1872 type: "turn-item.updated",
1873 threadId: sourceThreadId,
1874 runId: sourceRunId,
1875 occurredAt: now,
1876 payload: {
1877 id: TurnItemId.make("fork-missing-user-item"),
1878 threadId: sourceThreadId,
1879 runId: sourceRunId,
1880 nodeId: null,
1881 providerThreadId,
1882 providerTurnId: null,
1883 nativeItemRef: null,
1884 parentItemId: null,
1885 ordinal: 1,
1886 status: "completed",
1887 title: null,
1888 startedAt: now,
1889 completedAt: now,
1890 updatedAt: now,
1891 type: "user_message",
1892 createdBy: "user",
1893 creationSource: "web",
1894 inputIntent: "turn_start",
1895 messageId: userMessageId,
1896 text: "FORKED_SOURCE_MARKER",
1897 attachments: [],
1898 },
1899 },
1900 ],
1901 });
1902 yield* orchestrator.dispatch({
1903 type: "thread.fork",
1904 commandId: CommandId.make("fork-missing-fork"),
1905 sourceThreadId,
1906 targetThreadId,
1907 sourcePoint: { type: "run", runId: sourceRunId },
1908 createdBy: "user",
1909 creationSource: "web",
1910 });
1911 yield* orchestrator.dispatch({
1912 type: "message.dispatch",
1913 commandId: CommandId.make("fork-missing-continue"),
1914 threadId: targetThreadId,
1915 messageId: MessageId.make("fork-missing-continue"),
1916 text: "Continue the fork",
1917 attachments: [],
1918 modelSelection,
1919 dispatchMode: { type: "start_immediately" },
1920 createdBy: "user",
1921 creationSource: "web",
1922 });
1923 // Run every start attempt so the last one runs with willRetry false.
1924 for (let attempt = 0; attempt < 5; attempt++) {
1925 yield* worker.drain();
1926 yield* TestClock.adjust("1 second");
1927 }
1928
1929 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
1930 assert.deepEqual(
1931 projection.turnItems.flatMap((item) => (item.type === "error" ? [item.title] : [])),
1932 [],
1933 );
1934 assert.equal(projection.runs[0]?.status, "running");
1935 return { projection, turn: yield* Deferred.await(started), forkCalls };
1936 }).pipe(
1937 Effect.provide(
1938 ProviderReplayHarness.layerWithRegistry(
1939 { name: "fork-missing-native-source" },
1940 ProviderAdapterRegistry.layerFromAdapters([adapter]),
1941 ),
1942 ),
1943 );
1944 };
1945
1946 it.effect("a native fork whose source session is gone starts fresh with the source history", () =>
1947 Effect.gen(function* () {
1948 const { projection, turn } = yield* runForkWithFailingNativeSource(Number.POSITIVE_INFINITY);
1949 // Resolving the fork transfer stops later sends from retrying the native fork.
1950 assert.equal(projection.contextTransfers[0]?.status, "resolved_portable");
1951 assert.isNull(projection.providerThreads[0]?.forkedFrom);
1952 assert.include(JSON.stringify(turn), "FORKED_SOURCE_MARKER");
1953 const notices = projection.turnItems.flatMap((item) =>
1954 item.type === "system_notice" ? [item.message] : [],
1955 );
1956 assert.lengthOf(notices, 1);
1957 assert.include(notices[0], "Session not found: native-deleted-source");
1958 assert.notInclude(notices[0], "BearerSyntheticSecret");
1959 }),
1960 );
1961
1962 it.effect("a native fork that fails before its last attempt still forks natively", () =>
1963 Effect.gen(function* () {
1964 const { projection, forkCalls } = yield* runForkWithFailingNativeSource(1);
1965 assert.equal(forkCalls, 2);
1966 assert.equal(projection.contextTransfers[0]?.status, "consumed");
1967 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "native_fork");
1968 }),
1969 );