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

ThreadPullRequestService.test.ts

422 lines16.3 KB

1import {
2 ProjectId,
3 ProviderInstanceId,
4 SourceControlProviderKind,
5 ThreadId,
6 type OrchestrationProjectShell,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9 type OrchestrationV2ServerCommand,
10} from "@t3tools/contracts";
11import { describe, expect, it } from "@effect/vitest";
12import * as Crypto from "effect/Crypto";
13import * as DateTime from "effect/DateTime";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22​
23import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
24import * as GitManager from "../git/GitManager.ts";
25import * as ProjectStore from "./ProjectStore.ts";
26import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
27import * as PullRequestService from "../pullRequest/PullRequestService.ts";
28import * as ServerActivation from "../serverActivation.ts";
29import * as Orchestrator from "./Orchestrator.ts";
30import * as ThreadPullRequestService from "./ThreadPullRequestService.ts";
31​
32describe("ThreadPullRequestServiceV2 project guard", () => {
33 it("rejects a pull-request result when the project root changes before dispatch", () => {
34 const currentProject = Option.some({
35 workspaceRoot: "/workspace/replaced",
36 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
37​
38 expect(
39 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
40 currentProject,
41 "/workspace/original",
42 ),
43 ).toBe(false);
44 });
45});
46​
47describe("ThreadPullRequestServiceV2 reads", () => {
48 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
49 const threadShell = (id: string): OrchestrationV2ThreadShell => {
50 const threadId = ThreadId.make(id);
51 return {
52 id: threadId,
53 projectId: ProjectId.make("project-1"),
54 title: id,
55 providerInstanceId: ProviderInstanceId.make("codex"),
56 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
57 runtimeMode: "full-access",
58 interactionMode: "default",
59 branch: null,
60 worktreePath: null,
61 activeProviderThreadId: null,
62 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
63 forkedFrom: null,
64 createdBy: "user",
65 creationSource: "web",
66 activeRunId: null,
67 latestRunId: null,
68 status: "idle",
69 pendingRuntimeRequest: null,
70 latestVisibleMessage: null,
71 latestUserMessageAt: null,
72 hasActionableProposedPlan: false,
73 itemCount: 0,
74 visibleItemCount: 0,
75 createdAt: NOW,
76 updatedAt: NOW,
77 archivedAt: null,
78 settledOverride: null,
79 settledAt: null,
80 lastVisitedAt: null,
81 deletedAt: null,
82 };
83 };
84​
85 it.effect("does not sweep branch pull requests while no client is connected", () =>
86 Effect.scoped(
87 Effect.gen(function* () {
88 // Polling active branches without a connected client wastes GitHub requests.
89 const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
90 const project: OrchestrationProjectShell = {
91 id: thread.projectId,
92 title: "Project",
93 workspaceRoot: "/workspace/project",
94 defaultModelSelection: null,
95 scripts: [],
96 createdAt: "2026-08-01T00:00:00.000Z",
97 updatedAt: "2026-08-01T00:00:00.000Z",
98 };
99 const activation = yield* Deferred.make<void>();
100 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
101 const turnLookup = yield* Deferred.make<void>();
102 const lookups: Array<{ readonly refresh: boolean }> = [];
103 const dependencies = Layer.mergeAll(
104 Layer.mock(Orchestrator.OrchestratorV2)({
105 streamDomainEvents: Stream.fromQueue(domainEvents),
106 getShellSnapshot: () =>
107 Effect.succeed({
108 schemaVersion: 2,
109 snapshotSequence: 1,
110 threads: [thread],
111 archivedThreads: [],
112 }),
113 getThreadEventSequence: () => Effect.succeed(1),
114 getThreadShell: () => Effect.succeed(thread),
115 }),
116 Layer.mock(ProjectStore.ProjectStoreV2)({
117 listShells: () => Effect.succeed([project]),
118 getShell: () => Effect.succeedSome(project),
119 }),
120 Layer.mock(GitManager.GitManager)({
121 branchPullRequest: (_input, options) =>
122 Effect.gen(function* () {
123 const refresh = options?.refresh ?? false;
124 lookups.push({ refresh });
125 if (refresh) yield* Deferred.succeed(turnLookup, undefined);
126 return null;
127 }),
128 }),
129 Layer.mock(PullRequestService.PullRequestService)({}),
130 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
131 resolve: () =>
132 Effect.succeed({
133 canonicalKey: "github.com/acme/project",
134 locator: {
135 source: "git-remote" as const,
136 remoteName: "origin",
137 remoteUrl: "git@github.com:acme/project.git",
138 },
139 provider: SourceControlProviderKind.make("github"),
140 owner: "acme",
141 name: "project",
142 }),
143 }),
144 // No client holds an activity lease.
145 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
146 shouldRunScopeWork: () => Effect.succeed(false),
147 shouldRunOpportunisticWork: Effect.succeed(false),
148 }),
149 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
150 Layer.succeed(
151 Crypto.Crypto,
152 Crypto.make({
153 randomBytes: (size) => new Uint8Array(size).fill(1),
154 digest: (_algorithm, data) => Effect.succeed(data),
155 }),
156 ),
157 FileSystem.layerNoop({}),
158 );
159 yield* Effect.gen(function* () {
160 const service = yield* ThreadPullRequestService.make;
161 yield* service.start();
162 yield* Deferred.succeed(activation, undefined);
163​
164 // A finished turn still discovers the pull request for its branch.
165 yield* Queue.offer(domainEvents, {
166 type: "checkpoint.captured",
167 threadId: thread.id,
168 } as OrchestrationV2DomainEvent);
169 yield* Deferred.await(turnLookup);
170 yield* service.drain;
171 const lookupsBeforeIdle = lookups.length;
172​
173 yield* TestClock.adjust("10 minutes");
174 yield* service.drain;
175​
176 expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
177 }).pipe(Effect.provide(dependencies));
178 }),
179 ),
180 );
181​
182 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
183 Effect.scoped(
184 Effect.gen(function* () {
185 const parent = {
186 ...threadShell("parent-thread"),
187 branch: "feature/parent",
188 worktreePath: "/workspace/parent",
189 };
190 const child: OrchestrationV2ThreadShell = {
191 ...threadShell("child-thread"),
192 branch: "t3/reply-ok",
193 worktreePath: "/workspace/child",
194 lineage: {
195 rootThreadId: parent.id,
196 parentThreadId: parent.id,
197 relationshipToParent: "subagent",
198 },
199 };
200 const project: OrchestrationProjectShell = {
201 id: parent.projectId,
202 title: "Project",
203 workspaceRoot: "/workspace/project",
204 defaultModelSelection: null,
205 scripts: [],
206 createdAt: "2026-08-01T00:00:00.000Z",
207 updatedAt: "2026-08-01T00:00:00.000Z",
208 };
209 const activation = yield* Deferred.make<void>();
210 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
211 const sweeps = yield* Queue.unbounded<void>();
212 const childLookup = yield* Deferred.make<void>();
213 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
214 const dependencies = Layer.mergeAll(
215 Layer.mock(Orchestrator.OrchestratorV2)({
216 streamDomainEvents: Stream.fromQueue(domainEvents),
217 getShellSnapshot: () =>
218 Queue.offer(sweeps, undefined).pipe(
219 Effect.as({
220 schemaVersion: 2,
221 snapshotSequence: 1,
222 threads: [parent, child],
223 archivedThreads: [],
224 }),
225 ),
226 getThreadEventSequence: () => Effect.succeed(1),
227 getThreadShell: (threadId) =>
228 Effect.succeed([parent, child].find((thread) => thread.id === threadId) ?? null),
229 }),
230 Layer.mock(ProjectStore.ProjectStoreV2)({
231 listShells: () => Effect.succeed([project]),
232 getShell: () => Effect.succeedSome(project),
233 }),
234 Layer.mock(GitManager.GitManager)({
235 branchPullRequest: (input, options) =>
236 Effect.gen(function* () {
237 const refresh = options?.refresh ?? false;
238 lookups.push({ branch: input.branch, refresh });
239 if (input.branch === child.branch && refresh) {
240 yield* Deferred.succeed(childLookup, undefined);
241 }
242 return null;
243 }),
244 }),
245 Layer.mock(PullRequestService.PullRequestService)({}),
246 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
247 resolve: () =>
248 Effect.succeed({
249 canonicalKey: "github.com/acme/project",
250 locator: {
251 source: "git-remote" as const,
252 remoteName: "origin",
253 remoteUrl: "git@github.com:acme/project.git",
254 },
255 provider: SourceControlProviderKind.make("github"),
256 owner: "acme",
257 name: "project",
258 }),
259 }),
260 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
261 shouldRunScopeWork: () => Effect.succeed(true),
262 shouldRunOpportunisticWork: Effect.succeed(true),
263 }),
264 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
265 Layer.succeed(
266 Crypto.Crypto,
267 Crypto.make({
268 randomBytes: (size) => new Uint8Array(size).fill(1),
269 digest: (_algorithm, data) => Effect.succeed(data),
270 }),
271 ),
272 FileSystem.layerNoop({}),
273 );
274 yield* Effect.gen(function* () {
275 const service = yield* ThreadPullRequestService.make;
276 yield* service.start();
277 yield* Deferred.succeed(activation, undefined);
278​
279 // Startup backfill sweep, then one periodic sweep.
280 yield* Queue.take(sweeps);
281 yield* service.drain;
282 yield* TestClock.adjust("1 minute");
283 yield* Queue.take(sweeps);
284 yield* service.drain;
285 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
286​
287 // The child's own turn still discovers its pull request.
288 yield* Queue.offer(domainEvents, {
289 type: "checkpoint.captured",
290 threadId: child.id,
291 } as OrchestrationV2DomainEvent);
292 yield* Deferred.await(childLookup);
293 yield* service.drain;
294​
295 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
296 expect(lookups.slice(sweepLookups.length)).toEqual([
297 { branch: child.branch, refresh: true },
298 ]);
299 }).pipe(Effect.provide(dependencies));
300 }),
301 ),
302 );
303​
304 it.effect.each([
305 { state: "closed", sameBranch: false },
306 { state: "merged", sameBranch: false },
307 { state: "closed", sameBranch: true },
308 { state: "merged", sameBranch: true },
309 ] as const)(
310 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
311 ({ state, sameBranch }) =>
312 Effect.scoped(
313 Effect.gen(function* () {
314 const savedReference = {
315 projectId: ProjectId.make("project-1"),
316 repository: "acme/project",
317 number: 42,
318 url: "https://github.com/acme/project/pull/42",
319 };
320 const thread = {
321 ...threadShell("branch-pr-thread"),
322 branch: "main",
323 branchPullRequest: savedReference,
324 linkedPullRequest: savedReference,
325 };
326 const project: OrchestrationProjectShell = {
327 id: thread.projectId,
328 title: "Project",
329 workspaceRoot: "/workspace/project",
330 defaultModelSelection: null,
331 scripts: [],
332 createdAt: "2026-08-01T00:00:00.000Z",
333 updatedAt: "2026-08-01T00:00:00.000Z",
334 };
335 const activation = yield* Deferred.make<void>();
336 const sweepStarted = yield* Deferred.make<void>();
337 const commands: Array<OrchestrationV2ServerCommand> = [];
338 const dependencies = Layer.mergeAll(
339 Layer.mock(Orchestrator.OrchestratorV2)({
340 streamDomainEvents: Stream.never,
341 getShellSnapshot: () =>
342 Deferred.succeed(sweepStarted, undefined).pipe(
343 Effect.as({
344 schemaVersion: 2,
345 snapshotSequence: 1,
346 threads: [thread],
347 archivedThreads: [],
348 }),
349 ),
350 dispatch: (command) =>
351 Effect.sync(() => {
352 commands.push(command);
353 return { sequence: 2, storedEvents: [] };
354 }),
355 }),
356 Layer.mock(ProjectStore.ProjectStoreV2)({
357 listShells: () => Effect.succeed([project]),
358 getShell: () => Effect.succeedSome(project),
359 }),
360 Layer.mock(GitManager.GitManager)({
361 branchPullRequest: () => Effect.succeed(null),
362 }),
363 Layer.mock(PullRequestService.PullRequestService)({
364 summary: () =>
365 Effect.succeed({
366 ...savedReference,
367 provider: SourceControlProviderKind.make("github"),
368 title: "Previous branch work",
369 state,
370 headBranch: sameBranch ? thread.branch : "feature/previous-work",
371 baseBranch: "release",
372 updatedAt: "2026-09-19T00:00:00.000Z",
373 }),
374 }),
375 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
376 resolve: () =>
377 Effect.succeed({
378 canonicalKey: "github.com/acme/project",
379 locator: {
380 source: "git-remote" as const,
381 remoteName: "origin",
382 remoteUrl: "git@github.com:acme/project.git",
383 },
384 provider: SourceControlProviderKind.make("github"),
385 owner: "acme",
386 name: "project",
387 }),
388 }),
389 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
390 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
391 Layer.succeed(
392 Crypto.Crypto,
393 Crypto.make({
394 randomBytes: (size) => new Uint8Array(size).fill(1),
395 digest: (_algorithm, data) => Effect.succeed(data),
396 }),
397 ),
398 FileSystem.layerNoop({}),
399 );
400 yield* Effect.gen(function* () {
401 const service = yield* ThreadPullRequestService.make;
402 yield* service.start();
403 yield* Deferred.succeed(activation, undefined);
404 yield* Deferred.await(sweepStarted);
405 yield* service.drain;
406 }).pipe(Effect.provide(dependencies));
407​
408 if (sameBranch) {
409 expect(commands).toEqual([]);
410 } else {
411 expect(commands).toHaveLength(1);
412 expect(commands[0]).toMatchObject({
413 type: "thread.pull-request.sync",
414 threadId: thread.id,
415 branchPullRequest: null,
416 });
417 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
418 }
419 }),
420 ),
421 );
422});