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

ThreadFork.execution.test.ts

398 lines14.2 KB

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 = (["codex", "claudeAgent"] as const).flatMap((driverName) => {
30 const driver = ProviderDriverKind.make(driverName);
31 const instanceId = ProviderInstanceId.make(driver);
32 const modelSelection = { instanceId, model: "test-model" };
33 const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
34 instanceId,
35 driver,
36 getCapabilities: () =>
37 Effect.succeed(
38 driver === "codex" ? CodexProviderCapabilitiesV2 : ClaudeProviderCapabilitiesV2,
39 ),
40 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
41 openSession: () => Effect.die("Execution is paused after dispatch for handoff inspection"),
42 };
43 const layer = ProviderReplayHarness.layerWithRegistry(
44 { name: `fork-boundary-${driver}` },
45 ProviderAdapterRegistry.layerFromAdapters([adapter]),
46 { runEffectWorker: false },
47 );
48​
49 return (["failed", "interrupted", "cancelled"] as const).map((status) => ({
50 driver,
51 status,
52 instanceId,
53 modelSelection,
54 layer,
55 }));
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);