Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderThreadId,
11 ProviderTurnId,
12 RunAttemptId,
13 RunId,
14 ThreadId,
15 TurnItemId,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as TestClock from "effect/testing/TestClock";
20
21import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
22import { ClaudeProviderCapabilitiesV2 } from "./Adapters/ClaudeAdapterV2.ts";
23import * as EffectWorker from "./EffectWorker.ts";
24import * as EventSink from "./EventSink.ts";
25import * as Orchestrator from "./Orchestrator.ts";
26import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
27import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
28import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
29
30const forkCases = (
31 [
32 ["codex", "interrupted"],
33 ["claudeAgent", "failed"],
34 ] as const
35).map(([driverName, status]) => {
36 const driver = ProviderDriverKind.make(driverName);
37 const instanceId = ProviderInstanceId.make(driver);
38 const modelSelection = { instanceId, model: "test-model" };
39 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
40 instanceId,
41 driver,
42 getCapabilities: () =>
43 Effect.succeed(
44 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
45 ),
46 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
47 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
48 };
49 const layer = ProviderReplayHarness.layerWithRegistry(
50 { name: `fork-boundary-${driver}` },
51 ProviderAdapterRegistry.layerFromAdapters([adapter]),
52 { runEffectWorker: false },
53 );
54
55 return { driver, status, instanceId, modelSelection, layer };
56});
57
58it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
59 Effect.gen(function* () {
60 const orchestrator = yield* Orchestrator.OrchestratorV2;
61 const eventSink = yield* EventSink.EventSinkV2;
62 const now = yield* DateTime.now;
63 const { instanceId, modelSelection } = forkCases[0]!;
64 const sourceThreadId = ThreadId.make("fork-watch-source");
65 const targetThreadId = ThreadId.make("fork-watch-target");
66 const sourceRunId = RunId.make("fork-watch-source-run");
67 const key = { host: "github.com", repository: "example/repo", number: 1 };
68 const link = { url: "https://github.com/example/repo/pull/1", source: "agent" as const };
69
70 yield* orchestrator.dispatch({
71 type: "thread.create",
72 commandId: CommandId.make("fork-watch-create"),
73 threadId: sourceThreadId,
74 projectId: ProjectId.make("fork-watch-project"),
75 title: "Watching source",
76 modelSelection,
77 runtimeMode: "full-access",
78 interactionMode: "default",
79 branch: null,
80 worktreePath: null,
81 createdBy: "user",
82 creationSource: "web",
83 });
84 yield* eventSink.write({
85 events: [
86 {
87 id: EventId.make("fork-watch-source-run"),
88 type: "run.created",
89 threadId: sourceThreadId,
90 runId: sourceRunId,
91 occurredAt: now,
92 payload: {
93 id: sourceRunId,
94 threadId: sourceThreadId,
95 ordinal: 1,
96 providerInstanceId: instanceId,
97 modelSelection,
98 providerThreadId: null,
99 userMessageId: MessageId.make("fork-watch-source-message"),
100 rootNodeId: null,
101 activeAttemptId: null,
102 status: "completed",
103 requestedAt: now,
104 startedAt: now,
105 completedAt: now,
106 checkpointId: null,
107 contextHandoffId: null,
108 },
109 },
110 ],
111 });
112 yield* orchestrator.dispatch({
113 type: "thread.pull-request.watch",
114 commandId: CommandId.make("fork-watch-parent-start"),
115 threadId: sourceThreadId,
116 ...key,
117 watching: true,
118 link,
119 });
120 const parentBefore = yield* orchestrator.getThreadShell(sourceThreadId);
121 const parentWatch = parentBefore?.pullRequests?.[0]?.watch;
122 assert.isDefined(parentWatch);
123 assert.lengthOf(parentBefore?.pendingBackgroundTasks ?? [], 1);
124
125 yield* orchestrator.dispatch({
126 type: "thread.fork",
127 commandId: CommandId.make("fork-watch-fork"),
128 sourceThreadId,
129 targetThreadId,
130 sourcePoint: { type: "run", runId: sourceRunId },
131 createdBy: "user",
132 creationSource: "mcp",
133 });
134 const fork = yield* orchestrator.getThreadShell(targetThreadId);
135 assert.isNotNull(fork);
136 assert.deepEqual(fork.pullRequests, [
137 {
138 ...key,
139 ...link,
140 linkedAt: parentWatch.startedAt,
141 snapshot: null,
142 stack: null,
143 },
144 ]);
145 assert.deepEqual(fork.pendingBackgroundTasks, []);
146 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
147
148 // A delayed watcher update cannot reinstate the parent's subscription on the fork.
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 // Advance virtual time only to distinguish the independent watch's start time.
172 yield* TestClock.adjust("1 second");
173 yield* orchestrator.dispatch({
174 type: "thread.pull-request.watch",
175 commandId: CommandId.make("fork-watch-opt-in"),
176 threadId: targetThreadId,
177 ...key,
178 watching: true,
179 link,
180 });
181 const watchingFork = yield* orchestrator.getThreadShell(targetThreadId);
182 assert.isDefined(watchingFork?.pullRequests?.[0]?.watch);
183 assert.notEqual(watchingFork.pullRequests[0].watch.startedAt, parentWatch.startedAt);
184 assert.lengthOf(watchingFork.pendingBackgroundTasks ?? [], 1);
185 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
186
187 yield* orchestrator.dispatch({
188 type: "thread.pull-request.watch",
189 commandId: CommandId.make("fork-watch-opt-out"),
190 threadId: targetThreadId,
191 ...key,
192 watching: false,
193 });
194 const stoppedFork = yield* orchestrator.getThreadShell(targetThreadId);
195 const [forkLink] = fork.pullRequests ?? [];
196 assert.isDefined(forkLink);
197 // The fork remembers its own watch, never the parent's, so watching again resumes from it.
198 assert.deepEqual(stoppedFork?.pullRequests, [
199 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
200 ]);
201 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
202 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
203 }).pipe(Effect.provide(forkCases[0]!.layer)),
204);
205
206it.effect.each(forkCases)(
207 "bounds $driver context when continuing a fork of a $status run",
208 ({ driver, status, instanceId, modelSelection, layer }) =>
209 Effect.gen(function* () {
210 const orchestrator = yield* Orchestrator.OrchestratorV2;
211 const eventSink = yield* EventSink.EventSinkV2;
212 const now = yield* DateTime.now;
213 const sourceThreadId = ThreadId.make("fork-boundary-source");
214 const targetThreadId = ThreadId.make("fork-boundary-target");
215 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
216 const sourceRunId = RunId.make("fork-boundary-source-run");
217 const attemptId = RunAttemptId.make("interrupted-source-attempt");
218 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
219 const rootNodeId = NodeId.make("interrupted-source-root");
220
221 yield* orchestrator.dispatch({
222 type: "thread.create",
223 commandId: CommandId.make("create-source"),
224 threadId: sourceThreadId,
225 projectId: ProjectId.make("fork-boundary-project"),
226 title: "Fork boundary source",
227 modelSelection,
228 runtimeMode: "full-access",
229 interactionMode: "default",
230 branch: null,
231 worktreePath: null,
232 createdBy: "user",
233 creationSource: "web",
234 });
235 yield* eventSink.write({
236 events: [
237 {
238 id: EventId.make("source-provider-thread"),
239 type: "provider-thread.updated",
240 threadId: sourceThreadId,
241 occurredAt: now,
242 payload: {
243 id: providerThreadId,
244 driver,
245 providerInstanceId: instanceId,
246 providerSessionId: null,
247 appThreadId: sourceThreadId,
248 ownerNodeId: null,
249 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
250 nativeConversationHeadRef: null,
251 status: "idle",
252 firstRunOrdinal: 1,
253 lastRunOrdinal: 2,
254 handoffIds: [],
255 forkedFrom: null,
256 createdAt: now,
257 updatedAt: now,
258 },
259 },
260 ],
261 });
262 if (status === "interrupted") {
263 yield* eventSink.write({
264 events: [
265 {
266 id: EventId.make("source-attempt"),
267 type: "run-attempt.created",
268 threadId: sourceThreadId,
269 runId: sourceRunId,
270 occurredAt: now,
271 payload: {
272 id: attemptId,
273 runId: sourceRunId,
274 attemptOrdinal: 1,
275 rootNodeId,
276 providerInstanceId: instanceId,
277 providerThreadId,
278 providerTurnId,
279 reason: "initial",
280 status,
281 startedAt: now,
282 completedAt: now,
283 },
284 },
285 {
286 id: EventId.make("source-provider-turn"),
287 type: "provider-turn.updated",
288 threadId: sourceThreadId,
289 occurredAt: now,
290 payload: {
291 id: providerTurnId,
292 providerThreadId,
293 nodeId: rootNodeId,
294 runAttemptId: attemptId,
295 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
296 ordinal: 1,
297 status,
298 startedAt: now,
299 completedAt: now,
300 },
301 },
302 ],
303 });
304 }
305 for (const ordinal of [1, 2]) {
306 const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
307 const messageId = MessageId.make(`source-message-${ordinal}`);
308 yield* eventSink.write({
309 events: [
310 {
311 id: EventId.make(`run-${ordinal}`),
312 type: "run.created",
313 threadId: sourceThreadId,
314 runId,
315 occurredAt: now,
316 payload: {
317 id: runId,
318 threadId: sourceThreadId,
319 ordinal,
320 providerInstanceId: instanceId,
321 modelSelection,
322 providerThreadId,
323 userMessageId: messageId,
324 rootNodeId: null,
325 activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
326 status: ordinal === 1 ? status : "completed",
327 queuePosition: null,
328 requestedAt: now,
329 startedAt: now,
330 completedAt: now,
331 checkpointId: null,
332 contextHandoffId: null,
333 },
334 },
335 {
336 id: EventId.make(`item-${ordinal}`),
337 type: "turn-item.updated",
338 threadId: sourceThreadId,
339 runId,
340 occurredAt: now,
341 payload: {
342 id: TurnItemId.make(`item-${ordinal}`),
343 threadId: sourceThreadId,
344 runId,
345 nodeId: null,
346 providerThreadId,
347 providerTurnId: null,
348 nativeItemRef: null,
349 parentItemId: null,
350 ordinal,
351 status: "completed",
352 title: null,
353 startedAt: now,
354 completedAt: now,
355 updatedAt: now,
356 type: "user_message",
357 createdBy: "user",
358 creationSource: "web",
359 inputIntent: "turn_start",
360 messageId,
361 text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
362 attachments: [],
363 },
364 },
365 ],
366 });
367 }
368 yield* orchestrator.dispatch({
369 type: "thread.fork",
370 commandId: CommandId.make("fork-source"),
371 sourceThreadId,
372 targetThreadId,
373 sourcePoint: { type: "run", runId: sourceRunId },
374 createdBy: "user",
375 creationSource: "web",
376 });
377 yield* orchestrator.dispatch({
378 type: "message.dispatch",
379 commandId: CommandId.make("continue-fork"),
380 threadId: targetThreadId,
381 messageId: MessageId.make("continue-fork"),
382 text: "Continue from the selected source run",
383 attachments: [],
384 modelSelection,
385 dispatchMode: { type: "start_immediately" },
386 createdBy: "user",
387 creationSource: "web",
388 });
389 const target = yield* orchestrator.getThreadProjection(targetThreadId);
390 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
391 assert.lengthOf(target.contextHandoffs, 1);
392 const handoff = target.contextHandoffs[0]!;
393 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
394 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
395 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
396 assert.isNull(target.providerThreads[0]?.forkedFrom);
397 }).pipe(Effect.provide(layer)),
398);
399
400it.effect.each([
401 { execution: "portable_context", rejected: true },
402 { execution: "native_fork", rejected: false },
403] as const)(
404 "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
405 ({ execution, rejected }) => {
406 const opened: Array<ProviderInstanceId> = [];
407 const adapter = (driverName: "claudeAgent" | "codex") => {
408 const driver = ProviderDriverKind.make(driverName);
409 const instanceId = ProviderInstanceId.make(driverName);
410 return {
411 instanceId,
412 driver,
413 getCapabilities: () =>
414 Effect.succeed(
415 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
416 ),
417 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
418 openSession: (input) =>
419 Effect.sync(() => opened.push(instanceId)).pipe(
420 Effect.andThen(
421 new ProviderAdapter.ProviderAdapterOpenSessionError({
422 driver,
423 providerSessionId: input.providerSessionId,
424 }),
425 ),
426 ),
427 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
428 };
429 const claude = adapter("claudeAgent");
430 const target = execution === "portable_context" ? adapter("codex") : claude;
431 return Effect.gen(function* () {
432 const orchestrator = yield* Orchestrator.OrchestratorV2;
433 const eventSink = yield* EventSink.EventSinkV2;
434 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
435 const now = yield* DateTime.now;
436 const sourceThreadId = ThreadId.make("fork-compact-source");
437 const targetThreadId = ThreadId.make("fork-compact-target");
438 const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
439 const sourceRunId = RunId.make("fork-compact-source-run");
440 const userMessageId = MessageId.make("fork-compact-source-message");
441 const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
442
443 yield* orchestrator.dispatch({
444 type: "thread.create",
445 commandId: CommandId.make("fork-compact-create-source"),
446 threadId: sourceThreadId,
447 projectId: ProjectId.make("fork-compact-project"),
448 title: "Fork compact source",
449 modelSelection: sourceSelection,
450 runtimeMode: "full-access",
451 interactionMode: "default",
452 branch: null,
453 worktreePath: null,
454 createdBy: "user",
455 creationSource: "web",
456 });
457 const item = {
458 threadId: sourceThreadId,
459 runId: sourceRunId,
460 nodeId: null,
461 providerThreadId,
462 providerTurnId: null,
463 nativeItemRef: null,
464 parentItemId: null,
465 status: "completed",
466 title: null,
467 startedAt: now,
468 completedAt: now,
469 updatedAt: now,
470 } as const;
471 yield* eventSink.write({
472 events: [
473 {
474 id: EventId.make("fork-compact-provider-thread"),
475 type: "provider-thread.updated",
476 threadId: sourceThreadId,
477 occurredAt: now,
478 payload: {
479 id: providerThreadId,
480 driver: claude.driver,
481 providerInstanceId: claude.instanceId,
482 providerSessionId: null,
483 appThreadId: sourceThreadId,
484 ownerNodeId: null,
485 nativeThreadRef: {
486 driver: claude.driver,
487 nativeId: "native-fork-compact-source",
488 strength: "strong",
489 },
490 nativeConversationHeadRef: null,
491 status: "idle",
492 firstRunOrdinal: 1,
493 lastRunOrdinal: 1,
494 handoffIds: [],
495 forkedFrom: null,
496 createdAt: now,
497 updatedAt: now,
498 },
499 },
500 {
501 id: EventId.make("fork-compact-source-run"),
502 type: "run.created",
503 threadId: sourceThreadId,
504 runId: sourceRunId,
505 occurredAt: now,
506 payload: {
507 id: sourceRunId,
508 threadId: sourceThreadId,
509 ordinal: 1,
510 providerInstanceId: claude.instanceId,
511 modelSelection: sourceSelection,
512 providerThreadId,
513 userMessageId,
514 rootNodeId: null,
515 activeAttemptId: null,
516 status: "completed",
517 queuePosition: null,
518 requestedAt: now,
519 startedAt: now,
520 completedAt: now,
521 checkpointId: null,
522 contextHandoffId: null,
523 },
524 },
525 // Each message alone exceeds the default 16k handoff budget, so a
526 // portable handoff omits both whole items.
527 {
528 id: EventId.make("fork-compact-user-item"),
529 type: "turn-item.updated",
530 threadId: sourceThreadId,
531 runId: sourceRunId,
532 occurredAt: now,
533 payload: {
534 ...item,
535 id: TurnItemId.make("fork-compact-user-item"),
536 ordinal: 1,
537 type: "user_message",
538 createdBy: "user",
539 creationSource: "web",
540 inputIntent: "turn_start",
541 messageId: userMessageId,
542 text: "u".repeat(17_000),
543 attachments: [],
544 },
545 },
546 {
547 id: EventId.make("fork-compact-assistant-item"),
548 type: "turn-item.updated",
549 threadId: sourceThreadId,
550 runId: sourceRunId,
551 occurredAt: now,
552 payload: {
553 ...item,
554 id: TurnItemId.make("fork-compact-assistant-item"),
555 ordinal: 2,
556 type: "assistant_message",
557 messageId: MessageId.make("fork-compact-assistant-message"),
558 text: "a".repeat(17_000),
559 streaming: false,
560 },
561 },
562 ],
563 });
564 yield* orchestrator.dispatch({
565 type: "thread.fork",
566 commandId: CommandId.make("fork-compact-fork"),
567 sourceThreadId,
568 targetThreadId,
569 sourcePoint: { type: "run", runId: sourceRunId },
570 createdBy: "user",
571 creationSource: "web",
572 });
573 yield* orchestrator.dispatch({
574 type: "message.dispatch",
575 commandId: CommandId.make("fork-compact-compact"),
576 threadId: targetThreadId,
577 messageId: MessageId.make("fork-compact-compact"),
578 text: "/compact",
579 attachments: [],
580 modelSelection: { instanceId: target.instanceId, model: "test-model" },
581 dispatchMode: { type: "start_immediately" },
582 createdBy: "user",
583 creationSource: "web",
584 });
585 yield* worker.drain();
586
587 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
588 if (execution === "portable_context") {
589 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
590 assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
591 } else {
592 assert.isEmpty(projection.contextHandoffs);
593 }
594 const emptyCompaction = projection.turnItems.some(
595 (turnItem) =>
596 turnItem.type === "error" &&
597 turnItem.failure.message === "Start a conversation before compacting this thread.",
598 );
599 assert.equal(emptyCompaction, rejected);
600 assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
601 }).pipe(
602 Effect.provide(
603 ProviderReplayHarness.layerWithRegistry(
604 { name: `fork-compact-${execution}` },
605 ProviderAdapterRegistry.layerFromAdapters(
606 target === claude ? [claude] : [claude, target],
607 ),
608 ),
609 ),
610 );
611 },
612);