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

handlers.test.ts

754 lines27.4 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationV2ServerCommand as OrchestrationCommand,
7 PullRequestOperationError,
8 type OrchestrationProjectShell,
9 type PullRequestRef,
10 type PullRequestReviewGuideResult,
11 type ThreadPullRequestLink,
12 SourceControlProviderKind,
13} from "@t3tools/contracts";
14import { describe, expect, it } from "@effect/vitest";
15import * as SecureRandom from "effect/crypto/SecureRandom";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as Stream from "effect/Stream";
21import type { Tool } from "effect/ai";
22​
23import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts";
24import {
25 type PullRequestTestThread,
26 v2PullRequestThread,
27} from "../../../orchestration-v2/testkit/pullRequestFixtures.ts";
28import * as ProjectService from "../../../project/ProjectService.ts";
29import * as PullRequestWatchService from "../../../pullRequest/PullRequestWatchService.ts";
30import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts";
31import * as McpInvocationContext from "../../McpInvocationContext.ts";
32import * as McpToolAccess from "../../McpToolAccess.ts";
33import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts";
34import { listThreadPullRequests } from "./handlers.ts";
35import * as PullRequestsHandlers from "./handlers.ts";
36import { CHILD_PULL_REQUEST_REPORT_NEXT, PullRequestsToolkit } from "./tools.ts";
37​
38const PROJECT_ID = ProjectId.make("project-1");
39const THREAD_ID = ThreadId.make("thread-1");
40​
41const testCrypto = SecureRandom.make((size) => new Uint8Array(size).fill(7));
42​
43const invocation = (
44 capabilities: ReadonlyArray<McpInvocationContext.McpCapability>,
45): McpInvocationContext.McpInvocationScope => ({
46 environmentId: EnvironmentId.make("environment-1"),
47 requestNamespace: "provider-session-1",
48 thread: {
49 threadId: THREAD_ID,
50 providerSessionId: "provider-session-1",
51 providerInstanceId: ProviderInstanceId.make("codex"),
52 },
53 client: undefined,
54 capabilities: new Set(capabilities),
55 issuedAt: 1,
56});
57​
58function makeProject(
59 repositoryIdentity: OrchestrationProjectShell["repositoryIdentity"] = {
60 canonicalKey: "github.com/t3tools/t3code",
61 locator: {
62 source: "git-remote",
63 remoteName: "origin",
64 remoteUrl: "git@github.com:T3Tools/T3Code.git",
65 },
66 provider: SourceControlProviderKind.make("github"),
67 displayName: "T3Tools/T3Code",
68 owner: "T3Tools",
69 name: "T3Code",
70 },
71): OrchestrationProjectShell {
72 return {
73 id: PROJECT_ID,
74 title: "Project",
75 workspaceRoot: "/workspace/project",
76 defaultModelSelection: null,
77 scripts: [],
78 repositoryIdentity,
79 createdAt: "2026-08-01T00:00:00.000Z",
80 updatedAt: "2026-08-01T00:00:00.000Z",
81 };
83​
84function makeThread(pullRequests: ReadonlyArray<ThreadPullRequestLink>): PullRequestTestThread {
85 return {
86 id: THREAD_ID,
87 projectId: PROJECT_ID,
88 title: "Thread",
89 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
90 runtimeMode: "full-access",
91 interactionMode: "default",
92 branch: null,
93 worktreePath: null,
94 pullRequests,
95 createdAt: "2026-08-01T00:00:00.000Z",
96 updatedAt: "2026-08-20T00:00:00.000Z",
97 archivedAt: null,
98 settledOverride: null,
99 settledAt: null,
100 latestUserMessageAt: "2026-08-20T00:00:00.000Z",
101 };
103​
104function makeLink(
105 number: number,
106 overrides: Partial<ThreadPullRequestLink> & {
107 readonly headBranch?: string;
108 readonly baseBranch?: string;
109 } = {},
110): ThreadPullRequestLink {
111 const { headBranch, baseBranch, ...rest } = overrides;
112 return {
113 host: "github.com",
114 repository: "t3tools/t3code",
115 number,
116 url: `https://github.com/t3tools/t3code/pull/${number}`,
117 source: "manual",
118 linkedAt: "2026-08-10T00:00:00.000Z",
119 snapshot:
120 headBranch === undefined
121 ? null
122 : {
123 state: "open",
124 title: `PR ${number}`,
125 headBranch,
126 baseBranch: baseBranch ?? "main",
127 isDraft: false,
128 updatedAt: null,
129 syncedAt: "2026-08-27T00:00:00.000Z",
130 },
131 stack: null,
132 ...rest,
133 };
135​
136interface HarnessOptions {
137 readonly thread?: PullRequestTestThread | null;
138 readonly project?: OrchestrationProjectShell | null;
139 readonly reject?: (command: OrchestrationCommand) => string | null;
140 readonly projects?: ReadonlyArray<OrchestrationProjectShell>;
141 readonly generate?: (
142 input: PullRequestRef,
143 ) => Effect.Effect<
144 PullRequestReviewGuideResult & { started: boolean },
145 PullRequestOperationError
146 >;
148​
149const NO_GUIDE: PullRequestReviewGuideResult = { guide: null, run: null, currentHeadSha: "head-1" };
150​
151const makeHarness = Effect.fn("makePullRequestsToolkitHarness")(function* (
152 options: HarnessOptions = {},
153) {
154 const commands = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
155 const guideRequests = yield* Ref.make<ReadonlyArray<PullRequestRef>>([]);
156 const thread = options.thread === undefined ? makeThread([]) : options.thread;
157 const project = options.project === undefined ? makeProject() : options.project;
158 const dispatch: Orchestrator.OrchestratorV2Shape["dispatch"] = (command) =>
159 Effect.gen(function* () {
160 const rejection = options.reject?.(command) ?? null;
161 if (rejection !== null)
162 return yield* new Orchestrator.OrchestratorDispatchError({
163 commandId: command.commandId,
164 commandType: command.type,
165 cause: rejection,
166 });
167 yield* Ref.update(commands, (recorded) => [...recorded, command]);
168 return { sequence: 1, storedEvents: [] };
169 });
170 const layerDependencies = Layer.mergeAll(
171 Layer.mock(PullRequestWatchService.PullRequestWatchService)({}),
172 Layer.mock(ProjectService.ProjectService)({
173 getShell: () => Effect.succeed(Option.fromNullishOr(project)),
174 listShells: () => Effect.succeed(options.projects ?? (project ? [project] : [])),
175 }),
176 Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({
177 get: () => Effect.succeed(NO_GUIDE),
178 generate: (input) =>
179 Ref.update(guideRequests, (recorded) => [...recorded, input]).pipe(
180 Effect.andThen(
181 options.generate?.(input) ??
182 Effect.succeed({
183 ...NO_GUIDE,
184 run: {
185 _tag: "Running" as const,
186 headSha: "head-1",
187 startedAt: "2026-10-11T00:00:00.000Z",
188 },
189 started: true,
190 }),
191 ),
192 ),
193 }),
194 Layer.mock(Orchestrator.OrchestratorV2)({
195 getThreadShell: (id) =>
196 Effect.succeed(id === thread?.id ? v2PullRequestThread(thread) : null),
197 dispatch,
198 }),
199 Layer.succeed(SecureRandom.SecureRandom, testCrypto),
200 McpToolAccessTestkit.liveThreadsLayer,
201 );
202 const toolkit = yield* PullRequestsToolkit.pipe(
203 Effect.provide(
204 McpToolAccess.HandlersLayer.layer(PullRequestsHandlers.layer).pipe(
205 Layer.provide(layerDependencies),
206 ),
207 ),
208 );
209 const call = <Name extends keyof typeof PullRequestsToolkit.tools>(
210 name: Name,
211 params: Parameters<typeof toolkit.handle<Name>>[1],
212 capabilities: ReadonlyArray<McpInvocationContext.McpCapability> = ["pull-requests"],
213 ) =>
214 toolkit.handle(name, params).pipe(
215 Stream.unwrap,
216 Stream.runCollect,
217 Effect.map(
218 (chunk) => chunk.at(-1)!.result as Tool.Success<(typeof PullRequestsToolkit.tools)[Name]>,
219 ),
220 Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(capabilities)),
221 Effect.provide(layerDependencies),
222 );
223 return { commands, guideRequests, call };
224});
225​
226describe("pull request toolkit handlers", () => {
227 it.effect("refuses a credential without the pull-requests capability", () =>
228 Effect.gen(function* () {
229 const harness = yield* makeHarness();
230 const error = yield* harness
231 .call("list_thread_pull_requests", {}, ["preview"])
232 .pipe(Effect.flip);
233 expect(error).toMatchObject({
234 _tag: "McpCapabilityUnavailableError",
235 capability: "pull-requests",
236 threadId: THREAD_ID,
237 });
238 expect(yield* Ref.get(harness.commands)).toEqual([]);
239 }),
240 );
241​
242 it.effect("points a bare thread uuid at the mcp: thread it belongs to", () =>
243 Effect.gen(function* () {
244 const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04");
245 const harness = yield* makeHarness({
246 thread: { ...makeThread([]), id: ThreadId.make(`mcp:${bareId}`) },
247 });
248 const error = yield* harness
249 .call("link_pull_request", { threadId: bareId, number: 123 })
250 .pipe(Effect.flip);
251 expect(error.message).toBe(`Thread ${bareId} was not found. Did you mean \`mcp:${bareId}\`?`);
252 expect(error).toMatchObject({ _tag: "OrchestratorMcpFailure", code: "thread_not_found" });
253 expect(yield* Ref.get(harness.commands)).toEqual([]);
254 }),
255 );
256​
257 it.effect("links by URL with source agent on the token's thread", () =>
258 Effect.gen(function* () {
259 const harness = yield* makeHarness();
260 const result = yield* harness.call("link_pull_request", {
261 url: "https://github.com/T3Tools/T3Code/pull/123/files",
262 });
263 expect(result).toEqual({
264 host: "github.com",
265 repository: "t3tools/t3code",
266 number: 123,
267 url: "https://github.com/T3Tools/T3Code/pull/123/files",
268 alreadyLinked: false,
269 });
270 expect(yield* Ref.get(harness.commands)).toMatchObject([
271 {
272 type: "thread.pull-request.link",
273 threadId: THREAD_ID,
274 host: "github.com",
275 repository: "t3tools/t3code",
276 number: 123,
277 source: "agent",
278 },
279 ]);
280 }),
281 );
282​
283 it.effect("asks a subagent thread to end with its PR report after it links", () =>
284 Effect.gen(function* () {
285 const harness = yield* makeHarness({
286 thread: {
287 ...makeThread([]),
288 lineage: {
289 rootThreadId: ThreadId.make("parent"),
290 parentThreadId: ThreadId.make("parent"),
291 relationshipToParent: "subagent",
292 },
293 },
294 });
295 const result = yield* harness.call("link_pull_request", {
296 url: "https://github.com/t3tools/t3code/pull/124",
297 });
298 expect(result).toMatchObject({ number: 124, next: CHILD_PULL_REQUEST_REPORT_NEXT });
299 }),
300 );
301​
302 it.effect("canonicalizes GitCafe links independently of the thread's project host", () =>
303 Effect.gen(function* () {
304 for (const host of ["git.cafe", "staging.git.cafe"]) {
305 for (const project of [makeProject(), makeProject(null)]) {
306 for (const target of [
307 { host, repository: "PingDotGG/T3Code", number: 21353 },
308 { url: `https://${host}/PingDotGG/T3Code/pull/21353` },
309 { url: `https://${host}/PingDotGG/T3Code/pulls/21353` },
310 ]) {
311 const harness = yield* makeHarness({ project });
312 const result = yield* harness.call("link_pull_request", target);
313 const url = `https://${host}/pingdotgg/t3code/pulls/21353`;
314 expect(result).toMatchObject({
315 host,
316 repository: "pingdotgg/t3code",
317 number: 21353,
318 url,
319 });
320 expect(yield* Ref.get(harness.commands)).toMatchObject([
321 {
322 type: "thread.pull-request.link",
323 host,
324 repository: "pingdotgg/t3code",
325 number: 21353,
326 url,
327 },
328 ]);
329 }
330 }
331 }
332 }),
333 );
334​
335 it.effect("builds the URL in the project host's own shape", () =>
336 Effect.gen(function* () {
337 const harness = yield* makeHarness({
338 project: makeProject({
339 canonicalKey: "gitlab.com/group/sub/project",
340 locator: {
341 source: "git-remote",
342 remoteName: "origin",
343 remoteUrl: "git@gitlab.com:group/sub/project.git",
344 },
345 provider: SourceControlProviderKind.make("gitlab"),
346 displayName: "group/sub/project",
347 }),
348 });
349 const result = yield* harness.call("link_pull_request", {
350 repository: "group/sub/project",
351 number: 42,
352 });
353 expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42");
354 expect(result.host).toBe("gitlab.com");
355 const other = yield* harness.call("link_pull_request", {
356 host: "gitlab.example.test",
357 repository: "team/repo",
358 number: 7,
359 });
360 expect(other.url).toBe("https://gitlab.example.test/team/repo/-/merge_requests/7");
361 const onGitHub = yield* harness.call("link_pull_request", {
362 host: "github.com",
363 repository: "acme/web",
364 number: 9,
365 });
366 expect(onGitHub.url).toBe("https://github.com/acme/web/pull/9");
367 }),
368 );
369​
370 it.effect("links a URL but not a bare number when the project's host is unknown", () =>
371 Effect.gen(function* () {
372 const harness = yield* makeHarness({
373 project: makeProject({
374 canonicalKey: "scm.example.test/tfs/collection/project/_git/repo",
375 locator: {
376 source: "git-remote",
377 remoteName: "origin",
378 remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo",
379 },
380 provider: SourceControlProviderKind.make("unknown"),
381 displayName: "tfs/collection/project/_git/repo",
382 }),
383 });
384 const error = yield* harness
385 .call("link_pull_request", { repository: "tfs/Collection/Project/_git/Repo", number: 124 })
386 .pipe(Effect.flip);
387 expect(error).toMatchObject({ _tag: "PullRequestUrlUnavailableError" });
388​
389 const supplied = "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123";
390 const fromUrl = yield* harness.call("link_pull_request", { url: supplied });
391 expect(fromUrl).toEqual({
392 host: "scm.example.test",
393 repository: "tfs/collection/project/_git/repo",
394 number: 123,
395 url: supplied,
396 alreadyLinked: false,
397 });
398 expect(yield* Ref.get(harness.commands)).toMatchObject([
399 { type: "thread.pull-request.link", number: 123, url: supplied },
400 ]);
401 }),
402 );
403​
404 it.effect("treats a duplicate link as alreadyLinked rather than an error", () =>
405 Effect.gen(function* () {
406 const harness = yield* makeHarness({
407 thread: makeThread([makeLink(123)]),
408 reject: (command) =>
409 command.type === "thread.pull-request.link" ? "already linked" : null,
410 });
411 const result = yield* harness.call("link_pull_request", {
412 url: "https://github.com/t3tools/t3code/pull/123",
413 });
414 expect(result.alreadyLinked).toBe(true);
415 }),
416 );
417​
418 it.effect("unlinks a linked pull request and reports a missing one as wasLinked=false", () =>
419 Effect.gen(function* () {
420 const harness = yield* makeHarness({
421 thread: makeThread([makeLink(5)]),
422 reject: (command) =>
423 command.type === "thread.pull-request.unlink" && command.number !== 5
424 ? "not linked"
425 : null,
426 });
427 const linked = yield* harness.call("unlink_pull_request", {
428 repository: "t3tools/t3code",
429 number: 5,
430 });
431 expect(linked).toEqual({
432 host: "github.com",
433 repository: "t3tools/t3code",
434 number: 5,
435 wasLinked: true,
436 });
437 const missing = yield* harness.call("unlink_pull_request", {
438 url: "https://github.com/t3tools/t3code/pull/9",
439 });
440 expect(missing.wasLinked).toBe(false);
441 expect(yield* Ref.get(harness.commands)).toMatchObject([
442 { type: "thread.pull-request.unlink", number: 5 },
443 ]);
444 }),
445 );
446​
447 it.effect("reports a dismissed stack member as not linked and leaves it dismissed", () =>
448 Effect.gen(function* () {
449 const harness = yield* makeHarness({
450 thread: makeThread([makeLink(9, { source: "stack-dismissed" })]),
451 });
452 const result = yield* harness.call("unlink_pull_request", {
453 repository: "t3tools/t3code",
454 number: 9,
455 });
456 expect(result.wasLinked).toBe(false);
457 expect(yield* Ref.get(harness.commands)).toEqual([]);
458 }),
459 );
460​
461 it.effect("links several pull requests in one call", () =>
462 Effect.gen(function* () {
463 const harness = yield* makeHarness({
464 thread: makeThread([makeLink(1), { ...makeLink(2), source: "stack-dismissed" }]),
465 });
466 const url = (number: number) => `https://github.com/t3tools/t3code/pull/${number}`;
467 const result = yield* harness.call("link_pull_requests", {
468 urls: [url(1), url(2), url(3), url(3), "https://example.com/not-a-pr"],
469 });
470 expect(result).toEqual({
471 linked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [2, 3] }],
472 alreadyLinked: [{ host: "github.com", repository: "t3tools/t3code", numbers: [1] }],
473 linkedCount: 3,
474 invalidUrls: ["https://example.com/not-a-pr"],
475 });
476 expect(yield* Ref.get(harness.commands)).toMatchObject([
477 { type: "thread.pull-request.link", number: 2, source: "agent" },
478 { type: "thread.pull-request.link", number: 3, source: "agent" },
479 ]);
480 }),
481 );
482​
483 it.effect("unlinks every visible pull request in the given states in one call", () =>
484 Effect.gen(function* () {
485 const withState = (number: number, state: "open" | "closed" | "merged") => {
486 const link = makeLink(number, { headBranch: `branch-${number}` });
487 return { ...link, snapshot: { ...link.snapshot!, state } };
488 };
489 const harness = yield* makeHarness({
490 thread: makeThread([
491 withState(1, "merged"),
492 withState(2, "open"),
493 withState(3, "closed"),
494 makeLink(4),
495 { ...withState(5, "merged"), source: "stack-dismissed" },
496 ]),
497 });
498 const result = yield* harness.call("unlink_pull_requests", {
499 states: ["closed", "merged"],
500 });
501 expect(result).toEqual({
502 unlinked: [
503 { host: "github.com", repository: "t3tools/t3code", state: "merged", numbers: [1] },
504 { host: "github.com", repository: "t3tools/t3code", state: "closed", numbers: [3] },
505 ],
506 unlinkedCount: 2,
507 remaining: 2,
508 });
509 expect(yield* Ref.get(harness.commands)).toMatchObject([
510 { type: "thread.pull-request.unlink", number: 1 },
511 { type: "thread.pull-request.unlink", number: 3 },
512 ]);
513 }),
514 );
515​
516 it("reports an older Forgejo link's HTTP port when listing thread links", () => {
517 const result = listThreadPullRequests(
518 makeThread([
519 makeLink(42, {
520 host: "forge.example",
521 url: "http://forge.example:3000/t3tools/t3code/pulls/42",
522 }),
523 ]),
524 );
525 expect(result.pullRequests[0]?.host).toBe("forge.example:3000");
526 });
527​
528 it.effect("lists visible links with host state and derived chain order", () =>
529 Effect.gen(function* () {
530 const harness = yield* makeHarness({
531 thread: makeThread([
532 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-b", source: "agent" }),
533 makeLink(1, { headBranch: "feat-a", baseBranch: "main", source: "created" }),
534 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a", source: "agent" }),
535 makeLink(9, { source: "stack-dismissed" }),
536 makeLink(10),
537 ]),
538 });
539 const result = yield* harness.call("list_thread_pull_requests", {});
540 expect(result.pullRequests.map((entry) => entry.number)).toEqual([1, 2, 3, 10]);
541 expect(result.pullRequests[2]).toEqual({
542 host: "github.com",
543 repository: "t3tools/t3code",
544 number: 3,
545 url: "https://github.com/t3tools/t3code/pull/3",
546 source: "agent",
547 watching: false,
548 state: "open",
549 title: "PR 3",
550 headBranch: "feat-c",
551 baseBranch: "feat-b",
552 isDraft: false,
553 stack: { kind: "derived", position: 3, size: 3 },
554 });
555 expect(result.pullRequests[3]).toMatchObject({
556 number: 10,
557 state: null,
558 title: null,
559 headBranch: null,
560 stack: null,
561 });
562 expect(result.chains).toEqual([
563 { kind: "derived", numbers: [1, 2, 3] },
564 { kind: "derived", numbers: [10] },
565 ]);
566 }),
567 );
568});
569​
570describe("listThreadPullRequests", () => {
571 it("reports a native stack position for each member", () => {
572 const stack = {
573 kind: "native" as const,
574 id: "stack-1",
575 number: 1,
576 url: "https://github.com/t3tools/t3code/stack/1",
577 base: "main",
578 layers: [
579 { number: 1, headBranch: "a", state: "open" as const },
580 { number: 2, headBranch: "b", state: "open" as const },
581 ],
582 };
583 const result = listThreadPullRequests({
584 pullRequests: [
585 makeLink(2, { stack, source: "stack" }),
586 makeLink(1, { stack, source: "created" }),
587 ],
588 });
589 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
590 [1, { kind: "native", position: 1, size: 2 }],
591 [2, { kind: "native", position: 2, size: 2 }],
592 ]);
593 expect(result.chains).toEqual([{ kind: "native", numbers: [1, 2] }]);
594 });
595​
596 it("gives pull requests built on the same one the same position", () => {
597 const result = listThreadPullRequests({
598 pullRequests: [
599 makeLink(1, { headBranch: "feat-a", baseBranch: "main" }),
600 makeLink(2, { headBranch: "feat-b", baseBranch: "feat-a" }),
601 makeLink(3, { headBranch: "feat-c", baseBranch: "feat-a" }),
602 ],
603 });
604 expect(result.pullRequests.map((entry) => [entry.number, entry.stack])).toEqual([
605 [1, { kind: "derived", position: 1, size: 3 }],
606 [2, { kind: "derived", position: 2, size: 3 }],
607 [3, { kind: "derived", position: 2, size: 3 }],
608 ]);
609 expect(result.chains).toEqual([{ kind: "derived", numbers: [1, 2, 3] }]);
610 });
611​
612 it("pages a large list once through, with each page's stacks whole", () => {
613 const thread = {
614 pullRequests: [
615 makeLink(1, { headBranch: "feat-a" }),
616 ...Array.from({ length: 118 }, (_, index) => makeLink(index + 2)),
617 makeLink(120, { headBranch: "feat-z", baseBranch: "feat-a" }),
618 ],
619 };
620 const pages = [listThreadPullRequests(thread)];
621 for (let next = pages[0]!.nextCursor; next !== null; next = pages.at(-1)!.nextCursor) {
622 pages.push(listThreadPullRequests(thread, next));
623 }
624 expect(pages.map((page) => page.pullRequests.length)).toEqual([50, 50, 20]);
625 expect(pages.flatMap((page) => page.pullRequests.map((entry) => entry.number))).toEqual(
626 Array.from({ length: 120 }, (_, index) => index + 1),
627 );
628 const stack = { kind: "derived", numbers: [1, 120] };
629 expect(pages.map((page) => page.chains.length)).toEqual([50, 50, 20]);
630 expect(pages.map((page) => page.chains.filter((chain) => chain.numbers.length > 1))).toEqual([
631 [stack],
632 [],
633 [stack],
634 ]);
635​
636 // Unlinking the first page must not shift the cursor past PRs not yet seen.
637 const remaining = { pullRequests: thread.pullRequests.slice(50) };
638 expect(
639 listThreadPullRequests(remaining, pages[0]!.nextCursor!).pullRequests.map(
640 (entry) => entry.number,
641 ),
642 ).toEqual(Array.from({ length: 50 }, (_, index) => index + 51));
643 });
644​
645 it("filters by state before paging, counting a PR with no known state as open", () => {
646 const merged = (number: number) => {
647 const link = makeLink(number, { headBranch: `feat-${number}` });
648 return { ...link, snapshot: { ...link.snapshot!, state: "merged" as const } };
649 };
650 const thread = {
651 pullRequests: [
652 ...Array.from({ length: 50 }, (_, index) => merged(index + 1)),
653 ...Array.from({ length: 10 }, (_, index) => makeLink(index + 51)),
654 ],
655 };
656 const open = listThreadPullRequests(thread, undefined, ["open"]);
657 expect(open.pullRequests.map((entry) => entry.number)).toEqual(
658 Array.from({ length: 10 }, (_, index) => index + 51),
659 );
660 expect(open.nextCursor).toBeNull();
661 expect(listThreadPullRequests(thread, undefined, ["merged"]).nextCursor).toBeNull();
662 });
663});
664​
665describe("pull request guide tools", () => {
666 it.effect(
667 "writes guides through the project whose checkout is each pull request's repository",
668 () =>
669 Effect.gen(function* () {
670 const other = {
671 ...makeProject({
672 canonicalKey: "github.com/acme/web",
673 locator: {
674 source: "git-remote",
675 remoteName: "origin",
676 remoteUrl: "git@github.com:acme/web.git",
677 },
678 provider: SourceControlProviderKind.make("github"),
679 displayName: "acme/web",
680 owner: "acme",
681 name: "web",
682 }),
683 id: ProjectId.make("project-web"),
684 };
685 const harness = yield* makeHarness({ projects: [makeProject(), other] });
686 const result = yield* harness.call("write_pull_request_guides", {
687 pullRequests: [
688 { url: "https://github.com/acme/web/pull/7" },
689 { repository: "t3tools/t3code", number: 12 },
690 { url: "https://github.com/someone/else/pull/1" },
691 ],
692 });
693 expect(
694 result.guides.map((guide) => [guide.repository, guide.number, guide.outcome]),
695 ).toEqual([
696 ["acme/web", 7, "started"],
697 ["t3tools/t3code", 12, "started"],
698 ["someone/else", 1, "failed"],
699 ]);
700 expect(result.guides[2]?.detail).toContain("No project in this environment");
701 expect(
702 (yield* Ref.get(harness.guideRequests)).map((ref) => [ref.projectId, ref.number]),
703 ).toEqual([
704 ["project-web", 7],
705 [PROJECT_ID, 12],
706 ]);
707 }),
708 );
709​
710 it.effect("reports an unreadable entry on its own and still writes the rest of the batch", () =>
711 Effect.gen(function* () {
712 const harness = yield* makeHarness();
713 const result = yield* harness.call("write_pull_request_guides", {
714 pullRequests: [
715 { url: "https://example.com/not-a-pull-request" },
716 { repository: "t3tools/t3code" },
717 { repository: "t3tools/t3code", number: 5 },
718 ],
719 });
720 expect(result.guides.map((guide) => guide.outcome)).toEqual(["failed", "failed", "started"]);
721 expect(result.guides[0]?.detail).toContain("not a recognised pull request URL");
722 expect(result.guides[1]?.detail).toContain("Pass either url");
723 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.number)).toEqual([5]);
724 }),
725 );
726​
727 it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () =>
728 Effect.gen(function* () {
729 const azure = {
730 ...makeProject({
731 canonicalKey: "dev.azure.com/org/project/_git/web",
732 locator: {
733 source: "git-remote",
734 remoteName: "origin",
735 remoteUrl: "https://dev.azure.com/org/project/_git/web",
736 },
737 provider: SourceControlProviderKind.make("azure-devops"),
738 displayName: "org/project/_git/web",
739 owner: "org",
740 name: "web",
741 }),
742 id: ProjectId.make("project-azure"),
743 };
744 const harness = yield* makeHarness({ projects: [makeProject(), azure] });
745 const result = yield* harness.call("write_pull_request_guides", {
746 pullRequests: [{ host: "dev.azure.com", repository: "org/project/_git/web", number: 9 }],
747 });
748 expect(result.guides.map((guide) => guide.outcome)).toEqual(["started"]);
749 expect((yield* Ref.get(harness.guideRequests)).map((ref) => ref.projectId)).toEqual([
750 "project-azure",
751 ]);
752 }),
753 );
754});