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

PullRequestWatchService.test.ts

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