pi-odd-worktree 3.9.1 → 3.10.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.
Files changed (41) hide show
  1. package/README.md +63 -40
  2. package/extensions/odd-worktree-tools.ts +859 -12
  3. package/lib/gh-issues.js +65 -10
  4. package/lib/gh-prs.js +2011 -0
  5. package/lib/issue-preview.js +70 -4
  6. package/lib/issues-cache-store.js +4 -1
  7. package/lib/issues-section.js +346 -23
  8. package/lib/issues-view.js +116 -5
  9. package/lib/modules.js +5 -0
  10. package/lib/pr-preview.js +353 -0
  11. package/lib/prs-rail-store.js +317 -0
  12. package/lib/prs-view.js +2896 -0
  13. package/package.json +1 -1
  14. package/tools/files-bridge.test.js +2 -2
  15. package/tools/files-command.test.js +1 -1
  16. package/tools/fixtures/gh-pr-connection-page.json +84 -0
  17. package/tools/fixtures/gh-pr-metadata.json +29 -0
  18. package/tools/fixtures/gh-pr-rail.json +61 -0
  19. package/tools/fixtures/gh-pr-search-page.json +82 -0
  20. package/tools/fixtures/gh-pr-view.json +159 -0
  21. package/tools/gh-issues.test.js +4 -2
  22. package/tools/gh-prs.test.js +1828 -0
  23. package/tools/issue-preview.test.js +119 -0
  24. package/tools/issues-cache-store.test.js +2 -2
  25. package/tools/issues-command.test.js +10 -3
  26. package/tools/issues-open-guard.test.js +15 -0
  27. package/tools/issues-section.test.js +618 -9
  28. package/tools/issues-view.test.js +297 -0
  29. package/tools/modules-wiring.test.js +5 -0
  30. package/tools/package-surface.test.js +18 -4
  31. package/tools/pr-preview.test.js +281 -0
  32. package/tools/prs-command.test.js +1280 -0
  33. package/tools/prs-rail-store.test.js +343 -0
  34. package/tools/prs-t10-safety.test.js +326 -0
  35. package/tools/prs-t12-safety.test.js +348 -0
  36. package/tools/prs-t13-independent.test.js +378 -0
  37. package/tools/prs-t14-safety.test.js +340 -0
  38. package/tools/prs-t15-independent.test.js +259 -0
  39. package/tools/prs-t18-safety.test.js +217 -0
  40. package/tools/prs-t7-safety.test.js +127 -0
  41. package/tools/prs-view.test.js +1462 -0
@@ -19,7 +19,7 @@
19
19
  // body). Every field is optional.
20
20
  // comments an array of `{ author, body, createdAt }`; anything else is
21
21
  // treated as "no comments yet".
22
- // options { width, paint, emphasis, wrap, cache, note, pending, now }
22
+ // options { width, paint, emphasis, wrap, cache, note, pending, now, ranges }
23
23
  // `note` an extra short fact for the state row (a caller may
24
24
  // pass a worktree's assignment state); it never
25
25
  // replaces a fact of the issue itself.
@@ -29,6 +29,18 @@
29
29
  // `now` epoch ms for the relative ages.
30
30
  // `cache` a wrap memo from `createWrapCache()`; the default is
31
31
  // the module's shared instance (S23).
32
+ // `ranges` a caller-owned array the formatter APPENDS one click
33
+ // range per linked PR number to, as
34
+ // `{kind:'pullRequest', number, line, start, end}`.
35
+ // `line` is an index into the RETURNED rows and
36
+ // `start`/`end` are the plain cell columns of that
37
+ // `#N` token inside it (the token is ASCII, so its
38
+ // character index is its column). Only the numbers the
39
+ // relation row printed become ranges: the row label,
40
+ // the separators, the truncation ellipsis and any `#N`
41
+ // that appears in the title, the body or a comment
42
+ // carry none, so a click can never open the whole line.
43
+ // Without a collector nothing changes.
32
44
  //
33
45
  // S23: the wrap is memoized. A repaint at an unchanged width used to re-wrap
34
46
  // the whole body and every comment of the issue on screen; the memo is keyed
@@ -192,6 +204,40 @@ function bold(text) {
192
204
  return String(text);
193
205
  }
194
206
 
207
+ // S6: the click ranges of ONE `linked PRs:` row, once it is wrapped. Each `#N`
208
+ // token the row actually PRINTED becomes the range of that number on the row it
209
+ // landed on; nothing else does. A token the wrap had to split across two rows
210
+ // matches on neither, which is the honest answer — no half number is clickable.
211
+ // S6/D29: a token that is PART of a longer reference (`owner/repo#N`, the shape
212
+ // a link of another repository is painted in) is not a bare `#N` and is skipped,
213
+ // so a foreign number can never become a click target of this repository's PR.
214
+ function appendLinkedRanges(rows, numbers, firstLine, target) {
215
+ if (!Array.isArray(target)) return;
216
+ for (let at = 0; at < rows.length; at += 1) {
217
+ const text = String(rows[at] ?? '');
218
+ const pattern = /#(\d+)/g;
219
+ let match = pattern.exec(text);
220
+ while (match !== null) {
221
+ const before = match.index > 0 ? text[match.index - 1] : '';
222
+ const number = Number(match[1]);
223
+ if (/[A-Za-z0-9_/.-]/.test(before)) {
224
+ match = pattern.exec(text);
225
+ continue;
226
+ }
227
+ if (numbers.includes(number)) {
228
+ target.push({
229
+ kind: 'pullRequest',
230
+ number,
231
+ line: firstLine + at,
232
+ start: match.index,
233
+ end: match.index + match[0].length,
234
+ });
235
+ }
236
+ match = pattern.exec(text);
237
+ }
238
+ }
239
+ }
240
+
195
241
  /**
196
242
  * The preview pane for ONE issue: identity, state, labels, assignees, author
197
243
  * and ages, reaction/comment counts, projects, linked PRs, the body and every
@@ -209,6 +255,8 @@ function issueDetailLines(detail, comments, options = {}) {
209
255
  const wrap = typeof settings.wrap === 'function' ? settings.wrap : (text) => cache.wrap(text, width);
210
256
  const list = Array.isArray(comments) ? comments : [];
211
257
  const nowMs = Number.isFinite(settings.now) ? settings.now : Date.now();
258
+ // S6: the caller's optional click-range collector (see the contract above).
259
+ const ranges = Array.isArray(settings.ranges) ? settings.ranges : null;
212
260
 
213
261
  const lines = [];
214
262
  // S13: the title asks for the shared title role, and keeps its emphasis.
@@ -262,8 +310,20 @@ function issueDetailLines(detail, comments, options = {}) {
262
310
  // whole list.
263
311
  const linkedPrs = (Array.isArray(entry.linkedPullRequests) ? entry.linkedPullRequests : [])
264
312
  .filter((number) => Number.isInteger(number) && number > 0);
265
- if (linkedPrs.length > 0) {
266
- const listed = linkedPrs.map((number) => `#${number}`).join(', ');
313
+ // S6/D29: a linked pull request of ANOTHER repository is the other half of the
314
+ // same rule. It is named as `owner/repo#N` — the repository it belongs to, so
315
+ // nobody reads it as one of this repository's numbers — and it is not a click
316
+ // range: this panel can only open a pull request it has an identity for.
317
+ const foreignPrs = (Array.isArray(entry.linkedPullRequestsForeign) ? entry.linkedPullRequestsForeign : [])
318
+ .filter((ref) => ref && typeof ref === 'object' && typeof ref.repository === 'string'
319
+ && ref.repository !== '' && Number.isInteger(ref.number) && ref.number > 0)
320
+ .map((ref) => `${ref.repository}#${ref.number}`);
321
+ // The index of the relation row in `lines`, so its ranges can be reported
322
+ // against the rows `wrap` actually produced (−1 when the pane has none).
323
+ let linkedRowAt = -1;
324
+ if (linkedPrs.length > 0 || foreignPrs.length > 0) {
325
+ const listed = [...linkedPrs.map((number) => `#${number}`), ...foreignPrs].join(', ');
326
+ linkedRowAt = lines.length;
267
327
  lines.push(`linked PRs: ${listed}${entry.linkedPullRequestsTruncated === true ? ', …' : ''}`);
268
328
  }
269
329
  // A relation that could not be read (`unavailable`) or a whole failed read
@@ -273,7 +333,13 @@ function issueDetailLines(detail, comments, options = {}) {
273
333
 
274
334
  const out = [];
275
335
  lines.push('');
276
- for (const line of lines) out.push(...wrap(line));
336
+ for (let at = 0; at < lines.length; at += 1) {
337
+ const rows = wrap(lines[at]);
338
+ // S6: the relation row is the ONLY source of click ranges, and they are
339
+ // reported against the rows `wrap` produced, so a wrapped list maps right.
340
+ if (at === linkedRowAt) appendLinkedRanges(rows, linkedPrs, out.length, ranges);
341
+ out.push(...rows);
342
+ }
277
343
  out.push(...wrap(entry.body || '(no description)'));
278
344
  list.forEach((comment, at) => {
279
345
  out.push('');
@@ -30,7 +30,10 @@ const os = require('node:os');
30
30
 
31
31
  // The document carries its own version: a reader that does not recognize one
32
32
  // answers nothing instead of guessing at a shape it never wrote.
33
- const DOC_VERSION = 1;
33
+ // Version 2: a stored row's linked-PR mark is now repository-qualified (a pull
34
+ // request of another repository is never marked), so a document written by an older
35
+ // release, whose marks could name a foreign pull request, is silence.
36
+ const DOC_VERSION = 2;
34
37
  const DIR_NAME = 'odd-worktree';
35
38
  const FILE_NAME = 'issues-cache.json';
36
39
  const BUCKET_KEYS = ['mine', 'assigned', 'involved'];
@@ -82,6 +82,19 @@
82
82
  //
83
83
  // The module never leaves a timer or a state write behind after `dispose()`:
84
84
  // whatever the read lands with is dropped silently.
85
+ //
86
+ // T4 (S4, S5): the rail reads the repository's PULL REQUESTS beside its issues.
87
+ // `loadPullRequests` is the second seam — shaped like `listRailPullRequests`,
88
+ // `{ ok, mine, review }`, each row a `{ number, linkedIssues }` — and it decides
89
+ // exactly two things. It names the header's `pr` count, the DISTINCT numbers in
90
+ // the union of the two buckets, so the row reads `7 issues · 3 pr` (`7 issues`
91
+ // alone while that read is unavailable, and `· stale` is still kept after the
92
+ // issues list stalls). And it routes a row's click: an issue the read marked
93
+ // with a pull request opens the PR panel on it, `review` beating `mine`, while a
94
+ // pull request in neither bucket is `all`. Both decisions are the rail's own —
95
+ // the seam costs no child on a frame, both reads obey the same TTL, the same
96
+ // self-scheduled floor and the same drawn window, and a failed pull-request read
97
+ // keeps the last count instead of blanking a number the human already had.
85
98
 
86
99
  const DEFAULT_TTL_MS = 60000;
87
100
  // S11: how long a section counts as DRAWN after its last frame when the module
@@ -108,6 +121,8 @@ const EMPTY_ROW = { label: 'no open issues', tone: 'dim' };
108
121
  // contract today. This is noted where the mark is built.
109
122
  const PR_MARK_GLYPH = '\ue726';
110
123
  const READ_FAILED = 'cannot read issues';
124
+ // T4 (S4): the second read's own failure sentence, kept beside the first one.
125
+ const PULL_REQUESTS_FAILED = 'cannot read pull requests';
111
126
  // T12 (S4, L11) moved the row click's destination into the extension: the row
112
127
  // dispatches `/issues <number>` and the panel proves its own repository, so the
113
128
  // fallback line a failed click is recorded with no longer names a browser.
@@ -137,6 +152,12 @@ function issueRows(issues, limit) {
137
152
  .slice(0, limit)
138
153
  .map((item) => {
139
154
  const title = typeof item.title === 'string' ? item.title : '';
155
+ // The ONE linked pull request the row knows: the same normalized number the
156
+ // mark is drawn from, kept on the internal row (never on the painted one)
157
+ // so the deferred click can route to it (T4, S5).
158
+ const pullRequest = Number.isInteger(item.pullRequestNumber) && item.pullRequestNumber > 0
159
+ ? item.pullRequestNumber
160
+ : null;
140
161
  // `number` and `bucket` stay on the snapshot row so the deferred click
141
162
  // binds the issue AND the bucket it came from. The painted row below
142
163
  // exposes only its label, tone, click and — when its issue has a linked
@@ -155,9 +176,10 @@ function issueRows(issues, limit) {
155
176
  onClick: null,
156
177
  number: item.number,
157
178
  bucket: item.bucket,
179
+ pullRequest,
158
180
  };
159
- if (Number.isInteger(item.pullRequestNumber) && item.pullRequestNumber > 0) {
160
- row.meta = `${PR_MARK_GLYPH} #${item.pullRequestNumber}`;
181
+ if (pullRequest !== null) {
182
+ row.meta = `${PR_MARK_GLYPH} #${pullRequest}`;
161
183
  }
162
184
  return row;
163
185
  });
@@ -171,6 +193,16 @@ function overflowRow(hidden, truncated) {
171
193
  function createIssuesSection(options = {}) {
172
194
  const opts = options && typeof options === 'object' ? options : {};
173
195
  const load = typeof opts.load === 'function' ? opts.load : null;
196
+ // T4 (S4, S5): the second seam, optional exactly like `load`: a caller that
197
+ // names none reads no pull requests and paints the header it always painted.
198
+ const loadPullRequests = typeof opts.loadPullRequests === 'function' ? opts.loadPullRequests : null;
199
+ // D9 (S4): the stored entry's seam, optional too. It answers the rows a
200
+ // PREVIOUS process read for one repository identity, so a cold start paints
201
+ // `N issues · M pr` while the live read is still in flight. It is where the
202
+ // entry sleeps between processes, never what a read means: the section decides
203
+ // when it is asked (from a dispatched read alone), when it may paint (only
204
+ // while no read has painted a count) and that the live answer replaces it.
205
+ const hydratePullRequests = typeof opts.hydratePullRequests === 'function' ? opts.hydratePullRequests : null;
174
206
  const open = typeof opts.open === 'function' ? opts.open : null;
175
207
  const openAll = typeof opts.openAll === 'function' ? opts.openAll : null;
176
208
  const now = typeof opts.now === 'function' ? opts.now : Date.now;
@@ -193,7 +225,7 @@ function createIssuesSection(options = {}) {
193
225
  const maxRows = Math.min(requestedRows, DEFAULT_MAX_ROWS);
194
226
  const sectionId = typeof opts.sectionId === 'string' && opts.sectionId.length > 0 ? opts.sectionId : 'odd-worktree.issues';
195
227
  const title = typeof opts.title === 'string' && opts.title.length > 0 ? opts.title : 'GITHUB';
196
- const rowLabel = typeof opts.rowLabel === 'string' && opts.rowLabel.length > 0 ? opts.rowLabel : 'issues';
228
+ const rowLabel = typeof opts.rowLabel === 'string' && opts.rowLabel.length > 0 ? opts.rowLabel : 'github';
197
229
  const onRefreshed = typeof opts.onRefreshed === 'function' ? opts.onRefreshed : null;
198
230
 
199
231
  let snapshot = null;
@@ -228,6 +260,17 @@ function createIssuesSection(options = {}) {
228
260
  // S10 (T9): when the last FORCED read started, so the caller's anti-storm cap
229
261
  // measures from it. Null until one runs.
230
262
  let lastForcedAt = null;
263
+ // T4 (S4, S5): the pull-request read's own state, guarded and versioned exactly
264
+ // like the issues read's. `pullRequests` is `null` until a read lands, which is
265
+ // what makes the header fall back to `N issues` (the read is T5's seam, so a
266
+ // caller that never supplies one, or whose first read never succeeds, has no
267
+ // count to paint). A FAILED read keeps the last rows and count — a settle that
268
+ // produced no numbers never takes away the ones already on screen.
269
+ let pullRequests = null;
270
+ let pullRequestsScheduled = false;
271
+ let pullRequestsRunning = null;
272
+ let pullRequestsToken = 0;
273
+ let pullRequestsLastAttemptAt = null;
231
274
 
232
275
  // The time the staleness checks measure from: the last SETTLED attempt when
233
276
  // there is one, otherwise the last snapshot. Measuring the TTL from a failed
@@ -257,6 +300,10 @@ function createIssuesSection(options = {}) {
257
300
  }
258
301
 
259
302
  function ensureFresh() {
303
+ // T4 (S4): the pull-request read is asked FIRST and behind its own guards, so
304
+ // an issues read already in flight never suppresses it and a fresh issues
305
+ // snapshot never keeps an aged `pr` count on screen.
306
+ ensureFreshPullRequests();
260
307
  if (disposed || scheduled || running !== null) return;
261
308
  if (!isStale()) return;
262
309
  const queuedGeneration = generation;
@@ -332,15 +379,25 @@ function createIssuesSection(options = {}) {
332
379
  }
333
380
  }
334
381
 
382
+ // T10b (S4, D9): the ONE repaint request a landed read makes. The issues read
383
+ // reaches it through `replace()`, and both settlements of the pull-request read
384
+ // call it themselves: the `pr` count is a SECOND state, so a header that grew its
385
+ // `· M pr` segment would otherwise keep the old count until an unrelated frame.
386
+ // A frame never asks (it only schedules the read), a superseded answer never asks
387
+ // (the token check happens before the state is written), and a host without the
388
+ // notifier pays nothing.
389
+ function requestRepaint() {
390
+ if (onRefreshed === null) return;
391
+ try {
392
+ onRefreshed();
393
+ } catch {
394
+ // A repaint failure never breaks the frame that reads the snapshot.
395
+ }
396
+ }
397
+
335
398
  function replace(next) {
336
399
  snapshot = next;
337
- if (onRefreshed !== null) {
338
- try {
339
- onRefreshed();
340
- } catch {
341
- // A repaint failure never breaks the frame that reads the snapshot.
342
- }
343
- }
400
+ requestRepaint();
344
401
  }
345
402
 
346
403
  function apply(result) {
@@ -379,10 +436,7 @@ function createIssuesSection(options = {}) {
379
436
  const readGeneration = result.generation === undefined ? null : result.generation;
380
437
  const rows = issueRows(issues, maxRows);
381
438
  for (const row of rows) {
382
- row.onClick = deferSeam(
383
- () => (open === null ? undefined : open(row.number, identity, row.bucket, readGeneration)),
384
- OPEN_FAILED,
385
- );
439
+ row.onClick = deferSeam(invokeOpen(row, identity, readGeneration), OPEN_FAILED);
386
440
  }
387
441
  if (issues.length > maxRows) {
388
442
  const row = overflowRow(issues.length - maxRows, truncated);
@@ -398,6 +452,10 @@ function createIssuesSection(options = {}) {
398
452
  rows,
399
453
  truncated,
400
454
  });
455
+ // T4 (S4): this is the read that proves the checkout's repository, so the
456
+ // pull-request read starts HERE on a cold section — a collapsed first frame
457
+ // draws no body and nothing else would ask for it until the next floor.
458
+ ensureFreshPullRequests();
401
459
  return;
402
460
  }
403
461
  const error = textOf(result && result.error, READ_FAILED);
@@ -436,8 +494,233 @@ function createIssuesSection(options = {}) {
436
494
  if (tone === 'dim' || tone === 'muted') clearFloorTimer();
437
495
  }
438
496
 
439
- function recordOpenError(err, fallback) {
440
- if (disposed) return;
497
+ // T4 (S5): the click's destination. An issue the read marked with a linked pull
498
+ // request opens the PR panel on THAT pull request and carries the routing
499
+ // object the panel needs — `{ pullRequest, pullRequestBucket }`; every other
500
+ // row keeps the four arguments it always passed. The bucket is decided against
501
+ // the buckets the rail holds WHEN THE CLICK RUNS, so a retained row follows the
502
+ // read that has landed since it was painted. `review` beats `mine`, and a pull
503
+ // request in neither is `all` — the row still opens a PR panel even when the
504
+ // rail's own read could not place it.
505
+ function invokeOpen(row, identity, readGeneration) {
506
+ if (open === null) return () => undefined;
507
+ if (row.pullRequest === null) {
508
+ return () => open(row.number, identity, row.bucket, readGeneration);
509
+ }
510
+ const number = row.pullRequest;
511
+ return () => open(row.number, { pullRequest: number, pullRequestBucket: pullRequestBucket(number) });
512
+ }
513
+
514
+ // T4 (S4): one pull-request row, normalized to the one shape the rail reads: a
515
+ // positive integer number and the issues it links. A row without a usable
516
+ // number is not a pull request and is dropped, exactly like the issues read
517
+ // drops an issue it cannot paint.
518
+ function pullRequestRows(rows) {
519
+ const list = Array.isArray(rows) ? rows : [];
520
+ const kept = [];
521
+ for (const item of list) {
522
+ const entry = item && typeof item === 'object' ? item : {};
523
+ const number = Number.isInteger(entry.number) && entry.number > 0 ? entry.number : null;
524
+ if (number === null) continue;
525
+ const linkedIssues = Array.isArray(entry.linkedIssues)
526
+ ? entry.linkedIssues.filter((linked) => Number.isInteger(linked) && linked > 0)
527
+ : [];
528
+ kept.push({ number, linkedIssues });
529
+ }
530
+ return kept;
531
+ }
532
+
533
+ // T4 (S5): which bucket a pull request belongs to, from the rail's own read.
534
+ // No read (or a read that knows neither bucket) is `all`.
535
+ function pullRequestBucket(number) {
536
+ if (pullRequests === null) return 'all';
537
+ if (pullRequests.review.has(number)) return 'review';
538
+ if (pullRequests.mine.has(number)) return 'mine';
539
+ return 'all';
540
+ }
541
+
542
+ // T4 (S4): the count the header paints — the DISTINCT numbers in mine ∪ review.
543
+ // `null` means no count has ever been read, which is the header the section had
544
+ // before the seam existed.
545
+ function pullRequestCount() {
546
+ return pullRequests === null ? null : pullRequests.count;
547
+ }
548
+
549
+ // D8 (S4): the count one read (or one stored entry) proves, as the bucket sets
550
+ // it also routes clicks with. The base is the DISTINCT numbers the answer
551
+ // CARRIED. A bucket that reports an exact total larger than the rows it came
552
+ // with was cut by its own window, and every such cut row is a pull request the
553
+ // answer proved exists but never named: its number cannot be deduplicated
554
+ // against anything, so each one counts on its own. A total that is not a count,
555
+ // or one below the rows that came with it, adds nothing — the fetched numbers
556
+ // stay the floor, so no header is ever short of what is known.
557
+ function pullRequestUniverse(mine, review, totals) {
558
+ const mined = new Set(mine.map((row) => row.number));
559
+ const reviewed = new Set(review.map((row) => row.number));
560
+ const distinct = new Set([...mined, ...reviewed]);
561
+ const claimed = totals !== null && typeof totals === 'object' ? totals : {};
562
+ const remainder = (total, fetched) => (Number.isInteger(total) && total > fetched ? total - fetched : 0);
563
+ return {
564
+ mine: mined,
565
+ review: reviewed,
566
+ count: distinct.size + remainder(claimed.mine, mined.size) + remainder(claimed.review, reviewed.size),
567
+ };
568
+ }
569
+
570
+ function pullRequestsStale(maxAgeMs) {
571
+ if (pullRequests === null) return true;
572
+ const from = pullRequestsLastAttemptAt === null ? pullRequests.at : pullRequestsLastAttemptAt;
573
+ const age = now() - from;
574
+ return !Number.isFinite(age) || age >= maxAgeMs;
575
+ }
576
+
577
+ // T4 (S4): the pull-request read rides the SAME repository the issues read
578
+ // proved. While that proof is missing — no snapshot yet, or the settled state a
579
+ // cwd outside a repository or a missing `gh` draws — nothing is read, which is
580
+ // what keeps a non-repository checkout free of the child invariant 28 forbids.
581
+ function repositoryProved() {
582
+ return snapshot !== null && (snapshot.status === 'ready' || snapshot.status === 'stale');
583
+ }
584
+
585
+ // T4 (S4): one settled pull-request read. A success replaces the rows and their
586
+ // count; a failure only marks the state stalled and KEEPS the count, because a
587
+ // `gh` killed by its bound must never cost the human a number already painted.
588
+ // A failure with nothing ever read paints nothing at all.
589
+ function applyPullRequests(result) {
590
+ const at = now();
591
+ pullRequestsLastAttemptAt = at;
592
+ if (result && result.ok === true) {
593
+ const mine = pullRequestRows(result.mine);
594
+ const review = pullRequestRows(result.review);
595
+ const universe = pullRequestUniverse(mine, review, result.counts);
596
+ pullRequests = {
597
+ status: 'ready',
598
+ at,
599
+ mine: universe.mine,
600
+ review: universe.review,
601
+ count: universe.count,
602
+ error: null,
603
+ };
604
+ // T10b (S4, D9): the count the header paints just changed, so the frame the
605
+ // human reads it in is asked for here — the same request the issues read
606
+ // makes when its own rows land.
607
+ requestRepaint();
608
+ return;
609
+ }
610
+ const error = textOf(result && result.error, PULL_REQUESTS_FAILED);
611
+ if (pullRequests === null) return;
612
+ pullRequests = { ...pullRequests, status: 'stale', error };
613
+ // T10b (S4, D9): the settled attempt changed this state (its status), so it
614
+ // asks for the frame too; nothing asks while no count has ever been painted.
615
+ requestRepaint();
616
+ }
617
+
618
+ // T4 (S4): the same guard the issues read has — one read in flight, one queued,
619
+ // nothing outside a repository, nothing after `dispose()` or a session
620
+ // boundary — so a frame never waits and two stale frames start ONE read. The
621
+ // threshold is the caller's: the frame TTL by default, the activity floor while
622
+ // the section is drawn, and `0` for the caller's one forced read.
623
+ function ensureFreshPullRequests(maxAgeMs = ttlMs) {
624
+ if (disposed || loadPullRequests === null) return;
625
+ if (pullRequestsScheduled || pullRequestsRunning !== null) return;
626
+ if (!repositoryProved()) return;
627
+ if (!pullRequestsStale(maxAgeMs)) return;
628
+ const queuedGeneration = generation;
629
+ pullRequestsScheduled = true;
630
+ try {
631
+ schedule(() => {
632
+ if (disposed || queuedGeneration !== generation) return undefined;
633
+ pullRequestsScheduled = false;
634
+ if (pullRequestsRunning !== null) return undefined;
635
+ return refreshPullRequests();
636
+ });
637
+ } catch {
638
+ pullRequestsScheduled = false;
639
+ }
640
+ }
641
+
642
+ function refreshPullRequests() {
643
+ if (disposed || loadPullRequests === null) return Promise.resolve(pullRequests);
644
+ const token = (pullRequestsToken += 1);
645
+ let pending;
646
+ try {
647
+ pending = Promise.resolve(loadPullRequests());
648
+ } catch (err) {
649
+ pending = Promise.reject(err);
650
+ }
651
+ // D9 (S4): the stored entry is asked BESIDE the live read, never instead of
652
+ // it, and never awaited by this one: the disk is fast enough to paint the
653
+ // cold-start header while `gh` is still answering, and a slow disk postpones
654
+ // no read. `token` is what keeps a hydration from outliving the read it rode.
655
+ hydratePullRequestsFrom(token);
656
+ const run = pending.then(
657
+ (result) => {
658
+ if (disposed || token !== pullRequestsToken) return pullRequests;
659
+ applyPullRequests(result);
660
+ return pullRequests;
661
+ },
662
+ (err) => {
663
+ if (disposed || token !== pullRequestsToken) return pullRequests;
664
+ applyPullRequests({ ok: false, error: textOf(err, PULL_REQUESTS_FAILED) });
665
+ return pullRequests;
666
+ },
667
+ );
668
+ pullRequestsRunning = run;
669
+ const settle = () => {
670
+ if (pullRequestsRunning === run) pullRequestsRunning = null;
671
+ };
672
+ run.then(settle, settle);
673
+ return run;
674
+ }
675
+
676
+ // D9 (S4): one hydration, dispatched by the read that just started. Nothing is
677
+ // asked for a count already painted (the live answer, or the one this section
678
+ // already has, is the truth), for a section with no repository proof to key the
679
+ // entry with, or for a settled section — a `dim` state (no `gh`, not a
680
+ // repository) reads no disk and starts nothing, exactly like its read. A
681
+ // throwing or rejecting seam is silence: the live read still answers.
682
+ function hydratePullRequestsFrom(token) {
683
+ if (hydratePullRequests === null || pullRequests !== null) return;
684
+ const identity = snapshot === null ? null : snapshot.identity;
685
+ if (typeof identity !== 'string' || identity.length === 0) return;
686
+ let pending;
687
+ try {
688
+ pending = Promise.resolve(hydratePullRequests(identity));
689
+ } catch {
690
+ return;
691
+ }
692
+ pending.then((stored) => {
693
+ if (disposed || token !== pullRequestsToken) return;
694
+ // A live answer that landed FIRST owns the paint: a stored number never
695
+ // contradicts one the repository just answered.
696
+ if (pullRequests !== null) return;
697
+ if (stored === null || typeof stored !== 'object') return;
698
+ const mine = pullRequestRows(stored.mine);
699
+ const review = pullRequestRows(stored.review);
700
+ // T10b (S4, D15): the entry carries each bucket's TOTAL beside its rows, so
701
+ // the cold start paints the number the live read painted — the rows it
702
+ // carried plus what each total says the window cut. A total the store could
703
+ // not prove is already `null` here, and a document of a previous version is
704
+ // silence, never a failure.
705
+ const universe = pullRequestUniverse(mine, review, stored.counts);
706
+ // The AGE the count carries is the moment the stored read landed, never
707
+ // now: an old entry can never pass for a fresh one, and the TTL that the
708
+ // caller's live read obeys keeps counting from where the disk left it.
709
+ pullRequests = {
710
+ status: 'ready',
711
+ at: Number.isFinite(stored.syncedAt) ? stored.syncedAt : null,
712
+ mine: universe.mine,
713
+ review: universe.review,
714
+ count: universe.count,
715
+ error: null,
716
+ };
717
+ // T10b (S4, D9): a count painted from the disk is a count the header did not
718
+ // have a frame for either, so it asks for one exactly like the live answer.
719
+ requestRepaint();
720
+ }, () => {});
721
+ }
722
+
723
+ function recordOpenError(err, fallback) { if (disposed) return;
441
724
  const error = textOf(err, fallback);
442
725
  if (snapshot === null) {
443
726
  replace({
@@ -506,6 +789,10 @@ function createIssuesSection(options = {}) {
506
789
  // a run is in flight.
507
790
  function refresh() {
508
791
  if (disposed) return Promise.resolve(snapshot);
792
+ // T4 (S4): an explicit read reads the pull requests too, whatever the caller
793
+ // was told to refresh — the header and the routers are one snapshot of the
794
+ // repository.
795
+ ensureFreshPullRequests();
509
796
  const token = (runToken += 1);
510
797
  let pending;
511
798
  try {
@@ -551,6 +838,13 @@ function createIssuesSection(options = {}) {
551
838
  // T15 (defects 1 and 2): the previous checkout's attempt no longer sets the
552
839
  // floor, and a refresh already queued for it is now stale.
553
840
  lastAttemptAt = null;
841
+ // T4 (S4, S5): the `pr` count and the buckets a click is routed by belong to
842
+ // the checkout this session left, so they go with the rows — the header falls
843
+ // back to `N issues` and the newest token makes a late answer land nowhere.
844
+ pullRequests = null;
845
+ pullRequestsToken += 1;
846
+ pullRequestsScheduled = false;
847
+ pullRequestsLastAttemptAt = null;
554
848
  generation += 1;
555
849
  }
556
850
 
@@ -562,6 +856,10 @@ function createIssuesSection(options = {}) {
562
856
  // started, and it never throws or rejects.
563
857
  function refreshIfStale(maxAgeMs) {
564
858
  if (disposed) return false;
859
+ // T4 (S4): the pull-request read has its own TTL, so the activity seam asks
860
+ // it on its own terms — at the floor it was given, exactly like the issues
861
+ // read below — even when the issues list is fresh.
862
+ ensureFreshPullRequests(maxAgeMs);
565
863
  if (running !== null) return false;
566
864
  // S3 (T2): nothing to check outside a repository, so the activity seam starts
567
865
  // nothing either — however long the session lives there.
@@ -586,6 +884,11 @@ function createIssuesSection(options = {}) {
586
884
  // started, and it never throws.
587
885
  function forceRefresh(minIntervalMs) {
588
886
  if (disposed) return false;
887
+ // T4 (S4): a forced read is worth the pull requests too — the caller knows a
888
+ // mutation landed — so it starts one now, still behind the one-read-in-flight
889
+ // guard and never behind the caller's anti-storm cap, which stays the issues
890
+ // read's.
891
+ ensureFreshPullRequests(0);
589
892
  if (running !== null) return false;
590
893
  // S3 (T2): nothing to check outside a repository, so nothing is forced there.
591
894
  if (stateSettled()) return false;
@@ -629,6 +932,20 @@ function createIssuesSection(options = {}) {
629
932
  }
630
933
  }
631
934
 
935
+ // S12 (T10): the heading names its units. `7 issues`, and — from T4 (S4) — the
936
+ // pull requests the same repository holds for the viewer: `7 issues · 2 pr`,
937
+ // where the second number is the DISTINCT numbers in mine ∪ review. The `pr`
938
+ // segment appears only once a read has landed, so a caller with no seam (or a
939
+ // first read that failed) keeps the header it always had. A stalled list still
940
+ // has both counts — the ones its last successful reads produced — and says so
941
+ // (`· stale`) instead of hiding either failure.
942
+ function headerText(stale) {
943
+ const issues = `${snapshot.issues.length} issues`;
944
+ const pullRequestNumbers = pullRequestCount();
945
+ const counted = pullRequestNumbers === null ? issues : `${issues} · ${pullRequestNumbers} pr`;
946
+ return stale ? `${counted} · stale` : counted;
947
+ }
948
+
632
949
  function meta(_ctx) {
633
950
  try {
634
951
  // S3 amended (T13): a collapsed header is still a drawn section — the host
@@ -637,15 +954,12 @@ function createIssuesSection(options = {}) {
637
954
  // The heading only reads the snapshot. A collapsed section is drawn with
638
955
  // this call alone, so scheduling a refresh here would make it cost the
639
956
  // network it is supposed to cost nothing. S7 (T8): the count is the MERGED
640
- // list's length, before any display cap, and S12 (T10) names its unit:
641
- // `7 issues`, and `7 issues · stale` while the list is stalled. The rail
642
- // never separates mine from assigned, so it never names either. A stale
643
- // list still has a count — the one the last successful read produced — and
644
- // it says so instead of hiding the failure. No snapshot is no count.
957
+ // list's length, before any display cap. The rail never separates mine from
958
+ // assigned, so it never names either. No snapshot is no count.
645
959
  if (snapshot === null) return undefined;
646
- if (snapshot.status === 'stale') return `${snapshot.issues.length} issues · stale`;
960
+ if (snapshot.status === 'stale') return headerText(true);
647
961
  if (snapshot.status !== 'ready') return undefined;
648
- return `${snapshot.issues.length} issues`;
962
+ return headerText(false);
649
963
  } catch {
650
964
  return undefined;
651
965
  }
@@ -693,6 +1007,10 @@ function createIssuesSection(options = {}) {
693
1007
  lastForcedAt = null;
694
1008
  // T15 (defect 2): a refresh already queued for this section is stale.
695
1009
  generation += 1;
1010
+ // T4 (S4): the pull-request read is dropped the same way, so nothing it lands
1011
+ // with outlives the session that asked for it.
1012
+ pullRequestsScheduled = false;
1013
+ pullRequestsToken += 1;
696
1014
  }
697
1015
 
698
1016
  const section = {
@@ -700,6 +1018,11 @@ function createIssuesSection(options = {}) {
700
1018
  title,
701
1019
  rowLabel,
702
1020
  defaultVisible: true,
1021
+ // gentle-shell-bridge 0.13.0 lets a section name where it sits in the rail.
1022
+ // The GITHUB card goes AFTER every native card — the bridge's own default,
1023
+ // which an older bridge simply ignores — and it is said here so the placement
1024
+ // does not depend on a default another release could change.
1025
+ placement: 'end',
703
1026
  meta,
704
1027
  lines,
705
1028
  };