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

ThreadForkService.test.ts

379 lines12.6 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 ContextTransferId,
5 EnvironmentId,
6 MessageId,
7 type ModelSelection,
8 type OrchestrationV2AppThread,
9 type OrchestrationV2Run,
10 type OrchestrationV2ThreadProjection,
11 ProjectId,
12 ProviderInstanceId,
13 ProviderThreadId,
14 RunId,
15 ThreadId,
16 type ThreadPullRequestLink,
17} from "@t3tools/contracts";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20​
21import * as ThreadForkService from "./ThreadForkService.ts";
22​
23const sourceThreadId = ThreadId.make("thread:fork-snoozed-source");
24const targetThreadId = ThreadId.make("thread:fork-awake-target");
25const sourceRunId = RunId.make("run:fork-snoozed-source");
26const providerInstanceId = ProviderInstanceId.make("codex");
27const modelSelection = {
28 instanceId: providerInstanceId,
29 model: "gpt-5.4",
30} satisfies ModelSelection;
31const sourceCreatedAt = DateTime.makeUnsafe("2026-07-24T09:00:00.000Z");
32const snoozedAt = DateTime.makeUnsafe("2026-07-24T09:05:00.000Z");
33const snoozedUntil = DateTime.makeUnsafe("2026-07-25T09:00:00.000Z");
34const forkCreatedAt = DateTime.makeUnsafe("2026-07-24T09:10:00.000Z");
35​
36function makeSourceThread(): OrchestrationV2AppThread {
37 return {
38 createdBy: "user",
39 creationSource: "web",
40 id: sourceThreadId,
41 projectId: ProjectId.make("project:fork-snooze"),
42 title: "Snoozed source",
43 providerInstanceId,
44 modelSelection,
45 runtimeMode: "full-access",
46 interactionMode: "plan",
47 branch: "feature/source",
48 worktreePath: "/tmp/source-worktree",
49 activeProviderThreadId: ProviderThreadId.make("provider-thread:fork-snoozed-source"),
50 lineage: {
51 parentThreadId: null,
52 relationshipToParent: null,
53 rootThreadId: sourceThreadId,
54 },
55 forkedFrom: null,
56 createdAt: sourceCreatedAt,
57 updatedAt: snoozedAt,
58 archivedAt: null,
59 settledOverride: null,
60 settledAt: null,
61 lastVisitedAt: null,
62 snoozedUntil,
63 snoozedAt,
64 deletedAt: null,
65 };
67​
68function makeSourceRun(status: OrchestrationV2Run["status"]): OrchestrationV2Run {
69 return {
70 id: sourceRunId,
71 threadId: sourceThreadId,
72 ordinal: 1,
73 providerInstanceId,
74 modelSelection,
75 providerThreadId: ProviderThreadId.make("provider-thread:fork-snoozed-source"),
76 userMessageId: MessageId.make("message:fork-snoozed-source"),
77 rootNodeId: null,
78 activeAttemptId: null,
79 status,
80 queuePosition: null,
81 requestedAt: sourceCreatedAt,
82 startedAt: sourceCreatedAt,
83 completedAt: snoozedAt,
84 checkpointId: null,
85 contextHandoffId: null,
86 };
88​
89function makeSourceProjection(sourceRun: OrchestrationV2Run): OrchestrationV2ThreadProjection {
90 return {
91 thread: makeSourceThread(),
92 runs: [sourceRun],
93 attempts: [],
94 nodes: [],
95 subagents: [],
96 providerSessions: [],
97 providerThreads: [],
98 providerTurns: [],
99 runtimeRequests: [],
100 messages: [],
101 plans: [],
102 turnItems: [],
103 checkpointScopes: [],
104 checkpoints: [],
105 contextHandoffs: [],
106 contextTransfers: [],
107 visibleTurnItems: [],
108 updatedAt: snoozedAt,
109 };
111​
112const planFork = (
113 sourceRun: OrchestrationV2Run,
114 sourceProjection = makeSourceProjection(sourceRun),
115 options: { readonly sideChat?: boolean } = {},
116) =>
117 Effect.gen(function* () {
118 const service = yield* ThreadForkService.ThreadForkServiceV2;
119 return yield* service.plan({
120 sourceProjection,
121 sourceRun,
122 sourceProviderThread: undefined,
123 canonicalSourcePoint: {
124 threadId: sourceThreadId,
125 runId: sourceRunId,
126 },
127 transferId: ContextTransferId.make("context-transfer:fork-snoozed-source"),
128 targetThreadId,
129 title: "Awake fork",
130 ...options,
131 createdBy: "user",
132 creationSource: "mobile",
133 createdAt: forkCreatedAt,
134 });
135 }).pipe(Effect.provide(ThreadForkService.layer));
136​
137it.effect("resets a fork's pin, snooze, settle and delegation state but keeps its origin", () =>
138 Effect.gen(function* () {
139 const linkOrigin = { sessionId: "mcp-session:fork-source", label: "Linked laptop" };
140 const sourceThread: OrchestrationV2AppThread = {
141 ...makeSourceThread(),
142 lastSnoozeWakeAt: snoozedAt,
143 pinnedAt: snoozedAt,
144 pinOrderKey: "a0",
145 activeOrderKey: "a1",
146 autoSettleDisabledAt: snoozedAt,
147 delegatedFrom: {
148 environmentId: EnvironmentId.make("linked-environment"),
149 threadId: ThreadId.make("linked-parent"),
150 title: "Linked parent",
151 },
152 handoff: {
153 state: "departed",
154 handoffId: "handoff:fork-source",
155 environmentId: EnvironmentId.make("linked-environment"),
156 label: "Linked laptop",
157 threadId: ThreadId.make("linked-moved-source"),
158 },
159 historyOrigin: "v1_import",
160 linkOrigin,
161 tags: ["private"],
162 };
163 const sourceRun = makeSourceRun("completed");
164 const result = yield* planFork(sourceRun, {
165 ...makeSourceProjection(sourceRun),
166 thread: sourceThread,
167 });
168​
169 assert.isNull(result.targetThread.snoozedUntil);
170 assert.isNull(result.targetThread.snoozedAt);
171 assert.isNull(result.targetThread.lastSnoozeWakeAt);
172 assert.isNull(result.targetThread.pinnedAt);
173 assert.isNull(result.targetThread.pinOrderKey);
174 assert.isNull(result.targetThread.activeOrderKey);
175 assert.isNull(result.targetThread.autoSettleDisabledAt);
176 assert.isUndefined(result.targetThread.delegatedFrom);
177 assert.isUndefined(result.targetThread.handoff);
178 assert.equal(result.targetThread.historyOrigin, "v1_import");
179 assert.deepEqual(result.targetThread.linkOrigin, linkOrigin);
180 assert.deepEqual(result.targetThread.tags, ["private"]);
181 assert.equal(result.targetThread.projectId, sourceThread.projectId);
182 assert.equal(result.targetThread.providerInstanceId, sourceThread.providerInstanceId);
183 assert.deepEqual(result.targetThread.modelSelection, sourceThread.modelSelection);
184 assert.equal(result.targetThread.runtimeMode, sourceThread.runtimeMode);
185 assert.equal(result.targetThread.interactionMode, sourceThread.interactionMode);
186 assert.equal(result.targetThread.branch, sourceThread.branch);
187 assert.equal(result.targetThread.worktreePath, sourceThread.worktreePath);
188 assert.isNull(result.targetThread.activeProviderThreadId);
189 assert.deepEqual(result.targetThread.lineage, {
190 parentThreadId: sourceThreadId,
191 relationshipToParent: "fork",
192 rootThreadId: sourceThreadId,
193 });
194 assert.deepEqual(result.targetThread.forkedFrom, {
195 type: "run",
196 threadId: sourceThreadId,
197 runId: sourceRunId,
198 });
199 }),
200);
201​
202it.effect("starts a fork without the source thread's pending title regeneration", () =>
203 Effect.gen(function* () {
204 const sourceRun = makeSourceRun("completed");
205 const titleRegeneration = {
206 requestId: CommandId.make("command:fork-source-title"),
207 startedAt: snoozedAt,
208 };
209 const sourceProjection = {
210 ...makeSourceProjection(sourceRun),
211 thread: { ...makeSourceThread(), titleRegeneration },
212 };
213 const result = yield* planFork(sourceRun, sourceProjection);
214​
215 assert.isNull(result.targetThread.titleRegeneration);
216 assert.deepEqual(sourceProjection.thread.titleRegeneration, titleRegeneration);
217 }),
218);
219​
220it.effect("preserves pull request context without inheriting any watches", () =>
221 Effect.gen(function* () {
222 const sourceRun = makeSourceRun("completed");
223 const watch = {
224 startedAt: DateTime.formatIso(sourceCreatedAt),
225 headSha: "source-head",
226 failedChecks: ["lint"],
227 passed: false,
228 passedChecks: [],
229 remarksThrough: DateTime.formatIso(snoozedAt),
230 remarkIds: ["review-1"],
231 conflicting: true,
232 wakes: 2,
233 };
234 const links = (["agent", "stack", "manual", "stack-dismissed"] as const).map(
235 (source, index) =>
236 ({
237 host: "github.com",
238 repository: "example/repo",
239 number: index + 1,
240 url: `https://github.com/example/repo/pull/${index + 1}`,
241 source,
242 linkedAt: DateTime.formatIso(sourceCreatedAt),
243 snapshot: {
244 state: "open",
245 title: `Pull request ${index + 1}`,
246 headBranch: `feature-${index + 1}`,
247 baseBranch: "main",
248 isDraft: false,
249 updatedAt: null,
250 syncedAt: DateTime.formatIso(snoozedAt),
251 },
252 stack: {
253 kind: "native",
254 id: "stack-1",
255 number: 1,
256 url: "https://github.com/example/repo/stack/1",
257 base: "main",
258 layers: [{ number: 1, headBranch: "feature-1", state: "open" }],
259 },
260 }) satisfies ThreadPullRequestLink,
261 );
262 const watchedLinks: ReadonlyArray<ThreadPullRequestLink> = links.map((link, index) =>
263 index < 2 ? { ...link, watch } : link,
264 );
265 const legacyLink = {
266 projectId: makeSourceThread().projectId,
267 repository: "example/repo",
268 number: 1,
269 url: links[0]!.url,
270 };
271 const sourceProjection = {
272 ...makeSourceProjection(sourceRun),
273 thread: {
274 ...makeSourceThread(),
275 pullRequests: watchedLinks,
276 linkedPullRequest: legacyLink,
277 branchPullRequest: legacyLink,
278 },
279 };
280 const result = yield* planFork(sourceRun, sourceProjection);
281​
282 assert.deepEqual(result.targetThread.pullRequests, links);
283 assert.deepEqual(result.targetThread.linkedPullRequest, legacyLink);
284 assert.deepEqual(result.targetThread.branchPullRequest, legacyLink);
285 assert.deepEqual(sourceProjection.thread.pullRequests, watchedLinks);
286 assert.deepEqual(sourceProjection.thread.pullRequests[0]?.watch, watch);
287 assert.deepEqual(sourceProjection.thread.pullRequests[1]?.watch, watch);
288 }),
289);
290​
291it.effect("rejects in-progress and rolled-back fork sources", () =>
292 Effect.gen(function* () {
293 for (const status of ["running", "rolled_back"] as const) {
294 const sourceRun = makeSourceRun(status);
295 const error = yield* planFork(sourceRun).pipe(Effect.flip);
296 assert.equal(error._tag, "ThreadForkPlanError");
297 assert.equal(error.sourceThreadId, sourceThreadId);
298 assert.equal(error.targetThreadId, targetThreadId);
299 assert.equal(error.cause, ThreadForkService.forkableSourceRunStatusError(sourceRun));
300 }
301 }),
302);
303​
304it.effect("marks only requested forks as side chats and inherits parent permissions", () =>
305 Effect.gen(function* () {
306 const sourceRun = makeSourceRun("completed");
307 const sideChat = yield* planFork(sourceRun, makeSourceProjection(sourceRun), {
308 sideChat: true,
309 });
310 assert.isTrue(sideChat.targetThread.lineage.sideChat);
311 assert.equal(sideChat.targetThread.runtimeMode, "full-access");
312 for (const runtimeMode of [
313 "approval-required",
314 "auto-accept-edits",
315 "auto",
316 "full-access",
317 ] as const) {
318 const source = makeSourceProjection(sourceRun);
319 const inherited = yield* planFork(
320 sourceRun,
321 {
322 ...source,
323 thread: { ...source.thread, runtimeMode },
324 },
325 { sideChat: true },
326 );
327 assert.equal(inherited.targetThread.runtimeMode, runtimeMode);
328 }
329​
330 const sideChatSource = makeSourceProjection(sourceRun);
331 const sideChatProjection = {
332 ...sideChatSource,
333 thread: {
334 ...sideChatSource.thread,
335 lineage: { ...sideChatSource.thread.lineage, sideChat: true },
336 },
337 };
338 const forkOfSideChat = yield* planFork(sourceRun, sideChatProjection);
339 assert.isUndefined(forkOfSideChat.targetThread.lineage.sideChat);
340 assert.equal(forkOfSideChat.targetThread.runtimeMode, "full-access");
341​
342 const nested = yield* planFork(sourceRun, sideChatProjection, { sideChat: true }).pipe(
343 Effect.flip,
344 );
345 assert.equal(nested.cause, "A side chat cannot start another side chat.");
346​
347 const subagentSource = makeSourceProjection(sourceRun);
348 const fromSubagent = yield* planFork(
349 sourceRun,
350 {
351 ...subagentSource,
352 thread: {
353 ...subagentSource.thread,
354 lineage: { ...subagentSource.thread.lineage, relationshipToParent: "subagent" },
355 },
356 },
357 { sideChat: true },
358 ).pipe(Effect.flip);
359 assert.equal(fromSubagent.cause, "A subagent cannot start a side chat.");
360​
361 const delegatedSource = makeSourceProjection(sourceRun);
362 const fromDelegated = yield* planFork(
363 sourceRun,
364 {
365 ...delegatedSource,
366 thread: {
367 ...delegatedSource.thread,
368 delegatedFrom: {
369 environmentId: EnvironmentId.make("linked-environment"),
370 threadId: ThreadId.make("linked-parent"),
371 title: "Linked parent",
372 },
373 },
374 },
375 { sideChat: true },
376 ).pipe(Effect.flip);
377 assert.equal(fromDelegated.cause, "A subagent cannot start a side chat.");
378 }),
379);