SLOPSHOPPER

pr-watch

Live pane tracking the GitHub PRs touched in a session: CI, review, conflicts, merge. One shared poller for every session on the machine.

panebandguardcommandtoaststatus
★ 9v0.15.0MITupdated 2026-10-26ElirazKed/claude-code-pr-watch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pr-watch
│ ┃ Pull requests ✕ › fix the failing auth test and add an audit log call │ ┃ ⎇ Pull requests │ ┃ ──────────────────────────────────────────── ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ╭─────╮ ⎿ Added 2 lines, removed 1 line │ ┃ │ ⎇ ◌ │ ⏺ Bash(bun test) │ ┃ ╰─────╯ ⎿ 3 pass, 1 fail │ ┃ Nothing to watch yet │ ┃ PRs appear when Claude runs gh pr … ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ or with /pr-watch <url> │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ x: Close │ › /pr-watch │ ⎿ pr-watch: PR panel opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Pull requests
⎇ Pull requests ──────────────────────────────────────────────────────── ╭─────╮ │ ⎇ ◌ │ ╰─────╯ Nothing to watch yet PRs appear when Claude runs gh pr … or with /pr-watch <url> x: Close
README

pr-watch

A Claude Code mod that keeps a live pane of the GitHub pull requests a session touches: CI, review, conflicts, merge. You see when the PR Claude opened goes green, gets a review or hits a conflict, without asking.

Website: https://elirazked.github.io/claude-code-pr-watch/

The pr-watch pane docked beside a Claude Code session, showing this repo's PR #1 just merged

The pane in a real session, docked beside the conversation: this repo's first PR, a minute after it merged. While CI runs, a card looks like this:

╭──────────────────────────────────────────────╮
│  ● CI RUNNING                       acme/app │
│ #12 Retry uploads with exponential backoff   │
│ feat/retry → main  +120 −14  @octocat        │
│                                              │
│ ✓ Open ━━━━━━ ⠹ CI ┈┈┈┈┈┈ ○ Review ┈┈ ○ Merge │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1/3  │
│ Running build · 1 queued · 1/3 passed        │
│ open #12 ↗ · checked just now             ✕  │
╰──────────────────────────────────────────────╯

Install

Needs Claude Code 2.1.287 or later and the GitHub CLI logged in (gh auth login).

/plugin install pr-watch --marketplace ElirazKed/claude-code-pr-watch

Answer y to add the marketplace and press Enter for user scope. It's active at once, with no restart. Or in two steps:

/plugin marketplace add ElirazKed/claude-code-pr-watch
/plugin install pr-watch@claude-code-pr-watch

prw, the PR manager

prw on its demo cache: lists on the left, every watched PR in the middle, the selected PR's card on the right

prw is a full PR manager for your terminal: all your PRs in one place. Your own open PRs, your saved GitHub searches (review requests, a team's repos) and every PR your agents touch (Claude through the mod; Codex and others through prw mcp or prw watch), sorted by what needs you, with a full PR view to read, reply, resolve, approve and merge in, so GitHub can stay closed. It runs on its own, with or without Claude, and shares the mod's poll when both run. It needs the GitHub CLI logged in, as the mod does.

Install the latest release (macOS and Linux, x86_64 and arm64) to ~/.local/bin:

curl -LsSf https://github.com/ElirazKed/claude-code-pr-watch/releases/latest/download/prw-installer.sh | sh

Or run it with nix, or build it with cargo (Rust 1.88 or newer):

nix run github:ElirazKed/claude-code-pr-watch#prw
cargo install --locked --git https://github.com/ElirazKed/claude-code-pr-watch prw

The releases page has each build as an archive, with its checksum and a GitHub attestation (gh attestation verify <file> --repo ElirazKed/claude-code-pr-watch). prw --cache companion/demo --demo, from a clone, shows the demo above. More on prw's page; everything else is in companion/README.md.

What it watches

  • Automatically: PRs Claude acts on: opens (gh pr create), pushes to (git push to a branch with a PR), comments on, reviews, merges or follows CI for (gh pr checks), through gh or GitHub MCP write tools. Only open PRs are picked up; a merged or closed one never gets a card, and one you stopped watching stays stopped.
  • When you ask: /pr-watch <url>, or paste a PR link in a prompt. These are watched in any state.
  • When offered: PRs Claude only reads (gh pr view/diff, a fetched link, a GitHub MCP read). Claude asks once, and only if the PR looks like your own work rather than background reading.

/pr-watch opens the pane, and /pr-watch stop <number|url|all> stops watching. Finished PRs stay until you dismiss them, d dismisses them all, and r refreshes.

Close (x), beside Refresh, closes the pane, as does ctrl+x x or the mark on the pane's frame; the PRs stay watched, and /pr-watch, the next new PR, a /clear or a new session brings the pane back. It's there for when something drawn over the terminal's top rows hides the frame's mark.

Each card shows the state that matters most first: merge conflicts, then failing or running CI (naming the checks), then review, then whether GitHub will let it merge. A toast appears when the state changes or a review lands, and the status line follows the focused PR.

Under the pane's buttons, the gh meter shows how much of GitHub's hourly budget each of your gh logins has left, so you can put off heavy gh work before it runs out:

gh octocat ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀  94% ↻42m       ?
   hubot   ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀   3% ↻9m
  • One thin bar per login: it shows whichever is lower, GraphQL's points (most gh pr commands, and the poll) or REST's requests (gh api, gh run), the bucket that runs out first. It fills the top half of its row only, so the bars of two logins never run together. The percentage is that same lower share, and ↻42m is how long until that bucket refills.
  • Colours: the theme's green while there's plenty, its amber below 20% of a limit, its red below 5%; the number and refill turn the same colour.
  • ?: press it (or tab to it and press Enter) to open a short plain-English note under the meter: what the budget is, that it belongs to the login and every session on the machine shares it, that pr-watch stops polling a login that runs low, and what ↻ means. Press it again to close it. It stays as you left it for the session. With the pointer on ?, the same note shows over the pane without a press.
  • Hourly limits only: GitHub's secondary limits, on bursts of requests, have no counter to read, so the meter can't warn of them. Once one is hit, a line above the bars says so: ⏸ GitHub rate limit · resumes in 45s, counted down, gone when the wait is over. The cards keep their last data and their checked 2m ago meanwhile, and say nothing of it themselves.

Layout

layout in /config says where the PRs show:

  • pane (the default): the pane, opened as PRs come. Claude Code places it: docked beside the conversation in a wide fullscreen terminal, otherwise above the prompt.
  • band: a few short lines in the band just above the prompt instead, for a terminal with little room, or one whose top rows something else covers. The pane opens only when you ask for it.
✗ #13 Retry uploads with exponential backoff · 1 check failing
⠹ #12 Retry uploads with exponential backoff · CI running · 1/3
✓ #7 Retry uploads with exponential backoff · merged
o: Open pane  r: Refresh  f: Fix #13 with Claude
  • What it shows: a line per PR, most urgent first (conflicts, failing CI, changes requested, comments to address, then what can merge, what waits, what's done), with the card's icon and spinner, the title cut to fit, and the state in a few words. Five lines at most, the buttons included; past that, +3 more on the buttons' line. It takes two lines when another mod draws in the band too, and keeps theirs below.
  • Buttons: Open pane (o) opens the full pane at any width, with the keys. Refresh (r) asks GitHub now. The most urgent PR's hand-off, Resolve with Claude (c) where its branch conflicts, else Fix with Claude or Address with Claude (f, a), drafts in the prompt box as a card's does; where it would ask first, or the draft goes wrong, the pane opens with the keys to show that card's question or error. The keys work once the band has them: ctrl+x tab, or a click. Merging, dismissing and stopping stay in the pane.
  • When it's empty: nothing watched, the band is left empty, and a survey there has it to itself. ctrl+x ctrl+a or the band's [-] folds it away.
  • The pane: new PRs never open it. /pr-watch does, and an open pane works as ever.
  • The gh budget: the band mentions it only once some bucket is below 20%, at the end of the buttons' line, in the meter's words (gh 12% ↻42m, or gh 12%), and drops it first where the line is short. A secondary limit's pause (⏸ GitHub rate limit · resumes in 45s) shows there at once, ahead of the hand-off button.

A change applies at once. Switching to band closes the pane; switching back to pane opens it.

Themes

theme in /config sets how the cards look:

  • classic (the default): round borders coloured by the PR's state, dim until the pointer is on the card, and a filled status pill.
  • solid: no borders. Each card is a tile with a soft tint for its state: green ready, red failing, amber running or waiting on you, purple merged, neutral otherwise.
  • minimal: no boxes, just a thin rule between PRs. Only the status pill and the headline are coloured.
  • neon: bold borders in vivid colour that glow brighter under the pointer, with a saturated gradient rule and spinner.
  • retro: double borders in the terminal's own 16 colours, [bracketed] pills, a ═ rule and a |/-\ spinner, like an old TUI.
  • tide: each card is a glass that fills with liquid in its state's colour as the PR moves on. While CI runs the fill is the share of checks finished. In review it is nearly full, and ready or merged it is full. A closed PR's glass is empty. The liquid gets deeper toward the bottom and toward where it started. Its front is a wave that sways gently while the PR is moving and holds still when it isn't, and a full card that is still moving (auto-merge on) has a glint sweeping across. The header rule is a wave too.
  • aurora: each card is a night sky (a pale dawn on a light terminal) with soft curtains of northern light in its state's colours. The light reaches further across the card as the PR moves on, and drifts while it is moving.

tide and aurora lay the card out differently: a headline row with the number, title and state badge on the right; a meta row with repo · branch → base · +/− and the author; what it is doing now, with the CI tally; then reviewers, open threads and errors. The fill itself shows progress, so there is no separate bar or stepper. Each text cell is drawn in whichever of the theme's two text colours reads better on that cell's own background, so text stays readable over both the filled and the empty part. The buttons and the open #12 ↗ link sit on their own rows under the art and work as on any card. In a terminal the art is one painted cell grid per card, updated about five times a second, and only for cards that are moving. Emoji and other double-width characters in a title show as ? or • there, because each cell holds one single-width character. Off the terminal (the desktop app), the same rows are drawn as plain text on the card's tint.

/pr-watch theme <name> switches at once (any case: /pr-watch theme Neon) and saves the choice in /config, so every session uses it. Where /config has no row for it, the choice lasts for that session only, and the reply says so. /pr-watch theme lists the themes and marks the current one.

In tmux Claude Code paints with the 256-colour palette unless CLAUDE_CODE_TMUX_TRUECOLOR=1 is set (so does a terminal that doesn't say it takes 24-bit colour, such as Apple's Terminal). It would round a gradient there to blotches of other colours, so tide and aurora switch to a paint made of the palette's own colours: tide's water in three layers with wavy lines between them and a lit front, aurora's curtains with a glowing, rippling hem. pr-watch reads the same environment variables Claude Code does to decide. For the smooth gradients inside tmux, set CLAUDE_CODE_TMUX_TRUECOLOR=1 where your tmux passes 24-bit colour on to the terminal (its terminal-features include RGB, or the terminal's terminfo has Tc).

Themes follow Claude Code's light or dark theme. The tinted, vivid and painted ones have a light and a dark variant. If Claude Code's theme is auto, the terminal's COLORFGBG decides where it's set, and dark otherwise. The band uses the theme's colours too.

Reviews

A card says who reviewed and what is left to address:

╭──────────────────────────────────────────────╮
│  ↺ CHANGES REQUESTED                acme/app │
│ #12 Retry uploads with exponential backoff   │
│ feat/retry → main  +120 −14  @octocat        │
│                                              │
│ ✓ Open ━━━ ✓ CI ━━━ ↺ Review ┈┈┈ ○ Merge     │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3/3 │
│ Changes requested                            │
│ ✗ bob requested changes · ✓ alice approved   │
│ 3 unresolved threads (1 outdated)            │
│ open #12 ↗ · checked just now             ✕  │
╰──────────────────────────────────────────────╯
  • Who reviewed: each reviewer once, by what still counts. An approval (✓) or a change request (✗) stands until its reviewer changes it, as GitHub counts it; otherwise a review asked of them (◷ carol requested); otherwise their latest comment-only review (💬 nadav commented). Review apps count too, by a short name (copilot-pull-request-reviewer is copilot). When the line is too long for the card, the verbs are dropped first (✓ alice · 💬 nadav), and then the reviewers past what fits become +2 more.
  • Threads: how many review threads are unresolved, and how many of those are outdated (the code changed since). The poll asks about the newest 50 threads only, so past that the count is a floor (50+).
  • Headline: with threads open and no approval yet, the card says 3 comments to address (💬 COMMENTS) instead of Waiting for review. With comment-only reviews and every thread resolved it says Reviewed · waiting for approval. Approved with threads open, it says Approved · 2 unresolved threads, or Blocked · 2 unresolved threads when GitHub holds the merge back, as it does in a repo that requires conversations resolved. Conflicts and CI still come first.
  • Toasts: each new review toasts once: 💬 nadav commented on #532, ✓ alice approved #12, ✗ bob requested changes on #12. Reviews already there when the card first loads don't toast, and neither do your own (from any of your gh accounts). The card keeps the newest review it has seen, so a /clear or a reload doesn't toast them again.

Merging

A card offers a merge button once GitHub would merge the PR now (open, not a draft, no conflicts, required checks and reviews done) and your account can write to the repo. The method is your default on GitHub if the repo allows it, otherwise the first the repo allows of squash, rebase and merge, and the button says which: Squash & merge, Rebase & merge or Merge. When the repo allows more than one, a small ⇄ rebase button beside it switches.

  • Confirmation: the first press asks, e.g. Squash-merge #12 into main?, and only Confirm (y) runs anything; Cancel (n) goes back.
  • Auto-merge: while the PR waits on checks or reviews in a repo with auto-merge allowed, the button is Auto-merge · squash instead. It asks the same way, then GitHub merges the PR once everything passes (gh pr merge --auto). With auto-merge on, the card says so (Auto-merge on · squash) and has a Cancel auto-merge button, which needs no confirmation.
  • Which account: gh pr merge runs as the gh account that can see the repo, the one the poller reads it with, by that login's own token. If gh won't give that token, the card says so and nothing runs: never as another account.
  • While it runs: the card says so (Merging…), and a second press does nothing. If a reload cuts the run off, the buttons come back after 2 minutes.
  • When GitHub says no: its message shows on the card. If it refused the method itself (say, a ruleset that allows only rebase), that method isn't offered for the repo again this session.
  • When GitHub stumbles: a 502, 503 or 504 (or GitHub's own timeout) doesn't say whether the merge went through, so the card doesn't take it as a no. Two seconds later the PR is read again, as the same account. If it merged (or auto-merge turned on or off, as asked), the card just shows that. If it is still open as before, the merge runs once more, and if that fails too, its error shows. If the PR can't be read, the first error shows.

Comment

Every open PR's card, drafts too, has a dim Comment button after its other buttons. It opens a one-line text field on the card, Comment on #12 as octocat, so you see which account will post. Type, press Enter, and the text goes to the PR's conversation as a plain comment (not a review). There are no preset comments: what you type is what's posted.

  • Which account: as for a merge, the gh account that can see the repo, by that login's own token. If gh won't give that token, the card says so and nothing is posted: never as another account.
  • Exactly as typed: the text goes to gh api repos/<owner>/<repo>/issues/<n>/comments on its standard input, as the request's JSON body, never on the command line, so a comment that starts with @ or - is posted as it is.
  • Then: the field closes and the card says ✓ Commented as octocat · comment on #12 ↗, linking the new comment, and GitHub is asked about the PR again at once, since a comment can start checks or change a review.
  • While it posts: the card says Posting the comment…, and a second Enter does nothing. An empty field posts nothing.
  • When GitHub says no: its reason shows on the card (say, Couldn't comment: Unable to create comment because issue is locked.), and your text stays in the field to try again.
  • Cancel closes the field without posting and drops the text. Esc only hands the keys back to the prompt: the field stays open, and the next ctrl+x tab lands in it. What you typed stays in the field while the pane redraws (not across a reload of the mod); dismissing the card drops it. The band has no Comment; the desktop app's pane does, the mobile app's doesn't yet (it draws no text field).

Fix with Claude

A card whose CI failed (at least one check failing on its latest run, counted the way the card counts them) has a Fix with Claude button. It collects what failed and puts it in your prompt box as a draft: read it, change it if you like, and press Enter to send it to this session. Nothing reaches Claude until you do.

  • What's in it: the PR (repo, number, title, link, head branch → base), each failing check with its conclusion and link, the failed steps' logs, and the ask: find the cause and fix it on this branch, or say first if the repo or branch isn't checked out here. It doesn't ask Claude to push or merge.
  • Logs: for GitHub Actions jobs, gh run view --job <id> --log-failed, for the first 3 failing jobs. Each log loses its colour codes, timestamps and runner group markers, and keeps its last 120 lines, where the error usually is; all the logs together stay under about 12 KB. The draft says when a log was trimmed.
  • Other CI: a check from another CI app, or a commit status, has no log to fetch here, so its name, conclusion, summary or description, and link go in instead.
  • Which account: the checks and logs are fetched as the gh account that can see the repo, the one the poller reads it with, by its own token. If gh won't give that token, the card says so and nothing is fetched.
  • When something won't come: the card says why (say, No log for build: GitHub no longer keeps this log), and the draft still has the names and links.
  • While it collects: the card says Collecting logs…, and a second press does nothing. If a reload cuts it off, the button comes back after 2 minutes.
  • No prompt box: where the box won't take a draft, the card asks instead, Send CI failure of #12 to Claude?, and only Confirm (y) sends it; Cancel (n) sends nothing.

Address with Claude

A card with unresolved review threads has an Address with Claude button, beside Fix with Claude when CI failed too. It reads the threads and drafts them in your prompt box the same way: read the draft, change it if you like, and press Enter. Nothing reaches Claude until you do.

  • What's in it: the PR (repo, number, title, link, head branch → base), then each unresolved thread by file and line: where it is (src/upload.ts:40-42), its link, and the first comment and its replies, each by its author (the PR author's marked). Resolved threads are left out; an outdated one (the code changed since) stays in, marked, with the line it was left on. Then the ask: address each on this branch, changing the code where a comment is right and saying where Claude disagrees or a comment needs your call, or say first if the repo or branch isn't checked out here. It doesn't ask Claude to push or merge, and it tells Claude not to reply to or resolve a thread on GitHub, but to draft any reply in the session for you to read first.
  • Threads: one gh api graphql query for that PR alone, on the press: its newest 100 threads and the first 10 comments of each. The poll never asks what a thread says.
  • Trimmed: each comment loses the HTML comments review apps keep notes in and is clipped at 1,000 characters, each thread at 3,000, and all the threads together stay under about 12 KB. Threads that don't fit are counted, and the draft points to the PR's files tab.
  • Which account, while it reads, no prompt box: as for Fix with Claude. The card says Reading review threads…, a second press does nothing, and where the box won't take a draft it asks Send review comments of #12 to Claude? first.
  • Several at once: each button's draft replaces only its own earlier draft for that PR, so the others, and what you typed before them, stay in the box.

Resolve with Claude

A card whose branch conflicts with its base (⚠ CONFLICTS, or Draft · merge conflicts on a draft) has a Resolve with Claude button, first of the hand-offs, since a conflict blocks the merge whatever CI and review say. It drafts the ask in your prompt box the same way: read it, change it if you like, and press Enter. Nothing reaches Claude until you do.

  • What's in it: the PR (repo, number, title, link, head branch → base), that GitHub can't merge it cleanly, and the ask: fetch and merge origin/<base> into the branch rather than rebase it, so no history is rewritten and no force-push is needed (where the branch or repo clearly works by rebase, Claude says so and asks first); resolve each conflict keeping what both sides meant, and ask you where the intent is unclear; run the project's checks and tests; commit the merge. Or say first if the repo or branch isn't checked out here. It doesn't ask Claude to push or merge: the push stays your call.
  • Nothing to fetch: GitHub doesn't say which files conflict, so the press asks GitHub nothing; git finds them once the base is merged in. Where the card's latest round shows no conflict any more, it drafts nothing and asks GitHub again.
  • A second press, no prompt box: as for Fix with Claude. A double press drafts once, a later one replaces its own draft, and where the box won't take a draft it asks Send merge conflicts of #12 to Claude? first.

How it polls

Every session on the machine shares one poller, so 30 sessions watching 30 PRs cost about one GitHub call every 20–60 seconds, not 30.

  • Each session lists its PRs in ~/.cache/pr-watch/sessions/, with its agent, project folder and directory. The file's modified time is its heartbeat.
  • When the shared results are due, one session takes a short lease and fetches every live session's PRs in batched GraphQL queries, 20 PRs each, one after another. It writes them to ~/.cache/pr-watch/results.json, and the other sessions read that. The file is written whole (to a temp file, then renamed over it), so a reader never catches it half-written.
  • Other programs can share the cache too: companion/PROTOCOL.md says what each file
Source 18 files
hooks/register.tsx 2630 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Busy, CommentAsk, HandoffAsk, Limits, MergeAsk, Reviews, TrackedPr, Verdict } from '../types'
5import { barCells, barRuns, fullBarCells, meterCells, ruleCells, ruleText, spinnerCell } from './look'
6import { artCard, artCells, bannerLines, roleTone } from './art'
7import type { ArtCard, Seg } from './art'
8import { barPaint, cardBox, depthOf, inkOf, lookOf, modeOf, modeOfColours, optionTheme, pillOf, rasterBg, themeListing, themeOf, unknownTheme } from './theme'
9import type { Depth, Look, Mode, Role, ThemeName } from './theme'
10import {
11  MERGE_LABEL,
12  STEPS,
13  afterServerError,
14  ago,
15  cwdOf,
16  derive,
17  findPrUrls,
18  isActive,
19  isBusy,
20  isServerError,
21  mergeArgv,
22  mergeError,
23  mergeOf,
24  mergeQuestion,
25  mergeReadArgv,
26  mergeReadOf,
27  metaOf,
28  nextMethod,
29  pickMethod,
30  placeholder,
31  shellCode,
32  stepIndex,
33  touched,
34} from './pr'
35import { appendLog, buildQuery, callBudget, checksQuery, chunks, failureOf, logLine, parseChecks, parseHttp, parseReply, rateOf, retryAfterOf } from './batch'
36import type { CallFailure, CallLog, Http, RateLimit } from './batch'
37import { addressHeading, addressPrompt, openThreads, parseThreads, redraft, threadsQuery } from './address'
38import { failingChecks, fixHeading, fixPrompt, logError, logProblems, toFetch } from './fix'
39import type { Failure, Handoff } from './fix'
40import { resolveHeading, resolvePrompt } from './resolve'
41import { commentArgv, commentError, commentInput, commentPlaceholder, commentUrl, isPostable } from './comment'
42import { cells, newReviews, reviewToasts, reviewsOf, threadsBeside, verdictLine } from './review'
43import { CHECK_MS, PRW_LINE, PRW_PILL, PRW_TEXT, PRW_URL, companionIn, headOf, howToUpdate, isNewer, isPrwIn, noticeLines, noticeToast, versionIn } from './update'
44import type { CompanionState } from './update'
45import { BAND_ROWS, SHARED_ROWS, actionsOf, buttonCells, layoutOf, planOf, rowOf } from './band'
46import type { Layout } from './band'
47import { failedEntry, isMiss, isUnreachable, keptEntries } from './cache'
48import { NO_LOGINS, bestLogin, everyLogin, isDue, learned, loginFor, loginsOf, notFoundAs, ownersBelowWrite, rankOf, tokenError, untriedBy } from './accounts'
49import type { Logins, Token } from './accounts'
50import type { Entry } from './cache'
51import { GH_HELP, bandNote, bucketOf, ghMeter, isRestDue, legacyRate, lowUntil, restOf, roundWaitsUntil, withSeen } from './rate'
52import type { Bar, Rates } from './rate'
53import type { GhPr, MergeRun, PrRef } from './pr'
54import { isTemp, placeOf, sessionFile, tempPath, urlsIn } from './protocol'
55import type { Place } from './protocol'
56
57const PANE = 'pr-watch'
58const TITLE = 'Pull requests'
59// A slim dock beside the transcript (a width you drag it to wins over this).
60const OPEN = { id: PANE, title: TITLE, columns: 50, rows: 14 } as const
61const prs = atom({ plugin: 'pr-watch', key: 'prs' } as const, [])
62const now = atom({ plugin: 'pr-watch', key: 'now' } as const, 0)
63const suggested = atom({ plugin: 'pr-watch', key: 'suggested' } as const, [])
64// PRs the person stopped watching: Claude touching them again doesn't bring them back.
65const dropped = atom({ plugin: 'pr-watch', key: 'dropped' } as const, [])
66const merging = atom({ plugin: 'pr-watch', key: 'merging' } as const, {})
67// Methods GitHub refused for a repo: not offered again this session.
68const refused = atom({ plugin: 'pr-watch', key: 'refused' } as const, {})
69const fixing = atom({ plugin: 'pr-watch', key: 'fixing' } as const, {})
70const addressing = atom({ plugin: 'pr-watch', key: 'addressing' } as const, {})
71const resolving = atom({ plugin: 'pr-watch', key: 'resolving' } as const, {})
72// A card's comment: its field, the post, what came of it.
73const commenting = atom({ plugin: 'pr-watch', key: 'commenting' } as const, {})
74// Try again on a not-found card, while every login is asked.
75const retrying = atom({ plugin: 'pr-watch', key: 'retrying' } as const, {})
76// A newer pr-watch than this one, for the footer.
77const newer = atom({ plugin: 'pr-watch', key: 'newer' } as const, null)
78// Whether the card telling of prw shows (sayCompanion).
79const companion = atom({ plugin: 'pr-watch', key: 'companion' } as const, false)
80// GitHub's budget per login and a hold, for the gh meter.
81const limits = atom({ plugin: 'pr-watch', key: 'limits' } as const, { logins: [], heldUntil: 0 })
82// Whether the gh meter's explanation is open (its `?`): shut until asked, per session.
83const ghHelp = atom({ plugin: 'pr-watch', key: 'ghHelp' } as const, false)
84const WATCH_TOOL = 'mcp__pr-watch__watch'
85const FRAME_MS = 90
86
87// Module memory: lost on reload, which only costs one extra poll.
88let isTicking = false
89let hasHinted = false
90// What the pane last drew, so the animation can blit frames of the same size: a stacked card's
91// CI bar width, and a banner card as laid out (art.ts).
92const barWidth = new Map<string, number>()
93const artCards = new Map<string, ArtCard>()
94// A banner card repaints every ART_EVERY frames: the wave sways at the spinner's pace or slower.
95const ART_EVERY = 2
96// The pointer on the gh meter's `?` reveals its explanation over the pane.
97const HELP_SCOPE = 'pr-watch-gh-help'
98let anim: { cancel: () => void } | null = null
99let frame = 0
100// Whether the pane is drawn: set by its render, cleared when a spinner blit is refused (closed,
101// or never opened in the band layout), so a hidden pane costs no frames.
102let isPaneDrawn = false
103// The band's instance, and the PRs whose spinner it last drew, so the animation blits there too.
104let bandId: string | null = null
105const bandSpins = new Set<string>()
106// The end of the hold a timer is set for, so the pause line goes the moment it ends, ticks or not.
107let pauseEndsAt = 0
108// What each card's comment field holds, by PR url: kept here on every keystroke, so typing
109// redraws nothing, and a redraw (a poll round's) draws the field with it. Lost on reload.
110const drafts = new Map<string, string>()
111
112// Rows kept by an older version of this mod lack the newer fields.
113function full(pr: TrackedPr): TrackedPr {
114  return { ...placeholder(pr), ...pr, checks: { ...placeholder(pr).checks, ...pr.checks } }
115}
116
117const TOAST_ICON: Record<string, string> = { success: '✓', error: '✗', warning: '◷', merged: '🎉', suggestion: '⇢' }
118const VERDICT_COLOUR: Record<Verdict, 'success' | 'error' | 'suggestion' | undefined> = {
119  approved: 'success',
120  changes: 'error',
121  commented: 'suggestion',
122  requested: undefined,
123}
124
125// ---- One poller for the whole machine -------------------------------------------------
126// Every session lists the PRs it watches under ~/.cache/pr-watch/sessions/ (the file's mtime
127// is its heartbeat); whichever session finds the shared results due takes a short lease and
128// fetches every live session's PRs in one batched query, and the rest read results.json.
129// So N sessions cost one GitHub call per round, not N. Other readers and writers (the `prw`
130// companion) share these files: companion/PROTOCOL.md says what each holds, and what a reader
131// may meet in them.
132
133type Shared = {
134  fetchedAt: number
135  nextAt: number
136  prs: Record<string, Entry>
137  // Which gh login sees an owner's private repos (a login, never a token).
138  accounts: Record<string, string>
139  // What older versions read; this one keeps it as legacyRate says (rate.ts), and reads `rates`.
140  rate: RateLimit | null
141  // GitHub's hourly limits per gh login, as the last round and watch saw them (rate.ts).
142  rates: Rates
143  // pr-watch's newest version as the last check found it (null: none read yet), and when
144  // that check rode a round.
145  latest: { version: string | null; checkedAt: number }
146  // Until when a secondary limit holds every session off GitHub (absent: none yet).
147  heldUntil?: number
148}
149
150// How often a round runs while some PR moves, and otherwise: the `poll_active_seconds` and
151// `poll_idle_seconds` options, kept current by `config.set`.
152const MIN_POLL_MS = 10_000
153const pace = { fastMs: 20_000, slowMs: 60_000 }
154// The `update_notice` option, kept current the same way.
155let isNoticeOn = true
156// The `layout` option, the same way: the pane (opened as PRs come), or the band above the prompt.
157let layout: Layout = 'pane'
158// The `theme` option, the same way, or what /pr-watch theme picked; and whether the person's
159// terminal is light or dark (readMode), dark until known.
160let themeName: ThemeName = 'classic'
161let mode: Mode = 'dark'
162// How many colours Claude Code paints this terminal with (readDepth): 24-bit until known.
163let depth: Depth = 'truecolor'
164const look = (): Look => lookOf(themeName, mode, depth)
165const seconds = (value: unknown, fallback: number) =>
166  typeof value === 'number' && Number.isFinite(value) ? Math.max(MIN_POLL_MS, value * 1_000) : fallback
167// A session whose file has not been touched for this long has exited.
168const ALIVE_MS = 60_000
169const LEASE_MS = 30_000
170// A batch that failed on GitHub having a moment (a `timeout`, batch.ts) is asked once more,
171// RETRY_MS on, while the lease has time for it (callBudget, as for every call of a round).
172const RETRY_MS = 2_000
173const GH_MS = 20_000
174// /rate_limit answers at once, or not worth waiting for.
175const REST_CALL_MS = 5_000
176// How long every session holds off after a secondary limit that names no retry-after.
177const LIMIT_WAIT_MS = 60_000
178// Session files and temp files untouched this long are removed, at most every PRUNE_EVERY_MS.
179const PRUNE_MS = 86_400_000
180const PRUNE_EVERY_MS = 3_600_000
181// `mv` and `rm` on the cache's own files answer at once, or not at all.
182const FILE_OP_MS = 5_000
183
184// Survives /clear (the module stays loaded), unlike the session id.
185const INSTANCE = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
186let homeDir: string | null | undefined
187let dir: string | null = null
188// Where this session runs, for its session file: from the session start, and again whenever
189// the engine says the directory changed (classic.CwdChanged), never asked per tick.
190let place: Place | null = null
191let placeSeq = 0
192// gh's logins as `gh auth status` last listed them, when gh was last asked and whether it
193// answered (accounts.ts's isDue says when it is asked again), and the reading under way, so
194// callers at once share one. A reading that lists none is never kept: the last good one stands.
195let loginsKept: Logins = NO_LOGINS
196let loginsAsked: { at: number; isOk: boolean } | undefined
197let loginsAsk: Promise<Logins> | null = null
198// Each login's token as gh last gave it, and when; when gh last wouldn't, and what the card
199// says then (isDue again, for both); and the asks under way.
200const tokens = new Map<string, { at: number; token: string }>()
201const tokenMisses = new Map<string, { at: number; error: string }>()
202const tokenAsks = new Map<string, Promise<Token>>()
203let prunedAt = 0
204
205const empty = (): Shared => ({ fetchedAt: 0, nextAt: 0, prs: {}, accounts: {}, rate: null, rates: {}, latest: { version: null, checkedAt: 0 } })
206
207async function gh($: EngineInterface, argv: string[], token?: string, cwd?: string, timeoutMs = GH_MS) {
208  return $.process.run(['gh', ...argv], {
209    cwd,
210    timeoutMs,
211    env: token ? { GH_TOKEN: token } : undefined,
212  })
213}
214
215async function home($: EngineInterface): Promise<string | null> {
216  if (homeDir === undefined) homeDir = (await $.env.get('HOME')) ?? null
217
218  return homeDir
219}
220
221async function root($: EngineInterface): Promise<string> {
222  dir ??= `${(await home($)) ?? '/tmp'}/.cache/pr-watch`
223
224  return dir
225}
226
227async function readJson<T>($: EngineInterface, path: string): Promise<T | null> {
228  try {
229    return JSON.parse(String(await $.fs.read(path))) as T
230  } catch {
231    return null
232  }
233}
234
235// In place: a reader may catch the file half-written. Every tick's writes (lease.json, the
236// session file) go this way, as an exec each tick costs more than a torn read does (a reader
237// takes one as absent, readJson's null, and reads again next tick); results.json alone is
238// written whole (writeResults).
239async function writeJson($: EngineInterface, path: string, value: unknown) {
240  try {
241    await $.fs.write(path, JSON.stringify(value))
242  } catch {
243    // The cache is an optimisation: a session that cannot write it still polls for itself.
244  }
245}
246
247// results.json, which every reader reads whole, is written whole: to a temp file beside it,
248// then moved over it, a rename a reader sees all or nothing of. `$.fs` has no rename, so it is
249// an `mv`, once a round. Where that fails, the file is written in place as before, so the round
250// is shared all the same; a temp file left behind is taken over by this session's next round,
251// or pruned (liveUrls).
252async function writeResults($: EngineInterface, shared: Shared) {
253  const path = `${await root($)}/results.json`
254  const temp = tempPath(path, INSTANCE)
255  try {
256    await $.fs.write(temp, JSON.stringify(shared))
257    const moved = await $.process.run(['mv', '-f', temp, path], { timeoutMs: FILE_OP_MS })
258    if (moved.exitCode === 0) return
259  } catch {
260    // Written in place below.
261  }
262  await writeJson($, path, shared)
263}
264
265async function readShared($: EngineInterface): Promise<Shared> {
266  return { ...empty(), ...(await readJson<Shared>($, `${await root($)}/results.json`)) }
267}
268
269// Where the session runs, for its session file: the directory, and its project root's folder
270// as its name (a `cd` into a subfolder doesn't rename it). Where the engine won't say the root,
271// the directory names it. Only the latest call lands: the session start's read, left running,
272// never overwrites a later classic.CwdChanged's.
273async function readPlace($: EngineInterface, cwd: string) {
274  const seq = ++placeSeq
275  const at = placeOf(cwd, await $.session.root().catch(() => cwd))
276  if (seq === placeSeq) place = at
277}
278
279// This session's watch list, and who and where it is (protocol.ts); written every tick, so its
280// mtime says the session is alive.
281async function announce($: EngineInterface, urls: readonly string[]) {
282  await writeJson($, `${await root($)}/sessions/${INSTANCE}.json`, sessionFile(urls, place))
283}
284
285// Every live session's PRs: an older mod's file, a newer one's and the companion's alike
286// (urlsIn), one cut off mid-write listing none this time.
287async function liveUrls($: EngineInterface, at: number): Promise<string[]> {
288  const cache = await root($)
289  const base = `${cache}/sessions`
290  let entries: Awaited<ReturnType<EngineInterface['fs']['list']>> = []
291  try {
292    entries = await $.fs.list(base)
293  } catch {
294    return []
295  }
296  const live = entries.filter(f => f.kind === 'file' && f.name.endsWith('.json') && at - f.mtimeMs < ALIVE_MS)
297  const isPruneDue = at - prunedAt > PRUNE_EVERY_MS
298  // Listed beside the session reads, not after them: the round waits on neither alone.
299  const [lists, temps] = await Promise.all([
300    Promise.all(live.map(f => readJson<unknown>($, `${base}/${f.name}`))),
301    isPruneDue ? $.fs.list(cache).catch(() => []) : Promise.resolve([]),
302  ])
303  if (isPruneDue) {
304    prunedAt = at
305    // Exited sessions' files, and temp files a write left beside results.json (writeResults).
306    const dead = [
307      ...entries.filter(f => f.kind === 'file' && at - f.mtimeMs > PRUNE_MS).map(f => `${base}/${f.name}`),
308      ...temps.filter(f => f.kind === 'file' && isTemp(f.name) && at - f.mtimeMs > PRUNE_MS).map(f => `${cache}/${f.name}`),
309    ]
310    if (dead.length > 0) void $.process.run(['rm', '-f', ...dead], { timeoutMs: FILE_OP_MS }).catch(() => undefined)
311  }
312
313  return [...new Set(lists.flatMap(urlsIn))]
314}
315
316// A lease, not a lock: plain files have no atomic create, so claim, wait, and re-read. Two
317// sessions racing past this costs one duplicate round, never a missed one. Written in place
318// (writeJson): a lease read torn is no lease held, so at worst that costs a duplicate round too.
319async function takeLease($: EngineInterface, at: number): Promise<boolean> {
320  const path = `${await root($)}/lease.json`
321  const held = await readJson<{ owner: string; until: number }>($, path)
322  if (held !== null && held.owner !== INSTANCE && held.until > at) return false
323  await writeJson($, path, { owner: INSTANCE, until: at + LEASE_MS })
324  await $.clock.sleep(150)
325
326  return (await readJson<{ owner: string }>($, path))?.owner === INSTANCE
327}
328
329async function releaseLease($: EngineInterface) {
330  await writeJson($, `${await root($)}/lease.json`, { owner: INSTANCE, until: 0 })
331}
332
333// gh's logins, read again every few minutes (a login added or switched to shows): the last
334// good reading stands meanwhile, and is awaited only where there is none yet, or with
335// `isFresh` (before a round calls a PR not found).
336async function logins($: EngineInterface, isFresh = false, timeoutMs = GH_MS): Promise<Logins> {
337  // The time first: callers at once then see each other's ask, never start one each.
338  const at = await $.clock.now()
339  if (loginsAsk === null && (isFresh || isDue(loginsAsked, at))) {
340    loginsAsk = (async () => {
341      const status = await gh($, ['auth', 'status', '--hostname', 'github.com'], undefined, undefined, timeoutMs).catch(() => null)
342      const read = status === null ? null : loginsOf(`${status.stdout}\n${status.stderr}`)
343      loginsAsked = { at: await $.clock.now(), isOk: read !== null }
344      if (read !== null) loginsKept = read
345
346      return loginsKept
347    })().finally(() => (loginsAsk = null))
348  }
349
350  return loginsAsk !== null && (isFresh || loginsKept === NO_LOGINS) ? loginsAsk : loginsKept
351}
352
353// A login's own token, from gh, never written anywhere. Every call made as a login carries
354// it, the active one's too: gh's active account is whichever was switched to last, so a call
355// without a token may run as anyone. A token is asked of gh again every few minutes (a login
356// logged in again has a new one); where gh won't give it then, the last one it gave stands,
357// and where it never gave one, that is said, never stood in for.
358async function tokenFor($: EngineInterface, login: string, timeoutMs = GH_MS): Promise<Token> {
359  if (login === '') return { error: tokenError('') }
360  const at = await $.clock.now()
361  const good = tokens.get(login)
362  const miss = tokenMisses.get(login)
363  const isKept = (good !== undefined && !isDue({ at: good.at, isOk: true }, at)) || (miss !== undefined && !isDue({ at: miss.at, isOk: false }, at))
364  if (isKept && !tokenAsks.has(login)) return good !== undefined ? { token: good.token } : { error: miss?.error ?? tokenError(login) }
365  const asking =
366    tokenAsks.get(login) ??
367    (async (): Promise<Token> => {
368      const res = await gh($, ['auth', 'token', '--hostname', 'github.com', '--user', login], undefined, undefined, timeoutMs).catch(() => null)
369      const said = res?.stdout.trim() ?? ''
370      const doneAt = await $.clock.now()
371      if (res !== null && res.exitCode === 0 && said !== '') {
372        tokens.set(login, { at: doneAt, token: said })
373        tokenMisses.delete(login)
374
375        return { token: said }
376      }
377      const error = tokenError(login)
378      tokenMisses.set(login, { at: doneAt, error })
379      const why = res === null ? 'gh auth token did not finish' : res.stderr.trim().split('\n')[0] || `gh auth token exited ${res.exitCode}`
380      const http = { status: null, headers: {}, body: '' }
381      await logFailure($, { login, size: 0, ms: doneAt - at, http, failure: 'other', error: `${error}: ${why}` })
382      const last = tokens.get(login)
383
384      return last !== undefined ? { token: last.token } : { error }
385    })().finally(() => tokenAsks.delete(login))
386  tokenAsks.set(login, asking)
387
388  return asking
389}
390
391// The login a press acts as: the one the poller found sees the owner's repos, else the active
392// one, which polls the owners no other login was found for. Never another: a press whose
393// login has no token says so on the card.
394async function pressLogin($: EngineInterface, pr: TrackedPr): Promise<string> {
395  return loginFor((await readShared($)).accounts, ownerOf(pr), await logins($))
396}
397
398const ownerOf = (ref: PrRef) => ref.repo.split('/')[0] ?? ''
399
400// One batch's call, timed, and what GitHub said: the status and headers, and the reply.
401async function askBatch($: EngineInterface, part: readonly PrRef[], argv: string[], token: string, timeoutMs = GH_MS) {
402  const startedAt = await $.clock.now()
403  // A call past its timeout throws: it fails as a timeout, rather than losing the round.
404  const res = await gh($, argv, token, undefined, timeoutMs).catch(() => ({
405    stdout: '',
406    stderr: `gh api graphql did not finish: timeout after ${Math.round(timeoutMs / 1_000)}s`,
407  }))
408  const http = parseHttp(res.stdout)
409
410  return { http, reply: parseReply(http.body, res.stderr, part), ms: (await $.clock.now()) - startedAt }
411}
412
413// Why a failed call failed (null: it didn't), logged to errors.log on the way.
414async function failureIn($: EngineInterface, login: string, size: number, call: { http: Http; reply: { error: string | null }; ms: number }) {
415  if (call.reply.error === null) return null
416  const failure: CallFailure = failureOf(call.reply.error, call.http)
417  await logFailure($, { login, size, ms: call.ms, http: call.http, failure, error: call.reply.error })
418
419  return failure
420}
421
422// Best effort: a log that can't be read starts over, and one that can't be written is skipped.
423async function logFailure($: EngineInterface, call: CallLog) {
424  const path = `${await root($)}/errors.log`
425  let log = ''
426  try {
427    log = String(await $.fs.read(path))
428  } catch {
429    // None yet.
430  }
431  try {
432    await $.fs.write(path, appendLog(log, logLine(await $.clock.now(), call)))
433  } catch {
434    // Nothing to do: the log is for the person reading it later.
435  }
436}
437
438// `withLatest`: the first batch also asks for pr-watch's newest version. `until`: when the
439// lease ends (a second kept to write the results). A batch starts only with time left before
440// it and may take no more than is left (callBudget); the rest are `left` for the next round,
441// as they were. A secondary limit stops the asking (`waitMs`: how long every session holds
442// off), and spent points stop this login's. Neither is a card's error: the gh meter says it
443// (rate.ts), and the PRs keep what they have. Every batch goes as `login`, with its token; where
444// that won't come, nothing is asked, and the PRs fail as on a timeout: none is called not found.
445async function query($: EngineInterface, refs: readonly PrRef[], login: string, until: number, withLatest = false) {
446  const out = {
447    found: new Map<string, GhPr>(),
448    missing: [] as PrRef[],
449    failed: new Map<string, string>(),
450    left: [] as PrRef[],
451    // The points as the last reply said, and when.
452    rate: null as RateLimit | null,
453    rateAt: 0,
454    latest: null as string | null,
455    isLatestAsked: false,
456    waitMs: null as number | null,
457  }
458  // The token, too, comes inside the lease: a keyring that hangs never outlives it.
459  const tokenBudget = callBudget(until, await $.clock.now(), GH_MS)
460  if (tokenBudget === null) {
461    out.left.push(...refs)
462
463    return out
464  }
465  const token = await tokenFor($, login, tokenBudget)
466  if ('error' in token) {
467    for (const ref of refs) out.failed.set(ref.url, token.error)
468
469    return out
470  }
471  const parts = chunks(refs)
472  for (const [i, part] of parts.entries()) {
473    const budget = callBudget(until, await $.clock.now(), GH_MS)
474    if (budget === null) {
475      out.left.push(...parts.slice(i).flat())
476
477      break
478    }
479    const argv = ['api', 'graphql', '-f', `query=${buildQuery(part, withLatest && i === 0)}`, '-i']
480    out.isLatestAsked ||= withLatest && i === 0
481    let call = await askBatch($, part, argv, token.token, budget)
482    let failure = await failureIn($, login, part.length, call)
483    if (failure === 'timeout') {
484      const retry = callBudget(until, (await $.clock.now()) + RETRY_MS, GH_MS)
485      if (retry !== null) {
486        await $.clock.sleep(RETRY_MS)
487        call = await askBatch($, part, argv, token.token, retry)
488        failure = await failureIn($, login, part.length, call)
489      }
490    }
491    const { http, reply } = call
492    const isLimit = failure === 'secondary-limit' || failure === 'primary-limit'
493    if (reply.error !== null && !isLimit) for (const ref of part) out.failed.set(ref.url, reply.error)
494    for (const [url, pr] of reply.found) out.found.set(url, pr)
495    out.missing.push(...reply.missing)
496    const rate = rateOf(http.headers) ?? reply.rate
497    if (rate !== null) {
498      out.rate = rate
499      out.rateAt = await $.clock.now()
500    }
501    out.latest = reply.latest ?? out.latest
502    if (failure === 'secondary-limit') {
503      const after = retryAfterOf(http.headers)
504      out.waitMs = after !== null ? after * 1_000 : LIMIT_WAIT_MS
505
506      break
507    }
508    // Spent points: the login's other batches would only be refused the same way. This one
509    // went unanswered too, so it is left as well, never read as "not found".
510    if (failure === 'primary-limit') {
511      out.left.push(...parts.slice(i).flat())
512
513      break
514    }
515  }
516
517  return out
518}
519
520// One batched query per gh account; PRs the expected account cannot see are retried with
521// each other logged-in account, and the one that sees them is remembered per owner. The
522// newest version, when asked, rides the first batch that goes; `asked` says whether it went.
523// On a round (`isRound`), a login whose points are low (rate.ts) is left out until its reset,
524// its PRs keeping what they have, and the others are asked as ever; a watch or a Refresh, one
525// call the person asked for, still goes. `rates` goes in as known and comes back with
526// the points each login's replies said; `needed`: the logins these PRs are polled as.
527async function fetchRefs(
528  $: EngineInterface,
529  refs: readonly PrRef[],
530  accounts: Record<string, string>,
531  rates: Rates,
532  at: number,
533  until: number,
534  isRound: boolean,
535  withLatest = false,
536) {
537  const found = new Map<string, GhPr>()
538  const errors = new Map<string, { error: string; isMiss: boolean }>()
539  let seen = rates
540  let latest: string | null = null
541  let isAsking = withLatest
542  let waitMs: number | null = null
543  const known = await logins($)
544  const isLow = (login: string) => isRound && lowUntil(seen, login, at) !== null
545  const saw = (login: string, r: { rate: RateLimit | null; rateAt: number }) => {
546    const graphql = bucketOf(r.rate, r.rateAt)
547    if (graphql !== null) seen = withSeen(seen, login, { graphql })
548  }
549  // The logins that answered "not found" for each PR, by url: the card names them.
550  const missedBy = new Map<string, string[]>()
551  const missedAs = (login: string, refs: readonly PrRef[]) => refs.forEach(ref => missedBy.set(ref.url, [...(missedBy.get(ref.url) ?? []), login]))
552  // The active account polls the owners no other account was found for, and those whose
553  // login has logged out since.
554  const byLogin = new Map<string, PrRef[]>()
555  for (const ref of refs) {
556    const login = loginFor(accounts, ownerOf(ref), known)
557    byLogin.set(login, [...(byLogin.get(login) ?? []), ref])
558  }
559  const needed = [...byLogin.keys()]
560
561  let missing: PrRef[] = []
562  for (const [login, group] of byLogin) {
563    if (waitMs !== null) break
564    if (isLow(login)) continue
565    const r = await query($, group, login, until, isAsking)
566    if (r.isLatestAsked) isAsking = false
567    waitMs = r.waitMs
568    saw(login, r)
569    r.found.forEach((pr, url) => {
570      found.set(url, pr)
571      // Remembered as a login that has logged out, and seen as this one: this one from now on.
572      const ref = group.find(x => x.url === url)
573      const owner = ref === undefined ? '' : ownerOf(ref)
574      if (owner !== '' && accounts[owner] !== undefined && accounts[owner] !== login) accounts[owner] = login
575    })
576    r.failed.forEach((error, url) => errors.set(url, { error, isMiss: false }))
577    missedAs(login, r.missing)
578    missing.push(...r.missing)
579    latest = r.latest ?? latest
580  }
581  if (missing.length > 0 && waitMs === null) {
582    // "Not found" only once every logged-in account was asked and answered: one that failed,
583    // ran out of time, is low on points or gave no token might see them yet. Before any is
584    // called that, gh's logins are read again, so one logged in since is asked too.
585    let isSure = true
586    let order = everyLogin(known)
587    for (const isAgain of [false, true]) {
588      if (isAgain) {
589        const budget = callBudget(until, await $.clock.now(), GH_MS)
590        if (missing.length === 0 || waitMs !== null || !isSure || budget === null) break
591        order = everyLogin(await logins($, true, budget))
592      }
593      for (const login of order) {
594        const untried = untriedBy(missing, missedBy, login)
595        if (untried.length === 0) continue
596        if (isLow(login)) {
597          isSure = false
598
599          continue
600        }
601        const r = await query($, untried, login, until)
602        waitMs = r.waitMs
603        saw(login, r)
604        if (r.failed.size > 0 || r.left.length > 0) isSure = false
605        // A PR never read says why it still isn't: as a failure, which passes.
606        r.failed.forEach((error, url) => {
607          if (!errors.has(url)) errors.set(url, { error, isMiss: false })
608        })
609        missedAs(login, r.missing)
610        r.found.forEach((pr, url) => {
611          found.set(url, pr)
612          errors.delete(url)
613          const ref = untried.find(x => x.url === url)
614          if (ref !== undefined) accounts[ownerOf(ref)] = login
615        })
616        missing = missing.filter(ref => !r.found.has(ref.url))
617        if (missing.length === 0 || waitMs !== null) break
618      }
619    }
620    // Held by a secondary limit, the rest were not all asked: they wait, as they were.
621    // With gh's logins unread, the others were never asked: no PR is called not found.
622    if (waitMs === null && isSure && order.length > 0) for (const ref of missing) errors.set(ref.url, { error: notFoundAs(missedBy.get(ref.url) ?? []), isMiss: true })
623  }
624
625  // An owner nobody is remembered for, whose PRs came back with less than write (a public repo
626  // of the other account reads as anyone's): its PRs asked once as each other login, and the
627  // owner kept as one that sees them all with more rights, so a merge goes as the right one.
628  // After the PRs with no data: an owner one of them was found for is remembered, so not asked.
629  const sightings = refs.flatMap(ref => {
630    const pr = found.get(ref.url)
631
632    return pr === undefined ? [] : [{ owner: ownerOf(ref), permission: pr.repository?.viewerPermission }]
633  })
634  for (const owner of waitMs === null ? ownersBelowWrite(sightings, accounts, known) : []) {
635    const asked = loginFor(accounts, owner, known)
636    const theirs = refs.filter(ref => ownerOf(ref) === owner && found.has(ref.url))
637    const rank = (prs: Iterable<GhPr>) => Math.max(0, ...[...prs].map(pr => rankOf(pr.repository?.viewerPermission)))
638    const answers = [{ login: asked, seen: theirs.length, rank: rank(theirs.flatMap(ref => found.get(ref.url) ?? [])) }]
639    const got = new Map<string, Map<string, GhPr>>()
640    let isSure = true
641    for (const login of everyLogin(known).filter(login => login !== asked)) {
642      if (isLow(login)) {
643        isSure = false
644
645        continue
646      }
647      const r = await query($, theirs, login, until)
648      waitMs = r.waitMs
649      saw(login, r)
650      if (r.failed.size > 0 || r.left.length > 0) isSure = false
651      got.set(login, r.found)
652      answers.push({ login, seen: r.found.size, rank: rank(r.found.values()) })
653      if (waitMs !== null) break
654    }
655    const best = bestLogin(answers, theirs.length)
656    // Asked as every other login and none does more: the first stands, and isn't asked again.
657    if (best !== asked || (isSure && waitMs === null)) accounts[owner] = best
658    got.get(best)?.forEach((pr, url) => found.set(url, pr))
659    if (waitMs !== null) break
660  }
661
662  return { found, errors, rates: seen, needed, latest, waitMs, asked: withLatest && !isAsking }
663}
664
665// GitHub's /rate_limit for each logged-in login once REST_MS is up (rate.ts): REST's requests,
666// and the points again, for the gh meter. It counts against no limit. Only a round asks, in
667// what is left of its lease, never every session; asked counts as checked, answered or not.
668async function askRest($: EngineInterface, rates: Rates, at: number, until: number): Promise<Rates> {
669  let seen = rates
670  for (const login of everyLogin(await logins($))) {
671    if (!isRestDue(seen, login, at)) continue
672    const budget = callBudget(until, await $.clock.now(), REST_CALL_MS)
673    if (budget === null) break
674    // A login gh gives no token for is not asked as another: it counts as asked, unanswered.
675    const token = await tokenFor($, login, budget)
676    const res = 'token' in token ? await gh($, ['api', 'rate_limit'], token.token, undefined, budget).catch(() => null) : null
677    const read = res !== null && res.exitCode === 0 ? restOf(res.stdout, await $.clock.now()) : null
678    seen = withSeen(seen, login, { ...read, askedAt: at })
679  }
680
681  return seen
682}
683
684const refFromUrl = (url: string): PrRef | null => {
685  const m = url.match(/^https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)$/)
686
687  return m === null ? null : { url, repo: m[1] ?? '', number: Number(m[2]) }
688}
689
690// Fetches `refs` now and merges them into the shared results, which it returns. `live`, on a
691// round: the PRs live sessions watch; the round drops the others once they are old.
692async function publish($: EngineInterface, refs: readonly PrRef[], at: number, live?: ReadonlySet<string>): Promise<Shared> {
693  const isRound = live !== undefined
694  const before = await readShared($)
695  // Held by a secondary limit: no round, no Refresh, no new watch asks until the wait is over.
696  if ((before.heldUntil ?? 0) > at) return before
697  const until = at + LEASE_MS - 1_000
698  const accountsWere = { ...before.accounts }
699  // A round asks for the newest version too, once the last check is CHECK_MS old.
700  const withLatest = isRound && isNoticeOn && at - (before.latest?.checkedAt ?? 0) >= CHECK_MS
701  const { found, errors, rates, needed, latest, waitMs, asked } = await fetchRefs($, refs, before.accounts, before.rates, at, until, isRound, withLatest)
702  // REST's count rides a round, never a watch or a Refresh, nor a round a limit stopped.
703  const seen = isRound && waitMs === null ? await askRest($, rates, at, until) : rates
704  // Re-read: another session may have written while this one was asking GitHub.
705  const shared = await readShared($)
706  shared.accounts = { ...shared.accounts, ...learned(accountsWere, before.accounts) }
707  found.forEach((pr, url) => (shared.prs[url] = { at, pr }))
708  // A PR with data keeps it through a failure, and its card says so only once it lasts.
709  errors.forEach(({ error, isMiss }, url) => (shared.prs[url] = failedEntry(shared.prs[url], error, at, isMiss)))
710  // Each login's latest sighting wins, whichever session made it.
711  for (const [login, rate] of Object.entries(seen)) shared.rates = withSeen(shared.rates, login, rate)
712  shared.rate = legacyRate(shared.rates) ?? shared.rate
713  // Asked is checked, answered or not: a check that fails waits as long as one that didn't,
714  // so it never rides every round. An unanswered one keeps the version known before.
715  if (asked) shared.latest = { version: latest ?? shared.latest?.version ?? null, checkedAt: at }
716  if (isRound) {
717    shared.prs = keptEntries(shared.prs, live, at)
718    const isMoving = [...found.values()].some(pr => derive(pr).isMoving)
719    shared.fetchedAt = at
720    shared.nextAt = at + (isMoving ? pace.fastMs : pace.slowMs)
721    // Only once every login the round needs is low does the round itself wait, for the first
722    // reset; one spent login holds back its own PRs alone.
723    const resetAt = roundWaitsUntil(shared.rates, needed, at)
724    if (resetAt !== null) shared.nextAt = Math.max(shared.nextAt, resetAt)
725  }
726  // A secondary limit: no round, and no Refresh, until GitHub's wait is over. A hold another
727  // session set while this one asked stands too: this round's nextAt never cuts it short.
728  if (waitMs !== null) shared.heldUntil = Math.max(shared.heldUntil ?? 0, (await $.clock.now()) + waitMs)
729  shared.nextAt = Math.max(shared.nextAt, shared.heldUntil ?? 0)
730  await writeResults($, shared)
731
732  return shared
733}
734
735// A session's tick: say what it watches, then either run the round (lease held) or read it.
736async function tick($: EngineInterface, own: readonly PrRef[], at: number): Promise<Shared> {
737  await announce($, own.map(ref => ref.url))
738  const shared = await readShared($)
739  if (at < shared.nextAt || !(await takeLease($, at))) return shared
740  try {
741    const urls = new Set([...(await liveUrls($, at)), ...own.map(ref => ref.url)])
742    // Longest unasked first, so a batch the last round had no time for goes first in this one.
743    const askedAt = (url: string) => shared.prs[url]?.failedSince ?? shared.prs[url]?.at ?? 0
744    const due = [...urls]
745      .flatMap(url => {
746        const entry = shared.prs[url]
747        const isFinished = entry?.pr !== undefined && entry.pr.state !== 'OPEN'
748        const ref = refFromUrl(url)
749
750        return ref === null || isUnreachable(entry, at) || isFinished ? [] : [ref]
751      })
752      .sort((a, b) => askedAt(a.url) - askedAt(b.url))
753
754    return await publish($, due, at, urls)
755  } finally {
756    await releaseLease($)
757  }
758}
759
760// ---- This session's cards -------------------------------------------------------------
761
762const refOf = (pr: TrackedPr): PrRef => ({ url: pr.url, repo: pr.repo, number: pr.number })
763
764// Folds the shared results into this session's cards: newer entries only, and a toast when
765// a card's state changes or a review lands. A new review's toast says it all: the state change
766// it caused (a review or ready headline) doesn't toast as well; CI, conflicts and a merge still do.
767async function apply($: EngineInterface, shared: Shared) {
768  const at = await $.clock.now()
769  const list = (await read($, prs)).map(full)
770  // The person's own reviews never toast, whichever of their gh accounts wrote them.
771  const mine = everyLogin(await logins($))
772  const moved: string[] = []
773  const next = list.map(current => {
774    const entry = shared.prs[current.url]
775    if (entry === undefined) return current
776    const error = entry.error ?? null
777    // Never read, as no login could see it: the card offers Try again.
778    const isNotFound = isMiss(entry)
779    // No newer data, yet the error may have come or gone: a failure that lasted keeps the
780    // entry's time, so "checked 2m ago" stays the age of what the card shows.
781    if (current.checkedAt !== null && entry.at <= current.checkedAt) {
782      return error === current.error && isNotFound === current.isNotFound ? current : { ...current, error, isNotFound }
783    }
784    if (entry.pr === undefined) return { ...current, error, isNotFound, checkedAt: current.checkedAt ?? entry.at }
785    const { fresh, seen } = newReviews(entry.pr, current.reviewSeen, mine, entry.pr.author?.login)
786    const pr: TrackedPr = {
787      ...current,
788      title: entry.pr.title,
789      state: entry.pr.state,
790      ...derive(entry.pr, current.reviews),
791      ...metaOf(entry.pr),
792      merge: mergeOf(entry.pr, current.merge),
793      reviews: reviewsOf(entry.pr) ?? current.reviews,
794      reviewSeen: seen,
795      checkedAt: entry.at,
796      error,
797      isNotFound: false,
798    }
799    const said = reviewToasts(fresh, pr.number)
800    for (const text of said) $.ui.toast(text)
801    if (current.checkedAt !== null && current.pill !== pr.pill && pr.error === null) {
802      const isReviewCaused = said.length > 0 && (pr.stage === 'review' || (pr.stage === 'ready' && pr.tone !== 'error'))
803      if (!isReviewCaused) $.ui.toast(`${TOAST_ICON[pr.tone] ?? '•'} PR #${pr.number} · ${pr.headline}`)
804      moved.push(pr.url)
805    }
806
807    return pr
808  })
809  await update($, prs, () => next)
810  await update($, now, () => at)
811  await update($, limits, current => {
812    const shown = limitsOf(shared, mine)
813
814    return JSON.stringify(current) === JSON.stringify(shown) ? current : shown
815  })
816  const heldUntil = shared.heldUntil ?? 0
817  if (heldUntil > at && heldUntil !== pauseEndsAt) {
818    pauseEndsAt = heldUntil
819    $.clock.after(heldUntil - at, async () => {
820      const ended = await $.clock.now()
821      await update($, now, current => Math.max(current, ended))
822    })
823  }
824  // What a hand-off press said belongs to the failure, the threads or the conflict it was
825  // about: gone once the card moves on, or no longer offers that hand-off (a draft's pill
826  // stays put as its conflict comes and goes).
827  const cards = new Map(next.map(pr => [pr.url, pr]))
828  for (const handoff of HANDOFFS) {
829    const isStale = (url: string) => {
830      const card = cards.get(url)
831
832      return moved.includes(url) || (card !== undefined && !handoff.isOffered(card))
833    }
834    await updateRows($, handoff.id, all => {
835      const kept = Object.entries(all).filter(([url, ask]) => !isStale(url) || isBusy(ask.busy, at))
836
837      return kept.length === Object.keys(all).length ? all : Object.fromEntries(kept)
838    })
839  }
840  await refreshStatus($)
841  await syncAnimation($)
842  // Last, and never thrown: the update notice must not cost a PR result.
843  await sayNewer($, shared).catch(() => undefined)
844  await sayCompanion($).catch(() => undefined)
845}
846
847// What the gh meter shows: the logged-in logins' buckets, the active one first (every login the
848// results know of, where gh named none), and the hold.
849function limitsOf(shared: Shared, names: readonly string[]): Limits {
850  const { rates } = shared
851  const known = names.filter(name => name !== '')
852  const order = known.length > 0 ? known : Object.keys(rates)
853
854  return {
855    logins: order.flatMap(login => {
856      const { graphql, core } = rates[login] ?? {}
857
858      return graphql !== undefined || core !== undefined ? [{ login, ...(graphql && { graphql }), ...(core && { core }) }] : []
859    }),
860    heldUntil: shared.heldUntil ?? 0,
861  }
862}
863
864// This copy's own version, from its plugin.json (the API names the plugin, not its version).
865// Kept once read (null: no plain version to compare); unreadable, it is read again next time,
866// and until then nothing is said.
867let ownVersion: string | null | undefined
868// The version this load toasted, should notice.json not take the write.
869let toldVersion: string | null = null
870
871async function readOwnVersion($: EngineInterface): Promise<string | null> {
872  if (ownVersion === undefined) {
873    try {
874      ownVersion = versionIn(String(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`)))
875    } catch {
876      return null
877    }
878  }
879
880  return ownVersion
881}
882
883// Whether the last check found a newer pr-watch: the footer says so, and one toast per new
884// version across every session on the machine (notice.json keeps the one toasted, so a new
885// session or a reload doesn't toast it again).
886async function sayNewer($: EngineInterface, shared: Shared) {
887  const own = await readOwnVersion($)
888  const latest = shared.latest?.version ?? null
889  const next =
890    isNoticeOn && own !== null && latest !== null && isNewer(latest, own)
891      ? { version: latest, how: howToUpdate($.plugin.root, await home($), $.plugin.name) }
892      : null
893  await update($, newer, current => (current?.version === next?.version && current?.how === next?.how ? current : next))
894  if (next === null || toldVersion === next.version) return
895  toldVersion = next.version
896  const path = `${await root($)}/notice.json`
897  if ((await readJson<{ version?: string }>($, path))?.version === next.version) return
898  // Claim, wait, re-read (as takeLease does): sessions that read notice.json at once would
899  // otherwise all toast. Only the claim that stuck toasts.
900  await writeJson($, path, { version: next.version, owner: INSTANCE })
901  await $.clock.sleep(150)
902  const claim = await readJson<{ version?: string; owner?: string }>($, path)
903  if (claim?.version === next.version && claim.owner === INSTANCE) $.ui.toast(noticeToast(next.version, next.how))
904}
905
906// Why the card telling of prw is gone for good, once known: read from companion.json, which
907// a dismissal in any session writes, or written here on finding prw has run.
908let companionState: CompanionState | null = null
909
910// The card telling of prw: shown until someone dismisses it (in any session) or prw is seen
911// running, and only while the update notice is on.
912async function sayCompanion($: EngineInterface) {
913  const isNews = isNoticeOn && companionState === null && (await isCompanionNews($))
914  await update($, companion, current => {
915    // Asked again after the reads: a Dismiss pressed, or the notice turned off, while they ran wins.
916    const isShown = isNews && isNoticeOn && companionState === null
917
918    return current === isShown ? current : isShown
919  })
920}
921
922async function isCompanionNews($: EngineInterface): Promise<boolean> {
923  const cache = await root($)
924  const said = companionIn(await readJson<unknown>($, `${cache}/companion.json`))
925  // Read first, then `??=`: a Dismiss pressed during the read isn't undone by the file it hasn't
926  // written yet.
927  companionState ??= said
928  if (companionState !== null) return false
929  const names = (await $.fs.list(`${cache}/sessions`).catch(() => [])).map(f => f.name)
930  if (!isPrwIn(names)) return true
931  if (companionState !== null) return false
932  companionState = 'seen'
933  await writeJson($, `${cache}/companion.json`, { state: companionState })
934
935  return false
936}
937
938async function dismissCompanion($: EngineInterface) {
939  companionState = 'dismissed'
940  await update($, companion, () => false)
941  await writeJson($, `${await root($)}/companion.json`, { state: companionState, at: await $.clock.now() })
942}
943
944// Fetches these PRs now (a new watch, the Refresh button) rather than waiting for the round.
945async function fetchNow($: EngineInterface, refs: PrRef[]) {
946  if (refs.length === 0) return
947  // Held by a secondary limit, publish asks nothing: the next round does, once the wait is over.
948  await apply($, await publish($, refs, await $.clock.now()))
949}
950
951// Try again on a card no login could see: asked now as every login, the five-minute skip
952// (cache.ts) notwithstanding. Found, the card fills and the mark goes; not, the card says again
953// who was asked, gh's logins read afresh first (fetchRefs). A second press while it asks does
954// nothing.
955async function tryAgain($: EngineInterface, pr: TrackedPr) {
956  const busy = { at: await $.clock.now() }
957  let isClaimed = false
958  await update($, retrying, all => {
959    isClaimed = !isBusy(all[pr.url], busy.at)
960
961    return isClaimed ? { ...all, [pr.url]: busy } : all
962  })
963  if (!isClaimed) return
964  try {
965    await fetchNow($, [refOf(pr)])
966  } catch {
967    // The card says what it said: the button comes back to press again.
968  } finally {
969    await update($, retrying, all => {
970      const { [pr.url]: _, ...rest } = all
971
972      return all[pr.url]?.at === busy.at ? rest : all
973    })
974  }
975}
976
977async function setAsk($: EngineInterface, url: string, ask: MergeAsk | null) {
978  await update($, merging, all => {
979    const { [url]: _, ...rest } = all
980
981    return ask === null ? rest : { ...rest, [url]: ask }
982  })
983}
984
985// One question at a time across the pane, so y and n answer the one on screen.
986async function oneQuestion($: EngineInterface) {
987  await update($, merging, all => Object.fromEntries(Object.entries(all).map(([url, a]) => [url, { ...a, asking: undefined }])))
988  for (const handoff of HANDOFFS) {
989    await updateRows($, handoff.id, all => Object.fromEntries(Object.entries(all).map(([url, a]) => [url, { ...a, asking: undefined }])))
990  }
991}
992
993// Marks a card's merge row busy for a run, unless a run already holds it: false then, so a
994// second press (a double click, `y` twice) starts nothing. One write, so two can't both win.
995async function claimMerge($: EngineInterface, url: string, ask: MergeAsk & Required<Pick<MergeAsk, 'busy'>>) {
996  let isClaimed = false
997  await update($, merging, all => {
998    isClaimed = !isBusy(all[url]?.busy, ask.busy.at)
999
1000    return isClaimed ? { ...all, [url]: ask } : all
1001  })
1002
1003  return isClaimed
1004}
1005
1006const BUSY: Record<MergeRun['action'], string> = {
1007  merge: 'Merging…',
1008  auto: 'Turning on auto-merge…',
1009  'cancel-auto': 'Cancelling auto-merge…',
1010}
1011
1012// Runs gh pr merge as the account the poller found sees the repo (its token, never written
1013// anywhere), and only as that one, then asks GitHub again at once so the card shows what
1014// happened. A server error (a 502, a gateway timeout) says nothing of whether it went through:
1015// RETRY_MS on, the PR is read again as the same login, and the run counts as done, runs once
1016// more, or shows the error it had, as afterServerError says (pr.ts).
1017async function runMerge($: EngineInterface, pr: TrackedPr, run: MergeRun) {
1018  const method = run.action === 'cancel-auto' ? undefined : run.method
1019  const busy = { action: run.action, at: await $.clock.now() }
1020  if (!(await claimMerge($, pr.url, { method, busy }))) return
1021  let ask: MergeAsk = { method }
1022  try {
1023    const got = await tokenFor($, await pressLogin($, pr))
1024    if ('error' in got) ask = { method, error: got.error }
1025    else {
1026      let res = await gh($, mergeArgv(pr.url, run), got.token)
1027      if (res.exitCode !== 0 && isServerError(res.stderr || res.stdout)) {
1028        await $.clock.sleep(RETRY_MS)
1029        const view = await gh($, mergeReadArgv(pr.url), got.token).catch(() => null)
1030        const next = afterServerError(run, view !== null && view.exitCode === 0 ? mergeReadOf(view.stdout) : null)
1031        if (next === 'done') res = { ...res, exitCode: 0 }
1032        else if (next === 'retry') res = await gh($, mergeArgv(pr.url, run), got.token)
1033      }
1034      if (res.exitCode !== 0) {
1035        const { message, isMethodRefused } = mergeError(res.stderr || res.stdout)
1036        ask = { method: isMethodRefused ? undefined : method, error: message }
1037        if (isMethodRefused && method !== undefined) {
1038          await update($, refused, all => ({ ...all, [pr.repo]: [...new Set([...(all[pr.repo] ?? []), method])] }))
1039        }
1040      }
1041    }
1042  } catch {
1043    ask = { method, error: 'gh pr merge did not finish' }
1044  }
1045  // Only while the row is still this run's: not on a dismissed card, nor over a later press.
1046  await update($, merging, all => (all[pr.url]?.busy?.at === busy.at ? { ...all, [pr.url]: ask } : all))
1047  await fetchNow($, [refOf(pr)])
1048}
1049
1050// ---- Comment ------------------------------------------------------------------------------
1051// A card's Comment opens a field; Enter posts what it holds to the PR's conversation (an issue
1052// comment, not a review). Nothing is preset: the person writes every comment.
1053
1054// The field's address: what `$.ui.focus` and a test type into.
1055const commentKey = (url: string) => `comment-text:${url}`
1056
1057async function setComment($: EngineInterface, url: string, ask: CommentAsk | null) {
1058  await update($, commenting, all => {
1059    const { [url]: _, ...rest } = all
1060
1061    return ask === null ? rest : { ...rest, [url]: ask }
1062  })
1063}
1064
1065// Open or Cancel from a frame drawn before a post began (a quick click, another surface) waits
1066// on it: overwriting its row would drop what it came to, and let a second Enter post again.
1067// False: a post holds the row, nothing changed.
1068async function setIdleComment($: EngineInterface, url: string, ask: CommentAsk | null) {
1069  const at = await $.clock.now()
1070  let isSet = false
1071  await update($, commenting, all => {
1072    isSet = !isBusy(all[url]?.busy, at)
1073    if (!isSet) return all
1074    const { [url]: _, ...rest } = all
1075
1076    return ask === null ? rest : { ...rest, [url]: ask }
1077  })
1078
1079  return isSet
1080}
1081
1082// Comment opens the field, the last post's word gone, and moves the keys onto it where the pane
1083// holds them (a click, ctrl+x tab); where it doesn't, the field takes them once it does.
1084async function openComment($: EngineInterface, pr: TrackedPr) {
1085  if (!(await setIdleComment($, pr.url, { isOpen: true }))) return
1086  void $.ui.focus({ requestId: PANE, key: commentKey(pr.url) }).catch(() => undefined)
1087}
1088
1089// Cancel: the field closes and its text goes, nothing posted.
1090async function closeComment($: EngineInterface, url: string) {
1091  if (await setIdleComment($, url, null)) drafts.delete(url)
1092}
1093
1094// Enter in the field posts its text as the login the poller found sees the repo, by that login's
1095// own token, as a merge runs (runMerge): never as another account. Blank text does nothing, and
1096// neither does a second Enter while it posts. Posted, the field closes, the card links the
1097// comment and GitHub is asked again (a comment can start checks or change a review); refused,
1098// the text stays in the field and the card says why, to try again.
1099async function postComment($: EngineInterface, pr: TrackedPr, text: string) {
1100  if (!isPostable(text)) return
1101  const busy = { at: await $.clock.now() }
1102  let isClaimed = false
1103  await update($, commenting, all => {
1104    const ask = all[pr.url]
1105    isClaimed = ask?.isOpen === true && !isBusy(ask.busy, busy.at)
1106
1107    return isClaimed ? { ...all, [pr.url]: { isOpen: true, busy } } : all
1108  })
1109  if (!isClaimed) return
1110  drafts.set(pr.url, text)
1111  let ask: CommentAsk = { isOpen: true }
1112  try {
1113    const login = await pressLogin($, pr)
1114    const got = await tokenFor($, login)
1115    if ('error' in got) ask = { isOpen: true, error: got.error }
1116    else {
1117      // The text on stdin, never in argv (comment.ts), which is why this isn't gh().
1118      const res = await $.process.run(['gh', ...commentArgv(pr)], { timeoutMs: GH_MS, env: { GH_TOKEN: got.token }, stdin: commentInput(text) })
1119      ask = res.exitCode === 0 ? { done: { url: commentUrl(res.stdout) ?? pr.url, login } } : { isOpen: true, error: commentError(res.stderr || res.stdout, login) }
1120    }
1121  } catch {
1122    // Cut off, not refused: GitHub may have taken it, so a retry could post it twice.
1123    ask = { isOpen: true, error: "Couldn't tell whether it posted: gh api did not finish. Check the PR before trying again" }
1124  }
1125  if (ask.done !== undefined) drafts.delete(pr.url)
1126  // Only while the row is still this post's: not on a dismissed card.
1127  await update($, commenting, all => (all[pr.url]?.busy?.at === busy.at ? { ...all, [pr.url]: ask } : all))
1128  if (ask.done !== undefined) await fetchNow($, [refOf(pr)])
1129}
1130
1131// Which hand-off a row is: Fix with Claude's (`fixing`), Address with Claude's (`addressing`)
1132// or Resolve with Claude's (`resolving`). They run apart, so a card can collect logs while its
1133// threads come.
1134type Kind = 'fix' | 'address' | 'resolve'
1135type Rows = Record<string, HandoffAsk>
1136
1137// A hand-off row's state, each atom named where it is read or written, so the mod's state can
1138// be listed.
1139async function readRows($: EngineInterface, kind: Kind): Promise<Rows> {
1140  if (kind === 'fix') return read($, fixing)
1141
1142  return kind === 'address' ? read($, addressing) : read($, resolving)
1143}
1144
1145// Every hand-off's rows, by kind, for the pane and the band.
1146async function readHandoffs($: EngineInterface): Promise<Record<Kind, Rows>> {
1147  const [fix, address, resolve] = await Promise.all([readRows($, 'fix'), readRows($, 'address'), readRows($, 'resolve')])
1148
1149  return { fix, address, resolve }
1150}
1151
1152async function updateRows($: EngineInterface, kind: Kind, change: (all: Rows) => Rows) {
1153  if (kind === 'fix') await update($, fixing, change)
1154  else if (kind === 'address') await update($, addressing, change)
1155  else await update($, resolving, change)
1156}
1157
1158async function setHandoff($: EngineInterface, kind: Kind, url: string, ask: HandoffAsk | null) {
1159  await updateRows($, kind, all => {
1160    const { [url]: _, ...rest } = all
1161
1162    return ask === null ? rest : { ...rest, [url]: ask }
1163  })
1164}
1165
1166// A collection's outcome, only while the row is still its own (see runMerge).
1167async function settleHandoff($: EngineInterface, kind: Kind, url: string, at: number, ask: HandoffAsk) {
1168  await updateRows($, kind, all => (all[url]?.busy?.at === at ? { ...all, [url]: ask } : all))
1169}
1170
1171// claimMerge for a hand-off row: a second press while the logs or threads come starts nothing.
1172async function claimHandoff($: EngineInterface, kind: Kind, url: string, busy: Busy) {
1173  let isClaimed = false
1174  await updateRows($, kind, all => {
1175    isClaimed = !isBusy(all[url]?.busy, busy.at)
1176
1177    return isClaimed ? { ...all, [url]: { busy } } : all
1178  })
1179
1180  return isClaimed
1181}
1182
1183// Collects what failed on a card, as the gh account the poller found sees the repo: the
1184// failing checks as GitHub has them now, and the failed steps' logs of the first few Actions
1185// jobs. A part that won't come is said on the card; the rest still goes, names and links.
1186async function collectFailure($: EngineInterface, pr: TrackedPr) {
1187  const busy = { at: await $.clock.now() }
1188  if (!(await claimHandoff($, 'fix', pr.url, busy))) return
1189  try {
1190    const got = await tokenFor($, await pressLogin($, pr))
1191    // No token for that login: nothing is read as another one.
1192    if ('error' in got) {
1193      await settleHandoff($, 'fix', pr.url, busy.at, { error: got.error })
1194
1195      return
1196    }
1197    const { token } = got
1198    let failures: Failure[]
1199    let problem: string | null = null
1200    try {
hooks/look.ts 179 lines
1// The pane's true-colour paint: gradient bars, a shimmer over pending checks and a
2// hue-cycling spinner, all packed as Raster cells so the animation can blit frames. The
3// colours, glyphs and the background behind the cells are the theme's (theme.ts).
4import type { Checks } from '../types'
5import type { Ramp, RasterPaint, Rgb } from './theme'
6
7export type Cell = readonly [codePoint: number, fg: number, bg: number]
8
9// A cell's colour for the terminal's own background (or foreground).
10export const DEFAULT_BG = 0x01000000
11
12// What a CI bar is painted with: the theme's ramps, and the card's fill behind (null: the
13// terminal's own background).
14export type BarPaint = Pick<RasterPaint, 'green' | 'red' | 'amber' | 'shine'> & { bg: number | null }
15
16export const clamp01 = (n: number) => Math.min(1, Math.max(0, n))
17
18export function lerp(a: Rgb, b: Rgb, t: number): Rgb {
19  const k = clamp01(t)
20
21  return [0, 1, 2].map(i => Math.round(a[i]! + (b[i]! - a[i]!) * k)) as unknown as Rgb
22}
23
24export function hex([r, g, b]: Rgb): number {
25  return (r << 16) | (g << 8) | b
26}
27
28// The xterm cube's six levels a channel.
29const LEVELS = [0, 95, 135, 175, 215, 255] as const
30
31// The xterm 256-colour palette's colour `n` (16 to 255: the 6×6×6 cube, then 24 greys), as the
32// terminal paints it. Where Claude Code draws 256 colours (inside tmux, by default) it rounds
33// every colour to one of these; one of them stays itself.
34export function x256(n: number): Rgb {
35  if (n >= 232) {
36    const v = 8 + (n - 232) * 10
37
38    return [v, v, v]
39  }
40  const i = Math.max(0, n - 16)
41
42  return [LEVELS[Math.floor(i / 36) % 6]!, LEVELS[Math.floor(i / 6) % 6]!, LEVELS[i % 6]!]
43}
44
45// The palette colour Claude Code paints `rgb` as in 256 colours: the cube's nearest level on
46// each channel, or the grey ramp's nearest where that is closer (as its painter rounds).
47export function nearest256([r, g, b]: Rgb): Rgb {
48  const level = (c: number) => (c < 48 ? 0 : c < 115 ? 1 : c < 155 ? 2 : c < 195 ? 3 : c < 235 ? 4 : 5)
49  const cube: Rgb = [LEVELS[level(r)]!, LEVELS[level(g)]!, LEVELS[level(b)]!]
50  const grey = 8 + 10 * Math.max(0, Math.min(23, Math.round(((r + g + b) / 3 - 8) / 10)))
51  const far = (to: Rgb) => (r - to[0]) ** 2 + (g - to[1]) ** 2 + (b - to[2]) ** 2
52
53  return far([grey, grey, grey]) < far(cube) ? [grey, grey, grey] : cube
54}
55
56export function gradientAt(stops: readonly Rgb[], t: number): Rgb {
57  const span = (stops.length - 1) * clamp01(t)
58  const i = Math.min(stops.length - 2, Math.floor(span))
59
60  return lerp(stops[i]!, stops[i + 1]!, span - i)
61}
62
63export function encode(cells: readonly Cell[]): string {
64  const words = new Uint32Array(cells.length * 3)
65  cells.forEach(([cp, fg, bg], i) => words.set([cp, fg, bg], i * 3))
66  const bytes = new Uint8Array(words.buffer)
67  let binary = ''
68  for (const byte of bytes) binary += String.fromCharCode(byte)
69
70  return btoa(binary)
71}
72
73const cell = (glyph: string, rgb: Rgb, bg: number | null = null): Cell => [glyph.codePointAt(0)!, hex(rgb), bg ?? DEFAULT_BG]
74
75// Splits `width` cells among the counts, every non-zero count keeping at least one.
76export function allot(counts: readonly number[], width: number): number[] {
77  const total = counts.reduce((a, b) => a + b, 0)
78  if (total === 0) return counts.map(() => 0)
79  const raw = counts.map(n => (n / total) * width)
80  const out = raw.map((r, i) => (counts[i]! > 0 ? Math.max(1, Math.floor(r)) : 0))
81  let left = width - out.reduce((a, b) => a + b, 0)
82  const order = raw.map((r, i) => [r - Math.floor(r), i] as const).sort((a, b) => b[0] - a[0])
83  for (let k = 0; left > 0 && k < order.length * 4; k++) {
84    const i = order[k % order.length]![1]
85    if (counts[i]! > 0) {
86      out[i]! += 1
87      left -= 1
88    }
89  }
90  while (left < 0) {
91    const i = out.indexOf(Math.max(...out))
92    out[i]! -= 1
93    left += 1
94  }
95
96  return out
97}
98
99// One row of `━`: passed, failed, then pending (with a light sweeping across it).
100export function barCells(checks: Checks, width: number, frame: number, paint: BarPaint): string {
101  const [passed = 0, failed = 0, pending = 0] = allot([checks.passed, checks.failed, checks.pending], width)
102  const cells: Cell[] = []
103  const run = (n: number, [from, to]: Ramp, shine?: number) => {
104    for (let i = 0; i < n; i++) {
105      let rgb = lerp(from, to, n === 1 ? 1 : i / (n - 1))
106      if (shine !== undefined) rgb = lerp(rgb, paint.shine, Math.max(0, 1 - Math.abs(i - shine) / 3) * 0.85)
107      cells.push(cell('━', rgb, paint.bg))
108    }
109  }
110  run(passed, paint.green)
111  run(failed, paint.red)
112  run(pending, paint.amber, (frame % (pending + 8)) - 4)
113
114  return encode(cells)
115}
116
117export function fullBarCells(width: number, colours: Ramp, bg: number | null = null): string {
118  return encode(Array.from({ length: width }, (_, i) => cell('━', lerp(colours[0], colours[1], i / Math.max(1, width - 1)), bg)))
119}
120
121// The header's rule: the theme's `glyphs` repeated across (one, or a pattern such as a wave's
122// heights), through its gradient stops.
123export function ruleCells(width: number, stops: readonly Rgb[], glyphs: string): string {
124  const pattern = [...glyphs]
125
126  return encode(Array.from({ length: width }, (_, i) => cell(pattern[i % pattern.length]!, gradientAt(stops, i / Math.max(1, width - 1)))))
127}
128
129// The rule as text, `width` cells of the pattern, where no Raster draws.
130export function ruleText(width: number, glyphs: string): string {
131  const pattern = [...glyphs]
132
133  return Array.from({ length: width }, (_, i) => pattern[i % pattern.length]).join('')
134}
135
136// The gh meter's paint: a ramp per health (look.ts's green, amber and red), and the track.
137export type MeterPaint = Pick<RasterPaint, 'green' | 'amber' | 'red' | 'track' | 'isPalette'>
138export type Health = 'warning' | 'error' | null
139
140// One login's budget as one thin bar: the top half of each cell of a row of `▀`, the share left
141// coloured by its health over the track, the cell where it ends blended by how much of it is
142// filled; the bottom half is the terminal's own background, so the bars of two logins on rows
143// one over the other stay apart. Not known yet: no bar.
144export function meterCells(bar: { share: number; health: Health } | null, width: number, paint: MeterPaint): string {
145  const ramp = bar?.health === 'error' ? paint.red : bar?.health === 'warning' ? paint.amber : paint.green
146  const at = (i: number): Cell => {
147    if (bar === null) return [0x20, DEFAULT_BG, DEFAULT_BG]
148    const filled = clamp01(bar.share) * width
149    const colour = lerp(ramp[0], ramp[1], width === 1 ? 1 : i / (width - 1))
150
151    // In palette colours, the cell where the share ends is the bar's or the track's, never between;
152    // any share left keeps its first cell, so a nearly spent budget still shows red.
153    const part = paint.isPalette === true ? (i === 0 && filled > 0 ? 1 : Math.round(clamp01(filled - i))) : clamp01(filled - i)
154
155    return [0x2580, hex(lerp(paint.track, colour, part)), DEFAULT_BG]
156  }
157
158  return encode(Array.from({ length: width }, (_, i) => at(i)))
159}
160
161// One frame of the spinner: the theme's `glyphs` in turn, pulsing between its two colours.
162export function spinnerCell(frame: number, colours: Ramp, glyphs: readonly string[], bg: number | null = null): string {
163  const glyph = glyphs[frame % glyphs.length]!
164  const pulse = (Math.sin(frame / 3) + 1) / 2
165
166  return encode([cell(glyph, lerp(colours[0], colours[1], pulse), bg)])
167}
168
169// Text fallback for surfaces without Raster: the same bar as coloured runs.
170export function barRuns(checks: Checks, width: number): { text: string; colour: 'success' | 'error' | 'warning' }[] {
171  const [passed = 0, failed = 0, pending = 0] = allot([checks.passed, checks.failed, checks.pending], width)
172
173  return [
174    { text: '━'.repeat(passed), colour: 'success' as const },
175    { text: '━'.repeat(failed), colour: 'error' as const },
176    { text: '━'.repeat(pending), colour: 'warning' as const },
177  ].filter(run => run.text.length > 0)
178}
179
hooks/art.ts 477 lines
1// The banner cards (a theme's `layout: 'banner'`): each card one Raster, its text drawn into
2// the cells over painted art, so the art can sit behind the words. Tide: a liquid that fills the
3// card from the left as the PR moves on, deeper toward the bottom, behind a wavy front that
4// sways while the PR moves and is still when it doesn't. Aurora: curtains of light in the
5// state's colours, brighter as the PR moves on. Every text cell takes whichever of the theme's
6// two text colours reads better on that cell's background, so words read over both parts.
7// Where the terminal is painted in 256 colours (tmux, by default), a theme's paint has `steps`
8// and each art is drawn in a few palette colours instead (tideStepAt, auroraCell): gradients
9// would be rounded into blotches. Pure: the render lays a card out once, and the animation repaints it per frame.
10import type { Tone, TrackedPr } from '../types'
11import type { ArtKind, ArtPaint, ArtSteps, Rgb } from './theme'
12import { clamp01, encode, gradientAt, hex, lerp, nearest256 } from './look'
13import type { Cell } from './look'
14import { ago } from './pr'
15import { threadsBeside, verdictLine } from './review'
16
17// What a run of text is, so the painter colours it: the theme's text colours (`text`, `strong`,
18// `dim`), a tone's accent, the state badge's chip, the spinner, or no text at all.
19export type Role = 'text' | 'strong' | 'dim' | 'accent' | 'branch' | 'add' | 'del' | 'ok' | 'bad' | 'warn' | 'note' | 'badge' | 'spin' | 'blank'
20export type Seg = { text: string; role: Role }
21// A row of the card: runs from the left, and runs ending at the right edge (the badge).
22// `isRightSpare`: where the left runs won't fit beside them, the right runs give way.
23export type Line = { left: Seg[]; right?: Seg[]; isRightSpare?: boolean }
24export type Glyph = { cp: number; role: Role }
25
26// ---- How far the art has come --------------------------------------------------------------
27
28// A sliver, so a card that has only just started still shows its liquid moving.
29export const MIN_FILL = 0.04
30// CI done, a review to come: nearly full.
31export const REVIEW_FILL = 0.85
32
33// How much of the card the art fills, 0 to 1: CI's finished checks of all of them while they
34// run (a draft, half of that: it isn't heading for a merge yet), nearly full in review, full once
35// it is ready or merged; nothing for a closed PR, a sliver while it loads.
36export function fillOf(pr: Pick<TrackedPr, 'state' | 'stage' | 'checks'>): number {
37  if (pr.state === 'MERGED') return 1
38  if (pr.state === 'CLOSED') return 0
39  const { passed, failed, total } = pr.checks
40  const ci = total > 0 ? Math.min(1, (passed + failed) / total) : 0
41  switch (pr.stage) {
42    case 'merged':
43    case 'ready':
44      return 1
45    case 'review':
46      return REVIEW_FILL
47    case 'checks':
48      return Math.max(MIN_FILL, ci)
49    case 'draft':
50      return Math.max(MIN_FILL, ci / 2)
51    case 'closed':
52      return 0
53    case 'unknown':
54      return MIN_FILL
55  }
56}
57
58// Where tide's front stands on `row`, in cells from the left: the fill's share of the width,
59// swayed by two sines (`phase` moves them), the sway shrinking near either edge so the liquid
60// never leaves the card nor drains from it. Empty is 0 and full is `width`, unswayed.
61export function edgeAt(fill: number, width: number, row: number, phase: number): number {
62  const f = clamp01(fill)
63  if (f === 0) return 0
64  if (f === 1) return width
65  const base = f * width
66  const amp = Math.min(3.5, 0.8 * Math.min(base, width - base))
67  const wave = Math.sin(row * 1.1 + phase) * 0.65 + Math.sin(row * 2.3 - phase * 1.7) * 0.35
68
69  return Math.min(width, Math.max(0, base + amp * wave))
70}
71
72// ---- The cells' text ----------------------------------------------------------------------
73
74// A Raster's cell holds one printable width-1 character of the Basic Multilingual Plane. What
75// a terminal draws one cell wide, by range; zero-width marks are dropped; anything else (an
76// emoji, CJK, which take two) stands as one cell that says something was there.
77const NARROW: readonly (readonly [number, number])[] = [
78  [0x20, 0x7e],
79  [0xa0, 0x2ff],
80  [0x370, 0x482],
81  [0x48a, 0x52f],
82  [0x531, 0x58a],
83  [0x5d0, 0x5f4],
84  [0x620, 0x64a],
85  [0x660, 0x66f],
86  [0x671, 0x6d3],
87  [0x10a0, 0x10ff],
88  [0x1e00, 0x1fff],
89  [0x2010, 0x2027],
90  [0x2030, 0x205e],
91  [0x2070, 0x209c],
92  [0x20a0, 0x20c0],
93  [0x2100, 0x218b],
94  [0x2190, 0x2426],
95  [0x2440, 0x244a],
96  [0x2500, 0x2b73],
97]
98// Inside those, the ones drawn as an emoji (two cells).
99const WIDE: readonly (readonly [number, number])[] = [
100  [0x231a, 0x231b],
101  [0x2329, 0x232a],
102  [0x23e9, 0x23ec],
103  [0x23f0, 0x23f0],
104  [0x23f3, 0x23f3],
105  [0x25fd, 0x25fe],
106  [0x2614, 0x2615],
107  [0x2648, 0x2653],
108  [0x267f, 0x267f],
109  [0x2693, 0x2693],
110  [0x26a1, 0x26a1],
111  [0x26aa, 0x26ab],
112  [0x26bd, 0x26be],
113  [0x26c4, 0x26c5],
114  [0x26ce, 0x26ce],
115  [0x26d4, 0x26d4],
116  [0x26ea, 0x26ea],
117  [0x26f2, 0x26f3],
118  [0x26f5, 0x26f5],
119  [0x26fa, 0x26fa],
120  [0x26fd, 0x26fd],
121  [0x2705, 0x2705],
122  [0x270a, 0x270b],
123  [0x2728, 0x2728],
124  [0x274c, 0x274c],
125  [0x274e, 0x274e],
126  [0x2753, 0x2755],
127  [0x2757, 0x2757],
128  [0x2795, 0x2797],
129  [0x27b0, 0x27b0],
130  [0x27bf, 0x27bf],
131  [0x2b1b, 0x2b1c],
132  [0x2b50, 0x2b50],
133  [0x2b55, 0x2b55],
134]
135const ZERO: readonly (readonly [number, number])[] = [
136  [0xad, 0xad],
137  [0x300, 0x36f],
138  [0x483, 0x489],
139  [0x591, 0x5c7],
140  [0x610, 0x61a],
141  [0x64b, 0x65f],
142  [0x670, 0x670],
143  [0x200b, 0x200f],
144  [0x2028, 0x202e],
145  [0x2060, 0x2064],
146  [0x20d0, 0x20ff],
147  [0xfe00, 0xfe0f],
148  [0xfeff, 0xfeff],
149]
150// The card's own two-cell glyphs, drawn as one-cell ones that say the same.
151const STAND_IN: Record<string, string> = { '💬': '❝', '🎉': '✦' }
152
153const within = (ranges: readonly (readonly [number, number])[], cp: number) => ranges.some(([from, to]) => cp >= from && cp <= to)
154
155// `text` as Raster cells: one character a cell.
156export function narrowed(text: string): string[] {
157  return [...text].flatMap(ch => {
158    const cp = ch.codePointAt(0) ?? 0x3f
159    if (STAND_IN[ch] !== undefined) return [STAND_IN[ch]]
160    if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return [' ']
161    if (within(ZERO, cp)) return []
162    if (within(NARROW, cp) && !within(WIDE, cp)) return [ch]
163
164    return [cp > 0xffff ? '•' : '?']
165  })
166}
167
168const glyphsOf = (segs: readonly Seg[]): Glyph[] => segs.flatMap(seg => narrowed(seg.text).map(ch => ({ cp: ch.codePointAt(0) ?? 0x3f, role: seg.role })))
169
170// Left runs room the badge won't take from.
171const MIN_LEFT = 4
172
173// A row `width` cells wide: `pad` blank cells each side, the right runs against the right
174// edge, the left runs cut with "…" where they would reach them. Too narrow for both, the right
175// runs go (the status row says the state too).
176export function layoutLine(line: Line, width: number, pad = 1): Glyph[] {
177  const row: Glyph[] = Array.from({ length: width }, () => ({ cp: 0x20, role: 'blank' }))
178  const room = Math.max(0, width - 2 * pad)
179  let right = glyphsOf(line.right ?? [])
180  let left = glyphsOf(line.left)
181  if (right.length > 0 && (room - right.length - 1 < MIN_LEFT || (line.isRightSpare === true && left.length + right.length + 1 > room))) right = []
182  const leftRoom = Math.max(0, room - (right.length > 0 ? right.length + 1 : 0))
183  if (left.length > leftRoom) {
184    // Cut at a word's end where the cut falls on a space: "uploads…", never "uploads …".
185    const kept = left.slice(0, Math.max(0, leftRoom - 1))
186    while (kept.length > 0 && kept.at(-1)!.cp === 0x20) kept.pop()
187    // The "…" in the cut text's colour; never a blank's, which draws no glyph.
188    const role = kept.at(-1)?.role ?? left[0]!.role
189    left = leftRoom === 0 ? [] : [...kept, { cp: 0x2026, role: role === 'blank' ? 'dim' : role }]
190  }
191  left.forEach((glyph, i) => (row[pad + i] = glyph))
192  right.forEach((glyph, i) => (row[width - pad - right.length + i] = glyph))
193
194  return row
195}
196
197const VERDICT_ROLE = { approved: 'ok', changes: 'bad', commented: 'note', requested: 'dim' } as const
198
199// What a banner card says, a Line a row: the number, title and state badge; where it comes
200// from and goes (repo · branch → base · +/−); what it is doing now; then, as the stacked card
201// has them, failing checks past the first two, the reviewers, open threads and an error. Last,
202// an empty row, so the art has room below the words. Links and buttons are not cells: the
203// render draws them on rows of their own.
204export function bannerLines(pr: TrackedPr, at: number, columns: number): Line[] {
205  const isOpen = pr.state === 'OPEN'
206  const isMerged = pr.stage === 'merged'
207  const meta: Seg[] = [{ text: pr.repo, role: 'dim' }]
208  if (pr.branch !== '') {
209    meta.push(
210      { text: ' · ', role: 'dim' },
211      { text: pr.branch, role: 'branch' },
212      { text: ' → ', role: 'dim' },
213      { text: pr.base, role: 'dim' },
214      { text: '  ', role: 'blank' },
215      { text: `+${pr.additions}`, role: 'add' },
216      { text: ' ', role: 'blank' },
217      { text: `−${pr.deletions}`, role: 'del' },
218    )
219  }
220  const threads = isOpen && pr.reviews !== null ? threadsBeside(pr.headline, pr.reviews) : { line: '', note: '' }
221  const status: Seg[] = [...(pr.isMoving ? [{ text: '◌', role: 'spin' as const }, { text: ' ', role: 'blank' as const }] : []), { text: pr.headline, role: 'accent' }]
222  if (isMerged && pr.mergedAt !== null) status.push({ text: ` · ${ago(at - Date.parse(pr.mergedAt))}`, role: 'dim' })
223  if (threads.note !== '') status.push({ text: ` · ${threads.note}`, role: 'dim' })
224  // "4/5": CI's tally, unless the headline says it already.
225  const tally = `${pr.checks.passed}/${pr.checks.total}`
226  const lines: Line[] = [
227    { left: [{ text: `#${pr.number}`, role: 'accent' }, { text: ' ', role: 'blank' }, { text: pr.title || 'Loading…', role: 'strong' }], right: [{ text: ` ${pr.pill} `, role: 'badge' }] },
228    { left: meta, right: pr.author !== '' ? [{ text: `@${pr.author}`, role: 'dim' }] : [], isRightSpare: true },
229    { left: status, right: isOpen && pr.checks.total > 0 && !pr.headline.includes(tally) ? [{ text: tally, role: 'dim' }] : [], isRightSpare: true },
230  ]
231  for (const name of pr.checks.failing.slice(2, 5)) lines.push({ left: [{ text: `  ✗ ${name}`, role: 'bad' }] })
232  if (isOpen && pr.reviews !== null) {
233    const pieces = verdictLine(pr.reviews, columns - 2)
234    if (pieces.length > 0) {
235      lines.push({
236        left: pieces.flatMap((piece, i) => [
237          ...(i > 0 ? [{ text: ' · ', role: 'dim' as const }] : []),
238          { text: piece.text, role: piece.verdict === null ? ('dim' as const) : VERDICT_ROLE[piece.verdict] },
239        ]),
240      })
241    }
242    if (threads.line !== '') lines.push({ left: [{ text: threads.line, role: 'warn' }] })
243  }
244  if (pr.error !== null) lines.push({ left: [{ text: `⚠ ${pr.error}`, role: 'bad' }] })
245  lines.push({ left: [] })
246
247  return lines
248}
249
250// ---- The paint ----------------------------------------------------------------------------
251
252// A laid-out card, all the animation needs to paint a frame of it.
253export type ArtCard = {
254  kind: ArtKind
255  grid: Glyph[][]
256  fill: number
257  isMoving: boolean
258  // Sets each card's wave apart (the PR's number).
259  seed: number
260  tone: Tone
261  paint: ArtPaint
262  spin: readonly string[]
263}
264
265export function artCard(kind: ArtKind, pr: TrackedPr, at: number, columns: number, paint: ArtPaint, spin: readonly string[]): ArtCard {
266  return {
267    kind,
268    grid: bannerLines(pr, at, columns).map(line => layoutLine(line, columns)),
269    fill: fillOf(pr),
270    isMoving: pr.isMoving,
271    seed: pr.number,
272    tone: pr.tone,
273    paint,
274    spin,
275  }
276}
277
278// WCAG's relative luminance and contrast ratio.
279export function luminance([r, g, b]: Rgb): number {
280  const lin = (c: number) => {
281    const s = c / 255
282
283    return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
284  }
285
286  return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
287}
288
289export function contrast(a: Rgb, b: Rgb): number {
290  const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x) as [number, number]
291
292  return (hi + 0.05) / (lo + 0.05)
293}
294
295// Of the theme's light and dark text, the one that reads better on `bg`.
296export const inkOn = (bg: Rgb, paint: Pick<ArtPaint, 'light' | 'dark'>): Rgb => (contrast(paint.light, bg) >= contrast(paint.dark, bg) ? paint.light : paint.dark)
297
298// An accent is kept only where it reads this well on its cell; else the plain text colour.
299export const ACCENT_CONTRAST = 3
300
301const ROLE_TONE: Partial<Record<Role, Tone>> = { branch: 'suggestion', note: 'suggestion', add: 'success', ok: 'success', del: 'error', bad: 'error', warn: 'warning' }
302
303// The tone a role's accent comes from (`accent` and the spinner: the card's own); none for the
304// plain text colours.
305export const roleTone = (role: Role, tone: Tone): Tone | null => (role === 'accent' || role === 'spin' ? tone : (ROLE_TONE[role] ?? null))
306
307// A text cell's colour on `bg`.
308export function fgOf(role: Role, bg: Rgb, card: Pick<ArtCard, 'tone' | 'paint'>): Rgb {
309  const base = inkOn(bg, card.paint)
310  // In 256 colours, dimmed less and rounded here as the terminal would, so a cell is sent as
311  // painted.
312  if (role === 'dim') return card.paint.steps === undefined ? lerp(base, bg, 0.4) : nearest256(lerp(base, bg, 0.25))
313  const tone = roleTone(role, card.tone)
314  if (tone === null) return base
315  const ink = card.paint.tones[tone].ink
316
317  return contrast(ink, bg) >= ACCENT_CONTRAST ? ink : base
318}
319
320// Left partial blocks, by eighths filled: where the front crosses an empty cell, the liquid ends
321// inside it.
322const EIGHTHS = [...' ▏▎▍▌▋▊▉█']
323
324// Tide at a cell (tideAt): the background behind a word there; where the front ends inside
325// it, how much of it is liquid (null: none or all) and the liquid's colour there; and, painted
326// in 256 colours, its two halves where it holds no word.
327type TideCell = { bg: Rgb; cover: number | null; liquid: Rgb; halves?: readonly [top: Rgb, bottom: Rgb] }
328
329function tideAt(card: ArtCard, x: number, y: number, frame: number, rows: number, width: number): TideCell {
330  const { glass, surface, deep, crest } = card.paint.tones[card.tone]
331  const phase = card.seed * 0.7 + (card.isMoving ? frame * 0.22 : 0)
332  const edge = edgeAt(card.fill, width, y, phase)
333  const steps = card.paint.steps?.[card.tone]
334  if (steps !== undefined) return tideStepAt(card, x, y, frame, rows, width, edge, phase, steps.mid)
335  const depth = clamp01(0.55 * (rows <= 1 ? 1 : y / (rows - 1)) + 0.45 * (1 - (x + 0.5) / Math.max(1, edge)))
336  let liquid = lerp(surface, deep, depth)
337  // The crest catches the light; full, a glint sweeps across instead while the PR moves.
338  if (edge < width) liquid = lerp(liquid, crest, Math.max(0, 1 - (edge - (x + 0.5)) / 2.5) * 0.3)
339  else if (card.isMoving) {
340    const at = ((frame * 0.5 + card.seed * 3) % (width + 16)) - 8
341    liquid = lerp(liquid, crest, Math.max(0, 1 - Math.abs(x - at + y * 1.5) / 3) * 0.22)
342  }
343  const cover = clamp01(edge - x)
344  if (cover >= 1) return { bg: liquid, cover: null, liquid }
345  // Ahead of the front, the glass picks up a little of the water.
346  const ahead = lerp(glass, surface, Math.max(0, 1 - (x - edge) / 3) * 0.12)
347  if (cover <= 0) return { bg: ahead, cover: null, liquid }
348
349  return { bg: lerp(ahead, liquid, cover), cover, liquid }
350}
351
352// Tide in 256 colours: the water in three layers, the surface on top, the middle, the deep at
353// the bottom, the lines between them wavy (where a cell holds no word, its two halves can be
354// of two layers: `▀`) and swaying while the PR moves; its front, a cell that ends partway along
355// it, lit in the crest's colour. Full and moving, a glint runs across: a slant of cells a layer
356// lighter.
357function tideStepAt(card: ArtCard, x: number, y: number, frame: number, rows: number, width: number, edge: number, phase: number, mid: Rgb): TideCell {
358  const { glass, surface, deep, crest } = card.paint.tones[card.tone]
359  const layers = [surface, mid, deep] as const
360  const wave = 0.5 * Math.sin(x * 0.42 + phase) + 0.5 * Math.sin(x * 0.17 - phase * 0.6 + 1)
361  // The layer at a height, `at` rows down: a word's cell by its middle, unswayed, so the colour
362  // behind a word stays put; a half cell swayed.
363  const levelAt = (at: number, sway: number) => {
364    const depth = rows <= 1 ? 0 : at / rows + sway
365
366    return depth < 1 / 3 ? 0 : depth < 2 / 3 ? 1 : 2
367  }
368  const glint = (level: number): Rgb => {
369    if (edge < width || !card.isMoving) return layers[level]!
370    const at = ((frame * 0.5 + card.seed * 3) % (width + 16)) - 8
371
372    return Math.abs(x - at + y * 1.5) < 0.75 ? (level === 0 ? crest : layers[level - 1]!) : layers[level]!
373  }
374  const cover = clamp01(edge - x)
375  if (cover <= 0) return { bg: glass, cover: null, liquid: crest }
376  if (cover < 1) {
377    // The front: a word's cell takes whichever it is most of, an empty one the crest's sliver.
378    return { bg: cover >= 0.5 ? glint(levelAt(y + 0.5, 0)) : glass, cover, liquid: crest }
379  }
380
381  return { bg: glint(levelAt(y + 0.5, 0)), cover: null, liquid: crest, halves: [glint(levelAt(y + 0.25, 0.08 * wave)), glint(levelAt(y + 0.75, 0.08 * wave))] }
382}
383
384// Aurora's background at a cell: curtains rippling across the sky, through the state's colours
385// from left to right, brighter toward the top and as far as the PR has come, drifting while it
386// moves. Kept below 60% of the colour, so the text colours read on it.
387function auroraAt(card: ArtCard, x: number, y: number, frame: number, rows: number, width: number): Rgb {
388  const { glass, surface, deep, crest } = card.paint.tones[card.tone]
389  const t = card.isMoving ? frame * 0.06 : 0
390  // Two layers of curtains, tall and slow: they bend a little from row to row, never break up.
391  const sway = Math.sin(y * 0.45 + x * 0.05 + t + card.seed) * 0.9
392  const curtain = 0.6 * (0.5 + 0.5 * Math.sin(x * 0.21 + sway + t * 0.7)) + 0.4 * (0.5 + 0.5 * Math.sin(x * 0.53 - sway * 0.6 - t * 0.4 + card.seed))
393  const hue = clamp01(x / Math.max(1, width - 1) + 0.15 * Math.sin(y * 0.9 + t * 0.5 + card.seed))
394  const edge = card.fill * width
395  const reach = x <= edge ? 1 : Math.max(0.25, 1 - (x - edge) / 8)
396  const light = (0.18 + 0.42 * curtain) * reach * (1 - 0.25 * (rows <= 1 ? 0 : y / (rows - 1)))
397
398  return lerp(glass, gradientAt([deep, crest, surface], hue), light)
399}
400
401// Where aurora's curtain ends in column `x` (256 colours), in rows from the card's top: about
402// three quarters of the way down, its hem rippling (moving while the PR does), shorter past how
403// far the PR has come.
404export function hemAt(card: Pick<ArtCard, 'fill' | 'seed' | 'isMoving'>, x: number, frame: number, rows: number, width: number): number {
405  const t = card.isMoving ? frame * 0.08 : 0
406  const ripple = 0.55 * Math.sin(x * 0.23 + t + card.seed) + 0.45 * Math.sin(x * 0.61 - t * 0.7 + card.seed * 2)
407  const edge = card.fill * width
408  const reach = x <= edge ? 1 : Math.max(0.2, 1 - (x - edge) / 10)
409
410  return rows * (0.72 + 0.2 * ripple) * reach
411}
412
413// Aurora in 256 colours, a cell: the curtain in its dim colour down to its hem, the sky below;
414// the hem's last half cell lit in the bright colour where the cell holds no word. The colours by
415// the cell's third of the card across (deep, crest, surface), the folds between them slanting
416// from row to row. A word's cell takes the curtain's or the sky's colour by its middle.
417function auroraCell(card: ArtCard, glyph: Glyph, cp: number, x: number, y: number, frame: number, rows: number, width: number, steps: ArtSteps): Cell {
418  const { glass, surface, deep, crest } = card.paint.tones[card.tone]
419  const fold = 2.5 * Math.sin(y * 0.9 + card.seed)
420  const stop = Math.min(2, Math.max(0, Math.floor(((x + fold) / Math.max(1, width)) * 3)))
421  const dim = steps.dim[stop]!
422  const bright = [deep, crest, surface][stop]!
423  const hem = hemAt(card, x, frame, rows, width)
424  if (glyph.role !== 'blank') {
425    const bg = y + 0.5 < hem ? dim : glass
426
427    return [cp, hex(fgOf(glyph.role, bg, card)), hex(bg)]
428  }
429  const isTopIn = y + 0.25 < hem
430  const isBottomIn = y + 0.75 < hem
431  // The bottom half the hem's: dim over bright.
432  if (isBottomIn && hem < y + 1.25) return [0x2584, hex(bright), hex(dim)]
433  if (isBottomIn) return [0x20, hex(dim), hex(dim)]
434  // The top half the hem's: bright over the sky.
435  if (isTopIn) return [0x2580, hex(bright), hex(glass)]
436
437  return [0x20, hex(glass), hex(glass)]
438}
439
440// One frame of a card, a row of cells per row: the art behind, the text over it, the spinner
441// on the frame's glyph.
442export function artGrid(card: ArtCard, frame: number): Cell[][] {
443  const rows = card.grid.length
444  const width = card.grid[0]?.length ?? 0
445  const badge = card.paint.tones[card.tone].badge
446  const spun = card.spin[(frame + card.seed) % card.spin.length]?.codePointAt(0)
447  const cpOf = (glyph: Glyph) => (glyph.role === 'spin' && card.isMoving && spun !== undefined ? spun : glyph.cp)
448
449  return card.grid.map((row, y) =>
450    row.map((glyph, x): Cell => {
451      if (glyph.role === 'badge') return [glyph.cp, hex(inkOn(badge, card.paint)), hex(badge)]
452      if (card.kind === 'aurora') {
453        const steps = card.paint.steps?.[card.tone]
454        if (steps !== undefined) return auroraCell(card, glyph, cpOf(glyph), x, y, frame, rows, width, steps)
455        const bg = auroraAt(card, x, y, frame, rows, width)
456
457        return [cpOf(glyph), hex(glyph.role === 'blank' ? bg : fgOf(glyph.role, bg, card)), hex(bg)]
458      }
459      const { bg, cover, liquid, halves } = tideAt(card, x, y, frame, rows, width)
460      if (glyph.role === 'blank') {
461        const eighths = cover === null ? 0 : Math.round(cover * 8)
462        // The front inside an empty cell: a partial block of liquid over the glass beyond it.
463        if (eighths > 0 && eighths < 8) return [EIGHTHS[eighths]!.codePointAt(0)!, hex(liquid), hex(tideAt(card, x + 1, y, frame, rows, width).bg)]
464        // Layered water (256 colours): a wavy line between two layers through an empty cell.
465        if (halves !== undefined) return halves[0] === halves[1] ? [0x20, hex(halves[1]), hex(halves[1])] : [0x2580, hex(halves[0]), hex(halves[1])]
466
467        return [0x20, hex(bg), hex(bg)]
468      }
469
470      return [cpOf(glyph), hex(fgOf(glyph.role, bg, card)), hex(bg)]
471    }),
472  )
473}
474
475// A frame's cells, encoded for the Raster (RasterProps) and its blits.
476export const artCells = (card: ArtCard, frame: number): string => encode(artGrid(card, frame).flat())
477
hooks/theme.ts 799 lines
1// The pane's looks: borders, backgrounds, colour and feel, as data. Each theme gives a card
2// frame, a pill, a header rule and a spinner, and per mode (the person's light or dark
3// terminal) what each tone paints. The render reads a Look; it never asks which theme it is.
4import type { BoxHoverProps, BoxProps, Color } from 'claude-code'
5import type { Tone } from '../types'
6import type { BarPaint } from './look'
7import { hex, x256 } from './look'
8
9export const THEMES = ['classic', 'solid', 'minimal', 'neon', 'retro', 'tide', 'aurora'] as const
10export type ThemeName = (typeof THEMES)[number]
11export type Mode = 'light' | 'dark'
12export const MODES: readonly Mode[] = ['light', 'dark']
13export const TONES: readonly Tone[] = ['success', 'error', 'warning', 'merged', 'subtle', 'suggestion']
14
15export type Rgb = readonly [number, number, number]
16// From, to: a run of cells fades from one to the other.
17export type Ramp = readonly [Rgb, Rgb]
18
19// What one tone paints in one mode.
20export type ToneLook = {
21  // Text accents: the pill, the headline, the number, the current step, the band's line.
22  ink: Color
23  // The card's border, where the card has one.
24  border: Color | null
25  // The card's background: hex, so a Raster on the card can paint the same behind its cells (a
26  // banner theme's 256-colour paint: the palette entry its art paints, `ansi256(n)`).
27  fill: Color | null
28  // The border while the pointer is on the card.
29  glow: Color | null
30}
31
32// The Raster paint (look.ts): CI bars by outcome, the light sweeping over pending checks, the
33// header rule's gradient stops and the spinner's pulse.
34export type RasterPaint = {
35  green: Ramp
36  red: Ramp
37  amber: Ramp
38  mauve: Ramp
39  shine: Rgb
40  rule: readonly Rgb[]
41  spinner: Ramp
42  // The empty part of the gh meter's bars.
43  track: Rgb
44  // Every colour one of the 256-colour palette's (a theme's ansi256 paint): a bar is painted in
45  // them alone.
46  isPalette?: true
47}
48
49// How a card is laid out. stack: a framed box of text rows, a CI bar and a stepper. banner: a
50// painted card (art.ts), the text drawn into its cells, its progress the art itself, and the
51// links and buttons on rows of their own under it.
52export type CardLayout = 'stack' | 'banner'
53// What a banner card's cells are painted with: a liquid that advances with the PR's progress
54// behind a wavy front, or soft curtains of light.
55export type ArtKind = 'tide' | 'aurora'
56
57// One tone's paint on a banner card.
58export type ArtTone = {
59  // The card where the art hasn't reached: tide's empty glass, aurora's sky.
60  glass: Rgb
61  // Tide: the liquid at its surface and deep down, and the light on its crest. Aurora: the
62  // curtains' colours, across the card.
63  surface: Rgb
64  deep: Rgb
65  crest: Rgb
66  // The state badge's chip.
67  badge: Rgb
68  // The tone's text accents on the art (each kept only where it reads, art.ts).
69  ink: Rgb
70}
71
72// A tone's extra paint where the terminal shows 256 colours: tide's middle layer of water, and
73// aurora's curtains dimmed (for `deep`, `crest` and `surface`, in that order).
74export type ArtSteps = { mid: Rgb; dim: readonly [Rgb, Rgb, Rgb] }
75
76export type ArtPaint = {
77  tones: Record<Tone, ArtTone>
78  // The two text colours, whichever reads better on a cell's background is drawn there.
79  light: Rgb
80  dark: Rgb
81  // Present: the art is painted for 256 colours (art.ts), in a few palette colours each tone
82  // has rather than gradients, which the terminal would round to blotches of other colours.
83  steps?: Record<Tone, ArtSteps>
84}
85
86export type Variant = {
87  tones: Record<Tone, ToneLook>
88  // The pill's text where the pill is filled with the tone.
89  pillText: Color
90  raster: RasterPaint
91  // A banner card's paint (null: the theme stacks its cards).
92  art: ArtPaint | null
93  // Behind a note drawn over the pane (the gh meter's explanation under the pointer).
94  panel: Color
95}
96
97// The accents a quiet theme leaves uncoloured.
98export type Role = 'number' | 'steps' | 'branch' | 'diff'
99
100export type Theme = {
101  name: ThemeName
102  // One line for the theme listing.
103  blurb: string
104  layout: CardLayout
105  // What a banner card is painted with (null for a stacked one).
106  art: ArtKind | null
107  card: {
108    // A terminal border style (single, double, round, bold, classic…), or none.
109    border: string | null
110    // Drawn dim, full strength under the pointer.
111    isDim: boolean
112    // Rows of padding above and below the card's text; a border stands for one row each.
113    padY: number
114    // Blank rows after each card.
115    gap: number
116    // A rule drawn between cards, by its glyph.
117    separator: string | null
118  }
119  // `open` and `close` go around the pill's text; filled, the tone is its background.
120  pill: { open: string; close: string; isFilled: boolean }
121  // The header rule's glyphs, repeated across, and the spinner's frames.
122  rule: string
123  spin: readonly string[]
124  muted: readonly Role[]
125  light: Variant
126  dark: Variant
127  // Where the terminal shows 256 colours (depthOf), the paint made of the palette's own
128  // colours; without one, the same paint (the terminal rounds it).
129  ansi256?: { light: Variant; dark: Variant }
130}
131
132const BRAILLE = [...'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏']
133
134// Behind a note drawn over the pane, by mode.
135const PANEL = { light: '#f3f4f8', dark: '#1c1f2b' } as const
136
137// Today's paint, Catppuccin-flavoured, a shade deeper so it still reads on a light terminal:
138// one for both modes.
139const CATPPUCCIN: RasterPaint = {
140  green: [[64, 160, 43], [166, 227, 161]],
141  red: [[210, 15, 57], [243, 139, 168]],
142  amber: [[223, 142, 29], [249, 226, 175]],
143  mauve: [[136, 57, 239], [203, 166, 247]],
144  shine: [255, 248, 220],
145  rule: [
146    [203, 166, 247],
147    [137, 180, 250],
148    [148, 226, 213],
149    [245, 194, 231],
150  ],
151  spinner: [[223, 142, 29], [249, 226, 175]],
152  track: [108, 112, 134],
153}
154
155// The person's own theme colours: they follow light, dark and daltonized by themselves.
156const KEYED: Record<Tone, ToneLook> = {
157  success: { ink: 'success', border: 'success', fill: null, glow: null },
158  error: { ink: 'error', border: 'error', fill: null, glow: null },
159  warning: { ink: 'warning', border: 'warning', fill: null, glow: null },
160  merged: { ink: 'merged', border: 'merged', fill: null, glow: null },
161  subtle: { ink: 'subtle', border: 'subtle', fill: null, glow: null },
162  suggestion: { ink: 'suggestion', border: 'suggestion', fill: null, glow: null },
163}
164
165const classic: Theme = {
166  name: 'classic',
167  blurb: 'round borders coloured by state, a filled pill',
168  layout: 'stack',
169  art: null,
170  card: { border: 'round', isDim: true, padY: 0, gap: 1, separator: null },
171  pill: { open: ' ', close: ' ', isFilled: true },
172  rule: '─',
173  spin: BRAILLE,
174  muted: [],
175  light: { tones: KEYED, pillText: 'inverseText', raster: CATPPUCCIN, art: null, panel: PANEL.light },
176  dark: { tones: KEYED, pillText: 'inverseText', raster: CATPPUCCIN, art: null, panel: PANEL.dark },
177}
178
179// A soft tint per state, the theme's own keys for the text on it. Neutral where nothing is
180// asked of the person.
181const tile = (fills: Record<'green' | 'red' | 'amber' | 'purple' | 'neutral', `#${string}`>): Record<Tone, ToneLook> => ({
182  success: { ink: 'success', border: null, fill: fills.green, glow: null },
183  error: { ink: 'error', border: null, fill: fills.red, glow: null },
184  warning: { ink: 'warning', border: null, fill: fills.amber, glow: null },
185  merged: { ink: 'merged', border: null, fill: fills.purple, glow: null },
186  subtle: { ink: 'subtle', border: null, fill: fills.neutral, glow: null },
187  suggestion: { ink: 'suggestion', border: null, fill: fills.neutral, glow: null },
188})
189
190const solid: Theme = {
191  name: 'solid',
192  blurb: 'no borders: each card a tile tinted by its state',
193  // A row of padding each side stands for the border's rows, so a card keeps its size.
194  layout: 'stack',
195  art: null,
196  card: { border: null, isDim: false, padY: 1, gap: 1, separator: null },
197  pill: { open: ' ', close: ' ', isFilled: true },
198  rule: '─',
199  spin: BRAILLE,
200  muted: [],
201  light: {
202    tones: tile({ green: '#e1f3e4', red: '#fae1e5', amber: '#faefd6', purple: '#ece3f9', neutral: '#eaecf1' }),
203    pillText: 'inverseText',
204    art: null,
205    panel: PANEL.light,
206    raster: CATPPUCCIN,
207  },
208  dark: {
209    tones: tile({ green: '#1d3524', red: '#3d1f26', amber: '#3a3020', purple: '#2e2442', neutral: '#272a33' }),
210    pillText: 'inverseText',
211    art: null,
212    panel: PANEL.dark,
213    raster: CATPPUCCIN,
214  },
215}
216
217// The same keys with no frame to colour.
218const BARE = Object.fromEntries(TONES.map(tone => [tone, { ...KEYED[tone], border: null }])) as Record<Tone, ToneLook>
219
220const minimal: Theme = {
221  name: 'minimal',
222  blurb: 'no boxes, a thin rule between PRs, colour on the pill and headline only',
223  layout: 'stack',
224  art: null,
225  card: { border: null, isDim: false, padY: 0, gap: 1, separator: '─' },
226  pill: { open: '', close: '', isFilled: false },
227  rule: '─',
228  spin: BRAILLE,
229  muted: ['number', 'steps', 'branch', 'diff'],
230  light: {
231    tones: BARE,
232    pillText: 'inverseText',
233    art: null,
234    panel: PANEL.light,
235    raster: {
236      green: [[78, 138, 88], [104, 158, 112]],
237      red: [[176, 70, 88], [196, 104, 118]],
238      amber: [[168, 120, 50], [190, 148, 86]],
239      mauve: [[124, 96, 176], [150, 126, 196]],
240      shine: [236, 236, 244],
241      rule: [[176, 179, 192], [176, 179, 192]],
242      spinner: [[120, 120, 140], [70, 70, 90]],
243      track: [214, 216, 224],
244    },
245  },
246  dark: {
247    tones: BARE,
248    pillText: 'inverseText',
249    art: null,
250    panel: PANEL.dark,
251    raster: {
252      green: [[86, 140, 96], [124, 172, 132]],
253      red: [[170, 80, 96], [204, 124, 136]],
254      amber: [[170, 140, 80], [204, 178, 122]],
255      mauve: [[130, 110, 170], [166, 146, 202]],
256      shine: [214, 214, 226],
257      rule: [[88, 91, 112], [88, 91, 112]],
258      spinner: [[140, 140, 160], [200, 200, 216]],
259      track: [58, 60, 74],
260    },
261  },
262}
263
264const vivid = (inks: Record<Tone, readonly [ink: `#${string}`, glow: `#${string}`]>): Record<Tone, ToneLook> =>
265  Object.fromEntries(TONES.map(tone => [tone, { ink: inks[tone][0], border: inks[tone][0], fill: null, glow: inks[tone][1] }])) as Record<Tone, ToneLook>
266
267const neon: Theme = {
268  name: 'neon',
269  blurb: 'bold borders in vivid colour that glow under the pointer, a bright gradient rule',
270  layout: 'stack',
271  art: null,
272  card: { border: 'bold', isDim: false, padY: 0, gap: 1, separator: null },
273  pill: { open: ' ', close: ' ', isFilled: true },
274  rule: '━',
275  spin: BRAILLE,
276  muted: [],
277  // Deeper on a light terminal, so the vivid colour still reads on white; the pill's text white.
278  light: {
279    tones: vivid({
280      success: ['#00a63e', '#00d452'],
281      error: ['#d6006f', '#ff2b93'],
282      warning: ['#c27a00', '#f09c00'],
283      merged: ['#8f00d6', '#b33bff'],
284      subtle: ['#5c5c7a', '#8080a8'],
285      suggestion: ['#0077d6', '#1f9bff'],
286    }),
287    pillText: '#ffffff',
288    art: null,
289    panel: PANEL.light,
290    raster: {
291      green: [[0, 150, 56], [0, 212, 82]],
292      red: [[214, 0, 111], [255, 43, 147]],
293      amber: [[194, 122, 0], [240, 156, 0]],
294      mauve: [[143, 0, 214], [179, 59, 255]],
295      shine: [255, 255, 255],
296      rule: [
297        [214, 0, 214],
298        [0, 140, 214],
299        [0, 166, 62],
300        [214, 130, 0],
301      ],
302      spinner: [[0, 119, 214], [196, 0, 196]],
303      track: [222, 222, 236],
304    },
305  },
306  // Full strength on a dark one; the pill's text near-black.
307  dark: {
308    tones: vivid({
309      success: ['#39ff14', '#c2ffb0'],
310      error: ['#ff2079', '#ffa3c9'],
311      warning: ['#ffd300', '#fff2a6'],
312      merged: ['#bc13fe', '#e6b0ff'],
313      subtle: ['#9a9ac0', '#dcdcf2'],
314      suggestion: ['#00f0ff', '#b0fcff'],
315    }),
316    pillText: '#0b0b16',
317    art: null,
318    panel: PANEL.dark,
319    raster: {
320      green: [[57, 255, 20], [176, 255, 150]],
321      red: [[255, 32, 121], [255, 140, 186]],
322      amber: [[255, 211, 0], [255, 242, 150]],
323      mauve: [[188, 19, 254], [228, 150, 255]],
324      shine: [255, 255, 255],
325      rule: [
326        [255, 0, 255],
327        [0, 255, 255],
328        [57, 255, 20],
329        [255, 211, 0],
330      ],
331      spinner: [[0, 240, 255], [255, 0, 255]],
332      track: [44, 44, 70],
333    },
334  },
335}
336
337// The terminal's own 16 colours, by their numbers (`ansi256(0)` to `ansi256(15)` are the
338// palette's), which the terminal fits to light or dark itself.
339const sixteen = (n: number): ToneLook => ({ ink: `ansi256(${n})`, border: `ansi256(${n})`, fill: null, glow: null })
340const SIXTEEN: Record<Tone, ToneLook> = {
341  success: sixteen(2),
342  error: sixteen(1),
343  warning: sixteen(3),
344  merged: sixteen(5),
345  subtle: sixteen(8),
346  suggestion: sixteen(6),
347}
348
349// Flat runs, as an old terminal would draw them: no fade from one end to the other.
350const flat = (rgb: Rgb): Ramp => [rgb, rgb]
351
352const retro: Theme = {
353  name: 'retro',
354  blurb: 'double borders, the 16 terminal colours, [bracketed] pills: an old TUI',
355  layout: 'stack',
356  art: null,
357  card: { border: 'double', isDim: true, padY: 0, gap: 1, separator: null },
358  pill: { open: '[', close: ']', isFilled: false },
359  rule: '═',
360  spin: [...'|/-\\'],
361  muted: [],
362  light: {
363    tones: SIXTEEN,
364    pillText: 'inverseText',
365    art: null,
366    panel: PANEL.light,
367    raster: {
368      green: flat([0, 140, 0]),
369      red: flat([180, 0, 0]),
370      amber: flat([160, 120, 0]),
371      mauve: flat([150, 0, 150]),
372      shine: [255, 255, 255],
373      rule: [[0, 128, 128], [0, 128, 128]],
374      spinner: flat([0, 128, 128]),
375      track: [192, 192, 192],
376    },
377  },
378  dark: {
379    tones: SIXTEEN,
380    pillText: 'inverseText',
381    art: null,
382    panel: PANEL.dark,
383    raster: {
384      green: flat([0, 205, 0]),
385      red: flat([205, 0, 0]),
386      amber: flat([205, 205, 0]),
387      mauve: flat([205, 0, 205]),
388      shine: [255, 255, 255],
389      rule: [[0, 205, 205], [0, 205, 205]],
390      spinner: flat([0, 205, 205]),
391      track: [96, 96, 96],
392    },
393  },
394}
395
396// ---- Banner themes: painted cards (art.ts) ------------------------------------------------
397
398export const hexOf = ([r, g, b]: Rgb): `#${string}` => `#${[r, g, b].map(n => n.toString(16).padStart(2, '0')).join('')}`
399
400// The text keys of a banner theme: each tone's accent as hex, its glass behind the card's rows of
401// links and buttons.
402const painted = (art: ArtPaint): Record<Tone, ToneLook> =>
403  Object.fromEntries(
404    TONES.map(tone => [tone, { ink: hexOf(art.tones[tone].ink), border: null, fill: hexOf(art.tones[tone].glass), glow: null }]),
405  ) as Record<Tone, ToneLook>
406
407// A night sea: the liquid deep and dark enough under light text, its crest lit.
408const TIDE_DARK: ArtPaint = {
409  light: [246, 249, 252],
410  dark: [8, 10, 14],
411  tones: {
412    success: { glass: [17, 29, 26], surface: [24, 100, 72], deep: [8, 58, 48], crest: [96, 214, 160], badge: [72, 214, 150], ink: [132, 240, 186] },
413    error: { glass: [33, 19, 23], surface: [146, 36, 62], deep: [84, 14, 36], crest: [244, 128, 150], badge: [255, 104, 132], ink: [255, 154, 172] },
414    warning: { glass: [33, 28, 17], surface: [126, 80, 14], deep: [84, 46, 8], crest: [240, 190, 96], badge: [255, 192, 72], ink: [255, 212, 124] },
415    merged: { glass: [26, 21, 40], surface: [92, 54, 172], deep: [48, 24, 106], crest: [186, 150, 255], badge: [178, 136, 255], ink: [204, 176, 255] },
416    subtle: { glass: [23, 26, 33], surface: [64, 72, 94], deep: [36, 42, 58], crest: [150, 162, 188], badge: [152, 164, 192], ink: [178, 188, 210] },
417    suggestion: { glass: [17, 27, 39], surface: [28, 88, 156], deep: [12, 48, 98], crest: [120, 190, 250], badge: [98, 178, 255], ink: [144, 204, 255] },
418  },
419}
420
421// A day sea: pale water deepening to colour, under dark text.
422const TIDE_LIGHT: ArtPaint = {
423  light: [255, 255, 255],
424  dark: [26, 29, 36],
425  tones: {
426    success: { glass: [236, 246, 240], surface: [160, 226, 192], deep: [92, 190, 146], crest: [226, 255, 240], badge: [22, 128, 82], ink: [10, 98, 60] },
427    error: { glass: [251, 237, 240], surface: [246, 180, 192], deep: [226, 120, 142], crest: [255, 232, 237], badge: [190, 30, 66], ink: [150, 20, 50] },
428    warning: { glass: [251, 245, 231], surface: [248, 212, 140], deep: [226, 166, 70], crest: [255, 243, 210], badge: [168, 98, 0], ink: [124, 74, 0] },
429    merged: { glass: [243, 238, 252], surface: [206, 186, 248], deep: [158, 126, 230], crest: [240, 232, 255], badge: [110, 56, 200], ink: [86, 36, 168] },
430    subtle: { glass: [239, 241, 246], surface: [206, 212, 224], deep: [160, 170, 190], crest: [247, 249, 253], badge: [84, 94, 116], ink: [64, 74, 94] },
431    suggestion: { glass: [235, 244, 252], surface: [170, 210, 248], deep: [104, 166, 230], crest: [228, 242, 255], badge: [20, 100, 190], ink: [8, 78, 160] },
432  },
433}
434
435// Ocean water for the gh meter and the header's wave.
436const tideRaster = (mode: Mode): RasterPaint =>
437  mode === 'dark'
438    ? {
439        green: [[24, 150, 104], [96, 224, 168]],
440        red: [[196, 44, 76], [255, 128, 150]],
441        amber: [[196, 128, 20], [255, 204, 110]],
442        mauve: [[110, 66, 200], [186, 150, 255]],
443        shine: [230, 248, 255],
444        rule: [[22, 70, 132], [28, 140, 168], [104, 214, 200], [28, 140, 168]],
445        spinner: [[96, 214, 200], [144, 204, 255]],
446        track: [40, 50, 66],
447      }
448    : {
449        green: [[26, 150, 98], [92, 200, 150]],
450        red: [[196, 36, 70], [232, 110, 134]],
451        amber: [[190, 120, 10], [232, 170, 70]],
452        mauve: [[110, 56, 200], [158, 126, 230]],
453        shine: [255, 255, 255],
454        rule: [[30, 96, 170], [26, 150, 170], [84, 190, 170], [26, 150, 170]],
455        spinner: [[20, 110, 190], [26, 150, 170]],
456        track: [214, 224, 234],
457      }
458
459const tide: Theme = {
460  name: 'tide',
461  blurb: 'each card fills like a glass as its PR moves on, a wave on the front; links on their own row',
462  layout: 'banner',
463  art: 'tide',
464  // The painted rows are the card's whole width: no frame, no padding.
465  card: { border: null, isDim: false, padY: 0, gap: 1, separator: null },
466  pill: { open: ' ', close: ' ', isFilled: true },
467  rule: '▁▂▃▄▅▄▃▂',
468  spin: BRAILLE,
469  muted: [],
470  light: { tones: painted(TIDE_LIGHT), pillText: '#ffffff', raster: tideRaster('light'), art: TIDE_LIGHT, panel: '#eef5fb' },
471  dark: { tones: painted(TIDE_DARK), pillText: '#0d1117', raster: tideRaster('dark'), art: TIDE_DARK, panel: '#111b27' },
472}
473
474// A polar night: curtains of colour over a deep sky, kept dim enough under light text.
475const AURORA_DARK: ArtPaint = {
476  light: [240, 244, 250],
477  dark: [10, 12, 20],
478  tones: {
479    success: { glass: [10, 18, 26], surface: [40, 150, 190], deep: [20, 120, 100], crest: [60, 200, 110], badge: [92, 226, 150], ink: [140, 244, 190] },
480    error: { glass: [22, 12, 24], surface: [220, 110, 50], deep: [150, 26, 96], crest: [226, 50, 90], badge: [255, 112, 140], ink: [255, 160, 178] },
481    warning: { glass: [22, 18, 14], surface: [210, 80, 110], deep: [176, 104, 16], crest: [226, 166, 36], badge: [255, 196, 80], ink: [255, 214, 130] },
482    merged: { glass: [16, 12, 30], surface: [226, 86, 176], deep: [80, 46, 196], crest: [156, 76, 228], badge: [190, 146, 255], ink: [210, 182, 255] },
483    subtle: { glass: [14, 16, 24], surface: [80, 96, 130], deep: [54, 64, 96], crest: [96, 110, 140], badge: [156, 168, 196], ink: [182, 192, 214] },
484    suggestion: { glass: [10, 14, 30], surface: [126, 86, 228], deep: [26, 84, 196], crest: [36, 166, 226], badge: [110, 186, 255], ink: [150, 208, 255] },
485  },
486}
487
488// Dawn: the same curtains in pastel over a pale sky.
489const AURORA_LIGHT: ArtPaint = {
490  light: [255, 255, 255],
491  dark: [24, 26, 36],
492  tones: {
493    success: { glass: [244, 248, 250], surface: [160, 214, 244], deep: [140, 222, 200], crest: [172, 236, 168], badge: [20, 126, 86], ink: [10, 96, 62] },
494    error: { glass: [251, 244, 247], surface: [252, 196, 150], deep: [240, 160, 200], crest: [250, 160, 176], badge: [186, 28, 72], ink: [148, 20, 54] },
495    warning: { glass: [251, 248, 240], surface: [248, 174, 190], deep: [248, 206, 130], crest: [252, 226, 140], badge: [166, 96, 0], ink: [122, 72, 0] },
496    merged: { glass: [247, 244, 252], surface: [246, 176, 222], deep: [180, 166, 246], crest: [212, 170, 248], badge: [108, 54, 198], ink: [84, 34, 166] },
497    subtle: { glass: [244, 245, 249], surface: [204, 212, 228], deep: [192, 198, 216], crest: [214, 220, 232], badge: [84, 94, 116], ink: [64, 74, 94] },
498    suggestion: { glass: [243, 246, 253], surface: [206, 186, 248], deep: [160, 196, 246], crest: [158, 226, 246], badge: [20, 100, 190], ink: [8, 78, 160] },
499  },
500}
501
502const auroraRaster = (mode: Mode): RasterPaint =>
503  mode === 'dark'
504    ? {
505        green: [[20, 140, 120], [80, 226, 150]],
506        red: [[176, 30, 100], [250, 110, 120]],
507        amber: [[200, 120, 20], [250, 200, 90]],
508        mauve: [[90, 56, 210], [220, 110, 200]],
509        shine: [240, 250, 255],
510        rule: [[40, 200, 120], [36, 166, 226], [126, 86, 228], [226, 86, 176]],
511        spinner: [[60, 200, 140], [156, 76, 228]],
512        track: [36, 40, 58],
513      }
514    : {
515        green: [[20, 140, 110], [80, 196, 150]],
516        red: [[186, 28, 80], [236, 110, 140]],
517        amber: [[186, 112, 0], [232, 172, 60]],
518        mauve: [[108, 54, 198], [200, 100, 190]],
519        shine: [255, 255, 255],
520        rule: [[40, 170, 110], [30, 140, 200], [110, 80, 210], [200, 70, 160]],
521        spinner: [[30, 140, 200], [110, 80, 210]],
522        track: [222, 224, 236],
523      }
524
525const aurora: Theme = {
526  name: 'aurora',
527  blurb: 'each card a sky of soft northern lights in its state, brighter as its PR moves on',
528  layout: 'banner',
529  art: 'aurora',
530  card: { border: null, isDim: false, padY: 0, gap: 1, separator: null },
531  pill: { open: ' ', close: ' ', isFilled: true },
532  rule: '━',
533  spin: BRAILLE,
534  muted: [],
535  light: { tones: painted(AURORA_LIGHT), pillText: '#ffffff', raster: auroraRaster('light'), art: AURORA_LIGHT, panel: '#f5f3fb' },
536  dark: { tones: painted(AURORA_DARK), pillText: '#0a0c14', raster: auroraRaster('dark'), art: AURORA_DARK, panel: '#141426' },
537}
538
539// ---- Banner themes in 256 colours ---------------------------------------------------------
540
541// Inside tmux (unless CLAUDE_CODE_TMUX_TRUECOLOR is set), in Apple's Terminal and wherever the
542// terminal doesn't say it takes 24-bit colour, Claude Code paints with the 256-colour palette,
543// each colour rounded to its nearest there. The palette's darks are few and far apart, so a
544// gradient comes out as blotches of other colours (a dark teal goes grey). These paints are
545// made of palette colours (x256), a few steps a tone, so each step stays what it was picked as.
546
547// A tone's palette colours: the glass; tide's water at its surface, in the middle and deep down,
548// or aurora's curtains bright (deep, crest, surface) and `dim`; the crest; the badge; the accent.
549type Tone256 = { glass: number; surface: number; mid: number; deep: number; crest: number; badge: number; ink: number; dim: readonly [number, number, number] }
550type Paint256 = { light: number; dark: number; pillText: number; panel: number; tones: Record<Tone, Tone256> }
551
552const byTone = <T>(make: (tone: Tone) => T): Record<Tone, T> => Object.fromEntries(TONES.map(tone => [tone, make(tone)])) as Record<Tone, T>
553
554// A text colour Claude Code paints as that very palette colour.
555const ansi = (n: number): Color => `ansi256(${n})`
556
557const art256 = (p: Paint256): ArtPaint => ({
558  light: x256(p.light),
559  dark: x256(p.dark),
560  tones: byTone(tone => {
561    const t = p.tones[tone]
562
563    return { glass: x256(t.glass), surface: x256(t.surface), deep: x256(t.deep), crest: x256(t.crest), badge: x256(t.badge), ink: x256(t.ink) }
564  }),
565  steps: byTone(tone => ({ mid: x256(p.tones[tone].mid), dim: [x256(p.tones[tone].dim[0]), x256(p.tones[tone].dim[1]), x256(p.tones[tone].dim[2])] })),
566})
567
568const variant256 = (p: Paint256, raster: RasterPaint): Variant => ({
569  tones: byTone(tone => ({ ink: ansi(p.tones[tone].ink), border: null, fill: ansi(p.tones[tone].glass), glow: null })),
570  pillText: ansi(p.pillText),
571  raster,
572  art: art256(p),
573  panel: ansi(p.panel),
574})
575
576// The gh meter, CI bars and spinner in single palette colours: a ramp between two would be
577// rounded cell by cell into colours of other hues.
578const raster256 = (truecolour: RasterPaint, c: { green: number; red: number; amber: number; mauve: number; shine: number; spin: readonly [number, number]; track: number }): RasterPaint => ({
579  green: [x256(c.green), x256(c.green)],
580  red: [x256(c.red), x256(c.red)],
581  amber: [x256(c.amber), x256(c.amber)],
582  mauve: [x256(c.mauve), x256(c.mauve)],
583  shine: x256(c.shine),
584  // The header's wave keeps its gradient: one row of thin glyphs reads as a gradient still.
585  rule: truecolour.rule,
586  spinner: [x256(c.spin[0]), x256(c.spin[1])],
587  track: x256(c.track),
588  isPalette: true,
589})
590
591const TIDE_DARK_256: Paint256 = {
592  light: 231,
593  dark: 233,
594  pillText: 233,
595  panel: 234,
596  tones: {
597    success: { glass: 233, surface: 29, mid: 23, deep: 17, crest: 79, badge: 78, ink: 121, dim: [23, 23, 23] },
598    error: { glass: 233, surface: 125, mid: 89, deep: 52, crest: 211, badge: 204, ink: 217, dim: [89, 89, 89] },
599    warning: { glass: 233, surface: 136, mid: 94, deep: 52, crest: 222, badge: 214, ink: 222, dim: [94, 94, 94] },
600    merged: { glass: 233, surface: 97, mid: 55, deep: 54, crest: 183, badge: 141, ink: 183, dim: [55, 55, 55] },
601    subtle: { glass: 233, surface: 60, mid: 238, deep: 236, crest: 146, badge: 146, ink: 189, dim: [238, 238, 238] },
602    suggestion: { glass: 233, surface: 25, mid: 24, deep: 17, crest: 117, badge: 75, ink: 117, dim: [24, 24, 24] },
603  },
604}
605
606const TIDE_LIGHT_256: Paint256 = {
607  light: 231,
608  dark: 235,
609  pillText: 231,
610  panel: 255,
611  tones: {
612    success: { glass: 255, surface: 158, mid: 115, deep: 79, crest: 195, badge: 29, ink: 22, dim: [115, 115, 115] },
613    error: { glass: 255, surface: 224, mid: 217, deep: 211, crest: 231, badge: 161, ink: 88, dim: [217, 217, 217] },
614    warning: { glass: 255, surface: 223, mid: 222, deep: 179, crest: 230, badge: 130, ink: 94, dim: [222, 222, 222] },
615    merged: { glass: 255, surface: 189, mid: 183, deep: 141, crest: 231, badge: 55, ink: 54, dim: [183, 183, 183] },
616    subtle: { glass: 255, surface: 252, mid: 250, deep: 247, crest: 231, badge: 240, ink: 238, dim: [250, 250, 250] },
617    suggestion: { glass: 255, surface: 153, mid: 117, deep: 75, crest: 195, badge: 25, ink: 18, dim: [117, 117, 117] },
618  },
619}
620
621const AURORA_DARK_256: Paint256 = {
622  light: 231,
623  dark: 233,
624  pillText: 233,
625  panel: 234,
626  tones: {
627    success: { glass: 233, deep: 37, crest: 35, surface: 39, mid: 23, badge: 78, ink: 121, dim: [23, 22, 24] },
628    error: { glass: 233, deep: 162, crest: 161, surface: 166, mid: 89, badge: 204, ink: 217, dim: [53, 52, 88] },
629    warning: { glass: 233, deep: 172, crest: 178, surface: 168, mid: 94, badge: 214, ink: 222, dim: [94, 94, 95] },
630    merged: { glass: 233, deep: 99, crest: 93, surface: 163, mid: 55, badge: 141, ink: 183, dim: [54, 55, 90] },
631    subtle: { glass: 233, deep: 103, crest: 109, surface: 67, mid: 238, badge: 146, ink: 189, dim: [237, 238, 60] },
632    suggestion: { glass: 233, deep: 33, crest: 39, surface: 99, mid: 24, badge: 75, ink: 117, dim: [17, 18, 54] },
633  },
634}
635
636const AURORA_LIGHT_256: Paint256 = {
637  light: 231,
638  dark: 235,
639  pillText: 231,
640  panel: 255,
641  tones: {
642    success: { glass: 255, deep: 122, crest: 157, surface: 153, mid: 194, badge: 29, ink: 22, dim: [194, 194, 195] },
643    error: { glass: 255, deep: 217, crest: 218, surface: 223, mid: 224, badge: 161, ink: 88, dim: [224, 225, 230] },
644    warning: { glass: 255, deep: 222, crest: 223, surface: 218, mid: 230, badge: 130, ink: 94, dim: [230, 230, 225] },
645    merged: { glass: 255, deep: 183, crest: 219, surface: 147, mid: 189, badge: 55, ink: 54, dim: [189, 225, 189] },
646    subtle: { glass: 255, deep: 251, crest: 252, surface: 250, mid: 254, badge: 240, ink: 238, dim: [254, 254, 254] },
647    suggestion: { glass: 255, deep: 153, crest: 159, surface: 183, mid: 195, badge: 25, ink: 18, dim: [195, 195, 189] },
648  },
649}
650
651// Set here, under the palettes they are made of.
652tide.ansi256 = {
653  dark: variant256(TIDE_DARK_256, raster256(tideRaster('dark'), { green: 42, red: 204, amber: 214, mauve: 141, shine: 195, spin: [80, 117], track: 238 })),
654  light: variant256(TIDE_LIGHT_256, raster256(tideRaster('light'), { green: 35, red: 161, amber: 172, mauve: 98, shine: 231, spin: [25, 31], track: 252 })),
655}
656aurora.ansi256 = {
657  dark: variant256(AURORA_DARK_256, raster256(auroraRaster('dark'), { green: 42, red: 204, amber: 214, mauve: 170, shine: 195, spin: [43, 135], track: 237 })),
658  light: variant256(AURORA_LIGHT_256, raster256(auroraRaster('light'), { green: 35, red: 161, amber: 172, mauve: 97, shine: 231, spin: [31, 61], track: 252 })),
659}
660
661export const THEME: Record<ThemeName, Theme> = { classic, solid, minimal, neon, retro, tide, aurora }
662
663// ---- How many colours the terminal is painted with ---------------------------------------
664
665// truecolor: the 24-bit colours as given. ansi256: rounded to the xterm palette's 256.
666export type Depth = 'truecolor' | 'ansi256'
667
668// What Claude Code itself decides from its environment (2.1.x): 24-bit where COLORTERM says
669// so or the terminal is one known to take it, cut to 256 inside tmux unless
670// CLAUDE_CODE_TMUX_TRUECOLOR is set; 256 wherever it is unsure, the paint that reads anywhere.
671export type ColourEnv = { TMUX?: string; CLAUDE_CODE_TMUX_TRUECOLOR?: string; COLORTERM?: string; TERM?: string; TERM_PROGRAM?: string }
672const TRUECOLOR_TERMS = new Set(['alacritty', 'contour', 'foot', 'ghostty', 'rio', 'wezterm', 'xterm-ghostty', 'xterm-kitty'])
673const TRUECOLOR_PROGRAMS = new Set(['iTerm.app', 'vscode', 'WezTerm', 'ghostty'])
674const isSet = (value: string | undefined) => value !== undefined && value !== ''
675
676export function depthOf(env: ColourEnv): Depth {
677  if (isSet(env.TMUX) && !isSet(env.CLAUDE_CODE_TMUX_TRUECOLOR)) return 'ansi256'
678  const colorterm = (env.COLORTERM ?? '').toLowerCase()
679  const isTrue = colorterm === 'truecolor' || colorterm === '24bit' || TRUECOLOR_TERMS.has(env.TERM ?? '') || TRUECOLOR_PROGRAMS.has(env.TERM_PROGRAM ?? '')
680
681  return isTrue ? 'truecolor' : 'ansi256'
682}
683
684// A theme by its name, in any case; null for a name no theme has.
685export function themeOf(value: unknown): ThemeName | null {
686  if (typeof value !== 'string') return null
687  const name = value.trim().toLowerCase()
688
689  return (THEMES as readonly string[]).includes(name) ? (name as ThemeName) : null
690}
691
692// The `theme` option: a theme's name, else the classic look.
693export const optionTheme = (value: unknown): ThemeName => themeOf(value) ?? 'classic'
694
695// Light or dark from Claude Code's own `theme` row (light, light-daltonized, dark-ansi…); null
696// where it doesn't say (auto, a custom theme).
697export function modeOf(value: unknown): Mode | null {
698  if (typeof value !== 'string') return null
699  const name = value.trim().toLowerCase()
700
701  return name.startsWith('light') ? 'light' : name.startsWith('dark') ? 'dark' : null
702}
703
704// Light or dark from the terminal's COLORFGBG ("15;0": light text on black), where it sets one:
705// the background is its last number, 7 and 9 to 15 light.
706export function modeOfColours(value: unknown): Mode | null {
707  if (typeof value !== 'string') return null
708  const bg = value.trim().split(';').at(-1) ?? ''
709  if (!/^\d{1,2}$/.test(bg)) return null
710  const n = Number(bg)
711
712  return n === 7 || (n >= 9 && n <= 15) ? 'light' : 'dark'
713}
714
715export type Look = { theme: Theme; variant: Variant }
716
717// A theme's look in a mode, in the terminal's colours: its 256-colour paint where it has one.
718export const lookOf = (name: ThemeName, mode: Mode, depth: Depth = 'truecolor'): Look => {
719  const theme = THEME[name]
720
721  return { theme, variant: depth === 'ansi256' && theme.ansi256 !== undefined ? theme.ansi256[mode] : theme[mode] }
722}
723
724// A text accent's colour; undefined where the theme leaves that accent plain.
725export function inkOf(look: Look, tone: Tone, role?: Role): Color | undefined {
726  if (role !== undefined && look.theme.muted.includes(role)) return undefined
727
728  return look.variant.tones[tone].ink
729}
730
731// A card's frame. Without a border, padding stands for it, so a card keeps its width (and,
732// with `padY`, its height) whichever theme draws it: the text always has width - 4.
733export function cardBox(look: Look, tone: Tone): BoxProps {
734  const { card } = look.theme
735  const paint = look.variant.tones[tone]
736  const hover: BoxHoverProps = {}
737  const box: BoxProps = {}
738  if (card.border !== null) {
739    box.borderStyle = card.border
740    if (paint.border !== null) box.borderColor = paint.border
741    if (card.isDim) {
742      box.borderDimColor = true
743      hover.borderDimColor = false
744    }
745    if (paint.glow !== null) hover.borderColor = paint.glow
746  }
747  if (paint.fill !== null) box.backgroundColor = paint.fill
748  if (Object.keys(hover).length > 0) box.hover = hover
749  box.paddingX = card.border === null ? 2 : 1
750  if (card.padY > 0) box.paddingY = card.padY
751  box.marginBottom = card.gap
752
753  return box
754}
755
756// The pill: its text, and the Text props it is drawn with.
757export function pillOf(look: Look, tone: Tone, pill: string) {
758  const { open, close, isFilled } = look.theme.pill
759  const ink = look.variant.tones[tone].ink
760
761  return {
762    open,
763    close,
764    text: pill,
765    props: isFilled ? { backgroundColor: ink, color: look.variant.pillText, bold: true } : { color: ink, bold: true },
766  }
767}
768
769// What a Raster on a card paints behind its cells: the card's fill (hex, or a palette entry
770// `ansi256(n)`), as 0xRRGGBB, or null for the terminal's own background.
771export function rasterBg(look: Look, tone: Tone): number | null {
772  const fill = look.variant.tones[tone].fill
773  if (fill === null) return null
774  if (/^#[0-9a-f]{6}$/i.test(fill)) return parseInt(fill.slice(1), 16)
775  const n = /^ansi256\((\d+)\)$/.exec(fill)?.[1]
776
777  return n === undefined ? null : hex(x256(Number(n)))
778}
779
780// A card's CI bar: the theme's ramps over the card's fill.
781export function barPaint(look: Look, tone: Tone): BarPaint {
782  const { green, red, amber, shine } = look.variant.raster
783
784  return { green, red, amber, shine, bg: rasterBg(look, tone) }
785}
786
787// `/pr-watch theme`: every theme in a line, the current one marked.
788export function themeListing(current: ThemeName): string {
789  const width = Math.max(...THEMES.map(name => name.length))
790
791  return [
792    'pr-watch themes:',
793    ...THEMES.map(name => `${name === current ? '●' : '○'} ${name.padEnd(width)}  ${THEME[name].blurb}${name === current ? ' (current)' : ''}`),
794    '/pr-watch theme <name> switches.',
795  ].join('\n')
796}
797
798export const unknownTheme = (name: string) => `No theme "${name}". Themes: ${THEMES.join(', ')}.`
799
hooks/pr.ts 687 lines
1import type { Busy, Checks, MergeMethod, Mergeable, Reviews, Stage, Tone, TrackedPr } from '../types'
2import { reviewsOf, toAddress, unresolved } from './review'
3import type { ReviewFacts } from './review'
4
5const PR_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g
6
7export type PrRef = { url: string; repo: string; number: number }
8
9export function findPrUrls(text: string): PrRef[] {
10  const found = new Map<string, PrRef>()
11  for (const [, repo = '', num] of text.matchAll(PR_URL)) {
12    const number = Number(num)
13    const url = `https://github.com/${repo}/pull/${number}`
14    found.set(url, { url, repo, number })
15  }
16
17  return [...found.values()]
18}
19
20// Per `gh pr` subcommand, the flags that take no value (gh 2.10x `--help`), so the word after
21// one can be the PR. Any other flag is taken to carry a value (`--interval 20`, `--jq .state`,
22// `gh pr edit -m 3`): a PR it hides is missed, never made up. One letter means different things
23// across subcommands (`-c` is bare on view and review but takes the comment on close), hence per sub.
24const BARE_FLAGS: Record<string, ReadonlySet<string>> = Object.fromEntries(
25  Object.entries({
26    view: ['-c', '--comments', '-w', '--web'],
27    diff: ['--allow-escape-sequences', '--name-only', '--patch', '-w', '--web'],
28    checks: ['--fail-fast', '--required', '--watch', '-w', '--web'],
29    merge: ['--admin', '--auto', '-d', '--delete-branch', '--disable-auto', '-m', '--merge', '-r', '--rebase', '-s', '--squash'],
30    ready: ['--undo'],
31    edit: ['--remove-milestone'],
32    comment: ['--create-if-none', '--delete-last', '--edit-last', '-e', '--editor', '-w', '--web', '--yes'],
33    review: ['-a', '--approve', '-c', '--comment', '-r', '--request-changes'],
34    close: ['-d', '--delete-branch'],
35    reopen: [],
36    checkout: ['--detach', '-f', '--force', '--recurse-submodules'],
37    'update-branch': ['--rebase'],
38  }).map(([sub, flags]) => [sub, new Set(['--help', ...flags])]),
39)
40const NO_FLAGS: ReadonlySet<string> = new Set(['--help'])
41
42// Whether a flag word swallows the next word as its value. `-sd` is `-s -d`; in `-si20` the
43// value is attached.
44function takesNext(word: string, bare: ReadonlySet<string>): boolean {
45  if (word.startsWith('--')) return !word.includes('=') && !bare.has(word)
46  const letters = word.slice(1)
47  const firstValued = [...letters].findIndex(letter => !bare.has(`-${letter}`))
48
49  return firstValued === letters.length - 1
50}
51
52// A redirection word (`2>&1`, `>out`, `&>log`, `<in`); a bare operator (`>`, `2>`) owns the next word.
53const REDIRECT = /^(?:\d*|&)[<>]/
54const isBareRedirect = (word: string) => /^(?:\d*|&)[<>]+&?$/.test(word)
55
56// The simple commands of a line (`a && b; c | d`, `$(b)`, `(cd x && b)`), as words. A `&` inside
57// a redirection (`2>&1`, `&>log`) does not end a command; a `\`-newline continues it.
58const commandsOf = (code: string) =>
59  code
60    .replace(/\\\n/g, ' ')
61    .split(/\|\||&&|[;|\n()`]|(?<![<>])&(?!>)/)
62    .map(part => part.trim().split(/\s+/).filter(Boolean))
63    .filter(words => words.length > 0)
64
65// Each `gh pr <sub>` of the shell code, with the words after the subcommand.
66export function ghPrCommands(code: string): { sub: string; args: string[] }[] {
67  return commandsOf(code).flatMap(words => {
68    const at = words.findIndex((word, i) => /(^|\/)gh$/.test(word) && words[i + 1] === 'pr')
69    const sub = at < 0 ? undefined : words[at + 2]
70
71    return sub === undefined ? [] : [{ sub, args: words.slice(at + 3) }]
72  })
73}
74
75// `-R owner/repo`, or `-R github.com/owner/repo`; another host's PR has no github.com link.
76const repoOf = (value: string | undefined) => value?.match(/^(?:github\.com\/)?([\w.-]+\/[\w.-]+)$/)?.[1] ?? null
77
78// `gh pr view 12 -R owner/repo` style references that carry no URL: each `gh pr <sub>` of the
79// line with its own number and its own -R, never another command's (`gh pr list -R a/b; gh pr
80// view 7 -R c/d` is c/d#7), and never a flag's value or a redirection (`--interval 20`, `2>&1`).
81export function ghPrRefs(code: string, subs: (sub: string) => boolean = () => true): PrRef[] {
82  const refs: PrRef[] = []
83  for (const { sub, args } of ghPrCommands(code)) {
84    if (!subs(sub)) continue
85    const bare = BARE_FLAGS[sub] ?? NO_FLAGS
86    let number: number | null = null
87    let repo: string | null = null
88    let isPositionalSeen = false
89    let isFlagsDone = false
90    for (let i = 0; i < args.length; i++) {
91      const word = args[i] ?? ''
92      if (REDIRECT.test(word)) {
93        if (isBareRedirect(word)) i++
94        continue
95      }
96      if (!isFlagsDone && word === '--') {
97        isFlagsDone = true
98        continue
99      }
100      const flag = isFlagsDone ? null : word.match(/^(?:-R|--repo)(?:=(.*))?$/)
101      if (flag != null) {
102        repo = repoOf(flag[1] ?? args[++i])
103        continue
104      }
105      if (!isFlagsDone && word.startsWith('-') && word !== '-') {
106        if (takesNext(word, bare)) i++
107        continue
108      }
109      if (isPositionalSeen) continue
110      isPositionalSeen = true
111      const n = word.match(/^#?(\d+)$/)
112      if (n !== null) number = Number(n[1])
113    }
114    if (number !== null && repo !== null) refs.push({ url: `https://github.com/${repo}/pull/${number}`, repo, number })
115  }
116
117  return refs
118}
119
120export const refFromGhCommand = (command: string): PrRef | null => ghPrRefs(command)[0] ?? null
121
122const toolName = (tool: string) => tool.replace(/^mcp__[^_]+(?:_[^_]+)*?__/, '')
123
124// A command's shell code: heredoc bodies and quoted strings blanked, so a `gh pr create` in a
125// PR body or a commit message doesn't count, while `GH_TOKEN=$(…) gh pr create` and
126// `git -c k="…" push` do.
127export function shellCode(command: string): string {
128  return command
129    .replace(/<<-?\s*(['"]?)(\w+)\1([^\n]*)\n[\s\S]*?\n[ \t]*\2[ \t]*(?=\n|$)/g, (_m, _q, _tag, rest: string) => ` ${rest}`)
130    .replace(/'[^']*'|"(?:\\[\s\S]|[^"\\])*"/g, '""')
131}
132
133// `gh pr` subcommands that act on a PR. `checks` counts: following a PR's CI is shepherding it.
134const ACTS = new Set(['create', 'merge', 'ready', 'edit', 'comment', 'review', 'close', 'reopen', 'checkout', 'update-branch', 'checks'])
135// Single-PR read subcommands gh resolves to the current branch's PR when given no number.
136const READS_ONE = new Set(['view', 'diff'])
137const GIT_PUSH = /\bgit\b[^;&|\n]*?\spush\b/
138const GH_API_WRITE = /\bgh\s+api\b[^;&|\n]*?(?:(?:-X|--method)[\s=]*(?:POST|PATCH|PUT|DELETE)\b|\s(?:-f|-F|--field|--raw-field|--input)\s)/i
139const API_PULL = /\brepos\/([\w.-]+\/[\w.-]+)\/pulls\/(\d+)/g
140
141export type Touched = {
142  // PRs Claude acted on (opened, pushed to, commented, reviewed, merged, followed CI): watched.
143  acted: PrRef[]
144  // PRs Claude only read: offered, if they look like the person's own work.
145  read: PrRef[]
146  // The command named no PR (`git push`, `gh pr checks`), so gh must say which one it meant.
147  resolve: 'acted' | 'read' | null
148}
149
150// GitHub MCP tools that change a PR start with one of these (`merge_pull_request`,
151// `request_copilot_review`) or end in `_write`; `get_`, `list_`, `search_`, `_read` only read.
152const WRITE_VERBS = new Set(['create', 'update', 'merge', 'add', 'submit', 'request', 'push', 'enable', 'resolve', 'close', 'reopen', 'mark', 'dismiss'])
153
154const NONE: Touched = { acted: [], read: [], resolve: null }
155
156const uniq = (refs: PrRef[]) => [...new Map(refs.map(ref => [ref.url, ref])).values()]
157
158// A changelog full of links is not "dealing with" those PRs.
159const capped = (refs: PrRef[]) => (refs.length > 3 ? refs.slice(0, 1) : refs)
160
161export function touched(tool: string, input: Record<string, unknown>, output: string): Touched {
162  if (tool === 'Bash') return touchedByCommand(typeof input.command === 'string' ? input.command : '', output)
163  const name = toolName(tool)
164  const isPrTool = /pull|(^|_)prs?(_|$)/i.test(name)
165  if (!isPrTool) return { ...NONE, read: capped(findPrUrls(JSON.stringify(input))) }
166
167  const refs = findPrUrls(JSON.stringify(input))
168  const repo = [input.owner, input.repo].every(v => typeof v === 'string') ? `${input.owner}/${input.repo}` : null
169  const num = Number(input.pull_number ?? input.pullNumber ?? input.number ?? NaN)
170  if (repo !== null && Number.isInteger(num) && num > 0) refs.push({ url: `https://github.com/${repo}/pull/${num}`, repo, number: num })
171  const words = name.toLowerCase().split(/[_-]/)
172  const isWrite = WRITE_VERBS.has(words[0] ?? '') || words.includes('write')
173  if (!isWrite) {
174    return { ...NONE, read: capped(uniq([...refs, ...findPrUrls(output)])) }
175  }
176  // A new PR's own link comes first in the reply; its body may quote others.
177  const made = refs.length === 0 ? findPrUrls(output).slice(0, 1) : []
178
179  return { ...NONE, acted: uniq([...refs, ...made]) }
180}
181
182function touchedByCommand(command: string, output: string): Touched {
183  const code = shellCode(command)
184  const subs = ghPrCommands(code).map(c => c.sub)
185  const apiRefs = [...code.matchAll(API_PULL)].map(([, repo = '', n]) => ({ url: `https://github.com/${repo}/pull/${Number(n)}`, repo, number: Number(n) }))
186  // `gh pr checks 12 -R o/r`; not `gh pr list --limit 30 -R o/r`.
187  const isOneSub = (sub: string) => sub !== 'create' && (ACTS.has(sub) || READS_ONE.has(sub))
188  const isOnePr = subs.some(isOneSub)
189  const fromFlags = ghPrRefs(code, isOneSub)
190  const named = uniq([...findPrUrls(code), ...apiRefs, ...fromFlags])
191  const isPush = GIT_PUSH.test(code)
192  if (subs.some(sub => ACTS.has(sub)) || isPush || GH_API_WRITE.test(code)) {
193    // `gh pr create` prints the new PR; `gh pr comment` the comment's link on its PR.
194    const acted = uniq([...named, ...findPrUrls(output)])
195    const resolve = acted.length === 0 && (isPush || isOnePr) ? 'acted' : null
196
197    return { acted, read: [], resolve }
198  }
199  if (!/\bgh\s/.test(code)) return NONE
200  const read = capped(uniq([...named, ...findPrUrls(output)]))
201
202  return { acted: [], read, resolve: read.length === 0 && subs.some(sub => READS_ONE.has(sub)) ? 'read' : null }
203}
204
205// The directory a `cd dir && gh pr ...` command ran in, if it says.
206export function cwdOf(command: string): string | undefined {
207  return command.match(/^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*&&/)?.[1]?.replace(/^["']|["']$/g, '')
208}
209
210export type CheckItem = {
211  __typename?: string
212  name?: string
213  context?: string
214  status?: string
215  conclusion?: string
216  state?: string
217  workflow?: string
218  startedAt?: string | null
219  createdAt?: string | null
220  // Asked for only when a failure is handed to Claude (fix.ts), not by the poller. A GitHub
221  // Actions check run's databaseId is its job's id.
222  databaseId?: number | null
223  detailsUrl?: string | null
224  title?: string | null
225  summary?: string | null
226  targetUrl?: string | null
227  description?: string | null
228}
229
230export const isStatusContext = (item: CheckItem) => item.__typename === 'StatusContext' || item.state !== undefined
231
232// GitHub keeps every run of a check on the head commit: each pull_request event (a label,
233// an edit, a re-run) starts another, and the rollup lists them all. The PR page shows the
234// latest of each, so fold to that, or a failure that a later run fixed stays red.
235export function latestRuns(items: readonly CheckItem[]): CheckItem[] {
236  const latest = new Map<string, { item: CheckItem; at: number; order: number }>()
237  items.forEach((item, order) => {
238    const isContext = isStatusContext(item)
239    const key = isContext ? `status:${item.context ?? ''}` : `run:${item.workflow ?? ''}/${item.name ?? ''}`
240    // A run not started yet (queued, waiting) is the newest of its check.
241    const stamp = isContext ? item.createdAt : item.startedAt
242    const at = stamp == null ? (isContext ? 0 : Number.POSITIVE_INFINITY) : Date.parse(stamp) || 0
243    const held = latest.get(key)
244    if (held === undefined || at > held.at || (at === held.at && order > held.order)) latest.set(key, { item, at, order })
245  })
246
247  return [...latest.values()].sort((a, b) => a.order - b.order).map(entry => entry.item)
248}
249
250const PASSED = new Set(['SUCCESS', 'NEUTRAL', 'SKIPPED'])
251
252export function emptyChecks(): Checks {
253  return { passed: 0, failed: 0, pending: 0, total: 0, failing: [], running: [], queued: 0 }
254}
255
256export function verdictOf(item: CheckItem): 'passed' | 'pending' | 'failed' {
257  if (isStatusContext(item)) {
258    return item.state === 'SUCCESS' ? 'passed' : item.state === 'PENDING' || item.state === 'EXPECTED' ? 'pending' : 'failed'
259  }
260
261  return item.status !== 'COMPLETED' ? 'pending' : PASSED.has(item.conclusion ?? '') ? 'passed' : 'failed'
262}
263
264export function summarizeChecks(items: readonly CheckItem[] | null | undefined): Checks {
265  const checks = emptyChecks()
266  for (const item of latestRuns(items ?? [])) {
267    checks.total += 1
268    const isContext = isStatusContext(item)
269    const verdict = verdictOf(item)
270    checks[verdict] += 1
271    const name = item.name ?? item.context ?? 'check'
272    if (verdict === 'failed') checks.failing.push(name)
273    if (verdict === 'pending') {
274      // A status context only says PENDING once its CI has picked it up; EXPECTED is still waiting.
275      const isStarted = isContext ? item.state === 'PENDING' : item.status === 'IN_PROGRESS'
276      if (isStarted) checks.running.push(name)
277      else checks.queued += 1
278    }
279  }
280
281  return checks
282}
283
284// "Running build, e2e +1 · 2 queued": what CI is doing right now.
285export function activity(checks: Checks): string {
286  const names = checks.running.slice(0, 2).join(', ')
287  const more = checks.running.length > 2 ? ` +${checks.running.length - 2}` : ''
288  const running = checks.running.length > 0 ? `Running ${names}${more}` : ''
289  const queued = checks.queued > 0 ? `${checks.queued} queued` : ''
290
291  return [running, queued].filter(Boolean).join(' · ')
292}
293
294// Its reviews (review.ts) ride along too.
295export type GhPr = ReviewFacts & {
296  number: number
297  title: string
298  url: string
299  state: 'OPEN' | 'MERGED' | 'CLOSED'
300  isDraft: boolean
301  reviewDecision: string | null
302  mergeStateStatus: string | null
303  // MERGEABLE, CONFLICTING or UNKNOWN: the direct signal, when DIRTY is still being computed.
304  mergeable?: string | null
305  autoMergeRequest: { enabledAt?: string | null; mergeMethod?: string | null } | null
306  viewerCanEnableAutoMerge?: boolean
307  viewerCanDisableAutoMerge?: boolean
308  // Its repository's merge settings, asked for in the same query.
309  repository?: RepoMerge
310  statusCheckRollup: CheckItem[] | null
311  // When it was opened, and when anything on it last changed (prw's date columns); absent
312  // in an entry an older mod wrote.
313  createdAt?: string | null
314  updatedAt?: string | null
315  mergedAt: string | null
316  closedAt?: string | null
317  additions: number
318  deletions: number
319  headRefName: string
320  baseRefName: string
321  author: { login: string } | null
322}
323
324export type RepoMerge = {
325  squashMergeAllowed?: boolean
326  rebaseMergeAllowed?: boolean
327  mergeCommitAllowed?: boolean
328  viewerDefaultMergeMethod?: string | null
329  // READ, TRIAGE, WRITE, MAINTAIN or ADMIN: merging takes WRITE.
330  viewerPermission?: string | null
331}
332
333export function metaOf(pr: GhPr) {
334  return {
335    branch: pr.headRefName,
336    base: pr.baseRefName,
337    additions: pr.additions,
338    deletions: pr.deletions,
339    author: pr.author?.login ?? '',
340    mergedAt: pr.mergedAt,
341    isConflicted: isConflicted(pr),
342  }
343}
344
345const METHODS: readonly MergeMethod[] = ['squash', 'rebase', 'merge']
346const ALLOWS = { squash: 'squashMergeAllowed', rebase: 'rebaseMergeAllowed', merge: 'mergeCommitAllowed' } as const
347const MAY_MERGE = new Set(['WRITE', 'MAINTAIN', 'ADMIN'])
348// GitHub merges these now: HAS_HOOKS and UNSTABLE (an optional check failing) only warn.
349const MERGES_NOW = new Set(['CLEAN', 'HAS_HOOKS', 'UNSTABLE'])
350
351const asMethod = (value: string | null | undefined): MergeMethod | null => METHODS.find(m => m === value?.toLowerCase()) ?? null
352
353// The methods the repo allows, the viewer's default first while the repo still allows it.
354export function methodsOf(repo: RepoMerge | undefined): MergeMethod[] {
355  const allowed = METHODS.filter(m => repo?.[ALLOWS[m]] === true)
356  const preferred = asMethod(repo?.viewerDefaultMergeMethod)
357
358  return preferred !== null && allowed.includes(preferred) ? [preferred, ...allowed.filter(m => m !== preferred)] : allowed
359}
360
361const isConflicted = (pr: GhPr) => pr.mergeStateStatus === 'DIRTY' || pr.mergeable === 'CONFLICTING'
362
363export function noMerge(): Mergeable {
364  return { methods: [], canMerge: false, canAuto: false, isAuto: false, autoMethod: null, canCancelAuto: false }
365}
366
367// An entry written by an older version of this mod (one that won the poll lease) has no merge
368// facts: the card keeps what it last knew of them rather than lose its merge row for a round.
369// What the entry says of the PR itself still counts: no button on a draft or a conflicted
370// branch, and no merge now unless GitHub would merge it now.
371export function mergeOf(pr: GhPr, kept: Mergeable): Mergeable {
372  if (pr.state !== 'OPEN' || pr.repository !== undefined) return mergeableOf(pr)
373  if (pr.isDraft || isConflicted(pr)) return { ...kept, canMerge: false, canAuto: false }
374
375  return { ...kept, canMerge: kept.canMerge && MERGES_NOW.has(pr.mergeStateStatus ?? '') }
376}
377
378export function mergeableOf(pr: GhPr): Mergeable {
379  if (pr.state !== 'OPEN') return noMerge()
380  const methods = methodsOf(pr.repository)
381  const isAuto = pr.autoMergeRequest != null
382  const isEligible = !pr.isDraft && !isConflicted(pr) && !isAuto && methods.length > 0
383  const canMerge = isEligible && MAY_MERGE.has(pr.repository?.viewerPermission ?? '') && MERGES_NOW.has(pr.mergeStateStatus ?? '')
384  // Held back by checks or review, not by a stale branch.
385  const isWaiting =
386    pr.mergeStateStatus === 'BLOCKED' || (pr.mergeStateStatus !== 'BEHIND' && summarizeChecks(pr.statusCheckRollup).pending > 0)
387
388  return {
389    methods,
390    canMerge,
391    // False already where the repo doesn't allow auto-merge.
392    canAuto: isEligible && !canMerge && isWaiting && pr.viewerCanEnableAutoMerge === true,
393    isAuto,
394    autoMethod: asMethod(pr.autoMergeRequest?.mergeMethod),
395    canCancelAuto: isAuto && pr.viewerCanDisableAutoMerge === true,
396  }
397}
398
399// The method a card offers: the one the person switched to, while it is still on offer.
400export function pickMethod(methods: readonly MergeMethod[], chosen: MergeMethod | undefined): MergeMethod | null {
401  return chosen !== undefined && methods.includes(chosen) ? chosen : (methods[0] ?? null)
402}
403
404export function nextMethod(methods: readonly MergeMethod[], current: MergeMethod): MergeMethod {
405  return methods[(methods.indexOf(current) + 1) % methods.length] ?? current
406}
407
408export const MERGE_LABEL: Record<MergeMethod, string> = { squash: 'Squash & merge', rebase: 'Rebase & merge', merge: 'Merge' }
409const MERGE_VERB: Record<MergeMethod, string> = { squash: 'Squash-merge', rebase: 'Rebase-merge', merge: 'Merge' }
410
411// "Squash-merge #12 into main?": what Confirm will do.
412export function mergeQuestion(method: MergeMethod, pr: { number: number; base: string }, isAuto: boolean): string {
413  const into = `${MERGE_VERB[method]} #${pr.number} into ${pr.base || 'its base'}`
414
415  return isAuto ? `${into} once checks and review pass?` : `${into}?`
416}
417
418export type MergeRun = { action: 'merge' | 'auto'; method: MergeMethod } | { action: 'cancel-auto' }
419
420export function mergeArgv(url: string, run: MergeRun): string[] {
421  if (run.action === 'cancel-auto') return ['pr', 'merge', url, '--disable-auto']
422
423  return ['pr', 'merge', url, ...(run.action === 'auto' ? ['--auto'] : []), `--${run.method}`]
424}
425
426// A refusal of the method itself, not of this PR's state, in GitHub's words: the repo's
427// settings ("Merge method squash merging is not allowed on this repository", "Squash merges
428// are not allowed on this repository.", "Merge commits are not allowed…"), a ruleset's
429// ("Rebase is not an allowed merge method"), or linear history's.
430const METHOD_REFUSED = new RegExp(
431  [
432    String.raw`\bmerge method \w+ (?:merging )?is not allowed`,
433    String.raw`\b(?:squash|rebase) merg(?:es|ing) (?:are|is) not allowed`,
434    String.raw`\bmerge commits are not allowed`,
435    String.raw`\bis not an allowed merge method`,
436    String.raw`\bmust not contain merge commits`,
437  ].join('|'),
438  'i',
439)
440
441// What gh said, in plain words: without its ✗, the "GraphQL:" prefix, the mutation's name
442// (camelCase, `(mergePullRequest)`; a branch or check named in brackets stays), or the hints
443// about gh's own flags.
444export function mergeError(stderr: string): { message: string; isMethodRefused: boolean } {
445  const lines = stderr
446    .split('\n')
447    .map(line => line.trim().replace(/^[X✗!]\s+/, '').replace(/^GraphQL:\s*/, '').replace(/\s*\([a-z]+[A-Z]\w*\)$/, ''))
448    .filter(line => line !== '' && !/^To (?:have|use|merge)\b/.test(line))
449  const message = lines.join(' ') || 'gh pr merge failed'
450
451  // GitHub having a moment refuses no method, whatever its page says.
452  return { message, isMethodRefused: !isServerError(message) && METHOD_REFUSED.test(message) }
453}
454
455// GitHub's side gave up, in gh's words: "HTTP 502: Bad Gateway (https://api.github.com/graphql)",
456// "gh: Server Error (HTTP 503)", an older gh's "non-200 OK status code: 504 Gateway Timeout
457// body: …", a gateway's page ("502 Bad Gateway", "Service Unavailable"), or GraphQL's own
458// timeout ("Something went wrong while executing your query. This may be the result of a
459// timeout", "couldn't respond to your request in time"). Such an answer says nothing of whether
460// the merge went through: GitHub often finishes it after the gateway has stopped waiting.
461const SERVER_ERROR = new RegExp(
462  [
463    String.raw`\bHTTP(?:/[\d.]+)? 5\d\d\b`,
464    String.raw`\bstatus(?: code)?:? 5\d\d\b`,
465    String.raw`\b(?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b`,
466    String.raw`\bThis may be the result of a timeout\b`,
467    String.raw`\bcouldn't respond to your request in time\b`,
468  ].join('|'),
469  'i',
470)
471
472export const isServerError = (said: string) => SERVER_ERROR.test(said)
473
474// What gh pr merge needs to know of a PR after GitHub stumbled: one `gh pr view` (GraphQL, as
475// the poller asks), as the same login.
476export const mergeReadArgv = (url: string) => ['pr', 'view', url, '--json', 'state,autoMergeRequest']
477
478export type MergeRead = { state: string; isAuto: boolean }
479
480// `gh pr view --json state,autoMergeRequest`'s answer; null where it isn't one.
481export function mergeReadOf(stdout: string): MergeRead | null {
482  try {
483    const read = JSON.parse(stdout) as { state?: unknown; autoMergeRequest?: unknown } | null
484    if (typeof read?.state !== 'string') return null
485
486    return { state: read.state, isAuto: read.autoMergeRequest != null }
487  } catch {
488    return null
489  }
490}
491
492// After a gh pr merge GitHub answered with a server error (isServerError), as the PR reads
493// now: `done` (it went through: no error, the fetch after shows it), `retry` (it didn't, and
494// the PR is as it was: run it once more), or `failed` (the PR can't be read, or has moved on
495// otherwise: the first error stands).
496export function afterServerError(run: MergeRun, read: MergeRead | null): 'done' | 'retry' | 'failed' {
497  if (read === null) return 'failed'
498  const isOpen = read.state === 'OPEN'
499  switch (run.action) {
500    case 'merge':
501      return read.state === 'MERGED' ? 'done' : isOpen ? 'retry' : 'failed'
502    // gh merges at once where nothing is left to wait for.
503    case 'auto':
504      return read.state === 'MERGED' || (isOpen && read.isAuto) ? 'done' : isOpen ? 'retry' : 'failed'
505    case 'cancel-auto':
506      return !isOpen ? 'failed' : read.isAuto ? 'retry' : 'done'
507  }
508}
509
510// gh runs well inside this (its own timeouts stop it sooner; a collection's longest is a token,
511// the checks and a log in turn, 20 + 20 + 60 s): a busy mark older than this was left by a
512// module reload mid-run, so the row shows its buttons again.
513export const BUSY_MS = 120_000
514
515export function isBusy(busy: Busy | undefined, now: number): busy is Busy {
516  return typeof busy?.at === 'number' && now - busy.at < BUSY_MS
517}
518
519export function ago(ms: number): string {
520  const s = Math.max(0, Math.round(ms / 1000))
521  if (s < 10) return 'just now'
522  if (s < 60) return `${s}s ago`
523  if (s < 3600) return `${Math.floor(s / 60)}m ago`
524  if (s < 86_400) return `${Math.floor(s / 3600)}h ago`
525
526  return `${Math.floor(s / 86_400)}d ago`
527}
528
529// What a card's pill says, by the state derive() found: band.ts ranks and words them too.
530export const PILL = {
531  merged: '✓ MERGED',
532  closed: '✕ CLOSED',
533  draft: '✎ DRAFT',
534  conflicts: '⚠ CONFLICTS',
535  ciFailing: '✗ CI FAILING',
536  ciFailed: '✗ CI FAILED',
537  ciRunning: '● CI RUNNING',
538  changes: '↺ CHANGES REQUESTED',
539  comments: '💬 COMMENTS',
540  inReview: '◷ IN REVIEW',
541  behind: '↓ BEHIND',
542  blocked: '⏸ BLOCKED',
543  checking: '◌ CHECKING',
544  autoMerging: '⇢ AUTO-MERGING',
545  ready: '✓ READY',
546  loading: '◌ LOADING',
547} as const
548
549export type PillKind = keyof typeof PILL
550
551export type Derived = {
552  stage: Stage
553  headline: string
554  pill: string
555  tone: Tone
556  isMoving: boolean
557  checks: Checks
558}
559
560// `kept`: the card's last review facts, for an entry an older version of this mod wrote (none
561// of its own), so the headline doesn't flip back to "Waiting for review" for a round.
562export function derive(pr: GhPr, kept: Reviews | null = null): Derived {
563  const checks = summarizeChecks(pr.statusCheckRollup)
564  const ci = `${activity(checks)} · ${checks.passed}/${checks.total} passed`
565  const at = (stage: Stage, tone: Tone, pill: string, headline: string, isMoving = false): Derived => ({
566    stage,
567    tone,
568    pill,
569    headline,
570    isMoving,
571    checks,
572  })
573
574  if (pr.state === 'MERGED') return at('merged', 'merged', PILL.merged, 'Merged')
575  if (pr.state === 'CLOSED') return at('closed', 'subtle', PILL.closed, 'Closed without merging')
576  const names = checks.failing.slice(0, 2).join(', ')
577  const failing = `${names}${checks.failing.length > 2 ? ` +${checks.failing.length - 2}` : ''}`
578  if (pr.isDraft) {
579    const draft = isConflicted(pr) ? 'Draft · merge conflicts' : 'Draft'
580
581    return at('draft', 'subtle', PILL.draft, checks.pending > 0 ? `${draft} · ${ci}` : draft, checks.pending > 0)
582  }
583  // A conflict blocks the merge whatever CI says, and checks on a conflicted head are often
584  // stale (GitHub cannot build the merge commit), so it outranks CI and review. CI stays in
585  // the line, and on the stepper, as the second thing to know.
586  if (isConflicted(pr)) {
587    const stage = checks.failed > 0 || checks.pending > 0 ? 'checks' : 'ready'
588    const status =
589      checks.failed > 0 ? ` · failing: ${failing}` : checks.pending > 0 ? ` · ${activity(checks)}` : ''
590
591    return at(stage, 'error', PILL.conflicts, `Merge conflicts with base${status}`, checks.pending > 0)
592  }
593  if (checks.failed > 0) {
594    // Still running checks keep the card live: the spinner, the shimmer and the fast poll.
595    return checks.pending > 0
596      ? at('checks', 'error', PILL.ciFailing, `Failing: ${failing} · ${checks.pending} still running`, true)
597      : at('checks', 'error', PILL.ciFailed, `Failing: ${failing}`)
598  }
599  if (checks.pending > 0) return at('checks', 'warning', PILL.ciRunning, ci, true)
600  const reviews = reviewsOf(pr) ?? kept
601  // "2 unresolved threads", or nothing: open conversations, which a repo may require resolved.
602  const threads = reviews === null ? '' : unresolved(reviews)
603  const also = threads === '' ? '' : ` · ${threads}`
604  if (pr.reviewDecision === 'CHANGES_REQUESTED') return at('review', 'error', PILL.changes, 'Changes requested')
605  // Comments waiting for the author, where nobody has approved yet: a PR still in review, or
606  // one held back (BLOCKED) in a repo that needs no approval.
607  const isWaitingOnAuthor = pr.reviewDecision === 'REVIEW_REQUIRED' || (pr.reviewDecision !== 'APPROVED' && pr.mergeStateStatus === 'BLOCKED')
608  if (reviews !== null && threads !== '' && isWaitingOnAuthor) return at('review', 'warning', PILL.comments, toAddress(reviews))
609  if (pr.reviewDecision === 'REVIEW_REQUIRED') {
610    const isLookedAt = reviews?.reviewers.some(r => r.verdict !== 'requested') ?? false
611
612    return at('review', 'warning', PILL.inReview, isLookedAt ? 'Reviewed · waiting for approval' : 'Waiting for review')
613  }
614
615  const isAuto = Boolean(pr.autoMergeRequest)
616  switch (pr.mergeStateStatus) {
617    case 'BEHIND':
618      return at('ready', 'warning', PILL.behind, isAuto ? 'Behind base · auto-merge on' : 'Branch is behind base')
619    case 'BLOCKED': {
620      // Approved, held back, threads open: the likely cause where the repo requires
621      // conversations resolved (GitHub says which rule only to admins).
622      const why = threads !== '' ? `Blocked${also}` : isAuto ? 'Blocked' : 'Blocked by branch rules'
623
624      return at('ready', 'warning', PILL.blocked, isAuto ? `${why} · auto-merge on` : why)
625    }
626    case 'UNKNOWN':
627      return at('ready', 'subtle', PILL.checking, 'Computing mergeability…', true)
628    default: {
629      if (isAuto) return at('ready', 'suggestion', PILL.autoMerging, 'Merging as soon as GitHub allows', true)
630      const ready = pr.reviewDecision === 'APPROVED' ? 'Approved' : 'Ready to merge'
631
632      return at('ready', 'success', PILL.ready, threads === '' ? 'Ready to merge' : `${ready}${also}`)
633    }
634  }
635}
636
637export function placeholder(ref: PrRef): TrackedPr {
638  return {
639    ...ref,
640    title: '',
641    state: 'UNKNOWN',
642    stage: 'unknown',
643    headline: 'Fetching from GitHub…',
644    pill: PILL.loading,
645    tone: 'subtle',
646    isMoving: true,
647    checks: emptyChecks(),
648    branch: '',
649    base: '',
650    additions: 0,
651    deletions: 0,
652    author: '',
653    mergedAt: null,
654    checkedAt: null,
655    error: null,
656    merge: noMerge(),
657    reviews: null,
658    reviewSeen: null,
659    isConflicted: false,
660    isNotFound: false,
661  }
662}
663
664export function isActive(pr: TrackedPr): boolean {
665  return pr.state === 'OPEN' || pr.state === 'UNKNOWN'
666}
667
668export const STEPS = ['Open', 'CI', 'Review', 'Merge'] as const
669
670// Which step the PR is on: steps before it are done, it carries the tone.
671export function stepIndex(stage: Stage): number {
672  switch (stage) {
673    case 'draft':
674    case 'unknown':
675      return 0
676    case 'checks':
677      return 1
678    case 'review':
679      return 2
680    case 'ready':
681    case 'closed':
682      return 3
683    case 'merged':
684      return 4
685  }
686}
687
hooks/batch.ts 293 lines
1// One GraphQL query for many PRs: an aliased field per PR, so a tick costs one call whatever
2// the count, plus the rate limit it left. `gh pr view` fields, shaped back the way it gives them.
3import type { CheckItem, GhPr, PrRef, RepoMerge } from './pr'
4import { LATEST_FIELD, latestIn } from './update'
5
6// 20 PRs a query, run one after another: a query of 40 busy PRs can outlast GitHub's own
7// timeout (a 502 or 504) and lose the whole round, while two of 20 cost the same points and
8// each answers in a few seconds. 100 checks for each stays far inside the node cap. The
9// repo's merge settings ride on each PR's own repository field: plain scalars, which cost
10// nothing in rate-limit points or nodes. (Whether the repo allows auto-merge needs no field:
11// GitHub's viewerCanEnableAutoMerge is false where it doesn't.)
12export const BATCH_SIZE = 20
13
14// The head commit's checks, with whatever more a caller asks of each kind, and of the commit.
15const checksOf = (run = '', status = '', commit = '') => `commits(last: 1) { nodes { commit { statusCheckRollup { contexts(first: 100) { nodes {
16    __typename
17    ... on CheckRun { name status conclusion startedAt ${run}checkSuite { workflowRun { workflow { name } } } }
18    ... on StatusContext { context state createdAt${status} }
19  } } }${commit} } } }`
20
21// Who reviewed and the open threads (review.ts): small pages, logins and states, and of the
22// newest threads only whether they are resolved or outdated, never a comment's text. Each
23// connection costs a PR one more request in GitHub's reckoning (100 make a point), so a batch
24// of 20 costs 1 point (up to 24 would).
25const REVIEWS = `latestReviews(first: 10) { totalCount nodes { author { __typename login } state submittedAt } }
26  latestOpinionatedReviews(first: 10) { nodes { author { __typename login } state submittedAt } }
27  reviewRequests(first: 10) { totalCount nodes { requestedReviewer {
28    __typename ... on User { login } ... on Bot { login } ... on Mannequin { login } ... on Team { slug }
29  } } }
30  reviewThreads(last: 50) { totalCount nodes { isResolved isOutdated } }`
31
32const FRAGMENT = `fragment pr on PullRequest {
33  number title url state isDraft reviewDecision mergeStateStatus mergeable createdAt updatedAt mergedAt closedAt
34  additions deletions headRefName baseRefName author { login } autoMergeRequest { enabledAt mergeMethod }
35  viewerCanEnableAutoMerge viewerCanDisableAutoMerge
36  ${REVIEWS}
37  ${checksOf()}
38}
39fragment repo on Repository {
40  squashMergeAllowed rebaseMergeAllowed mergeCommitAllowed viewerDefaultMergeMethod viewerPermission
41}`
42
43// `withLatest`: also ask for pr-watch's newest version (update.ts), which costs nothing more.
44export function buildQuery(refs: readonly PrRef[], withLatest = false): string {
45  const fields = refs.map((ref, i) => {
46    const [owner = '', name = ''] = ref.repo.split('/')
47
48    return `p${i}: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { pullRequest(number: ${ref.number}) { ...pr } ...repo }`
49  })
50
51  const latest = withLatest ? `\n  ${LATEST_FIELD}` : ''
52
53  return `query {\n  rateLimit { limit remaining resetAt }${latest}\n  ${fields.join('\n  ')}\n}\n${FRAGMENT}`
54}
55
56// `limit`: the hourly points, where the reply said (an older results.json has none).
57export type RateLimit = { remaining: number; resetAt: string; limit?: number }
58
59export type BatchResult = {
60  found: Map<string, GhPr>
61  // Not visible to this token: another account may see them.
62  missing: PrRef[]
63  rate: RateLimit | null
64  // pr-watch's newest version, where the query asked and GitHub could say.
65  latest: string | null
66  // The whole call failed (network, auth, a limit): nothing in it is known.
67  error: string | null
68}
69
70// A failed check run's title and summary, asked apart from the rest (checksQuery).
71type GqlAbout = { databaseId?: number | null; title?: string | null; summary?: string | null }
72
73type GqlPr = Omit<GhPr, 'statusCheckRollup'> & {
74  commits: {
75    nodes: {
76      commit: {
77        statusCheckRollup: { contexts: { nodes: GqlCheck[] } } | null
78        checkSuites?: { nodes: ({ checkRuns: { nodes: GqlAbout[] } | null } | null)[] } | null
79      }
80    }[]
81  }
82}
83
84type GqlRepo = RepoMerge & { pullRequest: GqlPr | null }
85
86type GqlReply = {
87  data?: Record<string, unknown> | null
88  errors?: { type?: string; message?: string }[]
89}
90
91type GqlCheck = NonNullable<GhPr['statusCheckRollup']>[number] & {
92  checkSuite?: { workflowRun?: { workflow?: { name?: string } | null } | null } | null
93}
94
95// A check run's workflow name, lifted out of its suite, so two workflows' same-named jobs
96// stay apart when runs are folded to the latest of each; and its title and summary, where
97// they were asked apart.
98function flattenCheck(node: GqlCheck, about: ReadonlyMap<number, GqlAbout>) {
99  const { checkSuite, ...check } = node
100  const workflow = checkSuite?.workflowRun?.workflow?.name
101  const text = typeof check.databaseId === 'number' ? about.get(check.databaseId) : undefined
102  const named = workflow === undefined ? check : { ...check, workflow }
103
104  return text === undefined ? named : { ...named, title: text.title ?? null, summary: text.summary ?? null }
105}
106
107const firstLine = (text: string) => text.trim().split('\n')[0] ?? ''
108
109// `gh api graphql` exits 1 when any alias errs, yet still prints every alias it resolved.
110export function parseReply(stdout: string, stderr: string, refs: readonly PrRef[]): BatchResult {
111  const result: BatchResult = { found: new Map(), missing: [], rate: null, latest: null, error: null }
112  let reply: GqlReply
113  try {
114    reply = JSON.parse(stdout) as GqlReply
115  } catch {
116    result.error = firstLine(stderr) || 'gh api graphql failed'
117
118    return result
119  }
120  const data = reply.data
121  if (data == null) {
122    result.error = reply.errors?.[0]?.message ?? (firstLine(stderr) || 'GitHub returned no data')
123
124    return result
125  }
126  result.rate = (data.rateLimit as RateLimit | undefined) ?? null
127  // Null, with an error of its own, where the repo can't be read: the PRs don't mind.
128  result.latest = latestIn(data.pw)
129  refs.forEach((ref, i) => {
130    const { pullRequest: pr, ...repository } = (data[`p${i}`] as GqlRepo | null | undefined) ?? { pullRequest: null }
131    if (pr == null) {
132      result.missing.push(ref)
133
134      return
135    }
136    const { commits, ...rest } = pr
137    const commit = commits.nodes[0]?.commit
138    const nodes = commit?.statusCheckRollup?.contexts.nodes ?? []
139    const runs = (commit?.checkSuites?.nodes ?? []).flatMap(suite => suite?.checkRuns?.nodes ?? [])
140    const about = new Map(runs.flatMap(run => (typeof run.databaseId === 'number' ? [[run.databaseId, run] as const] : [])))
141    result.found.set(ref.url, { ...rest, repository, statusCheckRollup: nodes.map(node => flattenCheck(node, about)) })
142  })
143
144  return result
145}
146
147// ---- What GitHub said about a call ----------------------------------------------------
148// The poller runs `gh api graphql -i`, which prints, on stdout and whatever the status, the
149// status line ("HTTP/2.0 502 Bad Gateway", ending "\n"), the headers (each ending "\r\n",
150// named as Go spells them: "X-Ratelimit-Remaining"), a blank line, then the body. A call that
151// got no answer (a cut connection) prints nothing there; gh's stderr says why as before.
152
153export type Http = { status: number | null; headers: Record<string, string>; body: string }
154
155// Headers keyed in lower case; without a status line, all of stdout is the body.
156export function parseHttp(stdout: string): Http {
157  const head = stdout.match(/^HTTP\/[\d.]+ (\d{3})[^\n]*\n((?:[^\r\n]+\r?\n)*)\r?\n/)
158  if (head === null) return { status: null, headers: {}, body: stdout }
159  const lines = (head[2] ?? '').split(/\r?\n/).filter(line => line.includes(':'))
160  const headers = Object.fromEntries(lines.map(line => [line.slice(0, line.indexOf(':')).trim().toLowerCase(), line.slice(line.indexOf(':') + 1).trim()]))
161
162  return { status: Number(head[1]), headers, body: stdout.slice(head[0].length) }
163}
164
165// The primary limit as the headers give it, failed calls included (the body's rateLimit
166// field comes only with data); null where they don't, or where they speak of a limit other
167// than GraphQL's.
168export function rateOf(headers: Readonly<Record<string, string>>): RateLimit | null {
169  const remaining = Number(headers['x-ratelimit-remaining'] ?? NaN)
170  const reset = Number(headers['x-ratelimit-reset'] ?? NaN)
171  const limit = Number(headers['x-ratelimit-limit'] ?? NaN)
172  const resource = headers['x-ratelimit-resource']
173  if (!Number.isFinite(remaining) || !Number.isFinite(reset) || (resource !== undefined && resource !== 'graphql')) return null
174
175  return { remaining, resetAt: new Date(reset * 1_000).toISOString(), ...(Number.isFinite(limit) && { limit }) }
176}
177
178// Seconds GitHub asks to wait (`retry-after`), or null where it doesn't say.
179export function retryAfterOf(headers: Readonly<Record<string, string>>): number | null {
180  // An empty header is no wait named: Number('') would read it as 0.
181  const said = headers['retry-after']?.trim()
182  const seconds = said ? Number(said) : NaN
183
184  return Number.isFinite(seconds) && seconds >= 0 ? seconds : null
185}
186
187// Why a whole call failed, as far as asking again goes:
188// - `secondary-limit`: GitHub's limits on bursts and compute (a 403, or a 200 with errors,
189//   saying "secondary rate limit" or "abuse", or any retry-after). Never asked again at once:
190//   GitHub may ban a client that keeps on, so no session polls until it has waited.
191// - `primary-limit`: the hourly points are spent (x-ratelimit-remaining 0, or GitHub says
192//   "API rate limit exceeded"). The round backs off to the reset, as on a low rate.
193// - `timeout`: GitHub having a moment. Its gateway's 502, 503 or 504 (gh says "gh: HTTP 502",
194//   or "gh: Server Error (HTTP 502)" where the page says why), GraphQL's own timeout ("This
195//   may be the result of a timeout", "couldn't respond to your request in time"), or the
196//   connection cut on the way (`Post "https://api.github.com/graphql": EOF`, a reset, an
197//   HTTP/2 stream error). Asked once more.
198// - `other`: a refusal (401, 403, 404) and the rest: asking again won't help.
199export type CallFailure = 'timeout' | 'secondary-limit' | 'primary-limit' | 'other'
200
201export function failureOf(error: string, http: Http): CallFailure {
202  if (retryAfterOf(http.headers) !== null || /secondary rate limit|abuse/i.test(error)) return 'secondary-limit'
203  if (http.headers['x-ratelimit-remaining'] === '0' || /rate limit/i.test(error)) return 'primary-limit'
204  const isGateway = [502, 503, 504].includes(http.status ?? 0) || /\bHTTP 50[234]\b/.test(error)
205  const isCut = /\b(timeout|EOF|connection reset|broken pipe|stream error|GOAWAY|deadline exceeded)\b|request in time/i.test(error)
206
207  return isGateway || isCut ? 'timeout' : 'other'
208}
209
210// ---- A round's time ------------------------------------------------------------------
211// A round never outlives its lease, so it never runs beside another session's. A call starts
212// only with MIN_CALL_MS left before `until` (a batch has answered in 2.5 s, and a gateway that
213// gives up takes 10), and may take what is left, never more than `max`. Null: no call starts;
214// what it would have asked is left for the next round.
215export const MIN_CALL_MS = 5_000
216
217export function callBudget(until: number, now: number, max: number): number | null {
218  const left = until - now
219
220  return left >= MIN_CALL_MS ? Math.min(left, max) : null
221}
222
223// ---- The failure log ------------------------------------------------------------------
224// ~/.cache/pr-watch/errors.log: one JSON line per failed call, the newest last, the last
225// LOG_LINES kept, so the next "⚠ 502" has a record to `tail`.
226export const LOG_LINES = 200
227
228export type CallLog = { login: string; size: number; ms: number; http: Http; failure: CallFailure; error: string }
229
230export function logLine(at: number, call: CallLog): string {
231  const { headers } = call.http
232  const header = (name: string) => headers[name] ?? null
233
234  return JSON.stringify({
235    at: new Date(at).toISOString(),
236    login: call.login,
237    batch: call.size,
238    ms: call.ms,
239    status: call.http.status,
240    class: call.failure,
241    remaining: header('x-ratelimit-remaining'),
242    used: header('x-ratelimit-used'),
243    resource: header('x-ratelimit-resource'),
244    retryAfter: header('retry-after'),
245    error: call.error.slice(0, 200),
246  })
247}
248
249// The log with `line` added, cut to its last LOG_LINES lines.
250export function appendLog(log: string, line: string, max = LOG_LINES): string {
251  const lines = [...log.split('\n').filter(Boolean), line]
252
253  return `${lines.slice(-max).join('\n')}\n`
254}
255
256export function chunks<T>(items: readonly T[], size = BATCH_SIZE): T[][] {
257  const out: T[][] = []
258  for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size))
259
260  return out
261}
262
263// The conclusions a check run fails with (pr.ts's verdictOf: all but SUCCESS, NEUTRAL, SKIPPED).
264const FAILED = 'ACTION_REQUIRED, CANCELLED, FAILURE, STALE, STARTUP_FAILURE, TIMED_OUT'
265// The failed runs' titles and summaries, by the commit's check suites: a summary may run to
266// 65 KB, so a passing run's is never asked. Joined to its check by databaseId.
267const FAILED_RUNS = `
268    checkSuites(last: 50) { nodes { checkRuns(first: 20, filterBy: { checkType: LATEST, conclusions: [${FAILED}] }) {
269      nodes { databaseId title summary }
270    } } }`
271
272// One PR's checks with what handing a failure to Claude needs: a GitHub Actions run's job id
273// (its databaseId), the links and status descriptions (short: GitHub caps them at 140
274// characters), and the failed runs' summaries. One call, still one point. Asked only on that
275// press, so the poller's query stays as lean as it was; the same alias shape keeps one parser.
276export function checksQuery(ref: PrRef): string {
277  const [owner = '', name = ''] = ref.repo.split('/')
278
279  return `query {
280  p0: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { pullRequest(number: ${ref.number}) {
281    ${checksOf('databaseId detailsUrl ', ' description targetUrl', FAILED_RUNS)}
282  } }
283}`
284}
285
286export function parseChecks(stdout: string, stderr: string, ref: PrRef): { checks: CheckItem[] } | { error: string } {
287  const reply = parseReply(stdout, stderr, [ref])
288  if (reply.error !== null) return { error: reply.error }
289  const pr = reply.found.get(ref.url)
290
291  return pr === undefined ? { error: "Not found, or this gh account can't see it" } : { checks: pr.statusCheckRollup ?? [] }
292}
293
hooks/address.ts 180 lines
1// Handing a PR's open review threads to Claude: where each one is, who said what, and the
2// message that asks to address them. Pure, so the pane only fetches and delivers.
3import type { TrackedPr } from '../types'
4import { clip } from './fix'
5import type { PrRef } from './pr'
6
7// The newest threads read on a press, the comments read of each (the first and its replies),
8// what one comment and one thread may take, and the characters every thread together may
9// take: enough to act on, not a transcript of the whole review.
10export const THREADS = 100
11export const THREAD_COMMENTS = 10
12export const COMMENT_CHARS = 1_000
13export const THREAD_CHARS = 3_000
14export const REVIEW_CHARS = 12_000
15
16export type GhComment = { author: { login: string } | null; body: string; url: string }
17
18// A review thread as GitHub has it. `line` and `startLine` are where it sits on the PR's code
19// now (null once outdated, mostly); the `original` pair, where it was left.
20export type GhThread = {
21  isResolved: boolean
22  isOutdated: boolean
23  path: string
24  line: number | null
25  startLine: number | null
26  originalLine: number | null
27  originalStartLine: number | null
28  comments: { totalCount?: number; nodes: GhComment[] }
29}
30
31// One PR's review threads with what they say. Asked only on a press, never by the poller,
32// whose query only counts them; the alias shape is batch.ts's.
33export function threadsQuery(ref: PrRef): string {
34  const [owner = '', name = ''] = ref.repo.split('/')
35
36  return `query {
37  p0: repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { pullRequest(number: ${ref.number}) {
38    reviewThreads(last: ${THREADS}) { totalCount nodes {
39      isResolved isOutdated path line startLine originalLine originalStartLine
40      comments(first: ${THREAD_COMMENTS}) { totalCount nodes { author { login } body url } }
41    } }
42  } }
43}`
44}
45
46type Reply = {
47  data?: { p0?: { pullRequest?: { reviewThreads?: { totalCount?: number; nodes?: GhThread[] } | null } | null } | null } | null
48  errors?: { message?: string }[]
49}
50
51const firstLine = (text: string) => text.trim().split('\n')[0] ?? ''
52
53// The threads gh printed, and how many the PR has in all; or why there are none.
54export function parseThreads(stdout: string, stderr: string): { threads: GhThread[]; total: number } | { error: string } {
55  let reply: Reply
56  try {
57    reply = JSON.parse(stdout) as Reply
58  } catch {
59    return { error: firstLine(stderr) || 'gh api graphql failed' }
60  }
61  if (reply.data == null) return { error: reply.errors?.[0]?.message ?? (firstLine(stderr) || 'GitHub returned no data') }
62  const threads = reply.data.p0?.pullRequest?.reviewThreads
63  if (threads == null) return { error: "Not found, or this gh account can't see it" }
64  const nodes = threads.nodes ?? []
65
66  return { threads: nodes, total: threads.totalCount ?? nodes.length }
67}
68
69const lineOf = (thread: GhThread) => thread.line ?? thread.originalLine ?? 0
70
71// The threads still to address, by file and line: a resolved one is done, an outdated one may
72// not be.
73export function openThreads(threads: readonly GhThread[]): GhThread[] {
74  return threads
75    .filter(thread => !thread.isResolved)
76    .sort((a, b) => (a.path === b.path ? lineOf(a) - lineOf(b) : a.path < b.path ? -1 : 1))
77}
78
79const span = (start: number | null, end: number | null) => (end === null ? '' : start === null || start === end ? `${end}` : `${start}-${end}`)
80
81// Where a thread is: "src/upload.ts:42", "src/upload.ts:40-42", "src/upload.ts (outdated; was
82// line 42)", or "src/upload.ts (the whole file)" for a comment on the file.
83export function spot(thread: GhThread): string {
84  const now = span(thread.startLine, thread.line)
85  if (!thread.isOutdated) return now === '' ? `${thread.path} (the whole file)` : `${thread.path}:${now}`
86  if (now !== '') return `${thread.path}:${now} (outdated)`
87  const was = span(thread.originalStartLine, thread.originalLine)
88
89  return was === '' ? `${thread.path} (outdated)` : `${thread.path} (outdated; was line${was.includes('-') ? 's' : ''} ${was})`
90}
91
92// A comment as Claude needs it: without the HTML comments review apps keep their bookkeeping
93// in, or runs of blank lines, and clipped.
94export function cleanBody(body: string): string {
95  const text = body
96    .replace(/\r/g, '')
97    .replace(/<!--[\s\S]*?-->/g, '')
98    .replace(/\n[ \t]*\n(?:[ \t]*\n)+/g, '\n\n')
99    .trim()
100
101  return clip(text, COMMENT_CHARS) || '(no text)'
102}
103
104type PrFacts = Pick<TrackedPr, 'repo' | 'number' | 'title' | 'url' | 'branch' | 'base' | 'author'>
105
106// The draft's first words, by which a press finds an earlier draft of its own in the prompt box.
107export const addressHeading = (pr: Pick<PrFacts, 'repo' | 'number'>) => `Review comments to address on ${pr.repo}#${pr.number}:`
108
109// One thread, numbered: where it is and its link, then each comment under it by its author,
110// a body's later lines (not its blank ones) indented further so a reply can't pass for one.
111function threadBlock(thread: GhThread, n: number, author: string): string {
112  const comments = thread.comments.nodes
113  const head = `${n}. ${spot(thread)} · ${comments[0]?.url ?? 'no link'}`
114  const said = comments.map(c => {
115    const login = c.author?.login ?? 'ghost'
116    const who = login.toLowerCase() === author.toLowerCase() ? `@${login} (PR author)` : `@${login}`
117
118    return `   ${who}: ${cleanBody(c.body).replace(/\n(?!\n)/g, '\n     ')}`
119  })
120  const unread = (thread.comments.totalCount ?? comments.length) - comments.length
121  if (unread > 0) said.push(`   (${unread} more ${unread === 1 ? 'reply' : 'replies'}, not read)`)
122
123  return clip([head, ...said].join('\n'), THREAD_CHARS)
124}
125
126// The message for Claude: the PR, each open thread (outdated ones marked), and the ask. It
127// never asks for a push or a merge, nor for a word on GitHub: replies and resolving stay the
128// person's call.
129export function addressPrompt(pr: PrFacts, threads: readonly GhThread[], total = threads.length): string {
130  const open = openThreads(threads)
131  const branch = pr.branch || 'its head branch'
132  const outdated = open.filter(thread => thread.isOutdated).length
133  const blocks: string[] = []
134  let size = 0
135  for (const thread of open) {
136    const block = threadBlock(thread, blocks.length + 1, pr.author)
137    if (blocks.length > 0 && size + block.length > REVIEW_CHARS) break
138    blocks.push(block)
139    size += block.length + 2
140  }
141  const count = `${open.length} unresolved review thread${open.length === 1 ? '' : 's'}`
142  const stale = outdated === 0 ? '' : ` (${outdated} outdated: the code changed since, so check ${outdated === 1 ? 'it' : 'each'} still applies)`
143  const out = [
144    `${addressHeading(pr)} ${pr.title || 'untitled'}`,
145    `${pr.url} · ${branch} → ${pr.base || 'its base'} · files: ${pr.url}/files`,
146    '',
147    `${count}, by file${stale}:`,
148    '',
149    blocks.join('\n\n'),
150  ]
151  const unshown = open.length - blocks.length
152  if (unshown > 0) out.push('', `${unshown} more unresolved thread${unshown === 1 ? '' : 's'} didn't fit here; they're on the PR's files tab.`)
153  if (total > threads.length) out.push('', `Only the newest ${threads.length} of ${total} threads were read; older ones may be open too.`)
154  out.push(
155    '',
156    `Address each on this branch (${branch}): change the code where a comment is right, and where you'd disagree or a ` +
157      `comment needs my call, say so instead. If ${pr.repo} or ${branch} isn't checked out here, say so first.`,
158    "Don't reply to or resolve any thread on GitHub: if one needs a reply, draft it here for me to read first.",
159  )
160
161  return out.join('\n')
162}
163
164// Where a hand-off's draft starts, past the first: fixHeading's, addressHeading's and
165// resolveHeading's first words.
166const NEXT_DRAFT = /\n\n(?:CI failed|Review comments to address|Merge conflicts) on [\w.-]+\/[\w.-]+#\d+:/
167
168// The prompt box with a hand-off drafted in: over an earlier draft of the same one (keeping the
169// person's text before it and any other hand-off's draft after it), into an empty box, or
170// after whatever is there.
171export function redraft(box: string, heading: string, text: string): { text: string; mode: 'append' | 'replace' } {
172  const at = box.trim() === '' || box.startsWith(heading) ? 0 : box.indexOf(`\n\n${heading}`)
173  if (at === -1) return { text: `\n\n${text}`, mode: 'append' }
174  const start = at === 0 ? 0 : at + 2
175  const next = box.slice(start + heading.length).search(NEXT_DRAFT)
176  const after = next === -1 ? '' : box.slice(start + heading.length + next)
177
178  return { text: `${box.slice(0, start)}${text}${after}`, mode: 'replace' }
179}
180
hooks/fix.ts 157 lines
1// Handing a failed CI run to Claude: which checks failed, their logs trimmed to the part that
2// says why, and the message that asks for a fix. Pure, so the pane only fetches and delivers.
3import type { TrackedPr } from '../types'
4import { isStatusContext, latestRuns, verdictOf } from './pr'
5import type { CheckItem } from './pr'
6
7// The tail of each failed job's log that is kept, how many jobs' logs are fetched, and the
8// characters every log together may take: enough to find the error, not the runner's setup.
9export const LOG_LINES = 120
10export const LOG_JOBS = 3
11export const LOG_CHARS = 12_000
12const LINE_CHARS = 400
13
14export type Failure = {
15  name: string
16  workflow: string | null
17  // In words: "failure", "timed out", "error".
18  conclusion: string
19  url: string | null
20  // A check run's title and summary, or a status's description.
21  summary: string | null
22  // A GitHub Actions job, whose failed steps' log gh can fetch; null for any other CI.
23  jobId: number | null
24}
25
26const words = (value: string | null | undefined) => (value ?? 'failed').toLowerCase().replace(/_/g, ' ')
27
28export const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text)
29
30// The checks failing on the latest run of each, counted the way the card counts them.
31export function failingChecks(items: readonly CheckItem[], repo: string): Failure[] {
32  return latestRuns(items)
33    .filter(item => verdictOf(item) === 'failed')
34    .map(item => {
35      const isContext = isStatusContext(item)
36      const id = typeof item.databaseId === 'number' ? item.databaseId : null
37      const about = isContext ? item.description : [item.title, item.summary].filter(Boolean).join(' · ')
38      const fallback = id === null ? null : `https://github.com/${repo}/runs/${id}`
39
40      return {
41        name: item.name ?? item.context ?? 'check',
42        workflow: item.workflow ?? null,
43        conclusion: words(isContext ? item.state : item.conclusion),
44        url: item.detailsUrl ?? item.targetUrl ?? fallback,
45        summary: about ? clip(about.replace(/\s+/g, ' ').trim(), 300) : null,
46        // Only a run in a workflow is an Actions job; another app's check run has no log here.
47        jobId: !isContext && item.workflow !== undefined ? id : null,
48      }
49    })
50}
51
52// The jobs whose logs are worth a fetch: the first few Actions failures.
53export const toFetch = (failures: readonly Failure[]) => failures.filter(f => f.jobId !== null).slice(0, LOG_JOBS)
54
55const ANSI = /\u001b\[[0-9;?]*[A-Za-z]|\u001b\][^\u0007]*\u0007/g
56const STAMP = /^?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z ?/
57
58// `gh run view --log-failed` prints "job<TAB>step<TAB>timestamp text" a line: kept are the
59// text, without colour codes or the runner's group markers, and the failed steps' names.
60export function cleanLog(raw: string): { steps: string[]; lines: string[] } {
61  const steps = new Set<string>()
62  const lines: string[] = []
63  for (const row of raw.replace(/\r/g, '').split('\n')) {
64    const parts = row.split('\t')
65    const step = parts.length >= 3 ? (parts[1] ?? '') : ''
66    if (step !== '' && step !== 'UNKNOWN STEP') steps.add(step)
67    const text = (parts.length >= 3 ? parts.slice(2).join('\t') : row).replace(STAMP, '').replace(ANSI, '')
68    if (/^##\[endgroup\]/.test(text)) continue
69    lines.push(clip(text.replace(/^##\[group\]/, ''), LINE_CHARS))
70  }
71  while (lines.length > 0 && lines[lines.length - 1]?.trim() === '') lines.pop()
72  while (lines.length > 0 && lines[0]?.trim() === '') lines.shift()
73
74  return { steps: [...steps], lines }
75}
76
77export type Trimmed = { text: string; steps: string[]; kept: number; total: number }
78
79// The end of the log, where the error is: its last `maxLines` lines, fewer if they pass `maxChars`.
80export function trimLog(raw: string, maxLines = LOG_LINES, maxChars = LOG_CHARS): Trimmed {
81  const { steps, lines } = cleanLog(raw)
82  const tail = lines.slice(-maxLines)
83  let size = tail.reduce((n, line) => n + line.length + 1, 0)
84  while (tail.length > 1 && size > maxChars) size -= (tail.shift()?.length ?? 0) + 1
85  while (tail.length > 0 && tail[0]?.trim() === '') tail.shift()
86
87  return { text: tail.join('\n'), steps, kept: tail.length, total: lines.length }
88}
89
90// What gh said when a log would not come, in plain words.
91export function logError(stderr: string): string {
92  const text = (stderr.trim().split('\n')[0] ?? '').replace(/^failed to get run log:\s*/i, '')
93  if (/HTTP 410/.test(text)) return 'GitHub no longer keeps this log'
94  if (/HTTP 404/.test(text)) return "GitHub has no log for it, or this account can't see it"
95  if (/in progress/i.test(text)) return 'its run is still going, and GitHub gives the log once it ends'
96
97  return text || 'gh run view failed'
98}
99
100// A failure and what came of fetching its log: the raw log, or why there is none.
101export type Handoff = { failure: Failure; log?: string; error?: string }
102
103// Logs that would not come, for the card: "No log for build: GitHub no longer keeps this log".
104export function logProblems(handoffs: readonly Handoff[]): string | null {
105  const problems = handoffs.filter(h => h.error !== undefined).map(h => `No log for ${h.failure.name}: ${h.error}`)
106
107  return problems.length > 0 ? problems.join('; ') : null
108}
109
110// A fence longer than any run of backticks in the log, so the log can't close it.
111const fence = (text: string) => '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map(m => m[0].length + 1)))
112
113type PrFacts = Pick<TrackedPr, 'repo' | 'number' | 'title' | 'url' | 'branch' | 'base'>
114
115// The draft's first words, by which a press finds an earlier draft of its own in the prompt box.
116export const fixHeading = (pr: Pick<PrFacts, 'repo' | 'number'>) => `CI failed on ${pr.repo}#${pr.number}:`
117
118// A check as the PR page names it, its workflow first when that says more.
119const labelOf = (f: Failure) => (f.workflow === null || f.workflow === f.name ? f.name : `${f.workflow} / ${f.name}`)
120
121// The message for Claude: the PR, what failed, the logs' tails, and the ask. It never asks
122// for a push or a merge; that stays the person's call.
123export function fixPrompt(pr: PrFacts, handoffs: readonly Handoff[]): string {
124  const logs = handoffs.filter(h => h.log !== undefined)
125  const budget = Math.floor(LOG_CHARS / Math.max(1, logs.length))
126  const branch = pr.branch || 'its head branch'
127  const out = [
128    `${fixHeading(pr)} ${pr.title || 'untitled'}`,
129    `${pr.url} · ${branch} → ${pr.base || 'its base'} · checks: ${pr.url}/checks`,
130    '',
131    'Failing checks (the latest run of each):',
132    ...handoffs.map(({ failure: f }) => `- ${[labelOf(f), f.conclusion, f.summary, f.url].filter(Boolean).join(' · ')}`),
133  ]
134  for (const h of handoffs) {
135    const name = labelOf(h.failure)
136    if (h.error !== undefined) out.push('', `${name}: no log (${h.error}).`)
137    if (h.log === undefined) continue
138    const log = trimLog(h.log, LOG_LINES, budget)
139    if (log.kept === 0) {
140      out.push('', `${name}: gh found no failed step in its log.`)
141      continue
142    }
143    const step = log.steps.length > 0 ? `, failed step ${log.steps.map(s => `"${s}"`).join(', ')}` : ''
144    const span = log.kept < log.total ? `last ${log.kept} of ${log.total} lines, trimmed` : `all ${log.total} lines`
145    const bar = fence(log.text)
146    out.push('', `${name} log (${span}${step}):`, bar, log.text, bar)
147  }
148  const unfetched = handoffs.filter(h => h.failure.jobId !== null && h.log === undefined && h.error === undefined).length
149  if (unfetched > 0) out.push('', `Logs of the first ${LOG_JOBS} failing jobs only; ${unfetched} more not fetched.`)
150  out.push(
151    '',
152    `Find the cause and fix it on this branch (${branch}). If ${pr.repo} or ${branch} isn't checked out here, say so first.`,
153  )
154
155  return out.join('\n')
156}
157
hooks/resolve.ts 34 lines
1// Handing a conflicted PR to Claude: the message that asks to bring its base in and resolve
2// the conflicts. GitHub doesn't say which files conflict, so there is nothing to fetch: git
3// finds them once the base is merged in. Pure, so the pane only delivers.
4import type { TrackedPr } from '../types'
5
6type PrFacts = Pick<TrackedPr, 'repo' | 'number' | 'title' | 'url' | 'branch' | 'base'>
7
8// The draft's first words, by which a press finds an earlier draft of its own in the prompt box.
9export const resolveHeading = (pr: Pick<PrFacts, 'repo' | 'number'>) => `Merge conflicts on ${pr.repo}#${pr.number}:`
10
11// The message for Claude: the PR, what GitHub says, and the ask. A merge, not a rebase, so the
12// pushed history stays as it is and no force-push is needed; and like Fix with Claude's, it
13// never asks for a push or a merge: that stays the person's call.
14export function resolvePrompt(pr: PrFacts): string {
15  const branch = pr.branch || 'its head branch'
16  const base = pr.base || 'its base'
17  const origin = pr.base ? `origin/${pr.base}` : 'the base from origin'
18
19  return [
20    `${resolveHeading(pr)} ${pr.title || 'untitled'}`,
21    `${pr.url} · ${branch} → ${base}`,
22    '',
23    `GitHub says ${branch} can't be merged cleanly into ${base}.`,
24    '',
25    `Bring ${base} into this branch (${branch}): fetch, then merge ${origin} into it, so no history is rewritten and ` +
26      `no force-push is needed. If origin isn't ${pr.repo} (a fork's clone), merge ${base} from the remote that is. ` +
27      `If the branch or repo clearly works by rebase instead, say so and ask me first. ` +
28      `If ${pr.repo} or ${branch} isn't checked out here, say so first.`,
29    "Resolve each conflict keeping what both sides meant; where a side's intent is unclear, ask me rather than pick one. " +
30      "Then run the project's checks and tests, and commit the merge.",
31    "Don't push: that stays my call.",
32  ].join('\n')
33}
34
hooks/comment.ts 48 lines
1// Commenting on a PR from its card: the gh call that posts it, what GitHub answers, and how a
2// refusal reads on the card. Pure, so the pane only delivers.
3import type { PrRef } from './pr'
4
5// Only text with something in it posts: an empty or blank field does nothing.
6export const isPostable = (text: string) => text.trim() !== ''
7
8// A comment on the PR's conversation (an issue comment, not a review). The text never goes in
9// argv: it goes on stdin as the request's JSON body (commentInput), so a text starting with `@`
10// or `-`, or holding newlines, posts as typed and is never read as a flag or a file.
11export const commentArgv = (pr: Pick<PrRef, 'repo' | 'number'>) => [
12  'api',
13  '--method',
14  'POST',
15  `repos/${pr.repo}/issues/${pr.number}/comments`,
16  '--input',
17  '-',
18]
19
20// What gh writes to the call's stdin: the text whole, nothing trimmed.
21export const commentInput = (text: string) => JSON.stringify({ body: text })
22
23// The new comment's link, from GitHub's reply (null: the reply named none).
24export function commentUrl(stdout: string): string | null {
25  try {
26    const url = (JSON.parse(stdout) as { html_url?: unknown } | null)?.html_url
27
28    return typeof url === 'string' && url.startsWith('https://') ? url : null
29  } catch {
30    return null
31  }
32}
33
34// gh's first line, in plain words: "gh: Unable to create comment because issue is locked.
35// (HTTP 403)" is "Couldn't comment: Unable to create comment because issue is locked."
36export function commentError(stderr: string, login: string): string {
37  const text = (stderr.trim().split('\n')[0] ?? '').replace(/^gh:\s*/, '')
38  const who = login === '' ? 'this account' : login
39  if (/HTTP 404/.test(text)) return `Couldn't comment: GitHub has no such PR, or ${who} can't see it`
40  if (/HTTP 401/.test(text)) return `Couldn't comment: GitHub refused ${who}'s token; gh auth login renews it`
41  const said = text.replace(/\s*\(HTTP \d{3}\)$/, '')
42
43  return `Couldn't comment: ${said || 'gh api failed'}`
44}
45
46// The empty field's words: which PR, and which account will post.
47export const commentPlaceholder = (pr: Pick<PrRef, 'number'>, login: string) => (login === '' ? `Comment on #${pr.number}` : `Comment on #${pr.number} as ${login}`)
48
hooks/review.ts 160 lines
1// A PR's review state as a card shows it: where each reviewer stands, the review threads still
2// open, and which reviews landed since the last look.
3import type { Reviewer, Reviews, Verdict } from '../types'
4
5type Actor = { __typename?: string; login?: string; slug?: string } | null
6
7export type GhReview = { author: Actor; state: string; submittedAt?: string | null }
8
9// The review connections the poller asks for (batch.ts), in GitHub's shape. `latestReviews` is
10// each reviewer's last review of any kind, but leaves out a reviewer with a request pending (a
11// re-request too); `latestOpinionatedReviews` is each one's last approval or change request,
12// which still counts after a later comment or a re-request.
13export type ReviewFacts = {
14  latestReviews?: { totalCount?: number; nodes: GhReview[] } | null
15  latestOpinionatedReviews?: { nodes: GhReview[] } | null
16  reviewRequests?: { totalCount?: number; nodes: { requestedReviewer: Actor }[] } | null
17  // The newest threads, enough to count; never their comments.
18  reviewThreads?: { totalCount?: number; nodes: { isResolved: boolean; isOutdated: boolean }[] } | null
19}
20
21type Reviewed = Exclude<Verdict, 'requested'>
22
23const VERDICT: Record<string, Reviewed> = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes', COMMENTED: 'commented' }
24const RANK: readonly Verdict[] = ['changes', 'approved', 'commented', 'requested']
25
26// A review app's login cut to its name (copilot-pull-request-reviewer → copilot), so the line
27// stays short; a person's login stays whole.
28export function nameOf(actor: Actor): string {
29  const login = actor?.login ?? actor?.slug ?? ''
30
31  return actor?.__typename === 'Bot' && login.length > 12 ? login.split('-')[0] || login : login
32}
33
34const keyOf = (actor: Actor) => (actor?.__typename === 'Team' ? `team:${actor.slug ?? ''}` : (actor?.login ?? ''))
35
36// Each reviewer once. An approval or change request stands until its reviewer changes it, as
37// GitHub counts it for the decision; else a pending request; else their last comment. The PR's
38// author is no reviewer (their replies in a thread are reviews too). Null when the entry has no
39// review facts: an older version of this mod ran that round.
40export function reviewsOf(pr: ReviewFacts & { author?: { login: string } | null }): Reviews | null {
41  const { latestReviews: latest, reviewThreads: threads } = pr
42  if (latest == null || threads == null) return null
43  const requests = pr.reviewRequests ?? { nodes: [] }
44  const seen = new Map<string, Reviewer>()
45  const put = (actor: Actor, verdict: Verdict | undefined) => {
46    const key = keyOf(actor)
47    if (verdict === undefined || key === '' || key === pr.author?.login || seen.has(key)) return
48    seen.set(key, { login: nameOf(actor), verdict })
49  }
50  for (const review of pr.latestOpinionatedReviews?.nodes ?? []) {
51    if (review.state !== 'COMMENTED') put(review.author, VERDICT[review.state])
52  }
53  for (const request of requests.nodes) put(request.requestedReviewer, 'requested')
54  for (const review of latest.nodes) put(review.author, VERDICT[review.state])
55  const beyond = (total: number | undefined, shown: number) => Math.max(0, (total ?? shown) - shown)
56  const open = threads.nodes.filter(thread => !thread.isResolved)
57
58  return {
59    reviewers: [...seen.values()].sort((a, b) => RANK.indexOf(a.verdict) - RANK.indexOf(b.verdict)),
60    more: beyond(latest.totalCount, latest.nodes.length) + beyond(requests.totalCount, requests.nodes.length),
61    unresolved: open.length,
62    outdated: open.filter(thread => thread.isOutdated).length,
63    isCapped: beyond(threads.totalCount, threads.nodes.length) > 0,
64  }
65}
66
67// "3", or "8+" when there are more threads than were asked for: a floor, not a count.
68const count = (reviews: Reviews) => `${reviews.unresolved}${reviews.isCapped ? '+' : ''}`
69const plural = (reviews: Reviews, word: string) => `${count(reviews)} ${word}${reviews.unresolved === 1 && !reviews.isCapped ? '' : 's'}`
70
71// "3 unresolved threads", or nothing.
72export const unresolved = (reviews: Reviews) => (reviews.unresolved === 0 ? '' : plural(reviews, 'unresolved thread'))
73
74// "3 unresolved threads (1 outdated)": outdated ones are on code that has changed since.
75export function threadLine(reviews: Reviews): string {
76  const text = unresolved(reviews)
77
78  return text === '' || reviews.outdated === 0 ? text : `${text} (${reviews.outdated} outdated)`
79}
80
81// "3 comments to address", for the headline.
82export const toAddress = (reviews: Reviews) => `${plural(reviews, 'comment')} to address`
83
84// What a card says of the threads under its headline: the whole line, or, where the headline
85// counts them already ("3 comments to address", "Approved · 2 unresolved threads"), only how
86// many are outdated, beside it.
87export function threadsBeside(headline: string, reviews: Reviews): { line: string; note: string } {
88  const isCounted = reviews.unresolved > 0 && (headline === toAddress(reviews) || headline.includes(unresolved(reviews)))
89  if (!isCounted) return { line: threadLine(reviews), note: '' }
90
91  return { line: '', note: reviews.outdated > 0 ? `${reviews.outdated} outdated` : '' }
92}
93
94const ICON: Record<Verdict, string> = { approved: '✓', changes: '✗', commented: '💬', requested: '◷' }
95const SAYS: Record<Verdict, string> = { approved: 'approved', changes: 'requested changes', commented: 'commented', requested: 'requested' }
96
97// Terminal cells: an emoji outside the basic plane (💬) takes two.
98export function cells(text: string): number {
99  return [...text].reduce((n, ch) => n + ((ch.codePointAt(0) ?? 0) > 0xffff ? 2 : 1), 0)
100}
101
102export type Piece = { text: string; verdict: Verdict | null }
103
104const SEP = 3 // ' · '
105
106// The reviewers line, to fit `columns`: "✓ alice approved · ✗ bob requested changes" while it
107// fits, else just icons and names ("✓ alice · ✗ bob · 💬 nadav"), as many as fit beside a
108// "+2 more" (a null verdict). Always at least one reviewer: the card truncates the rest.
109export function verdictLine(reviews: Pick<Reviews, 'reviewers' | 'more'>, columns: number): Piece[] {
110  const width = (pieces: readonly Piece[]) => pieces.reduce((n, p) => n + cells(p.text), 0) + SEP * Math.max(0, pieces.length - 1)
111  const more = (n: number): Piece[] => (n > 0 ? [{ text: `+${n} more`, verdict: null }] : [])
112  const long = reviews.reviewers.map(r => ({ text: `${ICON[r.verdict]} ${r.login} ${SAYS[r.verdict]}`, verdict: r.verdict }))
113  if (width([...long, ...more(reviews.more)]) <= columns) return [...long, ...more(reviews.more)]
114  const short = reviews.reviewers.map(r => ({ text: `${ICON[r.verdict]} ${r.login}`, verdict: r.verdict }))
115  let shown = short.length
116  while (shown > 1 && width([...short.slice(0, shown), ...more(short.length - shown + reviews.more)]) > columns) shown -= 1
117
118  return [...short.slice(0, shown), ...more(short.length - shown + reviews.more)]
119}
120
121export type ReviewEvent = { who: string; verdict: Reviewed; at: number }
122
123// The reviews submitted since `seen` (the newest submission time already looked at), by anyone
124// but the person (any of their gh logins) or the PR's author (their thread replies are reviews
125// too, and reviewsOf leaves them out). On a PR's first look (`seen` null) none is new:
126// they were there before the card. Returns the new mark, which only moves forward, so a review
127// that drops out of the reply and comes back (a request made and withdrawn) isn't new again.
128export function newReviews(pr: ReviewFacts, seen: number | null, mine: readonly string[], author?: string): { fresh: ReviewEvent[]; seen: number | null } {
129  if (pr.latestReviews == null) return { fresh: [], seen }
130  const own = new Set([...mine, author ?? ''].filter(Boolean).map(login => login.toLowerCase()))
131  const all = new Map<string, ReviewEvent & { login: string }>()
132  for (const review of [...pr.latestReviews.nodes, ...(pr.latestOpinionatedReviews?.nodes ?? [])]) {
133    const at = Date.parse(review.submittedAt ?? '')
134    const verdict = VERDICT[review.state]
135    const login = review.author?.login ?? ''
136    if (Number.isFinite(at) && verdict !== undefined && login !== '') all.set(`${login}@${at}`, { who: nameOf(review.author), login, verdict, at })
137  }
138  const mark = Math.max(seen ?? 0, ...[...all.values()].map(review => review.at))
139  if (seen === null) return { fresh: [], seen: mark }
140  const fresh = [...all.values()]
141    .filter(review => review.at > seen && !own.has(review.login.toLowerCase()))
142    .sort((a, b) => a.at - b.at)
143    .map(({ who, verdict, at }) => ({ who, verdict, at }))
144
145  return { fresh, seen: mark }
146}
147
148const SAID: Record<Reviewed, (who: string, number: number) => string> = {
149  approved: (who, number) => `✓ ${who} approved #${number}`,
150  changes: (who, number) => `✗ ${who} requested changes on #${number}`,
151  commented: (who, number) => `💬 ${who} commented on #${number}`,
152}
153
154// One toast per new review; a burst of them (a round after a long sleep) is one toast.
155export function reviewToasts(fresh: readonly ReviewEvent[], number: number): string[] {
156  if (fresh.length > 2) return [`💬 ${fresh.length} new reviews on #${number}`]
157
158  return fresh.map(review => SAID[review.verdict](review.who, number))
159}
160
hooks/update.ts 99 lines
1// Saying when a newer pr-watch is out. Claude Code tells no one of a third-party marketplace's
2// new version, and a folder-loaded copy gets no updates at all, so the mod says it itself: the
3// poller's round also reads this repo's plugin.json (batch.ts, at most every CHECK_MS, no call
4// of its own), and each session compares that version with its own manifest's.
5import { cells } from './review'
6
7// How often a round also asks for the newest version.
8export const CHECK_MS = 2 * 3_600_000
9
10// The field a round adds beside its PRs: plugin.json on the default branch. The repo is
11// public, so any gh account reads it. Renamed, gone or private, GitHub answers it with null
12// and an error of its own, and the PRs beside it come through as ever.
13export const LATEST_FIELD =
14  'pw: repository(owner: "ElirazKed", name: "claude-code-pr-watch") { object(expression: "HEAD:.claude-plugin/plugin.json") { ... on Blob { text } } }'
15
16type Version = readonly [number, number, number]
17
18// Plain major.minor.patch only: anything else (a pre-release, a typo) is never compared.
19function parse(text: string): Version | null {
20  const m = text.trim().match(/^(\d+)\.(\d+)\.(\d+)$/)
21
22  return m === null ? null : [Number(m[1]), Number(m[2]), Number(m[3])]
23}
24
25// A manifest's version, from its text; null when it isn't JSON or has no version to compare.
26export function versionIn(manifest: unknown): string | null {
27  if (typeof manifest !== 'string') return null
28  try {
29    const version = (JSON.parse(manifest) as { version?: unknown } | null)?.version
30
31    return typeof version === 'string' && parse(version) !== null ? version.trim() : null
32  } catch {
33    return null
34  }
35}
36
37// The newest version in a reply's `pw` field; null when there is none to read.
38export function latestIn(field: unknown): string | null {
39  return versionIn((field as { object?: { text?: unknown } | null } | null | undefined)?.object?.text)
40}
41
42// Whether `latest` is a later version than `own`; false when either won't parse.
43export function isNewer(latest: string, own: string): boolean {
44  const a = parse(latest)
45  const b = parse(own)
46  if (a === null || b === null) return false
47  const i = a.findIndex((n, j) => n !== b[j])
48
49  return i !== -1 && (a[i] ?? 0) > (b[i] ?? 0)
50}
51
52// How this copy updates, by where it was loaded from. An install from a marketplace sits in
53// Claude Code's plugin cache (<config dir>/plugins/cache/<marketplace>/<plugin>/<version>/);
54// anything else is a folder (--plugin-dir, CLAUDE_CODE_PLUGIN_DIRS), most likely a clone.
55export function howToUpdate(root: string, home: string | null, name: string): string {
56  const path = root.replace(/\\/g, '/')
57  if (path.includes('/plugins/cache/')) {
58    const market = path.match(/\/plugins\/cache\/([^/]+)\/[^/]+/)?.[1]
59
60    return market === undefined ? `/plugin → Installed → ${name} → Update now` : `claude plugin update ${name}@${market}`
61  }
62  const base = home?.replace(/\\/g, '/').replace(/\/+$/, '') ?? ''
63  const isHome = base !== '' && (path === base || path.startsWith(`${base}/`))
64
65  return `git pull in ${isHome ? `~${path.slice(base.length)}` : path}`
66}
67
68// "↑ pr-watch 0.9.0 available": what's out, without how to get it (the band's short form).
69export const headOf = (version: string) => `↑ pr-watch ${version} available`
70
71export const noticeToast = (version: string, how: string) => `${headOf(version)} · ${how}`
72
73// The footer's note: one line where it fits, else what's out above how to get it.
74export function noticeLines(version: string, how: string, columns: number): string[] {
75  const line = noticeToast(version, how)
76
77  return cells(line) <= columns ? [line] : [headOf(version), how]
78}
79
80// Telling a mod user about prw, the companion app: a card in the pane (a line in the band)
81// that stays until it is dismissed, on every session of the machine. companion.json in the
82// cache keeps why it is gone (dismissed, or prw seen running), so it never comes back.
83export const PRW_URL = 'https://elirazked.github.io/claude-code-pr-watch/prw.html'
84export const PRW_PILL = '✦ NEW'
85export const PRW_TEXT = "all your PRs in one terminal. Yours, your searches, your agents'. Review, reply, resolve and merge without opening GitHub."
86export const PRW_LINE = 'New: prw, all your PRs in one terminal'
87
88export type CompanionState = 'dismissed' | 'seen'
89
90// What companion.json says, from its parsed text; null for none (or a file it can't read).
91export function companionIn(file: unknown): CompanionState | null {
92  const state = (file as { state?: unknown } | null | undefined)?.state
93
94  return state === 'dismissed' || state === 'seen' ? state : null
95}
96
97// Whether prw has been running here: it writes its session files as `prw-<id>…json`.
98export const isPrwIn = (names: readonly string[]) => names.some(name => name.startsWith('prw-') && name.endsWith('.json'))
99