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

PullRequestWatchService.test.ts

374 lines14.0 KB

1import {
2 ProjectId,
3 ProviderInstanceId,
4 ThreadId,
5 PullRequestOperationError,
6 PullRequestUnavailableError,
7 type PullRequestSummary,
8 type OrchestrationV2ServerCommand as OrchestrationCommand,
9 type OrchestrationProjectShell,
10 type ThreadPullRequestLink,
11 SourceControlProviderKind,
12} from "@t3tools/contracts";
13import { describe, expect, it } from "@effect/vitest";
14import * as SecureRandom from "effect/crypto/SecureRandom";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as Ref from "effect/Ref";
20​
21import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
22import {
23 type PullRequestTestThread,
24 v2PullRequestThread,
25} from "../orchestration-v2/testkit/pullRequestFixtures.ts";
26import * as PullRequestService from "./PullRequestService.ts";
27import * as PullRequestWatchService from "./PullRequestWatchService.ts";
28import type { PullRequestTarget } from "./pullRequestTarget.ts";
29​
30const PROJECT_ID = ProjectId.make("project-1");
31const THREAD_ID = ThreadId.make("thread-1");
32const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7));
33​
34function makeProject(
35 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
36 canonicalKey: "github.com/t3tools/t3code",
37 locator: {
38 source: "git-remote",
39 remoteName: "origin",
40 remoteUrl: "git@github.com:T3Tools/T3Code.git",
41 },
42 provider: SourceControlProviderKind.make("github"),
43 displayName: "T3Tools/T3Code",
44 owner: "T3Tools",
45 name: "T3Code",
46 },
47): OrchestrationProjectShell {
48 return {
49 id: PROJECT_ID,
50 title: "Project",
51 workspaceRoot: "/workspace/project",
52 defaultModelSelection: null,
53 scripts: [],
54 repositoryIdentity,
55 createdAt: "2026-08-01T00:00:00.000Z",
56 updatedAt: "2026-08-01T00:00:00.000Z",
57 };
59​
60function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
61 return {
62 id: THREAD_ID,
63 projectId: PROJECT_ID,
64 title: "Thread",
65 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
66 runtimeMode: "full-access",
67 interactionMode: "default",
68 branch: null,
69 worktreePath: null,
70 pullRequests,
71 createdAt: "2026-08-01T00:00:00.000Z",
72 updatedAt: "2026-08-20T00:00:00.000Z",
73 archivedAt: null,
74 settledOverride: null,
75 settledAt: null,
76 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
77 };
79​
80function makeLink(
81 number: number,
82 overrides: Partial<ThreadPullRequestLink> & {
83 readonly headBranch?: string;
84 readonly baseBranch?: string;
85 } = {},
86): ThreadPullRequestLink {
87 const { headBranch, baseBranch, ...rest } = overrides;
88 return {
89 host: "github.com",
90 repository: "t3tools/t3code",
91 number,
92 url: `https://github.com/t3tools/t3code/pull/${number}`,
93 source: "manual",
94 linkedAt: "2026-08-10T00:00:00.000Z",
95 snapshot:
96 headBranch === undefined
97 ? null
98 : {
99 state: "open",
100 title: `PR ${number}`,
101 headBranch,
102 baseBranch: baseBranch ?? "main",
103 isDraft: false,
104 updatedAt: null,
105 syncedAt: "2026-08-27T00:00:00.000Z",
106 },
107 stack: null,
108 ...rest,
109 };
111​
112interface HarnessOptions {
113 readonly thread?: PullRequestTestThread | null;
114 readonly project?: OrchestrationProjectShell | null;
115 readonly readFailure?: PullRequestService.PullRequestError;
116 readonly readState?: PullRequestSummary["state"];
117 readonly readChecksState?: PullRequestSummary["checksState"];
118 /** Holds only the first project lookup, so a later call can finish first. */
119 readonly holdProject?: {
120 readonly reached: Deferred.Deferred<void>;
121 readonly release: Deferred.Deferred<void>;
122 };
123 /** Holds every summary read until this many reads are in flight at once. */
124 readonly holdReadsUntil?: number;
126​
127const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* (
128 options: HarnessOptions = {},
129) {
130 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
131 const thread = options.thread === undefined ? makeThread([]) : options.thread;
132 const project = options.project === undefined ? makeProject() : options.project;
133 let projectLookups = 0;
134 const { holdReadsUntil } = options;
135 let reads = 0;
136 const readsArrived = yield* Deferred.make<void>();
137 const dependencies = Layer.mergeAll(
138 Layer.mock(Orchestrator.OrchestratorV2)({
139 getThreadShell: (id) =>
140 Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
141 dispatch: (command) =>
142 Ref.update(commands, (recorded) => [...recorded, command]).pipe(
143 Effect.as({ sequence: 1, storedEvents: [] }),
144 ),
145 }),
146 Layer.mock(PullRequestService.PullRequestService)({
147 addressedProject: () =>
148 (options.holdProject === undefined || projectLookups++ > 0
149 ? Effect.void
150 : Deferred.succeed(options.holdProject.reached, undefined).pipe(
151 Effect.andThen(Deferred.await(options.holdProject.release)),
152 )
153 ).pipe(Effect.as(project ?? undefined)),
154 summary: (input) =>
155 (holdReadsUntil === undefined
156 ? Effect.void
157 : Effect.suspend(() =>
158 ++reads >= holdReadsUntil
159 ? Deferred.succeed(readsArrived, undefined)
160 : Deferred.await(readsArrived),
161 )
162 ).pipe(
163 Effect.andThen(() =>
164 options.readFailure !== undefined
165 ? Effect.fail(options.readFailure)
166 : Effect.succeed({
167 ...input,
168 provider: SourceControlProviderKind.make("github"),
169 title: "Pull request",
170 url: `https://github.com/${input.repository}/pull/${input.number}`,
171 state: options.readState ?? "open",
172 ...(options.readChecksState !== undefined && {
173 checksState: options.readChecksState,
174 }),
175 headBranch: "feature",
176 baseBranch: "main",
177 updatedAt: "2026-08-20T00:00:00.000Z",
178 }),
179 ),
180 ),
181 }),
182 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
183 );
184 const service = yield* PullRequestWatchService.PullRequestWatchService.pipe(
185 Effect.provide(PullRequestWatchService.layer.pipe(Layer.provide(dependencies))),
186 );
187 return {
188 commands,
189 setWatching: (watching: boolean, target: PullRequestTarget) =>
190 service.setWatching({ threadId: THREAD_ID, target, watching }),
191 };
192});
193​
194describe("PullRequestWatchService", () => {
195 it.effect("links an unlinked watch even while the host has a transient read failure", () =>
196 Effect.gen(function* () {
197 const cases: ReadonlyArray<readonly [HarnessOptions, boolean | undefined]> = [
198 [{ readChecksState: "pending" }, true],
199 [{ readChecksState: "failing" }, false],
200 [{}, false],
201 [
202 {
203 readFailure: new PullRequestOperationError({
204 operation: "summary",
205 detail: "The host is temporarily unavailable.",
206 }),
207 },
208 undefined,
209 ],
210 ];
211 for (const [options, checksPending] of cases) {
212 const harness = yield* makeHarness(options);
213 const result = yield* harness.setWatching(true, {
214 url: "https://github.com/t3tools/t3code/pull/9",
215 });
216 expect(result).toMatchObject({ number: 9, wasWatching: false });
217 const commands = yield* Ref.get(harness.commands);
218 expect(commands).toMatchObject([
219 {
220 type: "thread.pull-request.watch",
221 number: 9,
222 watching: true,
223 link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
224 },
225 ]);
226 const [command] = commands;
227 expect(command?.type === "thread.pull-request.watch" ? command.checksPending : null).toBe(
228 checksPending,
229 );
230 }
231 }),
232 );
233​
234 it.effect("tells the caller when the checks already passed, since no wake will report it", () =>
235 Effect.gen(function* () {
236 const harness = yield* makeHarness({ readChecksState: "passing" });
237 const result = yield* harness.setWatching(true, {
238 url: "https://github.com/t3tools/t3code/pull/9",
239 });
240 expect(result).toMatchObject({ wasWatching: false, checksState: "passing" });
241 }),
242 );
243​
244 it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () =>
245 Effect.gen(function* () {
246 const missing = new PullRequestUnavailableError({
247 reason: "cli-missing",
248 provider: SourceControlProviderKind.make("gitlab"),
249 requirement: "Install glab on the T3 server's PATH.",
250 });
251 const harness = yield* makeHarness({ readFailure: missing });
252 const target = { url: "https://gitlab.example.com/team/project/-/merge_requests/42" };
253 const error = yield* harness.setWatching(true, target).pipe(Effect.flip);
254 expect(error).toEqual(missing);
255 expect(yield* Ref.get(harness.commands)).toEqual([]);
256​
257 yield* harness.setWatching(false, target);
258 expect(yield* Ref.get(harness.commands)).toMatchObject([
259 { type: "thread.pull-request.watch", watching: false },
260 ]);
261 }),
262 );
263​
264 it.effect("reports merged PRs without watching and keeps an active watch usable offline", () =>
265 Effect.gen(function* () {
266 const freshMerged = yield* makeHarness({ readState: "merged" });
267 expect(
268 yield* freshMerged.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
269 ).toMatchObject({ number: 1, watching: false, wasWatching: false, state: "merged" });
270 expect(yield* Ref.get(freshMerged.commands)).toEqual([]);
271​
272 const watch = {
273 startedAt: "2026-08-20T00:00:00.000Z",
274 headSha: null,
275 failedChecks: [],
276 passed: false,
277 passedChecks: [],
278 remarksThrough: "2026-08-20T00:00:00.000Z",
279 remarkIds: [],
280 conflicting: false,
281 wakes: 0,
282 };
283 const merged = makeLink(1, { headBranch: "done" });
284 const harness = yield* makeHarness({
285 readFailure: new PullRequestUnavailableError({ reason: "cli-missing" }),
286 thread: makeThread([
287 { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
288 makeLink(2, { headBranch: "idle" }),
289 makeLink(3, { headBranch: "watched", watch }),
290 ]),
291 });
292 expect(
293 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
294 ).toMatchObject({ number: 1, watching: false, state: "merged" });
295 expect(
296 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 3 }),
297 ).toMatchObject({ watching: true, wasWatching: true });
298 expect(
299 yield* harness.setWatching(false, { repository: "t3tools/t3code", number: 3 }),
300 ).toMatchObject({ wasWatching: true });
301 expect(yield* Ref.get(harness.commands)).toMatchObject([
302 { type: "thread.pull-request.watch", number: 3, watching: true },
303 { type: "thread.pull-request.watch", number: 3, watching: false },
304 ]);
305 }),
306 );
307​
308 it.effect("re-reads a pull request saved as closed, and watches it only if it reopened", () =>
309 Effect.gen(function* () {
310 const closed = makeLink(1, { headBranch: "closed" });
311 const closedThread = makeThread([
312 { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
313 ]);
314 const stillClosed = yield* makeHarness({ readState: "closed", thread: closedThread });
315 expect(
316 yield* stillClosed.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
317 ).toMatchObject({ watching: false, state: "closed" });
318 expect(yield* Ref.get(stillClosed.commands)).toEqual([]);
319​
320 const harness = yield* makeHarness({ readState: "open", thread: closedThread });
321 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 });
322 expect(yield* Ref.get(harness.commands)).toMatchObject([
323 { type: "thread.pull-request.watch", number: 1, watching: true },
324 ]);
325 }),
326 );
327​
328 it.effect("registers a start only when no later stop has run", () =>
329 Effect.gen(function* () {
330 const target = { url: "https://github.com/t3tools/t3code/pull/9" };
331 const holdProject = {
332 reached: yield* Deferred.make<void>(),
333 release: yield* Deferred.make<void>(),
334 };
335 const stopped = yield* makeHarness({ holdProject });
336 const starting = yield* stopped.setWatching(true, target).pipe(Effect.forkChild);
337 yield* Deferred.await(holdProject.reached);
338 yield* stopped.setWatching(false, target);
339 yield* Deferred.succeed(holdProject.release, undefined);
340 expect(yield* Fiber.join(starting)).toMatchObject({ watching: false });
341 expect(yield* Ref.get(stopped.commands)).toMatchObject([{ watching: false }]);
342​
343 const overlapping = yield* makeHarness({ holdReadsUntil: 2 });
344 const first = yield* overlapping.setWatching(true, target).pipe(Effect.forkChild);
345 const second = yield* overlapping.setWatching(true, target).pipe(Effect.forkChild);
346 yield* Fiber.join(first);
347 yield* Fiber.join(second);
348 expect(yield* Ref.get(overlapping.commands)).toMatchObject([
349 { watching: true },
350 { watching: true },
351 ]);
352 }),
353 );
354​
355 it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
356 Effect.gen(function* () {
357 const harness = yield* makeHarness({
358 thread: {
359 ...makeThread([makeLink(1, { headBranch: "feature" })]),
360 lineage: {
361 rootThreadId: ThreadId.make("parent"),
362 parentThreadId: ThreadId.make("parent"),
363 relationshipToParent: "subagent",
364 },
365 },
366 });
367 const error = yield* harness
368 .setWatching(true, { repository: "t3tools/t3code", number: 1 })
369 .pipe(Effect.flip);
370 expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
371 expect(yield* Ref.get(harness.commands)).toEqual([]);
372 }),
373 );
374});