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

ThreadPullRequestService.test.ts

539 lines20.6 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 SecureRandom from "effect/crypto/SecureRandom";
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 Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24​
25import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
26import * as GitManager from "../git/GitManager.ts";
27import * as ProjectStore from "./ProjectStore.ts";
28import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
29import * as PullRequestService from "../pullRequest/PullRequestService.ts";
30import * as ServerActivation from "../serverActivation.ts";
31import * as Orchestrator from "./Orchestrator.ts";
32import * as ThreadPullRequestService from "./ThreadPullRequestService.ts";
33​
34describe("ThreadPullRequestServiceV2 project guard", () => {
35 it("rejects a pull-request result when the project root changes before dispatch", () => {
36 const currentProject = Option.some({
37 workspaceRoot: "/workspace/replaced",
38 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
39​
40 expect(
41 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
42 currentProject,
43 "/workspace/original",
44 ),
45 ).toBe(false);
46 });
47});
48​
49describe("ThreadPullRequestServiceV2 reads", () => {
50 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
51 const threadShell = (id: string): OrchestrationV2ThreadShell => {
52 const threadId = ThreadId.make(id);
53 return {
54 id: threadId,
55 projectId: ProjectId.make("project-1"),
56 title: id,
57 providerInstanceId: ProviderInstanceId.make("codex"),
58 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
59 runtimeMode: "full-access",
60 interactionMode: "default",
61 branch: null,
62 worktreePath: null,
63 activeProviderThreadId: null,
64 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
65 forkedFrom: null,
66 createdBy: "user",
67 creationSource: "web",
68 activeRunId: null,
69 latestRunId: null,
70 status: "idle",
71 pendingRuntimeRequest: null,
72 latestVisibleMessage: null,
73 latestUserMessageAt: null,
74 hasActionableProposedPlan: false,
75 itemCount: 0,
76 visibleItemCount: 0,
77 createdAt: NOW,
78 updatedAt: NOW,
79 archivedAt: null,
80 settledOverride: null,
81 settledAt: null,
82 lastVisitedAt: null,
83 deletedAt: null,
84 };
85 };
86​
87 it.effect("does not sweep branch pull requests while no client is connected", () =>
88 Effect.scoped(
89 Effect.gen(function* () {
90 // Polling active branches without a connected client wastes GitHub requests.
91 const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
92 const project: OrchestrationProjectShell = {
93 id: thread.projectId,
94 title: "Project",
95 workspaceRoot: "/workspace/project",
96 defaultModelSelection: null,
97 scripts: [],
98 createdAt: "2026-08-01T00:00:00.000Z",
99 updatedAt: "2026-08-01T00:00:00.000Z",
100 };
101 const activation = yield* Deferred.make<void>();
102 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
103 const turnLookup = yield* Deferred.make<void>();
104 const lookups: Array<{ readonly refresh: boolean }> = [];
105 const dependencies = Layer.mergeAll(
106 Layer.mock(Orchestrator.OrchestratorV2)({
107 streamDomainEvents: Stream.fromQueue(domainEvents),
108 getShellSnapshot: () =>
109 Effect.succeed({
110 schemaVersion: 2,
111 snapshotSequence: 1,
112 threads: [thread],
113 archivedThreads: [],
114 }),
115 getThreadEventSequence: () => Effect.succeed(1),
116 getThreadShell: () => Effect.succeed(thread),
117 }),
118 Layer.mock(ProjectStore.ProjectStoreV2)({
119 listShells: () => Effect.succeed([project]),
120 getShell: () => Effect.succeedSome(project),
121 }),
122 Layer.mock(GitManager.GitManager)({
123 branchPullRequest: (_input, options) =>
124 Effect.gen(function* () {
125 const refresh = options?.refresh ?? false;
126 lookups.push({ refresh });
127 if (refresh) yield* Deferred.succeed(turnLookup, undefined);
128 return null;
129 }),
130 }),
131 Layer.mock(PullRequestService.PullRequestService)({}),
132 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
133 resolve: () =>
134 Effect.succeed({
135 canonicalKey: "github.com/acme/project",
136 locator: {
137 source: "git-remote" as const,
138 remoteName: "origin",
139 remoteUrl: "git@github.com:acme/project.git",
140 },
141 provider: SourceControlProviderKind.make("github"),
142 owner: "acme",
143 name: "project",
144 }),
145 }),
146 // No client holds an activity lease.
147 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
148 shouldRunScopeWork: () => Effect.succeed(false),
149 shouldRunOpportunisticWork: Effect.succeed(false),
150 }),
151 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
152 Layer.succeed(
153 SecureRandom.SecureRandom,
154 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
155 ),
156 FileSystem.layerNoop({}),
157 Path.layer,
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.each([
183 {
184 worktree: "a linked worktree",
185 existingPaths: ["/workspace/worktree", "/workspace/worktree/.git"],
186 unreadablePaths: [],
187 cwd: "/workspace/worktree",
188 },
189 // A folder that outlived its .git makes git fail with not_a_repository.
190 {
191 worktree: "a folder without .git",
192 existingPaths: ["/workspace/worktree"],
193 unreadablePaths: [],
194 cwd: "/workspace/project",
195 },
196 {
197 worktree: "a folder whose .git cannot be checked",
198 existingPaths: ["/workspace/worktree"],
199 unreadablePaths: ["/workspace/worktree/.git"],
200 cwd: "/workspace/worktree",
201 },
202 {
203 worktree: "a missing folder",
204 existingPaths: [],
205 unreadablePaths: [],
206 cwd: "/workspace/project",
207 },
208 ] as const)(
209 "looks up a branch whose worktree is $worktree in $cwd",
210 ({ existingPaths, unreadablePaths, cwd }) =>
211 Effect.scoped(
212 Effect.gen(function* () {
213 const thread = {
214 ...threadShell("worktree-thread"),
215 branch: "feature/worktree",
216 worktreePath: "/workspace/worktree",
217 };
218 const project: OrchestrationProjectShell = {
219 id: thread.projectId,
220 title: "Project",
221 workspaceRoot: "/workspace/project",
222 defaultModelSelection: null,
223 scripts: [],
224 createdAt: "2026-08-01T00:00:00.000Z",
225 updatedAt: "2026-08-01T00:00:00.000Z",
226 };
227 const activation = yield* Deferred.make<void>();
228 const sweepStarted = yield* Deferred.make<void>();
229 const lookupCwds: Array<string> = [];
230 const dependencies = Layer.mergeAll(
231 Layer.mock(Orchestrator.OrchestratorV2)({
232 streamDomainEvents: Stream.never,
233 getShellSnapshot: () =>
234 Deferred.succeed(sweepStarted, undefined).pipe(
235 Effect.as({
236 schemaVersion: 2,
237 snapshotSequence: 1,
238 threads: [thread],
239 archivedThreads: [],
240 }),
241 ),
242 }),
243 Layer.mock(ProjectStore.ProjectStoreV2)({
244 listShells: () => Effect.succeed([project]),
245 getShell: () => Effect.succeedSome(project),
246 }),
247 Layer.mock(GitManager.GitManager)({
248 branchPullRequest: (input) =>
249 Effect.sync(() => {
250 lookupCwds.push(input.cwd);
251 return null;
252 }),
253 }),
254 Layer.mock(PullRequestService.PullRequestService)({}),
255 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
256 resolve: () =>
257 Effect.succeed({
258 canonicalKey: "github.com/acme/project",
259 locator: {
260 source: "git-remote" as const,
261 remoteName: "origin",
262 remoteUrl: "git@github.com:acme/project.git",
263 },
264 provider: SourceControlProviderKind.make("github"),
265 owner: "acme",
266 name: "project",
267 }),
268 }),
269 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
270 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
271 Layer.succeed(
272 SecureRandom.SecureRandom,
273 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
274 ),
275 FileSystem.layerNoop({
276 exists: (path) =>
277 unreadablePaths.some((entry) => entry === path)
278 ? Effect.fail(
279 PlatformError.systemError({
280 _tag: "PermissionDenied",
281 module: "FileSystem",
282 method: "exists",
283 pathOrDescriptor: path,
284 }),
285 )
286 : Effect.succeed(existingPaths.some((entry) => entry === path)),
287 }),
288 Path.layer,
289 );
290 yield* Effect.gen(function* () {
291 const service = yield* ThreadPullRequestService.make;
292 yield* service.start();
293 yield* Deferred.succeed(activation, undefined);
294 yield* Deferred.await(sweepStarted);
295 yield* service.drain;
296 }).pipe(Effect.provide(dependencies));
297​
298 expect(lookupCwds).toEqual([cwd]);
299 }),
300 ),
301 );
302​
303 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
304 Effect.scoped(
305 Effect.gen(function* () {
306 const parent = {
307 ...threadShell("parent-thread"),
308 branch: "feature/parent",
309 worktreePath: "/workspace/parent",
310 };
311 const child: OrchestrationV2ThreadShell = {
312 ...threadShell("child-thread"),
313 branch: "t3/reply-ok",
314 worktreePath: "/workspace/child",
315 lineage: {
316 rootThreadId: parent.id,
317 parentThreadId: parent.id,
318 relationshipToParent: "subagent",
319 },
320 };
321 const project: OrchestrationProjectShell = {
322 id: parent.projectId,
323 title: "Project",
324 workspaceRoot: "/workspace/project",
325 defaultModelSelection: null,
326 scripts: [],
327 createdAt: "2026-08-01T00:00:00.000Z",
328 updatedAt: "2026-08-01T00:00:00.000Z",
329 };
330 const activation = yield* Deferred.make<void>();
331 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
332 const sweeps = yield* Queue.unbounded<void>();
333 const childLookup = yield* Deferred.make<void>();
334 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
335 const dependencies = Layer.mergeAll(
336 Layer.mock(Orchestrator.OrchestratorV2)({
337 streamDomainEvents: Stream.fromQueue(domainEvents),
338 getShellSnapshot: () =>
339 Queue.offer(sweeps, undefined).pipe(
340 Effect.as({
341 schemaVersion: 2,
342 snapshotSequence: 1,
343 threads: [parent, child],
344 archivedThreads: [],
345 }),
346 ),
347 getThreadEventSequence: () => Effect.succeed(1),
348 getThreadShell: (threadId) =>
349 Effect.succeed([parent, child].find((thread) => thread.id === threadId) ?? null),
350 }),
351 Layer.mock(ProjectStore.ProjectStoreV2)({
352 listShells: () => Effect.succeed([project]),
353 getShell: () => Effect.succeedSome(project),
354 }),
355 Layer.mock(GitManager.GitManager)({
356 branchPullRequest: (input, options) =>
357 Effect.gen(function* () {
358 const refresh = options?.refresh ?? false;
359 lookups.push({ branch: input.branch, refresh });
360 if (input.branch === child.branch && refresh) {
361 yield* Deferred.succeed(childLookup, undefined);
362 }
363 return null;
364 }),
365 }),
366 Layer.mock(PullRequestService.PullRequestService)({}),
367 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
368 resolve: () =>
369 Effect.succeed({
370 canonicalKey: "github.com/acme/project",
371 locator: {
372 source: "git-remote" as const,
373 remoteName: "origin",
374 remoteUrl: "git@github.com:acme/project.git",
375 },
376 provider: SourceControlProviderKind.make("github"),
377 owner: "acme",
378 name: "project",
379 }),
380 }),
381 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
382 shouldRunScopeWork: () => Effect.succeed(true),
383 shouldRunOpportunisticWork: Effect.succeed(true),
384 }),
385 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
386 Layer.succeed(
387 SecureRandom.SecureRandom,
388 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
389 ),
390 FileSystem.layerNoop({}),
391 Path.layer,
392 );
393 yield* Effect.gen(function* () {
394 const service = yield* ThreadPullRequestService.make;
395 yield* service.start();
396 yield* Deferred.succeed(activation, undefined);
397​
398 // Startup backfill sweep, then one periodic sweep.
399 yield* Queue.take(sweeps);
400 yield* service.drain;
401 yield* TestClock.adjust("1 minute");
402 yield* Queue.take(sweeps);
403 yield* service.drain;
404 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
405​
406 // The child's own turn still discovers its pull request.
407 yield* Queue.offer(domainEvents, {
408 type: "checkpoint.captured",
409 threadId: child.id,
410 } as OrchestrationV2DomainEvent);
411 yield* Deferred.await(childLookup);
412 yield* service.drain;
413​
414 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
415 expect(lookups.slice(sweepLookups.length)).toEqual([
416 { branch: child.branch, refresh: true },
417 ]);
418 }).pipe(Effect.provide(dependencies));
419 }),
420 ),
421 );
422​
423 it.effect.each([
424 { state: "closed", sameBranch: false },
425 { state: "merged", sameBranch: false },
426 { state: "closed", sameBranch: true },
427 { state: "merged", sameBranch: true },
428 ] as const)(
429 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
430 ({ state, sameBranch }) =>
431 Effect.scoped(
432 Effect.gen(function* () {
433 const savedReference = {
434 projectId: ProjectId.make("project-1"),
435 repository: "acme/project",
436 number: 42,
437 url: "https://github.com/acme/project/pull/42",
438 };
439 const thread = {
440 ...threadShell("branch-pr-thread"),
441 branch: "main",
442 branchPullRequest: savedReference,
443 linkedPullRequest: savedReference,
444 };
445 const project: OrchestrationProjectShell = {
446 id: thread.projectId,
447 title: "Project",
448 workspaceRoot: "/workspace/project",
449 defaultModelSelection: null,
450 scripts: [],
451 createdAt: "2026-08-01T00:00:00.000Z",
452 updatedAt: "2026-08-01T00:00:00.000Z",
453 };
454 const activation = yield* Deferred.make<void>();
455 const sweepStarted = yield* Deferred.make<void>();
456 const commands: Array<OrchestrationV2ServerCommand> = [];
457 const dependencies = Layer.mergeAll(
458 Layer.mock(Orchestrator.OrchestratorV2)({
459 streamDomainEvents: Stream.never,
460 getShellSnapshot: () =>
461 Deferred.succeed(sweepStarted, undefined).pipe(
462 Effect.as({
463 schemaVersion: 2,
464 snapshotSequence: 1,
465 threads: [thread],
466 archivedThreads: [],
467 }),
468 ),
469 dispatch: (command) =>
470 Effect.sync(() => {
471 commands.push(command);
472 return { sequence: 2, storedEvents: [] };
473 }),
474 }),
475 Layer.mock(ProjectStore.ProjectStoreV2)({
476 listShells: () => Effect.succeed([project]),
477 getShell: () => Effect.succeedSome(project),
478 }),
479 Layer.mock(GitManager.GitManager)({
480 branchPullRequest: () => Effect.succeed(null),
481 }),
482 Layer.mock(PullRequestService.PullRequestService)({
483 summary: () =>
484 Effect.succeed({
485 ...savedReference,
486 provider: SourceControlProviderKind.make("github"),
487 title: "Previous branch work",
488 state,
489 headBranch: sameBranch ? thread.branch : "feature/previous-work",
490 baseBranch: "release",
491 updatedAt: "2026-09-19T00:00:00.000Z",
492 }),
493 }),
494 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
495 resolve: () =>
496 Effect.succeed({
497 canonicalKey: "github.com/acme/project",
498 locator: {
499 source: "git-remote" as const,
500 remoteName: "origin",
501 remoteUrl: "git@github.com:acme/project.git",
502 },
503 provider: SourceControlProviderKind.make("github"),
504 owner: "acme",
505 name: "project",
506 }),
507 }),
508 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
509 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
510 Layer.succeed(
511 SecureRandom.SecureRandom,
512 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
513 ),
514 FileSystem.layerNoop({}),
515 Path.layer,
516 );
517 yield* Effect.gen(function* () {
518 const service = yield* ThreadPullRequestService.make;
519 yield* service.start();
520 yield* Deferred.succeed(activation, undefined);
521 yield* Deferred.await(sweepStarted);
522 yield* service.drain;
523 }).pipe(Effect.provide(dependencies));
524​
525 if (sameBranch) {
526 expect(commands).toEqual([]);
527 } else {
528 expect(commands).toHaveLength(1);
529 expect(commands[0]).toMatchObject({
530 type: "thread.pull-request.sync",
531 threadId: thread.id,
532 branchPullRequest: null,
533 });
534 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
535 }
536 }),
537 ),
538 );
539});