Open History to see the last commit
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 Option from "effect/Option";
18import * as Ref from "effect/Ref";
19
20import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
21import {
22 type PullRequestTestThread,
23 v2PullRequestThread,
24} from "../orchestration-v2/testkit/pullRequestFixtures.ts";
25import * as ProjectService from "../project/ProjectService.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 };
58}
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 };
78}
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 };
110}
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}
119
120const makeHarness = Effect.fn("makePullRequestWatchHarness")(function* (
121 options: HarnessOptions = {},
122) {
123 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
124 const thread = options.thread === undefined ? makeThread([]) : options.thread;
125 const project = options.project === undefined ? makeProject() : options.project;
126 const dependencies = Layer.mergeAll(
127 Layer.mock(ProjectService.ProjectService)({
128 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
129 }),
130 Layer.mock(Orchestrator.OrchestratorV2)({
131 getThreadShell: (id) =>
132 Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
133 dispatch: (command) =>
134 Ref.update(commands, (recorded) => [...recorded, command]).pipe(
135 Effect.as({ sequence: 1, storedEvents: [] }),
136 ),
137 }),
138 Layer.mock(PullRequestService.PullRequestService)({
139 summary: (input) =>
140 options.readFailure !== undefined
141 ? Effect.fail(options.readFailure)
142 : Effect.succeed({
143 ...input,
144 provider: SourceControlProviderKind.make("github"),
145 title: "Pull request",
146 url: `https://github.com/${input.repository}/pull/${input.number}`,
147 state: options.readState ?? "open",
148 ...(options.readChecksState !== undefined && {
149 checksState: options.readChecksState,
150 }),
151 headBranch: "feature",
152 baseBranch: "main",
153 updatedAt: "2026-08-20T00:00:00.000Z",
154 }),
155 }),
156 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
157 );
158 const service = yield* PullRequestWatchService.PullRequestWatchService.pipe(
159 Effect.provide(PullRequestWatchService.layer.pipe(Layer.provide(dependencies))),
160 );
161 return {
162 commands,
163 setWatching: (watching: boolean, target: PullRequestTarget) =>
164 service.setWatching({ threadId: THREAD_ID, target, watching }),
165 };
166});
167
168describe("PullRequestWatchService", () => {
169 it.effect("links an unlinked watch even while the host has a transient read failure", () =>
170 Effect.gen(function* () {
171 const cases: ReadonlyArray<readonly [HarnessOptions, boolean | undefined]> = [
172 [{ readChecksState: "pending" }, true],
173 [{ readChecksState: "failing" }, false],
174 [{}, false],
175 [
176 {
177 readFailure: new PullRequestOperationError({
178 operation: "summary",
179 detail: "The host is temporarily unavailable.",
180 }),
181 },
182 undefined,
183 ],
184 ];
185 for (const [options, checksPending] of cases) {
186 const harness = yield* makeHarness(options);
187 const result = yield* harness.setWatching(true, {
188 url: "https://github.com/t3tools/t3code/pull/9",
189 });
190 expect(result).toMatchObject({ number: 9, wasWatching: false });
191 const commands = yield* Ref.get(harness.commands);
192 expect(commands).toMatchObject([
193 {
194 type: "thread.pull-request.watch",
195 number: 9,
196 watching: true,
197 link: { url: "https://github.com/t3tools/t3code/pull/9", source: "agent" },
198 },
199 ]);
200 const [command] = commands;
201 expect(command?.type === "thread.pull-request.watch" ? command.checksPending : null).toBe(
202 checksPending,
203 );
204 }
205 }),
206 );
207
208 it.effect("tells the caller when the checks already passed, since no wake will report it", () =>
209 Effect.gen(function* () {
210 const harness = yield* makeHarness({ readChecksState: "passing" });
211 const result = yield* harness.setWatching(true, {
212 url: "https://github.com/t3tools/t3code/pull/9",
213 });
214 expect(result).toMatchObject({ wasWatching: false, checksState: "passing" });
215 }),
216 );
217
218 it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () =>
219 Effect.gen(function* () {
220 const missing = new PullRequestUnavailableError({
221 reason: "cli-missing",
222 provider: SourceControlProviderKind.make("gitlab"),
223 requirement: "Install glab on the T3 server's PATH.",
224 });
225 const harness = yield* makeHarness({ readFailure: missing });
226 const target = { url: "https://gitlab.example.com/team/project/-/merge_requests/42" };
227 const error = yield* harness.setWatching(true, target).pipe(Effect.flip);
228 expect(error).toEqual(missing);
229 expect(yield* Ref.get(harness.commands)).toEqual([]);
230
231 yield* harness.setWatching(false, target);
232 expect(yield* Ref.get(harness.commands)).toMatchObject([
233 { type: "thread.pull-request.watch", watching: false },
234 ]);
235 }),
236 );
237
238 it.effect("reports merged PRs without watching and keeps an active watch usable offline", () =>
239 Effect.gen(function* () {
240 const freshMerged = yield* makeHarness({ readState: "merged" });
241 expect(
242 yield* freshMerged.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
243 ).toMatchObject({ number: 1, watching: false, wasWatching: false, state: "merged" });
244 expect(yield* Ref.get(freshMerged.commands)).toEqual([]);
245
246 const watch = {
247 startedAt: "2026-08-20T00:00:00.000Z",
248 headSha: null,
249 failedChecks: [],
250 passed: false,
251 passedChecks: [],
252 remarksThrough: "2026-08-20T00:00:00.000Z",
253 remarkIds: [],
254 conflicting: false,
255 wakes: 0,
256 };
257 const merged = makeLink(1, { headBranch: "done" });
258 const harness = yield* makeHarness({
259 readFailure: new PullRequestUnavailableError({ reason: "cli-missing" }),
260 thread: makeThread([
261 { ...merged, snapshot: merged.snapshot && { ...merged.snapshot, state: "merged" } },
262 makeLink(2, { headBranch: "idle" }),
263 makeLink(3, { headBranch: "watched", watch }),
264 ]),
265 });
266 expect(
267 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
268 ).toMatchObject({ number: 1, watching: false, state: "merged" });
269 expect(
270 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 3 }),
271 ).toMatchObject({ watching: true, wasWatching: true });
272 expect(
273 yield* harness.setWatching(false, { repository: "t3tools/t3code", number: 3 }),
274 ).toMatchObject({ wasWatching: true });
275 expect(yield* Ref.get(harness.commands)).toMatchObject([
276 { type: "thread.pull-request.watch", number: 3, watching: true },
277 { type: "thread.pull-request.watch", number: 3, watching: false },
278 ]);
279 }),
280 );
281
282 it.effect("re-reads a pull request saved as closed, and watches it only if it reopened", () =>
283 Effect.gen(function* () {
284 const closed = makeLink(1, { headBranch: "closed" });
285 const closedThread = makeThread([
286 { ...closed, snapshot: closed.snapshot && { ...closed.snapshot, state: "closed" } },
287 ]);
288 const stillClosed = yield* makeHarness({ readState: "closed", thread: closedThread });
289 expect(
290 yield* stillClosed.setWatching(true, { repository: "t3tools/t3code", number: 1 }),
291 ).toMatchObject({ watching: false, state: "closed" });
292 expect(yield* Ref.get(stillClosed.commands)).toEqual([]);
293
294 const harness = yield* makeHarness({ readState: "open", thread: closedThread });
295 yield* harness.setWatching(true, { repository: "t3tools/t3code", number: 1 });
296 expect(yield* Ref.get(harness.commands)).toMatchObject([
297 { type: "thread.pull-request.watch", number: 1, watching: true },
298 ]);
299 }),
300 );
301
302 it.effect("refuses a watch from a subagent thread, whose parent owns the pull request", () =>
303 Effect.gen(function* () {
304 const harness = yield* makeHarness({
305 thread: {
306 ...makeThread([makeLink(1, { headBranch: "feature" })]),
307 lineage: {
308 rootThreadId: ThreadId.make("parent"),
309 parentThreadId: ThreadId.make("parent"),
310 relationshipToParent: "subagent",
311 },
312 },
313 });
314 const error = yield* harness
315 .setWatching(true, { repository: "t3tools/t3code", number: 1 })
316 .pipe(Effect.flip);
317 expect(error).toMatchObject({ _tag: "PullRequestWatchFromSubagentError" });
318 expect(yield* Ref.get(harness.commands)).toEqual([]);
319 }),
320 );
321});