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

handlers.test.ts

1,381 lines50.4 KB

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 };
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 };
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 };
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"]>;
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)(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​
239describe("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​
585describe("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​
680describe("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​
824describe("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 visibility: "private",
841 author: null,
842 headBranch: "tools",
843 baseBranch: "main",
844 headSha: "abc123",
845 mergeability: "mergeable",
846 additions: 1,
847 deletions: 0,
848 changedFiles: 1,
849 labels: [],
850 reviewers: [],
851 checks: [
852 { name: "CI", status: "success", description: null, url: null },
853 { name: "Lint", status: "failure", description: null, url: null },
854 { name: "E2E", status: "cancelled", description: null, url: null },
855 { name: "Deploy", status: "pending", description: null, url: null },
856 {
857 name: "Approval",
858 status: "action-required",
859 description: null,
860 url: null,
861 placeholder: true,
862 },
863 { name: "Docs", status: "skipped", description: null, url: null },
864 ],
865 } as unknown as PullRequestDetail;
866 const reviewThread = (id: string, isResolved: boolean) => ({
867 id,
868 path: "a.ts",
869 line: 1,
870 side: "right" as const,
871 isResolved,
872 isOutdated: false,
873 comments: [],
874 });
875 const activity: PullRequestActivity = {
876 comments: [],
877 commentCount: 0,
878 commentsTruncated: false,
879 reviewThreads: [reviewThread("open-thread", false), reviewThread("done-thread", true)],
880 commits: [],
881 };
882​
883 it.effect("reads the thread's branch PR compactly, adding only the sections asked", () =>
884 Effect.gen(function* () {
885 const asked: Array<PullRequestRef> = [];
886 let reviewThreadsTruncated = false;
887 const harness = yield* makeHarness({
888 thread: branchThread,
889 pullRequests: {
890 detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
891 activity: () => Effect.sync(() => ({ ...activity, reviewThreadsTruncated })),
892 },
893 });
894 const compact = yield* harness.call("pull_request_read", {});
895 expect(compact).toMatchObject({
896 visibility: "private",
897 headSha: "abc123",
898 checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true },
899 unresolvedThreads: 1,
900 });
901 expect(compact.body).toBeUndefined();
902 expect(compact.checkRuns).toBeUndefined();
903 expect(compact.conversation).toBeUndefined();
904 expect(compact.unresolvedThreadsTruncated).toBeUndefined();
905 const result = yield* harness.call("pull_request_read", { include: ["body", "threads"] });
906 expect(asked[1]).toEqual({
907 projectId: PROJECT_ID,
908 host: "github.com",
909 repository: "t3tools/t3code",
910 number: 42,
911 allowStale: false,
912 });
913 expect(result.body).toBe("Adds tools.");
914 expect(result.checkRuns).toBeUndefined();
915 expect(result.conversation?.comments).toBeUndefined();
916 expect(result.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual([
917 "open-thread",
918 ]);
919 // Unfetched threads may be unresolved, so the compact count says it is partial.
920 reviewThreadsTruncated = true;
921 expect(yield* harness.call("pull_request_read", {})).toMatchObject({
922 unresolvedThreads: 1,
923 unresolvedThreadsTruncated: true,
924 });
925 const commentsOnly = yield* harness.call("pull_request_read", { include: ["comments"] });
926 expect(commentsOnly.conversation?.truncated).toBe(false);
927 const threadsOnly = yield* harness.call("pull_request_read", { include: ["threads"] });
928 expect(threadsOnly.conversation?.truncated).toBe(true);
929 }),
930 );
931​
932 it.effect("pages a long conversation and the PR list through the cursors they return", () =>
933 Effect.gen(function* () {
934 const comment = (body: string) =>
935 ({ id: body.slice(0, 8), author: null, body, createdAt: "2026-11-01T00:00:00Z" }) as never;
936 const long = (id: string) => ({
937 ...reviewThread(id, false),
938 comments: [comment("x".repeat(20_000))],
939 });
940 const listed: Array<PullRequestListInput> = [];
941 let firstResolved = false;
942 const harness = yield* makeHarness({
943 thread: branchThread,
944 pullRequests: {
945 detail: () => Effect.succeed(detail),
946 activity: () =>
947 Effect.sync(() => ({
948 ...activity,
949 reviewThreads: [
950 {
951 ...long("first"),
952 isResolved: firstResolved,
953 nextCommentsCursor: "later",
954 },
955 long("second"),
956 reviewThread("done-thread", true),
957 ],
958 })),
959 threadComments: (input) =>
960 Effect.succeed(
961 input.cursor === "later"
962 ? { comments: [comment("reply")], nextCursor: null }
963 : { comments: [], nextCursor: null },
964 ),
965 list: (input) =>
966 Effect.sync(() => listed.push(input)).pipe(
967 Effect.as({
968 viewers: {},
969 providers: [],
970 entries: [],
971 errors: [],
972 truncated: input.cursors === undefined,
973 nextCursors: input.cursors === undefined ? { "t3tools/t3code": "page-2" } : {},
974 }),
975 ),
976 },
977 });
978 const first = yield* harness.call("pull_request_read", { include: ["threads"] });
979 expect(first.conversation?.reviewThreads).toMatchObject([
980 { id: "first", moreComments: false, comments: [{}, { body: "reply" }] },
981 ]);
982 const cursor = first.conversation?.nextCursor;
983 expect(cursor).toEqual(expect.any(String));
984 // The agent resolves what it read; the next page still starts at the next thread.
985 firstResolved = true;
986 const second = yield* harness.call("pull_request_read", { cursor: cursor! });
987 expect(second.conversation?.comments).toBeUndefined();
988 expect(second.conversation?.reviewThreads?.map((thread) => thread.id)).toEqual(["second"]);
989 expect(second.conversation?.nextCursor).toBeNull();
990 // A cursor past the current end finishes instead of repeating an empty page.
991 const stale = Base64Url.encode(
992 JSON.stringify({ threads: 99, comments: null, includeResolved: false }),
993 );
994 const past = yield* harness.call("pull_request_read", { cursor: stale });
995 expect(past.conversation).toMatchObject({ reviewThreads: [], nextCursor: null });
996​
997 const page = yield* harness.call("pull_request_list", {});
998 yield* harness.call("pull_request_list", { cursor: page.nextCursor! });
999 expect(listed.map((input) => input.cursors)).toEqual([
1000 undefined,
1001 { "t3tools/t3code": "page-2" },
1002 ]);
1003 const invalid = yield* harness
1004 .call("pull_request_read", { cursor: "not-a-cursor" })
1005 .pipe(Effect.flip);
1006 expect(invalid._tag).toBe("PullRequestCursorInvalidError");
1007 }),
1008 );
1009​
1010 it.effect("asks for a number when the thread's branch has no PR", () =>
1011 Effect.gen(function* () {
1012 const harness = yield* makeHarness();
1013 const error = yield* harness.call("pull_request_read", {}).pipe(Effect.flip);
1014 expect(error._tag).toBe("PullRequestBranchHasNoneError");
1015 }),
1016 );
1017​
1018 it.effect("reads the PR this thread opened before status sync reports it", () =>
1019 Effect.gen(function* () {
1020 const asked: Array<PullRequestRef> = [];
1021 const opened = (headBranch: string) =>
1022 makeHarness({
1023 thread: { ...makeThread([makeLink(43, { source: "created" })]), branch: "tools" },
1024 pullRequests: {
1025 summary: () => Effect.succeed({ state: "open", headBranch } as never),
1026 detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)),
1027 activity: () => Effect.succeed(activity),
1028 },
1029 });
1030 const harness = yield* opened("tools");
1031 yield* harness.call("pull_request_read", {});
1032 expect(asked).toMatchObject([{ number: 43 }]);
1033​
1034 // Before sync, the host says which branch it came from; another branch's is not this one.
1035 const moved = yield* opened("old");
1036 const unsynced = yield* moved.call("pull_request_read", {}).pipe(Effect.flip);
1037 expect(unsynced._tag).toBe("PullRequestBranchHasNoneError");
1038​
1039 // After a switch to another branch, the PR opened from the old one is not the branch's.
1040 const switched = yield* makeHarness({
1041 thread: {
1042 ...makeThread([makeLink(43, { source: "created", headBranch: "old" })]),
1043 branch: "new",
1044 },
1045 });
1046 const error = yield* switched
1047 .call("pull_request_update", { title: "New title" })
1048 .pipe(Effect.flip);
1049 expect(error._tag).toBe("PullRequestBranchHasNoneError");
1050 }),
1051 );
1052​
1053 it.effect("merges pinned to the head the agent checked", () =>
1054 Effect.gen(function* () {
1055 const actions: Array<PullRequestActionInput> = [];
1056 const harness = yield* makeHarness({
1057 thread: branchThread,
1058 pullRequests: {
1059 runAction: (input) => Effect.sync(() => void actions.push(input)),
1060 summary: () => Effect.succeed({ state: "open" } as never),
1061 },
1062 });
1063 const result = yield* harness.call("pull_request_merge", {
1064 expectedHeadSha: "abc123",
1065 method: "squash",
1066 auto: true,
1067 });
1068 expect(result).toMatchObject({ number: 42, state: "open" });
1069 expect(actions).toMatchObject([
1071 number: 42,
1072 action: "enable-auto-merge",
1073 expectedHeadSha: "abc123",
1074 mergeMethod: "squash",
1075 },
1076 ]);
1077 }),
1078 );
1079​
1080 it.effect("a stack merge pins every open layer up to the PR", () =>
1081 Effect.gen(function* () {
1082 const actions: Array<PullRequestActionInput> = [];
1083 let lowerHead: string | undefined = "bbb";
1084 let targetHead = "stale";
1085 const layer = (number: number, state: "open" | "merged", headSha: string | undefined) => ({
1086 number,
1087 state,
1088 ...(headSha === undefined ? {} : { headSha }),
1089 headBranch: `layer-${number}`,
1090 });
1091 const harness = yield* makeHarness({
1092 thread: branchThread,
1093 pullRequests: {
1094 stack: (_input, options) =>
1095 options?.bypassCache !== true
1096 ? Effect.die("a merge must not pin heads from the cache")
1097 : Effect.succeed({
1098 id: "stack-1",
1099 number: 7,
1100 url: "https://github.com/acme/app/stacks/7",
1101 base: "main",
1102 layers: [
1103 layer(40, "merged", "aaa"),
1104 layer(41, "open", lowerHead),
1105 layer(42, "open", targetHead),
1106 layer(43, "open", "ddd"),
1107 ],
1108 }),
1109 runAction: (input) => Effect.sync(() => void actions.push(input)),
1110 summary: () => Effect.succeed({ state: "merged" } as never),
1111 },
1112 });
1113 yield* harness.call("pull_request_merge", { expectedHeadSha: "ccc", stack: true });
1114 expect(actions).toMatchObject([
1116 number: 42,
1117 action: "merge",
1118 stackNumber: 7,
1119 expectedStackHeads: [
1120 { number: 41, headSha: "bbb" },
1121 { number: 42, headSha: "ccc" },
1122 ],
1123 },
1124 ]);
1125 const fullHead = "c0ffee1234567890abcdef1234567890abcdef12";
1126 targetHead = fullHead;
1127 yield* harness.call("pull_request_merge", { expectedHeadSha: "c0ffee1", stack: true });
1128 expect(actions[1]?.expectedStackHeads).toEqual([
1129 { number: 41, headSha: "bbb" },
1130 { number: 42, headSha: fullHead },
1131 ]);
1132 lowerHead = undefined;
1133 const unpinned = yield* harness
1134 .call("pull_request_merge", { expectedHeadSha: "ccc", stack: true })
1135 .pipe(Effect.flip);
1136 expect(unpinned._tag).toBe("PullRequestForgeError");
1137 expect(actions).toHaveLength(2);
1138 }),
1139 );
1140​
1141 it.effect("re-running checks reopens a watch that saw its checks finish", () =>
1142 Effect.gen(function* () {
1143 const watch = {
1144 startedAt: "2026-08-20T00:00:00.000Z",
1145 headSha: "abc123",
1146 failedChecks: ["test"],
1147 passed: false,
1148 passedChecks: [],
1149 remarksThrough: "2026-08-20T00:00:00.000Z",
1150 remarkIds: [],
1151 conflicting: false,
1152 wakes: 0,
1153 };
1154 const rerun = (checksPending: boolean | undefined, reran: boolean) =>
1155 Effect.gen(function* () {
1156 const harness = yield* makeHarness({
1157 thread: {
1158 ...branchThread,
1159 pullRequests: [
1160 makeLink(42, {
1161 watch: checksPending === undefined ? watch : { ...watch, checksPending },
1162 }),
1163 ],
1164 },
1165 pullRequests: {
1166 rerunChecks: () => Effect.succeed([{ name: "test", rerun: reran, detail: null }]),
1167 },
1168 });
1169 yield* harness.call("ci_rerun", {});
1170 return yield* Ref.get(harness.commands);
1171 });
1172 expect(yield* rerun(false, true)).toMatchObject([
1173 { type: "thread.pull-request-watch.checks-reopen", threadId: THREAD_ID },
1174 ]);
1175 // Nothing re-ran, or the watch has no answer to clear.
1176 expect(yield* rerun(false, false)).toEqual([]);
1177 expect(yield* rerun(undefined, true)).toEqual([]);
1178 }),
1179 );
1180​
1181 it.effect("opens a PR from the thread's worktree and links it even if dismissed", () =>
1182 Effect.gen(function* () {
1183 const opened: Array<{
1184 readonly cwd: string;
1185 readonly draft: boolean | undefined;
1186 readonly private: boolean | undefined;
1187 }> = [];
1188 const harness = yield* makeHarness({
1189 thread: {
1190 ...makeThread([makeLink(43, { source: "stack-dismissed" })]),
1191 worktreePath: "/workspace/worktree",
1192 },
1193 git: {
1194 createPullRequest: (input) =>
1195 Effect.sync(() =>
1196 opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }),
1197 ).pipe(
1198 Effect.as({
1199 status: "created" as const,
1200 url: "https://github.com/t3tools/t3code/pull/43",
1201 number: 43,
1202 baseBranch: "main",
1203 headBranch: "tools",
1204 title: input.title,
1205 }),
1206 ),
1207 },
1208 });
1209 const result = yield* harness.call("pull_request_create", {
1210 title: "Add tools",
1211 body: "Adds tools.",
1212 draft: true,
1213 private: true,
1214 });
1215 expect(result).toMatchObject({ number: 43, created: true });
1216 expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]);
1217 expect(yield* Ref.get(harness.commands)).toMatchObject([
1218 { type: "thread.pull-request.link", number: 43, source: "created" },
1219 ]);
1220 }),
1221 );
1222​
1223 it.effect("replies to and resolves a review thread, and refuses resolving without one", () =>
1224 Effect.gen(function* () {
1225 const calls: Array<string> = [];
1226 const harness = yield* makeHarness({
1227 thread: branchThread,
1228 pullRequests: {
1229 replyToThread: (input) => Effect.sync(() => calls.push(`reply ${input.threadId}`)),
1230 setThreadResolution: (input) =>
1231 input.threadId === "locked-thread"
1232 ? Effect.fail(
1233 new PullRequestOperationError({
1234 operation: "setThreadResolution",
1235 detail: "Locked.",
1236 }),
1238 : Effect.sync(() => void calls.push(`resolve ${input.threadId} ${input.resolved}`)),
1239 },
1240 });
1241 const result = yield* harness.call("pull_request_respond", {
1242 reviewThreadId: "open-thread",
1243 body: "Fixed.",
1244 resolved: true,
1245 });
1246 expect(result).toMatchObject({ replied: true, resolved: true });
1247 expect(calls).toEqual(["reply open-thread", "resolve open-thread true"]);
1248 const partial = yield* harness
1249 .call("pull_request_respond", {
1250 reviewThreadId: "locked-thread",
1251 body: "Fixed.",
1252 resolved: true,
1253 })
1254 .pipe(Effect.flip);
1255 expect(partial.message).toContain("The reply was posted");
1256 const error = yield* harness
1257 .call("pull_request_respond", { body: "Done", resolved: true })
1258 .pipe(Effect.flip);
1259 expect(error._tag).toBe("PullRequestNothingToDoError");
1260 }),
1261 );
1262​
1263 it.effect("places review comments by the diff page that shows their line", () =>
1264 Effect.gen(function* () {
1265 const reviews: Array<PullRequestSubmitReviewInput> = [];
1266 const pages: Record<string, PullRequestDiffResult> = {
1267 first: {
1268 patch:
1269 "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",
1270 truncated: false,
1271 nextCursor: "second",
1272 },
1273 second: {
1274 patch:
1275 "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",
1276 truncated: false,
1277 nextCursor: null,
1278 },
1279 };
1280 const harness = yield* makeHarness({
1281 thread: branchThread,
1282 pullRequests: {
1283 diff: (input) => Effect.succeed(pages[input.cursor ?? "first"]!),
1284 submitReview: (input) => Effect.sync(() => void reviews.push(input)),
1285 },
1286 });
1287 yield* harness.call("pull_request_review", {
1288 verdict: "request-changes",
1289 body: "Two things.",
1290 comments: [
1291 { path: "b.ts", line: 10, startLine: 9, body: "Why?" },
1292 { path: "a.ts", line: 1, side: "old", body: "Keep this." },
1293 ],
1294 });
1295 expect(reviews).toMatchObject([
1297 number: 42,
1298 verdict: "request-changes",
1299 body: "Two things.",
1300 comments: [
1302 path: "b.ts",
1303 position: { kind: "added", newLine: 10 },
1304 startPosition: { kind: "context", oldLine: 9, newLine: 9, side: "right" },
1305 },
1306 { path: "a.ts", position: { kind: "deleted", oldLine: 1 } },
1307 ],
1308 },
1309 ]);
1310​
1311 // A line the diff never shows fails before anything is posted.
1312 const error = yield* harness
1313 .call("pull_request_review", {
1314 verdict: "comment",
1315 comments: [{ path: "a.ts", line: 40, body: "Here?" }],
1316 })
1317 .pipe(Effect.flip);
1318 expect(error.message).toContain("a.ts line 40 (new side) is not in this PR's diff");
1319 expect(reviews).toHaveLength(1);
1320 }),
1321 );
1322​
1323 it.effect("updates labels, requests reviewers by login, and closes the PR", () =>
1324 Effect.gen(function* () {
1325 const calls: Array<unknown> = [];
1326 const harness = yield* makeHarness({
1327 thread: branchThread,
1328 pullRequests: {
1329 setLabels: (input) =>
1330 Effect.sync(() => void calls.push(["labels", input.labels, input.applied])),
1331 reviewerCandidates: (input) =>
1332 Effect.succeed({
1333 candidates: [
1335 id: "MDQ6VXNlcjE=",
1336 kind: "user",
1337 login: input.query === "Octo" ? "octo" : "x",
1338 name: null,
1339 avatarUrl: null,
1340 isRequested: false,
1341 },
1343 id: "core",
1344 kind: "team",
1345 login: "acme/core",
1346 name: null,
1347 avatarUrl: null,
1348 isRequested: false,
1349 },
1350 ],
1351 } as never),
1352 requestReviewers: (input) =>
1353 Effect.sync(() => void calls.push(["reviewers", input.reviewers])),
1354 runAction: (input) => Effect.sync(() => void calls.push(["action", input.action])),
1355 },
1356 });
1357 yield* harness.call("pull_request_update", {
1358 addLabels: ["bug"],
1359 removeLabels: ["wip"],
1360 requestReviewers: ["Octo", "acme/core"],
1361 state: "closed",
1362 });
1363 expect(calls).toEqual([
1364 ["labels", ["bug"], true],
1365 ["labels", ["wip"], false],
1367 "reviewers",
1369 { id: "MDQ6VXNlcjE=", kind: "user" },
1370 { id: "core", kind: "team" },
1371 ],
1372 ],
1373 ["action", "close"],
1374 ]);
1375 const unknown = yield* harness
1376 .call("pull_request_update", { requestReviewers: ["nobody"] })
1377 .pipe(Effect.flip);
1378 expect(unknown.message).toContain("No reviewer named nobody");
1379 }),
1380 );
1381});