@omercnet/paseo-pr-radar 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,6 +33,21 @@ DevTools before capture. Both PNGs come from an isolated Paseo test daemon at 2
33
33
 
34
34
  Paseo supplies normalized workspace pull request status. A daemon-side plugin handler uses the authenticated `gh` CLI to distinguish authored pull requests from review requests. If viewer lookup fails, PR Radar falls back conservatively and does not claim that a row needs the user.
35
35
 
36
+ ## Sorting
37
+
38
+ The Sort row applies after the current filters and search. **Needs attention first** is the default:
39
+ bucket order, then oldest activity first. **Mergeable first** puts Ready rows first, newest activity
40
+ first, then the remaining buckets. **Recently updated** and **Oldest first** order by activity, not
41
+ creation time. **Repository** orders by repository name, then PR number.
42
+
43
+ Activity ties use ascending titles; fully tied rows keep their input order. Missing or invalid
44
+ activity times count as the epoch, so they sort first in oldest-first orders and last in newest-first
45
+ orders. Sort selection stays local to the open screen and resets on reload, like search and the
46
+ time window.
47
+
48
+ On web, Tab enters the group at the selected option and Tab or Shift+Tab leaves it. Space selects
49
+ the focused option. Arrow keys select and focus the next or previous option, wrapping at either end.
50
+
36
51
  ## Sidebar row
37
52
 
38
53
  The sidebar row shows a "needs you" count; pressing the count opens a popover of those pull requests. Pressing one opens PR Radar focused on it (`param.pr`), and the needs-you link filters the queue (`param.filter`), so both survive reload and can be linked. A trailing `+` marks a count that may be incomplete: viewer lookup failed, a pagination or inbox cap was hit, or workspace status was unavailable.
@@ -1,7 +1,16 @@
1
1
  import { openExternalUrl, type PluginSurfaceProps, useRpc } from "@getpaseo/plugin/client";
2
+ import { copyText } from "@getpaseo/plugin/client/react-native";
2
3
  import { useMutation, useQueryClient } from "@tanstack/react-query";
3
4
  import { useCallback, useEffect, useMemo, useState } from "react";
4
- import { ActivityIndicator, FlatList, Pressable, Text, TextInput, View } from "react-native";
5
+ import {
6
+ ActivityIndicator,
7
+ FlatList,
8
+ Pressable,
9
+ ScrollView,
10
+ Text,
11
+ TextInput,
12
+ View,
13
+ } from "react-native";
5
14
  import { acknowledgeViewerScope } from "../shared/viewer-scope";
6
15
  import {
7
16
  agentActionFor,
@@ -15,6 +24,8 @@ import {
15
24
  openPullRequestUrl,
16
25
  type RadarBucket,
17
26
  type RadarRow,
27
+ type SortKey,
28
+ sortRows,
18
29
  } from "./radar";
19
30
  import {
20
31
  DIRECTORY_PARTIAL,
@@ -23,7 +34,9 @@ import {
23
34
  type RadarFilter,
24
35
  VIEWER_URL_LIMIT,
25
36
  } from "./screen-state";
37
+ import { SortControls } from "./sort-controls";
26
38
  import { useRadar } from "./use-radar";
39
+ import { revealFocusedChip } from "./web";
27
40
 
28
41
  const CLOCK_TICK_MS = 30_000;
29
42
 
@@ -56,9 +69,12 @@ function agentState(row: RadarRow): string {
56
69
  return `${agent.title} · ${agent.status}${extra}`;
57
70
  }
58
71
 
72
+ // Below this width (px) the radar uses its compact card layout: actions under the text.
73
+ const NARROW_PANE_WIDTH = 640;
74
+
59
75
  export function PrRadar({
60
76
  theme,
61
- layout,
77
+ layout: hostLayout,
62
78
  host,
63
79
  navigation,
64
80
  params = {},
@@ -66,6 +82,10 @@ export function PrRadar({
66
82
  const queryClient = useQueryClient();
67
83
  const acknowledgeUpdates = useRpc(acknowledgeViewerScope);
68
84
  const parsed = parseRadarParams(params);
85
+ // The host's compact flag follows the window, so a pane narrower than the window (the screen
86
+ // sits beside a sidebar) kept the wide card. Measure the radar's own width as well.
87
+ const [narrow, setNarrow] = useState(false);
88
+ const layout = { ...hostLayout, compact: hostLayout.compact || narrow };
69
89
  const [filter, setFilterState] = useState<RadarFilter | null>(parsed.filter);
70
90
  const [focusedPr, setFocusedPr] = useState<string | null>(parsed.pr);
71
91
  // Chips are local state: openScreen would push a new screen per tap. A chip press also ends PR focus.
@@ -80,10 +100,18 @@ export function PrRadar({
80
100
  ? (filter as SavedView)
81
101
  : null;
82
102
  const [windowDays, setWindowDays] = useState(30);
103
+ const [sortKey, setSortKey] = useState<SortKey>("attention");
83
104
  const [search, setSearch] = useState("");
84
105
  const [now, setNow] = useState(() => Date.now());
85
106
  const [openError, setOpenError] = useState<string | null>(null);
86
107
  const [actionNotice, setActionNotice] = useState<string | null>(null);
108
+ // A fresh object per copy re-arms the reset timer; the effect cleanup cancels it on re-copy and unmount.
109
+ const [copied, setCopied] = useState<{ id: string } | null>(null);
110
+ useEffect(() => {
111
+ if (!copied) return;
112
+ const timer = setTimeout(() => setCopied(null), 1500);
113
+ return () => clearTimeout(timer);
114
+ }, [copied]);
87
115
 
88
116
  const {
89
117
  paseo,
@@ -229,6 +257,7 @@ export function PrRadar({
229
257
  }),
230
258
  [activeOnly, now, rows, savedView, search, selected, focusedPr],
231
259
  );
260
+ const sortedRows = useMemo(() => sortRows(visibleRows, sortKey), [visibleRows, sortKey]);
232
261
 
233
262
  const styles = useMemo(() => {
234
263
  const gutter = layout.compact ? 14 : 24;
@@ -320,7 +349,9 @@ export function PrRadar({
320
349
  fontSize: 13,
321
350
  fontWeight: "700" as const,
322
351
  },
323
- chips: { flexDirection: "row" as const, flexWrap: "wrap" as const, gap: 7 },
352
+ // Filter chips stay on one line and scroll sideways instead of wrapping.
353
+ chipScroller: { flexGrow: 0 },
354
+ chipRow: { flexDirection: "row" as const, gap: 7, paddingRight: 6 },
324
355
  chip: {
325
356
  minHeight: 32,
326
357
  justifyContent: "center" as const,
@@ -357,6 +388,7 @@ export function PrRadar({
357
388
  },
358
389
  warningText: { color: theme.colors.foregroundMuted, fontSize: 12, lineHeight: 17 },
359
390
  row: {
391
+ position: "relative" as const,
360
392
  flexDirection: "row" as const,
361
393
  marginHorizontal: gutter,
362
394
  borderTopWidth: 1,
@@ -370,7 +402,22 @@ export function PrRadar({
370
402
  paddingLeft: 12,
371
403
  gap: 6,
372
404
  },
373
- rowTop: { flexDirection: "row" as const, alignItems: "center" as const, gap: 8 },
405
+ rowTop: {
406
+ flexDirection: "row" as const,
407
+ alignItems: "center" as const,
408
+ gap: 8,
409
+ paddingRight: 80,
410
+ },
411
+ copyButton: {
412
+ position: "absolute" as const,
413
+ top: 10,
414
+ right: 0,
415
+ minHeight: 28,
416
+ justifyContent: "center" as const,
417
+ paddingHorizontal: 8,
418
+ borderRadius: 6,
419
+ },
420
+ copyText: { color: theme.colors.foregroundMuted, fontSize: 11, fontWeight: "600" as const },
374
421
  identifier: {
375
422
  color: theme.colors.foregroundMuted,
376
423
  fontSize: 11,
@@ -452,6 +499,18 @@ export function PrRadar({
452
499
  }
453
500
  }, []);
454
501
 
502
+ const copyPrLink = useCallback(async (row: RadarRow) => {
503
+ setOpenError(null);
504
+ setCopied(null);
505
+ try {
506
+ await copyText(row.url);
507
+ setOpenError(null);
508
+ setCopied({ id: row.id });
509
+ } catch {
510
+ setOpenError(`Could not copy the link for ${row.repository}#${row.number ?? "PR"}.`);
511
+ }
512
+ }, []);
513
+
455
514
  const renderRow = ({ item }: { item: RadarRow }) => {
456
515
  const color = bucketColor(item.bucket, theme.colors);
457
516
  const age = formatAge(item.activityAt, now);
@@ -576,6 +635,16 @@ export function PrRadar({
576
635
  {layout.compact ? actions : null}
577
636
  </View>
578
637
  {layout.compact ? null : actions}
638
+ <Pressable
639
+ accessibilityRole="button"
640
+ accessibilityLabel={`Copy link to pull request ${item.repository} ${item.number ?? ""}`}
641
+ onPress={() => void copyPrLink(item)}
642
+ style={({ pressed }) => [styles.copyButton, pressed && styles.refreshPressed]}
643
+ >
644
+ <Text style={styles.copyText} accessibilityLiveRegion="polite">
645
+ {copied?.id === item.id ? "Copied" : "Copy link"}
646
+ </Text>
647
+ </Pressable>
579
648
  </View>
580
649
  );
581
650
  };
@@ -634,7 +703,14 @@ export function PrRadar({
634
703
  </View>
635
704
  ))}
636
705
  </View>
637
- <View accessibilityRole="tablist" style={styles.chips}>
706
+ <ScrollView
707
+ accessibilityRole="tablist"
708
+ horizontal
709
+ onFocus={revealFocusedChip}
710
+ showsHorizontalScrollIndicator={false}
711
+ style={styles.chipScroller}
712
+ contentContainerStyle={styles.chipRow}
713
+ >
638
714
  <Pressable
639
715
  accessibilityRole="tab"
640
716
  accessibilityState={{
@@ -704,7 +780,7 @@ export function PrRadar({
704
780
  </Text>
705
781
  </Pressable>
706
782
  ))}
707
- </View>
783
+ </ScrollView>
708
784
  <TextInput
709
785
  accessibilityLabel="Filter pull requests"
710
786
  autoCapitalize="none"
@@ -715,6 +791,7 @@ export function PrRadar({
715
791
  style={styles.search}
716
792
  value={search}
717
793
  />
794
+ <SortControls sortKey={sortKey} onSort={setSortKey} styles={styles} />
718
795
  {viewerData ? (
719
796
  <View style={{ gap: 7 }}>
720
797
  <Text style={styles.heroDetail}>
@@ -761,10 +838,13 @@ export function PrRadar({
761
838
  );
762
839
 
763
840
  return (
764
- <View style={styles.screen}>
841
+ <View
842
+ style={styles.screen}
843
+ onLayout={(event) => setNarrow(event.nativeEvent.layout.width < NARROW_PANE_WIDTH)}
844
+ >
765
845
  <FlatList
766
846
  contentContainerStyle={styles.content}
767
- data={visibleRows}
847
+ data={sortedRows}
768
848
  keyExtractor={(item) => item.id}
769
849
  ListHeaderComponent={header}
770
850
  ListEmptyComponent={
package/client/radar.ts CHANGED
@@ -559,6 +559,55 @@ export function applyViewerScope(
559
559
  return result;
560
560
  }
561
561
 
562
+ export const SORT_KEYS = ["attention", "mergeable", "recent", "oldest", "repository"] as const;
563
+ export type SortKey = (typeof SORT_KEYS)[number];
564
+
565
+ export const SORT_TITLES: Record<SortKey, string> = {
566
+ mergeable: "Mergeable first",
567
+ attention: "Needs attention first",
568
+ recent: "Recently updated",
569
+ oldest: "Oldest first",
570
+ repository: "Repository",
571
+ };
572
+
573
+ // Unknown or unparsable activity counts as the epoch (the oldest), which keeps the order total.
574
+ const activityOf = (row: RadarRow) => Date.parse(row.activityAt ?? "") || 0;
575
+ const oldestFirst = (left: RadarRow, right: RadarRow) =>
576
+ activityOf(left) - activityOf(right) || left.title.localeCompare(right.title);
577
+ const newestFirst = (left: RadarRow, right: RadarRow) =>
578
+ activityOf(right) - activityOf(left) || left.title.localeCompare(right.title);
579
+
580
+ /** Orders rows for display. Returns a new array; the input order is the bucket order. */
581
+ export function sortRows(rows: readonly RadarRow[], key: SortKey): RadarRow[] {
582
+ const sorted = [...rows];
583
+ switch (key) {
584
+ case "mergeable":
585
+ // classifyRow only yields "ready" for the viewer's own, non-draft, mergeable PRs.
586
+ return sorted.sort(
587
+ (left, right) =>
588
+ Number(right.bucket === "ready") - Number(left.bucket === "ready") ||
589
+ BUCKET_ORDER[left.bucket] - BUCKET_ORDER[right.bucket] ||
590
+ newestFirst(left, right),
591
+ );
592
+ case "attention":
593
+ // The default: the order applyViewerScope produces, longest waiting first within a bucket.
594
+ return sorted.sort(
595
+ (left, right) =>
596
+ BUCKET_ORDER[left.bucket] - BUCKET_ORDER[right.bucket] || oldestFirst(left, right),
597
+ );
598
+ case "recent":
599
+ return sorted.sort(newestFirst);
600
+ case "oldest":
601
+ return sorted.sort(oldestFirst);
602
+ case "repository":
603
+ return sorted.sort(
604
+ (left, right) =>
605
+ left.repository.localeCompare(right.repository) ||
606
+ (left.number ?? 0) - (right.number ?? 0),
607
+ );
608
+ }
609
+ }
610
+
562
611
  export function matchesRow(row: RadarRow, needle: string): boolean {
563
612
  const query = needle.trim().toLowerCase();
564
613
  if (!query) return true;
@@ -0,0 +1,86 @@
1
+ import {
2
+ Platform,
3
+ Pressable,
4
+ type StyleProp,
5
+ Text,
6
+ type TextStyle,
7
+ View,
8
+ type ViewStyle,
9
+ } from "react-native";
10
+ import { SORT_KEYS, SORT_TITLES, type SortKey } from "./radar";
11
+
12
+ interface SortControlsProps {
13
+ sortKey: SortKey;
14
+ onSort: (key: SortKey) => void;
15
+ styles: {
16
+ chip: StyleProp<ViewStyle>;
17
+ chipActive: StyleProp<ViewStyle>;
18
+ chipText: StyleProp<TextStyle>;
19
+ chipTextActive: StyleProp<TextStyle>;
20
+ };
21
+ }
22
+
23
+ // The host's React Native Web forwards this DOM event; native RN does not declare it.
24
+ export interface RadioKeyEvent {
25
+ key: string;
26
+ target: unknown;
27
+ currentTarget: {
28
+ parentElement: { querySelectorAll(selector: string): ArrayLike<{ focus(): void }> } | null;
29
+ };
30
+ preventDefault(): void;
31
+ }
32
+
33
+ const rowStyle: ViewStyle = { flexDirection: "row", flexWrap: "wrap", gap: 7 };
34
+
35
+ export function SortControls({ sortKey, onSort, styles }: SortControlsProps) {
36
+ const isWeb = Platform.OS === "web";
37
+ return (
38
+ <View accessibilityRole="radiogroup" accessibilityLabel="Sort pull requests" style={rowStyle}>
39
+ <Text style={[styles.chipText, { alignSelf: "center" }]}>Sort</Text>
40
+ {SORT_KEYS.map((key, index) => (
41
+ <Pressable
42
+ accessibilityRole="radio"
43
+ accessibilityState={{ checked: sortKey === key }}
44
+ aria-checked={sortKey === key}
45
+ key={key}
46
+ tabIndex={isWeb ? (sortKey === key ? 0 : -1) : undefined}
47
+ {...(isWeb
48
+ ? {
49
+ onKeyDown: (event: RadioKeyEvent) => {
50
+ if (event.target !== event.currentTarget) return;
51
+ let next = index;
52
+ switch (event.key) {
53
+ case " ":
54
+ break;
55
+ case "ArrowRight":
56
+ case "ArrowDown":
57
+ next = (index + 1) % SORT_KEYS.length;
58
+ break;
59
+ case "ArrowLeft":
60
+ case "ArrowUp":
61
+ next = (index + SORT_KEYS.length - 1) % SORT_KEYS.length;
62
+ break;
63
+ default:
64
+ return;
65
+ }
66
+ event.preventDefault();
67
+ if (SORT_KEYS[next] !== sortKey) onSort(SORT_KEYS[next]);
68
+ if (next !== index) {
69
+ event.currentTarget.parentElement
70
+ ?.querySelectorAll('[role="radio"]')
71
+ [next]?.focus();
72
+ }
73
+ },
74
+ }
75
+ : {})}
76
+ onPress={() => onSort(key)}
77
+ style={[styles.chip, sortKey === key && styles.chipActive]}
78
+ >
79
+ <Text style={[styles.chipText, sortKey === key && styles.chipTextActive]}>
80
+ {SORT_TITLES[key]}
81
+ </Text>
82
+ </Pressable>
83
+ ))}
84
+ </View>
85
+ );
86
+ }
@@ -44,8 +44,10 @@ export function useRadar(hostId: string, windowDays = 30, live = true) {
44
44
  queryKey: ["pr-radar-viewer-scope", hostId, scopeUrls, windowDays],
45
45
  queryFn: () => resolveViewerScope({ urls: scopeUrls, windowDays }),
46
46
  enabled: Boolean(directory.data),
47
- staleTime: 5 * 60_000,
48
- refetchInterval: live ? 5 * 60_000 : false,
47
+ // The server answers from its background cache, so polling is cheap; this only picks up
48
+ // what the server's own refresh loop (every 2 min) has already fetched.
49
+ staleTime: 30_000,
50
+ refetchInterval: live ? 60_000 : false,
49
51
  });
50
52
  useEffect(() => {
51
53
  if (!live) return;
package/client/web.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { Platform, type ScrollViewProps } from "react-native";
2
+
3
+ export const revealFocusedChip: NonNullable<ScrollViewProps["onFocus"]> = (event) => {
4
+ if (Platform.OS !== "web") return;
5
+
6
+ const target = event.target as unknown as {
7
+ scrollIntoView(options: { block: "nearest"; inline: "nearest" }): void;
8
+ };
9
+ target.scrollIntoView({ block: "nearest", inline: "nearest" });
10
+ };
package/index.server.ts CHANGED
@@ -1,9 +1,15 @@
1
1
  import type { PluginServerContext } from "@getpaseo/plugin/server";
2
- import { acknowledgeViewerUpdates, resolveViewerScope } from "./server/viewer-scope";
2
+ import {
3
+ acknowledgeViewerUpdates,
4
+ resolveViewerScope,
5
+ startBackgroundRefresh,
6
+ } from "./server/viewer-scope";
3
7
  import { acknowledgeViewerScope, viewerScope } from "./shared/viewer-scope";
4
8
 
5
9
  export default function contribute(server: PluginServerContext) {
6
10
  server.handle(viewerScope, resolveViewerScope);
7
11
  server.handle(acknowledgeViewerScope, acknowledgeViewerUpdates);
8
- return () => {};
12
+ // Keep GitHub data warm so opening the radar never waits on gh.
13
+ const stop = startBackgroundRefresh();
14
+ return () => stop();
9
15
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-pr-radar",
3
- "version": "3.0.1",
3
+ "version": "3.1.0",
4
4
  "type": "module",
5
5
  "description": "A viewer-aware delivery queue for pull requests linked to Paseo workspaces.",
6
6
  "license": "MIT",
@@ -0,0 +1,27 @@
1
+ const TRANSITION = /^(.+?): (.+) → (.+)$/;
2
+
3
+ /**
4
+ * Reports each field's net change from its first recorded origin to its trustworthy current value.
5
+ * Legacy pending lists deduplicate repeated transitions, so their last entry is not the latest state.
6
+ */
7
+ export function mergeChanges(
8
+ pending: string[],
9
+ detected: string[],
10
+ current: Readonly<Record<string, string | undefined>>,
11
+ ): string[] {
12
+ const merged: string[] = [];
13
+ const seen = new Set<string>();
14
+ for (const change of [...pending, ...detected]) {
15
+ const next = TRANSITION.exec(change);
16
+ const to = next ? current[next[1]] : undefined;
17
+ if (!next || typeof to !== "string") {
18
+ if (!merged.includes(change)) merged.push(change);
19
+ continue;
20
+ }
21
+ const [, label, from] = next;
22
+ if (seen.has(label)) continue;
23
+ seen.add(label);
24
+ if (from !== to) merged.push(`${label}: ${from} → ${to}`);
25
+ }
26
+ return merged;
27
+ }
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import type { z } from "zod";
7
7
  import type { acknowledgeViewerScope, GitHubInboxItem, viewerScope } from "../shared/viewer-scope";
8
+ import { mergeChanges } from "./changes";
8
9
 
9
10
  const execFileAsync = promisify(execFile);
10
11
  const SEARCH_LIMIT = 100;
@@ -291,14 +292,35 @@ async function readState(): Promise<StoredState> {
291
292
  return { version: 2, windows: {} };
292
293
  }
293
294
 
295
+ let writeSequence = 0;
296
+
294
297
  async function writeState(state: StoredState): Promise<void> {
295
298
  const path = statePath();
296
299
  await mkdir(dirname(path), { recursive: true });
297
- const temporaryPath = `${path}.${process.pid}.tmp`;
300
+ // Unique per write: overlapping writes must not rename each other's temp file away.
301
+ const temporaryPath = `${path}.${process.pid}.${++writeSequence}.tmp`;
298
302
  await writeFile(temporaryPath, `${JSON.stringify(state)}\n`, { mode: 0o600 });
299
303
  await rename(temporaryPath, path);
300
304
  }
301
305
 
306
+ let stateQueue: Promise<unknown> = Promise.resolve();
307
+
308
+ /**
309
+ * Serialises read-modify-write cycles on the state file. The change callback runs inside the
310
+ * queue after a fresh read, so a slow GitHub refresh cannot overwrite an acknowledgement made
311
+ * while it was in flight.
312
+ */
313
+ function updateState<T>(change: (state: StoredState) => T): Promise<T> {
314
+ const run = stateQueue.then(async () => {
315
+ const state = await readState();
316
+ const result = change(state);
317
+ await writeState(state);
318
+ return result;
319
+ });
320
+ stateQueue = run.catch(() => undefined);
321
+ return run;
322
+ }
323
+
302
324
  function storedItem(item: GitHubInboxItem): StoredItem {
303
325
  return {
304
326
  updatedAt: item.updatedAt,
@@ -330,41 +352,68 @@ function detectChanges(previous: StoredItem | undefined, item: GitHubInboxItem):
330
352
  return [...changes];
331
353
  }
332
354
 
333
- export async function resolveViewerScope({
334
- urls,
335
- windowDays,
336
- }: z.output<typeof viewerScope.input>): Promise<z.input<typeof viewerScope.output>> {
337
- try {
338
- const viewer = await viewerLogin();
339
- const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000)
340
- .toISOString()
341
- .slice(0, 10);
342
- const [authored, reviewRequested, authoredScope, reviewRequestedScope, stored] =
343
- await Promise.all([
344
- searchPullRequests("author", viewer, since),
345
- searchPullRequests("review-requested", viewer, since),
346
- searchScopeUrls("author"),
347
- searchScopeUrls("review-requested"),
348
- readState(),
349
- ]);
350
- const records = new Map<string, { record: SearchRecord; role: GitHubInboxItem["role"] }>();
351
- for (const record of reviewRequested) records.set(record.id, { record, role: "reviewer" });
352
- for (const record of authored) records.set(record.id, { record, role: "author" });
353
- const enrichment = await enrich([...records.keys()]);
354
- const inboxItems = [...records.values()].map(({ record, role }) =>
355
- toInboxItem(record, role, enrichment.states.get(record.id)),
356
- );
355
+ type ViewerScopeOutput = z.input<typeof viewerScope.output>;
357
356
 
358
- const key = String(windowDays);
357
+ /** Everything one GitHub refresh learns for a window; independent of the URLs a client asks about. */
358
+ interface Snapshot {
359
+ viewer: string;
360
+ authored: SearchRecord[];
361
+ reviewRequested: SearchRecord[];
362
+ authoredScope: string[];
363
+ reviewRequestedScope: string[];
364
+ inboxItems: GitHubInboxItem[];
365
+ enrichmentFailures: number;
366
+ acknowledgedAt: string | null;
367
+ }
368
+
369
+ /** The expensive part: ~5 s of gh searches and GraphQL enrichment. */
370
+ async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
371
+ const viewer = await viewerLogin();
372
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000).toISOString().slice(0, 10);
373
+ const [authored, reviewRequested, authoredScope, reviewRequestedScope] = await Promise.all([
374
+ searchPullRequests("author", viewer, since),
375
+ searchPullRequests("review-requested", viewer, since),
376
+ searchScopeUrls("author"),
377
+ searchScopeUrls("review-requested"),
378
+ ]);
379
+ const records = new Map<string, { record: SearchRecord; role: GitHubInboxItem["role"] }>();
380
+ for (const record of reviewRequested) records.set(record.id, { record, role: "reviewer" });
381
+ for (const record of authored) records.set(record.id, { record, role: "author" });
382
+ const enrichment = await enrich([...records.keys()]);
383
+ const inboxItems = [...records.values()].map(({ record, role }) =>
384
+ toInboxItem(record, role, enrichment.states.get(record.id)),
385
+ );
386
+
387
+ // Change tracking reads the state only now, after the slow GitHub work, inside the queue.
388
+ const key = String(windowDays);
389
+ const acknowledgedAt = await updateState((stored) => {
359
390
  const previous = stored.windows[key] ?? { items: {}, pendingChanges: {}, acknowledgedAt: null };
360
391
  const initialized = Object.keys(previous.items).length > 0;
361
392
  const nextItems: Record<string, StoredItem> = {};
362
393
  const nextPending: Record<string, string[]> = {};
363
394
  for (const item of inboxItems) {
364
395
  const prior = previous.items[item.id];
396
+ const state = enrichment.states.get(item.id);
365
397
  const detected =
366
398
  initialized && (!prior || enrichment.states.has(item.id)) ? detectChanges(prior, item) : [];
367
- item.changes = [...new Set([...(previous.pendingChanges[item.id] ?? []), ...detected])];
399
+ item.changes = mergeChanges(previous.pendingChanges[item.id] ?? [], detected, {
400
+ Checks:
401
+ state?.statusCheckRollup === null || item.checksStatus !== "none"
402
+ ? item.checksStatus
403
+ : undefined,
404
+ Review:
405
+ state?.reviewDecision === null || item.reviewDecision !== null
406
+ ? (item.reviewDecision ?? "none")
407
+ : undefined,
408
+ Mergeable:
409
+ item.mergeable === "MERGEABLE" || item.mergeable === "CONFLICTING"
410
+ ? item.mergeable.toLowerCase()
411
+ : undefined,
412
+ "Merge state":
413
+ item.mergeStateStatus && item.mergeStateStatus.toUpperCase() !== "UNKNOWN"
414
+ ? item.mergeStateStatus
415
+ : undefined,
416
+ });
368
417
  nextItems[item.id] = prior && !enrichment.states.has(item.id) ? prior : storedItem(item);
369
418
  if (item.changes.length > 0) nextPending[item.id] = item.changes;
370
419
  }
@@ -373,58 +422,175 @@ export async function resolveViewerScope({
373
422
  pendingChanges: nextPending,
374
423
  acknowledgedAt: previous.acknowledgedAt,
375
424
  };
376
- await writeState(stored);
377
-
378
- const requestedUrls = new Set(urls.map((url) => url.toLowerCase()));
379
- const authoredUrls = new Set([
380
- ...authored.map(({ url }) => url),
381
- ...authoredScope.filter((url) => requestedUrls.has(url.toLowerCase())),
382
- ]);
383
- const reviewRequestedUrls = new Set([
384
- ...reviewRequested.map(({ url }) => url),
385
- ...reviewRequestedScope.filter((url) => requestedUrls.has(url.toLowerCase())),
386
- ]);
387
- const coverageNote =
388
- enrichment.failures > 0
389
- ? `${enrichment.failures} GitHub detail request${enrichment.failures === 1 ? "" : "s"} failed; affected PRs use conservative states.`
390
- : `Open PRs visible to the GitHub CLI. Organization SSO restrictions may omit results.`;
391
- return {
392
- viewer,
393
- authoredUrls: [...authoredUrls],
394
- reviewRequestedUrls: [...reviewRequestedUrls],
395
- inboxItems,
396
- truncated: authored.length === SEARCH_LIMIT || reviewRequested.length === SEARCH_LIMIT,
397
- coverageNote,
398
- updates: inboxItems.filter(({ changes }) => changes.length > 0).length,
399
- acknowledgedAt: previous.acknowledgedAt,
400
- error: null,
401
- };
425
+ return previous.acknowledgedAt;
426
+ });
427
+
428
+ return {
429
+ viewer,
430
+ authored,
431
+ reviewRequested,
432
+ authoredScope,
433
+ reviewRequestedScope,
434
+ inboxItems,
435
+ enrichmentFailures: enrichment.failures,
436
+ acknowledgedAt,
437
+ };
438
+ }
439
+
440
+ /** The cheap part: shape a snapshot for the URLs this client knows about. */
441
+ export function projectSnapshot(snapshot: Snapshot, urls: string[]): ViewerScopeOutput {
442
+ const requestedUrls = new Set(urls.map((url) => url.toLowerCase()));
443
+ const withScope = (direct: SearchRecord[], scope: string[]) => [
444
+ ...new Set([
445
+ ...direct.map(({ url }) => url),
446
+ ...scope.filter((url) => requestedUrls.has(url.toLowerCase())),
447
+ ]),
448
+ ];
449
+ const coverageNote =
450
+ snapshot.enrichmentFailures > 0
451
+ ? `${snapshot.enrichmentFailures} GitHub detail request${snapshot.enrichmentFailures === 1 ? "" : "s"} failed; affected PRs use conservative states.`
452
+ : `Open PRs visible to the GitHub CLI. Organization SSO restrictions may omit results.`;
453
+ return {
454
+ viewer: snapshot.viewer,
455
+ authoredUrls: withScope(snapshot.authored, snapshot.authoredScope),
456
+ reviewRequestedUrls: withScope(snapshot.reviewRequested, snapshot.reviewRequestedScope),
457
+ inboxItems: snapshot.inboxItems,
458
+ truncated:
459
+ snapshot.authored.length === SEARCH_LIMIT || snapshot.reviewRequested.length === SEARCH_LIMIT,
460
+ coverageNote,
461
+ updates: snapshot.inboxItems.filter(({ changes }) => changes.length > 0).length,
462
+ acknowledgedAt: snapshot.acknowledgedAt,
463
+ error: null,
464
+ };
465
+ }
466
+
467
+ function errorOutput(error: unknown): ViewerScopeOutput {
468
+ return {
469
+ viewer: null,
470
+ authoredUrls: [],
471
+ reviewRequestedUrls: [],
472
+ inboxItems: [],
473
+ truncated: false,
474
+ coverageNote: "GitHub inbox data is unavailable.",
475
+ updates: 0,
476
+ acknowledgedAt: null,
477
+ error: error instanceof Error ? error.message : "GitHub viewer scope is unavailable.",
478
+ };
479
+ }
480
+
481
+ // ---------------------------------------------------------------------------
482
+ // Background cache. The plugin's server process is long-lived, so it keeps the last snapshot per
483
+ // window and refreshes it on a timer; client requests are answered from memory.
484
+ // ---------------------------------------------------------------------------
485
+
486
+ export const BACKGROUND_INTERVAL_MS = 2 * 60_000;
487
+ /** A request older than this triggers a refresh in the background (still answered from cache). */
488
+ export const STALE_AFTER_MS = 60_000;
489
+ /**
490
+ * A snapshot older than this is not served: a refresh that keeps failing (auth lost, rate limited)
491
+ * is reported instead of hiding behind old data. Entries are bounded by the 365 possible windows.
492
+ */
493
+ export const MAX_STALE_MS = 3 * BACKGROUND_INTERVAL_MS;
494
+ /** Windows nobody has asked about for this long stop being refreshed, so an unused radar costs no GitHub calls. */
495
+ const WINDOW_IDLE_MS = 30 * 60_000;
496
+ /** Warmed at startup so the first open of the radar does not wait on GitHub. */
497
+ const DEFAULT_WINDOW_DAYS = 30;
498
+
499
+ const snapshots = new Map<number, { snapshot: Snapshot; at: number }>();
500
+ const inflight = new Map<number, Promise<Snapshot>>();
501
+ const lastRequested = new Map<number, number>([[DEFAULT_WINDOW_DAYS, Date.now()]]);
502
+
503
+ /** Single-flight refresh: concurrent callers share one GitHub sweep. */
504
+ function refreshWindow(windowDays: number): Promise<Snapshot> {
505
+ const running = inflight.get(windowDays);
506
+ if (running) return running;
507
+ const started = Date.now();
508
+ const promise = fetchSnapshot(windowDays)
509
+ .then((snapshot) => {
510
+ snapshots.set(windowDays, { snapshot, at: Date.now() });
511
+ console.log(
512
+ `PR Radar: refreshed ${windowDays}d window in ${((Date.now() - started) / 1000).toFixed(1)}s (${snapshot.inboxItems.length} PRs)`,
513
+ );
514
+ return snapshot;
515
+ })
516
+ .finally(() => inflight.delete(windowDays));
517
+ inflight.set(windowDays, promise);
518
+ return promise;
519
+ }
520
+
521
+ function refreshInBackground(windowDays: number): void {
522
+ refreshWindow(windowDays).catch((error) => {
523
+ // Keep serving the last good snapshot until it passes MAX_STALE_MS.
524
+ console.error(`PR Radar: background refresh of ${windowDays}d window failed`, error);
525
+ });
526
+ }
527
+
528
+ /** Starts the refresh timer; returns a stop function for the plugin's cleanup. */
529
+ export function startBackgroundRefresh(intervalMs = BACKGROUND_INTERVAL_MS): () => void {
530
+ const tick = () => {
531
+ const now = Date.now();
532
+ for (const [windowDays, requestedAt] of lastRequested) {
533
+ if (now - requestedAt > WINDOW_IDLE_MS) {
534
+ lastRequested.delete(windowDays);
535
+ continue;
536
+ }
537
+ refreshInBackground(windowDays);
538
+ }
539
+ };
540
+ tick();
541
+ const timer = setInterval(tick, intervalMs);
542
+ timer.unref?.();
543
+ return () => clearInterval(timer);
544
+ }
545
+
546
+ export async function resolveViewerScope({
547
+ urls,
548
+ windowDays,
549
+ }: z.output<typeof viewerScope.input>): Promise<ViewerScopeOutput> {
550
+ lastRequested.set(windowDays, Date.now());
551
+ const cached = snapshots.get(windowDays);
552
+ if (cached && Date.now() - cached.at <= MAX_STALE_MS) {
553
+ if (Date.now() - cached.at > STALE_AFTER_MS) refreshInBackground(windowDays);
554
+ return projectSnapshot(cached.snapshot, urls);
555
+ }
556
+ // First request for this window, or its snapshot expired: wait once.
557
+ try {
558
+ return projectSnapshot(await refreshWindow(windowDays), urls);
402
559
  } catch (error) {
403
560
  console.error("PR Radar GitHub inbox refresh failed", error);
404
- return {
405
- viewer: null,
406
- authoredUrls: [],
407
- reviewRequestedUrls: [],
408
- inboxItems: [],
409
- truncated: false,
410
- coverageNote: "GitHub inbox data is unavailable.",
411
- updates: 0,
412
- acknowledgedAt: null,
413
- error: error instanceof Error ? error.message : "GitHub viewer scope is unavailable.",
414
- };
561
+ return errorOutput(error);
415
562
  }
416
563
  }
417
564
 
565
+ /** Test seam: waits for running refreshes so tests do not bleed into each other. */
566
+ export async function resetViewerScopeCache(): Promise<void> {
567
+ await Promise.allSettled([...inflight.values()]);
568
+ await stateQueue;
569
+ snapshots.clear();
570
+ inflight.clear();
571
+ lastRequested.clear();
572
+ lastRequested.set(DEFAULT_WINDOW_DAYS, Date.now());
573
+ }
574
+
418
575
  export async function acknowledgeViewerUpdates({
419
576
  windowDays,
420
577
  }: z.output<typeof acknowledgeViewerScope.input>): Promise<
421
578
  z.input<typeof acknowledgeViewerScope.output>
422
579
  > {
423
- const state = await readState();
424
580
  const key = String(windowDays);
425
581
  const acknowledgedAt = new Date().toISOString();
426
- const current = state.windows[key] ?? { items: {}, pendingChanges: {}, acknowledgedAt: null };
427
- state.windows[key] = { ...current, pendingChanges: {}, acknowledgedAt };
428
- await writeState(state);
582
+ await updateState((state) => {
583
+ const current = state.windows[key] ?? { items: {}, pendingChanges: {}, acknowledgedAt: null };
584
+ state.windows[key] = { ...current, pendingChanges: {}, acknowledgedAt };
585
+ });
586
+ // Keep the cached snapshot in step so the badge clears without waiting for a refresh.
587
+ const cached = snapshots.get(windowDays);
588
+ if (cached) {
589
+ cached.snapshot = {
590
+ ...cached.snapshot,
591
+ acknowledgedAt,
592
+ inboxItems: cached.snapshot.inboxItems.map((item) => ({ ...item, changes: [] })),
593
+ };
594
+ }
429
595
  return { acknowledgedAt };
430
596
  }