Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2928 lines (2716 loc) · 119 KB
/
Copy pathapp.js
File metadata and controls
2928 lines (2716 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/* Pingboard — a board for the pull requests you are shepherding through CI.
Static, no build step: talks to the GitHub API straight from the browser.
Sections
1. constants + utils
2. state + persistence
3. github api
4. PR model (checks, CI summary, failure evidence)
5. refresh scheduler
6. board operations (pins, groups, cursor)
7. actions (comments, update branch, labels, review, merge)
8. rendering
9. modals
10. keyboard + boot */
/* ── 1. constants + utils ──────────────────────────────────────────────── */
const TOKEN_KEY = "pingboard.githubToken";
const SESSION_KEY = "pingboard.sessionToken";
const API_ROOT = "https://api.github.com";
const API_VERSION = "2022-11-28";
const DEFAULT_REPO = "vllm-project/vllm";
const REFRESH_CONCURRENCY = 4;
const REFRESH_BATCH = 10; // PRs read per GraphQL request
const TICK_MS = 15 * 1000;
const CLOSED_TTL_S = 15 * 60; // merged/closed PRs barely change
const HIDDEN_SLOWDOWN = 5; // background tabs poll this much slower
const BASELINE_TTL_MS = 10 * 60 * 1000;
const BASELINE_COMMITS = 30; // recent base-branch commits scanned for failing jobs
const LABELS_TTL_MS = 24 * 60 * 60 * 1000;
const ACTION_DELAY = 3000; // ms before a comment / branch update is sent
const BOARD_WIDTH = 520; // default list width in px; the detail pane takes the rest
const BOARD_MIN = 280;
const DETAIL_MIN = 380;
const RATE_FLOOR = 150; // stop background polling below this many points
const GROUP_SEARCH_MS = 5 * 60 * 1000;
const UNPIN_CLOSED_MS = 24 * 60 * 60 * 1000;
const DISMISSED_MAX = 200; // unpinned search results remembered per group
/* Per-repo workflow knowledge. Anything not listed gets GENERIC_PROFILE. */
const REPO_PROFILES = {
"vllm-project/vllm": {
ciPrefix: "buildkite/", // only these checks count as "CI"; the rest are side checks
mainPipeline: "ci", // buildkite/<this>/… is the CI that gates merging; other pipelines are informational
ciCommands: { run: "/ci run", retry: "/ci retry", cancel: "/ci cancel", stale: "/ci run --allow-stale" },
quickLabels: ["ready", "verified"],
mergeMethod: "squash"
}
};
const GENERIC_PROFILE = { ciPrefix: null, mainPipeline: null, ciCommands: null, quickLabels: [], mergeMethod: "squash" };
const PROFILE_COMMAND_KEYS = ["run", "retry", "cancel", "stale"];
const MERGE_METHODS = new Set(["merge", "rebase", "squash"]);
function normalizeCommands(value, fallback) {
if (value === null) return null;
const source = value && typeof value === "object" ? value : fallback;
if (!source) return null;
const commands = Object.fromEntries(PROFILE_COMMAND_KEYS.map((key) => [key, typeof source[key] === "string" ? source[key].trim() : ""]));
return PROFILE_COMMAND_KEYS.some((key) => commands[key]) ? commands : null;
}
function normalizeProfile(raw, fallback = GENERIC_PROFILE) {
const value = raw && typeof raw === "object" ? raw : {};
const labels = Array.isArray(value.quickLabels)
? [...new Set(value.quickLabels.filter((label) => typeof label === "string").map((label) => label.trim()).filter(Boolean))]
: [...fallback.quickLabels];
return {
ciPrefix: typeof value.ciPrefix === "string" ? value.ciPrefix.trim() || null : fallback.ciPrefix,
mainPipeline: typeof value.mainPipeline === "string" ? value.mainPipeline.trim() || null : fallback.mainPipeline,
ciCommands: normalizeCommands(value.ciCommands, fallback.ciCommands),
quickLabels: labels,
mergeMethod: MERGE_METHODS.has(value.mergeMethod) ? value.mergeMethod : fallback.mergeMethod
};
}
function normalizeRepoProfiles(raw) {
if (!raw || typeof raw !== "object") return {};
const profiles = {};
for (const [repo, value] of Object.entries(raw)) {
if (/^[\w.-]+\/[\w.-]+$/.test(repo) && value && typeof value === "object") {
profiles[repo] = normalizeProfile(value, REPO_PROFILES[repo] || GENERIC_PROFILE);
}
}
return profiles;
}
function profileFor(repo) {
const base = REPO_PROFILES[repo] || GENERIC_PROFILE;
return normalizeProfile(state.prefs.repoProfiles?.[repo], base);
}
const store = {
get(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw === null ? fallback : JSON.parse(raw);
} catch {
return fallback;
}
},
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
/* quota or private mode: the board still works for this session */
}
}
};
function el(tag, props = {}, children = []) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value === undefined || value === null || value === false) continue;
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
else if (key === "style") node.style.cssText = value;
else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
else node.setAttribute(key, value === true ? "" : value);
}
for (const child of [].concat(children)) {
if (child !== null && child !== undefined && child !== false) node.append(child);
}
return node;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
function ago(value) {
if (!value) return "";
const seconds = Math.max(0, (Date.now() - new Date(value).getTime()) / 1000);
if (seconds < 60) return `${Math.floor(seconds)}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
return `${Math.floor(seconds / 86400)}d`;
}
function pinKey(repo, number) {
return `${repo}#${number}`;
}
function shortRef(repo, number) {
return repo === state.prefs.defaultRepo ? `#${number}` : `${repo}#${number}`;
}
/* URLs from the API end up in href / window.open; only ever follow web links. */
function safeUrl(url) {
return /^https?:\/\//.test(url || "") ? url : null;
}
function openUrl(url) {
if (safeUrl(url)) window.open(url, "_blank", "noopener");
}
/* "123", "#123", "owner/repo#123" or a PR URL; several may be pasted at once.
Returns null when the input is not purely PR references (i.e. it is a search). */
function parseRefs(raw) {
const refs = [];
for (const token of raw.trim().split(/[\s,]+/).filter(Boolean)) {
let match;
if ((match = token.match(/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/))) refs.push({ repo: match[1], number: Number(match[2]) });
else if ((match = token.match(/^([\w.-]+\/[\w.-]+)#(\d+)$/))) refs.push({ repo: match[1], number: Number(match[2]) });
else if ((match = token.match(/^#?(\d+)$/))) refs.push({ repo: state.prefs.defaultRepo, number: Number(match[1]) });
else return null;
}
return refs.length ? refs : null;
}
/* ── 2. state + persistence ────────────────────────────────────────────── */
const state = {
token: localStorage.getItem(TOKEN_KEY) || sessionStorage.getItem(SESSION_KEY) || "",
remember: Boolean(localStorage.getItem(TOKEN_KEY)),
user: null,
authLoading: false,
authError: "",
board: { groups: [], pins: [] }, // groups: [{id, name, collapsed, query?, dismissed?}]; pins: [{key, repo, number, group, addedAt, seen, seenActivity, via}]
prefs: { interval: 60, notify: false, defaultRepo: DEFAULT_REPO, boardWidth: BOARD_WIDTH, following: [], repoProfiles: {}, sort: "manual", filter: "all", owner: "all", unpinClosed: false },
data: new Map(), // pin key -> PR model
status: new Map(), // pin key -> {at, loading, error}
baselines: new Map(), // "repo@branch" -> {at, total, counts: Map(jobKey -> commits failing)}
commitFailures: new Map(), // "repo@oid" -> {hasCI, failed: [jobKey]} for finished base commits
labels: new Map(), // repo -> {at, items: [{name, color}]}
searches: new Map(), // group id -> {at, loading, error, missing: Set(pin key)}
cursor: null,
query: "",
modal: null,
pending: [], // deferred actions: [{id, label, timer}]
toasts: [],
seq: 0,
rate: { remaining: null, limit: null, reset: null },
lastSync: 0
};
function scopedKey(suffix) {
return `pingboard.v3.${state.user?.login || "anonymous"}.${suffix}`;
}
function normalizePrefs(raw) {
const prefs = raw && typeof raw === "object" ? raw : {};
return {
interval: [30, 60, 120, 300].includes(prefs.interval) ? prefs.interval : 60,
notify: Boolean(prefs.notify),
boardWidth: Number(prefs.boardWidth) || BOARD_WIDTH,
defaultRepo: /^[\w.-]+\/[\w.-]+$/.test(prefs.defaultRepo || "") ? prefs.defaultRepo : DEFAULT_REPO,
following: parseLogins(Array.isArray(prefs.following) ? prefs.following.join(" ") : ""),
repoProfiles: normalizeRepoProfiles(prefs.repoProfiles),
sort: SORTS.some((sort) => sort.id === prefs.sort) ? prefs.sort : "manual",
filter: FILTERS.some((filter) => filter.id === prefs.filter) ? prefs.filter : "all",
owner: OWNERS.some((owner) => owner.id === prefs.owner) ? prefs.owner : "all",
unpinClosed: Boolean(prefs.unpinClosed)
};
}
function loadUserState() {
state.prefs = normalizePrefs(store.get(scopedKey("prefs"), {}));
state.board = cleanBoard(store.get(scopedKey("board"), null)) || { groups: [{ id: "g1", name: "Tracking", collapsed: false }], pins: [] };
state.cursor = null;
}
/* Normalise a board read from storage or a backup file; null if it is not one. */
function cleanBoard(raw) {
if (!Array.isArray(raw?.groups) || !Array.isArray(raw.pins)) return null;
const groups = raw.groups
.filter((group) => group && typeof group.id === "string" && typeof group.name === "string" && group.name.trim())
.map((group) => ({
id: group.id,
name: group.name.trim(),
collapsed: Boolean(group.collapsed),
...(typeof group.query === "string" && group.query.trim() ? {
query: group.query.trim(),
dismissed: (Array.isArray(group.dismissed) ? group.dismissed : []).filter((key) => /^[\w.-]+\/[\w.-]+#\d+$/.test(key)).slice(-DISMISSED_MAX)
} : {})
}));
if (!groups.length) return null;
const seen = new Set();
const pins = [];
for (const pin of raw.pins) {
if (!pin || !/^[\w.-]+\/[\w.-]+$/.test(pin.repo || "") || !Number.isInteger(pin.number) || pin.number <= 0) continue;
const key = pinKey(pin.repo, pin.number);
if (seen.has(key)) continue;
seen.add(key);
pins.push({
key,
repo: pin.repo,
number: pin.number,
group: groups.some((group) => group.id === pin.group) ? pin.group : groups[0].id,
addedAt: Number(pin.addedAt) || Date.now(),
...(typeof pin.seen === "string" ? { seen: pin.seen } : {}),
...(typeof pin.seenActivity === "string" ? { seenActivity: pin.seenActivity } : {}),
...(groups.some((group) => group.id === pin.via) ? { via: pin.via } : {})
});
}
return { groups, pins };
}
/* Another tab saved the board: adopt it, so this tab never writes a stale copy back over it. */
function syncFromStorage(event) {
if (!state.user || event.storageArea !== localStorage) return;
if (event.key === scopedKey("board")) {
let board = null;
try {
board = cleanBoard(JSON.parse(event.newValue));
} catch {
/* unreadable: keep what this tab has */
}
if (!board) return;
state.board = board;
for (const key of [...state.data.keys()]) {
if (!pinByKey(key)) {
state.data.delete(key);
state.status.delete(key);
}
}
tick();
}
}
function exportBoard() {
const payload = {
pingboard: 1,
login: state.user.login,
exportedAt: new Date().toISOString(),
board: state.board,
// Deliberately copy only non-secret preferences; the GitHub token is never exported.
prefs: normalizePrefs(state.prefs)
};
const url = URL.createObjectURL(new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }));
el("a", { href: url, download: `pingboard-${state.user.login}.json` }).click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
async function importBoard(file) {
let board = null;
let prefs = null;
try {
const parsed = JSON.parse(await file.text());
board = cleanBoard(parsed.board || parsed);
if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "prefs")) {
prefs = normalizePrefs(parsed.prefs);
}
} catch {
/* handled below */
}
if (!board) return toast("That file is not a Pingboard backup", "error");
const count = `${board.pins.length} pull request${board.pins.length === 1 ? "" : "s"}`;
const applyPrefs = () => {
if (!prefs) return;
state.prefs = prefs;
persistPrefs();
applyBoardWidth();
};
openChoice({
title: `Import ${count}?`,
body: `From ${file.name}.${prefs ? " This backup includes non-secret preferences and repository profiles, but never your GitHub token." : ""} Adding keeps what is on your board now; replacing discards it.`,
options: [
{
key: "Enter",
label: "Add to my board",
run: () => {
const groupIds = new Map(board.groups.map((group) => {
const target = ensureGroup(group.name);
if (group.query && !target.query) Object.assign(target, { query: group.query, dismissed: group.dismissed });
return [group.id, target.id];
}));
const added = board.pins.filter((pin) => addPin(pin.repo, pin.number, groupIds.get(pin.group))).length;
applyPrefs();
toast(`Added ${added} of ${count}`, "ok");
render();
}
},
{
key: "r",
label: "Replace my board",
danger: true,
run: () => {
state.board = board;
state.data.clear();
state.status.clear();
persistBoard();
applyPrefs();
toast(`Board replaced with ${count}`, "ok");
tick();
}
}
]
});
}
/* Authors the user follows: highlighted wherever they appear, and a list in Add PRs. */
function parseLogins(text) {
const logins = [];
for (const token of text.split(/[\s,@]+/)) {
if (/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(token) && !logins.some((login) => login.toLowerCase() === token.toLowerCase())) logins.push(token);
}
return logins;
}
function isFollowed(login) {
return state.prefs.following.some((item) => item.toLowerCase() === String(login).toLowerCase());
}
function toggleFollow(login) {
const following = state.prefs.following;
state.prefs.following = isFollowed(login) ? following.filter((item) => item.toLowerCase() !== login.toLowerCase()) : following.concat(login);
persistPrefs();
render();
}
function authorName(login) {
return el("span", { class: `author${isFollowed(login) ? " followed" : ""}`, title: isFollowed(login) ? "You follow this author" : null, text: login });
}
function persistBoard() {
store.set(scopedKey("board"), state.board);
}
function persistPrefs() {
store.set(scopedKey("prefs"), state.prefs);
}
/* ── 3. github api ─────────────────────────────────────────────────────── */
function authHeaders() {
return {
Authorization: `Bearer ${state.token}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": API_VERSION
};
}
async function rest(method, path, body) {
const response = await fetch(`${API_ROOT}${path}`, {
method,
headers: { ...authHeaders(), ...(body ? { "Content-Type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined
});
if (response.status === 401) signOut("GitHub rejected the token.");
const text = await response.text();
let json = null;
try {
json = text ? JSON.parse(text) : null;
} catch {
/* non-JSON body */
}
if (!response.ok) throw new Error(json?.message || `${response.status} ${response.statusText}`);
return json;
}
async function gql(query, variables = {}, { strict = false, partial = false } = {}) {
const response = await fetch(`${API_ROOT}/graphql`, {
method: "POST",
headers: { ...authHeaders(), "Content-Type": "application/json" },
body: JSON.stringify({ query, variables })
});
const remaining = response.headers.get("x-ratelimit-remaining");
if (remaining !== null) {
state.rate = {
remaining: Number(remaining),
limit: Number(response.headers.get("x-ratelimit-limit")),
reset: Number(response.headers.get("x-ratelimit-reset")) * 1000
};
}
if (response.status === 401) signOut("GitHub rejected the token.");
const json = await response.json().catch(() => null);
// Reads tolerate partial errors (e.g. a ref that cannot be compared) because the
// rest of the data is usable; a mutation that reports any error did not happen.
if (!response.ok || !json?.data || (strict && json.errors?.length)) {
throw new Error(json?.errors?.[0]?.message || json?.message || `${response.status} ${response.statusText}`);
}
return partial ? { data: json.data, errors: json.errors || [] } : json.data;
}
const CONTEXT_FIELDS = `
__typename
... on StatusContext { context state description targetUrl createdAt }
... on CheckRun { name status conclusion detailsUrl startedAt checkSuite { app { slug } } }`;
const PR_FIELDS = `
fragment PullRequestFields on PullRequest {
id number title url state isDraft updatedAt closedAt
author { login } authorAssociation
baseRefName headRefOid
mergeable mergeStateStatus reviewDecision
viewerCanUpdateBranch
autoMergeRequest { enabledAt }
additions deletions changedFiles
labels(first: 40) { nodes { name color } }
latestOpinionatedReviews(first: 20) { nodes { state author { login } } }
reviewRequests(first: 100) { nodes { requestedReviewer { ... on User { isViewer } } } }
comments(last: 5) { nodes { author { login } bodyText createdAt url } }
reviews(last: 5) { nodes { author { login } submittedAt } }
commits(last: 1) { nodes { commit {
oid committedDate
statusCheckRollup { state contexts(first: 100) {
totalCount
statusContextCountsByState { state count }
checkRunCountsByState { state count }
pageInfo { hasNextPage endCursor }
nodes { ${CONTEXT_FIELDS} }
} }
} } }
}`;
/* Many PRs in one request, each under its own alias (pr0, pr1, …). */
function prsQuery(count) {
const at = [...Array(count).keys()];
const params = at.map((i) => `$owner${i}: String!, $name${i}: String!, $number${i}: Int!, $baseRef${i}: String!, $headRef${i}: String!`);
const fields = at.map((i) => `
pr${i}: repository(owner: $owner${i}, name: $name${i}) {
ref(qualifiedName: $baseRef${i}) { compare(headRef: $headRef${i}) { aheadBy behindBy } }
pullRequest(number: $number${i}) { ...PullRequestFields }
}`);
return `query(${params.join(", ")}) {${fields.join("")}\n}\n${PR_FIELDS}`;
}
const CONTEXTS_QUERY = `
query($owner: String!, $name: String!, $oid: GitObjectID!, $cursor: String) {
repository(owner: $owner, name: $name) {
object(oid: $oid) { ... on Commit { statusCheckRollup { contexts(first: 100, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes { ${CONTEXT_FIELDS} }
} } } }
}
}`;
const BASE_HISTORY_QUERY = `
query($owner: String!, $name: String!, $ref: String!, $count: Int!) {
repository(owner: $owner, name: $name) {
ref(qualifiedName: $ref) { target { ... on Commit { history(first: $count) {
nodes { oid statusCheckRollup { state } }
} } } }
}
}`;
const SEARCH_QUERY = `
query($query: String!) {
search(type: ISSUE, first: 30, query: $query) {
issueCount
nodes { ... on PullRequest {
number title isDraft updatedAt url
author { login }
reviewDecision
repository { nameWithOwner }
labels(first: 8) { nodes { name color } }
commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
} }
}
}`;
async function fetchContexts(owner, name, oid, cursor = null) {
const nodes = [];
for (let page = 0; page < 15; page += 1) {
const data = await gql(CONTEXTS_QUERY, { owner, name, oid, cursor });
const contexts = data.repository?.object?.statusCheckRollup?.contexts;
if (!contexts) break;
nodes.push(...contexts.nodes);
if (!contexts.pageInfo.hasNextPage) break;
cursor = contexts.pageInfo.endCursor;
}
return nodes;
}
/* ── 4. PR model ───────────────────────────────────────────────────────── */
const STATUS_STATES = { SUCCESS: "pass", FAILURE: "fail", ERROR: "fail", PENDING: "pending", EXPECTED: "pending" };
const CHECK_OK = new Set(["SUCCESS", "NEUTRAL", "SKIPPED"]);
/* Flatten statuses + check runs into one shape, newest entry per name.
Buildkite contexts look like buildkite/<pipeline>[/pr]/<job>; the bare
buildkite/<pipeline>[/pr] context is the build itself. Dropping the "pr"
segment makes job keys comparable between PR builds and base-branch builds. */
function normalizeChecks(nodes) {
const byName = new Map();
for (const node of nodes) {
if (!node) continue;
let check;
if (node.__typename === "StatusContext") {
check = { name: node.context, state: STATUS_STATES[node.state] || "pending", desc: node.description || "", url: safeUrl(node.targetUrl), at: node.createdAt };
} else if (node.__typename === "CheckRun") {
const done = node.status === "COMPLETED";
check = {
name: node.name,
state: !done ? "pending" : node.conclusion === "SUCCESS" ? "pass" : CHECK_OK.has(node.conclusion) ? "skip" : "fail",
desc: (done ? node.conclusion : node.status || "").toLowerCase().replace(/_/g, " "),
url: safeUrl(node.detailsUrl),
at: node.startedAt
};
} else {
continue;
}
const bk = check.name.match(/^buildkite\/([^/]+)(?:\/(.*))?$/);
if (bk) {
check.pipeline = bk[1];
check.job = (bk[2] || "").replace(/^pr(\/|$)/, "");
check.isBuild = !check.job;
check.jobKey = `${check.pipeline}/${check.job}`;
check.label = check.isBuild ? `${check.pipeline} build` : check.job;
} else {
check.jobKey = check.name;
check.label = check.name;
}
const prev = byName.get(check.name);
if (!prev || (check.at || "") >= (prev.at || "")) byName.set(check.name, check);
}
return [...byName.values()];
}
function isCiCheck(check, profile) {
if (!profile.ciPrefix) return true;
if (!check.name.startsWith(profile.ciPrefix)) return false;
return !profile.mainPipeline || check.pipeline === profile.mainPipeline;
}
/* A check from the CI system but not the gating pipeline (e.g. buildkite/amd-ci). */
function isAuxCheck(check, profile) {
return Boolean(profile.ciPrefix) && check.name.startsWith(profile.ciPrefix) && !isCiCheck(check, profile);
}
function summarizeCi(checks, profile) {
const ci = { state: "none", pass: 0, fail: 0, pending: 0, builds: [], failed: [], running: [], aux: [], other: { pass: 0, failed: [], running: [] } };
for (const check of checks) {
if (isAuxCheck(check, profile)) {
ci.aux.push(check);
continue;
}
if (!isCiCheck(check, profile)) {
if (check.state === "pass") ci.other.pass += 1;
else if (check.state === "fail") ci.other.failed.push(check);
else if (check.state === "pending") ci.other.running.push(check);
continue;
}
if (check.isBuild) {
ci.builds.push(check);
} else if (check.state === "fail") {
ci.fail += 1;
ci.failed.push(check);
} else if (check.state === "pending") {
ci.pending += 1;
ci.running.push(check);
} else if (check.state === "pass") {
ci.pass += 1;
}
}
const any = ci.builds.length + ci.pass + ci.fail + ci.pending > 0;
if (!any) ci.state = "none";
else if (ci.pending || ci.builds.some((build) => build.state === "pending")) ci.state = "running";
else if (ci.fail || ci.builds.some((build) => build.state === "fail")) ci.state = "failed";
else ci.state = "passed";
ci.failed.sort((a, b) => a.label.localeCompare(b.label));
ci.running.sort((a, b) => a.label.localeCompare(b.label));
return ci;
}
/* Each pin's repository (with its pullRequest), or the Error that kept it out:
GraphQL answers with partial data, and an error's path names its alias. */
async function loadPRs(pins, bases) {
const variables = {};
pins.forEach((pin, i) => {
const [owner, name] = pin.repo.split("/");
Object.assign(variables, {
[`owner${i}`]: owner, [`name${i}`]: name, [`number${i}`]: pin.number,
[`baseRef${i}`]: `refs/heads/${bases[i]}`, [`headRef${i}`]: `refs/pull/${pin.number}/head`
});
});
try {
const { data, errors } = await gql(prsQuery(pins.length), variables, { partial: true });
return pins.map((_, i) => {
if (data[`pr${i}`]?.pullRequest) return data[`pr${i}`];
// A missing PR also fails its compare; that error would be misleading.
const error = errors.find((entry) => entry.path?.[0] === `pr${i}` && entry.path[1] !== "ref");
return new Error(error?.message || "Pull request not found (or the token cannot see it)");
});
} catch (error) {
return pins.map(() => error);
}
}
/* Reads [{ pin, options }] in one request (two if a base branch moved); each
entry settles to its PR or its own Error. */
async function fetchPRs(entries) {
const pins = entries.map((entry) => entry.pin);
const bases = pins.map((pin) => state.data.get(pin.key)?.base || "main");
const repos = await loadPRs(pins, bases);
const moved = repos.flatMap((repo, i) => (!(repo instanceof Error) && repo.pullRequest.baseRefName !== bases[i] ? [i] : []));
if (moved.length) {
for (const i of moved) bases[i] = repos[i].pullRequest.baseRefName;
const again = await loadPRs(moved.map((i) => pins[i]), moved.map((i) => bases[i]));
moved.forEach((i, j) => (repos[i] = again[j]));
}
return Promise.all(entries.map(({ pin, options }, i) => (repos[i] instanceof Error ? repos[i] : toPR(pin, repos[i], bases[i], options).catch((error) => error))));
}
async function fetchPR(pin, options = {}) {
const [pr] = await fetchPRs([{ pin, options }]);
if (pr instanceof Error) throw pr;
return pr;
}
async function toPR(pin, repo, base, { force = false } = {}) {
const prev = state.data.get(pin.key);
const [owner, name] = pin.repo.split("/");
const pr = repo.pullRequest;
const commit = pr.commits.nodes[0]?.commit;
const contexts = commit?.statusCheckRollup?.contexts;
// Statuses do not bump the PR's updatedAt, so fingerprint the per-state counts:
// while they are unchanged the previously paged job list is still right.
const fingerprint = JSON.stringify([
commit?.oid, contexts?.totalCount, contexts?.statusContextCountsByState, contexts?.checkRunCountsByState,
contexts?.nodes.map((node) => node?.state || node?.conclusion || node?.status)
]);
let checks;
if (!contexts) {
checks = [];
} else if (!contexts.pageInfo.hasNextPage) {
checks = normalizeChecks(contexts.nodes);
} else if (!force && prev?.fingerprint === fingerprint) {
checks = prev.checks;
} else {
const rest_ = await fetchContexts(owner, name, commit.oid, contexts.pageInfo.endCursor);
checks = normalizeChecks(contexts.nodes.concat(rest_));
}
const profile = profileFor(pin.repo);
return {
key: pin.key,
repo: pin.repo,
number: pr.number,
id: pr.id,
title: pr.title,
url: safeUrl(pr.url),
state: pr.state,
isDraft: pr.isDraft,
updatedAt: pr.updatedAt,
closedAt: pr.closedAt,
author: pr.author?.login || "ghost",
base,
headOid: pr.headRefOid,
headDate: commit?.committedDate,
mergeable: pr.mergeable,
mergeState: pr.mergeStateStatus,
reviewDecision: pr.reviewDecision,
canUpdate: pr.viewerCanUpdateBranch,
autoMerge: Boolean(pr.autoMergeRequest),
additions: pr.additions,
deletions: pr.deletions,
files: pr.changedFiles,
labels: pr.labels.nodes,
reviews: pr.latestOpinionatedReviews.nodes.map((review) => ({ login: review.author?.login || "ghost", state: review.state })),
reviewRequested: pr.state === "OPEN" && pr.reviewRequests.nodes.some((request) => request.requestedReviewer?.isViewer),
comments: pr.comments.nodes.map((comment) => ({ login: comment.author?.login || "ghost", text: comment.bodyText.slice(0, 700), at: comment.createdAt, url: safeUrl(comment.url) })),
activityAt: newestActivity(pr),
behind: repo.ref?.compare?.behindBy ?? null,
checks,
fingerprint,
ci: summarizeCi(checks, profile)
};
}
/* What the user has "seen" for a PR; a different signature lights the change dot.
A review request is appended only while it stands, so other signatures stay as they were saved. */
function signature(pr) {
const parts = [pr.state, pr.headOid, pr.ci.state, pr.ci.fail, pr.reviewDecision];
return (pr.reviewRequested ? [...parts, "review-requested"] : parts).join("|");
}
/* Newest comment or review by someone else; COMMENTED reviews and repeat approvals don't change reviewDecision. */
function newestActivity(pr) {
const items = pr.comments.nodes.map((comment) => [comment.author?.login, comment.createdAt])
.concat(pr.reviews.nodes.map((review) => [review.author?.login, review.submittedAt]));
return items.reduce((newest, [login, at]) => (at && login !== state.user.login && at > newest ? at : newest), "");
}
function hasChanged(pin) {
const pr = state.data.get(pin.key);
if (!pr) return false;
return Boolean(pin.seen && pin.seen !== signature(pr)) || (pin.seenActivity !== undefined && pr.activityAt > pin.seenActivity);
}
/* Failing-job evidence, without reading logs:
base — the same job failed on N of the recent base-branch commits
others — the same job is failing on other PRs on this board */
function failureIndex() {
const index = new Map();
for (const pr of state.data.values()) {
if (pr.state !== "OPEN") continue;
for (const check of pr.ci.failed) {
if (!index.has(check.jobKey)) index.set(check.jobKey, []);
index.get(check.jobKey).push(pr);
}
}
return index;
}
function splitFailures(pr, index = failureIndex()) {
const baseline = state.baselines.get(`${pr.repo}@${pr.base}`);
const own = [];
const shared = [];
for (const check of pr.ci.failed) {
const evidence = {
base: baseline?.counts.get(check.jobKey) || 0,
baseTotal: baseline?.total || 0,
others: (index.get(check.jobKey) || []).filter((other) => other.key !== pr.key && other.repo === pr.repo)
};
(evidence.base || evidence.others.length ? shared : own).push({ check, evidence });
}
return { own, shared, baselineReady: Boolean(baseline) };
}
async function refreshBaseline(repo, base) {
const key = `${repo}@${base}`;
const [owner, name] = repo.split("/");
const profile = profileFor(repo);
const data = await gql(BASE_HISTORY_QUERY, { owner, name, ref: `refs/heads/${base}`, count: BASELINE_COMMITS });
const commits = data.repository?.ref?.target?.history?.nodes || [];
const failuresOf = async (commit) => {
const cacheKey = `${repo}@${commit.oid}`;
const cached = state.commitFailures.get(cacheKey);
if (cached) return cached;
const checks = normalizeChecks(await fetchContexts(owner, name, commit.oid)).filter((check) => isCiCheck(check, profile));
const jobs = checks.filter((check) => !check.isBuild);
const result = {
hasCI: jobs.length > 0,
finished: jobs.length > 0 && !checks.some((check) => check.state === "pending"),
failed: jobs.filter((check) => check.state === "fail").map((check) => check.jobKey)
};
// Only a finished build is final. (The rollup turns FAILURE at the first failed
// job, long before the build is done, so it cannot be used for this.)
if (result.finished) state.commitFailures.set(cacheKey, result);
return result;
};
const withChecks = commits.filter((commit) => commit.statusCheckRollup);
const counts = new Map();
let total = 0;
for (let at = 0; at < withChecks.length; at += REFRESH_CONCURRENCY) {
const results = await Promise.all(withChecks.slice(at, at + REFRESH_CONCURRENCY).map(failuresOf));
for (const result of results) {
// Count builds that are done, plus unfinished ones that already show a failure.
if (!result.finished && !result.failed.length) continue;
total += 1;
for (const jobKey of result.failed) counts.set(jobKey, (counts.get(jobKey) || 0) + 1);
}
}
state.baselines.set(key, { at: Date.now(), total, counts });
}
async function loadLabels(repo) {
const cached = state.labels.get(repo) || store.get(`pingboard.v3.labels.${repo}`, null);
if (cached && Date.now() - cached.at < LABELS_TTL_MS) {
state.labels.set(repo, cached);
return cached.items;
}
const items = [];
for (let page = 1; page <= 5; page += 1) {
const batch = await rest("GET", `/repos/${repo}/labels?per_page=100&page=${page}`);
items.push(...batch.map((label) => ({ name: label.name, color: label.color })));
if (batch.length < 100) break;
}
const entry = { at: Date.now(), items };
state.labels.set(repo, entry);
store.set(`pingboard.v3.labels.${repo}`, entry);
return items;
}
/* ── 5. refresh scheduler ──────────────────────────────────────────────── */
const refreshQueue = [];
const refreshQueued = new Set();
let refreshActive = 0;
const baselineInFlight = new Set();
const refreshAgain = new Set(); // keys whose in-flight refresh must be followed by a forced one
function queueRefresh(pin, options = {}) {
if (refreshQueued.has(pin.key)) {
if (!options.force) return;
const waiting = refreshQueue.find((entry) => entry.pin.key === pin.key);
if (waiting) waiting.options = { ...waiting.options, force: true };
else refreshAgain.add(pin.key);
return;
}
refreshQueued.add(pin.key);
refreshQueue.push({ pin, options });
queueMicrotask(pumpRefresh); // let pins queued in the same tick share a request
}
function pumpRefresh() {
while (refreshActive < REFRESH_CONCURRENCY && refreshQueue.length) {
const batch = refreshQueue.splice(0, REFRESH_BATCH);
refreshActive += 1;
refreshPins(batch).finally(() => {
refreshActive -= 1;
for (const { pin } of batch) {
refreshQueued.delete(pin.key);
if (refreshAgain.delete(pin.key) && pinByKey(pin.key)) queueRefresh(pin, { force: true });
}
pumpRefresh();
});
}
}
async function refreshPins(batch) {
for (const { pin } of batch) state.status.set(pin.key, { ...state.status.get(pin.key), loading: true });
render();
const results = await fetchPRs(batch);
batch.forEach(({ pin }, i) => settleRefresh(pin, results[i]));
refreshBaselines();
render();
}
function settleRefresh(pin, pr) {
if (pr instanceof Error) {
state.status.set(pin.key, { at: Date.now(), loading: false, error: pr.message });
return;
}
const prev = state.data.get(pin.key);
if (!pinByKey(pin.key)) return; // unpinned while the request was in flight
state.data.set(pin.key, pr);
// GitHub computes mergeability lazily; ask again shortly instead of showing a guess for a full interval.
const unknownTries = pr.state === "OPEN" && pr.mergeable === "UNKNOWN" ? (state.status.get(pin.key)?.unknownTries || 0) + 1 : 0;
state.status.set(pin.key, { at: Date.now(), loading: false, error: "", unknownTries });
if (unknownTries && unknownTries <= 2) setTimeout(() => pinByKey(pin.key) && queueRefresh(pin), 4000);
state.lastSync = Date.now();
// Pins saved before seenActivity existed start from what is there now, so upgrading lights no dots.
if (!pin.seen || pin.seenActivity === undefined) {
pin.seen ||= signature(pr);
pin.seenActivity ??= pr.activityAt;
persistBoard();
}
if (prev && prev.headOid === pr.headOid && prev.ci.state === "running" && pr.ci.state !== "running") announceCi(pr);
}
function announceCi(pr) {
const passed = pr.ci.state === "passed";
const summary = passed ? "CI passed" : `CI finished · ${pr.ci.fail} failed`;
toast(`${shortRef(pr.repo, pr.number)} ${summary}`, passed ? "ok" : "error");
if (state.prefs.notify && "Notification" in window && Notification.permission === "granted") {
const note = new Notification(`${shortRef(pr.repo, pr.number)} ${summary}`, { body: pr.title, tag: pr.key });
note.onclick = () => {
window.focus();
setCursor(pr.key);
};
}
}
/* Keep the base-branch failure baseline fresh for every base an open PR targets.
A failed read just leaves the previous baseline in place until the next try. */
function refreshBaselines() {
const now = Date.now();
for (const pr of state.data.values()) {
const key = `${pr.repo}@${pr.base}`;
if (pr.state !== "OPEN" || baselineInFlight.has(key)) continue;
if (now - (state.baselines.get(key)?.at || 0) <= BASELINE_TTL_MS) continue;
baselineInFlight.add(key);
refreshBaseline(pr.repo, pr.base).catch(() => {}).finally(() => {
baselineInFlight.delete(key);
render();
});
}
}
function tick() {
if (!state.user) return;
const now = Date.now();
const throttled = state.rate.remaining !== null && state.rate.remaining < RATE_FLOOR && now < state.rate.reset;
if (!throttled) {
const slowdown = document.hidden ? HIDDEN_SLOWDOWN : 1;
for (const pin of state.board.pins) {
const pr = state.data.get(pin.key);
const status = state.status.get(pin.key);
const ttl = (pr && pr.state !== "OPEN" ? CLOSED_TTL_S : state.prefs.interval) * 1000 * slowdown;
if (!status?.at || now - status.at >= ttl) queueRefresh(pin);
}
for (const group of state.board.groups) {
if (group.query && now - (state.searches.get(group.id)?.at || 0) >= GROUP_SEARCH_MS * slowdown) syncGroup(group.id);
}
refreshBaselines();
}
if (state.prefs.unpinClosed) {
const old = state.board.pins.filter((pin) => {
const pr = state.data.get(pin.key);
return pr && pr.state !== "OPEN" && now - Date.parse(pr.closedAt) > UNPIN_CLOSED_MS;
});
if (old.length) {
dropPins(old);
toast(`Unpinned ${old.length} merged/closed over a day ago`);
}
}
render();
}
/* Pin what a group's search finds, except results the user unpinned from it. A PR the
search pinned is unpinned once two searches in a row miss it while it is still open;
the forced refresh in between shows a merge as merged instead of making it vanish. */
async function syncGroup(id) {
const group = state.board.groups.find((item) => item.id === id);
const status = state.searches.get(id) || { missing: new Set() };
if (!group?.query || status.loading) return;
const query = group.query;
state.searches.set(id, { ...status, loading: true });
try {
const data = await gql(SEARCH_QUERY, { query: `is:pr is:open ${query} sort:updated-desc` });
const current = state.board.groups.find((item) => item.id === id); // another tab may have replaced the board
if (current?.query !== query) {
state.searches.delete(id);
return;
}
const found = new Set();
let added = 0;
for (const node of data.search.nodes) {
if (!node?.number) continue;
const repo = node.repository.nameWithOwner;
found.add(pinKey(repo, node.number));
if (!current.dismissed.includes(pinKey(repo, node.number)) && addPin(repo, node.number, id, id)) added += 1;
}
const missing = new Set();
// Only a complete result list shows that a PR left the search.
if (data.search.issueCount <= found.size) {
const leaving = state.board.pins.filter((pin) => pin.via === id && pin.group === id && !found.has(pin.key) && state.data.get(pin.key)?.state === "OPEN");
dropPins(leaving.filter((pin) => status.missing.has(pin.key)));
for (const pin of leaving.filter((item) => !status.missing.has(item.key))) {
missing.add(pin.key);
queueRefresh(pin, { force: true });
}