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

ThreadFork.execution.test.ts

1,203 lines43.0 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CheckpointId,
4 CommandId,
5 EventId,
6 MessageId,
7 NodeId,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ProviderThreadId,
12 ProviderTurnId,
13 RunAttemptId,
14 RunId,
15 ThreadId,
16 TurnItemId,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as TestClock from "effect/testing/TestClock";
21​
22import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
23import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
24import * as EffectWorker from "./EffectWorker.ts";
25import * as EventSink from "./EventSink.ts";
26import * as Orchestrator from "./Orchestrator.ts";
27import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
28import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
29import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
30​
31const forkCases = (
32 [
33 ["codex", "interrupted"],
34 ["claudeAgent", "failed"],
35 ] as const
36).map(([driverName, status]) => {
37 const driver = ProviderDriverKind.make(driverName);
38 const instanceId = ProviderInstanceId.make(driver);
39 const modelSelection = { instanceId, model: "test-model" };
40 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
41 instanceId,
42 driver,
43 getCapabilities: () =>
44 Effect.succeed(
45 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
46 ),
47 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
48 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
49 };
50 const layer = ProviderReplayHarness.layerWithRegistry(
51 { name: `fork-boundary-${driver}` },
52 ProviderAdapterRegistry.layerFromAdapters([adapter]),
53 { runEffectWorker: false },
54 );
55​
56 return { driver, status, instanceId, modelSelection, layer };
57});
58​
59it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
60 Effect.gen(function* () {
61 const orchestrator = yield* Orchestrator.OrchestratorV2;
62 const eventSink = yield* EventSink.EventSinkV2;
63 const now = yield* DateTime.now;
64 const { instanceId, modelSelection } = forkCases[0]!;
65 const sourceThreadId = ThreadId.make("fork-watch-source");
66 const targetThreadId = ThreadId.make("fork-watch-target");
67 const sourceRunId = RunId.make("fork-watch-source-run");
68 const key = { host: "github.com", repository: "example/repo", number: 1 };
69 const link = { url: "https://github.com/example/repo/pull/1", source: "agent" as const };
70​
71 yield* orchestrator.dispatch({
72 type: "thread.create",
73 commandId: CommandId.make("fork-watch-create"),
74 threadId: sourceThreadId,
75 projectId: ProjectId.make("fork-watch-project"),
76 title: "Watching source",
77 modelSelection,
78 runtimeMode: "full-access",
79 interactionMode: "default",
80 branch: null,
81 worktreePath: null,
82 createdBy: "user",
83 creationSource: "web",
84 });
85 yield* eventSink.write({
86 events: [
87 {
88 id: EventId.make("fork-watch-source-run"),
89 type: "run.created",
90 threadId: sourceThreadId,
91 runId: sourceRunId,
92 occurredAt: now,
93 payload: {
94 id: sourceRunId,
95 threadId: sourceThreadId,
96 ordinal: 1,
97 providerInstanceId: instanceId,
98 modelSelection,
99 providerThreadId: null,
100 userMessageId: MessageId.make("fork-watch-source-message"),
101 rootNodeId: null,
102 activeAttemptId: null,
103 status: "completed",
104 requestedAt: now,
105 startedAt: now,
106 completedAt: now,
107 checkpointId: null,
108 contextHandoffId: null,
109 },
110 },
111 ],
112 });
113 yield* orchestrator.dispatch({
114 type: "thread.pull-request.watch",
115 commandId: CommandId.make("fork-watch-parent-start"),
116 threadId: sourceThreadId,
117 ...key,
118 watching: true,
119 link,
120 });
121 const parentBefore = yield* orchestrator.getThreadShell(sourceThreadId);
122 const parentWatch = parentBefore?.pullRequests?.[0]?.watch;
123 assert.isDefined(parentWatch);
124 assert.lengthOf(parentBefore?.pendingBackgroundTasks ?? [], 1);
125​
126 yield* orchestrator.dispatch({
127 type: "thread.fork",
128 commandId: CommandId.make("fork-watch-fork"),
129 sourceThreadId,
130 targetThreadId,
131 sourcePoint: { type: "run", runId: sourceRunId },
132 createdBy: "user",
133 creationSource: "mcp",
134 });
135 const fork = yield* orchestrator.getThreadShell(targetThreadId);
136 assert.isNotNull(fork);
137 assert.deepEqual(fork.pullRequests, [
138 {
139 ...key,
140 ...link,
141 linkedAt: parentWatch.startedAt,
142 snapshot: null,
143 stack: null,
144 },
145 ]);
146 assert.deepEqual(fork.pendingBackgroundTasks, []);
147 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
148​
149 const stale = yield* orchestrator
150 .dispatch({
151 type: "thread.pull-request-watch.sync",
152 commandId: CommandId.make("fork-watch-stale-sync"),
153 threadId: targetThreadId,
154 ...key,
155 startedAt: parentWatch.startedAt,
156 watch: parentWatch,
157 wake: {
158 messageId: MessageId.make("fork-watch-unwanted-wake"),
159 text: "A check failed",
160 notification: {
161 source: { kind: "monitor" },
162 outcome: "updated",
163 summary: "A check failed",
164 },
165 },
166 })
167 .pipe(Effect.flip);
168 assert.equal(stale._tag, "OrchestratorDispatchError");
169 assert.deepEqual((yield* orchestrator.getThreadProjection(targetThreadId)).runs, []);
170​
171 yield* TestClock.adjust("1 second");
172 yield* orchestrator.dispatch({
173 type: "thread.pull-request.watch",
174 commandId: CommandId.make("fork-watch-opt-in"),
175 threadId: targetThreadId,
176 ...key,
177 watching: true,
178 link,
179 });
180 const watchingFork = yield* orchestrator.getThreadShell(targetThreadId);
181 assert.isDefined(watchingFork?.pullRequests?.[0]?.watch);
182 assert.notEqual(watchingFork.pullRequests[0].watch.startedAt, parentWatch.startedAt);
183 assert.lengthOf(watchingFork.pendingBackgroundTasks ?? [], 1);
184 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
185​
186 yield* orchestrator.dispatch({
187 type: "thread.pull-request.watch",
188 commandId: CommandId.make("fork-watch-opt-out"),
189 threadId: targetThreadId,
190 ...key,
191 watching: false,
192 });
193 const stoppedFork = yield* orchestrator.getThreadShell(targetThreadId);
194 const [forkLink] = fork.pullRequests ?? [];
195 assert.isDefined(forkLink);
196 assert.deepEqual(stoppedFork?.pullRequests, [
197 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
198 ]);
199 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
200 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
201 }).pipe(Effect.provide(forkCases[0]!.layer)),
202);
203​
204it.effect.each(forkCases)(
205 "bounds $driver context when continuing a fork of a $status run",
206 ({ driver, status, instanceId, modelSelection, layer }) =>
207 Effect.gen(function* () {
208 const orchestrator = yield* Orchestrator.OrchestratorV2;
209 const eventSink = yield* EventSink.EventSinkV2;
210 const now = yield* DateTime.now;
211 const sourceThreadId = ThreadId.make("fork-boundary-source");
212 const targetThreadId = ThreadId.make("fork-boundary-target");
213 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
214 const sourceRunId = RunId.make("fork-boundary-source-run");
215 const attemptId = RunAttemptId.make("interrupted-source-attempt");
216 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
217 const rootNodeId = NodeId.make("interrupted-source-root");
218 const grandparentThreadId = ThreadId.make("fork-boundary-grandparent");
219 const grandparentRunId = RunId.make("fork-boundary-grandparent-run");
220​
221 yield* orchestrator.dispatch({
222 type: "thread.create",
223 commandId: CommandId.make("create-grandparent"),
224 threadId: grandparentThreadId,
225 projectId: ProjectId.make("fork-boundary-project"),
226 title: "Fork boundary grandparent",
227 modelSelection,
228 runtimeMode: "full-access",
229 interactionMode: "default",
230 branch: null,
231 worktreePath: null,
232 createdBy: "user",
233 creationSource: "web",
234 });
235 yield* writeParentRun({
236 threadId: grandparentThreadId,
237 runId: RunId.make("fork-boundary-grandparent-rolled-back-run"),
238 ordinal: 1,
239 status: "rolled_back",
240 text: "ROLLED_BACK_MARKER",
241 });
242 yield* writeParentRun({
243 threadId: grandparentThreadId,
244 runId: grandparentRunId,
245 ordinal: 2,
246 status: "completed",
247 text: "GRANDPARENT_MARKER",
248 });
249 yield* orchestrator.dispatch({
250 type: "thread.fork",
251 commandId: CommandId.make("fork-grandparent"),
252 sourceThreadId: grandparentThreadId,
253 targetThreadId: sourceThreadId,
254 sourcePoint: { type: "run", runId: grandparentRunId },
255 createdBy: "user",
256 creationSource: "web",
257 });
258 yield* eventSink.write({
259 events: [
260 {
261 id: EventId.make("source-provider-thread"),
262 type: "provider-thread.updated",
263 threadId: sourceThreadId,
264 occurredAt: now,
265 payload: {
266 id: providerThreadId,
267 driver,
268 providerInstanceId: instanceId,
269 providerSessionId: null,
270 appThreadId: sourceThreadId,
271 ownerNodeId: null,
272 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
273 nativeConversationHeadRef: null,
274 status: "idle",
275 firstRunOrdinal: 2,
276 lastRunOrdinal: 3,
277 handoffIds: [],
278 forkedFrom: null,
279 createdAt: now,
280 updatedAt: now,
281 },
282 },
283 ],
284 });
285 if (status === "interrupted") {
286 yield* eventSink.write({
287 events: [
288 {
289 id: EventId.make("source-attempt"),
290 type: "run-attempt.created",
291 threadId: sourceThreadId,
292 runId: sourceRunId,
293 occurredAt: now,
294 payload: {
295 id: attemptId,
296 runId: sourceRunId,
297 attemptOrdinal: 1,
298 rootNodeId,
299 providerInstanceId: instanceId,
300 providerThreadId,
301 providerTurnId,
302 reason: "initial",
303 status,
304 startedAt: now,
305 completedAt: now,
306 },
307 },
308 {
309 id: EventId.make("source-provider-turn"),
310 type: "provider-turn.updated",
311 threadId: sourceThreadId,
312 occurredAt: now,
313 payload: {
314 id: providerTurnId,
315 providerThreadId,
316 nodeId: rootNodeId,
317 runAttemptId: attemptId,
318 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
319 ordinal: 1,
320 status,
321 startedAt: now,
322 completedAt: now,
323 },
324 },
325 ],
326 });
327 }
328 yield* writeParentRun({
329 threadId: sourceThreadId,
330 runId: RunId.make("fork-boundary-source-rolled-back-run"),
331 ordinal: 1,
332 status: "rolled_back",
333 text: "SOURCE_ROLLED_BACK_MARKER",
334 });
335 for (const ordinal of [2, 3]) {
336 const runId = ordinal === 2 ? sourceRunId : RunId.make("later-run");
337 const messageId = MessageId.make(`source-message-${ordinal}`);
338 yield* eventSink.write({
339 events: [
340 {
341 id: EventId.make(`run-${ordinal}`),
342 type: "run.created",
343 threadId: sourceThreadId,
344 runId,
345 occurredAt: now,
346 payload: {
347 id: runId,
348 threadId: sourceThreadId,
349 ordinal,
350 providerInstanceId: instanceId,
351 modelSelection,
352 providerThreadId,
353 userMessageId: messageId,
354 rootNodeId: null,
355 activeAttemptId: ordinal === 2 && status === "interrupted" ? attemptId : null,
356 status: ordinal === 2 ? status : "completed",
357 queuePosition: null,
358 requestedAt: now,
359 startedAt: now,
360 completedAt: now,
361 checkpointId: null,
362 contextHandoffId: null,
363 },
364 },
365 {
366 id: EventId.make(`item-${ordinal}`),
367 type: "turn-item.updated",
368 threadId: sourceThreadId,
369 runId,
370 occurredAt: now,
371 payload: {
372 id: TurnItemId.make(`item-${ordinal}`),
373 threadId: sourceThreadId,
374 runId,
375 nodeId: null,
376 providerThreadId,
377 providerTurnId: null,
378 nativeItemRef: null,
379 parentItemId: null,
380 ordinal,
381 status: "completed",
382 title: null,
383 startedAt: now,
384 completedAt: now,
385 updatedAt: now,
386 type: "user_message",
387 createdBy: "user",
388 creationSource: "web",
389 inputIntent: "turn_start",
390 messageId,
391 text: ordinal === 2 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
392 attachments: [],
393 },
394 },
395 ],
396 });
397 }
398 yield* orchestrator.dispatch({
399 type: "thread.fork",
400 commandId: CommandId.make("fork-source"),
401 sourceThreadId,
402 targetThreadId,
403 sourcePoint: { type: "run", runId: sourceRunId },
404 createdBy: "user",
405 creationSource: "web",
406 });
407 yield* orchestrator.dispatch({
408 type: "message.dispatch",
409 commandId: CommandId.make("continue-fork"),
410 threadId: targetThreadId,
411 messageId: MessageId.make("continue-fork"),
412 text: "Continue from the selected source run",
413 attachments: [],
414 modelSelection,
415 dispatchMode: { type: "start_immediately" },
416 createdBy: "user",
417 creationSource: "web",
418 });
419 const target = yield* orchestrator.getThreadProjection(targetThreadId);
420 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
421 assert.lengthOf(target.contextHandoffs, 1);
422 const handoff = target.contextHandoffs[0]!;
423 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
424 assert.include(`${handoff.summaryText}\n${history}`, "GRANDPARENT_MARKER");
425 assert.notInclude(`${handoff.summaryText}\n${history}`, "SOURCE_ROLLED_BACK_MARKER");
426 assert.notInclude(`${handoff.summaryText}\n${history}`, "ROLLED_BACK_MARKER");
427 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
428 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
429 assert.isNull(target.providerThreads[0]?.forkedFrom);
430 }).pipe(Effect.provide(layer)),
431);
432​
433it.effect.each([
434 { execution: "portable_context", rejected: true },
435 { execution: "native_fork", rejected: false },
436] as const)(
437 "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
438 ({ execution, rejected }) => {
439 const opened: Array<ProviderInstanceId> = [];
440 const adapter = (driverName: "claudeAgent" | "codex") => {
441 const driver = ProviderDriverKind.make(driverName);
442 const instanceId = ProviderInstanceId.make(driverName);
443 return {
444 instanceId,
445 driver,
446 getCapabilities: () =>
447 Effect.succeed(
448 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
449 ),
450 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
451 openSession: (input) =>
452 Effect.sync(() => opened.push(instanceId)).pipe(
453 Effect.andThen(
454 new ProviderAdapter.ProviderAdapterOpenSessionError({
455 driver,
456 providerSessionId: input.providerSessionId,
457 }),
458 ),
459 ),
460 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
461 };
462 const claude = adapter("claudeAgent");
463 const target = execution === "portable_context" ? adapter("codex") : claude;
464 return Effect.gen(function* () {
465 const orchestrator = yield* Orchestrator.OrchestratorV2;
466 const eventSink = yield* EventSink.EventSinkV2;
467 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
468 const now = yield* DateTime.now;
469 const sourceThreadId = ThreadId.make("fork-compact-source");
470 const targetThreadId = ThreadId.make("fork-compact-target");
471 const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
472 const sourceRunId = RunId.make("fork-compact-source-run");
473 const userMessageId = MessageId.make("fork-compact-source-message");
474 const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
475​
476 yield* orchestrator.dispatch({
477 type: "thread.create",
478 commandId: CommandId.make("fork-compact-create-source"),
479 threadId: sourceThreadId,
480 projectId: ProjectId.make("fork-compact-project"),
481 title: "Fork compact source",
482 modelSelection: sourceSelection,
483 runtimeMode: "full-access",
484 interactionMode: "default",
485 branch: null,
486 worktreePath: null,
487 createdBy: "user",
488 creationSource: "web",
489 });
490 const item = {
491 threadId: sourceThreadId,
492 runId: sourceRunId,
493 nodeId: null,
494 providerThreadId,
495 providerTurnId: null,
496 nativeItemRef: null,
497 parentItemId: null,
498 status: "completed",
499 title: null,
500 startedAt: now,
501 completedAt: now,
502 updatedAt: now,
503 } as const;
504 yield* eventSink.write({
505 events: [
506 {
507 id: EventId.make("fork-compact-provider-thread"),
508 type: "provider-thread.updated",
509 threadId: sourceThreadId,
510 occurredAt: now,
511 payload: {
512 id: providerThreadId,
513 driver: claude.driver,
514 providerInstanceId: claude.instanceId,
515 providerSessionId: null,
516 appThreadId: sourceThreadId,
517 ownerNodeId: null,
518 nativeThreadRef: {
519 driver: claude.driver,
520 nativeId: "native-fork-compact-source",
521 strength: "strong",
522 },
523 nativeConversationHeadRef: null,
524 status: "idle",
525 firstRunOrdinal: 1,
526 lastRunOrdinal: 1,
527 handoffIds: [],
528 forkedFrom: null,
529 createdAt: now,
530 updatedAt: now,
531 },
532 },
533 {
534 id: EventId.make("fork-compact-source-run"),
535 type: "run.created",
536 threadId: sourceThreadId,
537 runId: sourceRunId,
538 occurredAt: now,
539 payload: {
540 id: sourceRunId,
541 threadId: sourceThreadId,
542 ordinal: 1,
543 providerInstanceId: claude.instanceId,
544 modelSelection: sourceSelection,
545 providerThreadId,
546 userMessageId,
547 rootNodeId: null,
548 activeAttemptId: null,
549 status: "completed",
550 queuePosition: null,
551 requestedAt: now,
552 startedAt: now,
553 completedAt: now,
554 checkpointId: null,
555 contextHandoffId: null,
556 },
557 },
558 // Each message alone exceeds the default 16k handoff budget, so a
559 // portable handoff omits both whole items.
560 {
561 id: EventId.make("fork-compact-user-item"),
562 type: "turn-item.updated",
563 threadId: sourceThreadId,
564 runId: sourceRunId,
565 occurredAt: now,
566 payload: {
567 ...item,
568 id: TurnItemId.make("fork-compact-user-item"),
569 ordinal: 1,
570 type: "user_message",
571 createdBy: "user",
572 creationSource: "web",
573 inputIntent: "turn_start",
574 messageId: userMessageId,
575 text: "u".repeat(17_000),
576 attachments: [],
577 },
578 },
579 {
580 id: EventId.make("fork-compact-assistant-item"),
581 type: "turn-item.updated",
582 threadId: sourceThreadId,
583 runId: sourceRunId,
584 occurredAt: now,
585 payload: {
586 ...item,
587 id: TurnItemId.make("fork-compact-assistant-item"),
588 ordinal: 2,
589 type: "assistant_message",
590 messageId: MessageId.make("fork-compact-assistant-message"),
591 text: "a".repeat(17_000),
592 streaming: false,
593 },
594 },
595 ],
596 });
597 yield* orchestrator.dispatch({
598 type: "thread.fork",
599 commandId: CommandId.make("fork-compact-fork"),
600 sourceThreadId,
601 targetThreadId,
602 sourcePoint: { type: "run", runId: sourceRunId },
603 createdBy: "user",
604 creationSource: "web",
605 });
606 yield* orchestrator.dispatch({
607 type: "message.dispatch",
608 commandId: CommandId.make("fork-compact-compact"),
609 threadId: targetThreadId,
610 messageId: MessageId.make("fork-compact-compact"),
611 text: "/compact",
612 attachments: [],
613 modelSelection: { instanceId: target.instanceId, model: "test-model" },
614 dispatchMode: { type: "start_immediately" },
615 createdBy: "user",
616 creationSource: "web",
617 });
618 yield* worker.drain();
619​
620 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
621 if (execution === "portable_context") {
622 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
623 assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
624 } else {
625 assert.isEmpty(projection.contextHandoffs);
626 }
627 const emptyCompaction = projection.turnItems.some(
628 (turnItem) =>
629 turnItem.type === "error" &&
630 turnItem.failure.message === "Start a conversation before compacting this thread.",
631 );
632 assert.equal(emptyCompaction, rejected);
633 assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
634 }).pipe(
635 Effect.provide(
636 ProviderReplayHarness.layerWithRegistry(
637 { name: `fork-compact-${execution}` },
638 ProviderAdapterRegistry.layerFromAdapters(
639 target === claude ? [claude] : [claude, target],
640 ),
641 ),
642 ),
643 );
644 },
645);
646​
647const writeParentRun = (input: {
648 readonly threadId: ThreadId;
649 readonly runId: RunId;
650 readonly ordinal: number;
651 /** Preparing, failed, and interrupted runs asked for a new worktree. */
652 readonly status:
653 | "preparing"
654 | "running"
655 | "queued"
656 | "completed"
657 | "rolled_back"
658 | "failed"
659 | "interrupted";
660 readonly text: string;
661 /** A checkpointed run on a native provider thread, which `latest_stable` forks start from. */
662 readonly stable?: boolean;
663}) =>
664 Effect.gen(function* () {
665 const eventSink = yield* EventSink.EventSinkV2;
666 const now = yield* DateTime.now;
667 const { driver, instanceId, modelSelection } = forkCases[0]!;
668 const messageId = MessageId.make(`${input.runId}:message`);
669 const providerThreadId = input.stable
670 ? ProviderThreadId.make(`${input.runId}:provider-thread`)
671 : null;
672 yield* eventSink.write({
673 events: [
674 ...(providerThreadId === null
675 ? []
676 : [
677 {
678 id: EventId.make(`${input.runId}:provider-thread`),
679 type: "provider-thread.updated" as const,
680 threadId: input.threadId,
681 occurredAt: now,
682 payload: {
683 id: providerThreadId,
684 driver,
685 providerInstanceId: instanceId,
686 providerSessionId: null,
687 appThreadId: input.threadId,
688 ownerNodeId: null,
689 nativeThreadRef: {
690 driver,
691 nativeId: `${input.runId}:native`,
692 strength: "strong" as const,
693 },
694 nativeConversationHeadRef: null,
695 status: "idle" as const,
696 firstRunOrdinal: input.ordinal,
697 lastRunOrdinal: input.ordinal,
698 handoffIds: [],
699 forkedFrom: null,
700 createdAt: now,
701 updatedAt: now,
702 },
703 },
704 ]),
705 {
706 id: EventId.make(`${input.runId}:created`),
707 type: "run.created",
708 threadId: input.threadId,
709 runId: input.runId,
710 occurredAt: now,
711 payload: {
712 id: input.runId,
713 threadId: input.threadId,
714 ordinal: input.ordinal,
715 providerInstanceId: instanceId,
716 modelSelection,
717 providerThreadId,
718 userMessageId: messageId,
719 rootNodeId: null,
720 activeAttemptId: null,
721 status: input.status,
722 queuePosition: null,
723 requestedAt: now,
724 startedAt: now,
725 completedAt: input.status === "completed" ? now : null,
726 checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
727 contextHandoffId: null,
728 ...(input.status === "preparing" ||
729 input.status === "failed" ||
730 input.status === "interrupted"
731 ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } }
732 : {}),
733 },
734 },
735 {
736 id: EventId.make(`${input.runId}:item`),
737 type: "turn-item.updated",
738 threadId: input.threadId,
739 runId: input.runId,
740 occurredAt: now,
741 payload: {
742 id: TurnItemId.make(`${input.runId}:item`),
743 threadId: input.threadId,
744 runId: input.runId,
745 nodeId: null,
746 providerThreadId,
747 providerTurnId: null,
748 nativeItemRef: null,
749 parentItemId: null,
750 ordinal: input.ordinal * 100,
751 status: "completed",
752 title: null,
753 startedAt: now,
754 completedAt: now,
755 updatedAt: now,
756 type: "user_message",
757 createdBy: "user",
758 creationSource: "web",
759 inputIntent: "turn_start",
760 messageId,
761 text: input.text,
762 attachments: [],
763 },
764 },
765 ],
766 });
767 });
768​
769/** Marks `threadId` as imported from V1 and gives it one runless imported user message. */
770const writeImportedHistory = (threadId: ThreadId, text: string) =>
771 Effect.gen(function* () {
772 const orchestrator = yield* Orchestrator.OrchestratorV2;
773 const eventSink = yield* EventSink.EventSinkV2;
774 const now = yield* DateTime.now;
775 const { thread } = yield* orchestrator.getThreadProjection(threadId);
776 yield* eventSink.write({
777 events: [
778 {
779 id: EventId.make(`${threadId}:imported`),
780 type: "thread.metadata-updated",
781 threadId,
782 occurredAt: now,
783 payload: { ...thread, historyOrigin: "v1_import" },
784 },
785 {
786 id: EventId.make(`${threadId}:imported-item`),
787 type: "turn-item.updated",
788 threadId,
789 occurredAt: now,
790 payload: {
791 id: TurnItemId.make(`${threadId}:imported-item`),
792 threadId,
793 runId: null,
794 nodeId: null,
795 providerThreadId: null,
796 providerTurnId: null,
797 nativeItemRef: null,
798 parentItemId: null,
799 ordinal: 1,
800 status: "completed",
801 title: null,
802 startedAt: now,
803 completedAt: now,
804 updatedAt: now,
805 type: "user_message",
806 createdBy: "user",
807 creationSource: "web",
808 inputIntent: "turn_start",
809 messageId: MessageId.make(`${threadId}:imported-message`),
810 text,
811 attachments: [],
812 },
813 },
814 ],
815 });
816 });
817​
818const createParent = (threadId: ThreadId) =>
819 Effect.gen(function* () {
820 const orchestrator = yield* Orchestrator.OrchestratorV2;
821 yield* orchestrator.dispatch({
822 type: "thread.create",
823 commandId: CommandId.make(`${threadId}:create`),
824 threadId,
825 projectId: ProjectId.make("side-chat-project"),
826 title: "Side chat parent",
827 modelSelection: forkCases[0]!.modelSelection,
828 runtimeMode: "full-access",
829 interactionMode: "default",
830 branch: null,
831 worktreePath: null,
832 createdBy: "user",
833 creationSource: "web",
834 });
835 });
836​
837const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
838 Effect.gen(function* () {
839 const orchestrator = yield* Orchestrator.OrchestratorV2;
840 return yield* orchestrator.dispatch({
841 type: "thread.fork",
842 commandId: CommandId.make(commandId),
843 sourceThreadId,
844 targetThreadId,
845 sourcePoint: { type: "latest_stable" },
846 sideChat: true,
847 createdBy: "user",
848 creationSource: "web",
849 });
850 });
851​
852const askSideChat = (threadId: ThreadId, commandId: string) =>
853 Effect.gen(function* () {
854 const orchestrator = yield* Orchestrator.OrchestratorV2;
855 yield* orchestrator.dispatch({
856 type: "message.dispatch",
857 commandId: CommandId.make(commandId),
858 threadId,
859 messageId: MessageId.make(commandId),
860 text: "What is the main thread doing?",
861 attachments: [],
862 dispatchMode: { type: "start_immediately" },
863 createdBy: "user",
864 creationSource: "web",
865 });
866 });
867​
868it.effect("a side chat of an idle parent still starts with the framing note", () =>
869 Effect.gen(function* () {
870 const orchestrator = yield* Orchestrator.OrchestratorV2;
871 const parentId = ThreadId.make("side-chat-idle-parent");
872 const sideChatId = ThreadId.make("side-chat-idle-child");
873 yield* createParent(parentId);
874 yield* writeParentRun({
875 threadId: parentId,
876 runId: RunId.make("side-chat-idle-parent-run"),
877 ordinal: 1,
878 status: "completed",
879 text: "Parent work",
880 stable: true,
881 });
882​
883 yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId);
884 yield* askSideChat(sideChatId, "side-chat-idle-first-message");
885​
886 const started = yield* orchestrator.getThreadProjection(sideChatId);
887 assert.isNotNull(started.providerThreads[0]?.forkedFrom);
888 assert.lengthOf(started.contextHandoffs, 1);
889 const [handoff] = started.contextHandoffs;
890 assert.isTrue(
891 handoff!.summaryText.startsWith("You are in a side chat beside the main thread."),
892 );
893 assert.notInclude(handoff!.summaryText, "Main thread activity");
894 }).pipe(Effect.provide(forkCases[0]!.layer)),
895);
896​
897it.effect("a side chat waits for the parent's new worktree, also after its setup ended", () =>
898 Effect.gen(function* () {
899 for (const status of ["preparing", "failed", "interrupted"] as const) {
900 const parentId = ThreadId.make(`side-chat-worktree-parent-${status}`);
901 yield* createParent(parentId);
902 yield* writeParentRun({
903 threadId: parentId,
904 runId: RunId.make(`side-chat-worktree-parent-run-${status}`),
905 ordinal: 1,
906 status,
907 text: "Parent work",
908 });
909​
910 const rejected = yield* forkSideChat(
911 `side-chat-worktree-fork-${status}`,
912 parentId,
913 ThreadId.make(`side-chat-worktree-child-${status}`),
914 ).pipe(Effect.flip);
915 assert.include(String(rejected.cause), "has no worktree yet", status);
916 }
917 }).pipe(Effect.provide(forkCases[0]!.layer)),
918);
919​
920it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
921 Effect.gen(function* () {
922 const orchestrator = yield* Orchestrator.OrchestratorV2;
923 const parentId = ThreadId.make("side-chat-close-parent");
924 const unused = ThreadId.make("side-chat-close-unused");
925 const used = ThreadId.make("side-chat-close-used");
926 yield* createParent(parentId);
927 yield* writeParentRun({
928 threadId: parentId,
929 runId: RunId.make("side-chat-close-parent-run"),
930 ordinal: 1,
931 status: "completed",
932 text: "Parent work",
933 stable: true,
934 });
935 yield* forkSideChat("side-chat-close-fork-unused", parentId, unused);
936 yield* forkSideChat("side-chat-close-fork-used", parentId, used);
937 yield* askSideChat(used, "side-chat-close-used-message");
938 const close = (threadId: ThreadId) =>
939 orchestrator.dispatch({
940 type: "thread.delete",
941 commandId: CommandId.make(`side-chat-close:${threadId}`),
942 threadId,
943 onlyIfUnused: true,
944 });
945​
946 yield* close(unused);
947 yield* close(used);
948 assert.isNotNull((yield* orchestrator.getThreadProjection(unused)).thread.deletedAt);
949 assert.isNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
950​
951 yield* orchestrator.dispatch({
952 type: "thread.delete",
953 commandId: CommandId.make("side-chat-close-delete-parent"),
954 threadId: parentId,
955 });
956 assert.isNotNull((yield* orchestrator.getThreadProjection(used)).thread.deletedAt);
957 const orphan = yield* forkSideChat(
958 "side-chat-close-orphan",
959 parentId,
960 ThreadId.make("side-chat-close-orphan"),
961 ).pipe(Effect.flip);
962 assert.include(String(orphan.cause), "was deleted");
963 }).pipe(Effect.provide(forkCases[0]!.layer)),
964);
965​
966it.effect("a side chat opened during the parent's first turn starts from a digest", () =>
967 Effect.gen(function* () {
968 const orchestrator = yield* Orchestrator.OrchestratorV2;
969 const grandparentId = ThreadId.make("side-chat-busy-grandparent");
970 const grandparentRunId = RunId.make("side-chat-busy-grandparent-run");
971 const parentId = ThreadId.make("side-chat-busy-parent");
972 const sideChatId = ThreadId.make("side-chat-busy-child");
973 yield* createParent(grandparentId);
974 yield* writeParentRun({
975 threadId: grandparentId,
976 runId: grandparentRunId,
977 ordinal: 1,
978 status: "completed",
979 text: "GRANDPARENT_MARKER",
980 stable: true,
981 });
982 yield* orchestrator.dispatch({
983 type: "thread.fork",
984 commandId: CommandId.make("side-chat-busy-parent-fork"),
985 sourceThreadId: grandparentId,
986 targetThreadId: parentId,
987 sourcePoint: { type: "run", runId: grandparentRunId },
988 createdBy: "user",
989 creationSource: "web",
990 });
991 yield* writeImportedHistory(parentId, "PARENT_IMPORTED_MARKER");
992 yield* writeParentRun({
993 threadId: parentId,
994 runId: RunId.make("side-chat-rewound-parent-run"),
995 ordinal: 1,
996 status: "rolled_back",
997 text: "PARENT_ROLLED_BACK_MARKER",
998 });
999 yield* writeParentRun({
1000 threadId: parentId,
1001 runId: RunId.make("side-chat-busy-parent-run"),
1002 ordinal: 2,
1003 status: "running",
1004 text: "PARENT_RUNNING_MARKER",
1005 });
1006 yield* writeParentRun({
1007 threadId: parentId,
1008 runId: RunId.make("side-chat-queued-parent-run"),
1009 ordinal: 3,
1010 status: "queued",
1011 text: "PARENT_QUEUED_MARKER",
1012 });
1013 const fork = (commandId: string, sourceThreadId: ThreadId, targetThreadId: ThreadId) =>
1014 orchestrator.dispatch({
1015 type: "thread.fork",
1016 commandId: CommandId.make(commandId),
1017 sourceThreadId,
1018 targetThreadId,
1019 sourcePoint: { type: "latest_stable" },
1020 sideChat: true,
1021 createdBy: "user",
1022 creationSource: "web",
1023 });
1024​
1025 yield* fork("side-chat-busy-fork", parentId, sideChatId);
1026 const created = yield* orchestrator.getThreadProjection(sideChatId);
1027 assert.isTrue(created.thread.lineage.sideChat);
1028 assert.equal(created.thread.runtimeMode, "approval-required");
1029 assert.isNull(created.thread.forkedFrom);
1030 assert.deepEqual(created.contextTransfers[0]?.sourcePoint, { threadId: parentId });
1031​
1032 const nested = yield* fork(
1033 "side-chat-busy-nested",
1034 sideChatId,
1035 ThreadId.make("side-chat-busy-nested"),
1036 ).pipe(Effect.flip);
1037 assert.equal(nested._tag, "OrchestratorDispatchError");
1038 // Either would take the side chat's lock before the parent's, against the delete cascade.
1039 const ontoParent = yield* fork("side-chat-busy-onto-parent", sideChatId, parentId).pipe(
1040 Effect.flip,
1041 );
1042 assert.equal(ontoParent._tag, "OrchestratorThreadAlreadyExistsError");
1043 const ontoExisting = yield* fork("side-chat-busy-onto-existing", parentId, sideChatId).pipe(
1044 Effect.flip,
1045 );
1046 assert.equal(ontoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1047 const plainOntoExisting = yield* orchestrator
1048 .dispatch({
1049 type: "thread.fork",
1050 commandId: CommandId.make("side-chat-busy-plain-onto-existing"),
1051 sourceThreadId: parentId,
1052 targetThreadId: sideChatId,
1053 sourcePoint: { type: "latest_stable" },
1054 createdBy: "user",
1055 creationSource: "web",
1056 })
1057 .pipe(Effect.flip);
1058 assert.equal(plainOntoExisting._tag, "OrchestratorThreadAlreadyExistsError");
1059 const busyMergeBack = yield* orchestrator
1060 .dispatch({
1061 type: "thread.merge_back",
1062 commandId: CommandId.make("side-chat-busy-merge-back"),
1063 sourceThreadId: sideChatId,
1064 targetThreadId: parentId,
1065 sourcePoint: { type: "latest_stable" },
1066 createdBy: "user",
1067 creationSource: "web",
1068 })
1069 .pipe(Effect.flip);
1070 assert.include(String(busyMergeBack.cause), "active work");
1071​
1072 yield* orchestrator.dispatch({
1073 type: "message.dispatch",
1074 commandId: CommandId.make("side-chat-busy-first-message"),
1075 threadId: sideChatId,
1076 messageId: MessageId.make("side-chat-busy-first-message"),
1077 text: "What is the main thread doing?",
1078 attachments: [],
1079 dispatchMode: { type: "start_immediately" },
1080 createdBy: "user",
1081 creationSource: "web",
1082 });
1083 const started = yield* orchestrator.getThreadProjection(sideChatId);
1084 const [handoff] = started.contextHandoffs;
1085 assert.lengthOf(started.contextHandoffs, 1);
1086 assert.deepEqual(started.contextTransfers[0]?.resolution, {
1087 strategy: "portable_context",
1088 contextHandoffId: handoff!.id,
1089 });
1090 assert.include(handoff!.summaryText, "You are in a side chat beside the main thread.");
1091 // Inherited rows come first, so the cap truncates them first.
1092 assert.isAbove(
1093 handoff!.summaryText.indexOf("- User: PARENT_IMPORTED_MARKER"),
1094 handoff!.summaryText.indexOf("- User: GRANDPARENT_MARKER"),
1095 );
1096 assert.include(handoff!.summaryText, "- User: GRANDPARENT_MARKER");
1097 assert.notInclude(handoff!.summaryText, "PARENT_ROLLED_BACK_MARKER");
1098 assert.notInclude(handoff!.summaryText, "PARENT_QUEUED_MARKER");
1099 assert.include(handoff!.summaryText, "- User: PARENT_IMPORTED_MARKER");
1100 assert.include(handoff!.summaryText, "- User: PARENT_RUNNING_MARKER");
1101 assert.include(handoff!.summaryText, `t3_thread_read on thread ${parentId}`);
1102 assert.equal(
1103 started.messages.find((message) => message.role === "user")?.text,
1104 "What is the main thread doing?",
1105 );
1106​
1107 yield* orchestrator.dispatch({
1108 type: "thread.delete",
1109 commandId: CommandId.make("side-chat-busy-delete-parent"),
1110 threadId: parentId,
1111 });
1112 assert.isNotNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
1113 }).pipe(Effect.provide(forkCases[0]!.layer)),
1115​
1116it.effect("merge-back rejects a second fork's context until the first is consumed", () =>
1117 Effect.gen(function* () {
1118 const orchestrator = yield* Orchestrator.OrchestratorV2;
1119 const parentId = ThreadId.make("merge-back-guard-parent");
1120 const parentRunId = RunId.make("merge-back-guard-parent-run");
1121 yield* createParent(parentId);
1122 yield* writeParentRun({
1123 threadId: parentId,
1124 runId: parentRunId,
1125 ordinal: 1,
1126 status: "completed",
1127 text: "Parent work",
1128 });
1129 const forkAndRun = (name: string) =>
1130 Effect.gen(function* () {
1131 const threadId = ThreadId.make(`merge-back-guard-${name}`);
1132 const runId = RunId.make(`merge-back-guard-${name}-run`);
1133 yield* orchestrator.dispatch({
1134 type: "thread.fork",
1135 commandId: CommandId.make(`merge-back-guard-fork-${name}`),
1136 sourceThreadId: parentId,
1137 targetThreadId: threadId,
1138 sourcePoint: { type: "run", runId: parentRunId },
1139 sideChat: true,
1140 createdBy: "user",
1141 creationSource: "web",
1142 });
1143 yield* writeParentRun({ threadId, runId, ordinal: 1, status: "completed", text: name });
1144 return { threadId, runId };
1145 });
1146 const mergeBack = (commandId: string, fork: { threadId: ThreadId; runId: RunId }) =>
1147 orchestrator.dispatch({
1148 type: "thread.merge_back",
1149 commandId: CommandId.make(commandId),
1150 sourceThreadId: fork.threadId,
1151 targetThreadId: parentId,
1152 sourcePoint: { type: "run", runId: fork.runId },
1153 createdBy: "user",
1154 creationSource: "web",
1155 });
1156 const first = yield* forkAndRun("first");
1157 const second = yield* forkAndRun("second");
1158​
1159 yield* mergeBack("merge-back-guard-first", first);
1160 const rejected = yield* mergeBack("merge-back-guard-second", second).pipe(Effect.flip);
1161 assert.include(String(rejected.cause), "pending context from another side chat or fork");
1162 yield* mergeBack("merge-back-guard-first-again", first);
1163 // That pending merge-back targets the parent, so it does not block one into `first`.
1164 const nested = { threadId: ThreadId.make("merge-back-guard-nested") };
1165 const nestedRunId = RunId.make("merge-back-guard-nested-run");
1166 yield* orchestrator.dispatch({
1167 type: "thread.fork",
1168 commandId: CommandId.make("merge-back-guard-fork-nested"),
1169 sourceThreadId: first.threadId,
1170 targetThreadId: nested.threadId,
1171 sourcePoint: { type: "run", runId: first.runId },
1172 createdBy: "user",
1173 creationSource: "web",
1174 });
1175 yield* writeParentRun({
1176 threadId: nested.threadId,
1177 runId: nestedRunId,
1178 ordinal: 1,
1179 status: "completed",
1180 text: "nested",
1181 });
1182 yield* orchestrator.dispatch({
1183 type: "thread.merge_back",
1184 commandId: CommandId.make("merge-back-guard-nested"),
1185 sourceThreadId: nested.threadId,
1186 targetThreadId: first.threadId,
1187 sourcePoint: { type: "run", runId: nestedRunId },
1188 createdBy: "user",
1189 creationSource: "web",
1190 });
1191​
1192 const parent = yield* orchestrator.getThreadProjection(parentId);
1193 assert.deepEqual(
1194 parent.contextTransfers
1195 .filter((transfer) => transfer.type === "merge_back")
1196 .map((transfer) => [transfer.sourceThreadId, transfer.status]),
1198 [first.threadId, "superseded"],
1199 [first.threadId, "pending"],
1200 ],
1201 );
1202 }).pipe(Effect.provide(forkCases[0]!.layer)),