Open History to see the last commit
1import { afterEach, assert, expect, it, vi } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import { ChildProcessSpawner } from "effect/process";
5
6import * as AzureDevOpsCli from "./AzureDevOpsCli.ts";
7import * as AzureDevOpsPullRequestCli from "./AzureDevOpsPullRequestCli.ts";
8import * as AzureDevOpsPullRequestProvider from "./AzureDevOpsPullRequestProvider.ts";
9
10const mockedExecute = vi.fn<AzureDevOpsCli.AzureDevOpsCli["Service"]["execute"]>();
11
12const layer = it.layer(
13 AzureDevOpsPullRequestCli.layer.pipe(
14 Layer.provide(
15 Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
16 execute: mockedExecute,
17 }),
18 ),
19 ),
20);
21
22function output(stdout: string) {
23 return {
24 exitCode: ChildProcessSpawner.ExitCode(0),
25 stdout,
26 stderr: "",
27 stdoutTruncated: false,
28 stderrTruncated: false,
29 };
30}
31
32const VCS_DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
33
34function outputWithin(maxOutputBytes: number | undefined, response: string) {
35 const ceiling = maxOutputBytes ?? VCS_DEFAULT_MAX_OUTPUT_BYTES;
36 return ceiling >= Buffer.byteLength(response)
37 ? output(response)
38 : { ...output(response.slice(0, ceiling)), stdoutTruncated: true };
39}
40
41const json = (value: Record<string, unknown>) => JSON.stringify(value);
42
43const pullRequestRow = {
44 pullRequestId: 42,
45 title: "Add the page",
46 status: "active",
47 sourceRefName: "refs/heads/feat/page",
48 targetRefName: "refs/heads/main",
49 creationDate: "2026-07-01T00:00:00Z",
50 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
51 repository: { name: "web", project: { name: "platform" } },
52};
53
54const oneIteration = {
55 value: [
56 {
57 id: 1,
58 sourceRefCommit: { commitId: "a".repeat(40) },
59 commonRefCommit: { commitId: "b".repeat(40) },
60 },
61 ],
62};
63
64function pullRequestRows(
65 count: number,
66 firstNumber: number,
67): ReadonlyArray<Record<string, unknown>> {
68 return Array.from({ length: count }, (_, index) => ({
69 pullRequestId: firstNumber + index,
70 title: `Pull request ${firstNumber + index}`,
71 status: "active",
72 sourceRefName: "refs/heads/feat/page",
73 targetRefName: "refs/heads/main",
74 creationDate: "2026-07-01T00:00:00Z",
75 repository: { name: "web", project: { name: "platform" } },
76 url: `https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/${firstNumber + index}`,
77 }));
78}
79
80function pullRequests(count: number, firstNumber: number): string {
81 return JSON.stringify(pullRequestRows(count, firstNumber));
82}
83
84function argsOfCall(index: number): ReadonlyArray<string> {
85 const call = mockedExecute.mock.calls[index];
86 assert.isDefined(call);
87 return call[0].args;
88}
89
90function maxOutputBytesOfCall(index: number) {
91 const call = mockedExecute.mock.calls[index];
92 assert.isDefined(call);
93 return call[0].maxOutputBytes;
94}
95
96function changeEntries(count: number): ReadonlyArray<Record<string, unknown>> {
97 const commit = "c".repeat(40);
98 return Array.from({ length: count }, (_, index) => {
99 const path = `/apps/server/src/generated/module-${index}/persisted-projection-${index}.ts`;
100 return {
101 changeType: "edit",
102 item: {
103 path,
104 objectId: "a".repeat(40),
105 originalObjectId: "b".repeat(40),
106 commitId: commit,
107 gitObjectType: "blob",
108 url: `https://dev.azure.com/acme/platform/_apis/git/repositories/6f9c9b7f-0000-0000-0000-000000000000/items${path}?versionType=Commit&version=${commit}`,
109 },
110 };
111 });
112}
113
114function identity(name: string) {
115 const id = "6f9c9b7f-0000-0000-0000-000000000000";
116 return {
117 displayName: name,
118 id,
119 uniqueName: `${name.toLowerCase().replace(/ /g, ".")}@acme.com`,
120 descriptor: `aad.${"z".repeat(52)}`,
121 imageUrl: `https://dev.azure.com/acme/_api/_common/identityImage?id=${id}`,
122 url: `https://spsprodweu1.vssps.visualstudio.com/A${id}/_apis/Identities/${id}`,
123 _links: {
124 avatar: {
125 href: `https://dev.azure.com/acme/_apis/GraphProfile/MemberAvatars/aad.${"z".repeat(52)}`,
126 },
127 },
128 };
129}
130
131function threadRows(count: number): ReadonlyArray<Record<string, unknown>> {
132 return Array.from({ length: count }, (_, index) => ({
133 id: index + 1,
134 publishedDate: "2026-07-02T00:00:00Z",
135 lastUpdatedDate: "2026-07-02T00:00:00Z",
136 status: "active",
137 threadContext: { filePath: `/apps/server/src/generated/module-${index}.ts` },
138 identities: { 1: identity("Reviewer One") },
139 isDeleted: false,
140 comments: [
141 {
142 id: 1,
143 parentCommentId: 0,
144 author: identity("Reviewer One"),
145 content: `Comment ${index}: ${"this needs another look. ".repeat(20)}`,
146 publishedDate: "2026-07-02T00:00:00Z",
147 lastUpdatedDate: "2026-07-02T00:00:00Z",
148 commentType: "text",
149 usersLiked: [],
150 },
151 ],
152 }));
153}
154
155function iterationRows(count: number): ReadonlyArray<Record<string, unknown>> {
156 return Array.from({ length: count }, (_, index) => ({
157 id: index + 1,
158 description: `Pushed ${index} commits`,
159 author: identity("Author One"),
160 createdDate: "2026-07-02T00:00:00Z",
161 updatedDate: "2026-07-02T00:00:00Z",
162 sourceRefCommit: { commitId: `${index}`.padStart(40, "a") },
163 targetRefCommit: { commitId: "b".repeat(40) },
164 commonRefCommit: { commitId: "c".repeat(40) },
165 hasMultipleCommits: true,
166 reason: "push",
167 push: { pushId: index + 1, date: "2026-07-02T00:00:00Z", pushedBy: identity("Author One") },
168 }));
169}
170
171afterEach(() => {
172 mockedExecute.mockReset();
173});
174
175layer("AzureDevOpsPullRequestCli.layer", (it) => {
176 it.effect("asks for one row more than the page, to probe for a next page", () =>
177 Effect.gen(function* () {
178 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
179 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
180
181 const batch = yield* cli.listPullRequests({
182 cwd: "/w",
183 repository: "web",
184 state: "open",
185 involvement: "all",
186 viewer: "bilal@acme.dev",
187 limit: 10,
188 });
189
190 assert.strictEqual(batch.items.length, 3);
191 assert.isFalse(batch.truncated);
192 expect(argsOfCall(0)).toEqual([
193 "repos",
194 "pr",
195 "list",
196 "--detect",
197 "true",
198 "--repository",
199 "web",
200 "--status",
201 "active",
202 "--include-links",
203 "--top",
204 "11",
205 "--only-show-errors",
206 "--output",
207 "json",
208 ]);
209 }),
210 );
211
212 it.effect("reads an Azure pull request page larger than the VCS default output limit", () =>
213 Effect.gen(function* () {
214 const rows = pullRequestRows(100, 1).map((row) => ({
215 ...row,
216 description: "x".repeat(10_000),
217 }));
218 const response = JSON.stringify(rows);
219 expect(Buffer.byteLength(response)).toBeGreaterThan(1_000_000);
220
221 mockedExecute.mockImplementationOnce((input) =>
222 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
223 );
224 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
225
226 const batch = yield* cli.listPullRequests({
227 cwd: "/w",
228 repository: "web",
229 state: "merged",
230 involvement: "all",
231 viewer: "bilal@acme.dev",
232 limit: 99,
233 });
234
235 assert.strictEqual(batch.items.length, 99);
236 assert.isTrue(batch.truncated);
237 }),
238 );
239
240 it.effect("reads the page unnarrowed when asked to search, having nothing to search with", () =>
241 Effect.gen(function* () {
242 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
243 const provider = yield* AzureDevOpsPullRequestProvider.make;
244
245 const page = yield* provider.listChangeRequests({
246 cwd: "/w",
247 repository: "web",
248 host: "dev.azure.com",
249 state: "open",
250 involvement: "all",
251 viewer: "bilal@acme.dev",
252 limit: 10,
253 query: "page",
254 });
255
256 assert.strictEqual(page.items.length, 3);
257 expect(argsOfCall(0)).toEqual([
258 "repos",
259 "pr",
260 "list",
261 "--detect",
262 "true",
263 "--repository",
264 "web",
265 "--status",
266 "active",
267 "--include-links",
268 "--top",
269 "11",
270 "--only-show-errors",
271 "--output",
272 "json",
273 ]);
274 }),
275 );
276
277 it.effect("steps over what it has already handed over, which is all Azure can be told", () =>
278 Effect.gen(function* () {
279 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(3, 1))));
280 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
281
282 yield* cli.listPullRequests({
283 cwd: "/w",
284 repository: "web",
285 state: "open",
286 involvement: "all",
287 viewer: "bilal@acme.dev",
288 limit: 10,
289 cursor: { updatedBefore: "2026-07-02T00:00:00Z", delivered: 20 },
290 });
291
292 const args = argsOfCall(0);
293 expect(args).toContain("--skip");
294 assert.strictEqual(args[args.indexOf("--skip") + 1], "20");
295 expect(args).not.toContain("2026-07-02T00:00:00Z");
296 }),
297 );
298
299 it.effect("reports truncation from the extra row", () =>
300 Effect.gen(function* () {
301 mockedExecute.mockReturnValueOnce(Effect.succeed(output(pullRequests(11, 1))));
302 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
303
304 const batch = yield* cli.listPullRequests({
305 cwd: "/w",
306 repository: "web",
307 state: "open",
308 involvement: "all",
309 viewer: "bilal@acme.dev",
310 limit: 10,
311 });
312
313 assert.strictEqual(batch.items.length, 10);
314 assert.isTrue(batch.truncated);
315 assert.strictEqual(batch.cursorAdvance, 10);
316 }),
317 );
318
319 it.effect("advances by malformed raw rows and keeps reading until the page is full", () =>
320 Effect.gen(function* () {
321 mockedExecute
322 .mockReturnValueOnce(
323 Effect.succeed(
324 output(
325 JSON.stringify([
326 { pullRequestId: "malformed" },
327 pullRequestRows(1, 1)[0],
328 { pullRequestId: "also malformed" },
329 ]),
330 ),
331 ),
332 )
333 .mockReturnValueOnce(Effect.succeed(output(pullRequests(2, 2))));
334 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
335
336 const batch = yield* cli.listPullRequests({
337 cwd: "/w",
338 repository: "web",
339 state: "open",
340 involvement: "all",
341 viewer: "bilal@acme.dev",
342 limit: 2,
343 });
344
345 expect(batch.items.map((item) => item.number)).toEqual([1, 2]);
346 assert.isTrue(batch.truncated);
347 assert.strictEqual(batch.cursorAdvance, 4);
348 const secondArgs = argsOfCall(1);
349 assert.strictEqual(secondArgs[secondArgs.indexOf("--skip") + 1], "3");
350 assert.strictEqual(secondArgs[secondArgs.indexOf("--top") + 1], "2");
351 }),
352 );
353
354 it.effect("narrows to the author on the authored tab", () =>
355 Effect.gen(function* () {
356 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
357 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
358
359 yield* cli.listPullRequests({
360 cwd: "/w",
361 repository: "web",
362 state: "closed",
363 involvement: "authored",
364 viewer: "bilal@acme.dev",
365 limit: 10,
366 });
367
368 expect(argsOfCall(0)).toContain("--creator");
369 expect(argsOfCall(0)).toContain("bilal@acme.dev");
370 expect(argsOfCall(0)).toContain("abandoned");
371 }),
372 );
373
374 it.effect("asks Azure for every status on the All tab", () =>
375 Effect.gen(function* () {
376 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
377 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
378
379 yield* cli.listPullRequests({
380 cwd: "/w",
381 repository: "web",
382 state: "all",
383 involvement: "all",
384 viewer: "bilal@acme.dev",
385 limit: 10,
386 });
387
388 expect(argsOfCall(0)).toContain("--status");
389 expect(argsOfCall(0)).toContain("all");
390 }),
391 );
392
393 it.effect("narrows to the reviewer on the reviewing tab", () =>
394 Effect.gen(function* () {
395 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
396 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
397
398 yield* cli.listPullRequests({
399 cwd: "/w",
400 repository: "web",
401 state: "open",
402 involvement: "reviewing",
403 viewer: "bilal@acme.dev",
404 limit: 10,
405 });
406
407 expect(argsOfCall(0)).toContain("--reviewer");
408 }),
409 );
410
411 it.effect("reads the signed-in account, which az reports as a bare value", () =>
412 Effect.gen(function* () {
413 mockedExecute.mockReturnValueOnce(
414 Effect.succeed(output(JSON.stringify({ name: "bilal@acme.dev", type: "user" }))),
415 );
416 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
417
418 const viewer = yield* cli.getViewer({ cwd: "/w" });
419
420 assert.strictEqual(viewer, "bilal@acme.dev");
421 expect(argsOfCall(0)).toEqual([
422 "account",
423 "show",
424 "--query",
425 "user",
426 "--only-show-errors",
427 "--output",
428 "json",
429 ]);
430 }),
431 );
432
433 it.effect("names a token sign-in by the viewer's own pull request", () =>
434 Effect.gen(function* () {
435 const notLoggedIn = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
436 operation: "execute",
437 command: "az",
438 cwd: "/w",
439 argumentCount: 7,
440 cause: new Error("Please run 'az login' to setup account."),
441 });
442 mockedExecute
443 .mockReturnValueOnce(Effect.fail(notLoggedIn))
444 .mockReturnValueOnce(
445 Effect.succeed(
446 output(
447 JSON.stringify([{ ...pullRequestRow, createdBy: { uniqueName: "bilal@acme.dev" } }]),
448 ),
449 ),
450 )
451 .mockReturnValueOnce(Effect.succeed(output("")))
452 .mockReturnValueOnce(Effect.succeed(output("[]")));
453 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
454
455 assert.strictEqual(yield* cli.getViewer({ cwd: "/w" }), "bilal@acme.dev");
456 expect(argsOfCall(1)).toEqual(expect.arrayContaining(["--creator", "me", "--top", "1"]));
457 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
458 assert.strictEqual(error._tag, "AzureDevOpsViewerUnavailableError");
459 }),
460 );
461
462 it.effect("fails when no sign-in can read pull requests", () =>
463 Effect.gen(function* () {
464 const signedOut = new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
465 operation: "execute",
466 command: "az",
467 cwd: "/w",
468 argumentCount: 7,
469 cause: new Error("signed out"),
470 });
471 mockedExecute.mockReturnValue(Effect.fail(signedOut));
472 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
473
474 const error = yield* Effect.flip(cli.getViewer({ cwd: "/w" }));
475
476 assert.strictEqual(error._tag, "AzureDevOpsCliAuthenticationError");
477 }),
478 );
479
480 it.effect("completes a pull request to merge it, squashing only when asked", () =>
481 Effect.gen(function* () {
482 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
483 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
484
485 yield* cli.runPullRequestAction({
486 cwd: "/w",
487 number: 42,
488 action: "merge",
489 mergeMethod: "squash",
490 });
491
492 expect(argsOfCall(0)).toEqual([
493 "repos",
494 "pr",
495 "update",
496 "--detect",
497 "true",
498 "--id",
499 "42",
500 "--status",
501 "completed",
502 "--squash",
503 "true",
504 "--only-show-errors",
505 "--output",
506 "json",
507 ]);
508 }),
509 );
510
511 it.effect("stores the squash choice with an auto-completion, as a merge now does", () =>
512 Effect.gen(function* () {
513 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
514 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
515
516 yield* cli.runPullRequestAction({
517 cwd: "/w",
518 number: 42,
519 action: "enable-auto-merge",
520 mergeMethod: "squash",
521 });
522
523 expect(argsOfCall(0)).toEqual([
524 "repos",
525 "pr",
526 "update",
527 "--detect",
528 "true",
529 "--id",
530 "42",
531 "--auto-complete",
532 "true",
533 "--squash",
534 "true",
535 "--only-show-errors",
536 "--output",
537 "json",
538 ]);
539 }),
540 );
541
542 it.effect.each([
543 { action: "enable-auto-merge", expected: ["--auto-complete", "true"] },
544 { action: "disable-auto-merge", expected: ["--auto-complete", "false"] },
545 { action: "draft", expected: ["--draft", "true"] },
546 { action: "ready", expected: ["--draft", "false"] },
547 { action: "close", expected: ["--status", "abandoned"] },
548 { action: "reopen", expected: ["--status", "active"] },
549 ] as const)("moves a pull request with $action", ({ action, expected }) =>
550 Effect.gen(function* () {
551 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
552 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
553
554 yield* cli.runPullRequestAction({ cwd: "/w", number: 42, action });
555
556 expect(argsOfCall(0)).toEqual([
557 "repos",
558 "pr",
559 "update",
560 "--detect",
561 "true",
562 "--id",
563 "42",
564 ...expected,
565 "--only-show-errors",
566 "--output",
567 "json",
568 ]);
569 }),
570 );
571
572 it.effect.each([
573 { name: "a title", rewrite: { title: "Add the page" }, expected: ["--title=Add the page"] },
574 {
575 name: "a description",
576 rewrite: { body: "Why the page changed" },
577 expected: ["--description=Why the page changed"],
578 },
579 {
580 name: "both",
581 rewrite: { title: "Add the page", body: "Why the page changed" },
582 expected: ["--title=Add the page", "--description=Why the page changed"],
583 },
584 ] as const)("rewrites $name, sending nothing it was not given", ({ rewrite, expected }) =>
585 Effect.gen(function* () {
586 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
587 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
588
589 yield* cli.updatePullRequest({ cwd: "/w", number: 42, ...rewrite });
590
591 expect(argsOfCall(0)).toEqual([
592 "repos",
593 "pr",
594 "update",
595 "--detect",
596 "true",
597 "--id",
598 "42",
599 ...expected,
600 "--only-show-errors",
601 "--output",
602 "json",
603 ]);
604 }),
605 );
606
607 it.effect("sends a description that starts with a dash as one value, not as a flag", () =>
608 Effect.gen(function* () {
609 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
610 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
611
612 yield* cli.updatePullRequest({
613 cwd: "/w",
614 number: 42,
615 body: "- rewrote the page\n- kept the rest",
616 });
617
618 expect(argsOfCall(0)).toContain("--description=- rewrote the page\n- kept the rest");
619 }),
620 );
621
622 it.effect("rewrites through the provider, which says it takes one", () =>
623 Effect.gen(function* () {
624 mockedExecute.mockReturnValue(Effect.succeed(output("{}")));
625 const provider = yield* AzureDevOpsPullRequestProvider.make;
626
627 expect(provider.capabilities.edit).toEqual({ changeRequest: true, comment: false });
628 assert.isDefined(provider.updateChangeRequest);
629 yield* provider.updateChangeRequest({
630 cwd: "/w",
631 repository: "web",
632 host: "dev.azure.com",
633 number: 42,
634 title: "Add the page",
635 });
636
637 expect(argsOfCall(0)).toContain("--title=Add the page");
638 expect(argsOfCall(0)).not.toContain("--description");
639 }),
640 );
641
642 it.effect("names the head's blob as what a cleared file was cleared at", () =>
643 Effect.gen(function* () {
644 mockedExecute
645 .mockReturnValueOnce(
646 Effect.succeed(
647 output(
648 JSON.stringify({
649 pullRequestId: 42,
650 title: "Add the page",
651 status: "active",
652 sourceRefName: "refs/heads/feat/page",
653 targetRefName: "refs/heads/main",
654 creationDate: "2026-07-01T00:00:00Z",
655 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
656 repository: { name: "web", project: { name: "platform" } },
657 }),
658 ),
659 ),
660 )
661 .mockReturnValueOnce(
662 Effect.succeed(
663 output(
664 JSON.stringify({
665 value: [
666 {
667 id: 1,
668 sourceRefCommit: { commitId: "a".repeat(40) },
669 commonRefCommit: { commitId: "b".repeat(40) },
670 },
671 {
672 id: 2,
673 sourceRefCommit: { commitId: "c".repeat(40) },
674 commonRefCommit: { commitId: "b".repeat(40) },
675 },
676 ],
677 }),
678 ),
679 ),
680 )
681 .mockReturnValueOnce(
682 Effect.succeed(
683 output(
684 JSON.stringify({
685 changeEntries: [
686 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
687 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
688 ],
689 }),
690 ),
691 ),
692 );
693 const provider = yield* AzureDevOpsPullRequestProvider.make;
694
695 assert.strictEqual(provider.capabilities.viewedFiles, "environment");
696 assert.isDefined(provider.getFileRevisions);
697 const answer = yield* provider.getFileRevisions({
698 cwd: "/w",
699 repository: "web",
700 host: "dev.azure.com",
701 number: 42,
702 paths: ["README.md"],
703 });
704
705 expect(argsOfCall(2)).toContain("iterationId=2");
706 expect([...answer.revisions]).toEqual([["README.md", "8f80"]]);
707 }),
708 );
709
710 it.effect("reads where a pull request lives once, however often it is asked about", () =>
711 Effect.gen(function* () {
712 const pullRequest = Effect.succeed(
713 output(
714 JSON.stringify({
715 pullRequestId: 42,
716 title: "Add the page",
717 status: "active",
718 sourceRefName: "refs/heads/feat/page",
719 targetRefName: "refs/heads/main",
720 creationDate: "2026-07-01T00:00:00Z",
721 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
722 repository: { name: "web", project: { name: "platform" } },
723 }),
724 ),
725 );
726 const iterations = () =>
727 Effect.succeed(
728 output(
729 JSON.stringify({
730 value: [
731 {
732 id: 1,
733 sourceRefCommit: { commitId: "a".repeat(40) },
734 commonRefCommit: { commitId: "b".repeat(40) },
735 },
736 ],
737 }),
738 ),
739 );
740 const changes = () =>
741 Effect.succeed(
742 output(
743 JSON.stringify({
744 changeEntries: [
745 { changeType: "edit", item: { path: "/README.md", objectId: "8f80" } },
746 ],
747 }),
748 ),
749 );
750 mockedExecute
751 .mockReturnValueOnce(pullRequest)
752 .mockReturnValueOnce(iterations())
753 .mockReturnValueOnce(changes())
754 .mockReturnValueOnce(iterations())
755 .mockReturnValueOnce(changes());
756 const provider = yield* AzureDevOpsPullRequestProvider.make;
757 const read = provider.getFileRevisions;
758 assert.isDefined(read);
759 const ask = () =>
760 read({
761 cwd: "/w",
762 repository: "web",
763 host: "dev.azure.com",
764 number: 42,
765 paths: ["README.md"],
766 });
767
768 yield* ask();
769 const again = yield* ask();
770
771 assert.strictEqual(mockedExecute.mock.calls.length, 5);
772 expect(argsOfCall(3)).toContain("pullRequestIterations");
773 expect([...again.revisions]).toEqual([["README.md", "8f80"]]);
774 }),
775 );
776
777 it.effect(
778 "answers for a marked file the pull request no longer changes as the empty version",
779 () =>
780 Effect.gen(function* () {
781 mockedExecute
782 .mockReturnValueOnce(
783 Effect.succeed(
784 output(
785 json({
786 pullRequestId: 42,
787 title: "Add the page",
788 status: "active",
789 sourceRefName: "refs/heads/feat/page",
790 targetRefName: "refs/heads/main",
791 creationDate: "2026-07-01T00:00:00Z",
792 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
793 repository: { name: "web", project: { name: "platform" } },
794 }),
795 ),
796 ),
797 )
798 .mockReturnValueOnce(
799 Effect.succeed(
800 output(
801 json({
802 value: [
803 {
804 id: 1,
805 sourceRefCommit: { commitId: "a".repeat(40) },
806 commonRefCommit: { commitId: "b".repeat(40) },
807 },
808 ],
809 }),
810 ),
811 ),
812 )
813 .mockReturnValueOnce(Effect.succeed(output('{"changeEntries":[]}')));
814 const provider = yield* AzureDevOpsPullRequestProvider.make;
815 assert.isDefined(provider.getFileRevisions);
816
817 const answer = yield* provider.getFileRevisions({
818 cwd: "/w",
819 repository: "web",
820 host: "dev.azure.com",
821 number: 42,
822 paths: ["GONE.md"],
823 });
824
825 expect([...answer.revisions]).toEqual([["GONE.md", ""]]);
826 }),
827 );
828
829 it.effect("says nothing about the files past the end of a change it gave up following", () =>
830 Effect.gen(function* () {
831 const entries = (from: number, count: number) =>
832 Array.from({ length: count }, (_, index) => ({
833 changeType: "edit",
834 item: { path: `/src/f${from + index}.ts`, objectId: `blob-${from + index}` },
835 }));
836 mockedExecute
837 .mockReturnValueOnce(
838 Effect.succeed(
839 output(
840 json({
841 pullRequestId: 42,
842 title: "Add the page",
843 status: "active",
844 sourceRefName: "refs/heads/feat/page",
845 targetRefName: "refs/heads/main",
846 creationDate: "2026-07-01T00:00:00Z",
847 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
848 repository: { name: "web", project: { name: "platform" } },
849 }),
850 ),
851 ),
852 )
853 .mockReturnValueOnce(
854 Effect.succeed(
855 output(
856 json({
857 value: [
858 {
859 id: 1,
860 sourceRefCommit: { commitId: "a".repeat(40) },
861 commonRefCommit: { commitId: "b".repeat(40) },
862 },
863 ],
864 }),
865 ),
866 ),
867 )
868 .mockReturnValueOnce(
869 Effect.succeed(output(json({ changeEntries: entries(0, 5_000), nextSkip: 5_000 }))),
870 )
871 .mockReturnValueOnce(
872 Effect.succeed(output(json({ changeEntries: entries(5_000, 5_000), nextSkip: 10_000 }))),
873 );
874 const provider = yield* AzureDevOpsPullRequestProvider.make;
875 assert.isDefined(provider.getFileRevisions);
876
877 const answer = yield* provider.getFileRevisions({
878 cwd: "/w",
879 repository: "web",
880 host: "dev.azure.com",
881 number: 42,
882 paths: ["src/f1.ts", "src/f5001.ts", "src/past-the-cut.ts"],
883 });
884
885 expect(argsOfCall(3)).toContain("$skip=5000");
886 expect([...answer.revisions]).toEqual([
887 ["src/f1.ts", "blob-1"],
888 ["src/f5001.ts", "blob-5001"],
889 ]);
890 }),
891 );
892
893 it.effect("stops following pages by what Azure counts, not by what survives decoding", () =>
894 Effect.gen(function* () {
895 mockedExecute
896 .mockReturnValueOnce(
897 Effect.succeed(
898 output(
899 json({
900 pullRequestId: 42,
901 title: "Add the page",
902 status: "active",
903 sourceRefName: "refs/heads/feat/page",
904 targetRefName: "refs/heads/main",
905 creationDate: "2026-07-01T00:00:00Z",
906 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
907 repository: { name: "web", project: { name: "platform" } },
908 }),
909 ),
910 ),
911 )
912 .mockReturnValueOnce(
913 Effect.succeed(
914 output(
915 json({
916 value: [
917 {
918 id: 1,
919 sourceRefCommit: { commitId: "a".repeat(40) },
920 commonRefCommit: { commitId: "b".repeat(40) },
921 },
922 ],
923 }),
924 ),
925 ),
926 )
927 .mockImplementation((command) => {
928 const skip = command.args.find((arg) => arg.startsWith("$skip="));
929 const from = Number(skip?.slice("$skip=".length) ?? 0);
930 return Effect.succeed(
931 output(
932 json({
933 changeEntries: [{ changeType: "add", item: { path: "/src", isFolder: true } }],
934 nextSkip: from + 2_000,
935 }),
936 ),
937 );
938 });
939 const provider = yield* AzureDevOpsPullRequestProvider.make;
940 assert.isDefined(provider.getFileRevisions);
941
942 const answer = yield* provider.getFileRevisions({
943 cwd: "/w",
944 repository: "web",
945 host: "dev.azure.com",
946 number: 42,
947 paths: ["src/page.ts"],
948 });
949
950 assert.strictEqual(mockedExecute.mock.calls.length, 7);
951 assert.strictEqual(answer.revisions.size, 0);
952 }),
953 );
954
955 it.effect("leaves one file the host would not hand over listed without its hunks", () =>
956 Effect.gen(function* () {
957 mockedExecute
958 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
959 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
960 .mockReturnValueOnce(
961 Effect.succeed(
962 output(
963 json({
964 changeEntries: [
965 { changeType: "add", item: { path: "/huge.bin", objectId: "8f80" } },
966 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
967 ],
968 }),
969 ),
970 ),
971 )
972 .mockReturnValueOnce(
973 Effect.fail(
974 new AzureDevOpsCli.AzureDevOpsCommandFailedError({
975 operation: "execute",
976 command: "az",
977 cwd: "/w",
978 argumentCount: 1,
979 cause: "the blob is past what the route will carry",
980 }),
981 ),
982 )
983 .mockReturnValueOnce(Effect.succeed(output(json({ content: "hello\n" }))));
984 const provider = yield* AzureDevOpsPullRequestProvider.make;
985
986 const slice = yield* provider.getDiff({
987 cwd: "/w",
988 repository: "web",
989 host: "dev.azure.com",
990 number: 42,
991 });
992
993 assert.isTrue(slice.truncated);
994 expect(slice.patch).toContain("diff --git a/huge.bin b/huge.bin");
995 expect(slice.patch).toContain("+hello");
996 }),
997 );
998
999 it.effect("fails the whole read when it is the connection that would not answer", () =>
1000 Effect.gen(function* () {
1001 mockedExecute
1002 .mockReturnValueOnce(Effect.succeed(output(json(pullRequestRow))))
1003 .mockReturnValueOnce(Effect.succeed(output(json(oneIteration))))
1004 .mockReturnValueOnce(
1005 Effect.succeed(
1006 output(
1007 json({
1008 changeEntries: [
1009 { changeType: "add", item: { path: "/DEMO.md", objectId: "0ca4" } },
1010 ],
1011 }),
1012 ),
1013 ),
1014 )
1015 .mockReturnValueOnce(
1016 Effect.fail(
1017 new AzureDevOpsCli.AzureDevOpsCliRateLimitError({
1018 operation: "execute",
1019 command: "az",
1020 cwd: "/w",
1021 argumentCount: 1,
1022 cause: "429",
1023 }),
1024 ),
1025 );
1026 const provider = yield* AzureDevOpsPullRequestProvider.make;
1027
1028 const error = yield* Effect.flip(
1029 provider.getDiff({ cwd: "/w", repository: "web", host: "dev.azure.com", number: 42 }),
1030 );
1031
1032 assert.strictEqual(error.reason, "rate-limited");
1033 }),
1034 );
1035
1036 it.effect("takes Azure's own word on a file it will not spell out", () =>
1037 Effect.gen(function* () {
1038 mockedExecute
1039 .mockReturnValueOnce(
1040 Effect.succeed(
1041 output(
1042 json({
1043 pullRequestId: 42,
1044 title: "Add the page",
1045 status: "active",
1046 sourceRefName: "refs/heads/feat/page",
1047 targetRefName: "refs/heads/main",
1048 creationDate: "2026-07-01T00:00:00Z",
1049 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
1050 repository: { name: "web", project: { name: "platform" } },
1051 }),
1052 ),
1053 ),
1054 )
1055 .mockReturnValueOnce(
1056 Effect.succeed(
1057 output(
1058 json({
1059 value: [
1060 {
1061 id: 1,
1062 sourceRefCommit: { commitId: "a".repeat(40) },
1063 commonRefCommit: { commitId: "b".repeat(40) },
1064 },
1065 ],
1066 }),
1067 ),
1068 ),
1069 )
1070 .mockReturnValueOnce(
1071 Effect.succeed(
1072 output(
1073 json({
1074 changeEntries: [
1075 { changeType: "add", item: { path: "/logo.png", objectId: "8f80" } },
1076 ],
1077 }),
1078 ),
1079 ),
1080 )
1081 .mockReturnValueOnce(
1082 Effect.succeed(
1083 output(json({ content: "iVBORw0KGgo=", contentMetadata: { isBinary: true } })),
1084 ),
1085 );
1086 const provider = yield* AzureDevOpsPullRequestProvider.make;
1087
1088 const slice = yield* provider.getDiff({
1089 cwd: "/w",
1090 repository: "web",
1091 host: "dev.azure.com",
1092 number: 42,
1093 });
1094
1095 expect(argsOfCall(3)).toContain("includeContentMetadata=true");
1096 expect(slice.patch).toContain("Binary files a/logo.png and b/logo.png differ");
1097 assert.isTrue(slice.truncated);
1098 }),
1099 );
1100
1101 it.effect("stops following pages when one of them does not move the cursor on", () =>
1102 Effect.gen(function* () {
1103 mockedExecute
1104 .mockReturnValueOnce(
1105 Effect.succeed(
1106 output(
1107 json({
1108 pullRequestId: 42,
1109 title: "Add the page",
1110 status: "active",
1111 sourceRefName: "refs/heads/feat/page",
1112 targetRefName: "refs/heads/main",
1113 creationDate: "2026-07-01T00:00:00Z",
1114 url: "https://dev.azure.com/acme/_apis/git/repositories/web/pullRequests/42",
1115 repository: { name: "web", project: { name: "platform" } },
1116 }),
1117 ),
1118 ),
1119 )
1120 .mockReturnValueOnce(
1121 Effect.succeed(
1122 output(
1123 json({
1124 value: [
1125 {
1126 id: 1,
1127 sourceRefCommit: { commitId: "a".repeat(40) },
1128 commonRefCommit: { commitId: "b".repeat(40) },
1129 },
1130 ],
1131 }),
1132 ),
1133 ),
1134 )
1135 .mockReturnValueOnce(
1136 Effect.succeed(
1137 output(
1138 json({
1139 changeEntries: [{ changeType: "edit", item: { path: "/a.ts", objectId: "8f80" } }],
1140 nextSkip: 2_000,
1141 }),
1142 ),
1143 ),
1144 )
1145 .mockReturnValueOnce(
1146 Effect.succeed(
1147 output(
1148 json({
1149 changeEntries: [{ changeType: "edit", item: { path: "/b.ts", objectId: "0ca4" } }],
1150 nextSkip: 2_000,
1151 }),
1152 ),
1153 ),
1154 );
1155 const provider = yield* AzureDevOpsPullRequestProvider.make;
1156 assert.isDefined(provider.getFileRevisions);
1157
1158 const answer = yield* provider.getFileRevisions({
1159 cwd: "/w",
1160 repository: "web",
1161 host: "dev.azure.com",
1162 number: 42,
1163 paths: ["a.ts", "b.ts", "unlisted.ts"],
1164 });
1165
1166 assert.strictEqual(mockedExecute.mock.calls.length, 4);
1167 expect([...answer.revisions]).toEqual([
1168 ["a.ts", "8f80"],
1169 ["b.ts", "0ca4"],
1170 ]);
1171 }),
1172 );
1173
1174 it.effect("asks Azure nothing when no file has been ticked off", () =>
1175 Effect.gen(function* () {
1176 mockedExecute.mockReturnValue(Effect.succeed(output('{"changeEntries":[]}')));
1177 const provider = yield* AzureDevOpsPullRequestProvider.make;
1178 assert.isDefined(provider.getFileRevisions);
1179
1180 const answer = yield* provider.getFileRevisions({
1181 cwd: "/w",
1182 repository: "web",
1183 host: "dev.azure.com",
1184 number: 42,
1185 paths: [],
1186 });
1187
1188 expect(answer.revisions.size).toBe(0);
1189 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1190 }),
1191 );
1192
1193 it.effect("reads the conversation through the REST API, pinned to a version", () =>
1194 Effect.gen(function* () {
1195 mockedExecute.mockReturnValueOnce(
1196 Effect.succeed(
1197 output(
1198 JSON.stringify({
1199 value: [
1200 {
1201 id: 1,
1202 comments: [
1203 { id: 1, content: "Looks good.", publishedDate: "2026-07-02T00:00:00Z" },
1204 ],
1205 },
1206 ],
1207 }),
1208 ),
1209 ),
1210 );
1211 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1212
1213 const comments = yield* cli.listThreads({
1214 cwd: "/w",
1215 location: { project: "platform", repository: "web" },
1216 number: 42,
1217 });
1218
1219 assert.strictEqual(comments.length, 1);
1220 expect(argsOfCall(0)).toContain("invoke");
1221 expect(argsOfCall(0)).toContain("pullRequestThreads");
1222 expect(argsOfCall(0)).toContain("project=platform");
1223 expect(argsOfCall(0)).toContain("repositoryId=web");
1224 expect(argsOfCall(0)).toContain("pullRequestId=42");
1225 expect(maxOutputBytesOfCall(0)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1226 }),
1227 );
1228
1229 it.effect("reads a long review's threads, which are past the default output limit", () =>
1230 Effect.gen(function* () {
1231 const response = json({ value: threadRows(800) });
1232 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1233 mockedExecute.mockImplementationOnce((input) =>
1234 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
1235 );
1236 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1237
1238 const comments = yield* cli.listThreads({
1239 cwd: "/w",
1240 location: { project: "platform", repository: "web" },
1241 number: 42,
1242 });
1243
1244 assert.strictEqual(comments.length, 800);
1245 }),
1246 );
1247
1248 it.effect("reads a long review's iterations, which are past the default output limit", () =>
1249 Effect.gen(function* () {
1250 const response = json({ value: iterationRows(1_200) });
1251 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1252 mockedExecute.mockImplementationOnce((input) =>
1253 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
1254 );
1255 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1256
1257 const iterations = yield* cli.listIterations({
1258 cwd: "/w",
1259 location: { project: "platform", repository: "web" },
1260 number: 42,
1261 });
1262
1263 assert.strictEqual(iterations.length, 1_200);
1264 assert.strictEqual(iterations.at(-1)?.id, 1_200);
1265 }),
1266 );
1267
1268 it.effect("reads a full page of change entries, which is past the default output limit", () =>
1269 Effect.gen(function* () {
1270 const response = json({ changeEntries: changeEntries(2_000) });
1271 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1272 mockedExecute.mockImplementationOnce((input) =>
1273 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
1274 );
1275 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1276
1277 const page = yield* cli.listIterationChanges({
1278 cwd: "/w",
1279 location: { project: "platform", repository: "web" },
1280 number: 42,
1281 iterationId: 1,
1282 });
1283
1284 assert.strictEqual(page.changes.length, 2_000);
1285 assert.isFalse(page.truncated);
1286 }),
1287 );
1288
1289 it.effect("reads a file whose JSON envelope is past the default output limit", () =>
1290 Effect.gen(function* () {
1291 const file = "const value = 1;\n".repeat(57_000);
1292 const response = json({ content: file });
1293 expect(Buffer.byteLength(file)).toBeLessThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1294 expect(Buffer.byteLength(response)).toBeGreaterThan(VCS_DEFAULT_MAX_OUTPUT_BYTES);
1295 mockedExecute.mockImplementationOnce((input) =>
1296 Effect.succeed(outputWithin(input.maxOutputBytes, response)),
1297 );
1298 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1299
1300 const item = yield* cli.readItemContent({
1301 cwd: "/w",
1302 location: { project: "platform", repository: "web" },
1303 path: "src/generated/schema.ts",
1304 commit: "a".repeat(40),
1305 });
1306
1307 assert.strictEqual(item.contents, file);
1308 assert.isFalse(item.isBinary);
1309 }),
1310 );
1311
1312 it.effect("asks for a file by Azure's own spelling of its path", () =>
1313 Effect.gen(function* () {
1314 mockedExecute.mockReturnValueOnce(Effect.succeed(output(json({ content: "const a = 1;" }))));
1315 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1316
1317 yield* cli.readItemContent({
1318 cwd: "/w",
1319 location: { project: "platform", repository: "web" },
1320 path: "src/app.ts",
1321 commit: "a".repeat(40),
1322 });
1323
1324 expect(argsOfCall(0)).toContain("path=/src/app.ts");
1325 }),
1326 );
1327
1328 it.effect("reports a pull request it cannot place as its own outcome", () =>
1329 Effect.gen(function* () {
1330 mockedExecute.mockReturnValueOnce(
1331 Effect.succeed(
1332 output(
1333 JSON.stringify({
1334 pullRequestId: 42,
1335 title: "Add the page",
1336 sourceRefName: "refs/heads/feat/page",
1337 targetRefName: "refs/heads/main",
1338 creationDate: "2026-07-01T00:00:00Z",
1339 }),
1340 ),
1341 ),
1342 );
1343 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1344
1345 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1346
1347 assert.strictEqual(error._tag, "AzureDevOpsPullRequestIncompleteError");
1348 }),
1349 );
1350
1351 it.effect("fails the read when az returns something unreadable", () =>
1352 Effect.gen(function* () {
1353 mockedExecute.mockReturnValueOnce(Effect.succeed(output('{"message":"not found"}')));
1354 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1355
1356 const error = yield* Effect.flip(cli.getPullRequest({ cwd: "/w", number: 42 }));
1357
1358 assert.strictEqual(error._tag, "AzureDevOpsPullRequestReadError");
1359 }),
1360 );
1361
1362 it.effect("adds reviewers with the one command Azure has for it", () =>
1363 Effect.gen(function* () {
1364 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
1365 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1366
1367 yield* cli.setPullRequestReviewers({
1368 cwd: "/w",
1369 number: 42,
1370 reviewers: ["octocat@acme.test", "hubot@acme.test"],
1371 requested: true,
1372 });
1373
1374 expect(argsOfCall(0)).toEqual([
1375 "repos",
1376 "pr",
1377 "reviewer",
1378 "add",
1379 "--detect",
1380 "true",
1381 "--id",
1382 "42",
1383 "--reviewers",
1384 "octocat@acme.test",
1385 "hubot@acme.test",
1386 "--only-show-errors",
1387 "--output",
1388 "json",
1389 ]);
1390 }),
1391 );
1392
1393 it.effect("takes a reviewer off the pull request with the same command's counterpart", () =>
1394 Effect.gen(function* () {
1395 mockedExecute.mockReturnValueOnce(Effect.succeed(output("[]")));
1396 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1397
1398 yield* cli.setPullRequestReviewers({
1399 cwd: "/w",
1400 number: 42,
1401 reviewers: ["octocat@acme.test"],
1402 requested: false,
1403 });
1404
1405 expect(argsOfCall(0)).toContain("remove");
1406 }),
1407 );
1408
1409 it.effect("refuses a reviewer az would read as a flag, before running anything", () =>
1410 Effect.gen(function* () {
1411 const cli = yield* AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli;
1412
1413 const error = yield* Effect.flip(
1414 cli.setPullRequestReviewers({
1415 cwd: "/w",
1416 number: 42,
1417 reviewers: ["--query"],
1418 requested: true,
1419 }),
1420 );
1421
1422 assert.strictEqual(error._tag, "AzureDevOpsReviewerNameError");
1423 assert.strictEqual(mockedExecute.mock.calls.length, 0);
1424 }),
1425 );
1426});