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 const stale = yield* orchestrator
149 .dispatch({
150 type: "thread.pull-request-watch.sync",
151 commandId: CommandId.make("fork-watch-stale-sync"),
152 threadId: targetThreadId,
153 ...key,
154 startedAt: parentWatch.startedAt,
155 watch: parentWatch,
156 wake: {
157 messageId: MessageId.make("fork-watch-unwanted-wake"),
158 text: "A check failed",
159 notification: {
160 source: { kind: "monitor" },
161 outcome: "updated",
162 summary: "A check failed",
163 },
164 },
165 })
166 .pipe(Effect.flip);
167 assert.equal(stale._tag, "OrchestratorDispatchError");
168 assert.deepEqual((yield* orchestrator.getThreadProjection(targetThreadId)).runs, []);
169
170 yield* TestClock.adjust("1 second");
171 yield* orchestrator.dispatch({
172 type: "thread.pull-request.watch",
173 commandId: CommandId.make("fork-watch-opt-in"),
174 threadId: targetThreadId,
175 ...key,
176 watching: true,
177 link,
178 });
179 const watchingFork = yield* orchestrator.getThreadShell(targetThreadId);
180 assert.isDefined(watchingFork?.pullRequests?.[0]?.watch);
181 assert.notEqual(watchingFork.pullRequests[0].watch.startedAt, parentWatch.startedAt);
182 assert.lengthOf(watchingFork.pendingBackgroundTasks ?? [], 1);
183 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
184
185 yield* orchestrator.dispatch({
186 type: "thread.pull-request.watch",
187 commandId: CommandId.make("fork-watch-opt-out"),
188 threadId: targetThreadId,
189 ...key,
190 watching: false,
191 });
192 const stoppedFork = yield* orchestrator.getThreadShell(targetThreadId);
193 const [forkLink] = fork.pullRequests ?? [];
194 assert.isDefined(forkLink);
195 assert.deepEqual(stoppedFork?.pullRequests, [
196 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
197 ]);
198 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
199 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
200 }).pipe(Effect.provide(forkCases[0]!.layer)),
201);
202
203it.effect.each(forkCases)(
204 "bounds $driver context when continuing a fork of a $status run",
205 ({ driver, status, instanceId, modelSelection, layer }) =>
206 Effect.gen(function* () {
207 const orchestrator = yield* Orchestrator.OrchestratorV2;
208 const eventSink = yield* EventSink.EventSinkV2;
209 const now = yield* DateTime.now;
210 const sourceThreadId = ThreadId.make("fork-boundary-source");
211 const targetThreadId = ThreadId.make("fork-boundary-target");
212 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
213 const sourceRunId = RunId.make("fork-boundary-source-run");
214 const attemptId = RunAttemptId.make("interrupted-source-attempt");
215 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
216 const rootNodeId = NodeId.make("interrupted-source-root");
217
218 yield* orchestrator.dispatch({
219 type: "thread.create",
220 commandId: CommandId.make("create-source"),
221 threadId: sourceThreadId,
222 projectId: ProjectId.make("fork-boundary-project"),
223 title: "Fork boundary source",
224 modelSelection,
225 runtimeMode: "full-access",
226 interactionMode: "default",
227 branch: null,
228 worktreePath: null,
229 createdBy: "user",
230 creationSource: "web",
231 });
232 yield* eventSink.write({
233 events: [
234 {
235 id: EventId.make("source-provider-thread"),
236 type: "provider-thread.updated",
237 threadId: sourceThreadId,
238 occurredAt: now,
239 payload: {
240 id: providerThreadId,
241 driver,
242 providerInstanceId: instanceId,
243 providerSessionId: null,
244 appThreadId: sourceThreadId,
245 ownerNodeId: null,
246 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
247 nativeConversationHeadRef: null,
248 status: "idle",
249 firstRunOrdinal: 1,
250 lastRunOrdinal: 2,
251 handoffIds: [],
252 forkedFrom: null,
253 createdAt: now,
254 updatedAt: now,
255 },
256 },
257 ],
258 });
259 if (status === "interrupted") {
260 yield* eventSink.write({
261 events: [
262 {
263 id: EventId.make("source-attempt"),
264 type: "run-attempt.created",
265 threadId: sourceThreadId,
266 runId: sourceRunId,
267 occurredAt: now,
268 payload: {
269 id: attemptId,
270 runId: sourceRunId,
271 attemptOrdinal: 1,
272 rootNodeId,
273 providerInstanceId: instanceId,
274 providerThreadId,
275 providerTurnId,
276 reason: "initial",
277 status,
278 startedAt: now,
279 completedAt: now,
280 },
281 },
282 {
283 id: EventId.make("source-provider-turn"),
284 type: "provider-turn.updated",
285 threadId: sourceThreadId,
286 occurredAt: now,
287 payload: {
288 id: providerTurnId,
289 providerThreadId,
290 nodeId: rootNodeId,
291 runAttemptId: attemptId,
292 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
293 ordinal: 1,
294 status,
295 startedAt: now,
296 completedAt: now,
297 },
298 },
299 ],
300 });
301 }
302 for (const ordinal of [1, 2]) {
303 const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
304 const messageId = MessageId.make(`source-message-${ordinal}`);
305 yield* eventSink.write({
306 events: [
307 {
308 id: EventId.make(`run-${ordinal}`),
309 type: "run.created",
310 threadId: sourceThreadId,
311 runId,
312 occurredAt: now,
313 payload: {
314 id: runId,
315 threadId: sourceThreadId,
316 ordinal,
317 providerInstanceId: instanceId,
318 modelSelection,
319 providerThreadId,
320 userMessageId: messageId,
321 rootNodeId: null,
322 activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
323 status: ordinal === 1 ? status : "completed",
324 queuePosition: null,
325 requestedAt: now,
326 startedAt: now,
327 completedAt: now,
328 checkpointId: null,
329 contextHandoffId: null,
330 },
331 },
332 {
333 id: EventId.make(`item-${ordinal}`),
334 type: "turn-item.updated",
335 threadId: sourceThreadId,
336 runId,
337 occurredAt: now,
338 payload: {
339 id: TurnItemId.make(`item-${ordinal}`),
340 threadId: sourceThreadId,
341 runId,
342 nodeId: null,
343 providerThreadId,
344 providerTurnId: null,
345 nativeItemRef: null,
346 parentItemId: null,
347 ordinal,
348 status: "completed",
349 title: null,
350 startedAt: now,
351 completedAt: now,
352 updatedAt: now,
353 type: "user_message",
354 createdBy: "user",
355 creationSource: "web",
356 inputIntent: "turn_start",
357 messageId,
358 text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
359 attachments: [],
360 },
361 },
362 ],
363 });
364 }
365 yield* orchestrator.dispatch({
366 type: "thread.fork",
367 commandId: CommandId.make("fork-source"),
368 sourceThreadId,
369 targetThreadId,
370 sourcePoint: { type: "run", runId: sourceRunId },
371 createdBy: "user",
372 creationSource: "web",
373 });
374 yield* orchestrator.dispatch({
375 type: "message.dispatch",
376 commandId: CommandId.make("continue-fork"),
377 threadId: targetThreadId,
378 messageId: MessageId.make("continue-fork"),
379 text: "Continue from the selected source run",
380 attachments: [],
381 modelSelection,
382 dispatchMode: { type: "start_immediately" },
383 createdBy: "user",
384 creationSource: "web",
385 });
386 const target = yield* orchestrator.getThreadProjection(targetThreadId);
387 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
388 assert.lengthOf(target.contextHandoffs, 1);
389 const handoff = target.contextHandoffs[0]!;
390 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
391 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
392 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
393 assert.isNull(target.providerThreads[0]?.forkedFrom);
394 }).pipe(Effect.provide(layer)),
395);
396
397it.effect.each([
398 { execution: "portable_context", rejected: true },
399 { execution: "native_fork", rejected: false },
400] as const)(
401 "a $execution fork's first /compact is rejected only when no history reaches it: $rejected",
402 ({ execution, rejected }) => {
403 const opened: Array<ProviderInstanceId> = [];
404 const adapter = (driverName: "claudeAgent" | "codex") => {
405 const driver = ProviderDriverKind.make(driverName);
406 const instanceId = ProviderInstanceId.make(driverName);
407 return {
408 instanceId,
409 driver,
410 getCapabilities: () =>
411 Effect.succeed(
412 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
413 ),
414 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
415 openSession: (input) =>
416 Effect.sync(() => opened.push(instanceId)).pipe(
417 Effect.andThen(
418 new ProviderAdapter.ProviderAdapterOpenSessionError({
419 driver,
420 providerSessionId: input.providerSessionId,
421 }),
422 ),
423 ),
424 } satisfies ProviderAdapter.ProviderAdapterV2["Service"];
425 };
426 const claude = adapter("claudeAgent");
427 const target = execution === "portable_context" ? adapter("codex") : claude;
428 return Effect.gen(function* () {
429 const orchestrator = yield* Orchestrator.OrchestratorV2;
430 const eventSink = yield* EventSink.EventSinkV2;
431 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
432 const now = yield* DateTime.now;
433 const sourceThreadId = ThreadId.make("fork-compact-source");
434 const targetThreadId = ThreadId.make("fork-compact-target");
435 const providerThreadId = ProviderThreadId.make("fork-compact-native-thread");
436 const sourceRunId = RunId.make("fork-compact-source-run");
437 const userMessageId = MessageId.make("fork-compact-source-message");
438 const sourceSelection = { instanceId: claude.instanceId, model: "test-model" };
439
440 yield* orchestrator.dispatch({
441 type: "thread.create",
442 commandId: CommandId.make("fork-compact-create-source"),
443 threadId: sourceThreadId,
444 projectId: ProjectId.make("fork-compact-project"),
445 title: "Fork compact source",
446 modelSelection: sourceSelection,
447 runtimeMode: "full-access",
448 interactionMode: "default",
449 branch: null,
450 worktreePath: null,
451 createdBy: "user",
452 creationSource: "web",
453 });
454 const item = {
455 threadId: sourceThreadId,
456 runId: sourceRunId,
457 nodeId: null,
458 providerThreadId,
459 providerTurnId: null,
460 nativeItemRef: null,
461 parentItemId: null,
462 status: "completed",
463 title: null,
464 startedAt: now,
465 completedAt: now,
466 updatedAt: now,
467 } as const;
468 yield* eventSink.write({
469 events: [
470 {
471 id: EventId.make("fork-compact-provider-thread"),
472 type: "provider-thread.updated",
473 threadId: sourceThreadId,
474 occurredAt: now,
475 payload: {
476 id: providerThreadId,
477 driver: claude.driver,
478 providerInstanceId: claude.instanceId,
479 providerSessionId: null,
480 appThreadId: sourceThreadId,
481 ownerNodeId: null,
482 nativeThreadRef: {
483 driver: claude.driver,
484 nativeId: "native-fork-compact-source",
485 strength: "strong",
486 },
487 nativeConversationHeadRef: null,
488 status: "idle",
489 firstRunOrdinal: 1,
490 lastRunOrdinal: 1,
491 handoffIds: [],
492 forkedFrom: null,
493 createdAt: now,
494 updatedAt: now,
495 },
496 },
497 {
498 id: EventId.make("fork-compact-source-run"),
499 type: "run.created",
500 threadId: sourceThreadId,
501 runId: sourceRunId,
502 occurredAt: now,
503 payload: {
504 id: sourceRunId,
505 threadId: sourceThreadId,
506 ordinal: 1,
507 providerInstanceId: claude.instanceId,
508 modelSelection: sourceSelection,
509 providerThreadId,
510 userMessageId,
511 rootNodeId: null,
512 activeAttemptId: null,
513 status: "completed",
514 queuePosition: null,
515 requestedAt: now,
516 startedAt: now,
517 completedAt: now,
518 checkpointId: null,
519 contextHandoffId: null,
520 },
521 },
522 // Each message alone exceeds the default 16k handoff budget, so a
523 // portable handoff omits both whole items.
524 {
525 id: EventId.make("fork-compact-user-item"),
526 type: "turn-item.updated",
527 threadId: sourceThreadId,
528 runId: sourceRunId,
529 occurredAt: now,
530 payload: {
531 ...item,
532 id: TurnItemId.make("fork-compact-user-item"),
533 ordinal: 1,
534 type: "user_message",
535 createdBy: "user",
536 creationSource: "web",
537 inputIntent: "turn_start",
538 messageId: userMessageId,
539 text: "u".repeat(17_000),
540 attachments: [],
541 },
542 },
543 {
544 id: EventId.make("fork-compact-assistant-item"),
545 type: "turn-item.updated",
546 threadId: sourceThreadId,
547 runId: sourceRunId,
548 occurredAt: now,
549 payload: {
550 ...item,
551 id: TurnItemId.make("fork-compact-assistant-item"),
552 ordinal: 2,
553 type: "assistant_message",
554 messageId: MessageId.make("fork-compact-assistant-message"),
555 text: "a".repeat(17_000),
556 streaming: false,
557 },
558 },
559 ],
560 });
561 yield* orchestrator.dispatch({
562 type: "thread.fork",
563 commandId: CommandId.make("fork-compact-fork"),
564 sourceThreadId,
565 targetThreadId,
566 sourcePoint: { type: "run", runId: sourceRunId },
567 createdBy: "user",
568 creationSource: "web",
569 });
570 yield* orchestrator.dispatch({
571 type: "message.dispatch",
572 commandId: CommandId.make("fork-compact-compact"),
573 threadId: targetThreadId,
574 messageId: MessageId.make("fork-compact-compact"),
575 text: "/compact",
576 attachments: [],
577 modelSelection: { instanceId: target.instanceId, model: "test-model" },
578 dispatchMode: { type: "start_immediately" },
579 createdBy: "user",
580 creationSource: "web",
581 });
582 yield* worker.drain();
583
584 const projection = yield* orchestrator.getThreadProjection(targetThreadId);
585 if (execution === "portable_context") {
586 assert.equal(projection.contextTransfers[0]?.resolution?.strategy, "portable_context");
587 assert.deepEqual(projection.contextHandoffs[0]?.history?.messages, []);
588 } else {
589 assert.isEmpty(projection.contextHandoffs);
590 }
591 const emptyCompaction = projection.turnItems.some(
592 (turnItem) =>
593 turnItem.type === "error" &&
594 turnItem.failure.message === "Start a conversation before compacting this thread.",
595 );
596 assert.equal(emptyCompaction, rejected);
597 assert.deepEqual(opened, rejected ? [] : [target.instanceId]);
598 }).pipe(
599 Effect.provide(
600 ProviderReplayHarness.layerWithRegistry(
601 { name: `fork-compact-${execution}` },
602 ProviderAdapterRegistry.layerFromAdapters(
603 target === claude ? [claude] : [claude, target],
604 ),
605 ),
606 ),
607 );
608 },
609);