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

pullRequestList.logic.test.ts

890 lines30.2 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import type {
3 EnvironmentId,
4 ProjectId,
5 PullRequestAction,
6 PullRequestListEntry,
7} from "@t3tools/contracts";
8import { describe, expect, it } from "vite-plus/test";
9​
10import {
11 pullRequestHostActions,
12 largestPullRequestReadCount,
13 pullRequestQuickActions,
14 filterPullRequestsByInvolvement,
15 findProjectForRepository,
16 findScopedProject,
17 mergePullRequestLists,
18 pullRequestEntryKey,
19 groupPullRequestsByInvolvement,
20 pullRequestStatsBatches,
21 pullRequestStatsKeysToRequest,
22 pullRequestStatsRefreshBatches,
23 mergePullRequestDiffStats,
24 partitionPullRequestsWithPriority,
25 readPullRequestListSnapshot,
26 writePullRequestListSnapshot,
27 pullRequestAuthorChoices,
28 selectedPullRequestAuthor,
29 pullRequestLabelChoices,
30 rankPullRequestMatches,
31 rankPullRequestsBlockedOnAuthor,
32 rankPullRequestsByMergeReadiness,
33 sortPullRequestGroups,
34 resolveQueryEnvironmentIds,
35 resolveSelectedEnvironmentId,
36 type EnvironmentPullRequestEntry,
37 applyPullRequestOverrides,
38 reusePullRequestEntries,
39 settlePullRequestOverrides,
40} from "./pullRequestList.logic";
41import {
42 readPullRequestListPreferences,
43 writePullRequestListPreferences,
44} from "./pullRequestListPreferences";
45​
46const VIEWERS = { "github.com": "Bilal" } as const;
47​
48function entry(
49 overrides: Partial<EnvironmentPullRequestEntry> & Pick<PullRequestListEntry, "number">,
50) {
51 return {
52 environmentId: "env-1",
53 provider: SourceControlProviderKind.make("github"),
54 host: "github.com",
55 projectId: "project-1",
56 projectTitle: "t3code",
57 repository: "pingdotgg/t3code",
58 title: "Add the pull requests page",
59 url: `https://github.com/pingdotgg/t3code/pull/${overrides.number}`,
60 author: { login: "octocat", name: null, avatarUrl: null },
61 headBranch: `feat/branch-${overrides.number}`,
62 baseBranch: "main",
63 state: "open",
64 isDraft: false,
65 mergeability: "mergeable",
66 additions: 1,
67 deletions: 0,
68 createdAt: "2026-07-01T00:00:00Z",
69 updatedAt: "2026-07-02T00:00:00Z",
70 viewerReviewRequested: false,
71 labels: [],
72 ...overrides,
73 } as EnvironmentPullRequestEntry;
75​
76describe("visible pull request line-count targets", () => {
77 it("does not request a row again after its received batch is pruned", () => {
78 const entries = [
79 entry({ additions: 0, deletions: 0, number: 1 }),
80 entry({ additions: 0, deletions: 0, number: 2 }),
81 ];
82 const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
83 const firstKey = pullRequestEntryKey(entries[0]!);
84 const secondKey = pullRequestEntryKey(entries[1]!);
85 const completedStats = mergePullRequestDiffStats(new Map(), [
86 {
87 environmentId: ENV_1,
88 projectId: "project-1",
89 number: 1,
90 additions: 1,
91 deletions: 1,
92 },
93 ]);
94​
95 const keys = pullRequestStatsKeysToRequest(
96 entriesByKey,
97 new Set([firstKey, secondKey]),
98 [],
99 completedStats,
100 );
101 expect([...keys]).toEqual([secondKey]);
102 expect(pullRequestStatsBatches(entriesByKey, keys)[0]?.input.refs).toEqual([
103 { projectId: "project-1", repository: "pingdotgg/t3code", number: 2 },
104 ]);
105 });
106​
107 it("keeps every per-environment batch within the stats contract limit", () => {
108 const entries = Array.from({ length: 501 }, (_, index) =>
109 entry({ additions: 0, deletions: 0, number: index + 1 }),
110 );
111 const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
112 const batches = pullRequestStatsBatches(
113 entriesByKey,
114 new Set(entries.map(pullRequestEntryKey)),
115 );
116​
117 expect(batches.map((batch) => batch.input.refs.length)).toEqual([500, 1]);
118 expect(batches.flatMap((batch) => [...batch.keys])).toEqual(entries.map(pullRequestEntryKey));
119 });
120​
121 it("ignores a late refresh after the filter or stats policy changes", () => {
122 const entries = [
123 entry({ additions: 0, deletions: 0, number: 1 }),
124 entry({ additions: 0, deletions: 0, number: 2 }),
125 ];
126 const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
127 const visibleKeys = new Set([pullRequestEntryKey(entries[1]!)]);
128 const requestedScope = { key: "open", policy: "visible" } as const;
129 const refresh = (currentScope: { key: string; policy: "visible" | "eager" }) =>
130 pullRequestStatsRefreshBatches({
131 requestedScope,
132 currentScope,
133 entriesByKey,
134 candidateKeys: visibleKeys,
135 statsByRow: new Map(),
136 });
137​
138 expect(refresh(requestedScope)?.[0]?.input.refs.map((ref) => ref.number)).toEqual([2]);
139 expect(refresh({ key: "closed", policy: "visible" })).toBeNull();
140 expect(refresh({ key: "open", policy: "eager" })).toBeNull();
141 });
142});
143​
144describe("pull request involvement filtering", () => {
145 it("does not treat a matching login on another host as the viewer", () => {
146 const mixed = [
147 entry({ number: 1, author: { login: "Bilal", name: null, avatarUrl: null } }),
148 entry({
149 number: 2,
150 provider: SourceControlProviderKind.make("gitlab"),
151 host: "gitlab.com",
152 author: { login: "Bilal", name: null, avatarUrl: null },
153 }),
154 ];
155 expect(
156 filterPullRequestsByInvolvement(mixed, VIEWERS, "authored").map((item) => item.number),
157 ).toEqual([1]);
158 });
159});
160​
161describe("ranking what a search found", () => {
162 const row = (overrides: Partial<PullRequestListEntry> & { number?: number }) =>
163 entry({ number: 1, ...overrides });
164​
165 it("puts the pull request whose title says it above one that merely mentions it", () => {
166 const titled = row({
167 number: 1,
168 title: "Add the welcome wizard",
169 updatedAt: "2026-07-01T00:00:00Z",
170 });
171 const mentioned = row({
172 number: 2,
173 title: "Unrelated work",
174 updatedAt: "2026-08-01T00:00:00Z",
175 });
176 expect(
177 rankPullRequestMatches([mentioned, titled], "welcome wizard").map((entry) => entry.number),
178 ).toEqual([1, 2]);
179 });
180});
181​
182describe("default merge-readiness ranking", () => {
183 it("puts ready work first, finished work after open work, and every conflict last", () => {
184 const conflict = entry({
185 number: 1,
186 mergeability: "conflicting",
187 checksState: "passing",
188 reviewDecision: "approved",
189 updatedAt: "2026-09-01T00:00:00Z",
190 });
191 const other = entry({
192 number: 2,
193 checksState: "pending",
194 updatedAt: "2026-08-01T00:00:00Z",
195 });
196 const green = entry({
197 number: 3,
198 checksState: "passing",
199 reviewDecision: "review-required",
200 updatedAt: "2026-07-01T00:00:00Z",
201 });
202 const approved = entry({
203 number: 4,
204 checksState: "passing",
205 reviewDecision: "approved",
206 additions: 1_000,
207 updatedAt: "2026-06-01T00:00:00Z",
208 });
209 const draft = entry({
210 number: 5,
211 isDraft: true,
212 checksState: "passing",
213 reviewDecision: "approved",
214 updatedAt: "2026-09-02T00:00:00Z",
215 });
216 const finished = entry({
217 number: 6,
218 state: "merged",
219 checksState: "passing",
220 reviewDecision: "approved",
221 updatedAt: "2026-09-03T00:00:00Z",
222 });
223​
224 expect(
225 rankPullRequestsByMergeReadiness([conflict, other, green, approved, draft, finished]).map(
226 (row) => row.number,
227 ),
228 ).toEqual([4, 3, 5, 2, 6, 1]);
229 });
230​
231 it("distinguishes measured empty diffs from missing counts when sorting groups", () => {
232 const unknown = entry({ number: 1, additions: 0, deletions: 0 });
233 const measured = entry({ number: 2 });
234 const empty = entry({ number: 3, additions: 0, deletions: 0 });
235 const groups = [
236 { key: "others", label: "Others", entries: [unknown, measured, empty] },
237 ] as const;
238​
239 const sorted = sortPullRequestGroups(groups, "ready", "", (row) => row.number !== 1);
240​
241 expect(sorted[0]!.entries.map((row) => row.number)).toEqual([3, 2, 1]);
242 expect(sortPullRequestGroups(groups, "ready", "sidebar", (row) => row.number !== 1)).toEqual(
243 groups,
244 );
245 });
246​
247 // regression: #9453 authored pull requests were not prioritized
248 it("keeps authored work first and ranks each group by readiness", () => {
249 const authoredWaiting = entry({ number: 1, checksState: "pending" });
250 const authoredReady = entry({
251 number: 2,
252 checksState: "passing",
253 reviewDecision: "approved",
254 });
255 const otherReady = entry({
256 number: 3,
257 checksState: "passing",
258 reviewDecision: "approved",
259 });
260 const sorted = sortPullRequestGroups(
261 [
262 { key: "authored", label: "Authored", entries: [authoredWaiting, authoredReady] },
263 { key: "others", label: "Others", entries: [otherReady] },
264 ],
265 "ready",
266 "",
267 );
268​
269 expect(sorted.map((group) => group.key)).toEqual(["authored", "others"]);
270 expect(sorted.flatMap((group) => group.entries).map((row) => row.number)).toEqual([2, 1, 3]);
271 });
272});
273​
274describe("blocked-on-me ranking", () => {
275 it("ranks authored work by how surely it is the author's to unblock, newest first within a tier", () => {
276 const conflict = entry({
277 number: 1,
278 mergeability: "conflicting",
279 checksState: "failing",
280 updatedAt: "2026-08-01T00:00:00Z",
281 });
282 const olderFailing = entry({
283 number: 2,
284 checksState: "failing",
285 updatedAt: "2026-08-01T00:00:00Z",
286 });
287 const changesRequested = entry({
288 number: 3,
289 reviewDecision: "changes-requested",
290 checksState: "failing",
291 updatedAt: "2026-08-02T00:00:00Z",
292 });
293 const approved = entry({ number: 4, checksState: "passing", reviewDecision: "approved" });
294 const draft = entry({ number: 5, isDraft: true, checksState: "passing" });
295 const waiting = entry({ number: 6 });
296 const merged = entry({ number: 7, state: "merged", updatedAt: "2026-08-01T00:00:00Z" });
297 const newerClosed = entry({ number: 8, state: "closed", updatedAt: "2026-08-03T00:00:00Z" });
298 const newerFailing = entry({
299 number: 9,
300 checksState: "failing",
301 updatedAt: "2026-08-03T00:00:00Z",
302 });
303​
304 expect(
305 rankPullRequestsBlockedOnAuthor([
306 waiting,
307 merged,
308 olderFailing,
309 draft,
310 approved,
311 changesRequested,
312 newerClosed,
313 conflict,
314 newerFailing,
315 ]).map((row) => row.number),
316 ).toEqual([1, 3, 9, 2, 5, 6, 4, 8, 7]);
317 });
318});
319​
320describe("partitioning with the hosts' own priority reads", () => {
321 const authoredRow = (number: number, updatedAt: string) =>
322 entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });
323​
324 it("keeps Others in feed order when a continuation lands an authored row already partitioned", () => {
325 const older = entry({ number: 1, updatedAt: "2026-07-05T00:00:00Z" });
326 const newer = entry({ number: 2, updatedAt: "2026-07-06T00:00:00Z" });
327 const mine = authoredRow(3, "2026-07-04T00:00:00Z");
328 const groups = partitionPullRequestsWithPriority([newer, older, mine], [mine], []);
329 expect(groups.map((group) => group.key)).toEqual(["authored", "others"]);
330 expect(groups[1]!.entries.map((item) => item.number)).toEqual([2, 1]);
331 expect(groups[0]!.entries.map((item) => item.number)).toEqual([3]);
332 });
333​
334 it("gives authored precedence over review-requested and orders partitions by recency", () => {
335 const both = authoredRow(1, "2026-07-01T00:00:00Z");
336 const requested = entry({
337 number: 2,
338 viewerReviewRequested: true,
339 updatedAt: "2026-07-02T00:00:00Z",
340 });
341 const requestedOlder = entry({
342 number: 3,
343 viewerReviewRequested: true,
344 updatedAt: "2026-06-02T00:00:00Z",
345 });
346 const groups = partitionPullRequestsWithPriority([], [both], [both, requestedOlder, requested]);
347 expect(groups.map((group) => group.key)).toEqual(["authored", "reviewRequested"]);
348 expect(groups[0]!.entries.map((item) => item.number)).toEqual([1]);
349 expect(groups[1]!.entries.map((item) => item.number)).toEqual([2, 3]);
350 });
351});
352​
353describe("the list snapshot across a reload", () => {
354 const makeStorage = () => {
355 const held = new Map<string, string>();
356 return {
357 getItem: (key: string) => held.get(key) ?? null,
358 setItem: (key: string, value: string) => void held.set(key, value),
359 };
360 };
361 const data = {
362 entries: [entry({ number: 1 })],
363 viewers: { "github.com": "Bilal" },
364 providers: [],
365 errors: [{ projectId: "project-1", message: "boom" }],
366 truncated: true,
367 nextCursors: { "pingdotgg/t3code": "cursor-1" },
368 } as never;
369​
370 it("carries neither stale failures nor stale cursors", () => {
371 const storage = makeStorage();
372 writePullRequestListSnapshot(storage, "env-1", { scope: "s", data });
373 const snapshot = readPullRequestListSnapshot(storage, "env-1");
374 expect(snapshot?.data.errors).toEqual([]);
375 expect(snapshot?.data.nextCursors).toEqual({});
376 });
377​
378 it("caps the accumulated rows but keeps the whole host set", () => {
379 const storage = makeStorage();
380 const manyEntries = Array.from({ length: 120 }, (_, index) => entry({ number: index + 1 }));
381 const viewers = { "github.com": "Bilal", "gitlab.com": "Bilal" };
382 const providers = [
383 {
384 host: "github.com",
385 kind: "github",
386 searchesOnHost: true,
387 projectCount: 1,
388 configured: true,
389 detail: null,
390 },
391 {
392 host: "gitlab.com",
393 kind: "gitlab",
394 searchesOnHost: true,
395 projectCount: 1,
396 configured: true,
397 detail: null,
398 },
399 ];
400 const accumulated = {
401 entries: manyEntries,
402 viewers,
403 providers,
404 errors: [],
405 truncated: true,
406 nextCursors: {},
407 } as never;
408 writePullRequestListSnapshot(storage, "env-1", { scope: "s", data: accumulated });
409 const snapshot = readPullRequestListSnapshot(storage, "env-1");
410 expect(snapshot?.data.entries).toHaveLength(99);
411 expect(snapshot?.data.viewers).toEqual(viewers);
412 expect(snapshot?.data.providers).toEqual(providers);
413 });
414});
415​
416describe("remembered pull request list controls", () => {
417 const makeStorage = () => {
418 const held = new Map<string, string>();
419 return {
420 getItem: (key: string) => held.get(key) ?? null,
421 setItem: (key: string, value: string) => void held.set(key, value),
422 };
423 };
424​
425 // regression: #9188 corrupt stored list controls broke the page
426 it("falls back to the default controls when storage is corrupt", () => {
427 const storage = makeStorage();
428 storage.setItem("t3.pullRequests.preferences", "{not json");
429 expect(readPullRequestListPreferences(storage)).toEqual({ involvement: "all", state: "open" });
430 });
431​
432 it("falls back when browser policy denies storage", () => {
433 const denied = {
434 getItem: () => {
435 throw new Error("storage denied");
436 },
437 setItem: () => {
438 throw new Error("storage denied");
439 },
440 };
441 expect(readPullRequestListPreferences(denied)).toEqual({ involvement: "all", state: "open" });
442 expect(() =>
443 writePullRequestListPreferences({ involvement: "all", state: "open" }, denied),
444 ).not.toThrow();
445 });
446});
447​
448const ENV_1 = "env-1" as EnvironmentId;
449const ENV_2 = "env-2" as EnvironmentId;
450​
451describe("merging the environments' own listings", () => {
452 const answer = (
453 overrides: Partial<Parameters<typeof mergePullRequestLists>[0][number][1]> = {},
454 ) =>
455 ({
456 viewers: { "github.com": "Bilal" },
457 providers: [
458 {
459 host: "github.com",
460 kind: "github",
461 searchesOnHost: true,
462 projectCount: 1,
463 configured: true,
464 detail: null,
465 },
466 ],
467 entries: [],
468 errors: [],
469 truncated: false,
470 nextCursors: {},
471 ...overrides,
472 }) as Parameters<typeof mergePullRequestLists>[0][number][1];
473​
474 it("tags every row with the environment that read it, newest first", () => {
475 const merged = mergePullRequestLists([
476 [ENV_1, answer({ entries: [entry({ number: 1, updatedAt: "2026-07-01T00:00:00Z" })] })],
477 [ENV_2, answer({ entries: [entry({ number: 2, updatedAt: "2026-08-01T00:00:00Z" })] })],
478 ]);
479 expect(merged?.entries.map((row) => [row.environmentId, row.number])).toEqual([
480 [ENV_2, 2],
481 [ENV_1, 1],
482 ]);
483 });
484​
485 // regression: #6490 one environment's error showed on every environment
486 it("keeps project errors scoped to the environment that reported them", () => {
487 const error = {
488 projectId: "project-1" as ProjectId,
489 projectTitle: "Web",
490 message: "Not signed in",
491 } as const;
492 const merged = mergePullRequestLists([
493 [ENV_1, answer({ errors: [error] })],
494 [ENV_2, answer()],
495 ]);
496​
497 expect(merged?.errors).toEqual([{ ...error, environmentId: ENV_1 }]);
498 });
499​
500 it("folds a host reached from two environments into one switcher row", () => {
501 const merged = mergePullRequestLists([
502 [ENV_1, answer()],
503 [
504 ENV_2,
505 answer({
506 providers: [
507 {
508 host: "github.com",
509 kind: SourceControlProviderKind.make("github"),
510 searchesOnHost: false,
511 projectCount: 2,
512 configured: false,
513 detail: "Not signed in.",
514 },
515 ],
516 }),
517 ],
518 ]);
519 expect(merged?.providers).toEqual([
520 {
521 host: "github.com",
522 kind: "github",
523 searchesOnHost: false,
524 projectCount: 3,
525 configured: true,
526 detail: null,
527 },
528 ]);
529 });
530});
531​
532describe('who "I" am, per server', () => {
533 const answer = (viewers: Record<string, string>, entries: ReadonlyArray<PullRequestListEntry>) =>
534 ({
535 viewers,
536 providers: [],
537 entries,
538 errors: [],
539 truncated: false,
540 nextCursors: {},
541 }) as Parameters<typeof mergePullRequestLists>[0][number][1];
542 const byBilal = { login: "Bilal", name: null, avatarUrl: null };
543​
544 it("does not let one server's account decide who authored another server's rows", () => {
545 const merged = mergePullRequestLists([
546 [ENV_1, answer({ "github.com": "Bilal" }, [entry({ number: 1, author: byBilal })])],
547 [ENV_2, answer({ "github.com": "Octocat" }, [entry({ number: 2, author: byBilal })])],
548 ])!;
549​
550 const groups = groupPullRequestsByInvolvement(merged.entries, merged.viewers);
551 expect(
552 groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
553 ).toEqual([1]);
554 expect(
555 filterPullRequestsByInvolvement(merged.entries, merged.viewers, "authored").map(
556 (row) => row.number,
557 ),
558 ).toEqual([1]);
559 });
560});
561​
562describe("the project an id names", () => {
563 const projects = [
564 { id: "project-1", environmentId: ENV_1 },
565 { id: "project-1", environmentId: ENV_2 },
566 { id: "project-2", environmentId: ENV_2 },
567 ];
568​
569 it("answers a bare id only where one server has it", () => {
570 expect(findScopedProject(projects, null, "project-2")?.environmentId).toBe(ENV_2);
571 expect(findScopedProject(projects, null, "project-1")).toBeUndefined();
572 });
573});
574​
575describe("which environments a listing should ask", () => {
576 const ENV_3 = "env-3" as EnvironmentId;
577 const environmentIds = [ENV_1, ENV_2, ENV_3];
578​
579 it("asks only the environments that actually hold an ambiguous bare id, never a third that doesn't", () => {
580 const projects = [
581 { id: "project-1", environmentId: ENV_1 },
582 { id: "project-1", environmentId: ENV_2 },
583 ];
584 expect(
585 resolveQueryEnvironmentIds(environmentIds, projects, undefined, "project-1", true),
586 ).toEqual([ENV_1, ENV_2]);
587 });
588});
589​
590describe("the server a saved selection names", () => {
591 const known = new Set([ENV_1, ENV_2]);
592​
593 it("resolves to nothing yet for a server that is known but not ready, rather than falling back", () => {
594 expect(resolveSelectedEnvironmentId(ENV_2, known, ENV_1)).toBe(ENV_2);
595 });
596});
597​
598describe("the priority groups against a paginated feed", () => {
599 const authoredRow = (number: number, updatedAt: string) =>
600 entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });
601​
602 it("shows every authored row the host reported, not only the ones the feed page holds", () => {
603 const newest = authoredRow(6039, "2026-08-11T08:00:00Z");
604 const older = [
605 authoredRow(5499, "2026-08-10T17:00:00Z"),
606 authoredRow(5544, "2026-08-10T16:00:00Z"),
607 ];
608 const feed = [newest, entry({ number: 6123, updatedAt: "2026-08-11T09:00:00Z" })];
609​
610 const groups = partitionPullRequestsWithPriority(feed, [newest, ...older], []);
611​
612 expect(
613 groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
614 ).toEqual([6039, 5499, 5544]);
615 expect(
616 groups.find((group) => group.key === "others")?.entries.map((row) => row.number),
617 ).toEqual([6123]);
618 });
619});
620​
621describe("pull request list overrides", () => {
622 const entry = (number: number, state: "open" | "closed" | "merged") =>
623 ({
624 host: "github.com",
625 repository: "pingdotgg/t3code",
626 number,
627 state,
628 isDraft: false,
629 updatedAt: "2026-07-01T00:00:00Z",
630 labels: [],
631 }) as unknown as PullRequestListEntry;
632 const key = (row: { number: number }) => `#${row.number}`;
633​
634 it("writes the override over the row and drops it from a list whose state it left", () => {
635 const rows = [entry(1, "open"), entry(2, "open")];
636 const overrides = new Map([
637 ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at: 0 }],
638 ]);
639 expect(
640 applyPullRequestOverrides(rows, overrides, key, "open").map((row) => row.number),
641 ).toEqual([2]);
642 const all = applyPullRequestOverrides(rows, overrides, key, "all");
643 expect(all.map((row) => [row.number, row.state])).toEqual([
644 [1, "closed"],
645 [2, "open"],
646 ]);
647 expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows);
648 });
649​
650 it("keeps a confirmed close hidden when its override is cleared", () => {
651 const at = 1_000_000;
652 const rows = [entry(1, "closed"), entry(2, "open"), entry(3, "merged")];
653 const overrides = new Map([
654 ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at }],
655 ]);
656 const settled = settlePullRequestOverrides(overrides, rows, key, at + 5_000);
657 expect(settled.size).toBe(0);
658 expect(applyPullRequestOverrides(rows, settled, key, "open").map((row) => row.number)).toEqual([
659 2,
660 ]);
661 });
662});
663​
664describe("pull request list override settlement", () => {
665 const entry = (number: number, state: "open" | "closed" | "merged") =>
666 ({ number, state, isDraft: false, labels: [] }) as unknown as PullRequestListEntry;
667 const key = (row: { number: number }) => `#${row.number}`;
668​
669 it("keeps an override until an answer agrees with it", () => {
670 const at = 1_000_000;
671 const closed = { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at };
672 const overrides = new Map([["#1", closed]]);
673 expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 5_000)).toBe(
674 overrides,
675 );
676 expect(settlePullRequestOverrides(overrides, [entry(2, "open")], key, at + 5_000).size).toBe(1);
677 expect(settlePullRequestOverrides(overrides, [entry(1, "closed")], key, at + 5_000).size).toBe(
678 0,
679 );
680 expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 90_000).size).toBe(
681 0,
682 );
683 });
684​
685 it("does not hand back the old order when only the order changed", () => {
686 const previous = [entry(1, "open"), entry(2, "open")];
687 const swapped = reusePullRequestEntries(previous, [entry(2, "open"), entry(1, "open")], key);
688 expect(swapped).not.toBe(previous);
689 expect(swapped.map((row) => row.number)).toEqual([2, 1]);
690 });
691});
692​
693describe("pull request quick actions", () => {
694 const summary = (host: string, kind: string, actions?: ReadonlyArray<PullRequestAction>) => ({
695 host,
696 kind: SourceControlProviderKind.make(kind),
697 searchesOnHost: true,
698 projectCount: 1,
699 configured: true,
700 detail: null,
701 ...(actions === undefined ? {} : { actions }),
702 });
703​
704 it("offers what each host reports, and the host's own set when a server reports none", () => {
705 const actionsOf = pullRequestHostActions([
706 summary("bitbucket.org", "bitbucket", ["merge", "close"]),
707 summary("github.com", "github"),
708 summary("gitlab.com", "gitlab"),
709 ]);
710 const bitbucket = actionsOf({
711 host: "bitbucket.org",
712 provider: SourceControlProviderKind.make("bitbucket"),
713 });
714 expect(pullRequestQuickActions({ state: "closed", isDraft: false }, bitbucket)).toEqual([]);
715 const github = actionsOf({
716 host: "github.com",
717 provider: SourceControlProviderKind.make("github"),
718 });
719 expect(pullRequestQuickActions({ state: "open", isDraft: true }, github)).toEqual([
720 "close",
721 "ready",
722 ]);
723 const gitlab = actionsOf({
724 host: "gitlab.com",
725 provider: SourceControlProviderKind.make("gitlab"),
726 });
727 expect(pullRequestQuickActions({ state: "open", isDraft: false }, gitlab)).toEqual([]);
728 });
729});
730​
731describe("refresh page size", () => {
732 const twoPagesAcrossFourRepositories = (provider: "github" | "gitlab") =>
733 ["a", "b", "c", "d"].flatMap((name) =>
734 Array.from({ length: 198 }, (_, index) =>
735 entry({
736 number: index + 1,
737 provider: SourceControlProviderKind.make(provider),
738 repository: `pingdotgg/${name}`,
739 }),
740 ),
741 );
742​
743 it("asks each repository for its own rows where repositories are read one at a time", () => {
744 expect(largestPullRequestReadCount(twoPagesAcrossFourRepositories("gitlab"))).toBe(198);
745 });
746​
747 // regression: #19403 refreshes were not bounded by each tracker read
748 it("asks for the whole host where one search reads every repository", () => {
749 expect(largestPullRequestReadCount(twoPagesAcrossFourRepositories("github"))).toBe(792);
750 });
751});
752​
753describe("findProjectForRepository", () => {
754 it("resolves Azure bare names using matching project and environment scope", () => {
755 const azure = (id: string, environmentId: string, path: string) => ({
756 id,
757 environmentId,
758 repositoryIdentity: {
759 canonicalKey: `dev.azure.com/${path}`,
760 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
761 provider: SourceControlProviderKind.make("azure-devops"),
762 displayName: path,
763 owner: "contoso",
764 name: path.split("/").at(-1)!,
765 },
766 });
767 const payments = azure("p1", ENV_1, "contoso/payments/_git/api");
768 const billing = azure("p2", ENV_1, "contoso/billing/_git/api");
769 const remoteBilling = azure("p2", ENV_2, "contoso/billing/_git/api");
770 const unrelated = azure("p3", ENV_2, "contoso/billing/_git/web");
771 const projects = [payments, billing, remoteBilling, unrelated];
772​
773 expect(findProjectForRepository(projects, { repository: "api" })).toBe(payments);
774 expect(
775 findProjectForRepository(projects, {
776 repository: "api",
777 scopedProjectId: "p2",
778 scopedEnvironmentId: ENV_2,
779 }),
780 ).toBe(remoteBilling);
781 expect(
782 findProjectForRepository(projects, {
783 repository: "api",
784 scopedProjectId: "p3",
785 scopedEnvironmentId: ENV_2,
786 }),
787 ).toBe(payments);
788 });
789​
790 it("keeps repository matches on the selected environment when project IDs overlap", () => {
791 const project = (id: string, environmentId: string, repository: string) => ({
792 id,
793 environmentId,
794 repositoryIdentity: {
795 canonicalKey: `github.com/${repository}`,
796 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
797 provider: SourceControlProviderKind.make("github"),
798 displayName: repository,
799 },
800 });
801 const unrelated = project("p1", ENV_1, "acme/web");
802 const local = project("p2", ENV_1, "acme/api");
803 const remote = project("p1", ENV_2, "acme/api");
804 const projects = [unrelated, local, remote];
805​
806 expect(findProjectForRepository(projects, { repository: "acme/api" })).toBe(local);
807 expect(
808 findProjectForRepository(projects, {
809 repository: "acme/api",
810 selectedEnvironmentId: ENV_2,
811 }),
812 ).toBe(remote);
813 expect(
814 findProjectForRepository(projects, {
815 repository: "acme/web",
816 selectedEnvironmentId: ENV_2,
817 }),
818 ).toBeUndefined();
819 expect(
820 findProjectForRepository(projects, {
821 repository: "acme/api",
822 selectedEnvironmentId: "env-connecting",
823 }),
824 ).toBeUndefined();
825 });
826});
827​
828describe("filter picker choices", () => {
829 const actor = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null });
830​
831 it("offers authors the host found that no loaded row carries, after the loaded ones", () => {
832 const loaded = [
833 { actor: actor("julius", "Julius"), count: 4, mergedCount: 3 },
834 { actor: actor("theo"), count: 1, mergedCount: 0 },
835 ];
836​
837 const choices = pullRequestAuthorChoices(
838 loaded,
839 [actor("Julius"), actor("juliana", "Juliana")],
840 "jul",
841 );
842​
843 expect(choices.map((choice) => [choice.actor.login, choice.count])).toEqual([
844 ["julius", 4],
845 ["juliana", 0],
846 ]);
847 });
848​
849 it("keeps showing an author picked from the host's search once the search clears", () => {
850 const loaded = [{ actor: actor("julius"), count: 4, mergedCount: 3 }];
851 const hosted = [actor("Juliana", "Juliana")];
852​
853 expect(selectedPullRequestAuthor(loaded, hosted, "juliana")?.actor).toEqual(
854 actor("Juliana", "Juliana"),
855 );
856 expect(selectedPullRequestAuthor(loaded, [], "juliana")?.actor.login).toBe("juliana");
857 expect(selectedPullRequestAuthor(loaded, hosted, "JULIUS")?.count).toBe(4);
858 expect(selectedPullRequestAuthor(loaded, hosted, undefined)).toBeUndefined();
859 });
860​
861 it("puts the host's authors after the first loaded matches rather than after all of them", () => {
862 const loaded = Array.from({ length: 40 }, (_, index) => ({
863 actor: actor(`dev-${index}`),
864 count: 1,
865 mergedCount: 0,
866 }));
867​
868 const choices = pullRequestAuthorChoices(loaded, [actor("dev-from-host")], "dev");
869​
870 expect(choices.slice(0, 30).map((choice) => choice.actor.login)).toContain("dev-from-host");
871 });
872​
873 it("keeps a loaded label's count when only the host's search found it", () => {
874 const loaded = [{ name: "size:XL", color: "d93f0b", count: 7 }];
875​
876 const choices = pullRequestLabelChoices(
877 loaded,
878 [
879 { name: "size:XL", color: "d93f0b" },
880 { name: "bug", color: null },
881 ],
882 "xl-ish",
883 );
884​
885 expect(choices).toEqual([
886 { name: "size:XL", color: "d93f0b", count: 7 },
887 { name: "bug", color: null, count: 0 },
888 ]);
889 });
890});