SLOPSHOPPER

ci-watch

Watches CI on pull requests the agent drafts or opens, in a live pane, the status line and a notification when it settles

panebandspinnerguardcommandtoast
v0.5.0no licenseupdated 2026-10-25tidefox/claude-plugins/plugins/ci-watch
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ci-watch
│ ┃ CI ✕ › fix the failing auth test and add an audit log call │ ┃ CI watch waiting for a pull request○ IDLE │ ┃ ⏺ Read(src/auth.ts) │ ┃ ┃ ◉ No pull requests watched yet. ⎿ Read 6 lines │ ┃ ┃ They show up here when Claude runs gh pr ⏺ Update(src/auth.ts) │ ┃ ┃ create or gh pr ready, or with /ci watch ⎿ Added 2 lines, removed 1 line │ ┃ ┃ owner/repo#123. ⏺ Bash(bun test) │ ┃ ┃ ⎿ 3 pass, 1 fail │ ┃ ┃ RUNNING PASSED FAILED where CI stan │ ┃ ┃ ✓ ✗ ● ○ each check ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ┃ │ ┃ ┃ ━━━╍╍ the checks so far ✓N ✗M ✻ Worked for 42s · done 4:20 PM │ ┃ ┃ click a PR to pin it · j/k scroll · f │ ┃ ┃ follow live · u refresh › /ci │ ┃ ┃ ⎿ ci-watch: CI pane opened. │ ┃ ┃ │ ┃ │ ┃ ┃ Pull requests 0 │ ┃ ┃ ○ none yet │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ ┃ │ ┃ │ ┃ ┃ Running actions 0 ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · CI
CI watch waiting for a pull request ○ IDLE ┃ ◉ No pull requests watched yet. ┃ They show up here when Claude runs gh pr create or gh pr ┃ ready, or with /ci watch owner/repo#123. ┃ ┃ RUNNING PASSED FAILED where CI stands ┃ ✓ ✗ ● ○ each check ┃ ┃ ━━━╍╍ the checks so far ✓N ✗M ┃ click a PR to pin it · j/k scroll · f follow live · u ┃ refresh ┃ ┃ ┃ ┃ Pull requests 0 ┃ ○ none yet ┃ ┃ ┃ ┃ ┃ ┃ Running actions 0 ┃ ○ nothing running ┃ ┃ ┃ [ ↑ ] [ ↓ ]
README

ci-watch

A Claude Code mod that watches CI on pull requests the agent drafts or opens.

  • Detects gh pr create (draft or not) and gh pr ready in any Bash call, plus GitHub MCP create_pull_request / ready-for-review tools, and reads the PR URL from the output.
  • Polls gh pr checks <url> every 15s (configurable) until every check settles.
  • Pane: the same OpenCode-style fixed layout as follow, in Claude's orange: a header with a ● LIVE / ◎ PINNED / ○ SETTLED chip, then a card for every watched PR, the focused one first, stacked and scrolling inside the pane (mouse wheel, j / k, a scrollbar on the right). Each card has an accent bar in its status color and a raised fill (#N and the title, wrapped rather than cut, a status badge, a draft tag; repo, branch, done/total and elapsed CI time; the PR's URL on its own row; a segmented pass/fail/running bar with ✓N ✗M ●K chips, then per-check rows: failures first, names linked on desktop, live durations; passed and skipped checks collapse to a count when one PR's checks would fill the window). Below it, a Pull requests block of six fixed rows lists the watched PRs (a whole row lights under the pointer); click one to pin it, f to follow the newest running PR again. Buttons along the bottom: re-run failed, refresh (u), unwatch, clear settled. Between the list and the buttons, a Running actions block lists every GitHub Actions run in progress in the session's repo and the watched PRs' repos (gh run list), whoever started it. Before any PR is watched the same layout draws blank, with an ○ IDLE chip and a legend.
  • Block background: a shade dimmer than the terminal (by theme). Set blockBackground in /config to none, or to any color such as #1e1e2e.
  • Sidebar: like follow, it asks for a 64-column dock beside the transcript in Claude Code's fullscreen layout (CLAUDE_CODE_NO_FLICKER=1 claude, 110+ columns); otherwise it opens above the prompt.
  • Status line summary (CI #42 ◐ 5/8 ✗1), and a one-line band above the prompt when the pane can't be placed (narrow terminal).
  • On finish: a toast and a desktop notification. Optionally (onFinish in /config) it leaves Claude a note with the result (tell-claude), or starts a turn asking Claude to fix the failing checks (fix-failures).

Commands

CommandDoes
/ciopen the pane
`/ci watch <url \owner/repo#N>`watch any PR by hand
/ci cleardrop finished PRs
/ci stopstop watching everything

Install

Requires an authenticated gh CLI. In a Claude Code terminal session:

/plugin install ci-watch --marketplace tidefox/claude-plugins

Answer y to add the marketplace, then pick a scope (user scope loads it in every session).

Develop

claude --plugin-dir plugins/ci-watch      # run it from a checkout
claude plugin validate plugins/ci-watch
claude plugin test plugins/ci-watch
Source 2 files
hooks/register.tsx 962 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, UiScrollInput, UiScrollResult } from 'claude-code'
3
4import type { Check, CheckBucket, Phase, WatchedPr, WorkflowRun } from '../types'
5
6const PANE = 'ci-watch'
7/** The dock width asked for beside a fullscreen transcript, as follow asks; the person's own drag wins. */
8const SIDEBAR_COLUMNS = 64
9const TICK_MS = 1000
10const NO_CI_GRACE_MS = 5 * 60 * 1000
11const CONFIRM_MS = 10 * 1000
12const RERUN_HOLD_MS = 60 * 1000
13
14const prs = atom({ plugin: 'ci-watch', key: 'prs' } as const, [])
15const now = atom({ plugin: 'ci-watch', key: 'now' } as const, 0)
16const paneShown = atom({ plugin: 'ci-watch', key: 'paneShown' } as const, false)
17const pinned = atom({ plugin: 'ci-watch', key: 'pinned' } as const, null)
18const scroll = atom({ plugin: 'ci-watch', key: 'scroll' } as const, 0)
19const runs = atom({ plugin: 'ci-watch', key: 'runs' } as const, [])
20
21const PR_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g
22const PR_REF = /([\w.-]+\/[\w.-]+)#(\d+)/
23const PR_COMMAND = /\bgh\s+pr\s+(create|ready)\b/
24const SPINNER = ['◐', '◓', '◑', '◒']
25
26const GLYPH: Record<CheckBucket, string> = {
27  pass: '✓',
28  fail: '✗',
29  pending: '●',
30  skipping: '○',
31  cancel: '⊘',
32}
33const COLOR: Record<CheckBucket, string> = {
34  pass: 'success',
35  fail: 'error',
36  pending: 'warning',
37  skipping: 'inactive',
38  cancel: 'inactive',
39}
40const ORDER: Record<CheckBucket, number> = { fail: 0, cancel: 1, pending: 2, pass: 3, skipping: 4 }
41const BADGE: Record<Phase, { label: string; color: string }> = {
42  waiting: { label: 'WAITING', color: 'inactive' },
43  running: { label: 'RUNNING', color: 'warning' },
44  passed: { label: 'PASSED', color: 'success' },
45  failed: { label: 'FAILED', color: 'error' },
46  'no-ci': { label: 'NO CI', color: 'inactive' },
47  error: { label: 'ERROR', color: 'error' },
48}
49
50export const isActive = (pr: WatchedPr) => pr.phase === 'waiting' || pr.phase === 'running' || pr.phase === 'error'
51
52/** The PR a command's output names: the last github.com PR URL, else `owner/repo#N`. */
53export function findPr(text: string): { url: string; repo: string; number: number } | null {
54  const urls = [...text.matchAll(PR_URL)]
55  const last = urls[urls.length - 1]
56  if (last?.[1] && last[2]) {
57    return { url: last[0], repo: last[1], number: Number(last[2]) }
58  }
59  const ref = PR_REF.exec(text)
60  if (ref?.[1] && ref[2]) {
61    return { url: `https://github.com/${ref[1]}/pull/${ref[2]}`, repo: ref[1], number: Number(ref[2]) }
62  }
63
64  return null
65}
66
67function toTime(iso: unknown): number | null {
68  if (typeof iso !== 'string') return null
69  const t = Date.parse(iso)
70  // gh reports a check that has not started as 0001-01-01.
71  return Number.isFinite(t) && t > 946684800000 ? t : null
72}
73
74export function parseChecks(stdout: string): Check[] {
75  const rows = JSON.parse(stdout) as Record<string, unknown>[]
76  return rows.map(row => ({
77    name: String(row.name ?? ''),
78    workflow: String(row.workflow ?? ''),
79    bucket: (['pass', 'fail', 'pending', 'skipping', 'cancel'].includes(String(row.bucket))
80      ? row.bucket
81      : 'pending') as CheckBucket,
82    link: String(row.link ?? ''),
83    startedAt: toTime(row.startedAt),
84    completedAt: toTime(row.completedAt),
85  }))
86}
87
88export function parseRuns(stdout: string): WorkflowRun[] {
89  const rows = JSON.parse(stdout) as Record<string, unknown>[]
90  return rows.map(row => ({
91    url: String(row.url ?? ''),
92    name: String(row.workflowName ?? row.name ?? ''),
93    title: String(row.displayTitle ?? ''),
94    branch: String(row.headBranch ?? ''),
95    event: String(row.event ?? ''),
96    startedAt: toTime(row.startedAt),
97  }))
98}
99
100export function phaseOf(checks: Check[]): Phase {
101  if (checks.length === 0) return 'waiting'
102  if (checks.some(c => c.bucket === 'pending')) return 'running'
103  if (checks.some(c => c.bucket === 'fail' || c.bucket === 'cancel')) return 'failed'
104  return 'passed'
105}
106
107function count(checks: Check[], bucket: CheckBucket) {
108  return checks.filter(c => c.bucket === bucket).length
109}
110
111function duration(ms: number) {
112  const s = Math.max(0, Math.round(ms / 1000))
113  if (s < 60) return `${s}s`
114  const m = Math.floor(s / 60)
115  if (m < 60) return `${m}m${String(s % 60).padStart(2, '0')}s`
116  return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
117}
118
119function checkTime(c: Check, t: number) {
120  if (c.startedAt === null) return ''
121  return duration((c.completedAt ?? t) - c.startedAt)
122}
123
124/** How long CI has run: first check start to last finish, else since the watch began. */
125function ciElapsed(pr: WatchedPr, t: number) {
126  const starts = pr.checks.map(c => c.startedAt).filter((v): v is number => v !== null)
127  if (starts.length === 0) return duration((pr.finishedAt ?? t) - pr.addedAt)
128  const ends = pr.checks.map(c => (c.bucket === 'pending' ? t : c.completedAt ?? t))
129  return duration(Math.max(...ends) - Math.min(...starts))
130}
131
132/** A row of the checks list: one check, or a count standing in for those that did not fit. */
133export type CheckLine = { check: Check } | { bucket: CheckBucket; text: string }
134
135/**
136 * The checks list in at most `room` rows: failing, then running, then passed, each by name.
137 * Passed and skipped checks become one count each when the list runs out of room, and the
138 * counts give way before any failing or running name does: those that still do not fit end
139 * in an `N more` row.
140 */
141export function checkLines(checks: Check[], room: number): CheckLine[] {
142  const sorted = [...checks].sort((a, b) => ORDER[a.bucket] - ORDER[b.bucket] || a.name.localeCompare(b.name))
143  const of = (...buckets: CheckBucket[]) => sorted.filter(c => buckets.includes(c.bucket))
144  const head = of('fail', 'cancel', 'pending')
145  const passed = of('pass')
146  const skipped = of('skipping').length
147  const tail: CheckLine[] = skipped > 0 ? [{ bucket: 'skipping', text: `${skipped} skipped` }] : []
148  if (head.length + passed.length + tail.length <= room) return [...[...head, ...passed].map(check => ({ check })), ...tail]
149  if (passed.length > 0) tail.unshift({ bucket: 'pass', text: `${passed.length} passed` })
150  const kept = tail.slice(0, Math.max(0, room - head.length))
151  if (head.length <= room) return [...head.map(check => ({ check })), ...kept]
152  if (room <= 0) return []
153  const shown = head.slice(0, room - 1)
154  return [...shown.map(check => ({ check })), { bucket: head[shown.length]!.bucket, text: `${head.length - shown.length} more` }]
155}
156
157/** The PR the pane shows: the pinned one while it is watched, else the newest running, else the newest. */
158export function focusOf(list: WatchedPr[], pin: string | null): WatchedPr | undefined {
159  return list.find(pr => pr.url === pin) ?? list.find(isActive) ?? list[0]
160}
161
162/** Rows the PR list always shows. */
163const LIST_ROWS = 6
164/** Rows the running-actions block always shows. */
165const RUN_ROWS = 4
166/** Rows a wheel tick or j/k moves the cards. */
167const SCROLL_STEP = 3
168/** The cards' first row from the pane's top: the header, then a gap. */
169const CARDS_TOP = 2
170
171/**
172 * The fixed layout's rows, top to bottom: header, gap, the cards (one per PR, scrolling
173 * inside their rows), gap + heading + six rows for the PR list, the same with four rows for
174 * the running actions, and the buttons.
175 */
176export function paneLayout(bodyRows: number) {
177  return { listRows: LIST_ROWS, cardRows: Math.max(4, bodyRows - CARDS_TOP - (2 + LIST_ROWS) - (2 + RUN_ROWS) - 1) }
178}
179
180/** A scrollbar's thumb over `rows` cells for a window at `top` of `total`: where it starts and how long. */
181export function thumb(top: number, total: number, rows: number): { from: number; size: number } {
182  if (total <= rows) return { from: 0, size: rows }
183  const size = Math.max(1, Math.round((rows * rows) / total))
184  const from = Math.round((top / (total - rows)) * (rows - size))
185  return { from: Math.min(rows - size, Math.max(0, from)), size }
186}
187
188/** Where the cards last drew: the wheel and j/k move them from there. */
189let drawn = { rows: 0, top: 0, maxTop: 0 }
190
191async function scrollCards($: EngineInterface, by: number) {
192  const top = Math.min(drawn.maxTop, Math.max(0, drawn.top + by))
193  if (top === drawn.top) return
194  drawn = { ...drawn, top }
195  await update($, scroll, () => top)
196}
197
198// ── cells (as follow measures them) ──────────────────────────────────────
199
200/** East Asian Wide and Fullwidth: CJK, and the emoji a terminal draws two cells wide. */
201const WIDE =
202  /[\u1100-\u115f\u231a-\u231b\u2329-\u232a\u23e9-\u23ec\u23f0\u23f3\u25fd-\u25fe\u2614-\u2615\u2648-\u2653\u267f\u2693\u26a1\u26aa-\u26ab\u26bd-\u26be\u26c4-\u26c5\u26ce\u26d4\u26ea\u26f2-\u26f3\u26f5\u26fa\u26fd\u2705\u270a-\u270b\u2728\u274c\u274e\u2753-\u2755\u2757\u2795-\u2797\u27b0\u27bf\u2b1b-\u2b1c\u2b50\u2b55\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\ua960-\ua97f\uac00-\ud7a3\uf900-\ufaff\ufe10-\ufe19\ufe30-\ufe6f\uff00-\uff60\uffe0-\uffe6\u{16fe0}-\u{18cff}\u{1b000}-\u{1b2ff}\u{1f004}\u{1f0cf}\u{1f18e}\u{1f191}-\u{1f19a}\u{1f1e6}-\u{1f1ff}\u{1f200}-\u{1f2ff}\u{1f300}-\u{1f64f}\u{1f680}-\u{1f6ff}\u{1f7e0}-\u{1f7eb}\u{1f90c}-\u{1f9ff}\u{1fa70}-\u{1faff}\u{20000}-\u{3fffd}]/u
203const ZERO = /[\u0300-\u036f\u200b-\u200f\u20d0-\u20ff\ufe00-\ufe0f]/u
204
205/** Terminal cells one character takes: two for wide (CJK, emoji), none for a combining mark. */
206const charCells = (ch: string) => (ZERO.test(ch) ? 0 : WIDE.test(ch) ? 2 : 1)
207/** Printable ASCII, a cell a character: most names, measured and cut without a look at each character. */
208const ASCII = /^[ -~]*$/
209
210export function cellWidth(text: string): number {
211  if (ASCII.test(text)) return text.length
212  let n = 0
213  for (const ch of text) n += charCells(ch)
214  return n
215}
216
217/** `text` in at most `room` cells: cut at the end with `…`. */
218export function clip(text: string, room: number): string {
219  if (cellWidth(text) <= room) return text
220  if (room <= 1) return room === 1 ? '…' : ''
221  let out = ''
222  let col = 0
223  for (const ch of text) {
224    const w = charCells(ch)
225    if (col + w > room - 1) break
226    out += ch
227    col += w
228  }
229  return `${out}…`
230}
231
232/** `text` broken at spaces into lines of at most `room` cells; a word wider than a line is cut. */
233export function wrapCells(text: string, room: number): string[] {
234  const lines: string[] = []
235  let line = ''
236  for (const word of text.split(/\s+/).filter(Boolean)) {
237    const next = line ? `${line} ${word}` : word
238    if (cellWidth(next) <= room) line = next
239    else {
240      if (line) lines.push(line)
241      line = clip(word, room)
242    }
243  }
244  return line ? [...lines, line] : lines
245}
246
247let blockBackgroundOption = 'auto'
248let themeName: string | null = null
249
250async function theme($: EngineInterface): Promise<string> {
251  themeName ??= String((await $.config.list().catch(() => [])).find(row => row.key === 'theme')?.value ?? '')
252  return themeName
253}
254
255/** The blocks' fill: a shade dimmer than the terminal's, by theme, unless set in /config. */
256async function blockBackground($: EngineInterface): Promise<string | undefined> {
257  if (blockBackgroundOption === 'none') return undefined
258  if (blockBackgroundOption !== 'auto') return blockBackgroundOption
259  const name = await theme($)
260  return /light/.test(name) ? '#eeeeee' : /ansi/.test(name) ? undefined : '#1c1c1c'
261}
262
263/** A PR row under the pointer: a step off the fill, by theme. */
264async function rowHover($: EngineInterface): Promise<string> {
265  const name = await theme($)
266  return /light/.test(name) ? '#dcdcdc' : /ansi/.test(name) ? 'subtle' : '#303030'
267}
268
269let pollMs = 15000
270let onFinish = 'notify'
271const inFlight = new Set<string>()
272
273function patch($: EngineInterface, url: string, fields: Partial<WatchedPr>) {
274  return update($, prs, list => list.map(pr => (pr.url === url ? { ...pr, ...fields } : pr)))
275}
276
277async function openPane($: EngineInterface) {
278  const opened = await $.ui.open({ id: PANE, title: 'CI', columns: SIDEBAR_COLUMNS, rows: 30 })
279  await update($, paneShown, () => opened.isPlaced)
280}
281
282async function watch($: EngineInterface, found: { url: string; repo: string; number: number }, isReady = false) {
283  const t = await $.clock.now()
284  const list = await read($, prs)
285  const known = list.find(pr => pr.url === found.url)
286  if (known) {
287    // Marked ready for review: workflows that skip drafts start now, so watch again.
288    if (isReady) {
289      await patch($, found.url, { isDraft: false, phase: 'waiting', addedAt: t, polledAt: null, finishedAt: null, error: null, settleKey: null })
290    }
291  } else {
292    const pr: WatchedPr = {
293      ...found,
294      title: '',
295      isDraft: false,
296      branch: '',
297      phase: 'waiting',
298      checks: [],
299      addedAt: t,
300      polledAt: null,
301      finishedAt: null,
302      error: null,
303      settleKey: null,
304      rerunAt: null,
305    }
306    await update($, prs, all => [pr, ...all.filter(p => p.url !== found.url)].slice(0, 8))
307  }
308  void openPane($)
309}
310
311async function announce($: EngineInterface, pr: WatchedPr) {
312  const failed = pr.checks.filter(c => c.bucket === 'fail' || c.bucket === 'cancel')
313  const text =
314    pr.phase === 'passed'
315      ? `✓ CI passed on #${pr.number} (${pr.checks.length} checks)`
316      : pr.phase === 'failed'
317        ? `✗ CI failed on #${pr.number}: ${failed.map(c => c.name).join(', ')}`
318        : `No CI checks reported on #${pr.number}`
319  $.ui.toast(text)
320  void $.ui.notify(text, { title: pr.title ? `CI · ${pr.title}` : 'CI' })
321
322  if (onFinish === 'notify' || pr.phase === 'no-ci') return
323  const detail = failed.map(c => `- ${c.workflow ? `${c.workflow} / ` : ''}${c.name}: ${c.link}`).join('\n')
324  const note = `[ci-watch] ${text}\nPR: ${pr.url}${detail ? `\nFailing checks:\n${detail}` : ''}`
325  if (onFinish === 'fix-failures' && pr.phase === 'failed') {
326    await $.prompt.submit({
327      text: `${note}\n\nInvestigate the failing CI checks on this PR (gh run view --log-failed), fix them, and push.`,
328    })
329  } else {
330    await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: note }] } })
331  }
332}
333
334async function poll($: EngineInterface, pr: WatchedPr) {
335  if (inFlight.has(pr.url)) return
336  inFlight.add(pr.url)
337  try {
338    const t = await $.clock.now()
339    await patch($, pr.url, { polledAt: t })
340
341    if (pr.title === '') {
342      const view = await $.process.run(['gh', 'pr', 'view', pr.url, '--json', 'title,isDraft,headRefName'])
343      if (view.exitCode === 0) {
344        const meta = JSON.parse(view.stdout) as { title?: string; isDraft?: boolean; headRefName?: string }
345        await patch($, pr.url, { title: meta.title ?? '', isDraft: meta.isDraft === true, branch: meta.headRefName ?? '' })
346      }
347    }
348
349    // gh exits 8 while checks are pending and 1 when one failed: the JSON is on stdout either way.
350    const run = await $.process.run([
351      'gh', 'pr', 'checks', pr.url, '--json', 'bucket,name,workflow,link,startedAt,completedAt',
352    ])
353    const out = run.stdout.trim()
354    let next: Partial<WatchedPr>
355    if (out.startsWith('[')) {
356      const checks = parseChecks(out)
357      next = { checks, phase: phaseOf(checks), error: null }
358    } else if (/no checks reported/i.test(run.stderr)) {
359      next = { checks: [], phase: t - pr.addedAt > NO_CI_GRACE_MS ? 'no-ci' : 'waiting', error: null }
360    } else {
361      next = { phase: 'error', error: (run.stderr.trim() || `gh exited ${run.exitCode}`).split('\n')[0] ?? null }
362    }
363
364    // Every check reported so far may be done while later jobs have yet to register, or a
365    // re-run has yet to show: settle only when a second poll sees the same settled set.
366    if (next.phase === 'passed' || next.phase === 'failed') {
367      const key = (next.checks ?? []).map(c => `${c.name}:${c.bucket}`).sort().join('|')
368      const isHeld = pr.rerunAt !== null && t - pr.rerunAt < RERUN_HOLD_MS
369      if (isHeld || pr.settleKey !== key) {
370        next = { ...next, phase: 'running', settleKey: isHeld ? null : key, polledAt: t - pollMs + CONFIRM_MS }
371      }
372    } else if (next.phase === 'running') {
373      next = { ...next, settleKey: null, rerunAt: null }
374    }
375
376    const isDone = next.phase === 'passed' || next.phase === 'failed' || next.phase === 'no-ci'
377    if (isDone) next.finishedAt = t
378    await patch($, pr.url, next)
379    if (isDone) {
380      const settled = (await read($, prs)).find(p => p.url === pr.url)
381      // A failed notice must never reopen a settled PR, or it would announce on every poll.
382      if (settled) await announce($, settled).catch(() => undefined)
383    }
384  } catch (err) {
385    const message = err instanceof Error ? err.message : String(err)
386    await patch($, pr.url, { phase: 'error', error: /ENOENT|not found|cannot start/i.test(message) ? 'gh is not installed or not on PATH' : message })
387  } finally {
388    inFlight.delete(pr.url)
389  }
390}
391
392let runsAt = 0
393let runsBusy = false
394
395/** Every GitHub Actions run in progress, whatever started it: the session's repo and each watched PR's. */
396async function pollRuns($: EngineInterface, list: WatchedPr[]) {
397  if (runsBusy) return
398  runsBusy = true
399  try {
400    const fields = 'url,workflowName,displayTitle,headBranch,event,startedAt'
401    const repos = [...new Set(list.map(pr => pr.repo))]
402    const found = await Promise.all(
403      [[], ...repos.map(r => ['-R', r])].map(async target => {
404        const res = await $.process.run(['gh', 'run', 'list', '--status', 'in_progress', '--limit', '20', '--json', fields, ...target])
405        return res.exitCode === 0 && res.stdout.trim().startsWith('[') ? parseRuns(res.stdout) : []
406      }),
407    )
408    const all = [...new Map(found.flat().map(r => [r.url, r])).values()]
409    await update($, runs, () => all.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0)))
410  } catch {
411    // gh missing or signed out: the PR polls already say so.
412  } finally {
413    runsBusy = false
414  }
415}
416
417async function tick($: EngineInterface) {
418  const t = await $.clock.now()
419  const list = await read($, prs)
420  if ((await read($, paneShown)) && t - runsAt >= pollMs) {
421    runsAt = t
422    void pollRuns($, list)
423  }
424  if ((await read($, runs)).length > 0) await update($, now, () => t)
425  if (list.some(isActive)) await update($, now, () => t)
426  for (const pr of list) {
427    if (isActive(pr) && (pr.polledAt === null || t - pr.polledAt >= pollMs)) void poll($, pr)
428  }
429}
430
431async function rerunFailed($: EngineInterface, pr: WatchedPr) {
432  const runs = new Set<string>()
433  for (const c of pr.checks) {
434    const id = /\/actions\/runs\/(\d+)/.exec(c.link)?.[1]
435    if (id && (c.bucket === 'fail' || c.bucket === 'cancel')) runs.add(id)
436  }
437  if (runs.size === 0) {
438    $.ui.toast('No failed GitHub Actions runs to re-run')
439    return
440  }
441  for (const id of runs) {
442    const res = await $.process.run(['gh', 'run', 'rerun', id, '--failed', '-R', pr.repo])
443    if (res.exitCode !== 0) {
444      $.ui.toast(`Re-run of ${id} failed: ${res.stderr.trim().split('\n')[0] ?? ''}`)
445      return
446    }
447  }
448  $.ui.toast(`Re-running ${runs.size} failed workflow run${runs.size > 1 ? 's' : ''} on #${pr.number}`)
449  const t = await $.clock.now()
450  await patch($, pr.url, { phase: 'running', finishedAt: null, settleKey: null, rerunAt: t, polledAt: t - pollMs + 5000 })
451}
452
453export const register: Register = (on, options) => {
454  pollMs = Math.max(5, Number(options.pollSeconds ?? 15)) * 1000
455  onFinish = String(options.onFinish ?? 'notify')
456  blockBackgroundOption = String(options.blockBackground ?? 'auto').trim() || 'auto'
457  themeName = null
458
459  on('session.start', async ($, e, next) => {
460    await $.command.register({
461      name: 'ci',
462      description: 'CI watcher: open the pane, or watch <PR url|owner/repo#N>, clear, stop',
463      argumentHint: '[watch <pr> | clear | stop]',
464      immediate: true,
465    })
466    $.clock.every(TICK_MS, () => void tick($))
467    if ((await read($, prs)).length > 0) void openPane($)
468
469    return next(e)
470  })
471
472  on('command.run', { command: 'ci' }, async ($, e) => {
473    const [verb = '', ...rest] = e.args.trim().split(/\s+/)
474    if (verb === 'watch') {
475      const arg = rest.join(' ')
476      const found = findPr(arg)
477      if (!found) return { text: 'Usage: /ci watch <https://github.com/owner/repo/pull/N | owner/repo#N>' }
478      await watch($, found)
479      return { text: `Watching CI on ${found.repo}#${found.number}` }
480    }
481    if (verb === 'clear') {
482      await update($, prs, list => list.filter(isActive))
483      return { text: 'Cleared finished PRs.' }
484    }
485    if (verb === 'stop') {
486      await update($, prs, () => [])
487      await update($, pinned, () => null)
488      await $.ui.close({ id: PANE })
489      return { text: 'Stopped watching all PRs.' }
490    }
491    await openPane($)
492    return { text: 'CI pane opened.' }
493  })
494
495  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
496    const match = PR_COMMAND.exec(e.command)
497    if (!match) return next(e)
498    const ran = await next(e)
499    const found = findPr(ran.text ?? '')
500    if (found) void watch($, found, match[1] === 'ready')
501
502    return ran
503  }).catch(($, e, next) => next(e))
504
505  // GitHub MCP servers' create / ready tools.
506  on('tool.call', async ($, e, next) => {
507    const name = String(e.tool)
508    if (!name.startsWith('mcp__') || !/(create_pull_request|ready_for_review)/i.test(name)) return next(e)
509    const ran = await next(e)
510    const found = ran.isError ? null : findPr(ran.text ?? '')
511    if (found) void watch($, found, /ready/i.test(name))
512
513    return ran
514  }).catch(($, e, next) => next(e))
515
516  // The wheel over the cards scrolls them, not the pane: the layout is fixed.
517  on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e: UiScrollInput, next: (e: UiScrollInput) => Promise<UiScrollResult>) => {
518    if (e.origin.kind !== 'person' || e.by === 0) return next(e)
519    const row = e.pointer?.row
520    if (row !== undefined && (row < CARDS_TOP || row >= CARDS_TOP + drawn.rows)) return next(e)
521    // A page key asks for the body's height: page the cards instead.
522    await scrollCards($, row === undefined && Math.abs(e.by) >= e.bodyRows ? Math.sign(e.by) * drawn.rows : e.by)
523    return next({ ...e, offset: Math.max(0, e.offset - e.by) })
524  }).catch(($, e, next) => next(e))
525
526  on('ui.close', { id: PANE }, async ($, e, next) => {
527    await update($, paneShown, () => false)
528    return next(e)
529  }).catch(($, e, next) => next(e))
530
531  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
532    const { Box, Text, Button, Link } = $.ui.resolve(e)
533    // A terminal without OSC 8 draws a Link's text then its whole URL: the terminal gets the URL as its own row instead.
534    const isDesktop = e.surface === 'desktop'
535    const list = await read($, prs)
536    const running = await read($, runs)
537    const pin = await read($, pinned)
538    const t = Math.max(await read($, now), await $.clock.now())
539    const width = Math.max(24, e.props.bodyColumns)
540    const focus = focusOf(list, pin)
541    const isPinned = focus !== undefined && focus.url === pin
542    const isIdle = list.length === 0
543    const active = list.filter(isActive).length
544    const spin = SPINNER[Math.floor(t / TICK_MS) % SPINNER.length] ?? '●'
545
546    // A fixed layout as tall as the body: the cards take what the header and the PR list leave, and scroll inside it.
547    const rows = Math.max(16, e.props.scroll.bodyRows)
548    const layout = paneLayout(rows)
549    // A card's text runs between the pane's padding, its accent bar, its own padding and the scrollbar.
550    const inner = width - 6
551    const panel = await blockBackground($)
552    const hover = await rowHover($)
553
554    const chip = isIdle
555      ? { text: '○ IDLE', color: 'inactive' }
556      : isPinned
557        ? { text: '◎ PINNED', color: 'warning' }
558        : active > 0
559          ? { text: '● LIVE', color: 'claude' }
560          : { text: '○ SETTLED', color: 'inactive' }
561    const who = isIdle ? 'waiting for a pull request' : active > 0 ? `${active} running · every ${pollMs / 1000}s` : 'all settled'
562
563    const badge = (phase: Phase) => (
564      <Text bold color="inverseText" backgroundColor={BADGE[phase].color}>
565        {` ${phase === 'running' ? `${spin} ` : ''}${BADGE[phase].label} `}
566      </Text>
567    )
568    const fails = (pr: WatchedPr) => count(pr.checks, 'fail') + count(pr.checks, 'cancel')
569    const tally = (pr: WatchedPr) => (
570      <Text>
571        <Text bold backgroundColor="#1d460f">{` ✓${count(pr.checks, 'pass')} `}</Text>
572        <Text bold backgroundColor="#540d06">{` ✗${fails(pr)} `}</Text>
573        <Text bold color="warning">{` ●${count(pr.checks, 'pending')} `}</Text>
574      </Text>
575    )
576    const tallyWidth = (pr: WatchedPr) => `${count(pr.checks, 'pass')}${fails(pr)}${count(pr.checks, 'pending')}`.length + 9
577
578    // A block as OpenCode draws one: an accent bar down its left, a raised fill.
579    const block = (key: string, accent: string, height: number, body: unknown) => (
580      <Box key={key} flexDirection="row" marginTop={1} height={height}>
581        <Box flexDirection="column" flexShrink={0}>
582          {Array.from({ length: height }, () => (
583            <Text color={accent}>┃</Text>
584          ))}
585        </Box>
586        <Box flexDirection="column" flexGrow={1} flexShrink={1} backgroundColor={panel} paddingX={1} overflow="hidden">
587          {body as never}
588        </Box>
589      </Box>
590    )
591    const heading = (title: string, note: string) => (
592      <Box flexDirection="row" height={1}>
593        <Box flexGrow={1} flexShrink={1}>
594          <Text bold wrap="truncate-end">{title}</Text>
595        </Box>
596        <Box flexShrink={0}>
597          <Text dimColor>{note}</Text>
598        </Box>
599      </Box>
600    )
601
602    const bar = (pr: WatchedPr, room: number) => {
603      const total = pr.checks.length
604      if (total === 0) return <Text color="subtle">{'─'.repeat(room)}</Text>
605      const segments = (['pass', 'fail', 'cancel', 'pending', 'skipping'] as const).map(b => [b, count(pr.checks, b)] as const)
606      let used = 0
607      const cells = segments.map(([b, n], i) => {
608        const cellsFor = i === segments.length - 1 ? room - used : Math.round((n / total) * room)
609        used += cellsFor
610        return [b, cellsFor] as const
611      })
612      return (
613        <Text>
614          {cells.filter(([, n]) => n > 0).map(([b, n]) => (
615            <Text color={COLOR[b]} dimColor={b === 'skipping' || b === 'cancel'}>
616              {(b === 'pending' ? '╍' : '━').repeat(n)}
617            </Text>
618          ))}
619        </Text>
620      )
621    }
622
623    const checkRow = (line: CheckLine, i: number) => {
624      if (!('check' in line)) {
625        return (
626          <Text key={`more:${i}`} wrap="truncate-end">
627            <Text color={COLOR[line.bucket]}>{line.bucket === 'pending' ? spin : GLYPH[line.bucket]}</Text>
628            <Text dimColor> {line.text}</Text>
629          </Text>
630        )
631      }
632      const c = line.check
633      const time = checkTime(c, t)
634      // The glyph and a space; the duration and a space on the right.
635      const room = Math.max(4, inner - 2 - (time ? time.length + 1 : 0))
636      const flow = c.workflow && c.workflow !== c.name ? clip(c.workflow, Math.floor(room / 3)) : ''
637      const name = clip(c.name, room - (flow ? cellWidth(flow) + 3 : 0))
638      const isQuiet = c.bucket === 'pass' || c.bucket === 'skipping'
639      return (
640        <Box key={`check:${i}`} flexDirection="row" height={1}>
641          <Box flexShrink={0}>
642            <Text color={COLOR[c.bucket]}>{c.bucket === 'pending' ? spin : GLYPH[c.bucket]} </Text>
643          </Box>
644          <Box flexGrow={1} flexShrink={1}>
645            <Text wrap="truncate-end" dimColor={isQuiet} bold={c.bucket === 'fail'}>
646              {flow ? <Text dimColor>{flow} › </Text> : ''}
647              {c.link && isDesktop ? <Link href={c.link}>{name}</Link> : name}
648            </Text>
649          </Box>
650          <Box flexShrink={0}>
651            <Text dimColor>{time ? ` ${time}` : ''}</Text>
652          </Box>
653        </Box>
654      )
655    }
656
657    /** A PR's card as rows of one line each, so the cards scroll a row at a time. */
658    const card = (pr: WatchedPr) => {
659      const elapsed = ciElapsed(pr, t)
660      const done = pr.checks.filter(c => c.bucket !== 'pending').length
661      const notes = [
662        pr.phase === 'waiting' ? <Text dimColor>{spin} Waiting for checks to be reported…</Text> : null,
663        pr.phase === 'no-ci' ? <Text dimColor>○ No checks were reported for this PR.</Text> : null,
664        pr.error ? <Text color="error" wrap="truncate-end">⚠ {pr.error}</Text> : null,
665      ].filter(n => n !== null)
666      // The number, the draft tag and the badge keep their cells; the title wraps onto rows of its own.
667      const badgeWidth = BADGE[pr.phase].label.length + 2 + (pr.phase === 'running' ? 2 : 0)
668      const indent = String(pr.number).length + 2
669      const titleRoom = Math.max(8, inner - indent - (pr.isDraft ? 6 : 0) - 1 - badgeWidth)
670      const [first = '', ...rest] = wrapCells(pr.title || pr.repo, titleRoom)
671      // One PR's checks never take more than the window: passed and skipped collapse first.
672      const lines = checkLines(pr.checks, Math.max(3, layout.cardRows - 4 - rest.length - notes.length))
673      const timing = ` ${pr.checks.length > 0 ? `${done}/${pr.checks.length} · ` : ''}⏱ ${elapsed}`
674      const branchRoom = inner - cellWidth(timing) - cellWidth(pr.repo)
675      const accent = pr.url === pin ? 'warning' : BADGE[pr.phase].color
676      return [
677          <Box flexDirection="row" height={1}>
678            <Box flexShrink={0}>
679              <Text bold color="claude">{`#${pr.number} `}</Text>
680            </Box>
681            <Box flexGrow={1} flexShrink={1}>
682              <Text bold wrap="truncate-end">{first}</Text>
683            </Box>
684            <Box flexShrink={0}>
685              {pr.isDraft ? <Text color="inactive">{' DRAFT'}</Text> : ''}
686              <Text> </Text>
687              {badge(pr.phase)}
688            </Box>
689          </Box>,
690          ...rest.map(line => <Text bold wrap="truncate-end">{`${' '.repeat(indent)}${line}`}</Text>),
691          <Box flexDirection="row" height={1}>
692            <Box flexGrow={1} flexShrink={1}>
693              <Text dimColor wrap="truncate-end">
694                {pr.repo}
695                {pr.branch ? clip(` ⎇ ${pr.branch}`, branchRoom) : ''}
696              </Text>
697            </Box>
698            <Box flexShrink={0}>
699              <Text dimColor>{timing}</Text>
700            </Box>
701          </Box>,
702          <Text color="subtle" wrap="truncate-end">{isDesktop ? <Link href={pr.url}>{pr.url}</Link> : pr.url}</Text>,
703          <Box flexDirection="row" height={1}>
704            <Box flexGrow={1} flexShrink={1} overflow="hidden">
705              {bar(pr, Math.max(4, inner - tallyWidth(pr) - 1))}
706            </Box>
707            <Box flexShrink={0}>
708              <Text> </Text>
709              {tally(pr)}
710            </Box>
711          </Box>,
712        ...notes,
713        ...lines.map(checkRow),
714      ].map((node, i) => ({ key: `${pr.url}:${i}`, accent, node }))
715    }
716
717    const idleBlock = () =>
718      block(
719        'idle',
720        'claude',
721        layout.cardRows,
722        <Box flexDirection="column">
723          <Text bold color="claude">◉ No pull requests watched yet.</Text>
724          <Text dimColor wrap="wrap">They show up here when Claude runs gh pr create or gh pr ready, or with /ci watch owner/repo#123.</Text>
725          <Box marginTop={1} flexDirection="row" gap={1}>
726            {(['running', 'passed', 'failed'] as const).map(phase => (
727              <Text key={`k:${phase}`} bold color="inverseText" backgroundColor={BADGE[phase].color}>{` ${BADGE[phase].label} `}</Text>
728            ))}
729            <Text dimColor>where CI stands</Text>
730          </Box>
731          <Box flexDirection="row" gap={1}>
732            {(['pass', 'fail', 'pending', 'skipping'] as const).map(b => (
733              <Text key={`g:${b}`} color={COLOR[b]}>{GLYPH[b]}</Text>
734            ))}
735            <Text dimColor>each check</Text>
736          </Box>
737          <Box marginTop={1} flexDirection="column">
738            <Text>
739              <Text color="success">━━</Text>
740              <Text color="error">━</Text>
741              <Text color="warning">╍╍</Text>
742              <Text dimColor> the checks so far   </Text>
743              <Text bold backgroundColor="#1d460f">{' ✓N '}</Text>
744              <Text bold backgroundColor="#540d06">{' ✗M '}</Text>
745            </Text>
746            <Text dimColor wrap="wrap">click a PR to pin it · j/k scroll · f follow live · u refresh</Text>
747          </Box>
748        </Box>,
749      )
750
751    const prRow = (pr: WatchedPr) => {
752      const isFocus = pr.url === focus?.url
753      const age = ciElapsed(pr, t)
754      const tallyText = pr.checks.length > 0 ? ` ✓${count(pr.checks, 'pass')}${fails(pr) > 0 ? ` ✗${fails(pr)}` : ''}` : ''
755      // ▸, the phase glyph and a space, `#N` and a space; the tally, a space and the age on the right.
756      const room = inner - 3 - String(pr.number).length - 2 - tallyText.length - 1 - age.length
757      return (
758        // The whole row lights under the pointer, not only its text.
759        <Box key={`p:${pr.url}`} flexDirection="row" height={1} hover={{ backgroundColor: hover }}>
760          <Box flexGrow={1} flexShrink={1}>
761            <Button key={`pr:${pr.url}`} plain onPress={() => Promise.all([update($, pinned, () => pr.url), update($, scroll, () => 0)])}>
762              <Text color={isFocus ? 'claude' : 'subtle'}>{isFocus ? '▸' : ' '}</Text>
763              <Text color={BADGE[pr.phase].color}>{pr.phase === 'running' ? spin : pr.phase === 'passed' ? '✓' : pr.phase === 'failed' ? '✗' : pr.phase === 'error' ? '⚠' : '○'}</Text>{' '}
764              <Text bold color={isFocus ? 'claude' : undefined}>#{pr.number}</Text>{' '}
765              <Text dimColor={!isFocus && !isActive(pr)} bold={isFocus}>{clip(pr.title || pr.repo, room)}</Text>
766            </Button>
767          </Box>
768          <Box flexShrink={0}>
769            {pr.checks.length > 0 ? (
770              <Text>
771                {' '}
772                <Text color="success">✓{count(pr.checks, 'pass')}</Text>
773                {fails(pr) > 0 ? <Text color="error"> ✗{fails(pr)}</Text> : ''}
774              </Text>
775            ) : (
776              ''
777            )}
778            <Text dimColor>{` ${age}`}</Text>
779          </Box>
780        </Box>
781      )
782    }
783
784    const runRow = (run: WorkflowRun) => {
785      const age = run.startedAt === null ? '' : duration(t - run.startedAt)
786      const flow = clip(run.name, Math.floor(inner / 3))
787      const room = inner - 2 - cellWidth(flow) - 3 - (age ? age.length + 1 : 0)
788      const label = `${flow} › ${clip(`${run.title}${run.branch ? ` ⎇ ${run.branch}` : ''}`, room)}`
789      return (
790        <Box key={`r:${run.url}`} flexDirection="row" height={1}>
791          <Box flexShrink={0}>
792            <Text color="warning">{spin} </Text>
793          </Box>
794          <Box flexGrow={1} flexShrink={1}>
795            <Text wrap="truncate-end">{isDesktop ? <Link href={run.url}>{label}</Link> : label}</Text>
796          </Box>
797          <Box flexShrink={0}>
798            <Text dimColor>{age ? ` ${age}` : ''}</Text>
799          </Box>
800        </Box>
801      )
802    }
803
804    // Every PR's card, the focused one first, a blank row between: the window shows the rows from the scrolled top.
805    const cardList = focus ? [focus, ...list.filter(pr => pr !== focus)] : []
806    const cardLines = cardList.flatMap((pr, i) => [...(i > 0 ? [null] : []), ...card(pr)])
807    const maxTop = Math.max(0, cardLines.length - layout.cardRows)
808    const top = Math.min(maxTop, Math.max(0, await read($, scroll)))
809    drawn = { rows: layout.cardRows, top, maxTop }
810    const grip = thumb(top, cardLines.length, layout.cardRows)
811    const cardsBlock = () => (
812      <Box key="cards" flexDirection="row" marginTop={1} height={layout.cardRows}>
813        <Box flexDirection="column" flexGrow={1} flexShrink={1} overflow="hidden">
814          {cardLines.slice(top, top + layout.cardRows).map((line, i) =>
815            line === null ? (
816              <Text key={`gap:${top + i}`}> </Text>
817            ) : (
818              <Box key={line.key} flexDirection="row" height={1}>
819                <Box flexShrink={0}>
820                  <Text color={line.accent}>┃</Text>
821                </Box>
822                <Box flexGrow={1} flexShrink={1} backgroundColor={panel} paddingX={1} overflow="hidden">
823                  {line.node as never}
824                </Box>
825              </Box>
826            ),
827          )}
828        </Box>
829        {/* The scrollbar's column stays, blank when nothing scrolls: the cards never change width. */}
830        <Box flexDirection="column" flexShrink={0} width={1}>
831          {Array.from({ length: layout.cardRows }, (_, i) => {
832            const isThumb = i >= grip.from && i < grip.from + grip.size
833            return (
834              <Text key={`bar:${i}`} color={isThumb ? 'claude' : 'subtle'}>
835                {maxTop === 0 ? ' ' : isThumb ? '┃' : '│'}
836              </Text>
837            )
838          })}
839        </Box>
840      </Box>
841    )
842
843    const canRerun = focus !== undefined && fails(focus) > 0 && focus.phase !== 'running'
844
845    return (
846      <Box flexDirection="column" paddingX={1} height={rows} overflow="hidden">
847        <Box flexDirection="row" height={1}>
848          <Box flexGrow={1} flexShrink={1}>
849            <Text wrap="truncate-end">
850              <Text bold color="claude">CI watch</Text>
851              <Text dimColor>  {who}</Text>
852            </Text>
853          </Box>
854          <Box flexDirection="row" gap={1} flexShrink={0}>
855            <Text bold color={chip.color}>{chip.text}</Text>
856            {isPinned ? <Button key="live" label="⟲ follow live" variant="primary" hotkey="f" onPress={() => Promise.all([update($, pinned, () => null), update($, scroll, () => 0)])} /> : ''}
857          </Box>
858        </Box>
859
860        {focus ? cardsBlock() : idleBlock()}
861
862        {block(
863          'prs',
864          'subtle',
865          layout.listRows + 1,
866          <Box flexDirection="column">
867            {heading('Pull requests', list.length > layout.listRows ? `${layout.listRows} of ${list.length}` : String(list.length))}
868            {isIdle ? <Text dimColor>○ none yet</Text> : ''}
869            {list.slice(0, layout.listRows).map(prRow)}
870          </Box>,
871        )}
872
873        {block(
874          'runs',
875          'warning',
876          RUN_ROWS + 1,
877          <Box flexDirection="column">
878            {heading('Running actions', running.length > RUN_ROWS ? `${RUN_ROWS} of ${running.length}` : String(running.length))}
879            {running.length === 0 ? <Text dimColor>○ nothing running</Text> : ''}
880            {running.slice(0, RUN_ROWS).map(runRow)}
881          </Box>,
882        )}
883
884        <Box flexDirection="row" height={1} gap={1}>
885          <Button key="up" label="↑" hotkey="k" onPress={() => scrollCards($, -SCROLL_STEP)} />
886          <Button key="down" label="↓" hotkey="j" onPress={() => scrollCards($, SCROLL_STEP)} />
887          {focus && canRerun ? (
888            <Button key={`rerun:${focus.url}`} label="re-run failed" variant="primary" onPress={() => rerunFailed($, focus)} />
889          ) : (
890            ''
891          )}
892          {focus ? (
893            <Button
894              key={`refresh:${focus.url}`}
895              label="refresh"
896              hotkey="u"
897              onPress={() => patch($, focus.url, { phase: isActive(focus) ? focus.phase : 'running', finishedAt: null, settleKey: null, polledAt: null })}
898            />
899          ) : (
900            ''
901          )}
902          {focus ? (
903            <Button
904              key={`unwatch:${focus.url}`}
905              label="unwatch"
906              dimColor
907              onPress={() => update($, prs, all => all.filter(p => p.url !== focus.url))}
908            />
909          ) : (
910            ''
911          )}
912          {list.some(pr => !isActive(pr)) ? (
913            <Button key="clear" label="clear settled" dimColor onPress={() => update($, prs, all => all.filter(isActive))} />
914          ) : (
915            ''
916          )}
917        </Box>
918      </Box>
919    )
920  })
921
922  // A one-line band for when the pane waits undrawn (a narrow terminal it opened on unasked).
923  // A short chip in the footer's right-hand labels: the newest PR's CI state, `CI #101 ✓` or `CI 3/5`.
924  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
925    const list = await read($, prs)
926    // Reading `now` redraws the chip as a running PR polls.
927    await read($, now)
928    const pr = list.find(isActive) ?? list[0]
929    if (!pr || pr.phase === 'no-ci') return next(e)
930    const done = pr.checks.filter(c => c.bucket !== 'pending').length
931    const fails = pr.checks.filter(c => c.bucket === 'fail' || c.bucket === 'cancel').length
932    const state =
933      pr.phase === 'running' ? `${done}/${pr.checks.length}${fails > 0 ? ` ✗${fails}` : ''}` : pr.phase === 'passed' ? '✓' : pr.phase === 'failed' ? `✗${fails}` : pr.phase === 'waiting' ? '◌' : '⚠'
934    return next({ ...e, props: { ...e.props, modes: [...e.props.modes, `CI #${pr.number} ${state}`] } })
935  }).catch(($, e, next) => next(e))
936
937  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
938    const list = await read($, prs)
939    const pr = list.find(isActive)
940    if (!pr || e.props.hasSurvey || (await read($, paneShown))) return next(e)
941
942    const { Box, Text, Button } = $.ui.resolve(e)
943    const t = Math.max(await read($, now), await $.clock.now())
944    const fails = count(pr.checks, 'fail')
945    const spin = SPINNER[Math.floor(t / TICK_MS) % SPINNER.length] ?? '●'
946    const done = pr.checks.filter(c => c.bucket !== 'pending').length
947
948    return (
949      <Box flexDirection="row" gap={1}>
950        <Text bold color="inverseText" backgroundColor={BADGE[pr.phase].color}>
951          {` ${pr.phase === 'running' ? `${spin} ` : ''}${BADGE[pr.phase].label} `}
952        </Text>
953        <Text bold color="claude">CI #{pr.number}</Text>
954        {pr.checks.length > 0 && <Text dimColor>{done}/{pr.checks.length}</Text>}
955        <Text dimColor wrap="truncate-end">{pr.title}</Text>
956        {fails > 0 && <Text bold backgroundColor="#540d06">{` ✗${fails} `}</Text>}
957        <Button key="ci-open" label="details" plain hotkey="c" onPress={() => openPane($)} />
958      </Box>
959    )
960  })
961}
962
types/index.d.ts 49 lines
1export type CheckBucket = 'pass' | 'fail' | 'pending' | 'skipping' | 'cancel'
2
3export type Check = {
4  name: string
5  workflow: string
6  bucket: CheckBucket
7  link: string
8  startedAt: number | null
9  completedAt: number | null
10}
11
12export type Phase = 'waiting' | 'running' | 'passed' | 'failed' | 'no-ci' | 'error'
13
14export type WatchedPr = {
15  url: string
16  repo: string
17  number: number
18  title: string
19  isDraft: boolean
20  branch: string
21  phase: Phase
22  checks: Check[]
23  addedAt: number
24  polledAt: number | null
25  finishedAt: number | null
26  error: string | null
27  /** The check set of the last all-settled poll: CI settles when the next poll repeats it. */
28  settleKey: string | null
29  /** When failed runs were re-run: no settling until a check is seen pending, or a minute passes. */
30  rerunAt: number | null
31}
32
33/** A GitHub Actions run in progress, whether or not a watched PR started it. */
34export type WorkflowRun = {
35  url: string
36  name: string
37  title: string
38  branch: string
39  event: string
40  startedAt: number | null
41}
42
43declare module 'claude-code' {
44  interface PluginState {
45    /** `pinned`: the PR url the pane holds in view; null follows the newest running PR. `scroll`: the cards' top row. */
46    'ci-watch': { prs: WatchedPr[]; now: number; paneShown: boolean; pinned: string | null; scroll: number; runs: WorkflowRun[] }
47  }
48}
49