Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Context from "effect/Context";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as FetchHttpClient from "effect/http/FetchHttpClient";
7import * as HttpClient from "effect/http/HttpClient";
8import type * as HttpClientRequest from "effect/http/HttpClientRequest";
9import * as HttpClientResponse from "effect/http/HttpClientResponse";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
12
13import * as GitCafeApi from "./GitCafeApi.ts";
14import * as GitCafeCredentials from "./GitCafeCredentials.ts";
15import * as GitCafePullRequestProvider from "./GitCafePullRequestProvider.ts";
16
17const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
18const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
19
20interface SentRequest {
21 readonly method: string;
22 readonly path: string;
23 readonly query: URLSearchParams;
24 readonly host: string;
25 readonly body: unknown;
26 readonly redirect: string | undefined;
27}
28
29function fakeGitCafe(
30 routes: Record<string, unknown | ((request: SentRequest) => unknown)>,
31 options: { readonly status?: number; readonly env?: NodeJS.ProcessEnv } = {},
32) {
33 const sent: Array<SentRequest> = [];
34 const client = HttpClient.make(
35 (request: HttpClientRequest.HttpClientRequest, _url, _signal, fiber) => {
36 const url = new URL(request.url);
37 assert.isTrue(url.pathname.startsWith("/api/"), url.pathname);
38 assert.strictEqual(request.headers.authorization, "Bearer env-token");
39 const entry: SentRequest = {
40 method: request.method,
41 path: url.pathname.slice("/api".length),
42 query: url.searchParams,
43 host: url.host,
44 body:
45 request.body._tag === "Uint8Array"
46 ? decodeJson(new TextDecoder().decode(request.body.body))
47 : undefined,
48 redirect: Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit)?.redirect,
49 };
50 sent.push(entry);
51 const route = routes[`${entry.method} ${entry.path}`];
52 const response =
53 route === undefined
54 ? new Response(encodeJson({ type: "https://cafe.sh/errors/not-found" }), { status: 404 })
55 : route instanceof Response
56 ? route
57 : new Response(encodeJson(typeof route === "function" ? route(entry) : route), {
58 status: options.status ?? 200,
59 });
60 return Effect.succeed(HttpClientResponse.fromWeb(request, response));
61 },
62 );
63 const layer = GitCafeApi.layer.pipe(
64 Layer.provide(GitCafeCredentials.layer),
65 Layer.provide(TestSourceControlHost.layer()),
66 Layer.provide(
67 Layer.succeed(HostProcess.Environment, options.env ?? { CAFE_TOKEN: "env-token" }),
68 ),
69 Layer.provide(Layer.succeed(HostProcess.WorkingDirectory, "/server")),
70 Layer.provide(Layer.succeed(HttpClient.HttpClient, client)),
71 );
72 const writes = () =>
73 sent.filter((request) => request.method !== "GET").map((r) => `${r.method} ${r.path}`);
74 return { layer, sent, writes };
75}
76
77const target = { cwd: "/repo", host: "git.cafe", repository: "owner/repo", number: 7 };
78const timestamp = "2026-09-12T12:00:00Z";
79const headOid = "0123456789abcdef0123456789abcdef01234567";
80const baseOid = "89abcdef0123456789abcdef0123456789abcdef";
81const actor = {
82 kind: "local",
83 actorId: "act_one",
84 handle: "alice",
85 displayName: null,
86 avatarUrl: "/avatars/one",
87};
88const pull = {
89 id: "pr_one",
90 number: 7,
91 title: "Change",
92 state: "open",
93 draft: false,
94 sourceBranch: "feature",
95 targetBranch: "main",
96 headOid,
97 observedBaseOid: baseOid,
98 mergeRoute: "provider",
99 author: actor,
100 createdAt: timestamp,
101 updatedAt: timestamp,
102 version: 4,
103 description: "Body",
104 closedAt: null,
105 mergedAt: null,
106 sourceRepo: null,
107 capabilities: { comment: true, review: true, merge: true, edit: true, moderate: true },
108};
109const labels = [
110 { id: "label_bug", name: "bug", color: "#d73a4a", description: null },
111 { id: "label_docs", name: "docs", color: "#0075ca", description: "Documentation" },
112];
113const root = {
114 id: "root",
115 threadId: "root",
116 version: 2,
117 author: actor,
118 body: "Review",
119 path: "file.ts",
120 line: 3,
121 side: "right",
122 createdAt: timestamp,
123 commitOid: headOid,
124 resolvedAt: null,
125 capabilities: {
126 edit: true,
127 hide: false,
128 unhide: false,
129 delete: false,
130 resolve: true,
131 unresolve: false,
132 },
133};
134const stack = (
135 members: ReadonlyArray<{ number: number; headOid: string; state?: string }>,
136): Record<string, unknown> => ({
137 "GET /repos/owner/repo/pulls/7/stack": {
138 stack: {
139 id: "stack-one",
140 number: 3,
141 revision: 5,
142 landingBase: "main",
143 members: members.map((member, index) => ({
144 pullRequestNumber: member.number,
145 title: `Layer ${member.number}`,
146 state: member.state ?? "open",
147 draft: false,
148 sourceBranch: `layer-${member.number}`,
149 position: index + 1,
150 })),
151 },
152 },
153 ...Object.fromEntries(
154 members.map((member) => [
155 `GET /repos/owner/repo/pulls/${member.number}`,
156 { ...pull, number: member.number, headOid: member.headOid },
157 ]),
158 ),
159});
160
161const assertRequestId = (body: unknown) =>
162 assert.match(
163 (body as { readonly requestId?: unknown } | undefined)?.requestId as string,
164 /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
165 );
166
167describe("GitCafePullRequestProvider changed paths", () => {
168 const snapshot = { version: pull.version, headOid, comparisonBaseOid: baseOid };
169
170 it.effect("pages changed paths without fetching diff-file hunks", () => {
171 const server = fakeGitCafe({
172 "GET /repos/owner/repo/pulls/7": pull,
173 "GET /repos/owner/repo/pulls/7/changes": (request: SentRequest) => ({
174 ...snapshot,
175 items: request.query.has("after")
176 ? [{ path: "gone.ts", status: "deleted" }]
177 : [{ path: "new name.ts", oldPath: "old name.ts", status: "renamed" }],
178 next: request.query.has("after") ? null : "next-page",
179 }),
180 });
181 return Effect.gen(function* () {
182 const provider = yield* GitCafePullRequestProvider.make;
183 const first = yield* provider.getDiffFilePaths!(target);
184 const second = yield* provider.getDiffFilePaths!({ ...target, cursor: first.nextCursor! });
185 assert.deepStrictEqual(first.files, [{ oldPath: "old name.ts", newPath: "new name.ts" }]);
186 assert.deepStrictEqual(second, {
187 files: [{ oldPath: "gone.ts", newPath: "gone.ts" }],
188 nextCursor: null,
189 });
190 assert.isFalse(server.sent.some((request) => request.path.includes("/diff-file")));
191 }).pipe(Effect.provide(server.layer));
192 });
193
194 it.effect.each(["getDiff", "getDiffFilePaths"] as const)(
195 "%s rejects a repeated continuation cursor",
196 (method) => {
197 const server = fakeGitCafe({
198 "GET /repos/owner/repo/pulls/7": pull,
199 "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, items: [], next: "same-page" },
200 });
201 return Effect.gen(function* () {
202 const provider = yield* GitCafePullRequestProvider.make;
203 const first = yield* provider[method]!(target);
204 const input = { ...target, cursor: first.nextCursor! };
205 const result =
206 method === "getDiff"
207 ? yield* provider.getDiff(input).pipe(Effect.result)
208 : yield* provider.getDiffFilePaths!(input).pipe(Effect.result);
209 assert.strictEqual(result._tag, "Failure");
210 }).pipe(Effect.provide(server.layer));
211 },
212 );
213
214 // getDiff cases guard parity with the existing patch path; getDiffFilePaths must refuse the same pages.
215 it.effect.each(
216 (["getDiff", "getDiffFilePaths"] as const).flatMap((method) =>
217 [{ version: 5 }, { headOid: baseOid }, { comparisonBaseOid: headOid }].map((changed) => ({
218 method,
219 changed,
220 })),
221 ),
222 )(
223 "$method refuses a continuation from a different revision ($changed)",
224 ({ method, changed }) => {
225 const server = fakeGitCafe({
226 "GET /repos/owner/repo/pulls/7": pull,
227 "GET /repos/owner/repo/pulls/7/changes": (request: SentRequest) => ({
228 ...snapshot,
229 ...(request.query.has("after") ? changed : {}),
230 items: [],
231 next: request.query.has("after") ? null : "next-page",
232 }),
233 });
234 return Effect.gen(function* () {
235 const provider = yield* GitCafePullRequestProvider.make;
236 const read = (cursor?: string) =>
237 method === "getDiff"
238 ? provider.getDiff({ ...target, ...(cursor === undefined ? {} : { cursor }) })
239 : provider.getDiffFilePaths!({
240 ...target,
241 ...(cursor === undefined ? {} : { cursor }),
242 });
243 const first = yield* read();
244 const input = { ...target, cursor: first.nextCursor! };
245 const result =
246 method === "getDiff"
247 ? yield* provider.getDiff(input).pipe(Effect.result)
248 : yield* provider.getDiffFilePaths!(input).pipe(Effect.result);
249 assert.strictEqual(result._tag, "Failure");
250 }).pipe(Effect.provide(server.layer));
251 },
252 );
253
254 it.effect.each(["getDiff", "getDiffFilePaths"] as const)(
255 "%s reads a pull that reports no head yet",
256 (method) => {
257 const server = fakeGitCafe({
258 "GET /repos/owner/repo/pulls/7": { ...pull, headOid: null },
259 "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, items: [], next: null },
260 });
261 return Effect.gen(function* () {
262 const provider = yield* GitCafePullRequestProvider.make;
263 const result = yield* provider[method]!(target);
264 assert.isNull(result.nextCursor);
265 }).pipe(Effect.provide(server.layer));
266 },
267 );
268
269 it.effect.each([{ version: 5 }, { headOid: baseOid }])(
270 "refuses initial changed paths from a different pull revision (%j)",
271 (changed) => {
272 const server = fakeGitCafe({
273 "GET /repos/owner/repo/pulls/7": pull,
274 "GET /repos/owner/repo/pulls/7/changes": { ...snapshot, ...changed, items: [], next: null },
275 });
276 return Effect.gen(function* () {
277 const provider = yield* GitCafePullRequestProvider.make;
278 const result = yield* provider.getDiffFilePaths!(target).pipe(Effect.result);
279 assert.strictEqual(result._tag, "Failure");
280 }).pipe(Effect.provide(server.layer));
281 },
282 );
283});
284
285describe("GitCafePullRequestProvider source contents", () => {
286 const comparisonBase = "a".repeat(40);
287 const snapshot = { version: pull.version, headOid, comparisonBaseOid: comparisonBase };
288 const input = {
289 ...target,
290 changeType: "rename-changed" as const,
291 oldPath: "old name.ts",
292 newPath: "src/new #name.ts",
293 };
294 const blob = (request: SentRequest) => ({
295 commit: request.query.get("oid"),
296 oid: "b".repeat(40),
297 path: request.query.get("path"),
298 size: 16,
299 binary: false,
300 content: "const value = 1;",
301 });
302 const routes = {
303 "GET /repos/owner/repo/pulls/7": pull,
304 "GET /repos/owner/repo/pulls/7/changes": snapshot,
305 "GET /repos/owner/repo/blob": blob,
306 };
307
308 it.effect(
309 "pins rename source to the comparison base and fork head, without reading branches",
310 () => {
311 const server = fakeGitCafe({
312 ...routes,
313 "GET /repos/owner/repo/pulls/7": {
314 ...pull,
315 sourceRepo: { owner: "fork", name: "project" },
316 },
317 "GET /repos/fork/project/blob": blob,
318 });
319 return Effect.gen(function* () {
320 const provider = yield* GitCafePullRequestProvider.make;
321 const result = yield* provider.getDiffFileContents!(input);
322 assert.deepStrictEqual(result, {
323 oldContents: "const value = 1;",
324 newContents: "const value = 1;",
325 });
326 const changes = server.sent.find((request) => request.path.endsWith("/changes"))!;
327 assert.strictEqual(changes.query.get("expectedVersion"), "4");
328 assert.strictEqual(changes.query.get("limit"), "1");
329 assert.deepStrictEqual(
330 server.sent
331 .filter((request) => request.path.endsWith("/blob"))
332 .map((request) => ({
333 path: request.path,
334 oid: request.query.get("oid"),
335 file: request.query.get("path"),
336 ref: request.query.get("ref"),
337 })),
338 [
339 { path: "/repos/owner/repo/blob", oid: comparisonBase, file: input.oldPath, ref: null },
340 { path: "/repos/fork/project/blob", oid: headOid, file: input.newPath, ref: null },
341 ],
342 );
343 assert.deepStrictEqual(server.writes(), []);
344 }).pipe(Effect.provide(server.layer));
345 },
346 );
347
348 it.effect.each(["new", "deleted"] as const)(
349 "skips the absent side of a %s file",
350 (changeType) => {
351 const server = fakeGitCafe(routes);
352 return Effect.gen(function* () {
353 const provider = yield* GitCafePullRequestProvider.make;
354 const result = yield* provider.getDiffFileContents!({ ...input, changeType });
355 assert.strictEqual(result[changeType === "new" ? "oldContents" : "newContents"], "");
356 assert.lengthOf(
357 server.sent.filter((request) => request.path.endsWith("/blob")),
358 1,
359 );
360 }).pipe(Effect.provide(server.layer));
361 },
362 );
363
364 it.effect.each([
365 { ...snapshot, version: 5 },
366 { ...snapshot, headOid: baseOid },
367 { ...snapshot, comparisonBaseOid: "main" },
368 ])("refuses a changed or nonimmutable comparison snapshot", (response) => {
369 const server = fakeGitCafe({ ...routes, "GET /repos/owner/repo/pulls/7/changes": response });
370 return Effect.gen(function* () {
371 const provider = yield* GitCafePullRequestProvider.make;
372 const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);
373 assert.strictEqual(result._tag, "Failure");
374 assert.isFalse(server.sent.some((request) => request.path.endsWith("/blob")));
375 }).pipe(Effect.provide(server.layer));
376 });
377
378 it.effect.each([
379 { binary: true, content: null },
380 { content: "binary\0data" },
381 { size: 1_048_577 },
382 { size: 1, content: "x".repeat(1_048_577) },
383 { size: 1, content: "é".repeat(524_289) },
384 { commit: baseOid },
385 { path: "another.ts" },
386 { content: null },
387 ])("refuses unavailable, oversized, binary, or mismatched blobs", (fields) => {
388 const server = fakeGitCafe({
389 ...routes,
390 "GET /repos/owner/repo/blob": (request: SentRequest) => ({ ...blob(request), ...fields }),
391 });
392 return Effect.gen(function* () {
393 const provider = yield* GitCafePullRequestProvider.make;
394 const result = yield* provider.getDiffFileContents!(input).pipe(Effect.result);
395 assert.strictEqual(result._tag, "Failure");
396 assert.deepStrictEqual(server.writes(), []);
397 }).pipe(Effect.provide(server.layer));
398 });
399
400 it.effect.each([
401 [413, "oversized"],
402 [501, "unavailable"],
403 ] as const)("marks HTTP %s blob refusals permanently unavailable", ([status, reason]) => {
404 const server = fakeGitCafe({
405 ...routes,
406 "GET /repos/owner/repo/blob": new Response("{}", { status }),
407 });
408 return Effect.gen(function* () {
409 const provider = yield* GitCafePullRequestProvider.make;
410 const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(
411 Effect.flip,
412 );
413 assert.deepInclude(error.cause as object, {
414 _tag: "GitCafeDiffSourceUnavailableError",
415 reason,
416 });
417 }).pipe(Effect.provide(server.layer));
418 });
419
420 it.effect("preserves authentication failures from blob access", () => {
421 const server = fakeGitCafe({
422 ...routes,
423 "GET /repos/owner/repo/blob": new Response("{}", { status: 401 }),
424 });
425 return Effect.gen(function* () {
426 const provider = yield* GitCafePullRequestProvider.make;
427 const error = yield* provider.getDiffFileContents!({ ...input, changeType: "new" }).pipe(
428 Effect.flip,
429 );
430 assert.strictEqual(error.reason, "unauthenticated");
431 assert.strictEqual(error.operation, "getDiffFileContents");
432 }).pipe(Effect.provide(server.layer));
433 });
434
435 it.effect(
436 "refuses commit-specific contents consistently with unsupported GitCafe commit diffs",
437 () => {
438 const server = fakeGitCafe({});
439 return Effect.gen(function* () {
440 const provider = yield* GitCafePullRequestProvider.make;
441 const result = yield* provider.getDiffFileContents!({ ...input, commit: headOid }).pipe(
442 Effect.result,
443 );
444 assert.strictEqual(result._tag, "Failure");
445 assert.deepStrictEqual(server.sent, []);
446 }).pipe(Effect.provide(server.layer));
447 },
448 );
449});
450
451describe("GitCafePullRequestProvider", () => {
452 it.effect("keeps a staging repository's requests and links on staging", () => {
453 const server = fakeGitCafe(
454 { "GET /repos/owner/repo/pulls/7": pull },
455 { env: { CAFE_TOKEN: "env-token", CAFE_HOST: "staging.git.cafe" } },
456 );
457 return Effect.gen(function* () {
458 const provider = yield* GitCafePullRequestProvider.make;
459 const input = {
460 ...target,
461 host: "staging.git.cafe",
462 };
463 const preview = yield* provider.getChangeRequestPreview!(input);
464 assert.deepInclude(preview, {
465 number: 7,
466 title: "Change",
467 url: "https://staging.git.cafe/owner/repo/pulls/7",
468 author: { login: "alice", name: null, avatarUrl: "https://staging.git.cafe/avatars/one" },
469 state: "open",
470 isDraft: false,
471 createdAt: timestamp,
472 });
473 const summary = yield* provider.getChangeRequestSummary!(input);
474 assert.strictEqual(summary.url, "https://staging.git.cafe/owner/repo/pulls/7");
475 assert.isTrue(server.sent.every((request) => request.host === "staging.git.cafe"));
476 assert.deepStrictEqual(
477 server.sent.map((request) => `${request.method} ${request.path}`),
478 [
479 "GET /repos/owner/repo/pulls/7",
480 "GET /repos/owner/repo/pulls/7",
481 "GET /repos/owner/repo/pulls/7/changes",
482 ],
483 );
484 }).pipe(Effect.provide(server.layer));
485 });
486
487 it.effect("refuses a repository outside GitCafe's hosts before sending anything", () => {
488 const server = fakeGitCafe({});
489 return Effect.gen(function* () {
490 const provider = yield* GitCafePullRequestProvider.make;
491 const result = yield* provider
492 .getChangeRequest({ ...target, host: "github.com" })
493 .pipe(Effect.result);
494 assert.strictEqual(result._tag, "Failure");
495 assert.deepStrictEqual(server.sent, []);
496 }).pipe(Effect.provide(server.layer));
497 });
498
499 it.effect("reports a refused token as unauthenticated and a limit as rate-limited", () =>
500 Effect.gen(function* () {
501 for (const [status, reason] of [
502 [401, "unauthenticated"],
503 [429, "rate-limited"],
504 ] as const) {
505 const server = fakeGitCafe(
506 { "GET /repos/owner/repo/pulls/7/stack": { stack: null } },
507 {
508 status,
509 },
510 );
511 const error = yield* GitCafePullRequestProvider.make.pipe(
512 Effect.flatMap((provider) => provider.getChangeRequestStack!(target)),
513 Effect.flip,
514 Effect.provide(server.layer),
515 );
516 assert.strictEqual(error.reason, reason);
517 }
518 }),
519 );
520
521 it.effect("never lets fetch follow a redirect with the token", () => {
522 const server = fakeGitCafe({ "GET /repos/owner/repo/pulls/7/stack": { stack: null } });
523 return GitCafePullRequestProvider.make.pipe(
524 Effect.flatMap((provider) => provider.getChangeRequestStack!(target)),
525 Effect.tap(() =>
526 Effect.sync(() =>
527 assert.deepStrictEqual(
528 server.sent.map((r) => r.redirect),
529 ["manual"],
530 ),
531 ),
532 ),
533 Effect.provide(server.layer),
534 );
535 });
536
537 it.effect("follows a renumbered pull request's redirect only within the host's API", () =>
538 Effect.gen(function* () {
539 const moved = (location: string) =>
540 new Response(null, { status: 301, headers: { location } });
541 const renumbered = fakeGitCafe({
542 "GET /repos/owner/repo/pulls/7/stack": moved("/api/repos/owner/repo/pulls/8/stack"),
543 "GET /repos/owner/repo/pulls/8/stack": { stack: null },
544 });
545 yield* GitCafePullRequestProvider.make.pipe(
546 Effect.flatMap((provider) => provider.getChangeRequestStack!(target)),
547 Effect.provide(renumbered.layer),
548 );
549 assert.deepStrictEqual(
550 renumbered.sent.map((r) => `${r.host}${r.path}`),
551 ["git.cafe/repos/owner/repo/pulls/7/stack", "git.cafe/repos/owner/repo/pulls/8/stack"],
552 );
553
554 for (const location of [
555 "https://evil.example/api/repos/owner/repo/pulls/8/stack",
556 "//evil.example/api/repos/owner/repo/pulls/8/stack",
557 "https://staging.git.cafe/api/repos/owner/repo/pulls/8/stack",
558 "/repos/owner/repo/pulls/8/stack",
559 ]) {
560 const elsewhere = fakeGitCafe({ "GET /repos/owner/repo/pulls/7/stack": moved(location) });
561 const error = yield* GitCafePullRequestProvider.make.pipe(
562 Effect.flatMap((provider) => provider.getChangeRequestStack!(target)),
563 Effect.flip,
564 Effect.provide(elsewhere.layer),
565 );
566 assert.strictEqual(error.detail, "GitCafe answered HTTP 301.");
567 assert.strictEqual(elsewhere.sent.length, 1);
568 }
569 }),
570 );
571
572 it.effect("reads the stack a pull request belongs to, with each open layer's head", () => {
573 const { "GET /repos/owner/repo/pulls/6": _merged, ...routes } = stack([
574 { number: 6, headOid: baseOid, state: "merged" },
575 { number: 7, headOid },
576 ]);
577 const server = fakeGitCafe(routes);
578 return Effect.gen(function* () {
579 const provider = yield* GitCafePullRequestProvider.make;
580 const result = yield* provider.getChangeRequestStack!(target);
581 assert.strictEqual(result?.number, 3);
582 assert.deepStrictEqual(
583 result?.layers.map((layer) => [layer.number, layer.headSha]),
584 [
585 [6, undefined],
586 [7, headOid],
587 ],
588 );
589 }).pipe(Effect.provide(server.layer));
590 });
591
592 it.effect("resolves a thread through its root at the root's version", () => {
593 const server = fakeGitCafe({
594 "GET /repos/owner/repo/pulls/7/comments": { items: [root], next: null },
595 "POST /repos/owner/repo/pulls/7/comments/root/resolve": {
596 id: "root",
597 threadId: "root",
598 version: 3,
599 },
600 });
601 return Effect.gen(function* () {
602 const provider = yield* GitCafePullRequestProvider.make;
603 yield* provider.setThreadResolution({ ...target, threadId: "root", resolved: true });
604 assert.deepStrictEqual(server.writes(), [
605 "POST /repos/owner/repo/pulls/7/comments/root/resolve",
606 ]);
607 assert.deepStrictEqual(server.sent.at(-1)?.body, { expectedVersion: 2 });
608 }).pipe(Effect.provide(server.layer));
609 });
610
611 it.effect("keeps the timeline when GitCafe no longer has the head's commits", () => {
612 const comment = { ...root, id: "c1", threadId: "c1", body: "Looks good", path: null };
613 const server = fakeGitCafe({
614 "GET /repos/owner/repo/pulls/7": { ...pull, state: "closed", closedAt: timestamp },
615 "GET /repos/owner/repo/pulls/7/comments": { items: [comment], next: null },
616 "GET /repos/owner/repo/pulls/7/reviews": { items: [], next: null },
617 });
618 return Effect.gen(function* () {
619 const provider = yield* GitCafePullRequestProvider.make;
620 const activity = yield* provider.getChangeRequestActivity(target);
621 assert.deepStrictEqual(
622 activity.comments.map((entry) => entry.body),
623 ["Looks good"],
624 );
625 }).pipe(Effect.provide(server.layer));
626 });
627
628 it.effect("submits a review against the pull request's current head", () => {
629 const server = fakeGitCafe({
630 "GET /repos/owner/repo/pulls/7": pull,
631 "POST /repos/owner/repo/pulls/7/reviews": { id: "review-1" },
632 });
633 return Effect.gen(function* () {
634 const provider = yield* GitCafePullRequestProvider.make;
635 yield* provider.submitReview({
636 ...target,
637 verdict: "request-changes",
638 body: "Please fix",
639 comments: [],
640 });
641 assert.deepStrictEqual(server.writes(), ["POST /repos/owner/repo/pulls/7/reviews"]);
642 assert.deepInclude(server.sent.at(-1)?.body as object, {
643 verdict: "request_changes",
644 body: "Please fix",
645 commitOid: headOid,
646 });
647 assertRequestId(server.sent.at(-1)?.body);
648
649 // GitCafe rejects a null body; an empty review leaves it out.
650 yield* provider.submitReview({ ...target, verdict: "approve", body: "", comments: [] });
651 assert.notProperty(server.sent.at(-1)?.body as object, "body");
652 assertRequestId(server.sent.at(-1)?.body);
653 }).pipe(Effect.provide(server.layer));
654 });
655
656 it.effect.each([
657 ["completed", true],
658 ["failed", false],
659 ] as const)("merges synchronously and reads a %s outcome", ([state, succeeds]) => {
660 const server = fakeGitCafe({
661 "GET /repos/owner/repo/pulls/7": pull,
662 "POST /repos/owner/repo/pulls/7/merge": { id: "merge-1", state, reason: "Blocked" },
663 });
664 return Effect.gen(function* () {
665 const provider = yield* GitCafePullRequestProvider.make;
666 const result = yield* provider
667 .runAction({
668 ...target,
669 action: "merge",
670 mergeMethod: "squash",
671 expectedHeadSha: baseOid,
672 })
673 .pipe(Effect.result);
674 assert.strictEqual(result._tag, succeeds ? "Success" : "Failure");
675 assert.deepStrictEqual(server.writes(), ["POST /repos/owner/repo/pulls/7/merge"]);
676 assert.deepInclude(server.sent.at(-1)?.body as object, {
677 headOid: baseOid,
678 strategy: "squash",
679 expectedVersion: 4,
680 });
681 assertRequestId(server.sent.at(-1)?.body);
682 }).pipe(Effect.provide(server.layer));
683 });
684
685 it.effect("reads a GitHub-mirrored check's log, and re-runs only GitCafe Actions runs", () => {
686 const server = fakeGitCafe({
687 "GET /repos/owner/repo/ci/github/checks/555/log": {
688 content: "install\ntest\nFAIL a.test.ts\n",
689 truncated: true,
690 },
691 "POST /repos/owner/repo/actions/runs/actwfrun_abc/rerun": {},
692 "GET /repos/owner/repo/ci/github/checks/401/log": new Response("{}", { status: 401 }),
693 });
694 const mirrored = { name: "Test", url: "https://github.com/owner/repo/runs/555" };
695 const missing = { name: "Gone", url: "https://github.com/owner/repo/runs/404" };
696 const signedOut = { name: "Lint", url: "https://github.com/owner/repo/runs/401" };
697 const native = { name: "Build", url: "https://git.cafe/owner/repo/actions/runs/actwfrun_abc" };
698 return Effect.gen(function* () {
699 const provider = yield* GitCafePullRequestProvider.make;
700 const logs = yield* provider.getCheckLogs!({
701 ...target,
702 checks: [mirrored, missing],
703 tailLines: 1,
704 });
705 assert.deepInclude(logs[0], { log: "FAIL a.test.ts", truncated: true, detail: null });
706 assert.isNotNull(logs[1]?.detail);
707 const refused = yield* Effect.flip(
708 provider.getCheckLogs!({ ...target, checks: [signedOut], tailLines: 1 }),
709 );
710 assert.strictEqual(refused.reason, "unauthenticated");
711 const reruns = yield* provider.rerunChecks!({ ...target, checks: [mirrored, native] });
712 assert.deepStrictEqual(
713 reruns.map(({ name, rerun }) => [name, rerun]),
714 [
715 ["Test", false],
716 ["Build", true],
717 ],
718 );
719 assert.deepStrictEqual(server.writes(), [
720 "POST /repos/owner/repo/actions/runs/actwfrun_abc/rerun",
721 ]);
722 }).pipe(Effect.provide(server.layer));
723 });
724
725 it.effect(
726 "lands a stack through a layer only while its heads are the ones the reader saw",
727 () => {
728 const layers = [
729 { number: 6, headOid: baseOid },
730 { number: 7, headOid },
731 ];
732 const server = fakeGitCafe({
733 ...stack(layers),
734 "POST /repos/owner/repo/pulls/stacks/3/land-through": {
735 id: "land-1",
736 state: "completed",
737 landedCount: 2,
738 stepCount: 2,
739 stopReason: null,
740 error: null,
741 steps: [],
742 },
743 });
744 return Effect.gen(function* () {
745 const provider = yield* GitCafePullRequestProvider.make;
746 const heads = layers.map((layer) => ({ number: layer.number, headSha: layer.headOid }));
747 const stale = yield* provider
748 .runAction({
749 ...target,
750 action: "merge",
751 stackNumber: 3,
752 expectedStackHeads: [heads[0]!, { number: 7, headSha: baseOid }],
753 })
754 .pipe(Effect.result);
755 assert.strictEqual(stale._tag, "Failure");
756 assert.deepStrictEqual(server.writes(), []);
757
758 yield* provider.runAction({
759 ...target,
760 action: "merge",
761 stackNumber: 3,
762 expectedStackHeads: heads,
763 mergeMethod: "merge",
764 });
765 assert.deepStrictEqual(server.writes(), [
766 "POST /repos/owner/repo/pulls/stacks/3/land-through",
767 ]);
768 assert.deepInclude(server.sent.at(-1)?.body as object, {
769 expectedRevision: 5,
770 throughPullRequestNumber: 7,
771 strategy: "merge",
772 });
773 assertRequestId(server.sent.at(-1)?.body);
774 }).pipe(Effect.provide(server.layer));
775 },
776 );
777
778 it.effect.each([
779 ["authored", "authors"],
780 ["reviewing", "reviewers"],
781 ] as const)("filters %s pull requests by the viewer's actor on GitCafe", ([involvement, key]) => {
782 const server = fakeGitCafe({
783 "GET /auth/principal": { actorId: "act_one", handle: "Alice" },
784 "GET /repos/owner/repo/pulls": { items: [pull], next: null },
785 });
786 return Effect.gen(function* () {
787 const provider = yield* GitCafePullRequestProvider.make;
788 const page = yield* provider.listChangeRequests({
789 ...target,
790 state: "open",
791 involvement,
792 viewer: "alice",
793 limit: 10,
794 });
795 assert.strictEqual(server.sent.at(-1)?.query.get(key), '["act_one"]');
796 assert.strictEqual(
797 page.items[0]?.reviewRequestLogins.includes("alice"),
798 involvement === "reviewing",
799 );
800 }).pipe(Effect.provide(server.layer));
801 });
802
803 it.effect("narrows a listing on GitCafe by label ids, draft state and the author's actor", () => {
804 const server = fakeGitCafe({
805 "GET /repos/owner/repo/labels": { items: labels, next: null },
806 "GET /users/bob": { actorId: "act_bob", handle: "bob" },
807 "GET /repos/owner/repo/pulls": { items: [pull], next: null },
808 });
809 return Effect.gen(function* () {
810 const provider = yield* GitCafePullRequestProvider.make;
811 yield* provider.listChangeRequests({
812 ...target,
813 state: "open",
814 involvement: "all",
815 viewer: "alice",
816 limit: 10,
817 filters: {
818 draft: "hide",
819 labels: [["missing"], ["Bug", "docs"]],
820 excludedLabels: ["docs", "missing"],
821 author: "bob",
822 },
823 });
824 const listing = server.sent.at(-1)!;
825 assert.strictEqual(listing.path, "/repos/owner/repo/pulls");
826 assert.strictEqual(listing.query.get("labels"), '["label_bug","label_docs"]');
827 assert.strictEqual(listing.query.get("labelNots"), '["label_docs"]');
828 assert.strictEqual(listing.query.get("stateNots"), '["draft"]');
829 assert.strictEqual(listing.query.get("authors"), '["act_bob"]');
830 }).pipe(Effect.provide(server.layer));
831 });
832
833 it.effect("finds a GitHub-synced author's actor on their pull requests to narrow by it", () => {
834 const synced = {
835 ...pull,
836 number: 8,
837 author: { kind: "github", actorId: "act_synced", login: "Synced", avatarUrl: null },
838 };
839 const server = fakeGitCafe({
840 "GET /repos/owner/repo/pulls": (request: SentRequest) =>
841 request.query.get("authors") === '["act_synced"]'
842 ? { items: [synced], next: null }
843 : request.query.get("after") === null
844 ? { items: [pull], next: "o1" }
845 : { items: [synced], next: null },
846 });
847 return Effect.gen(function* () {
848 const provider = yield* GitCafePullRequestProvider.make;
849 const list = (author: string) =>
850 provider.listChangeRequests({
851 ...target,
852 state: "open",
853 involvement: "all",
854 viewer: "alice",
855 limit: 10,
856 filters: { author },
857 });
858 const page = yield* list("synced");
859 assert.deepStrictEqual(
860 page.items.map((item) => item.number),
861 [8],
862 );
863 assert.strictEqual(server.sent.at(-1)!.query.get("authors"), '["act_synced"]');
864 // Once seen, the actor is narrowed by straight away.
865 const sentBefore = server.sent.length;
866 yield* list("synced");
867 assert.deepStrictEqual(
868 server.sent.slice(sentBefore).map((request) => request.query.get("authors")),
869 [null, '["act_synced"]'],
870 );
871 // An author on none of the pages it reads gets nothing rather than unnarrowed rows a
872 // continuation would count against a different listing.
873 const missing = yield* list("nobody");
874 assert.deepStrictEqual(missing, { items: [], truncated: false, continues: false });
875 }).pipe(Effect.provide(server.layer));
876 });
877
878 it.effect("carries a listing on after the last row delivered when rows above it close", () => {
879 const created = (number: number) => `2026-09-12T12:00:0${9 - number}Z`;
880 let pulls = [1, 2, 3, 4, 5].map((number) => ({ ...pull, number, createdAt: created(number) }));
881 const server = fakeGitCafe({
882 "GET /repos/owner/repo/pulls": (request: SentRequest) => {
883 const offset = Number(request.query.get("after")?.slice(1) ?? 0);
884 const end = offset + Number(request.query.get("limit"));
885 return { items: pulls.slice(offset, end), next: end < pulls.length ? `o${end}` : null };
886 },
887 });
888 return Effect.gen(function* () {
889 const provider = yield* GitCafePullRequestProvider.make;
890 const list = (cursor?: { readonly resumeAfter?: string }) =>
891 provider.listChangeRequests({
892 ...target,
893 state: "open",
894 involvement: "all",
895 viewer: "alice",
896 limit: 2,
897 ...(cursor === undefined
898 ? {}
899 : { cursor: { updatedBefore: timestamp, delivered: 2, ...cursor } }),
900 });
901 const first = yield* list();
902 assert.deepStrictEqual(
903 first.items.map((item) => item.number),
904 [1, 2],
905 );
906 pulls = pulls.filter((candidate) => candidate.number !== 1);
907 const next = yield* list({ resumeAfter: first.resumeAfter! });
908 assert.deepStrictEqual(
909 next.items.map((item) => item.number),
910 [3, 4],
911 );
912 assert.isTrue(next.truncated);
913 assert.isTrue(next.continues);
914 }).pipe(Effect.provide(server.layer));
915 });
916
917 it.effect("lists nothing for a viewer the token does not belong to", () => {
918 const server = fakeGitCafe({
919 "GET /auth/principal": { actorId: "act_two", handle: "bob" },
920 });
921 return Effect.gen(function* () {
922 const provider = yield* GitCafePullRequestProvider.make;
923 const page = yield* provider.listChangeRequests({
924 ...target,
925 state: "open",
926 involvement: "authored",
927 viewer: "alice",
928 limit: 10,
929 });
930 assert.deepStrictEqual(page.items, []);
931 assert.deepStrictEqual(
932 server.sent.map((request) => request.path),
933 ["/auth/principal"],
934 );
935 }).pipe(Effect.provide(server.layer));
936 });
937
938 it.effect.each(["authored", "reviewing"] as const)(
939 "lists %s unnarrowed when GitCafe can't say who the viewer is",
940 (involvement) => {
941 const server = fakeGitCafe({ "GET /repos/owner/repo/pulls": { items: [pull], next: null } });
942 return Effect.gen(function* () {
943 const provider = yield* GitCafePullRequestProvider.make;
944 const page = yield* provider.listChangeRequests({
945 ...target,
946 state: "open",
947 involvement,
948 viewer: "alice",
949 limit: 10,
950 });
951 const listing = server.sent.find((request) => request.path === "/repos/owner/repo/pulls");
952 assert.isDefined(listing);
953 assert.isNull(listing!.query.get(involvement === "reviewing" ? "reviewers" : "authors"));
954 assert.notInclude(page.items[0]?.reviewRequestLogins ?? [], "alice");
955 }).pipe(Effect.provide(server.layer));
956 },
957 );
958
959 it.effect("reads line counts, open merge strategies, reviewers and labels", () => {
960 const snapshot = { version: 4, headOid, comparisonBaseOid: baseOid };
961 const files = (from: number, count: number) =>
962 Array.from({ length: count }, (_, index) => ({ path: `f${from + index}.ts` }));
963 let changePage = 0;
964 const server = fakeGitCafe({
965 "GET /repos/owner/repo/pulls/7": pull,
966 "GET /repos/owner/repo/pulls/7/reviewers": { items: [{ id: "act_one", actor }], next: null },
967 "GET /repos/owner/repo/pulls/7/labels": { items: [labels[0]], next: null },
968 "GET /repos/owner/repo/pulls/7/status": {
969 merge: {
970 conflicts: "none",
971 fastForward: true,
972 strategies: ["merge", "squash", "rebase"],
973 blockers: [{ blockedStrategies: ["squash"] }, {}],
974 },
975 checks: { pending: 0, failing: 0, total: 0 },
976 },
977 [`GET /repos/owner/repo/commits/${headOid}/checks`]: (request: SentRequest) => ({
978 items: [
979 {
980 name: request.query.has("after") ? "late" : "early",
981 status: "completed",
982 conclusion: request.query.has("after") ? "failure" : "success",
983 summary: null,
984 detailsUrl: null,
985 },
986 ],
987 next: request.query.has("after") ? null : "checks-1",
988 }),
989 "GET /repos/owner/repo/pulls/7/changes": () =>
990 changePage++ === 0
991 ? { ...snapshot, items: files(0, 2), next: "cursor-1" }
992 : { ...snapshot, items: files(2, 1), next: null },
993 "POST /repos/owner/repo/pulls/7/diff-files": (request: SentRequest) => ({
994 ...snapshot,
995 items: (request.body as { paths: ReadonlyArray<string> }).paths.map((path) => ({
996 path,
997 additions: 2,
998 deletions: 1,
999 })),
1000 }),
1001 });
1002 return Effect.gen(function* () {
1003 const provider = yield* GitCafePullRequestProvider.make;
1004 const detail = yield* provider.getChangeRequest(target);
1005 assert.deepInclude(detail, {
1006 additions: 6,
1007 deletions: 3,
1008 changedFiles: 3,
1009 mergeability: "mergeable",
1010 });
1011 assert.strictEqual(
1012 server.sent.filter((request) => request.path.endsWith("/changes"))[1]?.query.get("after"),
1013 "cursor-1",
1014 );
1015 assert.deepStrictEqual(detail.mergeCapabilities, {
1016 merge: true,
1017 squash: false,
1018 rebase: true,
1019 });
1020 assert.deepStrictEqual(
1021 detail.checks.map((check) => check.name),
1022 ["late", "early"],
1023 );
1024 assert.deepStrictEqual(
1025 detail.reviewers.map((reviewer) => reviewer.login),
1026 ["alice"],
1027 );
1028 assert.deepStrictEqual(detail.reviewRequestLogins, ["alice"]);
1029 assert.deepStrictEqual(detail.labels, [{ name: "bug", color: "#d73a4a" }]);
1030 }).pipe(Effect.provide(server.layer));
1031 });
1032
1033 it.effect("reads the checks state from each check's newest run", () => {
1034 const run = (id: string, conclusion: string) => ({
1035 id,
1036 name: "Check",
1037 status: "completed",
1038 conclusion,
1039 summary: null,
1040 detailsUrl: null,
1041 });
1042 const items = [run("120859457782", "success"), run("120857059247", "failure")];
1043 const detailWith = (checks: (request: SentRequest) => unknown) => {
1044 const server = fakeGitCafe({
1045 "GET /repos/owner/repo/pulls/7": pull,
1046 "GET /repos/owner/repo/pulls/7/reviewers": { items: [], next: null },
1047 "GET /repos/owner/repo/pulls/7/labels": { items: [], next: null },
1048 "GET /repos/owner/repo/pulls/7/status": {
1049 merge: { conflicts: "none", fastForward: null, strategies: [] },
1050 // GitCafe counts the cancelled run's failure beside the re-run that passed.
1051 checks: { pending: 0, failing: 1, total: 2 },
1052 },
1053 [`GET /repos/owner/repo/commits/${headOid}/checks`]: checks,
1054 "GET /repos/owner/repo/pulls/7/changes": {
1055 version: 4,
1056 headOid,
1057 comparisonBaseOid: baseOid,
1058 items: [],
1059 next: null,
1060 },
1061 });
1062 return Effect.gen(function* () {
1063 const provider = yield* GitCafePullRequestProvider.make;
1064 return yield* provider.getChangeRequest(target);
1065 }).pipe(Effect.provide(server.layer));
1066 };
1067 return Effect.gen(function* () {
1068 const detail = yield* detailWith(() => ({ items, next: null }));
1069 assert.deepStrictEqual(
1070 detail.checks.map((check) => [check.name, check.status]),
1071 [["Check", "success"]],
1072 );
1073 assert.strictEqual(detail.checksState, "passing");
1074
1075 // A listing cut off at the page limit may hide a failure, so GitCafe's counts decide.
1076 const truncated = yield* detailWith((request) => ({
1077 items,
1078 next: String(Number(request.query.get("after") ?? 0) + 1),
1079 }));
1080 assert.strictEqual(truncated.checksState, "failing");
1081 });
1082 });
1083
1084 it.effect("still reads a pull request whose reviewers the token may not see", () => {
1085 const server = fakeGitCafe({
1086 "GET /repos/owner/repo/pulls/7": { ...pull, headOid: null },
1087 "GET /repos/owner/repo/pulls/7/reviewers": new Response(
1088 encodeJson({ type: "https://cafe.sh/errors/forbidden" }),
1089 { status: 403 },
1090 ),
1091 "GET /repos/owner/repo/pulls/7/labels": { items: [labels[0]], next: null },
1092 "GET /repos/owner/repo/pulls/7/status": {
1093 merge: { conflicts: "unknown", fastForward: null, strategies: [] },
1094 checks: { pending: 0, failing: 0, total: 0 },
1095 },
1096 });
1097 return Effect.gen(function* () {
1098 const provider = yield* GitCafePullRequestProvider.make;
1099 const detail = yield* provider.getChangeRequest(target);
1100 assert.deepStrictEqual(detail.reviewers, []);
1101 assert.deepStrictEqual(detail.labels, [{ name: "bug", color: "#d73a4a" }]);
1102 }).pipe(Effect.provide(server.layer));
1103 });
1104
1105 it.effect("fails the detail rather than hide reviewers GitCafe could not serve", () => {
1106 const server = fakeGitCafe({
1107 "GET /repos/owner/repo/pulls/7": { ...pull, headOid: null },
1108 "GET /repos/owner/repo/pulls/7/reviewers": new Response("", { status: 503 }),
1109 "GET /repos/owner/repo/pulls/7/labels": { items: [], next: null },
1110 "GET /repos/owner/repo/pulls/7/status": {
1111 merge: { conflicts: "unknown", fastForward: null, strategies: [] },
1112 checks: { pending: 0, failing: 0, total: 0 },
1113 },
1114 });
1115 return Effect.gen(function* () {
1116 const provider = yield* GitCafePullRequestProvider.make;
1117 const result = yield* provider.getChangeRequest(target).pipe(Effect.result);
1118 assert.strictEqual(result._tag, "Failure");
1119 }).pipe(Effect.provide(server.layer));
1120 });
1121
1122 const detailWith = (overrides: Record<string, unknown>, reasons: ReadonlyArray<string> = []) =>
1123 fakeGitCafe({
1124 "GET /repos/owner/repo/pulls/7": { ...pull, headOid: null, ...overrides },
1125 "GET /repos/owner/repo/pulls/7/reviewers": { items: [], next: null },
1126 "GET /repos/owner/repo/pulls/7/labels": { items: [], next: null },
1127 "GET /repos/owner/repo/pulls/7/status": {
1128 merge: { conflicts: "none", fastForward: null, strategies: ["squash"], reasons },
1129 checks: { pending: 0, failing: 0, total: 0 },
1130 },
1131 });
1132
1133 it.effect("shows a merge GitCafe accepted as armed until it lands", () => {
1134 const server = detailWith({}, ["provider-merge-pending"]);
1135 return Effect.gen(function* () {
1136 const provider = yield* GitCafePullRequestProvider.make;
1137 const detail = yield* provider.getChangeRequest(target);
1138 assert.strictEqual(detail.autoMergeEnabled, true);
1139 assert.notInclude(detail.viewerPermissions?.actions ?? [], "merge");
1140 }).pipe(Effect.provide(server.layer));
1141 });
1142
1143 it.effect("reads a pull request GitHub merged as merged before the sync reports it", () => {
1144 const mergedAt = "2026-09-12T13:00:00Z";
1145 const mergeCommitOid = "3b2f958603a51d8c42c4ede02eee7b8cb310b2d9";
1146 const server = detailWith({ providerMerge: { mergedAt, mergeCommitOid } });
1147 return Effect.gen(function* () {
1148 const provider = yield* GitCafePullRequestProvider.make;
1149 const detail = yield* provider.getChangeRequest(target);
1150 assert.strictEqual(detail.state, "merged");
1151 assert.strictEqual(detail.mergedAt, mergedAt);
1152 const preview = yield* provider.getChangeRequestPreview!(target);
1153 assert.strictEqual(preview.state, "merged");
1154 assert.strictEqual(detail.mergeCommitSha, mergeCommitOid);
1155 }).pipe(Effect.provide(server.layer));
1156 });
1157
1158 it.effect.each([
1159 ["their own pull request", actor],
1160 [
1161 "the pull request GitHub sync opened for them",
1162 {
1163 kind: "github",
1164 actorId: "act_github",
1165 login: "alice",
1166 avatarUrl: null,
1167 linkedProfile: { handle: "alice", actorId: "act_one" },
1168 },
1169 ],
1170 ] as const)("leaves the author only a comment on %s", ([, author]) => {
1171 const server = detailWith({ author, viewerActorId: "act_one" });
1172 return Effect.gen(function* () {
1173 const provider = yield* GitCafePullRequestProvider.make;
1174 const detail = yield* provider.getChangeRequest(target);
1175 assert.deepStrictEqual(detail.viewerPermissions?.verdicts, ["comment"]);
1176 }).pipe(Effect.provide(server.layer));
1177 });
1178
1179 it.effect("requests and withdraws reviewers by rewriting the whole list", () => {
1180 const bob = { ...actor, actorId: "act_two", handle: "bob" };
1181 let requested = [{ id: "act_two", actor: bob }];
1182 const server = fakeGitCafe({
1183 "GET /repos/owner/repo/pulls/7": pull,
1184 "GET /repos/owner/repo/pulls/7/reviewer-candidates": {
1185 items: [
1186 { id: "act_one", actor },
1187 { id: "act_two", actor: bob },
1188 { id: "act_bot", actor: { ...actor, actorId: "act_bot", handle: "lint", bot: true } },
1189 ],
1190 next: null,
1191 },
1192 "GET /repos/owner/repo/pulls/7/reviewers": () => ({ items: requested, next: null }),
1193 "PUT /repos/owner/repo/pulls/7/reviewers": { version: 5, items: [] },
1194 });
1195 return Effect.gen(function* () {
1196 const provider = yield* GitCafePullRequestProvider.make;
1197 const list = yield* provider.listReviewerCandidates(target);
1198 // The author, alice, cannot review her own pull request.
1199 assert.deepStrictEqual(
1200 list.candidates.map((c) => [c.id, c.login, c.isRequested, c.isBot ?? false]),
1201 [
1202 ["act_two", "bob", true, false],
1203 ["act_bot", "lint", false, true],
1204 ],
1205 );
1206
1207 const set = (id: string, on: boolean) =>
1208 provider.setReviewerRequest({
1209 ...target,
1210 reviewers: [{ id, kind: "user" }],
1211 requested: on,
1212 });
1213 yield* set("act_bot", true);
1214 assert.deepStrictEqual(server.sent.at(-1)?.body, {
1215 expectedVersion: 4,
1216 actorIds: ["act_two", "act_bot"],
1217 });
1218 yield* set("act_two", false);
1219 assert.deepStrictEqual(server.sent.at(-1)?.body, { expectedVersion: 4, actorIds: [] });
1220
1221 requested = [];
1222 yield* set("act_two", false);
1223 assert.strictEqual(server.writes().length, 2);
1224 }).pipe(Effect.provide(server.layer));
1225 });
1226
1227 it.effect("names the missing scopes when the token may not request reviewers", () => {
1228 const server = fakeGitCafe({
1229 "GET /repos/owner/repo/pulls/7": pull,
1230 "GET /repos/owner/repo/pulls/7/reviewer-candidates": new Response("", { status: 403 }),
1231 "GET /repos/owner/repo/pulls/7/reviewers": { items: [], next: null },
1232 });
1233 return Effect.gen(function* () {
1234 const provider = yield* GitCafePullRequestProvider.make;
1235 const error = yield* Effect.flip(provider.listReviewerCandidates(target));
1236 assert.match(error.detail, /pr:reviewers:write/u);
1237 }).pipe(Effect.provide(server.layer));
1238 });
1239
1240 it.effect("applies and removes labels by name through their ids", () => {
1241 const server = fakeGitCafe({
1242 "GET /repos/owner/repo/pulls/7": pull,
1243 "GET /repos/owner/repo/labels": { items: labels, next: null },
1244 "GET /repos/owner/repo/pulls/7/labels": { items: [labels[0]], next: null },
1245 "PUT /repos/owner/repo/pulls/7/labels": { version: 5, items: [] },
1246 });
1247 return Effect.gen(function* () {
1248 const provider = yield* GitCafePullRequestProvider.make;
1249 const list = yield* provider.listLabelCandidates!(target);
1250 assert.deepStrictEqual(
1251 list.candidates.map((label) => [label.name, label.isApplied]),
1252 [
1253 ["bug", true],
1254 ["docs", false],
1255 ],
1256 );
1257
1258 yield* provider.setLabels!({ ...target, labels: ["docs"], applied: true });
1259 assert.deepStrictEqual(server.sent.at(-1)?.body, {
1260 expectedVersion: 4,
1261 labelIds: ["label_bug", "label_docs"],
1262 });
1263 yield* provider.setLabels!({ ...target, labels: ["bug"], applied: false });
1264 assert.deepStrictEqual(server.sent.at(-1)?.body, { expectedVersion: 4, labelIds: [] });
1265
1266 const missing = yield* provider.setLabels!({
1267 ...target,
1268 labels: ["nope"],
1269 applied: true,
1270 }).pipe(Effect.result);
1271 assert.strictEqual(missing._tag, "Failure");
1272 assert.strictEqual(server.writes().length, 2);
1273 }).pipe(Effect.provide(server.layer));
1274 });
1275
1276 it.effect("recounts summary lines only when the compared commits move", () => {
1277 const landedBase = "fedcba9876543210fedcba9876543210fedcba98";
1278 const mainTip = "0123012301230123012301230123012301230123";
1279 let comparisonBaseOid = baseOid;
1280 let tips = { targetBranch: "main", observedBaseOid: baseOid };
1281 let pullReads = 0;
1282 let listingCut = true;
1283 let hunksDown = false;
1284 const hunks = (request: SentRequest) => ({
1285 version: 4,
1286 headOid,
1287 comparisonBaseOid,
1288 items: (request.body as { paths: ReadonlyArray<string> }).paths.map((path) => ({
1289 path,
1290 additions: comparisonBaseOid === baseOid ? 3 : 1,
1291 deletions: 1,
1292 })),
1293 });
1294 const server = fakeGitCafe({
1295 // A comment moves the version without moving the compared commits.
1296 "GET /repos/owner/repo/pulls/7": () => ({ ...pull, ...tips, version: 4 + pullReads++ }),
1297 "GET /repos/owner/repo/pulls/7/changes": (request: SentRequest) => ({
1298 version: 4,
1299 headOid,
1300 comparisonBaseOid,
1301 ...(!listingCut
1302 ? { items: [{ path: "a.ts" }, { path: "b.ts" }], next: null }
1303 : request.query.has("after")
1304 ? { items: [], next: "more" }
1305 : { items: [{ path: "a.ts" }], next: "more" }),
1306 }),
1307 get "POST /repos/owner/repo/pulls/7/diff-files"() {
1308 return hunksDown
1309 ? new Response(encodeJson({ type: "https://cafe.sh/errors/conflict" }), { status: 409 })
1310 : hunks;
1311 },
1312 });
1313 const reads = (suffix: string) =>
1314 server.sent.filter((request) => request.path.endsWith(suffix)).length;
1315 return Effect.gen(function* () {
1316 const provider = yield* GitCafePullRequestProvider.make;
1317 // A listing that stops before its last page holds nothing for its commits.
1318 yield* provider.getChangeRequestSummary!(target);
1319 listingCut = false;
1320 hunksDown = true;
1321 // Unread hunks leave the lines unknown, and are read again next time.
1322 const unread = yield* provider.getChangeRequestSummary!(target);
1323 assert.strictEqual(unread.additions, undefined);
1324 hunksDown = false;
1325 const first = yield* provider.getChangeRequestSummary!(target);
1326 const second = yield* provider.getChangeRequestSummary!(target);
1327 assert.deepInclude(first, { additions: 6, deletions: 2, changedFiles: 2 });
1328 assert.deepInclude(second, { additions: 6, deletions: 2, changedFiles: 2 });
1329 // Neither the head nor the target tip moved, so the file list is not read again.
1330 assert.deepStrictEqual([reads("/changes"), reads("/diff-files")], [4, 3]);
1331 // The target branch advancing keeps the merge base, so only the file list is read.
1332 tips = { ...tips, observedBaseOid: mainTip };
1333 const third = yield* provider.getChangeRequestSummary!(target);
1334 assert.deepInclude(third, { additions: 6, deletions: 2, changedFiles: 2 });
1335 assert.deepStrictEqual([reads("/changes"), reads("/diff-files")], [5, 3]);
1336 // A landed parent layer retargets the pull and moves the comparison base under the same head.
1337 comparisonBaseOid = landedBase;
1338 tips = { targetBranch: "trunk", observedBaseOid: mainTip };
1339 const fourth = yield* provider.getChangeRequestSummary!(target);
1340 assert.deepInclude(fourth, { additions: 2, deletions: 2, changedFiles: 2 });
1341 assert.deepStrictEqual([reads("/changes"), reads("/diff-files")], [6, 4]);
1342 }).pipe(Effect.provide(server.layer));
1343 });
1344
1345 it.effect("fences a native merge on the target branch's current commit", () => {
1346 const branchOid = "fedcba9876543210fedcba9876543210fedcba98";
1347 const server = fakeGitCafe({
1348 "GET /repos/owner/repo/pulls/7": { ...pull, mergeRoute: "native", observedBaseOid: null },
1349 "GET /repos/owner/repo/commit": { oid: branchOid },
1350 "POST /repos/owner/repo/pulls/7/merge": { id: "merge-1", state: "completed" },
1351 });
1352 return Effect.gen(function* () {
1353 const provider = yield* GitCafePullRequestProvider.make;
1354 yield* provider.runAction({ ...target, action: "merge" });
1355 const branchRead = server.sent.find((request) => request.path === "/repos/owner/repo/commit");
1356 assert.strictEqual(branchRead?.query.get("ref"), "refs/heads/main");
1357 assert.deepInclude(server.sent.at(-1)?.body as object, { baseOid: branchOid, headOid });
1358 }).pipe(Effect.provide(server.layer));
1359 });
1360
1361 it.effect("refuses to drop a reaction whose id it cannot address", () => {
1362 const server = fakeGitCafe({
1363 "GET /repos/owner/repo/pulls/7/reactions/": {
1364 items: [
1365 {
1366 subject: { kind: "pull_request_comment", id: "root" },
1367 emoji: { kind: "unicode", value: "🚀" },
1368 count: 1,
1369 viewerReactionId: "../escape",
1370 reactors: [actor],
1371 },
1372 ],
1373 next: null,
1374 },
1375 });
1376 return Effect.gen(function* () {
1377 const provider = yield* GitCafePullRequestProvider.make;
1378 const result = yield* provider
1379 .setReaction({ ...target, subjectId: "root", content: "rocket", reacted: false })
1380 .pipe(Effect.result);
1381 assert.strictEqual(result._tag, "Failure");
1382 assert.deepStrictEqual(server.writes(), []);
1383 }).pipe(Effect.provide(server.layer));
1384 });
1385});