The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,372 lines 50.1 KB
Raw
1 import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2ServerCommand as OrchestrationCommand,
7 PullRequestOperationError,
8 type OrchestrationProjectShell,
9 type PullRequestActionInput,
10 type PullRequestDiffResult,
11 type PullRequestSubmitReviewInput,
12 type PullRequestActivity,
13 type PullRequestListInput,
14 type PullRequestDetail,
15 type PullRequestRef,
16 type PullRequestReviewGuideResult,
17 type ThreadPullRequestLink,
18 SourceControlProviderKind,
19 } from "@t3tools/contracts";
20 import { describe, expect, it } from "@effect/vitest";
21 import * as SecureRandom from "effect/crypto/SecureRandom";
22 import * as Effect from "effect/Effect";
23 import * as Base64Url from "effect/encoding/Base64Url";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 import * as Ref from "effect/Ref";
27 import * as Stream from "effect/Stream";
28 import type { Tool } from "effect/ai";
29
30 import * as GitManager from "../../../git/GitManager.ts";
31 import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
32 import {
33 type PullRequestTestThread,
34 v2PullRequestThread,
35 } from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
36 import * as ProjectService from "../../../project/ProjectService.ts";
37 import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
38 import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
39 import * as PullRequestService from "../../../pullRequest/PullRequestService.ts";
40 import * as McpInvocationContext from "../../McpInvocationContext.ts";
41 import * as McpToolAccess from "../../McpToolAccess.ts";
42 import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
43 import { listThreadPullRequests } from "./handlers.ts";
44 import * as PullRequestsHandlers from "./handlers.ts";
45 import { CHILD_PULL_REQUEST_REPORT_NEXT, PullRequestsToolkit } from "./tools.ts";
46
47 const PROJECT_ID = ProjectId.make("project-1");
48 const THREAD_ID = ThreadId.make("thread-1");
49
50 const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7));
51
52 const invocation = (
53 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
54 ): McpInvocationContext.McpInvocationScope => ({
55 environmentId: EnvironmentId.make("environment-1"),
56 requestNamespace: "provider-session-1",
57 thread: {
58 threadId: THREAD_ID,
59 providerSessionId: "provider-session-1",
60 providerInstanceId: ProviderInstanceId.make("codex"),
61 },
62 client: undefined,
63 capabilities: new Set(capabilities),
64 issuedAt: 1,
65 });
66
67 function makeProject(
68 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
69 canonicalKey: "github.com/t3tools/t3code",
70 locator: {
71 source: "git-remote",
72 remoteName: "origin",
73 remoteUrl: "git@github.com:T3Tools/T3Code.git",
74 },
75 provider: SourceControlProviderKind.make("github"),
76 displayName: "T3Tools/T3Code",
77 owner: "T3Tools",
78 name: "T3Code",
79 },
80 ): OrchestrationProjectShell {
81 return {
82 id: PROJECT_ID,
83 title: "Project",
84 workspaceRoot: "/workspace/project",
85 defaultModelSelection: null,
86 scripts: [],
87 repositoryIdentity,
88 createdAt: "2026-08-01T00:00:00.000Z",
89 updatedAt: "2026-08-01T00:00:00.000Z",
90 };
91 }
92
93 function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
94 return {
95 id: THREAD_ID,
96 projectId: PROJECT_ID,
97 title: "Thread",
98 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
99 runtimeMode: "full-access",
100 interactionMode: "default",
101 branch: null,
102 worktreePath: null,
103 pullRequests,
104 createdAt: "2026-08-01T00:00:00.000Z",
105 updatedAt: "2026-08-20T00:00:00.000Z",
106 archivedAt: null,
107 settledOverride: null,
108 settledAt: null,
109 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
110 };
111 }
112
113 function makeLink(
114 number: number,
115 overrides: Partial<ThreadPullRequestLink> & {
116 readonly headBranch?: string;
117 readonly baseBranch?: string;
118 } = {},
119 ): ThreadPullRequestLink {
120 const { headBranch, baseBranch, ...rest } = overrides;
121 return {
122 host: "github.com",
123 repository: "t3tools/t3code",
124 number,
125 url: `https://github.com/t3tools/t3code/pull/${number}`,
126 source: "manual",
127 linkedAt: "2026-08-10T00:00:00.000Z",
128 snapshot:
129 headBranch === undefined
130 ? null
131 : {
132 state: "open",
133 title: `PR ${number}`,
134 headBranch,
135 baseBranch: baseBranch ?? "main",
136 isDraft: false,
137 updatedAt: null,
138 syncedAt: "2026-08-27T00:00:00.000Z",
139 },
140 stack: null,
141 ...rest,
142 };
143 }
144
145 interface HarnessOptions {
146 readonly thread?: PullRequestTestThread | null;
147 readonly project?: OrchestrationProjectShell | null;
148 readonly reject?: (command: OrchestrationCommand) => string | null;
149 readonly projects?: ReadonlyArray<OrchestrationProjectShell>;
150 readonly generate?: (
151 input: PullRequestRef,
152 ) => Effect.Effect<
153 PullRequestReviewGuideResult & { started: boolean },
154 PullRequestOperationError
155 >;
156 readonly pullRequests?: Partial<PullRequestService.PullRequestService["Service"]>;
157 readonly git?: Partial<GitManager.GitManager["Service"]>;
158 }
159
160 const NO_GUIDE: PullRequestReviewGuideResult = { guide: null, run: null, currentHeadSha: "head-1" };
161
162 const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
163 options: HarnessOptions = {},
164 ) {
165 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
166 const guideRequests = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
167 const thread = options.thread === undefined ? makeThread([]) : options.thread;
168 const project = options.project === undefined ? makeProject() : options.project;
169 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) =>
170 Effect.gen(function* () {
171 const rejection = options.reject?.(command) ?? null;
172 if (rejection !== null)
173 return yield* new Orchestrator.OrchestratorDispatchError({
174 commandId: command.commandId,
175 commandType: command.type,
176 cause: rejection,
177 });
178 yield* Ref.update(commands, (recorded) => [...recorded, command]);
179 return { sequence: 1, storedEvents: [] };
180 });
181 const layerDependencies = Layer.mergeAll(
182 Layer.mock(PullRequestWatchService.PullRequestWatchService)({}),
183 Layer.mock(ProjectService.ProjectService)({
184 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
185 listShells: () => Effect.succeed(options.projects ?? (project ? [project] : [])),
186 }),
187 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({
188 get: () => Effect.succeed(NO_GUIDE),
189 generate: (input) =>
190 Ref.update(guideRequests, (recorded) => [...recorded, input]).pipe(
191 Effect.andThen(
192 options.generate?.(input) ??
193 Effect.succeed({
194 ...NO_GUIDE,
195 run: {
196 _tag: "Running" as const,
197 headSha: "head-1",
198 startedAt: "2026-10-11T00:00:00.000Z",
199 },
200 started: true,
201 }),
202 ),
203 ),
204 }),
205 Layer.mock(Orchestrator.OrchestratorV2)({
206 getThreadShell: (id) =>
207 Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
208 dispatch,
209 }),
210 Layer.mock(PullRequestService.PullRequestService)(options.pullRequests ?? {}),
211 Layer.mock(GitManager.GitManager)(options.git ?? {}),
212 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
213 McpToolAccessTestkit.liveThreadsLayer,
214 );
215 const toolkit = yield* PullRequestsToolkit.pipe(
216 Effect.provide(
217 McpToolAccess.HandlersLayer.layer(PullRequestsHandlers.layer).pipe(
218 Layer.provide(layerDependencies),
219 ),
220 ),
221 );
222 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
223 name: Name,
224 params: Parameters<typeof toolkit.handle<Name>>[1],
225 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
226 ) =>
227 toolkit.handle(name, params).pipe(
228 Stream.unwrap,
229 Stream.runCollect,
230 Effect.map(
231 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
232 ),
233 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
234 Effect.provide(layerDependencies),
235 );
236 return { commands, guideRequests, call };
237 });
238
239 describe("pull request toolkit handlers", () => {
240 it.effect("refuses a credential without the pull-requests capability", () =>
241 Effect.gen(function* () {
242 const harness = yield* makeHarness();
243 const error = yield* harness
244 .call("list_thread_pull_requests", {}, ["preview"])
245 .pipe(Effect.flip);
246 expect(error).toMatchObject({
247 _tag: "McpCapabilityUnavailableError",
248 capability: "pull-requests",
249 threadId: THREAD_ID,
250 });
251 expect(yield* Ref.get(harness.commands)).toEqual([]);
252 }),
253 );
254
255 it.effect("points a bare thread uuid at the mcp: thread it belongs to", () =>
256 Effect.gen(function* () {
257 const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04");
258 const harness = yield* makeHarness({
259 thread: { ...makeThread([]), id: ThreadId.make(`mcp:${bareId}`) },
260 });
261 const error = yield* harness
262 .call("link_pull_request", { threadId: bareId, number: 123 })
263 .pipe(Effect.flip);
264 expect(error.message).toBe(
265 `Thread ${bareId} was not found. Did you mean \`mcp:${bareId}\`? Thread ids belong to one environment: for a thread on a linked one, find it with \`t3_environment_links\` and pass its \`environmentId\` to a tool that takes one.`,
266 );
267 expect(error).toMatchObject({ _tag: "OrchestratorMcpFailure", code: "thread_not_found" });
268 expect(yield* Ref.get(harness.commands)).toEqual([]);
269 }),
270 );
271
272 it.effect("links by URL with source agent on the token's thread", () =>
273 Effect.gen(function* () {
274 const harness = yield* makeHarness();
275 const result = yield* harness.call("link_pull_request", {
276 url: "https://github.com/T3Tools/T3Code/pull/123/files",
277 });
278 expect(result).toEqual({
279 host: "github.com",
280 repository: "t3tools/t3code",
281 number: 123,
282 url: "https://github.com/T3Tools/T3Code/pull/123/files",
283 alreadyLinked: false,
284 });
285 expect(yield* Ref.get(harness.commands)).toMatchObject([
286 {
287 type: "thread.pull-request.link",
288 threadId: THREAD_ID,
289 host: "github.com",
290 repository: "t3tools/t3code",
291 number: 123,
292 source: "agent",
293 },
294 ]);
295 }),
296 );
297
298 it.effect("asks a subagent thread to end with its PR report after it links", () =>
299 Effect.gen(function* () {
300 const harness = yield* makeHarness({
301 thread: {
302 ...makeThread([]),
303 lineage: {
304 rootThreadId: ThreadId.make("parent"),
305 parentThreadId: ThreadId.make("parent"),
306 relationshipToParent: "subagent",
307 },
308 },
309 });
310 const result = yield* harness.call("link_pull_request", {
311 url: "https://github.com/t3tools/t3code/pull/124",
312 });
313 expect(result).toMatchObject({ number: 124, next: CHILD_PULL_REQUEST_REPORT_NEXT });
314 }),
315 );
316
317 it.effect("canonicalizes GitCafe links independently of the thread's project host", () =>
318 Effect.gen(function* () {
319 for (const host of ["git.cafe", "staging.git.cafe"]) {
320 for (const project of [makeProject(), makeProject(null)]) {
321 for (const target of [
322 { host, repository: "PingDotGG/T3Code", number: 21353 },
323 { url: `https://${host}/PingDotGG/T3Code/pull/21353` },
324 { url: `https://${host}/PingDotGG/T3Code/pulls/21353` },
325 ]) {
326 const harness = yield* makeHarness({ project });
327 const result = yield* harness.call("link_pull_request", target);
328 const url = `https://${host}/pingdotgg/t3code/pulls/21353`;
329 expect(result).toMatchObject({
330 host,
331 repository: "pingdotgg/t3code",
332 number: 21353,
333 url,
334 });
335 expect(yield* Ref.get(harness.commands)).toMatchObject([
336 {
337 type: "thread.pull-request.link",
338 host,
339 repository: "pingdotgg/t3code",
340 number: 21353,
341 url,
342 },
343 ]);
344 }
345 }
346 }
347 }),
348 );
349
350 it.effect("builds the URL in the project host's own shape", () =>
351 Effect.gen(function* () {
352 const harness = yield* makeHarness({
353 project: makeProject({
354 canonicalKey: "gitlab.com/group/sub/project",
355 locator: {
356 source: "git-remote",
357 remoteName: "origin",
358 remoteUrl: "git@gitlab.com:group/sub/project.git",
359 },
360 provider: SourceControlProviderKind.make("gitlab"),
361 displayName: "group/sub/project",
362 }),
363 });
364 const result = yield* harness.call("link_pull_request", {
365 repository: "group/sub/project",
366 number: 42,
367 });
368 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
369 expect(result.host).toBe("gitlab.com");
370 const other = yield* harness.call("link_pull_request", {
371 host: "gitlab.example.test",
372 repository: "team/repo",
373 number: 7,
374 });
375 expect(other.url).toBe("https://gitlab.example.test/team/repo/-/merge_requests/7");
376 const onGitHub = yield* harness.call("link_pull_request", {
377 host: "github.com",
378 repository: "acme/web",
379 number: 9,
380 });
381 expect(onGitHub.url).toBe("https://github.com/acme/web/pull/9");
382 }),
383 );
384
385 it.effect("links a URL but not a bare number when the project's host is unknown", () =>
386 Effect.gen(function* () {
387 const harness = yield* makeHarness({
388 project: makeProject({
389 canonicalKey: "scm.example.test/tfs/collection/project/_git/repo",
390 locator: {
391 source: "git-remote",
392 remoteName: "origin",
393 remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo",
394 },
395 provider: SourceControlProviderKind.make("unknown"),
396 displayName: "tfs/collection/project/_git/repo",
397 }),
398 });
399 const error = yield* harness
400 .call("link_pull_request", { repository: "tfs/Collection/Project/_git/Repo", number: 124 })
401 .pipe(Effect.flip);
402 expect(error).toMatchObject({ _tag: "PullRequestUrlUnavailableError" });
403
404 const supplied = "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123";
405 const fromUrl = yield* harness.call("link_pull_request", { url: supplied });
406 expect(fromUrl).toEqual({
407 host: "scm.example.test",
408 repository: "tfs/collection/project/_git/repo",
409 number: 123,
410 url: supplied,
411 alreadyLinked: false,
412 });
413 expect(yield* Ref.get(harness.commands)).toMatchObject([
414 { type: "thread.pull-request.link", number: 123, url: supplied },
415 ]);
416 }),
417 );
418
419 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
420 Effect.gen(function* () {
421 const harness = yield* makeHarness({
422 thread: makeThread([makeLink(123)]),
423 reject: (command) =>
424 command.type === "thread.pull-request.link" ? "already linked" : null,
425 });
426 const result = yield* harness.call("link_pull_request", {
427 url: "https://github.com/t3tools/t3code/pull/123",
428 });
429 expect(result.alreadyLinked).toBe(true);
430 }),
431 );
432
433 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
434 Effect.gen(function* () {
435 const harness = yield* makeHarness({
436 thread: makeThread([makeLink(5)]),
437 reject: (command) =>
438 command.type === "thread.pull-request.unlink" && command.number !== 5
439 ? "not linked"
440 : null,
441 });
442 const linked = yield* harness.call("unlink_pull_request", {
443 repository: "t3tools/t3code",
444 number: 5,
445 });
446 expect(linked).toEqual({
447 host: "github.com",
448 repository: "t3tools/t3code",
449 number: 5,
450 wasLinked: true,
451 });
452 const missing = yield* harness.call("unlink_pull_request", {
453 url: "https://github.com/t3tools/t3code/pull/9",
454 });
455 expect(missing.wasLinked).toBe(false);
456 expect(yield* Ref.get(harness.commands)).toMatchObject([
457 { type: "thread.pull-request.unlink", number: 5 },
458 ]);
459 }),
460 );
461
462 it.effect("reports a dismissed stack member as not linked and leaves it dismissed", () =>
463 Effect.gen(function* () {
464 const harness = yield* makeHarness({
465 thread: makeThread([makeLink(9, { source: "stack-dismissed" })]),
466 });
467 const result = yield* harness.call("unlink_pull_request", {
468 repository: "t3tools/t3code",
469 number: 9,
470 });
471 expect(result.wasLinked).toBe(false);
472 expect(yield* Ref.get(harness.commands)).toEqual([]);
473 }),
474 );
475
476 it.effect("links several pull requests in one call", () =>
477 Effect.gen(function* () {
478 const harness = yield* makeHarness({
479 thread: makeThread([makeLink(1), { ...makeLink(2), source: "stack-dismissed" }]),
480 });
481 const url = (number: number) => `https://github.com/t3tools/t3code/pull/${number}`;
482 const result = yield* harness.call("link_pull_requests", {
483 urls: [url(1), url(2), url(3), url(3), "https://example.com/not-a-pr"],
484 });
485 expect(result).toEqual({
486 linked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [2, 3] }],
487 alreadyLinked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [1] }],
488 linkedCount: 3,
489 invalidUrls: ["https://example.com/not-a-pr"],
490 });
491 expect(yield* Ref.get(harness.commands)).toMatchObject([
492 { type: "thread.pull-request.link", number: 2, source: "agent" },
493 { type: "thread.pull-request.link", number: 3, source: "agent" },
494 ]);
495 }),
496 );
497
498 it.effect("unlinks every visible pull request in the given states in one call", () =>
499 Effect.gen(function* () {
500 const withState = (number: number, state: "open" | "closed" | "merged") => {
501 const link = makeLink(number, { headBranch: `branch-${number}` });
502 return { ...link, snapshot: { ...link.snapshot!, state } };
503 };
504 const harness = yield* makeHarness({
505 thread: makeThread([
506 withState(1, "merged"),
507 withState(2, "open"),
508 withState(3, "closed"),
509 makeLink(4),
510 { ...withState(5, "merged"), source: "stack-dismissed" },
511 ]),
512 });
513 const result = yield* harness.call("unlink_pull_requests", {
514 states: ["closed", "merged"],
515 });
516 expect(result).toEqual({
517 unlinked: [
518 { host: "github.com", repository: "t3tools/t3code", state: "merged", numbers: [1] },
519 { host: "github.com", repository: "t3tools/t3code", state: "closed", numbers: [3] },
520 ],
521 unlinkedCount: 2,
522 remaining: 2,
523 });
524 expect(yield* Ref.get(harness.commands)).toMatchObject([
525 { type: "thread.pull-request.unlink", number: 1 },
526 { type: "thread.pull-request.unlink", number: 3 },
527 ]);
528 }),
529 );
530
531 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
532 const result = listThreadPullRequests(
533 makeThread([
534 makeLink(42, {
535 host: "forge.example",
536 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
537 }),
538 ]),
539 );
540 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
541 });
542
543 it.effect("lists visible links with host state and derived chain order", () =>
544 Effect.gen(function* () {
545 const harness = yield* makeHarness({
546 thread: makeThread([
547 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
548 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
549 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
550 makeLink(9, { source: "stack-dismissed" }),
551 makeLink(10),
552 ]),
553 });
554 const result = yield* harness.call("list_thread_pull_requests", {});
555 expect(result.pullRequests.map((entry) => entry.number)).toEqual([1, 2, 3, 10]);
556 expect(result.pullRequests[2]).toEqual({
557 host: "github.com",
558 repository: "t3tools/t3code",
559 number: 3,
560 url: "https://github.com/t3tools/t3code/pull/3",
561 source: "agent",
562 watching: false,
563 state: "open",
564 title: "PR 3",
565 headBranch: "feat-c",
566 baseBranch: "feat-b",
567 isDraft: false,
568 stack: { kind: "derived", position: 3, size: 3 },
569 });
570 expect(result.pullRequests[3]).toMatchObject({
571 number: 10,
572 state: null,
573 title: null,
574 headBranch: null,
575 stack: null,
576 });
577 expect(result.chains).toEqual([
578 { kind: "derived", numbers: [1, 2, 3] },
579 { kind: "derived", numbers: [10] },
580 ]);
581 }),
582 );
583 });
584
585 describe("listThreadPullRequests", () => {
586 it("reports a native stack position for each member", () => {
587 const stack = {
588 kind: "native" as const,
589 id: "stack-1",
590 number: 1,
591 url: "https://github.com/t3tools/t3code/stack/1",
592 base: "main",
593 layers: [
594 { number: 1, headBranch: "a", state: "open" as const },
595 { number: 2, headBranch: "b", state: "open" as const },
596 ],
597 };
598 const result = listThreadPullRequests({
599 pullRequests: [
600 makeLink(2, { stack, source: "stack" }),
601 makeLink(1, { stack, source: "created" }),
602 ],
603 });
604 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
605 [1, { kind: "native", position: 1, size: 2 }],
606 [2, { kind: "native", position: 2, size: 2 }],
607 ]);
608 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
609 });
610
611 it("gives pull requests built on the same one the same position", () => {
612 const result = listThreadPullRequests({
613 pullRequests: [
614 makeLink(1, { headBranch: "feat-a", baseBranch: "main" }),
615 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a" }),
616 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-a" }),
617 ],
618 });
619 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
620 [1, { kind: "derived", position: 1, size: 3 }],
621 [2, { kind: "derived", position: 2, size: 3 }],
622 [3, { kind: "derived", position: 2, size: 3 }],
623 ]);
624 expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]);
625 });
626
627 it("pages a large list once through, with each page's stacks whole", () => {
628 const thread = {
629 pullRequests: [
630 makeLink(1, { headBranch: "feat-a" }),
631 ...Array.from({ length: 118 }, (_, index) => makeLink(index + 2)),
632 makeLink(120, { headBranch: "feat-z", baseBranch: "feat-a" }),
633 ],
634 };
635 const pages = [listThreadPullRequests(thread)];
636 for (let next = pages[0]!.nextCursor; next !== null; next = pages.at(-1)!.nextCursor) {
637 pages.push(listThreadPullRequests(thread, next));
638 }
639 expect(pages.map((page) => page.pullRequests.length)).toEqual([50, 50, 20]);
640 expect(pages.flatMap((page) => page.pullRequests.map((entry) => entry.number))).toEqual(
641 Array.from({ length: 120 }, (_, index) => index + 1),
642 );
643 const stack = { kind: "derived", numbers: [1, 120] };
644 expect(pages.map((page) => page.chains.length)).toEqual([50, 50, 20]);
645 expect(pages.map((page) => page.chains.filter((chain) => chain.numbers.length > 1))).toEqual([
646 [stack],
647 [],
648 [stack],
649 ]);
650
651 // Unlinking the first page must not shift the cursor past PRs not yet seen.
652 const remaining = { pullRequests: thread.pullRequests.slice(50) };
653 expect(
654 listThreadPullRequests(remaining, pages[0]!.nextCursor!).pullRequests.map(
655 (entry) => entry.number,
656 ),
657 ).toEqual(Array.from({ length: 50 }, (_, index) => index + 51));
658 });
659
660 it("filters by state before paging, counting a PR with no known state as open", () => {
661 const merged = (number: number) => {
662 const link = makeLink(number, { headBranch: `feat-${number}` });
663 return { ...link, snapshot: { ...link.snapshot!, state: "merged" as const } };
664 };
665 const thread = {
666 pullRequests: [
667 ...Array.from({ length: 50 }, (_, index) => merged(index + 1)),
668 ...Array.from({ length: 10 }, (_, index) => makeLink(index + 51)),
669 ],
670 };
671 const open = listThreadPullRequests(thread, undefined, ["open"]);
672 expect(open.pullRequests.map((entry) => entry.number)).toEqual(
673 Array.from({ length: 10 }, (_, index) => index + 51),
674 );
675 expect(open.nextCursor).toBeNull();
676 expect(listThreadPullRequests(thread, undefined, ["merged"]).nextCursor).toBeNull();
677 });
678 });
679
680 describe("pull request guide tools", () => {
681 it.effect(
682 "writes guides through the project whose checkout is each pull request's repository",
683 () =>
684 Effect.gen(function* () {
685 const other = {
686 ...makeProject({
687 canonicalKey: "github.com/acme/web",
688 locator: {
689 source: "git-remote",
690 remoteName: "origin",
691 remoteUrl: "git@github.com:acme/web.git",
692 },
693 provider: SourceControlProviderKind.make("github"),
694 displayName: "acme/web",
695 owner: "acme",
696 name: "web",
697 }),
698 id: ProjectId.make("project-web"),
699 };
700 // A fork's canonical key follows its upstream; its own repository is `origin`.
701 const fork = {
702 ...makeProject({
703 canonicalKey: "github.com/acme/web",
704 locator: {
705 source: "git-remote",
706 remoteName: "upstream",
707 remoteUrl: "https://github.com/acme/web.git",
708 },
709 origin: {
710 canonicalKey: "github.com/someone/web",
711 remoteUrl: "https://github.com/someone/web.git",
712 },
713 provider: SourceControlProviderKind.make("github"),
714 displayName: "acme/web",
715 owner: "acme",
716 name: "web",
717 }),
718 id: ProjectId.make("project-fork"),
719 };
720 const harness = yield* makeHarness({ projects: [makeProject(), other, fork] });
721 const result = yield* harness.call("write_pull_request_guides", {
722 pullRequests: [
723 { url: "https://github.com/acme/web/pull/7" },
724 { repository: "t3tools/t3code", number: 12 },
725 { url: "https://github.com/someone/else/pull/1" },
726 { url: "https://github.com/someone/web/pull/3" },
727 ],
728 });
729 expect(
730 result.guides.map((guide) => [guide.repository, guide.number, guide.outcome]),
731 ).toEqual([
732 ["acme/web", 7, "started"],
733 ["t3tools/t3code", 12, "started"],
734 ["someone/else", 1, "failed"],
735 ["someone/web", 3, "started"],
736 ]);
737 expect(result.guides[2]?.detail).toContain("No project in this environment");
738 expect(
739 (yield* Ref.get(harness.guideRequests)).map((ref) => [ref.projectId, ref.number]),
740 ).toEqual([
741 ["project-web", 7],
742 [PROJECT_ID, 12],
743 ["project-fork", 3],
744 ]);
745 }),
746 );
747
748 it.effect("reports an unreadable entry on its own and still writes the rest of the batch", () =>
749 Effect.gen(function* () {
750 const harness = yield* makeHarness();
751 const result = yield* harness.call("write_pull_request_guides", {
752 pullRequests: [
753 { url: "https://example.com/not-a-pull-request" },
754 { repository: "t3tools/t3code" },
755 { repository: "t3tools/t3code", number: 5 },
756 ],
757 });
758 expect(result.guides.map((guide) => guide.outcome)).toEqual(["failed", "failed", "started"]);
759 expect(result.guides[0]?.detail).toContain("not a recognised pull request URL");
760 expect(result.guides[1]?.detail).toContain("Pass either url");
761 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.number)).toEqual([5]);
762 }),
763 );
764
765 it.effect(
766 "reads a guide on a host readable without a checkout through the caller's project",
767 () =>
768 Effect.gen(function* () {
769 const api = makeProject({
770 canonicalKey: "bitbucket.org/acme/api",
771 locator: {
772 source: "git-remote",
773 remoteName: "origin",
774 remoteUrl: "git@bitbucket.org:acme/api.git",
775 },
776 provider: SourceControlProviderKind.make("bitbucket"),
777 displayName: "acme/api",
778 owner: "acme",
779 name: "api",
780 });
781 const harness = yield* makeHarness({ project: api });
782 const result = yield* harness.call("read_pull_request_guide", {
783 url: "https://bitbucket.org/acme/web/pull-requests/123",
784 });
785 expect(result).toMatchObject({
786 host: "bitbucket.org",
787 repository: "acme/web",
788 number: 123,
789 guide: null,
790 currentHeadSha: "head-1",
791 });
792 }),
793 );
794
795 it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () =>
796 Effect.gen(function* () {
797 const azure = {
798 ...makeProject({
799 canonicalKey: "dev.azure.com/org/project/_git/web",
800 locator: {
801 source: "git-remote",
802 remoteName: "origin",
803 remoteUrl: "https://dev.azure.com/org/project/_git/web",
804 },
805 provider: SourceControlProviderKind.make("azure-devops"),
806 displayName: "org/project/_git/web",
807 owner: "org",
808 name: "web",
809 }),
810 id: ProjectId.make("project-azure"),
811 };
812 const harness = yield* makeHarness({ projects: [makeProject(), azure] });
813 const result = yield* harness.call("write_pull_request_guides", {
814 pullRequests: [{ host: "dev.azure.com", repository: "org/project/_git/web", number: 9 }],
815 });
816 expect(result.guides.map((guide) => guide.outcome)).toEqual(["started"]);
817 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.projectId)).toEqual([
818 "project-azure",
819 ]);
820 }),
821 );
822 });
823
824 describe("source control tools", () => {
825 const branchThread = {
826 ...makeThread([]),
827 worktreePath: "/workspace/worktree",
828 branchPullRequest: {
829 projectId: PROJECT_ID,
830 repository: "t3tools/t3code",
831 number: 42,
832 url: "https://github.com/t3tools/t3code/pull/42",
833 },
834 };
835 const detail = {
836 title: "Add tools",
837 body: "Adds tools.",
838 state: "open",
839 isDraft: false,
840 author: null,
841 headBranch: "tools",
842 baseBranch: "main",
843 headSha: "abc123",
844 mergeability: "mergeable",
845 additions: 1,
846 deletions: 0,
847 changedFiles: 1,
848 labels: [],
849 reviewers: [],
850 checks: [
851 { name: "CI", status: "success", description: null, url: null },
852 { name: "Lint", status: "failure", description: null, url: null },
853 { name: "E2E", status: "cancelled", description: null, url: null },
854 { name: "Deploy", status: "pending", description: null, url: null },
855 {
856 name: "Approval",
857 status: "action-required",
858 description: null,
859 url: null,
860 placeholder: true,
861 },
862 { name: "Docs", status: "skipped", description: null, url: null },
863 ],
864 } as unknown as PullRequestDetail;
865 const reviewThread = (id: string, isResolved: boolean) => ({
866 id,
867 path: "a.ts",
868 line: 1,
869 side: "right" as const,
870 isResolved,
871 isOutdated: false,
872 comments: [],
873 });
874 const activity: PullRequestActivity = {
875 comments: [],
876 commentCount: 0,
877 commentsTruncated: false,
878 reviewThreads: [reviewThread("open-thread", false), reviewThread("done-thread", true)],
879 commits: [],
880 };
881
882 it.effect("reads the thread's branch PR compactly, adding only the sections asked", () =>
883 Effect.gen(function* () {
884 const asked: Array<PullRequestRef> = [];
885 let reviewThreadsTruncated = false;
886 const harness = yield* makeHarness({
887 thread: branchThread,
888 pullRequests: {
889 detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
890 activity: () => Effect.sync(() => ({ ...activity, reviewThreadsTruncated })),
891 },
892 });
893 const compact = yield* harness.call("pull_request_read", {});
894 expect(compact).toMatchObject({
895 headSha: "abc123",
896 checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true },
897 unresolvedThreads: 1,
898 });
899 expect(compact.body).toBeUndefined();
900 expect(compact.checkRuns).toBeUndefined();
901 expect(compact.conversation).toBeUndefined();
902 expect(compact.unresolvedThreadsTruncated).toBeUndefined();
903 const result = yield* harness.call("pull_request_read", { include: ["body", "threads"] });
904 expect(asked[1]).toEqual({
905 projectId: PROJECT_ID,
906 host: "github.com",
907 repository: "t3tools/t3code",
908 number: 42,
909 allowStale: false,
910 });
911 expect(result.body).toBe("Adds tools.");
912 expect(result.checkRuns).toBeUndefined();
913 expect(result.conversation?.comments).toBeUndefined();
914 expect(result.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual([
915 "open-thread",
916 ]);
917 // Unfetched threads may be unresolved, so the compact count says it is partial.
918 reviewThreadsTruncated = true;
919 expect(yield* harness.call("pull_request_read", {})).toMatchObject({
920 unresolvedThreads: 1,
921 unresolvedThreadsTruncated: true,
922 });
923 const commentsOnly = yield* harness.call("pull_request_read", { include: ["comments"] });
924 expect(commentsOnly.conversation?.truncated).toBe(false);
925 const threadsOnly = yield* harness.call("pull_request_read", { include: ["threads"] });
926 expect(threadsOnly.conversation?.truncated).toBe(true);
927 }),
928 );
929
930 it.effect("pages a long conversation and the PR list through the cursors they return", () =>
931 Effect.gen(function* () {
932 const comment = (body: string) =>
933 ({ id: body.slice(0, 8), author: null, body, createdAt: "2026-11-01T00:00:00Z" }) as never;
934 const long = (id: string) => ({
935 ...reviewThread(id, false),
936 comments: [comment("x".repeat(20_000))],
937 });
938 const listed: Array<PullRequestListInput> = [];
939 let firstResolved = false;
940 const harness = yield* makeHarness({
941 thread: branchThread,
942 pullRequests: {
943 detail: () => Effect.succeed(detail),
944 activity: () =>
945 Effect.sync(() => ({
946 ...activity,
947 reviewThreads: [
948 {
949 ...long("first"),
950 isResolved: firstResolved,
951 nextCommentsCursor: "later",
952 },
953 long("second"),
954 reviewThread("done-thread", true),
955 ],
956 })),
957 threadComments: (input) =>
958 Effect.succeed(
959 input.cursor === "later"
960 ? { comments: [comment("reply")], nextCursor: null }
961 : { comments: [], nextCursor: null },
962 ),
963 list: (input) =>
964 Effect.sync(() => listed.push(input)).pipe(
965 Effect.as({
966 viewers: {},
967 providers: [],
968 entries: [],
969 errors: [],
970 truncated: input.cursors === undefined,
971 nextCursors: input.cursors === undefined ? { "t3tools/t3code": "page-2" } : {},
972 }),
973 ),
974 },
975 });
976 const first = yield* harness.call("pull_request_read", { include: ["threads"] });
977 expect(first.conversation?.reviewThreads).toMatchObject([
978 { id: "first", moreComments: false, comments: [{}, { body: "reply" }] },
979 ]);
980 const cursor = first.conversation?.nextCursor;
981 expect(cursor).toEqual(expect.any(String));
982 // The agent resolves what it read; the next page still starts at the next thread.
983 firstResolved = true;
984 const second = yield* harness.call("pull_request_read", { cursor: cursor! });
985 expect(second.conversation?.comments).toBeUndefined();
986 expect(second.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual(["second"]);
987 expect(second.conversation?.nextCursor).toBeNull();
988 // A cursor past the current end finishes instead of repeating an empty page.
989 const stale = Base64Url.encode(
990 JSON.stringify({ threads: 99, comments: null, includeResolved: false }),
991 );
992 const past = yield* harness.call("pull_request_read", { cursor: stale });
993 expect(past.conversation).toMatchObject({ reviewThreads: [], nextCursor: null });
994
995 const page = yield* harness.call("pull_request_list", {});
996 yield* harness.call("pull_request_list", { cursor: page.nextCursor! });
997 expect(listed.map((input) => input.cursors)).toEqual([
998 undefined,
999 { "t3tools/t3code": "page-2" },
1000 ]);
1001 const invalid = yield* harness
1002 .call("pull_request_read", { cursor: "not-a-cursor" })
1003 .pipe(Effect.flip);
1004 expect(invalid._tag).toBe("PullRequestCursorInvalidError");
1005 }),
1006 );
1007
1008 it.effect("asks for a number when the thread's branch has no PR", () =>
1009 Effect.gen(function* () {
1010 const harness = yield* makeHarness();
1011 const error = yield* harness.call("pull_request_read", {}).pipe(Effect.flip);
1012 expect(error._tag).toBe("PullRequestBranchHasNoneError");
1013 }),
1014 );
1015
1016 it.effect("reads the PR this thread opened before status sync reports it", () =>
1017 Effect.gen(function* () {
1018 const asked: Array<PullRequestRef> = [];
1019 const opened = (headBranch: string) =>
1020 makeHarness({
1021 thread: { ...makeThread([makeLink(43, { source: "created" })]), branch: "tools" },
1022 pullRequests: {
1023 summary: () => Effect.succeed({ state: "open", headBranch } as never),
1024 detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
1025 activity: () => Effect.succeed(activity),
1026 },
1027 });
1028 const harness = yield* opened("tools");
1029 yield* harness.call("pull_request_read", {});
1030 expect(asked).toMatchObject([{ number: 43 }]);
1031
1032 // Before sync, the host says which branch it came from; another branch's is not this one.
1033 const moved = yield* opened("old");
1034 const unsynced = yield* moved.call("pull_request_read", {}).pipe(Effect.flip);
1035 expect(unsynced._tag).toBe("PullRequestBranchHasNoneError");
1036
1037 // After a switch to another branch, the PR opened from the old one is not the branch's.
1038 const switched = yield* makeHarness({
1039 thread: {
1040 ...makeThread([makeLink(43, { source: "created", headBranch: "old" })]),
1041 branch: "new",
1042 },
1043 });
1044 const error = yield* switched
1045 .call("pull_request_update", { title: "New title" })
1046 .pipe(Effect.flip);
1047 expect(error._tag).toBe("PullRequestBranchHasNoneError");
1048 }),
1049 );
1050
1051 it.effect("merges pinned to the head the agent checked", () =>
1052 Effect.gen(function* () {
1053 const actions: Array<PullRequestActionInput> = [];
1054 const harness = yield* makeHarness({
1055 thread: branchThread,
1056 pullRequests: {
1057 runAction: (input) => Effect.sync(() => void actions.push(input)),
1058 summary: () => Effect.succeed({ state: "open" } as never),
1059 },
1060 });
1061 const result = yield* harness.call("pull_request_merge", {
1062 expectedHeadSha: "abc123",
1063 method: "squash",
1064 auto: true,
1065 });
1066 expect(result).toMatchObject({ number: 42, state: "open" });
1067 expect(actions).toMatchObject([
1068 {
1069 number: 42,
1070 action: "enable-auto-merge",
1071 expectedHeadSha: "abc123",
1072 mergeMethod: "squash",
1073 },
1074 ]);
1075 }),
1076 );
1077
1078 it.effect("a stack merge pins every open layer up to the PR", () =>
1079 Effect.gen(function* () {
1080 const actions: Array<PullRequestActionInput> = [];
1081 let lowerHead: string | undefined = "bbb";
1082 let targetHead = "stale";
1083 const layer = (number: number, state: "open" | "merged", headSha: string | undefined) => ({
1084 number,
1085 state,
1086 ...(headSha === undefined ? {} : { headSha }),
1087 headBranch: `layer-${number}`,
1088 });
1089 const harness = yield* makeHarness({
1090 thread: branchThread,
1091 pullRequests: {
1092 stack: (_input, options) =>
1093 options?.bypassCache !== true
1094 ? Effect.die("a merge must not pin heads from the cache")
1095 : Effect.succeed({
1096 id: "stack-1",
1097 number: 7,
1098 url: "https://github.com/acme/app/stacks/7",
1099 base: "main",
1100 layers: [
1101 layer(40, "merged", "aaa"),
1102 layer(41, "open", lowerHead),
1103 layer(42, "open", targetHead),
1104 layer(43, "open", "ddd"),
1105 ],
1106 }),
1107 runAction: (input) => Effect.sync(() => void actions.push(input)),
1108 summary: () => Effect.succeed({ state: "merged" } as never),
1109 },
1110 });
1111 yield* harness.call("pull_request_merge", { expectedHeadSha: "ccc", stack: true });
1112 expect(actions).toMatchObject([
1113 {
1114 number: 42,
1115 action: "merge",
1116 stackNumber: 7,
1117 expectedStackHeads: [
1118 { number: 41, headSha: "bbb" },
1119 { number: 42, headSha: "ccc" },
1120 ],
1121 },
1122 ]);
1123 const fullHead = "c0ffee1234567890abcdef1234567890abcdef12";
1124 targetHead = fullHead;
1125 yield* harness.call("pull_request_merge", { expectedHeadSha: "c0ffee1", stack: true });
1126 expect(actions[1]?.expectedStackHeads).toEqual([
1127 { number: 41, headSha: "bbb" },
1128 { number: 42, headSha: fullHead },
1129 ]);
1130 lowerHead = undefined;
1131 const unpinned = yield* harness
1132 .call("pull_request_merge", { expectedHeadSha: "ccc", stack: true })
1133 .pipe(Effect.flip);
1134 expect(unpinned._tag).toBe("PullRequestForgeError");
1135 expect(actions).toHaveLength(2);
1136 }),
1137 );
1138
1139 it.effect("re-running checks reopens a watch that saw its checks finish", () =>
1140 Effect.gen(function* () {
1141 const watch = {
1142 startedAt: "2026-08-20T00:00:00.000Z",
1143 headSha: "abc123",
1144 failedChecks: ["test"],
1145 passed: false,
1146 passedChecks: [],
1147 remarksThrough: "2026-08-20T00:00:00.000Z",
1148 remarkIds: [],
1149 conflicting: false,
1150 wakes: 0,
1151 };
1152 const rerun = (checksPending: boolean | undefined, reran: boolean) =>
1153 Effect.gen(function* () {
1154 const harness = yield* makeHarness({
1155 thread: {
1156 ...branchThread,
1157 pullRequests: [
1158 makeLink(42, {
1159 watch: checksPending === undefined ? watch : { ...watch, checksPending },
1160 }),
1161 ],
1162 },
1163 pullRequests: {
1164 rerunChecks: () => Effect.succeed([{ name: "test", rerun: reran, detail: null }]),
1165 },
1166 });
1167 yield* harness.call("ci_rerun", {});
1168 return yield* Ref.get(harness.commands);
1169 });
1170 expect(yield* rerun(false, true)).toMatchObject([
1171 { type: "thread.pull-request-watch.checks-reopen", threadId: THREAD_ID },
1172 ]);
1173 // Nothing re-ran, or the watch has no answer to clear.
1174 expect(yield* rerun(false, false)).toEqual([]);
1175 expect(yield* rerun(undefined, true)).toEqual([]);
1176 }),
1177 );
1178
1179 it.effect("opens a PR from the thread's worktree and links it even if dismissed", () =>
1180 Effect.gen(function* () {
1181 const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = [];
1182 const harness = yield* makeHarness({
1183 thread: {
1184 ...makeThread([makeLink(43, { source: "stack-dismissed" })]),
1185 worktreePath: "/workspace/worktree",
1186 },
1187 git: {
1188 createPullRequest: (input) =>
1189 Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe(
1190 Effect.as({
1191 status: "created" as const,
1192 url: "https://github.com/t3tools/t3code/pull/43",
1193 number: 43,
1194 baseBranch: "main",
1195 headBranch: "tools",
1196 title: input.title,
1197 }),
1198 ),
1199 },
1200 });
1201 const result = yield* harness.call("pull_request_create", {
1202 title: "Add tools",
1203 body: "Adds tools.",
1204 draft: true,
1205 });
1206 expect(result).toMatchObject({ number: 43, created: true });
1207 expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]);
1208 expect(yield* Ref.get(harness.commands)).toMatchObject([
1209 { type: "thread.pull-request.link", number: 43, source: "created" },
1210 ]);
1211 }),
1212 );
1213
1214 it.effect("replies to and resolves a review thread, and refuses resolving without one", () =>
1215 Effect.gen(function* () {
1216 const calls: Array<string> = [];
1217 const harness = yield* makeHarness({
1218 thread: branchThread,
1219 pullRequests: {
1220 replyToThread: (input) => Effect.sync(() => calls.push(`reply ${input.threadId}`)),
1221 setThreadResolution: (input) =>
1222 input.threadId === "locked-thread"
1223 ? Effect.fail(
1224 new PullRequestOperationError({
1225 operation: "setThreadResolution",
1226 detail: "Locked.",
1227 }),
1228 )
1229 : Effect.sync(() => void calls.push(`resolve ${input.threadId} ${input.resolved}`)),
1230 },
1231 });
1232 const result = yield* harness.call("pull_request_respond", {
1233 reviewThreadId: "open-thread",
1234 body: "Fixed.",
1235 resolved: true,
1236 });
1237 expect(result).toMatchObject({ replied: true, resolved: true });
1238 expect(calls).toEqual(["reply open-thread", "resolve open-thread true"]);
1239 const partial = yield* harness
1240 .call("pull_request_respond", {
1241 reviewThreadId: "locked-thread",
1242 body: "Fixed.",
1243 resolved: true,
1244 })
1245 .pipe(Effect.flip);
1246 expect(partial.message).toContain("The reply was posted");
1247 const error = yield* harness
1248 .call("pull_request_respond", { body: "Done", resolved: true })
1249 .pipe(Effect.flip);
1250 expect(error._tag).toBe("PullRequestNothingToDoError");
1251 }),
1252 );
1253
1254 it.effect("places review comments by the diff page that shows their line", () =>
1255 Effect.gen(function* () {
1256 const reviews: Array<PullRequestSubmitReviewInput> = [];
1257 const pages: Record<string, PullRequestDiffResult> = {
1258 first: {
1259 patch:
1260 "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1,2 +1,2 @@\n-old\n+new\n same\n",
1261 truncated: false,
1262 nextCursor: "second",
1263 },
1264 second: {
1265 patch:
1266 "diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -9,1 +9,2 @@\n kept\n+added\n",
1267 truncated: false,
1268 nextCursor: null,
1269 },
1270 };
1271 const harness = yield* makeHarness({
1272 thread: branchThread,
1273 pullRequests: {
1274 diff: (input) => Effect.succeed(pages[input.cursor ?? "first"]!),
1275 submitReview: (input) => Effect.sync(() => void reviews.push(input)),
1276 },
1277 });
1278 yield* harness.call("pull_request_review", {
1279 verdict: "request-changes",
1280 body: "Two things.",
1281 comments: [
1282 { path: "b.ts", line: 10, startLine: 9, body: "Why?" },
1283 { path: "a.ts", line: 1, side: "old", body: "Keep this." },
1284 ],
1285 });
1286 expect(reviews).toMatchObject([
1287 {
1288 number: 42,
1289 verdict: "request-changes",
1290 body: "Two things.",
1291 comments: [
1292 {
1293 path: "b.ts",
1294 position: { kind: "added", newLine: 10 },
1295 startPosition: { kind: "context", oldLine: 9, newLine: 9, side: "right" },
1296 },
1297 { path: "a.ts", position: { kind: "deleted", oldLine: 1 } },
1298 ],
1299 },
1300 ]);
1301
1302 // A line the diff never shows fails before anything is posted.
1303 const error = yield* harness
1304 .call("pull_request_review", {
1305 verdict: "comment",
1306 comments: [{ path: "a.ts", line: 40, body: "Here?" }],
1307 })
1308 .pipe(Effect.flip);
1309 expect(error.message).toContain("a.ts line 40 (new side) is not in this PR's diff");
1310 expect(reviews).toHaveLength(1);
1311 }),
1312 );
1313
1314 it.effect("updates labels, requests reviewers by login, and closes the PR", () =>
1315 Effect.gen(function* () {
1316 const calls: Array<unknown> = [];
1317 const harness = yield* makeHarness({
1318 thread: branchThread,
1319 pullRequests: {
1320 setLabels: (input) =>
1321 Effect.sync(() => void calls.push(["labels", input.labels, input.applied])),
1322 reviewerCandidates: (input) =>
1323 Effect.succeed({
1324 candidates: [
1325 {
1326 id: "MDQ6VXNlcjE=",
1327 kind: "user",
1328 login: input.query === "Octo" ? "octo" : "x",
1329 name: null,
1330 avatarUrl: null,
1331 isRequested: false,
1332 },
1333 {
1334 id: "core",
1335 kind: "team",
1336 login: "acme/core",
1337 name: null,
1338 avatarUrl: null,
1339 isRequested: false,
1340 },
1341 ],
1342 } as never),
1343 requestReviewers: (input) =>
1344 Effect.sync(() => void calls.push(["reviewers", input.reviewers])),
1345 runAction: (input) => Effect.sync(() => void calls.push(["action", input.action])),
1346 },
1347 });
1348 yield* harness.call("pull_request_update", {
1349 addLabels: ["bug"],
1350 removeLabels: ["wip"],
1351 requestReviewers: ["Octo", "acme/core"],
1352 state: "closed",
1353 });
1354 expect(calls).toEqual([
1355 ["labels", ["bug"], true],
1356 ["labels", ["wip"], false],
1357 [
1358 "reviewers",
1359 [
1360 { id: "MDQ6VXNlcjE=", kind: "user" },
1361 { id: "core", kind: "team" },
1362 ],
1363 ],
1364 ["action", "close"],
1365 ]);
1366 const unknown = yield* harness
1367 .call("pull_request_update", { requestReviewers: ["nobody"] })
1368 .pipe(Effect.flip);
1369 expect(unknown.message).toContain("No reviewer named nobody");
1370 }),
1371 );
1372 });