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

ThreadPullRequestService.test.ts

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