PR Pulse: live status, merge readiness, checks, comments, review queue and change alerts for your GitHub PRs, with a collapsible band

Live GitHub pull-request status inside Claude Code: checks, merge readiness, review comments, your review queue and change alerts, without leaving the terminal.

/plugin marketplace add gerricchaplin/pr-pulse
/plugin install pr-pulse@pr-pulse
Requires the GitHub CLI (gh), signed in (gh auth status). PR Pulse makes every GitHub call through gh, as you.
Run /pulse in a GitHub repo. Optional argument: owner/repo, owner/repo#123 or a PR URL.
PR Pulse opens in the same window as your Claude conversation, as three tabbed panes, so you can keep working with Claude while it watches.
| Pane | Shows |
|---|---|
| PR Pulse | Your open PRs, a merge-readiness verdict, check progress and drill-down into failures |
| PR history | Your PRs and everyone's merged in the last 7 days |
| PR reviews | PRs waiting on you, and on your teams |
✓ READY TO MERGE, ✗ BLOCKED · n, ◐ WAITING ON CHECKS) with the checklist behind it.gh pr update-branch; press twice to confirm).gh run rerun --failed, for flaky, timed-out or cancelled jobs (press twice to confirm). A real failure needs a fix, not a re-run.gh pr merge --auto, using the repo's allowed method, squash first); ✕ Cancel auto-merge turns it off again. Both need a second press, and the button only shows when GitHub says you can use it.When Claude runs gh pr create or git push, PR Pulse follows that PR, as the band if it was not open. If a check then fails on it, a short note with the failure log is added to your next prompt, so Claude already knows. A one-line note follows when CI is green again. Every note shows in Recent activity first, and nothing is sent on its own.
| Key | Action |
|---|---|
r | Refresh |
m | Minimise to a one-line band above the prompt; polling and alerts carry on |
e or /pulse | Expand the band again |
o | Open the PR in the browser |
q | Close |
Settings live in /config, under PR Pulse, and are both on by default:
autoFollow)ciContext)PR Pulse has no dependencies and a deliberately small reach: it runs only gh, git, uname and open/xdg-open (for https:// links), never writes files, never calls a model and never sends a prompt for you. It reads Claude's own gh pr create and git push commands, without changing or blocking them, and adds CI notes only to a prompt you send; both can be switched off. CI fails if that reach grows without review. Details, the checks this repository runs, and how to report a vulnerability: SECURITY.md.
A local plugin cannot receive webhooks, so PR Pulse polls, and keeps it cheap:
gh token, sharing its hourly limits with everything else you run.This repository doubles as a demo target. scripts/demo.sh <scenario> opens a throwaway draft PR in a known state:
| Scenario | What PR Pulse shows |
|---|---|
green | all checks pass, the "✓ All checks passed" alert |
fail | a failing build with its error log, and Fix with Claude |
slow | a two-minute check: the pane goes from running to green |
flaky | fails, then passes after gh run rerun --failed without a false alert |
skip | a skipped optional check |
title | the required pr-title check failing |
scripts/demo.sh clean closes them all.
npm ci # pinned Claude Code
npx claude plugin validate .
npx claude plugin test .
python3 scripts/check-capabilities.py # fails if the plugin's reach changed
Guidance for contributors and coding agents: AGENTS.md.
MIT
hooks/register.tsx 1408 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Alert, Armed, Check, Comment, Pr, PrRow, ReviewRow, Step, Thread, View } from '../types'
5
6const PANE = 'pr-pulse'
7const HISTORY = 'pr-pulse-history'
8const REVIEWS = 'pr-pulse-reviews'
9const POLL_MS = 15_000
10const HISTORY_DAYS = 7
11const SLOW_POLL_MS = 60_000 // history and review queue change slowly
12const IDLE_POLL_MS = 60_000 // nothing is running, so nothing changes quickly
13const MINIMISED_IDLE_POLL_MS = 120_000 // band only and nothing running: alerts can wait a little
14const BACKOFF_MAX_MS = 300_000
15const POST_MERGE_WAIT_MS = 120_000 // runs on the merge commit start a few seconds after the merge
16const RATE_LIMITED = /rate limit|abuse detection|secondary rate/i
17
18const prAtom = atom({ plugin: 'pr-pulse', key: 'pr' } as const, null as Pr | null)
19const errorAtom = atom({ plugin: 'pr-pulse', key: 'error' } as const, '')
20const loadedAtom = atom({ plugin: 'pr-pulse', key: 'loadedAt' } as const, 0)
21const viewAtom = atom({ plugin: 'pr-pulse', key: 'view' } as const, {} as View)
22const stepsAtom = atom({ plugin: 'pr-pulse', key: 'steps' } as const, [] as Step[])
23const logAtom = atom({ plugin: 'pr-pulse', key: 'failedLog' } as const, [] as string[])
24const repoAtom = atom({ plugin: 'pr-pulse', key: 'repo' } as const, '')
25const openAtom = atom({ plugin: 'pr-pulse', key: 'openPrs' } as const, [] as PrRow[])
26const historyAtom = atom({ plugin: 'pr-pulse', key: 'history' } as const, [] as PrRow[])
27const teamAtom = atom({ plugin: 'pr-pulse', key: 'teamMerged' } as const, [] as PrRow[])
28const reviewsAtom = atom({ plugin: 'pr-pulse', key: 'reviews' } as const, [] as ReviewRow[])
29const threadsAtom = atom({ plugin: 'pr-pulse', key: 'threads' } as const, [] as Thread[])
30const conversationAtom = atom({ plugin: 'pr-pulse', key: 'conversation' } as const, [] as Comment[])
31const commentsLoadedAtom = atom({ plugin: 'pr-pulse', key: 'commentsLoaded' } as const, false)
32const watchingAtom = atom({ plugin: 'pr-pulse', key: 'watching' } as const, false)
33const targetAtom = atom({ plugin: 'pr-pulse', key: 'target' } as const, '')
34const repoCacheAtom = atom({ plugin: 'pr-pulse', key: 'repoCache' } as const, '')
35const followedAtom = atom({ plugin: 'pr-pulse', key: 'followed' } as const, [] as string[])
36const notesAtom = atom({ plugin: 'pr-pulse', key: 'notes' } as const, [] as string[])
37const armedAtom = atom({ plugin: 'pr-pulse', key: 'armed' } as const, { key: '', at: 0 } as Armed)
38const collapsedAtom = atom({ plugin: 'pr-pulse', key: 'collapsed' } as const, false)
39const alertsAtom = atom({ plugin: 'pr-pulse', key: 'alerts' } as const, [] as Alert[])
40const selectedAtom = atom({ plugin: 'pr-pulse', key: 'selected' } as const, 0)
41
42let target = '' // "owner/repo#N" pinned by /pr-pulse <arg>; empty = latest PR of mine
43let repoCache = '' // repo of the session's cwd, else of my latest PR
44let autoFollow = true // userConfig: follow the PRs claude opens or pushes to
45let ciContext = true // userConfig: tell claude, with your next prompt, when CI fails on a followed PR
46let me = '' // github login of the gh user
47let slowAt = 0 // when history and reviews were last fetched
48let slowRepo = ''
49let extrasAt = 0 // when the behind-count was last fetched
50let extrasFor = 0
51let required: string[] = []
52let behind = 0
53let queueSeen: Set<number> | undefined // review-queue PR numbers already announced
54let watchedRoot = '' // git toplevel the pane currently follows
55let nextPollAt = 0 // the 15s heartbeat skips ticks until this, which stretches the interval without new timer calls
56let failures = 0
57let timer: { cancel: () => void } | undefined
58let running = false // panes opened and polling for this session
59
60type Theme = {
61 brand: string
62 brandBg: string
63 onBrand: string
64 accent: string
65 muted: string
66 rule: string
67 ok: string
68 fail: string
69 run: string
70 skip: string
71}
72// purple theme: #6000F0 primary with lavender tints and slate neutrals; soft status tones for long viewing
73const DARK: Theme = {
74 brand: '#A37BFF', brandBg: '#6000F0', onBrand: '#F4F0FF', accent: '#C9B8FB', muted: '#A7B1C2', rule: '#48566A',
75 ok: '#86D9A8', fail: '#F2A0A0', run: '#E9CB7C', skip: '#A7B1C2',
76}
77const LIGHT: Theme = {
78 brand: '#6000F0', brandBg: '#6000F0', onBrand: '#FFFFFF', accent: '#6000F0', muted: '#48566A', rule: '#C6D2E1',
79 ok: '#15803D', fail: '#B91C1C', run: '#B45309', skip: '#64748B',
80}
81let theme = DARK
82
83async function loadTheme($: any) {
84 try {
85 const row = (await $.config.list()).find((r: { key: string }) => r.key === 'theme')
86 theme = /light/i.test(String(row?.value ?? '')) ? LIGHT : DARK
87 } catch {
88 theme = DARK
89 }
90}
91
92const icon = (status: string, conclusion: string): { glyph: string; tone: Outcome } => {
93 if (status !== 'COMPLETED' && status !== 'completed') {
94 return { glyph: status === 'QUEUED' || status === 'queued' ? '○' : '◐', tone: 'running' }
95 }
96 const c = conclusion.toUpperCase()
97 if (c === 'SUCCESS') return { glyph: '✓', tone: 'passed' }
98 if (c === 'SKIPPED' || c === 'NEUTRAL') return { glyph: '–', tone: 'skipped' }
99 if (c === 'CANCELLED') return { glyph: '⊘', tone: 'failed' }
100 return { glyph: '✗', tone: 'failed' }
101}
102const isPending = (c: { status: string }) => c.status.toUpperCase() !== 'COMPLETED'
103// github treats a cancelled required check as failing, so a cancelled run must never read as green
104const isFailed = (c: Check) => !isPending(c) && !['SUCCESS', 'SKIPPED', 'NEUTRAL'].includes(c.conclusion.toUpperCase())
105const OUTCOMES = ['failed', 'running', 'passed', 'skipped'] as const
106type Outcome = (typeof OUTCOMES)[number]
107const outcome = (c: Check): Outcome =>
108 isPending(c) ? 'running' : isFailed(c) ? 'failed' : c.conclusion.toUpperCase() === 'SUCCESS' ? 'passed' : 'skipped'
109const tone = (o: Outcome) => ({ failed: theme.fail, running: theme.run, passed: theme.ok, skipped: theme.skip })[o]
110const GLYPH: Record<Outcome, string> = { failed: '✗', running: '◐', passed: '✓', skipped: '–' }
111const BAR_WIDTH = 30
112const LOG_LINES = 20
113const REVIEW_LABEL: Record<string, string> = {
114 APPROVED: 'approved',
115 CHANGES_REQUESTED: 'changes requested',
116 REVIEW_REQUIRED: 'review required',
117 NONE: 'no review needed',
118}
119const ALERTS_KEPT = 8
120const FOLLOWED_KEPT = 20
121const NOTES_KEPT = 5
122const NOTE_CHARS = 1500
123const PR_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/
124const CREATES_PR = /\bgh\s+pr\s+create\b/
125const PUSHES = /\bgit\s+push\b/
126const BAND_ALERT_MS = 60_000 // how long the newest alert stays on the collapsed band
127const BODY_CHARS = 700
128const BODY_LINES = 10
129
130let opener = '' // 'open' on macOS, 'xdg-open' elsewhere
131
132// the mod api has no open-url call; the person's own opener does it
133async function openUrl($: any, url: string) {
134 if (!/^https:\/\//.test(url)) return
135 if (!opener) opener = (await $.process.run(['uname'])).stdout.trim() === 'Darwin' ? 'open' : 'xdg-open'
136 const r = await $.process.run([opener, url])
137 if (r.exitCode !== 0) $.ui.toast(`Couldn't open ${url}`)
138}
139
140async function gh($: any, args: string[]) {
141 const r = await $.process.run(['gh', ...args], { timeoutMs: 30_000 })
142 if (r.exitCode !== 0) throw new Error((r.stderr || r.stdout || 'gh failed').trim().split('\n')[0])
143 return JSON.parse(r.stdout)
144}
145
146async function refresh($: any, force = false) {
147 try {
148 let repo: string
149 if (target) {
150 repo = /^(.+)#\d+$/.exec(target)![1]!
151 } else {
152 if (!repoCache) {
153 const here = await $.process.run(['gh', 'repo', 'view', '--json', 'nameWithOwner'])
154 if (here.exitCode === 0) {
155 repoCache = JSON.parse(here.stdout).nameWithOwner
156 } else {
157 const found = await gh($, [
158 'search', 'prs', '--author', '@me', '--sort', 'created', '--order', 'desc',
159 '--limit', '1', '--json', 'repository',
160 ])
161 if (!found.length) throw new Error('Not in a GitHub repo and no PRs found for your account')
162 repoCache = found[0].repository.nameWithOwner
163 }
164 }
165 repo = repoCache
166 }
167 const rows = (list: any[]): PrRow[] =>
168 list.map(p => ({
169 number: p.number, title: p.title, url: p.url, state: p.state, isDraft: !!p.isDraft,
170 author: p.author?.login ?? '',
171 when: String(p.mergedAt || p.closedAt || p.updatedAt || '').slice(0, 16).replace('T', ' '),
172 }))
173 if (!me) me = (await gh($, ['api', 'user'])).login
174 const since = new Date(Date.now() - HISTORY_DAYS * 86_400_000).toISOString().slice(0, 10)
175 const prevRepo: string = await read($, repoAtom)
176 const pinned = target ? Number(/#(\d+)$/.exec(target)![1]) : 0
177 const known: PrRow[] = prevRepo === repo ? [...(await read($, openAtom)), ...(await read($, historyAtom))] : []
178 const wanted: number = await read($, selectedAtom)
179 const guess = [pinned, wanted].find(n => n && known.some(p => p.number === n)) || pinned || known[0]?.number || 0
180 const [owner, name] = repo.split('/')
181 const slowDue = force || repo !== slowRepo || Date.now() - slowAt >= SLOW_POLL_MS
182 const fast = await gh($, ['api', 'graphql', ...gqlArgs(owner!, name!, {
183 list: `repo:${repo} is:pr is:open author:${me} sort:created-desc`,
184 merged: slowDue ? `repo:${repo} is:pr is:merged merged:>=${since} sort:updated-desc` : undefined,
185 queue: slowDue ? `repo:${repo} is:pr is:open review-requested:@me` : undefined,
186 num: guess,
187 })])
188 const openRaw = (fast.data.open.nodes as any[]).filter(n => n?.number)
189 const open: PrRow[] = openRaw.map(n => {
190 const cs = latestRuns(rollupOf(n))
191 const failing = cs.filter(isFailed).length
192 const checks = !cs.length ? 'none' : failing ? 'failed' : cs.some(isPending) ? 'running' : 'passed'
193 return {
194 number: n.number, title: n.title, url: n.url, state: n.state, isDraft: !!n.isDraft, author: n.author?.login ?? '',
195 when: String(n.updatedAt ?? '').slice(0, 16).replace('T', ' '), checks, failing, review: n.reviewDecision || 'NONE',
196 }
197 })
198 await update($, repoAtom, () => repo)
199 await update($, openAtom, () => open)
200 let history: PrRow[] = await read($, historyAtom)
201 if (slowDue) {
202 const teamMerged = rows(fast.data.merged.nodes.filter((n: any) => n?.number)).sort((a, b) => b.when.localeCompare(a.when))
203 history = teamMerged.filter(p => p.author === me)
204 const requested = fast.data.queue.nodes.filter((n: any) => n?.number)
205 const reviews: ReviewRow[] = rows(requested).map((r, i) => {
206 const asked = (requested[i].reviewRequests?.nodes ?? []).map((q: any) => q.requestedReviewer ?? {}) as { login?: string; slug?: string; name?: string }[]
207 return {
208 ...r,
209 direct: asked.some(q => q.login === me),
210 teams: asked.filter(q => !q.login).map(q => (q.slug ?? q.name ?? '').replace(/^[^/]+\//, '')),
211 }
212 })
213 await update($, historyAtom, () => history)
214 await update($, teamAtom, () => teamMerged)
215 await update($, reviewsAtom, () => reviews)
216 if (queueSeen && repo === slowRepo) {
217 for (const r of reviews.filter(r => !queueSeen!.has(r.number))) {
218 await alert($, `👀 Review requested${r.direct ? ' from you' : ''}: #${r.number} ${r.title} (${r.author})`, 'info', r.url)
219 }
220 }
221 queueSeen = new Set(reviews.map(r => r.number))
222 slowAt = Date.now()
223 slowRepo = repo
224 $.ui.log(`${repo} open=${open.length} mine-merged=${history.length} all-merged=${teamMerged.length} reviews=${reviews.length}`, { to: 'debug' })
225 }
226
227 const chosen: number = await read($, selectedAtom)
228 const number = [pinned, chosen].find(n => n && [...open, ...history].some(p => p.number === n)) || pinned || open[0]?.number || history[0]?.number
229 if (!number) {
230 await update($, prAtom, () => null)
231 throw new Error(`No PRs of yours in ${repo}`)
232 }
233 await update($, selectedAtom, () => number)
234 const detail = number === guess ? fast.data.repository : (await gh($, ['api', 'graphql', ...gqlArgs(owner!, name!, { num: number })])).data.repository
235 const v = detail.pullRequest
236 if (!v) throw new Error(`#${number} not found in ${repo}`)
237 // once merged, what matters is what ran on the merge commit; before those runs appear, say so
238 let checks = latestRuns(rollupOf(v))
239 let checksOn: Pr['checksOn'] = 'pr'
240 if (v.state === 'MERGED' && v.mergeCommit) {
241 const post = latestRuns(contextsOf(v.mergeCommit.statusCheckRollup))
242 if (post.length) {
243 checks = post
244 checksOn = 'merge'
245 } else if (Date.now() - Date.parse(v.mergedAt) < POST_MERGE_WAIT_MS) {
246 checks = []
247 checksOn = 'waiting'
248 }
249 }
250 const nodes = v.reviewThreads.nodes as { isResolved: boolean; comments: { totalCount: number; nodes: Latest[] } }[]
251 const threads = nodes.length
252 const unresolved = nodes.filter(n => !n.isResolved).length
253 const commentCount = v.comments.totalCount + nodes.reduce((a, n) => a + n.comments.totalCount, 0)
254 const latest = [...v.comments.nodes, ...nodes.flatMap(n => n.comments.nodes)] as Latest[]
255 latest.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
256 const lastCommenter = latest[0]?.author?.login ?? ''
257 if (force || number !== extrasFor || Date.now() - extrasAt >= SLOW_POLL_MS) {
258 try {
259 behind = (await gh($, ['api', `repos/${repo}/compare/${v.baseRefName}...${encodeURIComponent(v.headRefName)}`])).behind_by ?? 0
260 } catch {
261 behind = 0
262 }
263 extrasAt = Date.now()
264 extrasFor = number
265 }
266 required = checksOn === 'pr' ? rollupOf(v).filter((c: any) => c.isRequired).map((c: any) => c.name ?? c.context) : []
267 const pr: Pr = {
268 repo, number, title: v.title, url: v.url, state: v.state, isDraft: v.isDraft,
269 review: v.reviewDecision || 'NONE', mergeable: v.mergeable, checks, checksOn, unresolved, threads,
270 mergeState: v.mergeStateStatus ?? 'UNKNOWN', base: v.baseRefName ?? 'main', head: v.headRefName ?? '', behind, required,
271 latestReviews: (v.latestReviews?.nodes ?? []).map((r: any) => ({ author: r.author?.login ?? '', state: r.state ?? '' })),
272 commentCount, lastCommenter,
273 autoMerge: v.autoMergeRequest?.mergeMethod ?? '',
274 canAutoMerge: !!v.viewerCanEnableAutoMerge && !v.isDraft,
275 canCancelAutoMerge: !!v.viewerCanDisableAutoMerge,
276 mergeMethod: mergeMethodOf(detail),
277 }
278 const prev: Pr | null = await read($, prAtom)
279 await update($, prAtom, () => pr)
280 await announcePrChanges($, prev, pr)
281 await update($, errorAtom, () => '')
282 await update($, loadedAtom, () => Date.now())
283 const running = checks.filter(isPending).length
284 const failed = checks.filter(isFailed).length
285 $.ui.status(
286 `PR #${number} ${pr.state.toLowerCase()}${unresolved > 0 ? ` · ${unresolved} unresolved` : ''} · ${failed ? `${failed} failed` : running ? `${running} running` : 'checks ok'}`,
287 )
288 failures = 0
289 const busy = running > 0 || pr.checksOn === 'waiting' || open.some(r => r.checks === 'running')
290 const idleMs = (await read($, collapsedAtom)) ? MINIMISED_IDLE_POLL_MS : IDLE_POLL_MS
291 nextPollAt = (await $.clock.now()) + (busy ? POLL_MS : idleMs)
292 const view: View = await read($, viewAtom)
293 if (view.job) await loadSteps($, pr, view.job)
294 if (view.comments) await loadComments($, pr)
295 } catch (err) {
296 const reason = String((err as Error).message ?? err)
297 failures++
298 nextPollAt = (await $.clock.now()) + Math.min(BACKOFF_MAX_MS, (RATE_LIMITED.test(reason) ? SLOW_POLL_MS : POLL_MS) * 2 ** (failures - 1))
299 $.ui.log(`refresh failed: ${reason}`, { to: 'debug' })
300 await update($, errorAtom, () => String((err as Error).message ?? err))
301 }
302}
303
304// the rollup keeps superseded runs (a re-run, or a title edit re-triggering a check); keep each check's newest
305function latestRuns(rollup: any[]): Check[] {
306 // a queued re-run has no real start time yet (github reports 0001-01-01); it still supersedes finished runs
307 const rank = (c: any) => {
308 const live = String(c.status ?? '').toUpperCase() !== 'COMPLETED' && c.state !== 'SUCCESS' && c.state !== 'FAILURE'
309 const at = String(c.startedAt ?? c.createdAt ?? '')
310 return live && (!at || at.startsWith('0001')) ? '9999' : at
311 }
312 const newest = new Map<string, any>()
313 for (const c of rollup) {
314 const key = `${c.workflowName ?? ''}|${c.name ?? c.context ?? '?'}`
315 const seen = newest.get(key)
316 if (!seen || rank(c) >= rank(seen)) newest.set(key, c)
317 }
318 return [...newest.values()].map(c => ({
319 name: c.name ?? c.context ?? '?',
320 workflow: c.workflowName || 'Other checks',
321 status: c.status ?? (c.state === 'PENDING' ? 'IN_PROGRESS' : 'COMPLETED'),
322 conclusion: c.conclusion ?? c.state ?? '',
323 url: c.detailsUrl ?? c.targetUrl ?? '',
324 }))
325}
326
327const contexts = (required: boolean) => `contexts(first:100){nodes{__typename
328...on CheckRun{name status conclusion detailsUrl startedAt checkSuite{workflowRun{workflow{name}}}${required ? ' isRequired(pullRequestNumber:$num)' : ''}}
329...on StatusContext{context state targetUrl createdAt${required ? ' isRequired(pullRequestNumber:$num)' : ''}}}}`
330const rollup = (required: boolean) => `commits(last:1){nodes{commit{statusCheckRollup{${contexts(required)}}}}}`
331const ROW_FIELDS = 'number title url state isDraft updatedAt mergedAt closedAt author{login}'
332const LIST_FIELDS = `${ROW_FIELDS} reviewDecision ${rollup(false)}`
333const QUEUE_FIELDS = `${ROW_FIELDS} reviewRequests(first:20){nodes{requestedReviewer{__typename ...on User{login} ...on Team{slug name}}}}`
334const DETAIL_FIELDS = `title url state isDraft mergedAt mergeCommit{statusCheckRollup{${contexts(false)}}} autoMergeRequest{mergeMethod} viewerCanEnableAutoMerge viewerCanDisableAutoMerge reviewDecision mergeable mergeStateStatus baseRefName headRefName
335latestReviews(first:20){nodes{author{login} state}} ${rollup(true)}
336reviewThreads(first:100){nodes{isResolved comments(last:1){totalCount nodes{author{login} createdAt}}}}
337comments(last:1){totalCount nodes{author{login} createdAt}}`
338
339type GqlPart = { list?: string; num?: number; merged?: string; queue?: string }
340// one request carries the open-PR list, the selected PR's detail and, when due, history and the review queue
341function gqlArgs(owner: string, name: string, part: GqlPart): string[] {
342 const search = (alias: string, v: string, fields: string) => `${alias}:search(query:${v},type:ISSUE,first:${alias === 'open' ? 20 : 100}){nodes{...on PullRequest{${fields}}}}`
343 const decl = [
344 '$o:String!', '$n:String!',
345 ...(part.list ? ['$q:String!'] : []), ...(part.merged ? ['$mq:String!'] : []), ...(part.queue ? ['$rq:String!'] : []),
346 ...(part.num ? ['$num:Int!'] : []),
347 ].join(',')
348 const body = [
349 part.num ? `repository(owner:$o,name:$n){squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed pullRequest(number:$num){${DETAIL_FIELDS}}}` : 'repository(owner:$o,name:$n){id}',
350 part.list ? search('open', '$q', LIST_FIELDS) : '',
351 part.merged ? search('merged', '$mq', ROW_FIELDS) : '',
352 part.queue ? search('queue', '$rq', QUEUE_FIELDS) : '',
353 ].join('\n')
354 return [
355 '-f', `query=query(${decl}){${body}}`, '-f', `o=${owner}`, '-f', `n=${name}`,
356 ...(part.list ? ['-f', `q=${part.list}`] : []), ...(part.merged ? ['-f', `mq=${part.merged}`] : []),
357 ...(part.queue ? ['-f', `rq=${part.queue}`] : []), ...(part.num ? ['-F', `num=${part.num}`] : []),
358 ]
359}
360
361// the repo's allowed way to merge, preferring squash; an empty string when it allows none
362function mergeMethodOf(repo: { squashMergeAllowed?: boolean; mergeCommitAllowed?: boolean; rebaseMergeAllowed?: boolean }): string {
363 return repo.squashMergeAllowed ? 'squash' : repo.mergeCommitAllowed ? 'merge' : repo.rebaseMergeAllowed ? 'rebase' : ''
364}
365
366// gh's own rollup shape, which latestRuns already reads
367function rollupOf(pr: any): any[] {
368 return contextsOf(pr.commits?.nodes?.[0]?.commit?.statusCheckRollup)
369}
370
371function contextsOf(rollup: any): any[] {
372 const nodes = rollup?.contexts?.nodes ?? []
373 return nodes.map((c: any) => (c.__typename === 'CheckRun' ? { ...c, workflowName: c.checkSuite?.workflowRun?.workflow?.name ?? '' } : c))
374}
375
376type Latest = { author?: { login: string }; createdAt?: string }
377
378// a failing check on a PR claude opened or pushed to becomes context on your next prompt, never a prompt of its own
379async function noteForClaude($: any, prev: Pr, pr: Pr, failedBefore: Set<string>) {
380 if (!ciContext || !(await read($, followedAtom)).includes(`${pr.repo}#${pr.number}`)) return
381 const tag = `PR #${pr.number} (${pr.url})`
382 for (const c of pr.checks.filter(c => isFailed(c) && !failedBefore.has(c.name) && c.conclusion.toUpperCase() !== 'CANCELLED')) {
383 const log = await fetchFailureLog($, pr, c)
384 const note = [
385 `PR Pulse: the "${c.name}" check (${c.workflow}) failed on ${tag}, which you opened or pushed to.`,
386 log.length ? `Log excerpt:\n${log.join('\n')}` : `Logs: ${c.url}`,
387 ].join('\n').slice(0, NOTE_CHARS)
388 await queueNote($, note, `✦ Will tell Claude at your next prompt: ${c.name} failed on #${pr.number}`, c.url)
389 }
390 const green = (p: Pr) => p.checks.length > 0 && !p.checks.some(isPending) && !p.checks.some(isFailed)
391 if (failedBefore.size && green(pr) && !green(prev)) {
392 await queueNote($, `PR Pulse: CI is green again on ${tag}.`, `✦ Will tell Claude at your next prompt: CI green again on #${pr.number}`, pr.url)
393 }
394}
395
396async function queueNote($: any, note: string, shown: string, url: string) {
397 await update($, notesAtom, (list: string[]) => [...list.filter(n => n !== note), note].slice(-NOTES_KEPT))
398 await alert($, shown, 'info', url)
399}
400
401// claude's own `gh pr create` or `git push`: follow the PR it opened or updated
402async function followFromCommand($: any, command: string, output: string) {
403 let found = CREATES_PR.test(command) ? PR_URL.exec(output) : null
404 if (!found && PUSHES.test(command)) {
405 const r = await $.process.run(['gh', 'pr', 'view', '--json', 'url'], { timeoutMs: 30_000 })
406 if (r.exitCode !== 0) return
407 try {
408 found = PR_URL.exec(JSON.parse(r.stdout).url ?? '')
409 } catch {
410 return
411 }
412 }
413 if (found) await follow($, found[1]!, Number(found[2]), CREATES_PR.test(command) ? 'opened' : 'pushed to')
414}
415
416async function follow($: any, repo: string, number: number, verb: string) {
417 const key = `${repo}#${number}`
418 const isNew = !(await read($, followedAtom)).includes(key)
419 await update($, followedAtom, (list: string[]) => [key, ...list.filter(k => k !== key)].slice(0, FOLLOWED_KEPT))
420 target = ''
421 repoCache = repo
422 await update($, targetAtom, () => target)
423 await update($, repoCacheAtom, () => repoCache)
424 await update($, selectedAtom, () => number)
425 await update($, viewAtom, () => ({}))
426 if (!running) {
427 // started by claude rather than by you: stay out of the way as the band until expanded
428 running = true
429 await update($, watchingAtom, () => true)
430 await update($, collapsedAtom, () => true)
431 await loadTheme($)
432 if (!timer) timer = $.clock.every(POLL_MS, () => void tick($))
433 }
434 if (isNew) $.ui.toast(`PR Pulse is following #${number}, which Claude just ${verb}`, { timeoutMs: 6000 })
435 await refresh($, true)
436}
437
438async function alert($: any, text: string, tone: Alert['tone'], url = '') {
439 $.ui.toast(text, { timeoutMs: 8000 })
440 await update($, alertsAtom, (list: Alert[]) => [{ at: Date.now(), text, tone, url }, ...list].slice(0, ALERTS_KEPT))
441}
442
443// compare against the previous poll of the same PR; the first poll only records
444async function announcePrChanges($: any, prev: Pr | null, pr: Pr) {
445 if (!prev || prev.number !== pr.number || prev.repo !== pr.repo || !prev.mergeState) return
446 const tag = `#${pr.number}`
447 const failedBefore = new Set(prev.checks.filter(isFailed).map(c => c.name))
448 for (const c of pr.checks.filter(c => isFailed(c) && !failedBefore.has(c.name))) {
449 const cancelled = c.conclusion.toUpperCase() === 'CANCELLED'
450 await alert($, `${cancelled ? '⊘' : '✗'} ${c.name} ${cancelled ? 'cancelled' : 'failed'} on ${tag}`, 'fail', c.url)
451 }
452 const settled = (p: Pr) => p.checks.length > 0 && !p.checks.some(isPending)
453 if (!settled(prev) && settled(pr) && !pr.checks.some(isFailed)) await alert($, `✓ All checks passed on ${tag}`, 'ok', pr.url)
454 await noteForClaude($, prev, pr, failedBefore)
455 const before = new Map(prev.latestReviews.map(r => [r.author, r.state]))
456 for (const r of pr.latestReviews) {
457 if (r.author === me || before.get(r.author) === r.state) continue
458 if (r.state === 'APPROVED') await alert($, `✅ ${tag} approved by ${r.author}`, 'ok', pr.url)
459 else if (r.state === 'CHANGES_REQUESTED') await alert($, `✋ ${r.author} requested changes on ${tag}`, 'fail', pr.url)
460 else if (r.state === 'COMMENTED') await alert($, `💬 ${r.author} reviewed ${tag}`, 'info', pr.url)
461 }
462 if (pr.commentCount > prev.commentCount && pr.lastCommenter && pr.lastCommenter !== me) {
463 const n = pr.commentCount - prev.commentCount
464 await alert($, `💬 ${n} new comment${n === 1 ? '' : 's'} on ${tag} from ${pr.lastCommenter}`, 'info', pr.url)
465 }
466 if (pr.state === 'OPEN' && !prev.behind && pr.behind > 0) {
467 await alert($, `⇣ ${tag} is ${pr.behind} commit${pr.behind === 1 ? '' : 's'} behind ${pr.base}`, pr.mergeState === 'BEHIND' ? 'fail' : 'info', pr.url)
468 }
469 if (pr.state === 'OPEN' && prev.mergeable !== 'CONFLICTING' && pr.mergeable === 'CONFLICTING') {
470 await alert($, `✗ ${tag} has merge conflicts with ${pr.base}`, 'fail', pr.url)
471 }
472 if (prev.mergeState !== 'CLEAN' && pr.mergeState === 'CLEAN') await alert($, `● ${tag} is ready to merge`, 'ok', pr.url)
473 if (prev.state !== pr.state && pr.state === 'MERGED') await alert($, `⑂ ${tag} merged`, 'ok', pr.url)
474 if (prev.state !== pr.state && pr.state === 'CLOSED') await alert($, `⊘ ${tag} closed`, 'fail', pr.url)
475}
476
477// keep the lines leading up to the last ##[error] (else the tail), minus runner bookkeeping
478function failureExcerpt(raw: string) {
479 const lines = raw
480 .split('\n')
481 .map(l => (l.split('\t').length >= 3 ? l.split('\t').slice(2).join('\t') : l).replace(/^\S+Z /, '').replace(/\x1b\[[0-9;]*m/g, ''))
482 .filter(l => l.trim() && !/^##\[(end)?group\]/.test(l) && !/^Cleaning up orphan processes/.test(l))
483 const lastError = lines.map(l => l.startsWith('##[error]')).lastIndexOf(true)
484 const end = lastError >= 0 ? lastError + 1 : lines.length
485 return lines.slice(Math.max(0, end - LOG_LINES), end).map(l => l.replace(/^##\[error\]/, '✗ '))
486}
487
488const COMMENTS_QUERY = `query($o:String!,$n:String!,$num:Int!){repository(owner:$o,name:$n){pullRequest(number:$num){
489reviewThreads(first:100){nodes{isResolved isOutdated path line comments(first:30){nodes{author{login} body createdAt url}}}}
490comments(last:30){nodes{author{login} body createdAt url}}
491reviews(last:30){nodes{author{login} state body submittedAt url}}}}}`
492
493const clip = (body: string) => {
494 const lines = body.replace(/\r/g, '').trim().split('\n')
495 let text = lines.slice(0, BODY_LINES).join('\n')
496 if (text.length > BODY_CHARS) text = text.slice(0, BODY_CHARS)
497 return text.length < body.trim().length ? `${text.trimEnd()} …` : text
498}
499const stamp = (iso: string) => String(iso ?? '').slice(5, 16).replace('T', ' ')
500
501async function loadComments($: any, pr: Pr) {
502 try {
503 const [owner, name] = pr.repo.split('/')
504 const g = await gh($, ['api', 'graphql', '-f', `query=${COMMENTS_QUERY}`, '-f', `o=${owner}`, '-f', `n=${name}`, '-F', `num=${pr.number}`])
505 const p = g.data.repository.pullRequest
506 const comment = (c: any): Comment => ({
507 author: c.author?.login ?? 'ghost', body: clip(c.body ?? ''), when: stamp(c.createdAt ?? c.submittedAt), url: c.url ?? '',
508 state: c.state && c.state !== 'COMMENTED' ? c.state : '',
509 })
510 const threads: Thread[] = p.reviewThreads.nodes.map((t: any) => ({
511 path: t.path ?? '', line: t.line ?? 0, isResolved: !!t.isResolved, isOutdated: !!t.isOutdated,
512 url: t.comments.nodes[0]?.url ?? pr.url, comments: t.comments.nodes.map(comment),
513 }))
514 const conversation: Comment[] = [
515 ...p.comments.nodes.map(comment),
516 ...p.reviews.nodes.filter((r: any) => (r.body ?? '').trim() || (r.state && r.state !== 'COMMENTED')).map(comment),
517 ].sort((a, b) => a.when.localeCompare(b.when))
518 await update($, threadsAtom, () => threads)
519 await update($, conversationAtom, () => conversation)
520 await update($, commentsLoadedAtom, () => true)
521 } catch (err) {
522 await update($, errorAtom, () => String((err as Error).message ?? err))
523 }
524}
525
526async function fetchFailureLog($: any, pr: Pr, job: Check): Promise<string[]> {
527 const m = /runs\/(\d+)\/job\/(\d+)/.exec(job.url)
528 if (!m) return []
529 // --log-failed prints "<job>\t<step>\t<timestamp> <message>" per line
530 const log = await $.process.run(['gh', 'run', 'view', m[1]!, '-R', pr.repo, '--job', m[2]!, '--log-failed'], { timeoutMs: 60_000 })
531 return failureExcerpt(log.exitCode === 0 ? log.stdout : log.stderr)
532}
533
534// a draft in the person's prompt box, never sent on their behalf
535async function draftPrompt($: any, text: string) {
536 try {
537 const box = await $.prompt.read()
538 const r = await $.prompt.fill({ text: box.text.trim() ? `\n\n${text}` : text, mode: 'append' })
539 $.ui.toast(r.isFilled ? 'Draft added to your prompt: review it, then press Enter' : "Couldn't fill the prompt (is a dialog open?)", { timeoutMs: 6000 })
540 } catch (err) {
541 $.ui.toast(`Couldn't fill the prompt: ${String((err as Error).message ?? err)}`, { timeoutMs: 6000 })
542 }
543}
544
545async function fixCheck($: any, pr: Pr, job: Check) {
546 const log = await fetchFailureLog($, pr, job)
547 await draftPrompt($, [
548 `The "${job.name}" check (${job.workflow}) failed on PR #${pr.number} in ${pr.repo}: ${pr.url}`,
549 `Job: ${job.url}`,
550 log.length ? `Failure log excerpt:\n\`\`\`\n${log.join('\n')}\n\`\`\`` : 'Fetch the failing log with `gh run view --log-failed`.',
551 'Find the root cause and fix it on this branch. Tell me what you changed.',
552 ].join('\n'))
553}
554
555async function addressThread($: any, pr: Pr, th: Thread) {
556 const quoted = th.comments.map(c => `> **${c.author}**: ${c.body.replace(/\n/g, '\n> ')}`).join('\n>\n')
557 await draftPrompt($, [
558 `Address this review thread on PR #${pr.number} (${th.url}) at \`${th.path}${th.line ? `:${th.line}` : ''}\`:`,
559 quoted,
560 'Make the change if it is right, or tell me why not. Summarise what you did so I can reply on the thread.',
561 ].join('\n'))
562}
563
564let rerunning = false // one re-run at a time, like branch updates
565let updating = false // one branch update at a time; a second press while it runs is ignored
566const CONFIRM_MS = 5000
567
568const isArmed = (armed: Armed, key: string) => armed.key === key && Date.now() - armed.at < CONFIRM_MS
569
570// first press arms and redraws the button as "press again"; the second press within CONFIRM_MS runs it
571async function confirmThen($: any, key: string, run: () => Promise<void>) {
572 const armed: Armed = await read($, armedAtom)
573 if (!isArmed(armed, key)) {
574 await update($, armedAtom, () => ({ key, at: Date.now() }))
575 return
576 }
577 await update($, armedAtom, () => ({ key: '', at: 0 }))
578 await run()
579}
580
581// github updates the branch server-side; a rebase rewrites it, so a local checkout must pull before pushing again
582const runIdOf = (c: Check) => /\/actions\/runs\/(\d+)/.exec(c.url)?.[1] ?? ''
583
584// retries only the failed jobs of the run, which is the cheap fix for a flaky or cancelled job
585async function rerunFailed($: any, pr: Pr, c: Check) {
586 const run = runIdOf(c)
587 if (!run || rerunning) return
588 rerunning = true
589 try {
590 $.ui.toast(`Re-running the failed jobs of ${c.workflow}…`)
591 const r = await $.process.run(['gh', 'run', 'rerun', run, '--failed', '-R', pr.repo], { timeoutMs: 60_000 })
592 if (r.exitCode !== 0) {
593 $.ui.toast(`Couldn't re-run ${c.workflow}: ${(r.stderr || r.stdout || 'gh failed').trim().split('\n')[0]}`, { timeoutMs: 8000 })
594 return
595 }
596 $.ui.toast(`Re-running the failed jobs of ${c.workflow}`, { timeoutMs: 6000 })
597 await refresh($, true)
598 } finally {
599 rerunning = false
600 }
601}
602
603let merging = false // one auto-merge change at a time
604
605async function setAutoMerge($: any, pr: Pr, enable: boolean) {
606 if (merging) return
607 merging = true
608 try {
609 const r = await $.process.run(
610 ['gh', 'pr', 'merge', String(pr.number), '-R', pr.repo, ...(enable ? ['--auto', `--${pr.mergeMethod}`] : ['--disable-auto'])],
611 { timeoutMs: 60_000 },
612 )
613 if (r.exitCode !== 0) {
614 $.ui.toast(`Couldn't ${enable ? 'enable' : 'cancel'} auto-merge on #${pr.number}: ${(r.stderr || r.stdout || 'gh failed').trim().split('\n')[0]}`, { timeoutMs: 8000 })
615 return
616 }
617 $.ui.toast(enable ? `Auto-merge on for #${pr.number}: it merges (${pr.mergeMethod}) once required checks pass` : `Auto-merge cancelled on #${pr.number}`, { timeoutMs: 8000 })
618 await refresh($, true)
619 } finally {
620 merging = false
621 }
622}
623
624async function updateBranch($: any, pr: Pr, rebase: boolean) {
625 if (updating) return
626 updating = true
627 try {
628 $.ui.toast(rebase ? `Rebasing #${pr.number} on ${pr.base}…` : `Merging ${pr.base} into #${pr.number}…`)
629 const r = await $.process.run(
630 ['gh', 'pr', 'update-branch', String(pr.number), '-R', pr.repo, ...(rebase ? ['--rebase'] : [])],
631 { timeoutMs: 60_000 },
632 )
633 if (r.exitCode !== 0) {
634 $.ui.toast(`Couldn't update #${pr.number}: ${(r.stderr || r.stdout || 'gh failed').trim().split('\n')[0]}`, { timeoutMs: 8000 })
635 return
636 }
637 const local = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
638 const onBranch = local.exitCode === 0 && local.stdout.trim() === pr.head
639 const done = rebase ? `Rebased #${pr.number} on ${pr.base}` : `Merged ${pr.base} into #${pr.number}`
640 $.ui.toast(
641 onBranch ? `${done}: your checkout is on ${pr.head}, run \`git pull${rebase ? ' --rebase' : ''}\` before pushing again` : done,
642 { timeoutMs: 8000 },
643 )
644 await refresh($, true)
645 } finally {
646 updating = false
647 }
648}
649
650async function rebaseWithClaude($: any, pr: Pr) {
651 const conflicts = pr.mergeable === 'CONFLICTING'
652 const state = [pr.behind ? `${pr.behind} commit${pr.behind === 1 ? '' : 's'} behind \`${pr.base}\`` : '', conflicts ? 'has merge conflicts' : '']
653 .filter(Boolean)
654 .join(' and ')
655 await draftPrompt($, [
656 `PR #${pr.number} in ${pr.repo} (${pr.url}) is ${state}.`,
657 `Rebase \`${pr.head}\` onto the latest \`origin/${pr.base}\`: fetch, check out the branch, rebase, and resolve any conflicts keeping the intent of both sides.`,
658 'Run the tests, then show me what changed and ask before you push with `--force-with-lease`.',
659 ].join('\n'))
660}
661
662async function loadSteps($: any, pr: Pr, job: Check) {
663 const m = /runs\/(\d+)\/job\/(\d+)/.exec(job.url)
664 if (!m) return update($, stepsAtom, () => [])
665 try {
666 const run = await gh($, ['run', 'view', m[1]!, '-R', pr.repo, '--json', 'jobs'])
667 const j = run.jobs.find((x: any) => String(x.databaseId) === m[2])
668 await update($, stepsAtom, () =>
669 (j?.steps ?? []).map((s: any) => ({ name: s.name, status: s.status, conclusion: s.conclusion ?? '' })),
670 )
671 if (!isFailed(job)) return update($, logAtom, () => [])
672 const lines = await fetchFailureLog($, pr, job)
673 await update($, logAtom, () => lines)
674 } catch (err) {
675 await update($, errorAtom, () => String((err as Error).message ?? err))
676 }
677}
678
679// Follow the agent's `cd` into a different top-level git repo. A pinned
680// target (/pr-pulse owner/repo#N) or a non-repo directory leaves the view alone.
681async function followCwd($: any, cwd: string) {
682 if (target) return
683 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd })
684 if (top.exitCode !== 0) return
685 const root = top.stdout.trim()
686 if (!root || root === watchedRoot) return
687 const here = await $.process.run(['gh', 'repo', 'view', '--json', 'nameWithOwner'], { cwd: root })
688 if (here.exitCode !== 0) return
689 watchedRoot = root
690 repoCache = JSON.parse(here.stdout).nameWithOwner
691 await update($, viewAtom, () => ({}))
692 await update($, selectedAtom, () => 0)
693 await refresh($)
694}
695
696async function openPanes($: any) {
697 await $.ui.open({ id: HISTORY, title: 'PR history' })
698 await $.ui.open({ id: REVIEWS, title: 'PR reviews' })
699 // opened last and asked for focus, so the PR Pulse tab is the one in front
700 await $.ui.open({ id: PANE, title: 'PR Pulse', focus: true })
701}
702
703async function closePanes($: any) {
704 await $.ui.close({ id: REVIEWS })
705 await $.ui.close({ id: HISTORY })
706 await $.ui.close({ id: PANE })
707}
708
709// panes away, polling and alerts carry on, the AbovePrompt band summarises
710async function minimise($: any) {
711 await update($, collapsedAtom, () => true)
712 await closePanes($)
713}
714
715async function expand($: any, number = 0) {
716 if (number) {
717 await update($, selectedAtom, () => number)
718 await update($, viewAtom, () => ({}))
719 }
720 await update($, collapsedAtom, () => false)
721 await openPanes($)
722 await refresh($)
723}
724
725async function start($: any) {
726 running = true
727 await update($, watchingAtom, () => true)
728 await update($, collapsedAtom, () => false)
729 await update($, targetAtom, () => target)
730 await update($, repoCacheAtom, () => repoCache)
731 await loadTheme($)
732 await openPanes($)
733 await refresh($)
734 if (!timer) timer = $.clock.every(POLL_MS, () => void tick($))
735}
736
737// a reload starts the module over; pick the watch back up from session state
738async function resume($: any) {
739 if (running || !(await read($, watchingAtom))) return
740 running = true
741 target = await read($, targetAtom)
742 repoCache = await read($, repoCacheAtom)
743 await loadTheme($)
744 // the reload closed the panes; reopen them unless you had minimised to the band
745 if (!(await read($, collapsedAtom))) await openPanes($)
746 void refresh($, true)
747 if (!timer) timer = $.clock.every(POLL_MS, () => void tick($))
748}
749
750async function stop($: any) {
751 running = false
752 await update($, watchingAtom, () => false)
753 timer?.cancel()
754 timer = undefined
755 $.ui.status(undefined)
756 await update($, collapsedAtom, () => false)
757 await closePanes($)
758}
759
760async function tick($: any) {
761 if ((await $.clock.now()) < nextPollAt) return
762 await refresh($)
763}
764
765
766function paneBar(ui: any, $: any, title: string, repo: string) {
767 const { Box, Text, Button } = ui
768 return (
769 <Box flexDirection="row" justifyContent="space-between">
770 <Text>
771 <Text backgroundColor={theme.brandBg} color={theme.onBrand}> ◆ {title} </Text>
772 <Text color={theme.muted}> {repo || '…'}</Text>
773 </Text>
774 <Box flexDirection="row" gap={1}>
775 <Button key="minimise" label="▁ Minimise" hotkey="m" onPress={() => void minimise($)} />
776 <Button key="close" label="✕ Close" hotkey="q" onPress={() => void stop($)} />
777 </Box>
778 </Box>
779 )
780}
781
782// the one thing standing between a PR and merging, as a few words for the band
783function blocker(p: PrRow) {
784 if (p.failing) return `${p.failing} failing`
785 if (p.checks === 'running') return 'checks running'
786 if (p.isDraft) return 'draft'
787 if (p.review === 'CHANGES_REQUESTED') return 'changes requested'
788 if (p.review === 'REVIEW_REQUIRED') return 'needs review'
789 return 'ready'
790}
791
792function band(ui: any, $: any, open: PrRow[], selected: number, queue: number, latest: Alert | undefined) {
793 const { Box, Text, Button } = ui
794 const t = theme
795 const glyph = (p: PrRow) =>
796 p.checks === 'failed' ? { g: '✗', c: t.fail } : p.checks === 'running' ? { g: '◐', c: t.run } : p.checks === 'passed' ? { g: '✓', c: t.ok } : { g: '○', c: t.muted }
797 return (
798 <Box flexDirection="column">
799 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
800 <Text backgroundColor={t.brandBg} color={t.onBrand}> ◆ PR </Text>
801 {open.length === 0 && <Text color={t.muted}>no open PRs</Text>}
802 {open.map(p => {
803 const gl = glyph(p)
804 const b = blocker(p)
805 return (
806 <Box key={`chip-${p.number}`} flexDirection="row">
807 <Text color={gl.c}>{gl.g} </Text>
808 <Button plain key={`chip-open-${p.number}`} dimColor={p.number !== selected} label={`#${p.number}`} onPress={() => void expand($, p.number)} />
809 <Text color={b === 'ready' ? t.ok : t.muted}> {b}</Text>
810 </Box>
811 )
812 })}
813 {queue > 0 && <Text color={t.accent}>👀 {queue} to review</Text>}
814 <Button key="expand" label="⤢ Expand" hotkey="e" onPress={() => void expand($)} />
815 </Box>
816 {latest && (
817 <Text color={latest.tone === 'fail' ? t.fail : latest.tone === 'ok' ? t.ok : t.muted}>
818 {' '}{latest.text} · {new Date(latest.at).toLocaleTimeString().slice(0, 5)}
819 </Text>
820 )}
821 </Box>
822 )
823}
824
825function heading(ui: any, label: string, count: number, color = theme.accent) {
826 const { Box, Text } = ui
827 return (
828 <Box marginTop={1}>
829 <Text color={color}>{`${label.toUpperCase()} · ${count}`}</Text>
830 </Box>
831 )
832}
833
834export const register: Register = (on, options) => {
835 autoFollow = options.autoFollow !== false
836 ciContext = options.ciContext !== false
837
838 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
839 const ran = await next(e)
840 if (!autoFollow || ran.deny !== undefined || ran.isError || !(CREATES_PR.test(e.command) || PUSHES.test(e.command))) return ran
841 const result = ran.result as { stdout?: string; stderr?: string; backgroundTaskId?: string } | undefined
842 if (!result || result.backgroundTaskId) return ran
843 await followFromCommand($, e.command, `${result.stdout ?? ''}\n${result.stderr ?? ''}`)
844 return ran
845 })
846
847 on('prompt.submit', async ($, e, next) => {
848 const notes: string[] = await read($, notesAtom)
849 if (!ciContext || !notes.length) return next(e)
850 await update($, notesAtom, () => [])
851 return next({ ...e, context: [...(e.context ?? []), ...notes] })
852 })
853
854 on('session.start', async ($, e, next) => {
855 await $.command.register({
856 name: 'pulse',
857 description: 'PR Pulse: PR status, checks, comments and review queue. Optional arg: owner/repo#123',
858 })
859 await resume($)
860 return next(e)
861 })
862
863 on('classic.CwdChanged', async ($, e: any, next) => {
864 $.ui.log(`cwd changed to ${e.new_cwd}`, { to: 'debug' })
865 await followCwd($, String(e.new_cwd ?? ''))
866 return next(e)
867 })
868
869 on('command.run', { command: 'pulse' }, async ($, e: any) => {
870 const arg = String(e.args ?? '').trim()
871 if (running && !arg) {
872 if (await read($, collapsedAtom)) {
873 await expand($)
874 return { text: 'Expanded PR Pulse.' }
875 }
876 // a reload closes the panes while the watch carries on, so bring them back
877 await openPanes($)
878 await refresh($, true)
879 return { text: `Already watching ${target || repoCache || 'your latest PR'}; refreshed.` }
880 }
881 const url = /github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/.exec(arg)
882 repoCache = /^[\w.-]+\/[\w.-]+$/.test(arg) ? arg : ''
883 target = url ? `${url[1]}#${url[2]}` : /^.+#\d+$/.test(arg) ? arg : ''
884 await update($, viewAtom, () => ({}))
885 const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'])
886 watchedRoot = top.exitCode === 0 ? top.stdout.trim() : ''
887 const text = target ? `Watching ${target}` : repoCache ? `Watching ${repoCache}` : 'Watching your latest PR.'
888 await start($)
889 return { text }
890 })
891
892 on('ui.close', async ($, e, next) => {
893 if (e.id === PANE && e.origin.kind === 'person' && running && !(await read($, collapsedAtom))) void stop($)
894 return next(e)
895 })
896
897 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
898 if (e.props.hasSurvey || !(await read($, watchingAtom)) || !(await read($, collapsedAtom))) return next(e)
899 const open: PrRow[] = await read($, openAtom)
900 const selected: number = await read($, selectedAtom)
901 const queue: ReviewRow[] = await read($, reviewsAtom)
902 const alerts: Alert[] = await read($, alertsAtom)
903 const latest = alerts[0] && Date.now() - alerts[0].at < BAND_ALERT_MS ? alerts[0] : undefined
904 return band($.ui.resolve(e), $, open, selected, queue.length, latest)
905 })
906
907 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
908 const { Box, Text, Button } = $.ui.resolve(e)
909 const t = theme
910 const pr = await read($, prAtom)
911 const repo: string = await read($, repoAtom)
912 const openPrs: PrRow[] = await read($, openAtom)
913 const selected: number = await read($, selectedAtom)
914 const error = await read($, errorAtom)
915 const loaded: number = await read($, loadedAtom)
916 const view: View = await read($, viewAtom)
917 const steps: Step[] = await read($, stepsAtom)
918 const failedLog: string[] = await read($, logAtom)
919 const alerts: Alert[] = await read($, alertsAtom)
920
921 const pick = (n: number) => async () => {
922 await update($, selectedAtom, () => n)
923 await update($, viewAtom, () => ({}))
924 await update($, stepsAtom, () => [])
925 void refresh($)
926 }
927 const go = (v: View) => async () => {
928 await update($, viewAtom, () => v)
929 await update($, stepsAtom, () => [])
930 await update($, logAtom, () => [])
931 if (v.comments) await update($, commentsLoadedAtom, () => false)
932 if (v.job && pr) await loadSteps($, pr, v.job)
933 if (v.comments && pr) await loadComments($, pr)
934 }
935
936 const topBar = (
937 <Box flexDirection="row" justifyContent="space-between">
938 <Text>
939 <Text backgroundColor={t.brandBg} color={t.onBrand}> ◆ PR PULSE </Text>
940 <Text color={t.muted}> {repo || '…'}</Text>
941 </Text>
942 <Box flexDirection="row" gap={1}>
943 <Button key="refresh" label="↻ Refresh" hotkey="r" onPress={() => void refresh($, true)} />
944 <Button key="minimise" label="▁ Minimise" hotkey="m" onPress={() => void minimise($)} />
945 <Button key="close" label="✕ Close" hotkey="q" onPress={() => void stop($)} />
946 </Box>
947 </Box>
948 )
949 const section = (label: string, count?: number, color = t.accent) => (
950 <Box marginTop={1}>
951 <Text color={color}>{count === undefined ? label.toUpperCase() : `${label.toUpperCase()} · ${count}`}</Text>
952 </Box>
953 )
954 const errorLine = error ? <Text color={t.fail}>⚠ {error}</Text> : null
955
956 const openSection = (
957 <Box flexDirection="column">
958 {section('Open PRs', openPrs.length)}
959 {openPrs.length === 0 && <Text color={t.muted}>None open.</Text>}
960 {openPrs.map(p => {
961 const isSel = p.number === selected
962 return (
963 <Box key={`pr-row-${p.number}`} flexDirection="row">
964 <Text color={t.brand}>{isSel ? '▸ ' : ' '}</Text>
965 <Button plain key={`pr-${p.number}`} dimColor={!isSel} label={`#${p.number} ${p.title}`} onPress={pick(p.number)} />
966 {p.isDraft && <Text color={t.muted}> · draft</Text>}
967 </Box>
968 )
969 })}
970 </Box>
971 )
972
973 if (!pr) {
974 return (
975 <Box flexDirection="column">
976 {topBar}
977 {openSection}
978 {errorLine ?? <Text color={t.muted}>Loading PR…</Text>}
979 </Box>
980 )
981 }
982
983 const groups = new Map<string, Check[]>()
984 for (const c of pr.checks) groups.set(c.workflow, [...(groups.get(c.workflow) ?? []), c])
985 const total = pr.checks.length
986 const done = pr.checks.filter(c => !isPending(c)).length
987 const count = (cs: Check[]) => {
988 const n: Record<Outcome, number> = { failed: 0, running: 0, passed: 0, skipped: 0 }
989 for (const c of cs) n[outcome(c)]++
990 return n
991 }
992 const counts = count(pr.checks)
993
994 const bar = (n: Record<Outcome, number>, of: number) => {
995 const cells = (k: number) => (of ? Math.round((k / of) * BAR_WIDTH) : 0)
996 const order: Outcome[] = ['failed', 'passed', 'skipped', 'running']
997 const widths = order.map(o => cells(n[o]))
998 const rest = Math.max(0, BAR_WIDTH - widths.reduce((a, b) => a + b, 0))
999 return (
1000 <Text>
1001 {order.map((o, i) => <Text color={tone(o)}>{'█'.repeat(widths[i]!)}</Text>)}
1002 <Text color={t.rule}>{'░'.repeat(rest)}</Text>
1003 </Text>
1004 )
1005 }
1006 const tally = (n: Record<Outcome, number>) => (
1007 <Text>
1008 {OUTCOMES.filter(o => n[o]).map(o => (
1009 <Text color={tone(o)}>{GLYPH[o]} {n[o]} {o} </Text>
1010 ))}
1011 </Text>
1012 )
1013 const checkRow = (c: Check, key: string, label: string) => {
1014 const i = icon(c.status, c.conclusion)
1015 return (
1016 <Box key={key} flexDirection="row">
1017 <Text color={tone(i.tone)}>{i.glyph} </Text>
1018 <Button plain label={label} onPress={go({ workflow: c.workflow, job: c })} />
1019 </Box>
1020 )
1021 }
1022
1023 const review = pr.review.toUpperCase()
1024 const reviewColor = review === 'APPROVED' ? t.ok : review === 'CHANGES_REQUESTED' ? t.fail : t.run
1025 const reqChecks = pr.required.length ? pr.checks.filter(c => pr.required.includes(c.name)) : pr.checks
1026 const reqFailed = reqChecks.filter(isFailed).length
1027 const reqPending = reqChecks.filter(isPending).length
1028 const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
1029 const checkWord = pr.required.length ? 'required check' : 'check'
1030 // ok: true passes, false blocks, null is waiting or advisory
1031 const readiness: { ok: boolean | null; label: string }[] = [
1032 { ok: !pr.isDraft, label: pr.isDraft ? 'draft' : 'ready for review' },
1033 {
1034 ok: reqFailed ? false : reqPending ? null : true,
1035 label: reqFailed ? `${plural(reqFailed, checkWord)} failing` : reqPending ? `${plural(reqPending, checkWord)} running` : `${checkWord}s passed`,
1036 },
1037 {
1038 ok: review === 'APPROVED' || review === 'NONE',
1039 label: review === 'APPROVED' ? 'approved' : review === 'CHANGES_REQUESTED' ? 'changes requested' : review === 'NONE' ? 'no review required' : 'needs approval',
1040 },
1041 { ok: pr.unresolved <= 0, label: pr.unresolved > 0 ? plural(pr.unresolved, 'unresolved thread') : 'threads resolved' },
1042 { ok: pr.mergeable !== 'CONFLICTING', label: pr.mergeable === 'CONFLICTING' ? 'merge conflicts' : 'no conflicts' },
1043 // behind is only a blocker when a branch rule demands up-to-date branches, which github reports as BEHIND
1044 {
1045 ok: !pr.behind ? true : pr.mergeState === 'BEHIND' ? false : null,
1046 label: pr.behind ? `${plural(pr.behind, 'commit')} behind ${pr.base}` : `up to date with ${pr.base}`,
1047 },
1048 ]
1049 const waiting = readiness.some(r => r.ok === null && r.label.includes('running'))
1050 // github can block on rules the checklist cannot see (signed commits, codeowners, deployments)
1051 if (pr.mergeState === 'BLOCKED' && !waiting && readiness.every(r => r.ok !== false)) {
1052 readiness.push({ ok: false, label: 'blocked by a branch rule' })
1053 }
1054 const blockers = readiness.filter(r => r.ok === false).length
1055 const isReady = pr.state === 'OPEN' && !blockers && !waiting
1056 const verdict =
1057 pr.state === 'MERGED' ? { text: ' ⑂ MERGED ', bg: t.brandBg }
1058 : pr.state === 'CLOSED' ? { text: ' ⊘ CLOSED ', bg: t.rule }
1059 : isReady ? { text: ' ✓ READY TO MERGE ', bg: t.ok }
1060 : blockers ? { text: ` ✗ BLOCKED · ${blockers} `, bg: t.fail }
1061 : { text: ' ◐ WAITING ON CHECKS ', bg: t.run }
1062 const readinessLine = (
1063 <Box flexDirection="column" marginTop={1}>
1064 <Text>
1065 <Text backgroundColor={verdict.bg} color="#0F1729">{verdict.text}</Text>
1066 </Text>
1067 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
1068 {readiness.map(r => (
1069 <Text color={r.ok === true ? t.ok : r.ok === false ? t.fail : t.run}>
1070 {r.ok === true ? '✓' : r.ok === false ? '✗' : '◐'} {r.label}
1071 </Text>
1072 ))}
1073 </Box>
1074 </Box>
1075 )
1076
1077 // github can only update a branch without conflicts; with them, a local rebase is the way
1078 const conflicting = pr.mergeable === 'CONFLICTING'
1079 const armed: Armed = await read($, armedAtom)
1080 const branchActions = pr.state === 'OPEN' && (pr.behind > 0 || conflicting) ? (
1081 <Box flexDirection="row" flexWrap="wrap" gap={1} marginTop={1}>
1082 {!conflicting && (
1083 <Button
1084 key="update-merge"
1085 label={isArmed(armed, `merge-${pr.number}`) ? `Press again to merge ${pr.base} into #${pr.number}` : `⇣ Merge ${pr.base} in`}
1086 onPress={() => void confirmThen($, `merge-${pr.number}`, () => updateBranch($, pr, false))}
1087 />
1088 )}
1089 {!conflicting && (
1090 <Button
1091 key="update-rebase"
1092 label={isArmed(armed, `rebase-${pr.number}`) ? `Press again to rebase #${pr.number} on ${pr.base}` : `⇣ Rebase on ${pr.base}`}
1093 onPress={() => void confirmThen($, `rebase-${pr.number}`, () => updateBranch($, pr, true))}
1094 />
1095 )}
1096 <Button key="rebase-claude" label="✦ Rebase with Claude" onPress={() => void rebaseWithClaude($, pr)} />
1097 </Box>
1098 ) : null
1099 const autoMergeActions =
1100 pr.state !== 'OPEN' ? null
1101 : pr.autoMerge ? (
1102 <Box flexDirection="row" flexWrap="wrap" gap={1} marginTop={1}>
1103 <Text color={t.ok}>⚡ auto-merge on ({pr.autoMerge.toLowerCase()})</Text>
1104 {pr.canCancelAutoMerge && (
1105 <Button
1106 key="auto-merge-off"
1107 label={isArmed(armed, `automerge-off-${pr.number}`) ? `Press again to cancel auto-merge on #${pr.number}` : '✕ Cancel auto-merge'}
1108 onPress={() => void confirmThen($, `automerge-off-${pr.number}`, () => setAutoMerge($, pr, false))}
1109 />
1110 )}
1111 </Box>
1112 )
1113 : pr.canAutoMerge && pr.mergeMethod ? (
1114 <Box flexDirection="row" flexWrap="wrap" gap={1} marginTop={1}>
1115 <Button
1116 key="auto-merge-on"
1117 label={isArmed(armed, `automerge-on-${pr.number}`) ? `Press again to ${pr.mergeMethod}-merge #${pr.number} once checks pass` : '⚡ Auto-merge when checks pass'}
1118 onPress={() => void confirmThen($, `automerge-on-${pr.number}`, () => setAutoMerge($, pr, true))}
1119 />
1120 </Box>
1121 )
1122 : null
1123
1124 const card = (
1125 <Box flexDirection="column" borderStyle="round" borderColor={t.brand} paddingX={1} marginTop={1}>
1126 <Box flexDirection="row" gap={1}>
1127 <Button key="open-pr" variant="primary" label="↗ Open PR" hotkey="o" onPress={() => void openUrl($, pr.url)} />
1128 <Text>{pr.title}</Text>
1129 </Box>
1130 <Text>
1131 <Text color={t.accent}>#{pr.number}</Text>
1132 <Text color={t.muted}> · </Text>
1133 <Text color={pr.isDraft ? t.muted : t.ok}>{pr.isDraft ? '○ draft' : `● ${pr.state.toLowerCase()}`}</Text>
1134 <Text color={t.muted}> · </Text>
1135 <Text color={reviewColor}>● {REVIEW_LABEL[review] ?? review.toLowerCase().replace(/_/g, ' ')}</Text>
1136 <Text color={t.muted}> · </Text>
1137 <Text color={pr.mergeable === 'CONFLICTING' ? t.fail : t.muted}>{pr.mergeable.toLowerCase()}</Text>
1138 </Text>
1139 <Box flexDirection="row">
1140 <Text color={pr.unresolved > 0 ? t.run : t.ok}>{pr.unresolved > 0 ? '💬 ' : '✓ '}</Text>
1141 <Button
1142 plain
1143 key="comments"
1144 label={`${pr.unresolved > 0 ? `${pr.unresolved} unresolved` : 'no unresolved comments'} · ${pr.threads} thread${pr.threads === 1 ? '' : 's'} · conversation ›`}
1145 onPress={go({ comments: true })}
1146 />
1147 </Box>
1148 {readinessLine}
1149 {branchActions}
1150 {autoMergeActions}
1151 <Text color={t.muted}>updated {new Date(loaded).toLocaleTimeString()} · auto-refresh {POLL_MS / 1000}s</Text>
1152 {errorLine}
1153 </Box>
1154 )
1155 const back = (label: string, v: View) => (
1156 <Box marginTop={1}>
1157 <Button plain key={`back-${label}`} label={`← ${label}`} onPress={go(v)} />
1158 </Box>
1159 )
1160
1161 if (view.comments) {
1162 const { Markdown } = $.ui.resolve(e)
1163 const threads: Thread[] = await read($, threadsAtom)
1164 const conversation: Comment[] = await read($, conversationAtom)
1165 const loadedComments: boolean = await read($, commentsLoadedAtom)
1166 const open = threads.filter(th => !th.isResolved)
1167 const resolved = threads.filter(th => th.isResolved)
1168 const byline = (c: Comment) => (
1169 <Text>
1170 <Text color={c.author === me ? t.accent : undefined}>{c.author === me ? 'you' : c.author}</Text>
1171 {c.state && <Text color={c.state === 'APPROVED' ? t.ok : c.state === 'CHANGES_REQUESTED' ? t.fail : t.muted}> · {c.state.toLowerCase().replace(/_/g, ' ')}</Text>}
1172 <Text color={t.muted}> · {c.when}</Text>
1173 </Text>
1174 )
1175 const where = (th: Thread) => `${th.path}${th.line ? `:${th.line}` : ''}${th.isOutdated ? ' · outdated' : ''}`
1176 return (
1177 <Box flexDirection="column">
1178 {topBar}
1179 {card}
1180 {back('checks', {})}
1181 {!loadedComments && <Text color={t.muted}>Loading comments…</Text>}
1182 {loadedComments && (
1183 <Box flexDirection="column">
1184 {section('Unresolved threads', open.length, open.length ? t.run : t.accent)}
1185 {open.length === 0 && <Text color={t.ok}>✓ Nothing waiting on you.</Text>}
1186 {open.map((th, i) => (
1187 <Box key={`thread-${i}`} flexDirection="column" borderStyle="round" borderColor={t.run} paddingX={1}>
1188 <Box flexDirection="row" justifyContent="space-between">
1189 <Text color={t.accent}>{where(th)}</Text>
1190 <Box flexDirection="row" columnGap={1}>
1191 <Button key={`thread-fix-${i}`} label="✦ Address with Claude" onPress={() => void addressThread($, pr, th)} />
1192 <Button key={`thread-open-${i}`} label="↗ Open" onPress={() => void openUrl($, th.url)} />
1193 </Box>
1194 </Box>
1195 {th.comments.map((c, k) => (
1196 <Box key={`thread-${i}-c-${k}`} flexDirection="column" marginTop={k ? 1 : 0}>
1197 {byline(c)}
1198 <Markdown text={c.body || '_(no text)_'} />
1199 </Box>
1200 ))}types/index.d.ts 85 lines1export type Check = {
2 name: string
3 workflow: string
4 status: string
5 conclusion: string
6 url: string
7}
8export type Pr = {
9 repo: string
10 number: number
11 title: string
12 url: string
13 state: string
14 isDraft: boolean
15 review: string
16 mergeable: string
17 checks: Check[]
18 // 'merge' and 'waiting': a merged PR shows the runs on its merge commit instead of the PR's own
19 checksOn: 'pr' | 'merge' | 'waiting'
20 unresolved: number
21 threads: number
22 mergeState: string
23 base: string
24 head: string
25 behind: number
26 required: string[]
27 latestReviews: { author: string; state: string }[]
28 commentCount: number
29 lastCommenter: string
30 autoMerge: string
31 canAutoMerge: boolean
32 canCancelAutoMerge: boolean
33 mergeMethod: string
34}
35export type Armed = { key: string; at: number }
36export type Alert = { at: number; text: string; tone: 'ok' | 'fail' | 'run' | 'info'; url: string }
37export type PrRow = {
38 number: number
39 title: string
40 url: string
41 state: string
42 isDraft: boolean
43 author: string
44 when: string
45 // open-PR rows carry a check and review summary for the collapsed band
46 checks?: 'failed' | 'running' | 'passed' | 'skipped' | 'none'
47 failing?: number
48 review?: string
49}
50export type ReviewRow = PrRow & { direct: boolean; teams: string[] }
51export type Step = { name: string; status: string; conclusion: string }
52export type View = { workflow?: string; job?: Check; comments?: boolean }
53export type Comment = { author: string; body: string; when: string; url: string; state: string }
54export type Thread = { path: string; line: number; isResolved: boolean; isOutdated: boolean; url: string; comments: Comment[] }
55
56declare module 'claude-code' {
57 interface PluginState {
58 'pr-pulse': {
59 pr: Pr | null
60 error: string
61 loadedAt: number
62 view: View
63 steps: Step[]
64 failedLog: string[]
65 repo: string
66 openPrs: PrRow[]
67 history: PrRow[]
68 teamMerged: PrRow[]
69 reviews: ReviewRow[]
70 selected: number
71 threads: Thread[]
72 conversation: Comment[]
73 commentsLoaded: boolean
74 watching: boolean
75 target: string
76 repoCache: string
77 alerts: Alert[]
78 collapsed: boolean
79 followed: string[]
80 notes: string[]
81 armed: Armed
82 }
83 }
84}
85