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

pullRequestList.logic.test.ts

861 lines29.5 KB

1import { SourceControlProviderKind } from "@t3tools/contracts";
2import type {
3 EnvironmentId,
4 ProjectId,
5 PullRequestAction,
6 PullRequestListEntry,
7 PullRequestSummary,
8} from "@t3tools/contracts";
9import { describe, expect, it } from "vite-plus/test";
10​
11import {
12 pullRequestHostActions,
13 largestPullRequestReadCount,
14 pullRequestQuickActions,
15 filterPullRequestsByInvolvement,
16 findProjectForRepository,
17 findScopedProject,
18 mergePullRequestLists,
19 pullRequestEntryKey,
20 groupPullRequestsByInvolvement,
21 pullRequestStatsBatches,
22 pullRequestStatsKeysToRequest,
23 pullRequestStatsRefreshBatches,
24 mergePullRequestDiffStats,
25 partitionPullRequestsWithPriority,
26 pullRequestAuthorChoices,
27 selectedPullRequestAuthor,
28 pullRequestLabelChoices,
29 rankPullRequestMatches,
30 rankPullRequestsBlockedOnAuthor,
31 rankPullRequestsByMergeReadiness,
32 sortPullRequestGroups,
33 resolveQueryEnvironmentIds,
34 resolveSelectedEnvironmentId,
35 type EnvironmentPullRequestEntry,
36 applyPullRequestOverrides,
37 pullRequestOverrideAfterAction,
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("remembered pull request list controls", () => {
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​
362 // regression: #9188 corrupt stored list controls broke the page
363 it("falls back to the default controls when storage is corrupt", () => {
364 const storage = makeStorage();
365 storage.setItem("t3.pullRequests.preferences", "{not json");
366 expect(readPullRequestListPreferences(storage)).toEqual({ involvement: "all", state: "open" });
367 });
368​
369 it("falls back when browser policy denies storage", () => {
370 const denied = {
371 getItem: () => {
372 throw new Error("storage denied");
373 },
374 setItem: () => {
375 throw new Error("storage denied");
376 },
377 };
378 expect(readPullRequestListPreferences(denied)).toEqual({ involvement: "all", state: "open" });
379 expect(() =>
380 writePullRequestListPreferences({ involvement: "all", state: "open" }, denied),
381 ).not.toThrow();
382 });
383});
384​
385const ENV_1 = "env-1" as EnvironmentId;
386const ENV_2 = "env-2" as EnvironmentId;
387​
388describe("merging the environments' own listings", () => {
389 const answer = (
390 overrides: Partial<Parameters<typeof mergePullRequestLists>[0][number][1]> = {},
391 ) =>
392 ({
393 viewers: { "github.com": "Bilal" },
394 providers: [
395 {
396 host: "github.com",
397 kind: "github",
398 searchesOnHost: true,
399 projectCount: 1,
400 configured: true,
401 detail: null,
402 },
403 ],
404 entries: [],
405 errors: [],
406 truncated: false,
407 nextCursors: {},
408 ...overrides,
409 }) as Parameters<typeof mergePullRequestLists>[0][number][1];
410​
411 it("orders host timestamps by instant across offsets and fractional seconds", () => {
412 const entries = [
413 entry({ number: 1, updatedAt: "2026-07-05T01:00:00+02:00" }),
414 entry({ number: 2, updatedAt: "2026-07-05T00:30:00Z" }),
415 entry({ number: 3, updatedAt: "2026-07-05T00:30:00.5Z" }),
416 ];
417 const merged = mergePullRequestLists([
418 [ENV_1, answer({ entries: entries.slice(0, 2) })],
419 [ENV_2, answer({ entries: entries.slice(2) })],
420 ]);
421​
422 expect(merged?.entries.map((row) => row.number)).toEqual([3, 2, 1]);
423 });
424​
425 it("tags every row with the environment that read it, newest first", () => {
426 const merged = mergePullRequestLists([
427 [ENV_1, answer({ entries: [entry({ number: 1, updatedAt: "2026-07-01T00:00:00Z" })] })],
428 [ENV_2, answer({ entries: [entry({ number: 2, updatedAt: "2026-08-01T00:00:00Z" })] })],
429 ]);
430 expect(merged?.entries.map((row) => [row.environmentId, row.number])).toEqual([
431 [ENV_2, 2],
432 [ENV_1, 1],
433 ]);
434 });
435​
436 // regression: #6490 one environment's error showed on every environment
437 it("keeps project errors scoped to the environment that reported them", () => {
438 const error = {
439 projectId: "project-1" as ProjectId,
440 projectTitle: "Web",
441 message: "Not signed in",
442 } as const;
443 const merged = mergePullRequestLists([
444 [ENV_1, answer({ errors: [error] })],
445 [ENV_2, answer()],
446 ]);
447​
448 expect(merged?.errors).toEqual([{ ...error, environmentId: ENV_1 }]);
449 });
450​
451 it("folds a host reached from two environments into one switcher row", () => {
452 const merged = mergePullRequestLists([
453 [ENV_1, answer()],
454 [
455 ENV_2,
456 answer({
457 providers: [
458 {
459 host: "github.com",
460 kind: SourceControlProviderKind.make("github"),
461 searchesOnHost: false,
462 projectCount: 2,
463 configured: false,
464 detail: "Not signed in.",
465 },
466 ],
467 }),
468 ],
469 ]);
470 expect(merged?.providers).toEqual([
471 {
472 host: "github.com",
473 kind: "github",
474 searchesOnHost: false,
475 projectCount: 3,
476 configured: true,
477 detail: null,
478 },
479 ]);
480 });
481});
482​
483describe('who "I" am, per server', () => {
484 const answer = (viewers: Record<string, string>, entries: ReadonlyArray<PullRequestListEntry>) =>
485 ({
486 viewers,
487 providers: [],
488 entries,
489 errors: [],
490 truncated: false,
491 nextCursors: {},
492 }) as Parameters<typeof mergePullRequestLists>[0][number][1];
493 const byBilal = { login: "Bilal", name: null, avatarUrl: null };
494​
495 it("does not let one server's account decide who authored another server's rows", () => {
496 const merged = mergePullRequestLists([
497 [ENV_1, answer({ "github.com": "Bilal" }, [entry({ number: 1, author: byBilal })])],
498 [ENV_2, answer({ "github.com": "Octocat" }, [entry({ number: 2, author: byBilal })])],
499 ])!;
500​
501 const groups = groupPullRequestsByInvolvement(merged.entries, merged.viewers);
502 expect(
503 groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
504 ).toEqual([1]);
505 expect(
506 filterPullRequestsByInvolvement(merged.entries, merged.viewers, "authored").map(
507 (row) => row.number,
508 ),
509 ).toEqual([1]);
510 });
511});
512​
513describe("the project an id names", () => {
514 const projects = [
515 { id: "project-1", environmentId: ENV_1 },
516 { id: "project-1", environmentId: ENV_2 },
517 { id: "project-2", environmentId: ENV_2 },
518 ];
519​
520 it("answers a bare id only where one server has it", () => {
521 expect(findScopedProject(projects, null, "project-2")?.environmentId).toBe(ENV_2);
522 expect(findScopedProject(projects, null, "project-1")).toBeUndefined();
523 });
524});
525​
526describe("which environments a listing should ask", () => {
527 const ENV_3 = "env-3" as EnvironmentId;
528 const environmentIds = [ENV_1, ENV_2, ENV_3];
529​
530 it("asks only the environments that actually hold an ambiguous bare id, never a third that doesn't", () => {
531 const projects = [
532 { id: "project-1", environmentId: ENV_1 },
533 { id: "project-1", environmentId: ENV_2 },
534 ];
535 expect(
536 resolveQueryEnvironmentIds(environmentIds, projects, undefined, "project-1", true),
537 ).toEqual([ENV_1, ENV_2]);
538 });
539});
540​
541describe("the server a saved selection names", () => {
542 const known = new Set([ENV_1, ENV_2]);
543​
544 it("resolves to nothing yet for a server that is known but not ready, rather than falling back", () => {
545 expect(resolveSelectedEnvironmentId(ENV_2, known, ENV_1)).toBe(ENV_2);
546 });
547});
548​
549describe("the priority groups against a paginated feed", () => {
550 const authoredRow = (number: number, updatedAt: string) =>
551 entry({ number, updatedAt, author: { login: "Bilal", name: null, avatarUrl: null } });
552​
553 it("shows every authored row the host reported, not only the ones the feed page holds", () => {
554 const newest = authoredRow(6039, "2026-08-11T08:00:00Z");
555 const older = [
556 authoredRow(5499, "2026-08-10T17:00:00Z"),
557 authoredRow(5544, "2026-08-10T16:00:00Z"),
558 ];
559 const feed = [newest, entry({ number: 6123, updatedAt: "2026-08-11T09:00:00Z" })];
560​
561 const groups = partitionPullRequestsWithPriority(feed, [newest, ...older], []);
562​
563 expect(
564 groups.find((group) => group.key === "authored")?.entries.map((row) => row.number),
565 ).toEqual([6039, 5499, 5544]);
566 expect(
567 groups.find((group) => group.key === "others")?.entries.map((row) => row.number),
568 ).toEqual([6123]);
569 });
570});
571​
572describe("pull request list overrides", () => {
573 const entry = (number: number, state: "open" | "closed" | "merged") =>
574 ({
575 host: "github.com",
576 repository: "pingdotgg/t3code",
577 number,
578 state,
579 isDraft: false,
580 updatedAt: "2026-07-01T00:00:00Z",
581 labels: [],
582 }) as unknown as PullRequestListEntry;
583 const key = (row: { number: number }) => `#${row.number}`;
584​
585 it("writes the override over the row and drops it from a list whose state it left", () => {
586 const rows = [entry(1, "open"), entry(2, "open")];
587 const overrides = new Map([
588 ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at: 0 }],
589 ]);
590 expect(
591 applyPullRequestOverrides(rows, overrides, key, "open").map((row) => row.number),
592 ).toEqual([2]);
593 const all = applyPullRequestOverrides(rows, overrides, key, "all");
594 expect(all.map((row) => [row.number, row.state])).toEqual([
595 [1, "closed"],
596 [2, "open"],
597 ]);
598 expect(applyPullRequestOverrides(rows, new Map(), key, "open")).toBe(rows);
599 });
600​
601 it("shows a reply's queued merge as open and never un-merges a merged row", () => {
602 const reply = { state: "open", updatedAt: "2026-07-03T00:00:00Z", observedAt: 300 } as const;
603 const override = pullRequestOverrideAfterAction(
604 entry(1, "open"),
605 "merge",
606 new Date(900),
607 1,
608 reply as unknown as PullRequestSummary,
609 )!;
610 const overrides = new Map([["#1", override]]);
611 expect(applyPullRequestOverrides([entry(1, "open")], overrides, key, "open")).toMatchObject([
612 { state: "open", updatedAt: reply.updatedAt, observedAt: 300 },
613 ]);
614 expect(
615 applyPullRequestOverrides([entry(1, "merged")], overrides, key, "all").map(
616 (row) => row.state,
617 ),
618 ).toEqual(["merged"]);
619 });
620​
621 it("keeps a confirmed close hidden when its override is cleared", () => {
622 const at = 1_000_000;
623 const rows = [entry(1, "closed"), entry(2, "open"), entry(3, "merged")];
624 const overrides = new Map([
625 ["#1", { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at }],
626 ]);
627 const settled = settlePullRequestOverrides(overrides, rows, key, at + 5_000);
628 expect(settled.size).toBe(0);
629 expect(applyPullRequestOverrides(rows, settled, key, "open").map((row) => row.number)).toEqual([
630 2,
631 ]);
632 });
633});
634​
635describe("pull request list override settlement", () => {
636 const entry = (number: number, state: "open" | "closed" | "merged") =>
637 ({ number, state, isDraft: false, labels: [] }) as unknown as PullRequestListEntry;
638 const key = (row: { number: number }) => `#${row.number}`;
639​
640 it("keeps an override until an answer agrees with it", () => {
641 const at = 1_000_000;
642 const closed = { state: "closed" as const, updatedAt: "2026-07-03T00:00:00Z", token: 1, at };
643 const overrides = new Map([["#1", closed]]);
644 expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 5_000)).toBe(
645 overrides,
646 );
647 expect(settlePullRequestOverrides(overrides, [entry(2, "open")], key, at + 5_000).size).toBe(1);
648 expect(settlePullRequestOverrides(overrides, [entry(1, "closed")], key, at + 5_000).size).toBe(
649 0,
650 );
651 expect(settlePullRequestOverrides(overrides, [entry(1, "open")], key, at + 90_000).size).toBe(
652 0,
653 );
654 });
655​
656 it("does not hand back the old order when only the order changed", () => {
657 const previous = [entry(1, "open"), entry(2, "open")];
658 const swapped = reusePullRequestEntries(previous, [entry(2, "open"), entry(1, "open")], key);
659 expect(swapped).not.toBe(previous);
660 expect(swapped.map((row) => row.number)).toEqual([2, 1]);
661 });
662});
663​
664describe("pull request quick actions", () => {
665 const summary = (host: string, kind: string, actions?: ReadonlyArray<PullRequestAction>) => ({
666 host,
667 kind: SourceControlProviderKind.make(kind),
668 searchesOnHost: true,
669 projectCount: 1,
670 configured: true,
671 detail: null,
672 ...(actions === undefined ? {} : { actions }),
673 });
674​
675 it("offers what each host reports, and the host's own set when a server reports none", () => {
676 const actionsOf = pullRequestHostActions([
677 summary("bitbucket.org", "bitbucket", ["merge", "close"]),
678 summary("github.com", "github"),
679 summary("gitlab.com", "gitlab"),
680 ]);
681 const bitbucket = actionsOf({
682 host: "bitbucket.org",
683 provider: SourceControlProviderKind.make("bitbucket"),
684 });
685 expect(pullRequestQuickActions({ state: "closed", isDraft: false }, bitbucket)).toEqual([]);
686 const github = actionsOf({
687 host: "github.com",
688 provider: SourceControlProviderKind.make("github"),
689 });
690 expect(pullRequestQuickActions({ state: "open", isDraft: true }, github)).toEqual([
691 "close",
692 "ready",
693 ]);
694 const gitlab = actionsOf({
695 host: "gitlab.com",
696 provider: SourceControlProviderKind.make("gitlab"),
697 });
698 expect(pullRequestQuickActions({ state: "open", isDraft: false }, gitlab)).toEqual([]);
699 });
700});
701​
702describe("refresh page size", () => {
703 const twoPagesAcrossFourRepositories = (provider: "github" | "gitlab") =>
704 ["a", "b", "c", "d"].flatMap((name) =>
705 Array.from({ length: 198 }, (_, index) =>
706 entry({
707 number: index + 1,
708 provider: SourceControlProviderKind.make(provider),
709 repository: `pingdotgg/${name}`,
710 }),
711 ),
712 );
713​
714 it("asks each repository for its own rows where repositories are read one at a time", () => {
715 expect(largestPullRequestReadCount(twoPagesAcrossFourRepositories("gitlab"))).toBe(198);
716 });
717​
718 // regression: #19403 refreshes were not bounded by each tracker read
719 it("asks for the whole host where one search reads every repository", () => {
720 expect(largestPullRequestReadCount(twoPagesAcrossFourRepositories("github"))).toBe(792);
721 });
722});
723​
724describe("findProjectForRepository", () => {
725 it("resolves Azure bare names using matching project and environment scope", () => {
726 const azure = (id: string, environmentId: string, path: string) => ({
727 id,
728 environmentId,
729 repositoryIdentity: {
730 canonicalKey: `dev.azure.com/${path}`,
731 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
732 provider: SourceControlProviderKind.make("azure-devops"),
733 displayName: path,
734 owner: "contoso",
735 name: path.split("/").at(-1)!,
736 },
737 });
738 const payments = azure("p1", ENV_1, "contoso/payments/_git/api");
739 const billing = azure("p2", ENV_1, "contoso/billing/_git/api");
740 const remoteBilling = azure("p2", ENV_2, "contoso/billing/_git/api");
741 const unrelated = azure("p3", ENV_2, "contoso/billing/_git/web");
742 const projects = [payments, billing, remoteBilling, unrelated];
743​
744 expect(findProjectForRepository(projects, { repository: "api" })).toBe(payments);
745 expect(
746 findProjectForRepository(projects, {
747 repository: "api",
748 scopedProjectId: "p2",
749 scopedEnvironmentId: ENV_2,
750 }),
751 ).toBe(remoteBilling);
752 expect(
753 findProjectForRepository(projects, {
754 repository: "api",
755 scopedProjectId: "p3",
756 scopedEnvironmentId: ENV_2,
757 }),
758 ).toBe(payments);
759 });
760​
761 it("keeps repository matches on the selected environment when project IDs overlap", () => {
762 const project = (id: string, environmentId: string, repository: string) => ({
763 id,
764 environmentId,
765 repositoryIdentity: {
766 canonicalKey: `github.com/${repository}`,
767 locator: { source: "git-remote" as const, remoteName: "origin", remoteUrl: "" },
768 provider: SourceControlProviderKind.make("github"),
769 displayName: repository,
770 },
771 });
772 const unrelated = project("p1", ENV_1, "acme/web");
773 const local = project("p2", ENV_1, "acme/api");
774 const remote = project("p1", ENV_2, "acme/api");
775 const projects = [unrelated, local, remote];
776​
777 expect(findProjectForRepository(projects, { repository: "acme/api" })).toBe(local);
778 expect(
779 findProjectForRepository(projects, {
780 repository: "acme/api",
781 selectedEnvironmentId: ENV_2,
782 }),
783 ).toBe(remote);
784 expect(
785 findProjectForRepository(projects, {
786 repository: "acme/web",
787 selectedEnvironmentId: ENV_2,
788 }),
789 ).toBeUndefined();
790 expect(
791 findProjectForRepository(projects, {
792 repository: "acme/api",
793 selectedEnvironmentId: "env-connecting",
794 }),
795 ).toBeUndefined();
796 });
797});
798​
799describe("filter picker choices", () => {
800 const actor = (login: string, name: string | null = null) => ({ login, name, avatarUrl: null });
801​
802 it("offers authors the host found that no loaded row carries, after the loaded ones", () => {
803 const loaded = [
804 { actor: actor("julius", "Julius"), count: 4, mergedCount: 3 },
805 { actor: actor("theo"), count: 1, mergedCount: 0 },
806 ];
807​
808 const choices = pullRequestAuthorChoices(
809 loaded,
810 [actor("Julius"), actor("juliana", "Juliana")],
811 "jul",
812 );
813​
814 expect(choices.map((choice) => [choice.actor.login, choice.count])).toEqual([
815 ["julius", 4],
816 ["juliana", 0],
817 ]);
818 });
819​
820 it("keeps showing an author picked from the host's search once the search clears", () => {
821 const loaded = [{ actor: actor("julius"), count: 4, mergedCount: 3 }];
822 const hosted = [actor("Juliana", "Juliana")];
823​
824 expect(selectedPullRequestAuthor(loaded, hosted, "juliana")?.actor).toEqual(
825 actor("Juliana", "Juliana"),
826 );
827 expect(selectedPullRequestAuthor(loaded, [], "juliana")?.actor.login).toBe("juliana");
828 expect(selectedPullRequestAuthor(loaded, hosted, "JULIUS")?.count).toBe(4);
829 expect(selectedPullRequestAuthor(loaded, hosted, undefined)).toBeUndefined();
830 });
831​
832 it("puts the host's authors after the first loaded matches rather than after all of them", () => {
833 const loaded = Array.from({ length: 40 }, (_, index) => ({
834 actor: actor(`dev-${index}`),
835 count: 1,
836 mergedCount: 0,
837 }));
838​
839 const choices = pullRequestAuthorChoices(loaded, [actor("dev-from-host")], "dev");
840​
841 expect(choices.slice(0, 30).map((choice) => choice.actor.login)).toContain("dev-from-host");
842 });
843​
844 it("keeps a loaded label's count when only the host's search found it", () => {
845 const loaded = [{ name: "size:XL", color: "d93f0b", count: 7 }];
846​
847 const choices = pullRequestLabelChoices(
848 loaded,
849 [
850 { name: "size:XL", color: "d93f0b" },
851 { name: "bug", color: null },
852 ],
853 "xl-ish",
854 );
855​
856 expect(choices).toEqual([
857 { name: "size:XL", color: "d93f0b", count: 7 },
858 { name: "bug", color: null, count: 0 },
859 ]);
860 });
861});