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

ThreadPullRequestService.test.ts

302 lines11.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 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 // Reproduces #23702: an idle server with one active branch thread kept
89 // calling GitHub for that branch every minute with no client connected.
90 const thread = { ...threadShell("idle-branch-thread"), branch: "feature/idle" };
91 const project: OrchestrationProjectShell = {
92 id: thread.projectId,
93 title: "Project",
94 workspaceRoot: "/workspace/project",
95 defaultModelSelection: null,
96 scripts: [],
97 createdAt: "2026-08-01T00:00:00.000Z",
98 updatedAt: "2026-08-01T00:00:00.000Z",
99 };
100 const activation = yield* Deferred.make<void>();
101 const domainEvents = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
102 const turnLookup = yield* Deferred.make<void>();
103 const lookups: Array<{ readonly refresh: boolean }> = [];
104 const dependencies = Layer.mergeAll(
105 Layer.mock(Orchestrator.OrchestratorV2)({
106 streamDomainEvents: Stream.fromQueue(domainEvents),
107 getShellSnapshot: () =>
108 Effect.succeed({
109 schemaVersion: 2,
110 snapshotSequence: 1,
111 threads: [thread],
112 archivedThreads: [],
113 }),
114 getThreadEventSequence: () => Effect.succeed(1),
115 getThreadShell: () => Effect.succeed(thread),
116 }),
117 Layer.mock(ProjectStore.ProjectStoreV2)({
118 listShells: () => Effect.succeed([project]),
119 getShell: () => Effect.succeed(Option.some(project)),
120 }),
121 Layer.mock(GitManager.GitManager)({
122 branchPullRequest: (_input, options) =>
123 Effect.gen(function* () {
124 const refresh = options?.refresh ?? false;
125 lookups.push({ refresh });
126 if (refresh) yield* Deferred.succeed(turnLookup, undefined);
127 return null;
128 }),
129 }),
130 Layer.mock(PullRequestService.PullRequestService)({}),
131 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
132 resolve: () =>
133 Effect.succeed({
134 canonicalKey: "github.com/acme/project",
135 locator: {
136 source: "git-remote" as const,
137 remoteName: "origin",
138 remoteUrl: "git@github.com:acme/project.git",
139 },
140 provider: SourceControlProviderKind.make("github"),
141 owner: "acme",
142 name: "project",
143 }),
144 }),
145 // No client holds an activity lease.
146 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
147 hasDemand: () => Effect.succeed(false),
148 shouldRunScopeWork: () => Effect.succeed(false),
149 shouldRunOpportunisticWork: Effect.succeed(false),
150 }),
151 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
152 Layer.succeed(
153 Crypto.Crypto,
154 Crypto.make({
155 randomBytes: (size) => new Uint8Array(size).fill(1),
156 digest: (_algorithm, data) => Effect.succeed(data),
157 }),
158 ),
159 FileSystem.layerNoop({}),
160 );
161 yield* Effect.gen(function* () {
162 const service = yield* ThreadPullRequestService.make;
163 yield* service.start();
164 yield* Deferred.succeed(activation, undefined);
165​
166 // A finished turn still discovers the pull request for its branch.
167 yield* Queue.offer(domainEvents, {
168 type: "checkpoint.captured",
169 threadId: thread.id,
170 } as OrchestrationV2DomainEvent);
171 yield* Deferred.await(turnLookup);
172 yield* service.drain;
173 const lookupsBeforeIdle = lookups.length;
174​
175 yield* TestClock.adjust("10 minutes");
176 yield* service.drain;
177​
178 expect(lookups.slice(lookupsBeforeIdle)).toEqual([]);
179 }).pipe(Effect.provide(dependencies));
180 }),
181 ),
182 );
183​
184 it.effect.each([
185 { state: "closed", sameBranch: false },
186 { state: "merged", sameBranch: false },
187 { state: "closed", sameBranch: true },
188 { state: "merged", sameBranch: true },
189 ] as const)(
190 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
191 ({ state, sameBranch }) =>
192 Effect.scoped(
193 Effect.gen(function* () {
194 const savedReference = {
195 projectId: ProjectId.make("project-1"),
196 repository: "acme/project",
197 number: 42,
198 url: "https://github.com/acme/project/pull/42",
199 };
200 const thread = {
201 ...threadShell("branch-pr-thread"),
202 branch: "main",
203 branchPullRequest: savedReference,
204 linkedPullRequest: savedReference,
205 };
206 const project: OrchestrationProjectShell = {
207 id: thread.projectId,
208 title: "Project",
209 workspaceRoot: "/workspace/project",
210 defaultModelSelection: null,
211 scripts: [],
212 createdAt: "2026-08-01T00:00:00.000Z",
213 updatedAt: "2026-08-01T00:00:00.000Z",
214 };
215 const activation = yield* Deferred.make<void>();
216 const sweepStarted = yield* Deferred.make<void>();
217 const commands: Array<OrchestrationV2ServerCommand> = [];
218 const dependencies = Layer.mergeAll(
219 Layer.mock(Orchestrator.OrchestratorV2)({
220 streamDomainEvents: Stream.never,
221 getShellSnapshot: () =>
222 Deferred.succeed(sweepStarted, undefined).pipe(
223 Effect.as({
224 schemaVersion: 2,
225 snapshotSequence: 1,
226 threads: [thread],
227 archivedThreads: [],
228 }),
229 ),
230 dispatch: (command) =>
231 Effect.sync(() => {
232 commands.push(command);
233 return { sequence: 2, storedEvents: [] };
234 }),
235 }),
236 Layer.mock(ProjectStore.ProjectStoreV2)({
237 listShells: () => Effect.succeed([project]),
238 getShell: () => Effect.succeed(Option.some(project)),
239 }),
240 Layer.mock(GitManager.GitManager)({
241 branchPullRequest: () => Effect.succeed(null),
242 }),
243 Layer.mock(PullRequestService.PullRequestService)({
244 summary: () =>
245 Effect.succeed({
246 ...savedReference,
247 provider: SourceControlProviderKind.make("github"),
248 title: "Previous branch work",
249 state,
250 headBranch: sameBranch ? thread.branch : "feature/previous-work",
251 baseBranch: "release",
252 updatedAt: "2026-09-19T00:00:00.000Z",
253 }),
254 }),
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 Crypto.Crypto,
273 Crypto.make({
274 randomBytes: (size) => new Uint8Array(size).fill(1),
275 digest: (_algorithm, data) => Effect.succeed(data),
276 }),
277 ),
278 FileSystem.layerNoop({}),
279 );
280 yield* Effect.gen(function* () {
281 const service = yield* ThreadPullRequestService.make;
282 yield* service.start();
283 yield* Deferred.succeed(activation, undefined);
284 yield* Deferred.await(sweepStarted);
285 yield* service.drain;
286 }).pipe(Effect.provide(dependencies));
287​
288 if (sameBranch) {
289 expect(commands).toEqual([]);
290 } else {
291 expect(commands).toHaveLength(1);
292 expect(commands[0]).toMatchObject({
293 type: "thread.pull-request.sync",
294 threadId: thread.id,
295 branchPullRequest: null,
296 });
297 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
298 }
299 }),
300 ),
301 );
302});