SLOPSHOPPER

Review Inbox

Your GitHub work in a drawer: PRs waiting for your review, each summarized in plain language, your open PRs with their reviews, and your issues

panebandcommandtoastpromptmodel
★ 2v0.14.1MITupdated 2026-10-26SummerRiversound/review-inbox
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · review-inbox
│ ┃ Review inbox ✕ › fix the failing auth test and add an audit log call │ ┃ Review inbox [ ↻ ] │ ┃ ⏺ Read(src/auth.ts) │ ┃ Search: repo, #number, title, description o ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ [ To review 0 ] [ My PRs 0 ] [ Assigned & m ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ No PRs are waiting for your review. ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /review-inbox │ ⎿ review-inbox: Opened the review inbox. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Review inbox
Review inbox [ ↻ ] Search: repo, #number, title, description or note ⏎ Search [ To review 0 ] [ My PRs 0 ] [ Assigned & mentioned 0 ] │ [ No PRs are waiting for your review.
README

Review Inbox

validates Mentioned in Awesome Claude Code

English | 한국어 | 日本語 | 简体中文 | 繁體中文 | Español | Português | Deutsch | Français

A Claude Code mod that keeps your GitHub work in view while you code: the pull requests waiting for your review, each summarized in plain language before you open it, your own open PRs and the reviews they get, and the issues that pull you in.

The band above the prompt, then the drawer's three tabs: To review, My PRs and My issues

Quick start

With GitHub CLI logged in (gh auth login), at the prompt of a Claude Code session:

/plugin marketplace add https://github.com/SummerRiversound/review-inbox.git
/plugin install review-inbox@review-inbox
/review-inbox

The last line opens the drawer. Options and updates are under Install.

  • Band above the prompt — one line counting only what needs you: PRs waiting for your review, your PRs with something to do, and issues assigned to you or mentioning you. Its colour is how long the oldest review request has waited (yellow from 3 days, red from 14). Open opens the drawer. A count that goes down shows in green for a moment.
  • Drawer — /review-inbox, with five tabs: To review, My PRs and Assigned & mentioned hold what to act on, then Saved searches and Notifications are there to browse. Press 1 to 5 while the drawer has focus to switch to that tab, counting from the left. The number on a tab counts its cards; Saved searches has none, and Notifications counts the unread.
  • Toasts — a short notice when something new arrives while you work.

The interface and the summaries come in nine languages; see Language.

Requirements

  • Claude Code 2.1.287 or later, the first builds with mods (function-hook plugins). Tested on 2.1.292. Mods are in early access, and their API may change between releases.
  • GitHub CLI (gh) on your PATH, logged in (gh auth login) with access to the repositories you review.
  • GitHub Enterprise Server: set GH_HOST in the environment Claude Code starts in; every gh call goes to that host.

Install

At the prompt of a Claude Code session:

/plugin marketplace add https://github.com/SummerRiversound/review-inbox.git
/plugin install review-inbox@review-inbox

The install screen asks for the options below; all of them can stay empty or at their default.

Update and uninstall

claude plugin marketplace update review-inbox
claude plugin update review-inbox@review-inbox
claude plugin uninstall review-inbox@review-inbox

An update applies after a restart. Uninstalling leaves the mod's cache folder, ~/.claude/plugins/data/review-inbox, in place; delete it yourself to remove the cached lists and summaries. See the changelog for what each version changed.

Configuration

Set on the install screen; change them later in /config. A change applies right away.

OptionDefaultWhat it does
scopeemptyGitHub search qualifiers added to every search (review-requested:@me, author:@me, assignee:@me, mentions:@me). Empty means all of GitHub.
githubUseremptyThe gh account to use when several are logged in (gh auth token -u <user>). Empty uses the active account.
languageautoauto, or one of the codes in Language.
refreshMinutes10Minutes between fetches from GitHub: 5, 10, 15, 30 or 60. All sessions share one fetch.
repoPathsemptyWhere Claude works on each repository, for the next-step buttons. See below.
motionautooff stops the band's count flash. auto stops it too when Claude Code's reduced motion setting (prefersReducedMotion) is on.
directActionsoffon adds buttons that write to GitHub from a card. See Direct GitHub actions below.

scope takes anything GitHub's issue and PR search accepts:

org:my-org
org:my-org org:other-org
repo:owner/name repo:owner/other
org:my-org -repo:my-org/noisy-repo
user:my-username

Repeated org:, repo: and user: qualifiers match any of them. A team review request counts as a request for you, as GitHub's review-requested:@me defines it.

repoPaths takes comma-separated owner/repo=path entries. owner/*=path/* covers every repository of an owner, with * in the path standing for the repository's name; an exact name wins over a wildcard, and ~ is your home folder. A folder named here wins over the session's own folder and the ones the mod remembers.

my-org/*=~/code/*
my-org/legacy=~/old/legacy-app

Tabs

Each tab groups its cards into categories. Press a category's header to fold it, and again to open it. N hidden · show all at the top of a tab brings back that tab's hidden cards.

Note, under a card's ▸ Actions, writes one line above its title: what you checked, or what you agreed to do and when. Save keeps the card in view. Snooze until tomorrow and Snooze until next week put it away until 9 a.m. tomorrow or next Monday, or sooner when it has news: a new commit on a review request, a new state or a new review on your PR, new activity on an issue. A toast tells you when a snoozed card is back, with its note. Clear removes the note.

The search field at the top looks through every tab at once: repository, number, title, author, the first 2,000 characters of the description, the summary and your notes. Hidden and snoozed cards are found too, marked hidden. Empty the field to go back to the tabs. The Claude mobile app draws no text fields yet, so there it shows notes but has no search and no Note.

Cards a session is working on gather under In progress in a session at the top of To review and My PRs, with the session's folder name, or this session. My PR counts when a session's folder is checked out on its branch in its repository; any card counts once a prompt in that session links to it, as Review with Claude does. A session that is closed, or has not checked in for 10 minutes, lets its cards go back to their groups.

A session still running an older release of the mod, as one opened before an update and never reloaded, is named under the drawer's title, such as 2 sessions on an older version (dhub2): run /reload-plugins there. Such a session keeps its own lists in a file of its own, so it never shows its lists or errors in an up-to-date session. Reload them all beside it asks those sessions to run /reload-plugins themselves, through reload.json in the cache folder: each does once it is idle, and its other plugins reload with it. Only sessions on 0.13.0 or later can answer; an older one still needs /reload-plugins typed there once.

Cards from this session's repository come first in every group, tagged this repo. When the tabs also hold other repositories, This repo N and All N above the tabs narrow them to this repository or show everything again; the band always counts everything. This session's repository is the one GH_REPO names, as gh reads it, else the folder's GitHub remotes.

Under its title a card shows up to two labels and how many more, its comment count and, for a PR, → base when it targets a branch other than the repository's default.

A ● before a card's repository marks one updated since you last closed the drawer, as GitHub's own inbox marks what changed since your last visit. Before the first close nothing is marked.

When nothing needs you (no review request, none of your PRs to act on, no issue assigned to you or mentioning you), the drawer says ✓ Nothing needs you above the tabs, and the band stays hidden.

To review

One card per PR waiting for your review: a one-sentence summary, why the PR exists, what it touches, its size and author, and how long your review has been pending. Risky items, such as a schema change or a required deploy order, are marked ⚠️.

  • Review with Claude marks the card Added and keeps the drawer open, so you can pick several PRs. When you close the drawer (Esc or ×), a review request for each added PR goes into your prompt, with its warnings and what changed since your last review. Nothing is sent until you press Enter. A PR your draft already asks for shows as Added when the drawer opens.
  • Hide, under ▸ Actions beside Note, hides the card until the PR gets a new commit.
  • re-requested marks a PR you already reviewed that asks for you again, with a short summary of what changed since your last review.
  • Cards are grouped into direct requests, team requests and drafts.

Review on two cards marks them Added, Hide hides a third, and Esc puts both review requests into the prompt

The request also carries one line describing how you usually review, so Claude reviews the way you would. Once a week the mod reads your own comments on up to 30 PRs you recently reviewed, and asks Claude to describe your language and tone, what you look at first and how you phrase requests. With fewer than five comments to learn from, the request goes without that line; if learning fails, the last description stays and the mod tries again a day later.

My PRs

Your open PRs with their state instead of a summary, in the order you have to act on them: changes requested, CI failing, merge conflict, waiting for review (oldest first), approved, in merge queue, draft. Running CI is shown next to the state. A PR in a merge queue shows In merge queue: GitHub merges it once the queue's checks pass, so it is not counted in the band and never shows Ready to merge.

Hide hides a PR until it turns to another state or someone reviews it; your own push alone does not bring it back.

My PRs: six PRs from changes requested to draft, two with a new review

A review submitted after your latest commit shows as New review with who left it, until you commit again. That covers approvals, change requests and comment-only reviews, thread replies included, from people or bots; a dismissed review does not count. Such a PR counts as something to do and moves ahead of quiet ones in the same state. No model calls.

A PR stuck on you (changes requested, CI failing or a merge conflict) has a button for its next step: Address comments, Fix CI or Resolve conflict. Beside it is the folder Claude would work in: this folder when this session holds a clone of the repository, the folder of the last session that ran in it, or no local clone. The button adds the card the way Review with Claude does. When you close the drawer, the request names the step and the gh commands that read the comments or the failing logs, and asks Claude to work in a new worktree, leaving that folder's branch alone. With no known folder, Claude asks where your clone is, or offers gh repo clone and waits for your yes. No extra GitHub calls and no model calls.

Assigned & mentioned

Open issues assigned to you, and open issues and PRs that mention you; an item that is both shows once, as assigned. Below them, other issues and PRs from the last 30 days that referenced one of yours, with who did it. References you made yourself are left out, and only the newest 20 are shown. No model calls.

Items are grouped into assigned, mentions and references. Hide hides an item until it has new activity.

My issues: assigned issues, mentions, and references to your work from elsewhere

An issue assigned to you has a Work on this button that works the same way: Claude reads the issue, plans the change and starts on a new branch in a new worktree.

Saved searches

GitHub searches you name and save, each a section with its count and the 20 most recently updated matches. A title opens that PR or issue on GitHub, and N more on GitHub opens the whole search there. Three come built in, as in GitHub's own pull request inbox: Involves me (open PRs you take part in but did not open), Reviewed by me, still open and My open issues. Press a section's header to fold it. The searches run with every refresh, three at a time; one that fails shows why and leaves the others alone. No model calls.

Add your own under groups in the same actions.json as the card buttons; /review-inbox add-search asks Claude to write one with you.

{
  "groups": [
    { "id": "team", "name": "Team PRs", "query": "org:acme is:open label:urgent", "scope": "prs", "countInBand": true },
    { "id": "reviewed-by-me", "hidden": true }
  ]
}

query is GitHub search syntax. scope is prs or issues: it adds is:pr or is:issue unless the query already says which, and sort:updated-desc is added unless the query has its own sort:. The scope setting and This repo do not narrow these searches, so write org: or repo: into the query when you want that. "countInBand": true adds the search's count to the band as Saved searches N. A saved search with a built-in id replaces it, and "hidden": true removes it. An entry with a missing field or an unknown scope is left out; the drawer warns about it at the bottom, and /review-inbox buttons lists it with the reason. Only the first 15 saved searches run.

Notifications

Your GitHub notifications that no other tab already shows, in a section per reason (Comment, State changed, CI run and so on), newest first in each; press a section's header to fold it. They are comments, state changes and new activity on threads you opened or take part in, team mentions and security alerts. Finished GitHub Actions runs you started show too, as CI run, linked to the repository's Actions page; GitHub sends them only while Actions notifications are on for GitHub, under Notifications → System → Actions in your GitHub settings. Review requests, assignments and mentions are left out, as are threads whose PR or issue is already a card. An unread thread is marked ●, and the tab's number counts them. Up to 100 notifications from the last 30 days are read.

Done and Unsubscribe take the row away at once and leave Done · Undo or Unsubscribed · Undo in its place for 10 seconds; closing the drawer before then sends them right away. Then Done marks the thread done on GitHub, as GitHub's own inbox does, and Unsubscribe also stops its notifications until someone mentions you or you comment. A thread marked done comes back when it has new activity. If either fails, the row comes back with the reason. No model calls.

GitHub gives notifications only to gh's own sign-in and to classic tokens. Without access, the tab says so and how to get it (gh auth login, or gh auth refresh -s notifications).

Toasts

A new review request, a new review on one of your PRs, one of your PRs turning to changes requested, CI failing or conflicting, and a new assignment, mention or reference. A new session does not announce these one by one: one toast sums up what changed since a session last looked, such as While you were away · CI failing 2, and stays quiet when nothing did. When several arrive at once, they show one after another, 4.5 seconds apart.

Your PR turning approved with no CI running shows Ready to merge once.

Three toasts in turn below the prompt: a new review request, changes requested on your PR, and a new mention

Card buttons

▸ Actions on a card opens Note and Hide, then buttons that each hand the card to Claude with a ready-made request: Summarize risks, Explain this diff and Draft approval comment on a review request, Draft reply to reviewer and Investigate CI failure on your PR. A button adds the card the way Review with Claude does, and the request goes into your prompt when you close the drawer. Nothing runs and nothing is posted until you press Enter.

Add your own in actions.json in the cache folder. /review-inbox buttons shows its path, what it holds and any entry left out, and /review-inbox add-button asks Claude to write one with you.

{
  "buttons": [
    { "id": "test-plan", "name": "Test plan", "scope": "review", "prompt": "Write a test plan for {{.PrUrl}} in {{.RepoPath}}." },
    { "id": "draft-approval", "scope": "review", "hidden": true }
  ]
}

scope is review, pr or issue. The prompt can use RepoName, RepoPath, PrNumber, PrUrl, PrTitle, Author, HeadRefName, BaseRefName, IssueNumber, IssueTitle, IssueUrl, written {{.Name}}, {{Name}}, {{ .Name }} as in gh-dash; one the card has no value for is left empty. A button with a built-in id replaces it, and "hidden": true removes it. An entry with a missing field, an unknown scope or an unknown variable is left out; the drawer warns about it at the bottom, and /review-inbox buttons lists it with the reason. The rest keep working. PrTitle and Author come from GitHub as written, so a prompt that uses them passes someone else's text to Claude.

Direct GitHub actions

With directActions set to on, cards also get buttons that write to GitHub themselves, as your gh account.

  • Approve on a review request, Ready for review on your draft PR, and Update branch on your PR when its base branch has moved ahead. Others see these and they cannot be taken back, so the first press turns the row into a line naming what will be sent and as whom, such as Approve o/r#5 "Fix login" as kim — (no comment). Confirm approve sends it, as does y while the drawer has the keys; Cancel, or ten seconds, brings the buttons back. The focus moves to Cancel, and a confirm within 300 ms of the first press is ignored, so a held Enter sends nothing.
  • An approval has no comment and names the commit you looked at. If new commits arrived since, it is not sent and the card says so. Update branch merges the base branch in and never rebases.
  • Rerun failed CI on your PR with failing checks reruns the failed jobs of the GitHub Actions runs on its latest commit. Assign me on an issue that mentions you is sent at once, with Undo for ten seconds.
  • A write that fails stays on the card with GitHub's message, and its button comes back.

Nothing merges directly. Your approved PR with no checks running gets a Merge button, with directActions off too: it adds a request to your prompt to check the repository's merge methods and run gh pr merge, which you send with Enter and Claude Code asks permission to run.

Language

The band, the drawer, the toasts, the review request put into your prompt, and the summaries and review-style description the model writes all use one language.

CodeLanguage
enEnglish
koKorean (한국어)
jaJapanese (日本語)
zh-CNSimplified Chinese (简体中文)
zh-TWTraditional Chinese (繁體中文)
esSpanish (Español)
pt-BRBrazilian Portuguese (Português do Brasil)
deGerman (Deutsch)
frFrench (Français)
  • A code picks that language.
  • auto (the default) follows Claude Code's own language setting when it names one of these, by code, English name or its own name (ja-JP, Japanese, 日本語). Otherwise it follows the system locale (LC_ALL, LC_MESSAGES, then LANG), and otherwise English. Chinese is read as Simplified unless it is marked as Taiwan, Hong Kong, Macau or Traditional (zh-TW, zh-Hant, 繁體中文), and Portuguese as Brazilian.

Summaries and the description of your review style are kept per language, so switching writes each summary, and that description, once more in the new language. Any other language falls back to English.

Languages other than English and Korean were translated with Claude and have not been checked by native speakers yet. Corrections are welcome as an issue or a pull request: each language is one file in hooks/locales/, and the English table, which every other table follows, is in hooks/i18n.ts.

What it reads and runs

The mod reaches GitHub only through your own gh, sends PR text to Claude to write the summaries and, once a week, your own review comments to describe your style, and writes only to its own cache folder. Below is each thing it touches and why; it matches what claude plugin validate . lists for the mod.

reach

  • Runs gh: gh api graphql for the lists and, once a week, for your recent review comments; gh api repos/<owner>/<repo>/compare/<from>...<to> for a re-requested PR, and gh auth token -u <githubUser> when githubUser is set. For the Notifications tab it runs gh api notifications, and gh api -X DELETE notifications/threads/<id> (with /subscription first for Unsubscribe) when you press Done or Unsubscribe. With directActions on, a button you press runs gh api user for your account name and gh api repos/<owner>/<repo>/pulls/<n> to read the head commit, then one of gh api -X POST …/pulls/<n>/reviews (event=APPROVE, commit_id), gh pr ready, gh api -X PUT …/pulls/<n>/update-branch, gh api …/actions/runs?head_sha=<sha>&status=failure with gh api -X POST …/actions/runs/<id>/rerun-failed-jobs, or gh api -X POST/-X DELETE …/issues/<n>/assignees. The mod makes no other network calls of its own.
  • Runs git in the session's folder every 30 seconds: git branch --show-current and git remote -v, to find a session on your PR's branch, and git rev-parse --path-format=absolute --git-common-dir, to remember the main folder of that repository.
  • Asks Claude (the sonnet model) for each summary, sending a PR's repository name, title, description (first 12,000 characters), changed file paths (up to 80) and size; for a re-requested PR, also the first line of each commit message and up to 60 file paths since your last review. This counts against your Claude Code usage. Each PR is summarized once per head commit and language; a summary that fails is tried at most three times per commit. Once a week it also sends your own review comments on up to 30 PRs you recently reviewed, each cut to 500 characters, at most 60 of them and 12,000 characters in all, to describe your review style; with fewer than five, nothing is sent.
  • Writes files only in its cache folder, ~/.claude/plugins/data/review-inbox (CLAUDE_CONFIG_DIR takes the place of ~/.claude when set). inbox-<hash>-f<n>.json holds the lists and summaries; hidden-<hash>.json holds hidden PRs; notes-<hash>.json holds your notes and snoozes, one file per account and scope whatever the language; sessions.json holds each live session's folder name, release of the mod, branch, GitHub remotes and the PR links its prompts held, for every account; repos.json holds the main folder of each GitHub repository a session has run in, for the next-step buttons; style-<hash>.json holds the description of your review style. Each file is written beside itself and moved into place with mv, so a session never reads half of one; where there is no mv, as on Windows, it is written in place. It reads actions.json there if you made one, and never writes it.
  • Reads environment variables: CLAUDE_CONFIG_DIR, HOME and `USERPR
Source 21 files
hooks/register.tsx 1964 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren } from 'claude-code'
3
4import type {
5  Actions,
6  Activity,
7  ButtonScope,
8  Capped,
9  Confirming,
10  DirectAction,
11  DirectResult,
12  DirectTarget,
13  GroupHit,
14  GroupResult,
15  InboxFile,
16  InboxItem,
17  InboxStatus,
18  IssueItem,
19  MyPr,
20  Note,
21  Presence,
22  RepoPaths,
23  SearchGroup,
24  Settling,
25  Tab,
26  Thread,
27} from '../types'
28import { ACTIONS_FILE, MAX_PER_SCOPE, VARIABLES, builtInButtons, errorText, fillTemplate, mergeById, parseActions } from './actions'
29import type { Vars } from './actions'
30import { CONFIRM_GUARD_MS, CONFIRM_MS, canMerge, failedRunsArgs, headArgs, issueActions, needsConfirm, prActions, rerunArgs, reviewActions, writeArgs } from './direct'
31import { ACTIVITY_LIMIT, THREAD_JQ, UNDO_MS, byReason, hasNextPage, isThreadHidden, notificationsPath, pollAfter, shownThreads, splitResponse, threadKey, toThread } from './activity'
32import type { RawThread } from './activity'
33import { GROUP_HITS, GROUP_QUERY, bandSearchCount, groupQuery, resultOf, searchGroups, searchUrl, toHits } from './searches'
34import type { GqlHit } from './searches'
35import {
36  CLAIM_MS,
37  cacheKey,
38  INBOX_FORMAT,
39  INBOX_QUERY,
40  RETRY_MS,
41  ageColor,
42  detailsText,
43  failedSummary,
44  hasRequest,
45  isHidden,
46  isTorn,
47  itemKey,
48  lastReviewedSha,
49  minutesSince,
50  newArrivals,
51  parseSummary,
52  requestedAt,
53  requestedTeam,
54  reusableSummary,
55  reviewPrompts,
56  searchQuery,
57  shouldFetch,
58  shownReady,
59  sincePrompt,
60  sinceRules,
61  sortItems,
62  summaryPrompt,
63  summaryRules,
64  toDetail,
65  waitingDays,
66} from './inbox'
67import type { GqlPr, PrDetail, SearchHit, Summary } from './inbox'
68import { isLanguage, MESSAGES, pickLanguage } from './i18n'
69import { BODY_CHARS, isSnoozed, keptNotes, matches, snoozeUntil } from './notes'
70import { hereFirst, isHere, liveSessions, mainCheckout, mappedPath, olderSessions, parseRepoPaths, placeOf, remember, repoOf, shouldReload, thisRepos, workingOn } from './sessions'
71import type { Place, ReloadRequest } from './sessions'
72import type { Language, Messages } from './i18n'
73import { isGatewayTimeout, readPages, SEARCH_LIMIT } from './pages'
74import type { Page, Pages } from './pages'
75import { STYLE_JQ, STYLE_PRS, STYLE_QUERY, STYLE_RETRY_MS, parseStyle, shouldBuildStyle, stylePrompt, styleQuery, styleRules, styleSamples } from './style'
76import type { GqlReviewed, StyleFile } from './style'
77import {
78  REFERENCES_QUERY,
79  AUTHORED_DAYS,
80  ORDER,
81  REFERENCE_DAYS,
82  REFERENCE_PAGE,
83  TAB_QUERIES,
84  atLeast,
85  BAND_KEYS,
86  bandCounts,
87  bandLabels,
88  droppedCounts,
89  isIssueHidden,
90  isPrHidden,
91  issueAlerts,
92  issueHide,
93  issueHideKey,
94  issueKey,
95  awayText,
96  prAlertText,
97  prAlerts,
98  prHide,
99  prHideKey,
100  prSeenKeys,
101  reviewers,
102  referencesQuery,
103  stateColor,
104  tabQueries,
105  taskOf,
106  taskPrompts,
107  toIssues,
108  toMyPrs,
109  toReferences,
110} from './tabs'
111import type { BandCounts, GqlMyPr, GqlReferenced, GqlTouched, Task } from './tabs'
112
113const PANE = 'review-inbox'
114// Reading the shared file is a local disk read, so every session can afford it often.
115const SYNC_MS = 30_000
116const SUMMARY_MODEL = 'sonnet'
117const MODEL_TIMEOUT_MS = 60_000
118// A toast stays about four seconds and an inline session shows only the latest, so several are shown one after another.
119const TOAST_GAP_MS = 4_500
120
121const items = atom({ plugin: 'review-inbox', key: 'items' } as const, [] as InboxItem[])
122const status = atom({ plugin: 'review-inbox', key: 'status' } as const, {
123  kind: 'idle',
124} as InboxStatus)
125const hidden = atom({ plugin: 'review-inbox', key: 'hidden' } as const, {} as Record<string, string>)
126const mine = atom({ plugin: 'review-inbox', key: 'mine' } as const, [] as MyPr[])
127const issues = atom({ plugin: 'review-inbox', key: 'issues' } as const, [] as IssueItem[])
128const capped = atom({ plugin: 'review-inbox', key: 'capped' } as const, {} as Capped)
129const tab = atom({ plugin: 'review-inbox', key: 'tab' } as const, 'review' as Tab)
130const collapsed = atom({ plugin: 'review-inbox', key: 'collapsed' } as const, [] as string[])
131const notes = atom({ plugin: 'review-inbox', key: 'notes' } as const, {} as Record<string, Note>)
132const query = atom({ plugin: 'review-inbox', key: 'query' } as const, '')
133const editing = atom({ plugin: 'review-inbox', key: 'editing' } as const, '')
134const sessions = atom({ plugin: 'review-inbox', key: 'sessions' } as const, {} as Record<string, Presence>)
135const repos = atom({ plugin: 'review-inbox', key: 'repos' } as const, {} as RepoPaths)
136// The cards whose review request is in the prompt, so pressing Review again adds nothing.
137// PRs Review was pressed on since the drawer opened, filled when it closes; requested ones the draft already asked for when it opened.
138const added = atom({ plugin: 'review-inbox', key: 'added' } as const, [] as string[])
139const requested = atom({ plugin: 'review-inbox', key: 'requested' } as const, [] as string[])
140const onlyHere = atom({ plugin: 'review-inbox', key: 'onlyHere' } as const, false)
141const reloadAsked = atom({ plugin: 'review-inbox', key: 'reloadAsked' } as const, '')
142const dropped = atom({ plugin: 'review-inbox', key: 'dropped' } as const, [] as string[])
143const actions = atom({ plugin: 'review-inbox', key: 'actions' } as const, { buttons: [], groups: [], errors: [] } as Actions)
144const groupResults = atom({ plugin: 'review-inbox', key: 'groups' } as const, {} as Record<string, GroupResult>)
145const activity = atom({ plugin: 'review-inbox', key: 'activity' } as const, { threads: [] } as Activity)
146const settling = atom({ plugin: 'review-inbox', key: 'settling' } as const, {} as Record<string, Settling>)
147const settleErrors = atom({ plugin: 'review-inbox', key: 'settleErrors' } as const, {} as Record<string, string>)
148const more = atom({ plugin: 'review-inbox', key: 'more' } as const, '')
149const seenAt = atom({ plugin: 'review-inbox', key: 'seenAt' } as const, 0)
150const confirming = atom({ plugin: 'review-inbox', key: 'confirming' } as const, null as Confirming | null)
151const directs = atom({ plugin: 'review-inbox', key: 'directs' } as const, {} as Record<string, DirectResult>)
152
153type Options = { scope?: string; githubUser?: string; language?: string; refreshMinutes?: string; repoPaths?: string; motion?: string; directActions?: string }
154
155// A band count that goes down shows in the success color this long; no tween, nothing moves.
156const FLASH_MS = 250
157
158let config = { scope: '', githubUser: '', language: 'en' as Language, refreshMs: 10 * 60_000, repoPaths: {} as Record<string, string>, motion: 'auto', directActions: false }
159// Off by the motion option, or under auto by Claude Code's prefersReducedMotion setting.
160let isStill = false
161let lastBand: BandCounts | undefined
162// GH_REPO, which gh itself treats as the current repository.
163let ghRepo: string | undefined
164// Where actions.json lives, shown by /review-inbox buttons.
165let actionsPath = ''
166// A press of a card's own button is added as the card's key and the button's id.
167const buttonKey = (key: string, id: string) => `${key}::${id}`
168// The Merge button fills the prompt like a card's own button, under an id actions.json cannot give one.
169const MERGE = '@merge'
170let languageOption: string | undefined
171let m: Messages = MESSAGES.en
172let isFetching = false
173let terminalColumns = 160
174// What this session has already shown; undefined until its first look, which compares with the last session's instead.
175let shownKeys: string[] | undefined
176let shownPrKeys: string[] | undefined
177let shownIssueKeys: string[] | undefined
178// What any session last saw, shared through shownFile, and what this one last wrote there.
179type Shown = { reviews?: string[]; prs?: string[]; issues?: string[] }
180let shownWritten = ''
181let shownSnoozed: string[] | undefined
182// What the open note field holds; a button beside it saves this.
183let draft = ''
184// A button's or a command's dispatch ends before a fetch would, so they only ask; the session's timer does it.
185let wanted: 'sync' | 'fetch' | undefined
186let toastFreeAt = 0
187const sessionToken = Math.random().toString(36).slice(2)
188// The session's own id, which a reload keeps, and the PRs its prompts linked to.
189let selfId = ''
190// When this load of the module started; a reload request older than this is not for it.
191let loadedAt = 0
192let linked: string[] = []
193// This session's release, from plugin.json, so other sessions can tell it is current.
194let version: string | undefined
195// Shortens the folders shown on cards to ~.
196let home = ''
197
198// Claude Code's per-plugin data folder; a mod is not told its id, so it falls back to a fixed name there.
199async function cacheDir($: EngineInterface) {
200  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
201  const configDir = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home ? `${home}/.claude` : undefined)
202  // Without it a relative path would land inside whatever repo the session is in.
203  if (!configDir) throw new Error('neither HOME nor USERPROFILE is set')
204  return `${configDir}/plugins/data/review-inbox`
205}
206
207// undefined when the file exists but does not parse: another session may be mid-write, so skip this look.
208// One that stays unparsable was cut short, by a crash or an older version of the mod; it reads as missing so the next write replaces it.
209async function readJson<T>($: EngineInterface, name: string, missing: T): Promise<T | undefined> {
210  const path = `${await cacheDir($)}/${name}`
211  if (!(await $.fs.exists(path))) return missing
212  try {
213    return JSON.parse(await $.fs.read(path)) as T
214  } catch {
215    const stat = await $.fs.stat(path).catch(() => undefined)
216    return stat !== undefined && isTorn(stat.mtimeMs, Date.now()) ? missing : undefined
217  }
218}
219
220// Whether mv runs here; Windows has none, so the file is written in place there.
221let canMove: Promise<boolean> | undefined
222
223async function writeJson($: EngineInterface, name: string, value: unknown) {
224  const path = `${await cacheDir($)}/${name}`
225  const text = JSON.stringify(value)
226  canMove ??= $.process.run(['mv']).then(() => true, () => false)
227  if (await canMove) {
228    // Written aside and moved over, so a reader never sees half a file.
229    const temp = `${path}.${sessionToken}.tmp`
230    await $.fs.write(temp, text)
231    if ((await $.process.run(['mv', '-f', temp, path])).exitCode === 0) return
232  }
233  await $.fs.write(path, text)
234}
235
236// One shared file per account, scope and language, so sessions configured differently never overwrite each other
237// and a summary is never shown in another language than the cards around it.
238const inboxFile = () => `inbox-${cacheKey(config.githubUser, config.scope, config.language)}-f${INBOX_FORMAT}.json`
239// Keyed like the inbox: a hide prunes the entries its own list no longer has, so it must not share a file with another list.
240const hiddenFile = () => `hidden-${cacheKey(config.githubUser, config.scope, config.language)}.json`
241// Not keyed by language: a note I wrote stays when the language changes.
242const notesFile = () => `notes-${cacheKey(config.githubUser, config.scope)}.json`
243// Not keyed by language either: the last close of the drawer is the same whatever it was drawn in.
244const seenFile = () => `seen-${cacheKey(config.githubUser, config.scope)}.json`
245// Card keys carry no language, so the news a session announced holds whatever the language.
246const shownFile = () => `shown-${cacheKey(config.githubUser, config.scope)}.json`
247const styleFile = () => `style-${cacheKey(config.githubUser, config.scope, config.language)}.json`
248// One for every account: a session's branch and links say nothing about who is signed in.
249const SESSIONS_FILE = 'sessions.json'
250const RELOAD_FILE = 'reload.json'
251// Also one for every account: a folder holds the same repository whoever is signed in.
252const REPOS_FILE = 'repos.json'
253
254async function resolveLanguage($: EngineInterface): Promise<Language> {
255  const read = async <T,>(get: () => Promise<T>) => {
256    try {
257      return await get()
258    } catch {
259      // A policy can refuse any call; the language then falls through to the next source.
260      return undefined
261    }
262  }
263  if (isLanguage(languageOption)) return languageOption
264  // Only the one key: the settings also hold env values and credentials helpers.
265  const claudeLanguage = await read(async () => (await $.settings.read()).language)
266  const locale = await read(
267    async () => (await $.env.get('LC_ALL')) || (await $.env.get('LC_MESSAGES')) || (await $.env.get('LANG')),
268  )
269  return pickLanguage(languageOption, claudeLanguage, locale)
270}
271
272async function gh($: EngineInterface, args: string[], env: Record<string, string>) {
273  const run = await $.process.run(['gh', ...args], { env, timeoutMs: 120_000 })
274  if (run.exitCode !== 0) throw new Error(run.stderr.trim().split('\n')[0] || `gh ${args[0]} failed`)
275  if (run.isStdoutTruncated) throw new Error(`gh ${args[0]} output too large`)
276  return run.stdout
277}
278
279async function ask($: EngineInterface, rules: string, prompt: string, maxTokens: number) {
280  try {
281    // Rules go first in `prompt`, marked: that is where every provider's prompt cache finds them.
282    const reply = await $.model.complete({
283      model: SUMMARY_MODEL,
284      prompt: [{ text: rules, cache: true }, { text: prompt }],
285      maxTokens,
286      timeoutMs: MODEL_TIMEOUT_MS,
287    })
288    return reply.isAnswered ? { text: reply.text } : { reason: reply.reason }
289  } catch (error) {
290    // A model this setup blocks rejects instead of answering.
291    return { reason: error instanceof Error ? error.message : String(error) }
292  }
293}
294
295async function summarize(
296  $: EngineInterface,
297  hit: SearchHit,
298  detail: PrDetail,
299  prev: InboxItem | undefined,
300): Promise<Summary> {
301  const reply = await ask($, summaryRules(config.language), summaryPrompt(hit, detail), 800)
302  const parsed = reply.text !== undefined ? parseSummary(reply.text) : undefined
303  return parsed ?? failedSummary(hit.title, reply.reason ?? 'unreadable reply', prev, detail.headRefOid, m)
304}
305
306// A failed comparison (a force-push rewrote the reviewed commit) just leaves the line out.
307async function summarizeSince(
308  $: EngineInterface,
309  repo: string,
310  from: string,
311  to: string,
312  env: Record<string, string>,
313): Promise<string | undefined> {
314  try {
315    const diff = JSON.parse(
316      await gh(
317        $,
318        ['api', `repos/${repo}/compare/${from}...${to}`, '--jq',
319          '{commits: [.commits[].commit.message], files: [.files[].filename]}'],
320        env,
321      ),
322    ) as { commits: string[]; files: string[] }
323    const reply = await ask($, sinceRules(config.language), sincePrompt(diff.commits, diff.files), 300)
324    return reply.text?.trim() || undefined
325  } catch {
326    return undefined
327  }
328}
329
330// One search, read a page at a time; `jq` cuts each page below gh's output cap.
331function searchAll<T>($: EngineInterface, query: string, vars: Record<string, string>, env: Record<string, string>, limit: number, jq = '.data', pageSize?: number) {
332  const fields = Object.entries(vars).flatMap(([name, value]) => ['-f', `${name}=${value}`])
333  return readPages<T>(
334    async (first, after) =>
335      JSON.parse(
336        await gh($, ['api', 'graphql', '-f', `query=${query}`, ...fields, '-F', `first=${first}`, ...(after ? ['-f', `after=${after}`] : []), '--jq', jq], env),
337      ) as Page<T>,
338    limit,
339    pageSize,
340  )
341}
342
343// Lists fetched so far, merged into the claimed file as each one arrives.
344type Save = (lists: Partial<InboxFile>) => Promise<void>
345
346const trimBodies = (chars: number) => `.data | .search.nodes |= map(if .body then .body |= .[:${chars}] else . end)`
347
348async function ghEnv($: EngineInterface): Promise<Record<string, string>> {
349  if (!config.githubUser) return {}
350  return { GH_TOKEN: (await gh($, ['auth', 'token', '-u', config.githubUser], {})).trim() }
351}
352
353async function fetchTabs(
354  $: EngineInterface,
355  env: Record<string, string>,
356  previous: IssueItem[],
357  save: Save,
358): Promise<{ mine: MyPr[]; issues: IssueItem[]; capped: Capped }> {
359  const q = tabQueries(config.scope)
360  const tabSearch = <T,>(key: keyof typeof q): Promise<Pages<T>> => searchAll($, TAB_QUERIES[key], { q: q[key] }, env, SEARCH_LIMIT, trimBodies(BODY_CHARS))
361  const [minePrs, assigned, mentioned] = await Promise.all([tabSearch<GqlMyPr>('mine'), tabSearch<GqlTouched>('assigned'), tabSearch<GqlTouched>('mentioned')])
362  const me = minePrs.login ?? assigned.login ?? ''
363  const real = <T,>(nodes: Partial<T & { number: number }>[]) =>
364    nodes.filter((n): n is T & { number: number } => typeof n.number === 'number')
365  const mine = toMyPrs(real<GqlMyPr>(minePrs.nodes), me)
366  const withReferences = (references: IssueItem[]) => toIssues(real<GqlTouched>(assigned.nodes), real<GqlTouched>(mentioned.nodes), references)
367  const capped = { mine: minePrs.capped, issues: assigned.capped || mentioned.capped }
368  const lastReferences = previous.filter(i => i.kind === 'reference')
369  // References are the slowest search, so the other lists show first, beside the last references.
370  await save({ mine, issues: withReferences(lastReferences), capped })
371
372  const since = new Date(Date.now() - REFERENCE_DAYS * 86_400_000).toISOString()
373  const touchedSince = new Date(Date.now() - AUTHORED_DAYS * 86_400_000).toISOString()
374  let references: IssueItem[]
375  try {
376    // ponytail: at most 500 items touched in the window, newest first; past that the rest are left out
377    const referenced: Pages<GqlReferenced> = await searchAll($, REFERENCES_QUERY, { q: referencesQuery(config.scope, touchedSince), since }, env, 500, '.data', REFERENCE_PAGE)
378    references = toReferences(real<GqlReferenced>(referenced.nodes), me)
379  } catch {
380    // References are the costliest search; when GitHub refuses it, keep the last ones instead of failing every tab.
381    references = lastReferences
382  }
383
384  return { mine, issues: withReferences(references), capped }
385}
386
387async function fetchInbox(
388  $: EngineInterface,
389  env: Record<string, string>,
390  previous: InboxItem[],
391  heartbeat: () => Promise<void>,
392): Promise<{ items: InboxItem[]; capped: boolean }> {
393  const found: Pages<GqlPr> = await searchAll($, INBOX_QUERY, { q: searchQuery(config.scope) }, env, SEARCH_LIMIT, trimBodies(12_000))
394  const me = found.login ?? ''
395  // Search can return non-PR nodes as empty objects.
396  const prs = found.nodes.filter((n): n is GqlPr => typeof n.number === 'number')
397  const before = new Map(previous.map(i => [itemKey(i), i]))
398
399  const next: InboxItem[] = []
400  // ponytail: fixed batches of 3 model calls; a work queue only matters past a few dozen PRs
401  for (let i = 0; i < prs.length; i += 3) {
402    const batch = await Promise.all(
403      prs.slice(i, i + 3).map(async pr => {
404        const repo = pr.repository.nameWithOwner
405        const prev = before.get(`${repo}#${pr.number}`)
406        const detail = toDetail(pr)
407        const head = pr.headRefOid
408        const summary = reusableSummary(prev, head) ?? (await summarize($, pr, detail, prev))
409        const reviewedSha = lastReviewedSha(detail.reviews, me)
410        const team = requestedTeam(detail.reviewRequests, me)
411        const sinceLastReview =
412          !reviewedSha || reviewedSha === head
413            ? undefined
414            : prev?.headSha === head && prev.reviewedSha === reviewedSha
415              ? prev.sinceLastReview
416              : await summarizeSince($, pr.repository.nameWithOwner, reviewedSha, head, env)
417        return {
418          repo,
419          number: pr.number,
420          title: pr.title,
421          url: pr.url,
422          headSha: head,
423          isRerequest: reviewedSha !== undefined,
424          ...(reviewedSha ? { reviewedSha } : {}),
425          ...(sinceLastReview ? { sinceLastReview } : {}),
426          ...(pr.body ? { body: pr.body.slice(0, BODY_CHARS) } : {}),
427          author: pr.author?.login ?? 'ghost',
428          createdAt: pr.createdAt,
429          ...(pr.updatedAt ? { updatedAt: pr.updatedAt } : {}),
430          requestedAt: requestedAt(pr, me),
431          isDraft: pr.isDraft,
432          ...(team ? { team } : {}),
433          files: pr.changedFiles,
434          additions: pr.additions,
435          deletions: pr.deletions,
436          ...summary,
437        } satisfies InboxItem
438      }),
439    )
440    next.push(...batch)
441    await heartbeat()
442  }
443  return { items: sortItems(next), capped: found.capped }
444}
445
446// Each group is its own paged search, three at a time; one that fails keeps its error and leaves the others.
447async function fetchGroups($: EngineInterface, env: Record<string, string>): Promise<Record<string, GroupResult>> {
448  // Read here too: the fetching session may have opened no drawer since the file changed.
449  await loadActions($)
450  const { groups } = searchGroups(m, (await read($, actions)).groups)
451  const results: Record<string, GroupResult> = {}
452  for (let i = 0; i < groups.length; i += 3) {
453    await Promise.all(
454      groups.slice(i, i + 3).map(async group => {
455        const q = groupQuery(group)
456        try {
457          const found: Pages<GqlHit> = await searchAll($, GROUP_QUERY, { q }, env, GROUP_HITS)
458          results[group.id] = { query: q, count: found.count ?? found.nodes.length, hits: toHits(found.nodes) }
459        } catch (error) {
460          const message = error instanceof Error ? error.message : String(error)
461          results[group.id] = { query: q, count: 0, hits: [], error: isGatewayTimeout(message) ? m.status.timeout : message }
462        }
463      }),
464    )
465  }
466  return results
467}
468
469// The notifications, newest first; GitHub's poll interval or an unchanged list (a 304) keeps the last ones.
470async function fetchActivity($: EngineInterface, env: Record<string, string>, prev: Activity | undefined): Promise<Activity> {
471  const now = Date.now()
472  if (prev?.pollAfter !== undefined && now < prev.pollAfter) return prev
473  const threads: Thread[] = []
474  let first: Record<string, string> = {}
475  const unchanged = prev?.lastModified && !prev.error && !prev.noAccess ? ['-H', `If-Modified-Since: ${prev.lastModified}`] : []
476  try {
477    for (let page = 1; threads.length < ACTIVITY_LIMIT; page++) {
478      const { headers, body } = splitResponse(await gh($, ['api', '-i', ...(page === 1 ? unchanged : []), notificationsPath(page, now), '--jq', THREAD_JQ], env))
479      if (page === 1) first = headers
480      threads.push(...(JSON.parse(body || '[]') as RawThread[]).map(toThread))
481      if (!hasNextPage(headers)) break
482    }
483  } catch (error) {
484    const message = error instanceof Error ? error.message : String(error)
485    // A 304 has no body, so gh's --jq fails on it before gh reports the status.
486    if (prev && unchanged.length > 0 && /HTTP 304|unexpected end of JSON input/.test(message)) return prev
487    if (/HTTP 40[34]/.test(message)) return { threads: [], noAccess: true }
488    return { threads: prev?.threads ?? [], error: isGatewayTimeout(message) ? m.status.timeout : message }
489  }
490  const lastModified = first['last-modified']
491  const after = pollAfter(first, now)
492  return { threads: threads.slice(0, ACTIVITY_LIMIT), ...(lastModified ? { lastModified } : {}), ...(after ? { pollAfter: after } : {}) }
493}
494
495const without = <T,>(record: Record<string, T>, key: string) => Object.fromEntries(Object.entries(record).filter(([k]) => k !== key))
496
497// Done or Unsubscribe pressed: the row waits out its Undo, then this sends it.
498async function settleLater($: EngineInterface, thread: Thread, kind: Settling['kind']) {
499  const at = Date.now()
500  await update($, settleErrors, errors => without(errors, thread.id))
501  await update($, settling, s => ({ ...s, [thread.id]: { kind, at } }))
502  $.clock.after(UNDO_MS, () => void settle($, thread.id, at))
503}
504
505const sending = new Set<string>()
506
507// `at` is the press the timer belongs to; the drawer's close sends every pending one without it. A failure brings the row back with the error.
508async function settle($: EngineInterface, id: string, at?: number) {
509  const pending = (await read($, settling))[id]
510  if (!pending || (at !== undefined && pending.at !== at) || sending.has(id)) return
511  sending.add(id)
512  try {
513    const env = await ghEnv($)
514    if (pending.kind === 'unsubscribe') await gh($, ['api', '-X', 'DELETE', `notifications/threads/${id}/subscription`], env)
515    await gh($, ['api', '-X', 'DELETE', `notifications/threads/${id}`], env)
516    const thread = (await read($, activity)).threads.find(t => t.id === id)
517    if (thread) await setHidden($, hideMap => ({ ...hideMap, [threadKey(thread)]: thread.updatedAt }))
518  } catch (error) {
519    await update($, settleErrors, errors => ({ ...errors, [id]: error instanceof Error ? error.message : String(error) }))
520  } finally {
521    sending.delete(id)
522    await update($, settling, s => without(s, id))
523  }
524}
525
526// Who a write goes out as, named on its confirm row: the configured account, else gh's active one.
527let login: Promise<string> | undefined
528function loginName($: EngineInterface) {
529  login ??= ghEnv($).then(env => gh($, ['api', 'user', '--jq', '.login'], env)).then(text => text.trim())
530  // A failed look is tried again at the next press.
531  login.catch(() => (login = undefined))
532  return login
533}
534
535const setDirect = ($: EngineInterface, key: string, result: DirectResult | undefined) =>
536  update($, directs, d => (result ? { ...d, [key]: result } : without(d, key)))
537
538// A write others see asks first, on the card; the focus goes to Cancel, so a stray Enter does nothing.
539async function pressDirect($: EngineInterface, key: string, action: DirectAction, target: DirectTarget) {
540  if (!needsConfirm(action)) return sendDirect($, key, action, target)
541  const at = await $.clock.now()
542  await setDirect($, key, undefined)
543  await update($, confirming, () => ({ key, action, target, at }))
544  void $.ui.focus({ requestId: PANE, key: `direct-cancel-${key}` }).catch(() => undefined)
545  $.clock.after(CONFIRM_MS, () => void update($, confirming, c => (c?.at === at ? null : c)))
546  const name = await loginName($).catch(() => '')
547  await update($, confirming, c => (c?.at === at ? { ...c, login: name } : c))
548}
549
550async function confirmDirect($: EngineInterface) {
551  const asking = await read($, confirming)
552  if (!asking || (await $.clock.now()) - asking.at < CONFIRM_GUARD_MS) return
553  await update($, confirming, () => null)
554  await sendDirect($, asking.key, asking.action, asking.target)
555}
556
557// The mod's own refusal, shown as it is rather than as GitHub's.
558class Refused extends Error {}
559const writing = new Set<string>()
560
561// The card shows the write going, then how it went; a failure stays on the card until the next press.
562async function sendDirect($: EngineInterface, key: string, action: DirectAction, target: DirectTarget) {
563  if (writing.has(key)) return
564  writing.add(key)
565  await setDirect($, key, { action, phase: 'sending', at: Date.now() })
566  try {
567    const env = await ghEnv($)
568    // GitHub takes an approval of an older commit, so a head that moved since I looked stops it here.
569    if ((action === 'approve' || action === 'update-branch') && (await gh($, headArgs(target), env)).trim() !== target.sha) {
570      throw new Refused(m.direct.newCommits)
571    }
572    if (action === 'rerun') {
573      const runs = (await gh($, failedRunsArgs(target), env)).split('\n').filter(Boolean)
574      if (runs.length === 0) throw new Refused(m.direct.noRun)
575      for (const run of runs) await gh($, rerunArgs(target, run), env)
576    } else {
577      await gh($, writeArgs(action, target, action === 'assign' ? await loginName($) : ''), env)
578    }
579    const at = Date.now()
580    await setDirect($, key, { action, phase: 'done', at, ...(action === 'assign' ? { undo: true } : {}) })
581    $.ui.toast(`${m.direct.done[action]} · ${target.repo} #${target.number}`)
582    if (action !== 'assign') wanted = 'fetch'
583    // Fetched only once the Undo is gone: the card would move to Assigned and take its Undo with it.
584    else
585      $.clock.after(UNDO_MS, async () => {
586        await update($, directs, d => {
587          const result = d[key]
588          return result?.at === at ? { ...d, [key]: { ...result, undo: false } } : d
589        })
590        wanted = 'fetch'
591      })
592  } catch (error) {
593    const message = error instanceof Refused ? error.message : m.direct.failed(error instanceof Error ? error.message : String(error))
594    await setDirect($, key, { action, phase: 'failed', at: Date.now(), message })
595  } finally {
596    writing.delete(key)
597  }
598}
599
600// Assign me is the one write with an opposite, so its Undo really takes it back.
601async function undoAssign($: EngineInterface, key: string, target: DirectTarget) {
602  try {
603    await gh($, writeArgs('assign', target, await loginName($), true), await ghEnv($))
604    await setDirect($, key, undefined)
605  } catch (error) {
606    await setDirect($, key, { action: 'assign', phase: 'failed', at: Date.now(), message: m.direct.failed(error instanceof Error ? error.message : String(error)) })
607  }
608}
609
610function toast($: EngineInterface, text: string) {
611  const now = Date.now()
612  const at = Math.max(now, toastFreeAt)
613  toastFreeAt = at + TOAST_GAP_MS
614  if (at === now) $.ui.toast(text)
615  else $.clock.after(at - now, () => $.ui.toast(text))
616}
617
618// Run by the session that just fetched; a failure keeps the last style and tries again a day later.
619async function refreshStyle($: EngineInterface, env: Record<string, string>) {
620  const file = await readJson($, styleFile(), {} as StyleFile)
621  if (file === undefined || !shouldBuildStyle(file, Date.now())) return
622  try {
623    const reviewed: Pages<GqlReviewed> = await searchAll($, STYLE_QUERY, { q: styleQuery(config.scope) }, env, STYLE_PRS, STYLE_JQ)
624    const samples = styleSamples(reviewed.nodes, reviewed.login ?? '')
625    const prompt = stylePrompt(samples)
626    if (prompt === undefined) {
627      await writeJson($, styleFile(), { checkedAt: Date.now(), samples: samples.length } satisfies StyleFile)
628      return
629    }
630    const reply = await ask($, styleRules(config.language), prompt, 400)
631    const profile = reply.text === undefined ? undefined : parseStyle(reply.text)
632    if (profile === undefined) throw new Error(reply.reason ?? 'empty reply')
633    await writeJson($, styleFile(), { profile, checkedAt: Date.now(), samples: samples.length } satisfies StyleFile)
634  } catch {
635    await writeJson($, styleFile(), { ...file, retryAt: Date.now() + STYLE_RETRY_MS } satisfies StyleFile).catch(() => undefined)
636  }
637}
638
639// Every session runs this; only the one that finds the shared file stale and wins the claim goes to GitHub.
640async function sync($: EngineInterface, force = false) {
641  const file = await readJson($, inboxFile(), { items: [] } as InboxFile)
642  if (file === undefined) return
643  if (isFetching || !shouldFetch(file, Date.now(), force, config.refreshMs)) return show($, file)
644
645  isFetching = true
646  try {
647    // Sessions started together all see the file stale; the last claim written wins, the others back off.
648    const claim = { ...file, fetchingSince: Date.now(), fetchingBy: sessionToken }
649    await writeJson($, inboxFile(), claim)
650    await $.clock.sleep(500)
651    const settled = await readJson($, inboxFile(), { items: [] } as InboxFile)
652    if (settled?.fetchingBy !== sessionToken) return
653    await show($, claim)
654
655    // Each list is written as it arrives, which also renews the claim; writes go in order, and none after the fetch ends.
656    let partial: InboxFile = claim
657    let saving = Promise.resolve()
658    let isDone = false
659    const save: Save = lists => {
660      if (isDone) return saving
661      partial = { ...partial, ...lists, capped: { ...partial.capped, ...lists.capped }, fetchingSince: Date.now() }
662      const next = partial
663      // shortcut: a list write that fails is skipped; the final write below still lands, or the fetch fails as before
664      saving = saving
665        .then(async () => {
666          await writeJson($, inboxFile(), next)
667          await show($, next)
668        })
669        .catch(() => undefined)
670      return saving
671    }
672
673    let result: InboxFile
674    let env: Record<string, string> | undefined
675    try {
676      env = await ghEnv($)
677      const [tabs, groups, notifications, fetched] = await Promise.all([
678        fetchTabs($, env, file.issues ?? [], save),
679        fetchGroups($, env).then(async found => (await save({ groups: found }), found)),
680        fetchActivity($, env, file.activity).then(async found => (await save({ activity: found }), found)),
681        fetchInbox($, env, file.items, () => save({})).then(async found => (await save({ items: found.items }), found)),
682      ])
683      result = { items: fetched.items, ...tabs, groups, activity: notifications, capped: { ...tabs.capped, review: fetched.capped }, fetchedAt: Date.now() }
684    } catch (error) {
685      const raw = error instanceof Error ? error.message : String(error)
686      const message = isGatewayTimeout(raw) ? m.status.timeout : raw
687      // Keep the lists this fetch did get, the last good ones otherwise, and try again in a minute, not after a full refresh interval.
688      result = { items: partial.items, mine: partial.mine, issues: partial.issues, groups: partial.groups, activity: partial.activity, capped: partial.capped, fetchedAt: file.fetchedAt ?? Date.now(), retryAt: Date.now() + RETRY_MS, error: message }
689    }
690    isDone = true
691    await saving
692    await writeJson($, inboxFile(), result)
693    await show($, result)
694    if (env !== undefined && result.error === undefined) await refreshStyle($, env)
695  } finally {
696    isFetching = false
697  }
698}
699
700async function show($: EngineInterface, file: InboxFile) {
701  const claimed = file.fetchingSince !== undefined && Date.now() - file.fetchingSince < CLAIM_MS
702  // A file written by an older version of the mod, in this or another session, lacks newer fields;
703  // a missing list keeps what is shown rather than blanking a tab.
704  const prs = file.mine?.map(pr => ({ ...pr, newReviews: pr.newReviews ?? [] }))
705  const issueList = file.issues
706  await update($, items, () => file.items)
707  if (prs) await update($, mine, () => prs)
708  if (issueList) await update($, issues, () => issueList)
709  await update($, capped, () => file.capped ?? {})
710  const groupList = file.groups
711  if (groupList) await update($, groupResults, () => groupList)
712  const notifications = file.activity
713  if (notifications) await update($, activity, () => notifications)
714  await update($, status, () =>
715    claimed
716      ? { kind: 'loading' as const, updatedAt: file.fetchedAt }
717      : file.error
718        ? { kind: 'error' as const, message: file.error, updatedAt: file.fetchedAt }
719        : { kind: 'ready' as const, updatedAt: file.fetchedAt },
720  )
721  const hiddenNow = await readJson($, hiddenFile(), {} as Record<string, string>)
722  if (hiddenNow !== undefined) await update($, hidden, () => hiddenNow)
723  const notesNow = await readJson($, notesFile(), {} as Record<string, Note>)
724  if (notesNow !== undefined) await update($, notes, () => notesNow)
725
726  // An empty file from before the first fetch, or an error result, must not become the baseline, or everything reads as new.
727  if (claimed || file.fetchedAt === undefined || file.error !== undefined) return
728  // A session's first look compares with what the last session saw, and sums up in one toast what changed while none was open.
729  const isFirstLook = shownKeys === undefined
730  // A stale file is about to be fetched again; taking it as the baseline would announce its news one by one after the fetch.
731  if (isFirstLook && Date.now() - file.fetchedAt > config.refreshMs) return
732  const last = isFirstLook ? await readJson($, shownFile(), {} as Shown) : undefined
733  const fresh = newArrivals(shownKeys ?? last?.reviews, file.items)
734  const prNews = prs ? prAlerts(shownPrKeys ?? last?.prs, prs) : []
735  const newIssues = issueList ? issueAlerts(shownIssueKeys ?? last?.issues, issueList) : []
736  if (isFirstLook) {
737    const text = awayText(fresh.length, prNews, newIssues, m)
738    if (text) toast($, text)
739  } else {
740    for (const item of fresh.slice(0, 3)) {
741      toast($, `${m.toast.newRequest} · ${item.repo} #${item.number} · ${item.summary}`)
742    }
743    if (fresh.length > 3) toast($, m.toast.moreRequests(fresh.length - 3))
744    for (const alert of prNews.slice(0, 3)) toast($, prAlertText(alert, m))
745    if (prNews.length > 3) toast($, m.toast.morePrAlerts(prNews.length - 3))
746    for (const issue of newIssues.slice(0, 3)) {
747      toast($, `${m.issueKind[issue.kind]} · ${issue.repo} #${issue.number} · ${issue.title}`)
748    }
749    if (newIssues.length > 3) toast($, m.toast.moreIssueAlerts(newIssues.length - 3))
750  }
751  shownKeys = shownReady(file.items)
752  if (prs) shownPrKeys = prSeenKeys(prs)
753  if (issueList) shownIssueKeys = issueList.map(issueKey)
754  const shown: Shown = { reviews: shownKeys, prs: shownPrKeys, issues: shownIssueKeys }
755  if (JSON.stringify(shown) !== shownWritten) {
756    shownWritten = JSON.stringify(shown)
757    await writeJson($, shownFile(), shown).catch(() => undefined)
758  }
759  if (notesNow !== undefined) {
760    // Snoozed alone: a card that was away at the last look and no longer is came back by its day or its news.
761    const snoozed = awayTests({}, notesNow, Date.now())
762    const cards = [
763      ...file.items.map(i => ({ key: itemKey(i), name: `${i.repo} #${i.number}`, isAway: snoozed.review(i) })),
764      ...(prs ?? []).map(pr => ({ key: prHideKey(pr), name: `${pr.repo} #${pr.number}`, isAway: snoozed.pr(pr) })),
765      ...(issueList ?? []).map(i => ({ key: issueHideKey(i), name: `${i.repo} #${i.number}`, isAway: snoozed.issue(i) })),
766    ]
767    const before = shownSnoozed
768    shownSnoozed = cards.filter(c => c.isAway).map(c => c.key)
769    // A note cleared or unsnoozed by hand has no snooze left, so it is not announced.
770    for (const c of cards.filter(c => before?.includes(c.key) && !c.isAway && notesNow[c.key]?.until !== undefined)) {
771      toast($, [m.toast.back, c.name, notesNow[c.key]?.text].filter(Boolean).join(' · '))
772    }
773  }
774  await flashDrops($)
775}
776
777// What the band counts, after hides and snoozes: compared with the last count to flash a drop.
778async function bandNow($: EngineInterface): Promise<BandCounts> {
779  const away = awayTests(await read($, hidden), await read($, notes), Date.now())
780  const reviews = (await read($, items)).filter(i => !i.isDraft && !away.review(i))
781  const searches = bandSearchCount(searchGroups(m, (await read($, actions)).groups).groups, await read($, groupResults))
782  return bandCounts(reviews.length, (await read($, mine)).filter(pr => !away.pr(pr)), (await read($, issues)).filter(i => !away.issue(i)), searches)
783}
784
785async function flashDrops($: EngineInterface) {
786  const counts = await bandNow($)
787  const drops = droppedCounts(lastBand, counts)
788  lastBand = counts
789  if (isStill || drops.length === 0) return
790  await update($, dropped, () => drops)
791  $.clock.after(FLASH_MS, () => void update($, dropped, () => []))
792}
793
794// Read as the drawer opens, not while it is up, so a card stays marked until it closes.
795async function loadSeen($: EngineInterface) {
796  const seen = await readJson($, seenFile(), {} as { at?: number })
797  await update($, seenAt, () => seen?.at ?? 0)
798}
799
800async function openDrawer($: EngineInterface) {
801  // Opening an open drawer only brings it forward; its picks wait for the close that fills them.
802  if (!(await $.ui.panes()).some(p => p.id === PANE)) {
803    // What the draft already asks for shows as added; a sent or cleared draft frees the cards again.
804    const { text } = await $.prompt.read()
805    const cards = await pickable($)
806    await update($, requested, () => cards.filter(c => hasRequest(text, c.url)).map(c => c.key))
807    await update($, added, () => [])
808    await loadSeen($)
809    await loadActions($)
810    // A group added or edited since the last fetch has nothing to show yet.
811    const results = await read($, groupResults)
812    if (searchGroups(m, (await read($, actions)).groups).groups.some(g => !resultOf(g, results))) wanted = 'fetch'
813  }
814  await $.ui.open({
815    id: PANE,
816    title: m.title,
817    focus: true,
818    closeOnEscape: true,
819    columns: Math.max(60, Math.floor(terminalColumns / 2)),
820    // Inline (not fullscreen) the pane opens a third tall by default: one card. Ask for what the layout spares.
821    rows: 200,
822  })
823}
824
825type Pickable = { key: string; url: string; review?: InboxItem; task?: Task }
826
827// Every card Review or a task button can pick, by the key its hide and note use.
828async function pickable($: EngineInterface): Promise<Pickable[]> {
829  const task = (card: MyPr | IssueItem, key: string): Pickable[] => {
830    const kind = taskOf(card)
831    const base = 'base' in card ? card.base : undefined
832    return kind ? [{ key, url: card.url, task: { kind, repo: card.repo, url: card.url, ...(base ? { base } : {}) } }] : []
833  }
834  return [
835    ...(await read($, items)).map(i => ({ key: itemKey(i), url: i.url, review: i })),
836    ...(await read($, mine)).flatMap(pr => task(pr, prHideKey(pr))),
837    ...(await read($, issues)).flatMap(i => task(i, issueHideKey(i))),
838  ]
839}
840
841// This session's folder when it holds the repository, else the one remembered for it while that folder is still there.
842async function placeFor($: EngineInterface, repo: string): Promise<Place> {
843  const place = placeOf(repo, (await read($, sessions))[selfId], await read($, repos), mappedPath(repo, config.repoPaths, home))
844  return place.kind === 'folder' && !(await $.fs.exists(place.path)) ? { kind: 'unknown' } : place
845}
846
847// Filling the prompt takes the keyboard from the drawer, so Review and the task buttons only mark a card and the drawer's close fills them all.
848async function addCard($: EngineInterface, key: string) {
849  const keys = await read($, added)
850  if (keys.includes(key) || (await read($, requested)).includes(key)) return
851  await update($, added, () => [...keys, key])
852  $.ui.toast(m.toast.added(keys.length + 1))
853}
854
855// Read at each drawer open and each /review-inbox buttons, so an edit to the file shows without a restart.
856async function loadActions($: EngineInterface) {
857  actionsPath = `${await cacheDir($)}/${ACTIONS_FILE}`
858  const text = (await $.fs.exists(actionsPath)) ? await $.fs.read(actionsPath).catch(() => '') : undefined
859  await update($, actions, () => parseActions(text))
860}
861
862// Scopes with more buttons than a row can take in at a glance.
863const crowdedScopes = (buttons: { scope: ButtonScope }[]) =>
864  (['review', 'pr', 'issue'] as const)
865    .map(scope => [scope, buttons.filter(b => b.scope === scope).length] as const)
866    .filter(([, n]) => n > MAX_PER_SCOPE)
867
868// What /review-inbox buttons prints: the file, what of mine it holds, and each entry left out with its reason.
869async function buttonsReport($: EngineInterface): Promise<string> {
870  await loadActions($)
871  const own = await read($, actions)
872  const isEmpty = own.buttons.length + own.groups.length + own.errors.length === 0
873  return [
874    m.buttons.file(home && actionsPath.startsWith(`${home}/`) ? `~${actionsPath.slice(home.length)}` : actionsPath),
875    isEmpty ? m.buttons.none : m.buttons.counts(own.buttons.length, own.groups.length),
876    ...own.errors.map(error => errorText(error, m)),
877    ...crowdedScopes(mergeById(builtInButtons(m), own.buttons)).map(([scope, n]) => m.buttons.tooMany(n, m.buttons.scopes[scope])),
878    m.buttons.how,
879  ].join('\n')
880}
881
882// What a card's own buttons can fill in, by the key its hide and note use.
883async function buttonCards($: EngineInterface): Promise<Map<string, Vars>> {
884  return new Map<string, Vars>([
885    ...(await read($, items)).map(i => [itemKey(i), { RepoName: i.repo, PrNumber: `${i.number}`, PrUrl: i.url, PrTitle: i.title, Author: i.author }] as const),
886    ...(await read($, mine)).map(
887      pr => [prHideKey(pr), { RepoName: pr.repo, PrNumber: `${pr.number}`, PrUrl: pr.url, PrTitle: pr.title, HeadRefName: pr.branch, BaseRefName: pr.base }] as const,
888    ),
889    ...(await read($, issues)).map(i => [issueHideKey(i), { RepoName: i.repo, IssueNumber: `${i.number}`, IssueTitle: i.title, IssueUrl: i.url }] as const),
890  ])
891}
892
893// One line per press of a card's own button, in the order pressed.
894async function buttonPrompts($: EngineInterface, keys: string[]): Promise<string> {
895  const buttons = mergeById(builtInButtons(m), (await read($, actions)).buttons)
896  const cards = await buttonCards($)
897  let text = ''
898  for (const key of keys) {
899    const at = key.lastIndexOf('::')
900    const vars = at > 0 ? cards.get(key.slice(0, at)) : undefined
901    const id = key.slice(at + 2)
902    const button = id === MERGE ? { prompt: m.direct.mergePrompt } : buttons.find(b => b.id === id)
903    if (!vars || !button) continue
904    const place = await placeFor($, vars.RepoName ?? '')
905    const repoPath = place.kind === 'folder' ? place.path : place.kind === 'here' ? await $.session.cwd() : ''
906    text += `${fillTemplate(button.prompt, { ...vars, RepoPath: repoPath })}\n`
907  }
908  return text
909}
910
911// False only when a dialog holds the keys: that passes, so the drawer stays open with its picks and the next close tries again.
912async function fillAdded($: EngineInterface): Promise<boolean> {
913  const byKey = new Map((await pickable($)).map(c => [c.key, c]))
914  const keys = await read($, added)
915  const chosen = keys.flatMap(key => byKey.get(key) ?? [])
916  if (keys.length > 0) {
917    const { text } = await $.prompt.read()
918    const style = (await readJson($, styleFile(), {} as StyleFile))?.profile
919    const reviews = reviewPrompts(text, chosen.flatMap(c => c.review ?? []), m, style)
920    const tasks = await Promise.all(chosen.flatMap(c => c.task ?? []).map(async task => ({ task, place: await placeFor($, task.repo) })))
921    const queued = reviews + taskPrompts(text + reviews, tasks, m)
922    const own = await buttonPrompts($, keys)
923    const before = text + queued
924    const all = queued + (own && before !== '' && !before.endsWith('\n') ? `\n${own}` : own)
925    const filled = all ? await $.prompt.fill({ text: all, mode: 'append' }) : undefined
926    if (filled?.isFilled === false) {
927      $.ui.toast(m.toast.promptBusy)
928      if (filled.refusal === 'dialog') return false
929    }
930  }
931  await update($, added, () => [])
932  return true
933}
934
935// Whether each kind of card is out of view: hidden until its news, or snoozed until its day or its news.
936function awayTests(hiddenMap: Record<string, string>, notesMap: Record<string, Note>, now: number) {
937  const away = (key: string, test: (hideMap: Record<string, string>) => boolean) => test(hiddenMap) || isSnoozed(notesMap[key], key, now, test)
938  return {
939    review: (i: InboxItem) => away(itemKey(i), hideMap => isHidden(hideMap, i)),
940    pr: (pr: MyPr) => away(prHideKey(pr), hideMap => isPrHidden(hideMap, pr)),
941    issue: (i: IssueItem) => away(issueHideKey(i), hideMap => isIssueHidden(hideMap, i)),
942  }
943}
944
945async function liveKeys($: EngineInterface) {
946  return new Set([
947    ...(await read($, items)).map(itemKey),
948    ...(await read($, mine)).map(prHideKey),
949    ...(await read($, issues)).map(issueHideKey),
950    ...(await read($, activity)).threads.map(threadKey),
951  ])
952}
953
954// Read-modify-write on its own file, like a hide.
955async function setNotes($: EngineInterface, change: (n: Record<string, Note>) => Record<string, Note>) {
956  const current = await readJson($, notesFile(), {} as Record<string, Note>)
957  if (current === undefined) {
958    $.ui.toast(m.toast.retry)
959    return
960  }
961  const next = keptNotes(change(current), await liveKeys($), Date.now())
962  await writeJson($, notesFile(), next)
963  await update($, notes, () => next)
964  await flashDrops($)
965}
966
967// Saving the text keeps a snooze already set; an empty note with no snooze is no note.
968async function saveNote($: EngineInterface, key: string, text: string, snooze?: { until: number; mark: string }) {
969  await setNotes($, n => {
970    const { [key]: old, ...rest } = n
971    const note = { ...old, ...snooze, text: text.trim(), savedAt: Date.now() }
972    return note.text || note.until !== undefined ? { ...rest, [key]: note } : rest
973  })
974  await update($, editing, () => '')
975}
976
977// Show all ends the snoozes of the same cards; their text stays.
978async function unsnooze($: EngineInterface, keys: string[]) {
979  await setNotes($, n =>
980    Object.fromEntries(
981      Object.entries(n)
982        .map(([k, note]): [string, Note] => [k, keys.includes(k) ? { text: note.text, savedAt: note.savedAt } : note])
983        .filter(([, note]) => note.text || note.until !== undefined),
984    ),
985  )
986}
987
988// Reloads this session once when a newer release asks; the command waits until the session is idle.
989async function answerReload($: EngineInterface) {
990  const request = await readJson($, RELOAD_FILE, undefined as ReloadRequest | undefined)
991  if (!request || !shouldReload(request, version, loadedAt)) return
992  // Answered, even if the reload is refused or another session's clock runs ahead.
993  loadedAt = Math.max(Date.now(), request.at)
994  await $.command.run({ command: 'reload-plugins' })
995}
996
997// Tells the other sessions what this one is on, and reads what they are on.
998// shortcut: two sessions writing in the same instant can drop one entry until its next check-in, 30 seconds on; lock the file if that shows
999async function checkIn($: EngineInterface, leaving = false) {
1000  const file = await readJson($, SESSIONS_FILE, {} as Record<string, Presence>)
1001  if (file === undefined) return
1002  const { [selfId]: old, ...others } = liveSessions(file, Date.now())
1003  let next = others
1004  if (!leaving) {
1005    const cwd = await $.session.cwd()
1006    const git = (args: string[]) =>
1007      $.process.run(['git', '-C', cwd, ...args]).then(r => (r.exitCode === 0 ? r.stdout : ''), () => '')
1008    const branch = (await git(['branch', '--show-current'])).trim()
1009    const remotes = [...new Set((await git(['remote', '-v'])).split('\n').flatMap(line => repoOf(line.split(/\s+/)[1] ?? '') ?? []))]
1010    const prs = [...new Set([...(old?.prs ?? []), ...linked])].slice(-20)
1011    const folder = cwd.split(/[\\/]/).filter(Boolean).pop() ?? cwd
1012    next = { ...others, [selfId]: { at: Date.now(), folder, remotes, prs, ...(branch ? { branch } : {}), ...(version ? { version } : {}) } }
1013    await rememberFolder($, remotes, () => git(['rev-parse', '--path-format=absolute', '--git-common-dir']))
1014  }
1015  await writeJson($, SESSIONS_FILE, next)
1016  await update($, sessions, () => next)
1017}
1018
1019// Remembers which folder holds each of this session's repositories, so a card in another session can name it.
1020// shortcut: a folder moved or deleted is dropped only when a card's fill finds it gone; prune the file if it grows stale
1021async function rememberFolder($: EngineInterface, remotes: string[], commonDir: () => Promise<string>) {
1022  const file = await readJson($, REPOS_FILE, {} as RepoPaths)
1023  if (file === undefined) return
1024  home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
1025  const top = remotes.length > 0 ? mainCheckout(await commonDir(), home) : undefined
1026  // Written only when a folder changes, not at every check-in.
1027  const next = top !== undefined && remotes.some(repo => file[repo]?.path !== top) ? remember(file, remotes, top, Date.now()) : file
1028  if (next !== file) await writeJson($, REPOS_FILE, next)
1029  await update($, repos, () => next)
1030}
1031
1032// Read-modify-write on its own file, so a hide never races a fetch rewriting the inbox.
1033async function setHidden($: EngineInterface, change: (hideMap: Record<string, string>) => Record<string, string>) {
1034  const current = await readJson($, hiddenFile(), {} as Record<string, string>)
1035  if (current === undefined) {
1036    $.ui.toast(m.toast.retry)
1037    return
1038  }
1039  const live = await liveKeys($)
1040  const next = Object.fromEntries(Object.entries(change(current)).filter(([key]) => live.has(key)))
1041  await writeJson($, hiddenFile(), next)
1042  await update($, hidden, () => next)
1043  await flashDrops($)
1044}
1045
1046export const register: Register = (on, options) => {
1047  const opts = options as Options
1048  languageOption = opts.language
1049  const minutes = Number(opts.refreshMinutes)
1050  config = {
1051    scope: (opts.scope ?? '').trim(),
1052    githubUser: (opts.githubUser ?? '').trim(),
1053    language: 'en',
1054    refreshMs: (Number.isFinite(minutes) && minutes >= 5 ? minutes : 10) * 60_000,
1055    repoPaths: parseRepoPaths(opts.repoPaths ?? ''),
1056    motion: opts.motion === 'off' ? 'off' : 'auto',
1057    directActions: opts.directActions === 'on',
1058  }
1059  m = MESSAGES.en
1060
1061  on('session.start', async ($, e, next) => {
1062    // Before anything is drawn or fetched: the language decides the strings and which shared file is read.
1063    config.language = await resolveLanguage($)
1064    m = MESSAGES[config.language]
1065    home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
1066    ghRepo = await $.env.get('GH_REPO')
1067    await loadActions($).catch(() => undefined)
1068    // A pane a reload kept open was not opened through openDrawer.
1069    await loadSeen($).catch(() => undefined)
1070    isStill =
1071      config.motion === 'off' || (await $.settings.read({ key: 'prefersReducedMotion' }).then(v => v === true, () => false))
1072    // A reload keeps an open pane, its title and the last drawing; bring them to the language just resolved.
1073    const pane = (await $.ui.panes()).find(p => p.id === PANE)
1074    if (pane && pane.title !== m.title) await $.ui.open({ id: PANE, title: m.title, closeOnEscape: true })
1075    $.ui.invalidate('ui.render')
1076    await $.command.register({ name: 'review-inbox', description: m.command.description, argumentHint: '[buttons | add-button | add-search]' })
1077    // Spread sessions opened together so they do not all find the file stale in the same second.
1078    $.clock.after(1_000 + Math.floor(Math.random() * 4_000), () => void sync($))
1079    $.clock.every(SYNC_MS, () => void sync($))
1080    selfId = await $.session.id()
1081    loadedAt = Date.now()
1082    version = await $.fs
1083      .read(`${$.plugin.root}/.claude-plugin/plugin.json`)
1084      .then(text => (JSON.parse(text) as { version?: string }).version)
1085      .catch(() => undefined)
1086    $.clock.after(1_000, () => void checkIn($).catch(() => undefined))
1087    $.clock.every(SYNC_MS, () => void checkIn($).catch(() => undefined))
1088    $.clock.every(SYNC_MS, () => void answerReload($).catch(() => undefined))
1089    $.clock.every(1_000, () => {
1090      if (!wanted) return
1091      const force = wanted === 'fetch'
1092      wanted = undefined
1093      void sync($, force)
1094    })
1095    return next(e)
1096  })
1097
1098  // A prompt that links to a PR on the lists puts it in progress in this session.
1099  on('prompt.submit', async ($, e, next) => {
1100    const urls = [...(await read($, items)), ...(await read($, mine))].map(pr => pr.url).filter(url => hasRequest(e.text, url))
1101    if (urls.length > 0) {
1102      linked = [...linked, ...urls]
1103      await checkIn($).catch(() => undefined)
1104    }
1105    return next(e)
1106  })
1107
1108  on('session.end', async ($, e, next) => {
1109    await checkIn($, true).catch(() => undefined)
1110    return next(e)
1111  })
1112
1113  on('command.run', { command: 'review-inbox' }, async ($, e) => {
1114    const sub = e.args.trim()
1115    if (sub === 'buttons') return { text: await buttonsReport($) }
1116    if (sub === 'add-button' || sub === 'add-search') {
1117      await loadActions($)
1118      const text = sub === 'add-button' ? m.prompt.addButton(actionsPath, VARIABLES.join(', ')) : m.prompt.addGroup(actionsPath)
1119      const filled = await $.prompt.fill({ text, mode: 'append' })
1120      return { text: filled.isFilled ? m.command.filled : m.toast.promptBusy }
1121    }
1122    terminalColumns = e.presentation.columns
1123    await openDrawer($)
1124    wanted ??= 'sync'
1125    return { text: m.command.opened }
1126  })
1127
1128  // Fill before the drawer goes, so a fill a dialog refuses keeps it open; answering without next keeps a pane.
1129  on('ui.close', { id: PANE }, async ($, e, next) => {
1130    if (e.origin.kind === 'unload') return next(e)
1131    await Promise.all(Object.keys(await read($, settling)).map(id => settle($, id)))
1132    await update($, confirming, () => null)
1133    const isFilled = await fillAdded($).catch(() => {
1134      $.ui.toast(m.toast.retry)
1135      return true
1136    })
1137    if (!isFilled) return { value: undefined }
1138    await writeJson($, seenFile(), { at: Date.now() }).catch(() => undefined)
1139    return next(e)
1140  })
1141
1142  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1143    if (e.viewport) terminalColumns = e.viewport.columns
1144    const below = await next(e)
1145    if (e.props.hasSurvey) return below
1146    const away = awayTests(await read($, hidden), await read($, notes), Date.now())
1147    const reviews = (await read($, items)).filter(i => !i.isDraft && !away.review(i))
1148    const band = await bandNow($)
1149    const counts = bandLabels(band, m, await read($, capped))
1150    if (counts.length === 0) return below
1151    // bandLabels keeps this order and leaves out the same zeros.
1152    const keys = BAND_KEYS.filter(k => band[k] > 0)
1153    const flashing = await read($, dropped)
1154
1155    const { Box, Text, Button } = $.ui.resolve(e)
1156    const now = Date.now()
1157    const oldest = reviews.length > 0 ? Math.max(...reviews.map(i => waitingDays(i.requestedAt, now))) : undefined
1158
1159    return (
1160      <Box flexDirection="column">
1161        <Box flexDirection="row" justifyContent="space-between">
1162          <Box flexDirection="row">
1163            <Text color={oldest === undefined ? 'subtle' : ageColor(oldest)}>▌ </Text>
1164            <Text bold>
1165              {counts.map((label, i) => (
1166                <Text key={keys[i]} color={flashing.includes(keys[i]!) ? 'success' : undefined}>
1167                  {i > 0 ? ' · ' : ''}
1168                  {label}
1169                </Text>
1170              ))}
1171            </Text>
1172            {oldest !== undefined && <Text dimColor>{m.band.oldest(oldest)}</Text>}
1173          </Box>
1174          <Button key="open" label={m.band.open} variant="primary" onPress={() => void openDrawer($)} />
1175        </Box>
1176        {below}
1177      </Box>
1178    )
1179  })
1180
1181  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1182    const elements = $.ui.resolve(e)
1183    const { Box, Text, Button, Link } = elements
1184    // The mobile app draws no field yet: no search there, and notes are shown but not written.
1185    const Input = 'Input' in elements ? elements.Input : undefined
1186    const now = Date.now()
1187    const notesMap = await read($, notes)
1188    const away = awayTests(await read($, hidden), notesMap, now)
1189    const rawQuery = await read($, query)
1190    const q = rawQuery.trim()
1191    const editingKey = await read($, editing)
1192    const everything = await read($, items)
1193    const state = await read($, status)
1194    const active = await read($, tab)
1195    const allPrs = await read($, mine)
1196    const allIssues = await read($, issues)
1197    const live = liveSessions(await read($, sessions), now)
1198    const older = olderSessions(live, selfId, version)
1199    const asked = version !== undefined && (await read($, reloadAsked)) === version
1200    // This session's repositories come first in every group; the scope buttons narrow the tabs to them.
hooks/actions.ts 105 lines
1import type { Actions, ButtonError, ButtonScope, CardButton, GroupScope, SearchGroup } from '../types'
2import type { Messages } from './i18n'
3
4export const ACTIONS_FILE = 'actions.json'
5// Past this many in one scope, the card's row of buttons stops being a glance.
6export const MAX_PER_SCOPE = 20
7
8export const VARIABLES = [
9  'RepoName',
10  'RepoPath',
11  'PrNumber',
12  'PrUrl',
13  'PrTitle',
14  'Author',
15  'HeadRefName',
16  'BaseRefName',
17  'IssueNumber',
18  'IssueTitle',
19  'IssueUrl',
20] as const
21export type Variable = (typeof VARIABLES)[number]
22export type Vars = Partial<Record<Variable, string>>
23
24const SCOPES: readonly ButtonScope[] = ['review', 'pr', 'issue']
25const GROUP_SCOPES: readonly GroupScope[] = ['prs', 'issues']
26
27// gh-dash's spellings, {{.Name}}, {{Name}} and {{ .Name }}; no pipes or conditions.
28const TEMPLATE = /\{\{\s*\.?\s*([A-Za-z]+)\s*\}\}/g
29
30const isVariable = (name: string): name is Variable => (VARIABLES as readonly string[]).includes(name)
31
32export function unknownVariables(prompt: string): string[] {
33  return [...new Set([...prompt.matchAll(TEMPLATE)].map(match => match[1]!).filter(name => !isVariable(name)))]
34}
35
36// A variable the card has no value for becomes empty.
37export function fillTemplate(prompt: string, vars: Vars): string {
38  return prompt.replace(TEMPLATE, (_, name: string) => (isVariable(name) ? (vars[name] ?? '') : ''))
39}
40
41// Prompts reach Claude only through the prompt field: nothing here runs a command.
42export const BUILT_IN: { id: keyof Messages['buttons']['builtIn']; scope: ButtonScope }[] = [
43  { id: 'summarize-risks', scope: 'review' },
44  { id: 'explain-diff', scope: 'review' },
45  { id: 'draft-approval', scope: 'review' },
46  { id: 'draft-reply', scope: 'pr' },
47  { id: 'investigate-ci', scope: 'pr' },
48]
49
50export const builtInButtons = (m: Messages): CardButton[] => BUILT_IN.map(b => ({ ...b, ...m.buttons.builtIn[b.id] }))
51
52// A missing file is nothing of mine; a broken one, or a broken entry, is listed and leaves the rest working.
53export function parseActions(text: string | undefined): Actions {
54  const broken: Actions = { buttons: [], groups: [], errors: [{ at: ACTIONS_FILE, reason: 'file' }] }
55  if (text === undefined) return { buttons: [], groups: [], errors: [] }
56  let data: unknown
57  try {
58    data = JSON.parse(text)
59  } catch {
60    return broken
61  }
62  const lists = data !== null && typeof data === 'object' && !Array.isArray(data) ? (data as { buttons?: unknown; groups?: unknown }) : {}
63  const isList = (value: unknown) => value === undefined || Array.isArray(value)
64  if ((lists.buttons === undefined && lists.groups === undefined) || !isList(lists.buttons) || !isList(lists.groups)) return broken
65  const buttonEntries = (lists.buttons ?? []) as (Partial<Record<keyof CardButton, unknown>> | null)[]
66  const groupEntries = (lists.groups ?? []) as (Partial<Record<keyof SearchGroup, unknown>> | null)[]
67
68  const buttons: CardButton[] = []
69  const groups: SearchGroup[] = []
70  const errors: ButtonError[] = []
71  buttonEntries.forEach((entry, i) => {
72    const at = typeof entry?.id === 'string' && entry.id ? entry.id : `#${i + 1}`
73    const { id, name, scope, prompt, hidden } = entry ?? {}
74    if (typeof id !== 'string' || !id) return errors.push({ at, reason: 'fields' })
75    if (!SCOPES.includes(scope as ButtonScope)) return errors.push({ at, reason: 'scope', detail: String(scope) })
76    if (hidden === true) return buttons.push({ id, name: '', scope: scope as ButtonScope, prompt: '', hidden: true })
77    if (typeof name !== 'string' || !name || typeof prompt !== 'string' || !prompt) return errors.push({ at, reason: 'fields' })
78    const unknown = unknownVariables(prompt)
79    if (unknown.length > 0) return errors.push({ at, reason: 'variables', detail: unknown.join(', ') })
80    buttons.push({ id, name, scope: scope as ButtonScope, prompt })
81  })
82  groupEntries.forEach((entry, i) => {
83    const at = typeof entry?.id === 'string' && entry.id ? entry.id : `groups #${i + 1}`
84    const { id, name, query, scope, countInBand, hidden } = entry ?? {}
85    if (typeof id !== 'string' || !id) return errors.push({ at, reason: 'groupFields' })
86    if (hidden === true) return groups.push({ id, name: '', query: '', scope: 'prs', hidden: true })
87    if (!GROUP_SCOPES.includes(scope as GroupScope)) return errors.push({ at, reason: 'groupScope', detail: String(scope) })
88    if (typeof name !== 'string' || !name || typeof query !== 'string' || !query.trim()) return errors.push({ at, reason: 'groupFields' })
89    groups.push({ id, name, query, scope: scope as GroupScope, ...(countInBand === true ? { countInBand: true } : {}) })
90  })
91  return { buttons, groups, errors }
92}
93
94// A button or search group of mine with a built-in id takes its place; `hidden` removes it.
95export function mergeById<T extends { id: string; hidden?: boolean }>(builtIn: T[], mine: T[]): T[] {
96  const byId = new Map(builtIn.map(b => [b.id, b]))
97  for (const b of mine) byId.set(b.id, b)
98  return [...byId.values()].filter(b => !b.hidden)
99}
100
101export function errorText(error: ButtonError, m: Messages): string {
102  const reason = m.buttons.errors[error.reason]
103  return `${error.at}: ${typeof reason === 'string' ? reason : reason(error.detail ?? '')}`
104}
105
hooks/direct.ts 49 lines
1import type { DirectAction, DirectTarget, InboxItem, IssueItem, MyPr } from '../types'
2
3// A confirm row left alone goes back to the card's buttons.
4export const CONFIRM_MS = 10_000
5// A confirm this soon after the press that asked is that press's key repeat or a double tap, not a decision.
6export const CONFIRM_GUARD_MS = 300
7
8export type AskedAction = 'approve' | 'ready' | 'update-branch'
9// Others see these, and none can be taken back, so each is asked on the card first.
10export const needsConfirm = (action: DirectAction): action is AskedAction => action === 'approve' || action === 'ready' || action === 'update-branch'
11
12// Only what the card's state makes useful: an approve on a draft or a rerun on a green PR would only fail.
13export const reviewActions = (item: InboxItem): DirectAction[] => (item.isDraft ? [] : ['approve'])
14
15export function prActions(pr: MyPr): DirectAction[] {
16  return [
17    ...(pr.state === 'draft' ? ['ready' as const] : []),
18    ...(pr.isBehind && pr.headSha ? ['update-branch' as const] : []),
19    ...(pr.state === 'ci-failing' && pr.headSha ? ['rerun' as const] : []),
20  ]
21}
22
23// Mentions only: an assigned issue is mine already, and a reference is about one of mine.
24export const issueActions = (issue: IssueItem): DirectAction[] => (issue.kind === 'mention' ? ['assign'] : [])
25
26// Approved with nothing running: the Merge button fills the prompt, it never merges by itself.
27export const canMerge = (pr: MyPr) => pr.state === 'approved' && !pr.ciPending
28
29// The gh call for each write but rerun, which lists the failed runs first; `assignees` takes a PR's number as well as an issue's.
30export function writeArgs(action: Exclude<DirectAction, 'rerun'>, target: DirectTarget, login: string, isUndo = false): string[] {
31  const path = `repos/${target.repo}`
32  switch (action) {
33    case 'approve':
34      // Pinned to the commit I looked at, with no body: GitHub's own default is an empty approval.
35      return ['api', '-X', 'POST', `${path}/pulls/${target.number}/reviews`, '-f', 'event=APPROVE', '-f', `commit_id=${target.sha}`]
36    case 'ready':
37      return ['pr', 'ready', `${target.number}`, '--repo', target.repo]
38    case 'update-branch':
39      // Merge, never rebase: a rebase force-pushes the author's branch. GitHub refuses it if the head moved.
40      return ['api', '-X', 'PUT', `${path}/pulls/${target.number}/update-branch`, '-f', `expected_head_sha=${target.sha}`]
41    case 'assign':
42      return ['api', '-X', isUndo ? 'DELETE' : 'POST', `${path}/issues/${target.number}/assignees`, '-f', `assignees[]=${login}`]
43  }
44}
45
46export const failedRunsArgs = (target: DirectTarget) => ['api', `repos/${target.repo}/actions/runs?head_sha=${target.sha}&status=failure`, '--jq', '.workflow_runs[].id']
47export const rerunArgs = (target: DirectTarget, run: string) => ['api', '-X', 'POST', `repos/${target.repo}/actions/runs/${run}/rerun-failed-jobs`]
48export const headArgs = (target: DirectTarget) => ['api', `repos/${target.repo}/pulls/${target.number}`, '--jq', '.head.sha']
49
hooks/activity.ts 78 lines
1import type { Thread } from '../types'
2
3// The newest threads read; GitHub serves at most 50 a page.
4export const ACTIVITY_LIMIT = 100
5const PER_PAGE = 50
6// Threads updated in the last 30 days, like references.
7export const ACTIVITY_DAYS = 30
8export const UNDO_MS = 10_000
9
10// Already a card on another tab, or nothing to act on: left out whatever their target.
11const LEFT_OUT = ['review_requested', 'assign', 'mention', 'subscribed']
12
13// Read ones too, as GitHub's own inbox keeps them until Done; the window starts at midnight UTC so a day's looks ask the same.
14export function notificationsPath(page: number, now: number) {
15  const since = new Date((Math.floor(now / 86_400_000) - ACTIVITY_DAYS) * 86_400_000).toISOString()
16  return `notifications?all=true&participating=true&per_page=${PER_PAGE}&page=${page}&since=${since}`
17}
18
19export const THREAD_JQ = '[.[] | {id, unread, reason, updated_at, title: .subject.title, url: .subject.url, repo: .repository.full_name}]'
20
21// `gh api -i` prints the status line and headers, a blank line, then the body.
22export function splitResponse(text: string): { headers: Record<string, string>; body: string } {
23  const at = text.search(/\r?\n\r?\n/)
24  const head = at < 0 ? text : text.slice(0, at)
25  const headers = Object.fromEntries(
26    head
27      .split(/\r?\n/)
28      .slice(1)
29      .map(line => [line.slice(0, line.indexOf(':')).trim().toLowerCase(), line.slice(line.indexOf(':') + 1).trim()]),
30  )
31  return { headers, body: at < 0 ? '' : text.slice(at).trim() }
32}
33
34export const hasNextPage = (headers: Record<string, string>) => /rel="next"/.test(headers.link ?? '')
35
36export function pollAfter(headers: Record<string, string>, now: number) {
37  const seconds = Number(headers['x-poll-interval'])
38  return Number.isFinite(seconds) && seconds > 0 ? now + seconds * 1000 : undefined
39}
40
41// The subject's API URL as its page; a subject without one, such as a discussion, opens the repository.
42export function htmlUrl(api: string | null, repo: string) {
43  const path = api?.match(/^https:\/\/api\.github\.com\/repos\/(.+)$/)?.[1]
44  if (!path) return `https://github.com/${repo}`
45  return `https://github.com/${path.replace(/\/pulls\/(\d+)$/, '/pull/$1').replace(/\/commits\/(\w+)$/, '/commit/$1').replace(/\/releases\/\d+$/, '/releases')}`
46}
47
48export type RawThread = { id: string; unread: boolean; reason: string; updated_at: string; title: string; url: string | null; repo: string }
49
50export const toThread = (raw: RawThread): Thread => ({
51  id: raw.id,
52  repo: raw.repo,
53  title: raw.title,
54  // A workflow run has no subject URL; its repository's Actions page lists the run.
55  url: raw.reason === 'ci_activity' && !raw.url ? `https://github.com/${raw.repo}/actions` : htmlUrl(raw.url, raw.repo),
56  reason: raw.reason,
57  updatedAt: raw.updated_at,
58  unread: raw.unread,
59})
60
61export const threadKey = (thread: Thread) => `thread:${thread.id}`
62
63// A Done thread stays hidden until it has new activity.
64export const isThreadHidden = (hidden: Record<string, string>, thread: Thread) => hidden[threadKey(thread)] === thread.updatedAt
65
66// What the tab shows: no thread that is a card on another tab, or of a reason left out.
67export const shownThreads = (threads: Thread[], cardUrls: Set<string>) =>
68  threads.filter(t => !LEFT_OUT.includes(t.reason) && !cardUrls.has(t.url))
69
70// The tab's sections, in an order that does not shift as notifications arrive: talk first, then what happened on its own.
71const REASON_ORDER = ['comment', 'team_mention', 'state_change', 'ci_activity', 'security_alert', 'author']
72
73export function byReason(threads: Thread[]): [string, Thread[]][] {
74  const reasons = [...new Set(threads.map(t => t.reason))]
75  const rank = (reason: string) => (REASON_ORDER.includes(reason) ? REASON_ORDER.indexOf(reason) : REASON_ORDER.length)
76  return reasons.sort((a, b) => rank(a) - rank(b)).map(reason => [reason, threads.filter(t => t.reason === reason)])
77}
78
hooks/searches.ts 65 lines
1import type { GroupHit, GroupResult, SearchGroup } from '../types'
2import { mergeById } from './actions'
3import type { Messages } from './i18n'
4import { PAGE, PAGE_ARGS } from './pages'
5
6// Past this many the tab stops being a glance, and each group is one more search per refresh.
7export const MAX_GROUPS = 15
8// The newest of each group; the rest are a link to the same search on GitHub.
9export const GROUP_HITS = 20
10
11// GitHub Inbox's smart filters, as groups.
12export const BUILT_IN_GROUPS: { id: keyof Messages['searches']['builtIn']; scope: SearchGroup['scope']; query: string }[] = [
13  { id: 'involves-me', scope: 'prs', query: 'is:open involves:@me -author:@me' },
14  { id: 'reviewed-by-me', scope: 'prs', query: 'is:open reviewed-by:@me -author:@me -review-requested:@me' },
15  { id: 'my-open-issues', scope: 'issues', query: 'is:open author:@me' },
16]
17
18// What the Searches tab shows and the fetch runs, in file order after the built-ins; `extra` is how many were left out.
19export function searchGroups(m: Messages, mine: SearchGroup[]): { groups: SearchGroup[]; extra: number } {
20  const all = mergeById<SearchGroup>(BUILT_IN_GROUPS.map(g => ({ ...g, name: m.searches.builtIn[g.id] })), mine)
21  return { groups: all.slice(0, MAX_GROUPS), extra: Math.max(0, all.length - MAX_GROUPS) }
22}
23
24// The group's own query, plus its scope's kind and newest first unless it says otherwise. The scope setting does not apply.
25export function groupQuery(group: SearchGroup): string {
26  const q = group.query.trim()
27  const kind = /(^|[\s(])-?(is|type):(pr|issue)\b/i.test(q) ? [] : [group.scope === 'prs' ? 'is:pr' : 'is:issue']
28  const sort = /(^|[\s(])sort:/i.test(q) ? [] : ['sort:updated-desc']
29  return [q, ...kind, ...sort].join(' ')
30}
31
32export const searchUrl = (group: SearchGroup) =>
33  `https://github.com/search?q=${encodeURIComponent(groupQuery(group))}&type=${group.scope === 'prs' ? 'pullrequests' : 'issues'}`
34
35// A result answers the group only while its query is the group's current one.
36export const resultOf = (group: SearchGroup, results: Record<string, GroupResult>) =>
37  results[group.id]?.query === groupQuery(group) ? results[group.id] : undefined
38
39export const bandSearchCount = (groups: SearchGroup[], results: Record<string, GroupResult>) =>
40  groups.filter(g => g.countInBand).reduce((sum, g) => sum + (resultOf(g, results)?.count ?? 0), 0)
41
42const HIT = 'number title url updatedAt author { login } repository { nameWithOwner }'
43export const GROUP_QUERY = `query($q: String!, ${PAGE_ARGS}) {
44  search(query: $q, type: ISSUE, ${PAGE}) {
45    issueCount
46    pageInfo { hasNextPage endCursor }
47    nodes { ... on PullRequest { ${HIT} } ... on Issue { ${HIT} } }
48  }
49}`
50
51export type GqlHit = {
52  number: number
53  title: string
54  url: string
55  updatedAt: string
56  author: { login: string } | null
57  repository: { nameWithOwner: string }
58}
59
60export function toHits(nodes: Partial<GqlHit>[]): GroupHit[] {
61  return nodes
62    .filter((n): n is GqlHit => typeof n.number === 'number')
63    .map(n => ({ repo: n.repository.nameWithOwner, number: n.number, title: n.title, url: n.url, author: n.author?.login ?? 'ghost', updatedAt: n.updatedAt }))
64}
65
hooks/inbox.ts 318 lines
1import type { CardDetails, Impact, InboxFile, InboxItem } from '../types'
2import { MESSAGES } from './i18n'
3import { PAGE, PAGE_ARGS } from './pages'
4import type { Language, Messages } from './i18n'
5
6export type SearchHit = {
7  repository: { nameWithOwner: string }
8  number: number
9  title: string
10  url: string
11  author: { login: string } | null
12  createdAt: string
13  updatedAt?: string
14  isDraft: boolean
15}
16
17export type PrDetail = {
18  headRefOid: string
19  body: string
20  additions: number
21  deletions: number
22  changedFiles: number
23  reviewRequests: { login?: string; name?: string; slug?: string }[]
24  files?: { path: string }[]
25  reviews?: { state?: string; author: { login: string } | null; commit?: { oid: string } | null }[]
26}
27
28type Reviewer = { login?: string; name?: string; slug?: string } | null
29
30// What a card shows beside its state, asked for in every search.
31// shortcut: the first 10 labels only; a card shows two and a count, so more only matters for the count
32export const DETAILS_FIELDS = 'labels(first: 10) { nodes { name } } comments { totalCount }'
33
34// One GraphQL search returns every PR with what the cards need, so one PR can't fail the rest.
35export type GqlPr = SearchHit & GqlDetails & {
36  body: string
37  additions: number
38  deletions: number
39  changedFiles: number
40  headRefOid: string
41  files: { nodes: { path: string }[] } | null
42  reviewRequests: { nodes: { requestedReviewer: Reviewer }[] }
43  reviews: { nodes: { state?: string; author: { login: string } | null; commit: { oid: string } | null }[] }
44  timelineItems: { nodes: { createdAt?: string; requestedReviewer?: Reviewer }[] }
45}
46
47export const INBOX_QUERY = `query($q: String!, ${PAGE_ARGS}) {
48  viewer { login }
49  search(query: $q, type: ISSUE, ${PAGE}) {
50    pageInfo { hasNextPage endCursor }
51    nodes {
52      ... on PullRequest {
53        number title url isDraft createdAt updatedAt body additions deletions changedFiles headRefOid baseRefName ${DETAILS_FIELDS}
54        author { login }
55        repository { nameWithOwner defaultBranchRef { name } }
56        files(first: 80) { nodes { path } }
57        reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } ... on Team { name slug } } } }
58        reviews(last: 50) { nodes { state author { login } commit { oid } } }
59        timelineItems(itemTypes: [REVIEW_REQUESTED_EVENT], last: 50) {
60          nodes { ... on ReviewRequestedEvent { createdAt requestedReviewer { ... on User { login } ... on Team { slug } } } }
61        }
62      }
63    }
64  }
65}`
66
67// The user's scope narrows the base query; empty means every PR on GitHub that asks for my review.
68export function searchQuery(scope: string): string {
69  return ['is:pr is:open review-requested:@me', scope.trim()].filter(Boolean).join(' ')
70}
71
72// A short, filename-safe digest (FNV-1a) of what decides the inbox's contents.
73export function cacheKey(...parts: string[]): string {
74  let hash = 0x811c9dc5
75  for (const ch of parts.join('\n')) {
76    hash ^= ch.codePointAt(0)!
77    hash = Math.imul(hash, 0x01000193)
78  }
79  return (hash >>> 0).toString(16).padStart(8, '0')
80}
81
82// Part of the shared inbox file's name, so a session still running an older release, which keeps writing its own file,
83// never hands a newer one its lists or errors. Raise it in a release that changes what the file holds or how it is fetched.
84export const INBOX_FORMAT = 2
85
86export function toDetail(pr: GqlPr): PrDetail {
87  return {
88    headRefOid: pr.headRefOid,
89    body: pr.body,
90    additions: pr.additions,
91    deletions: pr.deletions,
92    changedFiles: pr.changedFiles,
93    reviewRequests: pr.reviewRequests.nodes.map(n => n.requestedReviewer ?? {}),
94    files: pr.files?.nodes ?? [],
95    reviews: pr.reviews.nodes,
96  }
97}
98
99// The latest time my review was asked for, directly or through a team still on the PR.
100export function requestedAt(pr: GqlPr, me: string): string {
101  const mine = (r: Reviewer | undefined) =>
102    r?.login?.toLowerCase() === me.toLowerCase() ||
103    (r?.slug !== undefined && pr.reviewRequests.nodes.some(n => n.requestedReviewer?.slug === r.slug))
104  const times = pr.timelineItems.nodes.filter(n => n.createdAt && mine(n.requestedReviewer)).map(n => n.createdAt!)
105  return times.sort().at(-1) ?? pr.createdAt
106}
107
108export type Summary = { summary: string; why: string; impact: Impact[]; summaryFailed?: number }
109
110const DAY_MS = 86_400_000
111export const REFRESH_MS = 10 * 60_000
112export const RETRY_MS = 60_000
113// A claim not renewed for this long belongs to a session that died mid-fetch.
114export const CLAIM_MS = 3 * 60_000
115// A write takes milliseconds; a file still unreadable this long after it was written was cut short and never completes.
116export const TORN_MS = 10_000
117const MAX_SUMMARY_TRIES = 3
118
119export function waitingDays(since: string, now: number): number {
120  return Math.max(0, Math.floor((now - Date.parse(since)) / DAY_MS))
121}
122
123export function ageColor(days: number): 'error' | 'warning' | 'subtle' {
124  return days >= 14 ? 'error' : days >= 3 ? 'warning' : 'subtle'
125}
126
127// The team my review was asked of; undefined when it was asked of me directly, which wins when both were.
128export function requestedTeam(requests: PrDetail['reviewRequests'], me: string): string | undefined {
129  if (requests.some(r => r.login?.toLowerCase() === me.toLowerCase())) return undefined
130  const team = requests.find(r => r.login === undefined && (r.name || r.slug))
131  return team ? (team.name ?? team.slug) : undefined
132}
133
134export function sortItems(items: InboxItem[]): InboxItem[] {
135  const isDirect = (i: InboxItem) => (i.team === undefined ? 0 : 1)
136  return [...items].sort(
137    (a, b) => isDirect(a) - isDirect(b) || Date.parse(a.requestedAt) - Date.parse(b.requestedAt),
138  )
139}
140
141export function shouldFetch(file: InboxFile, now: number, force: boolean, refreshMs = REFRESH_MS): boolean {
142  if (file.fetchingSince !== undefined && now - file.fetchingSince < CLAIM_MS) return false
143  if (force || file.fetchedAt === undefined) return true
144  if (file.retryAt !== undefined) return now >= file.retryAt
145  // A file written by an older version of the mod has no tabs; refresh it rather than show them empty.
146  return file.mine === undefined || now - file.fetchedAt >= refreshMs
147}
148
149export type GqlDetails = {
150  labels?: { nodes: { name: string }[] } | null
151  comments?: { totalCount: number } | null
152  baseRefName?: string
153  repository: { defaultBranchRef?: { name: string } | null }
154}
155
156export function detailsOf(node: GqlDetails): CardDetails {
157  const labels = node.labels?.nodes.map(l => l.name) ?? []
158  const main = node.repository.defaultBranchRef?.name
159  return {
160    ...(labels.length > 0 ? { labels } : {}),
161    ...(node.comments?.totalCount ? { comments: node.comments.totalCount } : {}),
162    ...(node.baseRefName && main && node.baseRefName !== main ? { offBase: node.baseRefName } : {}),
163  }
164}
165
166export function detailsText(card: CardDetails, m: Messages): string {
167  const labels = card.labels ?? []
168  return [
169    card.offBase && `→ ${card.offBase}`,
170    labels.length > 0 && [labels.slice(0, 2).join(', '), labels.length > 2 && `+${labels.length - 2}`].filter(Boolean).join(' '),
171    card.comments && m.card.comments(card.comments),
172  ]
173    .filter(Boolean)
174    .join(' · ')
175}
176
177export function isTorn(writtenAt: number, now: number): boolean {
178  return now - writtenAt >= TORN_MS
179}
180
181// Summaries are tied to the head commit, so an unchanged PR keeps its own; a failed one is retried a few times, then kept.
182export function reusableSummary(prev: InboxItem | undefined, headSha: string): Summary | undefined {
183  if (!prev || prev.headSha !== headSha) return undefined
184  if (prev.summaryFailed !== undefined && prev.summaryFailed < MAX_SUMMARY_TRIES) return undefined
185  return {
186    summary: prev.summary,
187    why: prev.why,
188    impact: prev.impact,
189    ...(prev.summaryFailed !== undefined ? { summaryFailed: prev.summaryFailed } : {}),
190  }
191}
192
193export function failedSummary(
194  title: string,
195  reason: string,
196  prev: InboxItem | undefined,
197  headSha: string,
198  m: Messages,
199): Summary {
200  const tries = prev?.headSha === headSha ? (prev.summaryFailed ?? 0) : 0
201  return { summary: title, why: m.summaryFailed(reason), impact: [], summaryFailed: tries + 1 }
202}
203
204export function summaryRules(language: Language): string {
205  const l = MESSAGES[language].model
206  return `You summarize a GitHub pull request for a reviewer who has not opened it yet.
207${l.language}
208
209Return only JSON: {"summary": string, "why": string, "impact": [{"text": string, "warn": boolean}]}
210- summary: one sentence. What changes for users or teammates, not how the code changes.
211- why: one or two sentences. The problem that exists without this PR.
212- impact: one to three items. Which screens, APIs, data or services this touches, and whether existing behaviour stays the same.
213  Set warn true only for: hard to roll back (DB schema, data migration), a required deploy or merge order, another service affected, permission or security changes.
214- ${l.sentence}
215- No function names, file paths, class names, internal acronyms or issue numbers. Say what a thing does instead.
216- ${l.filler}
217
218Example of a bad summary: "${l.bad}"
219Example of a good summary: "${l.good}"`
220}
221
222export function summaryPrompt(hit: SearchHit, detail: PrDetail): string {
223  const files = (detail.files ?? []).slice(0, 80).map(f => f.path).join('\n')
224  return [
225    `Repository: ${hit.repository.nameWithOwner}`,
226    `Title: ${hit.title}`,
227    `Size: ${detail.changedFiles} files, +${detail.additions} / -${detail.deletions}`,
228    `Changed files:\n${files}`,
229    `Description:\n${(detail.body ?? '').slice(0, 12_000) || '(empty)'}`,
230  ].join('\n\n')
231}
232
233export function parseSummary(text: string): Summary | undefined {
234  const json = text.match(/\{[\s\S]*\}/)?.[0]
235  if (!json) return undefined
236  try {
237    const raw = JSON.parse(json) as Partial<Summary>
238    if (typeof raw.summary !== 'string' || typeof raw.why !== 'string') return undefined
239    const impact = Array.isArray(raw.impact)
240      ? raw.impact
241          .filter(i => i && typeof i.text === 'string')
242          .map(i => ({ text: i.text, warn: i.warn === true }))
243      : []
244    return { summary: raw.summary, why: raw.why, impact }
245  } catch {
246    return undefined
247  }
248}
249
250export function itemKey(item: Pick<InboxItem, 'repo' | 'number'>): string {
251  return `${item.repo}#${item.number}`
252}
253
254// The commit my latest submitted review was left on; undefined when I never submitted one.
255export function lastReviewedSha(reviews: PrDetail['reviews'], me: string): string | undefined {
256  const mine = (reviews ?? []).filter(r => r.state !== 'PENDING' && r.author?.login.toLowerCase() === me.toLowerCase())
257  return mine.at(-1)?.commit?.oid
258}
259
260// Hidden until the PR gets a new commit.
261export function isHidden(hidden: Record<string, string>, item: InboxItem): boolean {
262  return hidden[itemKey(item)] === item.headSha
263}
264
265// The keys a session has shown as ready; a draft is left out so it announces once it is ready.
266export function shownReady(items: InboxItem[]): string[] {
267  return items.filter(i => !i.isDraft).map(itemKey)
268}
269
270// A session's first look has nothing to compare against, so it announces nothing.
271export function newArrivals(seen: string[] | undefined, items: InboxItem[]): InboxItem[] {
272  if (seen === undefined) return []
273  const known = new Set(seen)
274  return items.filter(i => !i.isDraft && !known.has(itemKey(i)))
275}
276
277export function sinceRules(language: Language): string {
278  return `You tell a reviewer what changed in a pull request since they last reviewed it.
279${MESSAGES[language].model.since}
280Say what changed in behaviour, not which files. No function names, file paths or ticket ids.
281Reply with the sentences only.`
282}
283
284export function sincePrompt(commits: string[], files: string[]): string {
285  return [
286    `Commits since the last review:\n${commits.map(c => `- ${c.split('\n')[0]}`).join('\n')}`,
287    `Files changed since the last review:\n${files.slice(0, 60).join('\n')}`,
288  ].join('\n\n')
289}
290
291// The style line is said once per prompt, so adding several PRs repeats only the requests.
292export function reviewPrompt(draft: string, item: InboxItem, m: Messages, style?: string): string {
293  const lines = [m.prompt.review(item.url)]
294  const styleLine = style ? `${m.prompt.style}${style}` : undefined
295  if (styleLine && !draft.includes(styleLine)) lines.push(styleLine)
296  const warnings = item.impact.filter(i => i.warn).map(i => i.text)
297  if (warnings.length > 0) lines.push(`${m.prompt.check}${warnings.join(' / ')}`)
298  if (item.sinceLastReview) lines.push(`${m.prompt.since}${item.sinceLastReview}`)
299  const text = `${lines.join('\n')}\n`
300  return draft === '' || draft.endsWith('\n') ? text : `\n${text}`
301}
302
303// What the drawer adds to the draft when it closes: one request per PR not already in it, in the order pressed.
304export function reviewPrompts(draft: string, items: InboxItem[], m: Messages, style?: string): string {
305  let text = draft
306  for (const item of items) if (!hasRequest(text, item.url)) text += reviewPrompt(text, item, m, style)
307  return text.slice(draft.length)
308}
309
310// The link must end where the draft's link ends, so /pull/12 is not found inside /pull/123 or /pull/12/files.
311export function hasRequest(draft: string, url: string): boolean {
312  return new RegExp(`${url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w/])`).test(draft)
313}
314
315export function minutesSince(at: number | undefined, now: number): number | undefined {
316  return at === undefined ? undefined : Math.floor((now - at) / 60_000)
317}
318
hooks/i18n.ts 273 lines
1import type { IssueKind, MyPrState, TaskKind } from '../types'
2import { de } from './locales/de'
3import { es } from './locales/es'
4import { fr } from './locales/fr'
5import { ja } from './locales/ja'
6import { ko } from './locales/ko'
7import { ptBR } from './locales/pt-BR'
8import { zhCN } from './locales/zh-CN'
9import { zhTW } from './locales/zh-TW'
10
11const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
12
13// English is the schema: every table in ./locales must have the same keys, and the tests check it at runtime too.
14const en = {
15  title: 'Review inbox',
16  command: {
17    description: 'Open the review inbox: PRs awaiting my review, my PRs, and issues assigned to me or mentioning me',
18    opened: 'Opened the review inbox.',
19    filled: 'Added to your prompt; press Enter to send it.',
20  },
21  band: {
22    open: 'Open',
23    reviews: (n: string) => `To review ${n}`,
24    prTodo: (n: string) => `My PRs to act on ${n}`,
25    issues: (n: string) => `Assigned & mentioned ${n}`,
26    searches: (n: string) => `Saved searches ${n}`,
27    oldest: (days: number) => ` · oldest waiting ${count(days, 'day')}`,
28  },
29  tabs: {
30    review: (n: string) => `To review ${n}`,
31    mine: (n: string) => `My PRs ${n}`,
32    issues: (n: string) => `Assigned & mentioned ${n}`,
33    searches: 'Saved searches',
34    activity: (n: string) => `Notifications ${n}`,
35  },
36  card: {
37    rerequest: 're-requested',
38    waiting: (days: number) => count(days, 'day'),
39    ago: (days: number) => (days === 0 ? 'today' : `${count(days, 'day')} ago`),
40    direct: 'direct request',
41    team: (team: string) => `team request (${team})`,
42    sinceMyReview: 'Since my last review',
43    summary: 'Summary',
44    why: 'Why',
45    impact: 'Impact',
46    size: (files: number, added: string, removed: string) => `${count(files, 'file')} (+${added} −${removed})`,
47    hide: 'Hide',
48    review: 'Review with Claude',
49    added: 'Added',
50    task: {
51      changes: 'Address comments',
52      'ci-failing': 'Fix CI',
53      conflict: 'Resolve conflict',
54      work: 'Work on this',
55    } satisfies Record<TaskKind, string>,
56    here: 'this folder',
57    at: (path: string) => `in ${path}`,
58    noClone: 'no local clone',
59    ciRunning: ' · CI running',
60    thisRepo: 'this repo',
61    comments: (n: number) => count(n, 'comment'),
62    newReview: (who: string) => `New review · ${who}`,
63    referenced: (by: string, target: string) => `${by} referenced my ${target}`,
64  },
65  state: {
66    changes: 'Changes requested',
67    'ci-failing': 'CI failing',
68    conflict: 'Merge conflict',
69    waiting: 'Waiting for review',
70    approved: 'Approved',
71    queued: 'In merge queue',
72    draft: 'Draft',
73  } satisfies Record<MyPrState, string>,
74  issueKind: {
75    assigned: 'Assigned to me',
76    mention: 'Mentions me',
77    reference: 'References my work',
78  } satisfies Record<IssueKind, string>,
79  status: {
80    loading: 'Loading…',
81    error: (message: string) => `Could not load; retrying in a minute (${message})`,
82    updated: (minutes: number) => (minutes < 1 ? 'Updated just now' : `Updated ${minutes} min ago`),
83    firstFetch: 'Fetching from GitHub. The first time takes about a minute.',
84    timeout: 'GitHub timed out; narrow the Search scope setting, e.g. org:my-org',
85    reloadAll: 'Reload them all',
86    reloadAsked: 'Asked',
87    older: (n: number, folders: string) => `${n} ${n === 1 ? 'session' : 'sessions'} on an older version (${folders}): run /reload-plugins there`,
88  },
89  empty: {
90    zero: '✓ Nothing needs you',
91    review: 'No PRs are waiting for your review.',
92    mine: 'You have no open PRs.',
93    issues: 'No issues are assigned to you or mention you.',
94    searches: "No saved searches. Add one with /review-inbox add-search.",
95    activity: "No other notifications. Review requests, assignments and mentions are on the other tabs.",
96  },
97  sections: {
98    here: (n: number) => `This repo ${n}`,
99    all: (n: number) => `All ${n}`,
100    session: (n: number) => `In progress in a session ${n}`,
101    hidden: (n: number) => `${n} hidden · show all`,
102    direct: (n: number) => `Direct requests ${n}`,
103    team: (n: number) => `Team requests ${n}`,
104    drafts: (n: number) => `Drafts · not ready for review ${n}`,
105    references: (days: number, n: number) => `Last ${days} days · my work referenced elsewhere ${n}`,
106  },
107  note: {
108    edit: 'Note',
109    label: 'Note',
110    placeholder: 'What you looked at or plan to do',
111    save: 'Save',
112    tomorrow: 'Snooze until tomorrow',
113    nextWeek: 'Snooze until next week',
114    cancel: 'Cancel',
115    clear: 'Clear',
116    shown: (text: string) => `Note: ${text}`,
117    until: (month: number, day: number) => `snoozed until ${month}/${day}`,
118  },
119  session: {
120    here: 'this session',
121    at: (names: string) => `Working in ${names}`,
122  },
123  search: {
124    label: 'Search',
125    placeholder: 'repo, #number, title, description or note',
126    empty: 'Nothing matches.',
127    hidden: 'hidden',
128  },
129  toast: {
130    away: 'While you were away',
131    back: 'Back from snooze',
132    added: (n: number) => `${count(n, 'card')} added · Esc puts their requests in the prompt`,
133    newRequest: 'New review request',
134    moreRequests: (n: number) => count(n, 'more review request'),
135    morePrAlerts: (n: number) => `${count(n, 'more alert')} on my PRs`,
136    moreIssueAlerts: (n: number) => count(n, 'more issue alert'),
137    promptBusy: 'The prompt is busy. Close the open dialog and press again.',
138    retry: 'Try again in a moment.',
139  },
140  alert: {
141    ready: 'Ready to merge',
142    turned: (state: string) => `My PR: ${state}`,
143    reviewed: 'New review on my PR',
144    by: (who: string) => `new review ${who}`,
145  },
146  buttons: {
147    more: "Actions",
148    none: "No buttons of my own yet; the built-in ones are shown.",
149    counts: (buttons: number, groups: number) => `Of my own: ${buttons} buttons, ${groups} saved searches`,
150    how: "/review-inbox add-button or /review-inbox add-search asks Claude to write one with you.",
151    hint: "See /review-inbox buttons",
152    file: (path: string) => `My buttons: ${path}`,
153    tooMany: (n: number, scope: string) => `${n} buttons on ${scope} cards; past 20 the row gets hard to scan`,
154    scopes: { review: "review", pr: "my PR", issue: "issue" },
155    errors: {
156      file: "not JSON with a \"buttons\" or \"groups\" list; only the built-in ones are shown",
157      fields: "needs an id, a name and a prompt",
158      scope: (scope: string) => `scope "${scope}" is not review, pr or issue`,
159      variables: (names: string) => `unknown variable ${names}`,
160      groupFields: "a saved search needs an id, a name and a query",
161      groupScope: (scope: string) => `saved search scope "${scope}" is not prs or issues`,
162    },
163    builtIn: {
164      "summarize-risks": { name: "Summarize risks", prompt: "Summarize the risks in {{.PrUrl}}: read the diff with `gh pr diff {{.PrUrl}}` and list what could break, for whom, and what to test first. Change nothing." },
165      "explain-diff": { name: "Explain this diff", prompt: "Explain the diff of {{.PrUrl}} file by file in plain language, so I can review it quickly; read it with `gh pr diff {{.PrUrl}}`." },
166      "draft-approval": { name: "Draft approval comment", prompt: "Draft an approval comment for {{.PrUrl}}: one or two sentences on what is good, then any small follow-ups. Read the diff with `gh pr diff {{.PrUrl}}`. Do not post it; show it to me." },
167      "draft-reply": { name: "Draft reply to reviewer", prompt: "Draft a reply to each reviewer on {{.PrUrl}}; read their comments with `gh pr view {{.PrUrl}} --comments`. Do not post anything; show me the drafts." },
168      "investigate-ci": { name: "Investigate CI failure", prompt: "Investigate the CI failure on {{.PrUrl}}: find the failing checks with `gh pr checks {{.PrUrl}}` and their logs with `gh run view <run-id> --log-failed`, then tell me the cause and the fix. Change nothing yet." },
169    },
170  },
171  searches: {
172    builtIn: { 'involves-me': "Involves me", 'reviewed-by-me': "Reviewed by me, still open", 'my-open-issues': "My open issues" },
173    none: "Nothing found.",
174    failed: (message: string) => `Search failed: ${message}`,
175    more: (n: number) => `${n} more on GitHub`,
176    tooMany: (n: number) => `${n} saved searches past the first 15 are left out`,
177  },
178  activity: {
179    reasons: { comment: "Comment", state_change: "State changed", author: "You opened it", team_mention: "Team mentioned", security_alert: "Security alert", ci_activity: "CI run" },
180    done: "Done",
181    unsubscribe: "Unsubscribe",
182    wasDone: "Done",
183    wasUnsubscribed: "Unsubscribed",
184    undo: "Undo",
185    failed: (message: string) => `Could not update the notification: ${message}`,
186    noAccess: "No access to notifications. GitHub gives them only to gh's own sign-in or a classic token: run gh auth login, or gh auth refresh -s notifications.",
187  },
188  direct: {
189    label: { approve: "Approve", ready: "Ready for review", 'update-branch': "Update branch", rerun: "Rerun failed CI", assign: "Assign me" },
190    merge: "Merge",
191    confirm: { approve: "Confirm approve", ready: "Confirm ready", 'update-branch': "Confirm update branch" },
192    cancel: "Cancel",
193    ask: { approve: (target: string, login: string) => `Approve ${target} as ${login} — (no comment)`, ready: (target: string, login: string) => `Mark ${target} ready for review as ${login} — code owners are asked to review`, 'update-branch': (target: string, login: string) => `Update ${target} as ${login} — its base branch is merged in` },
194    sending: "Sending to GitHub…",
195    done: { approve: "Approved", ready: "Ready for review", 'update-branch': "Branch updated", rerun: "Rerunning failed jobs", assign: "Assigned to you" },
196    failed: (message: string) => `GitHub did not take it: ${message}`,
197    newCommits: "New commits since you looked: refresh and read them first.",
198    noRun: "No failed GitHub Actions run on the latest commit; rerun other checks on GitHub.",
199    mergePrompt: "Merge {{.PrUrl}}. First check which merge methods the repository allows and whether auto-merge is on, then run `gh pr merge {{.PrNumber}} --repo {{.RepoName}} --squash`: add `--auto` when auto-merge is on, and use an allowed method if squash is not.",
200  },
201  prompt: {
202    addButton: (path: string, names: string) => `Add a button to my review inbox by editing ${path}; create it as {"buttons": []} if it is missing. Each entry is {"id", "name", "scope": "review" | "pr" | "issue", "prompt"}, and the prompt may use {{.Name}} with ${names}. Ask me what the button should do first.`,
203    addGroup: (path: string) => `Add a saved search to my review inbox by editing ${path}; create it as {"groups": []} if it is missing and keep any "buttons" in it. Each entry is {"id", "name", "query", "scope": "prs" | "issues"}, with "countInBand": true to count it in the band; the query is GitHub search syntax. Ask me what it should find first.`,
204    review: (url: string) => `Review ${url}.`,
205    check: 'Check in particular: ',
206    since: 'Changed since my last review: ',
207    style: 'My usual review style: ',
208    // Commands, not data: Claude reads the comments, checks and logs itself, so no outside text lands in the prompt.
209    task: {
210      changes: (url: string) => `Address the unresolved review comments on ${url}; read them with \`gh pr view ${url} --comments\`.`,
211      'ci-failing': (url: string) =>
212        `Fix the failing CI on ${url}: find the failing checks with \`gh pr checks ${url}\` and their logs with \`gh run view <run-id> --log-failed\`.`,
213      conflict: (url: string, base?: string) =>
214        `Resolve the merge conflict on ${url}: merge ${base ? `origin/${base}` : 'its base branch'} into its branch.`,
215      work: (url: string) => `Work on ${url}: read the issue, plan the change, and start on a new branch.`,
216    } satisfies Record<TaskKind, (url: string, base?: string) => string>,
217    here: 'this folder',
218    workIn: (where: string, isPr: boolean) =>
219      isPr
220        ? `Work in ${where}, in a new worktree with the PR checked out (\`gh pr checkout\` handles forks); leave the folder's current branch as it is.`
221        : `Work in ${where}, in a new worktree on a new branch; leave the folder's current branch as it is.`,
222    noClone: (repo: string) => `No local clone of ${repo} is known: ask me where it is, or offer \`gh repo clone ${repo}\` and wait for my yes.`,
223  },
224  summaryFailed: (reason: string) => `Could not write a summary (${reason}).`,
225  // The language lines of the model instructions; the rest of the rules are shared.
226  model: {
227    language: 'Write in plain English, as if explaining to a junior developer.',
228    sentence: 'Each sentence about 15 words, one idea per sentence.',
229    filler: 'No filler words such as effectively, overall, various, seamless.',
230    bad: 'Refactored the UserCache class to unify the SessionStore lookup path.',
231    good: 'Fixes the profile picture that sometimes showed blank right after login.',
232    since: 'Write in plain English, one or two short sentences, about 15 words each.',
233    style: 'Write in plain English.',
234  },
235}
236
237export type Messages = typeof en
238
239export const LANGUAGES = ['en', 'ko', 'ja', 'zh-CN', 'zh-TW', 'es', 'pt-BR', 'de', 'fr'] as const
240export type Language = (typeof LANGUAGES)[number]
241
242export const MESSAGES: Record<Language, Messages> = { en, ko, ja, 'zh-CN': zhCN, 'zh-TW': zhTW, es, 'pt-BR': ptBR, de, fr }
243
244export const isLanguage = (value: unknown): value is Language => (LANGUAGES as readonly unknown[]).includes(value)
245
246// A code must end where the value ends or at a region or encoding separator, so "kotlin" or "default" names no language.
247const NAMES: [Language, RegExp][] = [
248  ['ko', /^(kor?([-_.@]|$)|korean|한국|한글)/],
249  ['en', /^(eng?([-_.@]|$)|english|영어)/],
250  ['ja', /^((ja|jpn?)([-_.@]|$)|japanese|日本)/],
251  ['es', /^((es|spa)([-_.@]|$)|spanish|espa[ñn]ol|castellano)/],
252  ['pt-BR', /^((pt|por)([-_.@]|$)|portuguese|portugu[eê]s)/],
253  ['de', /^((de|deu|ger)([-_.@]|$)|german|deutsch)/],
254  ['fr', /^((fr|fra|fre)([-_.@]|$)|french|fran[çc]ais)/],
255]
256
257// Claude Code's `language` setting is free text ("日本語", "Korean", "zh-TW"), and a locale reads "ja_JP.UTF-8".
258function recognize(value: unknown): Language | undefined {
259  if (typeof value !== 'string') return undefined
260  const v = value.trim().toLowerCase()
261  // Chinese, named anywhere ("Simplified Chinese"), reads Simplified unless it carries a Taiwan, Hong Kong, Macau or Traditional mark.
262  if (/^(zh|zho|chi)([-_.@]|$)|chinese|中文|汉语|漢語|简体|簡體|繁體|繁体|正體/.test(v)) {
263    return /[-_](tw|hk|mo|hant)\b|traditional|繁|正體/.test(v) ? 'zh-TW' : 'zh-CN'
264  }
265  return NAMES.find(([, pattern]) => pattern.test(v))?.[0]
266}
267
268// The plugin option wins; `auto` follows Claude Code's language setting, then the system locale, then English.
269export function pickLanguage(option: unknown, claudeLanguage: unknown, locale: unknown): Language {
270  if (isLanguage(option)) return option
271  return recognize(claudeLanguage) ?? recognize(locale) ?? 'en'
272}
273
hooks/notes.ts 33 lines
1import type { Note } from '../types'
2
3// shortcut: the first 2,000 characters of a body are searched; raise it if bodies are searched past that, mindful of gh's 4 MiB output cap
4export const BODY_CHARS = 2_000
5// A note outlives its card this long, so a PR that drops off a list and comes back keeps it.
6export const NOTE_KEEP_MS = 60 * 86_400_000
7
8// Nine in the morning, local time: tomorrow, or the next Monday.
9export function snoozeUntil(when: 'tomorrow' | 'nextWeek', now: Date): number {
10  const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 9)
11  if (when === 'nextWeek') while (day.getDay() !== 1) day.setDate(day.getDate() + 1)
12  return day.getTime()
13}
14
15// Away until its day, or sooner when the card has the news that would end a hide: `stillHidden` is that card's hide test.
16export function isSnoozed(
17  note: Note | undefined,
18  key: string,
19  now: number,
20  stillHidden: (hidden: Record<string, string>) => boolean,
21): boolean {
22  return note?.until !== undefined && note.mark !== undefined && now < note.until && stillHidden({ [key]: note.mark })
23}
24
25export function matches(query: string, fields: (string | undefined)[]): boolean {
26  const text = fields.filter(Boolean).join('\n').toLowerCase()
27  return query.toLowerCase().split(/\s+/).filter(Boolean).every(word => text.includes(word))
28}
29
30export function keptNotes(notes: Record<string, Note>, live: Set<string>, now: number): Record<string, Note> {
31  return Object.fromEntries(Object.entries(notes).filter(([key, note]) => live.has(key) || now - note.savedAt < NOTE_KEEP_MS))
32}
33
hooks/sessions.ts 94 lines
1import type { Presence, RepoPaths } from '../types'
2
3// A session checks in every 30 seconds; one silent this long was closed or killed without a word.
4export const SESSION_STALE_MS = 10 * 60_000
5
6// shortcut: github.com remotes only, so under GH_HOST a session is found by its links alone; match that host too if Enterprise users ask
7export function repoOf(remote: string): string | undefined {
8  return /github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/.exec(remote)?.[1]
9}
10
11export function liveSessions(sessions: Record<string, Presence>, now: number): Record<string, Presence> {
12  return Object.fromEntries(Object.entries(sessions).filter(([, s]) => now - s.at < SESSION_STALE_MS))
13}
14
15// The folders of other sessions running an older release than mine; one that states none predates the field.
16export function olderSessions(sessions: Record<string, Presence>, selfId: string, version: string | undefined): string[] {
17  if (!version) return []
18  return Object.entries(sessions)
19    .filter(([id, s]) => id !== selfId && (!s.version || s.version.localeCompare(version, undefined, { numeric: true }) < 0))
20    .map(([, s]) => s.folder)
21}
22
23// A request from a newer release, in reload.json, for the sessions behind it to reload.
24export type ReloadRequest = { version: string; at: number }
25
26// Only a session loaded before the request answers it, so each answers once and one opened since never does.
27export function shouldReload(request: ReloadRequest | undefined, version: string | undefined, loadedAt: number): boolean {
28  if (!request || !version || request.at <= loadedAt) return false
29  return version.localeCompare(request.version, undefined, { numeric: true }) < 0
30}
31
32// The sessions working on a PR: checked out on its branch in its repository, or asked about it by link.
33export function workingOn(sessions: Record<string, Presence>, pr: { repo: string; url: string; branch?: string }): string[] {
34  return Object.entries(sessions)
35    .filter(([, s]) => s.prs.includes(pr.url) || (pr.branch !== undefined && s.branch === pr.branch && s.remotes.includes(pr.repo)))
36    .map(([id]) => id)
37}
38
39// Where Claude works on a repository: this session's folder, a folder remembered for it, or nowhere known yet.
40export type Place = { kind: 'here' } | { kind: 'folder'; path: string } | { kind: 'unknown' }
41
42const slashes = (path: string) => path.replace(/\\/g, '/').replace(/\/$/, '')
43
44// The common dir names the main checkout's .git from inside any of its worktrees; a bare repository or my home folder maps nothing.
45export function mainCheckout(commonDir: string, home: string): string | undefined {
46  const dir = commonDir.trim()
47  if (!dir.endsWith('/.git')) return undefined
48  const top = dir.slice(0, -'/.git'.length)
49  return slashes(top) === slashes(home) ? undefined : top
50}
51
52export function remember(repos: RepoPaths, remotes: string[], path: string, now: number): RepoPaths {
53  return { ...repos, ...Object.fromEntries(remotes.map(repo => [repo, { path, at: now }])) }
54}
55
56// A folder the repoPaths option names comes first, as the person set it on purpose.
57export function placeOf(repo: string, self: Presence | undefined, repos: RepoPaths, mapped?: string): Place {
58  if (mapped) return { kind: 'folder', path: mapped }
59  if (self?.remotes.includes(repo)) return { kind: 'here' }
60  const known = repos[repo]
61  return known ? { kind: 'folder', path: known.path } : { kind: 'unknown' }
62}
63
64// The repoPaths option: `owner/repo=path` or `owner/*=path/*`, comma-separated, as gh-dash's repoPaths.
65export function parseRepoPaths(text: string): Record<string, string> {
66  return Object.fromEntries(
67    text.split(',').flatMap(entry => {
68      const at = entry.indexOf('=')
69      const [repo, path] = [entry.slice(0, at).trim(), entry.slice(at + 1).trim()]
70      return at > 0 && path && /^[^/\s]+\/[^/\s]+$/.test(repo) ? [[repo.toLowerCase(), path]] : []
71    }),
72  )
73}
74
75// An exact name wins over its owner's wildcard; `*` in the path is the repository's name and a leading ~ is home.
76export function mappedPath(repo: string, paths: Record<string, string>, home: string): string | undefined {
77  const [owner = '', name = ''] = repo.toLowerCase().split('/')
78  const path = paths[repo.toLowerCase()] ?? paths[`${owner}/*`]?.replaceAll('*', repo.split('/')[1] ?? name)
79  return path?.replace(/^~(?=$|[\\/])/, home)
80}
81
82// What gh itself treats as the current repository: GH_REPO ([HOST/]OWNER/REPO) when set, else the folder's remotes.
83export function thisRepos(self: Presence | undefined, ghRepo: string | undefined): string[] {
84  const parts = (ghRepo ?? '').trim().split('/').filter(Boolean)
85  return parts.length >= 2 ? [parts.slice(-2).join('/')] : (self?.remotes ?? [])
86}
87
88export const isHere = (repo: string, here: string[]) => here.some(r => r.toLowerCase() === repo.toLowerCase())
89
90export const hereFirst = <T extends { repo: string }>(cards: T[], here: string[]) => [
91  ...cards.filter(c => isHere(c.repo, here)),
92  ...cards.filter(c => !isHere(c.repo, here)),
93]
94
hooks/pages.ts 56 lines
1// Every search reads GitHub a page at a time, so no single request grows with the account:
2// GitHub gives up on a query after about 10 s, however many nodes it was asked for.
3export const PAGE_SIZE = 25
4// A page that times out is asked again at half the size, down to this.
5export const MIN_PAGE = 5
6// One tab's search reads at most this many; past it, its count reads as at least that many.
7export const SEARCH_LIMIT = 100
8
9export type Page<T> = {
10  viewer?: { login: string }
11  search: { issueCount?: number; pageInfo: { hasNextPage: boolean; endCursor?: string | null }; nodes: Partial<T>[] }
12}
13
14// Each paged query takes these two variables and asks `pageInfo { hasNextPage endCursor }`.
15export const PAGE_ARGS = '$first: Int!, $after: String'
16export const PAGE = 'first: $first, after: $after'
17
18// GitHub's timeout comes back as an HTML error page that gh cannot parse.
19export const isGatewayTimeout = (message: string) => /HTTP 50[234]|invalid character '<'/.test(message)
20
21export const smallerPage = (size: number) => (size > MIN_PAGE ? Math.max(MIN_PAGE, Math.floor(size / 2)) : undefined)
22
23// What a paged search read: its nodes, whether more were left, and the login and count when asked.
24export type Pages<T> = { login?: string; count?: number; nodes: Partial<T>[]; capped: boolean }
25
26// Pages until GitHub has no more or `limit` nodes are read; `capped` says there were more, `count` how many when the query asks.
27export async function readPages<T>(
28  fetchPage: (first: number, after?: string) => Promise<Page<T>>,
29  limit: number,
30  size = PAGE_SIZE,
31): Promise<Pages<T>> {
32  const nodes: Partial<T>[] = []
33  let after: string | undefined
34  let login: string | undefined
35  let count: number | undefined
36  for (;;) {
37    let page: Page<T>
38    try {
39      page = await fetchPage(Math.min(size, limit - nodes.length), after)
40    } catch (error) {
41      const smaller = isGatewayTimeout(error instanceof Error ? error.message : String(error)) ? smallerPage(size) : undefined
42      if (smaller === undefined) throw error
43      // The rest of this search keeps the smaller size: its nodes are the heavy ones.
44      size = smaller
45      continue
46    }
47    login ??= page.viewer?.login
48    count ??= page.search.issueCount
49    nodes.push(...page.search.nodes)
50    const { hasNextPage, endCursor } = page.search.pageInfo
51    if (!hasNextPage || !endCursor) return { login, count, nodes, capped: false }
52    if (nodes.length >= limit) return { login, count, nodes, capped: true }
53    after = endCursor
54  }
55}
56
hooks/style.ts 85 lines
1import { MESSAGES } from './i18n'
2import type { Language } from './i18n'
3import { PAGE, PAGE_ARGS } from './pages'
4
5// PRs I reviewed and did not write, newest first; only my own reviews are kept, cut short, to stay far below gh's output cap.
6export const STYLE_QUERY = `query($q: String!, ${PAGE_ARGS}) {
7  viewer { login }
8  search(query: $q, type: ISSUE, ${PAGE}) {
9    pageInfo { hasNextPage endCursor }
10    nodes { ... on PullRequest { reviews(last: 20) { nodes { author { login } body comments(first: 20) { nodes { body } } } } } }
11  }
12}`
13export const STYLE_JQ =
14  '.data | .viewer.login as $me | .search.nodes |= map(if .reviews then .reviews.nodes |= map(select(.author.login == $me) | .body |= .[:500] | .comments.nodes |= map(.body |= .[:500])) else . end)'
15
16// Enough PRs to fill the samples; the newest say the most about how I review now.
17export const STYLE_PRS = 30
18
19export function styleQuery(scope: string): string {
20  return ['is:pr reviewed-by:@me -author:@me sort:updated-desc', scope.trim()].filter(Boolean).join(' ')
21}
22
23export type GqlReviewed = {
24  reviews: { nodes: { author: { login: string } | null; body: string; comments: { nodes: { body: string }[] } }[] }
25}
26
27const SAMPLE_CHARS = 500
28const MAX_SAMPLES = 60
29const MAX_SAMPLE_TOTAL = 12_000
30
31// My review bodies and inline comments, newest PRs first, capped so one long thread can't crowd out the rest.
32export function styleSamples(nodes: Partial<GqlReviewed>[], me: string): string[] {
33  const samples: string[] = []
34  let total = 0
35  for (const pr of nodes) {
36    for (const review of pr.reviews?.nodes ?? []) {
37      if (review.author?.login.toLowerCase() !== me.toLowerCase()) continue
38      for (const body of [review.body, ...(review.comments?.nodes ?? []).map(c => c.body)]) {
39        const text = (body ?? '').trim().slice(0, SAMPLE_CHARS)
40        if (!text) continue
41        if (samples.length >= MAX_SAMPLES || total + text.length > MAX_SAMPLE_TOTAL) return samples
42        samples.push(text)
43        total += text.length
44      }
45    }
46  }
47  return samples
48}
49
50// Fewer recent reviews than this say too little about how I write; the prompt then goes without a style line.
51export const MIN_STYLE_SAMPLES = 5
52
53export function stylePrompt(samples: string[]): string | undefined {
54  if (samples.length < MIN_STYLE_SAMPLES) return undefined
55  return `Past review comments, newest first:\n\n${samples.map(s => `---\n${s}`).join('\n')}`
56}
57
58export const STYLE_MS = 7 * 86_400_000
59export const STYLE_RETRY_MS = 86_400_000
60const MAX_STYLE_CHARS = 600
61
62// Shared by every session like the inbox: the learned style, when it was last learned, and when to retry after a failure.
63export type StyleFile = { profile?: string; checkedAt?: number; samples?: number; retryAt?: number }
64
65export function shouldBuildStyle(file: StyleFile, now: number): boolean {
66  if (file.retryAt !== undefined) return now >= file.retryAt
67  return file.checkedAt === undefined || now - file.checkedAt >= STYLE_MS
68}
69
70export function styleRules(language: Language): string {
71  return `You describe how one person writes code reviews, so an assistant can review a pull request the way they would.
72${MESSAGES[language].model.style}
73
74Read their past review comments and reply with two to four short sentences in one paragraph, covering:
75- the language and tone they review in, such as short and direct or polite questions
76- what they usually look at first
77- how they phrase requests, and how long their comments are
78Describe the style; do not give advice. No quotes, names, repository names, code, file paths or issue numbers.
79Reply with the paragraph only.`
80}
81
82export function parseStyle(text: string): string | undefined {
83  return text.replace(/\s+/g, ' ').trim().slice(0, MAX_STYLE_CHARS) || undefined
84}
85
hooks/tabs.ts 327 lines
1import type { Capped, IssueItem, MyPr, MyPrState, TaskKind } from '../types'
2import type { Messages } from './i18n'
3import { DETAILS_FIELDS, detailsOf, hasRequest } from './inbox'
4import type { GqlDetails } from './inbox'
5import { PAGE, PAGE_ARGS } from './pages'
6import type { Place } from './sessions'
7
8type Repo = { repository: { nameWithOwner: string; defaultBranchRef?: { name: string } | null } }
9type Item = Repo & { number: number; title: string; url: string }
10type Body = { body?: string | null }
11
12export type GqlMyPr = Item & Body & GqlDetails & {
13  headRefName?: string
14  baseRefName?: string
15  isDraft: boolean
16  createdAt: string
17  updatedAt?: string
18  isInMergeQueue?: boolean
19  headRefOid?: string
20  mergeStateStatus?: string
21  reviewDecision: 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED' | null
22  mergeable: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'
23  commits: { nodes: { commit: { committedDate: string; statusCheckRollup: { state: string } | null } }[] }
24  reviews: { nodes: { state: string; submittedAt: string | null; author: { login: string } | null }[] }
25}
26
27export type GqlTouched = Item & Body & GqlDetails & { updatedAt: string }
28
29export type GqlReferenced = Repo & {
30  number: number
31  timelineItems: {
32    nodes: { createdAt: string; actor: { login: string } | null; source: Partial<Item> }[]
33  }
34}
35
36const tabSearch = (nodes: string) => `query($q: String!, ${PAGE_ARGS}) {
37  viewer { login }
38  search(query: $q, type: ISSUE, ${PAGE}) { pageInfo { hasNextPage endCursor } nodes { ${nodes} } }
39}`
40
41// One search per tab list, each paged on its own: together they outran GitHub's ~10 s limit on accounts with many PRs.
42export const TAB_QUERIES = {
43  mine: tabSearch(`... on PullRequest {
44    number title url body headRefName baseRefName isDraft createdAt updatedAt isInMergeQueue headRefOid mergeStateStatus repository { nameWithOwner defaultBranchRef { name } } reviewDecision mergeable
45    ${DETAILS_FIELDS}
46    commits(last: 1) { nodes { commit { committedDate statusCheckRollup { state } } } }
47    reviews(last: 30) { nodes { state submittedAt author { login } } } }`),
48  assigned: tabSearch(`... on Issue { number title url body updatedAt repository { nameWithOwner } ${DETAILS_FIELDS} }`),
49  mentioned: tabSearch(
50    `... on Issue { number title url body updatedAt repository { nameWithOwner } ${DETAILS_FIELDS} }
51    ... on PullRequest { number title url body updatedAt repository { nameWithOwner } ${DETAILS_FIELDS} }`,
52  ),
53}
54
55// My PRs and issues touched lately, with who pointed at them from elsewhere.
56export const REFERENCES_QUERY = `query($q: String!, $since: DateTime!, ${PAGE_ARGS}) {
57  search(query: $q, type: ISSUE, ${PAGE}) {
58    pageInfo { hasNextPage endCursor }
59    nodes {
60      ... on PullRequest { number repository { nameWithOwner }
61        timelineItems(itemTypes: [CROSS_REFERENCED_EVENT], since: $since, last: 20) { nodes { ...ref } } }
62      ... on Issue { number repository { nameWithOwner }
63        timelineItems(itemTypes: [CROSS_REFERENCED_EVENT], since: $since, last: 20) { nodes { ...ref } } }
64    }
65  }
66}
67fragment ref on CrossReferencedEvent {
68  createdAt actor { login }
69  source { ... on PullRequest { number title url repository { nameWithOwner } }
70           ... on Issue { number title url repository { nameWithOwner } } }
71}`
72
73export const REFERENCE_DAYS = 30
74// A references node is a few small timeline events, so a page of 100 stays well inside GitHub's time limit:
75// measured on one account, 286 items took 3 requests and 6 s instead of 12 requests and 15 s at the default page.
76export const REFERENCE_PAGE = 100
77// A reference does not bump the referenced item's updatedAt, so items are picked from a wider window than the events.
78// ponytail: measured on one account, every missed reference was on an item touched 30-60 days before; older ones are still missed
79export const AUTHORED_DAYS = 60
80// ponytail: newest references only; a busy month had 50+, more than a drawer can show usefully
81const MAX_REFERENCES = 20
82
83// Newest activity first, so the page caps drop the stalest items rather than arbitrary ones.
84export function tabQueries(scope: string) {
85  const q = (base: string) => [base, 'sort:updated-desc', scope.trim()].filter(Boolean).join(' ')
86  return {
87    mine: q('is:pr is:open author:@me'),
88    assigned: q('is:issue is:open assignee:@me'),
89    mentioned: q('is:open mentions:@me'),
90  }
91}
92
93export function referencesQuery(scope: string, touchedSince: string): string {
94  return [`author:@me updated:>=${touchedSince.slice(0, 10)} sort:updated-desc`, scope.trim()].filter(Boolean).join(' ')
95}
96
97// Ordered by what I have to do next.
98export const ORDER: MyPrState[] = ['changes', 'ci-failing', 'conflict', 'waiting', 'approved', 'queued', 'draft']
99
100export function myPrState(pr: GqlMyPr): MyPrState {
101  const ci = pr.commits.nodes[0]?.commit.statusCheckRollup?.state
102  if (pr.isDraft) return 'draft'
103  // Nothing left for me: GitHub merges it once the queue's checks pass, or drops it back to a state that is.
104  if (pr.isInMergeQueue) return 'queued'
105  if (pr.reviewDecision === 'CHANGES_REQUESTED') return 'changes'
106  if (ci === 'FAILURE' || ci === 'ERROR') return 'ci-failing'
107  // UNKNOWN is GitHub not having computed it yet, not a conflict.
108  if (pr.mergeable === 'CONFLICTING') return 'conflict'
109  if (pr.reviewDecision === 'APPROVED') return 'approved'
110  return 'waiting'
111}
112
113// A review submitted after my latest commit is one I have not answered with a commit yet.
114// Compared by time, not by the review's commit: a thread reply stays pinned to the commit its thread started on.
115export function newReviews(pr: GqlMyPr, me: string): MyPr['newReviews'] {
116  const head = Date.parse(pr.commits.nodes[0]?.commit.committedDate ?? '') || 0
117  return pr.reviews.nodes
118    .filter(r => r.state !== 'PENDING' && r.state !== 'DISMISSED' && r.author && r.author.login.toLowerCase() !== me.toLowerCase())
119    .filter(r => r.submittedAt && Date.parse(r.submittedAt) > head)
120    .map(r => ({ by: r.author!.login, at: r.submittedAt! }))
121}
122
123export function toMyPrs(prs: GqlMyPr[], me: string): MyPr[] {
124  return prs
125    .map(pr => ({
126      repo: pr.repository.nameWithOwner,
127      number: pr.number,
128      title: pr.title,
129      url: pr.url,
130      createdAt: pr.createdAt,
131      ...(pr.updatedAt ? { updatedAt: pr.updatedAt } : {}),
132      state: myPrState(pr),
133      ...(pr.headRefOid ? { headSha: pr.headRefOid } : {}),
134      ...(pr.mergeStateStatus === 'BEHIND' ? { isBehind: true } : {}),
135      ciPending: ['PENDING', 'EXPECTED'].includes(pr.commits.nodes[0]?.commit.statusCheckRollup?.state ?? ''),
136      newReviews: newReviews(pr, me),
137      ...(pr.body ? { body: pr.body } : {}),
138      ...(pr.headRefName ? { branch: pr.headRefName } : {}),
139      ...(pr.baseRefName ? { base: pr.baseRefName } : {}),
140      ...detailsOf(pr),
141    }))
142    .sort(
143      (a, b) =>
144        ORDER.indexOf(a.state) - ORDER.indexOf(b.state) ||
145        Number(b.newReviews.length > 0) - Number(a.newReviews.length > 0) ||
146        Date.parse(a.createdAt) - Date.parse(b.createdAt),
147    )
148}
149
150// References by others to my items, newest first.
151export function toReferences(referenced: GqlReferenced[], me: string): IssueItem[] {
152  return referenced
153    .flatMap(target =>
154      target.timelineItems.nodes
155        // Links I made between my own PRs are not news.
156        .filter(e => e.actor && e.actor.login.toLowerCase() !== me.toLowerCase() && e.source.url)
157        .map(e => ({
158          kind: 'reference' as const,
159          repo: e.source.repository!.nameWithOwner,
160          number: e.source.number!,
161          title: e.source.title!,
162          url: e.source.url!,
163          at: e.createdAt,
164          by: e.actor!.login,
165          target: `${target.repository.nameWithOwner}#${target.number}`,
166        })),
167    )
168    .sort((a, b) => Date.parse(b.at) - Date.parse(a.at))
169}
170
171export function toIssues(assigned: GqlTouched[], mentioned: GqlTouched[], references: IssueItem[]): IssueItem[] {
172  const seen = new Set<string>()
173  const out: IssueItem[] = []
174  const add = (kind: IssueItem['kind'], i: GqlTouched) => {
175    // Assigned wins over a mention of the same thread.
176    if (seen.has(i.url)) return
177    seen.add(i.url)
178    out.push({ kind, repo: i.repository.nameWithOwner, number: i.number, title: i.title, url: i.url, at: i.updatedAt, ...(i.body ? { body: i.body } : {}), ...detailsOf(i) })
179  }
180  assigned.forEach(i => add('assigned', i))
181  mentioned.forEach(i => add('mention', i))
182
183  const keys = new Set<string>()
184  const rest = references
185    // A thread already listed for me directly, or the same link seen twice, shows once.
186    .filter(r => !seen.has(r.url) && !keys.has(issueKey(r)) && keys.add(issueKey(r)))
187    .slice(0, MAX_REFERENCES)
188
189  return [...out.sort((a, b) => Date.parse(b.at) - Date.parse(a.at)), ...rest]
190}
191
192export function stateColor(state: MyPrState): 'error' | 'warning' | 'success' | 'subtle' | 'inactive' {
193  return state === 'changes' || state === 'ci-failing'
194    ? 'error'
195    : state === 'conflict'
196      ? 'warning'
197      : state === 'approved' || state === 'queued'
198        ? 'success'
199        : state === 'draft'
200          ? 'inactive'
201          : 'subtle'
202}
203
204const stuck = (pr: MyPr) => pr.state === 'changes' || pr.state === 'ci-failing' || pr.state === 'conflict'
205export const needsMe = (pr: MyPr) => stuck(pr) || pr.newReviews.length > 0
206
207export type Task = { kind: TaskKind; repo: string; url: string; base?: string }
208
209export function taskOf(card: MyPr | IssueItem): TaskKind | undefined {
210  if ('state' in card) return stuck(card) ? (card.state as TaskKind) : undefined
211  return card.kind === 'assigned' ? 'work' : undefined
212}
213
214// Like the review requests: one per card the draft does not link yet, each saying where to work.
215export function taskPrompts(draft: string, tasks: { task: Task; place: Place }[], m: Messages): string {
216  let text = draft
217  for (const { task, place } of tasks) {
218    if (hasRequest(text, task.url)) continue
219    const where =
220      place.kind === 'unknown'
221        ? m.prompt.noClone(task.repo)
222        : m.prompt.workIn(place.kind === 'here' ? m.prompt.here : place.path, task.kind !== 'work')
223    const lines = `${m.prompt.task[task.kind](task.url, task.base)}\n${where}\n`
224    text += text === '' || text.endsWith('\n') ? lines : `\n${lines}`
225  }
226  return text.slice(draft.length)
227}
228
229export const reviewers = (pr: MyPr) => [...new Set(pr.newReviews.map(r => r.by))].join(', ')
230
231// One alert per PR: it turned to a state that needs me or became ready to merge, new reviews arrived, or both.
232export type PrAlert = { pr: MyPr; turned: boolean; ready?: boolean; by?: string }
233
234const stateKey = (pr: MyPr) => `${pr.url}@${pr.state}`
235// Approved with no CI running: the only success worth a toast, as CI passing alone is no news.
236const isReady = (pr: MyPr) => pr.state === 'approved' && !pr.ciPending
237const readyKey = (pr: MyPr) => `${pr.url}@ready`
238const reviewKey = (pr: MyPr, r: MyPr['newReviews'][number]) => `${pr.url}@review:${r.by}@${r.at}`
239
240export function prAlerts(seen: string[] | undefined, prs: MyPr[]): PrAlert[] {
241  if (seen === undefined) return []
242  const known = new Set(seen)
243  return prs.flatMap(pr => {
244    const turned = stuck(pr) && !known.has(stateKey(pr))
245    const ready = isReady(pr) && !known.has(readyKey(pr))
246    const fresh = pr.newReviews.filter(r => !known.has(reviewKey(pr, r)))
247    if (!turned && !ready && fresh.length === 0) return []
248    return [{ pr, turned, ...(ready ? { ready } : {}), ...(fresh.length > 0 ? { by: [...new Set(fresh.map(r => r.by))].join(', ') } : {}) }]
249  })
250}
251
252export function prAlertText({ pr, turned, ready, by }: PrAlert, m: Messages): string {
253  const head = turned ? m.alert.turned(m.state[pr.state]) : ready ? m.alert.ready : m.alert.reviewed
254  return [head, (turned || ready) && by ? m.alert.by(by) : by, `${pr.repo} #${pr.number}`]
255    .filter(Boolean)
256    .join(' · ')
257}
258
259// One toast for what changed while no session was open: each kind of news with how many, a PR counted once as prAlertText heads it.
260export function awayText(requests: number, prNews: PrAlert[], issues: IssueItem[], m: Messages): string | undefined {
261  const labels = [
262    ...Array<string>(requests).fill(m.toast.newRequest),
263    ...prNews.map(({ pr, turned, ready }) => (turned ? m.state[pr.state] : ready ? m.alert.ready : m.alert.reviewed)),
264    ...issues.map(i => m.issueKind[i.kind]),
265  ]
266  if (labels.length === 0) return undefined
267  const counts = new Map<string, number>()
268  for (const label of labels) counts.set(label, (counts.get(label) ?? 0) + 1)
269  return [m.toast.away, ...[...counts].map(([label, n]) => `${label} ${n}`)].join(' · ')
270}
271
272export const prSeenKeys = (prs: MyPr[]) =>
273  prs.flatMap(pr => [stateKey(pr), ...(isReady(pr) ? [readyKey(pr)] : []), ...pr.newReviews.map(r => reviewKey(pr, r))])
274
275export const issueKey = (i: IssueItem) => `${i.kind}:${i.url}:${i.target ?? ''}`
276
277// Hidden until it turns to another state or someone reviews it after the hide; my own push alone does not bring it back.
278export const prHideKey = (pr: MyPr) => `pr:${pr.url}`
279export const prHide = (pr: MyPr, now: number): [string, string] => [prHideKey(pr), `${pr.state}@${now}`]
280
281export function isPrHidden(hidden: Record<string, string>, pr: MyPr): boolean {
282  const [state, at] = (hidden[prHideKey(pr)] ?? '').split('@')
283  return state === pr.state && pr.newReviews.every(r => Date.parse(r.at) <= Number(at))
284}
285
286// Hidden until the thread has new activity.
287export const issueHideKey = (i: IssueItem) => `issue:${issueKey(i)}`
288export const issueHide = (i: IssueItem): [string, string] => [issueHideKey(i), i.at]
289
290export const isIssueHidden = (hidden: Record<string, string>, i: IssueItem) => hidden[issueHideKey(i)] === i.at
291
292export function issueAlerts(seen: string[] | undefined, issues: IssueItem[]): IssueItem[] {
293  if (seen === undefined) return []
294  const known = new Set(seen)
295  return issues.filter(i => !known.has(issueKey(i)))
296}
297
298// The band counts only what needs action.
299export type BandCounts = { reviews: number; prTodo: number; issues: number; searches: number }
300// The band's order.
301export const BAND_KEYS = ['reviews', 'prTodo', 'issues', 'searches'] as const
302
303// Each tab reads one page of search results; past it, a count is only a lower bound.
304export const atLeast = (n: number, capped = false) => (capped ? `${n}+` : `${n}`)
305
306// `searches` is what the search groups counted in the band found.
307export function bandCounts(reviews: number, prs: MyPr[], issues: IssueItem[], searches = 0): BandCounts {
308  return {
309    reviews,
310    prTodo: prs.filter(needsMe).length,
311    issues: issues.filter(i => i.kind !== 'reference').length,
312    searches,
313  }
314}
315
316// Zeros are left out.
317export function bandLabels(counts: BandCounts, m: Messages, capped: Capped = {}): string[] {
318  const tabOf = { reviews: 'review', prTodo: 'mine', issues: 'issues', searches: 'searches' } as const
319  return BAND_KEYS.filter(k => counts[k] > 0).map(k => m.band[k](atLeast(counts[k], capped[tabOf[k]])))
320}
321
322// A count that went down but not to zero, which leaves the band: what the band flashes for a moment.
323export function droppedCounts(before: BandCounts | undefined, after: BandCounts): (keyof BandCounts)[] {
324  if (before === undefined) return []
325  return BAND_KEYS.filter(k => after[k] > 0 && after[k] < before[k])
326}
327