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

ThreadPullRequestService.test.ts

413 lines16.0 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 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 SecureRandom.SecureRandom,
152 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
153 ),
154 FileSystem.layerNoop({}),
155 );
156 yield* Effect.gen(function* () {
157 const service = yield* ThreadPullRequestService.make;
158 yield* service.start();
159 yield* Deferred.succeed(activation, undefined);
160​
161 // A finished turn still discovers the pull request for its branch.
162 yield* Queue.offer(domainEvents, {
163 type: "checkpoint.captured",
164 threadId: thread.id,
165 } as OrchestrationV2DomainEvent);
166 yield* Deferred.await(turnLookup);
167 yield* service.drain;
168 const lookupsBeforeIdle = lookups.length;
169​
170 yield* TestClock.adjust("10 minutes");
171 yield* service.drain;
172​
173 expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
174 }).pipe(Effect.provide(dependencies));
175 }),
176 ),
177 );
178​
179 it.effect("leaves delegated child threads to their own refresh instead of the sweep", () =>
180 Effect.scoped(
181 Effect.gen(function* () {
182 const parent = {
183 ...threadShell("parent-thread"),
184 branch: "feature/parent",
185 worktreePath: "/workspace/parent",
186 };
187 const child: OrchestrationV2ThreadShell = {
188 ...threadShell("child-thread"),
189 branch: "t3/reply-ok",
190 worktreePath: "/workspace/child",
191 lineage: {
192 rootThreadId: parent.id,
193 parentThreadId: parent.id,
194 relationshipToParent: "subagent",
195 },
196 };
197 const project: OrchestrationProjectShell = {
198 id: parent.projectId,
199 title: "Project",
200 workspaceRoot: "/workspace/project",
201 defaultModelSelection: null,
202 scripts: [],
203 createdAt: "2026-08-01T00:00:00.000Z",
204 updatedAt: "2026-08-01T00:00:00.000Z",
205 };
206 const activation = yield* Deferred.make<void>();
207 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
208 const sweeps = yield* Queue.unbounded<void>();
209 const childLookup = yield* Deferred.make<void>();
210 const lookups: Array<{ readonly branch: string; readonly refresh: boolean }> = [];
211 const dependencies = Layer.mergeAll(
212 Layer.mock(Orchestrator.OrchestratorV2)({
213 streamDomainEvents: Stream.fromQueue(domainEvents),
214 getShellSnapshot: () =>
215 Queue.offer(sweeps, undefined).pipe(
216 Effect.as({
217 schemaVersion: 2,
218 snapshotSequence: 1,
219 threads: [parent, child],
220 archivedThreads: [],
221 }),
222 ),
223 getThreadEventSequence: () => Effect.succeed(1),
224 getThreadShell: (threadId) =>
225 Effect.succeed([parent, child].find((thread) => thread.id === threadId) ?? null),
226 }),
227 Layer.mock(ProjectStore.ProjectStoreV2)({
228 listShells: () => Effect.succeed([project]),
229 getShell: () => Effect.succeedSome(project),
230 }),
231 Layer.mock(GitManager.GitManager)({
232 branchPullRequest: (input, options) =>
233 Effect.gen(function* () {
234 const refresh = options?.refresh ?? false;
235 lookups.push({ branch: input.branch, refresh });
236 if (input.branch === child.branch && refresh) {
237 yield* Deferred.succeed(childLookup, undefined);
238 }
239 return null;
240 }),
241 }),
242 Layer.mock(PullRequestService.PullRequestService)({}),
243 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
244 resolve: () =>
245 Effect.succeed({
246 canonicalKey: "github.com/acme/project",
247 locator: {
248 source: "git-remote" as const,
249 remoteName: "origin",
250 remoteUrl: "git@github.com:acme/project.git",
251 },
252 provider: SourceControlProviderKind.make("github"),
253 owner: "acme",
254 name: "project",
255 }),
256 }),
257 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
258 shouldRunScopeWork: () => Effect.succeed(true),
259 shouldRunOpportunisticWork: Effect.succeed(true),
260 }),
261 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
262 Layer.succeed(
263 SecureRandom.SecureRandom,
264 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
265 ),
266 FileSystem.layerNoop({}),
267 );
268 yield* Effect.gen(function* () {
269 const service = yield* ThreadPullRequestService.make;
270 yield* service.start();
271 yield* Deferred.succeed(activation, undefined);
272​
273 // Startup backfill sweep, then one periodic sweep.
274 yield* Queue.take(sweeps);
275 yield* service.drain;
276 yield* TestClock.adjust("1 minute");
277 yield* Queue.take(sweeps);
278 yield* service.drain;
279 const sweepLookups = lookups.map((lookup) => lookup.branch).toSorted();
280​
281 // The child's own turn still discovers its pull request.
282 yield* Queue.offer(domainEvents, {
283 type: "checkpoint.captured",
284 threadId: child.id,
285 } as OrchestrationV2DomainEvent);
286 yield* Deferred.await(childLookup);
287 yield* service.drain;
288​
289 expect(sweepLookups).toEqual([parent.branch, parent.branch]);
290 expect(lookups.slice(sweepLookups.length)).toEqual([
291 { branch: child.branch, refresh: true },
292 ]);
293 }).pipe(Effect.provide(dependencies));
294 }),
295 ),
296 );
297​
298 it.effect.each([
299 { state: "closed", sameBranch: false },
300 { state: "merged", sameBranch: false },
301 { state: "closed", sameBranch: true },
302 { state: "merged", sameBranch: true },
303 ] as const)(
304 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
305 ({ state, sameBranch }) =>
306 Effect.scoped(
307 Effect.gen(function* () {
308 const savedReference = {
309 projectId: ProjectId.make("project-1"),
310 repository: "acme/project",
311 number: 42,
312 url: "https://github.com/acme/project/pull/42",
313 };
314 const thread = {
315 ...threadShell("branch-pr-thread"),
316 branch: "main",
317 branchPullRequest: savedReference,
318 linkedPullRequest: savedReference,
319 };
320 const project: OrchestrationProjectShell = {
321 id: thread.projectId,
322 title: "Project",
323 workspaceRoot: "/workspace/project",
324 defaultModelSelection: null,
325 scripts: [],
326 createdAt: "2026-08-01T00:00:00.000Z",
327 updatedAt: "2026-08-01T00:00:00.000Z",
328 };
329 const activation = yield* Deferred.make<void>();
330 const sweepStarted = yield* Deferred.make<void>();
331 const commands: Array<OrchestrationV2ServerCommand> = [];
332 const dependencies = Layer.mergeAll(
333 Layer.mock(Orchestrator.OrchestratorV2)({
334 streamDomainEvents: Stream.never,
335 getShellSnapshot: () =>
336 Deferred.succeed(sweepStarted, undefined).pipe(
337 Effect.as({
338 schemaVersion: 2,
339 snapshotSequence: 1,
340 threads: [thread],
341 archivedThreads: [],
342 }),
343 ),
344 dispatch: (command) =>
345 Effect.sync(() => {
346 commands.push(command);
347 return { sequence: 2, storedEvents: [] };
348 }),
349 }),
350 Layer.mock(ProjectStore.ProjectStoreV2)({
351 listShells: () => Effect.succeed([project]),
352 getShell: () => Effect.succeedSome(project),
353 }),
354 Layer.mock(GitManager.GitManager)({
355 branchPullRequest: () => Effect.succeed(null),
356 }),
357 Layer.mock(PullRequestService.PullRequestService)({
358 summary: () =>
359 Effect.succeed({
360 ...savedReference,
361 provider: SourceControlProviderKind.make("github"),
362 title: "Previous branch work",
363 state,
364 headBranch: sameBranch ? thread.branch : "feature/previous-work",
365 baseBranch: "release",
366 updatedAt: "2026-09-19T00:00:00.000Z",
367 }),
368 }),
369 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
370 resolve: () =>
371 Effect.succeed({
372 canonicalKey: "github.com/acme/project",
373 locator: {
374 source: "git-remote" as const,
375 remoteName: "origin",
376 remoteUrl: "git@github.com:acme/project.git",
377 },
378 provider: SourceControlProviderKind.make("github"),
379 owner: "acme",
380 name: "project",
381 }),
382 }),
383 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
384 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
385 Layer.succeed(
386 SecureRandom.SecureRandom,
387 SecureRandom.make((size) => new Uint8Array(size).fill(1)),
388 ),
389 FileSystem.layerNoop({}),
390 );
391 yield* Effect.gen(function* () {
392 const service = yield* ThreadPullRequestService.make;
393 yield* service.start();
394 yield* Deferred.succeed(activation, undefined);
395 yield* Deferred.await(sweepStarted);
396 yield* service.drain;
397 }).pipe(Effect.provide(dependencies));
398​
399 if (sameBranch) {
400 expect(commands).toEqual([]);
401 } else {
402 expect(commands).toHaveLength(1);
403 expect(commands[0]).toMatchObject({
404 type: "thread.pull-request.sync",
405 threadId: thread.id,
406 branchPullRequest: null,
407 });
408 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
409 }
410 }),
411 ),
412 );
413});