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

ThreadPullRequestService.test.ts

300 lines11.4 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.each([
183 { state: "closed", sameBranch: false },
184 { state: "merged", sameBranch: false },
185 { state: "closed", sameBranch: true },
186 { state: "merged", sameBranch: true },
187 ] as const)(
188 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
189 ({ state, sameBranch }) =>
190 Effect.scoped(
191 Effect.gen(function* () {
192 const savedReference = {
193 projectId: ProjectId.make("project-1"),
194 repository: "acme/project",
195 number: 42,
196 url: "https://github.com/acme/project/pull/42",
197 };
198 const thread = {
199 ...threadShell("branch-pr-thread"),
200 branch: "main",
201 branchPullRequest: savedReference,
202 linkedPullRequest: savedReference,
203 };
204 const project: OrchestrationProjectShell = {
205 id: thread.projectId,
206 title: "Project",
207 workspaceRoot: "/workspace/project",
208 defaultModelSelection: null,
209 scripts: [],
210 createdAt: "2026-08-01T00:00:00.000Z",
211 updatedAt: "2026-08-01T00:00:00.000Z",
212 };
213 const activation = yield* Deferred.make<void>();
214 const sweepStarted = yield* Deferred.make<void>();
215 const commands: Array<OrchestrationV2ServerCommand> = [];
216 const dependencies = Layer.mergeAll(
217 Layer.mock(Orchestrator.OrchestratorV2)({
218 streamDomainEvents: Stream.never,
219 getShellSnapshot: () =>
220 Deferred.succeed(sweepStarted, undefined).pipe(
221 Effect.as({
222 schemaVersion: 2,
223 snapshotSequence: 1,
224 threads: [thread],
225 archivedThreads: [],
226 }),
227 ),
228 dispatch: (command) =>
229 Effect.sync(() => {
230 commands.push(command);
231 return { sequence: 2, storedEvents: [] };
232 }),
233 }),
234 Layer.mock(ProjectStore.ProjectStoreV2)({
235 listShells: () => Effect.succeed([project]),
236 getShell: () => Effect.succeedSome(project),
237 }),
238 Layer.mock(GitManager.GitManager)({
239 branchPullRequest: () => Effect.succeed(null),
240 }),
241 Layer.mock(PullRequestService.PullRequestService)({
242 summary: () =>
243 Effect.succeed({
244 ...savedReference,
245 provider: SourceControlProviderKind.make("github"),
246 title: "Previous branch work",
247 state,
248 headBranch: sameBranch ? thread.branch : "feature/previous-work",
249 baseBranch: "release",
250 updatedAt: "2026-09-19T00:00:00.000Z",
251 }),
252 }),
253 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
254 resolve: () =>
255 Effect.succeed({
256 canonicalKey: "github.com/acme/project",
257 locator: {
258 source: "git-remote" as const,
259 remoteName: "origin",
260 remoteUrl: "git@github.com:acme/project.git",
261 },
262 provider: SourceControlProviderKind.make("github"),
263 owner: "acme",
264 name: "project",
265 }),
266 }),
267 Layer.mock(BackgroundPolicy.BackgroundPolicy)({}),
268 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
269 Layer.succeed(
270 Crypto.Crypto,
271 Crypto.make({
272 randomBytes: (size) => new Uint8Array(size).fill(1),
273 digest: (_algorithm, data) => Effect.succeed(data),
274 }),
275 ),
276 FileSystem.layerNoop({}),
277 );
278 yield* Effect.gen(function* () {
279 const service = yield* ThreadPullRequestService.make;
280 yield* service.start();
281 yield* Deferred.succeed(activation, undefined);
282 yield* Deferred.await(sweepStarted);
283 yield* service.drain;
284 }).pipe(Effect.provide(dependencies));
285​
286 if (sameBranch) {
287 expect(commands).toEqual([]);
288 } else {
289 expect(commands).toHaveLength(1);
290 expect(commands[0]).toMatchObject({
291 type: "thread.pull-request.sync",
292 threadId: thread.id,
293 branchPullRequest: null,
294 });
295 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
296 }
297 }),
298 ),
299 );
300});