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

pullRequestList.logic.test.ts

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