@accodev/pullywog 0.0.0-stage → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +100 -2
- package/package.json +30 -4
- package/pi/card.ts +134 -0
- package/pi/index.ts +444 -0
- package/pi/pointer.ts +126 -0
- package/pi/prs.ts +370 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marco Accorinti
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,101 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pullywog
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
pullywog is a Claude Code mod and a [Pi](https://pi.dev) extension that turns the GitHub pull request and issue references in the agent's replies into live chips. `#1234`, `owner/repo#1234`, GitHub URLs and the numbers in a table column headed `#`, `PR` or `Issue` get a dot in the state's color: green open, gray draft, purple merged, red closed. Hover a reference for its card: state, title, author, age, size, checks, reviews and open threads, each a link that Ctrl+click opens. A plain click tracks the PR in a band above the prompt, where the tracked PRs sit in three groups: needs you (your review is asked for, or your PR fails its checks or got changes requested), waiting, and done. Sessions in the same GitHub repo, worktrees included, share one tracked list. From the band one key acts on the selected PR: approve, request changes, re-run the failed checks, open it, copy its link as rich text for a chat such as Teams, or remove it. The details come from one `gh api graphql` call per repo, cached for 60 seconds.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
pullywog needs the GitHub CLI, `gh`, signed in to an account that can read the repos.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
claude plugin marketplace add accodev/pullywog
|
|
17
|
+
claude plugin install pullywog@pullywog
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Run `/reload-plugins` in an open session to load it. pullywog is tested on Claude Code 2.1.327, and needs that version or later. The hover card needs fullscreen rendering: run `/tui fullscreen` once, or start Claude Code with `CLAUDE_CODE_NO_FLICKER=1`. Without it the dots and links show, and cards do not open.
|
|
21
|
+
|
|
22
|
+
A click on a key under the chips runs it. For the keyboard, press the band focus key (Ctrl+X, then Tab, unless `abovePrompt:focus` is rebound in `~/.claude/keybindings.json`): ↑ ↓ (or Tab) move between chips, Esc goes back to the prompt, and one key acts on the focused chip.
|
|
23
|
+
|
|
24
|
+
| Key | Effect |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `a` | Approves the PR. Press it twice: the first press arms it. |
|
|
27
|
+
| `r` | Opens the PR to request changes, which need a comment. |
|
|
28
|
+
| `f` | Re-runs the failed checks. |
|
|
29
|
+
| `o` | Opens the PR or issue on GitHub. |
|
|
30
|
+
| `c` | Copies the link as rich text, or plain text where rich text cannot go. |
|
|
31
|
+
| `x` | Stops tracking it. |
|
|
32
|
+
|
|
33
|
+
A click on the Tracked PRs bar folds the band to the bar and the count.
|
|
34
|
+
|
|
35
|
+
Before 0.8.0 the plugin was named pr-cards. To move over, remove the old one and its marketplace, then install as above:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
claude plugin uninstall pr-cards@pr-cards
|
|
39
|
+
claude plugin marketplace remove pr-cards
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The tracked lists live in the plugin's own store file under `~/.claude/plugins/store/`. To keep them, copy `pr-cards_pr-cards-*.json` over the new `pullywog_pullywog-*.json` once pullywog has run.
|
|
43
|
+
|
|
44
|
+
## Pi
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
pi install npm:@accodev/pullywog
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Run `/reload` in an open session to load it. In Pi's fullscreen mode (`tuiMode`, the default) the extension works as the Claude Code mod: the dots, the card on hover, a plain click to track and Ctrl+click to open. Pi gives extensions no mouse hook in its transcript, so pullywog reads the mouse reports from the terminal input beside Pi, as `@narumitw/pi-inline` does. Pi's regular mode, tmux, Zellij and Screen send none: there the dots show, and the commands below stand in for the click.
|
|
51
|
+
|
|
52
|
+
| Command or key | Effect |
|
|
53
|
+
|---|---|
|
|
54
|
+
| `/track #1234` | Tracks a PR or issue: `#1234`, `owner/repo#1234` or a GitHub URL. With no argument it offers the references of this session's replies. |
|
|
55
|
+
| `/untrack #1234` | Stops tracking it. |
|
|
56
|
+
| `Alt+A` | Moves to the band: arrows pick a chip, the keys above act on it, Esc goes back. |
|
|
57
|
+
|
|
58
|
+
Bare numbers in a table column headed `#`, `PR` or `Issue` get no dot in Pi. Pi has no orange theme key, so the bar takes the theme's accent color. The Pi extension keeps its tracked lists in `~/.pi/agent/pullywog.json`, apart from Claude Code's. Pi's `settings.json` takes the options below under a `pullywog` key, for example `"pullywog": { "cardStyle": "github" }`.
|
|
59
|
+
|
|
60
|
+
## Settings
|
|
61
|
+
|
|
62
|
+
Claude Code keeps them in `settings.json`, under `pluginConfigs["pullywog@pullywog"].options`. Set them in `/plugin`, or from the shell:
|
|
63
|
+
|
|
64
|
+
```sh
|
|
65
|
+
echo '{"cardStyle": "github"}' | claude plugin configure pullywog@pullywog --values-stdin
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
| Option | Default | Effect |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| `cardStyle` | `card` | `card` draws the full card: state, title, author, size, checks, reviews and threads. `github` follows GitHub's own hover card: repo and date, state with title and number, branches, then the review and checks. |
|
|
71
|
+
| `trackedBand` | `true` | Shows the band of tracked PRs above the prompt. Off, a click on a reference does nothing. |
|
|
72
|
+
| `bandPerRow` | `3` | Tracked PRs in a row of a group, 1 to 6. |
|
|
73
|
+
| `shareTracked` | `true` | Gives the sessions of one GitHub repo, or of one folder outside git, one tracked list. Off, each session keeps its own. |
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
claude plugin validate .
|
|
79
|
+
claude plugin test .
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
```sh
|
|
83
|
+
npm ci
|
|
84
|
+
npm run typecheck:pi
|
|
85
|
+
npm run test:pi
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Those check the Pi extension in `pi/`. CI runs all five commands on every push to `main` and on pull requests. On `main` it also renders the README images with `scripts/screenshots.mjs` and pushes them to the `screenshots` branch.
|
|
89
|
+
|
|
90
|
+
```sh
|
|
91
|
+
node --experimental-strip-types scripts/screenshots.mjs out
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
That renders them locally, with Chrome or Edge. The scenes use pullywog's own drawing code on made-up repos and people.
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
uv run --no-project --with pywinpty --with pyte python -I scripts/e2e.py <folder of a GitHub repo>
|
|
98
|
+
uv run --no-project --with pywinpty --with pyte python -I scripts/pi-e2e.py <folder of a GitHub repo>
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Those drive a real fullscreen Claude Code or Pi session in a pseudo-terminal: they hover and click references, track a PR, and check the screen. The PR and issue numbers they use are at the top of each script. The design notes are in `docs/handover.md`, the repo rules in `AGENTS.md`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@accodev/pullywog",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "GitHub pull request tracking for Claude Code and Pi.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": "github:accodev/pullywog",
|
|
8
|
+
"keywords": ["pi-package"],
|
|
9
|
+
"files": ["pi/index.ts", "pi/prs.ts", "pi/card.ts", "pi/pointer.ts"],
|
|
10
|
+
"pi": {
|
|
11
|
+
"extensions": ["./pi/index.ts"]
|
|
12
|
+
},
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"typecheck:pi": "tsc -p pi",
|
|
18
|
+
"test:pi": "node --experimental-strip-types --no-warnings --test pi/tests.ts"
|
|
19
|
+
},
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"@earendil-works/pi-ai": "*",
|
|
22
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
23
|
+
"@earendil-works/pi-tui": "*"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
27
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
28
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
29
|
+
"@types/node": "^22.10.2",
|
|
30
|
+
"typescript": "5.6.3"
|
|
31
|
+
}
|
|
32
|
+
}
|
package/pi/card.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// The hover card, as lines of text with SGR colors and OSC 8 links. It needs no Pi host.
|
|
2
|
+
import { DOT, SGR, day, findRefs, toneOf, type Item, type Tone } from './prs.ts'
|
|
3
|
+
|
|
4
|
+
export const CARD_WIDTH = 66
|
|
5
|
+
const INNER = CARD_WIDTH - 4 // two border cells and one blank cell on each side
|
|
6
|
+
// A fixed dark gray (#303030), as the Claude Code card: palette black is the terminal background in
|
|
7
|
+
// most dark schemes, so a card filled with it shows no edge.
|
|
8
|
+
const BG = '\x1b[48;5;236m'
|
|
9
|
+
const PILL: Record<string, number> = { OPEN: 42, DRAFT: 100, MERGED: 45, CLOSED: 41, COMPLETED: 45, NOT_PLANNED: 100 }
|
|
10
|
+
const STATE_WORD: Record<string, string> = { OPEN: 'Open', DRAFT: 'Draft', MERGED: 'Merged', CLOSED: 'Closed', COMPLETED: 'Closed', NOT_PLANNED: 'Not planned' }
|
|
11
|
+
const REVIEW_WORD: Record<string, string> = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes requested', REVIEW_REQUIRED: 'review required' }
|
|
12
|
+
|
|
13
|
+
// A run of the card: its color, and the page a click on it opens.
|
|
14
|
+
type Seg = { text: string; tone?: Tone; bold?: boolean; pill?: number; href?: string }
|
|
15
|
+
const seg = (text: string, tone?: Tone, extra: Omit<Seg, 'text' | 'tone'> = {}): Seg => ({ text, tone, ...extra })
|
|
16
|
+
const linked = (text: string, href: string | undefined, tone?: Tone): Seg => (href ? { text, tone, href } : { text, tone })
|
|
17
|
+
|
|
18
|
+
const ESC = '\x1b'
|
|
19
|
+
const OSC8 = (href: string, text: string) => `${ESC}]8;;${href}${ESC}\\${text}${ESC}]8;;${ESC}\\`
|
|
20
|
+
|
|
21
|
+
function drawSeg(s: Seg): string {
|
|
22
|
+
let out = s.text
|
|
23
|
+
if (s.tone) out = `${ESC}[${SGR[s.tone]}m${out}${ESC}[39m`
|
|
24
|
+
if (s.bold) out = `${ESC}[1m${out}${ESC}[22m`
|
|
25
|
+
if (s.pill) out = `${ESC}[${s.pill}m${out}${BG}`
|
|
26
|
+
// Pi opens an OSC 8 link on a click.
|
|
27
|
+
return s.href ? OSC8(s.href, out) : out
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The runs of one card row, wrapped at word ends to the card's inner width, each row on the fill.
|
|
31
|
+
function fill(segs: Seg[]): string[] {
|
|
32
|
+
const rows: Seg[][] = [[]]
|
|
33
|
+
let used = 0
|
|
34
|
+
for (const s of segs) {
|
|
35
|
+
for (const word of s.text.split(/(?<=\s)/)) {
|
|
36
|
+
let rest = word
|
|
37
|
+
while (rest) {
|
|
38
|
+
const room = INNER - used
|
|
39
|
+
// A full row, or a word that does not fit after others: start a new row. Each pass takes at
|
|
40
|
+
// least one character, so the loop always ends.
|
|
41
|
+
if (room <= 0 || (used > 0 && rest.trimEnd().length > room)) {
|
|
42
|
+
rows.push([])
|
|
43
|
+
used = 0
|
|
44
|
+
rest = rest.trimStart()
|
|
45
|
+
continue
|
|
46
|
+
}
|
|
47
|
+
const take = rest.slice(0, room)
|
|
48
|
+
rows[rows.length - 1]!.push({ ...s, text: take })
|
|
49
|
+
used += take.length
|
|
50
|
+
rest = rest.slice(take.length)
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return rows.map((row) => {
|
|
55
|
+
const width = row.reduce((n, s) => n + s.text.length, 0)
|
|
56
|
+
return BG + ' ' + row.map(drawSeg).join('') + ' '.repeat(Math.max(0, INNER - width) + 2) + `${ESC}[0m`
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const edge = () => BG + ' '.repeat(CARD_WIDTH) + `${ESC}[0m`
|
|
61
|
+
const popup = (rows: Seg[][]) => [edge(), ...rows.flatMap(fill), edge()]
|
|
62
|
+
const short = (url: string) => url.replace(/^https:\/\//, '')
|
|
63
|
+
|
|
64
|
+
function parts(item: Item, viewer: string) {
|
|
65
|
+
const person = (login: string, tone?: Tone): Seg => (login === viewer ? { text: 'you', tone } : { text: '@' + login, tone: tone ?? 'link', href: 'https://github.com/' + login })
|
|
66
|
+
const people = (logins: string[], tone?: Tone): Seg[] => logins.flatMap((l, i) => [...(i ? [seg(', ', tone)] : []), person(l, tone)])
|
|
67
|
+
// The title with its references as links; GitHub sends an issue URL of a PR to the PR.
|
|
68
|
+
const title: Seg[] = []
|
|
69
|
+
let at = 0
|
|
70
|
+
for (const f of findRefs(item.title)) {
|
|
71
|
+
if (f.start > at) title.push(seg(item.title.slice(at, f.start), undefined, { bold: true }))
|
|
72
|
+
title.push(seg(item.title.slice(f.start, f.end), 'link', { bold: true, href: `https://github.com/${f.repo ?? item.repo}/issues/${f.number}` }))
|
|
73
|
+
at = f.end
|
|
74
|
+
}
|
|
75
|
+
if (at < item.title.length) title.push(seg(item.title.slice(at), undefined, { bold: true }))
|
|
76
|
+
return { person, people, title }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The card a hover on a reference opens, as the Claude Code mod's: `card` (state, title, who and
|
|
80
|
+
// when, size, checks, reviews, threads) or `github`, laid out as GitHub's own hover card.
|
|
81
|
+
export function cardLines(item: Item, style: 'card' | 'github', viewer: string): string[] {
|
|
82
|
+
const { person, people, title } = parts(item, viewer)
|
|
83
|
+
if (style === 'github') {
|
|
84
|
+
const repoUrl = 'https://github.com/' + item.repo
|
|
85
|
+
const rows: Seg[][] = [
|
|
86
|
+
[linked(item.repo, repoUrl, 'link'), seg(' on ' + day(item.created), 'dim')],
|
|
87
|
+
[],
|
|
88
|
+
[seg(DOT + ' ', toneOf(item)), ...title, seg(' '), linked('#' + item.number, item.url, 'dim')],
|
|
89
|
+
]
|
|
90
|
+
if (item.head && item.base) rows.push([linked(item.head, `${repoUrl}/tree/${item.head}`, 'code'), seg(' → ', 'dim'), linked(item.base, `${repoUrl}/tree/${item.base}`, 'code')])
|
|
91
|
+
const foot: Seg[] = [seg('opened by ', 'dim'), person(item.author), seg(' · ', 'dim')]
|
|
92
|
+
if (item.kind === 'issue') foot.push(linked(`${item.comments} comments`, item.url, 'dim'))
|
|
93
|
+
else if (item.changesBy?.length === 1 && item.changesBy[0] === viewer) foot.push(seg('● you requested changes', 'warn'))
|
|
94
|
+
else if (item.changesBy?.length) foot.push(seg('● changes requested by ', 'warn'), ...people(item.changesBy, 'warn'))
|
|
95
|
+
else if (item.approvedBy?.length === 1 && item.approvedBy[0] === viewer) foot.push(seg('✓ you approved', 'open'))
|
|
96
|
+
else if (item.approvedBy?.length) foot.push(seg('✓ approved by ', 'open'), ...people(item.approvedBy, 'open'))
|
|
97
|
+
else foot.push(seg(REVIEW_WORD[item.review ?? ''] ?? 'no reviews yet', 'dim'))
|
|
98
|
+
const c = item.checks
|
|
99
|
+
if (!c?.total) return popup([...rows, [], foot])
|
|
100
|
+
const checks = linked(`${c.failed ? 'x' : '✓'} ${c.ok} of ${c.total} checks`, item.url + '/checks', c.failed ? 'closed' : 'open')
|
|
101
|
+
// A long login would wrap the checks in the middle: then they take a row of their own.
|
|
102
|
+
const fits = foot.reduce((n, s) => n + s.text.length, 0) + 3 + checks.text.length <= INNER
|
|
103
|
+
return popup([...rows, [], ...(fits ? [[...foot, seg(' · ', 'dim'), checks]] : [foot, [checks]])])
|
|
104
|
+
}
|
|
105
|
+
const facts: Seg[][] = []
|
|
106
|
+
if (item.kind === 'issue') facts.push([person(item.author), seg(` · ${item.when} · `, 'dim'), linked(`${item.comments} comments`, item.url, 'dim')])
|
|
107
|
+
else {
|
|
108
|
+
const c = item.checks!
|
|
109
|
+
facts.push([person(item.author), seg(` · ${item.when} · `, 'dim'), seg('+' + item.additions, 'open'), seg(' '), seg('−' + item.deletions, 'closed'), seg(' · ', 'dim'), linked(`${item.changedFiles} files`, item.url + '/files', 'dim')])
|
|
110
|
+
if (c.total) {
|
|
111
|
+
const failing = item.failing ?? []
|
|
112
|
+
facts.push([
|
|
113
|
+
seg('✓', 'open'), seg(' '), linked(`${c.ok} of ${c.total} checks`, item.url + '/checks'),
|
|
114
|
+
...(failing.length ? [seg(' · '), seg('x ', 'closed'), linked(failing[0]!.name, failing[0]!.url, 'closed'), ...(failing.length > 1 ? [seg(` +${failing.length - 1}`, 'closed')] : [])] : []),
|
|
115
|
+
...(c.pending ? [seg(' · '), seg(`● ${c.pending} running`, 'warn')] : []),
|
|
116
|
+
])
|
|
117
|
+
}
|
|
118
|
+
const reviews: Seg[] = []
|
|
119
|
+
if (item.approvedBy?.length) reviews.push(seg('✓', 'open'), seg(' approved by '), ...people(item.approvedBy))
|
|
120
|
+
if (item.changesBy?.length) reviews.push(...(reviews.length ? [seg(' · ')] : []), seg('● changes requested by ', 'warn'), ...people(item.changesBy, 'warn'))
|
|
121
|
+
facts.push(reviews.length ? reviews : [seg(REVIEW_WORD[item.review ?? ''] ?? 'no reviews yet', 'dim')])
|
|
122
|
+
const threads = item.threads?.length ?? 0
|
|
123
|
+
if (threads) facts.push([linked(`${threads} open review thread${threads === 1 ? '' : 's'}`, item.url)])
|
|
124
|
+
}
|
|
125
|
+
return popup([
|
|
126
|
+
[seg(` ${STATE_WORD[item.state] ?? item.state} `, 'black', { pill: PILL[item.state] ?? 100, bold: true }), seg(' '), linked(item.repo, 'https://github.com/' + item.repo, 'dim'), seg(' '), linked('#' + item.number, item.url, 'dim')],
|
|
127
|
+
title,
|
|
128
|
+
...facts,
|
|
129
|
+
[seg(short(item.url), 'link', { href: item.url })],
|
|
130
|
+
])
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// The card of a lookup that failed: its error, in red.
|
|
134
|
+
export const errorCard = (error: string) => popup([[seg(error, 'closed')]])
|
package/pi/index.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { readFileSync, writeFileSync, renameSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { copyToClipboard, getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent'
|
|
5
|
+
import { matchesKey, type Component, type TUI } from '@earendil-works/pi-tui'
|
|
6
|
+
import { CARD_WIDTH, cardLines, errorCard } from './card.ts'
|
|
7
|
+
import { watchPointer } from './pointer.ts'
|
|
8
|
+
import {
|
|
9
|
+
BATCH, TTL_MS, bandLines, decorate, findRefs, keyFor, label, linkFormats, listName, pruned, query, refAt, runIds, sameList, savedItems, step,
|
|
10
|
+
toItem, withTracked, withoutTracked, type Band, type Entry, type Hit, type Raw, type Ref, type SavedList, type Style, type Tracked,
|
|
11
|
+
} from './prs.ts'
|
|
12
|
+
|
|
13
|
+
// Another session may change a shared list: the band reads the file again this often.
|
|
14
|
+
const SHARED_READ_MS = 5_000
|
|
15
|
+
// The band refreshes its PRs' checks and reviews this often.
|
|
16
|
+
const REFRESH_MS = 60_000
|
|
17
|
+
const FOCUS_KEY = 'alt+a'
|
|
18
|
+
|
|
19
|
+
type Settings = { cardStyle: 'card' | 'github'; trackedBand: boolean; perRow: number; share: boolean }
|
|
20
|
+
function readSettings(raw: unknown): Settings {
|
|
21
|
+
const o = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>
|
|
22
|
+
const off = (v: unknown) => v === false || String(v).toLowerCase() === 'false'
|
|
23
|
+
return {
|
|
24
|
+
cardStyle: String(o.cardStyle ?? 'card').trim().toLowerCase() === 'github' ? 'github' : 'card',
|
|
25
|
+
trackedBand: !off(o.trackedBand), perRow: Math.max(1, Math.min(6, Math.round(Number(o.bandPerRow) || 3))), share: !off(o.shareTracked),
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The system's own handler opens a page, as Pi does for a link.
|
|
30
|
+
function openUrl(url: string) {
|
|
31
|
+
const [cmd, args] = process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]]
|
|
32
|
+
spawn(cmd as string, args as string[], { detached: true, stdio: 'ignore', windowsHide: true }).on('error', () => undefined).unref()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Every Pi session's tracked lists, in one file as the Claude Code mod keeps them in its store.
|
|
36
|
+
type Store = { lists?: Record<string, SavedList> }
|
|
37
|
+
const storePath = () => join(getAgentDir(), 'pullywog.json')
|
|
38
|
+
function readStore(): Store {
|
|
39
|
+
try {
|
|
40
|
+
const raw = JSON.parse(readFileSync(storePath(), 'utf8')) as Store
|
|
41
|
+
return raw && typeof raw === 'object' ? raw : {}
|
|
42
|
+
} catch {
|
|
43
|
+
return {}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
// A rename puts the whole file down at once: a session reading meanwhile sees the old one or the new one.
|
|
47
|
+
function writeStore(store: Store) {
|
|
48
|
+
const tmp = `${storePath()}.${process.pid}.tmp`
|
|
49
|
+
writeFileSync(tmp, JSON.stringify(store))
|
|
50
|
+
renameSync(tmp, storePath())
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type Run = { code: number; stdout: string; stderr: string }
|
|
54
|
+
function run(argv: string[], options: { cwd?: string; stdin?: string; timeoutMs?: number } = {}): Promise<Run> {
|
|
55
|
+
return new Promise((resolve) => {
|
|
56
|
+
const child = spawn(argv[0]!, argv.slice(1), { cwd: options.cwd, windowsHide: true })
|
|
57
|
+
let stdout = ''
|
|
58
|
+
let stderr = ''
|
|
59
|
+
const timer = setTimeout(() => child.kill(), options.timeoutMs ?? 20_000)
|
|
60
|
+
child.stdout.on('data', (d) => (stdout += d))
|
|
61
|
+
child.stderr.on('data', (d) => (stderr += d))
|
|
62
|
+
child.on('error', (err) => { clearTimeout(timer); resolve({ code: -1, stdout, stderr: String(err) }) })
|
|
63
|
+
child.on('close', (code) => { clearTimeout(timer); resolve({ code: code ?? -1, stdout, stderr }) })
|
|
64
|
+
child.stdin.end(options.stdin ?? '')
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Windows PowerShell 5.1 puts both formats on the clipboard in one data object: HTML for chats such
|
|
69
|
+
// as Teams, plain text for everything else. It reads them as JSON on stdin, so no quoting reaches a shell.
|
|
70
|
+
const CLIPBOARD_PS =
|
|
71
|
+
"[Console]::InputEncoding=[Text.Encoding]::UTF8; $in=[Console]::In.ReadToEnd() | ConvertFrom-Json; " +
|
|
72
|
+
'Add-Type -AssemblyName System.Windows.Forms; $d=New-Object System.Windows.Forms.DataObject; ' +
|
|
73
|
+
"$d.SetData('HTML Format', $in.html); $d.SetData('UnicodeText', $in.text); " +
|
|
74
|
+
'[System.Windows.Forms.Clipboard]::SetDataObject($d, $true)'
|
|
75
|
+
|
|
76
|
+
export default function pullywog(pi: ExtensionAPI) {
|
|
77
|
+
let settings = readSettings(undefined)
|
|
78
|
+
let ctx: ExtensionContext | undefined
|
|
79
|
+
let tui: TUI | undefined
|
|
80
|
+
let cwd = process.cwd()
|
|
81
|
+
let sessionId = ''
|
|
82
|
+
// The session folder's GitHub repo: undefined until asked, null when it has none.
|
|
83
|
+
let cwdRepo: string | null | undefined
|
|
84
|
+
let viewer = ''
|
|
85
|
+
const cache = new Map<string, Entry>()
|
|
86
|
+
const queue = new Map<string, Set<number>>()
|
|
87
|
+
let flushQueued = false
|
|
88
|
+
// References in this session's replies, newest last, for /track's completions.
|
|
89
|
+
const seen = new Map<string, Ref>()
|
|
90
|
+
// Keys the transcript asked for before GitHub answered: the replies holding them draw again once it has.
|
|
91
|
+
const asked = new Set<string>()
|
|
92
|
+
|
|
93
|
+
let tracked: Tracked[] = []
|
|
94
|
+
let listKey: string | null = null
|
|
95
|
+
let selected: string | null = null
|
|
96
|
+
// Approving is seen by others on GitHub: the first press arms it, the second sends it.
|
|
97
|
+
let armed: string | null = null
|
|
98
|
+
let folded = false
|
|
99
|
+
// While the band has the keyboard it draws in the editor's place, and the widget draws nothing.
|
|
100
|
+
let focused = false
|
|
101
|
+
let timers: NodeJS.Timeout[] = []
|
|
102
|
+
// The stdin reader for hover and click on references, one per TUI.
|
|
103
|
+
let pointerTui: TUI | undefined
|
|
104
|
+
let stopPointer: (() => void) | undefined
|
|
105
|
+
|
|
106
|
+
const redraw = () => tui?.requestRender()
|
|
107
|
+
const repoOf = (r: Ref) => r.repo ?? cwdRepo
|
|
108
|
+
const lookup = (r: Ref) => {
|
|
109
|
+
const repo = repoOf(r)
|
|
110
|
+
return repo ? cache.get(keyFor(repo, r.number)) : undefined
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function askRepo() {
|
|
114
|
+
if (cwdRepo !== undefined) return Promise.resolve(cwdRepo)
|
|
115
|
+
return run(['gh', 'repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner'], { cwd, timeoutMs: 15_000 }).then((out) => {
|
|
116
|
+
cwdRepo = out.code === 0 && out.stdout.trim() ? out.stdout.trim() : null
|
|
117
|
+
redraw()
|
|
118
|
+
return cwdRepo
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function want(r: Ref, force = false) {
|
|
123
|
+
const repo = repoOf(r)
|
|
124
|
+
if (repo === undefined) return void askRepo().then(() => want(r, force))
|
|
125
|
+
if (repo === null) return
|
|
126
|
+
const key = keyFor(repo, r.number)
|
|
127
|
+
const hit = cache.get(key)
|
|
128
|
+
if (!force && hit && (hit.loading || Date.now() - hit.at < TTL_MS)) return
|
|
129
|
+
cache.set(key, { ...hit, at: Date.now(), loading: true })
|
|
130
|
+
queue.set(repo, (queue.get(repo) ?? new Set()).add(r.number))
|
|
131
|
+
if (flushQueued) return
|
|
132
|
+
flushQueued = true
|
|
133
|
+
// Every reference asked for in one pass goes out as one query per repo.
|
|
134
|
+
queueMicrotask(() => void flush())
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function flush() {
|
|
138
|
+
flushQueued = false
|
|
139
|
+
const jobs = [...queue].flatMap(([repo, numbers]) => {
|
|
140
|
+
const all = [...numbers]
|
|
141
|
+
const chunks: { repo: string; numbers: number[] }[] = []
|
|
142
|
+
for (let i = 0; i < all.length; i += BATCH) chunks.push({ repo, numbers: all.slice(i, i + BATCH) })
|
|
143
|
+
return chunks
|
|
144
|
+
})
|
|
145
|
+
queue.clear()
|
|
146
|
+
await Promise.all(jobs.map((j) => fetchChunk(j.repo, j.numbers)))
|
|
147
|
+
const answered = jobs.some((j) => j.numbers.some((n) => asked.delete(keyFor(j.repo, n))))
|
|
148
|
+
// Pi keeps each message's drawn lines: invalidating them runs the transformer again.
|
|
149
|
+
if (answered) tui?.invalidate()
|
|
150
|
+
tui?.requestRender(answered)
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function fetchChunk(repo: string, numbers: number[]) {
|
|
154
|
+
const fail = (error: string) => numbers.forEach((n) => cache.set(keyFor(repo, n), { at: Date.now(), loading: false, error }))
|
|
155
|
+
// The query goes in on stdin: a batch of 40 passes Windows' 32,767-character command line.
|
|
156
|
+
const out = await run(['gh', 'api', 'graphql', '--input', '-'], { stdin: JSON.stringify({ query: query(repo, numbers) }) })
|
|
157
|
+
try {
|
|
158
|
+
const body = JSON.parse(out.stdout || '{}') as { data?: { viewer?: { login: string }; repository?: Record<string, Raw | null> | null }; errors?: { message: string }[] }
|
|
159
|
+
viewer = body.data?.viewer?.login ?? viewer
|
|
160
|
+
const found = body.data?.repository
|
|
161
|
+
if (!found) return fail(body.errors?.[0]?.message ?? (out.stderr.trim().split('\n')[0] || `gh exited ${out.code}`))
|
|
162
|
+
for (const n of numbers) {
|
|
163
|
+
const raw = found[`n${n}`]
|
|
164
|
+
cache.set(keyFor(repo, n), raw ? { at: Date.now(), loading: false, item: toItem(repo, raw) } : { at: Date.now(), loading: false, missing: true })
|
|
165
|
+
}
|
|
166
|
+
} catch (err) {
|
|
167
|
+
fail(String(err))
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ---------- The tracked list ----------
|
|
172
|
+
|
|
173
|
+
async function loadList() {
|
|
174
|
+
listKey = listName(settings.share, sessionId, settings.share ? await askRepo() : null, cwd)
|
|
175
|
+
const store = readStore()
|
|
176
|
+
tracked = savedItems(store.lists?.[listKey])
|
|
177
|
+
writeStore({ ...store, lists: pruned(store.lists ?? {}, listKey) })
|
|
178
|
+
for (const t of tracked) want(t)
|
|
179
|
+
redraw()
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Applies one change to the list as the file holds it now, not to this session's copy: a copy
|
|
183
|
+
// another session changed since would otherwise be written back whole, undoing that change.
|
|
184
|
+
function change(edit: (items: Tracked[]) => Tracked[]) {
|
|
185
|
+
tracked = edit(tracked)
|
|
186
|
+
if (listKey) {
|
|
187
|
+
const store = readStore()
|
|
188
|
+
tracked = edit(savedItems(store.lists?.[listKey]))
|
|
189
|
+
writeStore({ ...store, lists: { ...store.lists, [listKey]: { at: Date.now(), items: tracked } } })
|
|
190
|
+
}
|
|
191
|
+
if (selected && !tracked.some((t) => keyFor(t.repo, t.number) === selected)) selected = null
|
|
192
|
+
redraw()
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function reread() {
|
|
196
|
+
if (!settings.share || !listKey) return
|
|
197
|
+
const items = savedItems(readStore().lists?.[listKey])
|
|
198
|
+
if (sameList(items, tracked)) return
|
|
199
|
+
tracked = items
|
|
200
|
+
if (selected && !tracked.some((t) => keyFor(t.repo, t.number) === selected)) selected = null
|
|
201
|
+
for (const t of tracked) want(t)
|
|
202
|
+
redraw()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function track(r: Ref) {
|
|
206
|
+
const repo = r.repo ?? (await askRepo())
|
|
207
|
+
if (!repo) return ctx?.ui.notify(`${label(r)} names no repo, and this folder has none`, 'warning')
|
|
208
|
+
const t = { repo, number: r.number }
|
|
209
|
+
selected = keyFor(repo, r.number)
|
|
210
|
+
change((items) => withTracked(items, t))
|
|
211
|
+
want(t)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// ---------- Actions on the selected PR ----------
|
|
215
|
+
|
|
216
|
+
async function act(argv: string[], done: string) {
|
|
217
|
+
const out = await run(argv, { cwd, timeoutMs: 60_000 })
|
|
218
|
+
ctx?.ui.notify(out.code === 0 ? done : `${argv.slice(0, 3).join(' ')} failed: ${out.stderr.trim().split('\n')[0] || `exit ${out.code}`}`, out.code === 0 ? 'info' : 'error')
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function copyLink(key: string) {
|
|
222
|
+
const item = cache.get(key)?.item
|
|
223
|
+
if (!item) return
|
|
224
|
+
const { name, html, text } = linkFormats(item)
|
|
225
|
+
if (process.platform === 'win32') {
|
|
226
|
+
const out = await run(['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', CLIPBOARD_PS], { stdin: JSON.stringify({ html, text }), timeoutMs: 15_000 })
|
|
227
|
+
if (out.code === 0) return ctx?.ui.notify(`copied ${name} as a link`, 'info')
|
|
228
|
+
}
|
|
229
|
+
await copyToClipboard(text)
|
|
230
|
+
ctx?.ui.notify(`copied ${name} as plain text`, 'info')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// One key on the selected chip. Returns false for a key the band does not use.
|
|
234
|
+
function press(data: string): boolean {
|
|
235
|
+
const band = bandState()
|
|
236
|
+
const move = (by: number) => { selected = step(band, by); armed = null; redraw() }
|
|
237
|
+
if (matchesKey(data, 'up') || matchesKey(data, 'left') || matchesKey(data, 'shift+tab')) return move(-1), true
|
|
238
|
+
if (matchesKey(data, 'down') || matchesKey(data, 'right') || matchesKey(data, 'tab')) return move(1), true
|
|
239
|
+
const key = selected
|
|
240
|
+
const item = key ? cache.get(key)?.item : undefined
|
|
241
|
+
if (!key) return false
|
|
242
|
+
if (data === 'x') return change((items) => withoutTracked(items, key)), true
|
|
243
|
+
if (!item) return false
|
|
244
|
+
const web = ['gh', item.kind === 'pr' ? 'pr' : 'issue', 'view', String(item.number), '--repo', item.repo, '--web']
|
|
245
|
+
const refresh = () => want(item, true)
|
|
246
|
+
const isOpen = item.kind === 'pr' && (item.state === 'OPEN' || item.state === 'DRAFT')
|
|
247
|
+
if (data === 'a' && isOpen && item.author !== viewer) {
|
|
248
|
+
if (armed !== key) return (armed = key), redraw(), true
|
|
249
|
+
armed = null
|
|
250
|
+
void act(['gh', 'pr', 'review', String(item.number), '--repo', item.repo, '--approve'], `approved #${item.number}`).then(refresh)
|
|
251
|
+
return true
|
|
252
|
+
}
|
|
253
|
+
// A review that asks for changes needs a comment: it opens the PR in the browser.
|
|
254
|
+
if (data === 'r' && isOpen && item.author !== viewer) return void act(web, `opened #${item.number} to request changes`), true
|
|
255
|
+
if (data === 'f' && runIds(item).length) {
|
|
256
|
+
void (async () => {
|
|
257
|
+
for (const id of runIds(item)) await act(['gh', 'run', 'rerun', id, '--failed', '--repo', item.repo], `re-running the failed jobs of #${item.number}`)
|
|
258
|
+
refresh()
|
|
259
|
+
})()
|
|
260
|
+
return true
|
|
261
|
+
}
|
|
262
|
+
if (data === 'o') return void act(web, `opened #${item.number}`), true
|
|
263
|
+
if (data === 'c') return void copyLink(key), true
|
|
264
|
+
return false
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---------- Drawing ----------
|
|
268
|
+
|
|
269
|
+
const bandState = (): Band => ({ tracked, lookup, viewer, selected, armed, folded, perRow: settings.perRow, focused })
|
|
270
|
+
|
|
271
|
+
function bandComponent(style: Style, keyboard: boolean): Component {
|
|
272
|
+
let hits: Hit[] = []
|
|
273
|
+
return {
|
|
274
|
+
render(width) {
|
|
275
|
+
if (focused !== keyboard) return []
|
|
276
|
+
const drawn = bandLines(bandState(), width, style)
|
|
277
|
+
hits = drawn.hits
|
|
278
|
+
return drawn.lines
|
|
279
|
+
},
|
|
280
|
+
handleMouse(e) {
|
|
281
|
+
if (e.type !== 'press' || e.button !== 'left') return undefined
|
|
282
|
+
const hit = hits.find((h) => h.row === e.y && e.x >= h.from && e.x < h.to)
|
|
283
|
+
if (!hit) return undefined
|
|
284
|
+
if (hit.target === 'bar') folded = !folded
|
|
285
|
+
else { selected = hit.target; armed = null }
|
|
286
|
+
redraw()
|
|
287
|
+
return { handled: true }
|
|
288
|
+
},
|
|
289
|
+
invalidate() {},
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function showWidget(c: ExtensionContext) {
|
|
294
|
+
if (c.mode !== 'tui') return
|
|
295
|
+
if (!settings.trackedBand) return c.ui.setWidget('pullywog', undefined)
|
|
296
|
+
c.ui.setWidget('pullywog', (t, theme) => {
|
|
297
|
+
tui = t
|
|
298
|
+
if (pointerTui !== t) {
|
|
299
|
+
stopPointer?.()
|
|
300
|
+
pointerTui = t
|
|
301
|
+
stopPointer = watchPointer(t, {
|
|
302
|
+
width: CARD_WIDTH,
|
|
303
|
+
cardFor: (r) => {
|
|
304
|
+
const entry = lookup(r)
|
|
305
|
+
return entry?.item ? cardLines(entry.item, settings.cardStyle, viewer) : entry?.error ? errorCard(entry.error) : undefined
|
|
306
|
+
},
|
|
307
|
+
want: (r) => want(r),
|
|
308
|
+
track: (r) => void track(r),
|
|
309
|
+
open: (r) => {
|
|
310
|
+
const repo = r.repo ?? cwdRepo
|
|
311
|
+
if (repo) openUrl(lookup(r)?.item?.url ?? `https://github.com/${repo}/issues/${r.number}`)
|
|
312
|
+
},
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
return bandComponent({ bar: (s) => theme.inverse(theme.fg('accent', s)), mark: (s) => theme.fg('accent', s), bold: (s) => theme.bold(s) }, false)
|
|
316
|
+
}, { placement: 'aboveEditor' })
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// The keyboard path: the band takes the editor's place until Esc.
|
|
320
|
+
async function focusBand(c: ExtensionContext) {
|
|
321
|
+
if (c.mode !== 'tui' || !tracked.length) return
|
|
322
|
+
focused = true
|
|
323
|
+
selected ??= step(bandState(), 1)
|
|
324
|
+
redraw()
|
|
325
|
+
await c.ui.custom<void>((t, theme, _keys, done) => {
|
|
326
|
+
const inner = bandComponent({ bar: (s) => theme.inverse(theme.fg('accent', s)), mark: (s) => theme.fg('accent', s), bold: (s) => theme.bold(s) }, true)
|
|
327
|
+
return {
|
|
328
|
+
...inner,
|
|
329
|
+
render: (width) => inner.render(width),
|
|
330
|
+
handleInput(data) {
|
|
331
|
+
if (matchesKey(data, 'escape') || !tracked.length) return done()
|
|
332
|
+
if (press(data)) t.requestRender()
|
|
333
|
+
},
|
|
334
|
+
}
|
|
335
|
+
})
|
|
336
|
+
focused = false
|
|
337
|
+
armed = null
|
|
338
|
+
redraw()
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ---------- References in the transcript ----------
|
|
342
|
+
|
|
343
|
+
// Pi draws the transcript itself: each known reference gets its state's dot and becomes a link.
|
|
344
|
+
// A reference not loaded yet is asked for, and draws once Pi draws the message again.
|
|
345
|
+
pi.registerMarkdownTransformer((md) => {
|
|
346
|
+
for (const f of findRefs(md)) {
|
|
347
|
+
const repo = repoOf(f)
|
|
348
|
+
if (repo === undefined) {
|
|
349
|
+
void askRepo().then((r) => r && (asked.add(keyFor(r, f.number)), want(f)))
|
|
350
|
+
continue
|
|
351
|
+
}
|
|
352
|
+
if (repo && !cache.get(keyFor(repo, f.number))?.item) asked.add(keyFor(repo, f.number))
|
|
353
|
+
want(f)
|
|
354
|
+
}
|
|
355
|
+
return decorate(md, lookup)
|
|
356
|
+
}, { messageTypes: ['assistant'] })
|
|
357
|
+
|
|
358
|
+
function remember(text: string) {
|
|
359
|
+
for (const f of findRefs(text)) {
|
|
360
|
+
const k = label(f)
|
|
361
|
+
seen.delete(k)
|
|
362
|
+
seen.set(k, { repo: f.repo, number: f.number })
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
const textOf = (message: unknown) => {
|
|
366
|
+
const m = message as { role?: string; content?: unknown } | undefined
|
|
367
|
+
if (m?.role !== 'assistant') return ''
|
|
368
|
+
if (typeof m.content === 'string') return m.content
|
|
369
|
+
return Array.isArray(m.content) ? m.content.flatMap((c: { type?: string; text?: string }) => (c?.type === 'text' && c.text ? [c.text] : [])).join('\n') : ''
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
pi.on('message_end', (e) => remember(textOf(e.message)))
|
|
373
|
+
|
|
374
|
+
const parseRef = (arg: string): Ref | null => {
|
|
375
|
+
const f = findRefs(arg.trim())[0]
|
|
376
|
+
if (f) return { repo: f.repo, number: f.number }
|
|
377
|
+
const n = /^\d+$/.exec(arg.trim())
|
|
378
|
+
return n ? { repo: null, number: Number(n[0]) } : null
|
|
379
|
+
}
|
|
380
|
+
const completions = (prefix: string, refs: Ref[]) =>
|
|
381
|
+
refs.map((r) => {
|
|
382
|
+
const item = lookup(r)?.item
|
|
383
|
+
return { value: label(r), label: label(r), description: item?.title }
|
|
384
|
+
}).filter((c) => c.value.toLowerCase().includes(prefix.trim().replace(/^#/, '').toLowerCase()))
|
|
385
|
+
|
|
386
|
+
pi.registerCommand('track', {
|
|
387
|
+
description: 'Track a PR or issue in the band above the editor: #1234, owner/repo#1234 or a GitHub URL',
|
|
388
|
+
getArgumentCompletions: (prefix) => completions(prefix, [...seen.values()].reverse()),
|
|
389
|
+
handler: async (args, c) => {
|
|
390
|
+
ctx = c
|
|
391
|
+
let ref = parseRef(args)
|
|
392
|
+
if (!ref && !args.trim()) {
|
|
393
|
+
const options = [...seen.keys()].reverse()
|
|
394
|
+
if (!options.length) return c.ui.notify('no PR references in this session yet: /track #1234', 'info')
|
|
395
|
+
const pick = await c.ui.select('Track which?', options)
|
|
396
|
+
ref = pick ? seen.get(pick) ?? null : null
|
|
397
|
+
}
|
|
398
|
+
if (!ref) return args.trim() ? c.ui.notify(`${args.trim()} is no PR reference`, 'warning') : undefined
|
|
399
|
+
await track(ref)
|
|
400
|
+
},
|
|
401
|
+
})
|
|
402
|
+
|
|
403
|
+
pi.registerCommand('untrack', {
|
|
404
|
+
description: 'Stop tracking a PR or issue',
|
|
405
|
+
getArgumentCompletions: (prefix) => completions(prefix, tracked.map((t) => ({ repo: t.repo, number: t.number }))),
|
|
406
|
+
handler: async (args, c) => {
|
|
407
|
+
ctx = c
|
|
408
|
+
const ref = parseRef(args)
|
|
409
|
+
const repo = ref ? ref.repo ?? (await askRepo()) : null
|
|
410
|
+
if (!ref || !repo) return c.ui.notify('/untrack owner/repo#1234', 'info')
|
|
411
|
+
change((items) => withoutTracked(items, keyFor(repo, ref.number)))
|
|
412
|
+
},
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
pi.registerShortcut(FOCUS_KEY, {
|
|
416
|
+
description: 'Move to the tracked PRs: arrows pick one, a key acts on it',
|
|
417
|
+
handler: (c) => focusBand(c),
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
pi.on('session_start', async (_e, c) => {
|
|
421
|
+
ctx = c
|
|
422
|
+
cwd = c.cwd
|
|
423
|
+
sessionId = c.sessionManager.getSessionId()
|
|
424
|
+
settings = readSettings((pi.getSettings() as Record<string, unknown>).pullywog)
|
|
425
|
+
for (const entry of c.sessionManager.getEntries() as { type?: string; message?: unknown }[]) {
|
|
426
|
+
if (entry.type === 'message') remember(textOf(entry.message))
|
|
427
|
+
}
|
|
428
|
+
showWidget(c)
|
|
429
|
+
await loadList()
|
|
430
|
+
timers.forEach(clearInterval)
|
|
431
|
+
timers = [
|
|
432
|
+
setInterval(reread, SHARED_READ_MS),
|
|
433
|
+
setInterval(() => tracked.forEach((t) => want(t)), REFRESH_MS),
|
|
434
|
+
]
|
|
435
|
+
})
|
|
436
|
+
|
|
437
|
+
pi.on('session_shutdown', async () => {
|
|
438
|
+
stopPointer?.()
|
|
439
|
+
stopPointer = undefined
|
|
440
|
+
pointerTui = undefined
|
|
441
|
+
timers.forEach(clearInterval)
|
|
442
|
+
timers = []
|
|
443
|
+
})
|
|
444
|
+
}
|
package/pi/pointer.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// The pointer on references in replies. Pi's fullscreen mode takes every mouse report before an
|
|
2
|
+
// extension's input listener, and its transcript has no mouse hook. The reports still arrive on
|
|
3
|
+
// stdin: read them there, beside Pi's own reader, as @narumitw/pi-inline does for its link previews.
|
|
4
|
+
// A hover on a reference opens its card, a plain click tracks it, and Ctrl+click opens it on GitHub.
|
|
5
|
+
import { StdinBuffer, TuiAltScreen, type OverlayHandle, type TUI } from '@earendil-works/pi-tui'
|
|
6
|
+
import { label, refAt, type Ref } from './prs.ts'
|
|
7
|
+
|
|
8
|
+
// The pointer has to rest this long on a reference before its card opens.
|
|
9
|
+
const HOVER_DELAY_MS = 250
|
|
10
|
+
|
|
11
|
+
export type PointerActions = {
|
|
12
|
+
// The card's lines, or nothing while the reference is still loading.
|
|
13
|
+
cardFor: (ref: Ref) => string[] | undefined
|
|
14
|
+
width: number
|
|
15
|
+
want: (ref: Ref) => void
|
|
16
|
+
track: (ref: Ref) => void
|
|
17
|
+
open: (ref: Ref) => void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Target = { row: number; col: number; key: string; ref: Ref }
|
|
21
|
+
type Rect = { top: number; bottom: number; left: number; right: number }
|
|
22
|
+
|
|
23
|
+
// What one SGR mouse report means: a move with no button held (35, plus 4, 8 or 16 for Shift, Alt
|
|
24
|
+
// or Ctrl), a drag (32 set), or the left button (0, plus 16 for Ctrl) going down or up.
|
|
25
|
+
export function readReport(data: string) {
|
|
26
|
+
const m = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data)
|
|
27
|
+
if (!m) return null
|
|
28
|
+
const button = Number(m[1])
|
|
29
|
+
const at = { col: Number(m[2]) - 1, row: Number(m[3]) - 1 }
|
|
30
|
+
if ((button & 35) === 35) return { kind: 'move' as const, ...at }
|
|
31
|
+
if (button & 32) return { kind: 'drag' as const, ...at }
|
|
32
|
+
if ((button & ~16) !== 0) return { kind: 'other' as const, ...at }
|
|
33
|
+
return { kind: m[4] === 'm' ? ('up' as const) : ('down' as const), ctrl: (button & 16) !== 0, ...at }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Starts reading the pointer for `t`; the returned function stops it.
|
|
37
|
+
export function watchPointer(t: TUI, act: PointerActions): () => void {
|
|
38
|
+
let hover: Target | undefined
|
|
39
|
+
let timer: NodeJS.Timeout | undefined
|
|
40
|
+
let overlay: OverlayHandle | undefined
|
|
41
|
+
let card: Rect | undefined
|
|
42
|
+
let press: { row: number; col: number } | undefined
|
|
43
|
+
const screenLine = (row: number) => (t instanceof TuiAltScreen ? t.getScreenLines()[row] ?? '' : '')
|
|
44
|
+
const onCard = (row: number, col: number) => card !== undefined && row >= card.top && row < card.bottom && col >= card.left && col < card.right
|
|
45
|
+
|
|
46
|
+
const hide = () => {
|
|
47
|
+
clearTimeout(timer)
|
|
48
|
+
hover = undefined
|
|
49
|
+
overlay?.hide()
|
|
50
|
+
overlay = undefined
|
|
51
|
+
card = undefined
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const show = (target: Target) => {
|
|
55
|
+
if (hover !== target || t.hasOverlay()) return
|
|
56
|
+
const lines = act.cardFor(target.ref)
|
|
57
|
+
// Not loaded yet: look again shortly, while the pointer stays.
|
|
58
|
+
if (!lines) {
|
|
59
|
+
timer = setTimeout(() => show(target), HOVER_DELAY_MS)
|
|
60
|
+
return
|
|
61
|
+
}
|
|
62
|
+
if (!refAt(screenLine(target.row), target.col)) return hide()
|
|
63
|
+
const { columns, rows } = t.terminal
|
|
64
|
+
const width = Math.min(act.width, columns)
|
|
65
|
+
const col = Math.max(0, Math.min(target.col, columns - width))
|
|
66
|
+
// It opens upward, as in Claude Code, unless the rows above are too few.
|
|
67
|
+
const up = target.row >= lines.length
|
|
68
|
+
const top = up ? target.row - lines.length : target.row + 1
|
|
69
|
+
card = { top, bottom: top + lines.length, left: col, right: col + width }
|
|
70
|
+
const place = up ? { anchor: 'bottom-left' as const, margin: { bottom: rows - target.row } } : { row: target.row + 1 }
|
|
71
|
+
overlay = t.showOverlay({ render: () => lines, invalidate: () => undefined }, {
|
|
72
|
+
nonCapturing: true, width, col, ...place,
|
|
73
|
+
visible: (w, h) => w === columns && h === rows,
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const observe = (data: string) => {
|
|
78
|
+
const r = readReport(data)
|
|
79
|
+
if (!r) {
|
|
80
|
+
if (hover) hide()
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
if (r.kind === 'move') {
|
|
84
|
+
if (onCard(r.row, r.col)) return
|
|
85
|
+
const ref = refAt(screenLine(r.row), r.col)
|
|
86
|
+
const key = ref ? label(ref) : ''
|
|
87
|
+
if (hover && hover.key === key && hover.row === r.row) return
|
|
88
|
+
hide()
|
|
89
|
+
if (!ref) return
|
|
90
|
+
act.want(ref)
|
|
91
|
+
const target = { row: r.row, col: r.col, key, ref }
|
|
92
|
+
hover = target
|
|
93
|
+
timer = setTimeout(() => show(target), HOVER_DELAY_MS)
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
// A drag selects text: no click follows.
|
|
97
|
+
if (r.kind === 'drag') press = undefined
|
|
98
|
+
if (r.kind !== 'down' && r.kind !== 'up') return
|
|
99
|
+
if (r.kind === 'down') {
|
|
100
|
+
// A click on the card is Pi's: it opens the link there.
|
|
101
|
+
if (!onCard(r.row, r.col)) hide()
|
|
102
|
+
press = { row: r.row, col: r.col }
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
const clicked = press !== undefined && press.row === r.row && press.col === r.col
|
|
106
|
+
press = undefined
|
|
107
|
+
if (!clicked || onCard(r.row, r.col)) return
|
|
108
|
+
const ref = refAt(screenLine(r.row), r.col)
|
|
109
|
+
if (!ref) return
|
|
110
|
+
if (r.ctrl) act.open(ref)
|
|
111
|
+
else act.track(ref)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const input = new StdinBuffer()
|
|
115
|
+
input.on('data', observe)
|
|
116
|
+
input.on('paste', hide)
|
|
117
|
+
const onData = (data: string | Buffer) => {
|
|
118
|
+
if (process.stdin.isRaw && t instanceof TuiAltScreen) input.process(data)
|
|
119
|
+
}
|
|
120
|
+
process.stdin.on('data', onData)
|
|
121
|
+
return () => {
|
|
122
|
+
process.stdin.off('data', onData)
|
|
123
|
+
input.destroy()
|
|
124
|
+
hide()
|
|
125
|
+
}
|
|
126
|
+
}
|
package/pi/prs.ts
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
// The parts of the Pi extension that need no Pi host: finding references, the GraphQL query, the
|
|
2
|
+
// tracked list and the band's lines. `node --test pi/tests.ts` runs them as they are.
|
|
3
|
+
|
|
4
|
+
export type Checks = { ok: number; failed: number; pending: number; total: number }
|
|
5
|
+
export type Item = {
|
|
6
|
+
kind: 'pr' | 'issue'
|
|
7
|
+
number: number
|
|
8
|
+
repo: string
|
|
9
|
+
title: string
|
|
10
|
+
url: string
|
|
11
|
+
// PR: OPEN | MERGED | CLOSED | DRAFT. Issue: OPEN | COMPLETED | NOT_PLANNED.
|
|
12
|
+
state: string
|
|
13
|
+
author: string
|
|
14
|
+
// `opened 2 days ago`, `merged 3 hours ago`...
|
|
15
|
+
when: string
|
|
16
|
+
created?: string
|
|
17
|
+
head?: string
|
|
18
|
+
base?: string
|
|
19
|
+
additions?: number
|
|
20
|
+
deletions?: number
|
|
21
|
+
changedFiles?: number
|
|
22
|
+
review?: string
|
|
23
|
+
checks?: Checks
|
|
24
|
+
// The failing checks, each with the page of its run.
|
|
25
|
+
failing?: { name: string; url?: string }[]
|
|
26
|
+
approvedBy?: string[]
|
|
27
|
+
changesBy?: string[]
|
|
28
|
+
// The users whose review is asked for and not given yet.
|
|
29
|
+
requested?: string[]
|
|
30
|
+
threads?: { path: string; line: number | null }[]
|
|
31
|
+
comments?: number
|
|
32
|
+
}
|
|
33
|
+
export type Entry = { item?: Item; error?: string; missing?: boolean; at: number; loading: boolean }
|
|
34
|
+
export type Ref = { repo: string | null; number: number }
|
|
35
|
+
export type Tracked = { repo: string; number: number }
|
|
36
|
+
export type SavedList = { at: number; items: Tracked[] }
|
|
37
|
+
|
|
38
|
+
export const TTL_MS = 60_000
|
|
39
|
+
export const BATCH = 40
|
|
40
|
+
// A saved list goes once no session has used it for this long.
|
|
41
|
+
export const TRACKED_TTL_MS = 14 * 86_400_000
|
|
42
|
+
|
|
43
|
+
// `#1234`, `owner/repo#1234` or a GitHub pull or issue URL, as the Claude Code mod finds them; a `#`
|
|
44
|
+
// after a word character, `[`, `#` or `/` is a heading, an anchor or a link label.
|
|
45
|
+
const REF = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/(?:pull|issues)\/(\d+)|(?<![\w[#/])(?:([\w.-]+\/[\w.-]+))?#(\d+)\b/g
|
|
46
|
+
|
|
47
|
+
export const keyFor = (repo: string, number: number) => `${repo.toLowerCase()}#${number}`
|
|
48
|
+
export const label = (r: Ref) => (r.repo ? `${r.repo}#${r.number}` : `#${r.number}`)
|
|
49
|
+
|
|
50
|
+
// Code spans and blocks, and link labels and targets, hold no references to draw: blank them out
|
|
51
|
+
// with spaces, so offsets in the masked text match the original.
|
|
52
|
+
const mask = (md: string) => md.replace(/```[\s\S]*?```|`[^`\n]*`|\[[^\]\n]*\]\([^)\n]*\)/g, (m) => ' '.repeat(m.length))
|
|
53
|
+
|
|
54
|
+
export type Found = Ref & { start: number; end: number; url: boolean }
|
|
55
|
+
|
|
56
|
+
export function findRefs(md: string): Found[] {
|
|
57
|
+
const found: Found[] = []
|
|
58
|
+
for (const m of mask(md).matchAll(REF)) {
|
|
59
|
+
const url = m[1] !== undefined
|
|
60
|
+
found.push({ repo: url ? m[1]! : m[3] ?? null, number: Number(url ? m[2] : m[4]), start: m.index!, end: m.index! + m[0].length, url })
|
|
61
|
+
}
|
|
62
|
+
return found
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// The 16 palette slots, as the Claude Code mod draws them: a terminal theme recolors them.
|
|
66
|
+
export const SGR = { open: 32, merged: 35, closed: 31, draft: 90, warn: 33, link: 34, dim: 90, code: 36, black: 30 } as const
|
|
67
|
+
export type Tone = keyof typeof SGR
|
|
68
|
+
export const paint = (tone: Tone, text: string) => `\x1b[${SGR[tone]}m${text}\x1b[39m`
|
|
69
|
+
const STATE_TONE: Record<string, Tone> = { OPEN: 'open', DRAFT: 'draft', MERGED: 'merged', CLOSED: 'closed', COMPLETED: 'merged', NOT_PLANNED: 'draft' }
|
|
70
|
+
export const toneOf = (item: Item): Tone => STATE_TONE[item.state] ?? 'dim'
|
|
71
|
+
export const DOT = '⬤'
|
|
72
|
+
|
|
73
|
+
// Each reference gets a dot, as the Claude Code mod draws them: the state's color once GitHub
|
|
74
|
+
// answered, hollow while loading, a red x when the lookup failed. A URL reads `owner/repo#N`. The
|
|
75
|
+
// reference stays text, not a link: Pi opens a link on any click, and a plain click tracks the PR.
|
|
76
|
+
// One GitHub does not know, or in a folder without a repo, stays as written.
|
|
77
|
+
export function decorate(md: string, lookup: (r: Ref) => Entry | undefined): string {
|
|
78
|
+
let out = ''
|
|
79
|
+
let at = 0
|
|
80
|
+
for (const f of findRefs(md)) {
|
|
81
|
+
const entry = lookup(f)
|
|
82
|
+
if (!entry || entry.missing) continue
|
|
83
|
+
const item = entry.item
|
|
84
|
+
const dot = item ? paint(toneOf(item), DOT) : entry.error ? paint('closed', 'x') : paint('dim', '○')
|
|
85
|
+
const text = f.url ? `${f.repo}#${f.number}` : md.slice(f.start, f.end)
|
|
86
|
+
out += md.slice(at, f.start) + `${dot} ${paint('link', text)}`
|
|
87
|
+
at = f.end
|
|
88
|
+
}
|
|
89
|
+
return out + md.slice(at)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The reference a decorated reply shows at column `col` of a screen line: the dot, a space, then the
|
|
93
|
+
// reference. The dot tells a decorated reference from the same text in the editor or a code block.
|
|
94
|
+
export function refAt(line: string, col: number): Ref | null {
|
|
95
|
+
// One character per cell, so string offsets are columns.
|
|
96
|
+
const text = plainCells(line).join('')
|
|
97
|
+
for (const m of text.matchAll(/(?:⬤|○|x) ((?:([\w.-]+\/[\w.-]+))?#(\d+))\b/g)) {
|
|
98
|
+
if (col >= m.index! && col < m.index! + m[0].length) return { repo: m[2] ?? null, number: Number(m[3]) }
|
|
99
|
+
}
|
|
100
|
+
return null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// A screen line as one character per cell: escape sequences dropped, a wide character's second cell
|
|
104
|
+
// a space. Pi's screen lines carry SGR colors and OSC 8 links.
|
|
105
|
+
export function plainCells(line: string): string[] {
|
|
106
|
+
const bare = line.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?<>]*[ -/]*[@-~]|\x1b[@-_]/g, '')
|
|
107
|
+
const cells: string[] = []
|
|
108
|
+
for (const ch of bare) {
|
|
109
|
+
cells.push(ch)
|
|
110
|
+
if (/[ᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩]|[\u{1f300}-\u{1faff}]/u.test(ch)) cells.push(' ')
|
|
111
|
+
}
|
|
112
|
+
return cells
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// The Claude Code mod's query: the band and the card need the same fields.
|
|
116
|
+
export const FIELDS = `
|
|
117
|
+
__typename
|
|
118
|
+
... on PullRequest { number title url state isDraft author { login } additions deletions changedFiles reviewDecision createdAt mergedAt closedAt headRefName baseRefName
|
|
119
|
+
statusCheckRollup { contexts(first: 100) { totalCount checkRunCountsByState { state count } statusContextCountsByState { state count }
|
|
120
|
+
nodes { __typename ... on CheckRun { name conclusion detailsUrl } ... on StatusContext { context state targetUrl } } } }
|
|
121
|
+
latestReviews(first: 20) { nodes { state author { login } } }
|
|
122
|
+
reviewRequests(first: 20) { nodes { requestedReviewer { ... on User { login } } } }
|
|
123
|
+
reviewThreads(first: 100) { nodes { isResolved path line } } }
|
|
124
|
+
... on Issue { number title url state stateReason author { login } comments { totalCount } createdAt closedAt }`
|
|
125
|
+
|
|
126
|
+
export function query(repo: string, numbers: number[]) {
|
|
127
|
+
const [owner, name] = repo.split('/')
|
|
128
|
+
return `query { viewer { login } repository(owner: ${JSON.stringify(owner)}, name: ${JSON.stringify(name)}) { ${numbers.map((n) => `n${n}: issueOrPullRequest(number: ${n}) { ${FIELDS} }`).join('\n')} } }`
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
type Count = { state: string; count: number }
|
|
132
|
+
export type Raw = {
|
|
133
|
+
__typename: 'PullRequest' | 'Issue'
|
|
134
|
+
number: number; title: string; url: string; state: string; isDraft?: boolean; stateReason?: string | null
|
|
135
|
+
author?: { login: string } | null; additions?: number; deletions?: number; changedFiles?: number; reviewDecision?: string | null
|
|
136
|
+
createdAt?: string; mergedAt?: string | null; closedAt?: string | null; headRefName?: string | null; baseRefName?: string | null
|
|
137
|
+
statusCheckRollup?: {
|
|
138
|
+
contexts: {
|
|
139
|
+
totalCount: number; checkRunCountsByState?: Count[]; statusContextCountsByState?: Count[]
|
|
140
|
+
nodes?: { __typename: string; name?: string; conclusion?: string | null; detailsUrl?: string | null; context?: string; state?: string; targetUrl?: string | null }[]
|
|
141
|
+
}
|
|
142
|
+
} | null
|
|
143
|
+
latestReviews?: { nodes: { state: string; author?: { login: string } | null }[] }
|
|
144
|
+
reviewRequests?: { nodes: { requestedReviewer?: { login?: string } | null }[] }
|
|
145
|
+
reviewThreads?: { nodes: { isResolved: boolean; path: string; line: number | null }[] }
|
|
146
|
+
comments?: { totalCount: number }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const OK = ['SUCCESS', 'NEUTRAL', 'SKIPPED']
|
|
150
|
+
const FAILED = ['FAILURE', 'ERROR', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE', 'STALE']
|
|
151
|
+
|
|
152
|
+
export function ago(iso: string | null | undefined, now = Date.now()) {
|
|
153
|
+
if (!iso) return ''
|
|
154
|
+
const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000))
|
|
155
|
+
const [n, unit] = minutes < 60 ? [minutes, 'minute'] : minutes < 1440 ? [Math.round(minutes / 60), 'hour'] : [Math.round(minutes / 1440), 'day']
|
|
156
|
+
return n === 0 ? 'just now' : `${n} ${unit}${n === 1 ? '' : 's'} ago`
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
|
|
160
|
+
// `Nov 18`, as GitHub dates a card; the year only when it is not this one.
|
|
161
|
+
export function day(iso?: string) {
|
|
162
|
+
if (!iso) return ''
|
|
163
|
+
const d = new Date(iso)
|
|
164
|
+
const year = d.getUTCFullYear() === new Date().getUTCFullYear() ? '' : `, ${d.getUTCFullYear()}`
|
|
165
|
+
return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}${year}`
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function toItem(repo: string, raw: Raw): Item {
|
|
169
|
+
const author = raw.author?.login ?? 'ghost'
|
|
170
|
+
if (raw.__typename === 'Issue') {
|
|
171
|
+
const state = raw.state === 'OPEN' ? 'OPEN' : raw.stateReason === 'NOT_PLANNED' ? 'NOT_PLANNED' : 'COMPLETED'
|
|
172
|
+
const when = state === 'OPEN' ? `opened ${ago(raw.createdAt)}` : `closed ${ago(raw.closedAt)}`
|
|
173
|
+
return { kind: 'issue', number: raw.number, repo, title: raw.title, url: raw.url, state, author, when, created: raw.createdAt, comments: raw.comments?.totalCount ?? 0 }
|
|
174
|
+
}
|
|
175
|
+
const contexts = raw.statusCheckRollup?.contexts
|
|
176
|
+
const counts = [...(contexts?.checkRunCountsByState ?? []), ...(contexts?.statusContextCountsByState ?? [])]
|
|
177
|
+
const sum = (states: string[]) => counts.filter((c) => states.includes(c.state)).reduce((a, c) => a + c.count, 0)
|
|
178
|
+
const total = contexts?.totalCount ?? 0
|
|
179
|
+
const ok = sum(OK)
|
|
180
|
+
const failed = sum(FAILED)
|
|
181
|
+
const reviews = raw.latestReviews?.nodes ?? []
|
|
182
|
+
const by = (s: string) => reviews.filter((r) => r.state === s).map((r) => r.author?.login ?? 'ghost')
|
|
183
|
+
const state = raw.state === 'OPEN' && raw.isDraft ? 'DRAFT' : raw.state
|
|
184
|
+
const when = state === 'MERGED' ? `merged ${ago(raw.mergedAt)}` : state === 'CLOSED' ? `closed ${ago(raw.closedAt)}` : `opened ${ago(raw.createdAt)}`
|
|
185
|
+
return {
|
|
186
|
+
kind: 'pr', number: raw.number, repo, title: raw.title, url: raw.url, state, author, when,
|
|
187
|
+
created: raw.createdAt, head: raw.headRefName ?? undefined, base: raw.baseRefName ?? undefined,
|
|
188
|
+
additions: raw.additions, deletions: raw.deletions, changedFiles: raw.changedFiles,
|
|
189
|
+
review: raw.reviewDecision ?? undefined,
|
|
190
|
+
checks: { ok, failed, pending: Math.max(0, total - ok - failed), total },
|
|
191
|
+
failing: (contexts?.nodes ?? []).filter((c) => FAILED.includes(c.conclusion ?? c.state ?? '')).map((c) => ({ name: c.name ?? c.context ?? '?', url: c.detailsUrl ?? c.targetUrl ?? undefined })),
|
|
192
|
+
approvedBy: by('APPROVED'), changesBy: by('CHANGES_REQUESTED'),
|
|
193
|
+
requested: (raw.reviewRequests?.nodes ?? []).flatMap((r) => r.requestedReviewer?.login ?? []),
|
|
194
|
+
threads: (raw.reviewThreads?.nodes ?? []).filter((t) => !t.isResolved).map((t) => ({ path: t.path, line: t.line })),
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// `2d`, `5h`, `20m`: how long ago, for a chip.
|
|
199
|
+
export function age(iso?: string, now = Date.now()) {
|
|
200
|
+
if (!iso) return ''
|
|
201
|
+
const minutes = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000))
|
|
202
|
+
return minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / 1440)}d`
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The band's group: 0 needs you (your review is asked for, or your PR fails its checks or got
|
|
206
|
+
// changes requested), 1 waiting (open, or not loaded yet), 2 done (merged or closed).
|
|
207
|
+
export function groupOf(item: Item | undefined, viewer: string) {
|
|
208
|
+
if (!item) return 1
|
|
209
|
+
if (item.state !== 'OPEN' && item.state !== 'DRAFT') return 2
|
|
210
|
+
if (!viewer) return 1
|
|
211
|
+
if (item.requested?.includes(viewer)) return 0
|
|
212
|
+
if (item.author === viewer && (item.checks?.failed || item.review === 'CHANGES_REQUESTED')) return 0
|
|
213
|
+
return 1
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ---------- The tracked list ----------
|
|
217
|
+
|
|
218
|
+
const isTracked = (t: unknown): t is Tracked => !!t && typeof (t as Tracked).repo === 'string' && typeof (t as Tracked).number === 'number'
|
|
219
|
+
export const savedItems = (saved: unknown) => (Array.isArray((saved as SavedList | undefined)?.items) ? (saved as SavedList).items.filter(isTracked) : [])
|
|
220
|
+
export const sameList = (a: Tracked[], b: Tracked[]) => a.length === b.length && a.every((t, i) => keyFor(t.repo, t.number) === keyFor(b[i]!.repo, b[i]!.number))
|
|
221
|
+
export const withTracked = (items: Tracked[], t: Tracked) => (items.some((i) => keyFor(i.repo, i.number) === keyFor(t.repo, t.number)) ? items : [...items, t])
|
|
222
|
+
export const withoutTracked = (items: Tracked[], key: string) => items.filter((t) => keyFor(t.repo, t.number) !== key)
|
|
223
|
+
|
|
224
|
+
// The list's name in the store: one per GitHub repo, its worktrees and clones included, or per folder
|
|
225
|
+
// outside git; one per session when sharing is off.
|
|
226
|
+
export function listName(share: boolean, sessionId: string, repo: string | null, cwd: string) {
|
|
227
|
+
if (!share) return `session.${sessionId}`
|
|
228
|
+
return repo ? `repo.${repo}` : `dir.${cwd}`
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Lists no session has used for TRACKED_TTL_MS go.
|
|
232
|
+
export function pruned(lists: Record<string, SavedList>, keep: string, now = Date.now()) {
|
|
233
|
+
return Object.fromEntries(Object.entries(lists).filter(([k, v]) => k === keep || (v && typeof v.at === 'number' && now - v.at <= TRACKED_TTL_MS)))
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ---------- The band ----------
|
|
237
|
+
|
|
238
|
+
export type Band = {
|
|
239
|
+
tracked: Tracked[]
|
|
240
|
+
lookup: (t: Tracked) => Entry | undefined
|
|
241
|
+
viewer: string
|
|
242
|
+
selected: string | null
|
|
243
|
+
armed: string | null
|
|
244
|
+
folded: boolean
|
|
245
|
+
perRow: number
|
|
246
|
+
// Keys are listed only while the band has the keyboard.
|
|
247
|
+
focused: boolean
|
|
248
|
+
}
|
|
249
|
+
export type Style = { bar: (text: string) => string; mark: (text: string) => string; bold: (text: string) => string }
|
|
250
|
+
// What a click at a row and column hits: the bar folds the band, a chip selects its PR.
|
|
251
|
+
export type Hit = { row: number; from: number; to: number; target: 'bar' | string }
|
|
252
|
+
|
|
253
|
+
export const LABEL = 10
|
|
254
|
+
// Design I3: the group rows start four cells right of the Tracked PRs bar, as its contents.
|
|
255
|
+
export const INDENT = 4
|
|
256
|
+
const GROUPS = ['needs you', 'waiting', 'done']
|
|
257
|
+
|
|
258
|
+
const cut = (s: string, n: number) => (n <= 0 ? '' : s.length > n ? `${s.slice(0, Math.max(0, n - 1))}…` : s)
|
|
259
|
+
|
|
260
|
+
export function chipWidth(columns: number, perRow: number) {
|
|
261
|
+
return Math.max(24, Math.min(44, Math.floor((columns - INDENT - LABEL) / perRow) - 1))
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// One chip, `width` cells: the edge (▎ when selected), the dot, number, title, author and age, the
|
|
265
|
+
// checks' mark, then spaces to its end.
|
|
266
|
+
export function chip(t: Tracked, entry: Entry | undefined, width: number, selected: boolean, s: Style): string {
|
|
267
|
+
const item = entry?.item
|
|
268
|
+
const runs: { text: string; tone?: Tone; bold?: boolean }[] = []
|
|
269
|
+
if (!item) runs.push({ text: `${entry?.error ? 'x' : '○'} `, tone: entry?.error ? 'closed' : 'dim' }, { text: `#${t.number}`, tone: 'link', bold: true })
|
|
270
|
+
else {
|
|
271
|
+
const c = item.checks
|
|
272
|
+
const tail = [
|
|
273
|
+
// A long login would eat the title: ten cells at most.
|
|
274
|
+
{ text: ` ${cut(item.author, 10)} ${age(item.created)}`, tone: 'dim' as Tone },
|
|
275
|
+
...(c?.total ? [{ text: ` ${c.failed ? 'x' : c.pending ? '●' : '✓'}`, tone: (c.failed ? 'closed' : c.pending ? 'warn' : 'open') as Tone }] : []),
|
|
276
|
+
]
|
|
277
|
+
const head = `#${t.number} `
|
|
278
|
+
const room = Math.max(4, width - 3 - head.length - tail.reduce((n, r) => n + r.text.length, 0) - 1)
|
|
279
|
+
runs.push({ text: `${DOT} `, tone: toneOf(item) }, { text: head, tone: 'link', bold: true }, { text: cut(item.title, room) }, ...tail)
|
|
280
|
+
}
|
|
281
|
+
const used = 1 + runs.reduce((n, r) => n + r.text.length, 0)
|
|
282
|
+
const body = runs.map((r) => {
|
|
283
|
+
const text = r.tone ? paint(r.tone, r.text) : r.text
|
|
284
|
+
return r.bold ? s.bold(text) : text
|
|
285
|
+
}).join('')
|
|
286
|
+
return (selected ? s.mark('▎') : ' ') + body + ' '.repeat(Math.max(1, width - used))
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function keysFor(b: Band): string[] {
|
|
290
|
+
const picked = b.tracked.find((t) => keyFor(t.repo, t.number) === b.selected)
|
|
291
|
+
if (!picked) return ['↑↓ move', 'esc back']
|
|
292
|
+
const item = b.lookup(picked)?.item
|
|
293
|
+
const keys: string[] = []
|
|
294
|
+
if (item) {
|
|
295
|
+
const isOpen = item.kind === 'pr' && (item.state === 'OPEN' || item.state === 'DRAFT')
|
|
296
|
+
if (isOpen && item.author !== b.viewer) keys.push(b.armed === b.selected ? 'a press again to approve' : 'a approve', 'r request changes')
|
|
297
|
+
if (runIds(item).length) keys.push('f re-run failed')
|
|
298
|
+
keys.push('o open', 'c copy link')
|
|
299
|
+
}
|
|
300
|
+
keys.push('x remove', 'esc back')
|
|
301
|
+
return keys
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export const runIds = (item: Item) => [...new Set((item.failing ?? []).flatMap((f) => /\/actions\/runs\/(\d+)/.exec(f.url ?? '')?.[1] ?? []))]
|
|
305
|
+
|
|
306
|
+
// The tracked list in groups (needs you, waiting, done), the same order the band draws it in.
|
|
307
|
+
export function ordered(b: Pick<Band, 'tracked' | 'lookup' | 'viewer'>): Tracked[][] {
|
|
308
|
+
const groups: Tracked[][] = [[], [], []]
|
|
309
|
+
for (const t of b.tracked) groups[groupOf(b.lookup(t)?.item, b.viewer)]!.push(t)
|
|
310
|
+
return groups
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// The band as lines of `width` cells: a blank row, the Tracked PRs bar, then each group's chips,
|
|
314
|
+
// `perRow` to a row with the group's name before its first row, then the keys when focused.
|
|
315
|
+
export function bandLines(b: Band, width: number, s: Style): { lines: string[]; hits: Hit[] } {
|
|
316
|
+
if (!b.tracked.length) return { lines: [], hits: [] }
|
|
317
|
+
const columns = Math.max(40, width) - 2
|
|
318
|
+
const title = b.folded ? ` ▸ Tracked PRs · ${b.tracked.length}` : ' ▾ Tracked PRs'
|
|
319
|
+
const lines = ['', ' ' + s.bar(s.bold(title.padEnd(columns)))]
|
|
320
|
+
const hits: Hit[] = [{ row: 1, from: 2, to: 2 + columns, target: 'bar' }]
|
|
321
|
+
if (b.folded) return { lines, hits }
|
|
322
|
+
const width1 = chipWidth(columns, b.perRow)
|
|
323
|
+
ordered(b).forEach((list, g) => {
|
|
324
|
+
for (let i = 0; i < list.length; i += b.perRow) {
|
|
325
|
+
const row = list.slice(i, i + b.perRow)
|
|
326
|
+
let col = 2 + INDENT + LABEL
|
|
327
|
+
for (const t of row) {
|
|
328
|
+
hits.push({ row: lines.length, from: col, to: col + width1, target: keyFor(t.repo, t.number) })
|
|
329
|
+
col += width1 + 1
|
|
330
|
+
}
|
|
331
|
+
const chips = row.map((t) => chip(t, b.lookup(t), width1, b.selected === keyFor(t.repo, t.number), s)).join(' ')
|
|
332
|
+
lines.push(' '.repeat(2 + INDENT) + paint('dim', (i ? '' : GROUPS[g]!).padEnd(LABEL)) + chips)
|
|
333
|
+
}
|
|
334
|
+
})
|
|
335
|
+
if (b.focused) lines.push(' ' + keysFor(b).map((k) => `${s.bold(k.slice(0, k.indexOf(' ')))}${paint('dim', k.slice(k.indexOf(' ')))}`).join(' '))
|
|
336
|
+
return { lines, hits }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// The chip one step from `selected` in the band's order: ↑ and ← go back, ↓, → and Tab forward.
|
|
340
|
+
export function step(b: Pick<Band, 'tracked' | 'lookup' | 'viewer' | 'selected'>, by: number): string | null {
|
|
341
|
+
const flat = ordered(b).flat().map((t) => keyFor(t.repo, t.number))
|
|
342
|
+
if (!flat.length) return null
|
|
343
|
+
const at = b.selected ? flat.indexOf(b.selected) : -1
|
|
344
|
+
if (at < 0) return flat[by > 0 ? 0 : flat.length - 1]!
|
|
345
|
+
return flat[Math.max(0, Math.min(flat.length - 1, at + by))]!
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ---------- Copying a link as rich text ----------
|
|
349
|
+
|
|
350
|
+
const escapeHtml = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
351
|
+
|
|
352
|
+
// The Windows clipboard's HTML format: a header of byte offsets around the fragment.
|
|
353
|
+
export function cfHtml(fragment: string) {
|
|
354
|
+
const pre = '<html><body><!--StartFragment-->'
|
|
355
|
+
const post = '<!--EndFragment--></body></html>'
|
|
356
|
+
const bytes = (x: string) => Buffer.byteLength(x, 'utf8')
|
|
357
|
+
const header = (a: number, b: number, c: number, d: number) =>
|
|
358
|
+
`Version:0.9\r\nStartHTML:${String(a).padStart(10, '0')}\r\nEndHTML:${String(b).padStart(10, '0')}\r\nStartFragment:${String(c).padStart(10, '0')}\r\nEndFragment:${String(d).padStart(10, '0')}\r\n`
|
|
359
|
+
const startHtml = bytes(header(0, 0, 0, 0))
|
|
360
|
+
const startFragment = startHtml + bytes(pre)
|
|
361
|
+
const endFragment = startFragment + bytes(fragment)
|
|
362
|
+
const endHtml = endFragment + bytes(post)
|
|
363
|
+
return header(startHtml, endHtml, startFragment, endFragment) + pre + fragment + post
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// `acme/shop#58` as a link, then the title: what a chat shows when it takes rich text.
|
|
367
|
+
export function linkFormats(item: Item) {
|
|
368
|
+
const name = `${item.repo}#${item.number}`
|
|
369
|
+
return { name, html: cfHtml(`<a href="${escapeHtml(item.url)}">${escapeHtml(name)}</a> ${escapeHtml(item.title)}`), text: `${name} ${item.title} ${item.url}` }
|
|
370
|
+
}
|