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 EventSink from "./EventSink.ts";
24import * as Orchestrator from "./Orchestrator.ts";
25import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
26import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
27import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
28
29const forkCases = (
30 [
31 ["codex", "interrupted"],
32 ["claudeAgent", "failed"],
33 ] as const
34).map(([driverName, status]) => {
35 const driver = ProviderDriverKind.make(driverName);
36 const instanceId = ProviderInstanceId.make(driver);
37 const modelSelection = { instanceId, model: "test-model" };
38 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
39 instanceId,
40 driver,
41 getCapabilities: () =>
42 Effect.succeed(
43 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
44 ),
45 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
46 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
47 };
48 const layer = ProviderReplayHarness.layerWithRegistry(
49 { name: `fork-boundary-${driver}` },
50 ProviderAdapterRegistry.layerFromAdapters([adapter]),
51 { runEffectWorker: false },
52 );
53
54 return { driver, status, instanceId, modelSelection, layer };
55});
56
57it.effect("a persisted fork leaves PR watching with its parent until explicitly opted in", () =>
58 Effect.gen(function* () {
59 const orchestrator = yield* Orchestrator.OrchestratorV2;
60 const eventSink = yield* EventSink.EventSinkV2;
61 const now = yield* DateTime.now;
62 const { instanceId, modelSelection } = forkCases[0]!;
63 const sourceThreadId = ThreadId.make("fork-watch-source");
64 const targetThreadId = ThreadId.make("fork-watch-target");
65 const sourceRunId = RunId.make("fork-watch-source-run");
66 const key = { host: "github.com", repository: "example/repo", number: 1 };
67 const link = { url: "https://github.com/example/repo/pull/1", source: "agent" as const };
68
69 yield* orchestrator.dispatch({
70 type: "thread.create",
71 commandId: CommandId.make("fork-watch-create"),
72 threadId: sourceThreadId,
73 projectId: ProjectId.make("fork-watch-project"),
74 title: "Watching source",
75 modelSelection,
76 runtimeMode: "full-access",
77 interactionMode: "default",
78 branch: null,
79 worktreePath: null,
80 createdBy: "user",
81 creationSource: "web",
82 });
83 yield* eventSink.write({
84 events: [
85 {
86 id: EventId.make("fork-watch-source-run"),
87 type: "run.created",
88 threadId: sourceThreadId,
89 runId: sourceRunId,
90 occurredAt: now,
91 payload: {
92 id: sourceRunId,
93 threadId: sourceThreadId,
94 ordinal: 1,
95 providerInstanceId: instanceId,
96 modelSelection,
97 providerThreadId: null,
98 userMessageId: MessageId.make("fork-watch-source-message"),
99 rootNodeId: null,
100 activeAttemptId: null,
101 status: "completed",
102 requestedAt: now,
103 startedAt: now,
104 completedAt: now,
105 checkpointId: null,
106 contextHandoffId: null,
107 },
108 },
109 ],
110 });
111 yield* orchestrator.dispatch({
112 type: "thread.pull-request.watch",
113 commandId: CommandId.make("fork-watch-parent-start"),
114 threadId: sourceThreadId,
115 ...key,
116 watching: true,
117 link,
118 });
119 const parentBefore = yield* orchestrator.getThreadShell(sourceThreadId);
120 const parentWatch = parentBefore?.pullRequests?.[0]?.watch;
121 assert.isDefined(parentWatch);
122 assert.lengthOf(parentBefore?.pendingBackgroundTasks ?? [], 1);
123
124 yield* orchestrator.dispatch({
125 type: "thread.fork",
126 commandId: CommandId.make("fork-watch-fork"),
127 sourceThreadId,
128 targetThreadId,
129 sourcePoint: { type: "run", runId: sourceRunId },
130 createdBy: "user",
131 creationSource: "mcp",
132 });
133 const fork = yield* orchestrator.getThreadShell(targetThreadId);
134 assert.isNotNull(fork);
135 assert.deepEqual(fork.pullRequests, [
136 {
137 ...key,
138 ...link,
139 linkedAt: parentWatch.startedAt,
140 snapshot: null,
141 stack: null,
142 },
143 ]);
144 assert.deepEqual(fork.pendingBackgroundTasks, []);
145 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
146
147 // A delayed watcher update cannot reinstate the parent's subscription on the fork.
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 // Advance virtual time only to distinguish the independent watch's start time.
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 // The fork remembers its own watch, never the parent's, so watching again resumes from it.
197 assert.deepEqual(stoppedFork?.pullRequests, [
198 { ...forkLink, endedWatch: watchingFork.pullRequests[0].watch },
199 ]);
200 assert.deepEqual(stoppedFork?.pendingBackgroundTasks, []);
201 assert.deepEqual(yield* orchestrator.getThreadShell(sourceThreadId), parentBefore);
202 }).pipe(Effect.provide(forkCases[0]!.layer)),
203);
204
205it.effect.each(forkCases)(
206 "bounds $driver context when continuing a fork of a $status run",
207 ({ driver, status, instanceId, modelSelection, layer }) =>
208 Effect.gen(function* () {
209 const orchestrator = yield* Orchestrator.OrchestratorV2;
210 const eventSink = yield* EventSink.EventSinkV2;
211 const now = yield* DateTime.now;
212 const sourceThreadId = ThreadId.make("fork-boundary-source");
213 const targetThreadId = ThreadId.make("fork-boundary-target");
214 const providerThreadId = ProviderThreadId.make("fork-boundary-native-thread");
215 const sourceRunId = RunId.make("fork-boundary-source-run");
216 const attemptId = RunAttemptId.make("interrupted-source-attempt");
217 const providerTurnId = ProviderTurnId.make("interrupted-source-turn");
218 const rootNodeId = NodeId.make("interrupted-source-root");
219
220 yield* orchestrator.dispatch({
221 type: "thread.create",
222 commandId: CommandId.make("create-source"),
223 threadId: sourceThreadId,
224 projectId: ProjectId.make("fork-boundary-project"),
225 title: "Fork boundary source",
226 modelSelection,
227 runtimeMode: "full-access",
228 interactionMode: "default",
229 branch: null,
230 worktreePath: null,
231 createdBy: "user",
232 creationSource: "web",
233 });
234 yield* eventSink.write({
235 events: [
236 {
237 id: EventId.make("source-provider-thread"),
238 type: "provider-thread.updated",
239 threadId: sourceThreadId,
240 occurredAt: now,
241 payload: {
242 id: providerThreadId,
243 driver,
244 providerInstanceId: instanceId,
245 providerSessionId: null,
246 appThreadId: sourceThreadId,
247 ownerNodeId: null,
248 nativeThreadRef: { driver, nativeId: "native-source", strength: "strong" },
249 nativeConversationHeadRef: null,
250 status: "idle",
251 firstRunOrdinal: 1,
252 lastRunOrdinal: 2,
253 handoffIds: [],
254 forkedFrom: null,
255 createdAt: now,
256 updatedAt: now,
257 },
258 },
259 ],
260 });
261 if (status === "interrupted") {
262 yield* eventSink.write({
263 events: [
264 {
265 id: EventId.make("source-attempt"),
266 type: "run-attempt.created",
267 threadId: sourceThreadId,
268 runId: sourceRunId,
269 occurredAt: now,
270 payload: {
271 id: attemptId,
272 runId: sourceRunId,
273 attemptOrdinal: 1,
274 rootNodeId,
275 providerInstanceId: instanceId,
276 providerThreadId,
277 providerTurnId,
278 reason: "initial",
279 status,
280 startedAt: now,
281 completedAt: now,
282 },
283 },
284 {
285 id: EventId.make("source-provider-turn"),
286 type: "provider-turn.updated",
287 threadId: sourceThreadId,
288 occurredAt: now,
289 payload: {
290 id: providerTurnId,
291 providerThreadId,
292 nodeId: rootNodeId,
293 runAttemptId: attemptId,
294 nativeTurnRef: { driver, nativeId: "turn:synthetic", strength: "weak" },
295 ordinal: 1,
296 status,
297 startedAt: now,
298 completedAt: now,
299 },
300 },
301 ],
302 });
303 }
304 for (const ordinal of [1, 2]) {
305 const runId = ordinal === 1 ? sourceRunId : RunId.make("later-run");
306 const messageId = MessageId.make(`source-message-${ordinal}`);
307 yield* eventSink.write({
308 events: [
309 {
310 id: EventId.make(`run-${ordinal}`),
311 type: "run.created",
312 threadId: sourceThreadId,
313 runId,
314 occurredAt: now,
315 payload: {
316 id: runId,
317 threadId: sourceThreadId,
318 ordinal,
319 providerInstanceId: instanceId,
320 modelSelection,
321 providerThreadId,
322 userMessageId: messageId,
323 rootNodeId: null,
324 activeAttemptId: ordinal === 1 && status === "interrupted" ? attemptId : null,
325 status: ordinal === 1 ? status : "completed",
326 queuePosition: null,
327 requestedAt: now,
328 startedAt: now,
329 completedAt: now,
330 checkpointId: null,
331 contextHandoffId: null,
332 },
333 },
334 {
335 id: EventId.make(`item-${ordinal}`),
336 type: "turn-item.updated",
337 threadId: sourceThreadId,
338 runId,
339 occurredAt: now,
340 payload: {
341 id: TurnItemId.make(`item-${ordinal}`),
342 threadId: sourceThreadId,
343 runId,
344 nodeId: null,
345 providerThreadId,
346 providerTurnId: null,
347 nativeItemRef: null,
348 parentItemId: null,
349 ordinal,
350 status: "completed",
351 title: null,
352 startedAt: now,
353 completedAt: now,
354 updatedAt: now,
355 type: "user_message",
356 createdBy: "user",
357 creationSource: "web",
358 inputIntent: "turn_start",
359 messageId,
360 text: ordinal === 1 ? "INCLUDED_SOURCE_MARKER" : "EXCLUDED_LATER_MARKER",
361 attachments: [],
362 },
363 },
364 ],
365 });
366 }
367 yield* orchestrator.dispatch({
368 type: "thread.fork",
369 commandId: CommandId.make("fork-source"),
370 sourceThreadId,
371 targetThreadId,
372 sourcePoint: { type: "run", runId: sourceRunId },
373 createdBy: "user",
374 creationSource: "web",
375 });
376 yield* orchestrator.dispatch({
377 type: "message.dispatch",
378 commandId: CommandId.make("continue-fork"),
379 threadId: targetThreadId,
380 messageId: MessageId.make("continue-fork"),
381 text: "Continue from the selected source run",
382 attachments: [],
383 modelSelection,
384 dispatchMode: { type: "start_immediately" },
385 createdBy: "user",
386 creationSource: "web",
387 });
388 const target = yield* orchestrator.getThreadProjection(targetThreadId);
389 assert.equal(target.contextTransfers[0]?.resolution?.strategy, "portable_context");
390 assert.lengthOf(target.contextHandoffs, 1);
391 const handoff = target.contextHandoffs[0]!;
392 const history = handoff.history?.messages.map((message) => message.text).join("\n") ?? "";
393 assert.include(`${handoff.summaryText}\n${history}`, "INCLUDED_SOURCE_MARKER");
394 assert.notInclude(`${handoff.summaryText}\n${history}`, "EXCLUDED_LATER_MARKER");
395 assert.isNull(target.providerThreads[0]?.forkedFrom);
396 }).pipe(Effect.provide(layer)),
397);