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
@@ -7722,8 +7722,12 @@ function issuesScopeLabel(name) {
7722
7722
  return typeof name === "string" && name.length > 0 ? name : "gh's default repository";
7723
7723
  }
7724
7724
 
7725
- function issuesScopeDriftLine(currentName, pinnedName) {
7726
- return `the checkout's repository changed since this issue list loaded (now ${issuesScopeLabel(currentName)} instead of ${issuesScopeLabel(pinnedName)}); reopen /issues`;
7725
+ function issuesScopeDriftLine(currentName, pinnedName, command = "/issues") {
7726
+ // D10 (S2): the refusal names the panel whose rows moved, so a `/prs` action
7727
+ // is never told to reopen `/issues`. Both sentences are built here so the two
7728
+ // panels cannot drift apart.
7729
+ const what = command === "/prs" ? "pull request list" : "issue list";
7730
+ return `the checkout's repository changed since this ${what} loaded (now ${issuesScopeLabel(currentName)} instead of ${issuesScopeLabel(pinnedName)}); reopen ${command}`;
7727
7731
  }
7728
7732
 
7729
7733
  // The TUI hands the terminal to another program: a browser open must give it
@@ -7776,7 +7780,11 @@ function withSuspendedTerminal(hostTui, run) {
7776
7780
  // is normalized with the same function every pinned read uses before it reaches
7777
7781
  // `-R`, so no raw value can ever move this open: a value that does not normalize
7778
7782
  // is not an identity, and the opener keeps its own "nothing loaded yet" refusal.
7779
- function issuesOpenInBrowser(hostTui, cwd, number, pinnedIdentity) {
7783
+ // The `o` opener, one fixed argv per kind: `gh issue view <n> --web -R <pinned>`
7784
+ // or `gh pr view <n> --web -R <pinned>`, never a shell and never an invented
7785
+ // opener, with `-R` the identity the LIST was read from.
7786
+ function githubItemOpenInBrowser(hostTui, cwd, kind, number, pinnedIdentity) {
7787
+ const label = kind === "pr" ? "pr" : "issue";
7780
7788
  try {
7781
7789
  const gh = libRequire("gh-issues.js");
7782
7790
  const git = libRequire("worktree-git.js");
@@ -7792,22 +7800,30 @@ function issuesOpenInBrowser(hostTui, cwd, number, pinnedIdentity) {
7792
7800
  return Promise.resolve({ ok: false, error: "the issue list has not loaded a repository yet" });
7793
7801
  }
7794
7802
  const bin = gh && typeof gh.ghBinary === "function" ? gh.ghBinary({}) : "gh";
7795
- const argv = ["issue", "view", String(number), "--web", "-R", normalized.identity];
7803
+ const argv = [label, "view", String(number), "--web", "-R", normalized.identity];
7796
7804
  return withSuspendedTerminal(hostTui, async () => {
7797
7805
  const res = await git.runArgvAsync(bin, argv, { cwd, timeoutMs: 30000 });
7798
- if (!res) return { ok: false, error: `cannot open issue #${number} in the browser` };
7806
+ if (!res) return { ok: false, error: `cannot open ${label} #${number} in the browser` };
7799
7807
  if (res.error) return { ok: false, error: res.error };
7800
7808
  if (typeof res.status === "number" && res.status !== 0) {
7801
7809
  const stderr = (res.stderr || "").trim().split("\n")[0];
7802
- return { ok: false, error: stderr || `cannot open issue #${number} in the browser (gh exited with status ${res.status})` };
7810
+ return { ok: false, error: stderr || `cannot open ${label} #${number} in the browser (gh exited with status ${res.status})` };
7803
7811
  }
7804
7812
  return { ok: true };
7805
7813
  });
7806
7814
  } catch (err) {
7807
- return Promise.resolve({ ok: false, error: (err && err.message) || `cannot open issue #${number} in the browser` });
7815
+ return Promise.resolve({ ok: false, error: (err && err.message) || `cannot open ${label} #${number} in the browser` });
7808
7816
  }
7809
7817
  }
7810
7818
 
7819
+ function issuesOpenInBrowser(hostTui, cwd, number, pinnedIdentity) {
7820
+ return githubItemOpenInBrowser(hostTui, cwd, "issue", number, pinnedIdentity);
7821
+ }
7822
+
7823
+ function prsOpenInBrowser(hostTui, cwd, number, pinnedIdentity) {
7824
+ return githubItemOpenInBrowser(hostTui, cwd, "pr", number, pinnedIdentity);
7825
+ }
7826
+
7811
7827
  function issuesWrapFailure(promise, what) {
7812
7828
  return Promise.resolve(promise).then((res) => {
7813
7829
  if (res && typeof res === "object") return res;
@@ -7917,14 +7933,14 @@ async function issuesBrowserRepoIdentity(gh, checkoutRoot, fresh) {
7917
7933
  // where `openIssuesPanel` releases it, before the human is looking at it). The
7918
7934
  // release is scoped to the token captured HERE, so a typed `/issues` (which owns
7919
7935
  // no token) releases nothing and can never clear a newer click's guard.
7920
- async function executeIssues(rawArgs, ctx, checkoutRoot) {
7936
+ async function executeIssues(rawArgs, ctx, checkoutRoot, pi) {
7921
7937
  const openToken = issuesPanelOpenToken;
7922
7938
  const releaseOpen = () => {
7923
7939
  if (openToken === null) return;
7924
7940
  releaseIssuesPanelOpen(openToken);
7925
7941
  };
7926
7942
  try {
7927
- return await openIssuesPanel(rawArgs, ctx, releaseOpen, checkoutRoot);
7943
+ return await openIssuesPanel(rawArgs, ctx, releaseOpen, checkoutRoot, pi);
7928
7944
  } finally {
7929
7945
  releaseOpen();
7930
7946
  }
@@ -7934,7 +7950,7 @@ async function executeIssues(rawArgs, ctx, checkoutRoot) {
7934
7950
  // command's own gate ALREADY performed (one `git rev-parse` pair) — handed over so
7935
7951
  // the open never pays for a second one. Absent, the open resolves it itself exactly
7936
7952
  // as before.
7937
- async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot) {
7953
+ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot, pi) {
7938
7954
  const notify = ctx && ctx.ui ? ctx.ui.notify : undefined;
7939
7955
  const raw = String(rawArgs ?? "").trim();
7940
7956
  // S7: `/issues <number>` (also `#<number>`) opens the same panel on one
@@ -8114,6 +8130,10 @@ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot)
8114
8130
  // The overlay factory's own host object is what the browser opener suspends.
8115
8131
  // Set just before the factory runs so no action can reach a stale host.
8116
8132
  let hostTuiRef = null;
8133
+ // S6 (prs): the panel's own close, captured from the host's factory, so a
8134
+ // cross-panel click can end this panel before opening the other one.
8135
+ let closePanel = () => {};
8136
+ let panelClosed = false;
8117
8137
  const actions = {
8118
8138
  // Created names go through `gh label create` first, then the whole delta
8119
8139
  // through `gh issue edit`. A failure at either step returns honestly and
@@ -8161,6 +8181,11 @@ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot)
8161
8181
  }
8162
8182
  return issuesOpenInBrowser(hostTuiRef, checkoutRoot, number, pinnedRepo.identity);
8163
8183
  },
8184
+ // S7 (prs): `enter` inserts `ISSUE #N` into the chat input and the view
8185
+ // closes itself; the text is never sent.
8186
+ insert: (text) => panelInsert(ctx, "issues", text),
8187
+ // S6 (prs): a click on one linked pull request opens `/prs N` in its place.
8188
+ openLinked: (link) => openLinkedPanel(pi, link, () => closePanel()),
8164
8189
  };
8165
8190
  // S8 (T4): the identity the panel just proved is the ONLY key that may seed
8166
8191
  // the first frame. Read ONCE, here, so every page of this mount comes from the
@@ -8179,6 +8204,15 @@ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot)
8179
8204
  await ctx.ui.custom(
8180
8205
  (hostTui, theme, _keybindings, done) => {
8181
8206
  hostTuiRef = hostTui;
8207
+ closePanel = () => {
8208
+ if (panelClosed) return;
8209
+ panelClosed = true;
8210
+ try {
8211
+ done(null);
8212
+ } catch {
8213
+ // A host that refuses the close is still the host's own decision.
8214
+ }
8215
+ };
8182
8216
  return libRequire("issues-view.js").createIssuesView({
8183
8217
  // Bucket metadata only: the rows arrive page by page through
8184
8218
  // `loadIssuePage`, so no accumulated list is handed over. The three
@@ -8233,6 +8267,7 @@ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot)
8233
8267
  theme,
8234
8268
  rowsAvailable: () => oddTerminalRows(hostTui),
8235
8269
  requestRender: () => {
8270
+ if (panelClosed) return;
8236
8271
  try {
8237
8272
  if (hostTui && typeof hostTui.requestRender === "function") hostTui.requestRender();
8238
8273
  } catch {
@@ -8252,6 +8287,752 @@ async function openIssuesPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot)
8252
8287
  }
8253
8288
  }
8254
8289
 
8290
+ // ---------------------------------------------------------------------------
8291
+ // S1, S4-S7 (prs panel): `/prs`, the pull-request sibling of `/issues`.
8292
+ //
8293
+ // Every mechanism here is the issues one, deliberately: the SAME `gh` gate and
8294
+ // session probe (invariant 24 — nothing on a session path waits on `gh`), the
8295
+ // same full-screen overlay, the same single-flight open with its one-shot hint,
8296
+ // the same pinned repository identity (invariant 6), the same fail-closed
8297
+ // capabilities (invariant 7 — the view reads them from the pull request's own
8298
+ // `permissions`, which T1 attaches with `includeMetadata`), the same `o` opener
8299
+ // through one fixed argv (invariant 9), and the same `enter` insert / linked
8300
+ // click seams the two views already implement.
8301
+ //
8302
+ // Cross-panel opening (S6): a click on a linked number CLOSES the panel it was
8303
+ // clicked in and dispatches the other command through the SAME single-flight
8304
+ // path a rail click uses, so two panels never stack. A dispatch that cannot
8305
+ // happen (a host without `sendUserMessage`, one that throws) is refused
8306
+ // visibly, exactly like a rail click's refusal.
8307
+ // ---------------------------------------------------------------------------
8308
+
8309
+ // The four buckets the reader's tabs and its lazy `g` view name. The client
8310
+ // derives the search qualifier from the bucket id (`author:@me`,
8311
+ // `review-requested:@me`, `involves:@me`) and reads the repository's own
8312
+ // pull-request connection for an unfiltered `all`, exactly like the issues
8313
+ // client. `lazy` keeps `all` out of the tab bar, the tab cycle and the prefetch.
8314
+ const PRS_INTERACTIVE_BUCKETS = [
8315
+ { id: "mine", label: "My Pull Request" },
8316
+ { id: "review", label: "Needs My Review" },
8317
+ { id: "involved", label: "Involved" },
8318
+ { id: "all", label: "All", connection: true, lazy: true },
8319
+ ];
8320
+ const PRS_FETCH_PAGE_SIZE = 30;
8321
+ // The client fills one GraphQL request with at most this many rows; asking for
8322
+ // more is a bug here, not a bigger read.
8323
+ const PRS_PAGE_MAX = 100;
8324
+
8325
+ const PRS_PANEL_DISPATCH_FAILED = "the host cannot dispatch the /prs command here";
8326
+ // One rail open at a time, the same bounded backstop the issues panel keeps:
8327
+ // `pi.sendUserMessage` returns `void`, so a command the host never runs must not
8328
+ // leave the rail dead. A token from a previous session generation is inert.
8329
+ const PRS_PANEL_OPEN_GUARD_MS = 10000;
8330
+ let prsPanelOpenToken = null;
8331
+ let prsPanelOpenTimer = null;
8332
+ // S5 (T4): the bucket the rail's click named, for the ONE numbered open it
8333
+ // dispatches. Cleared with the token it belongs to.
8334
+ let prsPanelOpenHint = null;
8335
+
8336
+ // The pull-request client is built ONCE per extension load and keeps the issue
8337
+ // client INJECTED: `lib/gh-prs.js` refuses to require it (package-surface pins
8338
+ // that), and the injected instance is the one whose runner seam and scope cache
8339
+ // every read here shares with `/issues`.
8340
+ let prsBoundClient = null;
8341
+ let prsBoundIssues = null;
8342
+
8343
+ // S4 (T4): the rail's stored pull-request read, built lazily like the issues
8344
+ // cache store so a host that never draws the rail never touches the file. A
8345
+ // mutation the panel makes marks its identity here, so the stored entry is never
8346
+ // offered back as if nothing had changed.
8347
+ let prsRailDiskStore = null;
8348
+ const prsRailStaleIdentities = new Set();
8349
+ // S4 (D9): ONE disk read serves BOTH halves of a flight — the section's cold
8350
+ // start hydration (which paints the stored count while `gh` answers) and the
8351
+ // loader's own fallback for a failed live read. The entry is remembered for the
8352
+ // identity it was read for, so a second read of the same identity costs no file.
8353
+ let prsRailStoredIdentity = null;
8354
+ let prsRailStoredEntry = null;
8355
+
8356
+ function clearPrsRailStoredEntry(identity) {
8357
+ if (typeof identity !== "string" || identity.length === 0) {
8358
+ prsRailStoredIdentity = null;
8359
+ prsRailStoredEntry = null;
8360
+ return;
8361
+ }
8362
+ if (prsRailStoredIdentity !== identity) return;
8363
+ prsRailStoredIdentity = null;
8364
+ prsRailStoredEntry = null;
8365
+ }
8366
+
8367
+ // The stored entry for ONE identity: `{ mine, review, counts, syncedAt }`, or
8368
+ // `null` for an identity a panel write invalidated, a document that is missing,
8369
+ // malformed, of a previous version or unreadable, and a host with no store at
8370
+ // all. The `counts` are the bucket totals that slept beside the rows (T10b, S4,
8371
+ // D15), already normalized by the store: a total it could not prove is `null`. It
8372
+ // is read at most once per identity (a `null` is remembered too, so a machine with
8373
+ // no cache file never asks the disk again), which is the same cost the loader
8374
+ // paid before the cold start needed it: no flight reads this file twice.
8375
+ async function loadStoredRailPullRequests(identity) {
8376
+ if (typeof identity !== "string" || identity.length === 0) return null;
8377
+ if (prsRailStaleIdentities.has(identity)) return null;
8378
+ if (prsRailStoredIdentity === identity) return prsRailStoredEntry;
8379
+ const store = prsRailStore();
8380
+ if (store === null) return null;
8381
+ let stored = null;
8382
+ try {
8383
+ stored = await store.load(identity);
8384
+ } catch {
8385
+ stored = null;
8386
+ }
8387
+ // A write made while the disk was answering owns the answer: it is never
8388
+ // remembered, so nothing paints an entry the panel just invalidated.
8389
+ if (prsRailStaleIdentities.has(identity)) return null;
8390
+ prsRailStoredIdentity = identity;
8391
+ prsRailStoredEntry = stored && Array.isArray(stored.mine) && Array.isArray(stored.review) ? stored : null;
8392
+ return prsRailStoredEntry;
8393
+ }
8394
+
8395
+ // T10b (S4, D15): the bucket totals a stored entry carries, or `null` when it
8396
+ // carries none. The store already dropped every total it could not prove (one
8397
+ // below its own rows, one that is not a count), so what arrives here is exactly
8398
+ // what the section's own count may add to the rows it paints.
8399
+ function storedRailCounts(stored) {
8400
+ if (!stored || typeof stored !== "object") return null;
8401
+ const counts = stored.counts;
8402
+ if (!counts || typeof counts !== "object" || Array.isArray(counts)) return null;
8403
+ return {
8404
+ mine: counts.mine === undefined ? null : counts.mine,
8405
+ review: counts.review === undefined ? null : counts.review,
8406
+ };
8407
+ }
8408
+
8409
+ function prsClient() {
8410
+ const issues = libRequire("gh-issues.js");
8411
+ if (prsBoundClient !== null && prsBoundIssues === issues) return prsBoundClient;
8412
+ const factory = libRequire("gh-prs.js");
8413
+ if (!factory || typeof factory.createPrsClient !== "function") {
8414
+ throw new Error("the pull-request client is unavailable");
8415
+ }
8416
+ prsBoundIssues = issues;
8417
+ prsBoundClient = factory.createPrsClient({ issues });
8418
+ return prsBoundClient;
8419
+ }
8420
+
8421
+ function prsRailStore() {
8422
+ if (prsRailDiskStore !== null) return prsRailDiskStore;
8423
+ try {
8424
+ const factory = libRequire("prs-rail-store.js");
8425
+ if (!factory || typeof factory.createPrsRailStore !== "function") return null;
8426
+ prsRailDiskStore = factory.createPrsRailStore();
8427
+ } catch {
8428
+ prsRailDiskStore = null;
8429
+ }
8430
+ return prsRailDiskStore;
8431
+ }
8432
+
8433
+ function clearPrsPanelOpenTimer() {
8434
+ if (prsPanelOpenTimer === null) return;
8435
+ const timer = prsPanelOpenTimer;
8436
+ prsPanelOpenTimer = null;
8437
+ try {
8438
+ clearTimeout(timer);
8439
+ } catch {
8440
+ // A host timer that cannot be cancelled still fires into a released guard.
8441
+ }
8442
+ }
8443
+
8444
+ // Idempotent, and scoped to one token when one is named, so a release can never
8445
+ // clear a NEWER open's guard.
8446
+ function releasePrsPanelOpen(token) {
8447
+ if (token !== undefined && prsPanelOpenToken !== token) return;
8448
+ clearPrsPanelOpenTimer();
8449
+ prsPanelOpenToken = null;
8450
+ prsPanelOpenHint = null;
8451
+ }
8452
+
8453
+ function prsPanelOpenBlocked() {
8454
+ if (prsPanelOpenToken === null) return false;
8455
+ return prsPanelOpenToken.generation === issuesSidebarCacheGeneration;
8456
+ }
8457
+
8458
+ // The bucket a rail click left for the numbered open it dispatches. It applies
8459
+ // to the SAME number only, and only in the generation it was recorded under;
8460
+ // taking it consumes it. A hint for another number is left alone.
8461
+ function takePrsPanelOpenBucketHint(number) {
8462
+ const hint = prsPanelOpenHint;
8463
+ if (hint === null) return null;
8464
+ if (!Number.isInteger(number) || hint.number !== number) return null;
8465
+ if (hint.generation !== issuesSidebarCacheGeneration) return null;
8466
+ prsPanelOpenHint = null;
8467
+ return hint.bucket;
8468
+ }
8469
+
8470
+ function prsBucketHint(bucket) {
8471
+ return bucket === "mine" || bucket === "review" || bucket === "involved" || bucket === "all"
8472
+ ? bucket
8473
+ : null;
8474
+ }
8475
+
8476
+ function armPrsPanelOpenGuard(token) {
8477
+ clearPrsPanelOpenTimer();
8478
+ let timer = null;
8479
+ try {
8480
+ timer = setTimeout(() => {
8481
+ releasePrsPanelOpen(token);
8482
+ }, PRS_PANEL_OPEN_GUARD_MS);
8483
+ } catch {
8484
+ timer = null;
8485
+ }
8486
+ // Unref'd: the interval is a safety net for the rail, never a reason for the
8487
+ // process to stay alive.
8488
+ if (timer && typeof timer.unref === "function") {
8489
+ try {
8490
+ timer.unref();
8491
+ } catch {
8492
+ // A host timer without a working unref still bounds the wait.
8493
+ }
8494
+ }
8495
+ prsPanelOpenTimer = timer;
8496
+ }
8497
+
8498
+ // A missing binary needs an install plus login; anything else already carries
8499
+ // gh's own `gh auth login` wording. The note says the command cannot OPEN,
8500
+ // never that it is unregistered, because registration is eager.
8501
+ function prsGateMessage(error) {
8502
+ const text = String(error || "gh check failed");
8503
+ if (/ENOENT|not available|not found/i.test(text)) {
8504
+ return "prs: the gh CLI is not available; install it (https://cli.github.com) and run `gh auth login` — /prs cannot open until then";
8505
+ }
8506
+ return `prs: ${text} — /prs cannot open until then`;
8507
+ }
8508
+
8509
+ // S7 (both panels): `enter` hands one line to the host's own insertion seam and
8510
+ // NOTHING is sent. `ctx.ui.pasteToEditor` is the seam the file picker's insert
8511
+ // already uses, so the chat input is the same editor and the fallback line is
8512
+ // the same honest one.
8513
+ function panelInsert(ctx, label, text) {
8514
+ const value = typeof text === "string" ? text : "";
8515
+ if (value.length === 0) return;
8516
+ try {
8517
+ if (ctx && ctx.ui && typeof ctx.ui.pasteToEditor === "function") {
8518
+ ctx.ui.pasteToEditor(value);
8519
+ return;
8520
+ }
8521
+ } catch {
8522
+ // Fall through to the honest line: the text never reached the editor.
8523
+ }
8524
+ const notify = ctx && ctx.ui ? ctx.ui.notify : undefined;
8525
+ if (typeof notify === "function") notify(`${label}: the editor did not accept the insertion: ${value}`, "warning");
8526
+ }
8527
+
8528
+ // S6 (both panels): one linked number opens the OTHER panel on that number. The
8529
+ // current panel is closed FIRST (never stacked), and the other one is dispatched
8530
+ // through the same single-flight path a rail click uses. While that other open is
8531
+ // already in flight the click changes nothing and the panel stays where it is,
8532
+ // instead of closing onto a dispatch that would be dropped.
8533
+ function openLinkedPanel(pi, link, closePanel) {
8534
+ const kind = link && (link.kind === "issue" || link.kind === "pullRequest") ? link.kind : null;
8535
+ const number = link ? Number(link.number) : NaN;
8536
+ if (kind === null || !Number.isInteger(number) || number <= 0) return;
8537
+ if (kind === "issue" ? issuesPanelOpenBlocked() : prsPanelOpenBlocked()) return;
8538
+ try {
8539
+ closePanel();
8540
+ } catch {
8541
+ // A host that refuses the close still gets the dispatch below.
8542
+ }
8543
+ if (kind === "issue") dispatchIssuesPanel(pi, number);
8544
+ else dispatchPrsPanel(pi, number);
8545
+ }
8546
+
8547
+ // S4 (T4): a panel write changed the repository's pull requests, so the rail's
8548
+ // count is no longer what its read said. The identity is marked so the disk half
8549
+ // cannot hand the old rows back, and the rail reads NOW when it is on screen (a
8550
+ // human's save is one action, so it is neither a script that needs the bash
8551
+ // anti-storm cap nor something to wait a floor for). Nothing here starts a read
8552
+ // for a section nobody is drawing (S11).
8553
+ function invalidatePrsRail(identity) {
8554
+ if (typeof identity === "string" && identity.length > 0) prsRailStaleIdentities.add(identity);
8555
+ // D9: the entry remembered for a cold start is gone with it.
8556
+ clearPrsRailStoredEntry(identity);
8557
+ const handle = issuesSidebarHandle;
8558
+ if (!handle) return;
8559
+ try {
8560
+ if (typeof handle.drawnWithin !== "function") return;
8561
+ if (handle.drawnWithin(ISSUES_SIDEBAR_DRAWN_WINDOW_MS) !== true) return;
8562
+ // FORCED, not merely refreshed: the section's pull-request read holds its own
8563
+ // TTL, so a plain `refresh()` would leave the stale count on screen after the
8564
+ // write the human just made. `forceRefresh(0)` reads both halves now (a
8565
+ // human's save is one action, so no anti-storm cap applies).
8566
+ if (typeof handle.forceRefresh === "function") {
8567
+ handle.forceRefresh(0);
8568
+ return;
8569
+ }
8570
+ if (typeof handle.refresh !== "function") return;
8571
+ const pending = handle.refresh();
8572
+ if (pending && typeof pending.catch === "function") pending.catch(() => {});
8573
+ } catch {
8574
+ // The rail is optional: a failed refresh never breaks the panel's write.
8575
+ }
8576
+ }
8577
+
8578
+ // S4 (T4): the rail's second read. ONE aliased GraphQL answers both counted
8579
+ // buckets; the identity is proved with the SAME composition the issues read and
8580
+ // the panel pin use, so the count and the click's routing belong to one
8581
+ // repository. The disk entry is a FALLBACK for a failed live read only — the rail
8582
+ // never paints a stored count as if the network had answered — and the entry is
8583
+ // written only from here, after a successful read in the generation that asked.
8584
+ // No session context reads nothing, and a missing `gh` costs no child.
8585
+ async function loadIssuesRailPullRequests() {
8586
+ const generation = issuesSidebarCacheGeneration;
8587
+ if (issuesGhCliMissing()) {
8588
+ return { ok: false, error: ISSUES_GH_CLI_MISSING_RAIL, errorTone: "dim" };
8589
+ }
8590
+ if (issuesSidebarCtx === null) {
8591
+ return { ok: false, error: "cannot read pull requests: the session has ended" };
8592
+ }
8593
+ const cwd = toolCwd(issuesSidebarCtx);
8594
+ let issues;
8595
+ let prs;
8596
+ try {
8597
+ issues = libRequire("gh-issues.js");
8598
+ prs = prsClient();
8599
+ } catch (err) {
8600
+ return { ok: false, error: `pull requests: cannot load the gh client: ${issuesSidebarError(err, "unknown error")}` };
8601
+ }
8602
+ const checkoutRoot = await oddCheckoutRootAsync(cwd);
8603
+ if (!checkoutRoot) return { ok: false, error: ISSUES_SIDEBAR_NOT_REPOSITORY, errorTone: "dim" };
8604
+ let resolved = null;
8605
+ try {
8606
+ resolved = await issuesBrowserRepoIdentity(issues, checkoutRoot);
8607
+ } catch (err) {
8608
+ resolved = { ok: false, error: issuesSidebarError(err, "cannot resolve this checkout's own repository") };
8609
+ }
8610
+ if (!resolved || resolved.ok !== true) {
8611
+ if (resolved && resolved.noRemote === true) {
8612
+ return { ok: false, error: ISSUES_SIDEBAR_NOT_GITHUB, errorTone: "dim" };
8613
+ }
8614
+ return { ok: false, error: (resolved && resolved.error) || "cannot resolve this checkout's own repository" };
8615
+ }
8616
+ const identity = resolved.identity;
8617
+ const store = prsRailStore();
8618
+ // D9: the stored entry is the SAME one the section's cold-start hydration asks
8619
+ // for, so a flight reads the document once and both halves agree on it.
8620
+ const stored = await loadStoredRailPullRequests(identity);
8621
+ let read = null;
8622
+ try {
8623
+ read = await prs.listRailPullRequests({}, { cwd: checkoutRoot, scope: identity });
8624
+ } catch (err) {
8625
+ read = { ok: false, error: issuesSidebarError(err, "GitHub query failed") };
8626
+ }
8627
+ if (!read || read.ok !== true) {
8628
+ // A failed live read paints the last SUCCESSFUL one when the disk has it, so
8629
+ // a cold start is not blank; nothing else is written from a failure.
8630
+ if (stored && Array.isArray(stored.mine) && Array.isArray(stored.review)) {
8631
+ // T10b (S4, D15): the fallback carries the bucket totals too, so the number
8632
+ // the last read painted survives the failure as well as the rows do.
8633
+ return {
8634
+ ok: true,
8635
+ identity,
8636
+ mine: stored.mine,
8637
+ review: stored.review,
8638
+ counts: storedRailCounts(stored),
8639
+ cached: true,
8640
+ };
8641
+ }
8642
+ return { ok: false, error: (read && read.error) || "GitHub query failed" };
8643
+ }
8644
+ prsRailStaleIdentities.delete(identity);
8645
+ // D8 (S4): the buckets' EXACT totals travel with their rows — the section
8646
+ // counts what the window cut as well as the numbers it carried. T10b (S4, D15):
8647
+ // they are also what the entry keeps, so a restart paints the same number.
8648
+ const counts = read.counts && typeof read.counts === "object" ? read.counts : null;
8649
+ if (store !== null && issuesSidebarCacheGeneration === generation) {
8650
+ const snapshot = {
8651
+ mine: read.mine,
8652
+ review: read.review,
8653
+ ...(counts === null ? {} : { counts }),
8654
+ syncedAt: Date.now(),
8655
+ };
8656
+ // The live answer IS what the entry now holds, so a later cold start paints
8657
+ // it without another read of the file.
8658
+ prsRailStoredIdentity = identity;
8659
+ prsRailStoredEntry = { ...snapshot };
8660
+ // Fire and forget: the answer is already visible, and a slow disk must not
8661
+ // hold the rail's next read.
8662
+ Promise.resolve().then(() => store.save(identity, snapshot)).catch(() => {});
8663
+ }
8664
+ return { ok: true, identity, mine: read.mine, review: read.review, ...(counts === null ? {} : { counts }) };
8665
+ }
8666
+
8667
+ // D9 (S4): the stored entry, asked BESIDE the live read by the section's own
8668
+ // dispatched pull-request read, so a cold start paints `N issues · M pr` while
8669
+ // `gh` is still answering. It is the same document `loadIssuesRailPullRequests`
8670
+ // writes, read for the identity the issues read just PROVED — so no entry is ever
8671
+ // painted under another repository's name — and it answers `null` for anything
8672
+ // that must not hydrate: no session, no `gh` CLI (a settled `dim` state reads no
8673
+ // disk at all, invariant 28), an identity a panel write invalidated (invariant
8674
+ // 25), or a document that is missing or unreadable. Nothing here is awaited by a
8675
+ // frame or a session path: only the section's async loader calls it.
8676
+ async function hydrateIssuesRailPullRequests(identity) {
8677
+ if (typeof identity !== "string" || identity.length === 0) return null;
8678
+ if (issuesGhCliMissing()) return null;
8679
+ if (issuesSidebarCtx === null) return null;
8680
+ if (prsRailStaleIdentities.has(identity)) return null;
8681
+ const stored = await loadStoredRailPullRequests(identity);
8682
+ if (!stored) return null;
8683
+ return { mine: stored.mine, review: stored.review, counts: storedRailCounts(stored), syncedAt: stored.syncedAt };
8684
+ }
8685
+
8686
+ function registerPrsCommand(pi) {
8687
+ if (typeof pi?.registerCommand !== "function") return;
8688
+ // S13 (T11) parity: without the `gh` CLI this command could do nothing, so it
8689
+ // is never registered — the same registration-time decision `/issues` makes.
8690
+ if (ISSUES_GH_CLI_ABSENT) return;
8691
+ const handler = async (args, ctx) => {
8692
+ const notify = ctx && ctx.ui ? ctx.ui.notify : undefined;
8693
+ const gate = await probeIssuesGate(ctx);
8694
+ if (gate.ok !== true) {
8695
+ releasePrsPanelOpen();
8696
+ if (gate.notRepository === true) {
8697
+ if (typeof notify === "function") notify(notGitRepositoryLine(toolCwd(ctx)), "info");
8698
+ return;
8699
+ }
8700
+ if (typeof notify === "function") notify(prsGateMessage(gate.error), "error");
8701
+ return;
8702
+ }
8703
+ await executePrs(args, ctx, gate.checkoutRoot, pi);
8704
+ };
8705
+ pi.registerCommand("prs", {
8706
+ description: "Browse fresh GitHub pull request pages and details; comment, label, assign, link, merge or close when permitted",
8707
+ handler,
8708
+ });
8709
+ }
8710
+
8711
+ // The rail click that dispatched this command owns the single-flight guard, and
8712
+ // EVERY exit of the open releases it, exactly like `executeIssues`. The release
8713
+ // is scoped to the token captured HERE, so a typed `/prs` releases nothing and
8714
+ // can never clear a newer click's guard.
8715
+ async function executePrs(rawArgs, ctx, checkoutRoot, pi) {
8716
+ const openToken = prsPanelOpenToken;
8717
+ const releaseOpen = () => {
8718
+ if (openToken === null) return;
8719
+ releasePrsPanelOpen(openToken);
8720
+ };
8721
+ try {
8722
+ return await openPrsPanel(rawArgs, ctx, releaseOpen, checkoutRoot, pi);
8723
+ } finally {
8724
+ releaseOpen();
8725
+ }
8726
+ }
8727
+
8728
+ // The no-UI fallback: the three scoped reads happen together; partial failure
8729
+ // keeps what answered and reports the first error, and a total failure claims no
8730
+ // rows.
8731
+ async function prsFetchPages(prs, cwd, scope) {
8732
+ const specs = PRS_INTERACTIVE_BUCKETS.filter((spec) => spec.lazy !== true);
8733
+ const outcomes = await Promise.all(specs.map(async (spec) => {
8734
+ try {
8735
+ const res = await prs.getPullRequestPage(
8736
+ { bucket: spec.id, pageSize: PRS_FETCH_PAGE_SIZE },
8737
+ { cwd, scope },
8738
+ );
8739
+ if (res && res.ok === true) {
8740
+ return { ok: true, rows: Array.isArray(res.rows) ? res.rows : [] };
8741
+ }
8742
+ return { ok: false, error: (res && res.error) || "gh pr list failed", rows: [] };
8743
+ } catch (err) {
8744
+ return { ok: false, error: (err && err.message) || "gh pr list failed", rows: [] };
8745
+ }
8746
+ }));
8747
+ const firstError = outcomes.find((outcome) => outcome.ok !== true);
8748
+ if (!outcomes.some((outcome) => outcome.ok === true)) {
8749
+ return { ok: false, error: (firstError && firstError.error) || "gh pr list failed", pages: outcomes.length };
8750
+ }
8751
+ return {
8752
+ ok: true,
8753
+ rows: outcomes.flatMap((outcome) => outcome.rows),
8754
+ pages: outcomes.length,
8755
+ loadError: firstError ? firstError.error : null,
8756
+ };
8757
+ }
8758
+
8759
+ async function openPrsPanel(rawArgs, ctx, releaseOpen, resolvedCheckoutRoot, pi) {
8760
+ const notify = ctx && ctx.ui ? ctx.ui.notify : undefined;
8761
+ const raw = String(rawArgs ?? "").trim();
8762
+ // `/prs <number>` (also `#<number>`) opens the same panel on one pull request.
8763
+ // ONLY a bare positive integer is accepted; every other argument keeps this
8764
+ // command's refusal, so a typo and a second argument behave exactly as before.
8765
+ let initialPullRequest = null;
8766
+ if (raw !== "") {
8767
+ const match = /^#?(\d+)$/.exec(raw);
8768
+ const number = match ? Number(match[1]) : NaN;
8769
+ if (!match || !Number.isInteger(number) || number <= 0) {
8770
+ if (typeof notify === "function") notify(`Unknown option "${raw}". Use /prs.`, "error");
8771
+ return;
8772
+ }
8773
+ initialPullRequest = number;
8774
+ }
8775
+ const cwd = toolCwd(ctx);
8776
+ const checkoutRoot = typeof resolvedCheckoutRoot === "string" && resolvedCheckoutRoot.length > 0
8777
+ ? resolvedCheckoutRoot
8778
+ : await oddCheckoutRootAsync(cwd);
8779
+ if (!checkoutRoot) {
8780
+ if (typeof notify === "function") notify(notGitRepositoryLine(cwd), "info");
8781
+ return;
8782
+ }
8783
+ let issues = null;
8784
+ let prs = null;
8785
+ try {
8786
+ issues = libRequire("gh-issues.js");
8787
+ prs = prsClient();
8788
+ } catch (err) {
8789
+ if (typeof notify === "function") notify(`prs: cannot load the gh client: ${(err && err.message) || err}`, "error");
8790
+ return;
8791
+ }
8792
+ // S5 (T4): a rail click leaves the bucket its row belonged to as a one-shot
8793
+ // hint, so the panel opens on the list that actually holds the pull request.
8794
+ // A typed `/prs N` has no hint and the view's own fallback decides.
8795
+ const hintedBucket = initialPullRequest === null ? null : takePrsPanelOpenBucketHint(initialPullRequest);
8796
+ const effectiveRepo = async (fresh) => issuesBrowserRepoIdentity(issues, checkoutRoot, fresh);
8797
+ const pinIdentity = (fresh) => effectiveRepo(fresh)
8798
+ .catch(() => ({ ok: false, error: "cannot resolve this checkout's own repository" }));
8799
+ let pinnedRepo;
8800
+ let pinnedPromise = null;
8801
+ const pinRepo = async () => {
8802
+ if (pinnedRepo !== undefined) return pinnedRepo;
8803
+ if (pinnedPromise === null) {
8804
+ // A numbered open — the form the rail dispatches — pins the scope the
8805
+ // checkout already proved, so its first frame is not behind a fresh probe;
8806
+ // a plain `/prs` keeps the fresh proof, and a cached pin that cannot be
8807
+ // read falls back to it ONCE. Nothing that mutates rides the pin: every
8808
+ // action still re-proves the checkout in `scopeDrift`.
8809
+ const pin = initialPullRequest === null
8810
+ ? pinIdentity(true)
8811
+ : pinIdentity(false).then((cached) => (cached && cached.ok === true ? cached : pinIdentity(true)));
8812
+ pinnedPromise = pin.then((pinned) => {
8813
+ pinnedRepo = pinned;
8814
+ return pinned;
8815
+ });
8816
+ }
8817
+ return pinnedPromise;
8818
+ };
8819
+ const pinnedReadArgs = async () => {
8820
+ const pinned = await pinRepo();
8821
+ if (!pinned || pinned.ok !== true) {
8822
+ return { ok: false, error: (pinned && pinned.error) || "cannot resolve this checkout's own repository" };
8823
+ }
8824
+ return { ok: true, args: { cwd: checkoutRoot, scope: pinned.identity } };
8825
+ };
8826
+ // An action runs only while the checkout still resolves to the displayed
8827
+ // repository and then BINDS the pinned identity, so a displayed number can
8828
+ // never be sent to another repository (invariant 6).
8829
+ const scopeDrift = async () => {
8830
+ const pinned = await pinRepo();
8831
+ if (!pinned || pinned.ok !== true) {
8832
+ return { ok: false, error: (pinned && pinned.error) || "cannot resolve this checkout's own repository" };
8833
+ }
8834
+ const current = await effectiveRepo(true);
8835
+ if (!current || current.ok !== true) {
8836
+ return { ok: false, error: (current && current.error) || "cannot verify this checkout's own repository" };
8837
+ }
8838
+ if (current.identity !== pinned.identity) {
8839
+ // D10 (S2): a `/prs` action tells the human to reopen `/prs`.
8840
+ return { ok: false, error: issuesScopeDriftLine(current.identity, pinned.identity, "/prs") };
8841
+ }
8842
+ return { ok: true, scope: pinned.identity };
8843
+ };
8844
+ // One page per request through the real client: `mine`, `review` and
8845
+ // `involved` are repository searches with the reader's text appended, and an
8846
+ // unfiltered `all` is the repository connection with an exact total. A typed
8847
+ // query inside `all` stays a capped search, exactly like issues.
8848
+ const loadPullRequestPage = (request = {}) => {
8849
+ const spec = PRS_INTERACTIVE_BUCKETS.find((bucket) => bucket.id === request.bucketId);
8850
+ if (!spec) return { ok: false, error: `unknown prs bucket "${String(request.bucketId)}"` };
8851
+ const asked = Number(request.limit);
8852
+ const limit = Number.isFinite(asked) ? Math.min(PRS_PAGE_MAX, Math.max(1, Math.floor(asked))) : 1;
8853
+ const cursor = request.cursor == null || request.cursor === "" ? null : String(request.cursor);
8854
+ const typed = typeof request.query === "string" ? request.query.trim() : "";
8855
+ return issuesWrapFailure((async () => {
8856
+ const pinned = await pinnedReadArgs();
8857
+ if (pinned.ok !== true) return pinned;
8858
+ if (spec.connection === true && typed === "") {
8859
+ if (typeof prs.getPullRequestConnectionPage !== "function") {
8860
+ return { ok: false, error: "cannot read pull requests: the gh client has no unfiltered pull request connection reader" };
8861
+ }
8862
+ return await prs.getPullRequestConnectionPage({ cursor, pageSize: limit }, pinned.args);
8863
+ }
8864
+ return await prs.getPullRequestPage({ bucket: spec.id, cursor, pageSize: limit, query: typed }, pinned.args);
8865
+ })(), "cannot read pull requests");
8866
+ };
8867
+ const loadLabels = async () => {
8868
+ const pinned = await pinnedReadArgs();
8869
+ if (pinned.ok !== true) return pinned;
8870
+ return await prs.listLabels(pinned.args);
8871
+ };
8872
+ const loadAssignees = async () => {
8873
+ const pinned = await pinnedReadArgs();
8874
+ if (pinned.ok !== true) return pinned;
8875
+ return await prs.listAssignableUsers(pinned.args);
8876
+ };
8877
+ const helpersPromise = Promise.resolve()
8878
+ .then(() => issuesTuiLoader())
8879
+ .catch(() => null);
8880
+ const [helpers] = await Promise.all([helpersPromise, pinRepo()]);
8881
+ if (!helpers || !ctx || !ctx.ui || typeof ctx.ui.custom !== "function") {
8882
+ const pinned = await pinnedReadArgs();
8883
+ const loaded = pinned.ok === true
8884
+ ? await prsFetchPages(prs, checkoutRoot, pinned.args.scope)
8885
+ : { ok: false, error: pinned.error, rows: [] };
8886
+ if (typeof notify === "function") {
8887
+ if (loaded.ok !== true) notify(`prs: ${loaded.error || "gh pr list failed"}`, "info");
8888
+ else notify(`prs: ${loaded.rows.length} pull request(s) across ${loaded.pages} pages (the viewer needs an interactive session)`, "info");
8889
+ }
8890
+ return;
8891
+ }
8892
+ // The overlay factory's own host object is what the browser opener suspends.
8893
+ let hostTuiRef = null;
8894
+ // S6: the panel's own close, captured from the host's factory, so a cross-panel
8895
+ // click can end it before opening the other one.
8896
+ let closePanel = () => {};
8897
+ let panelClosed = false;
8898
+ // S4: every successful write invalidates the rail's count for THIS repository.
8899
+ const afterRailMutation = (result) => {
8900
+ if (result && result.ok === true) {
8901
+ invalidatePrsRail(pinnedRepo && pinnedRepo.ok === true ? pinnedRepo.identity : null);
8902
+ }
8903
+ return result;
8904
+ };
8905
+ const mutate = (what, run) => issuesWrapFailure((async () => {
8906
+ const gate = await scopeDrift();
8907
+ if (gate.ok !== true) return gate;
8908
+ return afterRailMutation(await run({ cwd: checkoutRoot, scope: gate.scope }));
8909
+ })(), what);
8910
+ const actions = {
8911
+ // Created names go through `gh label create` first, then the whole delta
8912
+ // through `gh pr edit`; a failure at either step returns honestly and the
8913
+ // view keeps the editor open with local state unchanged.
8914
+ editLabels: (number, add, remove, created) => mutate("cannot edit labels", async (args) => {
8915
+ for (const name of Array.isArray(created) ? created : []) {
8916
+ if (typeof name !== "string" || name === "") continue;
8917
+ const made = await prs.createLabel({ name }, args);
8918
+ if (!made || made.ok !== true) return { ok: false, error: (made && made.error) || `cannot create label ${name}` };
8919
+ }
8920
+ return await prs.editLabels(number, { add, remove }, args);
8921
+ }),
8922
+ commentPullRequest: (number, text) => mutate("cannot comment", (args) => prs.commentPullRequest(number, text, args)),
8923
+ editAssignees: (number, changes) => mutate("cannot edit assignees", (args) => prs.editAssignees(number, changes, args)),
8924
+ closePullRequest: (number) => mutate("cannot close the pull request", (args) => prs.closePullRequest(number, args)),
8925
+ mergePullRequest: (number, entry) => mutate("cannot merge the pull request", (args) => prs.mergePullRequest(number, entry, args)),
8926
+ editLinkedIssues: (number, changes) => mutate("cannot edit the linked issues", (args) => prs.editLinkedIssues(number, changes, args)),
8927
+ // S7: `enter` inserts `PR #N` into the chat input and the view closes itself.
8928
+ insert: (text) => panelInsert(ctx, "prs", text),
8929
+ // S6: a click on one linked issue opens `/issues N` in its place.
8930
+ openLinked: (link) => openLinkedPanel(pi, link, () => closePanel()),
8931
+ openBrowser: (number) => {
8932
+ if (pinnedRepo === undefined) return { ok: false, error: "the pull request list has not loaded a repository yet" };
8933
+ if (pinnedRepo.ok !== true) {
8934
+ return { ok: false, error: pinnedRepo.error || "cannot resolve this checkout's own repository" };
8935
+ }
8936
+ return prsOpenInBrowser(hostTuiRef, checkoutRoot, number, pinnedRepo.identity);
8937
+ },
8938
+ };
8939
+ // S1 (issues-sidebar-click T1): the open is over the moment the panel mounts,
8940
+ // so the rail's clicks take effect again from the next frame on.
8941
+ releaseOpen();
8942
+ try {
8943
+ await ctx.ui.custom(
8944
+ (hostTui, theme, _keybindings, done) => {
8945
+ hostTuiRef = hostTui;
8946
+ closePanel = () => {
8947
+ if (panelClosed) return;
8948
+ panelClosed = true;
8949
+ try {
8950
+ done(null);
8951
+ } catch {
8952
+ // A host that refuses the close is still the host's own decision.
8953
+ }
8954
+ };
8955
+ return libRequire("prs-view.js").createPrsView({
8956
+ pages: PRS_INTERACTIVE_BUCKETS.map((spec) => ({
8957
+ id: spec.id,
8958
+ label: spec.label,
8959
+ rows: null,
8960
+ lazy: spec.lazy === true,
8961
+ })),
8962
+ loadPullRequestPage,
8963
+ // S1/T4: a numbered open starts on the bucket the rail's click named,
8964
+ // with that pull request pending selection; the command already
8965
+ // refused anything that is not a positive integer.
8966
+ ...(initialPullRequest === null
8967
+ ? {}
8968
+ : { initialPullRequest, ...(hintedBucket === null ? {} : { initialBucket: hintedBucket }) }),
8969
+ loadLabels,
8970
+ loadAssignees,
8971
+ prefetchBuckets: true,
8972
+ // `includeMetadata` is what carries the permissions, the merge methods
8973
+ // and the linked issues into the pane: without it the view sees no
8974
+ // confirmed capability and offers no editor or merge step (invariant 7).
8975
+ loadPullRequest: async (number) => {
8976
+ const pinned = await pinnedReadArgs();
8977
+ if (pinned.ok !== true) return pinned;
8978
+ return await prs.getPullRequest(number, { includeMetadata: true }, pinned.args);
8979
+ },
8980
+ actions,
8981
+ helpers,
8982
+ theme,
8983
+ rowsAvailable: () => oddTerminalRows(hostTui),
8984
+ requestRender: () => {
8985
+ if (panelClosed) return;
8986
+ try {
8987
+ if (hostTui && typeof hostTui.requestRender === "function") hostTui.requestRender();
8988
+ } catch {
8989
+ // A repaint failure never breaks navigation.
8990
+ }
8991
+ },
8992
+ done,
8993
+ });
8994
+ },
8995
+ // Full screen like the odd viewer and the issues reader.
8996
+ { overlay: true, overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%", margin: 0 } },
8997
+ );
8998
+ } catch {
8999
+ if (typeof notify === "function") notify("prs: the viewer could not open in this session", "info");
9000
+ }
9001
+ }
9002
+
9003
+ // The rail's PR open: one token, one dispatch, and the bucket its row named as a
9004
+ // one-shot hint for the command the host runs next. Refusals are the issues
9005
+ // panel's (one transcript entry, else the notice seam), because there is one
9006
+ // visible surface for a rail click that cannot be dispatched at all.
9007
+ function dispatchPrsPanel(pi, number, bucket) {
9008
+ // S1: a click while a rail open is in flight has no effect at all.
9009
+ if (prsPanelOpenBlocked()) return { ok: true };
9010
+ const token = { generation: issuesSidebarCacheGeneration };
9011
+ prsPanelOpenToken = token;
9012
+ const asked = Number(number);
9013
+ const namesPullRequest = Number.isInteger(asked) && asked > 0;
9014
+ const bucketHint = namesPullRequest ? prsBucketHint(bucket) : null;
9015
+ prsPanelOpenHint = namesPullRequest
9016
+ ? { number: asked, bucket: bucketHint, generation: token.generation }
9017
+ : null;
9018
+ armPrsPanelOpenGuard(token);
9019
+ const command = namesPullRequest ? `/prs ${asked}` : "/prs";
9020
+ if (!pi || typeof pi.sendUserMessage !== "function") {
9021
+ releasePrsPanelOpen(token);
9022
+ announceIssuesPanelRefusal(pi, PRS_PANEL_DISPATCH_FAILED);
9023
+ return { ok: false, error: PRS_PANEL_DISPATCH_FAILED };
9024
+ }
9025
+ try {
9026
+ pi.sendUserMessage(command, { expandPromptTemplates: true });
9027
+ } catch (err) {
9028
+ releasePrsPanelOpen(token);
9029
+ const message = `the /prs command could not be dispatched: ${issuesSidebarError(err, "unknown error")}`;
9030
+ announceIssuesPanelRefusal(pi, message);
9031
+ return { ok: false, error: message };
9032
+ }
9033
+ return { ok: true };
9034
+ }
9035
+
8255
9036
  // A missing binary needs an install plus login; anything else already carries
8256
9037
  // gh's own `gh auth login` wording. The note says the command cannot OPEN,
8257
9038
  // never that it is unregistered, because registration is eager.
@@ -8488,7 +9269,7 @@ function registerIssuesCommand(pi) {
8488
9269
  if (typeof notify === "function") notify(issuesGateMessage(gate.error), "error");
8489
9270
  return;
8490
9271
  }
8491
- await executeIssues(args, ctx, gate.checkoutRoot);
9272
+ await executeIssues(args, ctx, gate.checkoutRoot, pi);
8492
9273
  };
8493
9274
  pi.registerCommand("issues", {
8494
9275
  description: "Browse fresh GitHub issue pages and details; edit labels/assignees, comment or close when permitted",
@@ -9166,6 +9947,7 @@ function mountIssuesSidebar(pi, api) {
9166
9947
  // single-flight guard instead of leaving it to its timer.
9167
9948
  issuesSidebarCacheGeneration += 1;
9168
9949
  releaseIssuesPanelOpen();
9950
+ releasePrsPanelOpen();
9169
9951
  const onRefreshed = typeof api.requestRepaint === "function"
9170
9952
  ? () => {
9171
9953
  try {
@@ -9179,6 +9961,18 @@ function mountIssuesSidebar(pi, api) {
9179
9961
  try {
9180
9962
  handle = factory.createIssuesSection({
9181
9963
  load: () => loadIssuesSidebar(),
9964
+ // S4 (T4): the second read — the viewer's own pull requests and the ones
9965
+ // awaiting their review — paints the header's `· N pr` and routes a row's
9966
+ // click to its linked pull request. The section starts it only after the
9967
+ // issues read proved a repository, and it keeps the `github` row label the
9968
+ // human named in customize.
9969
+ loadPullRequests: () => loadIssuesRailPullRequests(),
9970
+ // D9 (S4): the persisted count paints a cold start while that read is in
9971
+ // flight. Hydration belongs to the read alone — this seam is reached only
9972
+ // from the section's async loader, never from a frame or a session path —
9973
+ // and the live answer always replaces what it painted.
9974
+ hydratePullRequests: (identity) => hydrateIssuesRailPullRequests(identity),
9975
+ rowLabel: "github",
9182
9976
  // S10 (T8, L9): the rail re-reads on TIME, not on the session's activity.
9183
9977
  // The section owns the timer (armed by a draw, unref'd, cleared by
9184
9978
  // `invalidate()`/`dispose()`) and stops it once the section leaves the
@@ -9191,7 +9985,16 @@ function mountIssuesSidebar(pi, api) {
9191
9985
  // path (`dispatchIssuesPanel` is synchronous). `openIssuesSidebarIssue` (the
9192
9986
  // browser opener this seam used to run) is gone with its only caller —
9193
9987
  // `issuesOpenInBrowser` survives for `/issues`' own `o` key.
9194
- open: (number, identity, bucket, generation) => dispatchIssuesPanel(pi, number, identity, bucket, generation),
9988
+ // S5 (T4): a row whose issue links a pull request carries the routed
9989
+ // destination instead of a click identity — the PR panel opens on THAT
9990
+ // number with the bucket its row belonged to. Every other row keeps the
9991
+ // old call, and the overflow row still opens the issues reader.
9992
+ open: (number, identity, bucket, generation) => {
9993
+ if (identity && typeof identity === "object" && Number.isInteger(identity.pullRequest)) {
9994
+ return dispatchPrsPanel(pi, identity.pullRequest, identity.pullRequestBucket);
9995
+ }
9996
+ return dispatchIssuesPanel(pi, number, identity, bucket, generation);
9997
+ },
9195
9998
  openAll: () => dispatchIssuesPanel(pi),
9196
9999
  onRefreshed,
9197
10000
  });
@@ -9612,6 +10415,35 @@ function refreshIssuesSidebarIfDrawn() {
9612
10415
  }
9613
10416
  }
9614
10417
 
10418
+ // S5 (T4/S5): was the rail on screen in the session a boundary is replacing? A
10419
+ // hidden section answers false and keeps costing nothing (invariant 28); the
10420
+ // answer is taken BEFORE the boundary drops the drawn stamp.
10421
+ function issuesSidebarWasDrawn() {
10422
+ const handle = issuesSidebarHandle;
10423
+ if (!handle || typeof handle.drawnWithin !== "function") return false;
10424
+ try {
10425
+ return handle.drawnWithin(ISSUES_SIDEBAR_DRAWN_WINDOW_MS) === true;
10426
+ } catch {
10427
+ return false;
10428
+ }
10429
+ }
10430
+
10431
+ // S5 (T4/S5): the start-of-session preload — the issues and pull-request reads
10432
+ // the rail would otherwise start on its first drawn frame. It is DISPATCHED and
10433
+ // never awaited (the host awaits every `session_start` handler, invariant 24's
10434
+ // sibling rule for the rail), and it runs only for the SAME section the host was
10435
+ // actually painting: a hidden, brand-new or re-mounted section starts its read
10436
+ // on the first DRAW, exactly as before, so nothing here spawns a child for a
10437
+ // section nobody sees, and a teardown-and-remount (a republished bridge) never
10438
+ // adds a second read behind the replacement's own first draw.
10439
+ function preloadIssuesSidebar(handleBefore, wasDrawn) {
10440
+ if (handleBefore === null || wasDrawn !== true) return;
10441
+ const handle = issuesSidebarHandle;
10442
+ if (handle === null || handle !== handleBefore) return;
10443
+ if (typeof handle.refreshIfStale !== "function") return;
10444
+ trackStartupTask(Promise.resolve().then(() => handle.refreshIfStale(ISSUES_SIDEBAR_ACTIVITY_FLOOR_MS)));
10445
+ }
10446
+
9615
10447
  // S10 (T9): the result of a `bash` call whose COMMAND mutates a GitHub issue or
9616
10448
  // pull request is the one moment the plugin knows something changed, so it forces
9617
10449
  // ONE read right after that tool ends. The decision is the classifier's
@@ -9824,6 +10656,9 @@ function registerOddWorktreeSurfaceEntries(pi) {
9824
10656
  // bound once — `alt+p` (S41) unless `GENTLE_PI_FILES_KEY` says otherwise.
9825
10657
  bindFilesShortcut(pi);
9826
10658
  registerIssuesCommand(pi);
10659
+ // S1 (prs): the pull-request sibling, behind the SAME `gh` gate and the same
10660
+ // session probe — absent `gh` means it is never registered either.
10661
+ registerPrsCommand(pi);
9827
10662
  // S5 (issues-linked-prs-and-alt-i T2): the issues panel's key, beside the
9828
10663
  // picker's — bound after its command exists, and therefore never when the
9829
10664
  // `gh`-absent gate left that command unregistered.
@@ -9872,11 +10707,19 @@ function registerOddWorktreeSurfaceEntries(pi) {
9872
10707
  // session is over — released here, and inert anyway through the generation
9873
10708
  // above.
9874
10709
  releaseIssuesPanelOpen();
10710
+ releasePrsPanelOpen();
10711
+ // S5 (T4/S5): the drawn stamp is read BEFORE the boundary clears it, and the
10712
+ // binding is remembered, because only a rail the host was painting — and that
10713
+ // is still the same section afterwards — earns the background preload below.
10714
+ const railHandleBefore = issuesSidebarHandle;
10715
+ const railWasDrawn = issuesSidebarWasDrawn();
9875
10716
  invalidateIssuesSidebar();
9876
10717
  // T18 (S11): a shutdown disposed the section, and a republished bridge is a
9877
10718
  // new binding. This is the moment both are picked up again; with a live
9878
10719
  // section on the same bridge it is a no-op.
9879
10720
  registerIssuesSidebar(pi);
10721
+ // S5 (T4/S5): dispatched, never awaited, and only while the rail is active.
10722
+ preloadIssuesSidebar(railHandleBefore, railWasDrawn);
9880
10723
  // T11 (S2 amended): the missing-plugin hint. It is armed in the same
9881
10724
  // boundary as the section's own state, and it says nothing yet when the
9882
10725
  // host could still announce.
@@ -9914,6 +10757,10 @@ function registerOddWorktreeSurfaceEntries(pi) {
9914
10757
  // S1 (issues-sidebar-click T1): an open the ended session dispatched never
9915
10758
  // blocks the next one.
9916
10759
  releaseIssuesPanelOpen();
10760
+ releasePrsPanelOpen();
10761
+ // S4 (T4): a mutation mark belongs to the session that made it; a new session
10762
+ // reads the repository fresh and may trust its stored fallback again.
10763
+ prsRailStaleIdentities.clear();
9917
10764
  invalidateIssuesSidebar();
9918
10765
  clearIssuesSidebarCache();
9919
10766
  // S5 (T8): the gate's own state is session state too. The generation moves on,