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